@agent-native/core 0.189.0 → 0.190.0-nightly-20260925211446

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 (233) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/templates/analytics/.agents/skills/analysis-workspace/SKILL.md +10 -0
  3. package/corpus/templates/analytics/.agents/skills/data-querying/SKILL.md +1 -1
  4. package/corpus/templates/analytics/AGENTS.md +11 -22
  5. package/corpus/templates/analytics/actions/list-data-dictionary.ts +7 -9
  6. package/corpus/templates/analytics/actions/search-analytics-query-catalog.ts +1 -1
  7. package/corpus/templates/analytics/app/components/AnalyticsReviewArtifactPreview.tsx +201 -0
  8. package/corpus/templates/analytics/app/i18n/en-US.ts +2 -0
  9. package/corpus/templates/analytics/app/pages/Settings.tsx +50 -3
  10. package/corpus/templates/analytics/changelog/2026-09-25-first-run-onboarding-records-setup-choices-and-builder-conne.md +6 -0
  11. package/corpus/templates/analytics/changelog/2026-09-25-human-review-previews-analytics-dashboards-as-real-charts.md +6 -0
  12. package/corpus/templates/analytics/changelog/2026-09-25-org-admins-can-review-agent-runs-from-settings.md +6 -0
  13. package/corpus/templates/analytics/changelog/2026-09-25-proactive-query-context.md +6 -0
  14. package/corpus/templates/analytics/seeds/dashboards/agent-native-templates-first-party.json +98 -2
  15. package/corpus/templates/analytics/server/lib/analytics-agent-context.ts +557 -0
  16. package/corpus/templates/analytics/server/lib/analytics-query-catalog.ts +217 -46
  17. package/corpus/templates/analytics/server/lib/dashboard-catalog.ts +2 -2
  18. package/corpus/templates/analytics/server/lib/dashboards-store.ts +39 -5
  19. package/corpus/templates/analytics/server/lib/data-dictionary-context.ts +4 -0
  20. package/corpus/templates/analytics/server/lib/first-party-metric-catalog.ts +268 -2
  21. package/corpus/templates/analytics/server/plugins/agent-chat.ts +44 -9
  22. package/corpus/templates/calendar/AGENTS.md +5 -0
  23. package/corpus/templates/calendar/CHANGELOG.md +6 -0
  24. package/corpus/templates/calendar/actions/get-event-rules-status.ts +47 -0
  25. package/corpus/templates/calendar/actions/list-events.ts +50 -4
  26. package/corpus/templates/calendar/actions/undo-calendar-event-rule.ts +229 -0
  27. package/corpus/templates/calendar/actions/update-settings.ts +8 -0
  28. package/corpus/templates/calendar/app/i18n/en-US.ts +27 -0
  29. package/corpus/templates/calendar/app/pages/Settings.tsx +196 -1
  30. package/corpus/templates/calendar/changelog/2026-09-25-calendar-feeds-with-the-same-url-keep-their-own-names-and-co.md +6 -0
  31. package/corpus/templates/calendar/changelog/2026-09-25-calendar-invitation-rules-surface-expired-connections-and-un.md +6 -0
  32. package/corpus/templates/calendar/changelog/2026-09-25-restore-locally-hidden-events-from-activity-after-disconnect.md +6 -0
  33. package/corpus/templates/calendar/server/lib/calendar-settings.ts +44 -10
  34. package/corpus/templates/calendar/server/lib/google-api.ts +15 -1
  35. package/corpus/templates/calendar/server/lib/google-calendar.ts +1 -1
  36. package/corpus/templates/calendar/server/plugins/event-rules.ts +628 -0
  37. package/corpus/templates/calendar/shared/api.ts +13 -0
  38. package/corpus/templates/calendar/shared/settings.ts +71 -1
  39. package/corpus/templates/clips/actions/create-recording.ts +83 -2
  40. package/corpus/templates/clips/actions/finalize-recording.ts +610 -110
  41. package/corpus/templates/clips/actions/get-recording-player-data.ts +6 -0
  42. package/corpus/templates/clips/actions/import-loom-recording.ts +2 -0
  43. package/corpus/templates/clips/actions/lib/create-recording-schema.ts +7 -0
  44. package/corpus/templates/clips/actions/lib/loom-import-job.ts +15 -1
  45. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +126 -26
  46. package/corpus/templates/clips/app/hooks/use-drop-video-upload.ts +75 -15
  47. package/corpus/templates/clips/app/routes/_app.r.$recordingId.tsx +5 -1
  48. package/corpus/templates/clips/app/routes/record.tsx +134 -40
  49. package/corpus/templates/clips/chrome-extension/src/background.ts +3 -0
  50. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +73 -16
  51. package/corpus/templates/clips/desktop/src/lib/recorder.ts +188 -18
  52. package/corpus/templates/clips/desktop/src/lib/recording-request.ts +1 -0
  53. package/corpus/templates/clips/server/db/schema.ts +4 -0
  54. package/corpus/templates/clips/server/jobs/media-verification.ts +78 -4
  55. package/corpus/templates/clips/server/jobs/recording-failure-backfill.ts +142 -0
  56. package/corpus/templates/clips/server/lib/media-verification-state.ts +29 -0
  57. package/corpus/templates/clips/server/lib/post-finalize-dispatch.ts +2 -0
  58. package/corpus/templates/clips/server/lib/recording-failures.ts +111 -0
  59. package/corpus/templates/clips/server/lib/recordings.ts +6 -1
  60. package/corpus/templates/clips/server/lib/s3-upload-provider.ts +8 -3
  61. package/corpus/templates/clips/server/lib/upload-lease.ts +25 -6
  62. package/corpus/templates/clips/server/plugins/calendar-jobs.ts +2 -0
  63. package/corpus/templates/clips/server/plugins/db.ts +18 -0
  64. package/corpus/templates/clips/server/routes/api/_agent-native-background/post-finalize-worker.post.ts +48 -5
  65. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/abort.post.ts +322 -31
  66. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/chunk.post.ts +223 -61
  67. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/interrupt.post.ts +62 -4
  68. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/reset-chunks.post.ts +74 -7
  69. package/corpus/templates/clips/shared/recording-core.ts +27 -0
  70. package/corpus/templates/design/actions/get-design.ts +35 -6
  71. package/corpus/templates/mail/.agents/skills/inbox-automations/SKILL.md +4 -0
  72. package/corpus/templates/mail/actions/consolidate-ai-filter-rules.ts +41 -0
  73. package/corpus/templates/mail/actions/get-ai-priority.ts +48 -8
  74. package/corpus/templates/mail/actions/record-ai-priority-feedback.ts +69 -0
  75. package/corpus/templates/mail/actions/update-mail-preferences.ts +2 -0
  76. package/corpus/templates/mail/app/components/email/EmailList.tsx +179 -32
  77. package/corpus/templates/mail/app/components/email/EmailListItem.tsx +97 -9
  78. package/corpus/templates/mail/app/components/email/EmailThread.tsx +55 -1
  79. package/corpus/templates/mail/app/components/email/ImportanceFeedbackMenu.tsx +52 -0
  80. package/corpus/templates/mail/app/components/email/compose-autocomplete.ts +2 -1
  81. package/corpus/templates/mail/app/components/layout/AppLayout.tsx +219 -188
  82. package/corpus/templates/mail/app/components/onboarding/AiInboxSetup.tsx +338 -0
  83. package/corpus/templates/mail/app/components/settings/AiFilterSection.tsx +597 -781
  84. package/corpus/templates/mail/app/components/settings/AiRulePromptField.tsx +37 -0
  85. package/corpus/templates/mail/app/global.css +42 -26
  86. package/corpus/templates/mail/app/hooks/use-ai-priority-feedback.ts +43 -0
  87. package/corpus/templates/mail/app/hooks/use-automations.ts +23 -0
  88. package/corpus/templates/mail/app/i18n/en-US.ts +58 -3
  89. package/corpus/templates/mail/app/pages/InboxPage.tsx +47 -10
  90. package/corpus/templates/mail/changelog/2026-09-25-editing-importance-rules-preserves-disabled-instructions-and.md +6 -0
  91. package/corpus/templates/mail/changelog/2026-09-25-handle-astral-unicode-letters-in-autocomplete-word-boundarie.md +6 -0
  92. package/corpus/templates/mail/changelog/2026-09-25-jev-priority-feedback-and-inbox-settings.md +6 -0
  93. package/corpus/templates/mail/changelog/2026-09-25-keep-existing-ai-filter-rules-intact-when-saving-a-prompt.md +6 -0
  94. package/corpus/templates/mail/server/lib/automation-engine.ts +21 -12
  95. package/corpus/templates/mail/server/lib/automations.ts +100 -1
  96. package/corpus/templates/mail/shared/types.ts +3 -0
  97. package/corpus/templates/plan/app/i18n/en-US.ts +6 -0
  98. package/corpus/templates/plan/app/lib/plan-invite-suggestion.ts +43 -0
  99. package/corpus/templates/plan/app/pages/PlansPage.tsx +249 -4
  100. package/corpus/templates/slides/actions/create-deck.ts +11 -1
  101. package/corpus/templates/slides/app/components/deck/SlideRenderer.tsx +117 -1
  102. package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +373 -330
  103. package/corpus/templates/slides/app/components/design-system/builder-index-response.ts +36 -5
  104. package/corpus/templates/slides/app/components/editor/BlockBubbleMenu.tsx +21 -53
  105. package/corpus/templates/slides/app/components/editor/SlideEditor.tsx +347 -671
  106. package/corpus/templates/slides/app/components/editor/bullet-editing.ts +55 -8
  107. package/corpus/templates/slides/app/components/editor/in-place-text-session.ts +2082 -0
  108. package/corpus/templates/slides/app/components/editor/list-editing.ts +174 -16
  109. package/corpus/templates/slides/app/components/editor/rich-text-selection.ts +497 -62
  110. package/corpus/templates/slides/app/components/editor/slide-text-targets.ts +102 -20
  111. package/corpus/templates/slides/app/context/DeckContext.tsx +9 -4
  112. package/corpus/templates/slides/app/global.css +7 -219
  113. package/corpus/templates/slides/app/i18n/en-US.ts +3 -0
  114. package/corpus/templates/slides/app/lib/sanitize-slide-html.ts +7 -0
  115. package/corpus/templates/slides/app/lib/slide-image-replacement.ts +203 -1
  116. package/corpus/templates/slides/app/lib/slide-source-map.ts +43 -0
  117. package/corpus/templates/slides/app/pages/DeckEditor.tsx +182 -4
  118. package/corpus/templates/slides/app/routes/settings.tsx +33 -2
  119. package/corpus/templates/slides/changelog/2026-09-25-improve-slides-design-system-setup-feedback.md +6 -0
  120. package/corpus/templates/slides/changelog/2026-09-25-org-admins-can-review-agent-runs-from-settings.md +6 -0
  121. package/corpus/templates/slides/changelog/2026-09-25-text-on-a-slide-is-now-edited-in-place-clicking-into-it-chan.md +6 -0
  122. package/corpus/templates/slides/package.json +0 -12
  123. package/corpus/templates/slides/scripts/edit-fidelity/README.md +4 -2
  124. package/corpus/templates/slides/scripts/edit-fidelity/run.ts +12 -3
  125. package/corpus/templates/slides/vite.config.ts +1 -10
  126. package/dist/agent/jev-tool-prefetch.d.ts +29 -3
  127. package/dist/agent/jev-tool-prefetch.js +161 -34
  128. package/dist/agent/production-agent.d.ts +11 -0
  129. package/dist/agent/production-agent.js +39 -8
  130. package/dist/app-config/runtime.d.ts +1 -0
  131. package/dist/app-config/runtime.js +4 -0
  132. package/dist/app-config/schema.d.ts +1 -0
  133. package/dist/client/AgentSidebar.d.ts +3 -1
  134. package/dist/client/AgentSidebar.js +8 -12
  135. package/dist/client/analytics/index.d.ts +1 -1
  136. package/dist/client/analytics/index.js +1 -1
  137. package/dist/client/analytics.d.ts +2 -0
  138. package/dist/client/analytics.js +9 -0
  139. package/dist/client/api-path.js +5 -2
  140. package/dist/client/chat/run-recovery.d.ts +0 -3
  141. package/dist/client/chat/run-recovery.js +13 -23
  142. package/dist/client/index.d.ts +1 -1
  143. package/dist/client/index.js +1 -1
  144. package/dist/client/observability/ObservabilityDashboard.d.ts +3 -0
  145. package/dist/client/observability/ObservabilityDashboard.js +366 -71
  146. package/dist/client/observability/ObservabilityReviewSummaryButton.d.ts +4 -1
  147. package/dist/client/observability/ObservabilityReviewSummaryButton.js +13 -9
  148. package/dist/client/observability/OutputPreview.d.ts +9 -4
  149. package/dist/client/observability/OutputPreview.js +230 -52
  150. package/dist/client/onboarding/FirstRunOnboarding.js +67 -4
  151. package/dist/client/onboarding/use-onboarding.js +2 -0
  152. package/dist/client/sharing/ShareButton.d.ts +2 -0
  153. package/dist/client/sharing/ShareButton.js +1 -0
  154. package/dist/client/sharing/useShareButtonController.d.ts +1 -0
  155. package/dist/client/sharing/useShareButtonController.js +29 -8
  156. package/dist/collab/awareness.d.ts +2 -2
  157. package/dist/collab/struct-routes.d.ts +1 -1
  158. package/dist/deploy/build.js +9 -1
  159. package/dist/embeddings/index.d.ts +3 -1
  160. package/dist/embeddings/index.js +20 -10
  161. package/dist/jobs/sweep-hooks.d.ts +7 -0
  162. package/dist/jobs/sweep-hooks.js +28 -0
  163. package/dist/localization/default-messages.d.ts +1 -0
  164. package/dist/localization/default-messages.js +1 -0
  165. package/dist/mcp/screen-memory-stdio.d.ts +7 -7
  166. package/dist/notifications/routes.d.ts +1 -1
  167. package/dist/observability/actions/authorization.d.ts +1 -0
  168. package/dist/observability/actions/authorization.js +22 -0
  169. package/dist/observability/actions/get-observability-review-detail.d.ts +5 -0
  170. package/dist/observability/actions/get-observability-review-detail.js +10 -2
  171. package/dist/observability/actions/get-observability-review-summary-source.d.ts +2 -0
  172. package/dist/observability/actions/get-observability-review-summary-source.js +3 -2
  173. package/dist/observability/actions/save-observability-instruction-update.js +2 -1
  174. package/dist/observability/actions/save-observability-review-summary.js +21 -10
  175. package/dist/observability/migrations.js +25 -0
  176. package/dist/observability/reviews.d.ts +3 -1
  177. package/dist/observability/reviews.js +410 -53
  178. package/dist/observability/routes.d.ts +6 -6
  179. package/dist/observability/store.d.ts +15 -0
  180. package/dist/observability/store.js +131 -11
  181. package/dist/observability/types.d.ts +18 -0
  182. package/dist/org/handlers.d.ts +1 -1
  183. package/dist/org/index.d.ts +1 -1
  184. package/dist/progress/routes.d.ts +1 -1
  185. package/dist/provider-api/actions/custom-provider-registration.d.ts +5 -5
  186. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  187. package/dist/secrets/routes.d.ts +3 -3
  188. package/dist/server/agent-chat/plugin-options.d.ts +4 -20
  189. package/dist/server/agent-chat/prompt-resources.d.ts +16 -0
  190. package/dist/server/agent-chat/prompt-resources.js +385 -22
  191. package/dist/server/agent-chat-plugin.d.ts +3 -1
  192. package/dist/server/agent-chat-plugin.js +149 -27
  193. package/dist/server/agent-engine-ollama-models-route.d.ts +1 -1
  194. package/dist/server/index.d.ts +3 -0
  195. package/dist/server/index.js +3 -0
  196. package/dist/server/prompts/framework-core-compact.js +1 -1
  197. package/dist/server/prompts/framework-core.js +1 -1
  198. package/dist/server/realtime-token.d.ts +1 -1
  199. package/dist/server/request-context.d.ts +6 -3
  200. package/dist/server/transcribe-voice.d.ts +1 -1
  201. package/dist/settings/org-settings.d.ts +4 -2
  202. package/dist/settings/org-settings.js +3 -3
  203. package/dist/settings/store.d.ts +3 -1
  204. package/dist/settings/store.js +8 -3
  205. package/dist/styles/agent-native.css +5 -0
  206. package/dist/templates/default/app/i18n/ar-SA.ts +1 -0
  207. package/dist/templates/default/app/i18n/de-DE.ts +1 -0
  208. package/dist/templates/default/app/i18n/en-US.ts +1 -0
  209. package/dist/templates/default/app/i18n/es-ES.ts +1 -0
  210. package/dist/templates/default/app/i18n/fr-FR.ts +1 -0
  211. package/dist/templates/default/app/i18n/hi-IN.ts +1 -0
  212. package/dist/templates/default/app/i18n/ja-JP.ts +1 -0
  213. package/dist/templates/default/app/i18n/ko-KR.ts +1 -0
  214. package/dist/templates/default/app/i18n/pt-BR.ts +1 -0
  215. package/dist/templates/default/app/i18n/zh-CN.ts +1 -0
  216. package/dist/templates/default/app/i18n/zh-TW.ts +1 -0
  217. package/dist/tracking/registry.js +11 -4
  218. package/package.json +4 -3
  219. package/src/templates/default/app/i18n/ar-SA.ts +1 -0
  220. package/src/templates/default/app/i18n/de-DE.ts +1 -0
  221. package/src/templates/default/app/i18n/en-US.ts +1 -0
  222. package/src/templates/default/app/i18n/es-ES.ts +1 -0
  223. package/src/templates/default/app/i18n/fr-FR.ts +1 -0
  224. package/src/templates/default/app/i18n/hi-IN.ts +1 -0
  225. package/src/templates/default/app/i18n/ja-JP.ts +1 -0
  226. package/src/templates/default/app/i18n/ko-KR.ts +1 -0
  227. package/src/templates/default/app/i18n/pt-BR.ts +1 -0
  228. package/src/templates/default/app/i18n/zh-CN.ts +1 -0
  229. package/src/templates/default/app/i18n/zh-TW.ts +1 -0
  230. package/corpus/templates/slides/app/components/editor/SlideBubbleMenu.tsx +0 -488
  231. package/corpus/templates/slides/app/components/editor/SlideInlineEditor.tsx +0 -589
  232. package/corpus/templates/slides/app/components/editor/SlideRichTextEditor.tsx +0 -1347
  233. package/corpus/templates/slides/app/components/editor/SlideSlashMenu.tsx +0 -373
@@ -1,1347 +0,0 @@
1
- import { SharedRichEditor } from "@agent-native/toolkit/editor";
2
- import { Extension } from "@tiptap/core";
3
- import Bold from "@tiptap/extension-bold";
4
- import { TextStyle } from "@tiptap/extension-text-style";
5
- import type { Editor } from "@tiptap/react";
6
- import {
7
- forwardRef,
8
- useCallback,
9
- useEffect,
10
- useImperativeHandle,
11
- useRef,
12
- useState,
13
- } from "react";
14
-
15
- import { sanitizeSlideHtml } from "@/lib/sanitize-slide-html";
16
-
17
- import { isBulletMarker } from "./bullet-editing";
18
- import type { InlineTextStylePatch } from "./rich-text-selection";
19
-
20
- export interface SlideTextSelectionOffsets {
21
- from: number;
22
- to: number;
23
- }
24
-
25
- export interface SlideRichTextEditorHandle {
26
- getEditor: () => Editor | null;
27
- getHTML: () => string;
28
- setSelectionFromRange: (range: Range | null) => boolean;
29
- setSelectionFromOffsets: (
30
- selection: SlideTextSelectionOffsets | null,
31
- ) => boolean;
32
- applyTextStyleToContent: (patch: InlineTextStylePatch) => void;
33
- applyTextStyle: (
34
- patch: InlineTextStylePatch,
35
- range: Range | null,
36
- ) => Range | null;
37
- }
38
-
39
- const SLIDE_TEXT_CONTAINER_TAGS = new Set([
40
- "BLOCKQUOTE",
41
- "H1",
42
- "H2",
43
- "H3",
44
- "H4",
45
- "LI",
46
- "OL",
47
- "P",
48
- "UL",
49
- ]);
50
-
51
- // A slide text block is one bounded block; StarterKit's trailing paragraph
52
- // would add an empty line under an edited list that the canvas never shows.
53
- const SLIDE_STARTER_KIT = { bold: false, trailingNode: false } as const;
54
-
55
- // TipTap treats font-weight values from 500 through 900 as bold marks. Slides
56
- // uses those values for ordinary block typography, so only semantic bold HTML
57
- // should create a bold mark while entering edit mode.
58
- export const SlideBold = Bold.extend({
59
- parseHTML() {
60
- return [
61
- { tag: "strong" },
62
- {
63
- tag: "b",
64
- getAttrs: (node) =>
65
- (node as HTMLElement).style.fontWeight !== "normal" && null,
66
- },
67
- {
68
- style: "font-weight=400",
69
- clearMark: (mark) => mark.type.name === this.name,
70
- },
71
- ];
72
- },
73
- });
74
-
75
- const SLIDE_EDITOR_BLOCK_ATTRIBUTES = ["dir", "data-pptx-paragraph"] as const;
76
- const SLIDE_EDITOR_BLOCK_STYLE_PROPERTIES = [
77
- "color",
78
- "font-family",
79
- "font-size",
80
- "font-style",
81
- "font-weight",
82
- "letter-spacing",
83
- "line-height",
84
- "min-height",
85
- "text-align",
86
- "text-decoration",
87
- ] as const;
88
-
89
- function syncSlideEditorBlockFormatting(
90
- source: HTMLElement,
91
- target: HTMLElement,
92
- clearMissing = false,
93
- ): void {
94
- const canRoundTripAttributes =
95
- target.tagName === "P" ||
96
- target.tagName === "LI" ||
97
- /^H[1-6]$/.test(target.tagName);
98
- for (const attributeName of SLIDE_EDITOR_BLOCK_ATTRIBUTES) {
99
- const value = source.getAttribute(attributeName);
100
- if (value !== null) target.setAttribute(attributeName, value);
101
- else if (clearMissing && canRoundTripAttributes) {
102
- target.removeAttribute(attributeName);
103
- }
104
- }
105
- for (const property of SLIDE_EDITOR_BLOCK_STYLE_PROPERTIES) {
106
- const value = source.style.getPropertyValue(property);
107
- if (value) {
108
- target.style.setProperty(
109
- property,
110
- value,
111
- source.style.getPropertyPriority(property),
112
- );
113
- } else if (clearMissing) {
114
- target.style.removeProperty(property);
115
- }
116
- }
117
- }
118
-
119
- export function isSlideTextContainerTag(tagName: string): boolean {
120
- return SLIDE_TEXT_CONTAINER_TAGS.has(tagName.toUpperCase());
121
- }
122
-
123
- /** Keep a semantic canvas element as the outer container around editor output. */
124
- export function contentForSlideTextContainer(
125
- tagName: string,
126
- html: string,
127
- listTagName?: "OL" | "UL",
128
- ): string {
129
- if (!html || typeof DOMParser === "undefined") {
130
- return html;
131
- }
132
- const doc = new DOMParser().parseFromString(html, "text/html");
133
- const first = doc.body.firstElementChild;
134
- const normalizedTagName = tagName.toUpperCase();
135
- if (
136
- normalizedTagName === "DIV" &&
137
- doc.body.children.length === 1 &&
138
- first?.tagName === "DIV" &&
139
- first.firstElementChild &&
140
- isBulletMarker(first.firstElementChild)
141
- ) {
142
- const source = first as HTMLElement;
143
- const paragraph = doc.createElement("p");
144
- syncSlideEditorBlockFormatting(source, paragraph);
145
- copyLegacyRowLayoutStyles(source, paragraph);
146
- paragraph.innerHTML = source.innerHTML;
147
- return paragraph.outerHTML;
148
- }
149
- if (!isSlideTextContainerTag(tagName)) return html;
150
- if (
151
- doc.body.children.length !== 1 ||
152
- first?.tagName.toUpperCase() !== tagName.toUpperCase()
153
- ) {
154
- return html;
155
- }
156
- if (/^H[1-6]$/.test(tagName.toUpperCase())) {
157
- const source = first as HTMLElement;
158
- const hasParagraphRoot =
159
- source.children.length === 1 && source.firstElementChild?.tagName === "P";
160
- const paragraph = hasParagraphRoot
161
- ? (source.firstElementChild!.cloneNode(true) as HTMLElement)
162
- : doc.createElement("p");
163
- if (!hasParagraphRoot) paragraph.innerHTML = source.innerHTML;
164
- syncSlideEditorBlockFormatting(source, paragraph);
165
- return paragraph.outerHTML;
166
- }
167
- if (tagName.toUpperCase() === "P") {
168
- const source = first as HTMLElement;
169
- const paragraph = doc.createElement("p");
170
- syncSlideEditorBlockFormatting(source, paragraph);
171
- if (source.firstElementChild && isBulletMarker(source.firstElementChild)) {
172
- copyLegacyRowLayoutStyles(source, paragraph);
173
- }
174
- paragraph.innerHTML = first.innerHTML;
175
- return paragraph.outerHTML;
176
- }
177
- if (tagName.toUpperCase() === "LI") {
178
- const list = doc.createElement(listTagName === "OL" ? "ol" : "ul");
179
- const item = doc.createElement("li");
180
- syncSlideEditorBlockFormatting(first as HTMLElement, item);
181
- item.innerHTML = first.innerHTML;
182
- list.appendChild(item);
183
- return list.outerHTML;
184
- }
185
- if (["BLOCKQUOTE", "OL", "UL"].includes(tagName.toUpperCase())) {
186
- const wrapper = doc.createElement(tagName.toLowerCase());
187
- syncSlideEditorBlockFormatting(first as HTMLElement, wrapper);
188
- wrapper.innerHTML = first.innerHTML;
189
- return wrapper.outerHTML;
190
- }
191
- return first.innerHTML;
192
- }
193
-
194
- /** Keep a semantic canvas target valid when rich text changes its block root. */
195
- export function restoreSlideTextContainerContent(
196
- element: HTMLElement,
197
- html: string,
198
- legacySourceHtml?: string,
199
- ): HTMLElement {
200
- html = restoreLegacyBulletRows(legacySourceHtml, html);
201
- if (!isSlideTextContainerTag(element.tagName)) {
202
- element.innerHTML =
203
- element.tagName === "DIV" && legacySourceHtml
204
- ? restoreLegacyBulletRowContent(legacySourceHtml, html, element)
205
- : html;
206
- return element;
207
- }
208
- if (!html || typeof DOMParser === "undefined") {
209
- element.innerHTML = html;
210
- return element;
211
- }
212
-
213
- const nextDocument = new DOMParser().parseFromString(html, "text/html");
214
- const nextRoot = nextDocument.body.firstElementChild as HTMLElement | null;
215
- const nextChildren = Array.from(nextDocument.body.children);
216
- if (nextChildren.length === 1 && nextRoot?.tagName === element.tagName) {
217
- syncSlideEditorBlockFormatting(nextRoot, element, true);
218
- element.innerHTML = nextRoot.innerHTML;
219
- return element;
220
- }
221
-
222
- const nextListRoot =
223
- nextRoot && (nextRoot.tagName === "OL" || nextRoot.tagName === "UL")
224
- ? nextRoot
225
- : null;
226
- let parentList =
227
- element.tagName === "LI" &&
228
- (element.parentElement?.tagName === "OL" ||
229
- element.parentElement?.tagName === "UL")
230
- ? element.parentElement
231
- : null;
232
- if (
233
- parentList &&
234
- nextListRoot &&
235
- parentList.tagName !== nextListRoot.tagName
236
- ) {
237
- const replacement = element.ownerDocument.createElement(
238
- nextListRoot.tagName.toLowerCase(),
239
- );
240
- for (const attribute of Array.from(parentList.attributes)) {
241
- replacement.setAttribute(attribute.name, attribute.value);
242
- }
243
- while (parentList.firstChild) {
244
- replacement.appendChild(parentList.firstChild);
245
- }
246
- parentList.replaceWith(replacement);
247
- parentList = replacement;
248
- }
249
-
250
- const content = contentForSlideTextContainer(element.tagName, html);
251
- if (content !== html) {
252
- element.innerHTML = content;
253
- return element;
254
- }
255
-
256
- const nextListItemRoot =
257
- element.tagName === "LI" &&
258
- nextListRoot !== null &&
259
- nextListRoot.children.length === 1 &&
260
- nextListRoot.firstElementChild?.tagName === "LI"
261
- ? (nextListRoot.firstElementChild as HTMLElement)
262
- : null;
263
- const hasMultipleListItems =
264
- element.tagName === "LI" &&
265
- nextListRoot !== null &&
266
- nextListRoot.children.length > 1 &&
267
- Array.from(nextListRoot.children).every((child) => child.tagName === "LI");
268
- const preservesListItemRoot =
269
- element.tagName === "LI" &&
270
- !hasMultipleListItems &&
271
- (nextListItemRoot !== null ||
272
- (nextChildren.length > 0 &&
273
- nextChildren.every((child) =>
274
- ["OL", "P", "UL"].includes(child.tagName),
275
- )));
276
- const preservesListRoot =
277
- (element.tagName === "UL" || element.tagName === "OL") &&
278
- nextRoot !== null &&
279
- ["OL", "UL"].includes(nextRoot.tagName) &&
280
- nextRoot.children.length > 0 &&
281
- Array.from(nextRoot.children).every((child) => child.tagName === "LI");
282
- const preservesRoot = preservesListItemRoot || preservesListRoot;
283
- if (
284
- nextChildren.length === 1 &&
285
- /^H[1-6]$/.test(element.tagName) &&
286
- nextRoot?.tagName === "P"
287
- ) {
288
- syncSlideEditorBlockFormatting(nextRoot, element, true);
289
- element.innerHTML = nextRoot.innerHTML;
290
- return element;
291
- }
292
- if (preservesRoot) {
293
- if (preservesListRoot && nextRoot?.tagName !== element.tagName) {
294
- const replacement = element.ownerDocument.createElement(
295
- nextRoot.tagName.toLowerCase(),
296
- );
297
- for (const attribute of Array.from(element.attributes)) {
298
- replacement.setAttribute(attribute.name, attribute.value);
299
- }
300
- syncSlideEditorBlockFormatting(nextRoot, replacement, true);
301
- replacement.innerHTML = nextRoot.innerHTML;
302
- element.replaceWith(replacement);
303
- return replacement;
304
- }
305
- if (element.tagName === "LI" && nextChildren[0]?.tagName === "P") {
306
- syncSlideEditorBlockFormatting(
307
- nextChildren[0] as HTMLElement,
308
- element,
309
- true,
310
- );
311
- }
312
- if (nextListItemRoot) {
313
- syncSlideEditorBlockFormatting(nextListItemRoot, element, true);
314
- element.innerHTML = nextListItemRoot.innerHTML;
315
- return element;
316
- }
317
- element.innerHTML = html;
318
- return element;
319
- }
320
-
321
- if (hasMultipleListItems && parentList && nextListRoot) {
322
- const firstItem = nextListRoot.firstElementChild as HTMLElement;
323
- syncSlideEditorBlockFormatting(firstItem, element, true);
324
- element.innerHTML = firstItem.innerHTML;
325
- const insertBefore = element.nextSibling;
326
- for (const item of Array.from(nextListRoot.children).slice(1)) {
327
- parentList.insertBefore(item.cloneNode(true), insertBefore);
328
- }
329
- return element;
330
- }
331
-
332
- const replacement = element.ownerDocument.createElement("div");
333
- for (const attribute of Array.from(element.attributes)) {
334
- replacement.setAttribute(attribute.name, attribute.value);
335
- }
336
- if (element.tagName === "UL" || element.tagName === "OL") {
337
- if (nextRoot?.tagName !== "UL" && nextRoot?.tagName !== "OL") {
338
- for (const property of [
339
- "list-style",
340
- "list-style-position",
341
- "list-style-type",
342
- "padding-left",
343
- ]) {
344
- replacement.style.removeProperty(property);
345
- }
346
- }
347
- }
348
- replacement.innerHTML = html;
349
- element.replaceWith(replacement);
350
- return replacement;
351
- }
352
-
353
- const CSS_STYLE_NAMES: Record<keyof InlineTextStylePatch, string> = {
354
- color: "color",
355
- fontFamily: "font-family",
356
- fontSize: "font-size",
357
- fontWeight: "font-weight",
358
- fontStyle: "font-style",
359
- textDecoration: "text-decoration",
360
- letterSpacing: "letter-spacing",
361
- lineHeight: "line-height",
362
- };
363
-
364
- /** Keep authored inline declarations when a selected text run is restyled. */
365
- const SlideTextStyle = TextStyle.extend({
366
- name: "textStyle",
367
- addAttributes() {
368
- return {
369
- ...(this.parent?.() ?? {}),
370
- style: {
371
- default: null,
372
- parseHTML: (element: HTMLElement) => element.getAttribute("style"),
373
- renderHTML: (attributes: { style?: string | null }) =>
374
- attributes.style ? { style: attributes.style } : {},
375
- },
376
- };
377
- },
378
- });
379
-
380
- const SlideBlockStyle = Extension.create({
381
- name: "slideBlockStyle",
382
- addGlobalAttributes() {
383
- return [
384
- {
385
- types: [
386
- "blockquote",
387
- "bulletList",
388
- "codeBlock",
389
- "heading",
390
- "listItem",
391
- "orderedList",
392
- "paragraph",
393
- ],
394
- attributes: {
395
- style: {
396
- default: null,
397
- parseHTML: (element: HTMLElement) => element.getAttribute("style"),
398
- renderHTML: (attributes: { style?: string | null }) =>
399
- attributes.style ? { style: attributes.style } : {},
400
- },
401
- },
402
- },
403
- {
404
- types: ["listItem", "paragraph"],
405
- attributes: {
406
- "data-pptx-paragraph": {
407
- default: null,
408
- parseHTML: (element: HTMLElement) =>
409
- element.getAttribute("data-pptx-paragraph"),
410
- renderHTML: (attributes: {
411
- "data-pptx-paragraph"?: string | null;
412
- }) =>
413
- attributes["data-pptx-paragraph"] === null ||
414
- attributes["data-pptx-paragraph"] === undefined
415
- ? {}
416
- : { "data-pptx-paragraph": attributes["data-pptx-paragraph"] },
417
- },
418
- dir: {
419
- default: null,
420
- parseHTML: (element: HTMLElement) => element.getAttribute("dir"),
421
- renderHTML: (attributes: { dir?: string | null }) =>
422
- attributes.dir ? { dir: attributes.dir } : {},
423
- },
424
- },
425
- },
426
- ];
427
- },
428
- });
429
-
430
- function mergeTextStyle(
431
- current: string | null | undefined,
432
- patch: InlineTextStylePatch,
433
- ownerDocument: Document,
434
- ): string | null {
435
- const styleElement = ownerDocument.createElement("span");
436
- if (current) styleElement.setAttribute("style", current);
437
- for (const [key, value] of Object.entries(patch) as Array<
438
- [keyof InlineTextStylePatch, string | undefined]
439
- >) {
440
- if (value !== undefined) {
441
- styleElement.style.setProperty(CSS_STYLE_NAMES[key], value);
442
- }
443
- }
444
- return styleElement.getAttribute("style");
445
- }
446
-
447
- function rangeInside(root: HTMLElement, range: Range): boolean {
448
- return (
449
- root.contains(range.startContainer) &&
450
- root.contains(range.endContainer) &&
451
- root.contains(range.commonAncestorContainer)
452
- );
453
- }
454
-
455
- function textPointAtOffset(
456
- root: HTMLElement,
457
- requestedOffset: number,
458
- ): [Node, number] {
459
- let remaining = Math.max(0, requestedOffset);
460
- const walker = root.ownerDocument.createTreeWalker(
461
- root,
462
- NodeFilter.SHOW_TEXT,
463
- );
464
- let lastText: Text | null = null;
465
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
466
- const text = node as Text;
467
- lastText = text;
468
- if (remaining <= text.data.length) return [text, remaining];
469
- remaining -= text.data.length;
470
- }
471
- if (lastText) return [lastText, lastText.data.length];
472
- return [root, root.childNodes.length];
473
- }
474
-
475
- /** Capture a native selection before the selected DOM is replaced by TipTap. */
476
- export function selectionOffsetsWithin(
477
- root: HTMLElement,
478
- range: Range,
479
- ): SlideTextSelectionOffsets {
480
- const offsetFor = (node: Node, offset: number) => {
481
- const point = root.ownerDocument.createRange();
482
- point.setStart(node, offset);
483
- point.collapse(true);
484
- const walker = root.ownerDocument.createTreeWalker(
485
- root,
486
- NodeFilter.SHOW_TEXT,
487
- );
488
- let total = 0;
489
- for (let text = walker.nextNode(); text; text = walker.nextNode()) {
490
- const textNode = text as Text;
491
- if (isRemovedLegacyBulletText(root, textNode)) continue;
492
- if (textNode === node) return total + Math.min(offset, textNode.length);
493
- const textRange = root.ownerDocument.createRange();
494
- textRange.selectNodeContents(textNode);
495
- if (point.compareBoundaryPoints(Range.START_TO_END, textRange) >= 0) {
496
- total += textNode.length;
497
- continue;
498
- }
499
- break;
500
- }
501
- return total;
502
- };
503
- return {
504
- from: offsetFor(range.startContainer, range.startOffset),
505
- to: offsetFor(range.endContainer, range.endOffset),
506
- };
507
- }
508
-
509
- function isLegacyBulletRow(element: Element): boolean {
510
- return (
511
- (element.tagName === "DIV" || element.tagName === "P") &&
512
- !!element.firstElementChild &&
513
- isBulletMarker(element.firstElementChild)
514
- );
515
- }
516
-
517
- function isRemovedLegacyBulletText(root: HTMLElement, node: Text): boolean {
518
- let element = node.parentElement;
519
- while (element && element !== root) {
520
- if (
521
- isLegacyBulletRow(element) &&
522
- element.firstElementChild?.contains(node)
523
- ) {
524
- return true;
525
- }
526
- element = element.parentElement;
527
- }
528
- return false;
529
- }
530
-
531
- const LEGACY_ROW_TEXT_STYLE_PROPERTIES = [
532
- "color",
533
- "font-family",
534
- "font-size",
535
- "font-style",
536
- "font-weight",
537
- "letter-spacing",
538
- "line-height",
539
- "text-align",
540
- "text-decoration",
541
- ];
542
- const LEGACY_ROW_LAYOUT_STYLE_PROPERTIES = [
543
- "align-items",
544
- "display",
545
- "flex-shrink",
546
- "gap",
547
- "justify-content",
548
- "row-gap",
549
- "column-gap",
550
- ];
551
- const LEGACY_MARKER_STYLE_PROPERTIES = [
552
- ["font-size", "--slide-legacy-marker-size"],
553
- ["color", "--slide-legacy-marker-color"],
554
- ["top", "--slide-legacy-marker-top"],
555
- ] as const;
556
-
557
- function listItemContent(
558
- item: HTMLElement,
559
- excludeChild?: HTMLElement,
560
- ): string {
561
- if (!excludeChild) {
562
- const firstChild = item.firstElementChild;
563
- return item.children.length === 1 && firstChild?.tagName === "P"
564
- ? firstChild.innerHTML
565
- : item.innerHTML;
566
- }
567
- // A Tab-indented sub-bullet nests its child <ul>/<ol> inside the same <li>
568
- // as the item's own text; strip it before reading content so the nested
569
- // row's markup isn't duplicated into its parent's text span.
570
- const clone = item.cloneNode(true) as HTMLElement;
571
- const excludeIndex = Array.from(item.children).indexOf(excludeChild);
572
- if (excludeIndex >= 0) clone.children[excludeIndex]?.remove();
573
- const firstChild = clone.firstElementChild;
574
- return clone.children.length === 1 && firstChild?.tagName === "P"
575
- ? firstChild.innerHTML
576
- : clone.innerHTML;
577
- }
578
-
579
- function restoreLegacyBulletRow(
580
- template: HTMLElement,
581
- item: HTMLElement,
582
- excludeChild?: HTMLElement,
583
- ): HTMLElement {
584
- const row = template.cloneNode(true) as HTMLElement;
585
- const marker = row.firstElementChild;
586
- if (!marker) return row;
587
-
588
- while (marker.nextSibling) marker.nextSibling.remove();
589
-
590
- const textTemplate = template.children[1];
591
- const content = listItemContent(item, excludeChild);
592
- if (textTemplate) {
593
- const text = textTemplate.cloneNode(false) as HTMLElement;
594
- text.innerHTML = content;
595
- row.appendChild(text);
596
- } else {
597
- row.insertAdjacentHTML("beforeend", content);
598
- }
599
-
600
- for (const attribute of Array.from(item.attributes)) {
601
- if (attribute.name !== "style") {
602
- row.setAttribute(attribute.name, attribute.value);
603
- }
604
- }
605
- for (const property of LEGACY_ROW_TEXT_STYLE_PROPERTIES) {
606
- row.style.removeProperty(property);
607
- }
608
- copyRowTextStyles(item, row);
609
- copyLegacyRowLayoutStyles(item, row);
610
- return row;
611
- }
612
-
613
- function applyRestoredLegacyBulletRow(
614
- target: HTMLElement,
615
- restored: HTMLElement,
616
- ): void {
617
- for (const attribute of Array.from(restored.attributes)) {
618
- if (attribute.name !== "style") {
619
- target.setAttribute(attribute.name, attribute.value);
620
- }
621
- }
622
- for (const property of [
623
- ...LEGACY_ROW_TEXT_STYLE_PROPERTIES,
624
- ...LEGACY_ROW_LAYOUT_STYLE_PROPERTIES,
625
- ]) {
626
- target.style.removeProperty(property);
627
- const value = restored.style.getPropertyValue(property);
628
- if (value) {
629
- target.style.setProperty(
630
- property,
631
- value,
632
- restored.style.getPropertyPriority(property),
633
- );
634
- }
635
- }
636
- target.innerHTML = restored.innerHTML;
637
- }
638
-
639
- function restoreLegacyBulletRowsInContainer(
640
- source: Element,
641
- current: Element,
642
- ): void {
643
- const sourceChildren = Array.from(source.children);
644
- let currentIndex = 0;
645
-
646
- for (let sourceIndex = 0; sourceIndex < sourceChildren.length; ) {
647
- const sourceChild = sourceChildren[sourceIndex];
648
- if (isLegacyBulletRow(sourceChild)) {
649
- const templates: HTMLElement[] = [];
650
- while (
651
- sourceIndex < sourceChildren.length &&
652
- isLegacyBulletRow(sourceChildren[sourceIndex])
653
- ) {
654
- templates.push(sourceChildren[sourceIndex] as HTMLElement);
655
- sourceIndex += 1;
656
- }
657
-
658
- const currentChild = current.children[currentIndex];
659
- if (currentChild?.tagName === "UL") {
660
- const rows: HTMLElement[] = [];
661
- collectLegacyBulletRows(
662
- templates,
663
- currentChild as HTMLElement,
664
- 0,
665
- rows,
666
- );
667
- if (rows.length > 0) {
668
- currentChild.replaceWith(...rows);
669
- currentIndex += rows.length;
670
- continue;
671
- }
672
- }
673
- currentIndex += 1;
674
- continue;
675
- }
676
-
677
- const currentChild = current.children[currentIndex];
678
- if (currentChild && currentChild.tagName === sourceChild.tagName) {
679
- restoreLegacyBulletRowsInContainer(sourceChild, currentChild);
680
- }
681
- sourceIndex += 1;
682
- currentIndex += 1;
683
- }
684
- }
685
-
686
- function restoreLegacyBulletRows(
687
- sourceHtml: string | undefined,
688
- html: string,
689
- ): string {
690
- if (
691
- !sourceHtml ||
692
- !html ||
693
- typeof DOMParser === "undefined" ||
694
- !sourceHtml.includes("<")
695
- ) {
696
- return html;
697
- }
698
- const sourceDocument = new DOMParser().parseFromString(
699
- sourceHtml,
700
- "text/html",
701
- );
702
- const currentDocument = new DOMParser().parseFromString(html, "text/html");
703
- restoreLegacyBulletRowsInContainer(sourceDocument.body, currentDocument.body);
704
- return currentDocument.body.innerHTML;
705
- }
706
-
707
- /**
708
- * Turn a Tab-indented sub-item's <ul>/<ol> into a flat sibling row offset by
709
- * padding-left, matching how AI-generated decks already draw sub-bullets
710
- * (see `restoreLegacyBulletRow`'s row shape) instead of leaving it a nested
711
- * DOM level the `isBulletRow`/`isBulletMarker` heuristics elsewhere don't
712
- * expect. Order is depth-first so each item's own sub-items land right after
713
- * it, matching outline order.
714
- */
715
- function collectLegacyBulletRows(
716
- templates: HTMLElement[],
717
- list: HTMLElement,
718
- depth: number,
719
- rows: HTMLElement[],
720
- ): void {
721
- for (const child of Array.from(list.children)) {
722
- if (child.tagName !== "LI") continue;
723
- const item = child as HTMLElement;
724
- const nestedList = Array.from(item.children).find(
725
- (c): c is HTMLElement => c.tagName === "UL" || c.tagName === "OL",
726
- );
727
- const template = templates[Math.min(rows.length, templates.length - 1)]!;
728
- const row = restoreLegacyBulletRow(template, item, nestedList);
729
- if (depth > 0) {
730
- const basePadding = Number.parseFloat(template.style.paddingLeft) || 0;
731
- row.style.paddingLeft = `${basePadding + depth * 24}px`;
732
- }
733
- rows.push(row);
734
- // A sub-list switched to numbered keeps its <ol> instead of glyph rows.
735
- if (nestedList?.tagName === "OL") {
736
- stripLegacyListStyles(nestedList);
737
- rows.push(nestedList);
738
- } else if (nestedList) {
739
- collectLegacyBulletRows(templates, nestedList, depth + 1, rows);
740
- }
741
- }
742
- }
743
-
744
- /**
745
- * A single legacy bullet row edited into more than one item stops being a
746
- * row and becomes the list holding them: flip its own flex-row layout
747
- * (marker beside text) to a flex-column stack so the new rows lay out one
748
- * per line instead of crammed onto one.
749
- */
750
- function applyLegacyBulletListLayout(target: HTMLElement): void {
751
- target.style.setProperty("display", "flex");
752
- target.style.setProperty("flex-direction", "column");
753
- target.style.removeProperty("align-items");
754
- target.style.removeProperty("justify-content");
755
- if (!target.style.getPropertyValue("gap")) {
756
- target.style.setProperty("gap", "0.6em");
757
- }
758
- }
759
-
760
- function restoreLegacyBulletRowContent(
761
- sourceHtml: string | undefined,
762
- html: string,
763
- target?: HTMLElement,
764
- ): string {
765
- if (!sourceHtml || typeof DOMParser === "undefined") return html;
766
- const sourceDocument = new DOMParser().parseFromString(
767
- `<div>${sourceHtml}</div>`,
768
- "text/html",
769
- );
770
- const sourceWrapper = sourceDocument.body.firstElementChild;
771
- if (sourceWrapper?.tagName !== "DIV" || !isLegacyBulletRow(sourceWrapper)) {
772
- return html;
773
- }
774
- const currentDocument = new DOMParser().parseFromString(html, "text/html");
775
- if (currentDocument.body.childNodes.length !== 1) return html;
776
- const currentRoot = currentDocument.body
777
- .firstElementChild as HTMLElement | null;
778
- if (!currentRoot) return html;
779
- if (currentRoot.tagName === "UL" || currentRoot.tagName === "OL") {
780
- const currentItems = Array.from(currentRoot.children).filter(
781
- (child) => child.tagName === "LI",
782
- );
783
- const hasNestedList = currentItems.some((item) =>
784
- Array.from(item.children).some(
785
- (child) => child.tagName === "UL" || child.tagName === "OL",
786
- ),
787
- );
788
- // A raw <ul style="--slide-legacy-list..."> only draws its marker via
789
- // ::before scoped to `.slide-shared-rich-editor` (see global.css) — the
790
- // live editor's own wrapper class. Persisted as slide content outside
791
- // that wrapper, the marker silently stops rendering. Expand every item
792
- // (and any Tab-nested sub-item) back into real marker rows instead of
793
- // leaking that editor-only markup into saved content.
794
- // A numbered list is the user's explicit choice; it persists as a real
795
- // <ol> rather than as copies of the source row's bullet glyph.
796
- if (currentRoot.tagName === "OL") {
797
- stripLegacyListStyles(currentRoot);
798
- return currentRoot.outerHTML;
799
- }
800
- if (currentItems.length > 1 || hasNestedList) {
801
- const rows: HTMLElement[] = [];
802
- collectLegacyBulletRows(
803
- [sourceWrapper as HTMLElement],
804
- currentRoot,
805
- 0,
806
- rows,
807
- );
808
- if (target) applyLegacyBulletListLayout(target);
809
- return rows.map((row) => row.outerHTML).join("");
810
- }
811
- }
812
- const currentItem =
813
- currentRoot.tagName === "UL" || currentRoot.tagName === "OL"
814
- ? (currentRoot.firstElementChild as HTMLElement | null)
815
- : currentRoot;
816
- if (!currentItem) return html;
817
- const restored = restoreLegacyBulletRow(
818
- sourceWrapper as HTMLElement,
819
- currentItem,
820
- );
821
- if (target) applyRestoredLegacyBulletRow(target, restored);
822
- return restored.innerHTML;
823
- }
824
-
825
- /**
826
- * The editor draws legacy glyph markers with `list-style: none` and
827
- * `--slide-legacy-*` variables; left on a real list they hide its numbers.
828
- */
829
- function stripLegacyListStyles(list: HTMLElement): void {
830
- if (list.style.getPropertyValue("--slide-legacy-list")) {
831
- list.style.removeProperty("list-style");
832
- list.style.removeProperty("padding-left");
833
- }
834
- for (const element of [
835
- list,
836
- ...Array.from(list.querySelectorAll<HTMLElement>("[style]")),
837
- ]) {
838
- const legacy: string[] = [];
839
- for (let index = 0; index < element.style.length; index += 1) {
840
- const property = element.style.item(index);
841
- if (property.startsWith("--slide-legacy-")) legacy.push(property);
842
- }
843
- for (const property of legacy) element.style.removeProperty(property);
844
- if (!element.style.length) element.removeAttribute("style");
845
- }
846
- }
847
-
848
- function copyRowTextStyles(row: HTMLElement, item: HTMLElement): void {
849
- for (const property of LEGACY_ROW_TEXT_STYLE_PROPERTIES) {
850
- const value = row.style.getPropertyValue(property);
851
- if (value) item.style.setProperty(property, value);
852
- }
853
- }
854
-
855
- function copyLegacyRowLayoutStyles(row: HTMLElement, item: HTMLElement): void {
856
- for (const property of LEGACY_ROW_LAYOUT_STYLE_PROPERTIES) {
857
- const value = row.style.getPropertyValue(property);
858
- if (value) item.style.setProperty(property, value);
859
- }
860
- }
861
-
862
- function copyLegacyListLayoutStyles(
863
- container: Element,
864
- list: HTMLUListElement,
865
- ): void {
866
- list.style.setProperty("--slide-legacy-list", "1");
867
- list.style.setProperty("list-style", "none");
868
- list.style.setProperty("padding-left", "0");
869
- for (const property of [
870
- "display",
871
- "flex-direction",
872
- "gap",
873
- "row-gap",
874
- "column-gap",
875
- ]) {
876
- const value = (container as HTMLElement).style.getPropertyValue(property);
877
- if (value) list.style.setProperty(property, value);
878
- }
879
- }
880
-
881
- function copyLegacyMarkerStyles(marker: HTMLElement, item: HTMLElement): void {
882
- const glyph = marker.textContent?.trim();
883
- if (glyph) {
884
- item.style.setProperty(
885
- "--slide-legacy-marker-content",
886
- JSON.stringify(glyph),
887
- );
888
- }
889
- for (const [property, variable] of LEGACY_MARKER_STYLE_PROPERTIES) {
890
- const value = marker.style.getPropertyValue(property);
891
- if (value) item.style.setProperty(variable, value);
892
- }
893
- }
894
-
895
- /** Turn older styled bullet rows into a semantic list for editing. */
896
- export function normalizeSlideEditorContent(html: string): string {
897
- if (!html || typeof DOMParser === "undefined") return html;
898
- const doc = new DOMParser().parseFromString(html, "text/html");
899
-
900
- const convert = (container: Element) => {
901
- const children = Array.from(container.children);
902
- const rows = children.filter(isLegacyBulletRow);
903
- if (rows.length > 0) {
904
- const converted: Element[] = [];
905
- let list: HTMLUListElement | null = null;
906
- for (const child of children) {
907
- if (isLegacyBulletRow(child)) {
908
- if (!list) {
909
- list = doc.createElement("ul");
910
- copyLegacyListLayoutStyles(container, list);
911
- converted.push(list);
912
- }
913
- const item = doc.createElement("li");
914
- const content = child.cloneNode(true) as HTMLElement;
915
- content.firstElementChild?.remove();
916
- item.innerHTML = content.innerHTML;
917
- for (const attribute of Array.from(child.attributes)) {
918
- if (attribute.name !== "style") {
919
- item.setAttribute(attribute.name, attribute.value);
920
- }
921
- }
922
- copyRowTextStyles(child as HTMLElement, item);
923
- copyLegacyRowLayoutStyles(child as HTMLElement, item);
924
- item.style.setProperty("list-style", "none");
925
- copyLegacyMarkerStyles(child.firstElementChild as HTMLElement, item);
926
- list.appendChild(item);
927
- } else {
928
- list = null;
929
- converted.push(child);
930
- }
931
- }
932
- container.replaceChildren(...converted);
933
- return;
934
- }
935
-
936
- for (const child of Array.from(container.children)) convert(child);
937
- };
938
-
939
- convert(doc.body);
940
- return doc.body.innerHTML;
941
- }
942
-
943
- const SLIDE_CLIPBOARD_BLOCK_TAGS = new Set([
944
- "ADDRESS",
945
- "ARTICLE",
946
- "ASIDE",
947
- "BLOCKQUOTE",
948
- "DIV",
949
- "DL",
950
- "FIGCAPTION",
951
- "FIGURE",
952
- "FOOTER",
953
- "FORM",
954
- "H1",
955
- "H2",
956
- "H3",
957
- "H4",
958
- "H5",
959
- "H6",
960
- "HEADER",
961
- "LI",
962
- "MAIN",
963
- "NAV",
964
- "OL",
965
- "P",
966
- "PRE",
967
- "SECTION",
968
- "TABLE",
969
- "TBODY",
970
- "TD",
971
- "TFOOT",
972
- "TH",
973
- "THEAD",
974
- "TR",
975
- "UL",
976
- ]);
977
-
978
- const SLIDE_CLIPBOARD_LAYOUT_STYLE_PROPERTIES = [
979
- "position",
980
- "inset",
981
- "top",
982
- "right",
983
- "bottom",
984
- "left",
985
- "width",
986
- "height",
987
- "min-width",
988
- "min-height",
989
- "max-width",
990
- "max-height",
991
- "margin",
992
- "margin-top",
993
- "margin-right",
994
- "margin-bottom",
995
- "margin-left",
996
- "box-sizing",
997
- "visibility",
998
- "pointer-events",
999
- "user-select",
1000
- "flex",
1001
- "flex-grow",
1002
- "flex-shrink",
1003
- "flex-basis",
1004
- "align-self",
1005
- "z-index",
1006
- "transform",
1007
- "transform-origin",
1008
- ] as const;
1009
-
1010
- function hasSlideClipboardText(element: Element): boolean {
1011
- return (
1012
- Boolean(element.textContent?.trim()) ||
1013
- element.querySelector("img") !== null
1014
- );
1015
- }
1016
-
1017
- function isSlideClipboardBlock(element: Element): boolean {
1018
- return SLIDE_CLIPBOARD_BLOCK_TAGS.has(element.tagName);
1019
- }
1020
-
1021
- /** Keep selected rich text, but discard editor context and source geometry. */
1022
- export function normalizeSlideClipboardHtml(html: string): string | null {
1023
- if (!html || typeof DOMParser === "undefined") return null;
1024
- const sanitized = sanitizeSlideHtml(html);
1025
- if (!sanitized.trim()) return null;
1026
-
1027
- const doc = new DOMParser().parseFromString(sanitized, "text/html");
1028
- doc
1029
- .querySelectorAll(
1030
- "style, .fmd-layout-spacer, [data-slide-layout-spacer-for]",
1031
- )
1032
- .forEach((element) => element.remove());
1033
- doc.querySelectorAll<HTMLImageElement>("img").forEach((image) => {
1034
- if (!image.getAttribute("src")?.trim().toLowerCase().startsWith("data:")) {
1035
- return;
1036
- }
1037
- const alt = image.getAttribute("alt");
1038
- if (alt) image.replaceWith(doc.createTextNode(alt));
1039
- else image.remove();
1040
- });
1041
- doc.querySelectorAll<HTMLElement>("*").forEach((element) => {
1042
- if (
1043
- element.style.visibility === "hidden" ||
1044
- (element.style.pointerEvents === "none" &&
1045
- element.style.userSelect === "none")
1046
- ) {
1047
- element.remove();
1048
- return;
1049
- }
1050
- for (const attribute of Array.from(element.attributes)) {
1051
- if (attribute.name.startsWith("data-"))
1052
- element.removeAttribute(attribute.name);
1053
- }
1054
- for (const property of SLIDE_CLIPBOARD_LAYOUT_STYLE_PROPERTIES) {
1055
- element.style.removeProperty(property);
1056
- }
1057
- });
1058
-
1059
- for (const node of Array.from(doc.body.childNodes)) {
1060
- if (node.nodeType === Node.TEXT_NODE && !node.textContent?.trim()) {
1061
- node.remove();
1062
- }
1063
- }
1064
-
1065
- const wrapper = doc.body.firstElementChild;
1066
- if (
1067
- doc.body.children.length === 1 &&
1068
- wrapper?.tagName === "DIV" &&
1069
- !wrapper.attributes.length
1070
- ) {
1071
- while (wrapper.firstChild) doc.body.append(wrapper.firstChild);
1072
- wrapper.remove();
1073
- }
1074
-
1075
- const children = Array.from(doc.body.children);
1076
- if (!children.some(isSlideClipboardBlock)) {
1077
- const paragraph = doc.createElement("p");
1078
- while (doc.body.firstChild) paragraph.append(doc.body.firstChild);
1079
- doc.body.append(paragraph);
1080
- }
1081
-
1082
- const content = Array.from(doc.body.children);
1083
- const firstTextIndex = content.findIndex(hasSlideClipboardText);
1084
- if (firstTextIndex < 0) return null;
1085
- let lastTextIndex = -1;
1086
- content.forEach((element, index) => {
1087
- if (hasSlideClipboardText(element)) lastTextIndex = index;
1088
- });
1089
- content.slice(0, firstTextIndex).forEach((element) => element.remove());
1090
- content.slice(firstTextIndex + 1, lastTextIndex + 1).forEach((element) => {
1091
- if (element.tagName === "P" && !hasSlideClipboardText(element)) {
1092
- element.innerHTML = "<br>";
1093
- }
1094
- });
1095
- content.slice(lastTextIndex + 1).forEach((element) => element.remove());
1096
-
1097
- return doc.body.innerHTML;
1098
- }
1099
-
1100
- interface SlideRichTextEditorProps {
1101
- value: string;
1102
- initialSelection?: SlideTextSelectionOffsets | null;
1103
- onChange: (html: string) => void;
1104
- onEditorReady?: (editor: Editor) => void;
1105
- }
1106
-
1107
- export const SlideRichTextEditor = forwardRef<
1108
- SlideRichTextEditorHandle,
1109
- SlideRichTextEditorProps
1110
- >(function SlideRichTextEditor(
1111
- { value, initialSelection, onChange, onEditorReady },
1112
- ref,
1113
- ) {
1114
- const [editor, setEditor] = useState<Editor | null>(null);
1115
- const selectionAppliedRef = useRef(false);
1116
- const handleEditorReady = useCallback(
1117
- (nextEditor: Editor) => setEditor(nextEditor),
1118
- [],
1119
- );
1120
-
1121
- useEffect(() => {
1122
- if (editor && !editor.isDestroyed) onEditorReady?.(editor);
1123
- }, [editor, onEditorReady]);
1124
-
1125
- const setSelectionFromRange = useCallback(
1126
- (range: Range | null) => {
1127
- if (!editor || editor.isDestroyed) return false;
1128
- if (range && !rangeInside(editor.view.dom, range)) return false;
1129
- editor.commands.focus();
1130
- if (!range) return true;
1131
- try {
1132
- const from = editor.view.posAtDOM(
1133
- range.startContainer,
1134
- range.startOffset,
1135
- );
1136
- const to = editor.view.posAtDOM(range.endContainer, range.endOffset);
1137
- return editor.commands.setTextSelection({ from, to });
1138
- // coercion-ok: a native range can be stale after the slide DOM is replaced.
1139
- } catch {
1140
- return false;
1141
- }
1142
- },
1143
- [editor],
1144
- );
1145
-
1146
- const setSelectionFromOffsets = useCallback(
1147
- (selection: SlideTextSelectionOffsets | null) => {
1148
- if (!editor || editor.isDestroyed || !selection) return false;
1149
- const root = editor.view.dom;
1150
- const [startNode, startOffset] = textPointAtOffset(root, selection.from);
1151
- const [endNode, endOffset] = textPointAtOffset(root, selection.to);
1152
- try {
1153
- const from = editor.view.posAtDOM(startNode, startOffset);
1154
- const to = editor.view.posAtDOM(endNode, endOffset);
1155
- editor.commands.focus();
1156
- return editor.commands.setTextSelection({ from, to });
1157
- } catch {
1158
- editor.commands.focus("end");
1159
- return false;
1160
- }
1161
- },
1162
- [editor],
1163
- );
1164
-
1165
- useImperativeHandle(
1166
- ref,
1167
- () => ({
1168
- getEditor: () => editor,
1169
- getHTML: () =>
1170
- editor && !editor.isDestroyed
1171
- ? editor.getHTML()
1172
- : normalizeSlideEditorContent(value),
1173
- setSelectionFromRange,
1174
- setSelectionFromOffsets,
1175
- applyTextStyleToContent: (patch) => {
1176
- if (!editor || editor.isDestroyed) return;
1177
- const { state } = editor;
1178
- const markType = state.schema.marks.textStyle;
1179
- if (!markType) return;
1180
- const transaction = state.tr;
1181
- state.doc.descendants((node, position) => {
1182
- if (node.isText) {
1183
- const current = node.marks.find((mark) => mark.type === markType)
1184
- ?.attrs.style as string | null | undefined;
1185
- const style = mergeTextStyle(
1186
- current,
1187
- patch,
1188
- editor.view.dom.ownerDocument,
1189
- );
1190
- if (style) {
1191
- transaction.addMark(
1192
- position,
1193
- position + node.nodeSize,
1194
- markType.create({ style }),
1195
- );
1196
- }
1197
- return;
1198
- }
1199
-
1200
- if (node.type.name === "doc" || !node.isBlock) return;
1201
- const current = node.attrs.style as string | null | undefined;
1202
- const style = mergeTextStyle(
1203
- current,
1204
- patch,
1205
- editor.view.dom.ownerDocument,
1206
- );
1207
- if (style) {
1208
- transaction.setNodeMarkup(position, undefined, {
1209
- ...node.attrs,
1210
- style,
1211
- });
1212
- }
1213
- });
1214
- if (transaction.docChanged) editor.view.dispatch(transaction);
1215
- },
1216
- applyTextStyle: (patch, range) => {
1217
- if (!editor || editor.isDestroyed) return null;
1218
- if (range && !setSelectionFromRange(range)) return null;
1219
- editor.commands.focus();
1220
-
1221
- const { state } = editor;
1222
- const markType = state.schema.marks.textStyle;
1223
- if (!markType) return null;
1224
- const selection = state.selection;
1225
-
1226
- if (selection.empty) {
1227
- const current = editor.getAttributes("textStyle") as {
1228
- style?: string | null;
1229
- };
1230
- const style = mergeTextStyle(
1231
- current.style,
1232
- patch,
1233
- editor.view.dom.ownerDocument,
1234
- );
1235
- if (!style) return null;
1236
- editor.chain().focus().setMark("textStyle", { style }).run();
1237
- } else {
1238
- const transaction = state.tr;
1239
- state.doc.nodesBetween(
1240
- selection.from,
1241
- selection.to,
1242
- (node, position) => {
1243
- if (!node.isText) return;
1244
- const from = Math.max(selection.from, position);
1245
- const to = Math.min(selection.to, position + node.nodeSize);
1246
- if (from >= to) return;
1247
- const current = node.marks.find((mark) => mark.type === markType)
1248
- ?.attrs.style as string | null | undefined;
1249
- const style = mergeTextStyle(
1250
- current,
1251
- patch,
1252
- editor.view.dom.ownerDocument,
1253
- );
1254
- if (style) {
1255
- transaction.addMark(from, to, markType.create({ style }));
1256
- }
1257
- },
1258
- );
1259
- if (transaction.docChanged) editor.view.dispatch(transaction);
1260
- }
1261
-
1262
- const selectionAfter = window.getSelection();
1263
- if (
1264
- !selectionAfter ||
1265
- selectionAfter.rangeCount !== 1 ||
1266
- !rangeInside(editor.view.dom, selectionAfter.getRangeAt(0))
1267
- ) {
1268
- return null;
1269
- }
1270
- const nextRange = selectionAfter.getRangeAt(0).cloneRange();
1271
- return nextRange.collapsed ? null : nextRange;
1272
- },
1273
- }),
1274
- [editor, setSelectionFromOffsets, setSelectionFromRange, value],
1275
- );
1276
-
1277
- useEffect(() => {
1278
- if (!editor || editor.isDestroyed || selectionAppliedRef.current) return;
1279
- let attempts = 0;
1280
- let frame = 0;
1281
- const applySelection = () => {
1282
- if (editor.isDestroyed) return;
1283
- if (initialSelection && setSelectionFromOffsets(initialSelection)) {
1284
- selectionAppliedRef.current = true;
1285
- return;
1286
- }
1287
-
1288
- const walker = editor.view.dom.ownerDocument.createTreeWalker(
1289
- editor.view.dom,
1290
- NodeFilter.SHOW_TEXT,
1291
- );
1292
- let lastText: Text | null = null;
1293
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
1294
- if ((node.textContent ?? "").trim()) lastText = node as Text;
1295
- }
1296
- if (lastText) {
1297
- try {
1298
- const position = editor.view.posAtDOM(lastText, lastText.data.length);
1299
- editor.commands.focus();
1300
- editor.commands.setTextSelection(position);
1301
- selectionAppliedRef.current = true;
1302
- return;
1303
- // coercion-ok: the shared editor may still be applying its initial value.
1304
- } catch {
1305
- // The shared editor may still be applying its initial value.
1306
- }
1307
- }
1308
- attempts += 1;
1309
- if (attempts < 6) frame = requestAnimationFrame(applySelection);
1310
- else {
1311
- editor.chain().focus("end").run();
1312
- selectionAppliedRef.current = true;
1313
- }
1314
- };
1315
- frame = requestAnimationFrame(applySelection);
1316
- return () => cancelAnimationFrame(frame);
1317
- }, [editor, initialSelection, setSelectionFromOffsets]);
1318
-
1319
- return (
1320
- <SharedRichEditor
1321
- value={normalizeSlideEditorContent(value)}
1322
- onChange={onChange}
1323
- onEditorReady={handleEditorReady}
1324
- dialect="gfm"
1325
- preset="content"
1326
- features={{
1327
- codeBlock: false,
1328
- markdown: false,
1329
- placeholder: false,
1330
- tables: false,
1331
- tasks: false,
1332
- }}
1333
- dragHandle={false}
1334
- placeholder=""
1335
- unstyled
1336
- starterKit={SLIDE_STARTER_KIT}
1337
- className="slide-shared-rich-editor"
1338
- ariaLabel="Slide text"
1339
- getMarkdown={(currentEditor) => currentEditor.getHTML()}
1340
- parseValue={false}
1341
- normalizeValue={(nextValue) => nextValue}
1342
- extraExtensions={[SlideBold, SlideTextStyle, SlideBlockStyle]}
1343
- />
1344
- );
1345
- });
1346
-
1347
- SlideRichTextEditor.displayName = "SlideRichTextEditor";