nudge-ui 0.2.2 → 0.2.4

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 (244) hide show
  1. package/README.md +164 -46
  2. package/dist/client.mjs +260 -61
  3. package/dist/css/value-semantics/colorSemantics.d.ts +4 -0
  4. package/dist/css/value-semantics/colorSemantics.js +17 -0
  5. package/dist/hosts/astro/astroRuntimeConfig.js +1 -0
  6. package/dist/hosts/astro/clientTransport.js +38 -32
  7. package/dist/hosts/astro/integration.js +5 -1
  8. package/dist/hosts/astro/markdownIdentity.d.ts +28 -0
  9. package/dist/hosts/astro/markdownIdentity.js +81 -0
  10. package/dist/hosts/next/manifest.js +1 -1
  11. package/dist/hosts/next/sidecar.js +5 -1
  12. package/dist/hosts/static/manifest.js +1 -1
  13. package/dist/hosts/static/server.js +3 -0
  14. package/dist/hosts/vite/vite.d.ts +3 -0
  15. package/dist/hosts/vite/vite.js +24 -4
  16. package/dist/inspector/agent/McpConnectionDialog.js +13 -19
  17. package/dist/inspector/agent/activity.d.ts +18 -0
  18. package/dist/inspector/agent/activity.js +70 -0
  19. package/dist/inspector/agent/client.d.ts +2 -0
  20. package/dist/inspector/agent/client.js +29 -1
  21. package/dist/inspector/agent/connectionStatus.js +1 -1
  22. package/dist/inspector/agent/httpTransport.js +9 -2
  23. package/dist/inspector/agent/protocol.d.ts +6 -3
  24. package/dist/inspector/agent/protocol.js +1 -1
  25. package/dist/inspector/agent/verification.d.ts +15 -7
  26. package/dist/inspector/agent/verification.js +113 -41
  27. package/dist/inspector/canvas/AgentActivityOverlay.d.ts +13 -0
  28. package/dist/inspector/canvas/AgentActivityOverlay.js +111 -0
  29. package/dist/inspector/canvas/CanvasCard.d.ts +9 -2
  30. package/dist/inspector/canvas/CanvasCard.js +135 -38
  31. package/dist/inspector/canvas/CanvasElementOverlay.js +166 -16
  32. package/dist/inspector/canvas/CanvasToolIcons.d.ts +10 -0
  33. package/dist/inspector/canvas/CanvasToolIcons.js +20 -0
  34. package/dist/inspector/canvas/CanvasToolbar.js +8 -4
  35. package/dist/inspector/canvas/CanvasWorkspace.js +270 -122
  36. package/dist/inspector/canvas/StaleChangeIndicator.js +3 -13
  37. package/dist/inspector/canvas/agentPresentation.d.ts +8 -8
  38. package/dist/inspector/canvas/agentPresentation.js +64 -52
  39. package/dist/inspector/canvas/canvasGestures.d.ts +1 -1
  40. package/dist/inspector/canvas/canvasGestures.js +1 -1
  41. package/dist/inspector/canvas/canvasStore.d.ts +46 -82
  42. package/dist/inspector/canvas/canvasStore.js +251 -284
  43. package/dist/inspector/canvas/frameContent.d.ts +21 -0
  44. package/dist/inspector/canvas/frameContent.js +44 -0
  45. package/dist/inspector/canvas/frameProtocol.d.ts +21 -4
  46. package/dist/inspector/canvas/frameProtocol.js +3 -3
  47. package/dist/inspector/canvas/frameScrollbarStyles.d.ts +3 -0
  48. package/dist/inspector/canvas/frameScrollbarStyles.js +21 -0
  49. package/dist/inspector/canvas/keyboardShortcuts.d.ts +3 -1
  50. package/dist/inspector/canvas/keyboardShortcuts.js +4 -4
  51. package/dist/inspector/canvas/layout.d.ts +52 -0
  52. package/dist/inspector/canvas/layout.js +106 -0
  53. package/dist/inspector/canvas/projection.d.ts +15 -5
  54. package/dist/inspector/canvas/projection.js +69 -13
  55. package/dist/inspector/canvas/rendererBootstrap.js +32 -4
  56. package/dist/inspector/canvas/rendererElementSelector.js +47 -6
  57. package/dist/inspector/canvas/rendererStylesheet.js +2 -2
  58. package/dist/inspector/canvas/resizeHandleScale.js +1 -1
  59. package/dist/inspector/canvas/sessionStore.d.ts +11 -26
  60. package/dist/inspector/canvas/sessionStore.js +43 -183
  61. package/dist/inspector/canvas/staleChangeDetector.js +9 -3
  62. package/dist/inspector/canvas/useCanvasLayoutAnimation.d.ts +5 -0
  63. package/dist/inspector/canvas/useCanvasLayoutAnimation.js +107 -0
  64. package/dist/inspector/canvas/viewStore.d.ts +38 -0
  65. package/dist/inspector/canvas/viewStore.js +104 -0
  66. package/dist/inspector/canvas/wheelPan.d.ts +8 -0
  67. package/dist/inspector/canvas/wheelPan.js +8 -0
  68. package/dist/inspector/changes/changesLog.d.ts +9 -6
  69. package/dist/inspector/changes/changesLog.js +48 -32
  70. package/dist/inspector/changes/codecs.d.ts +1 -0
  71. package/dist/inspector/changes/codecs.js +10 -1
  72. package/dist/inspector/changes/draftChanges.d.ts +58 -0
  73. package/dist/inspector/changes/draftChanges.js +304 -0
  74. package/dist/inspector/changes/editModel.d.ts +10 -0
  75. package/dist/inspector/changes/editModel.js +9 -2
  76. package/dist/inspector/changes/previewDiagnostics.d.ts +4 -2
  77. package/dist/inspector/changes/previewDiagnostics.js +11 -25
  78. package/dist/inspector/changes/types.d.ts +7 -0
  79. package/dist/inspector/clientManifest.d.ts +1 -1
  80. package/dist/inspector/comments/CommentsOverlay.d.ts +2 -0
  81. package/dist/inspector/comments/CommentsOverlay.js +250 -0
  82. package/dist/inspector/comments/element.d.ts +6 -0
  83. package/dist/inspector/comments/element.js +54 -0
  84. package/dist/inspector/comments/store.d.ts +29 -0
  85. package/dist/inspector/comments/store.js +121 -0
  86. package/dist/inspector/comments/verification.d.ts +5 -0
  87. package/dist/inspector/comments/verification.js +52 -0
  88. package/dist/inspector/componentSemantics/adapterRegistry.d.ts +6 -1
  89. package/dist/inspector/componentSemantics/adapterRegistry.js +23 -1
  90. package/dist/inspector/componentSemantics/reactRuntime.d.ts +2 -1
  91. package/dist/inspector/componentSemantics/reactRuntime.js +38 -0
  92. package/dist/inspector/componentSemantics/runtimeBridge.d.ts +4 -2
  93. package/dist/inspector/componentSemantics/runtimeBridge.js +17 -0
  94. package/dist/inspector/componentSemantics/types.d.ts +11 -0
  95. package/dist/inspector/drafts/model.d.ts +35 -0
  96. package/dist/inspector/drafts/model.js +45 -0
  97. package/dist/inspector/drafts/store.d.ts +28 -0
  98. package/dist/inspector/drafts/store.js +231 -0
  99. package/dist/inspector/index.js +20 -27
  100. package/dist/inspector/inline-text/inlineTextEditor.js +7 -0
  101. package/dist/inspector/inspection/useBrowserCssInspection.js +15 -1
  102. package/dist/inspector/iterations/capture.d.ts +2 -0
  103. package/dist/inspector/iterations/capture.js +174 -0
  104. package/dist/inspector/iterations/client.d.ts +7 -0
  105. package/dist/inspector/iterations/client.js +52 -0
  106. package/dist/inspector/iterations/coordinator.d.ts +15 -0
  107. package/dist/inspector/iterations/coordinator.js +130 -0
  108. package/dist/inspector/iterations/prompt.d.ts +3 -0
  109. package/dist/inspector/iterations/prompt.js +26 -0
  110. package/dist/inspector/overlay/DomNavigator.js +21 -15
  111. package/dist/inspector/overlay/interactionStyles.js +3 -1
  112. package/dist/inspector/overlay/spacingGestures.d.ts +13 -1
  113. package/dist/inspector/overlay/spacingGestures.js +82 -5
  114. package/dist/inspector/projection/{workspaceProjection.d.ts → draftProjection.d.ts} +6 -6
  115. package/dist/inspector/projection/{workspaceProjection.js → draftProjection.js} +4 -4
  116. package/dist/inspector/projection/renderedInstance.d.ts +17 -3
  117. package/dist/inspector/projection/renderedInstance.js +62 -11
  118. package/dist/inspector/projection/structuralProjection.d.ts +2 -1
  119. package/dist/inspector/projection/structuralProjection.js +21 -17
  120. package/dist/inspector/projection/textProjection.d.ts +2 -1
  121. package/dist/inspector/projection/textProjection.js +64 -15
  122. package/dist/inspector/prompt/PromptSettingsDialog.js +1 -5
  123. package/dist/inspector/prompt/clipboardHandoff.d.ts +15 -18
  124. package/dist/inspector/prompt/clipboardHandoff.js +97 -143
  125. package/dist/inspector/prompt/generatePrompt.d.ts +4 -1
  126. package/dist/inspector/prompt/generatePrompt.js +22 -17
  127. package/dist/inspector/runtime/runtimeConfig.d.ts +9 -0
  128. package/dist/inspector/runtime/runtimeConfig.js +24 -0
  129. package/dist/inspector/selection/sourceSite.d.ts +12 -0
  130. package/dist/inspector/selection/sourceSite.js +28 -0
  131. package/dist/inspector/settings/SettingsDialog.js +21 -8
  132. package/dist/inspector/shell/AgentStatusButton.d.ts +11 -0
  133. package/dist/inspector/shell/AgentStatusButton.js +36 -0
  134. package/dist/inspector/shell/AppShell.js +4 -2
  135. package/dist/inspector/shell/ChangesLog.js +46 -26
  136. package/dist/inspector/shell/CopyPromptButton.js +184 -93
  137. package/dist/inspector/shell/EmptyState.js +9 -8
  138. package/dist/inspector/shell/InspectorShell.js +13 -21
  139. package/dist/inspector/shell/PeekOriginalButton.js +24 -23
  140. package/dist/inspector/shell/originalPreview.js +5 -5
  141. package/dist/inspector/shell/shortcuts.d.ts +3 -0
  142. package/dist/inspector/shell/shortcuts.js +11 -0
  143. package/dist/inspector/sketch/SketchEditor.js +14 -14
  144. package/dist/inspector/sketch/SketchEntryButton.js +1 -1
  145. package/dist/inspector/sketch/SketchFrameOverlay.d.ts +3 -1
  146. package/dist/inspector/sketch/SketchFrameOverlay.js +11 -8
  147. package/dist/inspector/sketch/SketchLayersPanel.js +13 -5
  148. package/dist/inspector/sketch/SketchOverlay.js +7 -7
  149. package/dist/inspector/sketch/SketchWorkspace.js +18 -12
  150. package/dist/inspector/sketch/interaction.d.ts +1 -0
  151. package/dist/inspector/sketch/interaction.js +8 -4
  152. package/dist/inspector/sketch/model.d.ts +5 -0
  153. package/dist/inspector/sketch/model.js +6 -2
  154. package/dist/inspector/sketch/raster.d.ts +1 -2
  155. package/dist/inspector/sketch/raster.js +68 -4
  156. package/dist/inspector/styleEditors/BackgroundEditor.d.ts +4 -0
  157. package/dist/inspector/styleEditors/BackgroundEditor.js +195 -0
  158. package/dist/inspector/styleEditors/BorderEditor.js +49 -78
  159. package/dist/inspector/styleEditors/BorderRadiusEditor.js +6 -1
  160. package/dist/inspector/styleEditors/BoxShadowEditor.d.ts +1 -2
  161. package/dist/inspector/styleEditors/BoxShadowEditor.js +132 -4
  162. package/dist/inspector/styleEditors/ColorPicker.d.ts +5 -1
  163. package/dist/inspector/styleEditors/ColorPicker.js +10 -4
  164. package/dist/inspector/styleEditors/GapField.js +3 -5
  165. package/dist/inspector/styleEditors/GridChildSection.d.ts +1 -1
  166. package/dist/inspector/styleEditors/GridChildSection.js +18 -9
  167. package/dist/inspector/styleEditors/GridPicker.d.ts +1 -1
  168. package/dist/inspector/styleEditors/GridPicker.js +8 -2
  169. package/dist/inspector/styleEditors/GridSection.js +1 -1
  170. package/dist/inspector/styleEditors/GridValueField.js +19 -14
  171. package/dist/inspector/styleEditors/ImageBackgroundEditor.d.ts +18 -0
  172. package/dist/inspector/styleEditors/ImageBackgroundEditor.js +118 -0
  173. package/dist/inspector/styleEditors/LayoutBlockedIndicator.d.ts +2 -2
  174. package/dist/inspector/styleEditors/LayoutBlockedIndicator.js +3 -3
  175. package/dist/inspector/styleEditors/LayoutComboField.js +6 -4
  176. package/dist/inspector/styleEditors/LayoutDropdown.js +6 -3
  177. package/dist/inspector/styleEditors/LayoutSection.js +32 -11
  178. package/dist/inspector/styleEditors/SpacingBox.js +7 -5
  179. package/dist/inspector/styleEditors/Typography.js +11 -3
  180. package/dist/inspector/styleEditors/backgroundLayers.d.ts +24 -0
  181. package/dist/inspector/styleEditors/backgroundLayers.js +51 -0
  182. package/dist/inspector/styleEditors/gradientValue.d.ts +17 -0
  183. package/dist/inspector/styleEditors/gradientValue.js +114 -0
  184. package/dist/inspector/styleEditors/inlineAuthored.d.ts +10 -0
  185. package/dist/inspector/styleEditors/inlineAuthored.js +114 -0
  186. package/dist/inspector/styleEditors/layoutValue.d.ts +0 -8
  187. package/dist/inspector/styleEditors/layoutValue.js +0 -42
  188. package/dist/inspector/styleEditors/nudgeValue.d.ts +2 -2
  189. package/dist/inspector/styleEditors/nudgeValue.js +36 -8
  190. package/dist/inspector/tokens/TokenField.d.ts +7 -0
  191. package/dist/inspector/tokens/TokenField.js +35 -25
  192. package/dist/inspector/tokens/TokenLabel.js +5 -14
  193. package/dist/inspector/tokens/editActions.d.ts +1 -1
  194. package/dist/inspector/tokens/editActions.js +7 -1
  195. package/dist/inspector/ui/AtRuleContext.js +4 -6
  196. package/dist/inspector/ui/Button.d.ts +6 -2
  197. package/dist/inspector/ui/Button.js +4 -3
  198. package/dist/inspector/ui/ControlSurface.d.ts +2 -2
  199. package/dist/inspector/ui/ControlSurface.js +4 -3
  200. package/dist/inspector/ui/InlineStyleWarning.d.ts +11 -0
  201. package/dist/inspector/ui/InlineStyleWarning.js +13 -0
  202. package/dist/inspector/ui/InspectorPopover.d.ts +2 -1
  203. package/dist/inspector/ui/InspectorPopover.js +4 -5
  204. package/dist/inspector/ui/PopoverListbox.d.ts +2 -1
  205. package/dist/inspector/ui/PopoverListbox.js +8 -7
  206. package/dist/inspector/ui/SegmentedControl.d.ts +2 -1
  207. package/dist/inspector/ui/SegmentedControl.js +2 -2
  208. package/dist/inspector/ui/Select.d.ts +6 -1
  209. package/dist/inspector/ui/Select.js +7 -11
  210. package/dist/inspector/ui/SideValuesField.js +1 -1
  211. package/dist/inspector/ui/Tooltip.d.ts +26 -0
  212. package/dist/inspector/ui/Tooltip.js +32 -0
  213. package/dist/inspector/ui/classNames.d.ts +2 -0
  214. package/dist/inspector/ui/classNames.js +4 -0
  215. package/dist/inspector/ui/customCursors.d.ts +23 -0
  216. package/dist/inspector/ui/customCursors.js +122 -0
  217. package/dist/inspector/ui/dragCursor.d.ts +0 -2
  218. package/dist/inspector/ui/dragCursor.js +2 -10
  219. package/dist/inspector/ui/portalContainer.d.ts +2 -0
  220. package/dist/inspector/ui/portalContainer.js +6 -0
  221. package/dist/inspector/ui/styles.js +29 -21
  222. package/dist/inspector/workspace/commands.d.ts +9 -0
  223. package/dist/inspector/workspace/commands.js +82 -0
  224. package/dist/inspector/workspace/controller.d.ts +4 -0
  225. package/dist/inspector/workspace/controller.js +66 -0
  226. package/dist/inspector/workspace/handoff.d.ts +42 -0
  227. package/dist/inspector/workspace/handoff.js +115 -0
  228. package/dist/inspector/workspace/sentItems.d.ts +19 -0
  229. package/dist/inspector/workspace/sentItems.js +51 -0
  230. package/dist/inspector/workspace/timeline.d.ts +30 -0
  231. package/dist/inspector/workspace/timeline.js +108 -0
  232. package/dist/internal/agent-protocol.d.ts +19 -2
  233. package/dist/internal/agent-protocol.js +13 -0
  234. package/dist/nudge-ui.mjs +558 -311
  235. package/dist/project/artifacts.d.ts +13 -0
  236. package/dist/project/artifacts.js +253 -0
  237. package/dist/transport/artifacts.d.ts +8 -0
  238. package/dist/transport/artifacts.js +9 -0
  239. package/dist/transport/editor.js +3 -1
  240. package/dist/transport/routes.d.ts +2 -0
  241. package/dist/transport/routes.js +2 -0
  242. package/package.json +7 -3
  243. package/dist/inspector/changes/workspaceChanges.d.ts +0 -47
  244. package/dist/inspector/changes/workspaceChanges.js +0 -265
@@ -1,3 +1,4 @@
1
+ import { startWorkspaceController } from "./workspace/controller.js";
1
2
  import { createElement } from "react";
2
3
  import { createRoot } from "react-dom/client";
3
4
  import { InspectorShell, toggleInspector, setInspectorOpen } from "./shell/InspectorShell.js";
@@ -8,20 +9,19 @@ import { isCanvasRenderer } from "./canvas/roleDetection.js";
8
9
  import { isKeyboardShortcutMessage } from "./canvas/frameProtocol.js";
9
10
  import { subscribeCanvasRendererMessages } from "./canvas/rendererMessageRouter.js";
10
11
  import { bootstrapRenderer } from "./canvas/rendererBootstrap.js";
11
- import { hydrateSession, enableAutoSave, scheduleAutoSave, scheduleCanvasSave, setRestoreCount, } from "./canvas/sessionStore.js";
12
- import { subscribeChanges, getChangesList } from "./changes/changesLog.js";
13
- import { subscribe as subscribeCanvas } from "./canvas/canvasStore.js";
14
- import { acquireLease, enableWriteGuard, hasWriteLease, releaseLease, subscribeOwnership, } from "./canvas/workspaceLease.js";
12
+ import { setRestoreCount, } from "./canvas/sessionStore.js";
13
+ import { getChangesList } from "./changes/changesLog.js";
14
+ import { acquireLease, enableWriteGuard, hasWriteLease, subscribeOwnership, } from "./canvas/workspaceLease.js";
15
15
  import { cancelStaleDetection, startStaleDetection } from "./canvas/staleChangeDetector.js";
16
16
  import { LockedWorkspaceNotice } from "./canvas/LockedWorkspaceNotice.js";
17
17
  import { AppShell } from "./shell/AppShell.js";
18
18
  import { installInspectionBridge } from "./inspection/bridge.js";
19
- import { releaseDocumentProjection, subscribeStructuralChanges } from "./projection/structuralProjection.js";
19
+ import { releaseDocumentProjection, getStructuralChanges } from "./projection/structuralProjection.js";
20
20
  import { cancelInlineTextEdit } from "./inline-text/inlineTextEditor.js";
21
21
  import { configureNudgeUiRuntime, getNudgeUiRuntimeConfig, isDemoRuntime } from "./runtime/runtimeConfig.js";
22
- import { setCanvasMode } from "./canvas/canvasStore.js";
22
+ import { setCanvasMode } from "./canvas/viewStore.js";
23
23
  import { isNudgeUiDev, setNudgeUiHostDevFlag } from "./runtime/devFlag.js";
24
- import { clearClipboardHandoff, subscribeClipboardHandoff, } from "./prompt/clipboardHandoff.js";
24
+ import { clearClipboardHandoff, } from "./prompt/clipboardHandoff.js";
25
25
  import { createWorkspace, InspectorSessionProvider, } from "./session/index.js";
26
26
  import { clearSketchClipboardHandoff } from "./sketch/handoff.js";
27
27
  import { cancelSketchInteraction, isSketchInteractionActive } from "./sketch/interaction.js";
@@ -34,8 +34,7 @@ let lockedRoot = null;
34
34
  const workspace = createWorkspace();
35
35
  let inspectorSession = null;
36
36
  let rendererBootstrapHandle = null;
37
- let beforeUnloadAttached = false;
38
- let persistenceSubscribed = false;
37
+ let workspaceController = null;
39
38
  let unsubscribeOwnership = null;
40
39
  let removeInspectionBridge = null;
41
40
  let keyboardPeekHeld = false;
@@ -105,6 +104,8 @@ export function bootstrapNudgeUi(inspectorHost) {
105
104
  // The public demo shares the iframe editor while keeping the write lease,
106
105
  // persistence, and agent bridge disabled.
107
106
  setCanvasMode("canvas");
107
+ workspaceController?.dispose();
108
+ workspaceController = startWorkspaceController();
108
109
  mountInspector(inspectorHost);
109
110
  setInspectorOpen(false);
110
111
  return;
@@ -142,12 +143,17 @@ function startController(inspectorHost) {
142
143
  void initializeSketchStore(getNudgeUiRuntimeConfig().projectId).catch(() => undefined);
143
144
  unsubscribeOwnership?.();
144
145
  unsubscribeOwnership = subscribeOwnership((hasLease) => {
145
- if (!hasLease)
146
+ if (!hasLease) {
147
+ workspaceController?.dispose();
148
+ workspaceController = null;
146
149
  mountLockedNotice(inspectorHost);
150
+ }
147
151
  });
148
- const result = hydrateSession();
152
+ workspaceController?.dispose();
153
+ const result = startWorkspaceController();
154
+ workspaceController = result;
149
155
  if (result.restored) {
150
- setRestoreCount(result.changeCount);
156
+ setRestoreCount(getChangesList().length + getStructuralChanges().length);
151
157
  const restored = getChangesList();
152
158
  if (restored.length > 0) {
153
159
  startStaleDetection(restored);
@@ -159,21 +165,6 @@ function startController(inspectorHost) {
159
165
  setCanvasMode("canvas");
160
166
  }
161
167
  mountInspector(inspectorHost);
162
- enableAutoSave();
163
- if (!beforeUnloadAttached) {
164
- // enableAutoSave registers its flush listener first. Release the lease only
165
- // after the pending session write has had a chance to pass the ownership
166
- // gate during beforeunload.
167
- window.addEventListener("beforeunload", releaseLease);
168
- beforeUnloadAttached = true;
169
- }
170
- if (!persistenceSubscribed) {
171
- subscribeChanges(() => scheduleAutoSave());
172
- subscribeStructuralChanges(() => scheduleAutoSave());
173
- subscribeClipboardHandoff(() => scheduleAutoSave());
174
- subscribeCanvas(() => scheduleCanvasSave());
175
- persistenceSubscribed = true;
176
- }
177
168
  }
178
169
  function mountLockedNotice(host) {
179
170
  if (reactRoot) {
@@ -239,6 +230,8 @@ export function mountInspector(host) {
239
230
  export function unmountInspector() {
240
231
  rendererBootstrapHandle?.teardown();
241
232
  rendererBootstrapHandle = null;
233
+ workspaceController?.dispose();
234
+ workspaceController = null;
242
235
  unsubscribeOwnership?.();
243
236
  unsubscribeOwnership = null;
244
237
  if (lockedRoot) {
@@ -1,3 +1,4 @@
1
+ import { canEditDraft } from "../changes/draftChanges.js";
1
2
  import { useSyncExternalStore } from "react";
2
3
  import { appendChange } from "../changes/changesLog.js";
3
4
  import { registerInlineTextClearHandler } from "./inlineTextLifecycle.js";
@@ -1029,6 +1030,9 @@ export const inlineTextEditor = {
1029
1030
  /** Re-enter an existing canonical rendered-text projection through its empty
1030
1031
  * inspector affordance. This never guesses a new DOM target or source node. */
1031
1032
  export function beginInlineTextEditFromEmptyProjection(marker) {
1033
+ if (!canEditDraft()) {
1034
+ return { kind: "rejected", reason: "editing-active", message: "Wait for the iteration to finish saving before editing text." };
1035
+ }
1032
1036
  if (!isNudgeUiDev()) {
1033
1037
  return {
1034
1038
  kind: "rejected",
@@ -1063,6 +1067,9 @@ export function beginInlineTextEditFromEmptyProjection(marker) {
1063
1067
  }
1064
1068
  }
1065
1069
  export function beginInlineTextEdit(element, point) {
1070
+ if (!canEditDraft()) {
1071
+ return { kind: "rejected", reason: "editing-active", message: "Wait for the iteration to finish saving before editing text." };
1072
+ }
1066
1073
  if (!isNudgeUiDev()) {
1067
1074
  return {
1068
1075
  kind: "rejected",
@@ -5,6 +5,12 @@ const EMPTY_SELECTION = [];
5
5
  function isSelectedElementList(selected) {
6
6
  return Array.isArray(selected);
7
7
  }
8
+ const EMPTY_VIEW = {
9
+ element: null,
10
+ elements: [],
11
+ stableProperties: [],
12
+ documentTokens: null,
13
+ };
8
14
  function normalizeSelection(selected) {
9
15
  if (!selected)
10
16
  return EMPTY_SELECTION;
@@ -22,6 +28,9 @@ function inspectStableView(session, selected, state, includeDocumentTokens, elem
22
28
  : [];
23
29
  const documentTokens = includeDocumentTokens ? session.inspectTokens() : null;
24
30
  return {
31
+ selection: selected,
32
+ state,
33
+ session,
25
34
  element: primary,
26
35
  elements,
27
36
  stableProperties,
@@ -155,5 +164,10 @@ export function useBrowserCssInspection(selected, state = "base", options = {})
155
164
  const timeoutId = setTimeout(warm, 200);
156
165
  return () => clearTimeout(timeoutId);
157
166
  }, [session, selectedDocument]);
158
- return view;
167
+ // Selection effects run after children render. Never expose the previous
168
+ // element's authored rows while the new selection is waiting for inspection.
169
+ const matchesSelection = view.session === session && view.state === state
170
+ && view.selection.length === selectedElements.length
171
+ && view.selection.every((element, index) => element.domElement === selectedElements[index]?.domElement);
172
+ return matchesSelection ? view : EMPTY_VIEW;
159
173
  }
@@ -0,0 +1,2 @@
1
+ /** Captures the visible DOM of a same-origin frame as a script-free HTML iteration. */
2
+ export declare function captureHtmlIteration(frame: HTMLIFrameElement): Promise<string>;
@@ -0,0 +1,174 @@
1
+ import { HTML_ARTIFACT_REVISION_ATTRIBUTE } from "../../transport/artifacts.js";
2
+ import { FRAME_SCROLLBAR_STYLE_ID } from "../canvas/frameScrollbarStyles.js";
3
+ /** Captures the visible DOM of a same-origin frame as a script-free HTML iteration. */
4
+ export async function captureHtmlIteration(frame) {
5
+ const source = frame.contentDocument;
6
+ const view = frame.contentWindow;
7
+ if (!source || !view?.document.documentElement)
8
+ throw new Error("The frame is not ready to capture.");
9
+ await source.fonts?.ready;
10
+ await Promise.all([...source.images].map((image) => image.decode?.().catch(() => undefined)));
11
+ const original = source.documentElement;
12
+ const copy = original.cloneNode(true);
13
+ copy.removeAttribute(HTML_ARTIFACT_REVISION_ATTRIBUTE);
14
+ const sourceElements = [original, ...original.querySelectorAll("*")];
15
+ const copiedElements = [copy, ...copy.querySelectorAll("*")];
16
+ const assets = new Map();
17
+ for (let index = 0; index < sourceElements.length; index += 1) {
18
+ const sourceElement = sourceElements[index];
19
+ const copied = copiedElements[index];
20
+ if (sourceElement.nodeType !== 1 || copied.nodeType !== 1)
21
+ continue;
22
+ // Renderer IDs belong to the source iframe's node registry. The iteration's
23
+ // fresh registry can reuse those values for different nodes.
24
+ copied.removeAttribute("data-renderer-id");
25
+ // Preserve authored inline values (percentages, variables, and calc), rather
26
+ // than replacing them with computed dimensions at the capture viewport.
27
+ const inline = copied.getAttribute("style");
28
+ if (inline)
29
+ copied.setAttribute("style", await resolveCssUrls(inline, source.baseURI, assets));
30
+ if (sourceElement.tagName === "INPUT" && copied.tagName === "INPUT") {
31
+ const input = sourceElement;
32
+ copied.setAttribute("value", input.value);
33
+ if (input.checked)
34
+ copied.setAttribute("checked", "");
35
+ else
36
+ copied.removeAttribute("checked");
37
+ }
38
+ if (sourceElement.tagName === "TEXTAREA" && copied.tagName === "TEXTAREA")
39
+ copied.textContent = sourceElement.value;
40
+ if (sourceElement.tagName === "CANVAS" && copied.tagName === "CANVAS") {
41
+ try {
42
+ const image = source.createElement("img");
43
+ image.src = sourceElement.toDataURL();
44
+ for (const attribute of [...copied.attributes])
45
+ image.setAttribute(attribute.name, attribute.value);
46
+ copied.replaceWith(image);
47
+ }
48
+ catch { /* Tainted canvases remain empty. */ }
49
+ }
50
+ }
51
+ const base = source.createElement("base");
52
+ base.href = source.querySelector("base")?.href ?? source.location.href;
53
+ copy.querySelectorAll("base").forEach((element) => element.remove());
54
+ (copy.querySelector("head") ?? copy).prepend(base);
55
+ copy.querySelectorAll('script, iframe, object, embed, meta[http-equiv="refresh"], meta[http-equiv="Content-Security-Policy"], link[rel=modulepreload], link[rel=preload]').forEach((element) => element.remove());
56
+ copy.querySelectorAll(`[data-nudge-ui-mount], #nudge-ui-root, #${FRAME_SCROLLBAR_STYLE_ID}`).forEach((element) => element.remove());
57
+ copy.querySelectorAll("a, form").forEach((element) => {
58
+ element.removeAttribute("href");
59
+ element.removeAttribute("action");
60
+ });
61
+ copy.querySelectorAll("*").forEach((element) => {
62
+ for (const attribute of [...element.attributes]) {
63
+ if (/^on/i.test(attribute.name))
64
+ element.removeAttribute(attribute.name);
65
+ }
66
+ });
67
+ for (const image of copy.querySelectorAll("img")) {
68
+ const url = image.getAttribute("src");
69
+ if (url)
70
+ image.src = await inlineAsset(url, base.href, assets);
71
+ }
72
+ await captureStylesheets(source, copy, sourceElements, copiedElements, assets);
73
+ return `<!doctype html>\n${copy.outerHTML}`;
74
+ }
75
+ /** Copies live CSSOM rules in place so stylesheet order and media stay intact. */
76
+ async function captureStylesheets(document, copy, sourceElements, copiedElements, assets) {
77
+ for (const sheet of [...document.styleSheets]) {
78
+ const owner = sheet.ownerNode;
79
+ // Some DOM implementations do not expose ownerNode.
80
+ const sourceNode = owner ?? sourceElements.find((element) => "sheet" in element && element.sheet === sheet);
81
+ const index = sourceNode ? sourceElements.indexOf(sourceNode) : -1;
82
+ const copiedNode = index >= 0 ? copiedElements[index] : undefined;
83
+ if (!copiedNode?.parentNode)
84
+ continue;
85
+ if (sheet.disabled) {
86
+ copiedNode.remove();
87
+ continue;
88
+ }
89
+ let css;
90
+ try {
91
+ css = [...sheet.cssRules].map((rule) => rule.cssText).join("\n");
92
+ }
93
+ catch {
94
+ if (!sheet.href)
95
+ continue;
96
+ try {
97
+ const response = await fetch(sheet.href);
98
+ if (!response.ok)
99
+ continue;
100
+ css = await response.text();
101
+ }
102
+ catch {
103
+ // Keep the stylesheet link when CORS prevents embedding it. Its URL
104
+ // still resolves against the original base and retains responsiveness.
105
+ continue;
106
+ }
107
+ }
108
+ const style = document.createElement("style");
109
+ for (const attribute of [...copiedNode.attributes]) {
110
+ if (!["href", "rel", "integrity", "crossorigin"].includes(attribute.name)) {
111
+ style.setAttribute(attribute.name, attribute.value);
112
+ }
113
+ }
114
+ style.textContent = await resolveCssUrls(css, sheet.href ?? document.baseURI, assets);
115
+ // Captured edits become the iteration's base. The renderer must create its own
116
+ // managed stylesheet for new edits instead of clearing these captured rules.
117
+ if (style.id === "nudge-ui-styles") {
118
+ style.removeAttribute("id");
119
+ style.removeAttribute("data-nudge-ui");
120
+ style.setAttribute("data-nudge-capture-overrides", "");
121
+ }
122
+ copiedNode.replaceWith(style);
123
+ }
124
+ for (const sheet of document.adoptedStyleSheets ?? []) {
125
+ if (sheet.disabled)
126
+ continue;
127
+ const style = document.createElement("style");
128
+ style.textContent = await resolveCssUrls([...sheet.cssRules].map((rule) => rule.cssText).join("\n"), document.baseURI, assets);
129
+ (copy.querySelector("head") ?? copy).append(style);
130
+ }
131
+ }
132
+ async function resolveCssUrls(css, base, assets) {
133
+ const matches = [...css.matchAll(/url\(\s*(["']?)([^)"']+)\1\s*\)/g)];
134
+ const values = await Promise.all(matches.map((match) => inlineAsset(match[2], base, assets)));
135
+ let index = 0;
136
+ return css.replace(/url\(\s*(["']?)([^)"']+)\1\s*\)/g, () => `url("${values[index++]}")`);
137
+ }
138
+ async function inlineAsset(path, base, assets) {
139
+ if (path.trim().startsWith("#"))
140
+ return path;
141
+ let url;
142
+ try {
143
+ url = new URL(path, base).href;
144
+ }
145
+ catch {
146
+ return path;
147
+ }
148
+ if (!/^https?:/.test(url))
149
+ return url;
150
+ const existing = assets.get(url);
151
+ if (existing)
152
+ return existing;
153
+ const value = (async () => {
154
+ try {
155
+ const response = await fetch(url);
156
+ if (!response.ok || Number(response.headers.get("content-length")) > 4_000_000)
157
+ return url;
158
+ const blob = await response.blob();
159
+ if (blob.size > 4_000_000)
160
+ return url;
161
+ const bytes = new Uint8Array(await blob.arrayBuffer());
162
+ let binary = "";
163
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
164
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
165
+ }
166
+ return `data:${blob.type || "application/octet-stream"};base64,${btoa(binary)}`;
167
+ }
168
+ catch {
169
+ return url;
170
+ }
171
+ })();
172
+ assets.set(url, value);
173
+ return value;
174
+ }
@@ -0,0 +1,7 @@
1
+ import { type HtmlArtifactRevision } from "../../transport/artifacts.js";
2
+ export declare function artifactDocumentUrl(id: string): string;
3
+ export declare function readHtmlArtifactRevision(id: string): Promise<HtmlArtifactRevision>;
4
+ /** Checks the editing base before saving and promoting a captured document. */
5
+ export declare function commitHtmlArtifact(id: string, expected: HtmlArtifactRevision, html?: string): Promise<HtmlArtifactRevision>;
6
+ export declare function createHtmlArtifact(frame: HTMLIFrameElement, sourceUrl: string, title: string, capturedHtml?: string): Promise<string>;
7
+ export declare function removeHtmlArtifact(id: string): Promise<void>;
@@ -0,0 +1,52 @@
1
+ import { isHtmlArtifactRevision, HTML_ITERATION_CONFLICT } from "../../transport/artifacts.js";
2
+ import { NUDGE_UI_ARTIFACTS_PATH } from "../../transport/routes.js";
3
+ import { captureHtmlIteration } from "./capture.js";
4
+ export function artifactDocumentUrl(id) {
5
+ return `${NUDGE_UI_ARTIFACTS_PATH}/${id}/preview`;
6
+ }
7
+ export async function readHtmlArtifactRevision(id) {
8
+ const response = await fetch(`${NUDGE_UI_ARTIFACTS_PATH}/${id}/revision`, { cache: "no-store", signal: AbortSignal.timeout(10000) });
9
+ if (!response.ok)
10
+ throw new Error("The HTML iteration could not be refreshed.");
11
+ const revision = await response.json();
12
+ if (!isHtmlArtifactRevision(revision))
13
+ throw new Error("The HTML iteration returned an invalid revision.");
14
+ return revision;
15
+ }
16
+ /** Checks the editing base before saving and promoting a captured document. */
17
+ export async function commitHtmlArtifact(id, expected, html) {
18
+ const response = await fetch(`${NUDGE_UI_ARTIFACTS_PATH}/${id}/commit`, {
19
+ method: "POST",
20
+ signal: AbortSignal.timeout(10000),
21
+ headers: { "content-type": "application/json" },
22
+ body: JSON.stringify({ expected, ...(html === undefined ? {} : { html }) }),
23
+ });
24
+ if (response.status === 409)
25
+ throw new Error(HTML_ITERATION_CONFLICT);
26
+ if (!response.ok)
27
+ throw new Error((await response.text()) || "The HTML iteration could not be saved.");
28
+ const revision = await response.json();
29
+ if (!isHtmlArtifactRevision(revision))
30
+ throw new Error("The HTML iteration returned an invalid revision.");
31
+ return revision;
32
+ }
33
+ export async function createHtmlArtifact(frame, sourceUrl, title, capturedHtml) {
34
+ const id = crypto.randomUUID();
35
+ const html = capturedHtml ?? await captureHtmlIteration(frame);
36
+ const response = await fetch(NUDGE_UI_ARTIFACTS_PATH, {
37
+ method: "POST",
38
+ headers: { "content-type": "application/json" },
39
+ body: JSON.stringify({
40
+ id, html, sourceUrl, title,
41
+ viewport: { width: frame.clientWidth, height: frame.clientHeight },
42
+ }),
43
+ });
44
+ if (!response.ok)
45
+ throw new Error((await response.text()) || "The HTML iteration could not be saved.");
46
+ return id;
47
+ }
48
+ export async function removeHtmlArtifact(id) {
49
+ const response = await fetch(`${NUDGE_UI_ARTIFACTS_PATH}/${id}`, { method: "DELETE", keepalive: true });
50
+ if (!response.ok)
51
+ throw new Error((await response.text()) || "The HTML iteration could not be removed.");
52
+ }
@@ -0,0 +1,15 @@
1
+ import type { HtmlArtifactRevision } from "../../transport/artifacts.js";
2
+ import { type DraftContents } from "../changes/draftChanges.js";
3
+ /** Owned transport; tests use a working in-memory artifact store. */
4
+ export interface HtmlIterationStorage {
5
+ readRevision(id: string): Promise<HtmlArtifactRevision>;
6
+ commit(id: string, expected: HtmlArtifactRevision, html?: string): Promise<HtmlArtifactRevision>;
7
+ }
8
+ /** Owns save ordering, draft settlement, and external document promotion. */
9
+ export declare function createHtmlIterationCoordinator(storage: HtmlIterationStorage): {
10
+ prepare(cardId: string, artifactId: string, baseRevision: string, capture: () => Promise<string>): Promise<DraftContents>;
11
+ refresh(cardId: string, artifactId: string, baseRevision: string, available: () => boolean): Promise<boolean>;
12
+ };
13
+ /** Materializes pending intent before the agent can start editing document.html. */
14
+ export declare function prepareHtmlIterationHandoff(cardId: string, artifactId: string, frame: HTMLIFrameElement): Promise<DraftContents>;
15
+ export declare function refreshHtmlIteration(cardId: string, artifactId: string, frame: HTMLIFrameElement): Promise<boolean>;
@@ -0,0 +1,130 @@
1
+ import { HTML_ARTIFACT_REVISION_ATTRIBUTE } from "../../transport/artifacts.js";
2
+ import { getDraftForCard, getDraftContentsForCard, clearSavedIterationDraft } from "../drafts/store.js";
3
+ import { lockDraft } from "../changes/draftChanges.js";
4
+ import { canWriteWorkspace } from "../canvas/workspaceLease.js";
5
+ import { projectDraftToDocument, isCanvasProjectionRevisionCurrent, projectToAllReadyCards } from "../canvas/projection.js";
6
+ import { isInlineTextEditingActive } from "../inline-text/inlineTextEditor.js";
7
+ import { captureHtmlIteration } from "./capture.js";
8
+ import { artifactDocumentUrl, commitHtmlArtifact, readHtmlArtifactRevision } from "./client.js";
9
+ /** Owns save ordering, draft settlement, and external document promotion. */
10
+ export function createHtmlIterationCoordinator(storage) {
11
+ const operations = new Map();
12
+ async function serialize(id, operation) {
13
+ const previous = operations.get(id) ?? Promise.resolve();
14
+ const pending = previous.catch(() => undefined).then(operation);
15
+ operations.set(id, pending);
16
+ try {
17
+ return await pending;
18
+ }
19
+ finally {
20
+ if (operations.get(id) === pending)
21
+ operations.delete(id);
22
+ }
23
+ }
24
+ return {
25
+ prepare(cardId, artifactId, baseRevision, capture) {
26
+ return serialize(artifactId, async () => {
27
+ if (!canWriteWorkspace())
28
+ throw new Error("This workspace is open in another tab.");
29
+ const draft = getDraftForCard(cardId);
30
+ const workspace = getDraftContentsForCard(cardId);
31
+ if (!draft || draft.target.kind !== "html" || draft.target.artifactId !== artifactId || !workspace)
32
+ throw new Error("The iteration draft is no longer available.");
33
+ const html = await capture();
34
+ const current = getDraftForCard(cardId);
35
+ if (current?.id !== draft.id || current.revision !== draft.revision) {
36
+ throw new Error("The iteration changed while saving. Your edits are still pending. Try again.");
37
+ }
38
+ const release = lockDraft(draft.id);
39
+ try {
40
+ if (!canWriteWorkspace())
41
+ throw new Error("This workspace is open in another tab.");
42
+ await storage.commit(artifactId, { document: baseRevision, preview: baseRevision }, html);
43
+ if (!canWriteWorkspace())
44
+ throw new Error("The iteration was saved. Reopen the active workspace to continue.");
45
+ }
46
+ finally {
47
+ release();
48
+ }
49
+ // No await between releasing the lock and settling this exact revision.
50
+ if (!clearSavedIterationDraft(cardId, draft.revision)) {
51
+ throw new Error("The iteration was saved, but its newer edits remain pending.");
52
+ }
53
+ return workspace;
54
+ });
55
+ },
56
+ refresh(cardId, artifactId, baseRevision, available) {
57
+ return serialize(artifactId, async () => {
58
+ const clean = () => {
59
+ const workspace = getDraftContentsForCard(cardId);
60
+ return canWriteWorkspace() && available() && workspace !== null
61
+ && workspace.changes.length === 0 && workspace.structuralChanges.length === 0;
62
+ };
63
+ if (!clean())
64
+ return false;
65
+ const revision = await storage.readRevision(artifactId);
66
+ if (!clean())
67
+ return false;
68
+ // A previous promotion may have completed while an inline edit deferred reload.
69
+ if (revision.document === revision.preview)
70
+ return revision.preview !== baseRevision;
71
+ const draft = getDraftForCard(cardId);
72
+ if (!draft)
73
+ return false;
74
+ const release = lockDraft(draft.id);
75
+ try {
76
+ await storage.commit(artifactId, revision);
77
+ }
78
+ finally {
79
+ release();
80
+ }
81
+ return clean();
82
+ });
83
+ },
84
+ };
85
+ }
86
+ const coordinator = createHtmlIterationCoordinator({ readRevision: readHtmlArtifactRevision, commit: commitHtmlArtifact });
87
+ function loadedRevision(frame) {
88
+ const revision = frame.contentDocument?.documentElement.getAttribute(HTML_ARTIFACT_REVISION_ATTRIBUTE);
89
+ if (!revision || !/^[a-f0-9]{64}$/.test(revision))
90
+ throw new Error("The HTML iteration is still loading. Try again when the frame is ready.");
91
+ return revision;
92
+ }
93
+ /** Materializes pending intent before the agent can start editing document.html. */
94
+ export async function prepareHtmlIterationHandoff(cardId, artifactId, frame) {
95
+ if (isInlineTextEditingActive())
96
+ throw new Error("Finish editing the text before saving this iteration.");
97
+ const contents = getDraftContentsForCard(cardId);
98
+ if (!contents)
99
+ throw new Error("The iteration draft is no longer available.");
100
+ if (contents.changes.length + contents.structuralChanges.length === 0)
101
+ return contents;
102
+ const document = frame.contentDocument;
103
+ const baseRevision = loadedRevision(frame);
104
+ try {
105
+ const workspace = await coordinator.prepare(cardId, artifactId, baseRevision, async () => {
106
+ if (!document || isInlineTextEditingActive())
107
+ throw new Error("Finish editing the text before saving this iteration.");
108
+ const workspace = getDraftContentsForCard(cardId);
109
+ if (!workspace)
110
+ throw new Error("The iteration draft is no longer available.");
111
+ const revision = await projectDraftToDocument(document, workspace);
112
+ if (revision === null)
113
+ throw new Error("The iteration preview is still updating. Try again.");
114
+ const html = await captureHtmlIteration(frame);
115
+ if (frame.contentDocument !== document || !isCanvasProjectionRevisionCurrent(document, revision)) {
116
+ throw new Error("The iteration changed while saving. Your edits are still pending. Try again.");
117
+ }
118
+ return html;
119
+ });
120
+ frame.src = `${artifactDocumentUrl(artifactId)}?revision=${Date.now()}`;
121
+ return workspace;
122
+ }
123
+ finally {
124
+ projectToAllReadyCards();
125
+ }
126
+ }
127
+ export async function refreshHtmlIteration(cardId, artifactId, frame) {
128
+ const document = frame.contentDocument;
129
+ return coordinator.refresh(cardId, artifactId, loadedRevision(frame), () => frame.contentDocument === document && !isInlineTextEditingActive());
130
+ }
@@ -0,0 +1,3 @@
1
+ /** Defines the edit destination for every HTML-iteration handoff, including fallback copies. */
2
+ export declare function htmlIterationPrompt(id: string, changes: string, noInspectorChanges: boolean, hasSketches: boolean, customInstructions?: string): string;
3
+ export declare function htmlIterationImplementationPrompt(id: string, label: string, page: string, changes: string): string;
@@ -0,0 +1,26 @@
1
+ /** Defines the edit destination for every HTML-iteration handoff, including fallback copies. */
2
+ export function htmlIterationPrompt(id, changes, noInspectorChanges, hasSketches, customInstructions = "") {
3
+ const directory = `.nudge/artifacts/${id}`;
4
+ return [
5
+ "# Edit this HTML iteration",
6
+ "",
7
+ `Edit only \`${directory}/document.html\`. This is the standalone HTML and CSS shown in the selected Nudge iteration frame.`,
8
+ "Preserve its responsive CSS and existing design edits. Keep application source files unchanged. Any original source locations below identify captured elements; they are not files to edit.",
9
+ `Keep \`${directory}/baseline.html\`, \`${directory}/preview.html\`, and metadata unchanged. Nudge will reload the iteration from your updated document.`,
10
+ ...(hasSketches ? ["Implement the attached sketch notes in this iteration's HTML and CSS. Match numbered notes to their marks in the image."] : []),
11
+ "",
12
+ ...(noInspectorChanges ? ["Use the current iteration as the editing base. Existing visual edits are already saved in its markup and styles.", ...(customInstructions.trim() ? ["", "## Custom instructions", "", customInstructions.trim()] : [])] : [changes]),
13
+ ].join("\n");
14
+ }
15
+ export function htmlIterationImplementationPrompt(id, label, page, changes) {
16
+ const directory = `.nudge/artifacts/${id}`;
17
+ return [
18
+ `# Implement ${label} in the live app`,
19
+ "",
20
+ `Page: ${page}`,
21
+ `Use \`${directory}/document.html\` as the design reference, including all saved visual edits.`,
22
+ "Update application source for this page to match it. Reuse existing components and styles, and preserve app behavior and data.",
23
+ "Keep iteration files unchanged; captured source locations below are hints for finding app code.",
24
+ ...(changes.trim() ? ["", changes] : []),
25
+ ].join("\n");
26
+ }
@@ -1,18 +1,18 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useState } from "react";
3
+ import { IconMenu2 } from "@tabler/icons-react";
4
+ import { Popover as BasePopover } from "@base-ui/react/popover";
3
5
  import { setSelectedElement } from "../selection/selectionStore.js";
4
6
  import { computeNavigationNodes } from "../selection/hierarchy.js";
5
7
  import { resolveSelectionFromElement } from "../selection/resolveSelection.js";
6
- function nodeLabel(node) {
7
- return node.getAttribute("data-cid") ?? node.localName;
8
- }
8
+ import { portalContainer } from "../ui/portalContainer.js";
9
+ import { cx } from "../ui/classNames.js";
9
10
  function nodeDescription(node) {
10
11
  const id = node.id ? `#${node.id}` : "";
11
12
  const className = typeof node.className === "string"
12
13
  ? node.className.trim().split(/\s+/).filter(Boolean).slice(0, 2).map((name) => `.${name}`).join("")
13
14
  : "";
14
- const source = node.getAttribute("data-src");
15
- return `${node.localName}${id}${className}${source ? ` — ${source}` : ""}`;
15
+ return `${node.localName}${id}${className}`;
16
16
  }
17
17
  function selectNode(node) {
18
18
  const resolved = resolveSelectionFromElement(node);
@@ -21,20 +21,26 @@ function selectNode(node) {
21
21
  }
22
22
  export function DomNavigator({ selected, hierarchy, anchor, project }) {
23
23
  const nodes = computeNavigationNodes(selected.domElement, hierarchy);
24
+ const parents = nodes.filter((node) => node.direction === "up");
25
+ const children = nodes.filter((node) => node.direction === "down");
24
26
  const [expanded, setExpanded] = useState(false);
25
27
  const [hovered, setHovered] = useState(null);
26
28
  if (nodes.length === 0)
27
29
  return null;
28
30
  const preview = hovered ? project(hovered) : null;
29
- const close = () => {
30
- setExpanded(false);
31
- setHovered(null);
31
+ const setOpen = (next) => {
32
+ setExpanded(next);
33
+ if (!next)
34
+ setHovered(null);
35
+ };
36
+ const renderItem = (node, depth) => {
37
+ const current = node === null;
38
+ const element = current ? selected.domElement : node.element;
39
+ return (_jsx("button", { type: "button", className: cx("dom-navigator__item", current && "dom-navigator__item--selected"), "data-test": "dom-navigator-item", "data-current": current ? "true" : undefined, "data-direction": node?.direction, "data-depth": depth, "data-cid": element.getAttribute("data-cid") ?? undefined, style: { paddingLeft: `calc(var(--space-8) + ${depth * 16}px)` }, role: "menuitem", "aria-current": current ? "true" : undefined, onMouseEnter: () => setHovered(current ? null : element), onClick: () => {
40
+ if (!current)
41
+ selectNode(element);
42
+ setOpen(false);
43
+ }, children: _jsx("span", { children: nodeDescription(element) }) }, current ? "current" : `${node.direction}-${node.depth}-${element.getAttribute("data-cid") ?? element.localName}`));
32
44
  };
33
- return (_jsxs(_Fragment, { children: [preview ? _jsx("div", { className: "dom-navigator-preview", "data-test": "dom-navigator-preview", style: preview, "aria-hidden": "true" }) : null, _jsxs("div", { className: "dom-navigator", "data-test": "dom-navigator", "aria-label": "DOM navigator", style: { left: Math.max(4, anchor.left), top: Math.max(4, anchor.top) }, onMouseEnter: () => setExpanded(true), onMouseLeave: close, onFocus: () => setExpanded(true), onBlur: (event) => {
34
- if (!(event.relatedTarget instanceof Node) || !event.currentTarget.contains(event.relatedTarget))
35
- close();
36
- }, children: [_jsxs("button", { type: "button", className: "dom-navigator__trigger", "data-test": "dom-navigator-trigger", "aria-expanded": expanded, "aria-haspopup": "menu", title: nodeDescription(selected.domElement), onMouseEnter: () => setHovered(null), children: [_jsx("span", { children: nodeLabel(selected.domElement) }), _jsx("span", { "aria-hidden": "true", children: "\u2304" })] }), expanded ? (_jsx("div", { className: "dom-navigator__menu", role: "menu", children: nodes.map((node) => (_jsxs("button", { type: "button", className: "dom-navigator__item", "data-test": "dom-navigator-item", "data-direction": node.direction, "data-depth": node.depth, "data-cid": node.element.getAttribute("data-cid") ?? undefined, title: nodeDescription(node.element), role: "menuitem", onMouseEnter: () => setHovered(node.element), onClick: () => {
37
- selectNode(node.element);
38
- close();
39
- }, children: [_jsx("span", { "aria-hidden": "true", children: node.direction === "up" ? "↑" : "↓" }), _jsx("span", { children: nodeLabel(node.element) })] }, `${node.direction}-${node.depth}-${node.element.getAttribute("data-cid") ?? node.element.localName}`))) })) : null] })] }));
45
+ return (_jsxs(_Fragment, { children: [preview ? _jsx("div", { className: "dom-navigator-preview", "data-test": "dom-navigator-preview", style: preview, "aria-hidden": "true" }) : null, _jsx("div", { className: "dom-navigator", "data-test": "dom-navigator", "aria-label": "DOM navigator", style: { left: Math.max(4, anchor.left), top: Math.max(4, anchor.top - 28) }, children: _jsxs(BasePopover.Root, { open: expanded, onOpenChange: setOpen, children: [_jsx(BasePopover.Trigger, { render: _jsx("button", { type: "button", className: "dom-navigator__trigger", "data-test": "dom-navigator-trigger", "aria-label": "Open DOM navigator", "aria-haspopup": "menu", "aria-expanded": expanded, onMouseEnter: () => setHovered(null) }), children: _jsx(IconMenu2, { size: 14, "aria-hidden": "true" }) }), _jsx("span", { className: "dom-navigator__label", children: nodeDescription(selected.domElement) }), _jsx(BasePopover.Portal, { container: portalContainer(), children: _jsx(BasePopover.Positioner, { className: "dom-navigator__positioner", side: "top", align: "start", sideOffset: 4, children: _jsxs(BasePopover.Popup, { className: "dom-navigator__menu", role: "menu", "aria-label": "DOM navigator", onMouseLeave: () => setHovered(null), children: [parents.slice().reverse().map((node) => renderItem(node, parents.length - node.depth)), renderItem(null, parents.length), children.map((node) => renderItem(node, parents.length + node.depth))] }) }) })] }) })] }));
40
46
  }