soma-kit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +539 -2
- package/bin/soma-kit.mjs +27 -0
- package/package.json +66 -4
- package/packs/ai/agent-run-card.ts +64 -0
- package/packs/ai/evaluation-card.ts +51 -0
- package/packs/ai/guardrail-policy-card.ts +48 -0
- package/packs/ai/index.ts +31 -0
- package/packs/ai/model-card.ts +55 -0
- package/packs/ai/model-routing-card.ts +49 -0
- package/packs/ai/prompt-template-card.ts +49 -0
- package/packs/ai/texts.ts +19 -0
- package/packs/commerce/address-card.ts +58 -0
- package/packs/commerce/coupon-card.ts +64 -0
- package/packs/commerce/index.ts +25 -0
- package/packs/commerce/order-card.ts +60 -0
- package/packs/commerce/purchase-order-card.ts +74 -0
- package/packs/commerce/texts.ts +14 -0
- package/packs/finance/index.ts +30 -0
- package/packs/finance/invoice-summary-card.ts +48 -0
- package/packs/finance/reconcile-board.ts +450 -0
- package/packs/finance/reconcile-case-card.ts +70 -0
- package/packs/finance/reconcile-desk/compile.ts +208 -0
- package/packs/finance/reconcile-desk/index.ts +20 -0
- package/packs/finance/reconcile-desk/shell.ts +27 -0
- package/packs/finance/texts.ts +21 -0
- package/packs/ops/change-window-card.ts +54 -0
- package/packs/ops/dependency-status-card.ts +50 -0
- package/packs/ops/error-budget-card.ts +60 -0
- package/packs/ops/execution-task-runner.ts +61 -0
- package/packs/ops/index.ts +36 -0
- package/packs/ops/integration-status-card.ts +45 -0
- package/packs/ops/release-readiness-card.ts +63 -0
- package/packs/ops/runbook-execution-card.ts +81 -0
- package/packs/ops/texts.ts +21 -0
- package/packs/security/control-evidence-card.ts +54 -0
- package/packs/security/finding-card.ts +96 -0
- package/packs/security/index.ts +29 -0
- package/packs/security/texts.ts +31 -0
- package/packs/shared/card-util.ts +60 -0
- package/packs/shared/wrap.ts +13 -0
- package/spec/generated/kit-app.schema.json +84 -0
- package/spec/generated/kit-page.schema.json +2766 -0
- package/spec/kit-grammar.json +1358 -0
- package/spec/kit-grammar.schema.json +716 -0
- package/src/app/app-config.ts +108 -0
- package/src/app/compose-apps.ts +139 -0
- package/src/app/define-kit-actions.ts +89 -0
- package/src/app/define-kit-app.ts +362 -0
- package/src/app/define-kit-pack.ts +114 -0
- package/src/app/envelope.ts +117 -0
- package/src/app/index.ts +50 -0
- package/src/app/notify-renderer.ts +114 -0
- package/src/app/paged-list-adapter.ts +246 -0
- package/src/app/server-pages.ts +303 -0
- package/src/app/server.ts +244 -0
- package/src/app/submit.types.ts +87 -0
- package/src/base/action-busy.ts +159 -0
- package/src/base/action-gate.ts +267 -0
- package/src/base/action-status.ts +31 -0
- package/src/base/alert.ts +136 -0
- package/src/base/avatar.ts +271 -0
- package/src/base/button.ts +139 -0
- package/src/base/cascader.ts +523 -0
- package/src/base/check-core.ts +214 -0
- package/src/base/checkbox.ts +35 -0
- package/src/base/choice.ts +183 -0
- package/src/base/color-picker.ts +316 -0
- package/src/base/combobox.ts +61 -0
- package/src/base/command-palette.ts +371 -0
- package/src/base/context-menu.ts +103 -0
- package/src/base/countdown.ts +168 -0
- package/src/base/date-range.ts +444 -0
- package/src/base/date.ts +899 -0
- package/src/base/divider.ts +156 -0
- package/src/base/fab.ts +192 -0
- package/src/base/icons.ts +106 -0
- package/src/base/image.ts +177 -0
- package/src/base/index.ts +214 -0
- package/src/base/input.ts +316 -0
- package/src/base/kbd.ts +99 -0
- package/src/base/link.ts +167 -0
- package/src/base/listbox-core.ts +965 -0
- package/src/base/mentions.ts +323 -0
- package/src/base/menu-button.ts +240 -0
- package/src/base/menu-core.ts +341 -0
- package/src/base/month-grid.ts +171 -0
- package/src/base/motion/aura.ts +94 -0
- package/src/base/motion/hover-3d.ts +154 -0
- package/src/base/motion/hover-gallery.ts +185 -0
- package/src/base/motion/index.ts +27 -0
- package/src/base/motion/limits.ts +75 -0
- package/src/base/motion/marquee.ts +157 -0
- package/src/base/motion/text-rotate.ts +195 -0
- package/src/base/number.ts +121 -0
- package/src/base/otp.ts +259 -0
- package/src/base/permission-gate.ts +99 -0
- package/src/base/popover.ts +352 -0
- package/src/base/popup.ts +542 -0
- package/src/base/portal-core.ts +297 -0
- package/src/base/price-text.ts +126 -0
- package/src/base/progress.ts +216 -0
- package/src/base/qr-code.ts +446 -0
- package/src/base/qty-stepper.ts +241 -0
- package/src/base/radio.ts +33 -0
- package/src/base/range.ts +444 -0
- package/src/base/rating.ts +249 -0
- package/src/base/segmented.ts +286 -0
- package/src/base/select.ts +57 -0
- package/src/base/shared.ts +708 -0
- package/src/base/swap.ts +86 -0
- package/src/base/switch.ts +111 -0
- package/src/base/tag-input.ts +464 -0
- package/src/base/tag.ts +250 -0
- package/src/base/text.ts +126 -0
- package/src/base/textarea.ts +129 -0
- package/src/base/time-picker.ts +606 -0
- package/src/base/tree-select.ts +629 -0
- package/src/base/upload.ts +548 -0
- package/src/base/virtual-list.ts +286 -0
- package/src/biz/approval-desk/compile.ts +179 -0
- package/src/biz/approval-desk/index.ts +21 -0
- package/src/biz/approval-desk/shell.ts +50 -0
- package/src/biz/auth-panel/compile.ts +196 -0
- package/src/biz/auth-panel/index.ts +24 -0
- package/src/biz/auth-panel/shell.ts +46 -0
- package/src/biz/category-crud/compile.ts +173 -0
- package/src/biz/category-crud/index.ts +19 -0
- package/src/biz/category-crud/shell.ts +29 -0
- package/src/biz/checkout-page/compile.ts +111 -0
- package/src/biz/checkout-page/index.ts +20 -0
- package/src/biz/checkout-page/shell.ts +50 -0
- package/src/biz/compose.ts +313 -0
- package/src/biz/data-components.ts +26 -0
- package/src/biz/define.ts +23 -0
- package/src/biz/import-wizard/compile.ts +204 -0
- package/src/biz/import-wizard/hub.ts +540 -0
- package/src/biz/import-wizard/index.ts +24 -0
- package/src/biz/import-wizard/shell.ts +161 -0
- package/src/biz/index.ts +80 -0
- package/src/biz/landing-page/compile.ts +67 -0
- package/src/biz/landing-page/index.ts +20 -0
- package/src/biz/landing-page/shell.ts +48 -0
- package/src/biz/link/hub.ts +255 -0
- package/src/biz/link/shared.ts +493 -0
- package/src/biz/master-sub/compile.ts +232 -0
- package/src/biz/master-sub/index.ts +20 -0
- package/src/biz/master-sub/shell.ts +56 -0
- package/src/biz/multi-board/compile.ts +234 -0
- package/src/biz/multi-board/index.ts +19 -0
- package/src/biz/multi-board/shell.ts +70 -0
- package/src/biz/names.ts +30 -0
- package/src/biz/notification-center/compile.ts +138 -0
- package/src/biz/notification-center/index.ts +29 -0
- package/src/biz/notification-center/shell.ts +42 -0
- package/src/biz/page-templates/result-page/compile.ts +46 -0
- package/src/biz/page-templates/result-page/index.ts +19 -0
- package/src/biz/page-templates/result-page/shell.ts +31 -0
- package/src/biz/page-templates/shared.ts +121 -0
- package/src/biz/page-templates/sign-in-page/compile.ts +176 -0
- package/src/biz/page-templates/sign-in-page/index.ts +18 -0
- package/src/biz/page-templates/sign-in-page/shell.ts +116 -0
- package/src/biz/record-detail/compile.ts +290 -0
- package/src/biz/record-detail/index.ts +22 -0
- package/src/biz/record-detail/shell.ts +64 -0
- package/src/biz/settings-center/compile.ts +100 -0
- package/src/biz/settings-center/index.ts +18 -0
- package/src/biz/settings-center/shell.ts +51 -0
- package/src/biz/shared/action-host.ts +469 -0
- package/src/biz/shared/coordinator.ts +516 -0
- package/src/biz/shared/index.ts +9 -0
- package/src/biz/shared/pipes.ts +58 -0
- package/src/biz/shared/runtime-hub.ts +112 -0
- package/src/biz/shared/step-values.ts +25 -0
- package/src/biz/single-form/compile.ts +146 -0
- package/src/biz/single-form/index.ts +18 -0
- package/src/biz/single-form/shell.ts +38 -0
- package/src/biz/standard-crud/bridge.ts +11 -0
- package/src/biz/standard-crud/compile.ts +546 -0
- package/src/biz/standard-crud/index.ts +18 -0
- package/src/biz/standard-crud/shell.ts +157 -0
- package/src/biz/step-form/compile.ts +400 -0
- package/src/biz/step-form/hub.ts +412 -0
- package/src/biz/step-form/index.ts +23 -0
- package/src/biz/step-form/shell.ts +96 -0
- package/src/biz/step-form/steps-ref.ts +112 -0
- package/src/biz/types.ts +96 -0
- package/src/cli/kit-cli.ts +102 -0
- package/src/compile/action-host-attach.ts +76 -0
- package/src/compile/compile-page.ts +472 -0
- package/src/compile/component-candidates.ts +147 -0
- package/src/compile/fragment.ts +104 -0
- package/src/compile/hints.ts +255 -0
- package/src/compile/index.ts +16 -0
- package/src/compile/locate.ts +166 -0
- package/src/compile/page-params.ts +80 -0
- package/src/compile/parse.ts +355 -0
- package/src/compile/redirect.ts +90 -0
- package/src/compile/registry.ts +30 -0
- package/src/compile/remove-guard.ts +99 -0
- package/src/compile/styles.ts +244 -0
- package/src/compile/types.ts +106 -0
- package/src/data/amount-breakdown.ts +132 -0
- package/src/data/anchor-nav.ts +225 -0
- package/src/data/approval-flow.ts +269 -0
- package/src/data/assignment-picker.ts +652 -0
- package/src/data/async-result-panel.ts +308 -0
- package/src/data/breadcrumbs.ts +197 -0
- package/src/data/calendar.ts +363 -0
- package/src/data/carousel.ts +408 -0
- package/src/data/chart.ts +726 -0
- package/src/data/checklist.ts +215 -0
- package/src/data/code-view.ts +415 -0
- package/src/data/comment-thread.ts +342 -0
- package/src/data/confirm-dialog.ts +144 -0
- package/src/data/context-menu.ts +216 -0
- package/src/data/d9-limits.ts +42 -0
- package/src/data/d9-util.ts +81 -0
- package/src/data/diff.ts +239 -0
- package/src/data/display-util.ts +135 -0
- package/src/data/dock.ts +152 -0
- package/src/data/embed.ts +200 -0
- package/src/data/field-mapper.ts +544 -0
- package/src/data/flow-editor-contract.ts +41 -0
- package/src/data/flow-editor.ts +2622 -0
- package/src/data/flow-remote-options.ts +257 -0
- package/src/data/footer.ts +157 -0
- package/src/data/form-draft-registry.ts +76 -0
- package/src/data/gantt.ts +430 -0
- package/src/data/hero.ts +149 -0
- package/src/data/image-viewer.ts +333 -0
- package/src/data/index.ts +268 -0
- package/src/data/item-list.ts +335 -0
- package/src/data/kanban.ts +667 -0
- package/src/data/media-grid.ts +246 -0
- package/src/data/mega-menu.ts +257 -0
- package/src/data/menu-dom.ts +169 -0
- package/src/data/menu.ts +464 -0
- package/src/data/mockup.ts +176 -0
- package/src/data/modal-dialog.ts +182 -0
- package/src/data/navbar.ts +292 -0
- package/src/data/object-form.ts +1981 -0
- package/src/data/options-bus.ts +24 -0
- package/src/data/outcome-watch.ts +40 -0
- package/src/data/overlay-portal.ts +6 -0
- package/src/data/pager.ts +473 -0
- package/src/data/permission-matrix.ts +432 -0
- package/src/data/permission-tree.ts +916 -0
- package/src/data/pricing-table.ts +269 -0
- package/src/data/prompt-dialog.ts +235 -0
- package/src/data/reaction-bar.ts +236 -0
- package/src/data/record-card.ts +413 -0
- package/src/data/record-picker.ts +489 -0
- package/src/data/redirect.ts +109 -0
- package/src/data/remote-options.ts +54 -0
- package/src/data/request-console.ts +399 -0
- package/src/data/resident.ts +58 -0
- package/src/data/result-panel.ts +160 -0
- package/src/data/rich-text.ts +626 -0
- package/src/data/row-editor.ts +1066 -0
- package/src/data/rule-builder.ts +1137 -0
- package/src/data/shape-util.ts +221 -0
- package/src/data/staged-rows.ts +69 -0
- package/src/data/stat-group.ts +231 -0
- package/src/data/static-lazy.ts +63 -0
- package/src/data/static-registry.ts +227 -0
- package/src/data/steps.ts +195 -0
- package/src/data/survey.ts +455 -0
- package/src/data/system-switcher.ts +243 -0
- package/src/data/timeline.ts +204 -0
- package/src/data/tour-guide.ts +392 -0
- package/src/data/transfer.ts +597 -0
- package/src/data/tree-check.ts +30 -0
- package/src/data/tree-table.ts +674 -0
- package/src/data/tree.ts +656 -0
- package/src/data/trend-line.ts +147 -0
- package/src/data/virtual-rows.ts +556 -0
- package/src/data/watermark.ts +140 -0
- package/src/data/wrap.ts +267 -0
- package/src/data/wrapped-candidates.ts +96 -0
- package/src/frames/blank-frame.ts +19 -0
- package/src/frames/index.ts +44 -0
- package/src/frames/page-bar.ts +185 -0
- package/src/frames/page-header.ts +185 -0
- package/src/frames/page-status.ts +54 -0
- package/src/frames/resize-handle.ts +147 -0
- package/src/frames/shared.ts +242 -0
- package/src/frames/single-frame.ts +16 -0
- package/src/frames/split-frame/index.ts +4 -0
- package/src/frames/split-frame/shell.ts +219 -0
- package/src/frames/split-frame/span.ts +64 -0
- package/src/frames/split-frame/wiring.ts +164 -0
- package/src/frames/tabs-frame/index.ts +3 -0
- package/src/frames/tabs-frame/shell.ts +112 -0
- package/src/frames/tabs-frame/wiring.ts +69 -0
- package/src/frames/top-main-frame.ts +20 -0
- package/src/frames/types.ts +72 -0
- package/src/frames/workspace-frame/extras.ts +197 -0
- package/src/frames/workspace-frame/index.ts +13 -0
- package/src/frames/workspace-frame/shell.ts +282 -0
- package/src/frames/workspace-frame/state.ts +152 -0
- package/src/frames/workspace-frame/view.ts +1013 -0
- package/src/generated/kit-grammar-runtime.ts +2822 -0
- package/src/generated/page-origin.ts +57 -0
- package/src/i18n/index.ts +22 -0
- package/src/i18n/kit-text.ts +692 -0
- package/src/i18n/resolve-text-refs.ts +128 -0
- package/src/index.ts +6 -0
- package/src/object-renderer/action-gate.ts +216 -0
- package/src/object-renderer/adopt-gate.ts +333 -0
- package/src/object-renderer/arrange.ts +411 -0
- package/src/object-renderer/candidates.ts +68 -0
- package/src/object-renderer/collapse-wiring.ts +99 -0
- package/src/object-renderer/collection-expand.ts +185 -0
- package/src/object-renderer/collection-parts.ts +653 -0
- package/src/object-renderer/collection-table.ts +503 -0
- package/src/object-renderer/collection.ts +628 -0
- package/src/object-renderer/compile-data.ts +549 -0
- package/src/object-renderer/defaults.ts +252 -0
- package/src/object-renderer/display-checks.ts +153 -0
- package/src/object-renderer/emit-events.ts +498 -0
- package/src/object-renderer/emit-object.ts +98 -0
- package/src/object-renderer/emit-static.ts +1036 -0
- package/src/object-renderer/field-policy.ts +89 -0
- package/src/object-renderer/field-value.ts +581 -0
- package/src/object-renderer/form-detail.ts +116 -0
- package/src/object-renderer/index.ts +13 -0
- package/src/object-renderer/linkage.ts +371 -0
- package/src/object-renderer/merge-class.ts +126 -0
- package/src/object-renderer/mode.ts +25 -0
- package/src/object-renderer/outcome-draft.ts +61 -0
- package/src/object-renderer/parts.ts +136 -0
- package/src/object-renderer/pick-component.ts +36 -0
- package/src/object-renderer/render-object.ts +724 -0
- package/src/object-renderer/request-actions.ts +581 -0
- package/src/object-renderer/skeleton.ts +101 -0
- package/src/object-renderer/table-actions.ts +438 -0
- package/src/object-renderer/table-summary.ts +105 -0
- package/src/object-renderer/table-tools.ts +1072 -0
- package/src/object-renderer/types.ts +936 -0
- package/src/page-target/ai-surface.ts +154 -0
- package/src/page-target/compile.ts +354 -0
- package/src/page-target/drift.ts +186 -0
- package/src/page-target/index.ts +25 -0
- package/src/page-target/intent-map.ts +137 -0
- package/src/page-target/intent-schema.ts +711 -0
- package/src/page-target/origin.ts +17 -0
- package/src/page-target/target.ts +450 -0
- package/src/page-target/writer-policy.ts +315 -0
- package/src/theme/block-theme.ts +202 -0
- package/src/theme/kit-theme-text.ts +2 -0
- package/src/theme/kit-theme.css +275 -0
- package/src/theme/kit-theme.tpl +275 -0
- package/src/theme/theme-tokens.ts +135 -0
|
@@ -0,0 +1,2622 @@
|
|
|
1
|
+
// FlowEditor:流程编排画布(layer: data,写死形状,accept: single)。
|
|
2
|
+
//
|
|
3
|
+
// 数据 `data` = { nodes, edges, mappings?, config? };配置(nodeTypes、readonly、layout、validation、suggestions、texts…)显式传入,
|
|
4
|
+
// view 路径只能带 data 时,配置可随 `data.config` 下发(显式 props 优先)。组件里没有任何业务节点类型。
|
|
5
|
+
//
|
|
6
|
+
// 渲染:节点是 HTML 绝对定位(坐标写在 CSS 变量 --kit-x / --kit-y 上),连线是 inline SVG(描边色用 stroke-* 语义色)。
|
|
7
|
+
// 拖放:从节点右侧端口拖出连线走 core 拖放端口(`services.engines.dnd`:端口把手是 draggable,节点是 dropTarget,MoveIntent 汇成一条新连线)。
|
|
8
|
+
// 端口只给“放在谁身上”、不给坐标,所以节点自由移动用指针事件;没装配 dnd 时,连线退化为「点端口 -> 点目标」与键盘 C -> Enter。
|
|
9
|
+
// 变更一律抛 change { nodes, edges, mappings? },保存抛 save;组件不写数据、不调接口。
|
|
10
|
+
//
|
|
11
|
+
// 本文件依次是:数据与配置形状、类串表、几何、撤销栈、分层布局、输入解析、图编辑规则、组件。
|
|
12
|
+
// 纯函数(布局、几何、规则、撤销栈、解析)均已导出,供业务组件与测试直接用。
|
|
13
|
+
|
|
14
|
+
import type { SomaComponentControllerContext, SomaComponentDefinition, SomaDataPort } from 'soma-core';
|
|
15
|
+
import { watchKitOutcome } from './outcome-watch';
|
|
16
|
+
import { mappingPrefixOf } from './flow-remote-options';
|
|
17
|
+
import { FLOW_EDITOR_CONTRACT } from './flow-editor-contract';
|
|
18
|
+
import { pickPath } from '../object-renderer/adopt-gate';
|
|
19
|
+
import { designFlowEditorGeometry } from 'soma-foundation/layout';
|
|
20
|
+
import { KIT_DATA_LIMITS } from 'soma-foundation/kit-limits';
|
|
21
|
+
import { bool, findRoot, joinClass, num, str } from '../base/shared';
|
|
22
|
+
import { kitText, type KitTextKey } from '../i18n/kit-text';
|
|
23
|
+
import { kitIcon, type KitIconName } from '../base/icons';
|
|
24
|
+
import { createInput, KIT_INPUT_CLASS_CANDIDATES } from '../base/input';
|
|
25
|
+
import { createTextarea, KIT_TEXTAREA_CLASS_CANDIDATES } from '../base/textarea';
|
|
26
|
+
import { createSwitch, KIT_SWITCH_CLASS_CANDIDATES } from '../base/switch';
|
|
27
|
+
import { createNumber } from '../base/number';
|
|
28
|
+
import { KIT_QTY_STEPPER_CLASS_CANDIDATES } from '../base/qty-stepper';
|
|
29
|
+
import { KIT_LISTBOX_CLASS_CANDIDATES } from '../base/listbox-core';
|
|
30
|
+
import { createFieldMapper, KIT_FIELD_MAPPER_CLASS_CANDIDATES } from './field-mapper';
|
|
31
|
+
import { createKitEmbedBag, mountKitComponent, mountKitSelectField } from './embed';
|
|
32
|
+
|
|
33
|
+
// ════════════════════════════════════════════════════════════════
|
|
34
|
+
// 数据与配置形状(纯类型 + 默认文案,无 DOM)
|
|
35
|
+
//
|
|
36
|
+
// 数据:{ nodes: [{ id, type, label, x?, y?, status?, meta? }], edges: [{ id, from, to, label? }], mappings? }。
|
|
37
|
+
// mappings 对编辑器不透明:原样带进 change / save;只有它是「以节点 / 连线 id 为键的对象」时,删节点或连线才顺手删掉对应键。
|
|
38
|
+
// 配置(nodeTypes、readonly、layout、validation、suggestions)全部显式传入,组件里没有任何业务节点类型。
|
|
39
|
+
// ════════════════════════════════════════════════════════════════
|
|
40
|
+
|
|
41
|
+
export type FlowTone = 'neutral' | 'info' | 'success' | 'warning' | 'danger' | 'primary';
|
|
42
|
+
export const FLOW_TONES: readonly FlowTone[] = Object.freeze(['neutral', 'info', 'success', 'warning', 'danger', 'primary']);
|
|
43
|
+
|
|
44
|
+
export interface FlowNode {
|
|
45
|
+
id: string;
|
|
46
|
+
type: string;
|
|
47
|
+
label: string;
|
|
48
|
+
x?: number;
|
|
49
|
+
y?: number;
|
|
50
|
+
status?: string;
|
|
51
|
+
meta?: Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface FlowEdge {
|
|
55
|
+
id: string;
|
|
56
|
+
from: string;
|
|
57
|
+
to: string;
|
|
58
|
+
label?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface FlowGraph {
|
|
62
|
+
nodes: FlowNode[];
|
|
63
|
+
edges: FlowEdge[];
|
|
64
|
+
/** 不透明:编辑器不解释,原样回传 */
|
|
65
|
+
mappings?: unknown;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type FlowFieldKind = 'text' | 'textarea' | 'number' | 'switch' | 'select' | 'mapping';
|
|
69
|
+
export const FLOW_FIELD_KINDS: readonly FlowFieldKind[] = Object.freeze(['text', 'textarea', 'number', 'switch', 'select', 'mapping']);
|
|
70
|
+
|
|
71
|
+
export interface FlowFieldOption {
|
|
72
|
+
value: string;
|
|
73
|
+
label: string;
|
|
74
|
+
/** 选中该项时一并并入节点 meta 的键值(如选依赖接口时带出 interfaceId) */
|
|
75
|
+
meta?: Record<string, unknown>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface FlowMapTarget {
|
|
79
|
+
key: string;
|
|
80
|
+
label: string;
|
|
81
|
+
hint?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 节点 meta 字段。没写 kind:只在节点卡上展示;写了 kind:同时出现在侧边配置面板,值存 node.meta[key]。
|
|
86
|
+
* 面板控件复用对象表单同一套基础组件(Input / Textarea / Switch / Select)与 FieldMapper,没有另一套表单。
|
|
87
|
+
*/
|
|
88
|
+
export interface FlowField {
|
|
89
|
+
key: string;
|
|
90
|
+
label: string;
|
|
91
|
+
kind?: FlowFieldKind;
|
|
92
|
+
placeholder?: string;
|
|
93
|
+
help?: string;
|
|
94
|
+
required?: boolean;
|
|
95
|
+
/** select 的候选 */
|
|
96
|
+
options?: FlowFieldOption[];
|
|
97
|
+
/** select/text:值同步成节点标题 */
|
|
98
|
+
as_label?: boolean;
|
|
99
|
+
/** select:该字段变化时清空的其它 meta 键(如换依赖接口后旧映射作废) */
|
|
100
|
+
resets?: string[];
|
|
101
|
+
/** mapping:目标名前缀,可含 `{别的字段key}` 占位(取该字段当前值);不带前缀的裸名自动补上,别的命名空间丢弃并提示 */
|
|
102
|
+
prefix?: string;
|
|
103
|
+
/** mapping:固定目标(裸名,面板里补前缀) */
|
|
104
|
+
targets?: FlowMapTarget[];
|
|
105
|
+
/** mapping:取另一字段的值作键,从 targets_map 选目标;该字段为空时先提示去选 */
|
|
106
|
+
targets_by?: string;
|
|
107
|
+
targets_map?: Record<string, FlowMapTarget[]>;
|
|
108
|
+
/** mapping:参考提示文字取自 node.meta 的哪个键(字符串或字符串数组) */
|
|
109
|
+
hint_from?: string;
|
|
110
|
+
empty_text?: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface FlowNodeType {
|
|
114
|
+
type: string;
|
|
115
|
+
label: string;
|
|
116
|
+
/** 一个字符或短文本,装饰用(aria-hidden) */
|
|
117
|
+
icon: string;
|
|
118
|
+
tone: FlowTone;
|
|
119
|
+
/** 只读序号前缀(如 `M`):该类型的节点在卡片标题前显示 `M1`、`M2`…(按图的先后实时计算,不保存) */
|
|
120
|
+
numbered?: string;
|
|
121
|
+
maxIn?: number;
|
|
122
|
+
maxOut?: number;
|
|
123
|
+
minIn?: number;
|
|
124
|
+
minOut?: number;
|
|
125
|
+
/** 允许连向的节点类型;缺省不限 */
|
|
126
|
+
to?: string[];
|
|
127
|
+
fields: FlowField[];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export type FlowLayoutMode = 'manual' | 'layered';
|
|
131
|
+
|
|
132
|
+
export interface FlowIssue {
|
|
133
|
+
target: 'node' | 'edge';
|
|
134
|
+
id: string;
|
|
135
|
+
level: 'error' | 'warning';
|
|
136
|
+
message: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface FlowSuggestion {
|
|
140
|
+
id: string;
|
|
141
|
+
label: string;
|
|
142
|
+
reason: string;
|
|
143
|
+
nodes: FlowNode[];
|
|
144
|
+
edges: FlowEdge[];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface FlowConfig {
|
|
148
|
+
nodeTypes: Record<string, FlowNodeType>;
|
|
149
|
+
layout: FlowLayoutMode;
|
|
150
|
+
readonly: boolean;
|
|
151
|
+
/** 允许成环,缺省 false:连线会形成环时拒绝 */
|
|
152
|
+
allowCycles: boolean;
|
|
153
|
+
/** 状态值 -> 语气;缺省状态值本身是语气名就直接用 */
|
|
154
|
+
statusTones: Record<string, FlowTone>;
|
|
155
|
+
texts: Record<string, string>;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 流程文案键 -> 词表键(词表里已有的通用词复用,流程专属的住在 soma.kit.flow_*) */
|
|
159
|
+
const FLOW_TEXT_KEYS: Readonly<Record<string, KitTextKey>> = {
|
|
160
|
+
canvas: 'soma.kit.flow_canvas', help: 'soma.kit.flow_help', empty: 'soma.kit.flow_empty', emptyReadonly: 'soma.kit.flow_emptyReadonly',
|
|
161
|
+
loading: 'soma.kit.loading', undo: 'soma.kit.flow_undo', redo: 'soma.kit.flow_redo', del: 'soma.kit.delete',
|
|
162
|
+
connect: 'soma.kit.flow_connect', layout: 'soma.kit.flow_layout', zoomIn: 'soma.kit.zoom_in', zoomOut: 'soma.kit.zoom_out',
|
|
163
|
+
panelTitle: 'soma.kit.flow_panel_title', panelAria: 'soma.kit.flow_panel_aria', dropped: 'soma.kit.flow_dropped', mapEmpty: 'soma.kit.flow_map_empty',
|
|
164
|
+
pickFirst: 'soma.kit.flow_pick_first', selectPh: 'soma.kit.flow_select_ph',
|
|
165
|
+
fit: 'soma.kit.flow_fit', save: 'soma.kit.save', config: 'soma.kit.flow_config', accept: 'soma.kit.flow_accept', reject: 'soma.kit.flow_reject',
|
|
166
|
+
port: 'soma.kit.flow_port', edgeAria: 'soma.kit.flow_edgeAria', summary: 'soma.kit.flow_summary', errors: 'soma.kit.flow_errors',
|
|
167
|
+
warnings: 'soma.kit.flow_warnings', connecting: 'soma.kit.flow_connecting', connected: 'soma.kit.flow_connected', deleted: 'soma.kit.flow_deleted',
|
|
168
|
+
suggestion: 'soma.kit.flow_suggestion', r_self: 'soma.kit.flow_r_self', r_missing: 'soma.kit.flow_r_missing', r_duplicate: 'soma.kit.flow_r_duplicate',
|
|
169
|
+
r_max_out: 'soma.kit.flow_r_max_out', r_max_in: 'soma.kit.flow_r_max_in', r_type: 'soma.kit.flow_r_type', r_cycle: 'soma.kit.flow_r_cycle',
|
|
170
|
+
insertAbove: 'soma.kit.flow_insert_above', moveUp: 'soma.kit.flow_move_up', moveDown: 'soma.kit.flow_move_down',
|
|
171
|
+
inserted: 'soma.kit.flow_inserted', movedUp: 'soma.kit.flow_moved_up', movedDown: 'soma.kit.flow_moved_down', moveNone: 'soma.kit.flow_move_none',
|
|
172
|
+
nodeDefault: 'soma.kit.flow_nodeDefault', levelError: 'soma.kit.flow_levelError', levelWarning: 'soma.kit.flow_levelWarning', menu: 'soma.kit.flow_menu',
|
|
173
|
+
zoomLabel: 'soma.kit.flow_zoomLabel', zoomHint: 'soma.kit.flow_zoomHint', i_unknown: 'soma.kit.flow_i_unknown', i_min_in: 'soma.kit.flow_i_min_in',
|
|
174
|
+
i_min_out: 'soma.kit.flow_i_min_out', i_max_in: 'soma.kit.flow_i_max_in', i_max_out: 'soma.kit.flow_i_max_out', i_cycle: 'soma.kit.flow_i_cycle',
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/** 默认文案(占位 `{x}` 原样保留);`at` 是元素(读页面语言)或语言串,缺省取 zh-CN */
|
|
178
|
+
export function flowDefaultTexts(at?: Element | string | null): Record<string, string> {
|
|
179
|
+
const out: Record<string, string> = { add: '+ {type}', nodeAria: '{type}:{label}' };
|
|
180
|
+
for (const [k, key] of Object.entries(FLOW_TEXT_KEYS)) out[k] = kitText(key, undefined, at);
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export const FLOW_DEFAULT_TEXTS: Readonly<Record<string, string>> = Object.freeze(flowDefaultTexts());
|
|
185
|
+
|
|
186
|
+
export function fmt(template: string, vars: Record<string, string | number>): string {
|
|
187
|
+
return template.replace(/\{(\w+)\}/g, (_, k: string) => (vars[k] === undefined ? '' : String(vars[k])));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ════════════════════════════════════════════════════════════════
|
|
191
|
+
// 类串表:全部完整写死,颜色只用语义色名,尺度只用 utilityScales 内的键(间距为数字倍数)。
|
|
192
|
+
// 坐标、缩放、平移、框选矩形属于数据,经 CSS 自定义属性写到元素上,类里只用括号变量语法 `left-(--kit-x)`(不是方括号任意值)。
|
|
193
|
+
// hidden 与布局类分写两层:外层只管显隐,内层管布局。
|
|
194
|
+
// ════════════════════════════════════════════════════════════════
|
|
195
|
+
|
|
196
|
+
export const FLOW_CLASS = Object.freeze({
|
|
197
|
+
root: 'flex w-full flex-col gap-2',
|
|
198
|
+
toolbar: 'flex flex-wrap items-center gap-2',
|
|
199
|
+
btn: 'inline-flex h-8 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border border-border bg-surface px-3 text-sm text-fg transition-colors hover:bg-surface-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
|
|
200
|
+
btnPrimary: 'inline-flex h-8 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border border-primary bg-primary px-3 text-sm text-primary-fg transition-colors hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
|
|
201
|
+
zoomLabel: 'text-xs text-fg-muted',
|
|
202
|
+
row: 'flex w-full items-start gap-2',
|
|
203
|
+
panelOuter: 'w-80 shrink-0',
|
|
204
|
+
panel: 'flex h-120 flex-col gap-3 overflow-y-auto rounded-md border border-border-subtle bg-surface p-3',
|
|
205
|
+
panelTitle: 'text-sm font-semibold text-fg',
|
|
206
|
+
panelField: 'flex flex-col gap-1',
|
|
207
|
+
panelFull: 'w-full',
|
|
208
|
+
panelLabel: 'text-xs font-medium text-fg-muted',
|
|
209
|
+
panelReq: 'ms-1 text-danger-on-soft',
|
|
210
|
+
panelHelp: 'text-xs text-fg-muted',
|
|
211
|
+
panelWarn: 'rounded-md bg-warning-soft px-2 py-1 text-xs text-warning-on-soft',
|
|
212
|
+
stage: 'relative h-120 w-full touch-none select-none overflow-hidden rounded-md border border-border-subtle bg-surface-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
|
213
|
+
svgRoot: 'absolute left-0 top-0 h-full w-full',
|
|
214
|
+
gridDot: 'fill-border',
|
|
215
|
+
gridRect: 'h-full w-full',
|
|
216
|
+
overlaySvg: 'pointer-events-none absolute left-0 top-0 h-full w-full',
|
|
217
|
+
fo: 'overflow-visible',
|
|
218
|
+
nodeBase: 'relative box-border flex h-auto min-h-full w-full flex-col justify-between gap-1 rounded-lg border px-3 py-2 text-sm text-fg shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
|
219
|
+
head: 'flex items-center gap-2',
|
|
220
|
+
body: 'flex min-w-0 flex-col',
|
|
221
|
+
barCap: 'min-w-0 flex-1 truncate',
|
|
222
|
+
icon: 'w-4 shrink-0 text-center text-fg-muted',
|
|
223
|
+
label: 'min-w-0 flex-1 truncate font-medium',
|
|
224
|
+
line: 'truncate text-xs text-fg-muted',
|
|
225
|
+
lineError: 'truncate text-xs text-danger-on-soft',
|
|
226
|
+
lineWarning: 'truncate text-xs text-warning-on-soft',
|
|
227
|
+
cfgBtn: 'shrink-0 rounded-sm px-1 text-xs text-fg-muted transition-colors hover:bg-surface-sunken focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
|
228
|
+
inPort: 'pointer-events-none absolute -left-1 top-10 -mt-1 h-2 w-2 rounded-full border border-border bg-surface',
|
|
229
|
+
outPort: 'absolute -right-2 top-10 -mt-2 h-4 w-4 cursor-crosshair rounded-full border border-border bg-surface hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
|
230
|
+
bar: 'box-border flex h-full w-full items-center gap-1 rounded-md border border-border bg-surface px-2 text-xs text-fg shadow-sm',
|
|
231
|
+
edgeG: 'group cursor-pointer outline-none',
|
|
232
|
+
edgeHit: 'fill-none stroke-transparent stroke-12',
|
|
233
|
+
edgeLabel: 'fill-fg-muted text-xs',
|
|
234
|
+
edgeLabelBg: 'fill-surface stroke-border-subtle',
|
|
235
|
+
emptyOuter: '',
|
|
236
|
+
emptyInner: 'pointer-events-none absolute inset-0 flex items-center justify-center px-4 text-center text-sm text-fg-muted',
|
|
237
|
+
errorInner: 'rounded-md border border-danger bg-danger-soft px-3 py-2 text-sm text-danger-on-soft',
|
|
238
|
+
marqueeRect: 'fill-primary-soft stroke-primary opacity-50',
|
|
239
|
+
menuFo: 'pointer-events-auto overflow-visible',
|
|
240
|
+
menuInner: 'box-border flex w-full flex-col gap-1 rounded-md border border-border bg-surface p-1 shadow-lg',
|
|
241
|
+
menuItem: 'rounded-sm px-2 py-1 text-start text-sm text-fg transition-colors hover:bg-surface-sunken focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring',
|
|
242
|
+
menuItemDanger: 'rounded-sm px-2 py-1 text-start text-sm text-danger-on-soft transition-colors hover:bg-surface-sunken focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring',
|
|
243
|
+
status: 'text-xs text-fg-muted',
|
|
244
|
+
srOnly: 'sr-only',
|
|
245
|
+
hidden: 'hidden',
|
|
246
|
+
/** 连线 / 拖线时可作目标的节点高亮(运行期加到元素上,不重建 DOM) */
|
|
247
|
+
target: 'ring-2 ring-info',
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
export const FLOW_NODE_BG = Object.freeze({
|
|
251
|
+
normal: 'bg-surface',
|
|
252
|
+
selected: 'bg-primary-soft ring-2 ring-primary',
|
|
253
|
+
ghost: 'bg-primary-soft opacity-80',
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
export const FLOW_NODE_BORDER = Object.freeze({
|
|
257
|
+
normal: 'border-border',
|
|
258
|
+
error: 'border-danger',
|
|
259
|
+
warning: 'border-warning',
|
|
260
|
+
ghost: 'border-dashed border-primary',
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
export const FLOW_NODE_CURSOR = Object.freeze({ movable: 'cursor-grab', fixed: 'cursor-pointer' });
|
|
264
|
+
|
|
265
|
+
export const FLOW_EDGE_VIS = Object.freeze({
|
|
266
|
+
normal: 'fill-none stroke-2 stroke-border group-focus-visible:stroke-ring',
|
|
267
|
+
selected: 'fill-none stroke-2 stroke-primary group-focus-visible:stroke-ring',
|
|
268
|
+
error: 'fill-none stroke-2 stroke-danger group-focus-visible:stroke-ring',
|
|
269
|
+
warning: 'fill-none stroke-2 stroke-warning group-focus-visible:stroke-ring',
|
|
270
|
+
ghost: 'fill-none stroke-2 stroke-primary opacity-70',
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
export const FLOW_MARKER_FILL = Object.freeze({
|
|
274
|
+
normal: 'fill-border',
|
|
275
|
+
selected: 'fill-primary',
|
|
276
|
+
error: 'fill-danger',
|
|
277
|
+
warning: 'fill-warning',
|
|
278
|
+
ghost: 'fill-primary',
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
export const FLOW_TONE_BADGE: Readonly<Record<FlowTone, string>> = Object.freeze({
|
|
282
|
+
neutral: 'shrink-0 rounded-sm bg-surface-sunken px-1 text-xs text-fg-muted',
|
|
283
|
+
info: 'shrink-0 rounded-sm bg-info-soft px-1 text-xs text-info-on-soft',
|
|
284
|
+
success: 'shrink-0 rounded-sm bg-success-soft px-1 text-xs text-success-on-soft',
|
|
285
|
+
warning: 'shrink-0 rounded-sm bg-warning-soft px-1 text-xs text-warning-on-soft',
|
|
286
|
+
danger: 'shrink-0 rounded-sm bg-danger-soft px-1 text-xs text-danger-on-soft',
|
|
287
|
+
primary: 'shrink-0 rounded-sm bg-primary-soft px-1 text-xs text-primary-on-soft',
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
export const FLOW_TONE_DOT: Readonly<Record<FlowTone, string>> = Object.freeze({
|
|
291
|
+
neutral: 'h-2 w-2 shrink-0 rounded-full bg-fg-subtle',
|
|
292
|
+
info: 'h-2 w-2 shrink-0 rounded-full bg-info',
|
|
293
|
+
success: 'h-2 w-2 shrink-0 rounded-full bg-success',
|
|
294
|
+
warning: 'h-2 w-2 shrink-0 rounded-full bg-warning',
|
|
295
|
+
danger: 'h-2 w-2 shrink-0 rounded-full bg-danger',
|
|
296
|
+
primary: 'h-2 w-2 shrink-0 rounded-full bg-primary',
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
function split(value: string): string[] {
|
|
300
|
+
return value.split(/\s+/).filter((c) => c !== '');
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** 本组件自带的全部类(供编译器并入候选类):由上面的表推出,不手抄 */
|
|
304
|
+
export const KIT_FLOW_EDITOR_CLASS_CANDIDATES: readonly string[] = Object.freeze(
|
|
305
|
+
[...new Set([
|
|
306
|
+
...Object.values(FLOW_CLASS).flatMap(split),
|
|
307
|
+
...Object.values(FLOW_NODE_BG).flatMap(split),
|
|
308
|
+
...Object.values(FLOW_NODE_BORDER).flatMap(split),
|
|
309
|
+
...Object.values(FLOW_NODE_CURSOR).flatMap(split),
|
|
310
|
+
...Object.values(FLOW_EDGE_VIS).flatMap(split),
|
|
311
|
+
...Object.values(FLOW_MARKER_FILL).flatMap(split),
|
|
312
|
+
...Object.values(FLOW_TONE_BADGE).flatMap(split),
|
|
313
|
+
...Object.values(FLOW_TONE_DOT).flatMap(split),
|
|
314
|
+
// 配置面板嵌入的基础组件与 FieldMapper
|
|
315
|
+
...KIT_INPUT_CLASS_CANDIDATES,
|
|
316
|
+
...KIT_TEXTAREA_CLASS_CANDIDATES,
|
|
317
|
+
...KIT_SWITCH_CLASS_CANDIDATES,
|
|
318
|
+
...KIT_QTY_STEPPER_CLASS_CANDIDATES,
|
|
319
|
+
...KIT_LISTBOX_CLASS_CANDIDATES,
|
|
320
|
+
...KIT_FIELD_MAPPER_CLASS_CANDIDATES,
|
|
321
|
+
])].sort(),
|
|
322
|
+
);
|
|
323
|
+
|
|
324
|
+
// ════════════════════════════════════════════════════════════════
|
|
325
|
+
// 几何计算(纯函数,无 DOM)。坐标单位是画布世界坐标(px),与密度档无关:
|
|
326
|
+
// 节点盒尺寸经 CSS 变量写给元素,所以这里的数字就是屏幕上的真实尺寸。
|
|
327
|
+
// 这些数字是组件的交互手感常量,真源在 soma-design 的 limits#/flowEditor(每个数字带 basis),
|
|
328
|
+
// 经 soma-foundation/layout 的 designFlowEditorGeometry() 读取;这里不再写任何字面量。
|
|
329
|
+
// ════════════════════════════════════════════════════════════════
|
|
330
|
+
|
|
331
|
+
export const FLOW_GEOMETRY = Object.freeze({ ...designFlowEditorGeometry() });
|
|
332
|
+
|
|
333
|
+
// 边标签衬底:字号对应 edgeLabel 的 text-xs(12px);仅在 getBBox 量不出时按字数估算,内边距与量得时一致
|
|
334
|
+
const FLOW_LABEL_FONT = 12;
|
|
335
|
+
const FLOW_LABEL_PAD_X = 4;
|
|
336
|
+
const FLOW_LABEL_PAD_Y = 2;
|
|
337
|
+
|
|
338
|
+
export interface Pt { x: number; y: number }
|
|
339
|
+
export interface Rect { x: number; y: number; w: number; h: number }
|
|
340
|
+
export interface FlowView { zoom: number; panX: number; panY: number }
|
|
341
|
+
|
|
342
|
+
const r2 = (v: number): number => Math.round(v * 100) / 100;
|
|
343
|
+
|
|
344
|
+
export function clamp(v: number, lo: number, hi: number): number {
|
|
345
|
+
return Math.min(hi, Math.max(lo, v));
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function snap(v: number, grid: number = FLOW_GEOMETRY.grid): number {
|
|
349
|
+
return grid > 0 ? Math.round(v / grid) * grid : v;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export function nodeRect(p: Pt): Rect {
|
|
353
|
+
return { x: p.x, y: p.y, w: FLOW_GEOMETRY.nodeW, h: FLOW_GEOMETRY.nodeH };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** 出端口:节点右边中点;入端口:左边中点 */
|
|
357
|
+
export function outPort(p: Pt): Pt {
|
|
358
|
+
return { x: p.x + FLOW_GEOMETRY.nodeW, y: p.y + FLOW_GEOMETRY.nodeH / 2 };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export function inPort(p: Pt): Pt {
|
|
362
|
+
return { x: p.x, y: p.y + FLOW_GEOMETRY.nodeH / 2 };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** 连线:从 from 的出端口到 to 的入端口的三次贝塞尔;mid 是 t=0.5 处,放连线标签 */
|
|
366
|
+
export function edgeGeometry(from: Pt, to: Pt): { d: string; mid: Pt } {
|
|
367
|
+
const a = outPort(from);
|
|
368
|
+
const b = inPort(to);
|
|
369
|
+
const dx = Math.max(FLOW_GEOMETRY.bezierMin, Math.abs(b.x - a.x) / 2);
|
|
370
|
+
const c1 = { x: a.x + dx, y: a.y };
|
|
371
|
+
const c2 = { x: b.x - dx, y: b.y };
|
|
372
|
+
return {
|
|
373
|
+
d: `M ${r2(a.x)} ${r2(a.y)} C ${r2(c1.x)} ${r2(c1.y)} ${r2(c2.x)} ${r2(c2.y)} ${r2(b.x)} ${r2(b.y)}`,
|
|
374
|
+
mid: { x: r2((a.x + 3 * c1.x + 3 * c2.x + b.x) / 8), y: r2((a.y + 3 * c1.y + 3 * c2.y + b.y) / 8) },
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export function boundsOf(rects: readonly Rect[]): Rect | null {
|
|
379
|
+
if (rects.length === 0) return null;
|
|
380
|
+
let x0 = Infinity; let y0 = Infinity; let x1 = -Infinity; let y1 = -Infinity;
|
|
381
|
+
for (const r of rects) {
|
|
382
|
+
x0 = Math.min(x0, r.x); y0 = Math.min(y0, r.y);
|
|
383
|
+
x1 = Math.max(x1, r.x + r.w); y1 = Math.max(y1, r.y + r.h);
|
|
384
|
+
}
|
|
385
|
+
return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** 适应画布:全部矩形缩进视口并居中;放大不超过 1(小图不放大) */
|
|
389
|
+
export function fitView(rects: readonly Rect[], vw: number, vh: number): FlowView {
|
|
390
|
+
const b = boundsOf(rects);
|
|
391
|
+
if (b === null || vw <= 0 || vh <= 0) return { zoom: 1, panX: 0, panY: 0 };
|
|
392
|
+
const pad = FLOW_GEOMETRY.fitPad;
|
|
393
|
+
const zoom = clamp(Math.min((vw - 2 * pad) / b.w, (vh - 2 * pad) / b.h, 1), FLOW_GEOMETRY.minZoom, FLOW_GEOMETRY.maxZoom);
|
|
394
|
+
return {
|
|
395
|
+
zoom: r2(zoom),
|
|
396
|
+
panX: r2((vw - b.w * zoom) / 2 - b.x * zoom),
|
|
397
|
+
panY: r2((vh - b.h * zoom) / 2 - b.y * zoom),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** 以屏幕点 (cx, cy) 为不动点缩放 */
|
|
402
|
+
export function zoomAt(view: FlowView, factor: number, cx: number, cy: number): FlowView {
|
|
403
|
+
const zoom = clamp(view.zoom * factor, FLOW_GEOMETRY.minZoom, FLOW_GEOMETRY.maxZoom);
|
|
404
|
+
const wx = (cx - view.panX) / view.zoom;
|
|
405
|
+
const wy = (cy - view.panY) / view.zoom;
|
|
406
|
+
return { zoom: r2(zoom), panX: r2(cx - wx * zoom), panY: r2(cy - wy * zoom) };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export function screenToWorld(view: FlowView, sx: number, sy: number): Pt {
|
|
410
|
+
return { x: (sx - view.panX) / view.zoom, y: (sy - view.panY) / view.zoom };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export function normRect(a: Pt, b: Pt): Rect {
|
|
414
|
+
return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(a.x - b.x), h: Math.abs(a.y - b.y) };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function rectsIntersect(a: Rect, b: Rect): boolean {
|
|
418
|
+
return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** 框选命中:世界坐标矩形与节点盒相交的节点 id(保持输入顺序) */
|
|
422
|
+
export function marqueeHits(rect: Rect, boxes: ReadonlyArray<{ id: string; at: Pt }>): string[] {
|
|
423
|
+
return boxes.filter((b) => rectsIntersect(rect, nodeRect(b.at))).map((b) => b.id);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export type Dir = 'left' | 'right' | 'up' | 'down';
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* 空间邻居:从 from 朝 dir 找最近的节点(只看方向半平面,距离 = 主轴距离 + 2 × 副轴偏差;平手取 id 字典序小的)。
|
|
430
|
+
* 只读 / 自动布局下,方向键用它在节点间移焦点。
|
|
431
|
+
*/
|
|
432
|
+
export function neighborInDirection(
|
|
433
|
+
boxes: ReadonlyArray<{ id: string; at: Pt }>,
|
|
434
|
+
fromId: string,
|
|
435
|
+
dir: Dir,
|
|
436
|
+
): string | null {
|
|
437
|
+
const from = boxes.find((b) => b.id === fromId);
|
|
438
|
+
if (!from) return null;
|
|
439
|
+
let best: { id: string; score: number } | null = null;
|
|
440
|
+
for (const b of boxes) {
|
|
441
|
+
if (b.id === fromId) continue;
|
|
442
|
+
const dx = b.at.x - from.at.x;
|
|
443
|
+
const dy = b.at.y - from.at.y;
|
|
444
|
+
const main = dir === 'right' ? dx : dir === 'left' ? -dx : dir === 'down' ? dy : -dy;
|
|
445
|
+
if (main <= 0) continue;
|
|
446
|
+
const cross = dir === 'left' || dir === 'right' ? Math.abs(dy) : Math.abs(dx);
|
|
447
|
+
const score = main + 2 * cross;
|
|
448
|
+
if (best === null || score < best.score || (score === best.score && b.id < best.id)) best = { id: b.id, score };
|
|
449
|
+
}
|
|
450
|
+
return best === null ? null : best.id;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ════════════════════════════════════════════════════════════════
|
|
454
|
+
// 撤销 / 重做栈(纯函数,不可变)。快照 = 一份完整的图(节点、连线、mappings)。
|
|
455
|
+
// 评估结论:做。图小(百级节点),整图快照简单可靠,不需要命令式 diff。
|
|
456
|
+
// coalesce:连续同键的操作(如连按方向键移动同一节点)只记一次起点,撤销一步回到连按之前。
|
|
457
|
+
// ════════════════════════════════════════════════════════════════
|
|
458
|
+
|
|
459
|
+
export interface FlowHistory {
|
|
460
|
+
past: FlowGraph[];
|
|
461
|
+
future: FlowGraph[];
|
|
462
|
+
/** 最近一次入栈的合并键;任何非合并操作都会清掉它 */
|
|
463
|
+
lastKey: string;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
export function emptyHistory(): FlowHistory {
|
|
467
|
+
return { past: [], future: [], lastKey: '' };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** 在改动发生前,把当前图入栈。同 coalesce 键紧邻时不重复入栈 */
|
|
471
|
+
export function pushHistory(h: FlowHistory, present: FlowGraph, limit: number, coalesce = ''): FlowHistory {
|
|
472
|
+
if (coalesce !== '' && h.lastKey === coalesce) return { ...h, future: [] };
|
|
473
|
+
const past = [...h.past, present];
|
|
474
|
+
return { past: past.length > limit ? past.slice(past.length - limit) : past, future: [], lastKey: coalesce };
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export function canUndo(h: FlowHistory): boolean { return h.past.length > 0; }
|
|
478
|
+
export function canRedo(h: FlowHistory): boolean { return h.future.length > 0; }
|
|
479
|
+
|
|
480
|
+
export function undoHistory(h: FlowHistory, present: FlowGraph): { history: FlowHistory; graph: FlowGraph } | null {
|
|
481
|
+
const prev = h.past[h.past.length - 1];
|
|
482
|
+
if (prev === undefined) return null;
|
|
483
|
+
return { history: { past: h.past.slice(0, -1), future: [...h.future, present], lastKey: '' }, graph: prev };
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export function redoHistory(h: FlowHistory, present: FlowGraph): { history: FlowHistory; graph: FlowGraph } | null {
|
|
487
|
+
const next = h.future[h.future.length - 1];
|
|
488
|
+
if (next === undefined) return null;
|
|
489
|
+
return { history: { past: [...h.past, present], future: h.future.slice(0, -1), lastKey: '' }, graph: next };
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// ════════════════════════════════════════════════════════════════
|
|
493
|
+
// 分层布局(纯函数):写死的拓扑分层,同输入同输出;不做交叉最小化,不做优化或打分。
|
|
494
|
+
//
|
|
495
|
+
// 规则(全部确定):
|
|
496
|
+
// 1. 只认两端都存在、非自环、不重复的连线;
|
|
497
|
+
// 2. 成环时按“节点输入顺序 + 连线输入顺序”做深度优先,指回栈内节点的连线算回边,分层时忽略它;
|
|
498
|
+
// 3. 层号 = 沿前向连线的最长路径(无入边的节点在第 0 层),用 Kahn 队列(先进先出,初始按节点输入顺序)求;
|
|
499
|
+
// 4. 层内顺序 = 节点输入顺序;x = pad + 层号 × (nodeW + gapX),y = pad + 层内序号 × (nodeH + gapY)。
|
|
500
|
+
// ════════════════════════════════════════════════════════════════
|
|
501
|
+
|
|
502
|
+
export interface LayeredResult {
|
|
503
|
+
positions: Map<string, Pt>;
|
|
504
|
+
ranks: Map<string, number>;
|
|
505
|
+
/** 被当作回边忽略的连线 id(成环时才有) */
|
|
506
|
+
backEdges: string[];
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
export function layeredLayout(nodes: readonly FlowNode[], edges: readonly FlowEdge[]): LayeredResult {
|
|
510
|
+
const ids = nodes.map((n) => n.id);
|
|
511
|
+
const known = new Set(ids);
|
|
512
|
+
const order = new Map(ids.map((id, i) => [id, i] as const));
|
|
513
|
+
const out = new Map<string, FlowEdge[]>(ids.map((id) => [id, []]));
|
|
514
|
+
const seen = new Set<string>();
|
|
515
|
+
for (const e of edges) {
|
|
516
|
+
if (e.from === e.to || !known.has(e.from) || !known.has(e.to)) continue;
|
|
517
|
+
const key = `${e.from}\u0000${e.to}`;
|
|
518
|
+
if (seen.has(key)) continue;
|
|
519
|
+
seen.add(key);
|
|
520
|
+
out.get(e.from)!.push(e);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// 回边:显式栈的深度优先
|
|
524
|
+
const state = new Map<string, 0 | 1 | 2>(ids.map((id) => [id, 0]));
|
|
525
|
+
const back = new Set<string>();
|
|
526
|
+
for (const root of ids) {
|
|
527
|
+
if (state.get(root) !== 0) continue;
|
|
528
|
+
const stack: Array<{ id: string; i: number }> = [{ id: root, i: 0 }];
|
|
529
|
+
state.set(root, 1);
|
|
530
|
+
while (stack.length > 0) {
|
|
531
|
+
const top = stack[stack.length - 1]!;
|
|
532
|
+
const next = out.get(top.id)![top.i];
|
|
533
|
+
if (next === undefined) { state.set(top.id, 2); stack.pop(); continue; }
|
|
534
|
+
top.i += 1;
|
|
535
|
+
const s = state.get(next.to);
|
|
536
|
+
if (s === 1) back.add(next.id);
|
|
537
|
+
else if (s === 0) { state.set(next.to, 1); stack.push({ id: next.to, i: 0 }); }
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// 前向图上的最长路径分层
|
|
542
|
+
const indeg = new Map<string, number>(ids.map((id) => [id, 0]));
|
|
543
|
+
for (const id of ids) for (const e of out.get(id)!) if (!back.has(e.id)) indeg.set(e.to, indeg.get(e.to)! + 1);
|
|
544
|
+
const rank = new Map<string, number>(ids.map((id) => [id, 0]));
|
|
545
|
+
const queue = ids.filter((id) => indeg.get(id) === 0);
|
|
546
|
+
for (let head = 0; head < queue.length; head += 1) {
|
|
547
|
+
const u = queue[head]!;
|
|
548
|
+
for (const e of out.get(u)!) {
|
|
549
|
+
if (back.has(e.id)) continue;
|
|
550
|
+
rank.set(e.to, Math.max(rank.get(e.to)!, rank.get(u)! + 1));
|
|
551
|
+
indeg.set(e.to, indeg.get(e.to)! - 1);
|
|
552
|
+
if (indeg.get(e.to) === 0) queue.push(e.to);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const slot = new Map<number, number>();
|
|
557
|
+
const positions = new Map<string, Pt>();
|
|
558
|
+
const { pad, nodeW, nodeH, gapX, gapY } = FLOW_GEOMETRY;
|
|
559
|
+
for (const id of [...ids].sort((a, b) => order.get(a)! - order.get(b)!)) {
|
|
560
|
+
const r = rank.get(id)!;
|
|
561
|
+
const k = slot.get(r) ?? 0;
|
|
562
|
+
slot.set(r, k + 1);
|
|
563
|
+
positions.set(id, { x: pad + r * (nodeW + gapX), y: pad + k * (nodeH + gapY) });
|
|
564
|
+
}
|
|
565
|
+
return { positions, ranks: rank, backEdges: edges.filter((e) => back.has(e.id)).map((e) => e.id) };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function occupied(at: Pt, taken: readonly Pt[]): boolean {
|
|
569
|
+
const { nodeW, nodeH } = FLOW_GEOMETRY;
|
|
570
|
+
return taken.some((t) => Math.abs(t.x - at.x) < nodeW && Math.abs(t.y - at.y) < nodeH);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** 新节点的落点:最后一个节点右侧;被占就向下找空位。同输入同输出 */
|
|
574
|
+
export function nextFreeSlot(taken: readonly Pt[]): Pt {
|
|
575
|
+
const { pad, nodeW, nodeH, gapX, gapY } = FLOW_GEOMETRY;
|
|
576
|
+
const last = taken[taken.length - 1];
|
|
577
|
+
let at: Pt = last === undefined ? { x: pad, y: pad } : { x: last.x + nodeW + gapX, y: last.y };
|
|
578
|
+
while (occupied(at, taken)) at = { x: at.x, y: at.y + nodeH + gapY };
|
|
579
|
+
return at;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* 建议虚影节点的落点:节点自带 x、y 就用;否则放在“前驱”右侧(前驱 = 连进它的连线的起点,已有位置者),同一前驱的多个虚影依次向下错开;
|
|
584
|
+
* 没有前驱就取空位。realPos 是画布上已有节点的位置。
|
|
585
|
+
*/
|
|
586
|
+
export function placeGhosts(
|
|
587
|
+
realPos: ReadonlyMap<string, Pt>,
|
|
588
|
+
ghosts: readonly FlowNode[],
|
|
589
|
+
edges: readonly FlowEdge[],
|
|
590
|
+
): Map<string, Pt> {
|
|
591
|
+
const placed = new Map<string, Pt>();
|
|
592
|
+
const taken: Pt[] = [...realPos.values()];
|
|
593
|
+
const { nodeW, nodeH, gapX, gapY } = FLOW_GEOMETRY;
|
|
594
|
+
for (const g of ghosts) {
|
|
595
|
+
if (g.x !== undefined && g.y !== undefined) {
|
|
596
|
+
const at = { x: g.x, y: g.y };
|
|
597
|
+
placed.set(g.id, at);
|
|
598
|
+
taken.push(at);
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
const pre = edges.find((e) => e.to === g.id && (realPos.has(e.from) || placed.has(e.from)));
|
|
602
|
+
const base = pre === undefined ? undefined : (realPos.get(pre.from) ?? placed.get(pre.from));
|
|
603
|
+
let at = base === undefined ? nextFreeSlot(taken) : { x: base.x + nodeW + gapX, y: base.y };
|
|
604
|
+
while (occupied(at, taken)) at = { x: at.x, y: at.y + nodeH + gapY };
|
|
605
|
+
placed.set(g.id, at);
|
|
606
|
+
taken.push(at);
|
|
607
|
+
}
|
|
608
|
+
return placed;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// ════════════════════════════════════════════════════════════════
|
|
612
|
+
// 输入解析(纯函数):把 props 里的松散数据收成干净的图与配置。
|
|
613
|
+
// 只做“收口”,不改源数据:脏节点(缺 id、重复 id)丢弃,悬空连线丢弃,重复连线 id 丢弃。
|
|
614
|
+
// ════════════════════════════════════════════════════════════════
|
|
615
|
+
|
|
616
|
+
function rec(raw: unknown): Record<string, unknown> {
|
|
617
|
+
return raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function list(raw: unknown): unknown[] {
|
|
621
|
+
return Array.isArray(raw) ? raw : [];
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function toneOf(raw: unknown, fallback: FlowTone): FlowTone {
|
|
625
|
+
return FLOW_TONES.includes(raw as FlowTone) ? raw as FlowTone : fallback;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function nodeOf(raw: unknown): FlowNode | null {
|
|
629
|
+
const r = rec(raw);
|
|
630
|
+
const id = str(r.id);
|
|
631
|
+
if (id === '') return null;
|
|
632
|
+
const x = num(r.x);
|
|
633
|
+
const y = num(r.y);
|
|
634
|
+
const status = str(r.status);
|
|
635
|
+
const meta = r.meta !== null && typeof r.meta === 'object' && !Array.isArray(r.meta) ? r.meta as Record<string, unknown> : undefined;
|
|
636
|
+
return {
|
|
637
|
+
id,
|
|
638
|
+
type: str(r.type),
|
|
639
|
+
label: str(r.label, id) === '' ? id : str(r.label, id),
|
|
640
|
+
...(x !== null ? { x } : {}),
|
|
641
|
+
...(y !== null ? { y } : {}),
|
|
642
|
+
...(status !== '' ? { status } : {}),
|
|
643
|
+
...(meta !== undefined ? { meta } : {}),
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** 连线 id 缺省时按两端推:同输入同输出 */
|
|
648
|
+
export function edgeIdOf(from: string, to: string): string {
|
|
649
|
+
return `${from}->${to}`;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function edgeOf(raw: unknown): FlowEdge | null {
|
|
653
|
+
const r = rec(raw);
|
|
654
|
+
const from = str(r.from);
|
|
655
|
+
const to = str(r.to);
|
|
656
|
+
if (from === '' || to === '') return null;
|
|
657
|
+
const label = str(r.label);
|
|
658
|
+
return { id: str(r.id) === '' ? edgeIdOf(from, to) : str(r.id), from, to, ...(label !== '' ? { label } : {}) };
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
export function nodesOf(raw: unknown): FlowNode[] {
|
|
662
|
+
const seen = new Set<string>();
|
|
663
|
+
const out: FlowNode[] = [];
|
|
664
|
+
for (const item of list(raw)) {
|
|
665
|
+
const n = nodeOf(item);
|
|
666
|
+
if (n === null || seen.has(n.id)) continue;
|
|
667
|
+
seen.add(n.id);
|
|
668
|
+
out.push(n);
|
|
669
|
+
}
|
|
670
|
+
return out;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
export function edgesOf(raw: unknown, nodeIds: ReadonlySet<string>): FlowEdge[] {
|
|
674
|
+
const seen = new Set<string>();
|
|
675
|
+
const out: FlowEdge[] = [];
|
|
676
|
+
for (const item of list(raw)) {
|
|
677
|
+
const e = edgeOf(item);
|
|
678
|
+
if (e === null || seen.has(e.id) || !nodeIds.has(e.from) || !nodeIds.has(e.to)) continue;
|
|
679
|
+
seen.add(e.id);
|
|
680
|
+
out.push(e);
|
|
681
|
+
}
|
|
682
|
+
return out;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
export function graphOf(raw: unknown): FlowGraph {
|
|
686
|
+
const r = rec(raw);
|
|
687
|
+
const nodes = nodesOf(r.nodes);
|
|
688
|
+
const edges = edgesOf(r.edges, new Set(nodes.map((n) => n.id)));
|
|
689
|
+
return { nodes, edges, ...(r.mappings !== undefined ? { mappings: r.mappings } : {}) };
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** 比较用签名:只含数据,不含对象身份 */
|
|
693
|
+
export function graphSig(g: FlowGraph): string {
|
|
694
|
+
return JSON.stringify([g.nodes, g.edges, g.mappings ?? null]);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
function intOf(raw: unknown): number | undefined {
|
|
698
|
+
const n = num(raw);
|
|
699
|
+
return n !== null && n >= 0 ? Math.floor(n) : undefined;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function optionsOf(raw: unknown): FlowFieldOption[] {
|
|
703
|
+
const out: FlowFieldOption[] = [];
|
|
704
|
+
for (const item of list(raw)) {
|
|
705
|
+
if (typeof item === 'string') { out.push({ value: item, label: item }); continue; }
|
|
706
|
+
const r = rec(item);
|
|
707
|
+
const value = str(r.value);
|
|
708
|
+
if (value === '') continue;
|
|
709
|
+
out.push({ value, label: str(r.label, value), ...(Object.keys(rec(r.meta)).length > 0 ? { meta: rec(r.meta) } : {}) });
|
|
710
|
+
}
|
|
711
|
+
return out;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function targetsOf(raw: unknown): FlowMapTarget[] {
|
|
715
|
+
const out: FlowMapTarget[] = [];
|
|
716
|
+
for (const item of list(raw)) {
|
|
717
|
+
const r = typeof item === 'string' ? { key: item } : rec(item);
|
|
718
|
+
const key = str(r.key);
|
|
719
|
+
if (key !== '') out.push({ key, label: str(r.label, key), ...(str(r.hint) !== '' ? { hint: str(r.hint) } : {}) });
|
|
720
|
+
}
|
|
721
|
+
return out;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function fieldsOf(raw: unknown): FlowField[] {
|
|
725
|
+
const out: FlowField[] = [];
|
|
726
|
+
for (const item of list(raw)) {
|
|
727
|
+
if (typeof item === 'string' && item !== '') { out.push({ key: item, label: item }); continue; }
|
|
728
|
+
const r = rec(item);
|
|
729
|
+
const key = str(r.key);
|
|
730
|
+
if (key === '') continue;
|
|
731
|
+
const kind = FLOW_FIELD_KINDS.includes(r.kind as FlowFieldKind) ? r.kind as FlowFieldKind : undefined;
|
|
732
|
+
const map: Record<string, FlowMapTarget[]> = {};
|
|
733
|
+
for (const [k, v] of Object.entries(rec(r.targets_map))) map[k] = targetsOf(v);
|
|
734
|
+
const strs = (v: unknown): string[] => list(v).filter((x): x is string => typeof x === 'string' && x !== '');
|
|
735
|
+
out.push({
|
|
736
|
+
key,
|
|
737
|
+
label: str(r.label, key),
|
|
738
|
+
...(kind !== undefined ? { kind } : {}),
|
|
739
|
+
...(str(r.placeholder) !== '' ? { placeholder: str(r.placeholder) } : {}),
|
|
740
|
+
...(str(r.help) !== '' ? { help: str(r.help) } : {}),
|
|
741
|
+
...(bool(r.required) ? { required: true } : {}),
|
|
742
|
+
...(kind === 'select' ? { options: optionsOf(r.options) } : {}),
|
|
743
|
+
...(bool(r.as_label) ? { as_label: true } : {}),
|
|
744
|
+
...(strs(r.resets).length > 0 ? { resets: strs(r.resets) } : {}),
|
|
745
|
+
...(kind === 'mapping'
|
|
746
|
+
? {
|
|
747
|
+
prefix: str(r.prefix),
|
|
748
|
+
targets: targetsOf(r.targets),
|
|
749
|
+
...(str(r.targets_by) !== '' ? { targets_by: str(r.targets_by), targets_map: map } : {}),
|
|
750
|
+
...(str(r.hint_from) !== '' ? { hint_from: str(r.hint_from) } : {}),
|
|
751
|
+
...(str(r.empty_text) !== '' ? { empty_text: str(r.empty_text) } : {}),
|
|
752
|
+
}
|
|
753
|
+
: {}),
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
return out;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// ════════════════════════════════════════════════════════════════
|
|
760
|
+
// 节点配置面板的纯函数(无 DOM,可单测)
|
|
761
|
+
// ════════════════════════════════════════════════════════════════
|
|
762
|
+
|
|
763
|
+
/** 面板里要画的字段(有 kind 的) */
|
|
764
|
+
export function panelFieldsOf(def: FlowNodeType | undefined): FlowField[] {
|
|
765
|
+
return (def?.fields ?? []).filter((f) => f.kind !== undefined);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/** mapping 字段的目标前缀:`{key}` 占位取 meta 里同名键的当前值 */
|
|
769
|
+
export const mappingPrefix: (f: FlowField, meta: Record<string, unknown>) => string = mappingPrefixOf;
|
|
770
|
+
|
|
771
|
+
/** 目标名补前缀:不含 `.` 的裸名补上 prefix;已带前缀照用;其余(别的命名空间)返回 null */
|
|
772
|
+
export function normalizeMapTarget(raw: string, prefix: string): string | null {
|
|
773
|
+
const name = raw.trim();
|
|
774
|
+
if (name === '') return null;
|
|
775
|
+
if (prefix === '') return name;
|
|
776
|
+
if (!name.includes('.')) return `${prefix}${name}`;
|
|
777
|
+
return name.startsWith(prefix) ? name : null;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** 把 FieldMapper 抛出的映射收成合法映射表;被丢弃的目标名一并返回,用于提示 */
|
|
781
|
+
export function cleanFlowMapping(value: unknown, prefix: string): { mapping: Record<string, string>; dropped: string[] } {
|
|
782
|
+
const mapping: Record<string, string> = {};
|
|
783
|
+
const dropped: string[] = [];
|
|
784
|
+
for (const [target, source] of Object.entries(rec(value))) {
|
|
785
|
+
const s = str(source);
|
|
786
|
+
if (s === '') continue;
|
|
787
|
+
const k = normalizeMapTarget(target, prefix);
|
|
788
|
+
if (k === null) dropped.push(target); else mapping[k] = s;
|
|
789
|
+
}
|
|
790
|
+
return { mapping, dropped };
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** mapping 字段当前可用的目标(带前缀的完整 key):声明的 + meta 里已有但未声明的(label 去前缀) */
|
|
794
|
+
export function mappingTargets(f: FlowField, meta: Record<string, unknown>): { targets: FlowMapTarget[]; waiting: boolean } {
|
|
795
|
+
const prefix = mappingPrefix(f, meta);
|
|
796
|
+
let base = f.targets ?? [];
|
|
797
|
+
if (f.targets_by !== undefined) {
|
|
798
|
+
const by = str(meta[f.targets_by]);
|
|
799
|
+
if (by === '') return { targets: [], waiting: true };
|
|
800
|
+
base = f.targets_map?.[by] ?? [];
|
|
801
|
+
}
|
|
802
|
+
const targets = base.map((x) => ({ ...x, key: `${prefix}${x.key}` }));
|
|
803
|
+
const have = new Set(targets.map((x) => x.key));
|
|
804
|
+
for (const k of Object.keys(rec(meta[f.key]))) {
|
|
805
|
+
if (!have.has(k)) targets.push({ key: k, label: prefix !== '' && k.startsWith(prefix) ? k.slice(prefix.length) : k });
|
|
806
|
+
}
|
|
807
|
+
return { targets, waiting: false };
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** 面板签名:节点 id + 类型 + 面板字段的当前值;用户自己改完先记新签名,外部(撤销、数据下发)改了才重画 */
|
|
811
|
+
export function panelSig(node: FlowNode, fields: readonly FlowField[]): string {
|
|
812
|
+
return JSON.stringify([node.id, node.type, node.label, fields.map((f) => node.meta?.[f.key] ?? null)]);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** 改一个字段后的新节点(纯函数):值进 meta、select 的选项 meta 并入、resets 清空、as_label 同步标题 */
|
|
816
|
+
export function applyFieldValue(node: FlowNode, field: FlowField, value: unknown): FlowNode {
|
|
817
|
+
const meta: Record<string, unknown> = { ...node.meta };
|
|
818
|
+
if (value === undefined || value === null || value === '') delete meta[field.key]; else meta[field.key] = value;
|
|
819
|
+
if (field.kind === 'select') {
|
|
820
|
+
const opt = field.options?.find((o) => o.value === value);
|
|
821
|
+
if (opt?.meta) Object.assign(meta, opt.meta);
|
|
822
|
+
}
|
|
823
|
+
for (const k of field.resets ?? []) delete meta[k];
|
|
824
|
+
const label = field.as_label && typeof value === 'string' && value !== '' ? value : node.label;
|
|
825
|
+
return { ...node, label, meta };
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
export function nodeTypesOf(raw: unknown): Record<string, FlowNodeType> {
|
|
829
|
+
const out: Record<string, FlowNodeType> = {};
|
|
830
|
+
const src = Array.isArray(raw)
|
|
831
|
+
? raw.map((item) => [str(rec(item).type), item] as const)
|
|
832
|
+
: Object.entries(rec(raw));
|
|
833
|
+
for (const [type, item] of src) {
|
|
834
|
+
if (type === '') continue;
|
|
835
|
+
const r = rec(item);
|
|
836
|
+
const to = list(r.to).filter((v): v is string => typeof v === 'string' && v !== '');
|
|
837
|
+
const maxIn = intOf(r.maxIn);
|
|
838
|
+
const maxOut = intOf(r.maxOut);
|
|
839
|
+
const minIn = intOf(r.minIn);
|
|
840
|
+
const minOut = intOf(r.minOut);
|
|
841
|
+
out[type] = {
|
|
842
|
+
type,
|
|
843
|
+
label: str(r.label, type),
|
|
844
|
+
icon: str(r.icon),
|
|
845
|
+
tone: toneOf(r.tone, 'neutral'),
|
|
846
|
+
...(str(r.numbered) !== '' ? { numbered: str(r.numbered) } : {}),
|
|
847
|
+
...(maxIn !== undefined ? { maxIn } : {}),
|
|
848
|
+
...(maxOut !== undefined ? { maxOut } : {}),
|
|
849
|
+
...(minIn !== undefined ? { minIn } : {}),
|
|
850
|
+
...(minOut !== undefined ? { minOut } : {}),
|
|
851
|
+
...(to.length > 0 ? { to } : {}),
|
|
852
|
+
fields: fieldsOf(r.fields),
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
return out;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
export function issuesOf(raw: unknown): FlowIssue[] {
|
|
859
|
+
const out: FlowIssue[] = [];
|
|
860
|
+
for (const item of list(raw)) {
|
|
861
|
+
const r = rec(item);
|
|
862
|
+
const id = str(r.id) !== '' ? str(r.id) : str(r.node) !== '' ? str(r.node) : str(r.edge);
|
|
863
|
+
if (id === '') continue;
|
|
864
|
+
const target = r.target === 'edge' || (r.target === undefined && str(r.edge) !== '') ? 'edge' : 'node';
|
|
865
|
+
const level = r.level === 'warning' || r.level === 'warn' ? 'warning' : 'error';
|
|
866
|
+
out.push({ target, id, level, message: str(r.message) });
|
|
867
|
+
}
|
|
868
|
+
return out;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
export function suggestionsOf(raw: unknown): FlowSuggestion[] {
|
|
872
|
+
const out: FlowSuggestion[] = [];
|
|
873
|
+
const seen = new Set<string>();
|
|
874
|
+
for (const item of list(raw)) {
|
|
875
|
+
const r = rec(item);
|
|
876
|
+
const id = str(r.id);
|
|
877
|
+
if (id === '' || seen.has(id)) continue;
|
|
878
|
+
const nodes = nodesOf(r.nodes);
|
|
879
|
+
// 建议里的连线允许一端指向画布上已有节点,所以这里不做悬空过滤,只做形状收口
|
|
880
|
+
const edges: FlowEdge[] = [];
|
|
881
|
+
const edgeSeen = new Set<string>();
|
|
882
|
+
for (const e of list(r.edges)) {
|
|
883
|
+
const edge = edgeOf(e);
|
|
884
|
+
if (edge === null || edgeSeen.has(edge.id)) continue;
|
|
885
|
+
edgeSeen.add(edge.id);
|
|
886
|
+
edges.push(edge);
|
|
887
|
+
}
|
|
888
|
+
if (nodes.length === 0 && edges.length === 0) continue;
|
|
889
|
+
seen.add(id);
|
|
890
|
+
out.push({ id, label: str(r.label, id), reason: str(r.reason), nodes, edges });
|
|
891
|
+
}
|
|
892
|
+
return out;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* 请求结果 -> 画布建议(纯函数;`adopt: { from, path? }` 的取值,与表单采纳同口径):outcome.data 按 path 取值,
|
|
897
|
+
* 数组 = 多条建议,带 nodes / edges 的对象 = 一条。建议 id 带请求序号前缀,重新请求后「忽略」自动重置;
|
|
898
|
+
* 节点与连线 id 保持原样(采纳后就是画布草稿里的 id)。个数不超过 dataLimits.flowEditor.adoptSuggestMax。
|
|
899
|
+
*/
|
|
900
|
+
export function adoptSuggestionsOf(data: unknown, path: string, seq: number, label: string): FlowSuggestion[] {
|
|
901
|
+
const root = pickPath(data, path);
|
|
902
|
+
const items = Array.isArray(root) ? root : root !== null && typeof root === 'object' ? [root] : [];
|
|
903
|
+
const raw = items.slice(0, KIT_DATA_LIMITS.flowEditor.adoptSuggestMax).map((item, i) => {
|
|
904
|
+
const o = rec(item);
|
|
905
|
+
return { ...o, id: `adopt${seq}-${str(o.id) !== '' ? str(o.id) : String(i)}`, label: str(o.label) !== '' ? str(o.label) : label };
|
|
906
|
+
});
|
|
907
|
+
return suggestionsOf(raw);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function layoutOf(raw: unknown): FlowLayoutMode {
|
|
911
|
+
return raw === 'layered' ? 'layered' : 'manual';
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
function tonesOf(raw: unknown): Record<string, FlowTone> {
|
|
915
|
+
const out: Record<string, FlowTone> = {};
|
|
916
|
+
for (const [k, v] of Object.entries(rec(raw))) if (FLOW_TONES.includes(v as FlowTone)) out[k] = v as FlowTone;
|
|
917
|
+
return out;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function textsOf(raw: unknown, at?: Element | null): Record<string, string> {
|
|
921
|
+
const out: Record<string, string> = flowDefaultTexts(at);
|
|
922
|
+
for (const [k, v] of Object.entries(rec(raw))) if (typeof v === 'string') out[k] = v;
|
|
923
|
+
return out;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* 配置合并:显式 props 优先,其次是 `data.config`(view 路径只能带 data,配置随数据下发)。
|
|
928
|
+
*/
|
|
929
|
+
export function pickOf(props: Record<string, unknown>, key: string): unknown {
|
|
930
|
+
const v = props[key];
|
|
931
|
+
const empty = v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)
|
|
932
|
+
|| (typeof v === 'object' && !Array.isArray(v) && Object.keys(v as object).length === 0);
|
|
933
|
+
return empty ? rec(rec(props.data).config)[key] : v;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
export function configOf(props: Record<string, unknown>, at?: Element | null): FlowConfig {
|
|
937
|
+
const dataCfg = rec(rec(props.data).config);
|
|
938
|
+
const pick = (key: string): unknown => pickOf(props, key);
|
|
939
|
+
return {
|
|
940
|
+
nodeTypes: nodeTypesOf(pick('nodeTypes')),
|
|
941
|
+
layout: layoutOf(pick('layout')),
|
|
942
|
+
readonly: bool(props.readonly) || bool(props.disabled) || bool(dataCfg.readonly),
|
|
943
|
+
allowCycles: bool(pick('allowCycles')),
|
|
944
|
+
statusTones: tonesOf(pick('statusTones')),
|
|
945
|
+
texts: textsOf(pick('texts'), at),
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// ════════════════════════════════════════════════════════════════
|
|
950
|
+
// 图编辑规则(纯函数):能不能连、结构问题、增删移、采纳建议。全部返回新图,不改入参。
|
|
951
|
+
// ════════════════════════════════════════════════════════════════
|
|
952
|
+
|
|
953
|
+
export type ConnectReason = 'self' | 'missing' | 'duplicate' | 'max_out' | 'max_in' | 'type' | 'cycle';
|
|
954
|
+
|
|
955
|
+
export function degrees(edges: readonly FlowEdge[]): { inn: Map<string, number>; out: Map<string, number> } {
|
|
956
|
+
const inn = new Map<string, number>();
|
|
957
|
+
const out = new Map<string, number>();
|
|
958
|
+
for (const e of edges) {
|
|
959
|
+
out.set(e.from, (out.get(e.from) ?? 0) + 1);
|
|
960
|
+
inn.set(e.to, (inn.get(e.to) ?? 0) + 1);
|
|
961
|
+
}
|
|
962
|
+
return { inn, out };
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/** from 能否沿现有连线走到 to */
|
|
966
|
+
export function reachable(edges: readonly FlowEdge[], from: string, to: string): boolean {
|
|
967
|
+
const next = new Map<string, string[]>();
|
|
968
|
+
for (const e of edges) next.set(e.from, [...(next.get(e.from) ?? []), e.to]);
|
|
969
|
+
const seen = new Set<string>([from]);
|
|
970
|
+
const stack = [from];
|
|
971
|
+
while (stack.length > 0) {
|
|
972
|
+
const u = stack.pop()!;
|
|
973
|
+
if (u === to) return true;
|
|
974
|
+
for (const v of next.get(u) ?? []) if (!seen.has(v)) { seen.add(v); stack.push(v); }
|
|
975
|
+
}
|
|
976
|
+
return false;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
export function canConnect(
|
|
980
|
+
graph: FlowGraph,
|
|
981
|
+
types: Readonly<Record<string, FlowNodeType>>,
|
|
982
|
+
from: string,
|
|
983
|
+
to: string,
|
|
984
|
+
allowCycles: boolean,
|
|
985
|
+
): { ok: true } | { ok: false; reason: ConnectReason } {
|
|
986
|
+
const a = graph.nodes.find((n) => n.id === from);
|
|
987
|
+
const b = graph.nodes.find((n) => n.id === to);
|
|
988
|
+
if (!a || !b) return { ok: false, reason: 'missing' };
|
|
989
|
+
if (from === to) return { ok: false, reason: 'self' };
|
|
990
|
+
if (graph.edges.some((e) => e.from === from && e.to === to)) return { ok: false, reason: 'duplicate' };
|
|
991
|
+
const ta = types[a.type];
|
|
992
|
+
const tb = types[b.type];
|
|
993
|
+
if (ta?.to !== undefined && !ta.to.includes(b.type)) return { ok: false, reason: 'type' };
|
|
994
|
+
const d = degrees(graph.edges);
|
|
995
|
+
if (ta?.maxOut !== undefined && (d.out.get(from) ?? 0) >= ta.maxOut) return { ok: false, reason: 'max_out' };
|
|
996
|
+
if (tb?.maxIn !== undefined && (d.inn.get(to) ?? 0) >= tb.maxIn) return { ok: false, reason: 'max_in' };
|
|
997
|
+
if (!allowCycles && reachable(graph.edges, to, from)) return { ok: false, reason: 'cycle' };
|
|
998
|
+
return { ok: true };
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** 结构问题(组件自检,和外部传入的 validation 并列显示):未知类型、度数上下限、成环 */
|
|
1002
|
+
export function structureIssues(
|
|
1003
|
+
graph: FlowGraph,
|
|
1004
|
+
types: Readonly<Record<string, FlowNodeType>>,
|
|
1005
|
+
allowCycles: boolean,
|
|
1006
|
+
msg: (code: string) => string,
|
|
1007
|
+
): FlowIssue[] {
|
|
1008
|
+
const out: FlowIssue[] = [];
|
|
1009
|
+
const hasTypes = Object.keys(types).length > 0;
|
|
1010
|
+
const d = degrees(graph.edges);
|
|
1011
|
+
for (const n of graph.nodes) {
|
|
1012
|
+
const t = types[n.type];
|
|
1013
|
+
if (!t) {
|
|
1014
|
+
if (hasTypes) out.push({ target: 'node', id: n.id, level: 'error', message: msg('i_unknown') });
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
const i = d.inn.get(n.id) ?? 0;
|
|
1018
|
+
const o = d.out.get(n.id) ?? 0;
|
|
1019
|
+
if (t.minIn !== undefined && i < t.minIn) out.push({ target: 'node', id: n.id, level: 'warning', message: msg('i_min_in') });
|
|
1020
|
+
if (t.minOut !== undefined && o < t.minOut) out.push({ target: 'node', id: n.id, level: 'warning', message: msg('i_min_out') });
|
|
1021
|
+
if (t.maxIn !== undefined && i > t.maxIn) out.push({ target: 'node', id: n.id, level: 'error', message: msg('i_max_in') });
|
|
1022
|
+
if (t.maxOut !== undefined && o > t.maxOut) out.push({ target: 'node', id: n.id, level: 'error', message: msg('i_max_out') });
|
|
1023
|
+
}
|
|
1024
|
+
if (!allowCycles) {
|
|
1025
|
+
for (const e of graph.edges) {
|
|
1026
|
+
if (reachable(graph.edges.filter((x) => x.id !== e.id), e.to, e.from)) {
|
|
1027
|
+
out.push({ target: 'edge', id: e.id, level: 'error', message: msg('i_cycle') });
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
return out;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/** 最小的未被占用的 `<前缀><n>`,同输入同输出 */
|
|
1035
|
+
export function newId(prefix: string, existing: Iterable<string>): string {
|
|
1036
|
+
const used = new Set(existing);
|
|
1037
|
+
let n = 1;
|
|
1038
|
+
while (used.has(`${prefix}${n}`)) n += 1;
|
|
1039
|
+
return `${prefix}${n}`;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function pruneMappings(mappings: unknown, gone: ReadonlySet<string>): unknown {
|
|
1043
|
+
if (mappings === null || typeof mappings !== 'object' || Array.isArray(mappings)) return mappings;
|
|
1044
|
+
const out: Record<string, unknown> = {};
|
|
1045
|
+
for (const [k, v] of Object.entries(mappings as Record<string, unknown>)) if (!gone.has(k)) out[k] = v;
|
|
1046
|
+
return out;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function withMappings(base: FlowGraph, nodes: FlowNode[], edges: FlowEdge[], gone: ReadonlySet<string>): FlowGraph {
|
|
1050
|
+
return { nodes, edges, ...(base.mappings !== undefined ? { mappings: pruneMappings(base.mappings, gone) } : {}) };
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
export function removeItems(graph: FlowGraph, nodeIds: ReadonlySet<string>, edgeIds: ReadonlySet<string>): FlowGraph {
|
|
1054
|
+
const edges = graph.edges.filter((e) => !edgeIds.has(e.id) && !nodeIds.has(e.from) && !nodeIds.has(e.to));
|
|
1055
|
+
const goneEdges = new Set(graph.edges.filter((e) => !edges.includes(e)).map((e) => e.id));
|
|
1056
|
+
return withMappings(graph, graph.nodes.filter((n) => !nodeIds.has(n.id)), edges, new Set([...nodeIds, ...goneEdges]));
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
export function addNode(graph: FlowGraph, node: FlowNode): FlowGraph {
|
|
1060
|
+
return { ...graph, nodes: [...graph.nodes, node] };
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
export function addEdge(graph: FlowGraph, from: string, to: string): { graph: FlowGraph; edge: FlowEdge } {
|
|
1064
|
+
const base = edgeIdOf(from, to);
|
|
1065
|
+
const id = graph.edges.some((e) => e.id === base) ? newId('e', graph.edges.map((e) => e.id)) : base;
|
|
1066
|
+
const edge: FlowEdge = { id, from, to };
|
|
1067
|
+
return { graph: { ...graph, edges: [...graph.edges, edge] }, edge };
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/**
|
|
1071
|
+
* 在目标节点上方插入新节点(纯函数):目标的所有入边改指新节点(连线 id、标签保留),再加一条 新节点 -> 目标。
|
|
1072
|
+
* 类型约束:前驱的 `to` 须允许新类型、新类型的 `to` 须允许目标类型、新类型的入边上限不小于被改接的入边数、出边上限不小于 1。
|
|
1073
|
+
*/
|
|
1074
|
+
export function insertBefore(
|
|
1075
|
+
graph: FlowGraph,
|
|
1076
|
+
types: Readonly<Record<string, FlowNodeType>>,
|
|
1077
|
+
targetId: string,
|
|
1078
|
+
node: FlowNode,
|
|
1079
|
+
): { ok: true; graph: FlowGraph } | { ok: false; reason: ConnectReason } {
|
|
1080
|
+
const target = graph.nodes.find((n) => n.id === targetId);
|
|
1081
|
+
if (!target) return { ok: false, reason: 'missing' };
|
|
1082
|
+
const incoming = graph.edges.filter((e) => e.to === targetId);
|
|
1083
|
+
const tn = types[node.type];
|
|
1084
|
+
if (tn?.to !== undefined && !tn.to.includes(target.type)) return { ok: false, reason: 'type' };
|
|
1085
|
+
if (tn?.maxOut !== undefined && tn.maxOut < 1) return { ok: false, reason: 'max_out' };
|
|
1086
|
+
if (tn?.maxIn !== undefined && incoming.length > tn.maxIn) return { ok: false, reason: 'max_in' };
|
|
1087
|
+
for (const e of incoming) {
|
|
1088
|
+
const from = graph.nodes.find((n) => n.id === e.from);
|
|
1089
|
+
const tf = from ? types[from.type] : undefined;
|
|
1090
|
+
if (tf?.to !== undefined && !tf.to.includes(node.type)) return { ok: false, reason: 'type' };
|
|
1091
|
+
}
|
|
1092
|
+
const edges = graph.edges.map((e) => (e.to === targetId ? { ...e, to: node.id } : e));
|
|
1093
|
+
const link: FlowEdge = { id: edgeIdOf(node.id, targetId), from: node.id, to: targetId };
|
|
1094
|
+
const at = graph.nodes.findIndex((n) => n.id === targetId);
|
|
1095
|
+
const nodes = [...graph.nodes.slice(0, at), node, ...graph.nodes.slice(at)];
|
|
1096
|
+
return { ok: true, graph: { ...graph, nodes, edges: [...edges, link] } };
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* 先后调整(纯函数):把节点与它唯一的后继(down)或唯一的前驱(up)对调。
|
|
1101
|
+
* 只在 a -> b 是 a 唯一的出边、也是 b 唯一的入边时成立(分支的出口、汇合点不动):
|
|
1102
|
+
* a 的入边改接 b,a -> b 反向成 b -> a(id、标签保留),b 的出边改接 a;对调后各条连线仍要满足类型的 `to` 与度数上限。
|
|
1103
|
+
*/
|
|
1104
|
+
export function moveInChain(
|
|
1105
|
+
graph: FlowGraph,
|
|
1106
|
+
types: Readonly<Record<string, FlowNodeType>>,
|
|
1107
|
+
id: string,
|
|
1108
|
+
dir: 'up' | 'down',
|
|
1109
|
+
): { ok: true; graph: FlowGraph; a: string; b: string } | { ok: false } {
|
|
1110
|
+
const edgeIn = graph.edges.filter((e) => e.to === id);
|
|
1111
|
+
const edgeOut = graph.edges.filter((e) => e.from === id);
|
|
1112
|
+
const pair = dir === 'down'
|
|
1113
|
+
? (edgeOut.length === 1 ? edgeOut[0]! : null)
|
|
1114
|
+
: (edgeIn.length === 1 ? edgeIn[0]! : null);
|
|
1115
|
+
if (!pair) return { ok: false };
|
|
1116
|
+
const a = pair.from;
|
|
1117
|
+
const b = pair.to;
|
|
1118
|
+
if (graph.edges.filter((e) => e.from === a).length !== 1 || graph.edges.filter((e) => e.to === b).length !== 1) return { ok: false };
|
|
1119
|
+
const na = graph.nodes.find((n) => n.id === a);
|
|
1120
|
+
const nb = graph.nodes.find((n) => n.id === b);
|
|
1121
|
+
if (!na || !nb) return { ok: false };
|
|
1122
|
+
const edges = graph.edges.map((e) => {
|
|
1123
|
+
if (e.id === pair.id) return { ...e, from: b, to: a };
|
|
1124
|
+
if (e.to === a) return { ...e, to: b };
|
|
1125
|
+
if (e.from === b) return { ...e, from: a };
|
|
1126
|
+
return e;
|
|
1127
|
+
});
|
|
1128
|
+
// 约束:对调后新连线的两端类型要互相允许,度数不超上限
|
|
1129
|
+
const kindOf = (nid: string): FlowNodeType | undefined => types[graph.nodes.find((n) => n.id === nid)?.type ?? ''];
|
|
1130
|
+
const d = degrees(edges);
|
|
1131
|
+
for (const e of edges) {
|
|
1132
|
+
const tf = kindOf(e.from);
|
|
1133
|
+
const typeTo = graph.nodes.find((n) => n.id === e.to)?.type ?? '';
|
|
1134
|
+
if (tf?.to !== undefined && !tf.to.includes(typeTo)) return { ok: false };
|
|
1135
|
+
}
|
|
1136
|
+
for (const nid of [a, b]) {
|
|
1137
|
+
const t = kindOf(nid);
|
|
1138
|
+
if (t?.maxIn !== undefined && (d.inn.get(nid) ?? 0) > t.maxIn) return { ok: false };
|
|
1139
|
+
if (t?.maxOut !== undefined && (d.out.get(nid) ?? 0) > t.maxOut) return { ok: false };
|
|
1140
|
+
}
|
|
1141
|
+
// 节点数组里两者的先后同步对调(分层布局的层内顺序跟数组走)
|
|
1142
|
+
const nodes = graph.nodes.slice();
|
|
1143
|
+
const ia = nodes.findIndex((n) => n.id === a);
|
|
1144
|
+
const ib = nodes.findIndex((n) => n.id === b);
|
|
1145
|
+
[nodes[ia], nodes[ib]] = [nodes[ib]!, nodes[ia]!];
|
|
1146
|
+
return { ok: true, graph: { ...graph, nodes, edges }, a, b };
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/** 序号(只读):声明了 numbered 前缀的节点类型,按「分层、再按节点输入顺序」依次编号 `<前缀><n>`,随图实时重算,不保存 */
|
|
1150
|
+
export function ordinalsOf(graph: FlowGraph, types: Readonly<Record<string, FlowNodeType>>): Map<string, string> {
|
|
1151
|
+
const out = new Map<string, string>();
|
|
1152
|
+
if (!Object.values(types).some((t) => (t.numbered ?? '') !== '')) return out;
|
|
1153
|
+
const ranks = layeredLayout(graph.nodes, graph.edges).ranks;
|
|
1154
|
+
const order = new Map(graph.nodes.map((n, i) => [n.id, i] as const));
|
|
1155
|
+
const counters = new Map<string, number>();
|
|
1156
|
+
const sorted = [...graph.nodes].sort((x, y) => ((ranks.get(x.id) ?? 0) - (ranks.get(y.id) ?? 0)) || (order.get(x.id)! - order.get(y.id)!));
|
|
1157
|
+
for (const n of sorted) {
|
|
1158
|
+
const prefix = types[n.type]?.numbered ?? '';
|
|
1159
|
+
if (prefix === '') continue;
|
|
1160
|
+
const c = (counters.get(n.type) ?? 0) + 1;
|
|
1161
|
+
counters.set(n.type, c);
|
|
1162
|
+
out.set(n.id, `${prefix}${c}`);
|
|
1163
|
+
}
|
|
1164
|
+
return out;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/** 写入坐标(不在 moves 里的节点原样) */
|
|
1168
|
+
export function setPositions(graph: FlowGraph, moves: ReadonlyMap<string, { x: number; y: number }>): FlowGraph {
|
|
1169
|
+
return { ...graph, nodes: graph.nodes.map((n) => { const m = moves.get(n.id); return m ? { ...n, x: m.x, y: m.y } : n; }) };
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/** 采纳建议:节点按 id 去重加入,连线两端都存在且 id 不重才加入 */
|
|
1173
|
+
export function applySuggestion(graph: FlowGraph, s: FlowSuggestion, pos: ReadonlyMap<string, { x: number; y: number }>): FlowGraph {
|
|
1174
|
+
const have = new Set(graph.nodes.map((n) => n.id));
|
|
1175
|
+
const nodes = [...graph.nodes];
|
|
1176
|
+
for (const n of s.nodes) {
|
|
1177
|
+
if (have.has(n.id)) continue;
|
|
1178
|
+
have.add(n.id);
|
|
1179
|
+
const p = pos.get(n.id);
|
|
1180
|
+
nodes.push({ ...n, ...(p ? { x: p.x, y: p.y } : {}) });
|
|
1181
|
+
}
|
|
1182
|
+
const edgeIds = new Set(graph.edges.map((e) => e.id));
|
|
1183
|
+
const edges = [...graph.edges];
|
|
1184
|
+
for (const e of s.edges) {
|
|
1185
|
+
if (edgeIds.has(e.id) || !have.has(e.from) || !have.has(e.to)) continue;
|
|
1186
|
+
edgeIds.add(e.id);
|
|
1187
|
+
edges.push(e);
|
|
1188
|
+
}
|
|
1189
|
+
return { ...graph, nodes, edges };
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
// ════════════════════════════════════════════════════════════════
|
|
1193
|
+
// 组件
|
|
1194
|
+
// ════════════════════════════════════════════════════════════════
|
|
1195
|
+
|
|
1196
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
1197
|
+
const HL = FLOW_CLASS.target.split(' ');
|
|
1198
|
+
let SEQ = 0;
|
|
1199
|
+
|
|
1200
|
+
interface DragPortLike {
|
|
1201
|
+
draggable(el: HTMLElement, source: {
|
|
1202
|
+
id: string; data: () => Record<string, unknown>; canDrag?: () => boolean; onDragStart?(): void; onDragEnd?(): void;
|
|
1203
|
+
}): () => void;
|
|
1204
|
+
dropTarget(el: HTMLElement, target: {
|
|
1205
|
+
id: string; canDrop?: (sourceId: string) => boolean; onOver?(edge: unknown): void; onLeave?(): void;
|
|
1206
|
+
}): () => void;
|
|
1207
|
+
onMove(handler: (intent: { sourceId: string; targetId: string }) => void): () => void;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
type Level = 'error' | 'warning' | '';
|
|
1211
|
+
type Press =
|
|
1212
|
+
| { kind: 'node'; key: string; sx: number; sy: number; moved: boolean; additive: boolean; origin: Map<string, Pt> | null }
|
|
1213
|
+
| { kind: 'pan'; sx: number; sy: number; moved: boolean; start: FlowView; additive: boolean }
|
|
1214
|
+
| { kind: 'marquee'; sx: number; sy: number; moved: boolean; ax: number; ay: number };
|
|
1215
|
+
|
|
1216
|
+
function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls = '', attrs: Record<string, string> = {}): HTMLElementTagNameMap[K] {
|
|
1217
|
+
const e = document.createElement(tag);
|
|
1218
|
+
if (cls !== '') e.className = cls;
|
|
1219
|
+
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
|
|
1220
|
+
return e;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
function svg<K extends keyof SVGElementTagNameMap>(tag: K, cls = '', attrs: Record<string, string> = {}): SVGElementTagNameMap[K] {
|
|
1224
|
+
const e = document.createElementNS(SVG_NS, tag);
|
|
1225
|
+
if (cls !== '') e.setAttribute('class', cls);
|
|
1226
|
+
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
|
|
1227
|
+
return e;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/** SVG 元素的 className 是只读对象,统一用属性写类 */
|
|
1231
|
+
function setCls(target: Element, cls: string): void {
|
|
1232
|
+
target.setAttribute('class', cls);
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/** 坐标是数据:核心样式引擎不放行任意值类(含括号变量写法),所以定位全部走 SVG 几何属性,不写 style、不写 CSS 变量 */
|
|
1236
|
+
function place(target: Element, at: Pt, w: number, h: number): void {
|
|
1237
|
+
target.setAttribute('x', String(at.x));
|
|
1238
|
+
target.setAttribute('y', String(at.y));
|
|
1239
|
+
target.setAttribute('width', String(w));
|
|
1240
|
+
target.setAttribute('height', String(h));
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
const keyOfNode = (id: string): string => `n:${id}`;
|
|
1244
|
+
const keyOfEdge = (id: string): string => `e:${id}`;
|
|
1245
|
+
|
|
1246
|
+
export function createFlowEditor(): SomaComponentDefinition {
|
|
1247
|
+
return {
|
|
1248
|
+
contract: FLOW_EDITOR_CONTRACT,
|
|
1249
|
+
services: ['engines', 'data'],
|
|
1250
|
+
templateHtml: `<div data-soma-id="root" class="${FLOW_CLASS.root}"></div>`,
|
|
1251
|
+
controllerFactory: (ctx: SomaComponentControllerContext) => {
|
|
1252
|
+
const P = (): Record<string, unknown> => (ctx.readProps ? ctx.readProps() : ctx.props);
|
|
1253
|
+
const uid = `kit-flow-${++SEQ}`;
|
|
1254
|
+
|
|
1255
|
+
// ---- 状态
|
|
1256
|
+
let root: HTMLElement | null = null;
|
|
1257
|
+
let cfg: FlowConfig = configOf({});
|
|
1258
|
+
let graph: FlowGraph = { nodes: [], edges: [] };
|
|
1259
|
+
let history: FlowHistory = emptyHistory();
|
|
1260
|
+
let external: FlowIssue[] = [];
|
|
1261
|
+
let suggestions: FlowSuggestion[] = [];
|
|
1262
|
+
let rejected = new Set<string>();
|
|
1263
|
+
let sugSig = '';
|
|
1264
|
+
// adopt:来自请求结果的建议(订阅的 into 名、路径、标签、当前建议、退订)
|
|
1265
|
+
let adoptFrom = '';
|
|
1266
|
+
let adoptPath = '';
|
|
1267
|
+
let adoptLabel = '';
|
|
1268
|
+
let adoptSug: FlowSuggestion[] = [];
|
|
1269
|
+
let adoptOff: (() => void) | null = null;
|
|
1270
|
+
let lastDataSig = '';
|
|
1271
|
+
let view: FlowView = { zoom: 1, panX: 0, panY: 0 };
|
|
1272
|
+
let needFit = true;
|
|
1273
|
+
let selected = new Set<string>();
|
|
1274
|
+
let active = '';
|
|
1275
|
+
let connectFrom: string | null = null;
|
|
1276
|
+
let dragFrom: string | null = null;
|
|
1277
|
+
let flash = '';
|
|
1278
|
+
let press: Press | null = null;
|
|
1279
|
+
let dragPos: Map<string, Pt> | null = null;
|
|
1280
|
+
let posCache = new Map<string, Pt>();
|
|
1281
|
+
let ordinals = new Map<string, string>();
|
|
1282
|
+
let ghostPosCache = new Map<string, Pt>();
|
|
1283
|
+
let menuOpen = false;
|
|
1284
|
+
// 内置配置面板:已画好的节点(id|type)、面板字段值签名、强制重画标记、嵌入件释放袋
|
|
1285
|
+
let panelId = '';
|
|
1286
|
+
let panelVals = '';
|
|
1287
|
+
// H2a:面板 select 字段的候选签名(宿主异步取到 / 换了候选就重画,不受「正在打字」保护)
|
|
1288
|
+
let panelOptsSig = '';
|
|
1289
|
+
let panelForce = false;
|
|
1290
|
+
let hintEls: Array<{ el: HTMLElement; field: FlowField }> = [];
|
|
1291
|
+
const panelEmbeds = createKitEmbedBag();
|
|
1292
|
+
|
|
1293
|
+
// ---- 骨架元素(建一次)
|
|
1294
|
+
let panelOuter!: HTMLElement;
|
|
1295
|
+
let panelInner!: HTMLElement;
|
|
1296
|
+
let panelTitleEl!: HTMLElement;
|
|
1297
|
+
let toolbar!: HTMLElement;
|
|
1298
|
+
let stage!: HTMLElement;
|
|
1299
|
+
let gridPattern!: SVGPatternElement;
|
|
1300
|
+
let gridDot!: SVGCircleElement;
|
|
1301
|
+
let world!: SVGGElement;
|
|
1302
|
+
let svgLayer!: SVGGElement;
|
|
1303
|
+
let nodesLayer!: SVGGElement;
|
|
1304
|
+
let marqueeOuter!: SVGGElement;
|
|
1305
|
+
let marqueeRect!: SVGRectElement;
|
|
1306
|
+
let menuOuter!: SVGGElement;
|
|
1307
|
+
let menuFo!: SVGForeignObjectElement;
|
|
1308
|
+
let menuInner!: HTMLElement;
|
|
1309
|
+
let emptyOuter!: HTMLElement;
|
|
1310
|
+
let emptyInner!: HTMLElement;
|
|
1311
|
+
let errorOuter!: HTMLElement;
|
|
1312
|
+
let errorInner!: HTMLElement;
|
|
1313
|
+
let statusEl!: HTMLElement;
|
|
1314
|
+
let removers: Array<() => void> = [];
|
|
1315
|
+
let dndCleanups: Array<() => void> = [];
|
|
1316
|
+
let offMove: (() => void) | null = null;
|
|
1317
|
+
|
|
1318
|
+
const t = (key: string, vars: Record<string, string | number> = {}): string => fmt(cfg.texts[key] ?? key, vars);
|
|
1319
|
+
const editable = (): boolean => !cfg.readonly;
|
|
1320
|
+
const movable = (): boolean => editable() && cfg.layout === 'manual';
|
|
1321
|
+
const dndPort = (): DragPortLike | null => {
|
|
1322
|
+
const engines = (ctx.services as { engines?: { dnd?: DragPortLike } } | undefined)?.engines;
|
|
1323
|
+
return engines?.dnd ?? null;
|
|
1324
|
+
};
|
|
1325
|
+
const nodeById = (id: string): FlowNode | undefined => graph.nodes.find((n) => n.id === id);
|
|
1326
|
+
const typeOf = (n: FlowNode) => cfg.nodeTypes[n.type];
|
|
1327
|
+
const labelOf = (id: string): string => nodeById(id)?.label ?? id;
|
|
1328
|
+
const selectedNodeIds = (): string[] => [...selected].filter((k) => k.startsWith('n:')).map((k) => k.slice(2));
|
|
1329
|
+
const selectedEdgeIds = (): string[] => [...selected].filter((k) => k.startsWith('e:')).map((k) => k.slice(2));
|
|
1330
|
+
|
|
1331
|
+
// ---- 位置与问题
|
|
1332
|
+
const computePositions = (): Map<string, Pt> => {
|
|
1333
|
+
const lay = layeredLayout(graph.nodes, graph.edges).positions;
|
|
1334
|
+
const out = new Map<string, Pt>();
|
|
1335
|
+
for (const n of graph.nodes) {
|
|
1336
|
+
const auto = lay.get(n.id) ?? { x: 0, y: 0 };
|
|
1337
|
+
out.set(n.id, cfg.layout === 'layered' || n.x === undefined || n.y === undefined ? auto : { x: n.x, y: n.y });
|
|
1338
|
+
}
|
|
1339
|
+
return out;
|
|
1340
|
+
};
|
|
1341
|
+
const posOf = (id: string): Pt | undefined => dragPos?.get(id) ?? posCache.get(id) ?? ghostPosCache.get(id);
|
|
1342
|
+
|
|
1343
|
+
const visibleSuggestions = (): FlowSuggestion[] => suggestions.filter((s) => !rejected.has(s.id));
|
|
1344
|
+
|
|
1345
|
+
const ghostsOf = (): { nodes: Array<FlowNode & { sid: string }>; edges: Array<FlowEdge & { sid: string }> } => {
|
|
1346
|
+
const have = new Set(graph.nodes.map((n) => n.id));
|
|
1347
|
+
const nodes: Array<FlowNode & { sid: string }> = [];
|
|
1348
|
+
const edges: Array<FlowEdge & { sid: string }> = [];
|
|
1349
|
+
for (const s of visibleSuggestions()) {
|
|
1350
|
+
for (const n of s.nodes) if (!have.has(n.id)) { have.add(n.id); nodes.push({ ...n, sid: s.id }); }
|
|
1351
|
+
}
|
|
1352
|
+
const edgeIds = new Set(graph.edges.map((e) => e.id));
|
|
1353
|
+
for (const s of visibleSuggestions()) {
|
|
1354
|
+
for (const e of s.edges) {
|
|
1355
|
+
if (edgeIds.has(e.id) || !have.has(e.from) || !have.has(e.to)) continue;
|
|
1356
|
+
edgeIds.add(e.id);
|
|
1357
|
+
edges.push({ ...e, sid: s.id });
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
return { nodes, edges };
|
|
1361
|
+
};
|
|
1362
|
+
|
|
1363
|
+
let issueMemo: { graph: FlowGraph; external: FlowIssue[]; cfg: FlowConfig; map: Map<string, FlowIssue[]> } | null = null;
|
|
1364
|
+
const issueIndex = (): Map<string, FlowIssue[]> => {
|
|
1365
|
+
// 拖动节点时每次 pointermove 都重画连线;图、外部问题、配置没变就复用(成环检查是 O(E²))
|
|
1366
|
+
if (issueMemo && issueMemo.graph === graph && issueMemo.external === external && issueMemo.cfg === cfg) return issueMemo.map;
|
|
1367
|
+
const all = [...external, ...structureIssues(graph, cfg.nodeTypes, cfg.allowCycles, (code) => t(code))];
|
|
1368
|
+
const map = new Map<string, FlowIssue[]>();
|
|
1369
|
+
for (const i of all) {
|
|
1370
|
+
const key = i.target === 'edge' ? keyOfEdge(i.id) : keyOfNode(i.id);
|
|
1371
|
+
map.set(key, [...(map.get(key) ?? []), i]);
|
|
1372
|
+
}
|
|
1373
|
+
issueMemo = { graph, external, cfg, map };
|
|
1374
|
+
return map;
|
|
1375
|
+
};
|
|
1376
|
+
const levelOf = (list: readonly FlowIssue[] | undefined): Level =>
|
|
1377
|
+
list === undefined || list.length === 0 ? '' : list.some((i) => i.level === 'error') ? 'error' : 'warning';
|
|
1378
|
+
const worst = (list: readonly FlowIssue[] | undefined): FlowIssue | undefined =>
|
|
1379
|
+
list?.find((i) => i.level === 'error') ?? list?.[0];
|
|
1380
|
+
|
|
1381
|
+
// ---- 对外事件与提交
|
|
1382
|
+
const payload = (g: FlowGraph): Record<string, unknown> => {
|
|
1383
|
+
const graphOut = { nodes: g.nodes, edges: g.edges, ...(g.mappings !== undefined ? { mappings: g.mappings } : {}) };
|
|
1384
|
+
// value:作表单字段控件时表单取它作字段值(值协议同基础组件:change { value });整图原样,随表单一起提交
|
|
1385
|
+
return { ...graphOut, value: graphOut };
|
|
1386
|
+
};
|
|
1387
|
+
|
|
1388
|
+
const emitSelect = (lastKey?: string): void => {
|
|
1389
|
+
const k = lastKey ?? [...selected][selected.size - 1];
|
|
1390
|
+
if (k === undefined) ctx.emit('select', { id: '', kind: 'none' });
|
|
1391
|
+
else ctx.emit('select', { id: k.slice(2), kind: k.startsWith('n:') ? 'node' : 'edge' });
|
|
1392
|
+
};
|
|
1393
|
+
|
|
1394
|
+
const setSelection = (keys: Iterable<string>, lastKey?: string): void => {
|
|
1395
|
+
const next = new Set(keys);
|
|
1396
|
+
const same = next.size === selected.size && [...next].every((k) => selected.has(k));
|
|
1397
|
+
selected = next;
|
|
1398
|
+
if (!same) emitSelect(lastKey);
|
|
1399
|
+
};
|
|
1400
|
+
|
|
1401
|
+
const pruneSelection = (): void => {
|
|
1402
|
+
const ok = new Set([...graph.nodes.map((n) => keyOfNode(n.id)), ...graph.edges.map((e) => keyOfEdge(e.id))]);
|
|
1403
|
+
selected = new Set([...selected].filter((k) => ok.has(k)));
|
|
1404
|
+
if (connectFrom !== null && !nodeById(connectFrom)) connectFrom = null;
|
|
1405
|
+
};
|
|
1406
|
+
|
|
1407
|
+
/** 提交一次改动:入撤销栈、替换图、抛 change、重绘。coalesce 非空时同键连续操作只记一次起点 */
|
|
1408
|
+
const commit = (next: FlowGraph, coalesce = ''): void => {
|
|
1409
|
+
history = pushHistory(history, graph, FLOW_GEOMETRY.historyLimit, coalesce);
|
|
1410
|
+
graph = next;
|
|
1411
|
+
pruneSelection();
|
|
1412
|
+
ctx.emit('change', payload(graph));
|
|
1413
|
+
paint();
|
|
1414
|
+
};
|
|
1415
|
+
|
|
1416
|
+
/** 手动布局下,任何结构改动前先把所有节点的当前位置写实,避免之后新增连线让自动落点漂移 */
|
|
1417
|
+
const withPositions = (g: FlowGraph, overrides?: ReadonlyMap<string, Pt>): FlowGraph => {
|
|
1418
|
+
if (cfg.layout !== 'manual') return g;
|
|
1419
|
+
const all = new Map<string, Pt>();
|
|
1420
|
+
for (const n of g.nodes) {
|
|
1421
|
+
const p = overrides?.get(n.id) ?? posCache.get(n.id);
|
|
1422
|
+
if (p) all.set(n.id, p);
|
|
1423
|
+
}
|
|
1424
|
+
return setPositions(g, all);
|
|
1425
|
+
};
|
|
1426
|
+
|
|
1427
|
+
// ---- 动作
|
|
1428
|
+
const say = (text: string): void => { flash = text; };
|
|
1429
|
+
|
|
1430
|
+
const deleteSelection = (): void => {
|
|
1431
|
+
if (!editable()) return;
|
|
1432
|
+
let nodeIds = selectedNodeIds();
|
|
1433
|
+
let edgeIds = selectedEdgeIds();
|
|
1434
|
+
if (nodeIds.length + edgeIds.length === 0 && active !== '') {
|
|
1435
|
+
if (active.startsWith('n:')) nodeIds = [active.slice(2)]; else edgeIds = [active.slice(2)];
|
|
1436
|
+
}
|
|
1437
|
+
if (nodeIds.length + edgeIds.length === 0) return;
|
|
1438
|
+
const next = removeItems(graph, new Set(nodeIds), new Set(edgeIds));
|
|
1439
|
+
say(t('deleted', { n: nodeIds.length + edgeIds.length }));
|
|
1440
|
+
selected = new Set();
|
|
1441
|
+
active = '';
|
|
1442
|
+
commit(next);
|
|
1443
|
+
emitSelect();
|
|
1444
|
+
stage.focus();
|
|
1445
|
+
};
|
|
1446
|
+
|
|
1447
|
+
const tryConnect = (from: string, to: string): void => {
|
|
1448
|
+
const res = canConnect(graph, cfg.nodeTypes, from, to, cfg.allowCycles);
|
|
1449
|
+
connectFrom = null;
|
|
1450
|
+
if (!res.ok) { say(t(`r_${res.reason}`)); paint(); return; }
|
|
1451
|
+
const added = addEdge(withPositions(graph), from, to);
|
|
1452
|
+
say(t('connected', { from: labelOf(from), to: labelOf(to) }));
|
|
1453
|
+
commit(added.graph);
|
|
1454
|
+
};
|
|
1455
|
+
|
|
1456
|
+
const startConnect = (id: string): void => {
|
|
1457
|
+
if (!editable() || !nodeById(id)) return;
|
|
1458
|
+
connectFrom = connectFrom === id ? null : id;
|
|
1459
|
+
say(connectFrom === null ? '' : t('connecting', { label: labelOf(id) }));
|
|
1460
|
+
paint();
|
|
1461
|
+
};
|
|
1462
|
+
|
|
1463
|
+
const addNodeOfType = (type: string): void => {
|
|
1464
|
+
if (!editable()) return;
|
|
1465
|
+
const def = cfg.nodeTypes[type];
|
|
1466
|
+
const id = newId('n', graph.nodes.map((n) => n.id));
|
|
1467
|
+
const same = graph.nodes.filter((n) => n.type === type).length + 1;
|
|
1468
|
+
const base: FlowNode = { id, type, label: `${def?.label ?? (type === '' ? t('nodeDefault') : type)}${same}` };
|
|
1469
|
+
const next = withPositions(graph);
|
|
1470
|
+
const node: FlowNode = cfg.layout === 'manual'
|
|
1471
|
+
? { ...base, ...nextFreeSlot(next.nodes.map((n) => posCache.get(n.id) ?? { x: n.x ?? 0, y: n.y ?? 0 })) }
|
|
1472
|
+
: base;
|
|
1473
|
+
selected = new Set([keyOfNode(id)]);
|
|
1474
|
+
active = keyOfNode(id);
|
|
1475
|
+
needFit = false;
|
|
1476
|
+
commit(addNode(next, node));
|
|
1477
|
+
emitSelect();
|
|
1478
|
+
focusKey(keyOfNode(id));
|
|
1479
|
+
};
|
|
1480
|
+
|
|
1481
|
+
/** 在 targetId 上方插入一个 type 类型的新节点(连线改接,被拒时写明原因) */
|
|
1482
|
+
const insertAbove = (targetId: string, type: string): void => {
|
|
1483
|
+
if (!editable() || !nodeById(targetId)) return;
|
|
1484
|
+
const def = cfg.nodeTypes[type];
|
|
1485
|
+
const id = newId('n', graph.nodes.map((n) => n.id));
|
|
1486
|
+
const same = graph.nodes.filter((n) => n.type === type).length + 1;
|
|
1487
|
+
const base: FlowNode = { id, type, label: `${def?.label ?? (type === '' ? t('nodeDefault') : type)}${same}` };
|
|
1488
|
+
const next = withPositions(graph);
|
|
1489
|
+
const node: FlowNode = cfg.layout === 'manual'
|
|
1490
|
+
? { ...base, ...nextFreeSlot(next.nodes.map((n) => posCache.get(n.id) ?? { x: n.x ?? 0, y: n.y ?? 0 })) }
|
|
1491
|
+
: base;
|
|
1492
|
+
const res = insertBefore(next, cfg.nodeTypes, targetId, node);
|
|
1493
|
+
if (!res.ok) { say(t(`r_${res.reason}`)); paint(); return; }
|
|
1494
|
+
say(t('inserted', { label: labelOf(targetId), inserted: node.label }));
|
|
1495
|
+
selected = new Set([keyOfNode(id)]);
|
|
1496
|
+
active = keyOfNode(id);
|
|
1497
|
+
needFit = false;
|
|
1498
|
+
commit(res.graph);
|
|
1499
|
+
emitSelect();
|
|
1500
|
+
focusKey(keyOfNode(id));
|
|
1501
|
+
};
|
|
1502
|
+
|
|
1503
|
+
/** 与相邻节点对调先后(上移 = 与唯一前驱对调,下移 = 与唯一后继对调) */
|
|
1504
|
+
const moveNode = (id: string, dir: 'up' | 'down'): void => {
|
|
1505
|
+
if (!editable() || !nodeById(id)) return;
|
|
1506
|
+
const base = withPositions(graph);
|
|
1507
|
+
const res = moveInChain(base, cfg.nodeTypes, id, dir);
|
|
1508
|
+
if (!res.ok) { say(t('moveNone')); paint(); return; }
|
|
1509
|
+
let next = res.graph;
|
|
1510
|
+
if (cfg.layout === 'manual') {
|
|
1511
|
+
const pa = posCache.get(res.a);
|
|
1512
|
+
const pb = posCache.get(res.b);
|
|
1513
|
+
if (pa && pb) next = setPositions(next, new Map([[res.a, pb], [res.b, pa]]));
|
|
1514
|
+
}
|
|
1515
|
+
say(t(dir === 'up' ? 'movedUp' : 'movedDown', { label: labelOf(id) }));
|
|
1516
|
+
commit(next);
|
|
1517
|
+
focusKey(keyOfNode(id));
|
|
1518
|
+
};
|
|
1519
|
+
|
|
1520
|
+
const autoLayout = (): void => {
|
|
1521
|
+
if (!movable()) return;
|
|
1522
|
+
const lay = layeredLayout(graph.nodes, graph.edges).positions;
|
|
1523
|
+
commit(setPositions(graph, lay));
|
|
1524
|
+
fit();
|
|
1525
|
+
};
|
|
1526
|
+
|
|
1527
|
+
const doUndo = (): void => {
|
|
1528
|
+
const r = undoHistory(history, graph);
|
|
1529
|
+
if (!r) return;
|
|
1530
|
+
history = r.history; graph = r.graph; pruneSelection();
|
|
1531
|
+
ctx.emit('change', payload(graph));
|
|
1532
|
+
paint();
|
|
1533
|
+
};
|
|
1534
|
+
const doRedo = (): void => {
|
|
1535
|
+
const r = redoHistory(history, graph);
|
|
1536
|
+
if (!r) return;
|
|
1537
|
+
history = r.history; graph = r.graph; pruneSelection();
|
|
1538
|
+
ctx.emit('change', payload(graph));
|
|
1539
|
+
paint();
|
|
1540
|
+
};
|
|
1541
|
+
|
|
1542
|
+
// ---- 内置节点配置面板:选中单个节点,按类型的 kind 字段画表单;改动 -> 新图 -> change(经 core 事件写回)+ node_change
|
|
1543
|
+
const panelTarget = (): { node: FlowNode; fields: FlowField[] } | null => {
|
|
1544
|
+
if (P().panel === false) return null;
|
|
1545
|
+
const ids = selectedNodeIds();
|
|
1546
|
+
if (ids.length !== 1 || selectedEdgeIds().length > 0) return null;
|
|
1547
|
+
const node = nodeById(ids[0]!);
|
|
1548
|
+
const fields = node ? panelFieldsOf(typeOf(node)) : [];
|
|
1549
|
+
return node && fields.length > 0 ? { node, fields } : null;
|
|
1550
|
+
};
|
|
1551
|
+
|
|
1552
|
+
let panelRefocus = '';
|
|
1553
|
+
const setField = (id: string, f: FlowField, value: unknown): void => {
|
|
1554
|
+
const cur = nodeById(id);
|
|
1555
|
+
if (!cur || !editable()) return;
|
|
1556
|
+
const next = applyFieldValue(cur, f, value);
|
|
1557
|
+
panelVals = panelSig(next, panelFieldsOf(typeOf(cur)));
|
|
1558
|
+
if (f.kind === 'select' || (f.resets?.length ?? 0) > 0) { panelForce = true; panelRefocus = f.key; }
|
|
1559
|
+
commit({ ...graph, nodes: graph.nodes.map((n) => (n.id === id ? next : n)) }, `meta:${id}:${f.key}`);
|
|
1560
|
+
ctx.emit('node_change', { id, label: next.label, meta: next.meta ?? {} });
|
|
1561
|
+
};
|
|
1562
|
+
|
|
1563
|
+
const mountCtl = (def: SomaComponentDefinition, parent: HTMLElement, props: Record<string, unknown>, handlers: Record<string, (p: any) => void>): void => {
|
|
1564
|
+
panelEmbeds.add(mountKitComponent(def, parent, props, handlers));
|
|
1565
|
+
};
|
|
1566
|
+
|
|
1567
|
+
const hintText = (f: FlowField, meta: Record<string, unknown>): string => {
|
|
1568
|
+
const v = f.hint_from !== undefined ? meta[f.hint_from] : undefined;
|
|
1569
|
+
return Array.isArray(v) ? v.map(String).join('、') : str(v);
|
|
1570
|
+
};
|
|
1571
|
+
|
|
1572
|
+
const buildMapping = (row: HTMLElement, id: string, f: FlowField, meta: Record<string, unknown>): void => {
|
|
1573
|
+
const { targets, waiting } = mappingTargets(f, meta);
|
|
1574
|
+
if (waiting) {
|
|
1575
|
+
const by = panelFieldsOf(typeOf(nodeById(id)!)).find((x) => x.key === f.targets_by);
|
|
1576
|
+
const w = el('p', FLOW_CLASS.panelHelp);
|
|
1577
|
+
w.textContent = t('pickFirst', { field: by?.label ?? f.targets_by ?? '' });
|
|
1578
|
+
row.appendChild(w);
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
const warn = el('p', FLOW_CLASS.hidden, { role: 'status' });
|
|
1582
|
+
const prefix = mappingPrefix(f, meta);
|
|
1583
|
+
const box = el('div', '');
|
|
1584
|
+
row.append(box, warn);
|
|
1585
|
+
mountCtl(createFieldMapper(), box, {
|
|
1586
|
+
data: { targets, sources: [], mapping: rec(meta[f.key]) },
|
|
1587
|
+
allow_add: true,
|
|
1588
|
+
reset_label: '',
|
|
1589
|
+
disabled: !editable(),
|
|
1590
|
+
empty_text: f.empty_text ?? t('mapEmpty'),
|
|
1591
|
+
}, {
|
|
1592
|
+
change: (p: { value?: unknown }) => {
|
|
1593
|
+
const { mapping, dropped } = cleanFlowMapping(p.value, prefix);
|
|
1594
|
+
warn.className = dropped.length > 0 ? FLOW_CLASS.panelWarn : FLOW_CLASS.hidden;
|
|
1595
|
+
warn.textContent = dropped.length > 0 ? t('dropped', { prefix, names: dropped.join('、') }) : '';
|
|
1596
|
+
setField(id, f, mapping);
|
|
1597
|
+
},
|
|
1598
|
+
});
|
|
1599
|
+
};
|
|
1600
|
+
|
|
1601
|
+
const buildField = (node: FlowNode, f: FlowField): HTMLElement => {
|
|
1602
|
+
const meta = node.meta ?? {};
|
|
1603
|
+
const id = node.id;
|
|
1604
|
+
const ro = !editable();
|
|
1605
|
+
const row = el('div', FLOW_CLASS.panelField, { 'data-flow-field': f.key });
|
|
1606
|
+
const lab = el('span', FLOW_CLASS.panelLabel);
|
|
1607
|
+
lab.textContent = f.label;
|
|
1608
|
+
if (f.required) { const r = el('span', FLOW_CLASS.panelReq, { 'aria-hidden': 'true' }); r.textContent = '*'; lab.appendChild(r); }
|
|
1609
|
+
row.appendChild(lab);
|
|
1610
|
+
const common = { aria_label: f.label, disabled: ro, placeholder: f.placeholder ?? '' };
|
|
1611
|
+
const set = (v: unknown): void => setField(id, f, v);
|
|
1612
|
+
switch (f.kind) {
|
|
1613
|
+
case 'text': mountCtl(createInput(), row, { ...common, value: str(meta[f.key]) }, { change: (p) => set(str(p.value)) }); break;
|
|
1614
|
+
case 'textarea': mountCtl(createTextarea(), row, { ...common, value: str(meta[f.key]) }, { change: (p) => set(str(p.value)) }); break;
|
|
1615
|
+
case 'number':
|
|
1616
|
+
mountCtl(createNumber(), row, { ...common, value: meta[f.key] === undefined ? '' : String(meta[f.key]) }, { change: (p) => set(p.value === null || p.value === undefined ? undefined : Number(p.value)) });
|
|
1617
|
+
break;
|
|
1618
|
+
case 'switch': mountCtl(createSwitch(), row, { aria_label: f.label, disabled: ro, value: meta[f.key] === true }, { change: (p) => set(p.value === true) }); break;
|
|
1619
|
+
case 'select': {
|
|
1620
|
+
const options = f.options ?? [];
|
|
1621
|
+
const sel = panelEmbeds.add(mountKitSelectField({
|
|
1622
|
+
options, value: str(meta[f.key]), placeholder: f.placeholder ?? t('selectPh'), ariaLabel: f.label,
|
|
1623
|
+
disabled: ro, searchable: options.length > 8, className: FLOW_CLASS.panelFull, onChange: set,
|
|
1624
|
+
}));
|
|
1625
|
+
row.appendChild(sel.el);
|
|
1626
|
+
break;
|
|
1627
|
+
}
|
|
1628
|
+
case 'mapping': buildMapping(row, id, f, meta); break;
|
|
1629
|
+
default: break;
|
|
1630
|
+
}
|
|
1631
|
+
if (f.help) { const h = el('p', FLOW_CLASS.panelHelp); h.textContent = f.help; row.appendChild(h); }
|
|
1632
|
+
if (f.kind === 'mapping' && f.hint_from !== undefined) {
|
|
1633
|
+
const h = el('p', FLOW_CLASS.hidden);
|
|
1634
|
+
hintEls.push({ el: h, field: f });
|
|
1635
|
+
row.appendChild(h);
|
|
1636
|
+
}
|
|
1637
|
+
return row;
|
|
1638
|
+
};
|
|
1639
|
+
|
|
1640
|
+
const buildPanel = (node: FlowNode, fields: readonly FlowField[]): void => {
|
|
1641
|
+
panelEmbeds.release(panelInner);
|
|
1642
|
+
panelInner.textContent = '';
|
|
1643
|
+
hintEls = [];
|
|
1644
|
+
panelTitleEl = el('h3', FLOW_CLASS.panelTitle);
|
|
1645
|
+
panelInner.appendChild(panelTitleEl);
|
|
1646
|
+
for (const f of fields) panelInner.appendChild(buildField(node, f));
|
|
1647
|
+
};
|
|
1648
|
+
|
|
1649
|
+
const clearPanel = (): void => {
|
|
1650
|
+
panelEmbeds.release(panelInner);
|
|
1651
|
+
panelInner.textContent = '';
|
|
1652
|
+
hintEls = [];
|
|
1653
|
+
panelId = '';
|
|
1654
|
+
panelVals = '';
|
|
1655
|
+
};
|
|
1656
|
+
|
|
1657
|
+
const focusPanel = (key = ''): void => {
|
|
1658
|
+
const scope = key === '' ? panelInner : panelInner.querySelector<HTMLElement>(`[data-flow-field="${key}"]`) ?? panelInner;
|
|
1659
|
+
scope.querySelector<HTMLElement>('[role="combobox"], input:not([type="hidden"]), textarea, button')?.focus();
|
|
1660
|
+
};
|
|
1661
|
+
|
|
1662
|
+
function paintPanel(): void {
|
|
1663
|
+
const target = panelTarget();
|
|
1664
|
+
if (!target) {
|
|
1665
|
+
if (panelId !== '') clearPanel();
|
|
1666
|
+
panelOuter.className = FLOW_CLASS.hidden;
|
|
1667
|
+
return;
|
|
1668
|
+
}
|
|
1669
|
+
const { node, fields } = target;
|
|
1670
|
+
panelOuter.className = FLOW_CLASS.panelOuter;
|
|
1671
|
+
panelInner.setAttribute('aria-label', t('panelAria'));
|
|
1672
|
+
const id = `${node.id}|${node.type}`;
|
|
1673
|
+
const vals = panelSig(node, fields);
|
|
1674
|
+
// 用户正在面板的输入框里打字时,外部回灌(宿主规整了值)不重画,免得吞掉光标与输入
|
|
1675
|
+
const typing = panelInner.contains(document.activeElement);
|
|
1676
|
+
// 候选签名覆盖候选的真实内容:select 的选项(值 + 标签)、mapping 的声明目标(key + 标签,随 targets_by 当前值取);
|
|
1677
|
+
// 不含 meta 里用户自己写出的映射键(那随打字变化,不该触发重建)
|
|
1678
|
+
const optsSig = JSON.stringify(fields.map((f) => {
|
|
1679
|
+
if (f.kind === 'select') return [f.key, f.placeholder ?? '', (f.options ?? []).map((o) => [o.value, o.label])];
|
|
1680
|
+
if (f.kind === 'mapping') {
|
|
1681
|
+
const by = f.targets_by !== undefined ? str(node.meta?.[f.targets_by]) : '';
|
|
1682
|
+
const base = f.targets_by !== undefined ? (f.targets_map?.[by] ?? []) : (f.targets ?? []);
|
|
1683
|
+
return [f.key, f.prefix ?? '', by, base.map((x) => [x.key, x.label])];
|
|
1684
|
+
}
|
|
1685
|
+
return null;
|
|
1686
|
+
}));
|
|
1687
|
+
if (id !== panelId || panelForce || optsSig !== panelOptsSig || (vals !== panelVals && !typing)) {
|
|
1688
|
+
// 重建会销毁正在输入的元素:记下活动元素在面板里的位置与选区,重建后还原
|
|
1689
|
+
const act = typing ? document.activeElement as HTMLElement | null : null;
|
|
1690
|
+
let keep: { field: string; idx: number; start: number | null; end: number | null } | null = null;
|
|
1691
|
+
if (act && act !== panelInner) {
|
|
1692
|
+
const holder = act.closest<HTMLElement>('[data-flow-field]');
|
|
1693
|
+
const field = holder?.getAttribute('data-flow-field') ?? '';
|
|
1694
|
+
if (holder && field !== '' && panelRefocus === '') {
|
|
1695
|
+
const cands = Array.from(holder.querySelectorAll<HTMLElement>('input, textarea, [role="combobox"], button'));
|
|
1696
|
+
const idx = cands.indexOf(act);
|
|
1697
|
+
const inp = act as HTMLInputElement;
|
|
1698
|
+
let start: number | null = null;
|
|
1699
|
+
let end: number | null = null;
|
|
1700
|
+
try { start = inp.selectionStart; end = inp.selectionEnd; } catch { /* 非文本输入无选区 */ }
|
|
1701
|
+
if (idx >= 0) keep = { field, idx, start, end };
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
buildPanel(node, fields);
|
|
1705
|
+
panelOptsSig = optsSig;
|
|
1706
|
+
panelForce = false;
|
|
1707
|
+
if (panelRefocus !== '') { focusPanel(panelRefocus); panelRefocus = ''; }
|
|
1708
|
+
else if (keep) {
|
|
1709
|
+
const holder = panelInner.querySelector<HTMLElement>(`[data-flow-field="${keep.field}"]`);
|
|
1710
|
+
const target = holder ? Array.from(holder.querySelectorAll<HTMLElement>('input, textarea, [role="combobox"], button'))[keep.idx] : undefined;
|
|
1711
|
+
if (target) {
|
|
1712
|
+
target.focus();
|
|
1713
|
+
if (keep.start !== null && keep.end !== null) {
|
|
1714
|
+
try { (target as HTMLInputElement).setSelectionRange(keep.start, keep.end); } catch { /* 非文本输入无选区 */ }
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
panelId = id;
|
|
1720
|
+
panelVals = vals;
|
|
1721
|
+
panelTitleEl.textContent = t('panelTitle', { label: node.label });
|
|
1722
|
+
for (const h of hintEls) {
|
|
1723
|
+
const text = hintText(h.field, node.meta ?? {});
|
|
1724
|
+
h.el.className = text === '' ? FLOW_CLASS.hidden : FLOW_CLASS.panelHelp;
|
|
1725
|
+
h.el.textContent = text;
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
const requestConfig = (id: string): void => {
|
|
1730
|
+
if (!nodeById(id)) return;
|
|
1731
|
+
const key = keyOfNode(id);
|
|
1732
|
+
if (!(selected.size === 1 && selected.has(key))) { setSelection([key], key); paint(); }
|
|
1733
|
+
ctx.emit('node_config', { id });
|
|
1734
|
+
if (panelTarget() !== null) focusPanel();
|
|
1735
|
+
};
|
|
1736
|
+
|
|
1737
|
+
const accept = (sid: string): void => {
|
|
1738
|
+
const s = suggestions.find((x) => x.id === sid);
|
|
1739
|
+
if (!s || !editable()) return;
|
|
1740
|
+
const base = withPositions(graph);
|
|
1741
|
+
const next = applySuggestion(base, s, ghostPosCache);
|
|
1742
|
+
commit(next);
|
|
1743
|
+
ctx.emit('suggestion_accept', { id: sid });
|
|
1744
|
+
};
|
|
1745
|
+
const reject = (sid: string): void => {
|
|
1746
|
+
rejected = new Set([...rejected, sid]);
|
|
1747
|
+
paint();
|
|
1748
|
+
ctx.emit('suggestion_reject', { id: sid });
|
|
1749
|
+
};
|
|
1750
|
+
|
|
1751
|
+
// ---- 视图
|
|
1752
|
+
const applyView = (): void => {
|
|
1753
|
+
world.setAttribute('transform', `translate(${view.panX} ${view.panY}) scale(${view.zoom})`);
|
|
1754
|
+
if (FLOW_GEOMETRY.grid > 0) {
|
|
1755
|
+
const step = FLOW_GEOMETRY.grid * view.zoom;
|
|
1756
|
+
gridPattern.setAttribute('width', String(step));
|
|
1757
|
+
gridPattern.setAttribute('height', String(step));
|
|
1758
|
+
gridPattern.setAttribute('patternTransform', `translate(${view.panX - step / 2} ${view.panY - step / 2})`);
|
|
1759
|
+
gridDot.setAttribute('cx', String(step / 2));
|
|
1760
|
+
gridDot.setAttribute('cy', String(step / 2));
|
|
1761
|
+
}
|
|
1762
|
+
};
|
|
1763
|
+
const stageSize = (): { w: number; h: number } => ({ w: stage.clientWidth || 0, h: stage.clientHeight || 0 });
|
|
1764
|
+
const allRects = (): Rect[] => [...posCache.values(), ...ghostPosCache.values()].map(nodeRect);
|
|
1765
|
+
function fit(): void {
|
|
1766
|
+
const { w, h } = stageSize();
|
|
1767
|
+
view = w > 0 && h > 0 ? fitView(allRects(), w, h) : { zoom: 1, panX: 0, panY: 0 };
|
|
1768
|
+
needFit = false;
|
|
1769
|
+
applyView();
|
|
1770
|
+
updateZoomLabel();
|
|
1771
|
+
}
|
|
1772
|
+
const zoomBy = (factor: number): void => {
|
|
1773
|
+
const { w, h } = stageSize();
|
|
1774
|
+
view = zoomAt(view, factor, w / 2, h / 2);
|
|
1775
|
+
needFit = false;
|
|
1776
|
+
applyView();
|
|
1777
|
+
updateZoomLabel();
|
|
1778
|
+
};
|
|
1779
|
+
const updateZoomLabel = (): void => {
|
|
1780
|
+
const z = toolbar.querySelector<HTMLElement>('[data-flow-zoom]');
|
|
1781
|
+
if (z) z.textContent = t('zoomLabel', { n: Math.round(view.zoom * 100) });
|
|
1782
|
+
};
|
|
1783
|
+
|
|
1784
|
+
// ---- 焦点
|
|
1785
|
+
const findByAttr = (name: string, value: string): HTMLElement | null => {
|
|
1786
|
+
if (!root) return null;
|
|
1787
|
+
for (const e of root.querySelectorAll<HTMLElement>(`[${name}]:not([data-flow-label])`)) if (e.getAttribute(name) === value) return e;
|
|
1788
|
+
return null;
|
|
1789
|
+
};
|
|
1790
|
+
function focusKey(key: string): void {
|
|
1791
|
+
const e = findByAttr('data-flow-key', key);
|
|
1792
|
+
if (e) (e as unknown as { focus?: () => void }).focus?.();
|
|
1793
|
+
}
|
|
1794
|
+
const focusToken = (): { name: string; value: string } | null => {
|
|
1795
|
+
const a = document.activeElement;
|
|
1796
|
+
if (!root || !a || !root.contains(a) || a === stage) return null;
|
|
1797
|
+
const k = a.closest('[data-flow-key]')?.getAttribute('data-flow-key');
|
|
1798
|
+
if (k) return { name: 'data-flow-key', value: k };
|
|
1799
|
+
const act = a.closest('[data-flow-act]')?.getAttribute('data-flow-act');
|
|
1800
|
+
return act ? { name: 'data-flow-act', value: act } : null;
|
|
1801
|
+
};
|
|
1802
|
+
|
|
1803
|
+
// ---- 绘制
|
|
1804
|
+
const mkButton = (act: string, text: string, opts: { disabled?: boolean; primary?: boolean; icon?: KitIconName } = {}): HTMLButtonElement => {
|
|
1805
|
+
const b = el('button', opts.primary ? FLOW_CLASS.btnPrimary : FLOW_CLASS.btn, { type: 'button', 'data-flow-act': act });
|
|
1806
|
+
if (opts.icon !== undefined) {
|
|
1807
|
+
const ic = kitIcon(opts.icon, 'sm');
|
|
1808
|
+
ic.setAttribute('aria-hidden', 'true');
|
|
1809
|
+
b.appendChild(ic);
|
|
1810
|
+
b.appendChild(document.createTextNode(` ${text}`));
|
|
1811
|
+
} else b.textContent = text;
|
|
1812
|
+
if (opts.disabled) b.disabled = true;
|
|
1813
|
+
return b;
|
|
1814
|
+
};
|
|
1815
|
+
|
|
1816
|
+
const paintToolbar = (): void => {
|
|
1817
|
+
toolbar.textContent = '';
|
|
1818
|
+
if (editable()) {
|
|
1819
|
+
const types = Object.values(cfg.nodeTypes);
|
|
1820
|
+
if (types.length === 0) toolbar.appendChild(mkButton('add:', t('add', { type: t('nodeDefault') })));
|
|
1821
|
+
for (const ty of types) toolbar.appendChild(mkButton(`add:${ty.type}`, t('add', { type: ty.label })));
|
|
1822
|
+
toolbar.appendChild(mkButton('undo', t('undo'), { disabled: !canUndo(history) }));
|
|
1823
|
+
toolbar.appendChild(mkButton('redo', t('redo'), { disabled: !canRedo(history) }));
|
|
1824
|
+
toolbar.appendChild(mkButton('del', t('del'), { disabled: selected.size === 0 }));
|
|
1825
|
+
toolbar.appendChild(mkButton('connect', t('connect'), { disabled: selectedNodeIds().length !== 1 }));
|
|
1826
|
+
const one = selectedNodeIds().length === 1 && selectedEdgeIds().length === 0;
|
|
1827
|
+
toolbar.appendChild(mkButton('insert-above', t('insertAbove'), { disabled: !one, icon: 'plus' }));
|
|
1828
|
+
toolbar.appendChild(mkButton('move-up', t('moveUp'), { disabled: !one, icon: 'arrow-up' }));
|
|
1829
|
+
toolbar.appendChild(mkButton('move-down', t('moveDown'), { disabled: !one, icon: 'arrow-down' }));
|
|
1830
|
+
if (cfg.layout === 'manual') toolbar.appendChild(mkButton('layout', t('layout'), { disabled: graph.nodes.length === 0 }));
|
|
1831
|
+
}
|
|
1832
|
+
toolbar.appendChild(mkButton('zoom-out', t('zoomOut')));
|
|
1833
|
+
toolbar.appendChild(mkButton('zoom-in', t('zoomIn')));
|
|
1834
|
+
toolbar.appendChild(mkButton('fit', t('fit')));
|
|
1835
|
+
const z = el('span', FLOW_CLASS.zoomLabel, { 'data-flow-zoom': '' });
|
|
1836
|
+
z.textContent = t('zoomLabel', { n: Math.round(view.zoom * 100) });
|
|
1837
|
+
toolbar.appendChild(z);
|
|
1838
|
+
toolbar.appendChild(el('span', FLOW_CLASS.zoomLabel, { 'data-flow-hint': '' })).textContent = t('zoomHint');
|
|
1839
|
+
if (editable()) toolbar.appendChild(mkButton('save', t('save'), { primary: true }));
|
|
1840
|
+
};
|
|
1841
|
+
|
|
1842
|
+
const nodeClass = (sel: boolean, level: Level, ghost: boolean, canMove: boolean): string => {
|
|
1843
|
+
const bg = ghost ? FLOW_NODE_BG.ghost : sel ? FLOW_NODE_BG.selected : FLOW_NODE_BG.normal;
|
|
1844
|
+
const border = ghost ? FLOW_NODE_BORDER.ghost : level === 'error' ? FLOW_NODE_BORDER.error : level === 'warning' ? FLOW_NODE_BORDER.warning : FLOW_NODE_BORDER.normal;
|
|
1845
|
+
return `${FLOW_CLASS.nodeBase} ${bg} ${border} ${canMove ? FLOW_NODE_CURSOR.movable : FLOW_NODE_CURSOR.fixed}`;
|
|
1846
|
+
};
|
|
1847
|
+
|
|
1848
|
+
const statusTone = (status: string): FlowTone | null => {
|
|
1849
|
+
const mapped = cfg.statusTones[status];
|
|
1850
|
+
if (mapped) return mapped;
|
|
1851
|
+
return (['neutral', 'info', 'success', 'warning', 'danger', 'primary'] as const).find((x) => x === status) ?? null;
|
|
1852
|
+
};
|
|
1853
|
+
|
|
1854
|
+
/** 节点 = foreignObject(x、y、宽、高是几何属性)里放一个 HTML 卡片 */
|
|
1855
|
+
const buildNode = (n: FlowNode, at: Pt, opts: { ghost: boolean; issues?: FlowIssue[] }): SVGForeignObjectElement => {
|
|
1856
|
+
const key = keyOfNode(n.id);
|
|
1857
|
+
const def = typeOf(n);
|
|
1858
|
+
const sel = !opts.ghost && selected.has(key);
|
|
1859
|
+
const level = levelOf(opts.issues);
|
|
1860
|
+
const fo = svg('foreignObject', FLOW_CLASS.fo);
|
|
1861
|
+
place(fo, at, FLOW_GEOMETRY.nodeW, FLOW_GEOMETRY.nodeH);
|
|
1862
|
+
const node = el('div', nodeClass(sel, level, opts.ghost, movable() && !opts.ghost));
|
|
1863
|
+
fo.appendChild(node);
|
|
1864
|
+
const worstIssue = worst(opts.issues);
|
|
1865
|
+
if (opts.ghost) {
|
|
1866
|
+
node.setAttribute('data-flow-ghost', '');
|
|
1867
|
+
node.setAttribute('role', 'img');
|
|
1868
|
+
node.setAttribute('aria-label', `${t('suggestion', { label: n.label })}`);
|
|
1869
|
+
} else {
|
|
1870
|
+
node.setAttribute('data-flow-key', key);
|
|
1871
|
+
node.setAttribute('role', 'article');
|
|
1872
|
+
node.tabIndex = 0;
|
|
1873
|
+
if (sel) node.setAttribute('data-flow-selected', '');
|
|
1874
|
+
const lv = worstIssue ? `,${worstIssue.level === 'error' ? t('levelError') : t('levelWarning')}:${worstIssue.message}` : '';
|
|
1875
|
+
node.setAttribute('aria-label', `${t('nodeAria', { type: def?.label ?? n.type, label: n.label })}${lv}`);
|
|
1876
|
+
}
|
|
1877
|
+
const head = el('div', FLOW_CLASS.head);
|
|
1878
|
+
if (def?.icon) { const i = el('span', FLOW_CLASS.icon, { 'aria-hidden': 'true' }); i.textContent = def.icon; head.appendChild(i); }
|
|
1879
|
+
const ord = opts.ghost ? undefined : ordinals.get(n.id);
|
|
1880
|
+
if (ord !== undefined) { const o = el('span', FLOW_CLASS.line, { 'data-flow-ordinal': '' }); o.textContent = ord; head.appendChild(o); }
|
|
1881
|
+
const label = el('span', FLOW_CLASS.label);
|
|
1882
|
+
label.textContent = n.label;
|
|
1883
|
+
head.appendChild(label);
|
|
1884
|
+
const tone = n.status !== undefined ? statusTone(n.status) : null;
|
|
1885
|
+
if (tone) head.appendChild(el('span', FLOW_TONE_DOT[tone], { 'aria-hidden': 'true' }));
|
|
1886
|
+
if (!opts.ghost) {
|
|
1887
|
+
const cb = el('button', FLOW_CLASS.cfgBtn, { type: 'button', tabindex: '-1', 'data-flow-act': `cfg:${n.id}`, 'aria-label': `${t('config')} ${n.label}` });
|
|
1888
|
+
cb.textContent = '⚙';
|
|
1889
|
+
head.appendChild(cb);
|
|
1890
|
+
}
|
|
1891
|
+
node.appendChild(head);
|
|
1892
|
+
|
|
1893
|
+
const body = el('div', FLOW_CLASS.body);
|
|
1894
|
+
const meta = el('div', FLOW_CLASS.head);
|
|
1895
|
+
if (def) {
|
|
1896
|
+
const badge = el('span', FLOW_TONE_BADGE[def.tone]);
|
|
1897
|
+
badge.textContent = def.label;
|
|
1898
|
+
meta.appendChild(badge);
|
|
1899
|
+
}
|
|
1900
|
+
body.appendChild(meta);
|
|
1901
|
+
let lines = 0;
|
|
1902
|
+
if (worstIssue) {
|
|
1903
|
+
const l = el('span', worstIssue.level === 'error' ? FLOW_CLASS.lineError : FLOW_CLASS.lineWarning);
|
|
1904
|
+
l.textContent = worstIssue.message;
|
|
1905
|
+
body.appendChild(l);
|
|
1906
|
+
lines += 1;
|
|
1907
|
+
}
|
|
1908
|
+
for (const f of def?.fields ?? []) {
|
|
1909
|
+
if (lines >= 1 + (worstIssue ? 0 : 1)) break;
|
|
1910
|
+
if (f.kind === 'mapping') continue;
|
|
1911
|
+
const v = n.meta?.[f.key];
|
|
1912
|
+
if (v === undefined || v === null || v === '') continue;
|
|
1913
|
+
const l = el('span', FLOW_CLASS.line);
|
|
1914
|
+
l.textContent = `${f.label}:${typeof v === 'object' ? '…' : String(v)}`;
|
|
1915
|
+
body.appendChild(l);
|
|
1916
|
+
lines += 1;
|
|
1917
|
+
}
|
|
1918
|
+
node.appendChild(body);
|
|
1919
|
+
|
|
1920
|
+
if (!opts.ghost) {
|
|
1921
|
+
node.appendChild(el('span', FLOW_CLASS.inPort, { 'aria-hidden': 'true' }));
|
|
1922
|
+
if (editable()) {
|
|
1923
|
+
const port = el('button', FLOW_CLASS.outPort, { type: 'button', tabindex: '-1', 'data-flow-port': n.id, 'aria-label': t('port', { label: n.label }) });
|
|
1924
|
+
node.appendChild(port);
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
return fo;
|
|
1928
|
+
};
|
|
1929
|
+
|
|
1930
|
+
const markerId = (kind: string): string => `${uid}-arrow-${kind}`;
|
|
1931
|
+
|
|
1932
|
+
const paintEdges = (): void => {
|
|
1933
|
+
svgLayer.textContent = '';
|
|
1934
|
+
const defs = svg('defs');
|
|
1935
|
+
for (const kind of Object.keys(FLOW_MARKER_FILL) as Array<keyof typeof FLOW_MARKER_FILL>) {
|
|
1936
|
+
const m = svg('marker', '', { id: markerId(kind), markerWidth: '8', markerHeight: '8', refX: '7', refY: '4', orient: 'auto', markerUnits: 'userSpaceOnUse' });
|
|
1937
|
+
m.appendChild(svg('path', FLOW_MARKER_FILL[kind], { d: 'M0 0 L8 4 L0 8 z' }));
|
|
1938
|
+
defs.appendChild(m);
|
|
1939
|
+
}
|
|
1940
|
+
svgLayer.appendChild(defs);
|
|
1941
|
+
const issues = issueIndex();
|
|
1942
|
+
const draw = (e: FlowEdge, ghost: boolean): void => {
|
|
1943
|
+
let labelText: SVGTextElement | null = null;
|
|
1944
|
+
const a = posOf(e.from);
|
|
1945
|
+
const b = posOf(e.to);
|
|
1946
|
+
if (!a || !b) return;
|
|
1947
|
+
const key = keyOfEdge(e.id);
|
|
1948
|
+
const geo = edgeGeometry(a, b);
|
|
1949
|
+
const sel = !ghost && selected.has(key);
|
|
1950
|
+
const level = levelOf(issues.get(key));
|
|
1951
|
+
const kind = ghost ? 'ghost' : sel ? 'selected' : level === 'error' ? 'error' : level === 'warning' ? 'warning' : 'normal';
|
|
1952
|
+
const g = svg('g', FLOW_CLASS.edgeG);
|
|
1953
|
+
if (ghost) {
|
|
1954
|
+
g.setAttribute('aria-hidden', 'true');
|
|
1955
|
+
} else {
|
|
1956
|
+
const w = worst(issues.get(key));
|
|
1957
|
+
const base = t('edgeAria', { from: labelOf(e.from), to: labelOf(e.to) });
|
|
1958
|
+
g.setAttribute('data-flow-key', key);
|
|
1959
|
+
g.setAttribute('role', 'button');
|
|
1960
|
+
g.setAttribute('tabindex', '0');
|
|
1961
|
+
g.setAttribute('aria-pressed', sel ? 'true' : 'false');
|
|
1962
|
+
g.setAttribute('aria-label', `${base}${e.label ? `(${e.label})` : ''}${w ? `,${w.level === 'error' ? t('levelError') : t('levelWarning')}:${w.message}` : ''}`);
|
|
1963
|
+
if (w) {
|
|
1964
|
+
const tip = svg('title');
|
|
1965
|
+
tip.textContent = w.message;
|
|
1966
|
+
g.appendChild(tip);
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
g.appendChild(svg('path', FLOW_CLASS.edgeHit, { d: geo.d }));
|
|
1970
|
+
const vis = svg('path', FLOW_EDGE_VIS[kind], { d: geo.d, 'marker-end': `url(#${markerId(kind)})` });
|
|
1971
|
+
if (ghost) vis.setAttribute('stroke-dasharray', '6 4');
|
|
1972
|
+
g.appendChild(vis);
|
|
1973
|
+
pathLayer.appendChild(g);
|
|
1974
|
+
if (e.label) {
|
|
1975
|
+
// 标签层统一在全部连线之上;带同一边 key,点击 / 悬停仍命中对应边
|
|
1976
|
+
const lg = svg('g', FLOW_CLASS.edgeG);
|
|
1977
|
+
lg.setAttribute('aria-hidden', 'true');
|
|
1978
|
+
lg.setAttribute('data-flow-label', '');
|
|
1979
|
+
if (!ghost) lg.setAttribute('data-flow-key', key);
|
|
1980
|
+
const text = svg('text', FLOW_CLASS.edgeLabel, { x: String(geo.mid.x), y: String(geo.mid.y), 'text-anchor': 'middle', 'dominant-baseline': 'central' });
|
|
1981
|
+
text.textContent = e.label;
|
|
1982
|
+
lg.appendChild(text);
|
|
1983
|
+
labelLayer.appendChild(lg);
|
|
1984
|
+
labelText = text;
|
|
1985
|
+
// 标签白底衬垫:量出外框后垫一块带内边距的圆角底;量不出(未布局、宽高为 0)按字数估算
|
|
1986
|
+
let bx = geo.mid.x - (e.label.length * FLOW_LABEL_FONT) / 2;
|
|
1987
|
+
let by = geo.mid.y - FLOW_LABEL_FONT / 2;
|
|
1988
|
+
let bw = e.label.length * FLOW_LABEL_FONT;
|
|
1989
|
+
let bh = FLOW_LABEL_FONT;
|
|
1990
|
+
try {
|
|
1991
|
+
const bb = labelText.getBBox();
|
|
1992
|
+
if (bb.width > 0 && bb.height > 0) { bx = bb.x; by = bb.y; bw = bb.width; bh = bb.height; }
|
|
1993
|
+
} catch { /* 无布局环境:用估算 */ }
|
|
1994
|
+
lg.insertBefore(svg('rect', FLOW_CLASS.edgeLabelBg, {
|
|
1995
|
+
x: String(bx - FLOW_LABEL_PAD_X), y: String(by - FLOW_LABEL_PAD_Y), width: String(bw + FLOW_LABEL_PAD_X * 2), height: String(bh + FLOW_LABEL_PAD_Y * 2), rx: '4',
|
|
1996
|
+
}), text);
|
|
1997
|
+
}
|
|
1998
|
+
};
|
|
1999
|
+
const pathLayer = svg('g');
|
|
2000
|
+
const labelLayer = svg('g');
|
|
2001
|
+
svgLayer.appendChild(pathLayer);
|
|
2002
|
+
svgLayer.appendChild(labelLayer);
|
|
2003
|
+
for (const e of graph.edges) draw(e, false);
|
|
2004
|
+
for (const e of ghostsOf().edges) draw(e, true);
|
|
2005
|
+
};
|
|
2006
|
+
|
|
2007
|
+
const paintNodes = (issues: Map<string, FlowIssue[]>): void => {
|
|
2008
|
+
for (const fn of dndCleanups) fn();
|
|
2009
|
+
dndCleanups = [];
|
|
2010
|
+
dragFrom = null; // 注销后源的 onDragEnd 可能不再触发
|
|
2011
|
+
nodesLayer.textContent = '';
|
|
2012
|
+
ordinals = ordinalsOf(graph, cfg.nodeTypes);
|
|
2013
|
+
const port = dndPort();
|
|
2014
|
+
const valid = (from: string, to: string): boolean => canConnect(graph, cfg.nodeTypes, from, to, cfg.allowCycles).ok;
|
|
2015
|
+
for (const n of graph.nodes) {
|
|
2016
|
+
const at = posOf(n.id) ?? { x: 0, y: 0 };
|
|
2017
|
+
const fo = buildNode(n, at, { ghost: false, issues: issues.get(keyOfNode(n.id)) });
|
|
2018
|
+
const node = fo.firstElementChild as HTMLElement;
|
|
2019
|
+
if (connectFrom !== null && connectFrom !== n.id && valid(connectFrom, n.id)) node.classList.add(...HL);
|
|
2020
|
+
nodesLayer.appendChild(fo);
|
|
2021
|
+
const handle = node.querySelector<HTMLElement>('[data-flow-port]');
|
|
2022
|
+
if (port && handle) {
|
|
2023
|
+
try {
|
|
2024
|
+
dndCleanups.push(port.draggable(handle, {
|
|
2025
|
+
id: `${uid}|out|${n.id}`,
|
|
2026
|
+
data: () => ({ flowFrom: n.id }),
|
|
2027
|
+
canDrag: () => editable(),
|
|
2028
|
+
onDragStart: () => { dragFrom = n.id; markTargets(n.id); },
|
|
2029
|
+
onDragEnd: () => { dragFrom = null; markTargets(null); },
|
|
2030
|
+
}));
|
|
2031
|
+
dndCleanups.push(port.dropTarget(node, {
|
|
2032
|
+
id: `${uid}|in|${n.id}`,
|
|
2033
|
+
canDrop: (src) => fromOf(src) !== null,
|
|
2034
|
+
onOver: () => { if (dragFrom !== null && valid(dragFrom, n.id)) node.classList.add(...HL); },
|
|
2035
|
+
onLeave: () => { if (dragFrom === null || !valid(dragFrom, n.id)) node.classList.remove(...HL); },
|
|
2036
|
+
}));
|
|
2037
|
+
} catch {
|
|
2038
|
+
// 端口规格校验失败(重复登记等):退化为点击连线
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
const gh = ghostsOf();
|
|
2043
|
+
for (const n of gh.nodes) nodesLayer.appendChild(buildNode(n, ghostPosCache.get(n.id) ?? { x: 0, y: 0 }, { ghost: true }));
|
|
2044
|
+
for (const s of visibleSuggestions()) {
|
|
2045
|
+
const first = gh.nodes.find((n) => n.sid === s.id);
|
|
2046
|
+
const anchor = first ? ghostPosCache.get(first.id) : undefined;
|
|
2047
|
+
const firstEdge = gh.edges.find((e) => e.sid === s.id);
|
|
2048
|
+
const mid = firstEdge && posOf(firstEdge.from) && posOf(firstEdge.to) ? edgeGeometry(posOf(firstEdge.from)!, posOf(firstEdge.to)!).mid : undefined;
|
|
2049
|
+
const at = anchor ? { x: anchor.x, y: anchor.y + FLOW_GEOMETRY.nodeH + 4 } : mid;
|
|
2050
|
+
if (!at) continue;
|
|
2051
|
+
const barFo = svg('foreignObject', FLOW_CLASS.fo);
|
|
2052
|
+
place(barFo, at, FLOW_GEOMETRY.barW, FLOW_GEOMETRY.barH);
|
|
2053
|
+
const bar = el('div', FLOW_CLASS.bar, { role: 'group', 'data-flow-bar': s.id, 'aria-label': t('suggestion', { label: s.label }) });
|
|
2054
|
+
barFo.appendChild(bar);
|
|
2055
|
+
const cap = el('span', FLOW_CLASS.barCap);
|
|
2056
|
+
cap.textContent = s.reason === '' ? s.label : `${s.label}:${s.reason}`;
|
|
2057
|
+
bar.appendChild(cap);
|
|
2058
|
+
if (editable()) {
|
|
2059
|
+
bar.appendChild(mkButton(`accept:${s.id}`, t('accept'), { primary: true }));
|
|
2060
|
+
bar.appendChild(mkButton(`reject:${s.id}`, t('reject')));
|
|
2061
|
+
}
|
|
2062
|
+
nodesLayer.appendChild(barFo);
|
|
2063
|
+
}
|
|
2064
|
+
};
|
|
2065
|
+
|
|
2066
|
+
const markTargets = (from: string | null): void => {
|
|
2067
|
+
for (const e of nodesLayer.querySelectorAll<HTMLElement>('[data-flow-key^="n:"]')) {
|
|
2068
|
+
const id = (e.getAttribute('data-flow-key') ?? '').slice(2);
|
|
2069
|
+
const ok = from !== null && id !== from && canConnect(graph, cfg.nodeTypes, from, id, cfg.allowCycles).ok;
|
|
2070
|
+
if (ok) e.classList.add(...HL); else e.classList.remove(...HL);
|
|
2071
|
+
}
|
|
2072
|
+
};
|
|
2073
|
+
|
|
2074
|
+
const fromOf = (sourceId: string): string | null => {
|
|
2075
|
+
const prefix = `${uid}|out|`;
|
|
2076
|
+
return sourceId.startsWith(prefix) ? sourceId.slice(prefix.length) : null;
|
|
2077
|
+
};
|
|
2078
|
+
|
|
2079
|
+
function paint(): void {
|
|
2080
|
+
if (!root) return;
|
|
2081
|
+
const token = focusToken();
|
|
2082
|
+
const p = P();
|
|
2083
|
+
root.className = joinClass(FLOW_CLASS.root, p.class);
|
|
2084
|
+
posCache = computePositions();
|
|
2085
|
+
const gh = ghostsOf();
|
|
2086
|
+
ghostPosCache = placeGhosts(posCache, gh.nodes, gh.edges);
|
|
2087
|
+
const issues = issueIndex();
|
|
2088
|
+
paintToolbar();
|
|
2089
|
+
paintNodes(issues);
|
|
2090
|
+
paintEdges();
|
|
2091
|
+
paintPanel();
|
|
2092
|
+
|
|
2093
|
+
const errText = str(p.error);
|
|
2094
|
+
errorOuter.className = errText === '' ? FLOW_CLASS.hidden : '';
|
|
2095
|
+
errorInner.textContent = errText;
|
|
2096
|
+
const empty = graph.nodes.length === 0 && gh.nodes.length === 0;
|
|
2097
|
+
emptyOuter.className = empty ? '' : FLOW_CLASS.hidden;
|
|
2098
|
+
emptyInner.textContent = bool(p.loading) ? t('loading') : cfg.readonly ? t('emptyReadonly') : t('empty');
|
|
2099
|
+
|
|
2100
|
+
if (needFit && graph.nodes.length > 0 && stage.clientWidth > 0) fit();
|
|
2101
|
+
applyView();
|
|
2102
|
+
|
|
2103
|
+
const errors = [...issues.values()].flat().filter((i) => i.level === 'error').length;
|
|
2104
|
+
const warns = [...issues.values()].flat().filter((i) => i.level === 'warning').length;
|
|
2105
|
+
const parts = [t('summary', { nodes: graph.nodes.length, edges: graph.edges.length })];
|
|
2106
|
+
if (errors > 0) parts.push(t('errors', { n: errors }));
|
|
2107
|
+
if (warns > 0) parts.push(t('warnings', { n: warns }));
|
|
2108
|
+
statusEl.textContent = flash !== '' ? flash : bool(p.loading) ? t('loading') : parts.join(' · ');
|
|
2109
|
+
|
|
2110
|
+
if (token) {
|
|
2111
|
+
const target = findByAttr(token.name, token.value);
|
|
2112
|
+
if (target) (target as unknown as { focus?: () => void }).focus?.();
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
// ---- 数据同步
|
|
2117
|
+
const sync = (first: boolean): void => {
|
|
2118
|
+
const p = P();
|
|
2119
|
+
cfg = configOf(p, root);
|
|
2120
|
+
// GB4 作表单字段控件(表单给了字段名 name):图来自 value(草稿里的值),否则来自 data
|
|
2121
|
+
const data = graphOf(typeof p.name === 'string' && p.name !== '' ? p.value : p.data);
|
|
2122
|
+
if (root && typeof p.id === 'string' && p.id !== '') root.id = p.id;
|
|
2123
|
+
const dsig = graphSig(data);
|
|
2124
|
+
if (first || (dsig !== lastDataSig && dsig !== graphSig(graph))) {
|
|
2125
|
+
// 节点集合不变(宿主只回灌了规整后的 meta)时保持视口,不重新适应画布
|
|
2126
|
+
const sameIds = !first && graph.nodes.length === data.nodes.length && graph.nodes.every((n, i) => n.id === data.nodes[i]?.id);
|
|
2127
|
+
graph = data;
|
|
2128
|
+
history = emptyHistory();
|
|
2129
|
+
if (!sameIds) needFit = true;
|
|
2130
|
+
pruneSelection();
|
|
2131
|
+
}
|
|
2132
|
+
lastDataSig = dsig;
|
|
2133
|
+
external = (pickOf(p, 'validation') !== undefined ? issuesOf(pickOf(p, 'validation')) : []);
|
|
2134
|
+
bindAdopt(p);
|
|
2135
|
+
deriveSuggestions(p);
|
|
2136
|
+
};
|
|
2137
|
+
|
|
2138
|
+
// 建议 = 显式 suggestions + adopt 来自请求结果的;集合变了「忽略」重置
|
|
2139
|
+
const deriveSuggestions = (p: Record<string, unknown>): void => {
|
|
2140
|
+
suggestions = [...suggestionsOf(pickOf(p, 'suggestions')), ...adoptSug];
|
|
2141
|
+
const sig = JSON.stringify(suggestions.map((s) => s.id));
|
|
2142
|
+
if (sig !== sugSig) { sugSig = sig; rejected = new Set(); }
|
|
2143
|
+
};
|
|
2144
|
+
|
|
2145
|
+
// adopt.from 变了才重订;订阅当下的那次回调只取值不重绘(sync 随后会 paint)
|
|
2146
|
+
const bindAdopt = (p: Record<string, unknown>): void => {
|
|
2147
|
+
const decl = rec(p.adopt);
|
|
2148
|
+
adoptPath = str(decl.path);
|
|
2149
|
+
adoptLabel = str(decl.label) !== '' ? str(decl.label) : kitText('soma.kit.flow_adopt_label', undefined, root);
|
|
2150
|
+
const from = str(decl.from);
|
|
2151
|
+
if (from === adoptFrom) return;
|
|
2152
|
+
adoptOff?.();
|
|
2153
|
+
adoptOff = null;
|
|
2154
|
+
adoptFrom = from;
|
|
2155
|
+
adoptSug = [];
|
|
2156
|
+
if (from === '') return;
|
|
2157
|
+
let subscribing = true;
|
|
2158
|
+
adoptOff = watchKitOutcome((ctx.services as { data?: SomaDataPort } | undefined)?.data, from, (o) => {
|
|
2159
|
+
adoptSug = o.status === 'saved' ? adoptSuggestionsOf(o.data, adoptPath, o.seq, adoptLabel) : [];
|
|
2160
|
+
flash = o.status === 'saved' && adoptSug.length === 0 ? kitText('soma.kit.flow_adopt_none', undefined, root) : '';
|
|
2161
|
+
if (subscribing) return;
|
|
2162
|
+
deriveSuggestions(P());
|
|
2163
|
+
paint();
|
|
2164
|
+
});
|
|
2165
|
+
subscribing = false;
|
|
2166
|
+
};
|
|
2167
|
+
|
|
2168
|
+
// ---- 指针
|
|
2169
|
+
const stagePoint = (e: PointerEvent | MouseEvent | WheelEvent): Pt => {
|
|
2170
|
+
const r = stage.getBoundingClientRect();
|
|
2171
|
+
return { x: e.clientX - r.left, y: e.clientY - r.top };
|
|
2172
|
+
};
|
|
2173
|
+
|
|
2174
|
+
const closeMenu = (): void => {
|
|
2175
|
+
if (!menuOpen) return;
|
|
2176
|
+
menuOpen = false;
|
|
2177
|
+
setCls(menuOuter, FLOW_CLASS.hidden);
|
|
2178
|
+
menuInner.textContent = '';
|
|
2179
|
+
};
|
|
2180
|
+
|
|
2181
|
+
const openMenu = (key: string, at: Pt): void => {
|
|
2182
|
+
menuInner.textContent = '';
|
|
2183
|
+
menuInner.setAttribute('aria-label', t('menu'));
|
|
2184
|
+
const id = key.slice(2);
|
|
2185
|
+
const items: Array<[string, string, boolean]> = [];
|
|
2186
|
+
if (key.startsWith('n:')) {
|
|
2187
|
+
items.push([`menu-config:${id}`, t('config'), false]);
|
|
2188
|
+
if (editable()) {
|
|
2189
|
+
items.push([`menu-connect:${id}`, t('connect'), false]);
|
|
2190
|
+
items.push([`menu-insert:${id}`, t('insertAbove'), false]);
|
|
2191
|
+
items.push([`menu-up:${id}`, t('moveUp'), false]);
|
|
2192
|
+
items.push([`menu-down:${id}`, t('moveDown'), false]);
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
if (editable()) items.push([`menu-del:${key}`, t('del'), true]);
|
|
2196
|
+
if (items.length === 0) return;
|
|
2197
|
+
for (const [act, text, danger] of items) {
|
|
2198
|
+
const b = el('button', danger ? FLOW_CLASS.menuItemDanger : FLOW_CLASS.menuItem, { type: 'button', role: 'menuitem', 'data-flow-act': act });
|
|
2199
|
+
b.textContent = text;
|
|
2200
|
+
menuInner.appendChild(b);
|
|
2201
|
+
}
|
|
2202
|
+
place(menuFo, at, FLOW_GEOMETRY.menuW, items.length * FLOW_GEOMETRY.menuItemH + 12);
|
|
2203
|
+
setCls(menuOuter, '');
|
|
2204
|
+
menuOpen = true;
|
|
2205
|
+
menuInner.querySelector<HTMLElement>('button')?.focus();
|
|
2206
|
+
};
|
|
2207
|
+
|
|
2208
|
+
const showMarquee = (a: Pt, b: Pt): void => {
|
|
2209
|
+
const r = normRect(a, b);
|
|
2210
|
+
place(marqueeRect, { x: r.x, y: r.y }, r.w, r.h);
|
|
2211
|
+
setCls(marqueeOuter, '');
|
|
2212
|
+
};
|
|
2213
|
+
|
|
2214
|
+
const onPointerDown = (e: PointerEvent): void => {
|
|
2215
|
+
if (e.button !== 0) return;
|
|
2216
|
+
const target = e.target as Element | null;
|
|
2217
|
+
if (!target) return;
|
|
2218
|
+
if (menuOpen && !target.closest('[data-flow-act^="menu-"]')) closeMenu();
|
|
2219
|
+
if (target.closest('[data-flow-act],[data-flow-port]')) return;
|
|
2220
|
+
const additive = e.shiftKey || e.ctrlKey || e.metaKey;
|
|
2221
|
+
const nodeEl = target.closest('[data-flow-key^="n:"]');
|
|
2222
|
+
const p = stagePoint(e);
|
|
2223
|
+
if (nodeEl) {
|
|
2224
|
+
const key = nodeEl.getAttribute('data-flow-key') ?? '';
|
|
2225
|
+
press = { kind: 'node', key, sx: e.clientX, sy: e.clientY, moved: false, additive, origin: null };
|
|
2226
|
+
} else if (target.closest('[data-flow-key^="e:"],[data-flow-bar],[data-flow-ghost]')) {
|
|
2227
|
+
return;
|
|
2228
|
+
} else if (e.shiftKey) {
|
|
2229
|
+
press = { kind: 'marquee', sx: e.clientX, sy: e.clientY, moved: false, ax: p.x, ay: p.y };
|
|
2230
|
+
} else {
|
|
2231
|
+
press = { kind: 'pan', sx: e.clientX, sy: e.clientY, moved: false, start: { ...view }, additive };
|
|
2232
|
+
}
|
|
2233
|
+
};
|
|
2234
|
+
|
|
2235
|
+
const onPointerMove = (e: PointerEvent): void => {
|
|
2236
|
+
if (!press) return;
|
|
2237
|
+
// 按键已在画布外松开(未捕获指针时收不到 up):当作取消,避免无按键的“拖动”
|
|
2238
|
+
if (e.buttons === 0) { press = null; dragPos = null; setCls(marqueeOuter, FLOW_CLASS.hidden); return; }
|
|
2239
|
+
const dx = e.clientX - press.sx;
|
|
2240
|
+
const dy = e.clientY - press.sy;
|
|
2241
|
+
if (!press.moved && Math.hypot(dx, dy) < FLOW_GEOMETRY.dragThreshold) return;
|
|
2242
|
+
if (!press.moved) {
|
|
2243
|
+
// 越过拖动阈值才捕获指针:单击 / 双击的目标保持为节点本身(捕获会把 click、dblclick 改投给画布)
|
|
2244
|
+
try { stage.setPointerCapture?.(e.pointerId); } catch { /* 不支持捕获的环境 */ }
|
|
2245
|
+
}
|
|
2246
|
+
press.moved = true;
|
|
2247
|
+
if (press.kind === 'pan') {
|
|
2248
|
+
view = { ...press.start, panX: press.start.panX + dx, panY: press.start.panY + dy };
|
|
2249
|
+
needFit = false;
|
|
2250
|
+
applyView();
|
|
2251
|
+
} else if (press.kind === 'marquee') {
|
|
2252
|
+
showMarquee({ x: press.ax, y: press.ay }, stagePoint(e));
|
|
2253
|
+
} else if (press.kind === 'node' && movable() && connectFrom === null) {
|
|
2254
|
+
if (press.origin === null) {
|
|
2255
|
+
if (!selected.has(press.key)) setSelection(press.additive ? [...selected, press.key] : [press.key], press.key);
|
|
2256
|
+
press.origin = new Map();
|
|
2257
|
+
for (const id of selectedNodeIds()) { const at = posCache.get(id); if (at) press.origin.set(id, at); }
|
|
2258
|
+
}
|
|
2259
|
+
const next = new Map<string, Pt>();
|
|
2260
|
+
for (const [id, at] of press.origin) {
|
|
2261
|
+
next.set(id, { x: snap(at.x + dx / view.zoom), y: snap(at.y + dy / view.zoom) });
|
|
2262
|
+
}
|
|
2263
|
+
dragPos = next;
|
|
2264
|
+
for (const [id, at] of next) {
|
|
2265
|
+
const ne = findByAttr('data-flow-key', keyOfNode(id));
|
|
2266
|
+
const fo = ne?.parentElement;
|
|
2267
|
+
if (fo) { fo.setAttribute('x', String(at.x)); fo.setAttribute('y', String(at.y)); }
|
|
2268
|
+
}
|
|
2269
|
+
paintEdges();
|
|
2270
|
+
}
|
|
2271
|
+
};
|
|
2272
|
+
|
|
2273
|
+
const onPointerUp = (e: PointerEvent): void => {
|
|
2274
|
+
const pr = press;
|
|
2275
|
+
press = null;
|
|
2276
|
+
try { stage.releasePointerCapture?.(e.pointerId); } catch { /* 同上 */ }
|
|
2277
|
+
if (!pr) return;
|
|
2278
|
+
flash = '';
|
|
2279
|
+
if (pr.kind === 'pan') {
|
|
2280
|
+
if (!pr.moved && !pr.additive && selected.size > 0) { setSelection([]); paint(); }
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
if (pr.kind === 'marquee') {
|
|
2284
|
+
setCls(marqueeOuter, FLOW_CLASS.hidden);
|
|
2285
|
+
if (!pr.moved) return;
|
|
2286
|
+
const a = screenToWorld(view, pr.ax, pr.ay);
|
|
2287
|
+
const b = screenToWorld(view, stagePoint(e).x, stagePoint(e).y);
|
|
2288
|
+
const hits = marqueeHits(normRect(a, b), [...posCache].map(([id, at]) => ({ id, at })));
|
|
2289
|
+
setSelection(hits.map(keyOfNode));
|
|
2290
|
+
paint();
|
|
2291
|
+
return;
|
|
2292
|
+
}
|
|
2293
|
+
// 节点
|
|
2294
|
+
if (pr.moved && dragPos !== null && movable()) {
|
|
2295
|
+
const moved = dragPos;
|
|
2296
|
+
dragPos = null;
|
|
2297
|
+
commit(withPositions(graph, moved));
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
dragPos = null;
|
|
2301
|
+
const id = pr.key.slice(2);
|
|
2302
|
+
if (connectFrom !== null) { tryConnect(connectFrom, id); return; }
|
|
2303
|
+
if (pr.additive) {
|
|
2304
|
+
const next = new Set(selected);
|
|
2305
|
+
if (next.has(pr.key)) next.delete(pr.key); else next.add(pr.key);
|
|
2306
|
+
setSelection(next, pr.key);
|
|
2307
|
+
} else {
|
|
2308
|
+
setSelection([pr.key], pr.key);
|
|
2309
|
+
}
|
|
2310
|
+
active = pr.key;
|
|
2311
|
+
paint();
|
|
2312
|
+
};
|
|
2313
|
+
|
|
2314
|
+
const onPointerCancel = (): void => {
|
|
2315
|
+
if (!press) return;
|
|
2316
|
+
press = null;
|
|
2317
|
+
dragPos = null;
|
|
2318
|
+
dragFrom = null;
|
|
2319
|
+
setCls(marqueeOuter, FLOW_CLASS.hidden);
|
|
2320
|
+
paint();
|
|
2321
|
+
};
|
|
2322
|
+
|
|
2323
|
+
const onWheel = (e: WheelEvent): void => {
|
|
2324
|
+
// 只有 Ctrl / ⌘ + 滚轮(触控板双指捏合浏览器也会带 ctrlKey)才缩放并拦截;普通滚轮放行,页面照常滚动
|
|
2325
|
+
if (!(e.ctrlKey || e.metaKey)) return;
|
|
2326
|
+
e.preventDefault();
|
|
2327
|
+
needFit = false;
|
|
2328
|
+
const p = stagePoint(e);
|
|
2329
|
+
view = zoomAt(view, e.deltaY < 0 ? FLOW_GEOMETRY.zoomFactor : 1 / FLOW_GEOMETRY.zoomFactor, p.x, p.y);
|
|
2330
|
+
applyView();
|
|
2331
|
+
updateZoomLabel();
|
|
2332
|
+
};
|
|
2333
|
+
|
|
2334
|
+
const runAct = (act: string): void => {
|
|
2335
|
+
flash = '';
|
|
2336
|
+
const [name, ...rest] = act.split(':');
|
|
2337
|
+
const arg = rest.join(':');
|
|
2338
|
+
switch (name) {
|
|
2339
|
+
case 'add': addNodeOfType(arg); break;
|
|
2340
|
+
case 'undo': doUndo(); break;
|
|
2341
|
+
case 'redo': doRedo(); break;
|
|
2342
|
+
case 'del': deleteSelection(); break;
|
|
2343
|
+
case 'connect': { const ids = selectedNodeIds(); if (ids.length === 1) startConnect(ids[0]!); break; }
|
|
2344
|
+
case 'layout': autoLayout(); break;
|
|
2345
|
+
case 'insert-above': { const ids = selectedNodeIds(); if (ids.length === 1) insertAbove(ids[0]!, nodeById(ids[0]!)?.type ?? ''); break; }
|
|
2346
|
+
case 'move-up': case 'move-down': { const ids = selectedNodeIds(); if (ids.length === 1) moveNode(ids[0]!, name === 'move-up' ? 'up' : 'down'); break; }
|
|
2347
|
+
case 'menu-insert': { closeMenu(); insertAbove(arg, nodeById(arg)?.type ?? ''); break; }
|
|
2348
|
+
case 'menu-up': case 'menu-down': { closeMenu(); moveNode(arg, name === 'menu-up' ? 'up' : 'down'); break; }
|
|
2349
|
+
case 'zoom-in': zoomBy(FLOW_GEOMETRY.zoomFactor); break;
|
|
2350
|
+
case 'zoom-out': zoomBy(1 / FLOW_GEOMETRY.zoomFactor); break;
|
|
2351
|
+
case 'fit': fit(); break;
|
|
2352
|
+
case 'save': ctx.emit('save', payload(graph)); break;
|
|
2353
|
+
case 'cfg': requestConfig(arg); break;
|
|
2354
|
+
case 'accept': accept(arg); break;
|
|
2355
|
+
case 'reject': reject(arg); break;
|
|
2356
|
+
case 'menu-config': closeMenu(); focusKey(keyOfNode(arg)); requestConfig(arg); break;
|
|
2357
|
+
case 'menu-connect': closeMenu(); startConnect(arg); focusKey(keyOfNode(arg)); break;
|
|
2358
|
+
case 'menu-del': {
|
|
2359
|
+
closeMenu();
|
|
2360
|
+
setSelection([arg]);
|
|
2361
|
+
deleteSelection();
|
|
2362
|
+
break;
|
|
2363
|
+
}
|
|
2364
|
+
default: break;
|
|
2365
|
+
}
|
|
2366
|
+
};
|
|
2367
|
+
|
|
2368
|
+
const onClick = (e: MouseEvent): void => {
|
|
2369
|
+
const target = e.target as Element | null;
|
|
2370
|
+
if (!target) return;
|
|
2371
|
+
const act = target.closest('[data-flow-act]')?.getAttribute('data-flow-act');
|
|
2372
|
+
if (act) { runAct(act); return; }
|
|
2373
|
+
const port = target.closest('[data-flow-port]')?.getAttribute('data-flow-port');
|
|
2374
|
+
if (port) { flash = ''; startConnect(port); return; }
|
|
2375
|
+
const edgeKey = target.closest('[data-flow-key^="e:"]')?.getAttribute('data-flow-key');
|
|
2376
|
+
if (edgeKey) {
|
|
2377
|
+
flash = '';
|
|
2378
|
+
const additive = e.shiftKey || e.ctrlKey || e.metaKey;
|
|
2379
|
+
const next = additive ? new Set(selected) : new Set<string>();
|
|
2380
|
+
if (additive && next.has(edgeKey)) next.delete(edgeKey); else next.add(edgeKey);
|
|
2381
|
+
active = edgeKey;
|
|
2382
|
+
setSelection(next, edgeKey);
|
|
2383
|
+
paint();
|
|
2384
|
+
}
|
|
2385
|
+
};
|
|
2386
|
+
|
|
2387
|
+
const onDblClick = (e: MouseEvent): void => {
|
|
2388
|
+
const key = (e.target as Element | null)?.closest('[data-flow-key^="n:"]')?.getAttribute('data-flow-key');
|
|
2389
|
+
if (key) requestConfig(key.slice(2));
|
|
2390
|
+
};
|
|
2391
|
+
|
|
2392
|
+
const onContextMenu = (e: MouseEvent): void => {
|
|
2393
|
+
const key = (e.target as Element | null)?.closest('[data-flow-key]')?.getAttribute('data-flow-key');
|
|
2394
|
+
if (!key) return;
|
|
2395
|
+
e.preventDefault();
|
|
2396
|
+
if (!selected.has(key)) { setSelection([key], key); }
|
|
2397
|
+
active = key;
|
|
2398
|
+
paint();
|
|
2399
|
+
openMenu(key, stagePoint(e));
|
|
2400
|
+
};
|
|
2401
|
+
|
|
2402
|
+
const moveSelection = (dx: number, dy: number, fromKey: string): void => {
|
|
2403
|
+
let ids = selectedNodeIds();
|
|
2404
|
+
if (!selected.has(fromKey)) { ids = [fromKey.slice(2)]; selected = new Set([fromKey]); }
|
|
2405
|
+
const moves = new Map<string, Pt>();
|
|
2406
|
+
for (const id of ids) {
|
|
2407
|
+
const at = posCache.get(id);
|
|
2408
|
+
if (at) moves.set(id, { x: at.x + dx, y: at.y + dy });
|
|
2409
|
+
}
|
|
2410
|
+
commit(withPositions(graph, moves), `mv:${ids.join(',')}`);
|
|
2411
|
+
focusKey(fromKey);
|
|
2412
|
+
};
|
|
2413
|
+
|
|
2414
|
+
const onKeydown = (e: KeyboardEvent): void => {
|
|
2415
|
+
const target = e.target as Element | null;
|
|
2416
|
+
if (!target) return;
|
|
2417
|
+
if (menuOpen && e.key === 'Escape') { closeMenu(); focusKey(active); e.preventDefault(); return; }
|
|
2418
|
+
if (menuOpen && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && target.closest('[data-flow-act^="menu-"]')) {
|
|
2419
|
+
const items = [...menuInner.querySelectorAll<HTMLElement>('button')];
|
|
2420
|
+
const at = items.indexOf(target.closest('button') as HTMLElement);
|
|
2421
|
+
items[(at + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length]?.focus();
|
|
2422
|
+
e.preventDefault();
|
|
2423
|
+
return;
|
|
2424
|
+
}
|
|
2425
|
+
if (target.closest('[data-flow-act],[data-flow-port]') && !target.closest('[data-flow-key]')) return;
|
|
2426
|
+
const itemKey = target.closest('[data-flow-key]')?.getAttribute('data-flow-key') ?? null;
|
|
2427
|
+
if (target !== stage && itemKey === null) return;
|
|
2428
|
+
const mod = e.ctrlKey || e.metaKey;
|
|
2429
|
+
const key = e.key;
|
|
2430
|
+
const handled = (): void => { e.preventDefault(); };
|
|
2431
|
+
|
|
2432
|
+
if (mod && (key === 'z' || key === 'Z')) { handled(); flash = ''; if (e.shiftKey) doRedo(); else doUndo(); return; }
|
|
2433
|
+
if (mod && (key === 'y' || key === 'Y')) { handled(); flash = ''; doRedo(); return; }
|
|
2434
|
+
if (mod && (key === 'a' || key === 'A')) { handled(); setSelection(graph.nodes.map((n) => keyOfNode(n.id))); paint(); return; }
|
|
2435
|
+
if (mod && (key === 's' || key === 'S') && editable()) { handled(); ctx.emit('save', payload(graph)); return; }
|
|
2436
|
+
if (mod) return;
|
|
2437
|
+
if (key === '+' || key === '=') { handled(); zoomBy(FLOW_GEOMETRY.zoomFactor); return; }
|
|
2438
|
+
if (key === '-' || key === '_') { handled(); zoomBy(1 / FLOW_GEOMETRY.zoomFactor); return; }
|
|
2439
|
+
if (key === '0') { handled(); fit(); return; }
|
|
2440
|
+
if (key === 'Escape') {
|
|
2441
|
+
// 没有可取消的东西时不拦截,让外层浮层的 Esc 照常关闭
|
|
2442
|
+
if (connectFrom !== null) { handled(); connectFrom = null; flash = ''; paint(); return; }
|
|
2443
|
+
if (selected.size > 0) { handled(); setSelection([]); paint(); }
|
|
2444
|
+
return;
|
|
2445
|
+
}
|
|
2446
|
+
if (key === 'ContextMenu' || (key === 'F10' && e.shiftKey)) {
|
|
2447
|
+
if (itemKey === null) return;
|
|
2448
|
+
handled();
|
|
2449
|
+
const r = (target.closest('[data-flow-key]') as Element).getBoundingClientRect();
|
|
2450
|
+
const s = stage.getBoundingClientRect();
|
|
2451
|
+
openMenu(itemKey, { x: r.left - s.left + 8, y: r.top - s.top + 8 });
|
|
2452
|
+
return;
|
|
2453
|
+
}
|
|
2454
|
+
if (key === 'Delete' || key === 'Backspace') { if (!editable()) return; handled(); flash = ''; deleteSelection(); return; }
|
|
2455
|
+
|
|
2456
|
+
// Alt+上 / 下:与相邻节点对调先后(键盘可达,菜单与工具栏同一动作)
|
|
2457
|
+
if (e.altKey && (key === 'ArrowUp' || key === 'ArrowDown') && itemKey !== null && itemKey.startsWith('n:')) {
|
|
2458
|
+
handled();
|
|
2459
|
+
if (editable()) { flash = ''; moveNode(itemKey.slice(2), key === 'ArrowUp' ? 'up' : 'down'); }
|
|
2460
|
+
return;
|
|
2461
|
+
}
|
|
2462
|
+
const dir: Dir | null = key === 'ArrowLeft' ? 'left' : key === 'ArrowRight' ? 'right' : key === 'ArrowUp' ? 'up' : key === 'ArrowDown' ? 'down' : null;
|
|
2463
|
+
if (dir !== null) {
|
|
2464
|
+
handled();
|
|
2465
|
+
const step = e.shiftKey ? FLOW_GEOMETRY.bigStep : FLOW_GEOMETRY.step;
|
|
2466
|
+
const dx = dir === 'left' ? -step : dir === 'right' ? step : 0;
|
|
2467
|
+
const dy = dir === 'up' ? -step : dir === 'down' ? step : 0;
|
|
2468
|
+
if (itemKey === null) {
|
|
2469
|
+
// 画布本体:方向键平移
|
|
2470
|
+
view = { ...view, panX: view.panX - dx * 5, panY: view.panY - dy * 5 };
|
|
2471
|
+
needFit = false;
|
|
2472
|
+
applyView();
|
|
2473
|
+
return;
|
|
2474
|
+
}
|
|
2475
|
+
if (itemKey.startsWith('n:')) {
|
|
2476
|
+
if (movable()) { flash = ''; moveSelection(dx, dy, itemKey); return; }
|
|
2477
|
+
const next = neighborInDirection([...posCache].map(([id, at]) => ({ id, at })), itemKey.slice(2), dir);
|
|
2478
|
+
if (next !== null) focusKey(keyOfNode(next));
|
|
2479
|
+
}
|
|
2480
|
+
return;
|
|
2481
|
+
}
|
|
2482
|
+
if (itemKey === null) return;
|
|
2483
|
+
if (key === 'Enter') {
|
|
2484
|
+
handled();
|
|
2485
|
+
flash = '';
|
|
2486
|
+
if (itemKey.startsWith('n:')) {
|
|
2487
|
+
if (connectFrom !== null) { tryConnect(connectFrom, itemKey.slice(2)); return; }
|
|
2488
|
+
setSelection([itemKey], itemKey);
|
|
2489
|
+
paint();
|
|
2490
|
+
requestConfig(itemKey.slice(2));
|
|
2491
|
+
} else {
|
|
2492
|
+
setSelection([itemKey], itemKey);
|
|
2493
|
+
paint();
|
|
2494
|
+
}
|
|
2495
|
+
return;
|
|
2496
|
+
}
|
|
2497
|
+
if (key === ' ') {
|
|
2498
|
+
handled();
|
|
2499
|
+
const next = new Set(selected);
|
|
2500
|
+
if (next.has(itemKey)) next.delete(itemKey); else next.add(itemKey);
|
|
2501
|
+
setSelection(next, itemKey);
|
|
2502
|
+
paint();
|
|
2503
|
+
return;
|
|
2504
|
+
}
|
|
2505
|
+
if ((key === 'c' || key === 'C') && itemKey.startsWith('n:')) { handled(); flash = ''; startConnect(itemKey.slice(2)); return; }
|
|
2506
|
+
if ((key === 'i' || key === 'I') && itemKey.startsWith('n:')) { handled(); flash = ''; insertAbove(itemKey.slice(2), nodeById(itemKey.slice(2))?.type ?? ''); }
|
|
2507
|
+
};
|
|
2508
|
+
|
|
2509
|
+
const onFocusIn = (e: FocusEvent): void => {
|
|
2510
|
+
const k = (e.target as Element | null)?.closest('[data-flow-key]')?.getAttribute('data-flow-key');
|
|
2511
|
+
if (k) active = k;
|
|
2512
|
+
};
|
|
2513
|
+
|
|
2514
|
+
const on = <E extends Event>(target: EventTarget, type: string, fn: (e: E) => void, opts?: AddEventListenerOptions): void => {
|
|
2515
|
+
target.addEventListener(type, fn as EventListener, opts);
|
|
2516
|
+
removers.push(() => target.removeEventListener(type, fn as EventListener, opts));
|
|
2517
|
+
};
|
|
2518
|
+
|
|
2519
|
+
const build = (host: HTMLElement): void => {
|
|
2520
|
+
host.textContent = '';
|
|
2521
|
+
toolbar = el('div', FLOW_CLASS.toolbar, { role: 'toolbar', 'aria-label': t('canvas') });
|
|
2522
|
+
const help = el('p', FLOW_CLASS.srOnly, { id: `${uid}-help` });
|
|
2523
|
+
help.textContent = t('help');
|
|
2524
|
+
stage = el('div', FLOW_CLASS.stage, { tabindex: '0', role: 'group', 'aria-roledescription': t('canvas'), 'aria-label': t('canvas'), 'aria-describedby': `${uid}-help` });
|
|
2525
|
+
// 画布底层:一个满铺 SVG;世界层 <g transform> 承载缩放平移,连线层在下、节点层(foreignObject)在上
|
|
2526
|
+
const canvas = svg('svg', FLOW_CLASS.svgRoot);
|
|
2527
|
+
// 点阵网格:SVG pattern,间距取 FLOW_GEOMETRY.grid(与吸附同一刻度),点半径读 kit-limits;随平移缩放更新 pattern 尺寸与偏移
|
|
2528
|
+
const defs = svg('defs');
|
|
2529
|
+
gridPattern = svg('pattern', '', { id: `${uid}-dots`, patternUnits: 'userSpaceOnUse' });
|
|
2530
|
+
gridDot = svg('circle', FLOW_CLASS.gridDot, { r: String(KIT_DATA_LIMITS.flowEditor.dotRadius) });
|
|
2531
|
+
gridPattern.appendChild(gridDot);
|
|
2532
|
+
defs.appendChild(gridPattern);
|
|
2533
|
+
const gridRect = svg('rect', FLOW_CLASS.gridRect, { fill: `url(#${uid}-dots)` });
|
|
2534
|
+
canvas.append(defs, gridRect);
|
|
2535
|
+
world = svg('g');
|
|
2536
|
+
svgLayer = svg('g');
|
|
2537
|
+
nodesLayer = svg('g');
|
|
2538
|
+
world.append(svgLayer, nodesLayer);
|
|
2539
|
+
canvas.appendChild(world);
|
|
2540
|
+
// 屏幕坐标覆盖层:框选矩形与右键菜单(外层 g 只管显隐,内层管样式)
|
|
2541
|
+
const overlay = svg('svg', FLOW_CLASS.overlaySvg);
|
|
2542
|
+
marqueeOuter = svg('g', FLOW_CLASS.hidden);
|
|
2543
|
+
marqueeRect = svg('rect', FLOW_CLASS.marqueeRect);
|
|
2544
|
+
marqueeOuter.appendChild(marqueeRect);
|
|
2545
|
+
menuOuter = svg('g', FLOW_CLASS.hidden);
|
|
2546
|
+
menuFo = svg('foreignObject', FLOW_CLASS.menuFo);
|
|
2547
|
+
menuInner = el('div', FLOW_CLASS.menuInner, { role: 'menu' });
|
|
2548
|
+
menuFo.appendChild(menuInner);
|
|
2549
|
+
menuOuter.appendChild(menuFo);
|
|
2550
|
+
overlay.append(marqueeOuter, menuOuter);
|
|
2551
|
+
emptyOuter = el('div', '');
|
|
2552
|
+
emptyInner = el('div', FLOW_CLASS.emptyInner, { role: 'status' });
|
|
2553
|
+
emptyOuter.appendChild(emptyInner);
|
|
2554
|
+
stage.append(canvas, overlay, emptyOuter);
|
|
2555
|
+
errorOuter = el('div', FLOW_CLASS.hidden);
|
|
2556
|
+
errorInner = el('div', FLOW_CLASS.errorInner, { role: 'alert' });
|
|
2557
|
+
errorOuter.appendChild(errorInner);
|
|
2558
|
+
statusEl = el('p', FLOW_CLASS.status, { role: 'status', 'aria-live': 'polite' });
|
|
2559
|
+
// 画布 + 右侧配置面板同一行;面板外层只管显隐,内层管样式
|
|
2560
|
+
panelOuter = el('div', FLOW_CLASS.hidden);
|
|
2561
|
+
panelInner = el('div', FLOW_CLASS.panel, { role: 'region' });
|
|
2562
|
+
panelOuter.appendChild(panelInner);
|
|
2563
|
+
panelId = '';
|
|
2564
|
+
panelVals = '';
|
|
2565
|
+
const row = el('div', FLOW_CLASS.row);
|
|
2566
|
+
row.append(stage, panelOuter);
|
|
2567
|
+
host.append(errorOuter, toolbar, help, row, statusEl);
|
|
2568
|
+
};
|
|
2569
|
+
|
|
2570
|
+
return {
|
|
2571
|
+
onMount(): void {
|
|
2572
|
+
root = findRoot(ctx.host);
|
|
2573
|
+
sync(true);
|
|
2574
|
+
build(root);
|
|
2575
|
+
on(stage, 'pointerdown', onPointerDown as (e: Event) => void);
|
|
2576
|
+
on(stage, 'pointermove', onPointerMove as (e: Event) => void);
|
|
2577
|
+
on(stage, 'pointerup', onPointerUp as (e: Event) => void);
|
|
2578
|
+
on(stage, 'pointercancel', onPointerCancel);
|
|
2579
|
+
on(stage, 'wheel', onWheel as (e: Event) => void, { passive: false });
|
|
2580
|
+
on(root, 'pointerdown', ((e: PointerEvent) => {
|
|
2581
|
+
if (menuOpen && !(e.target as Element | null)?.closest('[data-flow-act^="menu-"]')) closeMenu();
|
|
2582
|
+
}) as (e: Event) => void);
|
|
2583
|
+
on(root, 'click', onClick as (e: Event) => void);
|
|
2584
|
+
on(root, 'dblclick', onDblClick as (e: Event) => void);
|
|
2585
|
+
on(root, 'contextmenu', onContextMenu as (e: Event) => void);
|
|
2586
|
+
on(root, 'keydown', onKeydown as (e: Event) => void);
|
|
2587
|
+
on(root, 'focusin', onFocusIn as (e: Event) => void);
|
|
2588
|
+
const port = dndPort();
|
|
2589
|
+
if (port) {
|
|
2590
|
+
offMove = port.onMove((intent) => {
|
|
2591
|
+
const from = fromOf(intent.sourceId);
|
|
2592
|
+
const prefix = `${uid}|in|`;
|
|
2593
|
+
if (from === null || !intent.targetId.startsWith(prefix)) return;
|
|
2594
|
+
flash = '';
|
|
2595
|
+
dragFrom = null;
|
|
2596
|
+
tryConnect(from, intent.targetId.slice(prefix.length));
|
|
2597
|
+
});
|
|
2598
|
+
}
|
|
2599
|
+
paint();
|
|
2600
|
+
},
|
|
2601
|
+
onPropsChange(): void {
|
|
2602
|
+
sync(false);
|
|
2603
|
+
paint();
|
|
2604
|
+
},
|
|
2605
|
+
onUnmount(): void {
|
|
2606
|
+
for (const fn of removers) fn();
|
|
2607
|
+
removers = [];
|
|
2608
|
+
for (const fn of dndCleanups) fn();
|
|
2609
|
+
dndCleanups = [];
|
|
2610
|
+
offMove?.();
|
|
2611
|
+
offMove = null;
|
|
2612
|
+
adoptOff?.();
|
|
2613
|
+
adoptOff = null;
|
|
2614
|
+
adoptFrom = '';
|
|
2615
|
+
adoptSug = [];
|
|
2616
|
+
panelEmbeds.release(panelInner);
|
|
2617
|
+
root = null;
|
|
2618
|
+
},
|
|
2619
|
+
};
|
|
2620
|
+
},
|
|
2621
|
+
};
|
|
2622
|
+
}
|