本文へ移動

GraphPalette と PropertyInspector ​

2 つの小さなコンポーネントで、droppable な NetworkGraph をダイアグラムエディターにできます。GraphPalette はノードのテンプレートを並べ、ユーザーはそれをグラフにドラッグするか、キーボードで挿入します。readPaletteDrop はグラフの node-drop イベントからテンプレートを読み取ります。PropertyInspector は型付きのフィールド定義から、選択中の項目のフォームを作ります。リソースの割り当てと依存関係の表も追加できます。

どちらもオプトインの制御コンポーネントです。パレットはドロップか insert を、インスペクターは change か list-change を知らせ、アプリケーション側がそれぞれを確定します(たとえば useEditHistory の 1 つの履歴として)。

最小の例 ​

vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  GraphPalette, NetworkGraph, PropertyInspector, readPaletteDrop,
  type GraphDrop, type GraphPaletteItem, type GraphPoint, type InspectorChange, type InspectorField, type NetworkNode,
} from '@eightkk/vue-weave'

const templates: GraphPaletteItem[] = [{ id: 'step', label: '工程', shape: 'box' }]
const nodes = ref<NetworkNode[]>([])
const positions = ref(new Map<string, GraphPoint>())
const graph = ref<InstanceType<typeof NetworkGraph>>()
const selectedId = ref<string>()
const selected = computed(() => nodes.value.find(node => node.id === selectedId.value) ?? null)
const fields: InspectorField<NetworkNode>[] = [{ id: 'label', kind: 'text', label: '名前', get: node => node.label }]

function add(template: GraphPaletteItem, at: GraphPoint) {
  const id = `${template.id}-${nodes.value.length + 1}`
  nodes.value = [...nodes.value, { id, label: template.label, shape: template.shape }]
  positions.value = new Map(positions.value).set(id, at)
}
function drop(event: GraphDrop) {
  const template = templates.find(item => item.id === readPaletteDrop(event)?.id)
  if (template) add(template, graph.value!.toGraphPoint(event.clientX, event.clientY))
}
function rename(change: InspectorChange) {
  nodes.value = nodes.value.map(node => node.id === change.id ? { ...node, label: String(change.after) } : node)
}
</script>

<template>
  <GraphPalette :items="templates" @insert="item => add(item, graph!.getViewportCenter())" />
  <NetworkGraph ref="graph" v-model:selected-id="selectedId" :nodes="nodes" :edges="[]" :positions="positions"
    droppable @node-drop="drop" />
  <PropertyInspector :item="selected" :fields="fields" @change="rename" />
</template>

例: ダイアグラムエディター。ガイド: ダイアグラムエディターの部品。型: GraphPaletteItem、InspectorField、GraphPaletteExposed、PropertyInspectorExposed。

英語の詳細

ここから下の詳細なリファレンスは英語です。

Diagram editor parts ​

Two small controlled components for building a diagram editor around NetworkGraph: GraphPalette, a list of node templates to drag onto the graph or insert from the keyboard, and PropertyInspector, a form generated from typed field definitions for the selected item. Both are exported from the Vue entry with their public component types (GraphPaletteComponent, PropertyInspectorComponent) and template ref types (GraphPaletteExposed, PropertyInspectorExposed); their data types and graphPaletteMimeType are also in @eightkk/vue-weave/core. Neither changes the graph or the item: the application applies what they report, for example as one useEditHistory entry. Both render on the server, take dir (ltr, rtl or auto, as for the charts; rtl writes dir="rtl" and adds vw-rtl, auto writes nothing and follows the inherited direction) and follow the dark themes.

GraphPalette ​

APIBehavior
itemsreadonly GraphPaletteItem<D>[] / required. id (unique, the ID rule of Validation and errors with the kind palette item), label, optional detail, shape (NetworkNodeShape, drawn in a 48 by 30 preview with the node outlines of NetworkGraph; default box), tone (default blue), section, keywords, disabled and data. D is inferred and reaches the item slot and insert.
searchableboolean / false. Shows a filter box (type="search") above the list. Every word of the text must occur, ignoring case, in the label, detail, section or keywords of an item. ArrowDown in the box focuses the first shown item; Escape clears a non-empty filter. When nothing matches, a role="status" paragraph says so (labels.noMatches).
labelsPartial<GraphPaletteLabels> / English. region (accessible name of the list, default Shape palette), search (Filter shapes) and noMatches.
dirChartDirection / ltr.
insert(item)Enter or Space on a focused, enabled item: the keyboard alternative to dragging it, because HTML drag and drop needs a pointer. Held keys do not repeat it. Add the node at getViewportCenter() of the graph.
item slot{ item, active }. Replaces the preview, label and detail of an item; the option element, its keyboard handling and its drag stay.
focusItem(id?)Exposed method. Focuses an item (default: the one with the tab stop) and resolves to false when it is not shown.

The list is a listbox of option elements; items with a section are grouped under a heading in a group named by it, in the order of each section's first item, and items without one are listed without a heading. One option takes the tab stop (tabindex="0", aria-selected="true", class vw-is-active): the last focused item while it is shown, else the first shown one. ArrowUp, ArrowDown, Home and End move focus between the shown items. A disabled item is listed with aria-disabled="true", is not draggable and does not emit insert.

Each enabled item is draggable. On dragstart it puts the JSON text { "id": ..., "data": ... } under graphPaletteMimeType (application/x-vue-weave-palette+json; data is left out when it cannot be serialised) and its label under text/plain, with effectAllowed = 'copy'. readPaletteDrop(source) (Vue entry; it reads a DataTransfer) takes the node-drop event of a droppable NetworkGraph, the bar-drop event of GanttChart or a DataTransfer and returns { id, data? }, or undefined for a drop without a palette payload, with malformed JSON or without a non-empty string id. Any page can start a drag with this type, so look the ID up in your own items rather than trusting data.

vue
<GraphPalette :items="templates" searchable @insert="item => addNode(item, graph!.getViewportCenter())" />
<NetworkGraph ref="graph" :nodes="nodes" :edges="edges" :positions="positions" droppable
  @node-drop="drop => { const hit = readPaletteDrop(drop); const item = templates.find(t => t.id === hit?.id); if (item) addNode(item, graph!.toGraphPoint(drop.clientX, drop.clientY)) }" />

Related exported types: GraphPaletteItem, GraphPaletteLabels, GraphPaletteDrop, PaletteDropSource.

PropertyInspector ​

APIBehavior
itemT / null / undefined (T extends InspectorItem, { id: string }). The inspected item; without one the form shows labels.empty or the empty slot. T is inferred from item and fields.
fieldsreadonly (InspectorField<T> | InspectorListField<T>)[] / required. Value fields and list fields, in display order. A typed field (TimelineFieldSpec: required, choices, multiple, min, max, integer, parse, format, timeZone, and so on) whose get(item) returns the raw value, plus label, kind, optional readonly, description and placeholder. IDs follow the ID rule with the kind inspector field; an unknown kind is a RangeError and a select without choices an Error, thrown while rendering.
validateChange(change, item) => boolean / string / void. Synchronous. False or a reason rejects the change: the reason (or labels.rejected) is shown under the field and change-rejected is emitted.
validateListChange(change, item) => boolean / string / void. Synchronous check of a list field change after validateInspectorList; false or a reason rejects it like validateChange and emits list-change-rejected.
labelsPartial<PropertyInspectorLabels> / English. region (accessible name of the form, default Properties), empty, rejected and none (the empty choice of an optional select, (none)); for list fields resource, units, predecessor, type, lag (column headings), for (between a heading and the row name in accessible names), remove, addAssignment, addDependency and noRows (default None).
dirChartDirection / ltr.
change(change)InspectorChange: id (the item), field (the field ID), before and after (FieldValue). Emitted for a committed value that passes the field checks and validateChange and differs from before (fieldValuesEqual). The parent updates the item to accept.
change-rejected(change, reason)A change refused by validateChange.
list-change(change)InspectorListChange: id, field, kind and the whole before and after row lists of a list field. The parent replaces the rows to accept. Value fields never emit it, and list fields never emit change.
list-change-rejected(change, reason)A list change refused by validateListChange.
field-<id> slotPropertyInspectorFieldSlot<T>: field, item, value, text, error, readonly, inputId (the ID the label points to), describedBy, and commit(value), commitText(text) and cancel(), which run the same checks as the built-in controls. Replaces the control of one field; its label, description and message stay.
empty slotReplaces the empty-state text.
focusField(id)Exposed method. Focuses the control of a field (for a list field, the first control of its table that can take the focus); returns false when it is not shown or its control cannot take the focus, such as the disabled control of a read-only checkbox, select or colour field.
cancelEdits()Exposed method. Drops every draft and message without a proposal.

Controls by kind: text, number, time and duration are text inputs (inputmode="decimal" for numbers and durations) parsed with parseFieldValue and shown with formatFieldValue; select is a select (a multiple one with multiple), checkbox a checkbox and color a colour input whose value is lowercase #rrggbb text (the built-in parser of a color field accepts #rgb and #rrggbb). A readonly text field is a readonly input; other read-only controls are disabled. Every control is named by its label element and described by the field's description and message (aria-describedby); an invalid field has aria-invalid="true" and its message is a role="alert" paragraph.

Text is a draft until it is committed with Enter or on blur; Escape drops the draft and its message; when there was one, the key does not propagate further. A parse or check failure (required, range, the colour format, a custom parser) keeps the draft and shows the message without emitting anything; a rejected draft is not proposed again on blur. Selects, checkboxes and colour inputs commit on change, and the control returns to the current value until the parent applies the change, so a rejected or ignored change leaves the old value. The form never shows a value the item does not have once a draft is gone.

Stale source data cancels an edit: when item changes to another ID, every draft and message is dropped; when the value under a draft or message changes (an undo, a collaborator, another view), that draft or message is dropped without a proposal. Drafts of fields whose value did not change are kept.

ts
const fields: InspectorField<MyNode>[] = [
  { id: 'label', kind: 'text', label: 'Label', get: node => node.label, required: true },
  { id: 'shape', kind: 'select', label: 'Shape', get: node => node.shape ?? 'box', required: true, choices: [{ value: 'box' }, { value: 'diamond' }] },
  { id: 'accent', kind: 'color', label: 'Accent', get: node => node.data?.accent ?? null },
]

Inspector list fields ​

Two opt-in field kinds edit a list of rows as a small table: assignments (InspectorAssignmentsField<T>: rows { resourceId, units }, a resource select, a units box and a remove button per row) and dependencies (InspectorDependenciesField<T>: rows { predecessorId, type, lag }, a predecessor select, an FS/SS/FF/SF select, a lag box and a remove button). Both have id, label, get(item) (the rows), options (InspectorOption[]: value and optional label, the resources or predecessors a row can name; unique non-empty strings) and optional readonly and description. assignments adds defaultUnits (units of an added row, default 1) and maxUnits, both positive integers; dependencies adds lagUnitSize (model units per displayed lag unit, default 1) and lagUnitLabel (a suffix shown after the box and accepted in the text). With lagUnitSize, a typed lag is rounded to whole model units ("0.3333333" hours becomes 1,200,000 ms). A bad option list is an Error, a bad defaultUnits, maxUnits or lagUnitSize a RangeError, thrown while rendering.

The table is a role="group" named by the field label and described by its description and message. Every control is named by its column heading, labels.for and the row's option label: "Resource for Crane", "Units for Crane", "Type for Design", "Lag for Design", and the remove button "Remove Crane". An option that another row uses is disabled in a row's select. The add button ("Add assignment", "Add dependency") appends a row with the first unused option (disabled when none is left) and focus moves to its select; after a remove, focus moves to the add button. Each edit proposes the whole new list through list-change: a select on change, a units or lag box on Enter or blur (Escape drops that box's draft and message), and add and remove at once. The rows are checked first with validateInspectorList(field, rows) (core): every option once, units positive safe integers (at most maxUnits), as ResourceAssignment requires, a known type, a lag that is a safe integer, as schedule links require; a failure shows its message without a proposal. A rejection by validateListChange shows its reason under the table (role="alert") and keeps the typed text until Escape; a rejected select returns to the current value. Messages belong to the control that caused them: the refused box or select gets aria-invalid="true", editing or cancelling another box leaves its message alone, and the table shows the latest one. The table keeps showing the item's rows until the parent applies the change, and drafts drop when the item or the field's rows change, as for value fields. List fields have no field-<id> slot; focusField(id) focuses the table's first control that can take the focus (in a read-only table, the first units or lag box).

List changes use their own event, list-change, so the before and after of change (InspectorChange) stay FieldValue.

ts
const fields: InspectorListField<Task>[] = [
  { id: 'resources', kind: 'assignments', label: 'Resources', get: task => task.assignments, options: [{ value: 'crane', label: 'Crane' }] },
  { id: 'links', kind: 'dependencies', label: 'Predecessors', get: task => task.links, options: tasks, lagUnitSize: 3_600_000, lagUnitLabel: 'h' },
]

Map assignment rows to ResourceAssignment with the task ID, and dependency rows to ScheduleLink or TimelineDependency (from: predecessorId, to the item).

Related exported types: InspectorItem, InspectorField, InspectorFieldKind, InspectorChange, InspectorChangeValidator, PropertyInspectorLabels, PropertyInspectorFieldSlot, InspectorListFieldKind, InspectorOption, InspectorAssignment, InspectorDependency, InspectorAssignmentsField, InspectorDependenciesField, InspectorListField, InspectorListChange, InspectorListChangeValidator.

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