Skip to content

Showcase

Production planning

Compare plans around a machine outage and see how a moved operation shifts later work, the shipping time and the resource load; follow a lot through the process graph in units or cost; edit an approval workflow; and plan a project in a schedule sheet. The planning and lot views share one linked selection, and every edit is saved to a mock server with app-wide undo, redo and visible conflicts. In English and Japanese.

Live demoView on GitHub ↗

Saved · Accepted version v1.

Production planning

Move a bar to see how the change affects later operations and the shipping time.

CNC maintenanceUnavailable from 10:00 to 13:00

Process graph

NetworkGraph
Prepare stock 08:00–10:00▤Prepare stock08:00–10:00Cut A 10:00–13:00ACut A10:00–13:00Cut B 10:00–12:00BCut B10:00–12:00Inspect 13:00–15:00✓Inspect13:00–15:00Pack 15:00–17:00□Pack15:00–17:00
115%

Gantt chart

GanttChart
100%
Operation
08:0010:0012:0014:0016:0018:0020:0022:0024:00
Shipping deadline 19:00
Prepare stock
Cut A
Cut B
Inspect
Pack
Drag a bar or adjust the start time in the operation details.

Drag a bar or adjust the start time in the operation details. Click empty chart space or press Escape to clear the selection.

Resource load

calculateResourceLoad
100%
Assigned resource
CNC maintenance08:0010:0012:0014:0016:0018:0020:0022:0024:00
Prep bench
CNC machine
Backup saw
Inspection
Packing
Resource load

Drag the lower-right corner of the demo to change its height.

Source code

vue
<script setup lang="ts">
// The production planning demo (Demo.vue) on a page of the documentation site: the same four views and their tabs,
// without the standalone app's header, language switch and theme switch, which the site provides. The language follows
// the site page (useDemoLocale); the colour scheme follows the `.dark` class that the site puts on the demo panel.
import { computed, ref } from 'vue'
import { useDemoLocale } from '../i18n'
import { copy, type Language } from './copy'
import ProductionWorkspace from './ProductionWorkspace.vue'
import './production.css'

const { locale } = useDemoLocale()
const language = computed<Language>(() => locale.value)
const ja = computed(() => language.value === 'ja')
const text = computed(() => copy[language.value])
const view = ref<'planning' | 'lot' | 'approval' | 'sheet'>('planning')
</script>

<template>
  <div class="production-app production-showcase" :lang="language">
    <nav class="production-nav production-showcase-nav" :aria-label="ja ? 'デモ' : 'Demos'">
      <button v-for="item in (['planning', 'lot', 'approval', 'sheet'] as const)" :key="item" type="button"
        :aria-current="view === item ? 'page' : undefined" @click="view = item">{{ text[item] }}</button>
    </nav>
    <div class="production-page">
      <ProductionWorkspace :text="text" :ja="ja" :view="view" />
    </div>
  </div>
</template>

<style>
.production-showcase.production-app { min-height: 0; color-scheme: light; border-radius: 10px; border: 1px solid var(--border); }
.dark .production-showcase.production-app { color-scheme: dark; }
.production-showcase-nav { padding-inline: 26px; border-bottom: 1px solid var(--border); background: var(--surface); border-radius: 10px 10px 0 0; }
@media (max-width: 720px) { .production-showcase-nav { padding-inline: 14px; } }
</style>
vue
<script setup lang="ts">
// The four views of the production demo over one saved document: the save bar (status, app-wide undo and redo, and the
// mock server's next answer) and the tabs. Demo.vue and ProductionShowcase.vue only add their own headers around it.
import SaveStatus from '../components/SaveStatus.vue'
import type { ServerMode } from '../adapters/transactionStore'
import ApprovalFlow from './ApprovalFlow.vue'
import LotFlow from './LotFlow.vue'
import ProductionPlan from './ProductionPlan.vue'
import WorkSheet from './WorkSheet.vue'
import type { Copy } from './copy'
import { provideProductionWorkspace } from './workspace'

defineProps<{ text: Copy; ja: boolean; view: 'planning' | 'lot' | 'approval' | 'sheet' }>()
const workspace = provideProductionWorkspace()
const { transaction, server } = workspace
const modes: ServerMode[] = ['accept', 'reject', 'conflict', 'uncertain']
</script>

<template>
  <div class="production-savebar" role="group" :aria-label="text.saving">
    <SaveStatus :status="transaction.status.value" :pending="transaction.pendingTransaction.value" :result="transaction.result.value"
      :busy="workspace.busy.value" :version="transaction.acceptedVersion.value"
      @dismiss="workspace.dismiss" @reload="workspace.reload" @reconcile="workspace.reconcile" />
    <div class="production-actions">
      <button type="button" :disabled="!transaction.canUndo.value || workspace.locked.value" @click="workspace.undo">{{ text.undo }}</button>
      <button type="button" :disabled="!transaction.canRedo.value || workspace.locked.value" @click="workspace.redo">{{ text.redo }}</button>
      <label>{{ text.serverMode }}
        <select v-model="server.info.mode">
          <option v-for="mode in modes" :key="mode" :value="mode">{{ text.serverModes[mode] }}</option>
        </select>
      </label>
    </div>
  </div>
  <KeepAlive>
    <ProductionPlan v-if="view === 'planning'" :text="text" />
    <LotFlow v-else-if="view === 'lot'" :text="text" :is-japanese="ja" />
    <ApprovalFlow v-else-if="view === 'approval'" :ja="ja" />
    <WorkSheet v-else :ja="ja" />
  </KeepAlive>
</template>
ts
import { computed, inject, provide, ref, shallowRef, type InjectionKey } from 'vue'
import {
  taskViewBindings, useEditTransaction, useLinkedSelection, type EntityRef, type SaveResult, type TransactionAdapter, type TransactionOutcome,
  type ViewBinding,
} from '../../src'
import { createTransactionStore } from '../adapters/transactionStore'
import { initialFlow, type Flow } from './approval'
import { calculatePlan, taskIds, type Plan, type Schedule, type TaskId } from './plan'
import { initialTasks, scheduleSheet, type Task } from './sheet'

// The whole app is one document on the (mock) server: the adopted production plan, the approval workflow and the
// schedule sheet. Every tab edits it through one useEditTransaction, so saving, conflicts and undo/redo are app-wide.
export interface ProductionDocument {
  plan: Plan
  approval: Flow
  sheet: readonly Task[]
}
// demo:save
/** One user action replaces the part of the document that its tab owns. */
export type ProductionChange =
  | { area: 'plan'; plan: Plan }
  | { area: 'approval'; flow: Flow }
  | { area: 'sheet'; tasks: readonly Task[] }

export const initialDocument: ProductionDocument = { plan: { strategy: 'original', starts: {} }, approval: initialFlow, sheet: initialTasks }

function createAdapter(save: TransactionAdapter<ProductionDocument, ProductionChange>['save']): TransactionAdapter<ProductionDocument, ProductionChange> {
  return {
    // The tabs check their edits with localized messages first; this is the last line of defence before saving.
    validate(_document, changes) {
      for (const change of changes) {
        if (change.area === 'plan' && !calculatePlan(change.plan)) return 'The plan cannot be scheduled.'
        if (change.area === 'sheet' && !scheduleSheet(change.tasks).ok) return 'The schedule sheet cannot be scheduled.'
      }
    },
    apply(document, changes) {
      let next = document
      for (const change of changes) {
        if (change.area === 'plan') next = { ...next, plan: change.plan }
        else if (change.area === 'approval') next = { ...next, approval: change.flow }
        else next = { ...next, sheet: change.tasks }
      }
      return next
    },
    save,
  }
}
// demo:end

// demo:link
// The planning operations and the steps of lot L-100 are the same production steps: the lot is prepared, cut on line A
// and line B, inspected and packed. Rework (a loop back to inspection) and overhead (a cost) have no operation.
export const lotStepOf: Record<TaskId, string> = { prep: 'lot', cutA: 'line-a', cutB: 'line-b', inspect: 'inspect', pack: 'pack' }
const operationOfStep = new Map(taskIds.map(id => [lotStepOf[id], id]))
/** The entity a lot flow step stands for. */
export const stepEntity = (stepId: string): EntityRef =>
  operationOfStep.has(stepId) ? { kind: 'operation', id: operationOfStep.get(stepId)! } : { kind: 'lot-step', id: stepId }
/** The lot flow step of an entity, if it has one. */
export const stepOf = (entity: EntityRef) =>
  entity.kind === 'operation' ? lotStepOf[entity.id as TaskId] : entity.kind === 'lot-step' ? entity.id : undefined

// The planning views show operations under their own IDs (graph node, bar, row and load); the lot flow graph shows
// them as its steps. Both graphs report as the `graph` view: a node ID of one names the same entity or nothing in the other.
function bindings(schedule: Schedule): ViewBinding[] {
  return [
    ...taskViewBindings({
      tasks: [...schedule.byId.values()], taskKind: 'operation',
      assignments: taskIds.map(taskId => ({ taskId, resourceId: schedule.resourceFor[taskId] })),
    }),
    ...taskIds.map((id): ViewBinding => ({ entity: { kind: 'operation', id }, target: { view: 'graph', kind: 'node', id: lotStepOf[id] } })),
    { entity: { kind: 'lot-step', id: 'rework' }, target: { view: 'graph', kind: 'node', id: 'rework' } },
  ]
}
// demo:end

/** A plan proposal of the planning tab: the plan and, after a move, the operation the planner moved. */
export interface PlanProposal { plan: Plan; moved?: TaskId }

export function createProductionWorkspace() {
  // In conflict mode another planner changes the trial run of the schedule sheet first, so the reload shows it. Like
  // any save, theirs must schedule: they lengthen the trial run by a day, or shorten it when it would no longer fit in
  // the project window, and change nothing when neither schedules.
  const server = createTransactionStore<ProductionDocument>(initialDocument, {
    delay: 200,
    remoteEdit: document => {
      const trial = document.sheet.find(item => item.id === 'trial')!
      for (const duration of [trial.duration + 1, trial.duration - 1]) {
        const sheet = document.sheet.map(item => item === trial ? { ...item, duration } : item)
        if (duration > 0 && scheduleSheet(sheet).ok) return { ...document, sheet }
      }
      return document
    },
  })
  const transaction = useEditTransaction<ProductionDocument, ProductionChange>({
    documentId: 'production', initialState: initialDocument, initialVersion: server.info.version,
    adapter: createAdapter((request, candidate) => server.save(request, candidate)),
  })
  /** What the tabs show: the candidate while it is being saved, else the accepted document. */
  const document = computed(() => transaction.candidateState.value ?? transaction.acceptedState.value)
  const saving = computed(() => transaction.status.value === 'saving')
  // demo:unknown
  // A save whose answer was lost waits for "Check with server". Until then nothing else is saved: useEditTransaction
  // would start the next save (or an undo or redo) on the version from before the lost one, which the server may have
  // moved past, and the lost operation could no longer be checked. Proposals can still be opened and edited.
  const unresolved = computed(() => transaction.status.value === 'uncertain')
  /** Saving, undo and redo wait while a save is in flight or its outcome is unknown. */
  const locked = computed(() => saving.value || unresolved.value)
  // demo:end
  /** Set when the last submit found another save in progress. */
  const busy = ref(false)

  // The open plan proposal of the planning tab. It is not saved until it is adopted.
  const proposal = shallowRef<PlanProposal>()
  /** Set when a save adopted the open proposal and closed it. The planning tab clears it when it opens another. */
  const adoptionNotice = ref(false)
  const adopted = computed(() => calculatePlan(document.value.plan)!)
  const schedule = computed(() => proposal.value ? calculatePlan(proposal.value.plan)! : adopted.value)
  /**
   * The operations whose start the open proposal changes, except the one the planner moved. Derived, not stored with
   * the proposal: the plan it is compared with changes when a save in flight is accepted or refused.
   */
  const changed = computed(() => {
    const open = proposal.value
    if (!open) return []
    return taskIds.filter(id => id !== open.moved && adopted.value.byId.get(id)!.start !== schedule.value.byId.get(id)!.start)
  })

  const linked = useLinkedSelection({ bindings: () => bindings(schedule.value) })
  linked.select('graph', [{ view: 'graph', kind: 'node', id: 'cutA' }])

  function track(outcome: Promise<TransactionOutcome<ProductionDocument>>) {
    return outcome.then(result => {
      busy.value = result.status === 'busy'
      return result
    })
  }
  /** Refuses a save while one is unknown, as `busy`: the save bar then asks for the check first. */
  function unlessUnresolved(save: () => Promise<TransactionOutcome<ProductionDocument>>) {
    return track(unresolved.value ? Promise.resolve({ status: 'busy' }) : save())
  }
  function submit(change: ProductionChange, source?: 'pointer' | 'keyboard' | 'api') {
    return unlessUnresolved(() => transaction.submit([change], { source }))
  }
  // Undo, redo and a reload replace the plan the proposal was based on, so they close it.
  function undo() {
    return unlessUnresolved(() => {
      proposal.value = undefined
      return transaction.undo()
    })
  }
  function redo() {
    return unlessUnresolved(() => {
      proposal.value = undefined
      return transaction.redo()
    })
  }
  function reload() {
    const latest = server.fetch()
    proposal.value = undefined
    unanswered = undefined
    busy.value = false
    transaction.refresh(latest.state, latest.version)
  }

  // demo:adopt
  // Adopting saves the open proposal through the app-wide transaction. A save settles either with its own answer or,
  // when that answer was lost, later through `reconcile`; both close the proposal that was saved, and only that one:
  // a proposal opened while the save was in flight stays open. The lost save is remembered by its operation ID.
  let unanswered: { operationId: string; proposal: PlanProposal } | undefined
  function closeAdopted(saved: PlanProposal) {
    if (proposal.value !== saved) return
    proposal.value = undefined
    adoptionNotice.value = true
  }
  async function adopt() {
    const saved = proposal.value
    if (!saved) return
    const outcome = await submit({ area: 'plan', plan: saved.plan })
    if (outcome.status === 'accepted') closeAdopted(saved)
    else if (outcome.status === 'uncertain') unanswered = { operationId: outcome.operationId, proposal: saved }
  }
  function reconcile() {
    const operationId = transaction.pendingTransaction.value?.operationId
    if (!operationId) return
    const stored: SaveResult<ProductionDocument> = server.lookup(operationId) ?? { status: 'rejected', operationId, code: 'not-applied' }
    const outcome = transaction.reconcile(stored)
    // A save refused while this one was unknown is not pending anywhere: the bar shows this result instead.
    busy.value = false
    if (unanswered?.operationId !== operationId || outcome.status === 'uncertain') return
    const saved = unanswered.proposal
    unanswered = undefined
    if (outcome.status === 'accepted') closeAdopted(saved)
  }
  // demo:end
  // The save bar offers no dismissal of an unknown result: it may have been applied, so only a check or a reload settles it.
  function dismiss() {
    busy.value = false
    transaction.clearResult()
  }

  return {
    server, transaction, document, saving, unresolved, locked, busy, proposal, changed, adoptionNotice, adopted, schedule, linked,
    submit, adopt, undo, redo, reload, reconcile, dismiss,
  }
}

export type ProductionWorkspace = ReturnType<typeof createProductionWorkspace>
const workspaceKey: InjectionKey<ProductionWorkspace> = Symbol('production-workspace')

export function provideProductionWorkspace() {
  const workspace = createProductionWorkspace()
  provide(workspaceKey, workspace)
  return workspace
}

export function useProductionWorkspace() {
  const workspace = inject(workspaceKey)
  if (!workspace) throw new Error('The production tabs need provideProductionWorkspace()')
  return workspace
}
vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import { GanttChart, type TimelineBar, type TimelineEdit, type ViewTargetEvent } from '../../src'
import ProcessGraph from './ProcessGraph.vue'
import CodePanel from './CodePanel.vue'
import { copy, type Copy } from './copy'
import { excerpt } from './sections'
import { clock, deadline, displayRange, downstreamEdits, hour, links, maintenance, proposeStart, range, resourceIds, taskIds, type Plan, type Strategy, type TaskId } from './plan'
import { useProductionWorkspace } from './workspace'
import planSource from './plan.ts?raw'
import viewSource from './ProductionPlan.vue?raw'
import workspaceSource from './workspace.ts?raw'

const props = defineProps<{ text: Copy }>()
const initial: Plan = { strategy: 'original', starts: {} }
const workspace = useProductionWorkspace()
const { linked, proposal, schedule } = workspace
const codeOpen = ref(false)
const rejected = ref(false)
// "Plan adopted." follows the workspace, which closes a proposal when its save is accepted, also after a reconcile.
const status = computed(() => rejected.value ? 'rejected' : workspace.adoptionNotice.value ? 'adopted' : undefined)
/** A new or closed proposal clears the messages about the previous one. */
function clearStatus() {
  rejected.value = false
  workspace.adoptionNotice.value = false
}
const draft = computed(() => proposal.value?.plan)
const strategy = computed(() => draft.value ?? workspace.document.value.plan)
const current = workspace.adopted
const changed = workspace.changed
const rows = computed(() => taskIds.map(id => ({ id, label: props.text.tasks[id] })))
const loadRows = computed(() => resourceIds.map(id => ({ id, label: props.text.resources[id] })))
const highlighted = computed(() => new Set<string>(changed.value))
// The operation shown in the details: the first one selected in any view, this tab's or the lot flow's.
const selected = computed(() => linked.selectedEntities.value.find(entity => entity.kind === 'operation')?.id as TaskId | undefined)
const selectedTask = computed(() => selected.value && schedule.value.byId.get(selected.value))
const selectedResource = computed(() => selected.value && schedule.value.resourceFor[selected.value])
const local = (en: string, ja: string) => props.text === copy.ja ? ja : en
const nodes = computed(() => rows.value.map(row => ({ ...row, detail: displayRange(schedule.value.byId.get(row.id)!) })))
const positions = new Map([
  ['prep', { x: 0, y: 82 }], ['cutA', { x: 219, y: 24 }], ['cutB', { x: 219, y: 140 }],
  ['inspect', { x: 438, y: 82 }], ['pack', { x: 657, y: 82 }],
])
const symbols = { prep: '▤', cutA: 'A', cutB: 'B', inspect: '✓', pack: '□' }
const bars = computed<TimelineBar[]>(() => taskIds.map(id => {
  const { start, end } = schedule.value.byId.get(id)!
  const baseline = current.value.byId.get(id)!
  return {
    id, rowId: id, label: props.text.tasks[id], start, end, editable: true,
    ...(highlighted.value.has(id) ? { tone: 'amber' } : {}),
    ...(draft.value && start !== baseline.start ? { baseline } : {}),
  }
}))

// demo:link
// One selection for the whole app: each view reports what it selected, and gets back its own selection and highlights.
const graphSelected = computed(() => [...linked.graph.value.selectedNodeIds].find(id => positions.has(id)) ?? '')
const graphLinked = computed(() => linked.graph.value.highlightedNodeIds)
const selectNode = (id: string) => linked.select('graph', [{ view: 'graph', kind: 'node', id }])
const selectBar = (id: string) => linked.select('timeline', [{ view: 'timeline', kind: 'bar', id }])
const activateLoad = (event: ViewTargetEvent) => event.target.view === 'load' && linked.select('load', [event.target])
const clearSelection = () => linked.clearSelection()
// demo:end

function openScenario(value: Exclude<Strategy, 'original'>) {
  // Reopening the strategy in use keeps its manual starts, so an adopted move is not silently dropped.
  const base = strategy.value
  const plan = { strategy: value, starts: value === base.strategy ? base.starts : {} }
  proposal.value = { plan }
  clearStatus()
}

function validate(change: TimelineEdit) {
  return change.mode === 'move' && Boolean(proposeStart(strategy.value, change.id as TaskId, change.after.start)) || props.text.rejected
}

function cascade(change: TimelineEdit) {
  if (change.mode !== 'move') return []
  const next = proposeStart(strategy.value, change.id as TaskId, change.after.start)
  return next ? downstreamEdits(schedule.value, next.computed, change) : []
}

function move(id: TaskId, start: number) {
  const next = proposeStart(strategy.value, id, start)
  if (!next) { rejected.value = true; return }
  proposal.value = { plan: next.next, moved: id }
  clearStatus()
}

function commitEdits(changes: TimelineEdit[]) {
  const first = changes[0]
  if (first) move(first.id as TaskId, first.after.start)
}

function dismiss() {
  proposal.value = undefined
  clearStatus()
}

function reset() {
  dismiss()
  void workspace.submit({ area: 'plan', plan: initial })
  selectNode('cutA')
}

const examples = computed(() => [
  { label: props.text.codeLink, code: excerpt(viewSource, 'link') + '\n\n' + excerpt(workspaceSource, 'link'), path: 'ProductionPlan.vue' },
  { label: props.text.codeReplan, code: excerpt(planSource, 'edit'), path: 'plan.ts' },
  { label: props.text.codeAdopt, code: excerpt(workspaceSource, 'adopt'), path: 'workspace.ts' },
  { label: props.text.codeSave, code: excerpt(workspaceSource, 'save'), path: 'workspace.ts' },
])
</script>

<template>
  <div class="production-title">
    <div><h1>{{ text.planning }}</h1><p>{{ text.introPlan }}</p></div>
    <div class="production-actions">
      <button type="button" @click="reset">{{ text.reset }}</button>
      <button type="button" :aria-expanded="codeOpen" @click="codeOpen = !codeOpen">{{ text.code }}</button>
    </div>
  </div>
  <CodePanel v-if="codeOpen" :text="text" :examples="examples" />

  <div class="production-incident"><span aria-hidden="true">!</span><strong>{{ text.maintenance }}</strong>{{ text.outage }}</div>
  <div class="production-layout">
    <div class="production-stack">
      <section class="production-panel">
        <div class="production-heading"><h2>{{ text.graph }}</h2><code>NetworkGraph</code></div>
        <ProcessGraph :selected-id="graphSelected" :linked-ids="graphLinked" :text="text" :label="text.graph"
          :nodes="nodes" :edges="links" :positions="positions" :symbols="symbols"
          :highlighted="highlighted" :height="265" @select="selectNode" @clear="clearSelection" />
      </section>

      <section class="production-panel">
        <div class="production-heading"><h2>{{ text.gantt }}</h2><code>GanttChart</code></div>
        <GanttChart :rows="rows" :bars="bars" :range="range" :dependencies="schedule.dependencies"
          :selected-ids="linked.timeline.value.selectedBarIds" :highlighted-bar-ids="linked.timeline.value.highlightedBarIds" :snap="hour" :tick-steps="[2 * hour, 4 * hour]"
          :label-width="106" :pixels-per-unit="42 / hour" :height="230" :row-height="34" :format-time="clock"
          :markers="[{ id: 'shipping', time: deadline, label: text.deadline }]"
          :labels="{ ...text.labels.gantt, region: text.gantt, editHint: text.planHelp, zoom: text.zoom, zoomIn: text.zoomIn, zoomOut: text.zoomOut }"
          :cascade="cascade" :validate-edit="validate" :validate-edits="changes => validate(changes[0]!)" @select="selectBar"
          @edit="change => commitEdits([change])" @edits="commitEdits"
          @edit-rejected="rejected = true" @edits-rejected="rejected = true" @background-click="clearSelection" @idle-escape="clearSelection">
          <template #row-heading>{{ text.task }}</template>
        </GanttChart>
        <p class="production-caption">{{ text.planHelp }} {{ local('Click empty chart space or press Escape to clear the selection.', '何もない所をクリックするか Escape で選択を解除します。') }}</p>
      </section>

      <section class="production-panel">
        <div class="production-heading"><h2>{{ text.load }}</h2><code>calculateResourceLoad</code></div>
        <GanttChart :rows="[]" :bars="[]" :range="range" :tick-steps="[2 * hour, 4 * hour]" :label-width="106"
          :pixels-per-unit="42 / hour" :height="224" :load-row-height="34" :format-time="clock"
          :load-rows="loadRows" :load-segments="schedule.load"
          :highlighted-load-targets="linked.load.value.highlighted" :selected-load-targets="linked.load.value.selected"
          :marker-ranges="[{ id: 'maintenance', ...maintenance, label: text.maintenance, tone: 'amber' }]"
          :labels="{ ...text.labels.gantt, region: text.load, empty: text.load, editHint: '', loadRegion: text.load, load: text.load, capacity: text.capacity, zoom: text.zoom, zoomIn: text.zoomIn, zoomOut: text.zoomOut }"
          load-selectable @target-activate="activateLoad">
          <template #row-heading>{{ text.resource }}</template>
        </GanttChart>
      </section>
    </div>

    <aside class="production-stack">
      <section class="production-panel">
        <div class="production-heading"><h2>{{ text.compare }}</h2></div>
        <div class="production-content">
          <div class="production-scenarios">
            <button v-for="op in (['wait', 'backup'] as const)" :key="op" type="button" :aria-pressed="strategy.strategy === op"
              @click="openScenario(op)"><strong>{{ text[op] }}</strong><small>{{ text[op === 'wait' ? 'waitDetail' : 'backupDetail'] }}</small></button>
          </div>
          <table class="production-table">
            <thead><tr><td></td><th scope="col">{{ text.current }}</th><th v-if="draft" scope="col">{{ text.draft }}</th></tr></thead>
            <tbody>
              <tr><th scope="row">{{ text.ship }}</th><td>{{ clock(current.shipping) }}</td><td v-if="draft">{{ clock(schedule.shipping) }}</td></tr>
              <tr><th scope="row">{{ text.late }}</th><td>{{ current.lateHours }}{{ text.hours }}</td><td v-if="draft">{{ schedule.lateHours }}{{ text.hours }}</td></tr>
              <tr><th scope="row">{{ text.overload }}</th><td>{{ current.cncOverload }}{{ text.hours }}</td><td v-if="draft">{{ schedule.cncOverload }}{{ text.hours }}</td></tr>
            </tbody>
          </table>
          <div class="production-actions">
            <button v-if="draft" class="primary" type="button" :disabled="workspace.locked.value" @click="workspace.adopt">{{ text.adopt }}</button>
            <button v-if="draft" type="button" @click="dismiss">{{ text.dismiss }}</button>
          </div>
        </div>
      </section>
      <section class="production-panel">
        <div class="production-heading"><h2>{{ text.details }}</h2></div>
        <div class="production-content">
          <template v-if="selected && selectedTask && selectedResource">
            <strong>{{ text.tasks[selected] }}</strong>
            <dl><dt>{{ text.schedule }}</dt><dd>{{ displayRange(selectedTask) }}</dd><dt>{{ text.resource }}</dt><dd>{{ text.resources[selectedResource] }}</dd></dl>
            <div class="production-actions">
              <button type="button" :aria-label="text.early" @click="move(selected, selectedTask.start - hour)">−1{{ text.hours }}</button>
              <button type="button" :aria-label="text.later" @click="move(selected, selectedTask.start + hour)">+1{{ text.hours }}</button>
            </div>
          </template>
          <p v-else class="production-caption">{{ local('Select an operation in the graph or the chart to see its details.', 'グラフかチャートで作業を選ぶと、その詳細を表示します。') }}</p>
          <p class="production-caption">{{ text.selectionNote }}</p>
          <p v-if="changed.length" class="production-caption">{{ text.affected }} · {{ changed.map(id => text.tasks[id]).join(' / ') }}</p>
          <p v-if="status" role="status" class="production-caption">{{ text[status] }}</p>
        </div>
      </section>
    </aside>
  </div>
</template>
ts
import {
  calculateResourceLoad, scheduleTasks, type ScheduleLink, type TimeRange, type TimelineEdit,
} from '../../src'

export const hour = 3_600_000
export const range = { start: 8 * hour, end: 24 * hour }
export const deadline = 19 * hour
export const maintenance = { start: 10 * hour, end: 13 * hour }
export const taskIds = ['prep', 'cutA', 'cutB', 'inspect', 'pack'] as const
export type TaskId = typeof taskIds[number]
export const resourceIds = ['workbench', 'cnc', 'saw', 'bench', 'dispatch'] as const
export type Strategy = 'original' | 'wait' | 'backup'
export interface Plan {
  strategy: Strategy
  starts: Partial<Record<TaskId, number>>
}

const duration = { prep: 2, cutA: 3, cutB: 2, inspect: 2, pack: 2 }
export const links: ScheduleLink[] = [
  { id: 'prep-a', from: 'prep', to: 'cutA' },
  { id: 'prep-b', from: 'prep', to: 'cutB' },
  { id: 'a-inspect', from: 'cutA', to: 'inspect' },
  { id: 'b-inspect', from: 'cutB', to: 'inspect' },
  { id: 'inspect-pack', from: 'inspect', to: 'pack' },
]
const waitLinks = [...links, { id: 'a-b', from: 'cutA', to: 'cutB' }]
const resources = resourceIds.map(id => ({
  id, capacity: 1, ...(id === 'cnc' ? { capacityPeriods: [{ ...maintenance, capacity: 0 }] } : {}),
}))

export function clock(time: number) {
  return String(Math.floor(time / hour)).padStart(2, '0') + ':00'
}

export function displayRange(task: TimeRange) {
  return clock(task.start) + '–' + clock(task.end)
}

// The starting plan still includes work during maintenance. Both alternatives respect the outage.
export function calculatePlan(plan: Plan) {
  const resourceFor = {
    prep: 'workbench', cutA: plan.strategy === 'backup' ? 'saw' : 'cnc',
    cutB: 'cnc', inspect: 'bench', pack: 'dispatch',
  } as const
  const dependencies = plan.strategy === 'wait' ? waitLinks : links
  const tasks = taskIds.map(id => {
    const afterMaintenance = (id === 'cutA' && plan.strategy === 'wait')
      || (id === 'cutB' && plan.strategy !== 'original')
    return {
      id, duration: duration[id] * hour,
      startNoEarlierThan: Math.max(plan.starts[id] ?? range.start, afterMaintenance ? maintenance.end : range.start),
    }
  })
  const schedule = scheduleTasks({ range, tasks, dependencies, quantum: hour })
  if (!schedule.ok) return undefined

  const byId = new Map(schedule.tasks.map(task => [task.id, task]))
  const load = calculateResourceLoad(range, schedule.tasks, resources,
    taskIds.map(taskId => ({ taskId, resourceId: resourceFor[taskId] })))
    .filter(segment => segment.load > 0)
  const shipping = byId.get('pack')!.end
  const lateHours = Math.max(0, shipping - deadline) / hour
  const cncOverload = load.filter(segment => segment.resourceId === 'cnc' && segment.overload > 0)
    .reduce((hours, segment) => hours + (segment.end - segment.start) / hour, 0)
  return { dependencies, byId, resourceFor, load, shipping, lateHours, cncOverload }
}

export type Schedule = NonNullable<ReturnType<typeof calculatePlan>>

// demo:edit
// Apply a proposed start to the input. The scheduler recomputes all dependent tasks in the same transaction.
export function proposeStart(plan: Plan, id: TaskId, start: number) {
  if (!Number.isInteger(start / hour) || start < range.start || start >= range.end) return undefined
  const next = { ...plan, starts: { ...plan.starts, [id]: start } }
  const computed = calculatePlan(next)
  if (!computed || computed.byId.get(id)!.start !== start) return undefined
  return { next, computed }
}

// Give GanttChart the downstream dates so it can preview them during the drag.
export function downstreamEdits(before: Schedule, after: Schedule, change: TimelineEdit): TimelineEdit[] {
  return taskIds.filter(id => id !== change.id && before.byId.get(id)!.start !== after.byId.get(id)!.start)
    .map(id => ({
      id, before: before.byId.get(id)!, after: after.byId.get(id)!, mode: 'move', source: change.source,
    }))
}
// demo:end
vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import { layoutFlowGraph, type GraphEdge, type NetworkNode } from '../../src'
import CodePanel from './CodePanel.vue'
import ProcessGraph from './ProcessGraph.vue'
import type { Copy } from './copy'
import { flows } from './lot-transfers'
import { excerpt } from './sections'
import { stepEntity, stepOf, useProductionWorkspace } from './workspace'
import source from './LotFlow.vue?raw'

const props = defineProps<{ text: Copy; isJapanese: boolean }>()
const unit = ref<'pcs' | 'EUR'>('pcs')
const { linked } = useProductionWorkspace()
// The step shown in the details: the first selected entity that is a step of this lot, selected here or in planning.
const selected = computed(() => linked.selectedEntities.value.map(stepOf).find(id => id !== undefined) ?? '')
const graphSelected = computed(() => [...linked.graph.value.selectedNodeIds].find(id => positions.has(id)) ?? '')
const selectStep = (id: string) => linked.selectEntities([stepEntity(id)], { source: 'lot-table' })
const codeOpen = ref(false)
const ids = ['lot', 'overhead', 'line-a', 'line-b', 'inspect', 'pack', 'rework'] as const
type Step = typeof ids[number]
const symbols = { lot: '▤', 'line-a': 'A', 'line-b': 'B', inspect: '✓', pack: '□', rework: '↶' }
const positions = new Map([
  ['lot', { x: 0, y: 127 }], ['line-a', { x: 223, y: 50 }], ['line-b', { x: 223, y: 204 }],
  ['inspect', { x: 446, y: 127 }], ['pack', { x: 669, y: 50 }], ['rework', { x: 669, y: 204 }],
])

function amount(value: number) {
  const number = value.toLocaleString(props.isJapanese ? 'ja-JP' : 'en-US')
  return number + (unit.value === 'EUR' ? ' €' : props.isJapanese ? '個' : ' pcs')
}

const nodes = computed<NetworkNode[]>(() => ids.map(id => {
  const overhead = unit.value === 'EUR' && flows.find(edge => edge.from === 'overhead' && edge.to === id)?.data?.EUR
  return {
    id, label: props.text.steps[id],
    ...(overhead ? { detail: '+' + amount(overhead) } : {}),
    ...(id === 'rework' || id === 'inspect' ? {
      ports: [{ id: 'return', side: id === 'rework' ? 'left' : 'right', offset: 0.92 }],
    } : {}),
  }
}))

// demo:flow
// Compare quantities in one unit at a time. The library separates the return loop from normal totals.
const projection = computed(() => layoutFlowGraph(nodes.value, flows, {
  quantity: edge => edge.data![unit.value] ?? edge.data!.EUR,
  unit: edge => unit.value === 'pcs' && edge.data!.pcs !== undefined ? 'pcs' : 'EUR',
  displayUnit: unit.value,
}))
const reference = computed(() => projection.value.bands.find(band => band.reference)!)
const totals = computed(() => projection.value.nodes.filter(row => row.id !== 'overhead' || unit.value === 'EUR'))
// demo:end

const diagramNodes = computed(() => nodes.value.filter(node => node.id !== 'overhead'))
const diagramEdges = computed<GraphEdge[]>(() => projection.value.bands.filter(band => band.from !== 'overhead').map(band => ({
  id: band.edgeId, from: band.from, to: band.to, label: amount(band.quantity), markerEnd: 'open-arrow',
  ...(band.reference ? { fromPort: 'return', toPort: 'return', animated: true } : {}),
})))
// Undefined while nothing is selected: a click on the empty graph canvas or Escape in it clears the selection.
const detail = computed(() => totals.value.find(row => row.id === selected.value))
const examples = computed(() => [{ label: props.text.codeFlow, path: 'LotFlow.vue', code: excerpt(source, 'flow') }])

function changeUnit(next: typeof unit.value) {
  unit.value = next
  if (next === 'pcs' && selected.value === 'overhead') selectStep('lot')
}
</script>

<template>
  <div class="production-title">
    <div><h1>{{ text.lot }}</h1><p>{{ text.introLot }}</p></div>
    <div class="production-actions">
      <div class="production-switch" role="group" :aria-label="text.unit">
        <button type="button" :aria-pressed="unit === 'pcs'" @click="changeUnit('pcs')">{{ text.pieces }}</button>
        <button type="button" :aria-pressed="unit === 'EUR'" @click="changeUnit('EUR')">{{ text.cost }}</button>
      </div>
      <button type="button" :aria-expanded="codeOpen" @click="codeOpen = !codeOpen">{{ text.code }}</button>
    </div>
  </div>
  <CodePanel v-if="codeOpen" :text="text" :examples="examples" />
  <div class="production-layout flow-layout">
    <section class="production-panel">
      <div class="production-heading"><h2>{{ text.lotLabel }}</h2><code>NetworkGraph</code></div>
      <ProcessGraph :selected-id="graphSelected" :linked-ids="linked.graph.value.highlightedNodeIds" :text="text" :label="text.lotLabel"
        :nodes="diagramNodes" :edges="diagramEdges" :positions="positions" :symbols="symbols" :height="420"
        @select="id => linked.select('graph', [{ view: 'graph', kind: 'node', id }])" @clear="linked.clearSelection()" />
      <div class="production-content production-note">
        <strong><span class="return-line" aria-hidden="true"></span>{{ text.handling }} {{ amount(reference.quantity) }}</strong>
        <p>{{ text.returnNote }}</p>
        <p v-if="unit === 'EUR'">{{ text.overheadNote }}</p>
      </div>
    </section>

    <aside class="production-stack">
      <section class="production-panel">
        <div class="production-heading"><h2>{{ text.stepDetail }}</h2></div>
        <div class="production-content" aria-live="polite">
          <template v-if="detail">
            <strong>{{ text.steps[selected as Step] }}</strong>
            <dl><dt>{{ text.input }}</dt><dd>{{ amount(detail.inflow) }}</dd><dt>{{ text.output }}</dt><dd>{{ amount(detail.outflow) }}</dd>
              <template v-if="selected === 'line-b'"><dt>{{ text.diff }}</dt><dd>{{ amount(detail.difference) }}</dd></template>
              <template v-if="detail.referenceInflow || detail.referenceOutflow"><dt>{{ text.handling }}</dt><dd>{{ amount(detail.referenceInflow || detail.referenceOutflow) }}</dd></template>
            </dl>
          </template>
          <p v-else class="production-caption">{{ isJapanese ? 'グラフか表で工程を選ぶと、その数量を表示します。' : 'Select a step in the graph or the table to see its quantities.' }}</p>
          <p class="production-caption">{{ text.lotSelectionNote }}</p>
        </div>
      </section>
      <section class="production-panel">
        <div class="production-content">
          <table class="production-table">
            <thead><tr><th scope="col">{{ text.step }}</th><th scope="col">{{ text.input }}</th><th scope="col">{{ text.output }}</th></tr></thead>
            <tbody>
              <tr v-for="row in totals" :key="row.id" :class="{ active: row.id === selected }">
                <th scope="row"><button type="button" :aria-pressed="row.id === selected" @click="selectStep(row.id)">{{ text.steps[row.id as Step] }}</button></th>
                <td>{{ amount(row.inflow) }}</td><td>{{ amount(row.outflow) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </aside>
  </div>
</template>
vue
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NetworkGraph, findGraphCycles, type GraphConnection, type GraphNodeMove, type NetworkNode } from '../../src'
import { componentLabels } from '../i18n'
import { outputs, type Flow, type Step } from './approval'
import { useProductionWorkspace } from './workspace'

const props = defineProps<{ ja: boolean }>()
const t = (ja: string, en: string) => props.ja ? ja : en
// The workflow is part of the app's saved document; its selection is its own, because no other tab shows these steps.
const workspace = useProductionWorkspace()
const flow = computed(() => workspace.document.value.approval)
const selected = ref('amount')
const step = computed(() => flow.value.steps.find(s => s.id === selected.value))
const warning = ref('')
let serial = 0
function label(s: Step) { return s.name[props.ja ? 0 : 1] }
function portName(port: string, from: string) {
  const amount = flow.value.steps.find(s => s.id === from)?.threshold ?? 0
  const limit = '¥' + amount.toLocaleString('en-US')
  if (port === 'low') return '< ' + limit
  if (port === 'high') return '≥ ' + limit
  return t('次のステップ', 'Next step')
}
const nodes = computed<NetworkNode[]>(() => flow.value.steps.map(s => ({
  id: s.id, label: label(s), detail: s.assignee,
  shape: s.kind === 'decision' ? 'diamond' : undefined,
  ports: [...(s.kind === 'start' ? [] : [{ id: 'in', side: 'left' as const }]),
    ...outputs(s).map((id, i, ports) => ({ id, side: 'right' as const, offset: (i + 1) / (ports.length + 1), label: portName(id, s.id) }))],
})))
const edges = computed(() => flow.value.edges.map(e => ({ ...e, label: e.fromPort === 'out' ? undefined : portName(e.fromPort!, e.from) })))
function commit(patch: Partial<Flow>) {
  warning.value = ''
  void workspace.submit({ area: 'approval', flow: { ...flow.value, ...patch } })
}
function validate(c: GraphConnection, replacing?: string) {
  const source = flow.value.steps.find(s => s.id === c.from)
  if (!source || !outputs(source).includes(c.fromPort ?? '') || c.toPort !== 'in' || c.to === 'request') {
    return t('出口から次のステップの入口へつないでください。', 'Connect an output to a step input.')
  }
  const other = flow.value.edges.filter(e => e.id !== replacing)
  if (other.some(e => e.from === c.from && e.fromPort === c.fromPort)) return t('この出口には接続先があります。', 'This output already has a destination.')
  if (findGraphCycles(nodes.value, [...other, { ...c, id: replacing ?? 'candidate' }]).length) return t('循環する経路は設定できません。', 'This route would create a cycle.')
}
function connect(c: GraphConnection, replacing?: string) {
  const reason = validate(c, replacing)
  if (reason) { warning.value = reason; return }
  const next = { id: replacing ?? 'edge-' + ++serial, ...c }
  commit({ edges: [...flow.value.edges.filter(e => e.id !== replacing), next] })
}
function route(port: string, to: string) {
  const from = selected.value
  const old = flow.value.edges.find(e => e.from === from && e.fromPort === port)
  if (to) connect({ from, fromPort: port, to, toPort: 'in' }, old?.id)
  else commit({ edges: flow.value.edges.filter(e => e !== old) })
}
function add(kind: 'approval' | 'decision') {
  const id = kind + '-' + ++serial
  const added: Step = kind === 'approval'
    ? { id, kind, name: ['追加承認', 'Additional review'] }
    : { id, kind, name: ['金額条件', 'Amount condition'], threshold: 100000 }
  commit({ steps: [...flow.value.steps, added] })
  selected.value = id
}
function updateStep(patch: Partial<Step>) {
  commit({ steps: flow.value.steps.map(s => s.id === selected.value ? { ...s, ...patch } : s) })
}
function remove() {
  const id = selected.value
  if (!step.value || step.value.kind === 'start' || step.value.kind === 'end') return
  const positions = new Map(flow.value.positions)
  positions.delete(id)
  commit({ steps: flow.value.steps.filter(s => s.id !== id), edges: flow.value.edges.filter(e => e.from !== id && e.to !== id), positions })
  selected.value = 'request'
}
function move(change: GraphNodeMove) { commit({ positions: new Map(flow.value.positions).set(change.id, change.after) }) }
// A click on the empty canvas or Escape in the graph clears the selection (an empty string).
function clearSelection() {
  selected.value = ''
}
// An app-wide undo can remove the selected step.
watch(step, value => { if (selected.value && !value) selected.value = 'request' })
function threshold(input: HTMLInputElement) {
  if (input.value && Number.isSafeInteger(input.valueAsNumber) && input.valueAsNumber >= 0) updateStep({ threshold: input.valueAsNumber })
  else input.value = String(step.value?.threshold ?? 0)
}
function destination(port: string) { return flow.value.edges.find(e => e.from === selected.value && e.fromPort === port)?.to ?? '' }
function pickRoute(port: string, select: HTMLSelectElement) { route(port, select.value); select.value = destination(port) }
</script>

<template>
  <div class="production-title"><div><h1>{{ t('承認フロー', 'Approval workflow') }}</h1>
    <p>{{ t('購買申請の承認者と、金額に応じた経路を編集できます。', 'Edit approvers and route purchase requests by amount.') }}</p></div>
    <div class="production-actions"><button @click="add('approval')">{{ t('承認ステップを追加', 'Add approval step') }}</button>
      <button @click="add('decision')">{{ t('条件分岐を追加', 'Add decision') }}</button></div></div>
  <div class="production-layout">
    <section class="production-panel"><div class="production-heading"><h2>{{ t('承認経路', 'Approval routes') }}</h2></div>
      <NetworkGraph v-model:selected-id="selected" :nodes="nodes" :edges="edges" :positions="flow.positions"
        :options="{ direction: 'LR', nodeWidth: 165, nodeHeight: 64, columnGap: 135 }" :height="360" background="dots" :labels="componentLabels(ja ? 'ja' : 'en').graph"
        draggable connectable reconnectable :validate-connection="validate" @node-move="move" @connect="connect"
        @reconnect="connect($event.after, $event.id)" @connect-rejected="(_change, reason) => warning = reason"
        @background-click="clearSelection" @idle-escape="clearSelection" />
    </section>
    <section class="production-panel"><div class="production-heading"><h2>{{ t('ステップの設定', 'Step settings') }}</h2></div>
      <div class="production-content workflow-fields">
        <label>{{ t('編集するステップ', 'Selected step') }}<select v-model="selected"><option v-if="!step" value="" disabled>{{ t('未選択', 'None') }}</option><option v-for="s in flow.steps" :key="s.id" :value="s.id">{{ label(s) }}</option></select></label>
        <template v-if="step">
          <label>{{ t('表示名', 'Step name') }}<input :value="label(step)" @change="e => { const el = e.target as HTMLInputElement; const name = el.value.trim(); if (name) updateStep({ name: [name, name] }); else el.value = label(step!) }"></label>
          <label v-if="step.kind === 'approval'">{{ t('承認者', 'Approver') }}<input :value="step.assignee" @change="updateStep({ assignee: ($event.target as HTMLInputElement).value.trim() })"></label>
          <label v-if="step.kind === 'decision'">{{ t('分岐の基準額(円)', 'Amount threshold (JPY)') }}<input type="number" min="0" step="1" :value="step.threshold" @change="threshold($event.target as HTMLInputElement)"></label>
          <label v-for="port in outputs(step)" :key="port">{{ portName(port, step.id) }}
            <select :value="destination(port)" @change="pickRoute(port, $event.target as HTMLSelectElement)"><option value="">{{ t('未接続', 'Unconnected') }}</option>
              <option v-for="s in flow.steps.filter(s => s.kind !== 'start' && s.id !== selected)" :key="s.id" :value="s.id">{{ label(s) }}</option></select></label>
          <button v-if="step.kind === 'approval' || step.kind === 'decision'" @click="remove">{{ t('ステップを削除', 'Delete step') }}</button>
        </template>
        <p v-else>{{ t('グラフか一覧でステップを選ぶと、その設定を編集できます。', 'Select a step in the graph or the list to edit its settings.') }}</p>
        <p role="status">{{ warning }}</p>
      </div>
    </section>
  </div>
</template>
vue
<script setup lang="ts">
// A project plan in the style of a scheduling app: the task grid on the left is the source of truth, and the bars,
// arrows and critical path on the right are derived from it by the core scheduler on every change.
import { computed, ref } from 'vue'
import {
  GanttChart, applyTimelineSheetEdit, formatFieldValue, scheduledBarFields, type FieldValue, type ScheduleResult, type TimelineColumn, type TimelineEdit,
  type TimelineFieldEdit, type TimelineFieldSpec, type TimelineSheetEdit,
} from '../../src'
import { componentLabels } from '../i18n'
import { names, origin, scheduleSheet as schedule, sheetLinks as links, sheetRange as range, weekends, type Task } from './sheet'
import { useProductionWorkspace } from './workspace'

const props = defineProps<{ ja: boolean }>()
const t = (ja: string, en: string) => props.ja ? ja : en
// The task grid is part of the app's saved document: edits are saved through the app-wide transaction.
const workspace = useProductionWorkspace()
const tasks = computed(() => workspace.document.value.sheet)

const workDays = (start: number, end: number) => Array.from({ length: end - start }, (_, i) => (start + i) % 7 < 5).filter(Boolean).length
const formatDay = (day: number) => { const date = new Date(origin + day * 86_400_000); return `${date.getUTCMonth() + 1}/${date.getUTCDate()}` }
function parseDay(text: string): FieldValue | { error: string } {
  const match = /^(\d{1,2})\/(\d{1,2})$/.exec(text.trim())
  const day = match ? (Date.UTC(2027, Number(match[1]) - 1, Number(match[2])) - origin) / 86_400_000 : NaN
  return Number.isInteger(day) && day >= range.start && day < range.end ? day : { error: t('3/1〜5/9 の日付を「月/日」で入力してください', 'Enter a date from 3/1 to 5/9 as month/day') }
}

// This tab saves only sheets that schedule, but the document can also come from the server (a reload after a conflict,
// a reconciled save) and a ScheduleResult can be a failure. Then the grid stays editable without dates and the cause is
// shown, so the planner can fix the sheet; nothing reads the tasks of a failed result.
const result = computed(() => schedule(tasks.value))
const plan = computed(() => result.value.ok ? result.value : undefined)
const isSummary = (id: string) => tasks.value.some(item => item.parentId === id)

const rows = computed(() => tasks.value.map((item, index) => ({
  id: item.id, parentId: item.parentId, label: names[item.id]![props.ja ? 0 : 1], number: index + 1, task: item, planned: plan.value?.tasks[index],
})))
type Row = typeof rows.value[number]
const numberOf = (id: string) => rows.value.find(row => row.id === id)!.number
/** Why a sheet does not schedule, in the planner's terms. */
function failureText(failure: Extract<ScheduleResult, { ok: false }>) {
  if (failure.code === 'cycle') {
    const numbers = failure.cycles[0]!.taskIds.map(numberOf).join(', ')
    return t(`先行関係が循環しています(タスク ${numbers})。`, `The predecessors form a cycle (tasks ${numbers}).`)
  }
  const label = rows.value.find(row => row.id === failure.taskId)?.label ?? failure.taskId
  return t(`「${label}」が計画期間(3/1〜5/9)に収まりません。`, `${label} does not fit in the project window (3/1 to 5/9).`)
}
const failure = computed(() => result.value.ok ? '' : t('保存されている工程表はスケジュールできません: ', 'The saved sheet cannot be scheduled: ')
  + failureText(result.value) + t('期間や開始日を直してください。', ' Change a duration or start to fix it.'))

const resources = computed(() => [['design', '設計', 'Design'], ['purchasing', '購買', 'Purchasing'], ['machining', '機械加工', 'Machining'],
  ['maintenance', '保全', 'Maintenance'], ['assembly', '組立班', 'Assembly'], ['qa', '品質保証', 'QA']].map(([value, ja, en]) => ({ value: value!, label: t(ja!, en!) })))
const leaf = (row: Row) => !isSummary(row.id)
// Each typed column has a `field`: the sheet parses, validates and formats cell text through it.
const columns = computed<TimelineColumn<Row>[]>(() => {
  const column = (id: string, label: string, width: number, spec: Omit<TimelineFieldSpec<Row>, 'id'>): TimelineColumn<Row> => {
    const field = { id, ...spec }
    return { id, label, width, editable: leaf, field, value: row => formatFieldValue(field, field.get(row)) }
  }
  return [
    { id: 'number', label: '#', width: 56, value: row => row.number },
    column('start', t('開始', 'Start'), 70, { kind: 'number', get: row => row.planned?.start ?? row.task.start ?? null, parse: parseDay, format: value => value === null ? '' : formatDay(Number(value)) }),
    column('duration', t('期間', 'Duration'), 76, { kind: 'duration', required: true, max: 60, unitLabel: t('日', 'd'), durationBasis: 'working',
      get: row => leaf(row) ? row.task.duration : row.planned ? workDays(row.planned.start, row.planned.end) : null }),
    column('after', t('先行', 'Predecessors'), 104, { kind: 'text', get: row => row.task.after.map(numberOf).join(', ') || null,
      parse: text => /^\d+(\s*,\s*\d+)*$/.test(text.trim()) ? text.trim().split(/\s*,\s*/).join(', ') : { error: t('「2, 3」のようにタスク番号で入力してください', 'Use task numbers such as 2, 3') } }),
    column('resource', t('担当', 'Resource'), 116, { kind: 'select', choices: resources.value, get: row => row.task.resource }),
    column('done', t('進捗 %', '% done'), 68, { kind: 'number', integer: true, min: 0, max: 100, get: row => leaf(row) ? row.task.done : Math.round(summaryDone(row.id)) }),
  ]
})
function summaryDone(id: string): number {
  const children = rows.value.filter(row => row.parentId === id)
  const weight = children.reduce((sum, row) => sum + row.task.duration, 0)
  return weight ? children.reduce((sum, row) => sum + row.task.duration * row.task.done, 0) / weight : 0
}

// Bars, arrows and the critical path come straight from the plan; summary rows get rollup bars from `showSummaries`.
// The weekend gaps of `segments` are left out, so bars run across weekends as in most project tools.
const bars = computed(() => rows.value.filter(leaf).flatMap(row => {
  if (!row.planned) return []
  const { segments: _, ...fields } = scheduledBarFields(row.planned)
  return { id: row.id, rowId: row.id, label: row.label, editable: true, progress: row.task.done / 100, ...fields }
}))
const dependencies = computed(() => plan.value ? links(tasks.value) : [])
const critical = computed(() => new Set(plan.value?.criticalDependencyIds))

// Every change goes through `plan`: it schedules the new tasks first and refuses the whole change when that fails.
const message = ref('')
function planChange(change: (rows: Row[]) => Row[]): { tasks: Task[] } | { reason: string } {
  let next: Task[], result: ScheduleResult
  try {
    next = change(rows.value).map(row => row.task)
    result = schedule(next)
  } catch (error) {
    return { reason: (error as Error).message }
  }
  if (result.ok) return { tasks: next }
  return { reason: result.code === 'cycle'
    ? t(`先行関係が循環するため取り消しました(タスク ${result.cycles[0]!.taskIds.map(numberOf).join(', ')})。`, `Rejected: the predecessors would form a cycle (tasks ${result.cycles[0]!.taskIds.map(numberOf).join(', ')}).`)
    : t('計画期間に収まらないため取り消しました。', 'Rejected: the plan would not fit in the project window.') }
}
function commit(change: (rows: Row[]) => Row[], source?: 'pointer' | 'keyboard') {
  const planned = planChange(change)
  if ('reason' in planned) return void (message.value = planned.reason)
  message.value = ''
  void workspace.submit({ area: 'sheet', tasks: planned.tasks }, source)
}
// Writes one typed edit into a row's task. Throwing here rejects the whole batch before anything is committed.
function writeField(row: Row, edit: TimelineFieldEdit<Row>): Row {
  const value = edit.after
  const item = { ...row.task }
  if (edit.fieldId === 'start') item.start = value === null ? undefined : Number(value)
  else if (edit.fieldId === 'duration') item.duration = Number(value)
  else if (edit.fieldId === 'resource') item.resource = value as string | null
  else if (edit.fieldId === 'done') item.done = Number(value ?? 0)
  else if (edit.fieldId === 'after') {
    item.after = value === null ? [] : String(value).split(', ').map(text => {
      const from = rows.value[Number(text) - 1]
      if (!from) throw new Error(t(`タスク ${text} は存在しないため取り消しました。`, `Rejected: task ${text} does not exist.`))
      if (from.id === row.parentId || from.parentId === row.id) throw new Error(t(`タスク ${text} は自身の親または子です。`, `Rejected: task ${text} is the task's own summary or subtask.`))
      return from.id
    })
  }
  return { ...row, task: item }
}
// A single cell edit and a whole paste, fill or clear batch use the same helper, so they commit as one undo step each.
const applyField = (edit: TimelineFieldEdit<Row>) => commit(current => applyTimelineSheetEdit(current, { fieldEdits: [edit] }, { field: writeField }), edit.source)
const sheetChange = (batch: TimelineSheetEdit<Row>) => (current: Row[]) => applyTimelineSheetEdit(current, batch, { field: writeField })
const applySheet = (batch: TimelineSheetEdit<Row>) => commit(sheetChange(batch))
// `validateSheetEdit` checks a whole paste, fill or clear before it is proposed; the chart then emits
// `sheet-edit-rejected` with the reason instead of `sheet-edit`.
function checkSheet(batch: TimelineSheetEdit<Row>) {
  const planned = planChange(sheetChange(batch))
  return 'reason' in planned ? planned.reason : true
}
// A bar move sets the start constraint; a resize sets the duration in working days.
function applyBar(edit: TimelineEdit) {
  commit(current => current.map(row => row.id !== edit.id ? row : { ...row, task: { ...row.task,
    start: edit.mode === 'end' ? row.task.start : edit.after.start,
    duration: edit.mode === 'move' ? row.task.duration : workDays(edit.after.start, edit.after.end) } }), edit.source)
}
const checkDuration = (edit: TimelineFieldEdit<Row>) =>
  edit.fieldId !== 'duration' || Number.isInteger(edit.after) || t('期間は日単位で入力してください', 'Durations are whole days')
</script>

<template>
  <div class="production-title"><div><h1>{{ t('工程表', 'Schedule sheet') }}</h1>
    <p>{{ t('表を編集すると、スケジューラーがバー・矢印・クリティカルパスを計算し直します。', 'Edit the task grid; the scheduler recalculates the bars, arrows and critical path.') }}</p></div>
    </div>
  <section class="production-panel"><div class="production-heading"><h2>{{ t('ライン3 改修プロジェクト', 'Line 3 retrofit') }}</h2></div>
    <GanttChart spreadsheet show-summaries summary-dependencies :rows="rows" :columns="columns" :bars="bars" :dependencies="dependencies"
      :highlighted-dependency-ids="critical" :range="range" :non-working-periods="weekends" :pixels-per-unit="22" :tick-steps="[7]"
      :snap="1" :min-duration="1" :format-time="formatDay" :height="480" :row-height="36" :label-width="150" :labels="{ ...componentLabels(ja ? 'ja' : 'en').gantt, rows: t('タスク', 'Task') }"
      :validate-field-edit="checkDuration" :validate-sheet-edit="checkSheet" @edit="applyBar" @field-edit="applyField" @sheet-edit="applySheet"
      @field-edit-rejected="(_, reason) => message = reason" @sheet-edit-rejected="reason => message = reason" />
    <p v-if="failure" class="production-caption sheet-status" role="alert">{{ failure }}</p>
    <p class="production-caption sheet-status" role="status" :aria-label="t('編集結果', 'Edit result')">{{ message }}</p>
    <p class="production-caption">{{ t('ダブルクリック・Enter・F2・文字入力でセルを編集。Shift+クリックまたはShift+矢印キーで範囲選択。Ctrl / ⌘+C・X・Vでコピー・切り取り・貼り付け、Deleteで消去、Ctrl / ⌘+Dで先頭行の値を下にコピー。選択範囲の右下をドラッグしてもコピーできます。先行はタスク番号で入力します。',
      'Double-click, Enter, F2 or typing edits a cell. Shift-click or Shift-arrow selects a range. Ctrl / ⌘ + C, X or V copies, cuts or pastes; Delete clears; Ctrl / ⌘ + D fills down from the first row. You can also drag the bottom-right handle down. Predecessors are task numbers.') }}</p>
  </section>
</template>

Released under the MIT License.