@lofcz/platejs-ai 52.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) Ziad Beyens, Dylan Schiemann, Joe Anderson, Felix Feng
4
+
5
+ Unless otherwise specified in a LICENSE file within an individual package directory,
6
+ this license applies to all files in this repository outside of those package directories.
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in
16
+ all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # Plate ai
2
+
3
+ Visit https://platejs.org/docs/ai to view the documentation.
4
+
5
+ ## License
6
+
7
+ [MIT](../../LICENSE)
@@ -0,0 +1,103 @@
1
+ import { KEYS, TextApi, bindFirst, createTSlatePlugin, getPluginType } from "platejs";
2
+ import { getTransientSuggestionKey } from "@platejs/suggestion";
3
+ import { isSelecting } from "@platejs/selection";
4
+
5
+ //#region src/lib/transforms/insertAINodes.ts
6
+ const insertAINodes = (editor, nodes, { target } = {}) => {
7
+ if (!target && !editor.selection?.focus.path) return;
8
+ const aiNodes = nodes.map((node) => ({
9
+ ...node,
10
+ ai: true
11
+ }));
12
+ editor.tf.withoutNormalizing(() => {
13
+ editor.tf.insertNodes(aiNodes, {
14
+ at: editor.api.end(target || editor.selection.focus.path),
15
+ select: true
16
+ });
17
+ editor.tf.collapse({ edge: "end" });
18
+ });
19
+ };
20
+
21
+ //#endregion
22
+ //#region src/lib/transforms/removeAIMarks.ts
23
+ const removeAIMarks = (editor, { at = [] } = {}) => {
24
+ const nodeType = getPluginType(editor, KEYS.ai);
25
+ editor.tf.unsetNodes(nodeType, {
26
+ at,
27
+ match: (n) => n[nodeType]
28
+ });
29
+ };
30
+
31
+ //#endregion
32
+ //#region src/lib/transforms/removeAINodes.ts
33
+ const removeAINodes = (editor, { at = [] } = {}) => {
34
+ editor.tf.removeNodes({
35
+ at,
36
+ match: (n) => TextApi.isText(n) && !!n.ai
37
+ });
38
+ };
39
+
40
+ //#endregion
41
+ //#region src/lib/transforms/undoAI.ts
42
+ const undoAI = (editor) => {
43
+ const hasAINodeOrAISuggestion = editor.api.some({
44
+ at: [],
45
+ match: (n) => !!n.ai
46
+ }) || editor.api.some({
47
+ at: [],
48
+ match: (n) => !!n[getTransientSuggestionKey()]
49
+ });
50
+ if (editor.history.undos.at(-1)?.ai && hasAINodeOrAISuggestion) {
51
+ editor.undo();
52
+ editor.history.redos.pop();
53
+ }
54
+ };
55
+
56
+ //#endregion
57
+ //#region src/lib/transforms/withAIBatch.ts
58
+ const withAIBatch = (editor, fn, { split } = {}) => {
59
+ if (split) editor.tf.withNewBatch(fn);
60
+ else editor.tf.withMerging(fn);
61
+ const lastBatch = editor.history.undos?.at(-1);
62
+ if (lastBatch) lastBatch.ai = true;
63
+ };
64
+
65
+ //#endregion
66
+ //#region src/lib/BaseAIPlugin.ts
67
+ const BaseAIPlugin = createTSlatePlugin({
68
+ key: KEYS.ai,
69
+ node: {
70
+ isDecoration: false,
71
+ isLeaf: true
72
+ }
73
+ }).extendTransforms(({ editor }) => ({
74
+ insertNodes: bindFirst(insertAINodes, editor),
75
+ removeMarks: bindFirst(removeAIMarks, editor),
76
+ removeNodes: bindFirst(removeAINodes, editor),
77
+ undo: bindFirst(undoAI, editor)
78
+ }));
79
+
80
+ //#endregion
81
+ //#region src/lib/utils/getEditorPrompt.ts
82
+ const createPromptFromConfig = (config, params) => {
83
+ const { isBlockSelecting, isSelecting: isSelecting$1 } = params;
84
+ if (isBlockSelecting && config.blockSelecting) return config.blockSelecting ?? config.default;
85
+ if (isSelecting$1 && config.selecting) return config.selecting ?? config.default;
86
+ return config.default;
87
+ };
88
+ const getEditorPrompt = (editor, { prompt = "" }) => {
89
+ const params = {
90
+ editor,
91
+ isBlockSelecting: editor.getOption({ key: KEYS.blockSelection }, "isSelectingSome"),
92
+ isSelecting: isSelecting(editor)
93
+ };
94
+ let promptText = "";
95
+ if (typeof prompt === "function") promptText = prompt(params);
96
+ else if (typeof prompt === "object") promptText = createPromptFromConfig(prompt, params);
97
+ else promptText = prompt;
98
+ return promptText;
99
+ };
100
+
101
+ //#endregion
102
+ export { removeAINodes as a, undoAI as i, BaseAIPlugin as n, removeAIMarks as o, withAIBatch as r, insertAINodes as s, getEditorPrompt as t };
103
+ //# sourceMappingURL=getEditorPrompt-BnVrgUl3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getEditorPrompt-BnVrgUl3.js","names":["Descendant","Path","SlateEditor","insertAINodes","editor","nodes","target","selection","focus","path","aiNodes","map","node","ai","tf","withoutNormalizing","insertNodes","at","api","end","select","collapse","edge","SlateEditor","TLocation","getPluginType","KEYS","removeAIMarks","editor","at","nodeType","ai","tf","unsetNodes","match","n","Path","SlateEditor","TextApi","removeAINodes","editor","at","tf","removeNodes","match","n","isText","ai","SlateEditor","getTransientSuggestionKey","undoAI","editor","hasAINodeOrAISuggestion","api","some","at","match","n","ai","history","undos","undo","redos","pop","History","SlateEditor","AIBatch","ai","withAIBatch","editor","fn","split","tf","withNewBatch","withMerging","lastBatch","history","undos","at","OmitFirst","PluginConfig","bindFirst","createTSlatePlugin","KEYS","removeAIMarks","undoAI","insertAINodes","removeAINodes","BaseAIPluginConfig","ai","insertNodes","removeMarks","removeNodes","BaseAIPlugin","key","node","isDecoration","isLeaf","extendTransforms","editor","undo","isSelecting","SlateEditor","KEYS","EditorPrompt","params","EditorPromptParams","PromptConfig","editor","isBlockSelecting","default","blockSelecting","selecting","createPromptFromConfig","config","getEditorPrompt","prompt","getOption","key","blockSelection","promptText"],"sources":["../src/lib/transforms/insertAINodes.ts","../src/lib/transforms/removeAIMarks.ts","../src/lib/transforms/removeAINodes.ts","../src/lib/transforms/undoAI.ts","../src/lib/transforms/withAIBatch.ts","../src/lib/BaseAIPlugin.ts","../src/lib/utils/getEditorPrompt.ts"],"sourcesContent":["import type { Descendant, Path, SlateEditor } from 'platejs';\n\nexport const insertAINodes = (\n editor: SlateEditor,\n nodes: Descendant[],\n {\n target,\n }: {\n target?: Path;\n } = {}\n) => {\n if (!target && !editor.selection?.focus.path) return;\n\n const aiNodes = nodes.map((node) => ({\n ...node,\n ai: true,\n }));\n\n editor.tf.withoutNormalizing(() => {\n editor.tf.insertNodes(aiNodes, {\n at: editor.api.end(target || editor.selection!.focus.path),\n select: true,\n });\n editor.tf.collapse({ edge: 'end' });\n });\n};\n","import { type SlateEditor, type TLocation, getPluginType, KEYS } from 'platejs';\n\nexport const removeAIMarks = (\n editor: SlateEditor,\n { at = [] }: { at?: TLocation } = {}\n) => {\n const nodeType = getPluginType(editor, KEYS.ai);\n\n editor.tf.unsetNodes(nodeType, {\n at,\n match: (n) => (n as any)[nodeType],\n });\n};\n","import { type Path, type SlateEditor, TextApi } from 'platejs';\n\nexport const removeAINodes = (\n editor: SlateEditor,\n { at = [] }: { at?: Path } = {}\n) => {\n editor.tf.removeNodes({\n at,\n match: (n) => TextApi.isText(n) && !!(n as any).ai,\n });\n};\n","import type { SlateEditor } from 'platejs';\n\nimport { getTransientSuggestionKey } from '@platejs/suggestion';\n\nexport const undoAI = (editor: SlateEditor) => {\n const hasAINodeOrAISuggestion =\n editor.api.some({\n at: [],\n match: (n) => !!(n as any).ai,\n }) ||\n editor.api.some({\n at: [],\n match: (n) => !!n[getTransientSuggestionKey()],\n });\n\n if ((editor.history.undos.at(-1) as any)?.ai && hasAINodeOrAISuggestion) {\n editor.undo();\n editor.history.redos.pop();\n }\n};\n","import type { History, SlateEditor } from 'platejs';\n\nexport type AIBatch = History['undos'][number] & { ai?: boolean };\n\nexport const withAIBatch = (\n editor: SlateEditor,\n fn: () => void,\n {\n split,\n }: {\n split?: boolean;\n } = {}\n) => {\n if (split) {\n editor.tf.withNewBatch(fn);\n } else {\n editor.tf.withMerging(fn);\n }\n\n const lastBatch = editor.history.undos?.at(-1) as AIBatch | undefined;\n\n if (lastBatch) {\n lastBatch.ai = true;\n }\n};\n","import {\n type OmitFirst,\n type PluginConfig,\n bindFirst,\n createTSlatePlugin,\n KEYS,\n} from 'platejs';\n\nimport { removeAIMarks, undoAI } from './transforms';\nimport { insertAINodes } from './transforms/insertAINodes';\nimport { removeAINodes } from './transforms/removeAINodes';\n\nexport type BaseAIPluginConfig = PluginConfig<\n 'ai',\n {},\n {},\n {\n ai: {\n insertNodes: OmitFirst<typeof insertAINodes>;\n removeMarks: OmitFirst<typeof removeAIMarks>;\n removeNodes: OmitFirst<typeof removeAINodes>;\n };\n }\n>;\n\nexport const BaseAIPlugin = createTSlatePlugin({\n key: KEYS.ai,\n node: { isDecoration: false, isLeaf: true },\n}).extendTransforms(({ editor }) => ({\n insertNodes: bindFirst(insertAINodes, editor),\n removeMarks: bindFirst(removeAIMarks, editor),\n removeNodes: bindFirst(removeAINodes, editor),\n undo: bindFirst(undoAI, editor),\n}));\n","import { isSelecting } from '@platejs/selection';\nimport { type SlateEditor, KEYS } from 'platejs';\n\nexport type EditorPrompt =\n | ((params: EditorPromptParams) => string)\n | PromptConfig\n | string;\n\nexport type EditorPromptParams = {\n editor: SlateEditor;\n isBlockSelecting: boolean;\n isSelecting: boolean;\n};\n\nexport type PromptConfig = {\n default: string;\n blockSelecting?: string;\n selecting?: string;\n};\n\nconst createPromptFromConfig = (\n config: PromptConfig,\n params: EditorPromptParams\n): string => {\n const { isBlockSelecting, isSelecting } = params;\n\n if (isBlockSelecting && config.blockSelecting) {\n return config.blockSelecting ?? config.default;\n }\n if (isSelecting && config.selecting) {\n return config.selecting ?? config.default;\n }\n return config.default;\n};\n\nexport const getEditorPrompt = (\n editor: SlateEditor,\n {\n prompt = '',\n }: {\n prompt?: EditorPrompt;\n }\n): string => {\n const params: EditorPromptParams = {\n editor,\n isBlockSelecting: editor.getOption(\n { key: KEYS.blockSelection },\n 'isSelectingSome'\n ),\n isSelecting: isSelecting(editor),\n };\n\n let promptText = '';\n\n if (typeof prompt === 'function') {\n promptText = prompt(params);\n } else if (typeof prompt === 'object') {\n promptText = createPromptFromConfig(prompt, params);\n } else {\n promptText = prompt;\n }\n\n return promptText;\n};\n"],"mappings":";;;;;AAEA,MAAaG,iBACXC,QACAC,OACA,EACEC,WAGE,EAAE,KACH;AACH,KAAI,CAACA,UAAU,CAACF,OAAOG,WAAWC,MAAMC,KAAM;CAE9C,MAAMC,UAAUL,MAAMM,KAAKC,UAAU;EACnC,GAAGA;EACHC,IAAI;EACL,EAAE;AAEHT,QAAOU,GAAGC,yBAAyB;AACjCX,SAAOU,GAAGE,YAAYN,SAAS;GAC7BO,IAAIb,OAAOc,IAAIC,IAAIb,UAAUF,OAAOG,UAAWC,MAAMC,KAAK;GAC1DW,QAAQ;GACT,CAAC;AACFhB,SAAOU,GAAGO,SAAS,EAAEC,MAAM,OAAO,CAAC;GACnC;;;;;ACtBJ,MAAaK,iBACXC,QACA,EAAEC,KAAK,EAAA,KAA2B,EAAE,KACjC;CACH,MAAMC,WAAWL,cAAcG,QAAQF,KAAKK,GAAG;AAE/CH,QAAOI,GAAGC,WAAW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AAII,oBAAoBK,OAAOH,eAC7B,QAAOG,OAAOH,kBAAkBG,OAAOJ;AAEzC,KAAIT,iBAAea,OAAOF,UACxB,QAAOE,OAAOF,aAAaE,OAAOJ;AAEpC,QAAOI,OAAOJ;;AAGhB,MAAaK,mBACXP,QACA,EACEQ,SAAS,SAIA;CACX,MAAMX,SAA6B;EACjCG;EACAC,kBAAkBD,OAAOS,UACvB,EAAEC,KAAKf,KAAKgB,gBAAgB,EAC5B,kBACD;EACDlB,aAAaA,YAAYO,OAAM;EAChC;CAED,IAAIY,aAAa;AAEjB,KAAI,OAAOJ,WAAW,WACpBI,cAAaJ,OAAOX,OAAO;UAClB,OAAOW,WAAW,SAC3BI,cAAaP,uBAAuBG,QAAQX,OAAO;KAEnDe,cAAaJ;AAGf,QAAOI"}
@@ -0,0 +1,85 @@
1
+ import { Descendant, History, OmitFirst, Path, PluginConfig, SlateEditor, TLocation } from "platejs";
2
+
3
+ //#region src/lib/transforms/insertAINodes.d.ts
4
+ declare const insertAINodes: (editor: SlateEditor, nodes: Descendant[], {
5
+ target
6
+ }?: {
7
+ target?: Path;
8
+ }) => void;
9
+ //#endregion
10
+ //#region src/lib/transforms/removeAIMarks.d.ts
11
+ declare const removeAIMarks: (editor: SlateEditor, {
12
+ at
13
+ }?: {
14
+ at?: TLocation;
15
+ }) => void;
16
+ //#endregion
17
+ //#region src/lib/transforms/removeAINodes.d.ts
18
+ declare const removeAINodes: (editor: SlateEditor, {
19
+ at
20
+ }?: {
21
+ at?: Path;
22
+ }) => void;
23
+ //#endregion
24
+ //#region src/lib/transforms/undoAI.d.ts
25
+ declare const undoAI: (editor: SlateEditor) => void;
26
+ //#endregion
27
+ //#region src/lib/transforms/withAIBatch.d.ts
28
+ type AIBatch = History['undos'][number] & {
29
+ ai?: boolean;
30
+ };
31
+ declare const withAIBatch: (editor: SlateEditor, fn: () => void, {
32
+ split
33
+ }?: {
34
+ split?: boolean;
35
+ }) => void;
36
+ //#endregion
37
+ //#region src/lib/BaseAIPlugin.d.ts
38
+ type BaseAIPluginConfig = PluginConfig<'ai', {}, {}, {
39
+ ai: {
40
+ insertNodes: OmitFirst<typeof insertAINodes>;
41
+ removeMarks: OmitFirst<typeof removeAIMarks>;
42
+ removeNodes: OmitFirst<typeof removeAINodes>;
43
+ };
44
+ }>;
45
+ declare const BaseAIPlugin: any;
46
+ //#endregion
47
+ //#region src/lib/types.d.ts
48
+ type AIToolName = 'comment' | 'edit' | 'generate' | null;
49
+ type AIMode = 'chat' | 'insert';
50
+ //#endregion
51
+ //#region src/lib/utils/getEditorPrompt.d.ts
52
+ type EditorPrompt = ((params: EditorPromptParams) => string) | PromptConfig | string;
53
+ type EditorPromptParams = {
54
+ editor: SlateEditor;
55
+ isBlockSelecting: boolean;
56
+ isSelecting: boolean;
57
+ };
58
+ type PromptConfig = {
59
+ default: string;
60
+ blockSelecting?: string;
61
+ selecting?: string;
62
+ };
63
+ declare const getEditorPrompt: (editor: SlateEditor, {
64
+ prompt
65
+ }: {
66
+ prompt?: EditorPrompt;
67
+ }) => string;
68
+ //#endregion
69
+ //#region src/lib/utils/replacePlaceholders.d.ts
70
+ type MarkdownType = 'block' | 'blockSelection' | 'blockSelectionWithBlockId' | 'blockWithBlockId' | 'editor' | 'editorWithBlockId' | 'tableCellWithId';
71
+ declare const replacePlaceholders: (editor: SlateEditor, text: string, {
72
+ prompt
73
+ }?: {
74
+ prompt?: string;
75
+ }) => string;
76
+ //#endregion
77
+ //#region src/lib/utils/getMarkdown.d.ts
78
+ declare const getMarkdown: (editor: SlateEditor, {
79
+ type
80
+ }: {
81
+ type: MarkdownType;
82
+ }) => string;
83
+ //#endregion
84
+ export { insertAINodes as _, EditorPromptParams as a, AIMode as c, BaseAIPluginConfig as d, AIBatch as f, removeAIMarks as g, removeAINodes as h, EditorPrompt as i, AIToolName as l, undoAI as m, MarkdownType as n, PromptConfig as o, withAIBatch as p, replacePlaceholders as r, getEditorPrompt as s, getMarkdown as t, BaseAIPlugin as u };
85
+ //# sourceMappingURL=index-B_bqJoKL.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-B_bqJoKL.d.ts","names":[],"sources":["../src/lib/transforms/insertAINodes.ts","../src/lib/transforms/removeAIMarks.ts","../src/lib/transforms/removeAINodes.ts","../src/lib/transforms/undoAI.ts","../src/lib/transforms/withAIBatch.ts","../src/lib/BaseAIPlugin.ts","../src/lib/types.ts","../src/lib/utils/getEditorPrompt.ts","../src/lib/utils/replacePlaceholders.ts","../src/lib/utils/getMarkdown.ts"],"sourcesContent":[],"mappings":";;;cAEa,wBACH,oBACD;;AAFT,CAAA;WAMa;AANb,CAAA,EAAA,GAAa,IAAA;;;cCAA,wBACH;;ADDV,CAAA;OCEsB;ADFtB,CAAA,EAAA,GAAa,IAAA;;;cEAA,wBACH;;AFDV,CAAA;OEEsB;AFFtB,CAAA,EAAA,GAAa,IAAA;;;cGEA,iBAAkB;;;KCFnB,OAAA,GAAU;;AJAtB,CAAA;AACU,cICG,WJDH,EAAA,CAAA,MAAA,EIEA,WJFA,EAAA,EAAA,EAAA,GAAA,GAAA,IAAA,EAAA;EAAA;CAER,CAFQ,EAAA;EACD,KAAA,CAAA,EAAA,OAAA;CACP,EAAA,GAAA,IAAA;;;AAFQ,KKSE,kBAAA,GAAqB,YLTvB,CAAA,IAAA,EAAA,CAAA,CAAA,EAAA,CAAA,CAAA,EAAA;EACD,EAAA,EAAA;IACP,WAAA,EKaiB,SLbjB,CAAA,OKakC,aLblC,CAAA;IAGW,WAAA,EKWM,SLXN,CAAA,OKWuB,aLXvB,CAAA;IAAI,WAAA,EKYE,SLZF,CAAA,OKYmB,aLZnB,CAAA;;;cKiBJ;;;KCzBD,UAAA;KAEA,MAAA;;;KCCA,YAAA,aACE,iCACV;KAGQ,kBAAA;EPNC,MAAA,EOOH,WPgBT;EAtBS,gBAAA,EAAA,OAAA;EACD,WAAA,EAAA,OAAA;CACP;AAGW,KOMD,YAAA,GPNC;EAAI,OAAA,EAAA,MAAA;;;;ACNJ,cMiCA,eNvBZ,EAAA,CAAA,MAAA,EMwBS,WNxBT,EAAA;EAAA;CAAA,EAAA;EATS,MAAA,CAAA,EMqCG,YNrCH;CACR,EAAA,GAAA,MAAA;;;KOAU,YAAA;cASC,8BACH;;CRXA;EADG,MAAA,CAAA,EAAA,MAAA;CACH,EAAA,GAAA,MAAA;;;cSyGG,sBACH;;;ET3GG,IAAA,ES+GH,YTxFT;CAtBS,EAAA,GAAA,MAAA"}
@@ -0,0 +1,2 @@
1
+ import { _ as insertAINodes, a as EditorPromptParams, c as AIMode, d as BaseAIPluginConfig, f as AIBatch, g as removeAIMarks, h as removeAINodes, i as EditorPrompt, l as AIToolName, m as undoAI, n as MarkdownType, o as PromptConfig, p as withAIBatch, r as replacePlaceholders, s as getEditorPrompt, t as getMarkdown, u as BaseAIPlugin } from "./index-B_bqJoKL";
2
+ export { AIBatch, AIMode, AIToolName, BaseAIPlugin, BaseAIPluginConfig, EditorPrompt, EditorPromptParams, MarkdownType, PromptConfig, getEditorPrompt, getMarkdown, insertAINodes, removeAIMarks, removeAINodes, replacePlaceholders, undoAI, withAIBatch };
package/dist/index.js ADDED
@@ -0,0 +1,125 @@
1
+ import { a as removeAINodes, i as undoAI, n as BaseAIPlugin, o as removeAIMarks, r as withAIBatch, s as insertAINodes, t as getEditorPrompt } from "./getEditorPrompt-BnVrgUl3.js";
2
+ import { KEYS } from "platejs";
3
+ import { serializeMd } from "@platejs/markdown";
4
+ import { getTableGridAbove } from "@platejs/table";
5
+
6
+ //#region src/lib/utils/getMarkdown.ts
7
+ /**
8
+ * Serialize table cell content to markdown string. Multiple paragraphs are
9
+ * joined with <br/>.
10
+ */
11
+ const serializeCellContent = (editor, cell) => {
12
+ const parts = [];
13
+ for (const child of cell.children) {
14
+ const md = serializeMd(editor, { value: [child] }).trim();
15
+ if (md) parts.push(md);
16
+ }
17
+ return parts.join("<br/>");
18
+ };
19
+ /**
20
+ * Serialize a table with selected cells replaced by <CellRef /> placeholders.
21
+ * Returns the table markdown and a map of cell IDs to their cells.
22
+ */
23
+ const serializeTableWithCellRefs = (editor, table, selectedCellIds) => {
24
+ const rows = [];
25
+ const selectedCells = [];
26
+ let headerSeparator = "";
27
+ for (let rowIdx = 0; rowIdx < table.children.length; rowIdx++) {
28
+ const row = table.children[rowIdx];
29
+ const cellTexts = [];
30
+ for (const cell of row.children) {
31
+ const cellId = cell.id;
32
+ if (cellId && selectedCellIds.has(cellId)) {
33
+ cellTexts.push(`<CellRef id="${cellId}" />`);
34
+ selectedCells.push({
35
+ cell,
36
+ id: cellId
37
+ });
38
+ } else {
39
+ const content = serializeCellContent(editor, cell);
40
+ cellTexts.push(content);
41
+ }
42
+ }
43
+ rows.push(`| ${cellTexts.join(" | ")} |`);
44
+ if (rowIdx === 0) headerSeparator = `| ${cellTexts.map(() => "---").join(" | ")} |`;
45
+ }
46
+ if (rows.length > 0 && headerSeparator) rows.splice(1, 0, headerSeparator);
47
+ return {
48
+ selectedCells,
49
+ tableMarkdown: `${rows.join("\n")}\n`
50
+ };
51
+ };
52
+ /**
53
+ * Serialize cell contents as separate Cell blocks. Each cell's content can
54
+ * contain multiple blocks (paragraphs, lists, etc.) since it's outside the
55
+ * table markdown structure.
56
+ */
57
+ const serializeCellBlocks = (editor, cells) => {
58
+ const blocks = [];
59
+ for (const { cell, id } of cells) {
60
+ const content = serializeMd(editor, { value: cell.children }).trim();
61
+ blocks.push(`<Cell id="${id}">\n${content}\n</Cell>`);
62
+ }
63
+ return blocks.join("\n\n");
64
+ };
65
+ const getMarkdown = (editor, { type }) => {
66
+ if (type === "editor" || type === "editorWithBlockId") return serializeMd(editor, { withBlockId: type === "editorWithBlockId" });
67
+ if (type === "block" || type === "blockWithBlockId") return serializeMd(editor, {
68
+ value: editor.api.blocks({ mode: "lowest" }).map(([node]) => node),
69
+ withBlockId: type === "blockWithBlockId"
70
+ });
71
+ if (type === "blockSelection" || type === "blockSelectionWithBlockId") {
72
+ const fragment = editor.api.fragment();
73
+ if (fragment.length === 1) return serializeMd(editor, {
74
+ value: [{
75
+ children: fragment[0].children,
76
+ type: KEYS.p
77
+ }],
78
+ withBlockId: type === "blockSelectionWithBlockId"
79
+ });
80
+ return serializeMd(editor, {
81
+ value: fragment,
82
+ withBlockId: type === "blockSelectionWithBlockId"
83
+ });
84
+ }
85
+ if (type === "tableCellWithId") {
86
+ const cellEntries = getTableGridAbove(editor, { format: "cell" });
87
+ if (cellEntries.length === 0) return "";
88
+ const selectedCellIds = /* @__PURE__ */ new Set();
89
+ for (const [cell] of cellEntries) {
90
+ const cellId = cell.id;
91
+ if (cellId) selectedCellIds.add(cellId);
92
+ }
93
+ const tableEntry = editor.api.block({
94
+ at: editor.selection,
95
+ match: { type: KEYS.table }
96
+ });
97
+ if (!tableEntry) return "";
98
+ const table = tableEntry[0];
99
+ const { selectedCells, tableMarkdown } = serializeTableWithCellRefs(editor, table, selectedCellIds);
100
+ return `${tableMarkdown}\n${serializeCellBlocks(editor, selectedCells)}`;
101
+ }
102
+ return "";
103
+ };
104
+
105
+ //#endregion
106
+ //#region src/lib/utils/replacePlaceholders.ts
107
+ const replacePlaceholders = (editor, text, { prompt } = {}) => {
108
+ let result = text.replace("{prompt}", prompt || "");
109
+ Object.entries({
110
+ "{blockSelectionWithBlockId}": "blockSelectionWithBlockId",
111
+ "{blockSelection}": "blockSelection",
112
+ "{blockWithBlockId}": "blockWithBlockId",
113
+ "{block}": "block",
114
+ "{editorWithBlockId}": "editorWithBlockId",
115
+ "{editor}": "editor",
116
+ "{tableCellWithId}": "tableCellWithId"
117
+ }).forEach(([placeholder, type]) => {
118
+ if (result.includes(placeholder)) result = result.replace(placeholder, getMarkdown(editor, { type }));
119
+ });
120
+ return result;
121
+ };
122
+
123
+ //#endregion
124
+ export { BaseAIPlugin, getEditorPrompt, getMarkdown, insertAINodes, removeAIMarks, removeAINodes, replacePlaceholders, undoAI, withAIBatch };
125
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["serializeMd","getTableGridAbove","SlateEditor","TElement","TTableCellElement","TTableElement","KEYS","MarkdownType","serializeCellContent","editor","cell","parts","child","children","md","value","trim","push","join","serializeTableWithCellRefs","table","selectedCellIds","Set","selectedCells","Array","id","tableMarkdown","rows","headerSeparator","rowIdx","length","row","cellTexts","cellId","has","content","map","splice","serializeCellBlocks","cells","blocks","getMarkdown","type","withBlockId","api","mode","node","fragment","modifiedFragment","p","cellEntries","format","add","tableEntry","block","at","selection","match","cellBlocks","SlateEditor","getMarkdown","MarkdownType","replacePlaceholders","editor","text","prompt","result","replace","placeholders","Record","Object","entries","forEach","placeholder","type","includes"],"sources":["../src/lib/utils/getMarkdown.ts","../src/lib/utils/replacePlaceholders.ts"],"sourcesContent":["import { serializeMd } from '@platejs/markdown';\nimport { getTableGridAbove } from '@platejs/table';\nimport {\n type SlateEditor,\n type TElement,\n type TTableCellElement,\n type TTableElement,\n KEYS,\n} from 'platejs';\n\nimport type { MarkdownType } from './replacePlaceholders';\n\n/**\n * Serialize table cell content to markdown string. Multiple paragraphs are\n * joined with <br/>.\n */\nconst serializeCellContent = (\n editor: SlateEditor,\n cell: TTableCellElement\n): string => {\n const parts: string[] = [];\n\n for (const child of cell.children) {\n const md = serializeMd(editor, { value: [child as TElement] }).trim();\n if (md) {\n parts.push(md);\n }\n }\n\n return parts.join('<br/>');\n};\n\n/**\n * Serialize a table with selected cells replaced by <CellRef /> placeholders.\n * Returns the table markdown and a map of cell IDs to their cells.\n */\nconst serializeTableWithCellRefs = (\n editor: SlateEditor,\n table: TTableElement,\n selectedCellIds: Set<string>\n): {\n selectedCells: Array<{ cell: TTableCellElement; id: string }>;\n tableMarkdown: string;\n} => {\n const rows: string[] = [];\n const selectedCells: Array<{ cell: TTableCellElement; id: string }> = [];\n let headerSeparator = '';\n\n for (let rowIdx = 0; rowIdx < table.children.length; rowIdx++) {\n const row = table.children[rowIdx];\n const cellTexts: string[] = [];\n\n for (const cell of row.children as TTableCellElement[]) {\n const cellId = cell.id as string | undefined;\n\n if (cellId && selectedCellIds.has(cellId)) {\n // Use CellRef placeholder for selected cells\n cellTexts.push(`<CellRef id=\"${cellId}\" />`);\n // Store cell for later content serialization\n selectedCells.push({ cell, id: cellId });\n } else {\n const content = serializeCellContent(editor, cell);\n cellTexts.push(content);\n }\n }\n\n rows.push(`| ${cellTexts.join(' | ')} |`);\n\n // Add header separator after first row\n if (rowIdx === 0) {\n headerSeparator = `| ${cellTexts.map(() => '---').join(' | ')} |`;\n }\n }\n\n // Insert header separator after first row\n if (rows.length > 0 && headerSeparator) {\n rows.splice(1, 0, headerSeparator);\n }\n\n return {\n selectedCells,\n tableMarkdown: `${rows.join('\\n')}\\n`,\n };\n};\n\n/**\n * Serialize cell contents as separate Cell blocks. Each cell's content can\n * contain multiple blocks (paragraphs, lists, etc.) since it's outside the\n * table markdown structure.\n */\nconst serializeCellBlocks = (\n editor: SlateEditor,\n cells: Array<{ cell: TTableCellElement; id: string }>\n): string => {\n const blocks: string[] = [];\n\n for (const { cell, id } of cells) {\n const content = serializeMd(editor, {\n value: cell.children as TElement[],\n }).trim();\n\n blocks.push(`<Cell id=\"${id}\">\\n${content}\\n</Cell>`);\n }\n\n return blocks.join('\\n\\n');\n};\n\n// Internal\nexport const getMarkdown = (\n editor: SlateEditor,\n {\n type,\n }: {\n type: MarkdownType;\n }\n) => {\n if (type === 'editor' || type === 'editorWithBlockId') {\n return serializeMd(editor, {\n withBlockId: type === 'editorWithBlockId',\n });\n }\n\n if (type === 'block' || type === 'blockWithBlockId') {\n const blocks = editor.api.blocks({ mode: 'lowest' }).map(([node]) => node);\n\n return serializeMd(editor, {\n value: blocks,\n withBlockId: type === 'blockWithBlockId',\n });\n }\n\n if (type === 'blockSelection' || type === 'blockSelectionWithBlockId') {\n const fragment = editor.api.fragment<TElement>();\n\n // Remove any block formatting\n if (fragment.length === 1) {\n const modifiedFragment = [\n {\n children: fragment[0].children,\n type: KEYS.p,\n },\n ];\n\n return serializeMd(editor, {\n value: modifiedFragment,\n withBlockId: type === 'blockSelectionWithBlockId',\n });\n }\n\n return serializeMd(editor, {\n value: fragment,\n withBlockId: type === 'blockSelectionWithBlockId',\n });\n }\n\n if (type === 'tableCellWithId') {\n // Get selected cells\n const cellEntries = getTableGridAbove(editor, { format: 'cell' });\n\n if (cellEntries.length === 0) {\n return '';\n }\n\n // Collect selected cell IDs\n const selectedCellIds = new Set<string>();\n\n for (const [cell] of cellEntries) {\n const cellId = (cell as TTableCellElement).id as string | undefined;\n\n if (cellId) {\n selectedCellIds.add(cellId);\n }\n }\n\n // Get the table containing the selection\n const tableEntry = editor.api.block({\n at: editor.selection!,\n match: { type: KEYS.table },\n });\n\n if (!tableEntry) {\n return '';\n }\n\n const table = tableEntry[0] as TTableElement;\n\n // Serialize table with CellRef placeholders\n const { selectedCells, tableMarkdown } = serializeTableWithCellRefs(\n editor,\n table,\n selectedCellIds\n );\n\n // Serialize Cell content blocks\n const cellBlocks = serializeCellBlocks(editor, selectedCells);\n\n // Combine: table + Cell blocks\n return `${tableMarkdown}\\n${cellBlocks}`;\n }\n\n return '';\n};\n","import type { SlateEditor } from 'platejs';\n\nimport { getMarkdown } from './getMarkdown';\n\nexport type MarkdownType =\n | 'block'\n | 'blockSelection'\n | 'blockSelectionWithBlockId'\n | 'blockWithBlockId'\n | 'editor'\n | 'editorWithBlockId'\n | 'tableCellWithId';\n\nexport const replacePlaceholders = (\n editor: SlateEditor,\n text: string,\n {\n prompt,\n }: {\n prompt?: string;\n } = {}\n): string => {\n let result = text.replace('{prompt}', prompt || '');\n\n const placeholders: Record<string, MarkdownType> = {\n '{blockSelectionWithBlockId}': 'blockSelectionWithBlockId',\n '{blockSelection}': 'blockSelection',\n '{blockWithBlockId}': 'blockWithBlockId',\n '{block}': 'block',\n '{editorWithBlockId}': 'editorWithBlockId',\n '{editor}': 'editor',\n '{tableCellWithId}': 'tableCellWithId',\n };\n\n Object.entries(placeholders).forEach(([placeholder, type]) => {\n if (result.includes(placeholder)) {\n result = result.replace(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