@prosekit/extensions 0.11.6 → 0.11.7
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/dist/{enter-rule-RdhEA900.js → enter-rule-5tkoU2Ir.js} +2 -3
- package/dist/enter-rule-5tkoU2Ir.js.map +1 -0
- package/dist/{file-DVUhe5KJ.js → file-nRyo7PMB.js} +2 -4
- package/dist/{file-DVUhe5KJ.js.map → file-nRyo7PMB.js.map} +1 -1
- package/dist/index-DY6lIIYV.d.ts.map +1 -1
- package/dist/{input-rule-B17tpW4m.js → input-rule-DO_iy2aT.js} +4 -7
- package/dist/input-rule-DO_iy2aT.js.map +1 -0
- package/dist/{paste-rule-BIztzELg.js → paste-rule-Brej6cWi.js} +2 -3
- package/dist/{paste-rule-BIztzELg.js.map → paste-rule-Brej6cWi.js.map} +1 -1
- package/dist/prosekit-extensions-autocomplete.js +1 -2
- package/dist/prosekit-extensions-autocomplete.js.map +1 -1
- package/dist/prosekit-extensions-blockquote.js +1 -1
- package/dist/prosekit-extensions-bold.js +1 -1
- package/dist/prosekit-extensions-code-block.js +4 -5
- package/dist/prosekit-extensions-code-block.js.map +1 -1
- package/dist/prosekit-extensions-code.js +1 -1
- package/dist/prosekit-extensions-commit.js +2 -4
- package/dist/prosekit-extensions-commit.js.map +1 -1
- package/dist/prosekit-extensions-enter-rule.js +1 -1
- package/dist/prosekit-extensions-file.js +1 -1
- package/dist/prosekit-extensions-heading.js +1 -1
- package/dist/prosekit-extensions-horizontal-rule.js +1 -1
- package/dist/prosekit-extensions-image.d.ts +85 -29
- package/dist/prosekit-extensions-image.d.ts.map +1 -1
- package/dist/prosekit-extensions-image.js +93 -52
- package/dist/prosekit-extensions-image.js.map +1 -1
- package/dist/prosekit-extensions-input-rule.js +1 -1
- package/dist/prosekit-extensions-italic.js +1 -1
- package/dist/prosekit-extensions-link.js +3 -3
- package/dist/prosekit-extensions-list.js +3 -5
- package/dist/prosekit-extensions-list.js.map +1 -1
- package/dist/prosekit-extensions-paste-rule.js +1 -1
- package/dist/prosekit-extensions-placeholder.js +2 -3
- package/dist/prosekit-extensions-placeholder.js.map +1 -1
- package/dist/prosekit-extensions-search.js +1 -2
- package/dist/prosekit-extensions-search.js.map +1 -1
- package/dist/prosekit-extensions-strike.js +1 -1
- package/dist/prosekit-extensions-table.js +1 -1
- package/dist/{table-BNwuK7xg.js → table-DND_1127.js} +9 -18
- package/dist/{table-BNwuK7xg.js.map → table-DND_1127.js.map} +1 -1
- package/package.json +4 -4
- package/src/file/file-upload.ts +2 -10
- package/src/image/image-commands/insert-image.ts +14 -0
- package/src/image/image-commands/upload-image.ts +137 -0
- package/src/image/image-commands.ts +7 -12
- package/src/image/image-upload-handler.ts +10 -70
- package/src/image/index.ts +8 -3
- package/dist/enter-rule-RdhEA900.js.map +0 -1
- package/dist/input-rule-B17tpW4m.js.map +0 -1
|
@@ -13,8 +13,7 @@ import { keydownHandler } from "@prosekit/pm/keymap";
|
|
|
13
13
|
* @public
|
|
14
14
|
*/
|
|
15
15
|
function defineEnterRule({ regex, handler, stop = false }) {
|
|
16
|
-
|
|
17
|
-
return defineFacetPayload(enterRule, [rule]);
|
|
16
|
+
return defineFacetPayload(enterRule, [new EnterRule(regex, handler, stop)]);
|
|
18
17
|
}
|
|
19
18
|
/**
|
|
20
19
|
* Defines an enter rule that replaces the matched text with a block node.
|
|
@@ -94,4 +93,4 @@ const MAX_MATCH = 200;
|
|
|
94
93
|
|
|
95
94
|
//#endregion
|
|
96
95
|
export { defineEnterRule, defineTextBlockEnterRule };
|
|
97
|
-
//# sourceMappingURL=enter-rule-
|
|
96
|
+
//# sourceMappingURL=enter-rule-5tkoU2Ir.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"enter-rule-5tkoU2Ir.js","names":["regex: RegExp","handler: EnterRuleHandler","stop: boolean","rules: EnterRule[]","command: Command"],"sources":["../src/enter-rule/index.ts"],"sourcesContent":["import {\n defineFacet,\n defineFacetPayload,\n getNodeType,\n isTextSelection,\n maybeRun,\n OBJECT_REPLACEMENT_CHARACTER,\n pluginFacet,\n type PlainExtension,\n type PluginPayload,\n} from '@prosekit/core'\nimport { keydownHandler } from '@prosekit/pm/keymap'\nimport type {\n Attrs,\n NodeType,\n} from '@prosekit/pm/model'\nimport {\n PluginKey,\n ProseMirrorPlugin,\n type Command,\n type EditorState,\n type Transaction,\n} from '@prosekit/pm/state'\nimport type { EditorView } from '@prosekit/pm/view'\n\n/**\n * @public\n *\n * Options for {@link EnterRuleHandler}.\n */\nexport interface EnterRuleHandlerOptions {\n /**\n * The current editor state.\n */\n state: EditorState\n\n /**\n * The start position of the matched text.\n */\n from: number\n\n /**\n * The end position of the matched text.\n */\n to: number\n\n /**\n * The matched result from the regular expression.\n */\n match: RegExpExecArray\n}\n\n/**\n * @public\n */\nexport type EnterRuleHandler = (options: EnterRuleHandlerOptions) => Transaction | null\n\n/**\n * Options for {@link defineEnterRule}.\n *\n * @public\n */\nexport type EnterRuleOptions = {\n /**\n * The regular expression to match against. It should end with `$`.\n */\n regex: RegExp\n\n /**\n * A function to be called when an enter rule is triggered.\n */\n handler: EnterRuleHandler\n\n /**\n * Whether to stop further handlers from being called if this rule is triggered.\n *\n * @default false\n */\n stop?: boolean\n}\n\n/**\n * Options for {@link defineTextBlockEnterRule}.\n *\n * @public\n */\nexport interface TextBlockEnterRuleOptions {\n /**\n * The regular expression to match against. It should end with `$`.\n */\n regex: RegExp\n\n /**\n * The node type to replace the matched text with.\n */\n type: string | NodeType\n\n /**\n * Attributes to set on the node. If a function is provided, it will be called\n * with the matched result from the regular expression.\n */\n attrs?: Attrs | null | ((match: RegExpMatchArray) => Attrs | null)\n\n /**\n * Whether to stop further handlers from being called if this rule is triggered.\n *\n * @default true\n */\n stop?: boolean\n}\n\n/**\n * Defines an enter rule. An enter rule applies when the text directly in front of\n * the cursor matches `regex` and user presses Enter. The `regex` should end\n * with `$`.\n *\n * @param options\n *\n * @public\n */\nexport function defineEnterRule({\n regex,\n handler,\n stop = false,\n}: EnterRuleOptions): PlainExtension {\n const rule: EnterRule = new EnterRule(regex, handler, stop)\n return defineFacetPayload(enterRule, [rule]) as PlainExtension\n}\n\n/**\n * Defines an enter rule that replaces the matched text with a block node.\n *\n * See also {@link defineEnterRule}.\n *\n * @param options\n *\n * @public\n */\nexport function defineTextBlockEnterRule({\n regex,\n type,\n attrs,\n stop = true,\n}: TextBlockEnterRuleOptions): PlainExtension {\n return defineEnterRule({\n regex,\n handler: ({ state, from, to, match }) => {\n const nodeType = getNodeType(state.schema, type)\n const $start = state.doc.resolve(from)\n\n if (\n !$start\n .node(-1)\n .canReplaceWith($start.index(-1), $start.indexAfter(-1), nodeType)\n ) {\n return null\n }\n\n const nodeAttrs = maybeRun(attrs, match)\n return state.tr\n .delete(from, to)\n .setBlockType(from, from, nodeType, nodeAttrs)\n },\n stop,\n })\n}\n\n/**\n * @internal\n */\nclass EnterRule {\n constructor(\n readonly regex: RegExp,\n readonly handler: EnterRuleHandler,\n readonly stop: boolean,\n ) {}\n}\n\nconst enterRule = defineFacet<EnterRule, PluginPayload>({\n reduce: () => {\n let rules: EnterRule[] = []\n\n const command: Command = (state, dispatch, view) => {\n if (!view) return false\n return execRules(view, rules, dispatch)\n }\n const handler = keydownHandler({ Enter: command })\n const plugin = new ProseMirrorPlugin({\n key: new PluginKey('prosekit-enter-rule'),\n props: { handleKeyDown: handler },\n })\n\n return function reducer(inputs) {\n rules = inputs\n return plugin\n }\n },\n\n parent: pluginFacet,\n})\n\nfunction execRules(\n view: EditorView,\n rules: readonly EnterRule[],\n dispatch?: (tr: Transaction) => void,\n): boolean {\n if (view.composing) return false\n const state = view.state\n const selection = state.selection\n if (!isTextSelection(selection)) return false\n const $cursor = selection.$cursor\n if (!$cursor || $cursor.parent.type.spec.code) return false\n\n const textBefore = $cursor.parent.textBetween(\n Math.max(0, $cursor.parentOffset - MAX_MATCH),\n $cursor.parentOffset,\n null,\n OBJECT_REPLACEMENT_CHARACTER,\n )\n\n for (const rule of rules) {\n rule.regex.lastIndex = 0\n const match = rule.regex.exec(textBefore)\n const tr = match\n && rule.handler({\n state,\n from: $cursor.pos - match[0].length,\n to: $cursor.pos,\n match,\n })\n if (!tr) continue\n dispatch?.(tr)\n\n if (rule.stop) {\n return true\n }\n }\n return false\n}\n\nconst MAX_MATCH = 200\n"],"mappings":";;;;;;;;;;;;;;AAwHA,SAAgB,gBAAgB,EAC9B,OACA,SACA,OAAO,SAC4B;AAEnC,QAAO,mBAAmB,WAAW,CADb,IAAI,UAAU,OAAO,SAAS,KAAK,CAChB,CAAC;;;;;;;;;;;AAY9C,SAAgB,yBAAyB,EACvC,OACA,MACA,OACA,OAAO,QACqC;AAC5C,QAAO,gBAAgB;EACrB;EACA,UAAU,EAAE,OAAO,MAAM,IAAI,YAAY;GACvC,MAAM,WAAW,YAAY,MAAM,QAAQ,KAAK;GAChD,MAAM,SAAS,MAAM,IAAI,QAAQ,KAAK;AAEtC,OACE,CAAC,OACE,KAAK,GAAG,CACR,eAAe,OAAO,MAAM,GAAG,EAAE,OAAO,WAAW,GAAG,EAAE,SAAS,CAEpE,QAAO;GAGT,MAAM,YAAY,SAAS,OAAO,MAAM;AACxC,UAAO,MAAM,GACV,OAAO,MAAM,GAAG,CAChB,aAAa,MAAM,MAAM,UAAU,UAAU;;EAElD;EACD,CAAC;;;;;AAMJ,IAAM,YAAN,MAAgB;CACd,YACE,AAASA,OACT,AAASC,SACT,AAASC,MACT;EAHS;EACA;EACA;;;AAIb,MAAM,YAAY,YAAsC;CACtD,cAAc;EACZ,IAAIC,QAAqB,EAAE;EAE3B,MAAMC,WAAoB,OAAO,UAAU,SAAS;AAClD,OAAI,CAAC,KAAM,QAAO;AAClB,UAAO,UAAU,MAAM,OAAO,SAAS;;EAEzC,MAAM,UAAU,eAAe,EAAE,OAAO,SAAS,CAAC;EAClD,MAAM,SAAS,IAAI,kBAAkB;GACnC,KAAK,IAAI,UAAU,sBAAsB;GACzC,OAAO,EAAE,eAAe,SAAS;GAClC,CAAC;AAEF,SAAO,SAAS,QAAQ,QAAQ;AAC9B,WAAQ;AACR,UAAO;;;CAIX,QAAQ;CACT,CAAC;AAEF,SAAS,UACP,MACA,OACA,UACS;AACT,KAAI,KAAK,UAAW,QAAO;CAC3B,MAAM,QAAQ,KAAK;CACnB,MAAM,YAAY,MAAM;AACxB,KAAI,CAAC,gBAAgB,UAAU,CAAE,QAAO;CACxC,MAAM,UAAU,UAAU;AAC1B,KAAI,CAAC,WAAW,QAAQ,OAAO,KAAK,KAAK,KAAM,QAAO;CAEtD,MAAM,aAAa,QAAQ,OAAO,YAChC,KAAK,IAAI,GAAG,QAAQ,eAAe,UAAU,EAC7C,QAAQ,cACR,MACA,6BACD;AAED,MAAK,MAAM,QAAQ,OAAO;AACxB,OAAK,MAAM,YAAY;EACvB,MAAM,QAAQ,KAAK,MAAM,KAAK,WAAW;EACzC,MAAM,KAAK,SACN,KAAK,QAAQ;GACd;GACA,MAAM,QAAQ,MAAM,MAAM,GAAG;GAC7B,IAAI,QAAQ;GACZ;GACD,CAAC;AACJ,MAAI,CAAC,GAAI;AACT,aAAW,GAAG;AAEd,MAAI,KAAK,KACP,QAAO;;AAGX,QAAO;;AAGT,MAAM,YAAY"}
|
|
@@ -86,9 +86,7 @@ var UploadTask = class {
|
|
|
86
86
|
const maybePromise = uploader({
|
|
87
87
|
file,
|
|
88
88
|
onProgress: (progress) => {
|
|
89
|
-
|
|
90
|
-
if (typeof progress.loaded !== "number") throw new TypeError("loaded must be a number");
|
|
91
|
-
if (progress.loaded > 0) for (const subscriber of this.subscribers) subscriber(progress);
|
|
89
|
+
for (const subscriber of this.subscribers) subscriber(progress);
|
|
92
90
|
}
|
|
93
91
|
});
|
|
94
92
|
Promise.resolve(maybePromise).then((result) => {
|
|
@@ -131,4 +129,4 @@ const store = /* @__PURE__ */ new Map();
|
|
|
131
129
|
|
|
132
130
|
//#endregion
|
|
133
131
|
export { UploadTask, defineFileDropHandler, defineFilePasteHandler };
|
|
134
|
-
//# sourceMappingURL=file-
|
|
132
|
+
//# sourceMappingURL=file-nRyo7PMB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-DVUhe5KJ.js","names":["getFiles","facet","getFiles","dropHandler: DropHandler","pasteHandler: PasteHandler"],"sources":["../src/file/helpers.ts","../src/file/file-drop-handler.ts","../src/file/file-paste-handler.ts","../src/file/file-upload.ts"],"sourcesContent":["import type { EditorView } from '@prosekit/pm/view'\n\ntype FileHandler<E extends Event> = (options: {\n view: EditorView\n event: E\n file: File\n}) => boolean | void\n\nfunction handleFile<E extends Event>(\n view: EditorView,\n event: E,\n file: File,\n handlers: FileHandler<E>[],\n) {\n // The last item in `handlers` should has the highest priority.\n for (let i = handlers.length - 1; i >= 0; i--) {\n const handler = handlers[i]\n if (handler({ view, event, file })) {\n return true\n }\n }\n return false\n}\n\nexport function handleEvent<E extends Event>(\n view: EditorView,\n event: E,\n handlers: FileHandler<E>[],\n getFiles: (event: E) => File[],\n): boolean {\n const files = getFiles(event)\n let handled = false\n for (const file of files) {\n if (handleFile(view, event, file, handlers)) {\n handled = true\n }\n }\n return handled\n}\n","import {\n defineFacet,\n defineFacetPayload,\n editorEventFacet,\n type DropHandler,\n type EditorEventPayload,\n type PlainExtension,\n} from '@prosekit/core'\nimport type { EditorView } from '@prosekit/pm/view'\n\nimport { handleEvent } from './helpers'\n\nexport interface FileDropHandlerOptions {\n /**\n * The editor view.\n */\n view: EditorView\n\n /**\n * The event that triggered the drop.\n */\n event: DragEvent\n\n /**\n * The file that was dropped.\n */\n file: File\n\n /**\n * The position of the document where the file was dropped.\n */\n pos: number\n}\n\n/**\n * A function that handles one of the files in a drop event.\n *\n * Returns `true` if the file was handled and thus should not be handled by\n * other handlers.\n */\nexport type FileDropHandler = (\n options: FileDropHandlerOptions,\n) => boolean | void\n\nexport function defineFileDropHandler(\n handler: FileDropHandler,\n): PlainExtension {\n return defineFacetPayload(facet, [handler]) as PlainExtension\n}\n\nfunction getFiles(event: DragEvent) {\n return Array.from(event.dataTransfer?.files ?? [])\n}\n\nconst facet = defineFacet<FileDropHandler, EditorEventPayload>({\n parent: editorEventFacet,\n singleton: true,\n reducer: (handlers: FileDropHandler[]): EditorEventPayload => {\n const dropHandler: DropHandler = (view, event): boolean => {\n const position = view.posAtCoords({ left: event.x, top: event.y })\n if (!position) {\n return false\n }\n const pos = position.inside > 0 ? position.inside : position.pos\n\n return handleEvent<DragEvent>(\n view,\n event,\n handlers.map((handler) => (options) => handler({ ...options, pos })),\n getFiles,\n )\n }\n return ['drop', dropHandler]\n },\n})\n","import {\n defineFacet,\n defineFacetPayload,\n editorEventFacet,\n type EditorEventPayload,\n type PasteHandler,\n type PlainExtension,\n} from '@prosekit/core'\nimport type { EditorView } from '@prosekit/pm/view'\n\nimport { handleEvent } from './helpers'\n\nexport interface FilePasteHandlerOptions {\n /**\n * The editor view.\n */\n view: EditorView\n\n /**\n * The event that triggered the paste.\n */\n event: ClipboardEvent\n\n /**\n * The file that was pasted.\n */\n file: File\n}\n\n/**\n * A function that handles one of the files in a paste event.\n *\n * Returns `true` if the file was handled and thus should not be handled by\n * other handlers.\n */\nexport type FilePasteHandler = (\n options: FilePasteHandlerOptions,\n) => boolean | void\n\nexport function defineFilePasteHandler(\n handler: FilePasteHandler,\n): PlainExtension {\n return defineFacetPayload(facet, [handler]) as PlainExtension\n}\n\nfunction getFiles(event: ClipboardEvent) {\n return Array.from(event.clipboardData?.files ?? [])\n}\n\nconst facet = defineFacet<FilePasteHandler, EditorEventPayload>({\n parent: editorEventFacet,\n singleton: true,\n reducer: (handlers: FilePasteHandler[]): EditorEventPayload => {\n const pasteHandler: PasteHandler = (view, event): boolean => {\n return handleEvent<ClipboardEvent>(view, event, handlers, getFiles)\n }\n return ['paste', pasteHandler]\n },\n})\n","import { ProseKitError } from '@prosekit/core'\n\n/**\n * An interface representing the upload progress.\n */\nexport interface UploadProgress {\n // A number representing the amount of work already performed by the\n // underlying process.\n loaded: number\n // A number representing the total amount of work that the underlying\n // process is in the progress of performing.\n total: number\n}\n\nexport interface UploaderOptions {\n /**\n * The file to be uploaded.\n */\n file: File\n\n /**\n * A callback function that should be called with the upload progress updates.\n */\n onProgress: (progress: UploadProgress) => void\n}\n\n/**\n * The implementation of the actual upload function. You need to implement this\n * function to upload files to your desired destination.\n */\nexport type Uploader<Result> = (options: UploaderOptions) => Promise<Result>\n\n/**\n * A class that represents a upload task.\n */\nexport class UploadTask<Result> {\n /**\n * An [object URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)\n * representing the file to be uploaded. This URL will be revoked once the\n * upload is complete successfully.\n */\n readonly objectURL: string\n\n /**\n * A boolean indicating whether the upload is complete (either successfully or with an error).\n */\n protected done = false\n\n /**\n * If the upload is complete successfully, this will be the result of the upload.\n */\n protected result: Result | undefined\n\n /**\n * If the upload is complete with an error, this will be the error that occurred.\n */\n protected error: Error | undefined\n\n /**\n * A promise that fulfills once the upload is complete, or rejects if an error occurs.\n */\n readonly finished: Promise<Result>\n\n private subscribers: ((progress: UploadProgress) => void)[] = []\n\n /**\n * Creates a new upload task. You can find the upload task by its object URL\n * later using `UploadTask.get()`.\n *\n * @param options - The options for the upload task.\n */\n constructor({ file, uploader }: { file: File; uploader: Uploader<Result> }) {\n this.objectURL = URL.createObjectURL(file)\n this.finished = new Promise((resolve, reject) => {\n const maybePromise = uploader({\n file,\n onProgress: (progress) => {\n if (typeof progress.total !== 'number') {\n throw new TypeError('total must be a number')\n }\n if (typeof progress.loaded !== 'number') {\n throw new TypeError('loaded must be a number')\n }\n if (progress.loaded > 0) {\n for (const subscriber of this.subscribers) {\n subscriber(progress)\n }\n }\n },\n })\n Promise.resolve(maybePromise).then(\n (result) => {\n this.done = true\n URL.revokeObjectURL(this.objectURL)\n this.result = result\n resolve(result)\n },\n (err) => {\n this.done = true\n const error = new ProseKitError('[prosekit] Failed to upload file', { cause: err })\n this.error = error\n reject(error)\n },\n )\n })\n store.set(this.objectURL, this)\n }\n\n /**\n * Subscribes to progress updates. Returns a function to unsubscribe.\n */\n public subscribeProgress(\n callback: (progress: UploadProgress) => void,\n ): VoidFunction {\n this.subscribers.push(callback)\n return () => {\n this.subscribers = this.subscribers.filter(\n (subscriber) => subscriber !== callback,\n )\n }\n }\n\n /**\n * Finds an upload task from the global store by its object URL.\n */\n static get<Result = unknown>(\n objectURL: string,\n ): UploadTask<Result> | undefined {\n return store.get(objectURL) as UploadTask<Result> | undefined\n }\n\n /**\n * Deletes an upload task from the global store by its object URL.\n */\n static delete(objectURL: string): void {\n store.delete(objectURL)\n }\n}\n\nconst store = new Map<string, UploadTask<unknown>>()\n"],"mappings":";;;AAQA,SAAS,WACP,MACA,OACA,MACA,UACA;AAEA,MAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK;EAC7C,MAAM,UAAU,SAAS;AACzB,MAAI,QAAQ;GAAE;GAAM;GAAO;GAAM,CAAC,CAChC,QAAO;;AAGX,QAAO;;AAGT,SAAgB,YACd,MACA,OACA,UACA,YACS;CACT,MAAM,QAAQA,WAAS,MAAM;CAC7B,IAAI,UAAU;AACd,MAAK,MAAM,QAAQ,MACjB,KAAI,WAAW,MAAM,OAAO,MAAM,SAAS,CACzC,WAAU;AAGd,QAAO;;;;;ACOT,SAAgB,sBACd,SACgB;AAChB,QAAO,mBAAmBC,SAAO,CAAC,QAAQ,CAAC;;AAG7C,SAASC,WAAS,OAAkB;AAClC,QAAO,MAAM,KAAK,MAAM,cAAc,SAAS,EAAE,CAAC;;AAGpD,MAAMD,UAAQ,YAAiD;CAC7D,QAAQ;CACR,WAAW;CACX,UAAU,aAAoD;EAC5D,MAAME,eAA4B,MAAM,UAAmB;GACzD,MAAM,WAAW,KAAK,YAAY;IAAE,MAAM,MAAM;IAAG,KAAK,MAAM;IAAG,CAAC;AAClE,OAAI,CAAC,SACH,QAAO;GAET,MAAM,MAAM,SAAS,SAAS,IAAI,SAAS,SAAS,SAAS;AAE7D,UAAO,YACL,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K,WAAW,KAAK;;;;;CAMjC,AAAO,kBACL,UACc;AACd,OAAK,YAAY,KAAK,SAAS;AAC/B,eAAa;AACX,QAAK,cAAc,KAAK,YAAY,QACjC,eAAe,eAAe,SAChC;;;;;;CAOL,OAAO,IACL,WACgC;AAChC,SAAO,MAAM,IAAI,UAAU;;;;;CAM7B,OAAO,OAAO,WAAyB;AACrC,QAAM,OAAO,UAAU;;;AAI3B,MAAM,wBAAQ,IAAI,KAAkC"}
|
|
1
|
+
{"version":3,"file":"file-nRyo7PMB.js","names":["getFiles","facet","getFiles","dropHandler: DropHandler","pasteHandler: PasteHandler"],"sources":["../src/file/helpers.ts","../src/file/file-drop-handler.ts","../src/file/file-paste-handler.ts","../src/file/file-upload.ts"],"sourcesContent":["import type { EditorView } from '@prosekit/pm/view'\n\ntype FileHandler<E extends Event> = (options: {\n view: EditorView\n event: E\n file: File\n}) => boolean | void\n\nfunction handleFile<E extends Event>(\n view: EditorView,\n event: E,\n file: File,\n handlers: FileHandler<E>[],\n) {\n // The last item in `handlers` should has the highest priority.\n for (let i = handlers.length - 1; i >= 0; i--) {\n const handler = handlers[i]\n if (handler({ view, event, file })) {\n return true\n }\n }\n return false\n}\n\nexport function handleEvent<E extends Event>(\n view: EditorView,\n event: E,\n handlers: FileHandler<E>[],\n getFiles: (event: E) => File[],\n): boolean {\n const files = getFiles(event)\n let handled = false\n for (const file of files) {\n if (handleFile(view, event, file, handlers)) {\n handled = true\n }\n }\n return handled\n}\n","import {\n defineFacet,\n defineFacetPayload,\n editorEventFacet,\n type DropHandler,\n type EditorEventPayload,\n type PlainExtension,\n} from '@prosekit/core'\nimport type { EditorView } from '@prosekit/pm/view'\n\nimport { handleEvent } from './helpers'\n\nexport interface FileDropHandlerOptions {\n /**\n * The editor view.\n */\n view: EditorView\n\n /**\n * The event that triggered the drop.\n */\n event: DragEvent\n\n /**\n * The file that was dropped.\n */\n file: File\n\n /**\n * The position of the document where the file was dropped.\n */\n pos: number\n}\n\n/**\n * A function that handles one of the files in a drop event.\n *\n * Returns `true` if the file was handled and thus should not be handled by\n * other handlers.\n */\nexport type FileDropHandler = (\n options: FileDropHandlerOptions,\n) => boolean | void\n\nexport function defineFileDropHandler(\n handler: FileDropHandler,\n): PlainExtension {\n return defineFacetPayload(facet, [handler]) as PlainExtension\n}\n\nfunction getFiles(event: DragEvent) {\n return Array.from(event.dataTransfer?.files ?? [])\n}\n\nconst facet = defineFacet<FileDropHandler, EditorEventPayload>({\n parent: editorEventFacet,\n singleton: true,\n reducer: (handlers: FileDropHandler[]): EditorEventPayload => {\n const dropHandler: DropHandler = (view, event): boolean => {\n const position = view.posAtCoords({ left: event.x, top: event.y })\n if (!position) {\n return false\n }\n const pos = position.inside > 0 ? position.inside : position.pos\n\n return handleEvent<DragEvent>(\n view,\n event,\n handlers.map((handler) => (options) => handler({ ...options, pos })),\n getFiles,\n )\n }\n return ['drop', dropHandler]\n },\n})\n","import {\n defineFacet,\n defineFacetPayload,\n editorEventFacet,\n type EditorEventPayload,\n type PasteHandler,\n type PlainExtension,\n} from '@prosekit/core'\nimport type { EditorView } from '@prosekit/pm/view'\n\nimport { handleEvent } from './helpers'\n\nexport interface FilePasteHandlerOptions {\n /**\n * The editor view.\n */\n view: EditorView\n\n /**\n * The event that triggered the paste.\n */\n event: ClipboardEvent\n\n /**\n * The file that was pasted.\n */\n file: File\n}\n\n/**\n * A function that handles one of the files in a paste event.\n *\n * Returns `true` if the file was handled and thus should not be handled by\n * other handlers.\n */\nexport type FilePasteHandler = (\n options: FilePasteHandlerOptions,\n) => boolean | void\n\nexport function defineFilePasteHandler(\n handler: FilePasteHandler,\n): PlainExtension {\n return defineFacetPayload(facet, [handler]) as PlainExtension\n}\n\nfunction getFiles(event: ClipboardEvent) {\n return Array.from(event.clipboardData?.files ?? [])\n}\n\nconst facet = defineFacet<FilePasteHandler, EditorEventPayload>({\n parent: editorEventFacet,\n singleton: true,\n reducer: (handlers: FilePasteHandler[]): EditorEventPayload => {\n const pasteHandler: PasteHandler = (view, event): boolean => {\n return handleEvent<ClipboardEvent>(view, event, handlers, getFiles)\n }\n return ['paste', pasteHandler]\n },\n})\n","import { ProseKitError } from '@prosekit/core'\n\n/**\n * An interface representing the upload progress.\n */\nexport interface UploadProgress {\n // A number representing the amount of work already performed by the\n // underlying process.\n loaded: number\n // A number representing the total amount of work that the underlying\n // process is in the progress of performing.\n total: number\n}\n\nexport interface UploaderOptions {\n /**\n * The file to be uploaded.\n */\n file: File\n\n /**\n * A callback function that should be called with the upload progress updates.\n */\n onProgress: (progress: UploadProgress) => void\n}\n\n/**\n * The implementation of the actual upload function. You need to implement this\n * function to upload files to your desired destination.\n */\nexport type Uploader<Result> = (options: UploaderOptions) => Promise<Result>\n\n/**\n * A class that represents a upload task.\n */\nexport class UploadTask<Result> {\n /**\n * An [object URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)\n * representing the file to be uploaded. This URL will be revoked once the\n * upload is complete successfully.\n */\n readonly objectURL: string\n\n /**\n * A boolean indicating whether the upload is complete (either successfully or with an error).\n */\n protected done = false\n\n /**\n * If the upload is complete successfully, this will be the result of the upload.\n */\n protected result: Result | undefined\n\n /**\n * If the upload is complete with an error, this will be the error that occurred.\n */\n protected error: Error | undefined\n\n /**\n * A promise that fulfills once the upload is complete, or rejects if an error occurs.\n */\n readonly finished: Promise<Result>\n\n private subscribers: ((progress: UploadProgress) => void)[] = []\n\n /**\n * Creates a new upload task. You can find the upload task by its object URL\n * later using `UploadTask.get()`.\n *\n * @param options - The options for the upload task.\n */\n constructor({ file, uploader }: { file: File; uploader: Uploader<Result> }) {\n this.objectURL = URL.createObjectURL(file)\n this.finished = new Promise((resolve, reject) => {\n const maybePromise = uploader({\n file,\n onProgress: (progress) => {\n for (const subscriber of this.subscribers) {\n subscriber(progress)\n }\n },\n })\n Promise.resolve(maybePromise).then(\n (result) => {\n this.done = true\n URL.revokeObjectURL(this.objectURL)\n this.result = result\n resolve(result)\n },\n (err) => {\n this.done = true\n const error = new ProseKitError('[prosekit] Failed to upload file', { cause: err })\n this.error = error\n reject(error)\n },\n )\n })\n store.set(this.objectURL, this)\n }\n\n /**\n * Subscribes to progress updates. Returns a function to unsubscribe.\n */\n public subscribeProgress(\n callback: (progress: UploadProgress) => void,\n ): VoidFunction {\n this.subscribers.push(callback)\n return () => {\n this.subscribers = this.subscribers.filter(\n (subscriber) => subscriber !== callback,\n )\n }\n }\n\n /**\n * Finds an upload task from the global store by its object URL.\n */\n static get<Result = unknown>(\n objectURL: string,\n ): UploadTask<Result> | undefined {\n return store.get(objectURL) as UploadTask<Result> | undefined\n }\n\n /**\n * Deletes an upload task from the global store by its object URL.\n */\n static delete(objectURL: string): void {\n store.delete(objectURL)\n }\n}\n\nconst store = new Map<string, UploadTask<unknown>>()\n"],"mappings":";;;AAQA,SAAS,WACP,MACA,OACA,MACA,UACA;AAEA,MAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK;EAC7C,MAAM,UAAU,SAAS;AACzB,MAAI,QAAQ;GAAE;GAAM;GAAO;GAAM,CAAC,CAChC,QAAO;;AAGX,QAAO;;AAGT,SAAgB,YACd,MACA,OACA,UACA,YACS;CACT,MAAM,QAAQA,WAAS,MAAM;CAC7B,IAAI,UAAU;AACd,MAAK,MAAM,QAAQ,MACjB,KAAI,WAAW,MAAM,OAAO,MAAM,SAAS,CACzC,WAAU;AAGd,QAAO;;;;;ACOT,SAAgB,sBACd,SACgB;AAChB,QAAO,mBAAmBC,SAAO,CAAC,QAAQ,CAAC;;AAG7C,SAASC,WAAS,OAAkB;AAClC,QAAO,MAAM,KAAK,MAAM,cAAc,SAAS,EAAE,CAAC;;AAGpD,MAAMD,UAAQ,YAAiD;CAC7D,QAAQ;CACR,WAAW;CACX,UAAU,aAAoD;EAC5D,MAAME,eAA4B,MAAM,UAAmB;GACzD,MAAM,WAAW,KAAK,YAAY;IAAE,MAAM,MAAM;IAAG,KAAK,MAAM;IAAG,CAAC;AAClE,OAAI,CAAC,SACH,Q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,eAAa;AACX,QAAK,cAAc,KAAK,YAAY,QACjC,eAAe,eAAe,SAChC;;;;;;CAOL,OAAO,IACL,WACgC;AAChC,SAAO,MAAM,IAAI,UAAU;;;;;CAM7B,OAAO,OAAO,WAAyB;AACrC,QAAM,OAAO,UAAU;;;AAI3B,MAAM,wBAAQ,IAAI,KAAkC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-DY6lIIYV.d.ts","names":[],"sources":["../src/file/file-drop-handler.ts","../src/file/file-paste-handler.ts","../src/file/file-upload.ts"],"sourcesContent":[],"mappings":";;;;UAYiB,sBAAA;;AAAjB;;MAIQ,EAAA,UAAA;;;;EAwBI,KAAA,EAnBH,SAmBG;EAII;;;MAEb,EApBK,IAoBL;EAAc;;;;AClCjB;;;;;;AAuBA;AAIgB,KDCJ,eAAA,GCD0B,CAAA,OAAA,EDE3B,sBCF2B,EAAA,GAAA,OAAA,GAAA,IAAA;AAAA,iBDKtB,qBAAA,CCLsB,OAAA,EDM3B,eCN2B,CAAA,EDOnC,cCPmC;;;UA3BrB,uBAAA;;ADAjB;;MAIQ,ECAA,UDAA;;;;EAwBI,KAAA,ECnBH,cDmBkB;EAIX;;;MAEb,ECpBK,IDoBL;;;;;AClCH;;;AASS,KAcG,gBAAA,GAdH,CAAA,OAAA,EAeE,uBAfF,EAAA,GAAA,OAAA,GAAA,IAAA;AAKD,iBAaQ,sBAAA,CAbR,OAAA,EAcG,gBAdH,CAAA,EAeL,cAfK;;;;;;UCrBS,cAAA;EFOA,MAAA,EAAA,MAAA;EAAsB,KAAA,EAAA,MAAA;;AAS9B,UEPQ,eAAA,CFOR;;;AAmBT;EAIgB,IAAA,EE1BR,IF0BQ;EAAqB;;;EAEpB,UAAA,EAAA,CAAA,QAAA,EEvBQ,cFuBR,EAAA,GAAA,IAAA;;;;AClCjB;;AAIQ,KCcI,QDdJ,CAAA,MAAA,CAAA,GAAA,CAAA,OAAA,ECciC,eDdjC,EAAA,GCcqD,ODdrD,CCc6D,MDd7D,CAAA;;;;AAmBI,cCAC,UDAe,CAAA,MACjB,CAAA,CAAA;EAGK;;;;;;;;AClChB;EASiB,UAAA,IAAA,EAAA,OAAe;EAAA;;;EASO,UAAA,MAAA,EA4BnB,MA5BmB,GAAA,SAAA;EAO3B;;;YAAyD,KAAA,EA0BlD,KA1BkD,GAAA,SAAA;;;AAKrE;EAAuB,SAAA,QAAA,EA0BF,OA1BE,CA0BM,MA1BN,CAAA;UAgBH,WAAA;;;;;;;aAoB+C,CAAA;IAAA,IAAA;IAAA;GAAA,EAAA;IAAT,IAAA,EAAhB,IAAgB;
|
|
1
|
+
{"version":3,"file":"index-DY6lIIYV.d.ts","names":[],"sources":["../src/file/file-drop-handler.ts","../src/file/file-paste-handler.ts","../src/file/file-upload.ts"],"sourcesContent":[],"mappings":";;;;UAYiB,sBAAA;;AAAjB;;MAIQ,EAAA,UAAA;;;;EAwBI,KAAA,EAnBH,SAmBG;EAII;;;MAEb,EApBK,IAoBL;EAAc;;;;AClCjB;;;;;;AAuBA;AAIgB,KDCJ,eAAA,GCD0B,CAAA,OAAA,EDE3B,sBCF2B,EAAA,GAAA,OAAA,GAAA,IAAA;AAAA,iBDKtB,qBAAA,CCLsB,OAAA,EDM3B,eCN2B,CAAA,EDOnC,cCPmC;;;UA3BrB,uBAAA;;ADAjB;;MAIQ,ECAA,UDAA;;;;EAwBI,KAAA,ECnBH,cDmBkB;EAIX;;;MAEb,ECpBK,IDoBL;;;;;AClCH;;;AASS,KAcG,gBAAA,GAdH,CAAA,OAAA,EAeE,uBAfF,EAAA,GAAA,OAAA,GAAA,IAAA;AAKD,iBAaQ,sBAAA,CAbR,OAAA,EAcG,gBAdH,CAAA,EAeL,cAfK;;;;;;UCrBS,cAAA;EFOA,MAAA,EAAA,MAAA;EAAsB,KAAA,EAAA,MAAA;;AAS9B,UEPQ,eAAA,CFOR;;;AAmBT;EAIgB,IAAA,EE1BR,IF0BQ;EAAqB;;;EAEpB,UAAA,EAAA,CAAA,QAAA,EEvBQ,cFuBR,EAAA,GAAA,IAAA;;;;AClCjB;;AAIQ,KCcI,QDdJ,CAAA,MAAA,CAAA,GAAA,CAAA,OAAA,ECciC,eDdjC,EAAA,GCcqD,ODdrD,CCc6D,MDd7D,CAAA;;;;AAmBI,cCAC,UDAe,CAAA,MACjB,CAAA,CAAA;EAGK;;;;;;;;AClChB;EASiB,UAAA,IAAA,EAAA,OAAe;EAAA;;;EASO,UAAA,MAAA,EA4BnB,MA5BmB,GAAA,SAAA;EAO3B;;;YAAyD,KAAA,EA0BlD,KA1BkD,GAAA,SAAA;;;AAKrE;EAAuB,SAAA,QAAA,EA0BF,OA1BE,CA0BM,MA1BN,CAAA;UAgBH,WAAA;;;;;;;aAoB+C,CAAA;IAAA,IAAA;IAAA;GAAA,EAAA;IAAT,IAAA,EAAhB,IAAgB;IAiCjC,QAAA,EAjCiC,QAiCjC,CAjC0C,MAiC1C,CAAA;;;;;yCAAA,0BACpB;;;;mDAcA,WAAW"}
|
|
@@ -55,8 +55,7 @@ function defineMarkInputRule(options) {
|
|
|
55
55
|
*/
|
|
56
56
|
function defineTextBlockInputRule({ regex, type, attrs }) {
|
|
57
57
|
return defineInputRuleFacetPayload(({ schema }) => {
|
|
58
|
-
|
|
59
|
-
return textblockTypeInputRule(regex, nodeType, attrs);
|
|
58
|
+
return textblockTypeInputRule(regex, getNodeType(schema, type), attrs);
|
|
60
59
|
});
|
|
61
60
|
}
|
|
62
61
|
/**
|
|
@@ -71,8 +70,7 @@ function defineTextBlockInputRule({ regex, type, attrs }) {
|
|
|
71
70
|
*/
|
|
72
71
|
function defineWrappingInputRule({ regex, type, attrs, join }) {
|
|
73
72
|
return defineInputRuleFacetPayload(({ schema }) => {
|
|
74
|
-
|
|
75
|
-
return wrappingInputRule(regex, nodeType, attrs, join);
|
|
73
|
+
return wrappingInputRule(regex, getNodeType(schema, type), attrs, join);
|
|
76
74
|
});
|
|
77
75
|
}
|
|
78
76
|
function defineInputRuleFacetPayload(input) {
|
|
@@ -81,8 +79,7 @@ function defineInputRuleFacetPayload(input) {
|
|
|
81
79
|
const inputRuleFacet = defineFacet({
|
|
82
80
|
reducer: (inputs) => {
|
|
83
81
|
return (context) => {
|
|
84
|
-
|
|
85
|
-
return [inputRules({ rules })];
|
|
82
|
+
return [inputRules({ rules: inputs.flatMap((callback) => callback(context)) })];
|
|
86
83
|
};
|
|
87
84
|
},
|
|
88
85
|
parent: pluginFacet
|
|
@@ -90,4 +87,4 @@ const inputRuleFacet = defineFacet({
|
|
|
90
87
|
|
|
91
88
|
//#endregion
|
|
92
89
|
export { createMarkInputRule, defineInputRule, defineMarkInputRule, defineTextBlockInputRule, defineWrappingInputRule };
|
|
93
|
-
//# sourceMappingURL=input-rule-
|
|
90
|
+
//# sourceMappingURL=input-rule-DO_iy2aT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"input-rule-DO_iy2aT.js","names":[],"sources":["../src/input-rule/index.ts"],"sourcesContent":["import {\n defineFacet,\n defineFacetPayload,\n getMarkType,\n getNodeType,\n isMarkAbsent,\n maybeRun,\n pluginFacet,\n type PlainExtension,\n type PluginPayload,\n} from '@prosekit/core'\nimport {\n InputRule,\n inputRules,\n textblockTypeInputRule,\n wrappingInputRule,\n} from '@prosekit/pm/inputrules'\nimport type {\n Attrs,\n MarkType,\n NodeType,\n ProseMirrorNode,\n Schema,\n} from '@prosekit/pm/model'\nimport type { Plugin } from '@prosekit/pm/state'\n\n/**\n * Defines an input rule extension.\n *\n * @param rule - The ProseMirror input rule to add.\n *\n * @public\n */\nexport function defineInputRule(rule: InputRule): PlainExtension {\n return defineInputRuleFacetPayload(() => rule)\n}\n\n/**\n * Options for {@link defineMarkInputRule}.\n *\n * @public\n */\nexport interface MarkInputRuleOptions {\n /**\n * The regular expression to match against, which should end with `$` and has\n * exactly one capture group. All other matched text outside the capture group\n * will be deleted.\n */\n regex: RegExp\n\n /**\n * The type of mark to set.\n */\n type: string | MarkType\n\n /**\n * Attributes to set on the mark.\n */\n attrs?: Attrs | null | ((match: RegExpMatchArray) => Attrs | null)\n\n /**\n * Whether this rule should fire inside marks marked as [code](https://prosemirror.net/docs/ref/#model.MarkSpec.code).\n *\n * @default `false`\n */\n inCodeMark?: boolean\n}\n\n/**\n * @internal\n */\nexport function createMarkInputRule({\n regex,\n type,\n attrs = null,\n inCodeMark = false,\n}: MarkInputRuleOptions): InputRule {\n const rule = new InputRule(regex, (state, match, start, end) => {\n const { tr, schema } = state\n const [fullText, markText] = match\n\n if (!markText) {\n return null\n }\n\n const markStart = start + fullText.indexOf(markText)\n const markEnd = markStart + markText.length\n\n if (!(start <= markStart && markStart < markEnd && markEnd <= end)) {\n // Incorrect regex.\n return null\n }\n\n const markType = getMarkType(schema, type)\n const mark = markType.create(maybeRun(attrs, match))\n\n if (!isMarkAbsent(tr.doc, markStart, markEnd, markType, attrs)) {\n // The mark is already active.\n return null\n }\n\n const initialStoredMarks = tr.storedMarks ?? []\n\n tr.addMark(markStart, markEnd, mark)\n\n if (markEnd < end) {\n tr.delete(markEnd, end)\n }\n if (start < markStart) {\n tr.delete(start, markStart)\n }\n\n // Make sure not to reactivate any marks which had previously been\n // deactivated. By keeping track of the initial stored marks we are able to\n // discard any unintended consequences of deleting text and adding it again.\n tr.setStoredMarks(initialStoredMarks)\n\n return tr\n }, { inCodeMark })\n\n return rule\n}\n\n/**\n * Defines an input rule for automatically adding inline marks when a given\n * pattern is typed.\n *\n * @public\n */\nexport function defineMarkInputRule(\n options: MarkInputRuleOptions,\n): PlainExtension {\n return defineInputRule(createMarkInputRule(options))\n}\n\n/**\n * Defines an input rule that changes the type of a textblock when the matched\n * text is typed into it.\n *\n * See also [textblockTypeInputRule](https://prosemirror.net/docs/ref/#inputrules.textblockTypeInputRule)\n *\n * @param options\n *\n * @public\n */\nexport function defineTextBlockInputRule({\n regex,\n type,\n attrs,\n}: {\n /**\n * The regular expression to match against, which should end with `$`. It\n * usually also starts with `^` to that it is only matched at the start of a\n * textblock.\n */\n regex: RegExp\n\n /**\n * The node type to replace the matched text with.\n */\n type: string | NodeType\n\n /**\n * Attributes to set on the node.\n */\n attrs?: Attrs | null | ((match: RegExpMatchArray) => Attrs | null)\n}): PlainExtension {\n return defineInputRuleFacetPayload(({ schema }): InputRule => {\n const nodeType = getNodeType(schema, type)\n return textblockTypeInputRule(regex, nodeType, attrs)\n })\n}\n\n/**\n * Defines an input rule for automatically wrapping a textblock when a given\n * string is typed.\n *\n * See also [wrappingInputRule](https://prosemirror.net/docs/ref/#inputrules.wrappingInputRule)\n *\n * @param options\n *\n * @public\n */\nexport function defineWrappingInputRule({\n regex,\n type,\n attrs,\n join,\n}: {\n /**\n * The regular expression to match against, which should end with `$`. It\n * usually also starts with `^` to that it is only matched at the start of a\n * textblock.\n */\n regex: RegExp\n\n /**\n * The type of node to wrap in.\n */\n type: string | NodeType\n\n /**\n * Attributes to set on the node.\n */\n attrs?: Attrs | null | ((match: RegExpMatchArray) => Attrs | null)\n\n /**\n * By default, if there's a node with the same type above the newly wrapped\n * node, the rule will try to\n * [join](https://prosemirror.net/docs/ref/#transform.Transform.join) those\n * two nodes. You can pass a join predicate, which takes a regular expression\n * match and the node before the wrapped node, and can return a boolean to\n * indicate whether a join should happen.\n */\n join?: (match: RegExpMatchArray, node: ProseMirrorNode) => boolean\n}): PlainExtension {\n return defineInputRuleFacetPayload(({ schema }): InputRule => {\n const nodeType = getNodeType(schema, type)\n return wrappingInputRule(regex, nodeType, attrs, join)\n })\n}\n\nfunction defineInputRuleFacetPayload(input: InputRulePayload): PlainExtension {\n return defineFacetPayload(inputRuleFacet, [input]) as PlainExtension\n}\n\ntype InputRulePayload = (context: { schema: Schema }) => InputRule\n\nconst inputRuleFacet = defineFacet<InputRulePayload, PluginPayload>({\n reducer: (inputs: InputRulePayload[]): PluginPayload => {\n return (context): Plugin[] => {\n const rules: InputRule[] = inputs.flatMap((callback) => callback(context))\n return [inputRules({ rules })]\n }\n },\n parent: pluginFacet,\n})\n"],"mappings":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;AAGJ,SAAS,4BAA4B,OAAyC;AAC5E,QAAO,mBAAmB,gBAAgB,CAAC,MAAM,CAAC;;AAKpD,MAAM,iBAAiB,YAA6C;CAClE,UAAU,WAA8C;AACtD,UAAQ,YAAsB;AAE5B,UAAO,CAAC,WAAW,EAAE,OADM,OAAO,SAAS,aAAa,SAAS,QAAQ,CAAC,EAC9C,CAAC,CAAC;;;CAGlC,QAAQ;CACT,CAAC"}
|
|
@@ -87,9 +87,8 @@ function splitTextByRegex(text, regex) {
|
|
|
87
87
|
function defineMarkPasteRule(options) {
|
|
88
88
|
return definePasteRule({ handler: ({ slice, view, plain }) => {
|
|
89
89
|
if (plain) return slice;
|
|
90
|
-
const markType = getMarkType(view.state.schema, options.type);
|
|
91
90
|
return replaceMarkInSlice({
|
|
92
|
-
markType,
|
|
91
|
+
markType: getMarkType(view.state.schema, options.type),
|
|
93
92
|
regex: options.regex,
|
|
94
93
|
getAttrs: options.getAttrs,
|
|
95
94
|
shouldSkip: options.shouldSkip
|
|
@@ -160,4 +159,4 @@ function replaceMarkInInlineNode(options, node) {
|
|
|
160
159
|
|
|
161
160
|
//#endregion
|
|
162
161
|
export { defineMarkPasteRule, definePasteRule };
|
|
163
|
-
//# sourceMappingURL=paste-rule-
|
|
162
|
+
//# sourceMappingURL=paste-rule-Brej6cWi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paste-rule-BIztzELg.js","names":["handlers: PasteRulePayload[]","chunks: Array<[string, RegExpExecArray | undefined]>","match: RegExpExecArray | null","children: ProseMirrorNode[]","newChildren: ProseMirrorNode[]","nodes: ProseMirrorNode[]","text"],"sources":["../src/paste-rule/paste-rule-plugin.ts","../src/paste-rule/paste-rule.ts","../src/paste-rule/split-text-by-regex.ts","../src/paste-rule/mark-paste-rule.ts"],"sourcesContent":["import {\n defineFacet,\n defineFacetPayload,\n pluginFacet,\n type PlainExtension,\n type PluginPayload,\n} from '@prosekit/core'\nimport type { Slice } from '@prosekit/pm/model'\nimport {\n PluginKey,\n ProseMirrorPlugin,\n} from '@prosekit/pm/state'\nimport type { EditorView } from '@prosekit/pm/view'\n\ntype PasteRulePayload = (options: { slice: Slice; view: EditorView; plain: boolean }) => Slice\n\n/**\n * @internal\n */\nconst pasteRuleFacet = defineFacet<PasteRulePayload, PluginPayload>({\n reduce: () => {\n let handlers: PasteRulePayload[] = []\n\n const transformPasted = (slice: Slice, view: EditorView, plain: boolean): Slice => {\n for (const handler of handlers) {\n slice = handler({ slice, view, plain })\n }\n return slice\n }\n\n const plugin = new ProseMirrorPlugin({\n key: new PluginKey('prosekit-paste-rule'),\n props: {\n transformPasted,\n },\n })\n\n return (inputs: PasteRulePayload[]) => {\n // Last added rule (highest priority) is applied first\n handlers = [...inputs].reverse()\n return plugin\n }\n },\n singleton: true,\n parent: pluginFacet,\n})\n\n/**\n * @internal\n */\nexport function definePasteRulePlugin(payload: PasteRulePayload): PlainExtension {\n return defineFacetPayload(pasteRuleFacet, [payload]) as PlainExtension\n}\n","import type { PlainExtension } from '@prosekit/core'\nimport type { Slice } from '@prosekit/pm/model'\nimport type { EditorView } from '@prosekit/pm/view'\n\nimport { definePasteRulePlugin } from './paste-rule-plugin'\n\n/**\n * @public\n *\n * Options for {@link PasteRuleHandler}.\n */\nexport interface PasteRuleHandlerOptions {\n /**\n * The slice to be pasted.\n */\n slice: Slice\n\n /**\n * The editor view.\n */\n view: EditorView\n\n /**\n * Whether the pasted content is treated as plain text. This is true when the\n * `Shift` key is held when pasting.\n */\n plain: boolean\n}\n\n/**\n * @public\n *\n * Can be used to transform pasted or dragged-and-dropped content before it is\n * applied to the document.\n */\nexport type PasteRuleHandler = (options: PasteRuleHandlerOptions) => Slice\n\n/**\n * Options for {@link definePasteRule}.\n *\n * @public\n */\nexport interface PasteRuleOptions {\n /**\n * A function to be called when a paste rule is triggered.\n */\n handler: PasteRuleHandler\n}\n\n/**\n * Defines a paste rule. This rule allows you to modify pasted or dragged\n * content before it is inserted into the document.\n *\n * @param options\n *\n * @public\n */\nexport function definePasteRule({ handler }: PasteRuleOptions): PlainExtension {\n return definePasteRulePlugin(handler)\n}\n","/**\n * Splits text into chunks based on regex matches, preserving both matched and unmatched segments.\n * Returns an array of tuples where each tuple contains a text segment and either the match data\n * (for matched segments) or undefined (for unmatched segments).\n */\nexport function splitTextByRegex(\n text: string,\n regex: RegExp,\n): Array<[string, RegExpExecArray | undefined]> | undefined {\n regex.lastIndex = 0\n\n const chunks: Array<[string, RegExpExecArray | undefined]> = []\n let lastIndex = 0\n let match: RegExpExecArray | null\n let matched = false\n\n while ((match = regex.exec(text))) {\n const start = match.index\n const end = regex.lastIndex\n\n // Push the unmatched prefix, if any.\n if (start > lastIndex) {\n chunks.push([text.slice(lastIndex, start), undefined])\n }\n\n // Push the matched segment.\n chunks.push([text.slice(start, end), match])\n matched = true\n\n if (lastIndex === end) {\n // Safeguard against zero-width matches that would otherwise cause an infinite loop.\n return\n }\n lastIndex = end\n }\n\n if (matched && lastIndex < text.length) {\n chunks.push([text.slice(lastIndex), undefined])\n }\n\n regex.lastIndex = 0\n\n return matched ? chunks : undefined\n}\n","import {\n getMarkType,\n type PlainExtension,\n} from '@prosekit/core'\nimport type {\n Attrs,\n MarkType,\n ProseMirrorNode,\n} from '@prosekit/pm/model'\nimport {\n Fragment,\n Slice,\n} from '@prosekit/pm/model'\n\nimport { definePasteRule } from './paste-rule'\nimport { splitTextByRegex } from './split-text-by-regex'\n\n/**\n * The options for {@link defineMarkPasteRule}.\n *\n * @public\n */\nexport interface MarkPasteRuleOptions {\n /**\n * The regular expression to match against. It must have a `g` flag to match\n * all instances of the mark.\n */\n regex: RegExp\n\n /**\n * The mark type to apply to the matched text.\n */\n type: string | MarkType\n\n /**\n * A function used to compute attributes to set on the mark created by this\n * rule. When it returns `false`, the rule won't match. When it returns `null`\n * or `undefined`, that is interpreted as an empty/default set of attributes.\n * @default null\n */\n getAttrs?: (match: RegExpExecArray) => Attrs | null | undefined | false\n\n /**\n * Optional function to determine if a text node should be skipped.\n * Default behavior: skip code nodes and nodes that already have the target mark.\n */\n shouldSkip?: (node: ProseMirrorNode) => boolean\n}\n\n/**\n * Defines a paste rule that applies marks based on regex patterns.\n *\n * @public\n */\nexport function defineMarkPasteRule(options: MarkPasteRuleOptions): PlainExtension {\n return definePasteRule({\n handler: ({ slice, view, plain }) => {\n if (plain) {\n return slice\n }\n\n const markType = getMarkType(view.state.schema, options.type)\n\n return replaceMarkInSlice({\n markType,\n regex: options.regex,\n getAttrs: options.getAttrs,\n shouldSkip: options.shouldSkip,\n }, slice)\n },\n })\n}\n\ninterface MarkPasteRuleHandlerOptions {\n markType: MarkType\n regex: RegExp\n getAttrs?: (match: RegExpExecArray) => Attrs | null | undefined | false\n shouldSkip?: (node: ProseMirrorNode) => boolean\n}\n\nfunction replaceMarkInSlice(options: MarkPasteRuleHandlerOptions, slice: Slice): Slice {\n const newFragment = replaceMarkInFragment(options, slice.content)\n if (!newFragment) {\n return slice\n }\n return new Slice(newFragment, slice.openStart, slice.openEnd)\n}\n\nfunction replaceMarkInFragment(options: MarkPasteRuleHandlerOptions, fragment: Fragment): Fragment | undefined {\n let changed = false\n let children: ProseMirrorNode[] = []\n\n for (const child of fragment.content) {\n const newChild = replaceMarkInNode(options, child)\n if (newChild) {\n changed = true\n }\n children.push(newChild || child)\n }\n\n if (changed) {\n return Fragment.from(children)\n }\n\n return\n}\n\nfunction replaceMarkInNode(options: MarkPasteRuleHandlerOptions, node: ProseMirrorNode): ProseMirrorNode | undefined {\n if (node.type.spec.code) {\n return\n }\n if (node.type.isInline) {\n return\n }\n if (node.type.isTextblock) {\n return replaceMarkInTextblockNode(options, node)\n }\n\n const newChildren = replaceMarkInFragment(options, node.content)\n if (!newChildren) {\n return\n }\n return node.copy(newChildren)\n}\n\nfunction replaceMarkInTextblockNode(options: MarkPasteRuleHandlerOptions, node: ProseMirrorNode): ProseMirrorNode | undefined {\n const newChildren: ProseMirrorNode[] = []\n let changed = false\n\n for (const inlineNode of node.content.content) {\n const newInlineNodes = replaceMarkInInlineNode(options, inlineNode)\n if (newInlineNodes) {\n changed = true\n newChildren.push(...newInlineNodes)\n } else {\n newChildren.push(inlineNode)\n }\n }\n if (changed) {\n return node.copy(Fragment.from(newChildren))\n }\n return\n}\n\nfunction replaceMarkInInlineNode(options: MarkPasteRuleHandlerOptions, node: ProseMirrorNode): ProseMirrorNode[] | undefined {\n const text = node.text\n if (!text) {\n return\n }\n\n const { markType, shouldSkip } = options\n\n // Use custom skip logic if provided, otherwise use default\n if (shouldSkip) {\n if (shouldSkip(node)) {\n return\n }\n } else {\n // Default skip logic: skip if already has the target mark or has code mark\n if (node.marks.some((mark) => mark.type === markType)) {\n return\n }\n if (node.marks.some((mark) => mark.type.spec.code)) {\n return\n }\n }\n\n const chunks = splitTextByRegex(text, options.regex)\n if (!chunks) {\n return\n }\n\n const schema = node.type.schema\n const nodes: ProseMirrorNode[] = []\n\n for (const [text, match] of chunks) {\n if (!text) {\n continue\n }\n if (match) {\n const attrs = options.getAttrs?.(match) ?? null\n if (attrs !== false) {\n const mark = markType.create(attrs)\n nodes.push(schema.text(text, [...node.marks, mark]))\n } else {\n nodes.push(schema.text(text, node.marks))\n }\n } else {\n nodes.push(schema.text(text, node.marks))\n }\n }\n\n return nodes\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,iBAAiB,YAA6C;CAClE,cAAc;EACZ,IAAIA,WAA+B,EAAE;EAErC,MAAM,mBAAmB,OAAc,MAAkB,UAA0B;AACjF,QAAK,MAAM,WAAW,SACpB,SAAQ,QAAQ;IAAE;IAAO;IAAM;IAAO,CAAC;AAEzC,UAAO;;EAGT,MAAM,SAAS,IAAI,kBAAkB;GACnC,KAAK,IAAI,UAAU,sBAAsB;GACzC,OAAO,EACL,iBACD;GACF,CAAC;AAEF,UAAQ,WAA+B;AAErC,cAAW,CAAC,GAAG,OAAO,CAAC,SAAS;AAChC,UAAO;;;CAGX,WAAW;CACX,QAAQ;CACT,CAAC;;;;AAKF,SAAgB,sBA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;AAClC,MAAI,CAACA,OACH;AAEF,MAAI,OAAO;GACT,MAAM,QAAQ,QAAQ,WAAW,MAAM,IAAI;AAC3C,OAAI,UAAU,OAAO;IACnB,MAAM,OAAO,SAAS,OAAO,MAAM;AACnC,UAAM,KAAK,OAAO,KAAKA,QAAM,CAAC,GAAG,KAAK,OAAO,KAAK,CAAC,CAAC;SAEpD,OAAM,KAAK,OAAO,KAAKA,QAAM,KAAK,MAAM,CAAC;QAG3C,OAAM,KAAK,OAAO,KAAKA,QAAM,KAAK,MAAM,CAAC;;AAI7C,QAAO"}
|
|
1
|
+
{"version":3,"file":"paste-rule-Brej6cWi.js","names":["handlers: PasteRulePayload[]","chunks: Array<[string, RegExpExecArray | undefined]>","match: RegExpExecArray | null","children: ProseMirrorNode[]","newChildren: ProseMirrorNode[]","nodes: ProseMirrorNode[]","text"],"sources":["../src/paste-rule/paste-rule-plugin.ts","../src/paste-rule/paste-rule.ts","../src/paste-rule/split-text-by-regex.ts","../src/paste-rule/mark-paste-rule.ts"],"sourcesContent":["import {\n defineFacet,\n defineFacetPayload,\n pluginFacet,\n type PlainExtension,\n type PluginPayload,\n} from '@prosekit/core'\nimport type { Slice } from '@prosekit/pm/model'\nimport {\n PluginKey,\n ProseMirrorPlugin,\n} from '@prosekit/pm/state'\nimport type { EditorView } from '@prosekit/pm/view'\n\ntype PasteRulePayload = (options: { slice: Slice; view: EditorView; plain: boolean }) => Slice\n\n/**\n * @internal\n */\nconst pasteRuleFacet = defineFacet<PasteRulePayload, PluginPayload>({\n reduce: () => {\n let handlers: PasteRulePayload[] = []\n\n const transformPasted = (slice: Slice, view: EditorView, plain: boolean): Slice => {\n for (const handler of handlers) {\n slice = handler({ slice, view, plain })\n }\n return slice\n }\n\n const plugin = new ProseMirrorPlugin({\n key: new PluginKey('prosekit-paste-rule'),\n props: {\n transformPasted,\n },\n })\n\n return (inputs: PasteRulePayload[]) => {\n // Last added rule (highest priority) is applied first\n handlers = [...inputs].reverse()\n return plugin\n }\n },\n singleton: true,\n parent: pluginFacet,\n})\n\n/**\n * @internal\n */\nexport function definePasteRulePlugin(payload: PasteRulePayload): PlainExtension {\n return defineFacetPayload(pasteRuleFacet, [payload]) as PlainExtension\n}\n","import type { PlainExtension } from '@prosekit/core'\nimport type { Slice } from '@prosekit/pm/model'\nimport type { EditorView } from '@prosekit/pm/view'\n\nimport { definePasteRulePlugin } from './paste-rule-plugin'\n\n/**\n * @public\n *\n * Options for {@link PasteRuleHandler}.\n */\nexport interface PasteRuleHandlerOptions {\n /**\n * The slice to be pasted.\n */\n slice: Slice\n\n /**\n * The editor view.\n */\n view: EditorView\n\n /**\n * Whether the pasted content is treated as plain text. This is true when the\n * `Shift` key is held when pasting.\n */\n plain: boolean\n}\n\n/**\n * @public\n *\n * Can be used to transform pasted or dragged-and-dropped content before it is\n * applied to the document.\n */\nexport type PasteRuleHandler = (options: PasteRuleHandlerOptions) => Slice\n\n/**\n * Options for {@link definePasteRule}.\n *\n * @public\n */\nexport interface PasteRuleOptions {\n /**\n * A function to be called when a paste rule is triggered.\n */\n handler: PasteRuleHandler\n}\n\n/**\n * Defines a paste rule. This rule allows you to modify pasted or dragged\n * content before it is inserted into the document.\n *\n * @param options\n *\n * @public\n */\nexport function definePasteRule({ handler }: PasteRuleOptions): PlainExtension {\n return definePasteRulePlugin(handler)\n}\n","/**\n * Splits text into chunks based on regex matches, preserving both matched and unmatched segments.\n * Returns an array of tuples where each tuple contains a text segment and either the match data\n * (for matched segments) or undefined (for unmatched segments).\n */\nexport function splitTextByRegex(\n text: string,\n regex: RegExp,\n): Array<[string, RegExpExecArray | undefined]> | undefined {\n regex.lastIndex = 0\n\n const chunks: Array<[string, RegExpExecArray | undefined]> = []\n let lastIndex = 0\n let match: RegExpExecArray | null\n let matched = false\n\n while ((match = regex.exec(text))) {\n const start = match.index\n const end = regex.lastIndex\n\n // Push the unmatched prefix, if any.\n if (start > lastIndex) {\n chunks.push([text.slice(lastIndex, start), undefined])\n }\n\n // Push the matched segment.\n chunks.push([text.slice(start, end), match])\n matched = true\n\n if (lastIndex === end) {\n // Safeguard against zero-width matches that would otherwise cause an infinite loop.\n return\n }\n lastIndex = end\n }\n\n if (matched && lastIndex < text.length) {\n chunks.push([text.slice(lastIndex), undefined])\n }\n\n regex.lastIndex = 0\n\n return matched ? chunks : undefined\n}\n","import {\n getMarkType,\n type PlainExtension,\n} from '@prosekit/core'\nimport type {\n Attrs,\n MarkType,\n ProseMirrorNode,\n} from '@prosekit/pm/model'\nimport {\n Fragment,\n Slice,\n} from '@prosekit/pm/model'\n\nimport { definePasteRule } from './paste-rule'\nimport { splitTextByRegex } from './split-text-by-regex'\n\n/**\n * The options for {@link defineMarkPasteRule}.\n *\n * @public\n */\nexport interface MarkPasteRuleOptions {\n /**\n * The regular expression to match against. It must have a `g` flag to match\n * all instances of the mark.\n */\n regex: RegExp\n\n /**\n * The mark type to apply to the matched text.\n */\n type: string | MarkType\n\n /**\n * A function used to compute attributes to set on the mark created by this\n * rule. When it returns `false`, the rule won't match. When it returns `null`\n * or `undefined`, that is interpreted as an empty/default set of attributes.\n * @default null\n */\n getAttrs?: (match: RegExpExecArray) => Attrs | null | undefined | false\n\n /**\n * Optional function to determine if a text node should be skipped.\n * Default behavior: skip code nodes and nodes that already have the target mark.\n */\n shouldSkip?: (node: ProseMirrorNode) => boolean\n}\n\n/**\n * Defines a paste rule that applies marks based on regex patterns.\n *\n * @public\n */\nexport function defineMarkPasteRule(options: MarkPasteRuleOptions): PlainExtension {\n return definePasteRule({\n handler: ({ slice, view, plain }) => {\n if (plain) {\n return slice\n }\n\n const markType = getMarkType(view.state.schema, options.type)\n\n return replaceMarkInSlice({\n markType,\n regex: options.regex,\n getAttrs: options.getAttrs,\n shouldSkip: options.shouldSkip,\n }, slice)\n },\n })\n}\n\ninterface MarkPasteRuleHandlerOptions {\n markType: MarkType\n regex: RegExp\n getAttrs?: (match: RegExpExecArray) => Attrs | null | undefined | false\n shouldSkip?: (node: ProseMirrorNode) => boolean\n}\n\nfunction replaceMarkInSlice(options: MarkPasteRuleHandlerOptions, slice: Slice): Slice {\n const newFragment = replaceMarkInFragment(options, slice.content)\n if (!newFragment) {\n return slice\n }\n return new Slice(newFragment, slice.openStart, slice.openEnd)\n}\n\nfunction replaceMarkInFragment(options: MarkPasteRuleHandlerOptions, fragment: Fragment): Fragment | undefined {\n let changed = false\n let children: ProseMirrorNode[] = []\n\n for (const child of fragment.content) {\n const newChild = replaceMarkInNode(options, child)\n if (newChild) {\n changed = true\n }\n children.push(newChild || child)\n }\n\n if (changed) {\n return Fragment.from(children)\n }\n\n return\n}\n\nfunction replaceMarkInNode(options: MarkPasteRuleHandlerOptions, node: ProseMirrorNode): ProseMirrorNode | undefined {\n if (node.type.spec.code) {\n return\n }\n if (node.type.isInline) {\n return\n }\n if (node.type.isTextblock) {\n return replaceMarkInTextblockNode(options, node)\n }\n\n const newChildren = replaceMarkInFragment(options, node.content)\n if (!newChildren) {\n return\n }\n return node.copy(newChildren)\n}\n\nfunction replaceMarkInTextblockNode(options: MarkPasteRuleHandlerOptions, node: ProseMirrorNode): ProseMirrorNode | undefined {\n const newChildren: ProseMirrorNode[] = []\n let changed = false\n\n for (const inlineNode of node.content.content) {\n const newInlineNodes = replaceMarkInInlineNode(options, inlineNode)\n if (newInlineNodes) {\n changed = true\n newChildren.push(...newInlineNodes)\n } else {\n newChildren.push(inlineNode)\n }\n }\n if (changed) {\n return node.copy(Fragment.from(newChildren))\n }\n return\n}\n\nfunction replaceMarkInInlineNode(options: MarkPasteRuleHandlerOptions, node: ProseMirrorNode): ProseMirrorNode[] | undefined {\n const text = node.text\n if (!text) {\n return\n }\n\n const { markType, shouldSkip } = options\n\n // Use custom skip logic if provided, otherwise use default\n if (shouldSkip) {\n if (shouldSkip(node)) {\n return\n }\n } else {\n // Default skip logic: skip if already has the target mark or has code mark\n if (node.marks.some((mark) => mark.type === markType)) {\n return\n }\n if (node.marks.some((mark) => mark.type.spec.code)) {\n return\n }\n }\n\n const chunks = splitTextByRegex(text, options.regex)\n if (!chunks) {\n return\n }\n\n const schema = node.type.schema\n const nodes: ProseMirrorNode[] = []\n\n for (const [text, match] of chunks) {\n if (!text) {\n continue\n }\n if (match) {\n const attrs = options.getAttrs?.(match) ?? null\n if (attrs !== false) {\n const mark = markType.create(attrs)\n nodes.push(schema.text(text, [...node.marks, mark]))\n } else {\n nodes.push(schema.text(text, node.marks))\n }\n } else {\n nodes.push(schema.text(text, node.marks))\n }\n }\n\n return nodes\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,iBAAiB,YAA6C;CAClE,cAAc;EACZ,IAAIA,WAA+B,EAAE;EAErC,MAAM,mBAAmB,OAAc,MAAkB,UAA0B;AACjF,QAAK,MAAM,WAAW,SACpB,SAAQ,QAAQ;IAAE;IAAO;IAAM;IAAO,CAAC;AAEzC,UAAO;;EAGT,MAAM,SAAS,IAAI,kBAAkB;GACnC,KAAK,IAAI,UAAU,sBAAsB;GACzC,OAAO,EACL,iBACD;GACF,CAAC;AAEF,UAAQ,WAA+B;AAErC,cAAW,CAAC,GAAG,OAAO,CAAC,SAAS;AAChC,UAAO;;;CAGX,WAAW;CACX,QAAQ;CACT,CAAC;;;;AAKF,SAAgB,sBAAsB,SAA2C;AAC/E,QAAO,mBAAmB,gBAAgB,CAAC,QAAQ,CAAC;;;;;;;;;;;;;ACMtD,SAAgB,gBAAgB,EAAE,WAA6C;AAC7E,QAAO,sBAAsB,QAAQ;;;;;;;;;;ACrDvC,SAAgB,iBACd,MACA,OAC0D;AAC1D,OAAM,YAAY;CAElB,MAAMC,SAAuD,EAAE;CAC/D,IAAI,YAAY;CAChB,IAAIC;CACJ,IAAI,UAAU;AAEd,QAAQ,QAAQ,MAAM,KAAK,KAAK,EAAG;EACjC,MAAM,QAAQ,MAAM;EACpB,MAAM,MAAM,MAAM;AAGlB,MAAI,QAAQ,UACV,QAAO,KAAK,CAAC,KAAK,MAAM,WAAW,MAAM,EAAE,OAAU,CAAC;AAIxD,SAAO,KAAK,CAAC,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H,MAAMC,cAAiC,EAAE;CACzC,IAAI,UAAU;AAEd,MAAK,MAAM,cAAc,KAAK,QAAQ,SAAS;EAC7C,MAAM,iBAAiB,wBAAwB,SAAS,WAAW;AACnE,MAAI,gBAAgB;AAClB,aAAU;AACV,eAAY,KAAK,GAAG,eAAe;QAEnC,aAAY,KAAK,WAAW;;AAGhC,KAAI,QACF,QAAO,KAAK,KAAK,SAAS,KAAK,YAAY,CAAC;;AAKhD,SAAS,wBAAwB,SAAsC,MAAsD;CAC3H,MAAM,OAAO,KAAK;AAClB,KAAI,CAAC,KACH;CAGF,MAAM,EAAE,UAAU,eAAe;AAGjC,KAAI,YACF;MAAI,WAAW,KAAK,CAClB;QAEG;AAEL,MAAI,KAAK,MAAM,MAAM,SAAS,KAAK,SAAS,SAAS,CACnD;AAEF,MAAI,KAAK,MAAM,MAAM,SAAS,KAAK,KAAK,KAAK,KAAK,CAChD;;CAIJ,MAAM,SAAS,iBAAiB,MAAM,QAAQ,MAAM;AACpD,KAAI,CAAC,OACH;CAGF,MAAM,SAAS,KAAK,KAAK;CACzB,MAAMC,QAA2B,EAAE;AAEnC,MAAK,MAAM,CAACC,QAAM,UAAU,QAAQ;AAClC,MAAI,CAACA,OACH;AAEF,MAAI,OAAO;GACT,MAAM,QAAQ,QAAQ,WAAW,MAAM,IAAI;AAC3C,OAAI,UAAU,OAAO;IACnB,MAAM,OAAO,SAAS,OAAO,MAAM;AACnC,UAAM,KAAK,OAAO,KAAKA,QAAM,CAAC,GAAG,KAAK,OAAO,KAAK,CAAC,CAAC;SAEpD,OAAM,KAAK,OAAO,KAAKA,QAAM,KAAK,MAAM,CAAC;QAG3C,OAAM,KAAK,OAAO,KAAKA,QAAM,KAAK,MAAM,CAAC;;AAI7C,QAAO"}
|
|
@@ -98,11 +98,10 @@ function calcPluginStateMatching(state, rules) {
|
|
|
98
98
|
const match = rule.regex.exec(textBefore);
|
|
99
99
|
if (!match) continue;
|
|
100
100
|
const to = $pos.pos;
|
|
101
|
-
const from = to - textBefore.length + match.index;
|
|
102
101
|
return {
|
|
103
102
|
rule,
|
|
104
103
|
match,
|
|
105
|
-
from,
|
|
104
|
+
from: to - textBefore.length + match.index,
|
|
106
105
|
to
|
|
107
106
|
};
|
|
108
107
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prosekit-extensions-autocomplete.js","names":["pluginKey: PluginKey<PredictionPluginState>","parentOffset: number","textBefore: string","rules: AutocompleteRule[]"],"sources":["../src/autocomplete/autocomplete-helpers.ts","../src/autocomplete/autocomplete-plugin.ts","../src/autocomplete/autocomplete.ts","../src/autocomplete/autocomplete-rule.ts"],"sourcesContent":["import type { ResolvedPos } from '@prosekit/pm/model'\nimport {\n PluginKey,\n type EditorState,\n type Transaction,\n} from '@prosekit/pm/state'\n\nimport type { AutocompleteRule } from './autocomplete-rule'\n\nexport function defaultCanMatch({ state }: { state: EditorState }): boolean {\n return state.selection.empty && !isInsideCode(state.selection.$from)\n}\n\nfunction isInsideCode($pos: ResolvedPos): boolean {\n for (let d = $pos.depth; d > 0; d--) {\n if ($pos.node(d).type.spec.code) {\n return true\n }\n }\n\n return $pos.marks().some((mark) => mark.type.name === 'code')\n}\n\n/**\n * @internal\n */\nexport interface PredictionPluginMatching {\n rule: AutocompleteRule\n from: number\n to: number\n match: RegExpExecArray\n}\n\n/**\n * @internal\n */\nexport interface PredictionPluginState {\n /**\n * The matching positions that should be ignored.\n */\n ignores: number[]\n\n /**\n * The current active matching.\n */\n matching: PredictionPluginMatching | null\n}\n\n/**\n * @internal\n */\ninterface PredictionTransactionMeta {\n /**\n * The from position that should be ignored.\n */\n ignore: number\n}\n\nexport function getPluginState(state: EditorState): PredictionPluginState | undefined {\n return pluginKey.getState(state)\n}\n\nexport function getTrMeta(tr: Transaction): PredictionTransactionMeta | undefined {\n return tr.getMeta(pluginKey) as PredictionTransactionMeta | undefined\n}\n\nexport function setTrMeta(\n tr: Transaction,\n meta: PredictionTransactionMeta,\n): Transaction {\n return tr.setMeta(pluginKey, meta)\n}\n\nexport const pluginKey: PluginKey<PredictionPluginState> = new PluginKey<PredictionPluginState>('prosekit-autocomplete')\n","import { OBJECT_REPLACEMENT_CHARACTER } from '@prosekit/core'\nimport {\n Plugin,\n type EditorState,\n type Transaction,\n} from '@prosekit/pm/state'\nimport {\n Decoration,\n DecorationSet,\n} from '@prosekit/pm/view'\n\nimport {\n getPluginState,\n getTrMeta,\n pluginKey,\n setTrMeta,\n type PredictionPluginMatching,\n type PredictionPluginState,\n} from './autocomplete-helpers'\nimport type { AutocompleteRule } from './autocomplete-rule'\n\nexport function createAutocompletePlugin({\n getRules,\n}: {\n getRules: () => AutocompleteRule[]\n}): Plugin {\n return new Plugin<PredictionPluginState>({\n key: pluginKey,\n\n state: {\n init: (): PredictionPluginState => {\n return { ignores: [], matching: null }\n },\n apply: (\n tr: Transaction,\n prevValue: PredictionPluginState,\n oldState: EditorState,\n newState: EditorState,\n ): PredictionPluginState => {\n const meta = getTrMeta(tr)\n\n // No changes\n if (\n !tr.docChanged\n && oldState.selection.eq(newState.selection)\n && !meta\n ) {\n return prevValue\n }\n\n // Receiving a meta means that we are ignoring a match\n if (meta) {\n let ignores = prevValue.ignores\n if (!ignores.includes(meta.ignore)) {\n ignores = [...ignores, meta.ignore]\n }\n return { matching: null, ignores }\n }\n\n // Calculate the new ignores\n const ignoreSet = new Set(prevValue.ignores.map(pos => tr.mapping.map(pos)))\n\n // Calculate the new matching\n let matching = calcPluginStateMatching(newState, getRules())\n\n // Check if the matching should be ignored\n if (matching && ignoreSet.has(matching.from)) {\n matching = null\n }\n\n // Return the new matching and ignores\n return { matching, ignores: Array.from(ignoreSet) }\n },\n },\n\n view: () => ({\n update: (view, prevState) => {\n const prevValue = getPluginState(prevState)\n const currValue = getPluginState(view.state)\n\n if (\n prevValue?.matching\n && prevValue.matching.rule !== currValue?.matching?.rule\n ) {\n // Deactivate the previous rule\n prevValue.matching.rule.onLeave?.()\n }\n\n if (\n currValue?.matching\n && !currValue.ignores.includes(currValue.matching.from)\n ) {\n // Activate the current rule\n\n const { from, to, match, rule } = currValue.matching\n\n const textContent = view.state.doc.textBetween(\n from,\n to,\n null,\n OBJECT_REPLACEMENT_CHARACTER,\n )\n\n const deleteMatch = () => {\n if (\n view.state.doc.textBetween(\n from,\n to,\n null,\n OBJECT_REPLACEMENT_CHARACTER,\n ) === textContent\n ) {\n view.dispatch(view.state.tr.delete(from, to))\n }\n }\n\n const ignoreMatch = () => {\n view.dispatch(\n setTrMeta(view.state.tr, { ignore: from }),\n )\n }\n\n rule.onMatch({\n state: view.state,\n match,\n from,\n to,\n deleteMatch,\n ignoreMatch,\n })\n }\n },\n }),\n\n props: {\n decorations: (state: EditorState) => {\n const pluginState = getPluginState(state)\n if (pluginState?.matching) {\n const { from, to } = pluginState.matching\n const deco = Decoration.inline(from, to, {\n class: 'prosemirror-prediction-match',\n })\n return DecorationSet.create(state.doc, [deco])\n }\n return null\n },\n },\n })\n}\n\nconst MAX_MATCH = 200\n\nfunction calcPluginStateMatching(\n state: EditorState,\n rules: AutocompleteRule[],\n): PredictionPluginMatching | null {\n const $pos = state.selection.$from\n\n const parentOffset: number = $pos.parentOffset\n\n const textBefore: string = $pos.parent.textBetween(\n Math.max(0, parentOffset - MAX_MATCH),\n parentOffset,\n null,\n OBJECT_REPLACEMENT_CHARACTER,\n )\n\n for (const rule of rules) {\n if (!rule.canMatch({ state })) {\n continue\n }\n\n rule.regex.lastIndex = 0\n const match = rule.regex.exec(textBefore)\n if (!match) {\n continue\n }\n\n const to = $pos.pos\n const from = to - textBefore.length + match.index\n\n return { rule, match, from, to }\n }\n\n return null\n}\n","import {\n defineFacet,\n defineFacetPayload,\n pluginFacet,\n type Extension,\n type PluginPayload,\n} from '@prosekit/core'\n\nimport { createAutocompletePlugin } from './autocomplete-plugin'\nimport type { AutocompleteRule } from './autocomplete-rule'\n\nexport function defineAutocomplete(rule: AutocompleteRule): Extension {\n return defineFacetPayload(autocompleteFacet, [rule])\n}\n\nconst autocompleteFacet = defineFacet<AutocompleteRule, PluginPayload>({\n reduce: () => {\n let rules: AutocompleteRule[] = []\n const getRules = () => rules\n const plugin = createAutocompletePlugin({ getRules })\n\n return function reducer(inputs) {\n rules = inputs\n return plugin\n }\n },\n parent: pluginFacet,\n singleton: true,\n})\n","import type { EditorState } from '@prosekit/pm/state'\n\nimport { defaultCanMatch } from './autocomplete-helpers'\n\n/**\n * Options for the {@link MatchHandler} callback.\n */\nexport interface MatchHandlerOptions {\n /**\n * The editor state.\n */\n state: EditorState\n\n /**\n * The result of `RegExp.exec`.\n */\n match: RegExpExecArray\n\n /**\n * The start position of the matched text.\n */\n from: number\n\n /**\n * The end position of the matched text.\n */\n to: number\n\n /**\n * Call this function to ignore the match. You probably want to call this\n * function when the user presses the `Escape` key.\n */\n ignoreMatch: () => void\n\n /**\n * Call this function to delete the matched text. For example, in a slash\n * menu, you might want to delete the matched text first then do something\n * else when the user presses the `Enter` key.\n */\n deleteMatch: () => void\n}\n\n/**\n * A callback that is called when the rule starts to match, and also on\n * subsequent updates while the rule continues to match.\n */\nexport type MatchHandler = (options: MatchHandlerOptions) => void\n\n/**\n * Options for the {@link CanMatchPredicate} callback.\n */\nexport interface CanMatchOptions {\n /**\n * The editor state.\n */\n state: EditorState\n}\n\n/**\n * A predicate to determine if the rule can be applied in the current editor state.\n */\nexport type CanMatchPredicate = (options: CanMatchOptions) => boolean\n\n/**\n * Options for creating an {@link AutocompleteRule}\n */\nexport interface AutocompleteRuleOptions {\n /**\n * The regular expression to match against the text before the cursor. The\n * last match before the cursor is used.\n *\n * For a slash menu, you might use `/(?<!\\S)\\/(|\\S.*)$/u`.\n * For a mention, you might use `/@\\w*$/`\n */\n regex: RegExp\n\n /**\n * A callback that is called when the rule starts to match, and also on\n * subsequent updates while the rule continues to match.\n */\n onEnter: MatchHandler\n\n /**\n * A callback that is called when the rule stops matching.\n */\n onLeave?: VoidFunction\n\n /**\n * A predicate to determine if the rule can be applied in the current editor\n * state. If not provided, it defaults to only allowing matches in empty\n * selections that are not inside a code block or code mark.\n */\n canMatch?: CanMatchPredicate\n}\n\n/**\n * An autocomplete rule that can be used to create an autocomplete extension.\n *\n * @public\n */\nexport class AutocompleteRule {\n /** @internal */\n readonly regex: RegExp\n /** @internal */\n readonly onMatch: MatchHandler\n /** @internal */\n readonly onLeave?: VoidFunction\n /** @internal */\n readonly canMatch: (options: { state: EditorState }) => boolean\n\n constructor(options: AutocompleteRuleOptions) {\n this.regex = options.regex\n this.onMatch = options.onEnter\n this.onLeave = options.onLeave\n this.canMatch = options.canMatch ?? defaultCanMatch\n }\n}\n"],"mappings":";;;;;AASA,SAAgB,gBAAgB,EAAE,SAA0C;AAC1E,QAAO,MAAM,UAAU,SAAS,CAAC,aAAa,MAAM,UAAU,MAAM;;AAGtE,SAAS,aAAa,MAA4B;AAChD,MAAK,IAAI,IAAI,KAAK,OAAO,IAAI,GAAG,IAC9B,KAAI,KAAK,KAAK,EAAE,CAAC,KAAK,KAAK,KACzB,QAAO;AAIX,QAAO,KAAK,OAAO,CAAC,MAAM,SAAS,KAAK,KAAK,SAAS,OAAO;;AAsC/D,SAAgB,eAAe,OAAuD;AACpF,QAAO,UAAU,SAAS,MAAM;;AAGlC,SAAgB,UAAU,IAAwD;AAChF,QAAO,GAAG,QAAQ,UAAU;;AAG9B,SAAgB,UACd,IACA,MACa;AACb,QAAO,GAAG,QAAQ,WAAW,KAAK;;AAGpC,MAAaA,YAA8C,IAAI,UAAiC,wBAAwB;;;;ACpDxH,SAAgB,yBAAyB,EACvC,YAGS;AACT,QAAO,IAAI,OAA8B;EACvC,KAAK;EAEL,OAAO;GACL,YAAmC;AACjC,WAAO;KAAE,SAAS,EAAE;KAAE,UAAU;KAAM;;GAExC,QACE,IACA,WACA,UACA,aAC0B;IAC1B,MAAM,OAAO,UAAU,GAAG;AAG1B,QACE,CAAC,GAAG,cACD,SAAS,UAAU,GAAG,SAAS,UAAU,IACzC,CAAC,KAEJ,QAAO;AAIT,QAAI,MAAM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AW,OAAO,MAAM,IAAI,EACvC,OAAO,gCACR,CAAC;AACF,WAAO,cAAc,OAAO,MAAM,KAAK,CAAC,KAAK,CAAC;;AAEhD,UAAO;KAEV;EACF,CAAC;;AAGJ,MAAM,YAAY;AAElB,SAAS,wBACP,OACA,OACiC;CACjC,MAAM,OAAO,MAAM,UAAU;CAE7B,MAAMC,eAAuB,KAAK;CAElC,MAAMC,aAAqB,KAAK,OAAO,YACrC,KAAK,IAAI,GAAG,eAAe,UAAU,EACrC,cACA,MACA,6BACD;AAED,MAAK,MAAM,QAAQ,OAAO;AACxB,MAAI,CAAC,KAAK,SAAS,EAAE,OAAO,CAAC,CAC3B;AAGF,OAAK,MAAM,YAAY;EACvB,MAAM,QAAQ,KAAK,MAAM,KAAK,WAAW;AACzC,MAAI,CAAC,MACH;EAGF,MAAM,KAAK,KAAK;EAChB,MAAM,OAAO,KAAK,WAAW,SAAS,MAAM;AAE5C,SAAO;GAAE;GAAM;GAAO;GAAM;GAAI;;AAGlC,QAAO;;;;;AC7KT,SAAgB,mBAAmB,MAAmC;AACpE,QAAO,mBAAmB,mBAAmB,CAAC,KAAK,CAAC;;AAGtD,MAAM,oBAAoB,YAA6C;CACrE,cAAc;EACZ,IAAIC,QAA4B,EAAE;EAClC,MAAM,iBAAiB;EACvB,MAAM,SAAS,yBAAyB,EAAE,UAAU,CAAC;AAErD,SAAO,SAAS,QAAQ,QAAQ;AAC9B,WAAQ;AACR,UAAO;;;CAGX,QAAQ;CACR,WAAW;CACZ,CAAC;;;;;;;;;ACwEF,IAAa,mBAAb,MAA8B;CAU5B,YAAY,SAAkC;AAC5C,OAAK,QAAQ,QAAQ;AACrB,OAAK,UAAU,QAAQ;AACvB,OAAK,UAAU,QAAQ;AACvB,OAAK,WAAW,QAAQ,YAAY"}
|
|
1
|
+
{"version":3,"file":"prosekit-extensions-autocomplete.js","names":["pluginKey: PluginKey<PredictionPluginState>","parentOffset: number","textBefore: string","rules: AutocompleteRule[]"],"sources":["../src/autocomplete/autocomplete-helpers.ts","../src/autocomplete/autocomplete-plugin.ts","../src/autocomplete/autocomplete.ts","../src/autocomplete/autocomplete-rule.ts"],"sourcesContent":["import type { ResolvedPos } from '@prosekit/pm/model'\nimport {\n PluginKey,\n type EditorState,\n type Transaction,\n} from '@prosekit/pm/state'\n\nimport type { AutocompleteRule } from './autocomplete-rule'\n\nexport function defaultCanMatch({ state }: { state: EditorState }): boolean {\n return state.selection.empty && !isInsideCode(state.selection.$from)\n}\n\nfunction isInsideCode($pos: ResolvedPos): boolean {\n for (let d = $pos.depth; d > 0; d--) {\n if ($pos.node(d).type.spec.code) {\n return true\n }\n }\n\n return $pos.marks().some((mark) => mark.type.name === 'code')\n}\n\n/**\n * @internal\n */\nexport interface PredictionPluginMatching {\n rule: AutocompleteRule\n from: number\n to: number\n match: RegExpExecArray\n}\n\n/**\n * @internal\n */\nexport interface PredictionPluginState {\n /**\n * The matching positions that should be ignored.\n */\n ignores: number[]\n\n /**\n * The current active matching.\n */\n matching: PredictionPluginMatching | null\n}\n\n/**\n * @internal\n */\ninterface PredictionTransactionMeta {\n /**\n * The from position that should be ignored.\n */\n ignore: number\n}\n\nexport function getPluginState(state: EditorState): PredictionPluginState | undefined {\n return pluginKey.getState(state)\n}\n\nexport function getTrMeta(tr: Transaction): PredictionTransactionMeta | undefined {\n return tr.getMeta(pluginKey) as PredictionTransactionMeta | undefined\n}\n\nexport function setTrMeta(\n tr: Transaction,\n meta: PredictionTransactionMeta,\n): Transaction {\n return tr.setMeta(pluginKey, meta)\n}\n\nexport const pluginKey: PluginKey<PredictionPluginState> = new PluginKey<PredictionPluginState>('prosekit-autocomplete')\n","import { OBJECT_REPLACEMENT_CHARACTER } from '@prosekit/core'\nimport {\n Plugin,\n type EditorState,\n type Transaction,\n} from '@prosekit/pm/state'\nimport {\n Decoration,\n DecorationSet,\n} from '@prosekit/pm/view'\n\nimport {\n getPluginState,\n getTrMeta,\n pluginKey,\n setTrMeta,\n type PredictionPluginMatching,\n type PredictionPluginState,\n} from './autocomplete-helpers'\nimport type { AutocompleteRule } from './autocomplete-rule'\n\nexport function createAutocompletePlugin({\n getRules,\n}: {\n getRules: () => AutocompleteRule[]\n}): Plugin {\n return new Plugin<PredictionPluginState>({\n key: pluginKey,\n\n state: {\n init: (): PredictionPluginState => {\n return { ignores: [], matching: null }\n },\n apply: (\n tr: Transaction,\n prevValue: PredictionPluginState,\n oldState: EditorState,\n newState: EditorState,\n ): PredictionPluginState => {\n const meta = getTrMeta(tr)\n\n // No changes\n if (\n !tr.docChanged\n && oldState.selection.eq(newState.selection)\n && !meta\n ) {\n return prevValue\n }\n\n // Receiving a meta means that we are ignoring a match\n if (meta) {\n let ignores = prevValue.ignores\n if (!ignores.includes(meta.ignore)) {\n ignores = [...ignores, meta.ignore]\n }\n return { matching: null, ignores }\n }\n\n // Calculate the new ignores\n const ignoreSet = new Set(prevValue.ignores.map(pos => tr.mapping.map(pos)))\n\n // Calculate the new matching\n let matching = calcPluginStateMatching(newState, getRules())\n\n // Check if the matching should be ignored\n if (matching && ignoreSet.has(matching.from)) {\n matching = null\n }\n\n // Return the new matching and ignores\n return { matching, ignores: Array.from(ignoreSet) }\n },\n },\n\n view: () => ({\n update: (view, prevState) => {\n const prevValue = getPluginState(prevState)\n const currValue = getPluginState(view.state)\n\n if (\n prevValue?.matching\n && prevValue.matching.rule !== currValue?.matching?.rule\n ) {\n // Deactivate the previous rule\n prevValue.matching.rule.onLeave?.()\n }\n\n if (\n currValue?.matching\n && !currValue.ignores.includes(currValue.matching.from)\n ) {\n // Activate the current rule\n\n const { from, to, match, rule } = currValue.matching\n\n const textContent = view.state.doc.textBetween(\n from,\n to,\n null,\n OBJECT_REPLACEMENT_CHARACTER,\n )\n\n const deleteMatch = () => {\n if (\n view.state.doc.textBetween(\n from,\n to,\n null,\n OBJECT_REPLACEMENT_CHARACTER,\n ) === textContent\n ) {\n view.dispatch(view.state.tr.delete(from, to))\n }\n }\n\n const ignoreMatch = () => {\n view.dispatch(\n setTrMeta(view.state.tr, { ignore: from }),\n )\n }\n\n rule.onMatch({\n state: view.state,\n match,\n from,\n to,\n deleteMatch,\n ignoreMatch,\n })\n }\n },\n }),\n\n props: {\n decorations: (state: EditorState) => {\n const pluginState = getPluginState(state)\n if (pluginState?.matching) {\n const { from, to } = pluginState.matching\n const deco = Decoration.inline(from, to, {\n class: 'prosemirror-prediction-match',\n })\n return DecorationSet.create(state.doc, [deco])\n }\n return null\n },\n },\n })\n}\n\nconst MAX_MATCH = 200\n\nfunction calcPluginStateMatching(\n state: EditorState,\n rules: AutocompleteRule[],\n): PredictionPluginMatching | null {\n const $pos = state.selection.$from\n\n const parentOffset: number = $pos.parentOffset\n\n const textBefore: string = $pos.parent.textBetween(\n Math.max(0, parentOffset - MAX_MATCH),\n parentOffset,\n null,\n OBJECT_REPLACEMENT_CHARACTER,\n )\n\n for (const rule of rules) {\n if (!rule.canMatch({ state })) {\n continue\n }\n\n rule.regex.lastIndex = 0\n const match = rule.regex.exec(textBefore)\n if (!match) {\n continue\n }\n\n const to = $pos.pos\n const from = to - textBefore.length + match.index\n\n return { rule, match, from, to }\n }\n\n return null\n}\n","import {\n defineFacet,\n defineFacetPayload,\n pluginFacet,\n type Extension,\n type PluginPayload,\n} from '@prosekit/core'\n\nimport { createAutocompletePlugin } from './autocomplete-plugin'\nimport type { AutocompleteRule } from './autocomplete-rule'\n\nexport function defineAutocomplete(rule: AutocompleteRule): Extension {\n return defineFacetPayload(autocompleteFacet, [rule])\n}\n\nconst autocompleteFacet = defineFacet<AutocompleteRule, PluginPayload>({\n reduce: () => {\n let rules: AutocompleteRule[] = []\n const getRules = () => rules\n const plugin = createAutocompletePlugin({ getRules })\n\n return function reducer(inputs) {\n rules = inputs\n return plugin\n }\n },\n parent: pluginFacet,\n singleton: true,\n})\n","import type { EditorState } from '@prosekit/pm/state'\n\nimport { defaultCanMatch } from './autocomplete-helpers'\n\n/**\n * Options for the {@link MatchHandler} callback.\n */\nexport interface MatchHandlerOptions {\n /**\n * The editor state.\n */\n state: EditorState\n\n /**\n * The result of `RegExp.exec`.\n */\n match: RegExpExecArray\n\n /**\n * The start position of the matched text.\n */\n from: number\n\n /**\n * The end position of the matched text.\n */\n to: number\n\n /**\n * Call this function to ignore the match. You probably want to call this\n * function when the user presses the `Escape` key.\n */\n ignoreMatch: () => void\n\n /**\n * Call this function to delete the matched text. For example, in a slash\n * menu, you might want to delete the matched text first then do something\n * else when the user presses the `Enter` key.\n */\n deleteMatch: () => void\n}\n\n/**\n * A callback that is called when the rule starts to match, and also on\n * subsequent updates while the rule continues to match.\n */\nexport type MatchHandler = (options: MatchHandlerOptions) => void\n\n/**\n * Options for the {@link CanMatchPredicate} callback.\n */\nexport interface CanMatchOptions {\n /**\n * The editor state.\n */\n state: EditorState\n}\n\n/**\n * A predicate to determine if the rule can be applied in the current editor state.\n */\nexport type CanMatchPredicate = (options: CanMatchOptions) => boolean\n\n/**\n * Options for creating an {@link AutocompleteRule}\n */\nexport interface AutocompleteRuleOptions {\n /**\n * The regular expression to match against the text before the cursor. The\n * last match before the cursor is used.\n *\n * For a slash menu, you might use `/(?<!\\S)\\/(|\\S.*)$/u`.\n * For a mention, you might use `/@\\w*$/`\n */\n regex: RegExp\n\n /**\n * A callback that is called when the rule starts to match, and also on\n * subsequent updates while the rule continues to match.\n */\n onEnter: MatchHandler\n\n /**\n * A callback that is called when the rule stops matching.\n */\n onLeave?: VoidFunction\n\n /**\n * A predicate to determine if the rule can be applied in the current editor\n * state. If not provided, it defaults to only allowing matches in empty\n * selections that are not inside a code block or code mark.\n */\n canMatch?: CanMatchPredicate\n}\n\n/**\n * An autocomplete rule that can be used to create an autocomplete extension.\n *\n * @public\n */\nexport class AutocompleteRule {\n /** @internal */\n readonly regex: RegExp\n /** @internal */\n readonly onMatch: MatchHandler\n /** @internal */\n readonly onLeave?: VoidFunction\n /** @internal */\n readonly canMatch: (options: { state: EditorState }) => boolean\n\n constructor(options: AutocompleteRuleOptions) {\n this.regex = options.regex\n this.onMatch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ACrC,cACA,MACA,6BACD;AAED,MAAK,MAAM,QAAQ,OAAO;AACxB,MAAI,CAAC,KAAK,SAAS,EAAE,OAAO,CAAC,CAC3B;AAGF,OAAK,MAAM,YAAY;EACvB,MAAM,QAAQ,KAAK,MAAM,KAAK,WAAW;AACzC,MAAI,CAAC,MACH;EAGF,MAAM,KAAK,KAAK;AAGhB,SAAO;GAAE;GAAM;GAAO,MAFT,KAAK,WAAW,SAAS,MAAM;GAEhB;GAAI;;AAGlC,QAAO;;;;;AC7KT,SAAgB,mBAAmB,MAAmC;AACpE,QAAO,mBAAmB,mBAAmB,CAAC,KAAK,CAAC;;AAGtD,MAAM,oBAAoB,YAA6C;CACrE,cAAc;EACZ,IAAIC,QAA4B,EAAE;EAClC,MAAM,iBAAiB;EACvB,MAAM,SAAS,yBAAyB,EAAE,UAAU,CAAC;AAErD,SAAO,SAAS,QAAQ,QAAQ;AAC9B,WAAQ;AACR,UAAO;;;CAGX,QAAQ;CACR,WAAW;CACZ,CAAC;;;;;;;;;ACwEF,IAAa,mBAAb,MAA8B;CAU5B,YAAY,SAAkC;AAC5C,OAAK,QAAQ,QAAQ;AACrB,OAAK,UAAU,QAAQ;AACvB,OAAK,UAAU,QAAQ;AACvB,OAAK,WAAW,QAAQ,YAAY"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { defineWrappingInputRule } from "./input-rule-
|
|
1
|
+
import { defineWrappingInputRule } from "./input-rule-DO_iy2aT.js";
|
|
2
2
|
import { defineCommands, defineKeymap, defineNodeSpec, insertNode, isAtBlockStart, toggleWrap, union, wrap } from "@prosekit/core";
|
|
3
3
|
import { joinBackward } from "@prosekit/pm/commands";
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { defineMarkInputRule } from "./input-rule-
|
|
1
|
+
import { defineMarkInputRule } from "./input-rule-DO_iy2aT.js";
|
|
2
2
|
import { canUseRegexLookbehind, defineCommands, defineKeymap, defineMarkSpec, toggleMark, union } from "@prosekit/core";
|
|
3
3
|
|
|
4
4
|
//#region src/bold/bold-commands.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { defineTextBlockInputRule } from "./input-rule-
|
|
2
|
-
import { defineTextBlockEnterRule } from "./enter-rule-
|
|
1
|
+
import { defineTextBlockInputRule } from "./input-rule-DO_iy2aT.js";
|
|
2
|
+
import { defineTextBlockEnterRule } from "./enter-rule-5tkoU2Ir.js";
|
|
3
3
|
import { defaultBlockAt, defineCommands, defineKeymap, defineNodeSpec, definePlugin, insertNode, setBlockType, setNodeAttrs, toggleNode, union } from "@prosekit/core";
|
|
4
4
|
import { TextSelection } from "@prosekit/pm/state";
|
|
5
5
|
import { createHighlightPlugin } from "prosemirror-highlight";
|
|
@@ -236,12 +236,11 @@ function createLazyParser(highlighterOptions) {
|
|
|
236
236
|
* @public
|
|
237
237
|
*/
|
|
238
238
|
function defineCodeBlockShiki({ themes = ["one-dark-pro"], langs = ["text"],...rest } = {}) {
|
|
239
|
-
|
|
239
|
+
return defineCodeBlockHighlight({ parser: createLazyParser({
|
|
240
240
|
themes,
|
|
241
241
|
langs,
|
|
242
242
|
...rest
|
|
243
|
-
});
|
|
244
|
-
return defineCodeBlockHighlight({ parser });
|
|
243
|
+
}) });
|
|
245
244
|
}
|
|
246
245
|
|
|
247
246
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prosekit-extensions-code-block.js","names":["existCodeBlock: Command","loaded: ((options: HighlighterOptions) => HighlighterResult) | undefined","createOrGetHighlighter","parser: Parser | undefined"],"sources":["../src/code-block/code-block-commands.ts","../src/code-block/code-block-input-rule.ts","../src/code-block/code-block-keymap.ts","../src/code-block/code-block-spec.ts","../src/code-block/code-block.ts","../src/code-block/code-block-highlight.ts","../src/code-block/shiki-highlighter.ts","../src/code-block/shiki-parser.ts","../src/code-block/code-block-shiki.ts"],"sourcesContent":["import {\n defineCommands,\n insertNode,\n setBlockType,\n setNodeAttrs,\n toggleNode,\n type Extension,\n} from '@prosekit/core'\n\nimport type { CodeBlockAttrs } from './code-block-types'\n\n/**\n * @internal\n */\nexport type CodeBlockCommandsExtension = Extension<{\n Commands: {\n setCodeBlock: [attrs?: CodeBlockAttrs]\n insertCodeBlock: [attrs?: CodeBlockAttrs]\n toggleCodeBlock: [attrs?: CodeBlockAttrs]\n setCodeBlockAttrs: [attrs: CodeBlockAttrs]\n }\n}>\n\n/**\n * Adds commands for working with `codeBlock` nodes.\n *\n * @public\n */\nexport function defineCodeBlockCommands(): CodeBlockCommandsExtension {\n return defineCommands({\n setCodeBlock: (attrs?: CodeBlockAttrs) => {\n return setBlockType({ type: 'codeBlock', attrs })\n },\n insertCodeBlock: (attrs?: CodeBlockAttrs) => {\n return insertNode({ type: 'codeBlock', attrs })\n },\n toggleCodeBlock: (attrs?: CodeBlockAttrs) => {\n return toggleNode({ type: 'codeBlock', attrs })\n },\n setCodeBlockAttrs: (attrs: CodeBlockAttrs) => {\n return setNodeAttrs({ type: 'codeBlock', attrs })\n },\n })\n}\n","import type { PlainExtension } from '@prosekit/core'\n\nimport { defineTextBlockEnterRule } from '../enter-rule'\nimport { defineTextBlockInputRule } from '../input-rule'\n\nimport type { CodeBlockAttrs } from './code-block-types'\n\n/**\n * Adds input rules for `codeBlock` nodes.\n *\n * @public\n */\nexport function defineCodeBlockInputRule(): PlainExtension {\n return defineTextBlockInputRule({\n regex: /^```(\\S*)\\s$/,\n type: 'codeBlock',\n attrs: getAttrs,\n })\n}\n\n/**\n * Adds enter rules for `codeBlock` nodes.\n *\n * @public\n */\nexport function defineCodeBlockEnterRule(): PlainExtension {\n return defineTextBlockEnterRule({\n regex: /^```(\\S*)$/,\n type: 'codeBlock',\n attrs: getAttrs,\n })\n}\n\nfunction getAttrs(match: RegExpMatchArray): CodeBlockAttrs {\n return { language: match[1] || '' }\n}\n","import {\n defaultBlockAt,\n defineKeymap,\n type PlainExtension,\n} from '@prosekit/core'\nimport {\n TextSelection,\n type Command,\n} from '@prosekit/pm/state'\n\n/**\n * Defines the keymap for code blocks.\n */\nexport function defineCodeBlockKeymap(): PlainExtension {\n return defineKeymap({\n Enter: existCodeBlock,\n })\n}\n\n/**\n * Exit a code block and insert a default block below if the cursor is at the\n * end of the code block and the code block is ended with two new lines.\n */\nconst existCodeBlock: Command = (state, dispatch) => {\n if (!state.selection.empty) {\n return false\n }\n\n const { $head } = state.selection\n const parent = $head.parent\n if (\n parent.isTextblock\n && parent.type.spec.code\n && $head.parentOffset === parent.content.size\n && parent.textContent.endsWith('\\n\\n')\n ) {\n const grandParent = $head.node(-1)\n const insertIndex = $head.indexAfter(-1)\n const type = defaultBlockAt(grandParent.contentMatchAt(insertIndex))\n\n if (!type || !grandParent.canReplaceWith(insertIndex, insertIndex, type)) {\n return false\n }\n\n if (dispatch) {\n const { tr } = state\n tr.delete($head.pos - 2, $head.pos)\n const pos = tr.selection.$head.after()\n const node = type.createAndFill()\n if (node) {\n tr.replaceWith(pos, pos, node)\n tr.setSelection(TextSelection.near(tr.doc.resolve(pos), 1))\n dispatch(tr.scrollIntoView())\n }\n }\n\n return true\n }\n\n return false\n}\n","import {\n defineNodeSpec,\n type Extension,\n} from '@prosekit/core'\n\nimport type { CodeBlockAttrs } from './code-block-types'\n\n/**\n * @internal\n */\nexport type CodeBlockSpecExtension = Extension<{\n Nodes: {\n codeBlock: CodeBlockAttrs\n }\n}>\n\n/**\n * Defines the `codeBlock` node spec.\n *\n * @public\n */\nexport function defineCodeBlockSpec(): CodeBlockSpecExtension {\n return defineNodeSpec({\n name: 'codeBlock',\n content: 'text*',\n group: 'block',\n code: true,\n defining: true,\n marks: '',\n attrs: { language: { default: '', validate: 'string' } },\n parseDOM: [\n {\n tag: 'pre',\n preserveWhitespace: 'full',\n getAttrs: (node): CodeBlockAttrs => {\n const language = extractLanguageFromElement(node)\n || extractLanguageFromElement(node.querySelector('code'))\n return { language }\n },\n },\n ],\n toDOM(node) {\n const { language } = node.attrs as CodeBlockAttrs\n return [\n 'pre',\n { 'data-language': language || undefined },\n // `class: language-${language}` is used by remark-rehype to highlight the code block\n ['code', { class: language ? `language-${language}` : undefined }, 0],\n ]\n },\n })\n}\n\nfunction extractLanguageFromElement(element: HTMLElement | null | undefined): string {\n if (!element) {\n return ''\n }\n\n const attr = element.getAttribute('data-language')\n if (attr) {\n return attr\n }\n\n const className = element.className\n const match = className.match(/language-(\\w+)/)\n if (match) {\n return match[1]\n }\n\n return ''\n}\n","import {\n union,\n type Union,\n} from '@prosekit/core'\n\nimport {\n defineCodeBlockCommands,\n type CodeBlockCommandsExtension,\n} from './code-block-commands'\nimport {\n defineCodeBlockEnterRule,\n defineCodeBlockInputRule,\n} from './code-block-input-rule'\nimport { defineCodeBlockKeymap } from './code-block-keymap'\nimport {\n defineCodeBlockSpec,\n type CodeBlockSpecExtension,\n} from './code-block-spec'\n\n/**\n * @internal\n */\nexport type CodeBlockExtension = Union<\n [CodeBlockSpecExtension, CodeBlockCommandsExtension]\n>\n\n/**\n * Adds `codeBlock` nodes to the editor. This includes the following extensions:\n *\n * - {@link defineCodeBlockSpec}\n * - {@link defineCodeBlockInputRule}\n * - {@link defineCodeBlockEnterRule}\n * - {@link defineCodeBlockKeymap}\n * - {@link defineCodeBlockCommands}.\n *\n * @public\n */\nexport function defineCodeBlock(): CodeBlockExtension {\n return union(\n defineCodeBlockSpec(),\n defineCodeBlockInputRule(),\n defineCodeBlockEnterRule(),\n defineCodeBlockKeymap(),\n defineCodeBlockCommands(),\n )\n}\n","import {\n definePlugin,\n type Extension,\n} from '@prosekit/core'\nimport {\n createHighlightPlugin,\n type Parser,\n} from 'prosemirror-highlight'\n\n/**\n * @public\n *\n * An alias for the `Parser` type from the `prosemirror-highlight` package.\n */\nexport type HighlightParser = Parser\n\n/**\n * @public\n */\nexport type CodeBlockHighlightOptions = {\n parser: HighlightParser\n}\n\n/**\n * Adds syntax highlighting to code blocks. This function requires a `Parser`\n * instance from the `prosemirror-highlight` package. See the\n * [documentation](https://github.com/ocavue/prosemirror-highlight) for more\n * information.\n *\n * @param options\n *\n * @public\n */\nexport function defineCodeBlockHighlight({\n parser,\n}: CodeBlockHighlightOptions): Extension {\n return definePlugin(\n createHighlightPlugin({ parser }),\n )\n}\n","import type {\n HighlighterOptions,\n HighlighterResult,\n} from './shiki-highlighter-chunk'\n\nlet loaded: ((options: HighlighterOptions) => HighlighterResult) | undefined\n\nasync function load() {\n const { createOrGetHighlighter } = await import('./shiki-highlighter-chunk')\n loaded = createOrGetHighlighter\n}\n\nexport function createOrGetHighlighter(\n options: HighlighterOptions,\n): HighlighterResult {\n if (!loaded) {\n return { promise: load() }\n }\n return loaded(options)\n}\n\nexport type { HighlighterOptions }\n","import type { Parser } from 'prosemirror-highlight'\nimport { createParser } from 'prosemirror-highlight/shiki'\n\nimport type { ShikiBundledLanguage } from './shiki-bundle'\nimport {\n createOrGetHighlighter,\n type HighlighterOptions,\n} from './shiki-highlighter'\n\n/**\n * @internal\n */\nexport function createLazyParser(\n highlighterOptions: HighlighterOptions,\n): Parser {\n let parser: Parser | undefined\n\n return function lazyParser(options) {\n const language = (options.language || '') as ShikiBundledLanguage\n const { highlighter, promise } = createOrGetHighlighter({\n ...highlighterOptions,\n langs: [language],\n })\n\n if (!highlighter) {\n return promise\n }\n\n if (!parser) {\n parser = createParser(highlighter, {\n theme: highlighterOptions.themes[0],\n })\n }\n return parser(options)\n }\n}\n","import type { Extension } from '@prosekit/core'\nimport type { SpecialLanguage } from 'shiki'\n\nimport { defineCodeBlockHighlight } from './code-block-highlight'\nimport type {\n ShikiBundledLanguage,\n ShikiBundledTheme,\n} from './shiki-bundle'\nimport type { ShikiHighlighterOptions } from './shiki-highlighter-chunk'\nimport { createLazyParser } from './shiki-parser'\n\n/**\n * The options to configure the Shiki highlighter.\n *\n * @public\n */\nexport interface CodeBlockShikiOptions extends Omit<ShikiHighlighterOptions, 'themes' | 'langs' | 'engine'> {\n /**\n * A list of Shiki themes to pre-load. The first theme in the list will be\n * used to render the code block.\n *\n * @default ['one-dark-pro']\n */\n themes?: ShikiBundledTheme[]\n\n /**\n * A list of Shiki languages to pre-load.\n *\n * @default ['text']\n */\n langs?: (ShikiBundledLanguage | SpecialLanguage)[]\n\n /**\n * The RegExp engine to use. By default, the JavaScript engine is used.\n */\n engine?: ShikiHighlighterOptions['engine']\n}\n\n/**\n * Adds syntax highlighting to code blocks using the [Shiki](https://github.com/shikijs/shiki) package.\n *\n * It will set two CSS variables on the code block elements:\n *\n * - `--prosemirror-highlight`: sets text color\n * - `--prosemirror-highlight-bg`: sets background color\n *\n * @param options - The options to configure the Shiki highlighter.\n *\n * @public\n */\nexport function defineCodeBlockShiki({\n themes = ['one-dark-pro'],\n langs = ['text'],\n ...rest\n}: CodeBlockShikiOptions = {}): Extension {\n const parser = createLazyParser({ themes, langs, ...rest })\n return defineCodeBlockHighlight({ parser })\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,SAAgB,0BAAsD;AACpE,QAAO,eAAe;EACpB,eAAe,UAA2B;AACxC,UAAO,aAAa;IAAE,MAAM;IAAa;IAAO,CAAC;;EAEnD,kBAAkB,UAA2B;AAC3C,UAAO,WAAW;IAAE,MAAM;IAAa;IAAO,CAAC;;EAEjD,kBAAkB,UAA2B;AAC3C,UAAO,WAAW;IAAE,MAAM;IAAa;IAAO,CAAC;;EAEjD,oBAAoB,UAA0B;AAC5C,UAAO,aAAa;IAAE,MAAM;IAAa;IAAO,CAAC;;EAEpD,CAAC;;;;;;;;;;AC9BJ,SAAgB,2BAA2C;AACzD,QAAO,yBAAyB;EAC9B,OAAO;EACP,MAAM;EACN,OAAO;EACR,CAAC;;;;;;;AAQJ,SAAgB,2BAA2C;AACzD,QAAO,yBAAyB;EAC9B,OAAO;EACP,MAAM;EACN,OAAO;EACR,CAAC;;AAGJ,SAAS,SAAS,OAAyC;AACzD,QAAO,EAAE,UAAU,MAAM,MAAM,IAAI;;;;;;;;ACrBrC,SAAgB,wBAAwC;AACtD,QAAO,aAAa,EAClB,OAAO,gBACR,CAAC;;;;;;AAO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D,QAAO,yBAAyB,EAAE,QAAQ,CAAC"}
|
|
1
|
+
{"version":3,"file":"prosekit-extensions-code-block.js","names":["existCodeBlock: Command","loaded: ((options: HighlighterOptions) => HighlighterResult) | undefined","createOrGetHighlighter","parser: Parser | undefined"],"sources":["../src/code-block/code-block-commands.ts","../src/code-block/code-block-input-rule.ts","../src/code-block/code-block-keymap.ts","../src/code-block/code-block-spec.ts","../src/code-block/code-block.ts","../src/code-block/code-block-highlight.ts","../src/code-block/shiki-highlighter.ts","../src/code-block/shiki-parser.ts","../src/code-block/code-block-shiki.ts"],"sourcesContent":["import {\n defineCommands,\n insertNode,\n setBlockType,\n setNodeAttrs,\n toggleNode,\n type Extension,\n} from '@prosekit/core'\n\nimport type { CodeBlockAttrs } from './code-block-types'\n\n/**\n * @internal\n */\nexport type CodeBlockCommandsExtension = Extension<{\n Commands: {\n setCodeBlock: [attrs?: CodeBlockAttrs]\n insertCodeBlock: [attrs?: CodeBlockAttrs]\n toggleCodeBlock: [attrs?: CodeBlockAttrs]\n setCodeBlockAttrs: [attrs: CodeBlockAttrs]\n }\n}>\n\n/**\n * Adds commands for working with `codeBlock` nodes.\n *\n * @public\n */\nexport function defineCodeBlockCommands(): CodeBlockCommandsExtension {\n return defineCommands({\n setCodeBlock: (attrs?: CodeBlockAttrs) => {\n return setBlockType({ type: 'codeBlock', attrs })\n },\n insertCodeBlock: (attrs?: CodeBlockAttrs) => {\n return insertNode({ type: 'codeBlock', attrs })\n },\n toggleCodeBlock: (attrs?: CodeBlockAttrs) => {\n return toggleNode({ type: 'codeBlock', attrs })\n },\n setCodeBlockAttrs: (attrs: CodeBlockAttrs) => {\n return setNodeAttrs({ type: 'codeBlock', attrs })\n },\n })\n}\n","import type { PlainExtension } from '@prosekit/core'\n\nimport { defineTextBlockEnterRule } from '../enter-rule'\nimport { defineTextBlockInputRule } from '../input-rule'\n\nimport type { CodeBlockAttrs } from './code-block-types'\n\n/**\n * Adds input rules for `codeBlock` nodes.\n *\n * @public\n */\nexport function defineCodeBlockInputRule(): PlainExtension {\n return defineTextBlockInputRule({\n regex: /^```(\\S*)\\s$/,\n type: 'codeBlock',\n attrs: getAttrs,\n })\n}\n\n/**\n * Adds enter rules for `codeBlock` nodes.\n *\n * @public\n */\nexport function defineCodeBlockEnterRule(): PlainExtension {\n return defineTextBlockEnterRule({\n regex: /^```(\\S*)$/,\n type: 'codeBlock',\n attrs: getAttrs,\n })\n}\n\nfunction getAttrs(match: RegExpMatchArray): CodeBlockAttrs {\n return { language: match[1] || '' }\n}\n","import {\n defaultBlockAt,\n defineKeymap,\n type PlainExtension,\n} from '@prosekit/core'\nimport {\n TextSelection,\n type Command,\n} from '@prosekit/pm/state'\n\n/**\n * Defines the keymap for code blocks.\n */\nexport function defineCodeBlockKeymap(): PlainExtension {\n return defineKeymap({\n Enter: existCodeBlock,\n })\n}\n\n/**\n * Exit a code block and insert a default block below if the cursor is at the\n * end of the code block and the code block is ended with two new lines.\n */\nconst existCodeBlock: Command = (state, dispatch) => {\n if (!state.selection.empty) {\n return false\n }\n\n const { $head } = state.selection\n const parent = $head.parent\n if (\n parent.isTextblock\n && parent.type.spec.code\n && $head.parentOffset === parent.content.size\n && parent.textContent.endsWith('\\n\\n')\n ) {\n const grandParent = $head.node(-1)\n const insertIndex = $head.indexAfter(-1)\n const type = defaultBlockAt(grandParent.contentMatchAt(insertIndex))\n\n if (!type || !grandParent.canReplaceWith(insertIndex, insertIndex, type)) {\n return false\n }\n\n if (dispatch) {\n const { tr } = state\n tr.delete($head.pos - 2, $head.pos)\n const pos = tr.selection.$head.after()\n const node = type.createAndFill()\n if (node) {\n tr.replaceWith(pos, pos, node)\n tr.setSelection(TextSelection.near(tr.doc.resolve(pos), 1))\n dispatch(tr.scrollIntoView())\n }\n }\n\n return true\n }\n\n return false\n}\n","import {\n defineNodeSpec,\n type Extension,\n} from '@prosekit/core'\n\nimport type { CodeBlockAttrs } from './code-block-types'\n\n/**\n * @internal\n */\nexport type CodeBlockSpecExtension = Extension<{\n Nodes: {\n codeBlock: CodeBlockAttrs\n }\n}>\n\n/**\n * Defines the `codeBlock` node spec.\n *\n * @public\n */\nexport function defineCodeBlockSpec(): CodeBlockSpecExtension {\n return defineNodeSpec({\n name: 'codeBlock',\n content: 'text*',\n group: 'block',\n code: true,\n defining: true,\n marks: '',\n attrs: { language: { default: '', validate: 'string' } },\n parseDOM: [\n {\n tag: 'pre',\n preserveWhitespace: 'full',\n getAttrs: (node): CodeBlockAttrs => {\n const language = extractLanguageFromElement(node)\n || extractLanguageFromElement(node.querySelector('code'))\n return { language }\n },\n },\n ],\n toDOM(node) {\n const { language } = node.attrs as CodeBlockAttrs\n return [\n 'pre',\n { 'data-language': language || undefined },\n // `class: language-${language}` is used by remark-rehype to highlight the code block\n ['code', { class: language ? `language-${language}` : undefined }, 0],\n ]\n },\n })\n}\n\nfunction extractLanguageFromElement(element: HTMLElement | null | undefined): string {\n if (!element) {\n return ''\n }\n\n const attr = element.getAttribute('data-language')\n if (attr) {\n return attr\n }\n\n const className = element.className\n const match = className.match(/language-(\\w+)/)\n if (match) {\n return match[1]\n }\n\n return ''\n}\n","import {\n union,\n type Union,\n} from '@prosekit/core'\n\nimport {\n defineCodeBlockCommands,\n type CodeBlockCommandsExtension,\n} from './code-block-commands'\nimport {\n defineCodeBlockEnterRule,\n defineCodeBlockInputRule,\n} from './code-block-input-rule'\nimport { defineCodeBlockKeymap } from './code-block-keymap'\nimport {\n defineCodeBlockSpec,\n type CodeBlockSpecExtension,\n} from './code-block-spec'\n\n/**\n * @internal\n */\nexport type CodeBlockExtension = Union<\n [CodeBlockSpecExtension, CodeBlockCommandsExtension]\n>\n\n/**\n * Adds `codeBlock` nodes to the editor. This includes the following extensions:\n *\n * - {@link defineCodeBlockSpec}\n * - {@link defineCodeBlockInputRule}\n * - {@link defineCodeBlockEnterRule}\n * - {@link defineCodeBlockKeymap}\n * - {@link defineCodeBlockCommands}.\n *\n * @public\n */\nexport function defineCodeBlock(): CodeBlockExtension {\n return union(\n defineCodeBlockSpec(),\n defineCodeBlockInputRule(),\n defineCodeBlockEnterRule(),\n defineCodeBlockKeymap(),\n defineCodeBlockCommands(),\n )\n}\n","import {\n definePlugin,\n type Extension,\n} from '@prosekit/core'\nimport {\n createHighlightPlugin,\n type Parser,\n} from 'prosemirror-highlight'\n\n/**\n * @public\n *\n * An alias for the `Parser` type from the `prosemirror-highlight` package.\n */\nexport type HighlightParser = Parser\n\n/**\n * @public\n */\nexport type CodeBlockHighlightOptions = {\n parser: HighlightParser\n}\n\n/**\n * Adds syntax highlighting to code blocks. This function requires a `Parser`\n * instance from the `prosemirror-highlight` package. See the\n * [documentation](https://github.com/ocavue/prosemirror-highlight) for more\n * information.\n *\n * @param options\n *\n * @public\n */\nexport function defineCodeBlockHighlight({\n parser,\n}: CodeBlockHighlightOptions): Extension {\n return definePlugin(\n createHighlightPlugin({ parser }),\n )\n}\n","import type {\n HighlighterOptions,\n HighlighterResult,\n} from './shiki-highlighter-chunk'\n\nlet loaded: ((options: HighlighterOptions) => HighlighterResult) | undefined\n\nasync function load() {\n const { createOrGetHighlighter } = await import('./shiki-highlighter-chunk')\n loaded = createOrGetHighlighter\n}\n\nexport function createOrGetHighlighter(\n options: HighlighterOptions,\n): HighlighterResult {\n if (!loaded) {\n return { promise: load() }\n }\n return loaded(options)\n}\n\nexport type { HighlighterOptions }\n","import type { Parser } from 'prosemirror-highlight'\nimport { createParser } from 'prosemirror-highlight/shiki'\n\nimport type { ShikiBundledLanguage } from './shiki-bundle'\nimport {\n createOrGetHighlighter,\n type HighlighterOptions,\n} from './shiki-highlighter'\n\n/**\n * @internal\n */\nexport function createLazyParser(\n highlighterOptions: HighlighterOptions,\n): Parser {\n let parser: Parser | undefined\n\n return function lazyParser(options) {\n const language = (options.language || '') as ShikiBundledLanguage\n const { highlighter, promise } = createOrGetHighlighter({\n ...highlighterOptions,\n langs: [language],\n })\n\n if (!highlighter) {\n return promise\n }\n\n if (!parser) {\n parser = createParser(highlighter, {\n theme: highlighterOptions.themes[0],\n })\n }\n return parser(options)\n }\n}\n","import type { Extension } from '@prosekit/core'\nimport type { SpecialLanguage } from 'shiki'\n\nimport { defineCodeBlockHighlight } from './code-block-highlight'\nimport type {\n ShikiBundledLanguage,\n ShikiBundledTheme,\n} from './shiki-bundle'\nimport type { ShikiHighlighterOptions } from './shiki-highlighter-chunk'\nimport { createLazyParser } from './shiki-parser'\n\n/**\n * The options to configure the Shiki highlighter.\n *\n * @public\n */\nexport interface CodeBlockShikiOptions extends Omit<ShikiHighlighterOptions, 'themes' | 'langs' | 'engine'> {\n /**\n * A list of Shiki themes to pre-load. The first theme in the list will be\n * used to render the code block.\n *\n * @default ['one-dark-pro']\n */\n themes?: ShikiBundledTheme[]\n\n /**\n * A list of Shiki languages to pre-load.\n *\n * @default ['text']\n */\n langs?: (ShikiBundledLanguage | SpecialLanguage)[]\n\n /**\n * The RegExp engine to use. By default, the JavaScript engine is used.\n */\n engine?: ShikiHighlighterOptions['engine']\n}\n\n/**\n * Adds syntax highlighting to code blocks using the [Shiki](https://github.com/shikijs/shiki) package.\n *\n * It will set two CSS variables on the code block elements:\n *\n * - `--prosemirror-highlight`: sets text color\n * - `--prosemirror-highlight-bg`: sets background color\n *\n * @param options - The options to configure the Shiki highlighter.\n *\n * @public\n */\nexport function defineCodeBlockShiki({\n themes = ['one-dark-pro'],\n langs = ['text'],\n ...rest\n}: CodeBlockShikiOptions = {}): Extension {\n const parser = createLazyParser({ themes, langs, ...rest })\n return defineCodeBlockHighlight({ parser })\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,SAAgB,0BAAsD;AACpE,QAAO,eAAe;EACpB,eAAe,UAA2B;AACxC,UAAO,aAAa;IAAE,MAAM;IAAa;IAAO,CAAC;;EAEnD,kBAAkB,UAA2B;AAC3C,UAAO,WAAW;IAAE,MAAM;IAAa;IAAO,CAAC;;EAEjD,kBAAkB,UAA2B;AAC3C,UAAO,WAAW;IAAE,MAAM;IAAa;IAAO,CAAC;;EAEjD,oB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Y,QAAQ,YAAY;EACtC,MAAM,EAAE,aAAa,YAAY,uBAAuB;GACtD,GAAG;GACH,OAAO,CAAC,SAAS;GAClB,CAAC;AAEF,MAAI,CAAC,YACH,QAAO;AAGT,MAAI,CAAC,OACH,UAAS,aAAa,aAAa,EACjC,OAAO,mBAAmB,OAAO,IAClC,CAAC;AAEJ,SAAO,OAAO,QAAQ;;;;;;;;;;;;;;;;;;ACiB1B,SAAgB,qBAAqB,EACnC,SAAS,CAAC,eAAe,EACzB,QAAQ,CAAC,OAAO,CAChB,GAAG,SACsB,EAAE,EAAa;AAExC,QAAO,yBAAyB,EAAE,QADnB,iBAAiB;EAAE;EAAQ;EAAO,GAAG;EAAM,CAAC,EACjB,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { defineMarkInputRule } from "./input-rule-
|
|
1
|
+
import { defineMarkInputRule } from "./input-rule-DO_iy2aT.js";
|
|
2
2
|
import { canUseRegexLookbehind, defineCommands, defineKeymap, defineMarkSpec, toggleMark, union } from "@prosekit/core";
|
|
3
3
|
|
|
4
4
|
//#region src/code/code-commands.ts
|
|
@@ -53,8 +53,7 @@ function decorateDeletionSlice(slice) {
|
|
|
53
53
|
return [render];
|
|
54
54
|
}
|
|
55
55
|
function decorateDeletion(doc, from, to, pos) {
|
|
56
|
-
const
|
|
57
|
-
const renders = decorateDeletionSlice(slice);
|
|
56
|
+
const renders = decorateDeletionSlice(doc.slice(from, to));
|
|
58
57
|
const count = renders.length;
|
|
59
58
|
return renders.map((render, index) => Decoration.widget(pos, render, {
|
|
60
59
|
side: -20 - count + index,
|
|
@@ -142,9 +141,8 @@ var CommitRecorder = class {
|
|
|
142
141
|
* Define an extension that can record the changes in the editor.
|
|
143
142
|
*/
|
|
144
143
|
function defineCommitRecorder(commitRecorder) {
|
|
145
|
-
const key = new PluginKey("prosekit-commit-recorder");
|
|
146
144
|
return definePlugin(new ProseMirrorPlugin({
|
|
147
|
-
key,
|
|
145
|
+
key: new PluginKey("prosekit-commit-recorder"),
|
|
148
146
|
state: {
|
|
149
147
|
init: (_, state) => {
|
|
150
148
|
commitRecorder.init(state.doc);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prosekit-extensions-commit.js","names":["decorations: Decoration[]","commit: Commit"],"sources":["../src/commit/index.ts"],"sourcesContent":["import {\n defineDefaultState,\n definePlugin,\n jsonFromNode,\n union,\n type NodeJSON,\n type PlainExtension,\n type StepJSON,\n} from '@prosekit/core'\nimport {\n DOMSerializer,\n Fragment,\n Slice,\n type ProseMirrorNode,\n} from '@prosekit/pm/model'\nimport {\n PluginKey,\n ProseMirrorPlugin,\n type Transaction,\n} from '@prosekit/pm/state'\nimport { Step } from '@prosekit/pm/transform'\nimport {\n Decoration,\n DecorationSet,\n type EditorView,\n} from '@prosekit/pm/view'\nimport {\n ChangeSet,\n type Change,\n} from 'prosemirror-changeset'\n\n/**\n * A JSON representation of a commit.\n */\ninterface Commit {\n /**\n * The current doc node in the JSON format\n */\n doc: NodeJSON\n /**\n * The parent node in the JSON format\n */\n parent: NodeJSON\n /**\n * An array of steps in the JSON format that transform the parent node to the\n * current doc node.\n */\n steps: StepJSON[]\n}\n\nfunction getChanges(\n doc: ProseMirrorNode,\n parent: ProseMirrorNode,\n steps: Step[],\n): readonly Change[] {\n const initSet = ChangeSet.create(parent)\n const currSet = initSet.addSteps(\n doc,\n steps.map((step) => step.getMap()),\n null,\n )\n return currSet.changes\n}\n\nfunction renderDivWeight(view: EditorView): HTMLElement {\n const document = view.dom.ownerDocument\n return document.createElement('div')\n}\n\nfunction decorateDeletionSlice(\n slice: Slice,\n): Array<(view: EditorView) => HTMLElement> {\n // Get the fragment of the deleted content\n let { openStart, openEnd, content } = slice\n\n while (openStart > 0 && openEnd > 0 && content.childCount === 1) {\n openStart--\n openEnd--\n content = content.child(0).content\n }\n\n // Nothing to render\n if (content.childCount === 0) {\n return []\n }\n\n // For example, if the slice is\n // {\n // openStart: 1,\n // openEnd: 1,\n // content: <p>Hello</p><p>World</p>\n // }\n // We should render the following decorations:\n // <span>Hello</span>\n // <div></div>\n // <span>World</span>\n if (openStart > 0 && openEnd > 0 && content.childCount === 2) {\n const head = Fragment.from([content.child(0)])\n const tail = Fragment.from([content.child(1)])\n return [\n ...decorateDeletionSlice(new Slice(head, openStart, openStart)),\n renderDivWeight,\n ...decorateDeletionSlice(new Slice(tail, openEnd, openEnd)),\n ]\n }\n\n // For example, if the slice is\n // {\n // openStart: 1,\n // openEnd: 0,\n // content: <p>Hello</p><p>World</p>\n // }\n // We should render the following decorations:\n // <span>Hello</span>\n // <div><p>World</p></div>\n if (openStart > 0 && content.childCount >= 2) {\n const nodes = content.content\n const head = Fragment.from(nodes.slice(0, 1))\n const body = Fragment.from(nodes.slice(1))\n\n return [\n ...decorateDeletionSlice(new Slice(head, openStart, openStart)),\n ...decorateDeletionSlice(new Slice(body, 0, openEnd)),\n ]\n }\n\n // For example, if the slice is\n // {\n // openStart: 0,\n // openEnd: 1,\n // content: <p>Hello</p><p>World</p>\n // }\n // We should render the following decorations:\n // <div><p>Hello</p></div>\n // <span>World</span>\n if (openEnd > 0 && content.childCount >= 2) {\n const nodes = content.content\n const body = Fragment.from(nodes.slice(0, -1))\n const tail = Fragment.from(nodes.slice(-1))\n return [\n ...decorateDeletionSlice(new Slice(body, openStart, 0)),\n ...decorateDeletionSlice(new Slice(tail, openEnd, openEnd)),\n ]\n }\n\n const schema = content.child(0).type.schema\n const isInline = content.child(0).isInline\n\n const render = (view: EditorView): HTMLElement => {\n const document = view.dom.ownerDocument\n\n // Render the fragment to HTML\n const element = document.createElement(isInline ? 'span' : 'div')\n const serializer = DOMSerializer.fromSchema(schema)\n serializer.serializeFragment(content, { document }, element)\n\n // Add the class to the element\n element.classList.add('prosekit-commit-deletion')\n return element\n }\n\n return [render]\n}\n\nfunction decorateDeletion(\n /** The doc node before the deletion */\n doc: ProseMirrorNode,\n /** The start position of the deleted text in the doc node */\n from: number,\n /** The end position of the deleted text in the doc node */\n to: number,\n /** The insert position of the decoration in the doc node after the change */\n pos: number,\n): Decoration[] {\n const slice = doc.slice(from, to)\n\n const renders = decorateDeletionSlice(slice)\n const count = renders.length\n\n return renders.map((render, index) =>\n Decoration.widget(pos, render, {\n side: -20 - count + index,\n // Ensure the text in the decoration is able to be selected.\n ignoreSelection: true,\n })\n )\n}\n\nfunction decorateAddition(\n /** The start position of the inserted text in the doc node */\n from: number,\n /** The end position of the inserted text in the doc node */\n to: number,\n): Decoration {\n return Decoration.inline(from, to, { class: 'prosekit-commit-addition' })\n}\n\nfunction decorateChange(prev: ProseMirrorNode, change: Change): Decoration[] {\n const { fromA, toA, fromB, toB } = change\n const decorations: Decoration[] = []\n\n if (fromA < toA) {\n decorations.push(...decorateDeletion(prev, fromA, toA, fromB))\n }\n if (fromB < toB) {\n decorations.push(decorateAddition(fromB, toB))\n }\n\n return decorations\n}\n\nfunction decorateCommit(\n doc: ProseMirrorNode,\n parent: ProseMirrorNode,\n steps: Step[],\n): DecorationSet {\n const changes = getChanges(doc, parent, steps)\n const decorations = changes.flatMap((change) => decorateChange(parent, change))\n return DecorationSet.create(doc, decorations)\n}\n\nfunction defineCommitDecoration(commit: Commit): PlainExtension {\n const key = new PluginKey<DecorationSet>('prosekit-commit-decoration')\n\n return definePlugin(({ schema }): ProseMirrorPlugin => {\n const parent = schema.nodeFromJSON(commit.parent)\n const steps = commit.steps.map((step) => Step.fromJSON(schema, step))\n\n return new ProseMirrorPlugin({\n key,\n state: {\n init: (_, instance): DecorationSet => {\n return decorateCommit(instance.doc, parent, steps)\n },\n apply: (tr, deco: DecorationSet): DecorationSet => {\n return deco.map(tr.mapping, tr.doc)\n },\n },\n props: {\n decorations: (state): DecorationSet | undefined => {\n return key.getState(state)\n },\n },\n })\n })\n}\n\n/**\n * Define an extension to display the changes from the given commit in the editor.\n */\nfunction defineCommitViewer(commit: Commit): PlainExtension {\n return union(\n defineDefaultState({ defaultDoc: commit.doc }),\n defineCommitDecoration(commit),\n )\n}\n\nclass CommitRecorder {\n private parent: ProseMirrorNode | null = null\n private doc: ProseMirrorNode | null = null\n private steps: Step[] = []\n\n /**\n * Return a commit object including all changes since the last commit. `null`\n * will be returned if there is no change.\n */\n commit(): Commit | null {\n if (\n !this.parent\n || !this.doc\n || this.steps.length === 0\n || this.parent.eq(this.doc)\n ) {\n return null\n }\n\n const commit: Commit = {\n doc: jsonFromNode(this.doc),\n parent: jsonFromNode(this.parent),\n steps: this.steps.map((step) => step.toJSON() as StepJSON),\n }\n this.init(this.doc)\n return commit\n }\n\n /**\n * @internal\n */\n init(doc: ProseMirrorNode): void {\n this.doc = doc\n this.parent = doc\n this.steps = []\n }\n\n /**\n * @internal\n */\n apply(tr: Transaction): void {\n this.steps.push(...tr.steps)\n this.doc = tr.doc\n }\n}\n\n/**\n * Define an extension that can record the changes in the editor.\n */\nfunction defineCommitRecorder(commitRecorder: CommitRecorder): PlainExtension {\n const key = new PluginKey<DecorationSet>('prosekit-commit-recorder')\n\n return definePlugin(\n new ProseMirrorPlugin({\n key,\n state: {\n init: (_, state): void => {\n commitRecorder.init(state.doc)\n },\n apply: (tr): void => {\n commitRecorder.apply(tr)\n },\n },\n }),\n )\n}\n\nexport {\n CommitRecorder,\n defineCommitRecorder,\n defineCommitViewer,\n type Commit,\n}\n"],"mappings":";;;;;;;;AAkDA,SAAS,WACP,KACA,QACA,OACmB;AAOnB,QANgB,UAAU,OAAO,OAAO,CAChB,SACtB,KACA,MAAM,KAAK,SAAS,KAAK,QAAQ,CAAC,EAClC,KACD,CACc;;AAGjB,SAAS,gBAAgB,MAA+B;AAEtD,QADiB,KAAK,IAAI,cACV,cAAc,MAAM;;AAGtC,SAAS,sBACP,OAC0C;CAE1C,IAAI,EAAE,WAAW,SAAS,YAAY;AAEtC,QAAO,YAAY,KAAK,UAAU,KAAK,QAAQ,eAAe,GAAG;AAC/D;AACA;AACA,YAAU,QAAQ,MAAM,EAAE,CAAC;;AAI7B,KAAI,QAAQ,eAAe,EACzB,QAAO,EAAE;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AAuC;AACjD,YAAO,KAAK,IAAI,GAAG,SAAS,GAAG,IAAI;;IAEtC;GACD,OAAO,EACL,cAAc,UAAqC;AACjD,WAAO,IAAI,SAAS,MAAM;MAE7B;GACF,CAAC;GACF;;;;;AAMJ,SAAS,mBAAmB,QAAgC;AAC1D,QAAO,MACL,mBAAmB,EAAE,YAAY,OAAO,KAAK,CAAC,EAC9C,uBAAuB,OAAO,CAC/B;;AAGH,IAAM,iBAAN,MAAqB;;gBACsB;aACH;eACd,EAAE;;;;;;CAM1B,SAAwB;AACtB,MACE,CAAC,KAAK,UACH,CAAC,KAAK,OACN,KAAK,MAAM,WAAW,KACtB,KAAK,OAAO,GAAG,KAAK,IAAI,CAE3B,QAAO;EAGT,MAAMC,SAAiB;GACrB,KAAK,aAAa,KAAK,IAAI;GAC3B,QAAQ,aAAa,KAAK,OAAO;GACjC,OAAO,KAAK,MAAM,KAAK,SAAS,KAAK,QAAQ,CAAa;GAC3D;AACD,OAAK,KAAK,KAAK,IAAI;AACnB,SAAO;;;;;CAMT,KAAK,KAA4B;AAC/B,OAAK,MAAM;AACX,OAAK,SAAS;AACd,OAAK,QAAQ,EAAE;;;;;CAMjB,MAAM,IAAuB;AAC3B,OAAK,MAAM,KAAK,GAAG,GAAG,MAAM;AAC5B,OAAK,MAAM,GAAG;;;;;;AAOlB,SAAS,qBAAqB,gBAAgD;CAC5E,MAAM,MAAM,IAAI,UAAyB,2BAA2B;AAEpE,QAAO,aACL,IAAI,kBAAkB;EACpB;EACA,OAAO;GACL,OAAO,GAAG,UAAgB;AACxB,mBAAe,KAAK,MAAM,IAAI;;GAEhC,QAAQ,OAAa;AACnB,mBAAe,MAAM,GAAG;;GAE3B;EACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"prosekit-extensions-commit.js","names":["decorations: Decoration[]","commit: Commit"],"sources":["../src/commit/index.ts"],"sourcesContent":["import {\n defineDefaultState,\n definePlugin,\n jsonFromNode,\n union,\n type NodeJSON,\n type PlainExtension,\n type StepJSON,\n} from '@prosekit/core'\nimport {\n DOMSerializer,\n Fragment,\n Slice,\n type ProseMirrorNode,\n} from '@prosekit/pm/model'\nimport {\n PluginKey,\n ProseMirrorPlugin,\n type Transaction,\n} from '@prosekit/pm/state'\nimport { Step } from '@prosekit/pm/transform'\nimport {\n Decoration,\n DecorationSet,\n type EditorView,\n} from '@prosekit/pm/view'\nimport {\n ChangeSet,\n type Change,\n} from 'prosemirror-changeset'\n\n/**\n * A JSON representation of a commit.\n */\ninterface Commit {\n /**\n * The current doc node in the JSON format\n */\n doc: NodeJSON\n /**\n * The parent node in the JSON format\n */\n parent: NodeJSON\n /**\n * An array of steps in the JSON format that transform the parent node to the\n * current doc node.\n */\n steps: StepJSON[]\n}\n\nfunction getChanges(\n doc: ProseMirrorNode,\n parent: ProseMirrorNode,\n steps: Step[],\n): readonly Change[] {\n const initSet = ChangeSet.create(parent)\n const currSet = initSet.addSteps(\n doc,\n steps.map((step) => step.getMap()),\n null,\n )\n return currSet.changes\n}\n\nfunction renderDivWeight(view: EditorView): HTMLElement {\n const document = view.dom.ownerDocument\n return document.createElement('div')\n}\n\nfunction decorateDeletionSlice(\n slice: Slice,\n): Array<(view: EditorView) => HTMLElement> {\n // Get the fragment of the deleted content\n let { openStart, openEnd, content } = slice\n\n while (openStart > 0 && openEnd > 0 && content.childCount === 1) {\n openStart--\n openEnd--\n content = content.child(0).content\n }\n\n // Nothing to render\n if (content.childCount === 0) {\n return []\n }\n\n // For example, if the slice is\n // {\n // openStart: 1,\n // openEnd: 1,\n // content: <p>Hello</p><p>World</p>\n // }\n // We should render the following decorations:\n // <span>Hello</span>\n // <div></div>\n // <span>World</span>\n if (openStart > 0 && openEnd > 0 && content.childCount === 2) {\n const head = Fragment.from([content.child(0)])\n const tail = Fragment.from([content.child(1)])\n return [\n ...decorateDeletionSlice(new Slice(head, openStart, openStart)),\n renderDivWeight,\n ...decorateDeletionSlice(new Slice(tail, openEnd, openEnd)),\n ]\n }\n\n // For example, if the slice is\n // {\n // openStart: 1,\n // openEnd: 0,\n // content: <p>Hello</p><p>World</p>\n // }\n // We should render the following decorations:\n // <span>Hello</span>\n // <div><p>World</p></div>\n if (openStart > 0 && content.childCount >= 2) {\n const nodes = content.content\n const head = Fragment.from(nodes.slice(0, 1))\n const body = Fragment.from(nodes.slice(1))\n\n return [\n ...decorateDeletionSlice(new Slice(head, openStart, openStart)),\n ...decorateDeletionSlice(new Slice(body, 0, openEnd)),\n ]\n }\n\n // For example, if the slice is\n // {\n // openStart: 0,\n // openEnd: 1,\n // content: <p>Hello</p><p>World</p>\n // }\n // We should render the following decorations:\n // <div><p>Hello</p></div>\n // <span>World</span>\n if (openEnd > 0 && content.childCount >= 2) {\n const nodes = content.content\n const body = Fragment.from(nodes.slice(0, -1))\n const tail = Fragment.from(nodes.slice(-1))\n return [\n ...decorateDeletionSlice(new Slice(body, openStart, 0)),\n ...decorateDeletionSlice(new Slice(tail, openEnd, openEnd)),\n ]\n }\n\n const schema = content.child(0).type.schema\n const isInline = content.child(0).isInline\n\n const render = (view: EditorView): HTMLElement => {\n const document = view.dom.ownerDocument\n\n // Render the fragment to HTML\n const element = document.createElement(isInline ? 'span' : 'div')\n const serializer = DOMSerializer.fromSchema(schema)\n serializer.serializeFragment(content, { document }, element)\n\n // Add the class to the element\n element.classList.add('prosekit-commit-deletion')\n return element\n }\n\n return [render]\n}\n\nfunction decorateDeletion(\n /** The doc node before the deletion */\n doc: ProseMirrorNode,\n /** The start position of the deleted text in the doc node */\n from: number,\n /** The end position of the deleted text in the doc node */\n to: number,\n /** The insert position of the decoration in the doc node after the change */\n pos: number,\n): Decoration[] {\n const slice = doc.slice(from, to)\n\n const renders = decorateDeletionSlice(slice)\n const count = renders.length\n\n return renders.map((render, index) =>\n Decoration.widget(pos, render, {\n side: -20 - count + index,\n // Ensure the text in the decoration is able to be selected.\n ignoreSelection: true,\n })\n )\n}\n\nfunction decorateAddition(\n /** The start position of the inserted text in the doc node */\n from: number,\n /** The end position of the inserted text in the doc node */\n to: number,\n): Decoration {\n return Decoration.inline(from, to, { class: 'prosekit-commit-addition' })\n}\n\nfunction decorateChange(prev: ProseMirrorNode, change: Change): Decoration[] {\n const { fromA, toA, fromB, toB } = change\n const decorations: Decoration[] = []\n\n if (fromA < toA) {\n decorations.push(...decorateDeletion(prev, fromA, toA, fromB))\n }\n if (fromB < toB) {\n decorations.push(decorateAddition(fromB, toB))\n }\n\n return decorations\n}\n\nfunction decorateCommit(\n doc: ProseMirrorNode,\n parent: ProseMirrorNode,\n steps: Step[],\n): DecorationSet {\n const changes = getChanges(doc, parent, steps)\n const decorations = changes.flatMap((change) => decorateChange(parent, change))\n return DecorationSet.create(doc, decorations)\n}\n\nfunction defineCommitDecoration(commit: Commit): PlainExtension {\n const key = new PluginKey<DecorationSet>('prosekit-commit-decoration')\n\n return definePlugin(({ schema }): ProseMirrorPlugin => {\n const parent = schema.nodeFromJSON(commit.parent)\n const steps = commit.steps.map((step) => Step.fromJSON(schema, step))\n\n return new ProseMirrorPlugin({\n key,\n state: {\n init: (_, instance): DecorationSet => {\n return decorateCommit(instance.doc, parent, steps)\n },\n apply: (tr, deco: DecorationSet): DecorationSet => {\n return deco.map(tr.mapping, tr.doc)\n },\n },\n props: {\n decorations: (state): DecorationSet | undefined => {\n return key.getState(state)\n },\n },\n })\n })\n}\n\n/**\n * Define an extension to display the changes from the given commit in the editor.\n */\nfunction defineCommitViewer(commit: Commit): PlainExtension {\n return union(\n defineDefaultState({ defaultDoc: commit.doc }),\n defineCommitDecoration(commit),\n )\n}\n\nclass CommitRecorder {\n private parent: ProseMirrorNode | null = null\n private doc: ProseMirrorNode | null = null\n private steps: Step[] = []\n\n /**\n * Return a commit object including all changes since the last commit. `null`\n * will be returned if there is no change.\n */\n commit(): Commit | null {\n if (\n !this.parent\n || !this.doc\n || this.steps.length === 0\n || this.parent.eq(this.doc)\n ) {\n return null\n }\n\n const commit: Commit = {\n doc: jsonFromNode(this.doc),\n parent: jsonFromNode(this.parent),\n steps: this.steps.map((step) => step.toJSON() as StepJSON),\n }\n this.init(this.doc)\n return commit\n }\n\n /**\n * @internal\n */\n init(doc: ProseMirrorNode): void {\n this.doc = doc\n this.parent = doc\n this.steps = []\n }\n\n /**\n * @internal\n */\n apply(tr: Transaction): void {\n this.steps.push(...tr.steps)\n this.doc = tr.doc\n }\n}\n\n/**\n * Define an extension that can record the changes in the editor.\n */\nfunction defineCommitRecorder(commitRecorder: CommitRecorder): PlainExtension {\n const key = new PluginKey<DecorationSet>('prosekit-commit-recorder')\n\n return definePlugin(\n new ProseMirrorPlugin({\n key,\n state: {\n init: (_, state): void => {\n commitRecorder.init(state.doc)\n },\n apply: (tr): void => {\n commitRecorder.apply(tr)\n },\n },\n }),\n )\n}\n\nexport {\n CommitRecorder,\n defineCommitRecorder,\n defineCommitViewer,\n type Commit,\n}\n"],"mappings":";;;;;;;;AAkDA,SAAS,WACP,KACA,QACA,OACmB;AAOnB,QANgB,UAAU,OAAO,OAAO,CAChB,SACtB,KACA,MAAM,KAAK,SAAS,KAAK,QAAQ,CAAC,EAClC,KACD,CACc;;AAGjB,SAAS,gBAAgB,MAA+B;AAEtD,QADiB,KAAK,IAAI,cACV,cAAc,MAAM;;AAGtC,SAAS,sBACP,OAC0C;CAE1C,IAAI,EAAE,WAAW,SAAS,YAAY;AAEtC,QAAO,YAAY,KAAK,UAAU,KAAK,QAAQ,eAAe,GAAG;AAC/D;AACA;AACA,YAAU,QAAQ,MAAM,EAAE,CAAC;;AAI7B,KAAI,QAAQ,eAAe,EACzB,QAAO,EAAE;AAaX,KAAI,YAAY,KAAK,UAAU,KAAK,QAAQ,eAAe,GAAG;EAC5D,MAAM,OAAO,SAAS,KAAK,CAAC,QAAQ,MAAM,EAAE,CAAC,CAAC;EAC9C,MAAM,OAAO,SAAS,KAAK,CAAC,QAAQ,MAAM,EAAE,CAAC,CAAC;AAC9C,SAAO;GACL,GAAG,sBAAsB,IAAI,MAAM,MAAM,WAAW,UAAU,CAAC;GAC/D;GACA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gBACsB;aACH;eACd,EAAE;;;;;;CAM1B,SAAwB;AACtB,MACE,CAAC,KAAK,UACH,CAAC,KAAK,OACN,KAAK,MAAM,WAAW,KACtB,KAAK,OAAO,GAAG,KAAK,IAAI,CAE3B,QAAO;EAGT,MAAMC,SAAiB;GACrB,KAAK,aAAa,KAAK,IAAI;GAC3B,QAAQ,aAAa,KAAK,OAAO;GACjC,OAAO,KAAK,MAAM,KAAK,SAAS,KAAK,QAAQ,CAAa;GAC3D;AACD,OAAK,KAAK,KAAK,IAAI;AACnB,SAAO;;;;;CAMT,KAAK,KAA4B;AAC/B,OAAK,MAAM;AACX,OAAK,SAAS;AACd,OAAK,QAAQ,EAAE;;;;;CAMjB,MAAM,IAAuB;AAC3B,OAAK,MAAM,KAAK,GAAG,GAAG,MAAM;AAC5B,OAAK,MAAM,GAAG;;;;;;AAOlB,SAAS,qBAAqB,gBAAgD;AAG5E,QAAO,aACL,IAAI,kBAAkB;EACpB,KAJQ,IAAI,UAAyB,2BAA2B;EAKhE,OAAO;GACL,OAAO,GAAG,UAAgB;AACxB,mBAAe,KAAK,MAAM,IAAI;;GAEhC,QAAQ,OAAa;AACnB,mBAAe,MAAM,GAAG;;GAE3B;EACF,CAAC,CACH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { defineTextBlockInputRule } from "./input-rule-
|
|
1
|
+
import { defineTextBlockInputRule } from "./input-rule-DO_iy2aT.js";
|
|
2
2
|
import { defineCommands, defineKeymap, defineNodeSpec, insertNode, isAtBlockStart, setBlockType, toggleNode, union, unsetBlockType, withSkipCodeBlock } from "@prosekit/core";
|
|
3
3
|
|
|
4
4
|
//#region src/heading/heading-commands.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { defineInputRule } from "./input-rule-
|
|
1
|
+
import { defineInputRule } from "./input-rule-DO_iy2aT.js";
|
|
2
2
|
import { defineCommands, defineNodeSpec, getNodeType, union } from "@prosekit/core";
|
|
3
3
|
import { InputRule } from "@prosekit/pm/inputrules";
|
|
4
4
|
import { Fragment, Slice } from "@prosekit/pm/model";
|