本文へ移動

ツリーグリッドと表

ツリーグリッド

約3,000行の製品階層を30列の属性・在庫と並べ、表示範囲だけを描画します。セル編集とスプレッドシート編集、行構造の編集、遅延読み込みのグループ、グラフと連動する選択を備え、見出しで並べ替え・絞り込み・列幅変更ができる費用内訳も示します。

ライブデモGitHub で見る ↗

ツリーグリッド

製品階層を属性と倉庫在庫に並べた約 3,000 行・30 列の表を、表示範囲だけ描画します。セルとスプレッドシートの編集、行構造の編集、遅延読み込みのグループ、グラフと連動する選択を備えています。

製品
SKU
価格
状態
発売日
仕入先
在庫あり
W01
W02
W03
W04
工具
不明
不明
不明
不明
不明
不明
不明
不明
不明
不明
工具 Basic
不明
不明
不明
不明
不明
不明
不明
不明
不明
不明
工具 Basic 001
SKU-00000
5
販売終了
2024-01-01
Northwind
いいえ
不明
不明
対象外
対象外
工具 Basic 002
SKU-00001
42.25
販売中
2024-01-02
Contoso
はい
1
4
不明
10
工具 Basic 003
SKU-00002
79.5
販売中
2024-01-03
Fabrikam
はい
不明
0
8
不明
工具 Basic 004
SKU-00003
116.75
販売中
2024-01-04
Northwind
はい
3
不明
不明
12
工具 Basic 005
SKU-00004
153
販売中
2024-01-05
Contoso
はい
不明
7
10
不明
工具 Basic 006
SKU-00005
190.25
販売中
2024-01-06
Fabrikam
はい
5
不明
0
14
工具 Basic 007
SKU-00006
227.5
販売中
2024-01-07
Northwind
はい
なし
9
不明
不明
工具 Basic 008
SKU-00007
264.75
販売中
2024-01-08
Contoso
いいえ
7
不明
13
16
工具 Basic 009
SKU-00008
301
販売中
2024-01-09
Fabrikam
はい
8
11
不明
0
工具 Basic 010
SKU-00009
338.25
販売中
2024-01-10
Northwind
はい
不明
なし
15
不明
工具 Basic 011
SKU-00010
375.5
販売中
2024-01-11
Contoso
はい
10
13
不明
19
工具 Basic 012
SKU-00011
12.75
販売終了
2024-01-12
Fabrikam
はい
不明
対象外
対象外
不明
工具 Basic 013
SKU-00012
49
販売中
2024-01-13
Northwind
はい
12
不明
なし
21
工具 Basic 014
SKU-00013
86.25
販売中
2024-01-14
Contoso
はい
不明
16
19
不明
工具 Basic 015
SKU-00014
123.5
販売中
2024-01-15
Fabrikam
いいえ
14
不明
20
23
工具 Basic 016
SKU-00015
160.75
販売中
2024-01-16
Northwind
はい
15
18
不明
なし
矢印キーでセル間を移動、左右キーで行を展開・折りたたみ、Enter で選択します。Alt+上下キーで行を移動、Alt+Shift+矢印でインデント・アウトデントします。Ctrl+Enter で下に行を、Ctrl+Shift+Enter で子の行を追加し、Delete で行を削除します。

行かセルをクリックするか Enter を押してください。文字入力、F2、ダブルクリックで編集し、Ctrl+C、Ctrl+V、Ctrl+D は範囲に使えます。

連動しているものはありません。

工具 工具工具 Basic 工具 Basic工具 Pro 工具 Pro工具 Compact 工具 Compact工具 Classic 工具 Classic工具 Smart 工具 Smart園芸 園芸園芸 Basic 園芸 Basic園芸 Pro 園芸 Pro園芸 Compact 園芸 Compact園芸 Classic 園芸 Classic園芸 Smart 園芸 Smartキッチン キッチンキッチン Basic キッチン Basicキッチン Pro キッチン Proキッチン Compact キッチン Compactキッチン Classic キッチン Classicキッチン Smart キッチン Smart照明 照明照明 Basic 照明 Basic照明 Pro 照明 Pro照明 Compact 照明 Compact照明 Classic 照明 Classic照明 Smart 照明 Smart収納 収納収納 Basic 収納 Basic収納 Pro 収納 Pro収納 Compact 収納 Compact収納 Classic 収納 Classic収納 Smart 収納 Smartアウトドア アウトドアアウトドア Basic アウトドア Basicアウトドア Pro アウトドア Proアウトドア Compact アウトドア Compactアウトドア Classic アウトドア Classicアウトドア Smart アウトドア SmartNorthwind NorthwindContoso ContosoFabrikam FabrikamTailspin TailspinLitware LitwareProseware ProsewareAdatum AdatumWoodgrove Woodgrove
15%

並べ替え、絞り込み、列幅

見出しで兄弟の行を親の中で並べ替え、祖先を残して行を絞り込み、列幅を変えられる費用内訳です。グリッドは提案し、並べ替え・絞り込み・列幅はページが保持します。

設計
レイアウト
Ben
18,000
9,500
進行中
構想
Ana
12,000
12,400
完了
設計レビュー
Chen
4,000
0
計画
製作
フレーム
Dana
40,000
31,000
進行中
配線
Ben
22,000
2,000
進行中
パネル
Ana
15,000
0
計画
試験
フィールド試験
Dana
14,000
0
計画
ベンチ試験
Chen
9,000
0
計画
矢印キーでセル間を移動、左右キーで行を展開・折りたたみ、Enter で選択します。

見出しのボタンで並べ替え、⏷ で絞り込み、列の端をドラッグするか矢印キーで幅を変えます。

デモの右下の角をドラッグすると高さを変えられます。

ソースコード

vue
<script setup lang="ts">
// Opt-in example of TreeGrid: a product hierarchy (categories, subcategories and about 3,000 products) against
// attributes and the stock of 24 warehouses. The grid is controlled: cell edits, spreadsheet batches and row creates,
// deletes and moves are proposals that this parent applies to one history entry each (undo and redo below). An
// "Archived products" group loads its children on demand. Selection links to a NetworkGraph of categories and suppliers
// through entities (`useLinkedSelection().selectEntities`): the same supplier is one entity in many cells.
import { computed, ref, shallowRef, useTemplateRef } from 'vue'
import {
  NetworkGraph, TreeGrid, applyTreeGridEdits, deleteTreeGridRows, insertTreeGridRow, matchTreeGridEntities, moveTimelineRow,
  useEditHistory, useLinkedSelection,
  type EntityRef, type GraphEdge, type NetworkNode, type TimelineRowMove, type TreeGridActivation, type TreeGridCell,
  type TreeGridCellEdit, type TreeGridColumn, type TreeGridEditCancel, type TreeGridPosition, type TreeGridRow,
  type TreeGridRowCreate, type TreeGridRowDelete, type TreeGridSheetEdit, type ViewBinding, type ViewTargetEvent,
} from '../src'
import DemoPanel from './components/DemoPanel.vue'
import { download } from './download'
import TreeGridColumnsDemo from './TreeGridColumnsDemo.vue'
import StatusLine from './components/StatusLine.vue'
import { useDemoLocale } from './i18n'

type Product = { kind: 'category' | 'product'; sku?: string; price?: number; status?: string; launch?: number; supplierId?: string; inStock?: boolean }
type Row = TreeGridRow<Product>

const { t, labels } = useDemoLocale()
const day = 86_400_000
const launchBase = Date.UTC(2024, 0, 1)
const categories = t({ en: ['Tools', 'Garden', 'Kitchen', 'Lighting', 'Storage', 'Outdoor'], ja: ['工具', '園芸', 'キッチン', '照明', '収納', 'アウトドア'] })
const subcategories = ['Basic', 'Pro', 'Compact', 'Classic', 'Smart']
const suppliers = ['Northwind', 'Contoso', 'Fabrikam', 'Tailspin', 'Litware', 'Proseware', 'Adatum', 'Woodgrove']
const warehouses = Array.from({ length: 24 }, (_, i) => 'W' + String(i + 1).padStart(2, '0'))

function initialRows(): Row[] {
  const rows: Row[] = []
  categories.forEach((category, c) => {
    const categoryId = 'cat-' + c
    rows.push({ id: categoryId, label: category, entities: [{ kind: 'category', id: categoryId }], data: { kind: 'category' } })
    subcategories.forEach((sub, s) => {
      const subId = `${categoryId}-${s}`
      rows.push({ id: subId, parentId: categoryId, label: `${category} ${sub}`, entities: [{ kind: 'category', id: subId }], data: { kind: 'category' } })
      for (let p = 0; p < 100; p++) {
        const n = c * 500 + s * 100 + p
        rows.push({
          id: 'p' + n, parentId: subId, label: `${category} ${sub} ${String(p + 1).padStart(3, '0')}`,
          entities: [{ kind: 'product', id: 'p' + n }],
          data: {
            kind: 'product', sku: `SKU-${String(n).padStart(5, '0')}`, price: 5 + ((n * 37) % 400) + (n % 4) * 0.25,
            status: n % 11 === 0 ? 'discontinued' : 'active', launch: launchBase + (n % 700) * day,
            supplierId: 'sup-' + ((c + s + (p % 3)) % suppliers.length), inStock: n % 7 !== 0,
          },
        })
      }
    })
  })
  rows.push({ id: 'archived', label: t({ en: 'Archived products', ja: 'アーカイブ済みの製品' }), childStatus: 'unloaded', data: { kind: 'category' } })
  return rows
}
function initialCells(rows: readonly Row[]): TreeGridCell[] {
  const cells: TreeGridCell[] = []
  for (const row of rows) {
    if (row.data?.kind !== 'product') continue
    const n = Number(row.id.slice(1))
    warehouses.forEach((warehouse, w) => {
      const pick = (n * 13 + w * 7) % 23
      if (pick < 9) return // not listed: unknown (missingCell)
      if (row.data!.status === 'discontinued') cells.push({ rowId: row.id, columnId: warehouse, status: 'not-applicable' })
      else if (pick === 9) cells.push({ rowId: row.id, columnId: warehouse, status: 'none' })
      else cells.push({ rowId: row.id, columnId: warehouse, value: pick === 10 ? 0 : (n + w * 3) % 60, ...pick > 20 ? { tone: 'amber' as const } : {} })
    })
  }
  return cells
}

const two = (value: number) => String(value).padStart(2, '0')
const formatDate = (value: unknown) => {
  if (typeof value !== 'number') return ''
  const date = new Date(value)
  return `${date.getUTCFullYear()}-${two(date.getUTCMonth() + 1)}-${two(date.getUTCDate())}`
}
const parseDate = (text: string) => {
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text.trim())
  if (!match) return { error: t({ en: 'Use the format YYYY-MM-DD', ja: 'YYYY-MM-DD の形式で入力してください' }) }
  const time = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))
  return formatDate(time) === text.trim() ? time : { error: t({ en: 'Not a calendar date: ', ja: '存在しない日付です: ' }) + text.trim() }
}
const isProduct = (row: Row) => row.data?.kind === 'product'
const field = <K extends keyof Product>(key: K) => (row: Row, value: unknown): Row => ({ ...row, data: { ...row.data!, [key]: value ?? undefined } })
const columns: TreeGridColumn<Row>[] = [
  { id: 'sku', label: 'SKU', width: 104, value: row => row.data?.sku, editor: { kind: 'text', required: true }, editable: isProduct, update: field('sku') },
  {
    id: 'price', label: t({ en: 'Price', ja: '価格' }), width: 88, value: row => row.data?.price, editor: { kind: 'number', min: 0 }, editable: isProduct, update: field('price'),
  },
  {
    id: 'status', label: t({ en: 'Status', ja: '状態' }), width: 120, value: row => row.data?.status,
    editor: { kind: 'select', required: true, choices: [{ value: 'active', label: t({ en: 'Active', ja: '販売中' }) }, { value: 'discontinued', label: t({ en: 'Discontinued', ja: '販売終了' }) }] },
    editable: isProduct, update: field('status'),
  },
  {
    id: 'launch', label: t({ en: 'Launch', ja: '発売日' }), width: 108, value: row => row.data?.launch,
    editor: { kind: 'time', parse: parseDate, format: formatDate }, editable: isProduct, update: field('launch'),
  },
  {
    id: 'supplier', label: t({ en: 'Supplier', ja: '仕入先' }), width: 112,
    value: row => row.data?.supplierId ? { value: suppliers[Number(row.data.supplierId.slice(4))]!, entities: [{ kind: 'supplier', id: row.data.supplierId }] } : undefined,
  },
  { id: 'inStock', label: t({ en: 'In stock', ja: '在庫あり' }), width: 80, value: row => row.data?.inStock, editor: { kind: 'checkbox' }, editable: isProduct, update: field('inStock') },
  ...warehouses.map(id => ({ id, label: id, width: 64, missingCell: 'unknown' as const, editor: { kind: 'number' as const, min: 0, integer: true }, editable: isProduct })),
]

const startRows = initialRows()
const history = useEditHistory<{ rows: Row[]; cells: TreeGridCell[] }>({ rows: startRows, cells: initialCells(startRows) })
const rows = computed(() => history.state.value.rows)
const cells = computed(() => history.state.value.cells)
const expandedIds = ref<string[]>(['cat-0', 'cat-0-0', 'cat-1'])
const activeCell = ref<TreeGridPosition>()
const status = ref(t({ en: 'Click or press Enter on a row or cell. Type, F2 or double-click edits; Ctrl+C, Ctrl+V and Ctrl+D work on ranges.', ja: '行かセルをクリックするか Enter を押してください。文字入力、F2、ダブルクリックで編集し、Ctrl+C、Ctrl+V、Ctrl+D は範囲に使えます。' }))
const failNextLoad = ref(false)
const archivedStatus = shallowRef<'unloaded' | 'loading' | 'loaded' | 'failed'>('unloaded')
let created = 0

const label = (id: string) => rows.value.find(row => row.id === id)?.label ?? id
const commit = (next: { rows?: Row[]; cells?: TreeGridCell[] }, text: string) => {
  history.commit({ ...history.state.value, ...next })
  status.value = text
}
function cellEdit(change: TreeGridCellEdit) {
  commit(applyTreeGridEdits({ rows: rows.value, columns, cells: cells.value }, [change]), `${label(change.rowId)} · ${change.columnId}: ${String(change.before)} → ${String(change.after)}.`)
}
function sheetEdit(change: TreeGridSheetEdit) {
  commit(applyTreeGridEdits({ rows: rows.value, columns, cells: cells.value }, change.edits), t({ en: `${change.action}: ${change.edits.length} cells changed.`, ja: `${change.action}: ${change.edits.length} セルを変更しました。` }))
}
function rejected(_change: unknown, reason: string) { status.value = t({ en: 'Rejected: ', ja: '却下: ' }) + reason }
function cancelled(event: TreeGridEditCancel) { status.value = t({ en: `Edit cancelled (${event.kind}, ${event.reason}).`, ja: `編集を取り消しました(${event.kind}、${event.reason})。` }) }
function validateCellEdit(change: TreeGridCellEdit) {
  return change.columnId !== 'price' || (typeof change.after === 'number' && change.after <= 10_000) || change.after === null || t({ en: 'Prices above 10,000 need approval.', ja: '10,000 を超える価格には承認が必要です。' })
}
function rowCreate(change: TreeGridRowCreate) {
  const id = 'new-' + ++created
  const parent = change.parentId ? rows.value.find(row => row.id === change.parentId) : undefined
  const product = parent && parent.parentId !== undefined
  const row: Row = {
    id, label: t({ en: `New ${product ? 'product' : 'group'} ${created}`, ja: `新しい${product ? '製品' : 'グループ'} ${created}` }), entities: [{ kind: 'product', id }],
    data: product ? { kind: 'product', sku: `NEW-${created}`, price: 0, status: 'active', inStock: false } : { kind: 'category' },
  }
  commit({ rows: insertTreeGridRow(rows.value, change, row) }, t({ en: `Added ${row.label}.`, ja: `${row.label} を追加しました。` }))
  if (change.parentId && !expandedIds.value.includes(change.parentId)) expandedIds.value = [...expandedIds.value, change.parentId]
  activeCell.value = { rowId: id }
}
function rowDelete(change: TreeGridRowDelete) {
  const names = change.ids.map(label).join(t({ en: ', ', ja: '、' }))
  commit(deleteTreeGridRows({ rows: rows.value, cells: cells.value }, change), t({ en: `Deleted ${names}${change.includeDescendants ? ' with its rows' : ''}.`, ja: `${names}${change.includeDescendants ? 'をその行ごと' : 'を'}削除しました。` }))
}
function rowMove(change: TimelineRowMove) {
  commit({ rows: moveTimelineRow(rows.value, change.id, change.after) }, t({
    en: `Moved ${label(change.id)}${change.after.parentId ? ' into ' + label(change.after.parentId) : ' to the top level'}.`,
    ja: `${label(change.id)} を${change.after.parentId ? label(change.after.parentId) + ' の中' : '最上位'}に移動しました。`,
  }))
}
function validateRowDelete(change: TreeGridRowDelete) {
  return change.ids.every(id => rows.value.find(row => row.id === id)?.parentId !== undefined) || t({ en: 'Top-level categories cannot be deleted.', ja: '最上位のカテゴリーは削除できません。' })
}
function validateRowMove(change: TimelineRowMove) {
  const row = rows.value.find(item => item.id === change.id)
  return !(row?.data?.kind === 'product' && change.after.parentId === undefined) || t({ en: 'A product needs a category.', ja: '製品にはカテゴリーが必要です。' })
}

// The lazily loaded group: its children arrive after a short delay, or fail on request.
function expandRequest(rowId: string) {
  if (rowId !== 'archived') return
  archivedStatus.value = 'loading'
  status.value = t({ en: 'Loading archived products…', ja: 'アーカイブ済みの製品を読み込み中…' })
  setTimeout(() => {
    if (failNextLoad.value) {
      failNextLoad.value = false
      archivedStatus.value = 'failed'
      status.value = t({ en: 'Loading archived products failed. Press Enter on the status line to retry.', ja: 'アーカイブ済みの製品を読み込めませんでした。状態の行で Enter を押すと再試行します。' })
      return
    }
    const loaded: Row[] = Array.from({ length: 20 }, (_, i) => ({
      id: 'arch-' + i, parentId: 'archived', label: t({ en: 'Archived ', ja: 'アーカイブ ' }) + String(i + 1).padStart(2, '0'), entities: [{ kind: 'product', id: 'arch-' + i }],
      data: { kind: 'product', sku: `OLD-${i}`, price: 1 + i, status: 'discontinued', supplierId: 'sup-' + (i % suppliers.length), inStock: false },
    }))
    archivedStatus.value = 'loaded'
    // Loaded data replaces the current entry: it is not an edit to undo.
    history.replaceCurrent({ ...history.state.value, rows: [...history.state.value.rows.filter(row => row.parentId !== 'archived'), ...loaded] })
    status.value = t({ en: 'Loaded 20 archived products.', ja: 'アーカイブ済みの製品を 20 件読み込みました。' })
  }, 600)
}
const gridRows = computed(() => rows.value.map(row => row.id === 'archived' ? { ...row, childStatus: archivedStatus.value } : row))

// Linked selection through entities.
const graphNodes = computed<NetworkNode[]>(() => [
  ...categories.flatMap((category, c) => [
    { id: 'cat-' + c, label: category, tone: 'blue' as const },
    ...subcategories.map((sub, s) => ({ id: `cat-${c}-${s}`, label: `${category} ${sub}`, tone: 'teal' as const })),
  ]),
  ...suppliers.map((name, i) => ({ id: 'sup-' + i, label: name, tone: 'amber' as const })),
])
const graphEdges = computed<GraphEdge[]>(() => categories.flatMap((_, c) => subcategories.flatMap((_, s) => [
  { id: `e-${c}-${s}`, from: 'cat-' + c, to: `cat-${c}-${s}` },
  { id: `s-${c}-${s}`, from: `cat-${c}-${s}`, to: 'sup-' + ((c + s) % suppliers.length) },
])))
const bindings = computed<ViewBinding[]>(() => graphNodes.value.map(node => ({
  entity: { kind: node.id.startsWith('sup-') ? 'supplier' : 'category', id: node.id }, target: { view: 'graph', kind: 'node', id: node.id },
})))
const linked = useLinkedSelection({ bindings })
const gridSelection = ref<string[]>([])
function activateInGrid(activation: TreeGridActivation) {
  gridSelection.value = [activation.rowId]
  linked.selectEntities(activation.entities, { source: 'tree-grid' })
  const names = activation.entities.map(entity => `${entity.kind}:${entity.id}`).join(', ') || t({ en: 'none', ja: 'なし' })
  status.value = t({
    en: `Activated ${label(activation.rowId)}${activation.columnId ? ' · ' + activation.columnId : ''} by ${activation.source}; entities ${names}.`,
    ja: `${activation.source}で ${label(activation.rowId)}${activation.columnId ? ' · ' + activation.columnId : ''} を選びました。エンティティ: ${names}。`,
  })
}
function activateInGraph(event: ViewTargetEvent) {
  gridSelection.value = []
  linked.select('graph', [event.target])
}
// A click on the empty graph canvas or Escape in the graph clears the linked selection in both views.
function clearSelection() {
  gridSelection.value = []
  linked.clearSelection()
}
const matches = computed(() => {
  const entities: EntityRef[] = linked.selectedEntities.value
  return matchTreeGridEntities({ rows: gridRows.value, columns, cells: cells.value }, entities)
})
const highlightedRowIds = computed(() => matches.value.rowIds.filter(id => !gridSelection.value.includes(id)))
const selectionText = computed(() => {
  const count = matches.value.rowIds.length + matches.value.cells.length
  const ids = linked.selectedEntities.value.map(entity => entity.id).join(', ')
  return linked.selectedEntities.value.length
    ? t({ en: `Linked: ${ids} (${count} grid matches)`, ja: `連動中: ${ids}(グリッドで ${count} 件一致)` })
    : t({ en: 'Nothing linked.', ja: '連動しているものはありません。' })
})
const rtl = ref(false)
const grid = useTemplateRef('grid')
function exportSvg() {
  const svg = grid.value?.exportSvg({ title: t({ en: 'Product matrix', ja: '製品マトリクス' }) })
  if (!svg) return
  download(svg, 'product-matrix.svg')
  status.value = t({ en: `Exported SVG (${svg.length} characters).`, ja: `SVG を出力しました(${svg.length} 文字)。` })
}
</script>

<template>
  <DemoPanel title-id="tree-grid-title" :title="t({ en: 'Tree grid', ja: 'ツリーグリッド' })" :subtitle="t({ en: 'A product hierarchy against attributes and warehouse stock: about 3,000 rows and 30 columns, rendered in a window, with cell and spreadsheet editing, row structure editing, a lazily loaded group and selection linked to a graph.', ja: '製品階層を属性と倉庫在庫に並べた約 3,000 行・30 列の表を、表示範囲だけ描画します。セルとスプレッドシートの編集、行構造の編集、遅延読み込みのグループ、グラフと連動する選択を備えています。' })">
    <template #options>
      <button type="button" :disabled="!history.canUndo.value" @click="history.undo()">{{ t({ en: 'Undo', ja: '元に戻す' }) }}</button>
      <button type="button" :disabled="!history.canRedo.value" @click="history.redo()">{{ t({ en: 'Redo', ja: 'やり直す' }) }}</button>
      <label><input v-model="failNextLoad" type="checkbox"> {{ t({ en: 'Fail next load', ja: '次の読み込みを失敗させる' }) }}</label>
      <label><input v-model="rtl" type="checkbox"> {{ t({ en: 'Right to left', ja: '右から左' }) }}</label>
      <button type="button" @click="exportSvg">{{ t({ en: 'Export SVG', ja: 'SVG で出力' }) }}</button>
    </template>
    <TreeGrid ref="grid" v-model:expanded-ids="expandedIds" v-model:active-cell="activeCell" :rows="gridRows" :columns="columns" :cells="cells"
      missing-cell="unknown" :height="420" :tree-column-width="260" :dir="rtl ? 'rtl' : 'ltr'" editable spreadsheet rows-editable
      :selected-row-ids="gridSelection" :highlighted-row-ids="highlightedRowIds" :highlighted-cells="matches.cells"
      :validate-cell-edit="validateCellEdit" :validate-row-delete="validateRowDelete" :validate-row-move="validateRowMove"
      :labels="{ ...labels.treeGrid, grid: t({ en: 'Product matrix', ja: '製品マトリクス' }), treeColumn: t({ en: 'Product', ja: '製品' }) }"
      @row-activate="activateInGrid" @cell-activate="activateInGrid" @expand-request="expandRequest"
      @cell-edit="cellEdit" @cell-edit-rejected="rejected" @sheet-edit="sheetEdit" @sheet-edit-rejected="rejected" @edit-cancel="cancelled"
      @row-create="rowCreate" @row-delete="rowDelete" @row-move="rowMove"
      @row-create-rejected="rejected" @row-delete-rejected="rejected" @row-move-rejected="rejected" />
    <StatusLine :label="t({ en: 'Tree grid status', ja: 'ツリーグリッドの状態' })">{{ status }}</StatusLine>
    <StatusLine :label="t({ en: 'Tree grid selection', ja: 'ツリーグリッドの選択' })">{{ selectionText }}</StatusLine>
    <NetworkGraph :nodes="graphNodes" :edges="graphEdges" :height="260" :options="{ nodeWidth: 160, nodeHeight: 34 }"
      :selected-ids="linked.graph.value.selectedNodeIds" :highlighted-node-ids="linked.graph.value.highlightedNodeIds"
      :labels="{ ...labels.graph, region: t({ en: 'Categories and suppliers', ja: 'カテゴリーと仕入先' }) }" @target-activate="activateInGraph"
      @background-click="clearSelection" @idle-escape="clearSelection" />
  </DemoPanel>
  <!-- The opt-in header controls (column widths, sorting and filtering) on a smaller grid. -->
  <TreeGridColumnsDemo />
</template>
vue
<script setup lang="ts">
// Opt-in header controls of TreeGrid: column resizing (`columnsResizable`), header sorting (`sortableColumns`) and
// filtering (`filterableColumns`). The grid only proposes; this parent keeps the widths, the sort and the filters, and
// shows the rows that `projectTreeGridRows` returns: siblings sorted within their parent, filtered rows with their
// ancestors. Cell edits apply to the full rows, so they survive a change of the sort or the filters.
import { computed, ref, shallowRef } from 'vue'
import {
  TreeGrid, applyTreeGridEdits, projectTreeGridRows, timelineLabelColumnId,
  type TimelineColumnResize, type TimelineViewFilter, type TimelineViewSort, type TreeGridCellEdit, type TreeGridColumn, type TreeGridRow,
} from '../src'
import DemoPanel from './components/DemoPanel.vue'
import StatusLine from './components/StatusLine.vue'
import { useDemoLocale } from './i18n'

type Row = TreeGridRow<{ owner?: string; budget?: number; spent?: number; status?: string }>

const { t, labels } = useDemoLocale()
const work = (id: string, parentId: string, label: string, owner: string, budget: number, spent: number, status: string): Row =>
  ({ id, parentId, label, data: { owner, budget, spent, status } })
const rows = shallowRef<Row[]>([
  { id: 'design', label: t({ en: 'Design', ja: '設計' }) },
  work('concept', 'design', t({ en: 'Concept', ja: '構想' }), 'Ana', 12_000, 12_400, 'done'),
  work('layout', 'design', t({ en: 'Layout', ja: 'レイアウト' }), 'Ben', 18_000, 9_500, 'active'),
  work('review', 'design', t({ en: 'Design review', ja: '設計レビュー' }), 'Chen', 4_000, 0, 'planned'),
  { id: 'build', label: t({ en: 'Build', ja: '製作' }) },
  work('frame', 'build', t({ en: 'Frame', ja: 'フレーム' }), 'Dana', 40_000, 31_000, 'active'),
  work('wiring', 'build', t({ en: 'Wiring', ja: '配線' }), 'Ben', 22_000, 2_000, 'active'),
  work('panels', 'build', t({ en: 'Panels', ja: 'パネル' }), 'Ana', 15_000, 0, 'planned'),
  { id: 'test', label: t({ en: 'Test', ja: '試験' }) },
  work('bench', 'test', t({ en: 'Bench test', ja: 'ベンチ試験' }), 'Chen', 9_000, 0, 'planned'),
  work('field', 'test', t({ en: 'Field test', ja: 'フィールド試験' }), 'Dana', 14_000, 0, 'planned'),
])
const statuses = [
  { value: 'planned', label: t({ en: 'Planned', ja: '計画' }) },
  { value: 'active', label: t({ en: 'Active', ja: '進行中' }) },
  { value: 'done', label: t({ en: 'Done', ja: '完了' }) },
]
const money = (value: unknown) => typeof value === 'number' ? value.toLocaleString('en-US') : ''
const update = (key: 'budget' | 'spent' | 'status') => (row: Row, value: unknown): Row => ({ ...row, data: { ...row.data, [key]: value ?? undefined } })
const isWork = (row: Row) => row.parentId !== undefined
const widths = ref<Record<string, number>>({ owner: 90, budget: 110, spent: 110, status: 110 })
const treeWidth = ref(200)
const columns = computed<TreeGridColumn<Row>[]>(() => [
  { id: 'owner', label: t({ en: 'Owner', ja: '担当' }), width: widths.value.owner!, value: row => row.data?.owner },
  {
    id: 'budget', label: t({ en: 'Budget', ja: '予算' }), width: widths.value.budget!, value: row => row.data?.budget,
    editor: { kind: 'number', min: 0, integer: true, format: money }, editable: isWork, update: update('budget'),
  },
  {
    id: 'spent', label: t({ en: 'Spent', ja: '実績' }), width: widths.value.spent!, value: row => row.data?.spent,
    editor: { kind: 'number', min: 0, integer: true, format: money }, editable: isWork, update: update('spent'),
  },
  {
    id: 'status', label: t({ en: 'Status', ja: '状態' }), width: widths.value.status!, value: row => row.data?.status,
    editor: { kind: 'select', required: true, choices: statuses }, editable: isWork, update: update('status'),
  },
])
const sort = ref<TimelineViewSort[]>([{ ruleId: 'budget', direction: 'desc' }])
const filters = ref<TimelineViewFilter[]>([])
const expandedIds = ref(['design', 'build', 'test'])
const status = ref(t({ en: 'Sort with the header buttons, filter with ⏷, and drag a column edge or use the arrow keys on it to resize.', ja: '見出しのボタンで並べ替え、⏷ で絞り込み、列の端をドラッグするか矢印キーで幅を変えます。' }))
const projection = computed(() => projectTreeGridRows({ rows: rows.value, columns: columns.value }, { sort: sort.value, filters: filters.value }))

function resize(change: TimelineColumnResize) {
  if (change.id === timelineLabelColumnId) treeWidth.value = change.after
  else widths.value = { ...widths.value, [change.id]: change.after }
  status.value = t({ en: `Column ${change.id}: ${change.before} → ${change.after} px.`, ja: `列 ${change.id}: ${change.before} → ${change.after} px。` })
}
function validateColumnResize(change: TimelineColumnResize) {
  return change.id !== timelineLabelColumnId || change.after >= 120 || t({ en: 'The name column needs at least 120 px.', ja: '名前の列には 120 px 以上が必要です。' })
}
function setSort(next: TimelineViewSort[]) {
  sort.value = next
  status.value = next.length
    ? t({ en: 'Sorted by ', ja: '並べ替え: ' }) + next.map(rule => `${rule.ruleId} ${rule.direction}`).join(', ')
    : t({ en: 'Not sorted.', ja: '並べ替えなし。' })
}
function setFilters(next: TimelineViewFilter[]) {
  filters.value = next
  status.value = t({ en: `${projection.value.matchedRowIds.length} matching rows.`, ja: `一致する行: ${projection.value.matchedRowIds.length} 件。` })
}
function cellEdit(change: TreeGridCellEdit) {
  rows.value = applyTreeGridEdits({ rows: rows.value, columns: columns.value }, [change]).rows
}
</script>

<template>
  <DemoPanel title-id="tree-grid-columns-title" :title="t({ en: 'Sorting, filtering and column widths', ja: '並べ替え、絞り込み、列幅' })"
    :subtitle="t({ en: 'A cost breakdown whose header sorts siblings within their parent, filters rows with their ancestors and resizes columns. The grid proposes; the page keeps the sort, the filters and the widths.', ja: '見出しで兄弟の行を親の中で並べ替え、祖先を残して行を絞り込み、列幅を変えられる費用内訳です。グリッドは提案し、並べ替え・絞り込み・列幅はページが保持します。' })">
    <TreeGrid v-model:expanded-ids="expandedIds" :rows="projection.rows" :columns="columns" :height="320" :tree-column-width="treeWidth"
      columns-resizable sortable-columns filterable-columns :sort="sort" :filters="filters" editable
      :validate-column-resize="validateColumnResize"
      :labels="{ ...labels.treeGrid, grid: t({ en: 'Cost breakdown', ja: '費用内訳' }), treeColumn: t({ en: 'Work', ja: '作業' }) }"
      @column-resize="resize" @column-resize-rejected="(_change, reason) => status = reason" @update:sort="setSort" @update:filters="setFilters"
      @cell-edit="cellEdit" />
    <StatusLine :label="t({ en: 'Column status', ja: '列の状態' })">{{ status }}</StatusLine>
  </DemoPanel>
</template>

MIT ライセンスで公開しています。