@conscience-technology/ovenn 0.7.3 → 0.7.5

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.
Files changed (150) hide show
  1. package/assets/components/AIMessage/AIMessage.module.css +10 -0
  2. package/assets/components/AIMessage/AIMessage.tsx +6 -2
  3. package/assets/components/Breadcrumb/Breadcrumb.module.css +82 -23
  4. package/assets/components/Breadcrumb/Breadcrumb.tsx +44 -26
  5. package/assets/components/Breadcrumb/index.ts +1 -0
  6. package/assets/components/Button/Button.module.css +2 -4
  7. package/assets/components/Callout/Callout.module.css +44 -18
  8. package/assets/components/Callout/Callout.tsx +9 -4
  9. package/assets/components/Callout/index.ts +1 -1
  10. package/assets/components/Canvas/Canvas.module.css +13 -0
  11. package/assets/components/Canvas/Canvas.tsx +378 -94
  12. package/assets/components/Canvas/clipboard.ts +5 -1
  13. package/assets/components/Canvas/collision.ts +5 -1
  14. package/assets/components/Canvas/graph.ts +14 -5
  15. package/assets/components/Canvas/history.ts +11 -4
  16. package/assets/components/Canvas/index.ts +2 -1
  17. package/assets/components/Canvas/types.ts +36 -1
  18. package/assets/components/CanvasEdge/tokens.css +14 -1
  19. package/assets/components/CanvasNode/tokens.css +13 -10
  20. package/assets/components/ChatInput/ChatInput.tsx +1 -1
  21. package/assets/components/ColorField/ColorField.module.css +6 -1
  22. package/assets/components/ColorPicker/ColorPicker.module.css +3 -0
  23. package/assets/components/CommandPalette/CommandPalette.module.css +115 -1
  24. package/assets/components/CommandPalette/CommandPalette.tsx +206 -21
  25. package/assets/components/CommandPalette/index.ts +1 -0
  26. package/assets/components/DatePicker/DatePicker.module.css +3 -2
  27. package/assets/components/Drawer/Drawer.module.css +30 -0
  28. package/assets/components/Drawer/Drawer.tsx +75 -16
  29. package/assets/components/Drawer/index.ts +1 -0
  30. package/assets/components/Icon/Icon.tsx +3 -0
  31. package/assets/components/Input/Input.module.css +4 -4
  32. package/assets/components/Select/Select.module.css +6 -2
  33. package/assets/components/SocialLoginButton/SocialLoginButton.module.css +198 -0
  34. package/assets/components/SocialLoginButton/SocialLoginButton.tsx +86 -0
  35. package/assets/components/SocialLoginButton/assets/amazon.svg +1 -0
  36. package/assets/components/SocialLoginButton/assets/apple.svg +3 -0
  37. package/assets/components/SocialLoginButton/assets/discord.svg +3 -0
  38. package/assets/components/SocialLoginButton/assets/facebook-white.png +0 -0
  39. package/assets/components/SocialLoginButton/assets/facebook.png +0 -0
  40. package/assets/components/SocialLoginButton/assets/github.svg +3 -0
  41. package/assets/components/SocialLoginButton/assets/google-mark.png +0 -0
  42. package/assets/components/SocialLoginButton/assets/kakao.svg +3 -0
  43. package/assets/components/SocialLoginButton/assets/line-icon.png +0 -0
  44. package/assets/components/SocialLoginButton/assets/line-white.png +0 -0
  45. package/assets/components/SocialLoginButton/assets/linkedin-white.png +0 -0
  46. package/assets/components/SocialLoginButton/assets/linkedin.png +0 -0
  47. package/assets/components/SocialLoginButton/assets/microsoft.svg +6 -0
  48. package/assets/components/SocialLoginButton/assets/naver.png +0 -0
  49. package/assets/components/SocialLoginButton/assets/slack.svg +17 -0
  50. package/assets/components/SocialLoginButton/assets/spotify.svg +3 -0
  51. package/assets/components/SocialLoginButton/assets/twitch.svg +21 -0
  52. package/assets/components/SocialLoginButton/assets/wechat.png +0 -0
  53. package/assets/components/SocialLoginButton/assets/x.svg +3 -0
  54. package/assets/components/SocialLoginButton/index.ts +2 -0
  55. package/assets/components/SocialLoginButton/provider-tokens.css +30 -0
  56. package/assets/components/SocialLoginButton/providers.ts +23 -0
  57. package/assets/components/TimePicker/TimePicker.module.css +3 -2
  58. package/assets/components/_data.ts +1 -1
  59. package/assets/components/_utils.css +2 -2
  60. package/assets/components/component-registry.json +30 -1
  61. package/assets/components/index.ts +1 -0
  62. package/assets/components/tokens.css +14 -15
  63. package/assets/prompts/ASSEMBLY.md +2 -0
  64. package/assets/prompts/CATALOG.md +1 -0
  65. package/assets/prompts/PRINCIPLES.md +1 -1
  66. package/assets/prompts/RULES.md +31 -0
  67. package/assets/prompts/axes/material.md +4 -4
  68. package/assets/prompts/axes/palette.md +1 -1
  69. package/assets/prompts/axes/shape.md +2 -2
  70. package/assets/prompts/axes/voice.md +2 -2
  71. package/assets/prompts/components/_variants.md +3 -3
  72. package/assets/prompts/components/accordion.md +1 -1
  73. package/assets/prompts/components/ai-message.md +6 -2
  74. package/assets/prompts/components/app-frame.md +2 -2
  75. package/assets/prompts/components/avatar.md +2 -2
  76. package/assets/prompts/components/badge.md +1 -1
  77. package/assets/prompts/components/breadcrumb.md +11 -5
  78. package/assets/prompts/components/button.md +2 -2
  79. package/assets/prompts/components/calendar.md +1 -1
  80. package/assets/prompts/components/callout.md +8 -4
  81. package/assets/prompts/components/canvas-edge.md +1 -1
  82. package/assets/prompts/components/canvas-node.md +2 -2
  83. package/assets/prompts/components/canvas.md +24 -8
  84. package/assets/prompts/components/chart-radial.md +1 -1
  85. package/assets/prompts/components/chart.md +1 -1
  86. package/assets/prompts/components/chat-reactions.md +1 -1
  87. package/assets/prompts/components/checkbox-card.md +3 -3
  88. package/assets/prompts/components/checkbox.md +1 -1
  89. package/assets/prompts/components/chip.md +4 -4
  90. package/assets/prompts/components/code-block.md +1 -1
  91. package/assets/prompts/components/combobox.md +3 -3
  92. package/assets/prompts/components/command-palette.md +52 -44
  93. package/assets/prompts/components/comment.md +2 -2
  94. package/assets/prompts/components/control-group.md +1 -1
  95. package/assets/prompts/components/data-table.md +1 -1
  96. package/assets/prompts/components/disclosure.md +1 -1
  97. package/assets/prompts/components/drawer.md +15 -1
  98. package/assets/prompts/components/dropdown-menu.md +1 -1
  99. package/assets/prompts/components/event-chip.md +2 -2
  100. package/assets/prompts/components/file-icon.md +1 -1
  101. package/assets/prompts/components/file-upload.md +1 -1
  102. package/assets/prompts/components/icon-button.md +1 -1
  103. package/assets/prompts/components/input.md +3 -3
  104. package/assets/prompts/components/list-item.md +1 -1
  105. package/assets/prompts/components/menu-item.md +2 -2
  106. package/assets/prompts/components/metric-card.md +1 -1
  107. package/assets/prompts/components/mini-calendar.md +1 -1
  108. package/assets/prompts/components/page-header.md +1 -1
  109. package/assets/prompts/components/segmented-chart.md +1 -1
  110. package/assets/prompts/components/sidebar.md +3 -3
  111. package/assets/prompts/components/skeleton.md +3 -3
  112. package/assets/prompts/components/social-login-button.md +117 -0
  113. package/assets/prompts/components/tab-strip.md +1 -1
  114. package/assets/prompts/components/table-cell.md +1 -1
  115. package/assets/prompts/components/table-header.md +1 -1
  116. package/assets/prompts/components/table-row-edit.md +3 -3
  117. package/assets/prompts/components/table-row.md +1 -1
  118. package/assets/prompts/components/table-toolbar.md +1 -1
  119. package/assets/prompts/components/timeline-view.md +2 -2
  120. package/assets/prompts/components/toast.md +1 -1
  121. package/assets/prompts/components/tooltip.md +3 -3
  122. package/assets/prompts/components/tree-nav.md +2 -2
  123. package/assets/prompts/design-examples/ai-chat-full-page.png +0 -0
  124. package/assets/prompts/design-examples/catalog.json +9 -9
  125. package/assets/prompts/design-examples/sources/ai-chat-full-page/ChatExperience.module.css +37 -1
  126. package/assets/prompts/design-examples/sources/ai-chat-full-page/ChatExperience.tsx +113 -18
  127. package/assets/prompts/design-examples/sources/ai-chat-full-page/FullPageChat.tsx +2 -2
  128. package/assets/prompts/design-examples/sources/ai-chat-full-page/REFERENCE.md +3 -1
  129. package/assets/prompts/design-examples/sources/ai-chat-full-page/useChatDemo.ts +99 -51
  130. package/assets/prompts/primitives/scroll.md +1 -1
  131. package/assets/prompts/tokens/color.md +4 -5
  132. package/assets/prompts/tokens/material.md +5 -2
  133. package/assets/prompts/tokens/radius.md +1 -1
  134. package/assets/prompts/use-cases/chat-chat-input.md +382 -74
  135. package/assets/prompts/use-cases/data-list-item.md +38 -431
  136. package/assets/prompts/use-cases/feedback-drawer.md +112 -33
  137. package/assets/prompts/use-cases/overlay-command-palette.md +2004 -0
  138. package/assets/prompts/use-cases/structure-canvas.md +1016 -0
  139. package/assets/skills/ovenn-validate/SKILL.md +1 -1
  140. package/assets/skills/ovenn-validate/scripts/lib/component-usage.js +27 -5
  141. package/assets/skills/ovenn-validate/scripts/rules/hard-rules.mjs +174 -0
  142. package/assets/skills/ovenn-validate/scripts/rules/hard-rules.test.mjs +57 -0
  143. package/assets/skills/ovenn-validate/scripts/validate.mjs +2 -0
  144. package/package.json +1 -1
  145. package/src/commands/info.js +5 -4
  146. package/src/commands/update.js +5 -1
  147. package/src/utils/agents.js +28 -17
  148. package/src/utils/client-bridges.js +4 -2
  149. package/src/utils/component-usage.js +27 -5
  150. package/src/utils/patch.js +2 -1
@@ -0,0 +1,1016 @@
1
+ # Canvas 사용 사례 소스
2
+
3
+ <!-- Generated by scripts/build-use-cases.mjs. Edit original TSX/CSS, then regenerate. -->
4
+
5
+ ### 사례 목록
6
+
7
+ - Create a connected block
8
+ - Add steps and branches
9
+
10
+ 문서: /en/components/structure/canvas#use-cases
11
+
12
+ 문서 페이지에서 렌더하는 사례입니다.
13
+
14
+ ### 조회 방법
15
+
16
+ get_guide(topic="use-cases/structure-canvas", sections=["사례 목록", "파일 목록"])로 먼저 확인하고, 필요한 Section 또는 Source 파일 헤딩만 sections로 조회하세요. 전체 문서는 문서 페이지의 다른 예제도 포함합니다. 공용 컴포넌트 계약은 get_component로 읽고, 예제의 docs 전용 셸·locale·import 경로는 대상 프로젝트에 맞게 조합하세요. 이 연결은 디자인 승인이나 기능 검증을 뜻하지 않습니다.
17
+
18
+ ### 파일 목록
19
+
20
+ - `web/app/[lang]/components/structure/canvas/DropExample.tsx`
21
+ - `web/app/[lang]/components/structure/canvas/ExecutionExample.tsx`
22
+ - `web/app/[lang]/components/structure/canvas/GuideAnchor.tsx`
23
+ - `web/app/[lang]/components/structure/canvas/page.module.css`
24
+ - `web/app/[lang]/components/structure/canvas/page.tsx`
25
+ - `web/app/[lang]/components/structure/canvas/WorkflowExample.tsx`
26
+
27
+ ### Section: web/app/[lang]/components/structure/canvas/page.tsx#use-cases
28
+
29
+ ```tsx
30
+ <section id="use-cases">
31
+ <h2>{ko ? "사용 사례" : "Use cases"}</h2>
32
+ <article className={styles.useCase} aria-labelledby="canvas-drop-title">
33
+ <h3 id="canvas-drop-title">{ko ? "빈 공간에서 블록 만들기" : "Create a connected block"}</h3>
34
+ <p className="desc">{ko
35
+ ? "요청 노드에 마우스를 올리거나 탭한 뒤 추가 버튼을 눌러 보세요. 연결점을 빈 공간에 끌어 놓아도 아래쪽에는 작업, 오른쪽에는 알림을 추가할 수 있어요."
36
+ : "Hover over or tap Request to reveal its add buttons. You can also drag a handle into empty space. The bottom handle adds a task and the right handle adds a notification."}</p>
37
+ <ExampleBlock code={dropSample} previewWidth="full">
38
+ <DropExample ko={ko} labels={ko ? korean : undefined} dropMode={dropMode} guideVisibility={guideVisibility} />
39
+ </ExampleBlock>
40
+ </article>
41
+ <article className={styles.useCase} aria-labelledby="canvas-workflow-title">
42
+ <h3 id="canvas-workflow-title">{ko ? "단계와 분기 추가하기" : "Add steps and branches"}</h3>
43
+ <p className="desc">{ko
44
+ ? "노드나 연결선에 마우스를 올리거나 탭해 추가 버튼을 표시하세요. 줄 사이에는 공통 단계를 추가하는 버튼이 하나만 표시돼요. 분기는 같은 줄의 양끝이나 노드 사이에서 추가해요."
45
+ : "Hover over or tap a node or connection to reveal its add buttons. Each gap between rows gets one button for a shared step. Add branches at the ends of a row or between its nodes."}</p>
46
+ <ExampleBlock code={workflowSample} previewWidth="full">
47
+ <WorkflowExample ko={ko} labels={ko ? korean : undefined} guideVisibility={guideVisibility} />
48
+ </ExampleBlock>
49
+ </article>
50
+ </section>
51
+ ```
52
+
53
+ ### Source: web/app/[lang]/components/structure/canvas/DropExample.tsx
54
+
55
+ ````tsx
56
+ "use client";
57
+
58
+ import { useRef, useState } from "react";
59
+ import {
60
+ Canvas, canUseCanvasPort, type CanvasConnection, type CanvasConnectionDropNode, type CanvasConnectionDropRequest,
61
+ type CanvasGraph, type CanvasLabels, type CanvasPort,
62
+ } from "@/components/Canvas";
63
+ import { canvasNodeSelectionIds } from "@/components/Canvas/selection";
64
+ import { Button } from "@/components/Button";
65
+ import { Icon } from "@/components/Icon";
66
+ import { IconButton } from "@/components/IconButton";
67
+ import { Modal } from "@/components/Modal";
68
+ import styles from "./page.module.css";
69
+ import { GuideAnchor, type GuideMode } from "./GuideAnchor";
70
+
71
+ type DropMode = "off" | "auto" | "choose";
72
+ type Kind = "task" | "review" | "notice";
73
+ const options: Record<string, Partial<Record<CanvasPort["side"], readonly Kind[]>>> = {
74
+ request: { bottom: ["task", "review"], right: ["notice"] },
75
+ task: { bottom: ["review"] },
76
+ };
77
+ const icons = { task: "list", review: "check-square", notice: "bell" };
78
+ const sideLabel = { left: "왼쪽", right: "오른쪽", top: "위쪽", bottom: "아래쪽" };
79
+
80
+ function allowedBlocks(source: CanvasPort, graph: CanvasGraph): readonly Kind[] {
81
+ const kind = graph.nodes.find(node => node.id === source.nodeId)?.kind;
82
+ return (kind && options[kind]?.[source.side]) || [];
83
+ }
84
+
85
+ function validExampleConnection(connection: CanvasConnection, graph: CanvasGraph) {
86
+ const kind = graph.nodes.find(node => node.id === connection.target.nodeId)?.kind;
87
+ return kind === "result" ? connection.source.side === "bottom" :
88
+ allowedBlocks(connection.source, graph).some(option => option === kind);
89
+ }
90
+
91
+ export function DropExample({ ko = false, labels, dropMode = "auto", guideVisibility = "hover" }: {
92
+ ko?: boolean;
93
+ labels?: Partial<CanvasLabels>;
94
+ dropMode?: DropMode;
95
+ guideVisibility?: GuideMode | "hidden";
96
+ }) {
97
+ const names = ko ? { task: "작업", review: "검토", notice: "알림" } : { task: "Task", review: "Review", notice: "Notification" };
98
+ const [graph, setGraph] = useState<CanvasGraph>(() => ({
99
+ nodes: [
100
+ { id: "request", kind: "request", title: ko ? "요청" : "Request", shape: "tile", media: <Icon name="package" />,
101
+ position: { x: 0, y: 0 }, ports: ["right", "bottom"],
102
+ portRules: { right: { role: "output", maxOutgoing: 1 }, bottom: { role: "output", maxOutgoing: 2 } } },
103
+ { id: "output", kind: "result", title: ko ? "결과" : "Result", shape: "tile", media: <Icon name="check" />,
104
+ position: { x: 160, y: 128 }, ports: ["top"], portRules: { top: { role: "input", maxIncoming: 1 } } },
105
+ ],
106
+ edges: [],
107
+ }));
108
+ const [picker, setPicker] = useState<{ request: CanvasConnectionDropRequest; drafts: CanvasConnectionDropNode[] } | null>(null);
109
+ const returnFocus = useRef<HTMLElement | null>(null);
110
+ const canvas = useRef<HTMLDivElement>(null);
111
+ const closeLabel = ko ? "닫기" : "Close";
112
+ const blockFields = (kind: Kind) => ({ kind, title: names[kind], shape: "tile" as const, media: <Icon name={icons[kind]} /> });
113
+ const create = (request: CanvasConnectionDropRequest) => {
114
+ const drafts = allowedBlocks(request.source, graph).map<CanvasConnectionDropNode>(kind => {
115
+ const targetSide = kind === "notice" ? "left" : "top";
116
+ return {
117
+ node: {
118
+ id: crypto.randomUUID(), ...blockFields(kind),
119
+ ports: kind === "task" ? ["top", "bottom"] : [targetSide],
120
+ portRules: { [targetSide]: { role: "input", maxIncoming: 1 }, ...(kind === "task" && { bottom: { role: "output", maxOutgoing: 1 } }) },
121
+ },
122
+ targetSide,
123
+ };
124
+ }).filter(request.canCommit);
125
+ if (!drafts.length) {
126
+ request.dismiss();
127
+ } else if (dropMode === "auto") {
128
+ if (!request.commit(drafts[0])) request.dismiss();
129
+ } else {
130
+ const active = document.activeElement;
131
+ returnFocus.current = active instanceof HTMLElement ? active : null;
132
+ request.signal.addEventListener("abort", () => {
133
+ setPicker(current => current?.request === request ? null : current);
134
+ }, { once: true });
135
+ setPicker({ request, drafts });
136
+ }
137
+ };
138
+
139
+ return <div className={styles.editorExample} lang={ko ? "ko" : "en"}>
140
+ <div ref={canvas}>
141
+ <Canvas {...graph} viewportLocked className={dropMode !== "off" && guideVisibility === "hover" ? styles.syncedGuideCanvas : undefined}
142
+ labels={{ ...labels, instructions: ko
143
+ ? "연결점을 다른 노드에 놓아 연결하거나, 빈 공간에 놓아 연결할 노드를 만들 수 있어요. 키보드에서는 두 연결점에서 차례로 Enter나 Space를 누르세요."
144
+ : "Drop a handle on another node to connect it, or drop it in empty space to create a connected node. With a keyboard, press Enter or Space on each handle in turn." }}
145
+ onGraphChange={setGraph} isValidConnection={validExampleConnection}
146
+ onConnectDrop={dropMode === "off" ? undefined : create}
147
+ renderOverlay={dropMode === "off" || guideVisibility === "hidden" ? undefined : ({
148
+ portPosition, requestConnectionDrop, canPlaceConnectionDrop, hoveredNodeId, focusedNodeId, selection,
149
+ }) => {
150
+ const selected = canvasNodeSelectionIds(selection);
151
+ return graph.nodes.flatMap(node => (node.ports ?? []).map(side => {
152
+ const port = { nodeId: node.id, side };
153
+ const kinds = allowedBlocks(port, graph);
154
+ if (!kinds.length || !canUseCanvasPort(graph.nodes, graph.edges, port, "source")) return null;
155
+ if (side === "bottom" && (
156
+ graph.edges.some(({ source }) => source.nodeId === node.id && source.side === side) ||
157
+ !kinds.some(kind => canPlaceConnectionDrop(port, blockFields(kind), "top"))
158
+ )) return null;
159
+ const at = portPosition(port);
160
+ if (!at) return null;
161
+ const label = ko ? `${node.title} ${sideLabel[side]}에 블록 추가` : `Add block to ${node.title} (${side})`;
162
+ return <GuideAnchor key={`${node.id}:${side}`} className={styles.canvasAction} mode={guideVisibility} at={at} side={side}
163
+ hovered={hoveredNodeId === node.id} focused={focusedNodeId === node.id} selected={selected.includes(node.id)}>
164
+ <IconButton size="md" variant="outline" className={styles.guideButton} icon={<Icon name="plus" />} aria-label={label} title={label}
165
+ onClick={event => {
166
+ event.currentTarget.focus({ preventScroll: true });
167
+ requestConnectionDrop(port);
168
+ }} />
169
+ </GuideAnchor>;
170
+ }));
171
+ }}
172
+ />
173
+ </div>
174
+ <Modal open={!!picker} size="sm" title={ko ? "추가할 블록" : "Add a block"} dismissLabel={closeLabel}
175
+ onOpenChange={open => { if (!open) picker?.request.dismiss(); }}
176
+ onCloseAutoFocus={event => {
177
+ event.preventDefault();
178
+ const active = returnFocus.current;
179
+ if (active?.isConnected) active.focus({ preventScroll: true });
180
+ else canvas.current?.querySelector<HTMLElement>("[data-slot='canvas']")?.focus({ preventScroll: true });
181
+ }}>
182
+ <div className={styles.dropChoices}>
183
+ {picker?.drafts.map(draft => <Button key={draft.node.id} variant="secondary" onClick={() => {
184
+ if (!picker.request.commit(draft)) picker.request.dismiss();
185
+ }}>{draft.node.title}</Button>)}
186
+ </div>
187
+ </Modal>
188
+ </div>;
189
+ }
190
+ ````
191
+
192
+ ### Source: web/app/[lang]/components/structure/canvas/ExecutionExample.tsx
193
+
194
+ ````tsx
195
+ "use client";
196
+
197
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
198
+ import { Canvas, type CanvasItem, type CanvasLink, type CanvasLabels } from "@/components/Canvas";
199
+ import { Icon } from "@/components/Icon";
200
+ import styles from "./page.module.css";
201
+
202
+ type NodeId = "input" | "process" | "save" | "notify";
203
+ type EdgeId = "input-process" | "process-save" | "process-notify";
204
+ const timeline: { at: number; nodes?: Partial<Record<NodeId, CanvasItem["status"]>>; edges?: Partial<Record<EdgeId, CanvasLink["status"]>> }[] = [
205
+ { at: 0, nodes: { input: "running" }, edges: { "input-process": "running" } },
206
+ { at: 3000, nodes: { input: "success", process: "running" }, edges: { "input-process": "success", "process-save": "running", "process-notify": "running" } },
207
+ { at: 6500, nodes: { process: "success", save: "running", notify: "running" }, edges: { "process-save": "success", "process-notify": "success" } },
208
+ { at: 9500, nodes: { save: "success" } },
209
+ { at: 10500, nodes: { notify: "error" }, edges: { "process-notify": "error" } },
210
+ ];
211
+
212
+ export function ExecutionExample({ ko, labels }: { ko: boolean; labels?: Partial<CanvasLabels> }) {
213
+ const container = useRef<HTMLDivElement>(null);
214
+ const [compact, setCompact] = useState<boolean | null>(null);
215
+ const [step, setStep] = useState(-1);
216
+ useLayoutEffect(() => {
217
+ const element = container.current;
218
+ if (!element) return;
219
+ const measure = () => setCompact(element.clientWidth < 420);
220
+ measure();
221
+ const observer = new ResizeObserver(measure);
222
+ observer.observe(element);
223
+ return () => observer.disconnect();
224
+ }, []);
225
+ useEffect(() => {
226
+ let generation = 0;
227
+ let timers: ReturnType<typeof setTimeout>[] = [];
228
+ const play = () => {
229
+ timers.forEach(clearTimeout);
230
+ const run = ++generation;
231
+ setStep(0);
232
+ timers = timeline.slice(1).map((frame, index) => setTimeout(() => {
233
+ if (run === generation) setStep(index + 1);
234
+ }, frame.at));
235
+ timers.push(setTimeout(() => {
236
+ if (run === generation) play();
237
+ }, timeline[timeline.length - 1].at + 2200));
238
+ };
239
+ play();
240
+ return () => { generation++; timers.forEach(clearTimeout); };
241
+ }, []);
242
+ const state = useMemo(() => {
243
+ const nodes: Partial<Record<NodeId, CanvasItem["status"]>> = {};
244
+ const edges: Partial<Record<EdgeId, CanvasLink["status"]>> = {};
245
+ for (const frame of timeline.slice(0, step + 1)) { Object.assign(nodes, frame.nodes); Object.assign(edges, frame.edges); }
246
+ return { nodes, edges };
247
+ }, [step]);
248
+ const text = ko ? { input: "입력", process: "처리", save: "저장", notify: "알림", loading: "불러오는 중", running: "실행 중", success: "완료", error: "오류" }
249
+ : { input: "Input", process: "Process", save: "Save", notify: "Notify", loading: "Loading", running: "Running", success: "Complete", error: "Error" };
250
+ const positions = compact ? { input: { x: 88, y: 0 }, process: { x: 32, y: 136 }, save: { x: 0, y: 300 }, notify: { x: 176, y: 300 } }
251
+ : { input: { x: 0, y: 134.5 }, process: { x: 160, y: 132 }, save: { x: 480, y: 40 }, notify: { x: 480, y: 264 } };
252
+ const statusLabel = (status: CanvasItem["status"] | CanvasLink["status"]) => status && status !== "idle" ? text[status] : undefined;
253
+ const nodes: CanvasItem[] = (["input", "process", "save", "notify"] as const).map(id => ({
254
+ id, title: text[id], position: positions[id], shape: id === "input" ? "circle" : id === "process" ? "card" : "tile",
255
+ media: <Icon name={id === "input" ? "package" : id === "process" ? "sliders" : id === "save" ? "stack" : "bell"} />,
256
+ ports: compact ? id === "input" ? ["bottom"] : id === "process" ? ["top", "bottom"] : ["top"]
257
+ : id === "input" ? ["right"] : id === "process" ? ["left", "right"] : ["left"],
258
+ status: state.nodes[id] ?? "idle", statusLabel: statusLabel(state.nodes[id]),
259
+ }));
260
+ const edges: CanvasLink[] = (["input-process", "process-save", "process-notify"] as const).map(id => ({
261
+ id, source: { nodeId: id === "input-process" ? "input" : "process", side: compact ? "bottom" : "right" },
262
+ target: { nodeId: id === "input-process" ? "process" : id === "process-save" ? "save" : "notify", side: compact ? "top" : "left" },
263
+ status: state.edges[id] ?? "idle", statusLabel: statusLabel(state.edges[id]),
264
+ }));
265
+ return <div ref={container} className={styles.execution} data-canvas-execution data-compact={compact || undefined} data-step={step}>
266
+ {compact !== null && <Canvas key={compact ? "vertical" : "horizontal"} className={styles.executionCanvas} nodes={nodes} edges={edges} readOnly
267
+ labels={{ ...labels, instructions: ko ? "자동으로 반복되는 실행 흐름이에요. 보기 도구로 배율을 조절하고 Space와 드래그로 화면을 이동할 수 있어요."
268
+ : "Execution plays automatically on a loop. Use the view controls to zoom, or Space and drag to pan." }} />}
269
+ </div>;
270
+ }
271
+ ````
272
+
273
+ ### Source: web/app/[lang]/components/structure/canvas/GuideAnchor.tsx
274
+
275
+ ````tsx
276
+ "use client";
277
+
278
+ import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
279
+ import type { CanvasPoint, CanvasPort } from "@/components/Canvas";
280
+ import styles from "./page.module.css";
281
+
282
+ export type GuideMode = "hover" | "click";
283
+
284
+ export function GuideAnchor({ mode, at, side, hovered, focused, selected, retainHover = true, endpointDistance, className, children }: {
285
+ mode: GuideMode;
286
+ at: CanvasPoint;
287
+ side?: CanvasPort["side"];
288
+ hovered: boolean;
289
+ focused: boolean;
290
+ selected: boolean;
291
+ retainHover?: boolean;
292
+ endpointDistance?: number;
293
+ className: string;
294
+ children: ReactNode;
295
+ }) {
296
+ const [retained, setRetained] = useState(false);
297
+ useEffect(() => {
298
+ if (mode !== "hover" || !retainHover || hovered) {
299
+ setRetained(mode === "hover" && retainHover && hovered);
300
+ return;
301
+ }
302
+ // Allow the pointer to move from the node across the gap to its guide.
303
+ const timer = window.setTimeout(() => setRetained(false), 220);
304
+ return () => window.clearTimeout(timer);
305
+ }, [mode, hovered, retainHover]);
306
+
307
+ const visible = mode === "hover" ? hovered : selected;
308
+ return <div className={`${styles.guideAction} ${className}`} data-direction={side} data-guide-mode={mode}
309
+ data-visible={visible || undefined} data-retained={retainHover && retained || undefined}
310
+ data-node-focus={focused || undefined} data-touch-selected={selected || undefined}
311
+ style={{ left: at.x, top: at.y, "--guide-endpoint-distance": endpointDistance === undefined ? undefined : `${endpointDistance}px` } as CSSProperties}>
312
+ <svg className={styles.guideRing} aria-hidden="true" focusable="false">
313
+ <circle cx="50%" cy="50%" fill="none" />
314
+ </svg>
315
+ {children}
316
+ </div>;
317
+ }
318
+ ````
319
+
320
+ ### Source: web/app/[lang]/components/structure/canvas/page.module.css
321
+
322
+ ````css
323
+ .demo { width: 100%; }
324
+
325
+ .useCase + .useCase { margin-block-start: var(--space-10); }
326
+ .useCase :global(.desc) { margin-block-end: 0; }
327
+ .useCase :global(.example-preview) { padding: var(--space-4); }
328
+
329
+ .execution { width: 100%; display: flex; flex-direction: column; gap: var(--space-3); }
330
+ .executionCanvas { --canvas-height: 480px; } /* lint-hardcoded: ignore */
331
+ .execution[data-compact] .executionCanvas { --canvas-height: 540px; } /* lint-hardcoded: ignore */
332
+
333
+ @property --canvas-demo-guide-expansion {
334
+ syntax: "<number>";
335
+ inherits: true;
336
+ initial-value: 0;
337
+ }
338
+
339
+ @property --canvas-demo-guide-visibility {
340
+ syntax: "<number>";
341
+ inherits: true;
342
+ initial-value: 0;
343
+ }
344
+
345
+ @property --canvas-demo-guide-scale {
346
+ syntax: "<number>";
347
+ inherits: true;
348
+ initial-value: 1;
349
+ }
350
+
351
+ .editorExample {
352
+ --workflow-canvas-height: 640px; /* lint-hardcoded: ignore */
353
+ --guide-stroke-color: color-mix(in oklab, var(--fg-subtle) 85%, var(--fg-muted));
354
+ --guide-stroke-hover: color-mix(in oklab, var(--fg-subtle) 40%, var(--fg-muted));
355
+ --guide-stroke-active: var(--fg);
356
+ --guide-ring-width: var(--hairline);
357
+ --guide-ring-outer-radius: calc(var(--iconbtn-h-md) / 2 - var(--space-0_5) / 2);
358
+ --guide-icon-size: calc((var(--icon-size-xs) + var(--icon-size-sm)) / 2);
359
+ --guide-no-delay: 0s; /* lint-hardcoded: ignore */
360
+
361
+ display: flex;
362
+ flex-direction: column;
363
+ gap: var(--space-3);
364
+ width: 100%;
365
+ }
366
+
367
+ .workflowCanvas { --canvas-height: var(--workflow-canvas-height); }
368
+ .dropChoices { display: flex; flex-direction: column; gap: var(--space-2); }
369
+ .guideAction {
370
+ --guide-current-color: var(--guide-stroke-color);
371
+ --canvas-demo-guide-expansion: 0;
372
+ --canvas-demo-guide-visibility: 0;
373
+ --guide-port-fill: var(--node-port-bg);
374
+ --guide-port-radius: calc(var(--node-port-size) * var(--canvas-zoom) * var(--canvas-demo-guide-scale) / 2);
375
+ --guide-port-stroke-width: calc(var(--hairline) * var(--canvas-zoom) * var(--canvas-demo-guide-scale));
376
+ --guide-current-width: calc(var(--guide-port-stroke-width) + (var(--guide-ring-width) - var(--guide-port-stroke-width)) * var(--canvas-demo-guide-expansion));
377
+ --guide-expanded-radius: var(--guide-ring-outer-radius);
378
+ --guide-current-radius: calc(var(--guide-port-radius) + (var(--guide-expanded-radius) - var(--guide-port-radius)) * var(--canvas-demo-guide-expansion));
379
+
380
+ position: absolute;
381
+ display: flex;
382
+ opacity: var(--canvas-demo-guide-visibility);
383
+ pointer-events: none;
384
+ transition:
385
+ --canvas-demo-guide-expansion var(--duration-base) var(--ease-out),
386
+ --canvas-demo-guide-visibility var(--duration-base) var(--ease-out);
387
+ }
388
+ .canvasAction {
389
+ --canvas-demo-guide-scale: var(--node-port-hidden-scale);
390
+ --guide-hit-delay: var(--node-hover-duration);
391
+
392
+ transition:
393
+ --canvas-demo-guide-expansion var(--duration-base) var(--ease-out),
394
+ --canvas-demo-guide-visibility var(--node-hover-duration) var(--ease-out),
395
+ --canvas-demo-guide-scale var(--node-port-duration) var(--node-port-easing),
396
+ pointer-events var(--guide-no-delay) var(--guide-hit-delay) allow-discrete;
397
+ }
398
+ /* Start the two transitions from the same Canvas hover state. */
399
+ .syncedGuideCanvas :global([data-slot="canvas-node"]:hover:not([data-ports-visible], [data-selected]) [data-side]:not([data-connected])) {
400
+ opacity: 0;
401
+ transform: translate(var(--node-port-x), var(--node-port-y)) scale(var(--node-port-hidden-scale));
402
+ }
403
+
404
+ :global([data-mode="dark"]) .guideAction { --guide-port-fill: var(--node-surface); }
405
+
406
+ .canvasAction[data-guide-mode="hover"][data-retained] {
407
+ --canvas-demo-guide-visibility: var(--guide-motionless-rescue, 0);
408
+ --canvas-demo-guide-scale: var(--guide-motionless-rescue, var(--node-port-hidden-scale));
409
+
410
+ pointer-events: var(--guide-motionless-hit, none);
411
+ }
412
+
413
+ :global([data-motion="none"]) .canvasAction {
414
+ --guide-motionless-rescue: 1;
415
+ --guide-motionless-hit: auto;
416
+ }
417
+
418
+ @media (prefers-reduced-motion: reduce) {
419
+ .canvasAction {
420
+ --guide-motionless-rescue: 1;
421
+ --guide-motionless-hit: auto;
422
+ }
423
+ }
424
+
425
+ .guideAction:is([data-visible], [data-guide-mode="hover"]:hover, :focus-within),
426
+ :is(.workflowAction, .workflowBranchAction)[data-guide-mode="hover"][data-retained],
427
+ :global(html[data-input-method="keyboard"]) .guideAction[data-node-focus] {
428
+ --canvas-demo-guide-visibility: 1;
429
+ --canvas-demo-guide-scale: 1;
430
+ --guide-hit-delay: var(--guide-no-delay);
431
+
432
+ pointer-events: auto;
433
+ }
434
+
435
+ @media (hover: hover) {
436
+ .guideAction:has(.guideButton:hover) {
437
+ --canvas-demo-guide-expansion: 1;
438
+ --guide-current-color: var(--guide-stroke-hover);
439
+ }
440
+ }
441
+
442
+ @media (hover: none) {
443
+ .guideAction[data-touch-selected] {
444
+ --canvas-demo-guide-expansion: 1;
445
+ --canvas-demo-guide-visibility: 1;
446
+ --canvas-demo-guide-scale: 1;
447
+ --guide-hit-delay: var(--guide-no-delay);
448
+
449
+ pointer-events: auto;
450
+ }
451
+ }
452
+
453
+ .canvasAction[data-direction="bottom"] {
454
+ transform: translate(-50%, calc((var(--lh-xs) + var(--space-2)) * var(--canvas-zoom) + var(--space-1)));
455
+ }
456
+ .canvasAction[data-direction="right"] { transform: translate(var(--space-4), -50%); }
457
+
458
+ .workflowAction {
459
+ --guide-expanded-radius: max(var(--guide-port-radius), min(var(--guide-ring-outer-radius), calc(var(--guide-endpoint-distance) - var(--guide-port-radius) - var(--hairline))));
460
+
461
+ transform: translate(-50%, -50%);
462
+ }
463
+ .workflowBranchAction[data-direction="left"] { transform: translate(calc(-100% - var(--space-2)), -50%); }
464
+ .workflowBranchAction[data-direction="right"] { transform: translate(var(--space-2), -50%); }
465
+ .workflowBranchAction:not([data-direction]) {
466
+ --guide-expanded-radius: max(var(--guide-port-radius), min(var(--guide-ring-outer-radius), calc(var(--guide-endpoint-distance) - var(--hairline))));
467
+
468
+ transform: translate(-50%, -50%);
469
+ }
470
+ .workflowBranchAction:not([data-direction]) .guideButton {
471
+ width: min(var(--iconbtn-h-md), calc(var(--guide-endpoint-distance) * 2));
472
+ }
473
+ .guideAction .guideButton,
474
+ .guideAction .guideButton:hover:not(:disabled) {
475
+ border-color: transparent;
476
+ color: var(--guide-current-color);
477
+ background: transparent;
478
+ transition-property: box-shadow, transform;
479
+ }
480
+ .guideAction .guideButton > svg {
481
+ width: min(var(--guide-icon-size), var(--guide-expanded-radius));
482
+ height: min(var(--guide-icon-size), var(--guide-expanded-radius));
483
+ opacity: var(--canvas-demo-guide-expansion);
484
+ }
485
+ .guideRing {
486
+ position: absolute;
487
+ inset: 0;
488
+ width: 100%;
489
+ height: 100%;
490
+ pointer-events: none;
491
+ }
492
+ .guideRing circle {
493
+ r: calc(var(--guide-current-radius) - var(--guide-current-width) / 2);
494
+ fill: color-mix(in oklab, transparent calc(var(--canvas-demo-guide-expansion) * 100%), var(--guide-port-fill));
495
+ stroke: color-mix(in oklab, var(--guide-current-color) calc(var(--canvas-demo-guide-expansion) * 100%), var(--node-port-border));
496
+ stroke-width: var(--guide-current-width);
497
+ }
498
+ .guideAction:has(.guideButton:focus-visible) {
499
+ --canvas-demo-guide-expansion: 1;
500
+ --guide-current-color: var(--guide-stroke-active);
501
+ }
502
+ .workflowCutout { position: absolute; }
503
+ .workflowCutoutCircle {
504
+ /* End the connector at the outer contour so translucent strokes don't stack at the join. */
505
+ r: calc(var(--guide-current-radius) / var(--canvas-zoom));
506
+ opacity: var(--canvas-demo-guide-visibility);
507
+ }
508
+
509
+ @media (prefers-contrast: more) {
510
+ .editorExample { --guide-stroke-color: var(--fg-muted); }
511
+ }
512
+ ````
513
+
514
+ ### Source: web/app/[lang]/components/structure/canvas/page.tsx
515
+
516
+ ````tsx
517
+ "use client";
518
+
519
+ import { useLayoutEffect, useRef, useState } from "react";
520
+ import { usePathname } from "next/navigation";
521
+ import { Icon } from "@/components/Icon";
522
+ import { Canvas, type CanvasItem, type CanvasLink, type CanvasLabels, type CanvasBackground, type CanvasEdgeCornerRadius } from "@/components/Canvas";
523
+ import type { CanvasNodeVariant } from "@/components/CanvasNode";
524
+ import type { ToolbarOrientation } from "@/components/Toolbar";
525
+ import type { CanvasEdgeLineStyle } from "@/components/CanvasEdge";
526
+ import { useTheme } from "@/components/ThemeController";
527
+ import { Code } from "@/components/Code";
528
+ import { ExampleBlock } from "@/app/_components/ExampleBlock";
529
+ import { Playground } from "@/app/_components/Playground";
530
+ import { DocsTable } from "@/app/_components/DocsTable";
531
+ import styles from "./page.module.css";
532
+ import { ExecutionExample } from "./ExecutionExample";
533
+ import { DropExample } from "./DropExample";
534
+ import { WorkflowExample } from "./WorkflowExample";
535
+
536
+ function initialNodes(ko: boolean, compact = false): CanvasItem[] {
537
+ const title = (letter: string) => `${ko ? "노드" : "Node"} ${letter}`;
538
+ const nodes: CanvasItem[] = [
539
+ { id: "a", position: { x: 60, y: 150 }, title: title("A"), media: <Icon name="package" />, shape: "tile", ports: ["right", "top"] },
540
+ { id: "b", position: { x: 250, y: 50 }, title: title("B"), media: <Icon name="sliders" />, shape: "card", ports: ["left", "right", "bottom"] },
541
+ { id: "c", position: { x: 280, y: 260 }, title: title("C"), media: <Icon name="stack" />, shape: "tile", ports: ["left", "right", "top"] },
542
+ { id: "d", position: { x: 540, y: 150 }, title: title("D"), media: <Icon name="squares-four" />, shape: "circle", ports: ["left", "bottom"] },
543
+ ];
544
+ const positions = [{ x: 0, y: 80 }, { x: 96, y: 0 }, { x: 0, y: 240 }, { x: 208, y: 240 }];
545
+ return compact ? nodes.map((node, index) => ({ ...node, position: positions[index] })) : nodes;
546
+ }
547
+ const initialEdges: CanvasLink[] = [
548
+ { id: "ab", source: { nodeId: "a", side: "right" }, target: { nodeId: "b", side: "left" } },
549
+ { id: "bd", source: { nodeId: "b", side: "right" }, target: { nodeId: "d", side: "left" } },
550
+ ];
551
+ const korean: CanvasLabels = {
552
+ canvas: "노드 캔버스", controls: "보기 도구", zoomIn: "확대", zoomOut: "축소", fit: "전체 보기", zoom: "배율",
553
+ instructions: "노드를 끌어서 이동하세요. 핸들을 누른 채 끌어 다른 노드나 핸들에서 놓으세요. 키보드로는 두 핸들에서 차례로 Enter 또는 Space를 누르세요. 노드에 포커스한 후 방향키로 이동하고 Shift로 더 크게 이동하세요. Escape는 취소, Delete는 선택 삭제예요. Cmd/Ctrl+Z로 실행 취소하고 Shift와 함께 다시 실행하세요. 빈 배경을 끌어 노드와 선을 함께 선택하세요. Shift와 함께 끌면 기존 선택에 추가해요. Space를 누른 채 끌거나 가운데 버튼으로 화면을 이동하세요.",
554
+ connecting: "연결할 다른 노드의 핸들에서 Enter 또는 Space를 누르세요. Escape로 취소할 수 있어요.", connected: "연결했어요.", cancelled: "연결을 취소했어요.",
555
+ createFromPort: "출력 핸들에서 Shift+Enter를 누르면 연결할 블록을 추가할 수 있어요.",
556
+ port: (title, side) => `${title} ${{ left: "왼쪽", right: "오른쪽", top: "위쪽", bottom: "아래쪽" }[side]} 연결점`,
557
+ };
558
+ function DemoGraph({ compact, ko, nodeVariant = "default", edgeCornerRadius, lineStyle = "solid", controlsOrientation = "horizontal", grid = true, background, backgroundScale, readOnly = false, highContrast = false }: { compact: boolean; ko: boolean; nodeVariant?: CanvasNodeVariant; edgeCornerRadius?: CanvasEdgeCornerRadius; lineStyle?: CanvasEdgeLineStyle; controlsOrientation?: ToolbarOrientation; grid?: boolean; background?: CanvasBackground; backgroundScale?: number; readOnly?: boolean; highContrast?: boolean }) {
559
+ const [nodes, setNodes] = useState(() => initialNodes(ko, compact));
560
+ const [edges, setEdges] = useState(initialEdges);
561
+ const visuals = initialNodes(ko, compact);
562
+ const renderedNodes = nodes.map(node => {
563
+ const visual = visuals.find(item => item.id === node.id);
564
+ return { ...node, ...(visual ? { title: visual.title, media: visual.media } : {}), variant: nodeVariant };
565
+ });
566
+ return <Canvas nodes={renderedNodes} edges={edges} onNodesChange={setNodes} onEdgesChange={setEdges}
567
+ edgeCornerRadius={edgeCornerRadius} lineStyle={lineStyle} controlsOrientation={controlsOrientation} grid={grid} background={background} backgroundScale={backgroundScale} readOnly={readOnly} highContrast={highContrast} labels={ko ? korean : undefined} />;
568
+ }
569
+ function Demo(props: Omit<Parameters<typeof DemoGraph>[0], "compact">) {
570
+ const ref = useRef<HTMLDivElement>(null);
571
+ const [compact, setCompact] = useState<boolean | null>(null);
572
+ useLayoutEffect(() => { setCompact((ref.current?.clientWidth ?? 800) < 420); }, []);
573
+ return <div ref={ref} className={styles.demo}>{compact !== null && <DemoGraph {...props} compact={compact} />}</div>;
574
+ }
575
+ const sample = `"use client";
576
+
577
+ import { useState } from "react";
578
+ import { Icon } from "@/components/Icon";
579
+ import { Canvas, type CanvasItem, type CanvasLink } from "@/components/Canvas";
580
+
581
+ export function CanvasExample() {
582
+ const [nodes, setNodes] = useState<CanvasItem[]>([
583
+ { id: "a", title: "Node A", position: { x: 60, y: 80 },
584
+ shape: "tile", media: <Icon name="package" />, ports: ["right"] },
585
+ { id: "b", title: "Node B", position: { x: 320, y: 180 },
586
+ shape: "card", media: <Icon name="package" />, ports: ["left", "top"] },
587
+ ]);
588
+ const [edges, setEdges] = useState<CanvasLink[]>([]);
589
+ return <Canvas nodes={nodes} edges={edges}
590
+ onNodesChange={setNodes} onEdgesChange={setEdges} />;
591
+ }`;
592
+ const dropMode = "auto";
593
+ const guideVisibility = "hover";
594
+ const dropSample = `<DropExample
595
+ dropMode="${dropMode}"
596
+ guideVisibility="${guideVisibility}"
597
+ />
598
+
599
+ // dropMode: "off" | "auto" | "choose"
600
+ // guideVisibility: "hover" | "click" | "hidden"
601
+ // Canvas: viewportLocked, onConnectDrop, renderOverlay`;
602
+
603
+ const workflowSample = `<WorkflowExample
604
+ guideVisibility="${guideVisibility}"
605
+ />
606
+
607
+ // guideVisibility: "hover" | "click"
608
+ // Canvas: viewportLocked, readOnly, renderOverlay`;
609
+
610
+ export default function CanvasPage() {
611
+ const ko = !!usePathname()?.startsWith("/ko");
612
+ const { shape } = useTheme();
613
+ const [cornerSelection, setEdgeCornerRadius] = useState<CanvasEdgeCornerRadius | undefined>();
614
+ const edgeCornerRadius = cornerSelection === "sm" || cornerSelection === "md" || cornerSelection === "lg" ? cornerSelection : undefined;
615
+ const defaultCornerType: CanvasEdgeCornerRadius = shape === "crisp" ? "sm" : shape === "standard" ? "md" : "lg";
616
+ const [backgroundPercent, setBackgroundPercent] = useState(90);
617
+ const [nodeVariant, setNodeVariant] = useState<CanvasNodeVariant>("default");
618
+ const [lineStyle, setLineStyle] = useState<CanvasEdgeLineStyle>("solid");
619
+ const [background, setBackground] = useState<CanvasBackground>("dots");
620
+ const [controlsOrientation, setControlsOrientation] = useState<ToolbarOrientation>("horizontal");
621
+ const [readOnly, setReadOnly] = useState(false);
622
+ const [highContrast, setHighContrast] = useState(false);
623
+ const props = [
624
+ ["nodes", "CanvasItem[]", "", ko ? "id, position과 CanvasNode의 표현 속성이에요." : "Node IDs, positions, and CanvasNode presentation props."],
625
+ ["edges", "CanvasLink[]", "", ko ? "id, source/target 연결점과 CanvasEdge의 표현 속성이에요." : "Edge IDs, source/target ports, and CanvasEdge presentation props."],
626
+ ["onNodesChange", "(nodes) => void", "", ko ? "노드 이동·삭제 결과를 반영해요." : "Applies node movement and deletion."],
627
+ ["onEdgesChange", "(edges) => void", "", ko ? "새 연결·삭제 결과를 반영해요." : "Applies new connections and deletion."],
628
+ ["selection", "CanvasSelection", "", ko ? "단일 노드·선, nodes/ids 또는 nodeIds/edgeIds 혼합 선택을 제어해요. 생략하면 내부에서 관리해요." : "Controls a node, edge, nodes/ids, or mixed nodeIds/edgeIds selection; otherwise managed internally."],
629
+ ["onSelectionChange", "(selection) => void", "", ko ? "노드·선 선택 변경을 전달해요." : "Reports node or edge selection."],
630
+ ["onGraphChange", "(graph) => void", "", ko ? "노드와 연결선을 한 번에 반영해요." : "Applies nodes and edges in a single update."],
631
+ ["onConnectDrop", "(request) => void", "", ko ? "빈 공간에서 놓은 연결의 블록 생성 요청을 받아요." : "Receives a block creation request on an empty-space drop."],
632
+ ["renderOverlay", "(context) => ReactNode", "", ko ? "핸들 위치에 맞춰 화면 위에 추가 버튼을 배치해요." : "Renders screen-sized actions anchored to handles."],
633
+ ["isValidConnection", "(connection, graph) => boolean", "", ko ? "연결에 추가 업무 제약을 적용해요." : "Adds domain-specific connection validation."],
634
+ ["edgeCornerRadius", "sm | md | lg", "Shape", ko ? "세 가지 모서리 타입. 생략하면 Shape 기본값을 따르고, 연결별 cornerRadius가 우선해요." : "Three corner presets. Omitted values follow Shape; per-edge cornerRadius takes precedence."],
635
+ ["lineStyle", "solid | dashed", "solid", ko ? "연결의 기본 선 패턴이에요." : "Default edge pattern."],
636
+ ["readOnly", "boolean", "false", ko ? "노드 이동·연결·삭제를 막아요. 보기 이동은 가능해요." : "Prevents graph edits; viewing and selection remain available."],
637
+ ["highContrast", "boolean", "false", ko ? "노드 테두리와 연결선에 전경색을 사용해 대비를 높여요." : "Uses the foreground color for neutral node outlines and connections."],
638
+ ["background", "dots | grid | none", "dots", ko ? "캔버스 외부 설정에서 배경을 제어해요." : "Sets the background from external controls."],
639
+ ["backgroundScale", "number", "0.9", ko ? "배경 패턴 간격의 배율이에요. 0.5~2이며 화면 배율·노드 위치는 바꾸지 않아요." : "Pattern spacing scale, 0.5 to 2. Does not change viewport zoom or node positions."],
640
+ ["defaultBackground", "dots | grid | none", "dots", ko ? "초기 배경값이에요." : "Initial background pattern."],
641
+ ["controlsOrientation", "horizontal | vertical", "horizontal", ko ? "보기 툴바의 가로·세로 배치예요." : "View toolbar orientation."],
642
+ ["fitInlineInset", "number", "", ko ? "전체 보기에서 그래프 양옆에 확보할 최소 화면 여백이에요." : "Minimum screen-space room on each side of the fitted graph."],
643
+ ["viewportLocked", "boolean", "false", ko ? "보기 도구와 화면 이동을 끄고 그래프가 프리뷰 안에 들어오게 맞춰요." : "Locks manual navigation, hides view controls, and fits the graph automatically."],
644
+ ["grid / controls", "boolean", "true", ko ? "grid는 기존 점 배경 토글이에요. controls는 툴바 표시 여부예요." : "Legacy dots toggle and toolbar visibility."],
645
+ ["labels", "Partial<CanvasLabels>", "English", ko ? "연결점 이름·상태 안내·키보드 설명을 현지화해요." : "Localizes controls, port names, status, and keyboard instructions."],
646
+ ];
647
+ return <div data-slot="canvas-docs">
648
+ <h1 className="page-title">Canvas</h1>
649
+ <p className="page-lead">{ko ? "노드를 옮기고 핸들을 연결하는 캔버스." : "Move nodes and connect their handles."}</p>
650
+ <section id="usage" className="section-first">
651
+ <h2>{ko ? "사용법" : "Usage"}</h2>
652
+ <p className="desc">{ko ? "노드를 끌어 옮기거나, 핸들을 다른 노드 위로 끌어 연결하세요. 빈 배경을 드래그하면 노드와 선을 함께 선택해요." : "Drag nodes to move them, or drag a handle onto another node to connect. Drag an empty area to select nodes and edges."}</p>
653
+ <ExampleBlock code={sample} previewWidth="full"><Demo ko={ko} /></ExampleBlock>
654
+ </section>
655
+ <Playground axes={[
656
+ { label: "nodeVariant", value: nodeVariant, onChange: value => setNodeVariant(value as CanvasNodeVariant), options: ["default", "connector"] },
657
+ { label: "controlsOrientation", value: controlsOrientation, onChange: value => setControlsOrientation(value as ToolbarOrientation), options: ["horizontal", "vertical"] },
658
+ { label: "edgeCornerRadius", value: edgeCornerRadius ?? defaultCornerType, onChange: (value: string) => setEdgeCornerRadius(value as CanvasEdgeCornerRadius), options: ["sm", "md", "lg"] },
659
+ { label: "lineStyle", value: lineStyle, onChange: value => setLineStyle(value as CanvasEdgeLineStyle), options: ["solid", "dashed"] },
660
+ { label: "background", value: background, onChange: value => setBackground(value as CanvasBackground), options: ["dots", "grid", "none"] },
661
+ ]} sliders={[{ label: "backgroundScale", value: backgroundPercent, onChange: setBackgroundPercent, min: 50, max: 200, step: 10, unit: "%", disabled: background === "none" }]} togglesLabel={ko ? "캔버스 옵션" : "Canvas options"} toggles={[
662
+ { label: "readOnly", value: readOnly, onChange: setReadOnly },
663
+ { label: ko ? "고대비" : "High contrast", value: highContrast, onChange: setHighContrast },
664
+ ]}>
665
+ <Demo ko={ko} nodeVariant={nodeVariant} edgeCornerRadius={edgeCornerRadius} lineStyle={lineStyle} controlsOrientation={controlsOrientation} background={background} backgroundScale={backgroundPercent / 100} readOnly={readOnly} highContrast={highContrast} />
666
+ </Playground>
667
+ <section id="use-cases">
668
+ <h2>{ko ? "사용 사례" : "Use cases"}</h2>
669
+ <article className={styles.useCase} aria-labelledby="canvas-drop-title">
670
+ <h3 id="canvas-drop-title">{ko ? "빈 공간에서 블록 만들기" : "Create a connected block"}</h3>
671
+ <p className="desc">{ko
672
+ ? "요청 노드에 마우스를 올리거나 탭한 뒤 추가 버튼을 눌러 보세요. 연결점을 빈 공간에 끌어 놓아도 아래쪽에는 작업, 오른쪽에는 알림을 추가할 수 있어요."
673
+ : "Hover over or tap Request to reveal its add buttons. You can also drag a handle into empty space. The bottom handle adds a task and the right handle adds a notification."}</p>
674
+ <ExampleBlock code={dropSample} previewWidth="full">
675
+ <DropExample ko={ko} labels={ko ? korean : undefined} dropMode={dropMode} guideVisibility={guideVisibility} />
676
+ </ExampleBlock>
677
+ </article>
678
+ <article className={styles.useCase} aria-labelledby="canvas-workflow-title">
679
+ <h3 id="canvas-workflow-title">{ko ? "단계와 분기 추가하기" : "Add steps and branches"}</h3>
680
+ <p className="desc">{ko
681
+ ? "노드나 연결선에 마우스를 올리거나 탭해 추가 버튼을 표시하세요. 줄 사이에는 공통 단계를 추가하는 버튼이 하나만 표시돼요. 분기는 같은 줄의 양끝이나 노드 사이에서 추가해요."
682
+ : "Hover over or tap a node or connection to reveal its add buttons. Each gap between rows gets one button for a shared step. Add branches at the ends of a row or between its nodes."}</p>
683
+ <ExampleBlock code={workflowSample} previewWidth="full">
684
+ <WorkflowExample ko={ko} labels={ko ? korean : undefined} guideVisibility={guideVisibility} />
685
+ </ExampleBlock>
686
+ </article>
687
+ </section>
688
+ <section id="execution">
689
+ <h2>{ko ? "실행 흐름" : "Execution"}</h2>
690
+ <ExampleBlock previewWidth="full"><ExecutionExample ko={ko} labels={ko ? korean : undefined} /></ExampleBlock>
691
+ </section>
692
+ <section id="keyboard">
693
+ <h2>{ko ? "키보드" : "Keyboard"}</h2>
694
+ <DocsTable columns={[{ key: "key", label: ko ? "키" : "Key" }, { key: "action", label: ko ? "동작" : "Action", flex: true }]} rows={[
695
+ { key: <Code>Tab</Code>, action: ko ? "노드·연결점·선·도구로 포커스 이동" : "Focus nodes, ports, edges, and controls" },
696
+ { key: <Code>Enter / Space</Code>, action: ko ? "노드·선 선택, 연결점에서 연결 시작·완료" : "Select nodes/edges; start or finish a connection on a handle" },
697
+ { key: <Code>Shift + Enter</Code>, action: ko ? "블록 생성이 켜져 있으면 출력 연결점에서 새 블록 만들기" : "Create a block from an output handle when block creation is enabled" },
698
+ { key: <Code>↑ ↓ ← →</Code>, action: ko ? "포커스된 노드 이동. Shift와 함께 더 크게 이동" : "Move a focused node. Hold Shift for a larger step" },
699
+ { key: <Code>Escape</Code>, action: ko ? "현재 연결·드래그 취소" : "Cancel the current connection or drag" },
700
+ { key: <Code>Shift + click / Enter</Code>, action: ko ? "노드·선 선택 추가·해제" : "Toggle a node or edge in the selection" },
701
+ { key: <Code>Space + drag</Code>, action: ko ? "화면 이동. 가운데 버튼 드래그도 사용 가능" : "Pan the view; middle-button dragging also works" },
702
+ { key: <Code>⌘ / Ctrl + C</Code>, action: ko ? "선택한 노드와 노드 사이 연결선 복사" : "Copy selected nodes and their internal connections" },
703
+ { key: <Code>⌘ / Ctrl + V</Code>, action: ko ? "복사한 노드·연결선 붙여넣기" : "Paste copied nodes and connections" },
704
+ { key: <Code>⌘ / Ctrl + Z</Code>, action: ko ? "이동·연결·삭제·붙여넣기 실행 취소" : "Undo moves, connections, deletions, and pastes" },
705
+ { key: <Code>⌘ / Ctrl + Shift + Z</Code>, action: ko ? "다시 실행" : "Redo the last undone edit" },
706
+ { key: <Code>Delete / Backspace</Code>, action: ko ? "선택 삭제" : "Delete selection" },
707
+ ]} />
708
+ </section>
709
+ <section id="props">
710
+ <h2>{ko ? "속성" : "Props"}</h2>
711
+ <DocsTable columns={[{ key: "prop", label: ko ? "속성" : "Prop" }, { key: "type", label: ko ? "타입" : "Type" }, { key: "default", label: "Default" }, { key: "description", label: ko ? "설명" : "Description", flex: true }]}
712
+ rows={props.map(([prop, type, value, description]) => ({ prop: <Code>{prop}</Code>, type: <Code>{type}</Code>, default: value, description }))} />
713
+ </section>
714
+ </div>;
715
+ }
716
+ ````
717
+
718
+ ### Source: web/app/[lang]/components/structure/canvas/WorkflowExample.tsx
719
+
720
+ ````tsx
721
+ "use client";
722
+
723
+ import { useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
724
+ import { Canvas, type CanvasItem, type CanvasLabels, type CanvasLink, type CanvasPoint } from "@/components/Canvas";
725
+ import { canvasEdgeSelectionIds, canvasNodeSelectionIds } from "@/components/Canvas/selection";
726
+ import { Icon } from "@/components/Icon";
727
+ import { IconButton } from "@/components/IconButton";
728
+ import styles from "./page.module.css";
729
+ import { GuideAnchor, type GuideMode } from "./GuideAnchor";
730
+
731
+ type Side = "left" | "right";
732
+ type Row = { id: string; nodeIds: readonly string[] };
733
+ type Boundary = { id: string; from: Row; to: Row; edgeIds: readonly string[] };
734
+ type History = { past: readonly (readonly Row[])[]; rows: readonly Row[]; future: readonly (readonly Row[])[] };
735
+ const rowGap = 128;
736
+ const laneGap = 160;
737
+ const branchGuideInset = 48;
738
+
739
+ const copy = {
740
+ ko: { start: "시작", end: "끝", block: "노드",
741
+ distinguish: (title: string, index: number) => `${title} ${index}`,
742
+ commonStep: "공통 단계 추가", beforeBranch: "분기 앞에 공통 단계 추가", afterBranch: "분기 뒤에 공통 단계 추가",
743
+ insertCommon: (name: string) => `${name} 줄 앞에 공통 단계 추가`,
744
+ addBranch: (title: string, side: Side) => `${title} ${side === "left" ? "왼쪽" : "오른쪽"}에 분기 추가`,
745
+ addBetween: (left: string, right: string) => `${left} 뒤, ${right} 앞에 분기 추가`,
746
+ between: "노드 사이에 분기 추가",
747
+ insertBefore: (title: string) => `${title} 앞에 단계 추가` },
748
+ en: { start: "Start", end: "End", block: "Node",
749
+ distinguish: (title: string, index: number) => `${title} ${index}`,
750
+ commonStep: "Add a shared step", beforeBranch: "Add a shared step before the split", afterBranch: "Add a shared step after the merge",
751
+ insertCommon: (name: string) => `Add a shared step before the row with ${name}`,
752
+ addBranch: (title: string, side: Side) => `Add a branch to the ${side} of ${title}`,
753
+ addBetween: (left: string, right: string) => `Add a branch between ${left} and ${right}`,
754
+ between: "Add a branch between nodes",
755
+ insertBefore: (title: string) => `Add a step before ${title}` },
756
+ };
757
+
758
+ function layout(rows: readonly Row[], text: typeof copy.ko) {
759
+ const graphRows = [{ id: "start", nodeIds: ["start"] }, ...rows, { id: "end", nodeIds: ["end"] }];
760
+ const names = new Map<string, string>([["start", text.start], ["end", text.end]]);
761
+ const nodeCount = rows.reduce((count, row) => count + row.nodeIds.length, 0);
762
+ let index = 0;
763
+ const nodes = graphRows.flatMap<CanvasItem>((row, rank) => row.nodeIds.map((id, column) => {
764
+ const endpoint = id === "start" || id === "end";
765
+ const title = endpoint ? text[id] : text.block;
766
+ if (!endpoint) names.set(id, nodeCount > 1 ? text.distinguish(title, ++index) : title);
767
+ return {
768
+ id, title, shape: endpoint ? "circle" : "tile",
769
+ position: { x: (column - (row.nodeIds.length - 1) / 2) * laneGap, y: (rank - rows.length / 2) * rowGap },
770
+ ports: id === "start" ? ["bottom"] : id === "end" ? ["top"] : ["top", "bottom"],
771
+ };
772
+ }));
773
+ const edges: CanvasLink[] = [];
774
+ const boundaries = graphRows.slice(1).map<Boundary>((to, rank) => {
775
+ const from = graphRows[rank];
776
+ const edgeIds = from.nodeIds.flatMap(source => to.nodeIds.map(target => {
777
+ const id = `${source}>${target}`;
778
+ edges.push({ id, source: { nodeId: source, side: "bottom" }, target: { nodeId: target, side: "top" } });
779
+ return id;
780
+ }));
781
+ return { id: `${from.id}>${to.id}`, from, to, edgeIds };
782
+ });
783
+ return { nodes, edges, boundaries, names };
784
+ }
785
+
786
+ type InsertionPoint = {
787
+ tracks: readonly SVGPathElement[];
788
+ screen: CanvasPoint;
789
+ world: CanvasPoint;
790
+ endpointDistance: number;
791
+ bounds: { x: number; y: number; width: number; height: number };
792
+ };
793
+
794
+ function boundaryPoint(tracks: readonly SVGPathElement[]): CanvasPoint {
795
+ const paths = tracks.map(track => ({ track, length: track.getTotalLength() }));
796
+ const center = paths.reduce((sum, { track, length }) => {
797
+ const start = track.getPointAtLength(0), end = track.getPointAtLength(length);
798
+ return { x: sum.x + start.x + end.x, y: sum.y + start.y + end.y };
799
+ }, { x: 0, y: 0 });
800
+ center.x /= paths.length * 2;
801
+ center.y /= paths.length * 2;
802
+ const first = paths[0];
803
+ let y = first.track.getPointAtLength(first.length / 2).y;
804
+ if (paths.length === 1) return { x: center.x, y };
805
+
806
+ // Find a height near the routes while keeping the control on the row's center axis.
807
+ let distance = Infinity;
808
+ const samples = 24;
809
+ for (const { track, length } of paths) {
810
+ for (let step = 1; step < samples; step++) {
811
+ const candidate = track.getPointAtLength(length * step / samples);
812
+ const nextDistance = Math.hypot(candidate.x - center.x, candidate.y - center.y);
813
+ if (nextDistance < distance) {
814
+ distance = nextDistance;
815
+ y = candidate.y;
816
+ }
817
+ }
818
+ }
819
+ return { x: center.x, y };
820
+ }
821
+
822
+ function edgeAt(target: EventTarget | null) {
823
+ const element = target instanceof Element ? target.closest("[data-canvas-edge-id]") : null;
824
+ return element?.getAttribute("data-canvas-edge-id") ?? null;
825
+ }
826
+
827
+ function InsertionCutout({ point }: { point: InsertionPoint }) {
828
+ const id = useId();
829
+ const { tracks, world, bounds } = point;
830
+ useLayoutEffect(() => {
831
+ tracks.forEach(track => track.setAttribute("mask", `url(#${id})`));
832
+ return () => tracks.forEach(track => track.removeAttribute("mask"));
833
+ }, [tracks, id]);
834
+
835
+ return <svg width="0" height="0" className={styles.workflowCutout} aria-hidden="true" focusable="false">
836
+ <defs>
837
+ <mask id={id} maskUnits="userSpaceOnUse" {...bounds}>
838
+ <rect {...bounds} fill="white" />
839
+ <circle className={styles.workflowCutoutCircle} cx={world.x} cy={world.y} fill="black" />
840
+ </mask>
841
+ </defs>
842
+ </svg>;
843
+ }
844
+
845
+ export function WorkflowExample({ ko = false, labels, guideVisibility = "hover" }: {
846
+ ko?: boolean;
847
+ labels?: Partial<CanvasLabels>;
848
+ guideVisibility?: GuideMode;
849
+ }) {
850
+ const text = ko ? copy.ko : copy.en;
851
+ const [history, setHistory] = useState<History>({ past: [], rows: [], future: [] });
852
+ const canvas = useRef<HTMLDivElement>(null);
853
+ const [hoveredEdgeId, setHoveredEdgeId] = useState<string | null>(null);
854
+ const [focusedEdgeId, setFocusedEdgeId] = useState<string | null>(null);
855
+ const [points, setPoints] = useState<ReadonlyMap<string, InsertionPoint>>(new Map());
856
+ const { nodes, edges, boundaries, names } = useMemo(() => layout(history.rows, text), [history.rows, text]);
857
+ useLayoutEffect(() => {
858
+ const root = canvas.current?.firstElementChild;
859
+ const svg = root?.querySelector<SVGSVGElement>("svg[aria-label]");
860
+ const world = svg?.parentElement;
861
+ if (!root || !svg || !world) return;
862
+
863
+ const measure = () => {
864
+ const { left, top } = root.getBoundingClientRect();
865
+ const next = new Map<string, InsertionPoint>();
866
+ const tracksById = new Map<string, SVGPathElement>();
867
+ for (const track of svg.querySelectorAll<SVGPathElement>("[data-canvas-edge-id] [data-edge-part='track']")) {
868
+ const id = edgeAt(track);
869
+ if (id && track.getTotalLength()) tracksById.set(id, track);
870
+ }
871
+ for (const boundary of boundaries) {
872
+ const tracks = boundary.edgeIds.flatMap(id => {
873
+ const track = tracksById.get(id);
874
+ return track ? [track] : [];
875
+ });
876
+ const matrix = tracks[0]?.getScreenCTM();
877
+ if (!matrix || tracks.length !== boundary.edgeIds.length) continue;
878
+ const world = boundaryPoint(tracks);
879
+ const screen = new DOMPoint(world.x, world.y).matrixTransform(matrix);
880
+ const bounds = tracks.map(track => track.getBBox());
881
+ const distances = tracks.flatMap(track => [0, track.getTotalLength()].map(length => {
882
+ const end = track.getPointAtLength(length).matrixTransform(matrix);
883
+ return Math.hypot(end.x - screen.x, end.y - screen.y);
884
+ }));
885
+ const padding = 4 / Math.hypot(matrix.a, matrix.b);
886
+ const x = Math.min(...bounds.map(box => box.x)) - padding;
887
+ const y = Math.min(...bounds.map(box => box.y)) - padding;
888
+ const width = Math.max(...bounds.map(box => box.x + box.width)) + padding - x;
889
+ const height = Math.max(...bounds.map(box => box.y + box.height)) + padding - y;
890
+ next.set(boundary.id, { tracks, world, endpointDistance: Math.min(...distances),
891
+ screen: { x: screen.x - left, y: screen.y - top }, bounds: { x, y, width, height } });
892
+ }
893
+ setPoints(next);
894
+ };
895
+ measure();
896
+ const observer = new MutationObserver(changes => {
897
+ if (changes.some(change => change.target === world || svg.contains(change.target))) measure();
898
+ });
899
+ observer.observe(world, { attributes: true, attributeFilter: ["style", "d"], childList: true, subtree: true });
900
+ return () => observer.disconnect();
901
+ }, [boundaries]);
902
+ const travel = (redo: boolean) => setHistory(state => {
903
+ if (redo) {
904
+ const [rows, ...future] = state.future;
905
+ return rows ? { past: [...state.past, state.rows], rows, future } : state;
906
+ }
907
+ const rows = state.past.at(-1);
908
+ return rows ? { past: state.past.slice(0, -1), rows, future: [state.rows, ...state.future] } : state;
909
+ });
910
+ const keyboard = (event: KeyboardEvent<HTMLElement>) => {
911
+ if (event.defaultPrevented || !(event.ctrlKey || event.metaKey) || event.altKey || event.key.toLowerCase() !== "z") return;
912
+ event.preventDefault();
913
+ travel(event.shiftKey);
914
+ };
915
+ const edit = (update: (rows: readonly Row[]) => readonly Row[]) => {
916
+ canvas.current?.querySelector<HTMLElement>("[data-slot='canvas']")?.focus({ preventScroll: true });
917
+ setHistory(state => {
918
+ const rows = update(state.rows);
919
+ return rows === state.rows ? state : { past: [...state.past.slice(-99), state.rows], rows, future: [] };
920
+ });
921
+ };
922
+ const insert = (boundary: Boundary) => {
923
+ const id = crypto.randomUUID();
924
+ edit(rows => {
925
+ const index = boundary.to.id === "end" ? rows.length : rows.findIndex(row => row.id === boundary.to.id);
926
+ if (index < 0 || (rows[index - 1]?.id ?? "start") !== boundary.from.id) return rows;
927
+ return [...rows.slice(0, index), { id, nodeIds: [id] }, ...rows.slice(index)];
928
+ });
929
+ };
930
+ const addBranch = (rowId: string, nodeId: string, side: Side) => {
931
+ const id = crypto.randomUUID();
932
+ edit(rows => {
933
+ const row = rows.find(item => item.id === rowId);
934
+ const neighbor = row?.nodeIds.indexOf(nodeId) ?? -1;
935
+ if (!row || neighbor < 0) return rows;
936
+ const index = neighbor + (side === "right" ? 1 : 0);
937
+ const nodeIds = [...row.nodeIds.slice(0, index), id, ...row.nodeIds.slice(index)];
938
+ return rows.map(item => item === row ? { ...row, nodeIds } : item);
939
+ });
940
+ };
941
+ return <div className={styles.editorExample} lang={ko ? "ko" : "en"} onKeyDown={keyboard}>
942
+ <div ref={canvas}>
943
+ <Canvas className={styles.workflowCanvas} nodes={nodes} edges={edges} fitInlineInset={branchGuideInset} readOnly viewportLocked labels={{
944
+ ...labels,
945
+ instructions: ko ? "줄 사이 버튼은 모든 갈래가 공유하는 단계를 추가해요. 같은 줄의 양끝이나 노드 사이 버튼은 분기를 추가해요."
946
+ : "The button between rows inserts a shared step. The buttons at either end of a row or between its nodes add branches.",
947
+ }}
948
+ onKeyDown={keyboard}
949
+ onPointerOver={event => setHoveredEdgeId(edgeAt(event.target))}
950
+ onPointerLeave={() => setHoveredEdgeId(null)}
951
+ onFocusCapture={event => setFocusedEdgeId(edgeAt(event.target))}
952
+ onBlurCapture={event => setFocusedEdgeId(edgeAt(event.relatedTarget))}
953
+ renderOverlay={({ hoveredNodeId, focusedNodeId, selection, portPosition }) => {
954
+ const selectedNodes = canvasNodeSelectionIds(selection);
955
+ const selectedEdges = canvasEdgeSelectionIds(selection);
956
+ const anchors = boundaries.map(boundary => {
957
+ const point = points.get(boundary.id);
958
+ if (!point) return null;
959
+ const { from, to, edgeIds } = boundary;
960
+ const shared = edgeIds.length > 1;
961
+ const target = names.get(to.nodeIds[0]) ?? text.end;
962
+ const title = from.nodeIds.length > 1 && to.nodeIds.length > 1 ? text.commonStep
963
+ : to.nodeIds.length > 1 ? text.beforeBranch
964
+ : from.nodeIds.length > 1 ? text.afterBranch
965
+ : text.insertBefore(target);
966
+ const label = shared && to.id !== "end" ? text.insertCommon(target) : title;
967
+ const appliesToNode = (id: string | null) => id !== null && (from.nodeIds.includes(id) || to.nodeIds.includes(id));
968
+ const appliesToEdge = (id: string | null) => id !== null && edgeIds.includes(id);
969
+ const hovered = appliesToNode(hoveredNodeId) || appliesToEdge(hoveredEdgeId);
970
+ return <GuideAnchor key={boundary.id} className={styles.workflowAction} mode={guideVisibility} at={point.screen}
971
+ hovered={hovered}
972
+ focused={hoveredNodeId === null && hoveredEdgeId === null && (appliesToNode(focusedNodeId) || appliesToEdge(focusedEdgeId))}
973
+ selected={selectedNodes.some(appliesToNode) || selectedEdges.some(appliesToEdge)} endpointDistance={point.endpointDistance}>
974
+ <InsertionCutout point={point} />
975
+ <IconButton size="md" variant="outline" className={styles.guideButton} icon={<Icon name="plus" />}
976
+ aria-label={label} title={title} onClick={() => insert(boundary)} />
977
+ </GuideAnchor>;
978
+ });
979
+ return <>
980
+ {anchors}
981
+ {history.rows.flatMap(row => {
982
+ const positions = row.nodeIds.flatMap(nodeId => {
983
+ const top = portPosition({ nodeId, side: "top" });
984
+ const bottom = portPosition({ nodeId, side: "bottom" });
985
+ if (!top || !bottom) return [];
986
+ const half = (bottom.y - top.y) / 2;
987
+ return [{ nodeId, x: top.x, y: top.y + half, half }];
988
+ });
989
+ if (positions.length !== row.nodeIds.length) return [];
990
+ const guides = positions.map((position, index) => ({ position, next: positions[index + 1], side: "right" as const }));
991
+ return [{ position: positions[0], next: undefined, side: "left" as const }, ...guides].map(({ position, next, side }) => {
992
+ const { nodeId, x, y, half } = position;
993
+ const at = { x: next ? (x + next.x) / 2 : x + (side === "left" ? -half : half), y };
994
+ const name = names.get(nodeId) ?? text.block;
995
+ const accessibleLabel = next ? text.addBetween(name, names.get(next.nodeId) ?? text.block) : text.addBranch(name, side);
996
+ const title = next ? text.between : text.addBranch(text.block, side);
997
+ const key = next ? `${nodeId}>${next.nodeId}:branch` : `${nodeId}:${side}`;
998
+ const appliesToNode = (id: string | null) => id === nodeId || id === next?.nodeId;
999
+ const hovered = appliesToNode(hoveredNodeId);
1000
+ return <GuideAnchor key={key} className={styles.workflowBranchAction} mode={guideVisibility} at={at}
1001
+ side={next ? undefined : side} endpointDistance={next ? (next.x - next.half - x - half) / 2 : undefined}
1002
+ hovered={hovered} focused={hoveredNodeId === null && hoveredEdgeId === null && appliesToNode(focusedNodeId)}
1003
+ selected={selectedNodes.some(appliesToNode)}
1004
+ retainHover={hoveredNodeId === null || hovered}>
1005
+ <IconButton size="md" variant="outline" className={styles.guideButton} icon={<Icon name="plus" />}
1006
+ aria-label={accessibleLabel} title={title} onClick={() => addBranch(row.id, nodeId, side)} />
1007
+ </GuideAnchor>;
1008
+ });
1009
+ })}
1010
+ </>;
1011
+ }}
1012
+ />
1013
+ </div>
1014
+ </div>;
1015
+ }
1016
+ ````