@lupinum/ginko-editor 0.1.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +7 -73
  2. package/LICENSE +1 -1
  3. package/README.md +15 -340
  4. package/dist/assets.d.ts +70 -0
  5. package/dist/assets.js +31 -0
  6. package/dist/core/component-props.d.ts +87 -0
  7. package/dist/core/component-props.js +134 -0
  8. package/dist/core/convert.d.ts +24 -0
  9. package/dist/core/convert.js +278 -0
  10. package/dist/core/editor.d.ts +60 -0
  11. package/dist/core/editor.js +85 -0
  12. package/dist/core/extensions.d.ts +38 -0
  13. package/dist/core/extensions.js +444 -0
  14. package/dist/core/file-images.d.ts +9 -0
  15. package/dist/core/file-images.js +54 -0
  16. package/dist/core/image-frame.d.ts +23 -0
  17. package/dist/core/image-frame.js +24 -0
  18. package/dist/core/index.d.ts +17 -0
  19. package/dist/core/index.js +17 -0
  20. package/dist/core/link-card.d.ts +20 -0
  21. package/dist/core/link-card.js +70 -0
  22. package/dist/core/link.d.ts +3 -0
  23. package/dist/core/link.js +8 -0
  24. package/dist/core/move.d.ts +11 -0
  25. package/dist/core/move.js +37 -0
  26. package/dist/core/paste-html.d.ts +6 -0
  27. package/dist/core/paste-html.js +384 -0
  28. package/dist/core/paste.d.ts +21 -0
  29. package/dist/core/paste.js +108 -0
  30. package/dist/core/problems.d.ts +31 -0
  31. package/dist/core/problems.js +54 -0
  32. package/dist/core/search.d.ts +47 -0
  33. package/dist/core/search.js +148 -0
  34. package/dist/core/slash.d.ts +93 -0
  35. package/dist/core/slash.js +215 -0
  36. package/dist/core/table.d.ts +34 -0
  37. package/dist/core/table.js +141 -0
  38. package/dist/core/uploads.d.ts +23 -0
  39. package/dist/core/uploads.js +71 -0
  40. package/dist/core/use-editor.d.ts +19 -0
  41. package/dist/core/use-editor.js +53 -0
  42. package/dist/index.d.ts +6 -15
  43. package/dist/index.js +6 -5668
  44. package/dist/issues.d.ts +49 -0
  45. package/dist/issues.js +9 -0
  46. package/dist/today.d.ts +6 -0
  47. package/dist/today.js +19 -0
  48. package/dist/useUpload.d.ts +48 -0
  49. package/dist/useUpload.js +59 -0
  50. package/dist/values.d.ts +14 -0
  51. package/dist/values.js +36 -0
  52. package/package.json +35 -95
  53. package/dist/GinkoEditor.vue.d.ts +0 -96
  54. package/dist/GinkoImagePicker.vue.d.ts +0 -36
  55. package/dist/agent/AGENTS.md +0 -13
  56. package/dist/agent/pages/docs/getting-started/collaboration.md +0 -435
  57. package/dist/agent/pages/docs/getting-started/component-coverage.md +0 -107
  58. package/dist/agent/pages/docs/getting-started/customize.md +0 -384
  59. package/dist/agent/pages/docs/getting-started/images.md +0 -188
  60. package/dist/agent/pages/docs/getting-started/in-place-editing.md +0 -110
  61. package/dist/agent/pages/docs/getting-started/layout-blocks.md +0 -148
  62. package/dist/agent/pages/docs/getting-started/runtime.md +0 -111
  63. package/dist/agent/pages/docs/getting-started.md +0 -128
  64. package/dist/authoring-D7MJezVG.js +0 -1780
  65. package/dist/authoring-D7MJezVG.js.map +0 -1
  66. package/dist/authoring.d.ts +0 -122
  67. package/dist/authoring.js +0 -2
  68. package/dist/collaboration.d.ts +0 -14
  69. package/dist/collaboration.js +0 -907
  70. package/dist/collaboration.js.map +0 -1
  71. package/dist/composables/useAssetRequests.d.ts +0 -44
  72. package/dist/composables/useCollaborationBinding.d.ts +0 -59
  73. package/dist/composables/useDevice.d.ts +0 -10
  74. package/dist/composables/useInsertMenu.d.ts +0 -67
  75. package/dist/composables/useMarkdownSync.d.ts +0 -96
  76. package/dist/composables/useStableAuthoringKit.d.ts +0 -16
  77. package/dist/documentConfig-Z6LdrWZj.js +0 -2360
  78. package/dist/documentConfig-Z6LdrWZj.js.map +0 -1
  79. package/dist/editorProps.d.ts +0 -124
  80. package/dist/index.js.map +0 -1
  81. package/dist/layout-kit.d.ts +0 -922
  82. package/dist/lib/collaboration/presence-record.d.ts +0 -18
  83. package/dist/lib/collaboration/presence.d.ts +0 -103
  84. package/dist/lib/collaboration/protocol.d.ts +0 -133
  85. package/dist/lib/collaboration/recovery.d.ts +0 -45
  86. package/dist/lib/collaboration/session.d.ts +0 -163
  87. package/dist/lib/collaboration/validation.d.ts +0 -42
  88. package/dist/lib/component-converters.d.ts +0 -119
  89. package/dist/lib/config/documentConfig.d.ts +0 -19
  90. package/dist/lib/config/editorConfig.d.ts +0 -38
  91. package/dist/lib/container-items.d.ts +0 -55
  92. package/dist/lib/conversionInvariants.d.ts +0 -3
  93. package/dist/lib/conversionLogger.d.ts +0 -10
  94. package/dist/lib/conversionPipeline.d.ts +0 -17
  95. package/dist/lib/conversionState.d.ts +0 -10
  96. package/dist/lib/conversionTypes.d.ts +0 -50
  97. package/dist/lib/editor-operations.d.ts +0 -39
  98. package/dist/lib/environment.d.ts +0 -6
  99. package/dist/lib/extensions/code-block.d.ts +0 -18
  100. package/dist/lib/extensions/component-boundary.d.ts +0 -9
  101. package/dist/lib/extensions/container-items.d.ts +0 -29
  102. package/dist/lib/extensions/element.d.ts +0 -19
  103. package/dist/lib/extensions/file.d.ts +0 -24
  104. package/dist/lib/extensions/heading.d.ts +0 -5
  105. package/dist/lib/extensions/image-upload.d.ts +0 -39
  106. package/dist/lib/extensions/image.d.ts +0 -39
  107. package/dist/lib/extensions/index.d.ts +0 -10
  108. package/dist/lib/extensions/inline-element.d.ts +0 -13
  109. package/dist/lib/extensions/markdown-clipboard.d.ts +0 -21
  110. package/dist/lib/extensions/profile.d.ts +0 -11
  111. package/dist/lib/extensions/slot.d.ts +0 -16
  112. package/dist/lib/extensions/span-style.d.ts +0 -15
  113. package/dist/lib/extensions/video.d.ts +0 -15
  114. package/dist/lib/image-properties.d.ts +0 -20
  115. package/dist/lib/input-rules.d.ts +0 -7
  116. package/dist/lib/markdown.d.ts +0 -11
  117. package/dist/lib/marks.d.ts +0 -7
  118. package/dist/lib/mdcToTiptap.d.ts +0 -20
  119. package/dist/lib/mdcTypes.d.ts +0 -20
  120. package/dist/lib/nodes.d.ts +0 -57
  121. package/dist/lib/nodeviews/block-actions.d.ts +0 -7
  122. package/dist/lib/nodeviews/code.d.ts +0 -4
  123. package/dist/lib/nodeviews/columns.d.ts +0 -17
  124. package/dist/lib/nodeviews/component.d.ts +0 -6
  125. package/dist/lib/nodeviews/icons.d.ts +0 -26
  126. package/dist/lib/nodeviews/image.d.ts +0 -9
  127. package/dist/lib/nodeviews/items.d.ts +0 -15
  128. package/dist/lib/nodeviews/lifecycle.d.ts +0 -45
  129. package/dist/lib/nodeviews/popover.d.ts +0 -15
  130. package/dist/lib/nodeviews/settings.d.ts +0 -11
  131. package/dist/lib/nodeviews/table-operations.d.ts +0 -50
  132. package/dist/lib/nodeviews/table.d.ts +0 -4
  133. package/dist/lib/profiles.d.ts +0 -62
  134. package/dist/lib/property-input.d.ts +0 -10
  135. package/dist/lib/property-step.d.ts +0 -77
  136. package/dist/lib/props.d.ts +0 -13
  137. package/dist/lib/stripStyleNodes.d.ts +0 -2
  138. package/dist/lib/tiptapToMdc.d.ts +0 -18
  139. package/dist/presence-record-CLdPZWKC.js +0 -291
  140. package/dist/presence-record-CLdPZWKC.js.map +0 -1
  141. package/dist/runtime.d.ts +0 -13
  142. package/dist/runtime.js +0 -3
  143. package/dist/style.css +0 -2
  144. package/dist/types.d.ts +0 -126
  145. package/dist/ui/GinkoActionButton.vue.d.ts +0 -8
  146. package/dist/ui/GinkoInsertMenu.vue.d.ts +0 -49
  147. package/dist/ui/GinkoKeyboardDock.vue.d.ts +0 -15
  148. package/dist/ui/GinkoNodePopover.vue.d.ts +0 -21
  149. package/dist/ui/GinkoRecipeIcon.vue.d.ts +0 -6
  150. package/dist/ui/GinkoSelectionToolbar.vue.d.ts +0 -10
  151. package/dist/ui/GinkoToolbar.vue.d.ts +0 -26
  152. package/dist/ui/GinkoToolbarIcon.vue.d.ts +0 -6
  153. package/dist/ui/block-shortcuts.d.ts +0 -6
  154. package/dist/ui/commands.d.ts +0 -78
  155. package/dist/ui/context.d.ts +0 -23
  156. package/dist/ui/editor-keyboard.d.ts +0 -15
  157. package/dist/ui/messages.d.ts +0 -214
  158. package/dist/ui/messages.de.d.ts +0 -6
  159. package/dist/ui/recipe-command.d.ts +0 -14
  160. package/dist/ui/recipe-search.d.ts +0 -47
  161. package/dist/ui/slash-command.d.ts +0 -17
  162. package/dist/ui/writingRecipes.d.ts +0 -13
  163. package/skills/ginko-editor/SKILL.md +0 -40
  164. package/skills/ginko-editor/agents/openai.yaml +0 -4
  165. package/skills/ginko-editor/references/in-place-editing.md +0 -50
  166. package/skills/ginko-editor/references/quickstart.md +0 -55
@@ -0,0 +1,70 @@
1
+ import { imageFrameOf, TEXT_IMAGE_FRAMES } from "./image-frame.js";
2
+ import { propFields, editorMeta } from "./component-props.js";
3
+ export function linkCardTag(registry) {
4
+ if (!registry) return void 0;
5
+ const candidates = Object.entries(registry).filter(([, def]) => def.kind === "block" && !def.parents?.length && !editorMeta(def).hidden).map(([tag, def]) => ({ tag, fields: propFields(def) })).filter(({ fields }) => fields.some(([key, field]) => key === "href" && !field.optional) && fields.every(([key, field]) => key === "href" || field.optional));
6
+ return candidates.sort((a, b) => a.fields.length - b.fields.length)[0]?.tag;
7
+ }
8
+ export function makeLinkCard(editor, pos, url, tag) {
9
+ const node = editor.state.doc.nodeAt(pos);
10
+ if (!node || node.type.name !== "paragraph" || node.textContent !== url) return false;
11
+ const type = editor.schema.nodes.component;
12
+ const paragraph = editor.schema.nodes.paragraph;
13
+ if (!type || !paragraph) return false;
14
+ const card = type.create({ tag, props: { href: url } }, paragraph.create());
15
+ const tr = editor.state.tr.replaceWith(pos, pos + node.nodeSize, card);
16
+ editor.view.dispatch(tr);
17
+ editor.commands.focus(pos + 2);
18
+ return true;
19
+ }
20
+ export function figureTag(registry) {
21
+ if (!registry) return void 0;
22
+ const candidates = Object.entries(registry).filter(([, def]) => def.kind === "block" && !def.parents?.length && !editorMeta(def).hidden).map(([tag, def]) => ({ tag, fields: propFields(def) })).filter(({ fields }) => fields.some(([key, field]) => key === "src" && field.type === "image" && !field.optional) && fields.some(([key, field]) => key === "caption" && field.type === "text" && field.optional));
23
+ return candidates.sort((a, b) => a.fields.length - b.fields.length)[0]?.tag;
24
+ }
25
+ export function makeFigure(editor, pos, tag, registry, alt) {
26
+ const { state } = editor;
27
+ const image = state.doc.nodeAt(pos);
28
+ const type = editor.schema.nodes.component;
29
+ if (!image || image.type.name !== "image" || !type) return void 0;
30
+ const props = { src: String(image.attrs.src ?? "") };
31
+ const altField = registry[tag]?.props.alt;
32
+ if (altField?.type === "text" && alt.trim()) props.alt = alt.trim();
33
+ const frame = imageFrameOf(image);
34
+ const shape = TEXT_IMAGE_FRAMES.find((f) => f.aspect === frame.aspect)?.figure;
35
+ const offers = (key, value) => {
36
+ const field = registry[tag]?.props[key];
37
+ return field?.type === "choice" && field.options.some((o) => o.value === value);
38
+ };
39
+ if (shape && offers("aspect", shape)) {
40
+ props.aspect = shape;
41
+ if (offers("fit", frame.fit)) props.fit = frame.fit;
42
+ }
43
+ const figure = type.create({ tag, props });
44
+ const $pos = state.doc.resolve(pos);
45
+ const before = $pos.nodeBefore;
46
+ const after = state.doc.resolve(pos + 1).nodeAfter;
47
+ const from = pos - (before?.isText ? before.text.length - before.text.trimEnd().length : 0);
48
+ const to = pos + 1 + (after?.isText ? after.text.length - after.text.trimStart().length : 0);
49
+ const first = from === $pos.start();
50
+ const last = to === $pos.end();
51
+ const tr = state.tr;
52
+ let at;
53
+ if (first && last) {
54
+ at = $pos.before();
55
+ tr.replaceWith(at, $pos.after(), figure);
56
+ } else if (first) {
57
+ at = $pos.before();
58
+ tr.delete(from, to).insert(at, figure);
59
+ } else if (last) {
60
+ tr.delete(from, to);
61
+ at = tr.mapping.map($pos.after());
62
+ tr.insert(at, figure);
63
+ } else {
64
+ tr.delete(from, to).split(from);
65
+ at = from + 1;
66
+ tr.insert(at, figure);
67
+ }
68
+ editor.view.dispatch(tr);
69
+ return at;
70
+ }
@@ -0,0 +1,3 @@
1
+ export declare const LINK_REFUSED = "Dieser Link ist nicht erlaubt. Erlaubt sind Webadressen (https://\u2026), E-Mail (mailto:) und Telefon (tel:).";
2
+ /** What a person types into the link box, made into an address: "www.x.de" gets https://, "a@b.de" gets mailto:. */
3
+ export declare function normalizeHref(raw: string): string;
@@ -0,0 +1,8 @@
1
+ export const LINK_REFUSED = "Dieser Link ist nicht erlaubt. Erlaubt sind Webadressen (https://\u2026), E-Mail (mailto:) und Telefon (tel:).";
2
+ export function normalizeHref(raw) {
3
+ const t = raw.trim();
4
+ if (/^tel:/i.test(t)) return t.replace(/\s+/g, "");
5
+ if (/^[a-z0-9-]+(\.[a-z0-9-]+)+([/?#]\S*)?$/i.test(t)) return `https://${t}`;
6
+ if (/^[^\s@/:]+@[^\s@/:]+\.[^\s@/:]+$/.test(t)) return `mailto:${t}`;
7
+ return t;
8
+ }
@@ -0,0 +1,11 @@
1
+ import { Extension, type Editor } from '@tiptap/core';
2
+ export declare const moveBlock: (editor: Editor, direction: "up" | "down") => boolean;
3
+ declare module '@tiptap/core' {
4
+ interface Commands<ReturnType> {
5
+ ginkoMove: {
6
+ moveBlockUp: () => ReturnType;
7
+ moveBlockDown: () => ReturnType;
8
+ };
9
+ }
10
+ }
11
+ export declare const MoveExtension: Extension<any, any>;
@@ -0,0 +1,37 @@
1
+ import { Extension } from "@tiptap/core";
2
+ import { NodeSelection, TextSelection } from "@tiptap/pm/state";
3
+ function applyMove(state, tr, direction, dispatch) {
4
+ const { doc, selection } = state;
5
+ if (state.schema.topNodeType.spec.content === "paragraph") return false;
6
+ const index = selection.$from.index(0);
7
+ const target = direction === "up" ? index - 1 : index + 1;
8
+ if (target < 0 || target >= doc.childCount) return false;
9
+ const isRoom = (i) => i === doc.childCount - 1 && doc.child(i).type.name === "paragraph" && doc.child(i).content.size === 0;
10
+ if (isRoom(index) || isRoom(target)) return false;
11
+ let start = 0;
12
+ for (let i = 0; i < Math.min(index, target); i++) start += doc.child(i).nodeSize;
13
+ const upper = doc.child(Math.min(index, target));
14
+ const lower = doc.child(Math.max(index, target));
15
+ const moving = doc.child(index);
16
+ if (!dispatch) return true;
17
+ tr.replaceWith(start, start + upper.nodeSize + lower.nodeSize, direction === "up" ? [moving, upper] : [lower, moving]);
18
+ const oldStart = direction === "up" ? start + upper.nodeSize : start;
19
+ const newStart = direction === "up" ? start : start + lower.nodeSize;
20
+ const shift = newStart - oldStart;
21
+ tr.setSelection(selection instanceof NodeSelection ? NodeSelection.create(tr.doc, selection.from + shift) : TextSelection.create(tr.doc, selection.anchor + shift, selection.head + shift));
22
+ tr.scrollIntoView();
23
+ return true;
24
+ }
25
+ export const moveBlock = (editor, direction) => direction === "up" ? editor.commands.moveBlockUp() : editor.commands.moveBlockDown();
26
+ export const MoveExtension = Extension.create({
27
+ name: "ginkoMove",
28
+ addCommands() {
29
+ return {
30
+ moveBlockUp: () => ({ state, tr, dispatch }) => applyMove(state, tr, "up", !!dispatch),
31
+ moveBlockDown: () => ({ state, tr, dispatch }) => applyMove(state, tr, "down", !!dispatch)
32
+ };
33
+ },
34
+ addKeyboardShortcuts() {
35
+ return { "Alt-ArrowUp": () => moveBlock(this.editor, "up"), "Alt-ArrowDown": () => moveBlock(this.editor, "down") };
36
+ }
37
+ });
@@ -0,0 +1,6 @@
1
+ import type { MarkdownProfile } from '@lupinum/ginko/internal';
2
+ export interface CleanOptions {
3
+ profile: MarkdownProfile;
4
+ }
5
+ /** `html` cleaned for `profile`. Returns an empty string when nothing is left (the paste then does nothing). */
6
+ export declare function cleanPastedHtml(html: string, options: CleanOptions): string;
@@ -0,0 +1,384 @@
1
+ import { fileRefOf, isSafeHref, profileCovers } from "@lupinum/ginko/internal";
2
+ const DROP = /* @__PURE__ */ new Set(["script", "style", "meta", "link", "title", "head", "noscript", "iframe", "object", "embed", "svg", "canvas", "form", "button", "input", "select", "textarea", "nav", "aside", "footer", "audio", "video", "template", "xml"]);
3
+ const BLOCK = /* @__PURE__ */ new Set(["p", "div", "section", "article", "main", "header", "figure", "figcaption", "address", "details", "summary", "dl", "dt", "dd", "center", "body", "html", "fieldset"]);
4
+ const levelOf = (n) => n <= 2 ? 2 : n === 3 ? 3 : 4;
5
+ const styleOf = (el) => (el.getAttribute("style") ?? "").toLowerCase().replace(/\s+/g, "");
6
+ const isBoldStyle = (style) => /(?:^|;)font-weight:(bold|bolder|[6-9]00)/.test(style);
7
+ const isItalicStyle = (style) => /(?:^|;)font-style:italic/.test(style);
8
+ const isStrikeStyle = (style) => /text-decoration(-line)?:[^;]*line-through/.test(style);
9
+ const isMonoStyle = (style) => /font-family:[^;]*(courier|consolas|monospace|menlo)/.test(style);
10
+ const tidy = (text) => text.replace(/[\u00a0\u2007\u202f]/g, " ").replace(/[\u200b\ufeff]/g, "").replace(/\s+/g, " ");
11
+ const lowerTag = (node) => node.nodeType === 1 ? node.tagName.toLowerCase().replace(/^o:|^w:/, "o:") : "";
12
+ function inlineChildren(node, ctx, out = [], inHeading = false) {
13
+ for (const child of Array.from(node.childNodes)) {
14
+ if (child.nodeType === 3) {
15
+ const text = tidy(child.textContent ?? "");
16
+ if (text) out.push(ctx.doc.createTextNode(text));
17
+ continue;
18
+ }
19
+ if (child.nodeType !== 1) continue;
20
+ const el = child;
21
+ const tag = lowerTag(el);
22
+ if (DROP.has(tag) || tag.startsWith("o:p") && !el.textContent?.trim()) continue;
23
+ const style = styleOf(el);
24
+ if (/mso-list:ignore/.test(style)) continue;
25
+ if (tag === "br") {
26
+ out.push(ctx.doc.createElement("br"));
27
+ continue;
28
+ }
29
+ if (tag === "img") {
30
+ const img = cleanImage(el, ctx);
31
+ if (img) out.push(img);
32
+ continue;
33
+ }
34
+ const inner = inlineChildren(el, ctx, [], inHeading);
35
+ if (!inner.length) continue;
36
+ let wrapped = inner;
37
+ const wrap = (name, attrs = {}) => {
38
+ const outer = ctx.doc.createElement(name);
39
+ for (const [key, value] of Object.entries(attrs)) outer.setAttribute(key, value);
40
+ for (const item of wrapped) outer.appendChild(item);
41
+ wrapped = [outer];
42
+ };
43
+ const guid = (el.getAttribute("id") ?? "").startsWith("docs-internal-guid");
44
+ const bold = !inHeading && !guid && ctx.marks && (tag === "strong" || tag === "b" && !/(?:^|;)font-weight:(normal|400)/.test(style) || isBoldStyle(style));
45
+ const italic = !inHeading && ctx.marks && (tag === "em" || tag === "i" || isItalicStyle(style));
46
+ const strike = ctx.rich && (tag === "del" || tag === "s" || tag === "strike" || isStrikeStyle(style));
47
+ const code = ctx.rich && (tag === "code" || tag === "kbd" || tag === "samp" || tag === "tt" || isMonoStyle(style));
48
+ if (code) wrap("code");
49
+ if (strike) wrap("del");
50
+ if (italic) wrap("em");
51
+ if (bold) wrap("strong");
52
+ if (tag === "a") {
53
+ const href = hrefOf(el.getAttribute("href"));
54
+ if (href) wrap("a", { href });
55
+ }
56
+ out.push(...wrapped);
57
+ }
58
+ return out;
59
+ }
60
+ function hrefOf(raw) {
61
+ let href = (raw ?? "").trim();
62
+ if (!href || href.startsWith("#")) return void 0;
63
+ try {
64
+ const url = new URL(href, "https://x.invalid");
65
+ if (/^(www\.)?google\.[a-z.]+$/.test(url.hostname) && url.pathname === "/url" && url.searchParams.get("q")) href = url.searchParams.get("q");
66
+ } catch {
67
+ }
68
+ return isSafeHref(href) ? href : void 0;
69
+ }
70
+ function cleanImage(el, ctx) {
71
+ if (!ctx.rich) return void 0;
72
+ const src = (el.getAttribute("src") ?? "").trim();
73
+ const library = fileRefOf(src) !== void 0;
74
+ if (!library && !/^https:\/\//i.test(src)) return void 0;
75
+ const size = (name) => Number.parseInt(el.getAttribute(name) ?? "", 10);
76
+ if (size("width") <= 2 || size("height") <= 2 || /display:none/.test(styleOf(el)) || !library && /(pixel|beacon|track|spacer)/i.test(src)) return void 0;
77
+ const img = ctx.doc.createElement("img");
78
+ img.setAttribute("src", src);
79
+ img.setAttribute("alt", (el.getAttribute("alt") ?? "").trim());
80
+ return img;
81
+ }
82
+ const isBlank = (nodes) => nodes.every((n) => n.nodeType === 3 ? !n.textContent.trim() : lowerTag(n) === "br");
83
+ function paragraph(ctx, content) {
84
+ trim(content);
85
+ if (isBlank(content)) return void 0;
86
+ const p = ctx.doc.createElement("p");
87
+ for (const node of content) p.appendChild(node);
88
+ return p;
89
+ }
90
+ function trim(nodes) {
91
+ while (nodes.length && (lowerTag(nodes[0]) === "br" || nodes[0].nodeType === 3 && !nodes[0].textContent.trim())) nodes.shift();
92
+ while (nodes.length && (lowerTag(nodes.at(-1)) === "br" || nodes.at(-1).nodeType === 3 && !nodes.at(-1).textContent.trim())) nodes.pop();
93
+ const first = nodes[0];
94
+ if (first?.nodeType === 3) first.textContent = first.textContent.replace(/^\s+/, "");
95
+ const last = nodes.at(-1);
96
+ if (last?.nodeType === 3) last.textContent = last.textContent.replace(/\s+$/, "");
97
+ }
98
+ function wordListItem(el, ctx) {
99
+ if (lowerTag(el) !== "p" && !/^h[1-6]$/.test(lowerTag(el))) return void 0;
100
+ const match = /mso-list:[^;]*?level(\d+)/i.exec(el.getAttribute("style") ?? "");
101
+ if (!match || /mso-list:\s*none/i.test(el.getAttribute("style") ?? "")) return void 0;
102
+ const marker = Array.from(el.querySelectorAll("span")).find((s) => /mso-list:\s*ignore/i.test(s.getAttribute("style") ?? ""));
103
+ const label = tidy(marker?.textContent ?? "").trim();
104
+ return { level: Number(match[1]), ordered: /^(\d+|[a-z]|[ivxlc]+)[.)]$/i.test(label), content: inlineChildren(el, ctx) };
105
+ }
106
+ function buildList(items, ctx) {
107
+ const root = ctx.doc.createElement("div");
108
+ const stack = [];
109
+ for (const item of items) {
110
+ trim(item.content);
111
+ if (isBlank(item.content)) continue;
112
+ while (stack.length && stack.at(-1).level > item.level) stack.pop();
113
+ let top = stack.at(-1);
114
+ if (!top || top.level < item.level) {
115
+ const list = ctx.doc.createElement(item.ordered ? "ol" : "ul");
116
+ if (top?.last) top.last.appendChild(list);
117
+ else root.appendChild(list);
118
+ top = { level: item.level, list };
119
+ stack.push(top);
120
+ }
121
+ const li = ctx.doc.createElement("li");
122
+ for (const node of item.content) li.appendChild(node);
123
+ top.list.appendChild(li);
124
+ top.last = li;
125
+ }
126
+ return root.firstElementChild;
127
+ }
128
+ function convertList(el, ctx, out) {
129
+ const ordered = lowerTag(el) === "ol";
130
+ if (!ctx.blocks) {
131
+ for (const li of Array.from(el.children)) if (lowerTag(li) === "li") {
132
+ const p = paragraph(ctx, inlineChildren(li, ctx));
133
+ if (p) out.push(p);
134
+ }
135
+ return;
136
+ }
137
+ const list = ctx.doc.createElement(ordered ? "ol" : "ul");
138
+ const start = Number.parseInt(el.getAttribute("start") ?? "", 10);
139
+ if (ordered && start > 1) list.setAttribute("start", String(start));
140
+ for (const li of Array.from(el.children)) {
141
+ if (lowerTag(li) !== "li") continue;
142
+ const item = ctx.doc.createElement("li");
143
+ const inline = [];
144
+ const nested = [];
145
+ const flush = () => {
146
+ trim(inline);
147
+ if (!isBlank(inline)) for (const n of inline) item.appendChild(n);
148
+ inline.length = 0;
149
+ };
150
+ const walk = (node) => {
151
+ for (const child of Array.from(node.childNodes)) {
152
+ const tag = lowerTag(child);
153
+ if (tag === "ul" || tag === "ol") {
154
+ flush();
155
+ convertList(child, ctx, nested);
156
+ } else if (tag === "p" || tag === "div") {
157
+ if (inline.length) inline.push(ctx.doc.createElement("br"));
158
+ walk(child);
159
+ } else inline.push(...inlineChildren({ childNodes: [child] }, ctx));
160
+ }
161
+ };
162
+ walk(li);
163
+ flush();
164
+ for (const n of nested) item.appendChild(n);
165
+ if (item.childNodes.length) list.appendChild(item);
166
+ }
167
+ if (list.childNodes.length) out.push(list);
168
+ }
169
+ function convertTable(el, ctx, out) {
170
+ const rows = Array.from(el.querySelectorAll("tr")).filter((tr) => tr.closest("table") === el);
171
+ if (!ctx.rich) {
172
+ for (const tr of rows) {
173
+ const cells = Array.from(tr.children).filter((c) => /^(td|th)$/.test(lowerTag(c))).map((c) => tidy(c.textContent ?? "").trim()).filter(Boolean);
174
+ if (!cells.length) continue;
175
+ const p = ctx.doc.createElement("p");
176
+ p.textContent = cells.join(" \xB7 ");
177
+ out.push(p);
178
+ }
179
+ return;
180
+ }
181
+ const grid = rows.map(() => []);
182
+ rows.forEach((tr, r) => {
183
+ let c = 0;
184
+ for (const cell of Array.from(tr.children)) {
185
+ if (!/^(td|th)$/.test(lowerTag(cell))) continue;
186
+ while (grid[r][c] !== void 0) c++;
187
+ const span = (name, max) => Math.min(max, Math.max(1, Number.parseInt(cell.getAttribute(name) ?? "", 10) || 1));
188
+ const cols = span("colspan", 100);
189
+ const down = span("rowspan", rows.length - r);
190
+ const inline = inlineChildren(cell, ctx);
191
+ trim(inline);
192
+ for (let y = r; y < r + down; y++) for (let x = c; x < c + cols; x++) grid[y][x] = null;
193
+ grid[r][c] = inline;
194
+ c += cols;
195
+ }
196
+ });
197
+ const width = Math.max(0, ...grid.map((row) => row.length));
198
+ const table = ctx.doc.createElement("table");
199
+ const body = ctx.doc.createElement("tbody");
200
+ table.appendChild(body);
201
+ for (const places of grid) {
202
+ if (!places.length) continue;
203
+ const row = ctx.doc.createElement("tr");
204
+ for (let c = 0; c < width; c++) {
205
+ const made = ctx.doc.createElement(body.childNodes.length === 0 ? "th" : "td");
206
+ const p = ctx.doc.createElement("p");
207
+ for (const n of places[c] ?? []) p.appendChild(n);
208
+ made.appendChild(p);
209
+ row.appendChild(made);
210
+ }
211
+ body.appendChild(row);
212
+ }
213
+ if (body.childNodes.length) out.push(table);
214
+ }
215
+ const hasBlocks = (el) => el.querySelector("p,div,h1,h2,h3,h4,h5,h6,ul,ol,table,blockquote,pre,hr") !== null;
216
+ function blockChildren(node, ctx, out = []) {
217
+ let run = [];
218
+ const flush = () => {
219
+ const p = paragraph(ctx, run);
220
+ if (p) out.push(p);
221
+ run = [];
222
+ };
223
+ const children = Array.from(node.childNodes);
224
+ for (let i = 0; i < children.length; i++) {
225
+ const child = children[i];
226
+ if (child.nodeType === 3 || child.nodeType !== 1) {
227
+ if (child.nodeType === 3) run.push(...inlineChildren({ childNodes: [child] }, ctx));
228
+ continue;
229
+ }
230
+ const el = child;
231
+ const tag = lowerTag(el);
232
+ if (DROP.has(tag)) continue;
233
+ const first = wordListItem(el, ctx);
234
+ if (first) {
235
+ flush();
236
+ const items = [first];
237
+ while (i + 1 < children.length) {
238
+ const next = children[i + 1];
239
+ if (next.nodeType === 3 && !next.textContent.trim()) {
240
+ i++;
241
+ continue;
242
+ }
243
+ const item = next.nodeType === 1 ? wordListItem(next, ctx) : void 0;
244
+ if (!item) break;
245
+ items.push(item);
246
+ i++;
247
+ }
248
+ if (ctx.blocks) {
249
+ const list = buildList(items, ctx);
250
+ if (list) out.push(list);
251
+ } else for (const item of items) {
252
+ const p = paragraph(ctx, item.content);
253
+ if (p) out.push(p);
254
+ }
255
+ continue;
256
+ }
257
+ if (/^h[1-6]$/.test(tag) || /^mso(title|subtitle)$/i.test(el.className) || /^MsoHeading\d$/.test(el.className)) {
258
+ flush();
259
+ const fromClass = /MsoHeading(\d)/.exec(el.className)?.[1];
260
+ const n = /^h([1-6])$/.test(tag) ? Number(tag[1]) : fromClass ? Number(fromClass) : 1;
261
+ const content = inlineChildren(el, ctx, [], true);
262
+ trim(content);
263
+ if (isBlank(content)) continue;
264
+ if (!ctx.headings) {
265
+ const strong = ctx.doc.createElement("strong");
266
+ for (const c of content) strong.appendChild(c);
267
+ const p = paragraph(ctx, ctx.marks ? [strong] : content);
268
+ if (p) out.push(p);
269
+ continue;
270
+ }
271
+ const h = ctx.doc.createElement(`h${levelOf(n)}`);
272
+ for (const c of content) h.appendChild(c);
273
+ out.push(h);
274
+ continue;
275
+ }
276
+ if (tag === "ul" || tag === "ol") {
277
+ flush();
278
+ convertList(el, ctx, out);
279
+ continue;
280
+ }
281
+ if (tag === "table") {
282
+ flush();
283
+ convertTable(el, ctx, out);
284
+ continue;
285
+ }
286
+ if (tag === "blockquote") {
287
+ flush();
288
+ const inner = blockChildren(el, ctx);
289
+ if (!inner.length) continue;
290
+ if (!ctx.blocks) {
291
+ out.push(...inner);
292
+ continue;
293
+ }
294
+ const q = ctx.doc.createElement("blockquote");
295
+ for (const n of inner) q.appendChild(n);
296
+ out.push(q);
297
+ continue;
298
+ }
299
+ if (tag === "pre") {
300
+ flush();
301
+ const text = (el.textContent ?? "").replace(/\r\n?/g, "\n").replace(/\u00a0/g, " ").replace(/\n+$/, "");
302
+ if (!text.trim()) continue;
303
+ if (ctx.rich) {
304
+ const pre = ctx.doc.createElement("pre");
305
+ const code = ctx.doc.createElement("code");
306
+ code.textContent = text;
307
+ pre.appendChild(code);
308
+ out.push(pre);
309
+ } else {
310
+ const lines = text.split("\n");
311
+ const content = [];
312
+ lines.forEach((line, index) => {
313
+ if (index) content.push(ctx.doc.createElement("br"));
314
+ content.push(ctx.doc.createTextNode(line));
315
+ });
316
+ const p = ctx.doc.createElement("p");
317
+ for (const c of content) p.appendChild(c);
318
+ out.push(p);
319
+ }
320
+ continue;
321
+ }
322
+ if (tag === "hr") {
323
+ flush();
324
+ if (ctx.blocks) out.push(ctx.doc.createElement("hr"));
325
+ continue;
326
+ }
327
+ if (tag === "li") {
328
+ flush();
329
+ const p = paragraph(ctx, inlineChildren(el, ctx));
330
+ if (p) out.push(p);
331
+ continue;
332
+ }
333
+ if (tag === "img" && !ctx.rich) continue;
334
+ if (BLOCK.has(tag) || /^(tbody|thead|tfoot|tr|td|th|caption|colgroup)$/.test(tag)) {
335
+ flush();
336
+ if (hasBlocks(el)) blockChildren(el, ctx, out);
337
+ else {
338
+ const p = paragraph(ctx, inlineChildren(el, ctx));
339
+ if (p) out.push(p);
340
+ }
341
+ continue;
342
+ }
343
+ if (hasBlocks(el)) {
344
+ flush();
345
+ blockChildren(el, ctx, out);
346
+ continue;
347
+ }
348
+ run.push(...inlineChildren({ childNodes: [child] }, ctx));
349
+ }
350
+ flush();
351
+ return out;
352
+ }
353
+ function toRun(blocks, ctx) {
354
+ const p = ctx.doc.createElement("p");
355
+ const push = (nodes) => {
356
+ if (p.childNodes.length && nodes.length) p.appendChild(ctx.doc.createElement("br"));
357
+ for (const n of nodes) p.appendChild(n);
358
+ };
359
+ for (const block of blocks) {
360
+ const tag = lowerTag(block);
361
+ if (tag === "ul" || tag === "ol") for (const li of Array.from(block.childNodes)) push(Array.from(li.childNodes));
362
+ else push(Array.from(block.childNodes));
363
+ }
364
+ return p;
365
+ }
366
+ export function cleanPastedHtml(html, options) {
367
+ const { profile } = options;
368
+ const parsed = new DOMParser().parseFromString(html, "text/html");
369
+ const doc = parsed;
370
+ const ctx = {
371
+ doc,
372
+ profile,
373
+ marks: true,
374
+ headings: profileCovers(profile, "basic"),
375
+ blocks: profileCovers(profile, "basic"),
376
+ rich: profileCovers(profile, "rich")
377
+ };
378
+ const root = parsed.body ?? parsed.documentElement;
379
+ let blocks = blockChildren(root, ctx);
380
+ if (profile === "inline") blocks = [toRun(blocks, ctx)].filter((p) => p.childNodes.length);
381
+ const holder = doc.createElement("div");
382
+ for (const b of blocks) holder.appendChild(b);
383
+ return holder.innerHTML;
384
+ }
@@ -0,0 +1,21 @@
1
+ import type { ComponentRegistry, MarkdownProfile } from '@lupinum/ginko/internal';
2
+ import { Extension } from '@tiptap/core';
3
+ export interface PasteOptions {
4
+ profile: MarkdownProfile;
5
+ components?: ComponentRegistry;
6
+ /**
7
+ * Image files that were pasted or dropped, with the position they belong at (the caret for a paste, the drop point).
8
+ * Return true to say the UI takes them. Without it, image files are ignored.
9
+ */
10
+ onImageFiles?: (files: File[], pos: number) => boolean;
11
+ /** A bare address was pasted on an empty line and is now a link: the UI may offer to make it a card. `pos` = start of its paragraph. */
12
+ onUrlPasted?: (info: {
13
+ url: string;
14
+ pos: number;
15
+ }) => void;
16
+ }
17
+ /** Plain text that is meant as Markdown: a line starting a heading, list, quote or code block, or inline syntax. */
18
+ export declare function looksLikeMarkdown(text: string): boolean;
19
+ /** The image files of a clipboard or drop, when the move is about the picture (no text came with it). */
20
+ export declare function imageFilesOf(data: DataTransfer | null | undefined, allowText?: boolean): File[];
21
+ export declare function pasteExtension(options: PasteOptions): Extension<any, any>;
@@ -0,0 +1,108 @@
1
+ import { isSafeHref, parseMarkdown } from "@lupinum/ginko/internal";
2
+ import { Extension } from "@tiptap/core";
3
+ import { Fragment, Slice } from "@tiptap/pm/model";
4
+ import { Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
5
+ import { toEditorDoc } from "./convert.js";
6
+ import { cleanPastedHtml } from "./paste-html.js";
7
+ const URL_ONLY = /^https?:\/\/[^\s]+$/i;
8
+ export function looksLikeMarkdown(text) {
9
+ if (/^( {0,3}#{1,6} \S|\s*[-*+] \S|\s*\d{1,9}[.)] \S|\s*> ?\S|```|~~~|\s*[-*_]{3,}\s*$|\|.+\|\s*$)/m.test(text)) return true;
10
+ return /\*\*[^*\n]+\*\*|(?<![\w*])_[^_\n]+_(?![\w*])|\[[^\]\n]+\]\([^)\s]+\)|`[^`\n]+`|~~[^~\n]+~~/.test(text);
11
+ }
12
+ const textOfHtml = (html) => new DOMParser().parseFromString(html, "text/html").body.textContent?.replace(/\s+/g, " ").trim() ?? "";
13
+ export function imageFilesOf(data, allowText = false) {
14
+ if (!data) return [];
15
+ const files = Array.from(data.files ?? []).filter((file) => file.type.startsWith("image/"));
16
+ if (!files.length) return [];
17
+ if (!allowText && data.getData("text/plain").trim()) return [];
18
+ return files;
19
+ }
20
+ async function sliceOfMarkdown(text, view, options) {
21
+ const { profile, components } = options;
22
+ const parsed = await parseMarkdown(text, { profile, components });
23
+ if (parsed.problems.length) return void 0;
24
+ const { schema } = view.state;
25
+ try {
26
+ const doc = toEditorDoc(parsed.value.nodes, { components });
27
+ const nodes = (doc.content ?? []).map((json) => schema.nodeFromJSON(json));
28
+ nodes.forEach((node) => node.check());
29
+ if (!nodes.length) return void 0;
30
+ const only = nodes.length === 1 && nodes[0].type.name === "paragraph" ? nodes[0] : void 0;
31
+ if (only) return new Slice(only.content, 0, 0);
32
+ if (profile === "inline") return void 0;
33
+ return new Slice(Fragment.fromArray(nodes), 0, 0);
34
+ } catch {
35
+ return void 0;
36
+ }
37
+ }
38
+ function insertPlain(view, text) {
39
+ view.dispatch(view.state.tr.insertText(text).scrollIntoView().setMeta("uiEvent", "paste"));
40
+ }
41
+ function onEmptyLine(state) {
42
+ const { $from, empty } = state.selection;
43
+ return empty && $from.parent.type.name === "paragraph" && $from.parent.content.size === 0;
44
+ }
45
+ function linkUrl(view, url) {
46
+ const { state } = view;
47
+ const link = state.schema.marks.link;
48
+ if (!link || !isSafeHref(url) || !state.selection.$from.parent.inlineContent) return false;
49
+ const mark = link.create({ href: url });
50
+ const { from, to, empty } = state.selection;
51
+ const tr = empty ? state.tr.insertText(url, from).addMark(from, from + url.length, mark) : state.tr.addMark(from, to, mark);
52
+ if (empty) tr.removeStoredMark(link);
53
+ view.dispatch(tr.scrollIntoView().setMeta("uiEvent", "paste"));
54
+ return true;
55
+ }
56
+ const key = new PluginKey("ginkoPaste");
57
+ export function pasteExtension(options) {
58
+ const { profile } = options;
59
+ return Extension.create({
60
+ name: "ginkoPaste",
61
+ addProseMirrorPlugins() {
62
+ return [new Plugin({
63
+ key,
64
+ props: {
65
+ // Word, Docs and web pages: only what the profile has stays.
66
+ transformPastedHTML: (html) => cleanPastedHtml(html, { profile }),
67
+ handlePaste: (view, event) => {
68
+ const data = event.clipboardData;
69
+ if (!data) return false;
70
+ const files = imageFilesOf(data);
71
+ if (files.length && options.onImageFiles) {
72
+ if (options.onImageFiles(files, view.state.selection.to)) return true;
73
+ }
74
+ const html = data.getData("text/html");
75
+ const text = data.getData("text/plain");
76
+ const trimmed = text.trim();
77
+ if (view.state.selection.$from.parent.type.spec.code) return false;
78
+ if (URL_ONLY.test(trimmed) && (!html || textOfHtml(html) === trimmed || html.includes("<a "))) {
79
+ const onEmpty = onEmptyLine(view.state);
80
+ const start = view.state.selection.$from.before();
81
+ if (!linkUrl(view, trimmed)) return false;
82
+ if (onEmpty) options.onUrlPasted?.({ url: trimmed, pos: start });
83
+ return true;
84
+ }
85
+ if (!html && trimmed && looksLikeMarkdown(text)) {
86
+ void sliceOfMarkdown(text, view, options).then((slice) => {
87
+ if (view.isDestroyed) return;
88
+ if (slice) view.dispatch(view.state.tr.replaceSelection(slice).scrollIntoView().setMeta("uiEvent", "paste"));
89
+ else insertPlain(view, text);
90
+ });
91
+ return true;
92
+ }
93
+ return false;
94
+ },
95
+ handleDrop: (view, event) => {
96
+ const files = imageFilesOf(event.dataTransfer, true);
97
+ if (!files.length || !options.onImageFiles) return false;
98
+ const at = view.posAtCoords({ left: event.clientX, top: event.clientY });
99
+ const pos = at?.pos ?? view.state.selection.to;
100
+ const selection = TextSelection.near(view.state.doc.resolve(pos));
101
+ view.dispatch(view.state.tr.setSelection(selection));
102
+ return options.onImageFiles(files, selection.to);
103
+ }
104
+ }
105
+ })];
106
+ }
107
+ });
108
+ }