diff --git a/.gitignore b/.gitignore index 40d74f32..c8780ba6 100644 --- a/.gitignore +++ b/.gitignore @@ -48,17 +48,18 @@ wolai-frontend/public/documents/ wolai-frontend/public/documents/** artifacts/ artifacts/** -tmp -design - -# Rust 本地构建与调试产物 -/rust/target/ -/rust/spikes/**/target/ - -# Harness 本地运行状态/调试产物 -/.harness-active -/.harness-stop-counter -/harness-tasks.json.bak - -# pnpm 本地缓存 -/.pnpm-store/ +tmp +design + +# Rust 本地构建与调试产物 +/rust/target/ +/rust/spikes/**/target/ + +# Harness 本地运行状态/调试产物 +/.harness-active +/.harness-stop-counter +/harness-tasks.json.bak + +# pnpm 本地缓存 +/.pnpm-store/ +.playwright-mcp \ No newline at end of file diff --git a/rust/spikes/leptos-tiptap-spike/Cargo.lock b/rust/spikes/leptos-tiptap-spike/Cargo.lock index 721b6ce2..d6df6614 100644 --- a/rust/spikes/leptos-tiptap-spike/Cargo.lock +++ b/rust/spikes/leptos-tiptap-spike/Cargo.lock @@ -976,6 +976,7 @@ dependencies = [ "leptos-tiptap", "leptos_dom", "serde", + "serde-wasm-bindgen", "serde_json", "wasm-bindgen", "web-sys", diff --git a/rust/spikes/leptos-tiptap-spike/Cargo.toml b/rust/spikes/leptos-tiptap-spike/Cargo.toml index 8c8817f0..82a982a9 100644 --- a/rust/spikes/leptos-tiptap-spike/Cargo.toml +++ b/rust/spikes/leptos-tiptap-spike/Cargo.toml @@ -5,15 +5,24 @@ edition = "2021" [workspace] +[lib] +path = "src/lib.rs" +crate-type = ["cdylib", "rlib"] + +[[bin]] +name = "mnote-leptos-tiptap-spike" +path = "src/main.rs" + [dependencies] console_error_panic_hook = "0.1.7" leptos = { version = "0.8.19", features = ["csr"] } leptos_dom = "0.8.8" serde = { version = "1", features = ["derive"] } serde_json = "1" +serde-wasm-bindgen = "0.6" js-sys = "0.3.77" wasm-bindgen = "0.2" -web-sys = { version = "0.3.77", features = ["DataTransfer", "Document", "DomRect", "DragEvent", "Element", "EventTarget", "HtmlElement", "MouseEvent", "Node", "Range", "Selection", "Storage", "Window"] } +web-sys = { version = "0.3.77", features = ["CustomEvent", "CustomEventInit", "DataTransfer", "Document", "DomRect", "DragEvent", "Element", "EventTarget", "HtmlElement", "MessageEvent", "MouseEvent", "Node", "Range", "Selection", "Storage", "Window"] } [dependencies.leptos-tiptap] path = "../../../design/05-editor-mainline/reference-code/leptos-tiptap" diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island.d.ts b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island.d.ts new file mode 100644 index 00000000..fb411b4f --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island.d.ts @@ -0,0 +1,102 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * The `ReadableStreamType` enum. + * + * *This API requires the following crate features to be activated: `ReadableStreamType`* + */ + +type ReadableStreamType = "bytes"; + +export class IntoUnderlyingByteSource { + private constructor(); + free(): void; + [Symbol.dispose](): void; + cancel(): void; + pull(controller: ReadableByteStreamController): Promise; + start(controller: ReadableByteStreamController): void; + readonly autoAllocateChunkSize: number; + readonly type: ReadableStreamType; +} + +export class IntoUnderlyingSink { + private constructor(); + free(): void; + [Symbol.dispose](): void; + abort(reason: any): Promise; + close(): Promise; + write(chunk: any): Promise; +} + +export class IntoUnderlyingSource { + private constructor(); + free(): void; + [Symbol.dispose](): void; + cancel(): void; + pull(controller: ReadableStreamDefaultController): Promise; +} + +export function mount(container: Element, options: any): number; + +export function unmount(mount_id: number): void; + +export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module; + +export interface InitOutput { + readonly memory: WebAssembly.Memory; + readonly mount: (a: any, b: any) => [number, number, number]; + readonly unmount: (a: number) => [number, number]; + readonly __wbg_intounderlyingbytesource_free: (a: number, b: number) => void; + readonly intounderlyingbytesource_type: (a: number) => number; + readonly intounderlyingbytesource_autoAllocateChunkSize: (a: number) => number; + readonly intounderlyingbytesource_start: (a: number, b: any) => void; + readonly intounderlyingbytesource_pull: (a: number, b: any) => any; + readonly intounderlyingbytesource_cancel: (a: number) => void; + readonly __wbg_intounderlyingsink_free: (a: number, b: number) => void; + readonly intounderlyingsink_write: (a: number, b: any) => any; + readonly intounderlyingsink_close: (a: number) => any; + readonly intounderlyingsink_abort: (a: number, b: any) => any; + readonly __wbg_intounderlyingsource_free: (a: number, b: number) => void; + readonly intounderlyingsource_pull: (a: number, b: any) => any; + readonly intounderlyingsource_cancel: (a: number) => void; + readonly wasm_bindgen__convert__closures_____invoke__h36e788bd1cd1f0f7: (a: number, b: number, c: any) => [number, number]; + readonly wasm_bindgen__convert__closures_____invoke__hb0ba6117a7ec12e8: (a: number, b: number, c: any, d: any) => void; + readonly wasm_bindgen__convert__closures_____invoke__h2593b18d2d6f8a75: (a: number, b: number, c: any) => void; + readonly wasm_bindgen__convert__closures_____invoke__h1ea2b89742286ce6: (a: number, b: number, c: any) => void; + readonly wasm_bindgen__convert__closures_____invoke__h03deb55668e1377f: (a: number, b: number, c: any) => void; + readonly wasm_bindgen__convert__closures_____invoke__h837fba73fce77300: (a: number, b: number, c: any) => void; + readonly wasm_bindgen__convert__closures_____invoke__h60e57afd955e8441: (a: number, b: number) => number; + readonly wasm_bindgen__convert__closures_____invoke__hd17f30facfdd737f: (a: number, b: number) => void; + readonly wasm_bindgen__convert__closures_____invoke__hf726e22cfd1ee0a9: (a: number, b: number) => void; + readonly __wbindgen_malloc: (a: number, b: number) => number; + readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number; + readonly __externref_table_alloc: () => number; + readonly __wbindgen_externrefs: WebAssembly.Table; + readonly __wbindgen_exn_store: (a: number) => void; + readonly __wbindgen_free: (a: number, b: number, c: number) => void; + readonly __wbindgen_destroy_closure: (a: number, b: number) => void; + readonly __externref_table_dealloc: (a: number) => void; + readonly __wbindgen_start: () => void; +} + +export type SyncInitInput = BufferSource | WebAssembly.Module; + +/** + * Instantiates the given `module`, which can either be bytes or + * a precompiled `WebAssembly.Module`. + * + * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated. + * + * @returns {InitOutput} + */ +export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput; + +/** + * If `module_or_path` is {RequestInfo} or {URL}, makes a request and + * for everything else, calls `WebAssembly.instantiate` directly. + * + * @param {{ module_or_path: InitInput | Promise }} module_or_path - Passing `InitInput` directly is deprecated. + * + * @returns {Promise} + */ +export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise } | InitInput | Promise): Promise; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island.js b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island.js new file mode 100644 index 00000000..22336f28 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island.js @@ -0,0 +1,1495 @@ +/* @ts-self-types="./mnote-leptos-tiptap-spike-island.d.ts" */ +import { create, destroy, init_bridge_runtime } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js'; +import { register_blockquote } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_blockquote.js'; +import { register_bold } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bold.js'; +import { register_bullet_list } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bullet_list.js'; +import { register_code } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code.js'; +import { register_code_block } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code_block.js'; +import { register_document } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_document.js'; +import { register_dropcursor } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_dropcursor.js'; +import { register_gapcursor } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_gapcursor.js'; +import { register_hard_break } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_hard_break.js'; +import { register_heading } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_heading.js'; +import { register_highlight } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_highlight.js'; +import { register_history } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_history.js'; +import { register_horizontal_rule } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_horizontal_rule.js'; +import { register_image } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_image.js'; +import { register_italic } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_italic.js'; +import { register_link } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_link.js'; +import { register_list_item } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_list_item.js'; +import { register_ordered_list } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_ordered_list.js'; +import { register_paragraph } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_paragraph.js'; +import { register_placeholder } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_placeholder.js'; +import { register_strike } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_strike.js'; +import { register_task_item } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_item.js'; +import { register_task_list } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_list.js'; +import { register_text } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text.js'; +import { register_text_align } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_align.js'; +import { register_text_style } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_style.js'; +import { register_underline } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_underline.js'; +import { register_youtube } from './snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_youtube.js'; +import * as import1 from "./snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js" +import * as import2 from "./snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js" + + +export class IntoUnderlyingByteSource { + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + IntoUnderlyingByteSourceFinalization.unregister(this); + return ptr; + } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_intounderlyingbytesource_free(ptr, 0); + } + /** + * @returns {number} + */ + get autoAllocateChunkSize() { + const ret = wasm.intounderlyingbytesource_autoAllocateChunkSize(this.__wbg_ptr); + return ret >>> 0; + } + cancel() { + const ptr = this.__destroy_into_raw(); + wasm.intounderlyingbytesource_cancel(ptr); + } + /** + * @param {ReadableByteStreamController} controller + * @returns {Promise} + */ + pull(controller) { + const ret = wasm.intounderlyingbytesource_pull(this.__wbg_ptr, controller); + return ret; + } + /** + * @param {ReadableByteStreamController} controller + */ + start(controller) { + wasm.intounderlyingbytesource_start(this.__wbg_ptr, controller); + } + /** + * @returns {ReadableStreamType} + */ + get type() { + const ret = wasm.intounderlyingbytesource_type(this.__wbg_ptr); + return __wbindgen_enum_ReadableStreamType[ret]; + } +} +if (Symbol.dispose) IntoUnderlyingByteSource.prototype[Symbol.dispose] = IntoUnderlyingByteSource.prototype.free; + +export class IntoUnderlyingSink { + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + IntoUnderlyingSinkFinalization.unregister(this); + return ptr; + } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_intounderlyingsink_free(ptr, 0); + } + /** + * @param {any} reason + * @returns {Promise} + */ + abort(reason) { + const ptr = this.__destroy_into_raw(); + const ret = wasm.intounderlyingsink_abort(ptr, reason); + return ret; + } + /** + * @returns {Promise} + */ + close() { + const ptr = this.__destroy_into_raw(); + const ret = wasm.intounderlyingsink_close(ptr); + return ret; + } + /** + * @param {any} chunk + * @returns {Promise} + */ + write(chunk) { + const ret = wasm.intounderlyingsink_write(this.__wbg_ptr, chunk); + return ret; + } +} +if (Symbol.dispose) IntoUnderlyingSink.prototype[Symbol.dispose] = IntoUnderlyingSink.prototype.free; + +export class IntoUnderlyingSource { + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + IntoUnderlyingSourceFinalization.unregister(this); + return ptr; + } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_intounderlyingsource_free(ptr, 0); + } + cancel() { + const ptr = this.__destroy_into_raw(); + wasm.intounderlyingsource_cancel(ptr); + } + /** + * @param {ReadableStreamDefaultController} controller + * @returns {Promise} + */ + pull(controller) { + const ret = wasm.intounderlyingsource_pull(this.__wbg_ptr, controller); + return ret; + } +} +if (Symbol.dispose) IntoUnderlyingSource.prototype[Symbol.dispose] = IntoUnderlyingSource.prototype.free; + +/** + * @param {Element} container + * @param {any} options + * @returns {number} + */ +export function mount(container, options) { + const ret = wasm.mount(container, options); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ret[0] >>> 0; +} + +/** + * @param {number} mount_id + */ +export function unmount(mount_id) { + const ret = wasm.unmount(mount_id); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } +} +function __wbg_get_imports() { + const import0 = { + __proto__: null, + __wbg_Error_960c155d3d49e4c2: function(arg0, arg1) { + const ret = Error(getStringFromWasm0(arg0, arg1)); + return ret; + }, + __wbg_Number_32bf70a599af1d4b: function(arg0) { + const ret = Number(arg0); + return ret; + }, + __wbg_String_8564e559799eccda: function(arg0, arg1) { + const ret = String(arg1); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg___wbindgen_bigint_get_as_i64_3d3aba5d616c6a51: function(arg0, arg1) { + const v = arg1; + const ret = typeof(v) === 'bigint' ? v : undefined; + getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }, + __wbg___wbindgen_boolean_get_6ea149f0a8dcc5ff: function(arg0) { + const v = arg0; + const ret = typeof(v) === 'boolean' ? v : undefined; + return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0; + }, + __wbg___wbindgen_debug_string_ab4b34d23d6778bd: function(arg0, arg1) { + const ret = debugString(arg1); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg___wbindgen_in_a5d8b22e52b24dd1: function(arg0, arg1) { + const ret = arg0 in arg1; + return ret; + }, + __wbg___wbindgen_is_bigint_ec25c7f91b4d9e93: function(arg0) { + const ret = typeof(arg0) === 'bigint'; + return ret; + }, + __wbg___wbindgen_is_falsy_c07bb72123e65555: function(arg0) { + const ret = !arg0; + return ret; + }, + __wbg___wbindgen_is_function_3baa9db1a987f47d: function(arg0) { + const ret = typeof(arg0) === 'function'; + return ret; + }, + __wbg___wbindgen_is_null_52ff4ec04186736f: function(arg0) { + const ret = arg0 === null; + return ret; + }, + __wbg___wbindgen_is_object_63322ec0cd6ea4ef: function(arg0) { + const val = arg0; + const ret = typeof(val) === 'object' && val !== null; + return ret; + }, + __wbg___wbindgen_is_string_6df3bf7ef1164ed3: function(arg0) { + const ret = typeof(arg0) === 'string'; + return ret; + }, + __wbg___wbindgen_is_undefined_29a43b4d42920abd: function(arg0) { + const ret = arg0 === undefined; + return ret; + }, + __wbg___wbindgen_jsval_eq_d3465d8a07697228: function(arg0, arg1) { + const ret = arg0 === arg1; + return ret; + }, + __wbg___wbindgen_jsval_loose_eq_cac3565e89b4134c: function(arg0, arg1) { + const ret = arg0 == arg1; + return ret; + }, + __wbg___wbindgen_number_get_c7f42aed0525c451: function(arg0, arg1) { + const obj = arg1; + const ret = typeof(obj) === 'number' ? obj : undefined; + getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }, + __wbg___wbindgen_string_get_7ed5322991caaec5: function(arg0, arg1) { + const obj = arg1; + const ret = typeof(obj) === 'string' ? obj : undefined; + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg___wbindgen_throw_6b64449b9b9ed33c: function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }, + __wbg__wbg_cb_unref_b46c9b5a9f08ec37: function(arg0) { + arg0._wbg_cb_unref(); + }, + __wbg_activeElement_737cd2e5ce862ac0: function(arg0) { + const ret = arg0.activeElement; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_addEventListener_8176dab41b09531c: function() { return handleError(function (arg0, arg1, arg2, arg3) { + arg0.addEventListener(getStringFromWasm0(arg1, arg2), arg3); + }, arguments); }, + __wbg_altKey_c4f26b40f1b826b4: function(arg0) { + const ret = arg0.altKey; + return ret; + }, + __wbg_anchorNode_3a44321bc1cb148e: function(arg0) { + const ret = arg0.anchorNode; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_appendChild_e95c8b3b936d250a: function() { return handleError(function (arg0, arg1) { + const ret = arg0.appendChild(arg1); + return ret; + }, arguments); }, + __wbg_body_c7b35a55457167ba: function(arg0) { + const ret = arg0.body; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_bottom_12dded5de5311aff: function(arg0) { + const ret = arg0.bottom; + return ret; + }, + __wbg_buffer_d0f5ea0926a691fd: function(arg0) { + const ret = arg0.buffer; + return ret; + }, + __wbg_button_c794bf4b1dcd7c4c: function(arg0) { + const ret = arg0.button; + return ret; + }, + __wbg_buttons_9b45c5f89c8d91db: function(arg0) { + const ret = arg0.buttons; + return ret; + }, + __wbg_byobRequest_dc6aed9db01b12c6: function(arg0) { + const ret = arg0.byobRequest; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_byteLength_3e660e5661f3327e: function(arg0) { + const ret = arg0.byteLength; + return ret; + }, + __wbg_byteOffset_ecd62abe44dd28d4: function(arg0) { + const ret = arg0.byteOffset; + return ret; + }, + __wbg_call_14b169f759b26747: function() { return handleError(function (arg0, arg1) { + const ret = arg0.call(arg1); + return ret; + }, arguments); }, + __wbg_call_a24592a6f349a97e: function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.call(arg1, arg2); + return ret; + }, arguments); }, + __wbg_cancelBubble_56aa5b315d711482: function(arg0) { + const ret = arg0.cancelBubble; + return ret; + }, + __wbg_children_9c299b52b2889289: function(arg0) { + const ret = arg0.children; + return ret; + }, + __wbg_clientHeight_01b31bebacb195f0: function(arg0) { + const ret = arg0.clientHeight; + return ret; + }, + __wbg_clientX_48ead8c93aa7a872: function(arg0) { + const ret = arg0.clientX; + return ret; + }, + __wbg_clientY_ddcce7762c925e13: function(arg0) { + const ret = arg0.clientY; + return ret; + }, + __wbg_cloneNode_50658ff5fec44693: function() { return handleError(function (arg0, arg1) { + const ret = arg0.cloneNode(arg1 !== 0); + return ret; + }, arguments); }, + __wbg_cloneNode_eb01fe238729dac4: function() { return handleError(function (arg0) { + const ret = arg0.cloneNode(); + return ret; + }, arguments); }, + __wbg_close_e6c8977a002e9e13: function() { return handleError(function (arg0) { + arg0.close(); + }, arguments); }, + __wbg_close_fb954dfaf67b5732: function() { return handleError(function (arg0) { + arg0.close(); + }, arguments); }, + __wbg_closest_7cf140b67f393018: function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.closest(getStringFromWasm0(arg1, arg2)); + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, arguments); }, + __wbg_composedPath_e2b9e0f5161335eb: function(arg0) { + const ret = arg0.composedPath(); + return ret; + }, + __wbg_content_13d0cb7e0ea91c39: function(arg0) { + const ret = arg0.content; + return ret; + }, + __wbg_createComment_592a0c17b1cf8cad: function(arg0, arg1, arg2) { + const ret = arg0.createComment(getStringFromWasm0(arg1, arg2)); + return ret; + }, + __wbg_createElementNS_e0e4bbb6e664f948: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { + const ret = arg0.createElementNS(arg1 === 0 ? undefined : getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4)); + return ret; + }, arguments); }, + __wbg_createElement_bbd4c90086fe6f7b: function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.createElement(getStringFromWasm0(arg1, arg2)); + return ret; + }, arguments); }, + __wbg_createTextNode_7949043038fd9f7b: function(arg0, arg1, arg2) { + const ret = arg0.createTextNode(getStringFromWasm0(arg1, arg2)); + return ret; + }, + __wbg_create_057dfeb379c77c81: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { + create(arg0, arg1, arg2, arg3, arg4); + }, arguments); }, + __wbg_ctrlKey_31968cccd46bdef6: function(arg0) { + const ret = arg0.ctrlKey; + return ret; + }, + __wbg_currentTarget_fac617eb326a4ee6: function(arg0) { + const ret = arg0.currentTarget; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_deleteProperty_d5f7bd763acbdb44: function() { return handleError(function (arg0, arg1) { + const ret = Reflect.deleteProperty(arg0, arg1); + return ret; + }, arguments); }, + __wbg_deltaY_ca7744a8772482e1: function(arg0) { + const ret = arg0.deltaY; + return ret; + }, + __wbg_destroy_9b66fbc28176b62a: function(arg0, arg1) { + let deferred0_0; + let deferred0_1; + try { + deferred0_0 = arg0; + deferred0_1 = arg1; + destroy(getStringFromWasm0(arg0, arg1)); + } finally { + wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); + } + }, + __wbg_detail_c850e1ba165488a1: function(arg0) { + const ret = arg0.detail; + return ret; + }, + __wbg_dispatchEvent_d8729fc7c0462621: function() { return handleError(function (arg0, arg1) { + const ret = arg0.dispatchEvent(arg1); + return ret; + }, arguments); }, + __wbg_document_7a41071f2f439323: function(arg0) { + const ret = arg0.document; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_done_9158f7cc8751ba32: function(arg0) { + const ret = arg0.done; + return ret; + }, + __wbg_elementFromPoint_69f15053cea2ece4: function(arg0, arg1, arg2) { + const ret = arg0.elementFromPoint(arg1, arg2); + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_enqueue_4767ce322820c94d: function() { return handleError(function (arg0, arg1) { + arg0.enqueue(arg1); + }, arguments); }, + __wbg_entries_e0b73aa8571ddb56: function(arg0) { + const ret = Object.entries(arg0); + return ret; + }, + __wbg_error_a6fa202b58aa1cd3: function(arg0, arg1) { + let deferred0_0; + let deferred0_1; + try { + deferred0_0 = arg0; + deferred0_1 = arg1; + console.error(getStringFromWasm0(arg0, arg1)); + } finally { + wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); + } + }, + __wbg_firstElementChild_f67647a589d437a2: function(arg0) { + const ret = arg0.firstElementChild; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_focusNode_13a1b4aca2ce0453: function(arg0) { + const ret = arg0.focusNode; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_getAttribute_8627dea35cdb7b06: function(arg0, arg1, arg2, arg3) { + const ret = arg1.getAttribute(getStringFromWasm0(arg2, arg3)); + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg_getBoundingClientRect_726f24ef9e4e7eaa: function(arg0) { + const ret = arg0.getBoundingClientRect(); + return ret; + }, + __wbg_getBoundingClientRect_ddac06b2c6b52b98: function(arg0) { + const ret = arg0.getBoundingClientRect(); + return ret; + }, + __wbg_getItem_7fe1351b9ea3b2f3: function() { return handleError(function (arg0, arg1, arg2, arg3) { + const ret = arg1.getItem(getStringFromWasm0(arg2, arg3)); + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, arguments); }, + __wbg_getRangeAt_b7ea59f2b148e5d9: function() { return handleError(function (arg0, arg1) { + const ret = arg0.getRangeAt(arg1 >>> 0); + return ret; + }, arguments); }, + __wbg_getSelection_dfd0ccff15057bd1: function() { return handleError(function (arg0) { + const ret = arg0.getSelection(); + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, arguments); }, + __wbg_get_1affdbdd5573b16a: function() { return handleError(function (arg0, arg1) { + const ret = Reflect.get(arg0, arg1); + return ret; + }, arguments); }, + __wbg_get_6011fa3a58f61074: function() { return handleError(function (arg0, arg1) { + const ret = Reflect.get(arg0, arg1); + return ret; + }, arguments); }, + __wbg_get_8360291721e2339f: function(arg0, arg1) { + const ret = arg0[arg1 >>> 0]; + return ret; + }, + __wbg_get_unchecked_17f53dad852b9588: function(arg0, arg1) { + const ret = arg0[arg1 >>> 0]; + return ret; + }, + __wbg_get_with_ref_key_6412cf3094599694: function(arg0, arg1) { + const ret = arg0[arg1]; + return ret; + }, + __wbg_height_cc0f4b9ec7073c11: function(arg0) { + const ret = arg0.height; + return ret; + }, + __wbg_host_207aa9237088c9e9: function(arg0) { + const ret = arg0.host; + return ret; + }, + __wbg_init_bridge_runtime_777169bfaa015be2: function() { return handleError(function () { + init_bridge_runtime(); + }, arguments); }, + __wbg_innerHTML_df4703c8599a85c4: function(arg0, arg1) { + const ret = arg1.innerHTML; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg_insertBefore_38c7d835a2dcac23: function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.insertBefore(arg1, arg2); + return ret; + }, arguments); }, + __wbg_instanceof_ArrayBuffer_7c8433c6ed14ffe3: function(arg0) { + let result; + try { + result = arg0 instanceof ArrayBuffer; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_CustomEvent_7a9c6ffc1d87485e: function(arg0) { + let result; + try { + result = arg0 instanceof CustomEvent; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_Element_56c8d987654f359e: function(arg0) { + let result; + try { + result = arg0 instanceof Element; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_HtmlElement_47620edd062da622: function(arg0) { + let result; + try { + result = arg0 instanceof HTMLElement; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_Map_1b76fd4635be43eb: function(arg0) { + let result; + try { + result = arg0 instanceof Map; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_Node_d192134fe9a0b445: function(arg0) { + let result; + try { + result = arg0 instanceof Node; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_ShadowRoot_d26d95cd2363a2c1: function(arg0) { + let result; + try { + result = arg0 instanceof ShadowRoot; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_Uint8Array_152ba1f289edcf3f: function(arg0) { + let result; + try { + result = arg0 instanceof Uint8Array; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_instanceof_Window_cc64c86c8ef9e02b: function(arg0) { + let result; + try { + result = arg0 instanceof Window; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }, + __wbg_isArray_c3109d14ffc06469: function(arg0) { + const ret = Array.isArray(arg0); + return ret; + }, + __wbg_isCollapsed_465613ddcec18e68: function(arg0) { + const ret = arg0.isCollapsed; + return ret; + }, + __wbg_isSafeInteger_4fc213d1989d6d2a: function(arg0) { + const ret = Number.isSafeInteger(arg0); + return ret; + }, + __wbg_isSameNode_484f58633744648f: function(arg0, arg1) { + const ret = arg0.isSameNode(arg1); + return ret; + }, + __wbg_is_8f7ba86b7f249abd: function(arg0, arg1) { + const ret = Object.is(arg0, arg1); + return ret; + }, + __wbg_item_2756ef1395ab5dda: function(arg0, arg1) { + const ret = arg0.item(arg1 >>> 0); + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_iterator_013bc09ec998c2a7: function() { + const ret = Symbol.iterator; + return ret; + }, + __wbg_key_2cbc38fa83cdb336: function(arg0, arg1) { + const ret = arg1.key; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg_left_ea423c913972748d: function(arg0) { + const ret = arg0.left; + return ret; + }, + __wbg_length_3d4ecd04bd8d22f1: function(arg0) { + const ret = arg0.length; + return ret; + }, + __wbg_length_9107c083c5526b42: function(arg0) { + const ret = arg0.length; + return ret; + }, + __wbg_length_9f1775224cf1d815: function(arg0) { + const ret = arg0.length; + return ret; + }, + __wbg_localStorage_f5f66b1ffd2486bc: function() { return handleError(function (arg0) { + const ret = arg0.localStorage; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, arguments); }, + __wbg_location_73c89ca5bb53ddf3: function(arg0) { + const ret = arg0.location; + return ret; + }, + __wbg_metaKey_665498d01ebfd062: function(arg0) { + const ret = arg0.metaKey; + return ret; + }, + __wbg_new_0c7403db6e782f19: function(arg0) { + const ret = new Uint8Array(arg0); + return ret; + }, + __wbg_new_227d7c05414eb861: function() { + const ret = new Error(); + return ret; + }, + __wbg_new_34d45cc8e36aaead: function() { + const ret = new Map(); + return ret; + }, + __wbg_new_5e360d2ff7b9e1c3: function(arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return ret; + }, + __wbg_new_682678e2f47e32bc: function() { + const ret = new Array(); + return ret; + }, + __wbg_new_aa8d0fa9762c29bd: function() { + const ret = new Object(); + return ret; + }, + __wbg_new_typed_323f37fd55ab048d: function(arg0, arg1) { + try { + var state0 = {a: arg0, b: arg1}; + var cb0 = (arg0, arg1) => { + const a = state0.a; + state0.a = 0; + try { + return wasm_bindgen__convert__closures_____invoke__hb0ba6117a7ec12e8(a, state0.b, arg0, arg1); + } finally { + state0.a = a; + } + }; + const ret = new Promise(cb0); + return ret; + } finally { + state0.a = 0; + } + }, + __wbg_new_with_byte_offset_and_length_01848e8d6a3d49ad: function(arg0, arg1, arg2) { + const ret = new Uint8Array(arg0, arg1 >>> 0, arg2 >>> 0); + return ret; + }, + __wbg_new_with_event_init_dict_5f4f1e5009457f42: function() { return handleError(function (arg0, arg1, arg2) { + const ret = new CustomEvent(getStringFromWasm0(arg0, arg1), arg2); + return ret; + }, arguments); }, + __wbg_next_0340c4ae324393c3: function() { return handleError(function (arg0) { + const ret = arg0.next(); + return ret; + }, arguments); }, + __wbg_next_7646edaa39458ef7: function(arg0) { + const ret = arg0.next; + return ret; + }, + __wbg_parentElement_d1271cca94202d1f: function(arg0) { + const ret = arg0.parentElement; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_parentNode_e94744054a57a837: function(arg0) { + const ret = arg0.parentNode; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_preventDefault_f55c01cb5fd2bcc0: function(arg0) { + arg0.preventDefault(); + }, + __wbg_prompt_3034b934fde6d338: function() { return handleError(function (arg0, arg1, arg2, arg3) { + const ret = arg1.prompt(getStringFromWasm0(arg2, arg3)); + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, arguments); }, + __wbg_prototypesetcall_a6b02eb00b0f4ce2: function(arg0, arg1, arg2) { + Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2); + }, + __wbg_querySelector_8d395ebd237ebd46: function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.querySelector(getStringFromWasm0(arg1, arg2)); + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, arguments); }, + __wbg_queueMicrotask_5d15a957e6aa920e: function(arg0) { + queueMicrotask(arg0); + }, + __wbg_queueMicrotask_f8819e5ffc402f36: function(arg0) { + const ret = arg0.queueMicrotask; + return ret; + }, + __wbg_register_blockquote_fd046c8c627399c8: function() { return handleError(function () { + register_blockquote(); + }, arguments); }, + __wbg_register_bold_2b13f7d8d32a68a6: function() { return handleError(function () { + register_bold(); + }, arguments); }, + __wbg_register_bullet_list_23d19bbb247b29b2: function() { return handleError(function () { + register_bullet_list(); + }, arguments); }, + __wbg_register_code_17538350657a84ff: function() { return handleError(function () { + register_code(); + }, arguments); }, + __wbg_register_code_block_67cb3f10a65d47b1: function() { return handleError(function () { + register_code_block(); + }, arguments); }, + __wbg_register_document_b09a29acea25aee7: function() { return handleError(function () { + register_document(); + }, arguments); }, + __wbg_register_dropcursor_3e92acfad1f63121: function() { return handleError(function () { + register_dropcursor(); + }, arguments); }, + __wbg_register_gapcursor_d7ccf87cc4edb016: function() { return handleError(function () { + register_gapcursor(); + }, arguments); }, + __wbg_register_hard_break_07ddb05349884964: function() { return handleError(function () { + register_hard_break(); + }, arguments); }, + __wbg_register_heading_e50200c58560edd7: function() { return handleError(function () { + register_heading(); + }, arguments); }, + __wbg_register_highlight_c4d2879cceafc399: function() { return handleError(function () { + register_highlight(); + }, arguments); }, + __wbg_register_history_198629931b125d1f: function() { return handleError(function () { + register_history(); + }, arguments); }, + __wbg_register_horizontal_rule_98d8c5150b1280b8: function() { return handleError(function () { + register_horizontal_rule(); + }, arguments); }, + __wbg_register_image_e7ab6b7e73c53a29: function() { return handleError(function () { + register_image(); + }, arguments); }, + __wbg_register_italic_5f4ba7f902484959: function() { return handleError(function () { + register_italic(); + }, arguments); }, + __wbg_register_link_22a39104d1bd5922: function() { return handleError(function () { + register_link(); + }, arguments); }, + __wbg_register_list_item_6a490bd22eebd93e: function() { return handleError(function () { + register_list_item(); + }, arguments); }, + __wbg_register_ordered_list_f34144c7789a446c: function() { return handleError(function () { + register_ordered_list(); + }, arguments); }, + __wbg_register_paragraph_81a3d65f48231543: function() { return handleError(function () { + register_paragraph(); + }, arguments); }, + __wbg_register_placeholder_fe16746e327b8095: function() { return handleError(function () { + register_placeholder(); + }, arguments); }, + __wbg_register_strike_cd23a4801fbee3aa: function() { return handleError(function () { + register_strike(); + }, arguments); }, + __wbg_register_task_item_f3bd8792f78774ac: function() { return handleError(function () { + register_task_item(); + }, arguments); }, + __wbg_register_task_list_6148af4bfed5c47e: function() { return handleError(function () { + register_task_list(); + }, arguments); }, + __wbg_register_text_align_a0b3ac6d1515da18: function() { return handleError(function () { + register_text_align(); + }, arguments); }, + __wbg_register_text_b7263f896f7b1a7c: function() { return handleError(function () { + register_text(); + }, arguments); }, + __wbg_register_text_style_61ece26a92563bc1: function() { return handleError(function () { + register_text_style(); + }, arguments); }, + __wbg_register_underline_f8cd359f982028f4: function() { return handleError(function () { + register_underline(); + }, arguments); }, + __wbg_register_youtube_fd5d6301c55e98d7: function() { return handleError(function () { + register_youtube(); + }, arguments); }, + __wbg_removeAttribute_c75ac657c944b3f1: function() { return handleError(function (arg0, arg1, arg2) { + arg0.removeAttribute(getStringFromWasm0(arg1, arg2)); + }, arguments); }, + __wbg_removeChild_172df530ec85cc8a: function() { return handleError(function (arg0, arg1) { + const ret = arg0.removeChild(arg1); + return ret; + }, arguments); }, + __wbg_removeEventListener_7bdf07404d9b24bd: function() { return handleError(function (arg0, arg1, arg2, arg3) { + arg0.removeEventListener(getStringFromWasm0(arg1, arg2), arg3); + }, arguments); }, + __wbg_removeProperty_af5e61d737797fcc: function() { return handleError(function (arg0, arg1, arg2, arg3) { + const ret = arg1.removeProperty(getStringFromWasm0(arg2, arg3)); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, arguments); }, + __wbg_remove_48cb93cf7a6c4260: function(arg0) { + arg0.remove(); + }, + __wbg_remove_9ffcfa2a5664fa43: function(arg0) { + arg0.remove(); + }, + __wbg_resolve_e6c466bc1052f16c: function(arg0) { + const ret = Promise.resolve(arg0); + return ret; + }, + __wbg_respond_008ca9525ae22847: function() { return handleError(function (arg0, arg1) { + arg0.respond(arg1 >>> 0); + }, arguments); }, + __wbg_run_0b0a622deae25fda: function(arg0, arg1, arg2) { + try { + var state0 = {a: arg1, b: arg2}; + var cb0 = () => { + const a = state0.a; + state0.a = 0; + try { + return wasm_bindgen__convert__closures_____invoke__h60e57afd955e8441(a, state0.b, ); + } finally { + state0.a = a; + } + }; + const ret = arg0.run(cb0); + return ret; + } finally { + state0.a = 0; + } + }, + __wbg_scrollHeight_5fe8cbb97ae906d8: function(arg0) { + const ret = arg0.scrollHeight; + return ret; + }, + __wbg_scrollTop_f548101d48000fe9: function(arg0) { + const ret = arg0.scrollTop; + return ret; + }, + __wbg_search_ceee70e1153af3ec: function() { return handleError(function (arg0, arg1) { + const ret = arg1.search; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, arguments); }, + __wbg_setAttribute_6fde4098d274155c: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { + arg0.setAttribute(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4)); + }, arguments); }, + __wbg_setItem_e6399d3faae141dc: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { + arg0.setItem(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4)); + }, arguments); }, + __wbg_setProperty_0d903d23a71dfe70: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { + arg0.setProperty(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4)); + }, arguments); }, + __wbg_set_022bee52d0b05b19: function() { return handleError(function (arg0, arg1, arg2) { + const ret = Reflect.set(arg0, arg1, arg2); + return ret; + }, arguments); }, + __wbg_set_3bf1de9fab0cd644: function(arg0, arg1, arg2) { + arg0[arg1 >>> 0] = arg2; + }, + __wbg_set_3d484eb794afec82: function(arg0, arg1, arg2) { + arg0.set(getArrayU8FromWasm0(arg1, arg2)); + }, + __wbg_set_6be42768c690e380: function(arg0, arg1, arg2) { + arg0[arg1] = arg2; + }, + __wbg_set_detail_68bec5c91196ba57: function(arg0, arg1) { + arg0.detail = arg1; + }, + __wbg_set_fde2cec06c23692b: function(arg0, arg1, arg2) { + const ret = arg0.set(arg1, arg2); + return ret; + }, + __wbg_set_innerHTML_a3c82996073b31ea: function(arg0, arg1, arg2) { + arg0.innerHTML = getStringFromWasm0(arg1, arg2); + }, + __wbg_set_nodeValue_f39ed00fc286b285: function(arg0, arg1, arg2) { + arg0.nodeValue = arg1 === 0 ? undefined : getStringFromWasm0(arg1, arg2); + }, + __wbg_set_scrollTop_e931da7f2ad87c86: function(arg0, arg1) { + arg0.scrollTop = arg1; + }, + __wbg_stack_3b0d974bbf31e44f: function(arg0, arg1) { + const ret = arg1.stack; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg_static_accessor_CREATE_TASK_f3ab6a6954bda493: function() { + const ret = typeof console === 'undefined' ? null : console?.createTask; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_static_accessor_GLOBAL_8cfadc87a297ca02: function() { + const ret = typeof global === 'undefined' ? null : global; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_static_accessor_GLOBAL_THIS_602256ae5c8f42cf: function() { + const ret = typeof globalThis === 'undefined' ? null : globalThis; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_static_accessor_SELF_e445c1c7484aecc3: function() { + const ret = typeof self === 'undefined' ? null : self; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_static_accessor_WINDOW_f20e8576ef1e0f17: function() { + const ret = typeof window === 'undefined' ? null : window; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_stopPropagation_e088fca8231e68c4: function(arg0) { + arg0.stopPropagation(); + }, + __wbg_style_c331a9f6564f8f62: function(arg0) { + const ret = arg0.style; + return ret; + }, + __wbg_tagName_a6d6785a7c70fca2: function(arg0, arg1) { + const ret = arg1.tagName; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg_target_6d97e221d11b71b6: function(arg0) { + const ret = arg0.target; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_then_8e16ee11f05e4827: function(arg0, arg1) { + const ret = arg0.then(arg1); + return ret; + }, + __wbg_top_158f7c4dd1427771: function(arg0) { + const ret = arg0.top; + return ret; + }, + __wbg_value_6079dd28568d83c9: function(arg0, arg1) { + const ret = arg1.value; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }, + __wbg_value_ee3a06f4579184fa: function(arg0) { + const ret = arg0.value; + return ret; + }, + __wbg_view_701664ffb3b1ce67: function(arg0) { + const ret = arg0.view; + return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); + }, + __wbg_warn_3cc416af27dbdc02: function(arg0) { + console.warn(arg0); + }, + __wbg_warn_bd0f407277b102f4: function(arg0, arg1, arg2) { + console.warn(arg0, arg1, arg2); + }, + __wbg_width_9673a519d7bd5a6a: function(arg0) { + const ret = arg0.width; + return ret; + }, + __wbindgen_cast_0000000000000001: function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 1204, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h2593b18d2d6f8a75); + return ret; + }, + __wbindgen_cast_0000000000000002: function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 1295, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h36e788bd1cd1f0f7); + return ret; + }, + __wbindgen_cast_0000000000000003: function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 949, ret: Unit, inner_ret: Some(Unit) }, mutable: false }) -> Externref`. + const ret = makeClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h1ea2b89742286ce6); + return ret; + }, + __wbindgen_cast_0000000000000004: function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1130, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h03deb55668e1377f); + return ret; + }, + __wbindgen_cast_0000000000000005: function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1206, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h837fba73fce77300); + return ret; + }, + __wbindgen_cast_0000000000000006: function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1143, ret: Unit, inner_ret: Some(Unit) }, mutable: false }) -> Externref`. + const ret = makeClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hd17f30facfdd737f); + return ret; + }, + __wbindgen_cast_0000000000000007: function(arg0, arg1) { + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1205, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hf726e22cfd1ee0a9); + return ret; + }, + __wbindgen_cast_0000000000000008: function(arg0) { + // Cast intrinsic for `F64 -> Externref`. + const ret = arg0; + return ret; + }, + __wbindgen_cast_0000000000000009: function(arg0) { + // Cast intrinsic for `I64 -> Externref`. + const ret = arg0; + return ret; + }, + __wbindgen_cast_000000000000000a: function(arg0, arg1) { + // Cast intrinsic for `Ref(String) -> Externref`. + const ret = getStringFromWasm0(arg0, arg1); + return ret; + }, + __wbindgen_cast_000000000000000b: function(arg0) { + // Cast intrinsic for `U64 -> Externref`. + const ret = BigInt.asUintN(64, arg0); + return ret; + }, + __wbindgen_init_externref_table: function() { + const table = wasm.__wbindgen_externrefs; + const offset = table.grow(4); + table.set(0, undefined); + table.set(offset + 0, undefined); + table.set(offset + 1, null); + table.set(offset + 2, true); + table.set(offset + 3, false); + }, + }; + return { + __proto__: null, + "./mnote-leptos-tiptap-spike-island_bg.js": import0, + "./snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js": import1, + "./snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js": import2, + }; +} + +function wasm_bindgen__convert__closures_____invoke__hd17f30facfdd737f(arg0, arg1) { + wasm.wasm_bindgen__convert__closures_____invoke__hd17f30facfdd737f(arg0, arg1); +} + +function wasm_bindgen__convert__closures_____invoke__hf726e22cfd1ee0a9(arg0, arg1) { + wasm.wasm_bindgen__convert__closures_____invoke__hf726e22cfd1ee0a9(arg0, arg1); +} + +function wasm_bindgen__convert__closures_____invoke__h60e57afd955e8441(arg0, arg1) { + const ret = wasm.wasm_bindgen__convert__closures_____invoke__h60e57afd955e8441(arg0, arg1); + return ret !== 0; +} + +function wasm_bindgen__convert__closures_____invoke__h2593b18d2d6f8a75(arg0, arg1, arg2) { + wasm.wasm_bindgen__convert__closures_____invoke__h2593b18d2d6f8a75(arg0, arg1, arg2); +} + +function wasm_bindgen__convert__closures_____invoke__h1ea2b89742286ce6(arg0, arg1, arg2) { + wasm.wasm_bindgen__convert__closures_____invoke__h1ea2b89742286ce6(arg0, arg1, arg2); +} + +function wasm_bindgen__convert__closures_____invoke__h03deb55668e1377f(arg0, arg1, arg2) { + wasm.wasm_bindgen__convert__closures_____invoke__h03deb55668e1377f(arg0, arg1, arg2); +} + +function wasm_bindgen__convert__closures_____invoke__h837fba73fce77300(arg0, arg1, arg2) { + wasm.wasm_bindgen__convert__closures_____invoke__h837fba73fce77300(arg0, arg1, arg2); +} + +function wasm_bindgen__convert__closures_____invoke__h36e788bd1cd1f0f7(arg0, arg1, arg2) { + const ret = wasm.wasm_bindgen__convert__closures_____invoke__h36e788bd1cd1f0f7(arg0, arg1, arg2); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } +} + +function wasm_bindgen__convert__closures_____invoke__hb0ba6117a7ec12e8(arg0, arg1, arg2, arg3) { + wasm.wasm_bindgen__convert__closures_____invoke__hb0ba6117a7ec12e8(arg0, arg1, arg2, arg3); +} + + +const __wbindgen_enum_ReadableStreamType = ["bytes"]; +const IntoUnderlyingByteSourceFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_intounderlyingbytesource_free(ptr >>> 0, 1)); +const IntoUnderlyingSinkFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_intounderlyingsink_free(ptr >>> 0, 1)); +const IntoUnderlyingSourceFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_intounderlyingsource_free(ptr >>> 0, 1)); + +function addToExternrefTable0(obj) { + const idx = wasm.__externref_table_alloc(); + wasm.__wbindgen_externrefs.set(idx, obj); + return idx; +} + +const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(state => wasm.__wbindgen_destroy_closure(state.a, state.b)); + +function debugString(val) { + // primitive types + const type = typeof val; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; + } + if (type == 'string') { + return `"${val}"`; + } + if (type == 'symbol') { + const description = val.description; + if (description == null) { + return 'Symbol'; + } else { + return `Symbol(${description})`; + } + } + if (type == 'function') { + const name = val.name; + if (typeof name == 'string' && name.length > 0) { + return `Function(${name})`; + } else { + return 'Function'; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = '['; + if (length > 0) { + debug += debugString(val[0]); + } + for(let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); + } + debug += ']'; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches && builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == 'Object') { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return 'Object(' + JSON.stringify(val) + ')'; + } catch (_) { + return 'Object'; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; +} + +function getArrayU8FromWasm0(ptr, len) { + ptr = ptr >>> 0; + return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len); +} + +let cachedDataViewMemory0 = null; +function getDataViewMemory0() { + if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { + cachedDataViewMemory0 = new DataView(wasm.memory.buffer); + } + return cachedDataViewMemory0; +} + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return decodeText(ptr, len); +} + +let cachedUint8ArrayMemory0 = null; +function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + const idx = addToExternrefTable0(e); + wasm.__wbindgen_exn_store(idx); + } +} + +function isLikeNone(x) { + return x === undefined || x === null; +} + +function makeClosure(arg0, arg1, f) { + const state = { a: arg0, b: arg1, cnt: 1 }; + const real = (...args) => { + + // First up with a closure we increment the internal reference + // count. This ensures that the Rust closure environment won't + // be deallocated while we're invoking it. + state.cnt++; + try { + return f(state.a, state.b, ...args); + } finally { + real._wbg_cb_unref(); + } + }; + real._wbg_cb_unref = () => { + if (--state.cnt === 0) { + wasm.__wbindgen_destroy_closure(state.a, state.b); + state.a = 0; + CLOSURE_DTORS.unregister(state); + } + }; + CLOSURE_DTORS.register(real, state, state); + return real; +} + +function makeMutClosure(arg0, arg1, f) { + const state = { a: arg0, b: arg1, cnt: 1 }; + const real = (...args) => { + + // First up with a closure we increment the internal reference + // count. This ensures that the Rust closure environment won't + // be deallocated while we're invoking it. + state.cnt++; + const a = state.a; + state.a = 0; + try { + return f(a, state.b, ...args); + } finally { + state.a = a; + real._wbg_cb_unref(); + } + }; + real._wbg_cb_unref = () => { + if (--state.cnt === 0) { + wasm.__wbindgen_destroy_closure(state.a, state.b); + state.a = 0; + CLOSURE_DTORS.unregister(state); + } + }; + CLOSURE_DTORS.register(real, state, state); + return real; +} + +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = cachedTextEncoder.encodeInto(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +function takeFromExternrefTable0(idx) { + const value = wasm.__wbindgen_externrefs.get(idx); + wasm.__externref_table_dealloc(idx); + return value; +} + +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); +cachedTextDecoder.decode(); +const MAX_SAFARI_DECODE_BYTES = 2146435072; +let numBytesDecoded = 0; +function decodeText(ptr, len) { + numBytesDecoded += len; + if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) { + cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + cachedTextDecoder.decode(); + numBytesDecoded = len; + } + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); +} + +const cachedTextEncoder = new TextEncoder(); + +if (!('encodeInto' in cachedTextEncoder)) { + cachedTextEncoder.encodeInto = function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; + }; +} + +let WASM_VECTOR_LEN = 0; + +let wasmModule, wasm; +function __wbg_finalize_init(instance, module) { + wasm = instance.exports; + wasmModule = module; + cachedDataViewMemory0 = null; + cachedUint8ArrayMemory0 = null; + wasm.__wbindgen_start(); + return wasm; +} + +async function __wbg_load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + } catch (e) { + const validResponse = module.ok && expectedResponseType(module.type); + + if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + + } else { throw e; } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + } else { + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + } else { + return instance; + } + } + + function expectedResponseType(type) { + switch (type) { + case 'basic': case 'cors': case 'default': return true; + } + return false; + } +} + +function initSync(module) { + if (wasm !== undefined) return wasm; + + + if (module !== undefined) { + if (Object.getPrototypeOf(module) === Object.prototype) { + ({module} = module) + } else { + console.warn('using deprecated parameters for `initSync()`; pass a single object instead') + } + } + + const imports = __wbg_get_imports(); + if (!(module instanceof WebAssembly.Module)) { + module = new WebAssembly.Module(module); + } + const instance = new WebAssembly.Instance(module, imports); + return __wbg_finalize_init(instance, module); +} + +async function __wbg_init(module_or_path) { + if (wasm !== undefined) return wasm; + + + if (module_or_path !== undefined) { + if (Object.getPrototypeOf(module_or_path) === Object.prototype) { + ({module_or_path} = module_or_path) + } else { + console.warn('using deprecated parameters for the initialization function; pass a single object instead') + } + } + + if (module_or_path === undefined) { + module_or_path = new URL('mnote-leptos-tiptap-spike-island_bg.wasm', import.meta.url); + } + const imports = __wbg_get_imports(); + + if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { + module_or_path = fetch(module_or_path); + } + + const { instance, module } = await __wbg_load(await module_or_path, imports); + + return __wbg_finalize_init(instance, module); +} + +export { initSync, __wbg_init as default }; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island_bg.wasm b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island_bg.wasm new file mode 100644 index 00000000..2909d732 Binary files /dev/null and b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island_bg.wasm differ diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island_bg.wasm.d.ts b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island_bg.wasm.d.ts new file mode 100644 index 00000000..c0f06dd9 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/mnote-leptos-tiptap-spike-island_bg.wasm.d.ts @@ -0,0 +1,36 @@ +/* tslint:disable */ +/* eslint-disable */ +export const memory: WebAssembly.Memory; +export const mount: (a: any, b: any) => [number, number, number]; +export const unmount: (a: number) => [number, number]; +export const __wbg_intounderlyingbytesource_free: (a: number, b: number) => void; +export const intounderlyingbytesource_type: (a: number) => number; +export const intounderlyingbytesource_autoAllocateChunkSize: (a: number) => number; +export const intounderlyingbytesource_start: (a: number, b: any) => void; +export const intounderlyingbytesource_pull: (a: number, b: any) => any; +export const intounderlyingbytesource_cancel: (a: number) => void; +export const __wbg_intounderlyingsink_free: (a: number, b: number) => void; +export const intounderlyingsink_write: (a: number, b: any) => any; +export const intounderlyingsink_close: (a: number) => any; +export const intounderlyingsink_abort: (a: number, b: any) => any; +export const __wbg_intounderlyingsource_free: (a: number, b: number) => void; +export const intounderlyingsource_pull: (a: number, b: any) => any; +export const intounderlyingsource_cancel: (a: number) => void; +export const wasm_bindgen__convert__closures_____invoke__h36e788bd1cd1f0f7: (a: number, b: number, c: any) => [number, number]; +export const wasm_bindgen__convert__closures_____invoke__hb0ba6117a7ec12e8: (a: number, b: number, c: any, d: any) => void; +export const wasm_bindgen__convert__closures_____invoke__h2593b18d2d6f8a75: (a: number, b: number, c: any) => void; +export const wasm_bindgen__convert__closures_____invoke__h1ea2b89742286ce6: (a: number, b: number, c: any) => void; +export const wasm_bindgen__convert__closures_____invoke__h03deb55668e1377f: (a: number, b: number, c: any) => void; +export const wasm_bindgen__convert__closures_____invoke__h837fba73fce77300: (a: number, b: number, c: any) => void; +export const wasm_bindgen__convert__closures_____invoke__h60e57afd955e8441: (a: number, b: number) => number; +export const wasm_bindgen__convert__closures_____invoke__hd17f30facfdd737f: (a: number, b: number) => void; +export const wasm_bindgen__convert__closures_____invoke__hf726e22cfd1ee0a9: (a: number, b: number) => void; +export const __wbindgen_malloc: (a: number, b: number) => number; +export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number; +export const __externref_table_alloc: () => number; +export const __wbindgen_externrefs: WebAssembly.Table; +export const __wbindgen_exn_store: (a: number) => void; +export const __wbindgen_free: (a: number, b: number, c: number) => void; +export const __wbindgen_destroy_closure: (a: number, b: number) => void; +export const __externref_table_dealloc: (a: number) => void; +export const __wbindgen_start: () => void; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js new file mode 100644 index 00000000..0726559d --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/bridge_runtime.js @@ -0,0 +1,91 @@ +var La=Object.defineProperty;var ae=(n,e)=>{for(var t in e)La(n,t,{get:e[t],enumerable:!0})};var bo="__LEPTOS_TIPTAP_BRIDGE__";function xo(){return{}}function So(){let n=globalThis,e=n[bo];if(e!=null)return e;let t={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return n[bo]=t,t}var ro={};ae(ro,{CommandManager:()=>ot,Editor:()=>Wi,Extension:()=>ue,InputRule:()=>$e,Mark:()=>Yn,Node:()=>Ki,NodePos:()=>er,NodeView:()=>Ji,PasteRule:()=>Ot,Tracker:()=>Hi,callOrReturn:()=>N,canInsertNode:()=>dp,combineTransactionSteps:()=>Cf,createChainableState:()=>nn,createDocument:()=>Zn,createNodeFromContent:()=>Nt,createStyleTag:()=>ka,defaultBlockAt:()=>na,deleteProps:()=>$i,elementFromString:()=>Et,escapeForRegEx:()=>up,extensions:()=>np,findChildren:()=>wf,findChildrenInRange:()=>Mf,findDuplicates:()=>Yl,findParentNode:()=>an,findParentNodeClosestToPos:()=>ra,fromString:()=>Jl,generateHTML:()=>Ef,generateJSON:()=>Of,generateText:()=>Tf,getAttributes:()=>oa,getAttributesFromExtensions:()=>qi,getChangedRanges:()=>Df,getDebugJSON:()=>la,getExtensionField:()=>x,getHTMLFromFragment:()=>on,getMarkAttributes:()=>eo,getMarkRange:()=>rr,getMarkType:()=>De,getMarksBetween:()=>no,getNodeAtPosition:()=>Af,getNodeAttributes:()=>ia,getNodeType:()=>F,getRenderedAttributes:()=>Gn,getSchema:()=>ir,getSchemaByResolvedExtensions:()=>Gi,getSchemaTypeByName:()=>Un,getSchemaTypeNameByName:()=>ln,getSplittedAttributes:()=>en,getText:()=>to,getTextBetween:()=>Yi,getTextContentFromNodes:()=>Hl,getTextSerializersFromSchema:()=>nr,injectExtensionAttributesToParseRule:()=>Fi,inputRulesPlugin:()=>ql,isActive:()=>aa,isAtEndOfNode:()=>vf,isAtStartOfNode:()=>Rf,isEmptyObject:()=>Kl,isExtensionRulesEnabled:()=>Li,isFunction:()=>Ui,isList:()=>ji,isMacOS:()=>Qi,isMarkActive:()=>Qn,isNodeActive:()=>Dt,isNodeEmpty:()=>or,isNodeSelection:()=>If,isNumber:()=>Ul,isPlainObject:()=>Qt,isRegExp:()=>tr,isSafari:()=>Ql,isString:()=>fp,isTextSelection:()=>Xi,isiOS:()=>Tt,markInputRule:()=>ip,markPasteRule:()=>cp,mergeAttributes:()=>Wl,mergeDeep:()=>sn,minMax:()=>be,nodeInputRule:()=>op,nodePasteRule:()=>pp,objectIncludes:()=>tn,pasteRulesPlugin:()=>Gl,posToDOMRect:()=>Pf,removeDuplicates:()=>sa,resolveFocusPosition:()=>Zi,rewriteUnknownContent:()=>_f,selectionToInsertionEnd:()=>ta,splitExtensions:()=>rn,textInputRule:()=>lp,textPasteRule:()=>hp,textblockTypeInputRule:()=>sp,wrappingInputRule:()=>ap});var vr={};ae(vr,{AllSelection:()=>q,EditorState:()=>jt,NodeSelection:()=>S,Plugin:()=>P,PluginKey:()=>te,Selection:()=>E,SelectionRange:()=>Ye,TextSelection:()=>T,Transaction:()=>bn});function H(n){this.content=n}H.prototype={constructor:H,find:function(n){for(var e=0;e>1}};H.from=function(n){if(n instanceof H)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new H(e)};var fr=H;function vo(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),o=e.child(r);if(i==o){t+=i.nodeSize;continue}if(!i.sameMarkup(o))return t;if(i.isText&&i.text!=o.text){for(let s=0;i.text[s]==o.text[s];s++)t++;return t}if(i.content.size||o.content.size){let s=vo(i.content,o.content,t+1);if(s!=null)return s}t+=i.nodeSize}}function Ro(n,e,t,r){for(let i=n.childCount,o=e.childCount;;){if(i==0||o==0)return i==o?null:{a:t,b:r};let s=n.child(--i),l=e.child(--o),a=s.nodeSize;if(s==l){t-=a,r-=a;continue}if(!s.sameMarkup(l))return{a:t,b:r};if(s.isText&&s.text!=l.text){let c=0,d=Math.min(s.text.length,l.text.length);for(;ce&&r(a,i+l,o||null,s)!==!1&&a.content.size){let d=l+1;a.nodesBetween(Math.max(0,e-d),Math.min(a.content.size,t-d),r,i+d)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let o="",s=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(s?s=!1:o+=r),o+=c},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),o=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),o=1);oe)for(let o=0,s=0;se&&((st)&&(l.isText?l=l.cut(Math.max(0,e-s),Math.min(l.text.length,t-s)):l=l.cut(Math.max(0,e-s-1),Math.min(l.content.size,t-s-1))),r.push(l),i+=l.nodeSize),s=a}return new n(r,i)}cutByIndex(e,t){return e==t?n.empty:e==0&&t==this.content.length?this:new n(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),o=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new n(i,o)}addToStart(e){return new n([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new n(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),o=r+i.nodeSize;if(o>=e)return o==e?un(t+1,o):un(t,r);r=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return n.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return new n(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return n.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(o)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};D.none=[];var ve=class extends Error{},b=class n{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Po(this.content,e+this.openStart,t);return r&&new n(r,this.openStart,this.openEnd)}removeBetween(e,t){return new n(Io(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return n.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new n(k.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let o=e.firstChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.firstChild)r++;for(let o=e.lastChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.lastChild)i++;return new n(e,r,i)}};b.empty=new b(k.empty,0,0);function Io(n,e,t){let{index:r,offset:i}=n.findIndex(e),o=n.maybeChild(r),{index:s,offset:l}=n.findIndex(t);if(i==e||o.isText){if(l!=t&&!n.child(s).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=s)throw new RangeError("Removing non-flat range");return n.replaceChild(r,o.copy(Io(o.content,e-i-1,t-i-1)))}function Po(n,e,t,r){let{index:i,offset:o}=n.findIndex(e),s=n.maybeChild(i);if(o==e||s.isText)return r&&!r.canReplace(i,i,t)?null:n.cut(0,e).append(t).append(n.cut(e));let l=Po(s.content,e-o-1,t,s);return l&&n.replaceChild(i,s.copy(l))}function Va(n,e,t){if(t.openStart>n.depth)throw new ve("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new ve("Inconsistent open depths");return _o(n,e,t,0)}function _o(n,e,t,r){let i=n.index(r),o=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function vt(n,e,t,r){let i=(e||n).node(t),o=0,s=e?e.index(t):i.childCount;n&&(o=n.index(t),n.depth>t?o++:n.textOffset&&(je(n.nodeAfter,r),o++));for(let l=o;li&&mr(n,e,i+1),s=r.depth>i&&mr(t,r,i+1),l=[];return vt(null,n,i,l),o&&s&&e.index(i)==t.index(i)?(Bo(o,s),je(We(o,zo(n,e,t,r,i+1)),l)):(o&&je(We(o,hn(n,e,i+1)),l),vt(e,t,i,l),s&&je(We(s,hn(t,r,i+1)),l)),vt(r,null,i,l),new k(l)}function hn(n,e,t){let r=[];if(vt(null,n,t,r),n.depth>t){let i=mr(n,e,t+1);je(We(i,hn(n,e,t+1)),r)}return vt(e,null,t,r),new k(r)}function $a(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let o=t-1;o>=0;o--)i=e.node(o).copy(k.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}var It=class n{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let o=0;o0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Re(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,o=t;for(let s=e;;){let{index:l,offset:a}=s.content.findIndex(o),c=o-a;if(r.push(s,l,i+a),!c||(s=s.child(l),s.isText))break;o=c-1,i+=a+1}return new n(t,r,o)}static resolveCached(e,t){let r=Co.get(e);if(r)for(let o=0;oe&&this.nodesBetween(e,t,o=>(r.isInSet(o.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Fo(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=k.empty,i=0,o=r.childCount){let s=this.contentMatchAt(e).matchFragment(r,i,o),l=s&&s.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=k.fromJSON(e,t.content),o=e.nodeType(t.type).create(t.attrs,i,r);return o.type.checkAttrs(o.attrs),o}};Y.prototype.text=void 0;var yr=class n extends Y{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Fo(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new n(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new n(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function Fo(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}var Ie=class n{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new kr(e,t);if(r.next==null)return n.empty;let i=Lo(r);r.next&&r.err("Unexpected trailing text");let o=Ya(Ga(i));return Xa(o,r),o}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let o=i+(r.validEnd?"*":" ")+" ";for(let s=0;s"+e.indexOf(r.next[s].next);return o}).join(` +`)}};Ie.empty=new Ie(!0);var kr=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}};function Lo(n){let e=[];do e.push(Ka(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Ka(n){let e=[];do e.push(Ja(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Ja(n){let e=Ua(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=Ha(n,e);else break;return e}function wo(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function Ha(n,e){let t=wo(n),r=t;return n.eat(",")&&(n.next!="}"?r=wo(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function qa(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let o in t){let s=t[o];s.isInGroup(e)&&i.push(s)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function Ua(n){if(n.eat("(")){let e=Lo(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=qa(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Ga(n){let e=[[]];return i(o(n,0),t()),e;function t(){return e.push([])-1}function r(s,l,a){let c={term:a,to:l};return e[s].push(c),c}function i(s,l){s.forEach(a=>a.to=l)}function o(s,l){if(s.type=="choice")return s.exprs.reduce((a,c)=>a.concat(o(c,l)),[]);if(s.type=="seq")for(let a=0;;a++){let c=o(s.exprs[a],l);if(a==s.exprs.length-1)return c;i(c,l=t())}else if(s.type=="star"){let a=t();return r(l,a),i(o(s.expr,a),a),[r(a)]}else if(s.type=="plus"){let a=t();return i(o(s.expr,l),a),i(o(s.expr,a),a),[r(a)]}else{if(s.type=="opt")return[r(l)].concat(o(s.expr,l));if(s.type=="range"){let a=l;for(let c=0;c{n[s].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let d=0;d{c||i.push([l,c=[]]),c.indexOf(d)==-1&&c.push(d)})})});let o=e[r.join(",")]=new Ie(r.indexOf(n.length-1)>-1);for(let s=0;s-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:jo(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Y(this,this.computeAttrs(e),k.from(t),D.setFrom(r))}createChecked(e=null,t,r){return t=k.from(t),this.checkContent(t),new Y(this,this.computeAttrs(e),t,D.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=k.from(t),t.size){let s=this.contentMatch.fillBefore(t);if(!s)return null;t=s.append(t)}let i=this.contentMatch.matchFragment(t),o=i&&i.fillBefore(k.empty,!0);return o?new Y(this,e,t.append(o),D.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[o]=new n(o,t,s));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let o in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Za(n,e,t){let r=t.split("|");return i=>{let o=i===null?"null":typeof i;if(r.indexOf(o)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${o}`)}}var br=class{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Za(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}},at=class n{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Ko(e,i.attrs),this.excluded=null;let o=$o(this.attrs);this.instance=o?new D(this,o):null}create(e=null){return!e&&this.instance?this.instance:new D(this,jo(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((o,s)=>r[o]=new n(o,i++,t,s)),r}removeFromSet(e){for(var t=0;t-1}},ct=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=fr.from(e.nodes),t.marks=fr.from(e.marks||{}),this.nodes=Pt.compile(this.spec.nodes,this),this.marks=at.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let o=this.nodes[i],s=o.spec.content||"",l=o.spec.marks;if(o.contentMatch=r[s]||(r[s]=Ie.parse(s,this.nodes)),o.inlineContent=o.contentMatch.inlineContent,o.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!o.isInline||!o.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=o}o.markSet=l=="_"?null:l?Eo(this,l.split(" ")):l==""||!o.inlineContent?[]:null}for(let i in this.marks){let o=this.marks[i],s=o.spec.excludes;o.excluded=s==null?[o]:s==""?[]:Eo(this,s.split(" "))}this.nodeFromJSON=i=>Y.fromJSON(this,i),this.markFromJSON=i=>D.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Pt){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new yr(r,r.defaultAttrs,e,D.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}};function Eo(n,e){let t=[];for(let r=0;r-1)&&t.push(s=a)}if(!s)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Qa(n){return n.tag!=null}function ec(n){return n.style!=null}var ce=class n{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Qa(i))this.tags.push(i);else if(ec(i)){let o=/[^=]*/.exec(i.style)[0];r.indexOf(o)<0&&r.push(o),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let o=e.nodes[i.node];return o.contentMatch.matchType(o)})}parse(e,t={}){let r=new mn(this,t,!1);return r.addAll(e,D.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new mn(this,t,!0);return r.addAll(e,D.none,t.from,t.to),b.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(s.getAttrs){let a=s.getAttrs(t);if(a===!1)continue;s.attrs=a||void 0}return s}}}static schemaRules(e){let t=[];function r(i){let o=i.priority==null?50:i.priority,s=0;for(;s{r(s=To(s)),s.mark||s.ignore||s.clearMark||(s.mark=i)})}for(let i in e.nodes){let o=e.nodes[i].spec.parseDOM;o&&o.forEach(s=>{r(s=To(s)),s.node||s.ignore||s.mark||(s.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new n(e,n.schemaRules(e)))}},Jo={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},tc={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Ho={ol:!0,ul:!0},_t=1,xr=2,Rt=4;function Oo(n,e,t){return e!=null?(e?_t:0)|(e==="full"?xr:0):n&&n.whitespace=="pre"?_t|xr:t&~Rt}var lt=class{constructor(e,t,r,i,o,s){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=s,this.content=[],this.activeMarks=D.none,this.match=o||(s&Rt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(k.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&_t)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let o=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=o.withText(o.text.slice(0,o.text.length-i[0].length))}}let t=k.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(k.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Jo.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},mn=class{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,o,s=Oo(null,t.preserveWhitespace,0)|(r?Rt:0);i?o=new lt(i.type,i.attrs,D.none,!0,t.topMatch||i.type.contentMatch,s):r?o=new lt(null,null,D.none,!0,null,s):o=new lt(e.schema.topNodeType,null,D.none,!0,null,s),this.nodes=[o],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,o=i.options&xr?"full":this.localPreserveWS||(i.options&_t)>0,{schema:s}=this.parser;if(o==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(o)if(o==="full")r=r.replace(/\r\n?/g,` +`);else if(s.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(s.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let o,s;if(t.node)if(s=this.parser.schema.nodes[t.node],s.isLeaf)this.insertNode(s.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(s,t.attrs||null,r,t.preserveWhitespace);a&&(o=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(s&&s.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}o&&this.sync(l)&&this.open--}addAll(e,t,r,i){let o=r||0;for(let s=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];s!=l;s=s.nextSibling,++o)this.findAtPoint(e,o),this.addDOM(s,t);this.findAtPoint(e,o)}findPlace(e,t,r){let i,o;for(let s=this.open,l=0;s>=0;s--){let a=this.nodes[s],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,o=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(o);for(let s=0;s(s.type?s.type.allowsMarkType(c.type):No(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new lt(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=_t)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(i?0:1),s=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=o;a--)if(s(l-1,a))return!0;return!1}else{let d=a>0||a==0&&i?this.nodes[a].type:r&&a>=o?r.node(a-o).type:null;if(!d||d.name!=c&&!d.isInGroup(c))return!1;a--}}return!0};return s(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}};function nc(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Ho.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function rc(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function To(n){let e={};for(let t in n)e[t]=n[t];return e}function No(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let o=[],s=l=>{o.push(l);for(let a=0;a{if(o.length||s.marks.length){let l=0,a=0;for(;l=0;i--){let o=this.serializeMark(e.marks[i],e.isInline,t);o&&((o.contentDOM||o.dom).appendChild(r),r=o.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&fn(hr(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return fn(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new n(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=Do(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return Do(e.marks)}};function Do(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function hr(n){return n.document||window.document}var Ao=new WeakMap;function ic(n){let e=Ao.get(n);return e===void 0&&Ao.set(n,e=oc(n)),e}function oc(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let s=i.indexOf(" ");s>0&&(t=i.slice(0,s),i=i.slice(s+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],d=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){d=2;for(let u in c)if(c[u]!=null){let f=u.indexOf(" ");f>0?a.setAttributeNS(u.slice(0,f),u.slice(f+1),c[u]):u=="style"&&a.style?a.style.cssText=c[u]:a.setAttribute(u,c[u])}}for(let u=d;ud)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else{let{dom:p,contentDOM:h}=fn(n,f,t,r);if(a.appendChild(p),h){if(l)throw new RangeError("Multiple content holes");l=h}}}return{dom:a,contentDOM:l}}var Go=65535,Yo=Math.pow(2,16);function sc(n,e){return n+e*Yo}function qo(n){return n&Go}function lc(n){return(n-(n&Go))/Yo}var Xo=1,Zo=2,gn=4,Qo=8,dt=class{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&Qo)>0}get deletedBefore(){return(this.delInfo&(Xo|gn))>0}get deletedAfter(){return(this.delInfo&(Zo|gn))>0}get deletedAcross(){return(this.delInfo&gn)>0}},he=class n{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&n.empty)return n.empty}recover(e){let t=0,r=qo(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+o],d=this.ranges[l+s],u=a+c;if(e<=u){let f=c?e==a?-1:e==u?1:t:t,p=a+i+(f<0?0:d);if(r)return p;let h=e==(t<0?a:u)?null:sc(l/3,e-a),m=e==a?Zo:e==u?Xo:gn;return(t<0?e!=a:e!=u)&&(m|=Qo),new dt(p,m,h)}i+=d-c}return r?e+i:new dt(e+i,0,null)}touches(e,t){let r=0,i=qo(t),o=this.inverted?2:1,s=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+o],d=a+c;if(e<=d&&l==i*3)return!0;r+=this.ranges[l+s]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,o=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new n;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;ro&&a!s.isAtom||!l.type.allowsMarkType(this.mark.type)?s:s.mark(this.mark.addToSet(s.marks)),i),t.openStart,t.openEnd);return L.fromReplace(e,this.from,this.to,o)}invert(){return new Pe(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};z.jsonID("addMark",ft);var Pe=class n extends z{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new b(Or(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return L.fromReplace(e,this.from,this.to,r)}invert(){return new ft(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};z.jsonID("removeMark",Pe);var pt=class n extends z{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return L.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return L.fromReplace(e,this.pos,this.pos+1,new b(k.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new n(t.pos,r.pos,i,o,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new n(t.from,t.to,t.gapFrom,t.gapTo,b.fromJSON(e,t.slice),t.insert,!!t.structure)}};z.jsonID("replaceAround",I);function Mr(n,e,t){let r=n.resolve(e),i=t-e,o=r.depth;for(;i>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,i--;if(i>0){let s=r.node(o).maybeChild(r.indexAfter(o));for(;i>0;){if(!s||s.isLeaf)return!0;s=s.firstChild,i--}}return!1}function ac(n,e,t,r){let i=[],o=[],s,l;n.doc.nodesBetween(e,t,(a,c,d)=>{if(!a.isInline)return;let u=a.marks;if(!r.isInSet(u)&&d.type.allowsMarkType(r.type)){let f=Math.max(c,e),p=Math.min(c+a.nodeSize,t),h=r.addToSet(u);for(let m=0;mn.step(a)),o.forEach(a=>n.step(a))}function cc(n,e,t,r){let i=[],o=0;n.doc.nodesBetween(e,t,(s,l)=>{if(!s.isInline)return;o++;let a=null;if(r instanceof at){let c=s.marks,d;for(;d=r.isInSet(c);)(a||(a=[])).push(d),c=d.removeFromSet(c)}else r?r.isInSet(s.marks)&&(a=[r]):a=s.marks;if(a&&a.length){let c=Math.min(l+s.nodeSize,t);for(let d=0;dn.step(new Pe(s.from,s.to,s.style)))}function Tr(n,e,t,r=t.contentMatch,i=!0){let o=n.doc.nodeAt(e),s=[],l=e+1;for(let a=0;a=0;a--)n.step(s[a])}function dc(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function me(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,o=0;;--r){let s=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-o;if(rt;h--)m||r.index(h)>0?(m=!0,d=k.from(r.node(h).copy(d)),u++):a--;let f=k.empty,p=0;for(let h=o,m=!1;h>t;h--)m||i.after(h+1)=0;s--){if(r.size){let l=t[s].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=k.from(t[s].type.create(t[s].attrs,r))}let i=e.start,o=e.end;n.step(new I(i,o,i,o,new b(r,0,0),t.length,!0))}function mc(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=n.steps.length;n.doc.nodesBetween(e,t,(s,l)=>{let a=typeof i=="function"?i(s):i;if(s.isTextblock&&!s.hasMarkup(r,a)&&gc(n.doc,n.mapping.slice(o).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",h=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!h?c=!1:!p&&h&&(c=!0)}c===!1&&ts(n,s,l,o),Tr(n,n.mapping.slice(o).map(l,1),r,void 0,c===null);let d=n.mapping.slice(o),u=d.map(l,1),f=d.map(l+s.nodeSize,1);return n.step(new I(u,f,u+1,f-1,new b(k.from(r.create(a,null,s.marks)),0,0),1,!0)),c===!0&&es(n,s,l,o),!1}})}function es(n,e,t,r){e.forEach((i,o)=>{if(i.isText){let s,l=/\r?\n|\r/g;for(;s=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+o+s.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function ts(n,e,t,r){e.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let s=n.mapping.slice(r).map(t+1+o);n.replaceWith(s,s+1,e.type.schema.text(` +`))}})}function gc(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function yc(n,e,t,r,i){let o=n.doc.nodeAt(e);if(!o)throw new RangeError("No node at given position");t||(t=o.type);let s=t.create(r,null,i||o.marks);if(o.isLeaf)return n.replaceWith(e,e+o.nodeSize,s);if(!t.validContent(o.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new I(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new b(k.from(s),0,0),1,!0))}function ee(n,e,t=1,r){let i=n.resolve(e),o=i.depth-t,s=r&&r[r.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!s.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,d=t-2;c>o;c--,d--){let u=i.node(c),f=i.index(c);if(u.type.spec.isolating)return!1;let p=u.content.cutByIndex(f,u.childCount),h=r&&r[d+1];h&&(p=p.replaceChild(0,h.type.create(h.attrs)));let m=r&&r[d]||u;if(!u.canReplace(f+1,u.childCount)||!m.type.validContent(p))return!1}let l=i.indexAfter(o),a=r&&r[0];return i.node(o).canReplaceWith(l,l,a?a.type:i.node(o+1).type)}function kc(n,e,t=1,r){let i=n.doc.resolve(e),o=k.empty,s=k.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){o=k.from(i.node(l).copy(o));let d=r&&r[c];s=k.from(d?d.type.create(d.attrs,s):i.node(l).copy(s))}n.step(new V(e,e,new b(o.append(s),t,t),!0))}function re(n,e){let t=n.resolve(e),r=t.index();return ns(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function bc(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(o=r.node(i+1),l++,s=r.node(i).maybeChild(l)):(o=r.node(i).maybeChild(l-1),s=r.node(i+1)),o&&!o.isTextblock&&ns(o,s)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function xc(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,o=n.doc.resolve(e-t),s=o.node().type;if(i&&s.inlineContent){let d=s.whitespace=="pre",u=!!s.contentMatch.matchType(i);d&&!u?r=!1:!d&&u&&(r=!0)}let l=n.steps.length;if(r===!1){let d=n.doc.resolve(e+t);ts(n,d.node(),d.before(),l)}s.inlineContent&&Tr(n,e+t-1,s,o.node().contentMatchAt(o.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new V(c,a.map(e+t,-1),b.empty,!0)),r===!0){let d=n.doc.resolve(c);es(n,d.node(),d.before(),n.steps.length)}return n}function rs(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let o=r.index(i);if(r.node(i).canReplaceWith(o,o,t))return r.before(i+1);if(o>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let o=r.indexAfter(i);if(r.node(i).canReplaceWith(o,o,t))return r.after(i+1);if(o=0;s--){let l=s==r.depth?0:r.pos<=(r.start(s+1)+r.end(s+1))/2?-1:1,a=r.index(s)+(l>0?1:0),c=r.node(s),d=!1;if(o==1)d=c.canReplace(a,a,i);else{let u=c.contentMatchAt(a).findWrapping(i.firstChild.type);d=u&&c.canReplaceWith(a,a,u[0])}if(d)return l==0?r.pos:l<0?r.before(s+1):r.after(s+1)}return null}function ht(n,e,t=e,r=b.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),o=n.resolve(t);return is(i,o,r)?new V(e,t,r):new Er(i,o,r).fit()}function is(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}var Er=class{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=k.empty;for(let i=0;i<=e.depth;i++){let o=e.node(i);this.frontier.push({type:o.type,match:o.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=k.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let o=this.placed,s=r.depth,l=i.depth;for(;s&&l&&o.childCount==1;)o=o.firstChild.content,s--,l--;let a=new b(o,s,l);return e>-1?new I(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new V(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),o.type.spec.isolating&&i<=r){e=r;break}t=o.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,o=null;r?(o=Cr(this.unplaced.content,r-1).firstChild,i=o.content):i=this.unplaced.content;let s=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],d,u=null;if(t==1&&(s?c.matchType(s.type)||(u=c.fillBefore(k.from(s),!1)):o&&a.compatibleContent(o.type)))return{sliceDepth:r,frontierDepth:l,parent:o,inject:u};if(t==2&&s&&(d=c.findWrapping(s.type)))return{sliceDepth:r,frontierDepth:l,parent:o,wrap:d};if(o&&c.matchType(o.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=Cr(e,t);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new b(e,t+1,Math.max(r,i.size+t>=e.size-r?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=Cr(e,t);if(i.childCount<=1&&t>0){let o=e.size-t<=t+i.size;this.unplaced=new b(Bt(e,t-1,1),t-1,o?t-1:r)}else this.unplaced=new b(Bt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:o}){for(;this.depth>t;)this.closeFrontierNode();if(o)for(let m=0;m1||a==0||m.content.size)&&(u=g,d.push(ss(m.mark(f.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?p:-1)))}let h=c==l.childCount;h||(p=-1),this.placed=zt(this.placed,t,k.from(d)),this.frontier[t].match=u,h&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],o=t=0;l--){let{match:a,type:c}=this.frontier[l],d=wr(e,l,c,a,!0);if(!d||d.childCount)continue e}return{depth:t,fit:s,move:o?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=zt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),o=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,o)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=zt(this.placed,this.depth,k.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(k.empty,!0);t.childCount&&(this.placed=zt(this.placed,this.frontier.length,t))}};function Bt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(Bt(n.firstChild.content,e-1,t)))}function zt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(zt(n.lastChild.content,e-1,t)))}function Cr(n,e){for(let t=0;t1&&(r=r.replaceChild(0,ss(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(k.empty,!0)))),n.copy(r)}function wr(n,e,t,r,i){let o=n.node(e),s=i?n.indexAfter(e):n.index(e);if(s==o.childCount&&!t.compatibleContent(o.type))return null;let l=r.fillBefore(o.content,!0,s);return l&&!Sc(t,o.content,s)?l:null}function Sc(n,e,t){for(let r=t;r0;f--,p--){let h=i.node(f).type.spec;if(h.defining||h.definingAsContext||h.isolating)break;s.indexOf(f)>-1?l=f:i.before(f)==p&&s.splice(1,0,-f)}let a=s.indexOf(l),c=[],d=r.openStart;for(let f=r.content,p=0;;p++){let h=f.firstChild;if(c.push(h),p==r.openStart)break;f=h.content}for(let f=d-1;f>=0;f--){let p=c[f],h=Cc(p.type);if(h&&!p.sameMarkup(i.node(Math.abs(l)-1)))d=f;else if(h||!p.type.isTextblock)break}for(let f=r.openStart;f>=0;f--){let p=(f+d+1)%(r.openStart+1),h=c[p];if(h)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>u));f--){let p=s[f];p<0||(e=i.before(p),t=o.after(p))}}function ls(n,e,t,r,i){if(er){let o=i.contentMatchAt(0),s=o.fillBefore(n).append(n);n=s.append(o.matchFragment(s).fillBefore(k.empty,!0))}return n}function Mc(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=rs(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new b(k.from(r),0,0))}function Ec(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let s=r.sharedDepth(t),l=!1;for(let a=r.depth;a>s;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>s;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let o=as(r,i);for(let s=0;s0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let s=1;s<=r.depth&&s<=i.depth;s++)if(e-r.start(s)==r.depth-s&&t>r.end(s)&&i.end(s)-t!=i.depth-s&&r.start(s-1)==i.start(s-1)&&r.node(s-1).canReplace(r.index(s-1),i.index(s-1)))return n.delete(r.before(s),t);n.delete(e,t)}function as(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let o=n.start(i);if(oe.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(o==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==o-1)&&t.push(i)}return t}var Ft=class n extends z{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return L.fail("No node at attribute step's position");let r=Object.create(null);for(let o in t.attrs)r[o]=t.attrs[o];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return L.fromReplace(e,this.pos,this.pos+1,new b(k.from(i),0,t.isLeaf?0:1))}getMap(){return he.empty}invert(e){return new n(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new n(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new n(t.pos,t.attr,t.value)}};z.jsonID("attr",Ft);var Lt=class n extends z{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return L.ok(r)}getMap(){return he.empty}invert(e){return new n(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new n(t.attr,t.value)}};z.jsonID("docAttr",Lt);var Je=class extends Error{};Je=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Je.prototype=Object.create(Error.prototype);Je.prototype.constructor=Je;Je.prototype.name="TransformError";var He=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new ut}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new Je(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=b.empty){let i=ht(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new b(k.from(r),0,0))}delete(e,t){return this.replace(e,t,b.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return wc(this,e,t,r),this}replaceRangeWith(e,t,r){return Mc(this,e,t,r),this}deleteRange(e,t){return Ec(this,e,t),this}lift(e,t){return uc(this,e,t),this}join(e,t=1){return xc(this,e,t),this}wrap(e,t){return hc(this,e,t),this}setBlockType(e,t=e,r,i=null){return mc(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return yc(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new Ft(e,t,r)),this}setDocAttribute(e,t){return this.step(new Lt(e,t)),this}addNodeMark(e,t){return this.step(new pt(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof D)t.isInSet(r.marks)&&this.step(new Ke(e,t));else{let i=r.marks,o,s=[];for(;o=t.isInSet(i);)s.push(new Ke(e,o)),i=o.removeFromSet(i);for(let l=s.length-1;l>=0;l--)this.step(s[l])}return this}split(e,t=1,r){return kc(this,e,t,r),this}addMark(e,t,r){return ac(this,e,t,r),this}removeMark(e,t,r){return cc(this,e,t,r),this}clearIncompatible(e,t,r){return Tr(this,e,t,r),this}};var Nr=Object.create(null),E=class{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new Ye(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;o--){let s=t<0?mt(e.node(0),e.node(o),e.before(o+1),e.index(o),t,r):mt(e.node(0),e.node(o),e.after(o+1),e.index(o)+1,t,r);if(s)return s}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new q(e.node(0))}static atStart(e){return mt(e,e,0,0,1)||new q(e)}static atEnd(e){return mt(e,e,e.content.size,e.childCount,-1)||new q(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Nr[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Nr)throw new RangeError("Duplicate use of selection JSON ID "+e);return Nr[e]=t,t.prototype.jsonID=e,t}getBookmark(){return T.between(this.$anchor,this.$head).getBookmark()}};E.prototype.visible=!0;var Ye=class{constructor(e,t){this.$from=e,this.$to=t}},cs=!1;function ds(n){!cs&&!n.parent.inlineContent&&(cs=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}var T=class n extends E{constructor(e,t=e){ds(e),ds(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return E.near(r);let i=e.resolve(t.map(this.anchor));return new n(i.parent.inlineContent?i:r,r)}replace(e,t=b.empty){if(super.replace(e,t),t==b.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof n&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new kn(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new n(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let o=E.findFrom(t,r,!0)||E.findFrom(t,-r,!0);if(o)t=o.$head;else return E.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(E.findFrom(e,-r,!0)||E.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?s=0;s+=i){let l=e.child(s);if(l.isAtom){if(!o&&S.isSelectable(l))return S.create(n,t-(i<0?l.nodeSize:0))}else{let a=mt(n,l,t+i,i<0?l.childCount:0,i,o);if(a)return a}t+=l.nodeSize*i}return null}function us(n,e,t){let r=n.steps.length-1;if(r{s==null&&(s=d)}),n.setSelection(E.near(n.doc.resolve(s),t))}var fs=1,yn=2,ps=4,bn=class extends He{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=yn,this}ensureMarks(e){return D.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&yn)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~yn,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||D.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let o=this.storedMarks;if(!o){let s=this.doc.resolve(t);o=r==t?s.marks():s.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,o)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(E.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=ps,this}get scrolledIntoView(){return(this.updated&ps)>0}};function hs(n,e){return!e||!n?n:n.bind(e)}var Ge=class{constructor(e,t,r){this.name=e,this.init=hs(t.init,r),this.apply=hs(t.apply,r)}},Tc=[new Ge("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Ge("selection",{init(n,e){return n.selection||E.atStart(e.doc)},apply(n){return n.selection}}),new Ge("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Ge("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})],$t=class{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Tc.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Ge(r.key,r.spec.state,r))})}},jt=class n{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],o=i.spec.state;o&&o.toJSON&&(t[r]=o.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new $t(e.schema,e.plugins),o=new n(i);return i.fields.forEach(s=>{if(s.name=="doc")o.doc=Y.fromJSON(e.schema,t.doc);else if(s.name=="selection")o.selection=E.fromJSON(o.doc,t.selection);else if(s.name=="storedMarks")t.storedMarks&&(o.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==s.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){o[s.name]=c.fromJSON.call(a,e,t[l],o);return}}o[s.name]=s.init(e,o)}}),o}};function ms(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=ms(i,e,{})),t[r]=i}return t}var P=class{constructor(e){this.spec=e,this.props={},e.props&&ms(e.props,this,this.props),this.key=e.key?e.key.key:gs("plugin")}getState(e){return e[this.key]}},Dr=Object.create(null);function gs(n){return n in Dr?n+"$"+ ++Dr[n]:(Dr[n]=0,n+"$")}var te=class{constructor(e="key"){this.key=gs(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var di={};ae(di,{Decoration:()=>de,DecorationSet:()=>X,EditorView:()=>wt,__endComposition:()=>nu,__parseFromClipboard:()=>tu});var $=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},xt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e},zr=null,Ee=function(n,e,t){let r=zr||(zr=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Nc=function(){zr=null},rt=function(n,e,t,r){return t&&(ys(n,e,t,r,-1)||ys(n,e,t,r,1))},Dc=/^(img|br|input|textarea|hr)$/i;function ys(n,e,t,r,i){for(var o;;){if(n==t&&e==r)return!0;if(e==(i<0?0:oe(n))){let s=n.parentNode;if(!s||s.nodeType!=1||Yt(n)||Dc.test(n.nodeName)||n.contentEditable=="false")return!1;e=$(n)+(i<0?0:1),n=s}else if(n.nodeType==1){let s=n.childNodes[e+(i<0?-1:0)];if(s.nodeType==1&&s.contentEditable=="false")if(!((o=s.pmViewDesc)===null||o===void 0)&&o.ignoreForSelection)e+=i;else return!1;else n=s,e=i<0?oe(n):0}else return!1}}function oe(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Ac(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=oe(n)}else if(n.parentNode&&!Yt(n))e=$(n),n=n.parentNode;else return null}}function vc(n,e){for(;;){if(n.nodeType==3&&e2),ie=St||(ge?/Mac/.test(ge.platform):!1),Zs=ge?/Win/.test(ge.platform):!1,Oe=/Android \d/.test(Ve),Xt=!!ks&&"webkitFontSmoothing"in ks.documentElement.style,_c=Xt?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Bc(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function Me(n,e){return typeof n=="number"?n:n[e]}function zc(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function bs(n,e,t){let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,o=n.dom.ownerDocument;for(let s=t||n.dom;s;){if(s.nodeType!=1){s=xt(s);continue}let l=s,a=l==o.body,c=a?Bc(o):zc(l),d=0,u=0;if(e.topc.bottom-Me(r,"bottom")&&(u=e.bottom-e.top>c.bottom-c.top?e.top+Me(i,"top")-c.top:e.bottom-c.bottom+Me(i,"bottom")),e.leftc.right-Me(r,"right")&&(d=e.right-c.right+Me(i,"right")),d||u)if(a)o.defaultView.scrollBy(d,u);else{let p=l.scrollLeft,h=l.scrollTop;u&&(l.scrollTop+=u),d&&(l.scrollLeft+=d);let m=l.scrollLeft-p,g=l.scrollTop-h;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let f=a?"fixed":getComputedStyle(s).position;if(/^(fixed|sticky)$/.test(f))break;s=f=="absolute"?s.offsetParent:xt(s)}}function Fc(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let o=(e.left+e.right)/2,s=t+1;s=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:Qs(n.dom)}}function Qs(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=xt(r));return e}function Lc({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;el(t,r==0?0:r-e)}function el(n,e){for(let t=0;t=l){s=Math.max(h.bottom,s),l=Math.min(h.top,l);let m=h.left>e.left?h.left-e.left:h.right=(h.left+h.right)/2?1:0));continue}}else h.top>e.top&&!a&&h.left<=e.left&&h.right>=e.left&&(a=d,c={left:Math.max(h.left,Math.min(h.right,e.left)),top:h.top});!t&&(e.left>=h.right&&e.top>=h.top||e.left>=h.left&&e.top>=h.bottom)&&(o=u+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?$c(t,i):!t||r&&t.nodeType==1?{node:n,offset:o}:tl(t,i)}function $c(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let o=0;o=(s.left+s.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function ti(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function jc(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(s.left+s.right)/2?1:-1}return n.docView.posFromDOM(r,i,o)}function Kc(n,e,t,r){let i=-1;for(let o=e,s=!1;o!=n.dom;){let l=n.docView.nearestDesc(o,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!s&&a.left>r.left||a.top>r.top?i=l.posBefore:(!s&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function nl(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;Xt&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Kc(n,r,i,e))}l==null&&(l=Wc(n,s,e));let a=n.docView.nearestDesc(s,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function xs(n){return n.top=0&&i==r.nodeValue.length?(a--,d=1):t<0?a--:c++,Wt(_e(Ee(r,a,c),d),d<0)}if(!n.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&i&&(t<0||i==oe(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Rr(a.getBoundingClientRect(),!1)}if(o==null&&i=0)}if(o==null&&i&&(t<0||i==oe(r))){let a=r.childNodes[i-1],c=a.nodeType==3?Ee(a,oe(a)-(s?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return Wt(_e(c,1),!1)}if(o==null&&i=0)}function Wt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Rr(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function il(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function qc(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return il(n,e,()=>{let{node:o}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(o,!0);if(!l)break;if(l.node.isBlock){o=l.contentDOM||l.dom;break}o=l.dom.parentNode}let s=rl(n,i.pos,1);for(let l=o.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=Ee(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cd.top+1&&(t=="up"?s.top-d.top>(d.bottom-s.top)*2:d.bottom-s.bottom>(s.bottom-d.top)*2))return!1}}return!0})}var Uc=/[\u0590-\u08ac]/;function Gc(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,o=!i,s=i==r.parent.content.size,l=n.domSelection();return l?!Uc.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?o:s:il(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:d,anchorOffset:u}=n.domSelectionRange(),f=l.caretBidiLevel;l.modify("move",t,"character");let p=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:h,focusOffset:m}=n.domSelectionRange(),g=h&&!p.contains(h.nodeType==1?h:h.parentNode)||a==h&&c==m;try{l.collapse(d,u),a&&(a!=d||c!=u)&&l.extend&&l.extend(a,c)}catch{}return f!=null&&(l.caretBidiLevel=f),g}):r.pos==r.start()||r.pos==r.end()}var Ss=null,Cs=null,ws=!1;function Yc(n,e,t){return Ss==e&&Cs==t?ws:(Ss=e,Cs=t,ws=t=="up"||t=="down"?qc(n,e,t):Gc(n,e,t))}var le=0,Ms=1,Ze=2,ye=3,it=class{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=le,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;t$(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!1;break}if(o.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!0;break}if(o.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let o=this.getDesc(i),s;if(o&&(!t||o.node))if(r&&(s=o.nodeDOM)&&!(s.nodeType==1?s.contains(e.nodeType==1?e:e.parentNode):s==e))r=!1;else return o}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let o=this.getDesc(i);if(o)return o.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||s instanceof Cn){i=e-o;break}o=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let o;r&&!(o=this.children[r-1]).size&&o instanceof xn&&o.side>=0;r--);if(t<=0){let o,s=!0;for(;o=r?this.children[r-1]:null,!(!o||o.dom.parentNode==this.contentDOM);r--,s=!1);return o&&t&&s&&!o.border&&!o.domAtom?o.domFromPos(o.size,t):{node:this.contentDOM,offset:o?$(o.dom)+1:0}}else{let o,s=!0;for(;o=r=d&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,d);e=s;for(let u=l;u>0;u--){let f=this.children[u-1];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(1)){i=$(f.dom)+1;break}e-=f.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let d=l+1;dh&&st){let h=l;l=a,a=h}let p=document.createRange();p.setEnd(a.node,a.offset),p.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+o.border,a=s-o.border;if(e>=l&&t<=a){this.dirty=e==r||t==s?Ze:Ms,e==l&&t==a&&(o.contentLost||o.dom.parentNode!=this.contentDOM)?o.dirty=ye:o.markDirty(e-l,t-l);return}else o.dirty=o.dom==o.contentDOM&&o.dom.parentNode==this.contentDOM&&!o.children.length?Ze:ye}r=s}this.dirty=Ze}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Ze:Ms;t.dirty{if(!o)return i;if(o.parent)return o.parent.posBeforeChild(o)})),!t.type.spec.raw){if(s.nodeType!=1){let l=document.createElement("span");l.appendChild(s),s=l}s.contentEditable="false",s.classList.add("ProseMirror-widget")}super(e,[],s,null),this.widget=t,this.widget=t,o=this}matchesWidget(e){return this.dirty==le&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},$r=class extends it{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}},Ct=class n extends it{constructor(e,t,r,i,o){super(e,[],r,i),this.mark=t,this.spec=o}static create(e,t,r,i){let o=i.nodeViews[t.type.name],s=o&&o(t,i,r);return(!s||!s.dom)&&(s=pe.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new n(e,t,s.dom,s.contentDOM||s.dom,s)}parseRule(){return this.dirty&ye||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ye&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=le){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(o=Jr(o,0,e,r));for(let l=0;l{if(!a)return s;if(a.parent)return a.parent.posBeforeChild(a)},r,i),d=c&&c.dom,u=c&&c.contentDOM;if(t.isText){if(!d)d=document.createTextNode(t.text);else if(d.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else d||({dom:d,contentDOM:u}=pe.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!u&&!t.isText&&d.nodeName!="BR"&&(d.hasAttribute("contenteditable")||(d.contentEditable="false"),t.type.spec.draggable&&(d.draggable=!0));let f=d;return d=ll(d,r,t),c?a=new jr(e,t,r,i,d,u||null,f,c,o,s+1):t.isText?new Sn(e,t,r,i,d,f,o):new n(e,t,r,i,d,u||null,f,o,s+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let t=this.children.length-1;t>=0;t--){let r=this.children[t];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>k.empty)}return e}matchesNode(e,t,r){return this.dirty==le&&e.eq(this.node)&&wn(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,o=e.composing?this.localCompositionInfo(e,t):null,s=o&&o.pos>-1?o:null,l=o&&o.pos<0,a=new Kr(this,s&&s.node,e);ed(this.node,this.innerDeco,(c,d,u)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,d):c.type.side>=0&&!u&&a.syncToMarks(d==this.node.childCount?D.none:this.node.child(d).marks,r,e,d),a.placeWidget(c,e,i)},(c,d,u,f)=>{a.syncToMarks(c.marks,r,e,f);let p;a.findNodeMatch(c,d,u,f)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,d,u,p,e)||a.updateNextNode(c,d,u,e,f,i)||a.addNode(c,d,u,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Ze)&&(s&&this.protectLocalComposition(e,s),ol(this.contentDOM,this.children,e),St&&td(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof T)||rt+this.node.content.size)return null;let o=e.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let s=o.nodeValue,l=nd(this.node.content,s,r-t,i-t);return l<0?null:{node:o,pos:l,text:s}}else return{node:o,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let o=t;for(;o.parentNode!=this.contentDOM;o=o.parentNode){for(;o.previousSibling;)o.parentNode.removeChild(o.previousSibling);for(;o.nextSibling;)o.parentNode.removeChild(o.nextSibling);o.pmViewDesc&&(o.pmViewDesc=void 0)}let s=new $r(this,o,t,i);e.input.compositionNodes.push(s),this.children=Jr(this.children,r,r+i.length,e,s)}update(e,t,r,i){return this.dirty==ye||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=le}updateOuterDeco(e){if(wn(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=sl(this.dom,this.nodeDOM,Wr(this.outerDeco,this.node,t),Wr(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}};function Es(n,e,t,r,i){ll(r,e,n);let o=new Le(void 0,n,e,t,r,r,r,i,0);return o.contentDOM&&o.updateChildren(i,0),o}var Sn=class n extends Le{constructor(e,t,r,i,o,s,l){super(e,t,r,i,o,null,s,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==ye||this.dirty!=le&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=le||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=le,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),o=document.createTextNode(i.text);return new n(this.parent,i,this.outerDeco,this.innerDeco,o,o,r)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=ye)}get domAtom(){return!1}isText(e){return this.node.text==e}},Cn=class extends it{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==le&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}},jr=class extends Le{constructor(e,t,r,i,o,s,l,a,c,d){super(e,t,r,i,o,s,l,c,d),this.spec=a}update(e,t,r,i){if(this.dirty==ye)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let o=this.spec.update(e,t,r);return o&&this.updateInner(e,t,r,i),o}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}};function ol(n,e,t){let r=n.firstChild,i=!1;for(let o=0;o>1,l=Math.min(s,e.length);for(;o-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let d=Ct.create(this.top,e[s],t,r);this.top.children.splice(this.index,0,d),this.top=d,this.changed=!0}this.index=0,s++}}findNodeMatch(e,t,r,i){let o=-1,s;if(i>=this.preMatch.index&&(s=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&s.matchesNode(e,t,r))o=this.top.children.indexOf(s,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Ct)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,o.set(l,i),s.push(l)}}return{index:i,matched:o,matches:s.reverse()}}function Qc(n,e){return n.type.side-e.type.side}function ed(n,e,t,r){let i=e.locals(n),o=0;if(i.length==0){for(let c=0;co;)l.push(i[s++]);let h=o+f.nodeSize;if(f.isText){let g=h;s!g.inline):l.slice();r(f,m,e.forChild(o,f),p),o=h}}function td(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function nd(n,e,t,r){for(let i=0,o=0;i=t){if(o>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Jr(n,e,t,r,i){let o=[];for(let s=0,l=0;s=t||d<=e?o.push(a):(ct&&o.push(a.slice(t-c,a.size,r)))}return o}function ni(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),o=i&&i.size==0,s=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(s<0)return null;let l=r.resolve(s),a,c;if(Dn(t)){for(a=s;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&S.isSelectable(u)&&i.parent&&!(u.isInline&&Rc(t.focusNode,t.focusOffset,i.dom))){let f=i.posBefore;c=new S(s==f?l:r.resolve(f))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let u=s,f=s;for(let p=0;p{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!al(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function id(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,$(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&ne&&Fe<=11&&(t.disabled=!0,t.disabled=!1)}function cl(n,e){if(e instanceof S){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(As(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else As(n)}function As(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function ri(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||T.between(e,t,r)}function vs(n){return n.editable&&!n.hasFocus()?!1:dl(n)}function dl(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function od(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return rt(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Hr(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),o=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return o&&E.findFrom(o,e)}function Be(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Rs(n,e,t){let r=n.state.selection;if(r instanceof T)if(t.indexOf("s")>-1){let{$head:i}=r,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let s=n.state.doc.resolve(i.pos+o.nodeSize*(e<0?-1:1));return Be(n,new T(r.$anchor,s))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Hr(n.state,e);return i&&i instanceof S?Be(n,i):!1}else if(!(ie&&t.indexOf("m")>-1)){let i=r.$head,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,s;if(!o||o.isText)return!1;let l=e<0?i.pos-o.nodeSize:i.pos;return o.isAtom||(s=n.docView.descAt(l))&&!s.contentDOM?S.isSelectable(o)?Be(n,new S(e<0?n.state.doc.resolve(i.pos-o.nodeSize):i)):Xt?Be(n,new T(n.state.doc.resolve(e<0?l:l+o.nodeSize))):!1:!1}}else return!1;else{if(r instanceof S&&r.node.isInline)return Be(n,new T(e>0?r.$to:r.$from));{let i=Hr(n.state,e);return i?Be(n,i):!1}}}function Mn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Jt(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function yt(n,e){return e<0?sd(n):ld(n)}function sd(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,o,s=!1;for(se&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(Jt(l,-1))i=t,o=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(ul(t))break;{let l=t.previousSibling;for(;l&&Jt(l,-1);)i=t.parentNode,o=$(l),l=l.previousSibling;if(l)t=l,r=Mn(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}s?qr(n,t,r):i&&qr(n,i,o)}function ld(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=Mn(t),o,s;for(;;)if(r{n.state==i&&Te(n)},50)}function Is(n,e){let t=n.state.doc.resolve(e);if(!(j||Zs)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let o=n.coordsAtPos(e-1),s=(o.top+o.bottom)/2;if(s>i.top&&s1)return o.lefti.top&&s1)return o.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Ps(n,e,t){let r=n.state.selection;if(r instanceof T&&!r.empty||t.indexOf("s")>-1||ie&&t.indexOf("m")>-1)return!1;let{$from:i,$to:o}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let s=Hr(n.state,e);if(s&&s instanceof S)return Be(n,s)}if(!i.parent.inlineContent){let s=e<0?i:o,l=r instanceof q?E.near(s,e):E.findFrom(s,e);return l?Be(n,l):!1}return!1}function _s(n,e){if(!(n.state.selection instanceof T))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(o&&!o.isText){let s=n.state.tr;return e<0?s.delete(t.pos-o.nodeSize,t.pos):s.delete(t.pos,t.pos+o.nodeSize),n.dispatch(s),!0}return!1}function Bs(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function dd(n){if(!G||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Bs(n,r,"true"),setTimeout(()=>Bs(n,r,"false"),20)}return!1}function ud(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function fd(n,e){let t=e.keyCode,r=ud(e);if(t==8||ie&&t==72&&r=="c")return _s(n,-1)||yt(n,-1);if(t==46&&!e.shiftKey||ie&&t==68&&r=="c")return _s(n,1)||yt(n,1);if(t==13||t==27)return!0;if(t==37||ie&&t==66&&r=="c"){let i=t==37?Is(n,n.state.selection.from)=="ltr"?-1:1:-1;return Rs(n,i,r)||yt(n,i)}else if(t==39||ie&&t==70&&r=="c"){let i=t==39?Is(n,n.state.selection.from)=="ltr"?1:-1:1;return Rs(n,i,r)||yt(n,i)}else{if(t==38||ie&&t==80&&r=="c")return Ps(n,-1,r)||yt(n,-1);if(t==40||ie&&t==78&&r=="c")return dd(n)||Ps(n,1,r)||yt(n,1);if(r==(ie?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function ii(n,e){n.someProp("transformCopied",p=>{e=p(e,n)});let t=[],{content:r,openStart:i,openEnd:o}=e;for(;i>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,o--;let p=r.firstChild;t.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let s=n.someProp("clipboardSerializer")||pe.fromSchema(n.state.schema),l=gl(),a=l.createElement("div");a.appendChild(s.serializeFragment(r,{document:l}));let c=a.firstChild,d,u=0;for(;c&&c.nodeType==1&&(d=ml[c.nodeName.toLowerCase()]);){for(let p=d.length-1;p>=0;p--){let h=l.createElement(d[p]);for(;a.firstChild;)h.appendChild(a.firstChild);a.appendChild(h),u++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${o}${u?` -${u}`:""} ${JSON.stringify(t)}`);let f=n.someProp("clipboardTextSerializer",p=>p(e,n))||e.content.textBetween(0,e.content.size,` + +`);return{dom:a,text:f,slice:e}}function oi(n,e,t,r,i){let o=i.parent.type.spec.code,s,l;if(!t&&!e)return null;let a=!!e&&(r||o||!t);if(a){if(n.someProp("transformPastedText",f=>{e=f(e,o||r,n)}),o)return l=new b(k.from(n.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),n.someProp("transformPasted",f=>{l=f(l,n,!0)}),l;let u=n.someProp("clipboardTextParser",f=>f(e,i,r,n));if(u)l=u;else{let f=i.marks(),{schema:p}=n.state,h=pe.fromSchema(p);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=s.appendChild(document.createElement("p"));m&&g.appendChild(h.serializeNode(p.text(m,f)))})}}else n.someProp("transformPastedHTML",u=>{t=u(t,n)}),s=gd(t),Xt&&yd(s);let c=s&&s.querySelector("[data-pm-slice]"),d=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(d&&d[3])for(let u=+d[3];u>0;u--){let f=s.firstChild;for(;f&&f.nodeType!=1;)f=f.nextSibling;if(!f)break;s=f}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||ce.fromSchema(n.state.schema)).parseSlice(s,{preserveWhitespace:!!(a||d),context:i,ruleFromNode(f){return f.nodeName=="BR"&&!f.nextSibling&&f.parentNode&&!pd.test(f.parentNode.nodeName)?{ignore:!0}:null}})),d)l=kd(zs(l,+d[1],+d[2]),d[4]);else if(l=b.maxOpen(hd(l.content,i),!0),l.openStart||l.openEnd){let u=0,f=0;for(let p=l.content.firstChild;u{l=u(l,n,a)}),l}var pd=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function hd(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),o,s=[];if(n.forEach(l=>{if(!s)return;let a=i.findWrapping(l.type),c;if(!a)return s=null;if(c=s.length&&o.length&&pl(a,o,l,s[s.length-1],0))s[s.length-1]=c;else{s.length&&(s[s.length-1]=hl(s[s.length-1],o.length));let d=fl(l,a);s.push(d),i=i.matchType(d.type),o=a}}),s)return k.from(s)}return n}function fl(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,k.from(n));return n}function pl(n,e,t,r,i){if(i1&&(o=0),i=t&&(l=e<0?s.contentMatchAt(0).fillBefore(l,o<=i).append(l):l.append(s.contentMatchAt(s.childCount).fillBefore(k.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,s.copy(l))}function zs(n,e,t){return et})),Pr.createHTML(n)):n}function gd(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=gl().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(n),i;if((i=r&&ml[r[1].toLowerCase()])&&(n=i.map(o=>"<"+o+">").join("")+n+i.map(o=>"").reverse().join("")),t.innerHTML=md(n),i)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;i=k.from(a.create(r[l+1],i)),o++,s++}return new b(i,o,s)}var Z={},Q={},bd={touchstart:!0,touchmove:!0},Gr=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function xd(n){for(let e in Z){let t=Z[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Cd(n,r)&&!si(n,r)&&(n.editable||!(r.type in Q))&&t(n,r)},bd[e]?{passive:!0}:void 0)}G&&n.dom.addEventListener("input",()=>null),Yr(n)}function ze(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Sd(n){n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function Yr(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>si(n,r))})}function si(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Cd(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function wd(n,e){!si(n,e)&&Z[e.type]&&(n.editable||!(e.type in Q))&&Z[e.type](n,e)}Q.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!kl(n,t)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(Oe&&j&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),St&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,Xe(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||fd(n,t)?t.preventDefault():ze(n,"key")};Q.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)};Q.keypress=(n,e)=>{let t=e;if(kl(n,t)||!t.charCode||t.ctrlKey&&!t.altKey||ie&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof T)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),o=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",s=>s(n,r.$from.pos,r.$to.pos,i,o))&&n.dispatch(o()),t.preventDefault()}};function An(n){return{left:n.clientX,top:n.clientY}}function Md(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function li(n,e,t,r,i){if(r==-1)return!1;let o=n.state.doc.resolve(r);for(let s=o.depth+1;s>0;s--)if(n.someProp(e,l=>s>o.depth?l(n,t,o.nodeAfter,o.before(s),i,!0):l(n,t,o.node(s),o.before(s),i,!1)))return!0;return!1}function bt(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);t=="pointer"&&r.setMeta("pointer",!0),n.dispatch(r)}function Ed(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&S.isSelectable(r)?(bt(n,new S(t),"pointer"),!0):!1}function Od(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof S&&(r=t.node);let o=n.state.doc.resolve(e);for(let s=o.depth+1;s>0;s--){let l=s>o.depth?o.nodeAfter:o.node(s);if(S.isSelectable(l)){r&&t.$from.depth>0&&s>=t.$from.depth&&o.before(t.$from.depth+1)==t.$from.pos?i=o.before(t.$from.depth):i=o.before(s);break}}return i!=null?(bt(n,S.create(n.state.doc,i),"pointer"),!0):!1}function Td(n,e,t,r,i){return li(n,"handleClickOn",e,t,r)||n.someProp("handleClick",o=>o(n,e,r))||(i?Od(n,t):Ed(n,t))}function Nd(n,e,t,r){return li(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Dd(n,e,t,r){return li(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ad(n,t,r)}function Ad(n,e,t){if(t.button!=0)return!1;let r=n.state.doc;if(e==-1)return r.inlineContent?(bt(n,T.create(r,0,r.content.size),"pointer"),!0):!1;let i=r.resolve(e);for(let o=i.depth+1;o>0;o--){let s=o>i.depth?i.nodeAfter:i.node(o),l=i.before(o);if(s.inlineContent)bt(n,T.create(r,l+1,l+1+s.content.size),"pointer");else if(S.isSelectable(s))bt(n,S.create(r,l),"pointer");else continue;return!0}}function ai(n){return Ht(n)}var yl=ie?"metaKey":"ctrlKey";Z.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=ai(n),i=Date.now(),o="singleClick";i-n.input.lastClick.time<500&&Md(t,n.input.lastClick)&&!t[yl]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?o="doubleClick":n.input.lastClick.type=="doubleClick"&&(o="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:o,button:t.button};let s=n.posAtCoords(An(t));s&&(o=="singleClick"?(n.input.mouseDown&&n.input.mouseDown.done(),n.input.mouseDown=new Xr(n,s,t,!!r)):(o=="doubleClick"?Nd:Dd)(n,s.pos,s.inside,t)?t.preventDefault():ze(n,"pointer"))};var Xr=class{constructor(e,t,r,i){this.view=e,this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[yl],this.allowDefault=r.shiftKey;let o,s;if(t.inside>-1)o=e.state.doc.nodeAt(t.inside),s=t.inside;else{let d=e.state.doc.resolve(t.pos);o=d.parent,s=d.depth?d.before():0}let l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(o.type.spec.draggable&&o.type.spec.selectable!==!1||c instanceof S&&c.from<=s&&c.to>s)&&(this.mightDrag={node:o,pos:s,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&se&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),ze(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Te(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(An(e))),this.updateAllowDefault(e),this.allowDefault||!t?ze(this.view,"pointer"):Td(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||G&&this.mightDrag&&!this.mightDrag.node.isAtom||j&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(bt(this.view,E.near(this.view.state.doc.resolve(t.pos)),"pointer"),e.preventDefault()):ze(this.view,"pointer")}move(e){this.updateAllowDefault(e),ze(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}};Z.touchstart=n=>{n.input.lastTouch=Date.now(),ai(n),ze(n,"pointer")};Z.touchmove=n=>{n.input.lastTouch=Date.now(),ze(n,"pointer")};Z.contextmenu=n=>ai(n);function kl(n,e){return n.composing?!0:G&&Math.abs(e.timeStamp-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}var vd=Oe?5e3:-1;Q.compositionstart=Q.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof T&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||j&&Zs&&Rd(n)))n.markCursor=n.state.storedMarks||t.marks(),Ht(n,!0),n.markCursor=null;else if(Ht(n,!e.selection.empty),se&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,o=r.focusOffset;i&&i.nodeType==1&&o!=0;){let s=o<0?i.lastChild:i.childNodes[o-1];if(!s)break;if(s.nodeType==3){let l=n.domSelection();l&&l.collapse(s,s.nodeValue.length);break}else i=s,o=-1}}n.input.composing=!0}bl(n,vd)};function Rd(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}Q.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=e.timeStamp,n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,bl(n,20))};function bl(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>Ht(n),e))}function xl(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Pd());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Id(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Ac(e.focusNode,e.focusOffset),r=vc(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,o=n.domObserver.lastChangedTextNode;if(t==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let s=t.pmViewDesc;if(!(!s||!s.isText(t.nodeValue)))return r}}return t||r}function Pd(){let n=document.createEvent("Event");return n.initEvent("event",!0,!0),n.timeStamp}function Ht(n,e=!1){if(!(Oe&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),xl(n),e||n.docView&&n.docView.dirty){let t=ni(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function _d(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}var qt=ne&&Fe<15||St&&_c<604;Z.copy=Q.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let o=qt?null:t.clipboardData,s=r.content(),{dom:l,text:a}=ii(n,s);o?(t.preventDefault(),o.clearData(),o.setData("text/html",l.innerHTML),o.setData("text/plain",a)):_d(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Bd(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function zd(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?Ut(n,r.value,null,i,e):Ut(n,r.textContent,r.innerHTML,i,e)},50)}function Ut(n,e,t,r,i){let o=oi(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,o||b.empty)))return!0;if(!o)return!1;let s=Bd(o),l=s?n.state.tr.replaceSelectionWith(s,r):n.state.tr.replaceSelection(o);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Sl(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}Q.paste=(n,e)=>{let t=e;if(n.composing&&!Oe)return;let r=qt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&Ut(n,Sl(r),r.getData("text/html"),i,t)?t.preventDefault():zd(n,t)};var En=class{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}},Fd=ie?"altKey":"ctrlKey";function Cl(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Fd]}Z.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,o=i.empty?null:n.posAtCoords(An(t)),s;if(!(o&&o.pos>=i.from&&o.pos<=(i instanceof S?i.to-1:i.to))){if(r&&r.mightDrag)s=S.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let u=n.docView.nearestDesc(t.target,!0);u&&u.node.type.spec.draggable&&u!=n.docView&&(s=S.create(n.state.doc,u.posBefore))}}let l=(s||n.state.selection).content(),{dom:a,text:c,slice:d}=ii(n,l);(!t.dataTransfer.files.length||!j||Xs>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(qt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",qt||t.dataTransfer.setData("text/plain",c),n.dragging=new En(d,Cl(n,t),s)};Z.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)};Q.dragover=Q.dragenter=(n,e)=>e.preventDefault();Q.drop=(n,e)=>{try{Ld(n,e,n.dragging)}finally{n.dragging=null}};function Ld(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(An(e));if(!r)return;let i=n.state.doc.resolve(r.pos),o=t&&t.slice;o?n.someProp("transformPasted",p=>{o=p(o,n,!1)}):o=oi(n,Sl(e.dataTransfer),qt?null:e.dataTransfer.getData("text/html"),!1,i);let s=!!(t&&Cl(n,e));if(n.someProp("handleDrop",p=>p(n,e,o||b.empty,s))){e.preventDefault();return}if(!o)return;e.preventDefault();let l=o?Vt(n.state.doc,i.pos,o):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(s){let{node:p}=t;p?p.replace(a):a.deleteSelection()}let c=a.mapping.map(l),d=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,u=a.doc;if(d?a.replaceRangeWith(c,c,o.content.firstChild):a.replaceRange(c,c,o),a.doc.eq(u))return;let f=a.doc.resolve(c);if(d&&S.isSelectable(o.content.firstChild)&&f.nodeAfter&&f.nodeAfter.sameMarkup(o.content.firstChild))a.setSelection(new S(f));else{let p=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((h,m,g,y)=>p=y),a.setSelection(ri(n,f,a.doc.resolve(p)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}Z.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&Te(n)},20))};Z.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)};Z.beforeinput=(n,e)=>{if(j&&Oe&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",o=>o(n,Xe(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in Q)Z[n]=Q[n];function Gt(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}var On=class n{constructor(e,t){this.toDOM=e,this.spec=t||tt,this.side=this.spec.side||0}map(e,t,r,i){let{pos:o,deleted:s}=e.mapResult(t.from+i,this.side<0?-1:1);return s?null:new de(o-r,o-r,this)}valid(){return!0}eq(e){return this==e||e instanceof n&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Gt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},et=class n{constructor(e,t){this.attrs=e,this.spec=t||tt}map(e,t,r,i){let o=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,s=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return o>=s?null:new de(o,s,this)}valid(e,t){return t.from=e&&(!o||o(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let s=0;se){let l=this.children[s]+1;this.children[s+2].findInner(e-l,t-l,r,i+l,o)}}map(e,t,r){return this==U||e.maps.length==0?this:this.mapInner(e,t,0,0,r||tt)}mapInner(e,t,r,i,o){let s;for(let l=0;l{let c=a+r,d;if(d=Ml(t,l,c)){for(i||(i=this.children.slice());ol&&u.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let o=e+1,s=o+t.content.size;for(let l=0;lo&&a.type instanceof et){let c=Math.max(o,a.from)-o,d=Math.min(s,a.to)-o;ci.map(e,t,tt));return n.from(r)}forChild(e,t){if(t.isLeaf)return X.empty;let r=[];for(let i=0;it instanceof X)?e:e.reduce((t,r)=>t.concat(r instanceof X?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-h-(p-f);for(let y=0;yw+d-u)continue;let M=l[y]+d-u;p>=M?l[y+1]=f<=M?-2:-1:f>=d&&g&&(l[y]+=g,l[y+1]+=g)}u+=g}),d=t.maps[c].map(d,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let f=t.map(n[c+1]+o,-1),p=f-i,{index:h,offset:m}=r.content.findIndex(u),g=r.maybeChild(h);if(g&&m==u&&m+g.nodeSize==p){let y=l[c+2].mapInner(t,g,d+1,n[c]+o+1,s);y!=U?(l[c]=u,l[c+1]=p,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=$d(l,n,e,t,i,o,s),d=Nn(c,r,0,s);e=d.local;for(let u=0;ut&&s.to{let c=Ml(n,l,a+t);if(c){o=!0;let d=Nn(c,l,t+a+1,r);d!=U&&i.push(a,a+l.nodeSize,d)}});let s=wl(o?El(n):n,-t).sort(nt);for(let l=0;l0;)e++;n.splice(e,0,t)}function _r(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=U&&e.push(r)}),n.cursorWrapper&&e.push(X.create(n.state.doc,[n.cursorWrapper.deco])),Tn.from(e)}var jd={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Wd=ne&&Fe<=11,Qr=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},ei=class{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Qr,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():G&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Wd&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,jd)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(vs(this.view)){if(this.suppressingSelectionUpdates)return Te(this.view);if(ne&&Fe<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&rt(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let o=e.focusNode;o;o=xt(o))t.add(o);for(let o=e.anchorNode;o;o=xt(o))if(t.has(o)){r=o;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&vs(e)&&!this.ignoreSelectionChange(r),o=-1,s=-1,l=!1,a=[];if(e.editable)for(let d=0;dd.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let d of a)if(d.nodeName=="BR"&&d.parentNode){let u=d.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){d.parentNode.removeChild(d);break}u=u.firstChild}}}else if(se&&a.length){let d=a.filter(u=>u.nodeName=="BR");if(d.length==2){let[u,f]=d;u.parentNode&&u.parentNode.parentNode==f.parentNode?f.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let f of d){let p=f.parentNode;p&&p.nodeName=="LI"&&(!u||Hd(e,u)!=p)&&f.remove()}}}let c=null;o<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(o>-1&&(e.docView.markDirty(o,s),Kd(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,qd(e,a)),this.handleDOMChange(o,s,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Te(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let d=0;di;g--){let y=r.childNodes[g-1],w=y.pmViewDesc;if(y.nodeName=="BR"&&!w){o=g;break}if(!w||w.size)break}let u=n.state.doc,f=n.someProp("domParser")||ce.fromSchema(n.state.schema),p=u.resolve(s),h=null,m=f.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:i,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:Gd,context:p});if(c&&c[0].pos!=null){let g=c[0].pos,y=c[1]&&c[1].pos;y==null&&(y=g),h={anchor:g+s,head:y+s}}return{doc:m,sel:h,from:s,to:l}}function Gd(n){let e=n.pmViewDesc;if(e)return e.parseRule();if(n.nodeName=="BR"&&n.parentNode){if(G&&/^(ul|ol)$/i.test(n.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}else if(n.parentNode.lastChild==n||G&&/^(tr|table)$/i.test(n.parentNode.nodeName))return{ignore:!0}}else if(n.nodeName=="IMG"&&n.getAttribute("mark-placeholder"))return{ignore:!0};return null}var Yd=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function Xd(n,e,t,r,i){let o=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let O=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,R=ni(n,O);if(R&&!n.state.selection.eq(R)){if(j&&Oe&&n.input.lastKeyCode===13&&Date.now()-100Fa(n,Xe(13,"Enter"))))return;let J=n.state.tr.setSelection(R);O=="pointer"?J.setMeta("pointer",!0):O=="key"&&J.scrollIntoView(),o&&J.setMeta("composition",o),n.dispatch(J)}return}let s=n.state.doc.resolve(e),l=s.sharedDepth(t);e=s.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Ud(n,e,t),d=n.state.doc,u=d.slice(c.from,c.to),f,p;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Oe)&&i.some(O=>O.nodeType==1&&!Yd.test(O.nodeName))&&(!h||h.endA>=h.endB)&&n.someProp("handleKeyDown",O=>O(n,Xe(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!h)if(r&&a instanceof T&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))h={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let O=Ws(n,n.state.doc,c.sel);if(O&&!O.eq(n.state.selection)){let R=n.state.tr.setSelection(O);o&&R.setMeta("composition",o),n.dispatch(R)}}return}n.state.selection.fromn.state.selection.from&&h.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?h.start=n.state.selection.from:h.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(h.endB+=n.state.selection.to-h.endA,h.endA=n.state.selection.to)),ne&&Fe<=11&&h.endB==h.start+1&&h.endA==h.start&&h.start>c.from&&c.doc.textBetween(h.start-c.from-1,h.start-c.from+1)==" \xA0"&&(h.start--,h.endA--,h.endB--);let m=c.doc.resolveNoCache(h.start-c.from),g=c.doc.resolveNoCache(h.endB-c.from),y=d.resolve(h.start),w=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=h.endA;if((St&&n.input.lastIOSEnter>Date.now()-225&&(!w||i.some(O=>O.nodeName=="DIV"||O.nodeName=="P"))||!w&&m.posO(n,Xe(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>h.start&&Qd(d,h.start,h.endA,m,g)&&n.someProp("handleKeyDown",O=>O(n,Xe(8,"Backspace")))){Oe&&j&&n.domObserver.suppressSelectionUpdates();return}j&&h.endB==h.start&&(n.input.lastChromeDelete=Date.now()),Oe&&!w&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==h.endA&&(h.endB-=2,g=c.doc.resolveNoCache(h.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(O){return O(n,Xe(13,"Enter"))})},20));let M=h.start,A=h.endA,v=O=>{let R=O||n.state.tr.replace(M,A,c.doc.slice(h.start-c.from,h.endB-c.from));if(c.sel){let J=Ws(n,R.doc,c.sel);J&&!(j&&n.composing&&J.empty&&(h.start!=h.endB||n.input.lastChromeDeleteTe(n),20));let O=v(n.state.tr.delete(M,A)),R=d.resolve(h.start).marksAcross(d.resolve(h.endA));R&&O.ensureMarks(R),n.dispatch(O)}else if(h.endA==h.endB&&(B=Zd(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,h.endA-y.start())))){let O=v(n.state.tr);B.type=="add"?O.addMark(M,A,B.mark):O.removeMark(M,A,B.mark),n.dispatch(O)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let O=m.parent.textBetween(m.parentOffset,g.parentOffset),R=()=>v(n.state.tr.insertText(O,M,A));n.someProp("handleTextInput",J=>J(n,M,A,O,R))||n.dispatch(R())}else n.dispatch(v());else n.dispatch(v())}function Ws(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:ri(n,e.resolve(t.anchor),e.resolve(t.head))}function Zd(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,o=r,s,l,a;for(let d=0;dd.mark(l.addToSet(d.marks));else if(i.length==0&&o.length==1)l=o[0],s="remove",a=d=>d.mark(l.removeFromSet(d.marks));else return null;let c=[];for(let d=0;dt||Br(s,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let o=n.node(r).maybeChild(n.indexAfter(r));for(;o&&!o.isLeaf;)o=o.firstChild,i++}return i}function eu(n,e,t,r,i){let o=n.findDiffStart(e,t);if(o==null)return null;let{a:s,b:l}=n.findDiffEnd(e,t+n.size,t+e.size);if(i=="end"){let a=Math.max(0,o-Math.min(s,l));r-=s+a-o}if(s=s?o-r:0;o-=a,o&&o=l?o-r:0;o-=a,o&&o=56320&&e<=57343&&t>=55296&&t<=56319}var tu=oi,nu=Ht,wt=class{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Gr,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(Gs),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=qs(this),Hs(this),this.nodeViews=Us(this),this.docView=Es(this.state.doc,Js(this),_r(this),this.dom,this),this.domObserver=new ei(this,(r,i,o,s)=>Xd(this,r,i,o,s)),this.domObserver.start(),xd(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&Yr(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Gs),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,o=!1,s=!1;e.storedMarks&&this.composing&&(xl(this),s=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let p=Us(this);iu(p,this.nodeViews)&&(this.nodeViews=p,o=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&Yr(this),this.editable=qs(this),Hs(this);let a=_r(this),c=Js(this),d=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=o||!this.docView.matchesNode(e.doc,c,a);(u||!e.selection.eq(i.selection))&&(s=!0);let f=d=="preserve"&&s&&this.dom.style.overflowAnchor==null&&Fc(this);if(s){this.domObserver.stop();let p=u&&(ne||j)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&ru(i.selection,e.selection);if(u){let h=j?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Id(this)),(o||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=Es(e.doc,c,a,this.dom,this)),h&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&od(this))?Te(this,p):(cl(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),d=="reset"?this.dom.scrollTop=0:d=="to selection"?this.scrollToSelection():f&&Lc(f)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof S){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&bs(this,t.getBoundingClientRect(),e)}else bs(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&ot.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Jc(this,e)}coordsAtPos(e,t=1){return rl(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Yc(this,t||this.state,e)}pasteHTML(e,t){return Ut(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Ut(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return ii(this,e)}destroy(){this.docView&&(Sd(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],_r(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Nc())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return wd(this,e)}domSelectionRange(){let e=this.domSelection();return e?G&&this.root.nodeType===11&&Ic(this.dom.ownerDocument)==this.dom&&Jd(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};wt.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function Js(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[de.node(0,n.state.doc.content.size,e)]}function Hs(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:de.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function qs(n){return!n.someProp("editable",e=>e(n.state)===!1)}function ru(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function Us(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function iu(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function Gs(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var pi={};ae(pi,{keydownHandler:()=>In,keymap:()=>fi});var Ne={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},Rn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},ou=typeof navigator<"u"&&/Mac/.test(navigator.platform),su=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(_=0;_<10;_++)Ne[48+_]=Ne[96+_]=String(_);var _;for(_=1;_<=24;_++)Ne[_+111]="F"+_;var _;for(_=65;_<=90;_++)Ne[_]=String.fromCharCode(_+32),Rn[_]=String.fromCharCode(_);var _;for(vn in Ne)Rn.hasOwnProperty(vn)||(Rn[vn]=Ne[vn]);var vn;function Ol(n){var e=ou&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||su&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Rn:Ne)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}var lu=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),au=typeof navigator<"u"&&/Win/.test(navigator.platform);function cu(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,o,s;for(let l=0;lIe,DOMParser:()=>ce,DOMSerializer:()=>pe,Fragment:()=>k,Mark:()=>D,MarkType:()=>at,Node:()=>Y,NodeRange:()=>Re,NodeType:()=>Pt,ReplaceError:()=>ve,ResolvedPos:()=>It,Schema:()=>ct,Slice:()=>b});var mi={};ae(mi,{AddMarkStep:()=>ft,AddNodeMarkStep:()=>pt,AttrStep:()=>Ft,DocAttrStep:()=>Lt,MapResult:()=>dt,Mapping:()=>ut,RemoveMarkStep:()=>Pe,RemoveNodeMarkStep:()=>Ke,ReplaceAroundStep:()=>I,ReplaceStep:()=>V,Step:()=>z,StepMap:()=>he,StepResult:()=>L,Transform:()=>He,TransformError:()=>Je,canJoin:()=>re,canSplit:()=>ee,dropPoint:()=>Vt,findWrapping:()=>qe,insertPoint:()=>rs,joinPoint:()=>Ue,liftTarget:()=>me,replaceStep:()=>ht});var Di={};ae(Di,{autoJoin:()=>yu,baseKeymap:()=>bu,chainCommands:()=>Jn,createParagraphNear:()=>Vn,deleteSelection:()=>Zt,exitCode:()=>Ln,joinBackward:()=>Pn,joinDown:()=>Ci,joinForward:()=>Bn,joinTextblockBackward:()=>yi,joinTextblockForward:()=>ki,joinUp:()=>Si,lift:()=>wi,liftEmptyBlock:()=>$n,macBaseKeymap:()=>Ni,newlineInCode:()=>Fn,pcBaseKeymap:()=>ke,selectAll:()=>Rl,selectNodeBackward:()=>_n,selectNodeForward:()=>zn,selectParentNode:()=>Oi,selectTextblockEnd:()=>Wn,selectTextblockStart:()=>jn,setBlockType:()=>Kn,splitBlock:()=>Ei,splitBlockAs:()=>vl,splitBlockKeepMarks:()=>uu,toggleMark:()=>mu,wrapIn:()=>Ti});var Zt=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Nl(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}var Pn=(n,e,t)=>{let r=Nl(n,t);if(!r)return!1;let i=bi(r);if(!i){let s=r.blockRange(),l=s&&me(s);return l==null?!1:(e&&e(n.tr.lift(s,l).scrollIntoView()),!0)}let o=i.nodeBefore;if(Il(n,i,e,-1))return!0;if(r.parent.content.size==0&&(Mt(o,"end")||S.isSelectable(o)))for(let s=r.depth;;s--){let l=ht(n.doc,r.before(s),r.after(s),b.empty);if(l&&l.slice.size1)break}return o.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView()),!0):!1},yi=(n,e,t)=>{let r=Nl(n,t);if(!r)return!1;let i=bi(r);return i?Dl(n,i,e):!1},ki=(n,e,t)=>{let r=Al(n,t);if(!r)return!1;let i=xi(r);return i?Dl(n,i,e):!1};function Dl(n,e,t){let r=e.nodeBefore,i=r,o=e.pos-1;for(;!i.isTextblock;o--){if(i.type.spec.isolating)return!1;let d=i.lastChild;if(!d)return!1;i=d}let s=e.nodeAfter,l=s,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let d=l.firstChild;if(!d)return!1;l=d}let c=ht(n.doc,o,a,b.empty);if(!c||c.from!=o||c instanceof V&&c.slice.size>=a-o)return!1;if(t){let d=n.tr.step(c);d.setSelection(T.create(d.doc,o)),t(d.scrollIntoView())}return!0}function Mt(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}var _n=(n,e,t)=>{let{$head:r,empty:i}=n.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;o=bi(r)}let s=o&&o.nodeBefore;return!s||!S.isSelectable(s)?!1:(e&&e(n.tr.setSelection(S.create(n.doc,o.pos-s.nodeSize)).scrollIntoView()),!0)};function bi(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Al(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=Al(n,t);if(!r)return!1;let i=xi(r);if(!i)return!1;let o=i.nodeAfter;if(Il(n,i,e,1))return!0;if(r.parent.content.size==0&&(Mt(o,"start")||S.isSelectable(o))){let s=ht(n.doc,r.before(),r.after(),b.empty);if(s&&s.slice.size{let{$head:r,empty:i}=n.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof S,i;if(r){if(t.node.isTextblock||!re(n.doc,t.from))return!1;i=t.from}else if(i=Ue(n.doc,t.from,-1),i==null)return!1;if(e){let o=n.tr.join(i);r&&o.setSelection(S.create(o.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(o.scrollIntoView())}return!0},Ci=(n,e)=>{let t=n.selection,r;if(t instanceof S){if(t.node.isTextblock||!re(n.doc,t.to))return!1;r=t.to}else if(r=Ue(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},wi=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),o=i&&me(i);return o==null?!1:(e&&e(n.tr.lift(i,o).scrollIntoView()),!0)},Fn=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function Mi(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),o=t.indexAfter(-1),s=Mi(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,s.createAndFill());a.setSelection(E.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Vn=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof q||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=Mi(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let o=t.before();if(ee(n.doc,o))return e&&e(n.tr.split(o).scrollIntoView()),!0}let r=t.blockRange(),i=r&&me(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function vl(n){return(e,t)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof S&&e.selection.node.isBlock)return!r.parentOffset||!ee(e.doc,r.pos)?!1:(t&&t(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],s,l,a=!1,c=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){a=r.end(p)==r.pos+(r.depth-p),c=r.start(p)==r.pos-(r.depth-p),l=Mi(r.node(p-1).contentMatchAt(r.indexAfter(p-1)));let m=n&&n(i.parent,a,r);o.unshift(m||(a&&l?{type:l}:null)),s=p;break}else{if(p==1)return!1;o.unshift(null)}let d=e.tr;(e.selection instanceof T||e.selection instanceof q)&&d.deleteSelection();let u=d.mapping.map(r.pos),f=ee(d.doc,u,o.length,o);if(f||(o[0]=l?{type:l}:null,f=ee(d.doc,u,o.length,o)),!f)return!1;if(d.split(u,o.length,o),!a&&c&&r.node(s).type!=l){let p=d.mapping.map(r.before(s)),h=d.doc.resolve(p);l&&r.node(s-1).canReplaceWith(h.index(),h.index()+1,l)&&d.setNodeMarkup(d.mapping.map(r.before(s)),l)}return t&&t(d.scrollIntoView()),!0}}var Ei=vl(),uu=(n,e)=>Ei(n,e&&(t=>{let r=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();r&&t.ensureMarks(r),e(t)})),Oi=(n,e)=>{let{$from:t,to:r}=n.selection,i,o=t.sharedDepth(r);return o==0?!1:(i=t.before(o),e&&e(n.tr.setSelection(S.create(n.doc,i))),!0)},Rl=(n,e)=>(e&&e(n.tr.setSelection(new q(n.doc))),!0);function fu(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,o=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||re(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Il(n,e,t,r){let i=e.nodeBefore,o=e.nodeAfter,s,l,a=i.type.spec.isolating||o.type.spec.isolating;if(!a&&fu(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(s=(l=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&l.matchType(s[0]||o.type).validEnd){if(t){let p=e.pos+o.nodeSize,h=k.empty;for(let y=s.length-1;y>=0;y--)h=k.from(s[y].create(null,h));h=k.from(i.copy(h));let m=n.tr.step(new I(e.pos-1,p,e.pos,p,new b(h,1,0),s.length,!0)),g=m.doc.resolve(p+2*s.length);g.nodeAfter&&g.nodeAfter.type==i.type&&re(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let d=o.type.spec.isolating||r>0&&a?null:E.findFrom(e,1),u=d&&d.$from.blockRange(d.$to),f=u&&me(u);if(f!=null&&f>=e.depth)return t&&t(n.tr.lift(u,f).scrollIntoView()),!0;if(c&&Mt(o,"start",!0)&&Mt(i,"end")){let p=i,h=[];for(;h.push(p),!p.isTextblock;)p=p.lastChild;let m=o,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,m.content)){if(t){let y=k.empty;for(let M=h.length-1;M>=0;M--)y=k.from(h[M].copy(y));let w=n.tr.step(new I(e.pos-h.length,e.pos+o.nodeSize,e.pos+g,e.pos+o.nodeSize-g,new b(y,h.length,0),0,!0));t(w.scrollIntoView())}return!0}}return!1}function Pl(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,o=i.depth;for(;i.node(o).isInline;){if(!o)return!1;o--}return i.node(o).isTextblock?(t&&t(e.tr.setSelection(T.create(e.doc,n<0?i.start(o):i.end(o)))),!0):!1}}var jn=Pl(-1),Wn=Pl(1);function Ti(n,e=null){return function(t,r){let{$from:i,$to:o}=t.selection,s=i.blockRange(o),l=s&&qe(s,n,e);return l?(r&&r(t.tr.wrap(s,l).scrollIntoView()),!0):!1}}function Kn(n,e=null){return function(t,r){let i=!1;for(let o=0;o{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let d=t.doc.resolve(c),u=d.index();i=d.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let o=t.tr;for(let s=0;s{if(l||!r&&a.isAtom&&a.isInline&&c>=o.pos&&c+a.nodeSize<=s.pos)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function hu(n){let e=[];for(let t=0;t{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos)return s+1>r.pos&&e.push(new Ye(r,r.doc.resolve(s+1))),r=r.doc.resolve(s+1+o.content.size),!1}),r.poss.doc.rangeHasMark(p.$from.pos,p.$to.pos,n)):u=!d.every(p=>{let h=!1;return f.doc.nodesBetween(p.$from.pos,p.$to.pos,(m,g,y)=>{if(h)return!1;h=!n.isInSet(m.marks)&&!!y&&y.type.allowsMarkType(n)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,p.$from.pos-g),Math.min(m.nodeSize,p.$to.pos-g))))}),!h});for(let p=0;p{if(!t.isGeneric)return n(t);let r=[];for(let o=0;or.push(c,d))}let i=[];for(let o=0;oo-s);for(let o=i.length-1;o>=0;o--)re(t.doc,i[o])&&t.join(i[o]);n(t)}}function yu(n,e){let t=Array.isArray(e)?r=>e.indexOf(r.type.name)>-1:e;return(r,i,o)=>n(r,i&&gu(i,t),o)}function Jn(...n){return function(e,t,r){for(let i=0;iwu,bulletList:()=>Bl,liftListItem:()=>Ri,listItem:()=>zl,orderedList:()=>_l,sinkListItem:()=>Ii,splitListItem:()=>Ll,splitListItemKeepMarks:()=>Eu,wrapInList:()=>vi,wrapRangeInList:()=>Fl});var xu=["ol",0],Su=["ul",0],Cu=["li",0],_l={attrs:{order:{default:1,validate:"number"}},parseDOM:[{tag:"ol",getAttrs(n){return{order:n.hasAttribute("start")?+n.getAttribute("start"):1}}}],toDOM(n){return n.attrs.order==1?xu:["ol",{start:n.attrs.order},0]}},Bl={parseDOM:[{tag:"ul"}],toDOM(){return Su}},zl={parseDOM:[{tag:"li"}],toDOM(){return Cu},defining:!0};function Ai(n,e){let t={};for(let r in n)t[r]=n[r];for(let r in e)t[r]=e[r];return t}function wu(n,e,t){return n.append({ordered_list:Ai(_l,{content:"list_item+",group:t}),bullet_list:Ai(Bl,{content:"list_item+",group:t}),list_item:Ai(zl,{content:e})})}function vi(n,e=null){return function(t,r){let{$from:i,$to:o}=t.selection,s=i.blockRange(o);if(!s)return!1;let l=r?t.tr:null;return Fl(l,s,n,e)?(r&&r(l.scrollIntoView()),!0):!1}}function Fl(n,e,t,r=null){let i=!1,o=e,s=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=s.resolve(e.start-2);o=new Re(a,a,e.depth),e.endIndex=0;d--)o=k.from(t[d].type.create(t[d].attrs,o));n.step(new I(e.start-(r?2:0),e.end,e.start,e.end,new b(o,0,0),t.length,!0));let s=0;for(let d=0;d=i.depth-3;y--)u=k.from(i.node(y).copy(u));let p=i.indexAfter(-1){if(g>-1)return!1;y.isTextblock&&y.content.size==0&&(g=w+1)}),g>-1&&m.setSelection(E.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let a=o.pos==i.end()?l.contentMatchAt(0).defaultType:null,c=t.tr.delete(i.pos,o.pos),d=a?[e?{type:n,attrs:e}:null,{type:a}]:void 0;return ee(c.doc,i.pos,2,d)?(r&&r(c.split(i.pos,2,d).scrollIntoView()),!0):!1}}function Eu(n,e){let t=Ll(n,e);return(r,i)=>t(r,i&&(o=>{let s=r.storedMarks||r.selection.$to.parentOffset&&r.selection.$from.marks();s&&o.ensureMarks(s),i(o)}))}function Ri(n){return function(e,t){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,s=>s.childCount>0&&s.firstChild.type==n);return o?t?r.node(o.depth-1).type==n?Ou(e,t,n,o):Tu(e,t,o):!0:!1}}function Ou(n,e,t,r){let i=n.tr,o=r.end,s=r.$to.end(r.depth);om;h--)p-=i.child(h).nodeSize,r.delete(p-1,p+1);let o=r.doc.resolve(t.start),s=o.nodeAfter;if(r.mapping.map(t.end)!=t.start+o.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=o.node(-1),d=o.index(-1);if(!c.canReplace(d+(l?0:1),d+1,s.content.append(a?k.empty:k.from(i))))return!1;let u=o.pos,f=u+s.nodeSize;return r.step(new I(u-(l?1:0),f+(a?1:0),u+1,f-1,new b((l?k.empty:k.from(i.copy(k.empty))).append(a?k.empty:k.from(i.copy(k.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Ii(n){return function(e,t){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let l=o.parent,a=l.child(s-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,d=k.from(c?n.create():null),u=new b(k.from(n.create(null,k.from(l.type.create(null,d)))),c?3:1,0),f=o.start,p=o.end;t(e.tr.step(new I(f-(c?3:1),p,f,p,u,1,!0)).scrollIntoView())}return!0}}function nn(n){let{state:e,transaction:t}=n,{selection:r}=t,{doc:i}=t,{storedMarks:o}=t;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return o},get selection(){return r},get doc(){return i},get tr(){return r=t.selection,i=t.doc,o=t.storedMarks,t}}}var ot=class{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){let{rawCommands:e,editor:t,state:r}=this,{view:i}=t,{tr:o}=r,s=this.buildProps(o);return Object.fromEntries(Object.entries(e).map(([l,a])=>[l,(...d)=>{let u=a(...d)(s);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(o),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){let{rawCommands:r,editor:i,state:o}=this,{view:s}=i,l=[],a=!!e,c=e||o.tr,d=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),l.every(f=>f===!0)),u={...Object.fromEntries(Object.entries(r).map(([f,p])=>[f,(...m)=>{let g=this.buildProps(c,t),y=p(...m)(g);return l.push(y),u}])),run:d};return u}createCan(e){let{rawCommands:t,state:r}=this,i=!1,o=e||r.tr,s=this.buildProps(o,i);return{...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,(...d)=>c(...d)({...s,dispatch:void 0})])),chain:()=>this.createChain(o,i)}}buildProps(e,t=!0){let{rawCommands:r,editor:i,state:o}=this,{view:s}=i,l={tr:e,editor:i,view:s,state:nn({state:o,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...d)=>c(...d)(l)]))}};return l}},zi=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){let r=this.callbacks[e];return r&&r.forEach(i=>i.apply(this,t)),this}off(e,t){let r=this.callbacks[e];return r&&(t?this.callbacks[e]=r.filter(i=>i!==t):delete this.callbacks[e]),this}once(e,t){let r=(...i)=>{this.off(e,r),t.apply(this,i)};return this.on(e,r)}removeAllListeners(){this.callbacks={}}};function x(n,e,t){return n.config[e]===void 0&&n.parent?x(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?x(n.parent,e,t):null}):n.config[e]}function rn(n){let e=n.filter(i=>i.type==="extension"),t=n.filter(i=>i.type==="node"),r=n.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:t,markExtensions:r}}function qi(n){let e=[],{nodeExtensions:t,markExtensions:r}=rn(n),i=[...t,...r],o={default:null,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return n.forEach(s=>{let l={name:s.name,options:s.options,storage:s.storage,extensions:i},a=x(s,"addGlobalAttributes",l);if(!a)return;a().forEach(d=>{d.types.forEach(u=>{Object.entries(d.attributes).forEach(([f,p])=>{e.push({type:u,name:f,attribute:{...o,...p}})})})})}),i.forEach(s=>{let l={name:s.name,options:s.options,storage:s.storage},a=x(s,"addAttributes",l);if(!a)return;let c=a();Object.entries(c).forEach(([d,u])=>{let f={...o,...u};typeof f?.default=="function"&&(f.default=f.default()),f?.isRequired&&f?.default===void 0&&delete f.default,e.push({type:s.name,name:d,attribute:f})})}),e}function F(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}function Wl(...n){return n.filter(e=>!!e).reduce((e,t)=>{let r={...e};return Object.entries(t).forEach(([i,o])=>{if(!r[i]){r[i]=o;return}if(i==="class"){let l=o?String(o).split(" "):[],a=r[i]?r[i].split(" "):[],c=l.filter(d=>!a.includes(d));r[i]=[...a,...c].join(" ")}else if(i==="style"){let l=o?o.split(";").map(d=>d.trim()).filter(Boolean):[],a=r[i]?r[i].split(";").map(d=>d.trim()).filter(Boolean):[],c=new Map;a.forEach(d=>{let[u,f]=d.split(":").map(p=>p.trim());c.set(u,f)}),l.forEach(d=>{let[u,f]=d.split(":").map(p=>p.trim());c.set(u,f)}),r[i]=Array.from(c.entries()).map(([d,u])=>`${d}: ${u}`).join("; ")}else r[i]=o}),r},{})}function Gn(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>Wl(t,r),{})}function Ui(n){return typeof n=="function"}function N(n,e=void 0,...t){return Ui(n)?e?n.bind(e)(...t):n(...t):n}function Kl(n={}){return Object.keys(n).length===0&&n.constructor===Object}function Jl(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Fi(n,e){return"style"in n?n:{...n,getAttrs:t=>{let r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;let i=e.reduce((o,s)=>{let l=s.attribute.parseHTML?s.attribute.parseHTML(t):Jl(t.getAttribute(s.name));return l==null?o:{...o,[s.name]:l}},{});return{...r,...i}}}}function Vl(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&Kl(t)?!1:t!=null))}function Gi(n,e){var t;let r=qi(n),{nodeExtensions:i,markExtensions:o}=rn(n),s=(t=i.find(c=>x(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{let d=r.filter(y=>y.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},f=n.reduce((y,w)=>{let M=x(w,"extendNodeSchema",u);return{...y,...M?M(c):{}}},{}),p=Vl({...f,content:N(x(c,"content",u)),marks:N(x(c,"marks",u)),group:N(x(c,"group",u)),inline:N(x(c,"inline",u)),atom:N(x(c,"atom",u)),selectable:N(x(c,"selectable",u)),draggable:N(x(c,"draggable",u)),code:N(x(c,"code",u)),whitespace:N(x(c,"whitespace",u)),linebreakReplacement:N(x(c,"linebreakReplacement",u)),defining:N(x(c,"defining",u)),isolating:N(x(c,"isolating",u)),attrs:Object.fromEntries(d.map(y=>{var w;return[y.name,{default:(w=y?.attribute)===null||w===void 0?void 0:w.default}]}))}),h=N(x(c,"parseHTML",u));h&&(p.parseDOM=h.map(y=>Fi(y,d)));let m=x(c,"renderHTML",u);m&&(p.toDOM=y=>m({node:y,HTMLAttributes:Gn(y,d)}));let g=x(c,"renderText",u);return g&&(p.toText=g),[c.name,p]})),a=Object.fromEntries(o.map(c=>{let d=r.filter(g=>g.type===c.name),u={name:c.name,options:c.options,storage:c.storage,editor:e},f=n.reduce((g,y)=>{let w=x(y,"extendMarkSchema",u);return{...g,...w?w(c):{}}},{}),p=Vl({...f,inclusive:N(x(c,"inclusive",u)),excludes:N(x(c,"excludes",u)),group:N(x(c,"group",u)),spanning:N(x(c,"spanning",u)),code:N(x(c,"code",u)),attrs:Object.fromEntries(d.map(g=>{var y;return[g.name,{default:(y=g?.attribute)===null||y===void 0?void 0:y.default}]}))}),h=N(x(c,"parseHTML",u));h&&(p.parseDOM=h.map(g=>Fi(g,d)));let m=x(c,"renderHTML",u);return m&&(p.toDOM=g=>m({mark:g,HTMLAttributes:Gn(g,d)})),[c.name,p]}));return new ct({topNode:s,nodes:l,marks:a})}function Un(n,e){return e.nodes[n]||e.marks[n]||null}function Li(n,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===n.name):e}function on(n,e){let t=pe.fromSchema(e).serializeFragment(n),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(t),i.innerHTML}var Hl=(n,e=500)=>{let t="",r=n.parentOffset;return n.parent.nodesBetween(Math.max(0,r-e),r,(i,o,s,l)=>{var a,c;let d=((c=(a=i.type.spec).toText)===null||c===void 0?void 0:c.call(a,{node:i,pos:o,parent:s,index:l}))||i.textContent||"%leaf%";t+=i.isAtom&&!i.isText?d:d.slice(0,Math.max(0,r-o))}),t};function tr(n){return Object.prototype.toString.call(n)==="[object RegExp]"}var $e=class{constructor(e){this.find=e.find,this.handler=e.handler}},Nu=(n,e)=>{if(tr(e))return e.exec(n);let t=e(n);if(!t)return null;let r=[t.text];return r.index=t.index,r.input=n,r.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(t.replaceWith)),r};function Hn(n){var e;let{editor:t,from:r,to:i,text:o,rules:s,plugin:l}=n,{view:a}=t;if(a.composing)return!1;let c=a.state.doc.resolve(r);if(c.parent.type.spec.code||!((e=c.nodeBefore||c.nodeAfter)===null||e===void 0)&&e.marks.find(f=>f.type.spec.code))return!1;let d=!1,u=Hl(c)+o;return s.forEach(f=>{if(d)return;let p=Nu(u,f.find);if(!p)return;let h=a.state.tr,m=nn({state:a.state,transaction:h}),g={from:r-(p[0].length-o.length),to:i},{commands:y,chain:w,can:M}=new ot({editor:t,state:m});f.handler({state:m,range:g,match:p,commands:y,chain:w,can:M})===null||!h.steps.length||(h.setMeta(l,{transform:h,from:r,to:i,text:o}),a.dispatch(h),d=!0)}),d}function ql(n){let{editor:e,rules:t}=n,r=new P({state:{init(){return null},apply(i,o,s){let l=i.getMeta(r);if(l)return l;let a=i.getMeta("applyInputRules");return a&&setTimeout(()=>{let{text:d}=a;typeof d=="string"?d=d:d=on(k.from(d),s.schema);let{from:u}=a,f=u+d.length;Hn({editor:e,from:u,to:f,text:d,rules:t,plugin:r})}),i.selectionSet||i.docChanged?null:o}},props:{handleTextInput(i,o,s,l){return Hn({editor:e,from:o,to:s,text:l,rules:t,plugin:r})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{let{$cursor:o}=i.state.selection;o&&Hn({editor:e,from:o.pos,to:o.pos,text:"",rules:t,plugin:r})}),!1)},handleKeyDown(i,o){if(o.key!=="Enter")return!1;let{$cursor:s}=i.state.selection;return s?Hn({editor:e,from:s.pos,to:s.pos,text:` +`,rules:t,plugin:r}):!1}},isInputRules:!0});return r}function Du(n){return Object.prototype.toString.call(n).slice(8,-1)}function Qt(n){return Du(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function sn(n,e){let t={...n};return Qt(n)&&Qt(e)&&Object.keys(e).forEach(r=>{Qt(e[r])&&Qt(n[r])?t[r]=sn(n[r],e[r]):t[r]=e[r]}),t}var Yn=class n{constructor(e={}){this.type="mark",this.name="mark",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...e},this.name=this.config.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=N(x(this,"addOptions",{name:this.name}))),this.storage=N(x(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(e={}){return new n(e)}configure(e={}){let t=this.extend({...this.config,addOptions:()=>sn(this.options,e)});return t.name=this.name,t.parent=this.parent,t}extend(e={}){let t=new n(e);return t.parent=this,this.child=t,t.name=e.name?e.name:t.parent.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${t.name}".`),t.options=N(x(t,"addOptions",{name:t.name})),t.storage=N(x(t,"addStorage",{name:t.name,options:t.options})),t}static handleExit({editor:e,mark:t}){let{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){let s=i.marks();if(!!!s.find(c=>c?.type.name===t.name))return!1;let a=s.find(c=>c?.type.name===t.name);return a&&r.removeStoredMark(a),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}};function Ul(n){return typeof n=="number"}var Ot=class{constructor(e){this.find=e.find,this.handler=e.handler}},Au=(n,e,t)=>{if(tr(e))return[...n.matchAll(e)];let r=e(n,t);return r?r.map(i=>{let o=[i.text];return o.index=i.index,o.input=n,o.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),o.push(i.replaceWith)),o}):[]};function vu(n){let{editor:e,state:t,from:r,to:i,rule:o,pasteEvent:s,dropEvent:l}=n,{commands:a,chain:c,can:d}=new ot({editor:e,state:t}),u=[];return t.doc.nodesBetween(r,i,(p,h)=>{if(!p.isTextblock||p.type.spec.code)return;let m=Math.max(r,h),g=Math.min(i,h+p.content.size),y=p.textBetween(m-h,g-h,void 0,"\uFFFC");Au(y,o.find,s).forEach(M=>{if(M.index===void 0)return;let A=m+M.index+1,v=A+M[0].length,B={from:t.tr.mapping.map(A),to:t.tr.mapping.map(v)},O=o.handler({state:t,range:B,match:M,commands:a,chain:c,can:d,pasteEvent:s,dropEvent:l});u.push(O)})}),u.every(p=>p!==null)}var qn=null,Ru=n=>{var e;let t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)===null||e===void 0||e.setData("text/html",n),t};function Gl(n){let{editor:e,rules:t}=n,r=null,i=!1,o=!1,s=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}let a=({state:d,from:u,to:f,rule:p,pasteEvt:h})=>{let m=d.tr,g=nn({state:d,transaction:m});if(!(!vu({editor:e,state:g,from:Math.max(u-1,0),to:f.b-1,rule:p,pasteEvent:h,dropEvent:l})||!m.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return s=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,m}};return t.map(d=>new P({view(u){let f=h=>{var m;r=!((m=u.dom.parentElement)===null||m===void 0)&&m.contains(h.target)?u.dom.parentElement:null,r&&(qn=e)},p=()=>{qn&&(qn=null)};return window.addEventListener("dragstart",f),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",f),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(u,f)=>{if(o=r===u.dom.parentElement,l=f,!o){let p=qn;p?.isEditable&&setTimeout(()=>{let h=p.state.selection;h&&p.commands.deleteRange({from:h.from,to:h.to})},10)}return!1},paste:(u,f)=>{var p;let h=(p=f.clipboardData)===null||p===void 0?void 0:p.getData("text/html");return s=f,i=!!h?.includes("data-pm-slice"),!1}}},appendTransaction:(u,f,p)=>{let h=u[0],m=h.getMeta("uiEvent")==="paste"&&!i,g=h.getMeta("uiEvent")==="drop"&&!o,y=h.getMeta("applyPasteRules"),w=!!y;if(!m&&!g&&!w)return;if(w){let{text:v}=y;typeof v=="string"?v=v:v=on(k.from(v),p.schema);let{from:B}=y,O=B+v.length,R=Ru(v);return a({rule:d,state:p,from:B,to:{b:O},pasteEvt:R})}let M=f.doc.content.findDiffStart(p.doc.content),A=f.doc.content.findDiffEnd(p.doc.content);if(!(!Ul(M)||!A||M===A.b))return a({rule:d,state:p,from:M,to:A,pasteEvt:s})}}))}function Yl(n){let e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}var Xn=class n{constructor(e,t){this.splittableMarks=[],this.editor=t,this.extensions=n.resolve(e),this.schema=Gi(this.extensions,t),this.setupExtensions()}static resolve(e){let t=n.sort(n.flatten(e)),r=Yl(t.map(i=>i.name));return r.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${r.map(i=>`'${i}'`).join(", ")}]. This can lead to issues.`),t}static flatten(e){return e.map(t=>{let r={name:t.name,options:t.options,storage:t.storage},i=x(t,"addExtensions",r);return i?[t,...this.flatten(i())]:t}).flat(10)}static sort(e){return e.sort((r,i)=>{let o=x(r,"priority")||100,s=x(i,"priority")||100;return o>s?-1:o{let r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:Un(t.name,this.schema)},i=x(t,"addCommands",r);return i?{...e,...i()}:e},{})}get plugins(){let{editor:e}=this,t=n.sort([...this.extensions].reverse()),r=[],i=[],o=t.map(s=>{let l={name:s.name,options:s.options,storage:s.storage,editor:e,type:Un(s.name,this.schema)},a=[],c=x(s,"addKeyboardShortcuts",l),d={};if(s.type==="mark"&&x(s,"exitable",l)&&(d.ArrowRight=()=>Yn.handleExit({editor:e,mark:s})),c){let m=Object.fromEntries(Object.entries(c()).map(([g,y])=>[g,()=>y({editor:e})]));d={...d,...m}}let u=fi(d);a.push(u);let f=x(s,"addInputRules",l);Li(s,e.options.enableInputRules)&&f&&r.push(...f());let p=x(s,"addPasteRules",l);Li(s,e.options.enablePasteRules)&&p&&i.push(...p());let h=x(s,"addProseMirrorPlugins",l);if(h){let m=h();a.push(...m)}return a}).flat();return[ql({editor:e,rules:r}),...Gl({editor:e,rules:i}),...o]}get attributes(){return qi(this.extensions)}get nodeViews(){let{editor:e}=this,{nodeExtensions:t}=rn(this.extensions);return Object.fromEntries(t.filter(r=>!!x(r,"addNodeView")).map(r=>{let i=this.attributes.filter(a=>a.type===r.name),o={name:r.name,options:r.options,storage:r.storage,editor:e,type:F(r.name,this.schema)},s=x(r,"addNodeView",o);if(!s)return[];let l=(a,c,d,u,f)=>{let p=Gn(a,i);return s()({node:a,view:c,getPos:d,decorations:u,innerDecorations:f,editor:e,extension:r,HTMLAttributes:p})};return[r.name,l]}))}setupExtensions(){this.extensions.forEach(e=>{var t;this.editor.extensionStorage[e.name]=e.storage;let r={name:e.name,options:e.options,storage:e.storage,editor:this.editor,type:Un(e.name,this.schema)};e.type==="mark"&&(!((t=N(x(e,"keepOnSplit",r)))!==null&&t!==void 0)||t)&&this.splittableMarks.push(e.name);let i=x(e,"onBeforeCreate",r),o=x(e,"onCreate",r),s=x(e,"onUpdate",r),l=x(e,"onSelectionUpdate",r),a=x(e,"onTransaction",r),c=x(e,"onFocus",r),d=x(e,"onBlur",r),u=x(e,"onDestroy",r);i&&this.editor.on("beforeCreate",i),o&&this.editor.on("create",o),s&&this.editor.on("update",s),l&&this.editor.on("selectionUpdate",l),a&&this.editor.on("transaction",a),c&&this.editor.on("focus",c),d&&this.editor.on("blur",d),u&&this.editor.on("destroy",u)})}},ue=class n{constructor(e={}){this.type="extension",this.name="extension",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...e},this.name=this.config.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=N(x(this,"addOptions",{name:this.name}))),this.storage=N(x(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(e={}){return new n(e)}configure(e={}){let t=this.extend({...this.config,addOptions:()=>sn(this.options,e)});return t.name=this.name,t.parent=this.parent,t}extend(e={}){let t=new n({...this.config,...e});return t.parent=this,this.child=t,t.name=e.name?e.name:t.parent.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${t.name}".`),t.options=N(x(t,"addOptions",{name:t.name})),t.storage=N(x(t,"addStorage",{name:t.name,options:t.options})),t}};function Yi(n,e,t){let{from:r,to:i}=e,{blockSeparator:o=` + +`,textSerializers:s={}}=t||{},l="";return n.nodesBetween(r,i,(a,c,d,u)=>{var f;a.isBlock&&c>r&&(l+=o);let p=s?.[a.type.name];if(p)return d&&(l+=p({node:a,pos:c,parent:d,index:u,range:e})),!1;a.isText&&(l+=(f=a?.text)===null||f===void 0?void 0:f.slice(Math.max(r,c)-c,i-c))}),l}function nr(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}var Xl=ue.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new P({key:new te("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{let{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,{ranges:o}=i,s=Math.min(...o.map(d=>d.$from.pos)),l=Math.max(...o.map(d=>d.$to.pos)),a=nr(t);return Yi(r,{from:s,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:a})}}})]}}),Iu=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{var t;n.isDestroyed||(e.dom.blur(),(t=window?.getSelection())===null||t===void 0||t.removeAllRanges())}),!0),Pu=(n=!1)=>({commands:e})=>e.setContent("",n),_u=()=>({state:n,tr:e,dispatch:t})=>{let{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:o,$to:s})=>{n.doc.nodesBetween(o.pos,s.pos,(l,a)=>{if(l.type.isText)return;let{doc:c,mapping:d}=e,u=c.resolve(d.map(a)),f=c.resolve(d.map(a+l.nodeSize)),p=u.blockRange(f);if(!p)return;let h=me(p);if(l.type.isTextblock){let{defaultType:m}=u.parent.contentMatchAt(u.index());e.setNodeMarkup(p.start,m)}(h||h===0)&&e.lift(p,h)})}),!0},Bu=n=>e=>n(e),zu=()=>({state:n,dispatch:e})=>Vn(n,e),Fu=(n,e)=>({editor:t,tr:r})=>{let{state:i}=t,o=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);let s=r.mapping.map(e);return r.insert(s,o.content),r.setSelection(new T(r.doc.resolve(Math.max(s-1,0)))),!0},Lu=()=>({tr:n,dispatch:e})=>{let{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;let i=n.selection.$anchor;for(let o=i.depth;o>0;o-=1)if(i.node(o).type===r.type){if(e){let l=i.before(o),a=i.after(o);n.delete(l,a).scrollIntoView()}return!0}return!1},Vu=n=>({tr:e,state:t,dispatch:r})=>{let i=F(n,t.schema),o=e.selection.$anchor;for(let s=o.depth;s>0;s-=1)if(o.node(s).type===i){if(r){let a=o.before(s),c=o.after(s);e.delete(a,c).scrollIntoView()}return!0}return!1},$u=n=>({tr:e,dispatch:t})=>{let{from:r,to:i}=n;return t&&e.delete(r,i),!0},ju=()=>({state:n,dispatch:e})=>Zt(n,e),Wu=()=>({commands:n})=>n.keyboardShortcut("Enter"),Ku=()=>({state:n,dispatch:e})=>Ln(n,e);function tn(n,e,t={strict:!0}){let r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:tr(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function Zl(n,e,t={}){return n.find(r=>r.type===e&&tn(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function $l(n,e,t={}){return!!Zl(n,e,t)}function rr(n,e,t){var r;if(!n||!e)return;let i=n.parent.childAfter(n.parentOffset);if((!i.node||!i.node.marks.some(d=>d.type===e))&&(i=n.parent.childBefore(n.parentOffset)),!i.node||!i.node.marks.some(d=>d.type===e)||(t=t||((r=i.node.marks[0])===null||r===void 0?void 0:r.attrs),!Zl([...i.node.marks],e,t)))return;let s=i.index,l=n.start()+i.offset,a=s+1,c=l+i.node.nodeSize;for(;s>0&&$l([...n.parent.child(s-1).marks],e,t);)s-=1,l-=n.parent.child(s).nodeSize;for(;a({tr:t,state:r,dispatch:i})=>{let o=De(n,r.schema),{doc:s,selection:l}=t,{$from:a,from:c,to:d}=l;if(i){let u=rr(a,o,e);if(u&&u.from<=c&&u.to>=d){let f=T.create(s,u.from,u.to);t.setSelection(f)}}return!0},Hu=n=>e=>{let t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:o})=>{e={scrollIntoView:!0,...e};let s=()=>{(Tt()||Vi())&&r.dom.focus(),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),Ql()&&!Tt()&&!Vi()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&n===null||n===!1)return!0;if(o&&n===null&&!Xi(t.state.selection))return s(),!0;let l=Zi(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return o&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),s()),!0},Uu=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Gu=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),ea=n=>{let e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){let r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&ea(r)}return n};function Et(n){let e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return ea(t)}function Nt(n,e,t){if(n instanceof Y||n instanceof k)return n;t={slice:!0,parseOptions:{},...t};let r=typeof n=="object"&&n!==null,i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return k.fromArray(n.map(l=>e.nodeFromJSON(l)));let s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(o){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:o});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",o),Nt("",e,t)}if(i){if(t.errorOnInvalidContent){let s=!1,l="",a=new ct({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(s=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?ce.fromSchema(a).parseSlice(Et(n),t.parseOptions):ce.fromSchema(a).parse(Et(n),t.parseOptions),t.errorOnInvalidContent&&s)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}let o=ce.fromSchema(e);return t.slice?o.parseSlice(Et(n),t.parseOptions).content:o.parse(Et(n),t.parseOptions)}return Nt("",e,t)}function ta(n,e,t){let r=n.steps.length-1;if(r{s===0&&(s=d)}),n.setSelection(E.near(n.doc.resolve(s),t))}var Yu=n=>!("type"in n),Xu=(n,e,t)=>({tr:r,dispatch:i,editor:o})=>{var s;if(i){t={parseOptions:o.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l,a=g=>{o.emit("contentError",{editor:o,error:g,disableCollaboration:()=>{o.storage.collaboration&&(o.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!o.options.enableContentCheck&&o.options.emitContentError)try{Nt(e,o.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{l=Nt(e,o.schema,{parseOptions:c,errorOnInvalidContent:(s=t.errorOnInvalidContent)!==null&&s!==void 0?s:o.options.enableContentCheck})}catch(g){return a(g),!1}let{from:d,to:u}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},f=!0,p=!0;if((Yu(l)?l:[l]).forEach(g=>{g.check(),f=f?g.isText&&g.marks.length===0:!1,p=p?g.isBlock:!1}),d===u&&p){let{parent:g}=r.doc.resolve(d);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(d-=1,u+=1)}let m;if(f){if(Array.isArray(e))m=e.map(g=>g.text||"").join("");else if(e instanceof k){let g="";e.forEach(y=>{y.text&&(g+=y.text)}),m=g}else typeof e=="object"&&e&&e.text?m=e.text:m=e;r.insertText(m,d,u)}else m=l,r.replaceWith(d,u,m);t.updateSelection&&ta(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:d,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:d,text:m})}return!0},Zu=()=>({state:n,dispatch:e})=>Si(n,e),Qu=()=>({state:n,dispatch:e})=>Ci(n,e),ef=()=>({state:n,dispatch:e})=>Pn(n,e),tf=()=>({state:n,dispatch:e})=>Bn(n,e),nf=()=>({state:n,dispatch:e,tr:t})=>{try{let r=Ue(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},rf=()=>({state:n,dispatch:e,tr:t})=>{try{let r=Ue(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},of=()=>({state:n,dispatch:e})=>yi(n,e),sf=()=>({state:n,dispatch:e})=>ki(n,e);function Qi(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function lf(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t==="Space"&&(t=" ");let r,i,o,s;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{let o=lf(n).split(/-(?!$)/),s=o.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:s==="Space"?" ":s,altKey:o.includes("Alt"),ctrlKey:o.includes("Ctrl"),metaKey:o.includes("Meta"),shiftKey:o.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{let d=c.map(r.mapping);d&&i&&r.maybeStep(d)}),!0};function Dt(n,e,t={}){let{from:r,to:i,empty:o}=n.selection,s=e?F(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(u,f)=>{if(u.isText)return;let p=Math.max(r,f),h=Math.min(i,f+u.nodeSize);l.push({node:u,from:p,to:h})});let a=i-r,c=l.filter(u=>s?s.name===u.node.type.name:!0).filter(u=>tn(u.node.attrs,t,{strict:!1}));return o?!!c.length:c.reduce((u,f)=>u+f.to-f.from,0)>=a}var cf=(n,e={})=>({state:t,dispatch:r})=>{let i=F(n,t.schema);return Dt(t,i,e)?wi(t,r):!1},df=()=>({state:n,dispatch:e})=>$n(n,e),uf=n=>({state:e,dispatch:t})=>{let r=F(n,e.schema);return Ri(r)(e,t)},ff=()=>({state:n,dispatch:e})=>Fn(n,e);function ln(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function $i(n,e){let t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}var pf=(n,e)=>({tr:t,state:r,dispatch:i})=>{let o=null,s=null,l=ln(typeof n=="string"?n:n.name,r.schema);return l?(l==="node"&&(o=F(n,r.schema)),l==="mark"&&(s=De(n,r.schema)),i&&t.selection.ranges.forEach(a=>{r.doc.nodesBetween(a.$from.pos,a.$to.pos,(c,d)=>{o&&o===c.type&&t.setNodeMarkup(d,void 0,$i(c.attrs,e)),s&&c.marks.length&&c.marks.forEach(u=>{s===u.type&&t.addMark(d,d+c.nodeSize,s.create($i(u.attrs,e)))})})}),!0):!1},hf=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),mf=()=>({tr:n,dispatch:e})=>{if(e){let t=new q(n.doc);n.setSelection(t)}return!0},gf=()=>({state:n,dispatch:e})=>_n(n,e),yf=()=>({state:n,dispatch:e})=>zn(n,e),kf=()=>({state:n,dispatch:e})=>Oi(n,e),bf=()=>({state:n,dispatch:e})=>Wn(n,e),xf=()=>({state:n,dispatch:e})=>jn(n,e);function Zn(n,e,t={},r={}){return Nt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}var Sf=(n,e=!1,t={},r={})=>({editor:i,tr:o,dispatch:s,commands:l})=>{var a,c;let{doc:d}=o;if(t.preserveWhitespace!=="full"){let u=Zn(n,i.schema,t,{errorOnInvalidContent:(a=r.errorOnInvalidContent)!==null&&a!==void 0?a:i.options.enableContentCheck});return s&&o.replaceWith(0,d.content.size,u).setMeta("preventUpdate",!e),!0}return s&&o.setMeta("preventUpdate",!e),l.insertContentAt({from:0,to:d.content.size},n,{parseOptions:t,errorOnInvalidContent:(c=r.errorOnInvalidContent)!==null&&c!==void 0?c:i.options.enableContentCheck})};function eo(n,e){let t=De(e,n.schema),{from:r,to:i,empty:o}=n.selection,s=[];o?(n.storedMarks&&s.push(...n.storedMarks),s.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{s.push(...a.marks)});let l=s.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function Cf(n,e){let t=new He(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function na(n){for(let e=0;e{e(r)&&t.push({node:r,pos:i})}),t}function Mf(n,e,t){let r=[];return n.nodesBetween(e.from,e.to,(i,o)=>{t(i)&&r.push({node:i,pos:o})}),r}function ra(n,e){for(let t=n.depth;t>0;t-=1){let r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function an(n){return e=>ra(e.$from,n)}function ir(n,e){let t=Xn.resolve(n);return Gi(t,e)}function Ef(n,e){let t=ir(e),r=Y.fromJSON(t,n);return on(r.content,t)}function Of(n,e){let t=ir(e),r=Et(n);return ce.fromSchema(t).parse(r).toJSON()}function to(n,e){let t={from:0,to:n.content.size};return Yi(n,t,e)}function Tf(n,e,t){let{blockSeparator:r=` + +`,textSerializers:i={}}=t||{},o=ir(e),s=Y.fromJSON(o,n);return to(s,{blockSeparator:r,textSerializers:{...nr(o),...i}})}function ia(n,e){let t=F(e,n.schema),{from:r,to:i}=n.selection,o=[];n.doc.nodesBetween(r,i,l=>{o.push(l)});let s=o.reverse().find(l=>l.type.name===t.name);return s?{...s.attrs}:{}}function oa(n,e){let t=ln(typeof e=="string"?e:e.name,n.schema);return t==="node"?ia(n,e):t==="mark"?eo(n,e):{}}function sa(n,e=JSON.stringify){let t={};return n.filter(r=>{let i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Nf(n){let e=sa(n);return e.length===1?e:e.filter((t,r)=>!e.filter((o,s)=>s!==r).some(o=>t.oldRange.from>=o.oldRange.from&&t.oldRange.to<=o.oldRange.to&&t.newRange.from>=o.newRange.from&&t.newRange.to<=o.newRange.to))}function Df(n){let{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,o)=>{let s=[];if(i.ranges.length)i.forEach((l,a)=>{s.push({from:l,to:a})});else{let{from:l,to:a}=t[o];if(l===void 0||a===void 0)return;s.push({from:l,to:a})}s.forEach(({from:l,to:a})=>{let c=e.slice(o).map(l,-1),d=e.slice(o).map(a),u=e.invert().map(c,-1),f=e.invert().map(d);r.push({oldRange:{from:u,to:f},newRange:{from:c,to:d}})})}),Nf(r)}function la(n,e=0){let r=n.type===n.type.schema.topNodeType?0:1,i=e,o=i+n.nodeSize,s=n.marks.map(c=>{let d={type:c.type.name};return Object.keys(c.attrs).length&&(d.attrs={...c.attrs}),d}),l={...n.attrs},a={type:n.type.name,from:i,to:o};return Object.keys(l).length&&(a.attrs=l),s.length&&(a.marks=s),n.content.childCount&&(a.content=[],n.forEach((c,d)=>{var u;(u=a.content)===null||u===void 0||u.push(la(c,e+d+r))})),n.text&&(a.text=n.text),a}function no(n,e,t){let r=[];return n===e?t.resolve(n).marks().forEach(i=>{let o=t.resolve(n),s=rr(o,i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,o)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(s=>({from:o,to:o+i.nodeSize,mark:s})))}),r}var Af=(n,e,t,r=20)=>{let i=n.doc.resolve(t),o=r,s=null;for(;o>0&&s===null;){let l=i.node(o);l?.type.name===e?s=l:o-=1}return[s,o]};function en(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{let i=n.find(o=>o.type===e&&o.name===r);return i?i.attribute.keepOnSplit:!1}))}function Qn(n,e,t={}){let{empty:r,ranges:i}=n.selection,o=e?De(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(u=>o?o.name===u.type.name:!0).find(u=>tn(u.attrs,t,{strict:!1}));let s=0,l=[];if(i.forEach(({$from:u,$to:f})=>{let p=u.pos,h=f.pos;n.doc.nodesBetween(p,h,(m,g)=>{if(!m.isText&&!m.marks.length)return;let y=Math.max(p,g),w=Math.min(h,g+m.nodeSize),M=w-y;s+=M,l.push(...m.marks.map(A=>({mark:A,from:y,to:w})))})}),s===0)return!1;let a=l.filter(u=>o?o.name===u.mark.type.name:!0).filter(u=>tn(u.mark.attrs,t,{strict:!1})).reduce((u,f)=>u+f.to-f.from,0),c=l.filter(u=>o?u.mark.type!==o&&u.mark.type.excludes(o):!0).reduce((u,f)=>u+f.to-f.from,0);return(a>0?a+c:a)>=s}function aa(n,e,t={}){if(!e)return Dt(n,null,t)||Qn(n,null,t);let r=ln(e,n.schema);return r==="node"?Dt(n,e,t):r==="mark"?Qn(n,e,t):!1}var vf=(n,e)=>{let{$from:t,$to:r,$anchor:i}=n.selection;if(e){let o=an(l=>l.type.name===e)(n.selection);if(!o)return!1;let s=n.doc.resolve(o.pos+1);return i.pos+1===s.end()}return!(r.parentOffset{let{$from:e,$to:t}=n.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function ji(n,e){let{nodeExtensions:t}=rn(e),r=t.find(s=>s.name===n);if(!r)return!1;let i={name:r.name,options:r.options,storage:r.storage},o=N(x(r,"group",i));return typeof o!="string"?!1:o.split(" ").includes("list")}function or(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){var r;if(t){if(n.type.name==="hardBreak")return!0;if(n.isText)return/^\s*$/m.test((r=n.text)!==null&&r!==void 0?r:"")}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(o=>{i!==!1&&(or(o,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function If(n){return n instanceof S}function Pf(n,e,t){let i=n.state.doc.content.size,o=be(e,0,i),s=be(t,0,i),l=n.coordsAtPos(o),a=n.coordsAtPos(s,-1),c=Math.min(l.top,a.top),d=Math.max(l.bottom,a.bottom),u=Math.min(l.left,a.left),f=Math.max(l.right,a.right),p=f-u,h=d-c,y={top:c,bottom:d,left:u,right:f,width:p,height:h,x:u,y:c};return{...y,toJSON:()=>y}}function ca({json:n,validMarks:e,validNodes:t,options:r,rewrittenContent:i=[]}){return n.marks&&Array.isArray(n.marks)&&(n.marks=n.marks.filter(o=>{let s=typeof o=="string"?o:o.type;return e.has(s)?!0:(i.push({original:JSON.parse(JSON.stringify(o)),unsupported:s}),!1)})),n.content&&Array.isArray(n.content)&&(n.content=n.content.map(o=>ca({json:o,validMarks:e,validNodes:t,options:r,rewrittenContent:i}).json).filter(o=>o!=null)),n.type&&!t.has(n.type)?(i.push({original:JSON.parse(JSON.stringify(n)),unsupported:n.type}),n.content&&Array.isArray(n.content)&&r?.fallbackToParagraph!==!1?(n.type="paragraph",{json:n,rewrittenContent:i}):{json:null,rewrittenContent:i}):{json:n,rewrittenContent:i}}function _f(n,e,t){return ca({json:n,validNodes:new Set(Object.keys(e.nodes)),validMarks:new Set(Object.keys(e.marks)),options:t})}function Bf(n,e,t){var r;let{selection:i}=e,o=null;if(Xi(i)&&(o=i.$cursor),o){let l=(r=n.storedMarks)!==null&&r!==void 0?r:o.marks();return!!t.isInSet(l)||!l.some(a=>a.type.excludes(t))}let{ranges:s}=i;return s.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(d,u,f)=>{if(c)return!1;if(d.isInline){let p=!f||f.type.allowsMarkType(t),h=!!t.isInSet(d.marks)||!d.marks.some(m=>m.type.excludes(t));c=p&&h}return!c}),c})}var zf=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let{selection:o}=t,{empty:s,ranges:l}=o,a=De(n,r.schema);if(i)if(s){let c=eo(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{let d=c.$from.pos,u=c.$to.pos;r.doc.nodesBetween(d,u,(f,p)=>{let h=Math.max(p,d),m=Math.min(p+f.nodeSize,u);f.marks.find(y=>y.type===a)?f.marks.forEach(y=>{a===y.type&&t.addMark(h,m,a.create({...y.attrs,...e}))}):t.addMark(h,m,a.create(e))})});return Bf(r,t,a)},Ff=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),Lf=(n,e={})=>({state:t,dispatch:r,chain:i})=>{let o=F(n,t.schema),s;return t.selection.$anchor.sameParent(t.selection.$head)&&(s=t.selection.$anchor.parent.attrs),o.isTextblock?i().command(({commands:l})=>Kn(o,{...s,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Kn(o,{...s,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Vf=n=>({tr:e,dispatch:t})=>{if(t){let{doc:r}=e,i=be(n,0,r.content.size),o=S.create(r,i);e.setSelection(o)}return!0},$f=n=>({tr:e,dispatch:t})=>{if(t){let{doc:r}=e,{from:i,to:o}=typeof n=="number"?{from:n,to:n}:n,s=T.atStart(r).from,l=T.atEnd(r).to,a=be(i,s,l),c=be(o,s,l),d=T.create(r,a,c);e.setSelection(d)}return!0},jf=n=>({state:e,dispatch:t})=>{let r=F(n,e.schema);return Ii(r)(e,t)};function jl(n,e){let t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){let r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}var Wf=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{let{selection:o,doc:s}=e,{$from:l,$to:a}=o,c=i.extensionManager.attributes,d=en(c,l.node().type.name,l.node().attrs);if(o instanceof S&&o.node.isBlock)return!l.parentOffset||!ee(s,l.pos)?!1:(r&&(n&&jl(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;let u=a.parentOffset===a.parent.content.size,f=l.depth===0?void 0:na(l.node(-1).contentMatchAt(l.indexAfter(-1))),p=u&&f?[{type:f,attrs:d}]:void 0,h=ee(e.doc,e.mapping.map(l.pos),1,p);if(!p&&!h&&ee(e.doc,e.mapping.map(l.pos),1,f?[{type:f}]:void 0)&&(h=!0,p=f?[{type:f,attrs:d}]:void 0),r){if(h&&(o instanceof T&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,p),f&&!u&&!l.parentOffset&&l.parent.type!==f)){let m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,f)&&e.setNodeMarkup(e.mapping.map(l.before()),f)}n&&jl(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return h},Kf=(n,e={})=>({tr:t,state:r,dispatch:i,editor:o})=>{var s;let l=F(n,r.schema),{$from:a,$to:c}=r.selection,d=r.selection.node;if(d&&d.isBlock||a.depth<2||!a.sameParent(c))return!1;let u=a.node(-1);if(u.type!==l)return!1;let f=o.extensionManager.attributes;if(a.parent.content.size===0&&a.node(-1).childCount===a.indexAfter(-1)){if(a.depth===2||a.node(-3).type!==l||a.index(-2)!==a.node(-2).childCount-1)return!1;if(i){let y=k.empty,w=a.index(-1)?1:a.index(-2)?2:3;for(let R=a.depth-w;R>=a.depth-3;R-=1)y=k.from(a.node(R).copy(y));let M=a.indexAfter(-1){if(O>-1)return!1;R.isTextblock&&R.content.size===0&&(O=J+1)}),O>-1&&t.setSelection(T.near(t.doc.resolve(O))),t.scrollIntoView()}return!0}let p=c.pos===a.end()?u.contentMatchAt(0).defaultType:null,h={...en(f,u.type.name,u.attrs),...e},m={...en(f,a.node().type.name,a.node().attrs),...e};t.delete(a.pos,c.pos);let g=p?[{type:l,attrs:h},{type:p,attrs:m}]:[{type:l,attrs:h}];if(!ee(t.doc,a.pos,2))return!1;if(i){let{selection:y,storedMarks:w}=r,{splittableMarks:M}=o.extensionManager,A=w||y.$to.parentOffset&&y.$from.marks();if(t.split(a.pos,2,g).scrollIntoView(),!A||!i)return!0;let v=A.filter(B=>M.includes(B.type.name));t.ensureMarks(v)}return!0},_i=(n,e)=>{let t=an(s=>s.type===e)(n.selection);if(!t)return!0;let r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;let i=n.doc.nodeAt(r);return t.node.type===i?.type&&re(n.doc,t.pos)&&n.join(t.pos),!0},Bi=(n,e)=>{let t=an(s=>s.type===e)(n.selection);if(!t)return!0;let r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;let i=n.doc.nodeAt(r);return t.node.type===i?.type&&re(n.doc,r)&&n.join(r),!0},Jf=(n,e,t,r={})=>({editor:i,tr:o,state:s,dispatch:l,chain:a,commands:c,can:d})=>{let{extensions:u,splittableMarks:f}=i.extensionManager,p=F(n,s.schema),h=F(e,s.schema),{selection:m,storedMarks:g}=s,{$from:y,$to:w}=m,M=y.blockRange(w),A=g||m.$to.parentOffset&&m.$from.marks();if(!M)return!1;let v=an(B=>ji(B.type.name,u))(m);if(M.depth>=1&&v&&M.depth-v.depth<=1){if(v.node.type===p)return c.liftListItem(h);if(ji(v.node.type.name,u)&&p.validContent(v.node.content)&&l)return a().command(()=>(o.setNodeMarkup(v.pos,p),!0)).command(()=>_i(o,p)).command(()=>Bi(o,p)).run()}return!t||!A||!l?a().command(()=>d().wrapInList(p,r)?!0:c.clearNodes()).wrapInList(p,r).command(()=>_i(o,p)).command(()=>Bi(o,p)).run():a().command(()=>{let B=d().wrapInList(p,r),O=A.filter(R=>f.includes(R.type.name));return o.ensureMarks(O),B?!0:c.clearNodes()}).wrapInList(p,r).command(()=>_i(o,p)).command(()=>Bi(o,p)).run()},Hf=(n,e={},t={})=>({state:r,commands:i})=>{let{extendEmptyMarkRange:o=!1}=t,s=De(n,r.schema);return Qn(r,s,e)?i.unsetMark(s,{extendEmptyMarkRange:o}):i.setMark(s,e)},qf=(n,e,t={})=>({state:r,commands:i})=>{let o=F(n,r.schema),s=F(e,r.schema),l=Dt(r,o,t),a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(s,a):i.setNode(o,{...a,...t})},Uf=(n,e={})=>({state:t,commands:r})=>{let i=F(n,t.schema);return Dt(t,i,e)?r.lift(i):r.wrapIn(i,e)},Gf=()=>({state:n,dispatch:e})=>{let t=n.plugins;for(let r=0;r=0;a-=1)s.step(l.steps[a].invert(l.docs[a]));if(o.text){let a=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,n.schema.text(o.text,a))}else s.delete(o.from,o.to)}return!0}}return!1},Yf=()=>({tr:n,dispatch:e})=>{let{selection:t}=n,{empty:r,ranges:i}=t;return r||e&&i.forEach(o=>{n.removeMark(o.$from.pos,o.$to.pos)}),!0},Xf=(n,e={})=>({tr:t,state:r,dispatch:i})=>{var o;let{extendEmptyMarkRange:s=!1}=e,{selection:l}=t,a=De(n,r.schema),{$from:c,empty:d,ranges:u}=l;if(!i)return!0;if(d&&s){let{from:f,to:p}=l,h=(o=c.marks().find(g=>g.type===a))===null||o===void 0?void 0:o.attrs,m=rr(c,a,h);m&&(f=m.from,p=m.to),t.removeMark(f,p,a)}else u.forEach(f=>{t.removeMark(f.$from.pos,f.$to.pos,a)});return t.removeStoredMark(a),!0},Zf=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let o=null,s=null,l=ln(typeof n=="string"?n:n.name,r.schema);return l?(l==="node"&&(o=F(n,r.schema)),l==="mark"&&(s=De(n,r.schema)),i&&t.selection.ranges.forEach(a=>{let c=a.$from.pos,d=a.$to.pos,u,f,p,h;t.selection.empty?r.doc.nodesBetween(c,d,(m,g)=>{o&&o===m.type&&(p=Math.max(g,c),h=Math.min(g+m.nodeSize,d),u=g,f=m)}):r.doc.nodesBetween(c,d,(m,g)=>{g=c&&g<=d&&(o&&o===m.type&&t.setNodeMarkup(g,void 0,{...m.attrs,...e}),s&&m.marks.length&&m.marks.forEach(y=>{if(s===y.type){let w=Math.max(g,c),M=Math.min(g+m.nodeSize,d);t.addMark(w,M,s.create({...y.attrs,...e}))}}))}),f&&(u!==void 0&&t.setNodeMarkup(u,void 0,{...f.attrs,...e}),s&&f.marks.length&&f.marks.forEach(m=>{s===m.type&&t.addMark(p,h,s.create({...m.attrs,...e}))}))}),!0):!1},Qf=(n,e={})=>({state:t,dispatch:r})=>{let i=F(n,t.schema);return Ti(i,e)(t,r)},ep=(n,e={})=>({state:t,dispatch:r})=>{let i=F(n,t.schema);return vi(i,e)(t,r)},tp=Object.freeze({__proto__:null,blur:Iu,clearContent:Pu,clearNodes:_u,command:Bu,createParagraphNear:zu,cut:Fu,deleteCurrentNode:Lu,deleteNode:Vu,deleteRange:$u,deleteSelection:ju,enter:Wu,exitCode:Ku,extendMarkRange:Ju,first:Hu,focus:qu,forEach:Uu,insertContent:Gu,insertContentAt:Xu,joinBackward:ef,joinDown:Qu,joinForward:tf,joinItemBackward:nf,joinItemForward:rf,joinTextblockBackward:of,joinTextblockForward:sf,joinUp:Zu,keyboardShortcut:af,lift:cf,liftEmptyBlock:df,liftListItem:uf,newlineInCode:ff,resetAttributes:pf,scrollIntoView:hf,selectAll:mf,selectNodeBackward:gf,selectNodeForward:yf,selectParentNode:kf,selectTextblockEnd:bf,selectTextblockStart:xf,setContent:Sf,setMark:zf,setMeta:Ff,setNode:Lf,setNodeSelection:Vf,setTextSelection:$f,sinkListItem:jf,splitBlock:Wf,splitListItem:Kf,toggleList:Jf,toggleMark:Hf,toggleNode:qf,toggleWrap:Uf,undoInputRule:Gf,unsetAllMarks:Yf,unsetMark:Xf,updateAttributes:Zf,wrapIn:Qf,wrapInList:ep}),da=ue.create({name:"commands",addCommands(){return{...tp}}}),ua=ue.create({name:"drop",addProseMirrorPlugins(){return[new P({key:new te("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),fa=ue.create({name:"editable",addProseMirrorPlugins(){return[new P({key:new te("editable"),props:{editable:()=>this.editor.options.editable}})]}}),pa=new te("focusEvents"),ha=ue.create({name:"focusEvents",addProseMirrorPlugins(){let{editor:n}=this;return[new P({key:pa,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;let r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;let r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),ma=ue.create({name:"keymap",addKeyboardShortcuts(){let n=()=>this.editor.commands.first(({commands:s})=>[()=>s.undoInputRule(),()=>s.command(({tr:l})=>{let{selection:a,doc:c}=l,{empty:d,$anchor:u}=a,{pos:f,parent:p}=u,h=u.parent.isTextblock&&f>0?l.doc.resolve(f-1):u,m=h.parent.type.spec.isolating,g=u.pos-u.parentOffset,y=m&&h.parent.childCount===1?g===u.pos:E.atStart(c).from===f;return!d||!p.type.isTextblock||p.textContent.length||!y||y&&u.parent.type.name==="paragraph"?!1:s.clearNodes()}),()=>s.deleteSelection(),()=>s.joinBackward(),()=>s.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:s})=>[()=>s.deleteSelection(),()=>s.deleteCurrentNode(),()=>s.joinForward(),()=>s.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:s})=>[()=>s.newlineInCode(),()=>s.createParagraphNear(),()=>s.liftEmptyBlock(),()=>s.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},o={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Tt()||Qi()?o:i},addProseMirrorPlugins(){return[new P({key:new te("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(m=>m.getMeta("composition")))return;let r=n.some(m=>m.docChanged)&&!e.doc.eq(t.doc),i=n.some(m=>m.getMeta("preventClearDocument"));if(!r||i)return;let{empty:o,from:s,to:l}=e.selection,a=E.atStart(e.doc).from,c=E.atEnd(e.doc).to;if(o||!(s===a&&l===c)||!or(t.doc))return;let f=t.tr,p=nn({state:t,transaction:f}),{commands:h}=new ot({editor:this.editor,state:p});if(h.clearNodes(),!!f.steps.length)return f}})]}}),ga=ue.create({name:"paste",addProseMirrorPlugins(){return[new P({key:new te("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),ya=ue.create({name:"tabindex",addProseMirrorPlugins(){return[new P({key:new te("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),np=Object.freeze({__proto__:null,ClipboardTextSerializer:Xl,Commands:da,Drop:ua,Editable:fa,FocusEvents:ha,Keymap:ma,Paste:ga,Tabindex:ya,focusEventsPluginKey:pa}),er=class n{get name(){return this.node.type.name}constructor(e,t,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=t,this.currentNode=i}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!==null&&e!==void 0?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let t=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can\u2019t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}t=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:t,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;let e=this.resolvedPos.start(this.resolvedPos.depth-1),t=this.resolvedPos.doc.resolve(e);return new n(t,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new n(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new n(e,this.editor)}get children(){let e=[];return this.node.content.forEach((t,r)=>{let i=t.isBlock&&!t.isTextblock,o=t.isAtom&&!t.isText,s=this.pos+r+(o?0:1);if(s<0||s>this.resolvedPos.doc.nodeSize-2)return;let l=this.resolvedPos.doc.resolve(s);if(!i&&l.depth<=this.depth)return;let a=new n(l,this.editor,i,i?t:null);i&&(a.actualDepth=this.depth+1),e.push(new n(l,this.editor,i,i?t:null))}),e}get firstChild(){return this.children[0]||null}get lastChild(){let e=this.children;return e[e.length-1]||null}closest(e,t={}){let r=null,i=this.parent;for(;i&&!r;){if(i.node.type.name===e)if(Object.keys(t).length>0){let o=i.node.attrs,s=Object.keys(t);for(let l=0;l{r&&i.length>0||(s.node.type.name===e&&o.every(a=>t[a]===s.node.attrs[a])&&i.push(s),!(r&&i.length>0)&&(i=i.concat(s.querySelectorAll(e,t,r))))}),i}setAttribute(e){let{tr:t}=this.editor.state;t.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(t)}},rp=`.ProseMirror { + position: relative; +} + +.ProseMirror { + word-wrap: break-word; + white-space: pre-wrap; + white-space: break-spaces; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ +} + +.ProseMirror [contenteditable="false"] { + white-space: normal; +} + +.ProseMirror [contenteditable="false"] [contenteditable="true"] { + white-space: pre-wrap; +} + +.ProseMirror pre { + white-space: pre-wrap; +} + +img.ProseMirror-separator { + display: inline !important; + border: none !important; + margin: 0 !important; + width: 0 !important; + height: 0 !important; +} + +.ProseMirror-gapcursor { + display: none; + pointer-events: none; + position: absolute; + margin: 0; +} + +.ProseMirror-gapcursor:after { + content: ""; + display: block; + position: absolute; + top: -2px; + width: 20px; + border-top: 1px solid black; + animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; +} + +@keyframes ProseMirror-cursor-blink { + to { + visibility: hidden; + } +} + +.ProseMirror-hideselection *::selection { + background: transparent; +} + +.ProseMirror-hideselection *::-moz-selection { + background: transparent; +} + +.ProseMirror-hideselection * { + caret-color: transparent; +} + +.ProseMirror-focused .ProseMirror-gapcursor { + display: block; +} + +.tippy-box[data-animation=fade][data-state=hidden] { + opacity: 0 +}`;function ka(n,e,t){let r=document.querySelector(`style[data-tiptap-style${t?`-${t}`:""}]`);if(r!==null)return r;let i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute(`data-tiptap-style${t?`-${t}`:""}`,""),i.innerHTML=n,document.getElementsByTagName("head")[0].appendChild(i),i}var Wi=class extends zi{constructor(e={}){super(),this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.options={element:document.createElement("div"),content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:t})=>{throw t},onPaste:()=>null,onDrop:()=>null},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("contentError",this.options.onContentError),this.createView(),this.injectCSS(),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:t,slice:r,moved:i})=>this.options.onDrop(t,r,i)),this.on("paste",({event:t,slice:r})=>this.options.onPaste(t,r)),window.setTimeout(()=>{this.isDestroyed||(this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&document&&(this.css=ka(rp,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},!(!this.view||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(e,t=!0){this.setOptions({editable:e}),t&&this.emit("update",{editor:this,transaction:this.state.tr})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get state(){return this.view.state}registerPlugin(e,t){let r=Ui(t)?t(e,[...this.state.plugins]):[...this.state.plugins,e],i=this.state.reconfigure({plugins:r});return this.view.updateState(i),i}unregisterPlugin(e){if(this.isDestroyed)return;let t=this.state.plugins,r=t;if([].concat(e).forEach(o=>{let s=typeof o=="string"?`${o}$`:o.key;r=r.filter(l=>!l.key.startsWith(s))}),t.length===r.length)return;let i=this.state.reconfigure({plugins:r});return this.view.updateState(i),i}createExtensionManager(){var e,t;let i=[...this.options.enableCoreExtensions?[fa,Xl.configure({blockSeparator:(t=(e=this.options.coreExtensionOptions)===null||e===void 0?void 0:e.clipboardTextSerializer)===null||t===void 0?void 0:t.blockSeparator}),da,ha,ma,ya,ua,ga].filter(o=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[o.name]!==!1:!0):[],...this.options.extensions].filter(o=>["extension","node","mark"].includes(o?.type));this.extensionManager=new Xn(i,this)}createCommandManager(){this.commandManager=new ot({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var e;let t;try{t=Zn(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(s){if(!(s instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(s.message))throw s;this.emit("contentError",{editor:this,error:s,disableCollaboration:()=>{this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(l=>l.name!=="collaboration"),this.createExtensionManager()}}),t=Zn(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}let r=Zi(t,this.options.autofocus);this.view=new wt(this.options.element,{...this.options.editorProps,attributes:{role:"textbox",...(e=this.options.editorProps)===null||e===void 0?void 0:e.attributes},dispatchTransaction:this.dispatchTransaction.bind(this),state:jt.create({doc:t,selection:r||void 0})});let i=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(i),this.createNodeViews(),this.prependClass();let o=this.view.dom;o.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`tiptap ${this.view.dom.className}`}captureTransaction(e){this.isCapturingTransaction=!0,e(),this.isCapturingTransaction=!1;let t=this.capturedTransaction;return this.capturedTransaction=null,t}dispatchTransaction(e){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=e;return}e.steps.forEach(s=>{var l;return(l=this.capturedTransaction)===null||l===void 0?void 0:l.step(s)});return}let t=this.state.apply(e),r=!this.state.selection.eq(t.selection);this.emit("beforeTransaction",{editor:this,transaction:e,nextState:t}),this.view.updateState(t),this.emit("transaction",{editor:this,transaction:e}),r&&this.emit("selectionUpdate",{editor:this,transaction:e});let i=e.getMeta("focus"),o=e.getMeta("blur");i&&this.emit("focus",{editor:this,event:i.event,transaction:e}),o&&this.emit("blur",{editor:this,event:o.event,transaction:e}),!(!e.docChanged||e.getMeta("preventUpdate"))&&this.emit("update",{editor:this,transaction:e})}getAttributes(e){return oa(this.state,e)}isActive(e,t){let r=typeof e=="string"?e:null,i=typeof e=="string"?t:e;return aa(this.state,r,i)}getJSON(){return this.state.doc.toJSON()}getHTML(){return on(this.state.doc.content,this.schema)}getText(e){let{blockSeparator:t=` + +`,textSerializers:r={}}=e||{};return to(this.state.doc,{blockSeparator:t,textSerializers:{...nr(this.schema),...r}})}get isEmpty(){return or(this.state.doc)}getCharacterCount(){return console.warn('[tiptap warn]: "editor.getCharacterCount()" is deprecated. Please use "editor.storage.characterCount.characters()" instead.'),this.state.doc.content.size-2}destroy(){if(this.emit("destroy"),this.view){let e=this.view.dom;e&&e.editor&&delete e.editor,this.view.destroy()}this.removeAllListeners()}get isDestroyed(){var e;return!(!((e=this.view)===null||e===void 0)&&e.docView)}$node(e,t){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelector(e,t))||null}$nodes(e,t){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelectorAll(e,t))||null}$pos(e){let t=this.state.doc.resolve(e);return new er(t,this)}get $doc(){return this.$pos(0)}};function ip(n){return new $e({find:n.find,handler:({state:e,range:t,match:r})=>{let i=N(n.getAttributes,void 0,r);if(i===!1||i===null)return null;let{tr:o}=e,s=r[r.length-1],l=r[0];if(s){let a=l.search(/\S/),c=t.from+l.indexOf(s),d=c+s.length;if(no(t.from,t.to,e.doc).filter(p=>p.mark.type.excluded.find(m=>m===n.type&&m!==p.mark.type)).filter(p=>p.to>c).length)return null;dt.from&&o.delete(t.from+a,c);let f=t.from+a+s.length;o.addMark(t.from+a,f,n.type.create(i||{})),o.removeStoredMark(n.type)}}})}function op(n){return new $e({find:n.find,handler:({state:e,range:t,match:r})=>{let i=N(n.getAttributes,void 0,r)||{},{tr:o}=e,s=t.from,l=t.to,a=n.type.create(i);if(r[1]){let c=r[0].lastIndexOf(r[1]),d=s+c;d>l?d=l:l=d+r[1].length;let u=r[0][r[0].length-1];o.insertText(u,s+r[0].length-1),o.replaceWith(d,l,a)}else if(r[0]){let c=n.type.isInline?s:s-1;o.insert(c,n.type.create(i)).delete(o.mapping.map(s),o.mapping.map(l))}o.scrollIntoView()}})}function sp(n){return new $e({find:n.find,handler:({state:e,range:t,match:r})=>{let i=e.doc.resolve(t.from),o=N(n.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),n.type))return null;e.tr.delete(t.from,t.to).setBlockType(t.from,t.from,n.type,o)}})}function lp(n){return new $e({find:n.find,handler:({state:e,range:t,match:r})=>{let i=n.replace,o=t.from,s=t.to;if(r[1]){let l=r[0].lastIndexOf(r[1]);i+=r[0].slice(l+r[1].length),o+=l;let a=o-s;a>0&&(i=r[0].slice(l-a,l)+i,o=s)}e.tr.insertText(i,o,s)}})}function ap(n){return new $e({find:n.find,handler:({state:e,range:t,match:r,chain:i})=>{let o=N(n.getAttributes,void 0,r)||{},s=e.tr.delete(t.from,t.to),a=s.doc.resolve(t.from).blockRange(),c=a&&qe(a,n.type,o);if(!c)return null;if(s.wrap(a,c),n.keepMarks&&n.editor){let{selection:u,storedMarks:f}=e,{splittableMarks:p}=n.editor.extensionManager,h=f||u.$to.parentOffset&&u.$from.marks();if(h){let m=h.filter(g=>p.includes(g.type.name));s.ensureMarks(m)}}if(n.keepAttributes){let u=n.type.name==="bulletList"||n.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(u,o).run()}let d=s.doc.resolve(t.from-1).nodeBefore;d&&d.type===n.type&&re(s.doc,t.from-1)&&(!n.joinPredicate||n.joinPredicate(r,d))&&s.join(t.from-1)}})}var Ki=class n{constructor(e={}){this.type="node",this.name="node",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...e},this.name=this.config.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=N(x(this,"addOptions",{name:this.name}))),this.storage=N(x(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(e={}){return new n(e)}configure(e={}){let t=this.extend({...this.config,addOptions:()=>sn(this.options,e)});return t.name=this.name,t.parent=this.parent,t}extend(e={}){let t=new n(e);return t.parent=this,this.child=t,t.name=e.name?e.name:t.parent.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${t.name}".`),t.options=N(x(t,"addOptions",{name:t.name})),t.storage=N(x(t,"addStorage",{name:t.name,options:t.options})),t}},Ji=class{constructor(e,t,r){this.isDragging=!1,this.component=e,this.editor=t.editor,this.options={stopEvent:null,ignoreMutation:null,...r},this.extension=t.extension,this.node=t.node,this.decorations=t.decorations,this.innerDecorations=t.innerDecorations,this.view=t.view,this.HTMLAttributes=t.HTMLAttributes,this.getPos=t.getPos,this.mount()}mount(){}get dom(){return this.editor.view.dom}get contentDOM(){return null}onDragStart(e){var t,r,i,o,s,l,a;let{view:c}=this.editor,d=e.target,u=d.nodeType===3?(t=d.parentElement)===null||t===void 0?void 0:t.closest("[data-drag-handle]"):d.closest("[data-drag-handle]");if(!this.dom||!((r=this.contentDOM)===null||r===void 0)&&r.contains(d)||!u)return;let f=0,p=0;if(this.dom!==u){let w=this.dom.getBoundingClientRect(),M=u.getBoundingClientRect(),A=(i=e.offsetX)!==null&&i!==void 0?i:(o=e.nativeEvent)===null||o===void 0?void 0:o.offsetX,v=(s=e.offsetY)!==null&&s!==void 0?s:(l=e.nativeEvent)===null||l===void 0?void 0:l.offsetY;f=M.x-w.x+A,p=M.y-w.y+v}let h=this.dom.cloneNode(!0);(a=e.dataTransfer)===null||a===void 0||a.setDragImage(h,f,p);let m=this.getPos();if(typeof m!="number")return;let g=S.create(c.state.doc,m),y=c.state.tr.setSelection(g);c.dispatch(y)}stopEvent(e){var t;if(!this.dom)return!1;if(typeof this.options.stopEvent=="function")return this.options.stopEvent({event:e});let r=e.target;if(!(this.dom.contains(r)&&!(!((t=this.contentDOM)===null||t===void 0)&&t.contains(r))))return!1;let o=e.type.startsWith("drag"),s=e.type==="drop";if((["INPUT","BUTTON","SELECT","TEXTAREA"].includes(r.tagName)||r.isContentEditable)&&!s&&!o)return!0;let{isEditable:a}=this.editor,{isDragging:c}=this,d=!!this.node.type.spec.draggable,u=S.isSelectable(this.node),f=e.type==="copy",p=e.type==="paste",h=e.type==="cut",m=e.type==="mousedown";if(!d&&u&&o&&e.target===this.dom&&e.preventDefault(),d&&o&&!c&&e.target===this.dom)return e.preventDefault(),!1;if(d&&a&&!c&&m){let g=r.closest("[data-drag-handle]");g&&(this.dom===g||this.dom.contains(g))&&(this.isDragging=!0,document.addEventListener("dragend",()=>{this.isDragging=!1},{once:!0}),document.addEventListener("drop",()=>{this.isDragging=!1},{once:!0}),document.addEventListener("mouseup",()=>{this.isDragging=!1},{once:!0}))}return!(c||s||f||p||h||m&&u)}ignoreMutation(e){return!this.dom||!this.contentDOM?!0:typeof this.options.ignoreMutation=="function"?this.options.ignoreMutation({mutation:e}):this.node.isLeaf||this.node.isAtom?!0:e.type==="selection"||this.dom.contains(e.target)&&e.type==="childList"&&(Tt()||Vi())&&this.editor.isFocused&&[...Array.from(e.addedNodes),...Array.from(e.removedNodes)].every(r=>r.isContentEditable)?!1:this.contentDOM===e.target&&e.type==="attributes"?!0:!this.contentDOM.contains(e.target)}updateAttributes(e){this.editor.commands.command(({tr:t})=>{let r=this.getPos();return typeof r!="number"?!1:(t.setNodeMarkup(r,void 0,{...this.node.attrs,...e}),!0)})}deleteNode(){let e=this.getPos();if(typeof e!="number")return;let t=e+this.node.nodeSize;this.editor.commands.deleteRange({from:e,to:t})}};function cp(n){return new Ot({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{let o=N(n.getAttributes,void 0,r,i);if(o===!1||o===null)return null;let{tr:s}=e,l=r[r.length-1],a=r[0],c=t.to;if(l){let d=a.search(/\S/),u=t.from+a.indexOf(l),f=u+l.length;if(no(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(g=>g===n.type&&g!==h.mark.type)).filter(h=>h.to>u).length)return null;ft.from&&s.delete(t.from+d,u),c=t.from+d+l.length,s.addMark(t.from+d,c,n.type.create(o||{})),s.removeStoredMark(n.type)}}})}function dp(n,e){let{selection:t}=n,{$from:r}=t;if(t instanceof S){let o=r.index();return r.parent.canReplaceWith(o,o+1,e)}let i=r.depth;for(;i>=0;){let o=r.index(i);if(r.node(i).contentMatchAt(o).matchType(e))return!0;i-=1}return!1}function up(n){return n.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}function fp(n){return typeof n=="string"}function pp(n){return new Ot({find:n.find,handler({match:e,chain:t,range:r,pasteEvent:i}){let o=N(n.getAttributes,void 0,e,i),s=N(n.getContent,void 0,o);if(o===!1||o===null)return null;let l={type:n.type.name,attrs:o};s&&(l.content=s),e.input&&t().deleteRange(r).insertContentAt(r.from,l)}})}function hp(n){return new Ot({find:n.find,handler:({state:e,range:t,match:r})=>{let i=n.replace,o=t.from,s=t.to;if(r[1]){let l=r[0].lastIndexOf(r[1]);i+=r[0].slice(l+r[1].length),o+=l;let a=o-s;a>0&&(i=r[0].slice(l-a,l)+i,o=s)}e.tr.insertText(i,o,s)}})}var Hi=class{constructor(e){this.transaction=e,this.currentStep=this.transaction.steps.length}map(e){let t=!1;return{position:this.transaction.steps.slice(this.currentStep).reduce((i,o)=>{let s=o.getMap().mapResult(i);return s.deleted&&(t=!0),s.pos},e),deleted:t}}};var oo={};ae(oo,{dropCursor:()=>mp});function mp(n={}){return new P({view(e){return new io(e,n)}})}var io=class{constructor(e,t){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=t.width)!==null&&r!==void 0?r:1,this.color=t.color===!1?void 0:t.color||"black",this.class=t.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let o=s=>{this[i](s)};return e.dom.addEventListener(i,o),{name:i,handler:o}})}destroy(){this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){this.cursorPos!=null&&t.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,r,i=this.editorView.dom,o=i.getBoundingClientRect(),s=o.width/i.offsetWidth,l=o.height/i.offsetHeight;if(t){let u=e.nodeBefore,f=e.nodeAfter;if(u||f){let p=this.editorView.nodeDOM(this.cursorPos-(u?u.nodeSize:0));if(p){let h=p.getBoundingClientRect(),m=u?h.bottom:h.top;u&&f&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:h.left,right:h.right,top:m-g,bottom:m+g}}}}if(!r){let u=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*s;r={left:u.left-f,right:u.left+f,top:u.top,bottom:u.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",t),this.element.classList.toggle("prosemirror-dropcursor-inline",!t);let c,d;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,d=-pageYOffset;else{let u=a.getBoundingClientRect(),f=u.width/a.offsetWidth,p=u.height/a.offsetHeight;c=u.left-a.scrollLeft*f,d=u.top-a.scrollTop*p}this.element.style.left=(r.left-c)/s+"px",this.element.style.top=(r.top-d)/l+"px",this.element.style.width=(r.right-r.left)/s+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),i=r&&r.type.spec.disableDropCursor,o=typeof i=="function"?i(this.editorView,t,e):i;if(t&&!o){let s=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=Vt(this.editorView.state.doc,s,this.editorView.dragging.slice);l!=null&&(s=l)}this.setCursor(s),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}};var lo={};ae(lo,{GapCursor:()=>W,gapCursor:()=>kp});var W=class n extends E{constructor(e){super(e,e)}map(e,t){let r=e.resolve(t.map(this.head));return n.valid(r)?new n(r):E.near(r)}content(){return b.empty}eq(e){return e instanceof n&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new n(e.resolve(t.pos))}getBookmark(){return new so(this.anchor)}static valid(e){let t=e.parent;if(t.inlineContent||!gp(e)||!yp(e))return!1;let r=t.type.spec.allowGapCursor;if(r!=null)return r;let i=t.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,t,r=!1){e:for(;;){if(!r&&n.valid(e))return e;let i=e.pos,o=null;for(let s=e.depth;;s--){let l=e.node(s);if(t>0?e.indexAfter(s)0){o=l.child(t>0?e.indexAfter(s):e.index(s)-1);break}else if(s==0)return null;i+=t;let a=e.doc.resolve(i);if(n.valid(a))return a}for(;;){let s=t>0?o.firstChild:o.lastChild;if(!s){if(o.isAtom&&!o.isText&&!S.isSelectable(o)){e=e.doc.resolve(i+o.nodeSize*t),r=!1;continue e}break}o=s,i+=t;let l=e.doc.resolve(i);if(n.valid(l))return l}return null}}};W.prototype.visible=!1;W.findFrom=W.findGapCursorFrom;E.jsonID("gapcursor",W);var so=class n{constructor(e){this.pos=e}map(e){return new n(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return W.valid(t)?new W(t):E.near(t)}};function ba(n){return n.isAtom||n.spec.isolating||n.spec.createGapCursor}function gp(n){for(let e=n.depth;e>=0;e--){let t=n.index(e),r=n.node(e);if(t==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(t-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||ba(i.type))return!0;if(i.inlineContent)return!1}}return!0}function yp(n){for(let e=n.depth;e>=0;e--){let t=n.indexAfter(e),r=n.node(e);if(t==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(t);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||ba(i.type))return!0;if(i.inlineContent)return!1}}return!0}function kp(){return new P({props:{decorations:Cp,createSelectionBetween(n,e,t){return e.pos==t.pos&&W.valid(t)?new W(t):null},handleClick:xp,handleKeyDown:bp,handleDOMEvents:{beforeinput:Sp}}})}var bp=In({ArrowLeft:sr("horiz",-1),ArrowRight:sr("horiz",1),ArrowUp:sr("vert",-1),ArrowDown:sr("vert",1)});function sr(n,e){let t=n=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,o){let s=r.selection,l=e>0?s.$to:s.$from,a=s.empty;if(s instanceof T){if(!o.endOfTextblock(t)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=W.findGapCursorFrom(l,e,a);return c?(i&&i(r.tr.setSelection(new W(c))),!0):!1}}function xp(n,e,t){if(!n||!n.editable)return!1;let r=n.state.doc.resolve(e);if(!W.valid(r))return!1;let i=n.posAtCoords({left:t.clientX,top:t.clientY});return i&&i.inside>-1&&S.isSelectable(n.state.doc.nodeAt(i.inside))?!1:(n.dispatch(n.state.tr.setSelection(new W(r))),!0)}function Sp(n,e){if(e.inputType!="insertCompositionText"||!(n.state.selection instanceof W))return!1;let{$from:t}=n.state.selection,r=t.parent.contentMatchAt(t.index()).findWrapping(n.state.schema.nodes.text);if(!r)return!1;let i=k.empty;for(let s=r.length-1;s>=0;s--)i=k.from(r[s].createAndFill(null,i));let o=n.state.tr.replace(t.pos,t.pos,new b(i,0,0));return o.setSelection(T.near(o.doc.resolve(t.pos+1))),n.dispatch(o),!1}function Cp(n){if(!(n.selection instanceof W))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",X.create(n.doc,[de.widget(n.selection.head,e,{key:"gapcursor"})])}var fo={};ae(fo,{closeHistory:()=>Ap,history:()=>vp,isHistoryTransaction:()=>Bp,redo:()=>Ea,redoDepth:()=>_p,redoNoScroll:()=>Ip,undo:()=>Ma,undoDepth:()=>Pp,undoNoScroll:()=>Rp});var lr=200,K=function(){};K.prototype.append=function(e){return e.length?(e=K.from(e),!this.length&&e||e.length=t?K.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};K.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};K.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};K.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(o,s){return i.push(e(o,s))},t,r),i};K.from=function(e){return e instanceof K?e:e&&e.length?new xa(e):K.empty};var xa=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,o){return i==0&&o==this.length?this:new e(this.values.slice(i,o))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,o,s,l){for(var a=o;a=s;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=lr)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=lr)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(K);K.empty=new xa([]);var wp=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,o)-l,s+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,o,s){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(o,l)-l,s+l)===!1||o=o?this.right.slice(r-o,i-o):this.left.slice(r,o).append(this.right.slice(0,i-o))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(K),ao=K;var Mp=500,st=class n{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,o;t&&(i=this.remapping(r,this.items.length),o=i.maps.length);let s=e.tr,l,a,c=[],d=[];return this.items.forEach((u,f)=>{if(!u.step){i||(i=this.remapping(r,f+1),o=i.maps.length),o--,d.push(u);return}if(i){d.push(new xe(u.map));let p=u.step.map(i.slice(o)),h;p&&s.maybeStep(p).doc&&(h=s.mapping.maps[s.mapping.maps.length-1],c.push(new xe(h,void 0,void 0,c.length+d.length))),o--,h&&i.appendMap(h,o)}else s.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(o)):u.selection,a=new n(this.items.slice(0,r).append(d.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:s,selection:l}}addTransform(e,t,r,i){let o=[],s=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let d=0;dOp&&(l=Ep(l,c),s-=c),new n(l.append(o),s)}remapping(e,t){let r=new ut;return this.items.forEach((i,o)=>{let s=i.mirrorOffset!=null&&o-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,s)},e,t),r}addMaps(e){return this.eventCount==0?this:new n(this.items.append(e.map(t=>new xe(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),o=e.mapping,s=e.steps.length,l=this.eventCount;this.items.forEach(f=>{f.selection&&l--},i);let a=t;this.items.forEach(f=>{let p=o.getMirror(--a);if(p==null)return;s=Math.min(s,p);let h=o.maps[p];if(f.step){let m=e.steps[p].invert(e.docs[p]),g=f.selection&&f.selection.map(o.slice(a+1,p));g&&l++,r.push(new xe(h,m,g))}else r.push(new xe(h))},i);let c=[];for(let f=t;fMp&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],o=0;return this.items.forEach((s,l)=>{if(l>=e)i.push(s),s.selection&&o++;else if(s.step){let a=s.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let d=s.selection&&s.selection.map(t.slice(r));d&&o++;let u=new xe(c.invert(),a,d),f,p=i.length-1;(f=i.length&&i[p].merge(u))?i[p]=f:i.push(u)}}else s.map&&r--},this.items.length,0),new n(ao.from(i.reverse()),o)}};st.empty=new st(ao.empty,0);function Ep(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}var xe=class n{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new n(t.getMap().invert(),t,this.selection)}}},Se=class{constructor(e,t,r,i,o){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=o}},Op=20;function Tp(n,e,t,r){let i=t.getMeta(Ce),o;if(i)return i.historyState;t.getMeta(wa)&&(n=new Se(n.done,n.undone,null,0,-1));let s=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(s&&s.getMeta(Ce))return s.getMeta(Ce).redo?new Se(n.done.addTransform(t,void 0,r,ar(e)),n.undone,Sa(t.mapping.maps),n.prevTime,n.prevComposition):new Se(n.done,n.undone.addTransform(t,void 0,r,ar(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(s&&s.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!s&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Np(t,n.prevRanges)),c=s?co(n.prevRanges,t.mapping):Sa(t.mapping.maps);return new Se(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,ar(e)),st.empty,c,t.time,l??n.prevComposition)}else return(o=t.getMeta("rebased"))?new Se(n.done.rebased(t,o),n.undone.rebased(t,o),co(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Se(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),co(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Np(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let o=0;o=e[o]&&(t=!0)}),t}function Sa(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,o,s)=>e.push(o,s));return e}function co(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Ce.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let o=Dp(i,t,n);o&&r(e?o.scrollIntoView():o)}return!0}}var Ma=cr(!1,!0),Ea=cr(!0,!0),Rp=cr(!1,!1),Ip=cr(!0,!1);function Pp(n){let e=Ce.getState(n);return e?e.done.eventCount:0}function _p(n){let e=Ce.getState(n);return e?e.undone.eventCount:0}function Bp(n){return n.getMeta(Ce)!=null}var zp={"@tiptap/core":ro,"@tiptap/pm/commands":Di,"@tiptap/pm/dropcursor":oo,"@tiptap/pm/gapcursor":lo,"@tiptap/pm/history":fo,"@tiptap/pm/keymap":pi,"@tiptap/pm/model":hi,"@tiptap/pm/schema-list":Pi,"@tiptap/pm/state":vr,"@tiptap/pm/transform":mi,"@tiptap/pm/view":di};function po(n){Object.assign(n,zp)}var fe=new Map,At=new Map,dn=So(),ho=1,mo,go=Aa;po(dn.modules);function Fp(){let n=dn.modules["@tiptap/core"];if(n==null)throw new Error("leptos-tiptap tiptap_core runtime is not initialized");return n}function Aa(n){let e=Fp().Editor;return new e(n)}function Ae(n){return{ok:!0,value:n}}function Lp(){return{kind:"empty"}}function va(){return Ae(Lp())}function we(n,e,t){return{ok:!1,error:{kind:n,message:e,operation:t}}}function Ra(n,e){return console.error(n),we("extension_unavailable",n,e)}function Oa(n){return console.error(n),we("extension_registration_failed",n)}function Vp(){return mo??globalThis.document}function Ia(n){try{n.destroy()}catch(e){console.error("Could not destroy Tiptap editor instance.",e)}}function $p(){let n=ho;return ho+=1,n}function jp(n){let e=fe.get(n);e!=null&&(e.entry!=null&&Ia(e.entry.editor),fe.delete(n))}function Wp(n,e,t,r,i){let o=fe.get(n);return o==null||o.generation!==e?(Ia(t),!1):(o.entry={editor:t,onSelection:r,commandHandlers:i.commandHandlers,selectionContributors:i.selectionContributors},!0)}function ko(n){return fe.get(n)?.entry}function Kp(n,e){let t=ko(n);return t?.editor===e?t:void 0}function Jp(n,e){let t=Kp(n,e);t!=null&&Pa(t)}function yo(n){if(At.get(n.name)!=null)throw new Error(`Tiptap extension "${n.name}" has already been registered.`);At.set(n.name,n)}function dr(n,e,t,r){let i=fe.get(n),o=i?.entry;if(i?.generation!==e||o==null){let s=`Can not execute ${t} for Tiptap instance "${n}", as no current editor is registered for this handle.`;return we("editor_unavailable",s,t)}return r(o)}function Hp(n){let e=Vp().getElementById(n);if(e!=null)return Ae(e);let t=`Can not create Tiptap instance on element with id "${n}", as the element could not be found in the DOM.`;return console.error(t),we("editor_mount_failed",t)}function qp(n){if(fe.get(n)?.entry==null)return va();let e=`Can not create Tiptap instance "${n}", as another live editor is already registered for that id.`;return console.error(e),we("duplicate_editor_id",e)}function Ta(n,e){return console.error(n,e),we("invalid_content",`${n}${e==null?"":` ${e instanceof Error?e.message:String(e)}`}`)}function ur(n){if(n.format==="html")return typeof n.value!="string"?Ta("Could not parse Tiptap HTML content."):Ae(n.value);if(typeof n.value=="string")try{return Ae(JSON.parse(n.value))}catch(e){return Ta("Could not parse Tiptap JSON content.",e)}return Ae(n.value)}function Up(n,e){return _a(za(e),()=>e==="html"?{format:e,value:n.getHTML()}:{format:e,value:n.getJSON()})}function Gp(n){let e=xo();for(let t of n.selectionContributors)Object.assign(e,t(n.editor));return Object.assign(e,Yp(n.editor)),e}function Yp(n){let e=n.state.selection,t=e.from,r=e.to,i=e.empty,o=null,s=null,l=null;return n.state.doc.forEach((a,c,d)=>{if(o!=null)return;let u=c+1,f=c+a.nodeSize-1;t>=u&&t<=f&&(o=d,s=u,l=f)}),{current_block_index:o,current_block_from:s,current_block_to:l,selection_from:t,selection_to:r,selection_empty:i}}function cn(n,e){return(n??null)===(e??null)}function Xp(n,e){return(n??null)===(e??null)}function Zp(n,e){let t=new Set(["current_block_index","current_block_from","current_block_to","selection_from","selection_to","selection_empty"]),r=new Set([...Object.keys(n),...Object.keys(e)].filter(i=>!t.has(i)));for(let i of r)if((n[i]??!1)!==(e[i]??!1))return!1;return cn(n.current_block_index,e.current_block_index)&&cn(n.current_block_from,e.current_block_from)&&cn(n.current_block_to,e.current_block_to)&&cn(n.selection_from,e.selection_from)&&cn(n.selection_to,e.selection_to)&&Xp(n.selection_empty,e.selection_empty)}function Pa(n,e={}){let t=Gp(n);e.force!==!0&&n.lastSelectionState!=null&&Zp(n.lastSelectionState,t)||(n.lastSelectionState=t,n.onSelection(t))}function _a(n,e){try{return Ae(e())}catch(t){let r=`${n} failed: ${t instanceof Error?t.message:String(t)}`;return console.error(r,t),we("operation_failed",r,n)}}function C(n,e){try{return e()===!1?we("command_rejected",`Tiptap rejected the ${n} command for the current editor state.`,n):va()}catch(t){let r=`${n} failed: ${t instanceof Error?t.message:String(t)}`;return console.error(r,t),we("operation_failed",r,n)}}function Ba(n){return n==null?{}:{preserveWhitespace:n.preserve_whitespace,from:n.from,to:n.to}}function Qp(n){return{scrollIntoView:n?.scroll_into_view}}function Na(n){return{parseOptions:Ba(n?.parse_options),updateSelection:n?.update_selection,applyInputRules:n?.apply_input_rules,applyPasteRules:n?.apply_paste_rules,errorOnInvalidContent:n?.error_on_invalid_content}}function Da(n){return{extendEmptyMarkRange:n?.extend_empty_mark_range}}function eh(n,e){switch(e.kind){case"blur":return C(e.kind,()=>n.commands.blur());case"clear_content":return C(e.kind,()=>n.commands.clearContent(e.emit_update));case"clear_nodes":return C(e.kind,()=>n.commands.clearNodes());case"create_paragraph_near":return C(e.kind,()=>n.commands.createParagraphNear());case"cut":return C(e.kind,()=>n.commands.cut(e.range,e.target_pos));case"delete_current_node":return C(e.kind,()=>n.commands.deleteCurrentNode());case"delete_node":return C(e.kind,()=>n.commands.deleteNode(e.type_or_name));case"delete_range":return C(e.kind,()=>n.commands.deleteRange(e.range));case"delete_selection":return C(e.kind,()=>n.commands.deleteSelection());case"enter":return C(e.kind,()=>n.commands.enter());case"exit_code":return C(e.kind,()=>n.commands.exitCode());case"extend_mark_range":return C(e.kind,()=>n.commands.extendMarkRange(e.type_or_name,e.attributes??void 0));case"focus":return C(e.kind,()=>n.commands.focus(e.target??null,Qp(e.options)));case"insert_content":{let t=ur(e.content);if(!t.ok)return t;let{from:r,to:i}=n.state.selection;return C(e.kind,()=>n.commands.insertContentAt({from:r,to:i},t.value,Na(e.options)))}case"insert_content_at":{let t=ur(e.content);return t.ok?C(e.kind,()=>n.commands.insertContentAt(e.position,t.value,Na(e.options))):t}case"join_up":return C(e.kind,()=>n.commands.joinUp());case"join_down":return C(e.kind,()=>n.commands.joinDown());case"join_backward":return C(e.kind,()=>n.commands.joinBackward());case"join_forward":return C(e.kind,()=>n.commands.joinForward());case"join_item_backward":return C(e.kind,()=>n.commands.joinItemBackward());case"join_item_forward":return C(e.kind,()=>n.commands.joinItemForward());case"join_textblock_backward":return C(e.kind,()=>n.commands.joinTextblockBackward());case"join_textblock_forward":return C(e.kind,()=>n.commands.joinTextblockForward());case"keyboard_shortcut":return C(e.kind,()=>n.commands.keyboardShortcut(e.name));case"lift":return C(e.kind,()=>n.commands.lift(e.type_or_name,e.attributes??void 0));case"lift_empty_block":return C(e.kind,()=>n.commands.liftEmptyBlock());case"newline_in_code":return C(e.kind,()=>n.commands.newlineInCode());case"reset_attributes":return C(e.kind,()=>n.commands.resetAttributes(e.type_or_name,e.attribute_names));case"scroll_into_view":return C(e.kind,()=>n.commands.scrollIntoView());case"select_all":return C(e.kind,()=>n.commands.selectAll());case"select_node_backward":return C(e.kind,()=>n.commands.selectNodeBackward());case"select_node_forward":return C(e.kind,()=>n.commands.selectNodeForward());case"select_parent_node":return C(e.kind,()=>n.commands.selectParentNode());case"select_textblock_end":return C(e.kind,()=>n.commands.selectTextblockEnd());case"select_textblock_start":return C(e.kind,()=>n.commands.selectTextblockStart());case"set_mark":return C(e.kind,()=>n.commands.setMark(e.type_or_name,e.attributes??void 0));case"set_meta":return C(e.kind,()=>n.commands.setMeta(e.key,e.value));case"set_node":return C(e.kind,()=>n.commands.setNode(e.type_or_name,e.attributes??void 0));case"set_node_selection":return C(e.kind,()=>n.commands.setNodeSelection(e.position));case"set_text_selection":return C(e.kind,()=>n.commands.setTextSelection(e.position));case"split_block":return C(e.kind,()=>n.commands.splitBlock({keepMarks:e.keep_marks}));case"toggle_list":return C(e.kind,()=>n.commands.toggleList(e.list_type_or_name,e.item_type_or_name,e.keep_marks,e.attributes??void 0));case"toggle_mark":return C(e.kind,()=>n.commands.toggleMark(e.type_or_name,e.attributes??void 0,Da(e.options)));case"toggle_node":return C(e.kind,()=>n.commands.toggleNode(e.type_or_name,e.toggle_type_or_name,e.attributes??void 0));case"toggle_wrap":return C(e.kind,()=>n.commands.toggleWrap(e.type_or_name,e.attributes??void 0));case"undo_input_rule":return C(e.kind,()=>n.commands.undoInputRule());case"unset_all_marks":return C(e.kind,()=>n.commands.unsetAllMarks());case"unset_mark":return C(e.kind,()=>n.commands.unsetMark(e.type_or_name,Da(e.options)));case"update_attributes":return C(e.kind,()=>n.commands.updateAttributes(e.type_or_name,e.attributes));case"wrap_in":return C(e.kind,()=>n.commands.wrapIn(e.type_or_name,e.attributes??void 0));case"wrap_in_list":return C(e.kind,()=>n.commands.wrapInList(e.type_or_name,e.attributes??void 0));default:return}}function za(n){return n==="html"?"get_content_html":"get_content_json"}function th(n){let e=[];for(let t of n){let r=At.get(t);if(r==null)return Ra(`Can not create Tiptap instance, as extension "${t}" is not registered.`);e.push({descriptor:r,selectionKeys:r.selection_keys??[]})}return Ae(e)}function nh(n,e){let t=th(n);if(!t.ok)return t;let r=new Map,i=[],o=[],s=new Set;for(let{descriptor:l,selectionKeys:a}of t.value){let c;try{c=l.create(e)}catch(d){let u=`Can not create Tiptap instance, as extension "${l.name}" failed to initialize.`;return console.error(u,d),we("extension_registration_failed",`${u} ${d instanceof Error?d.message:String(d)}`)}Array.isArray(c)?o.push(...c):o.push(c);for(let d of a){if(s.has(d))return Oa(`Can not create Tiptap instance, as multiple selected extensions contribute selection key "${d}".`);s.add(d)}l.selection_state!=null&&i.push(l.selection_state);for(let[d,u]of Object.entries(l.commands??{}))if(u!=null){if(r.has(d))return Oa(`Can not create Tiptap instance, as multiple selected extensions handle command "${d}".`);r.set(d,u)}}return Ae({extensions:o,commandHandlers:r,selectionContributors:i})}function cm(){dn.registerExtension=yo}function dm(n,e,t,r,i){let o=qp(n.id);if(!o.ok){i(o.error);return}let s=Hp(n.id);if(!s.ok){i(s.error);return}let l=nh(n.extensions,{placeholder:n.placeholder});if(!l.ok){i(l.error);return}let a=ur(n.content);if(!a.ok){i(a.error);return}let c=$p();fe.set(n.id,{generation:c});let d=_a("create_editor",()=>go({element:s.value,editable:n.editable,extensions:l.value.extensions,injectCSS:!1,content:a.value,onUpdate:({editor:f})=>{t()},onSelectionUpdate:({editor:f})=>{Jp(n.id,f)}}));if(!d.ok){let f=fe.get(n.id);f?.generation===c&&f.entry==null&&fe.delete(n.id),i(d.error);return}if(!Wp(n.id,c,d.value,r,l.value))return;let u=ko(n.id);u!=null?(e({generation:c}),Pa(u,{force:!0})):e({generation:c})}function um(n){jp(n)}function fm(n){let{id:e,generation:t,command:r}=n;return r.kind==="set_editable"?dr(e,t,r.kind,({editor:i})=>C(r.kind,()=>{i.setEditable(r.editable)})):dr(e,t,r.kind,i=>{let o=eh(i.editor,r);if(o!=null)return o;let s=r,l=i.commandHandlers.get(s.kind);return l==null?Ra(`Can not execute ${s.kind} for Tiptap instance "${e}", as no active extension provides this command.`,s.kind):C(s.kind,()=>l(i.editor,s))})}function pm(n){let{id:e,generation:t,request:r}=n;switch(r.kind){case"get_content":return dr(e,t,za(r.format),({editor:i})=>{let o=Up(i,r.format);return o.ok?Ae({kind:"content",content:o.value}):o});case"set_content":return dr(e,t,r.kind,i=>{let o=ur(r.content);return o.ok?C(r.kind,()=>i.editor.commands.setContent(o.value,r.options?.emit_update??!1,Ba(r.options?.parse_options),{errorOnInvalidContent:r.options?.error_on_invalid_content})):o})}}var hm={getEditorEntry:ko,getRegisteredExtensionNames(){return[...At.keys()]},hasRegisteredExtension(n){return At.has(n)},registerExtension:yo,reset(){fe.clear(),At.clear(),po(dn.modules),dn.registerExtension=yo,mo=void 0,go=Aa,ho=1},getSlotCount(){return fe.size},setDocument(n){mo=n},setEditorFactory(n){go=n}};export{hm as __testing,fm as command,dm as create,um as destroy,pm as document,cm as init_bridge_runtime}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_blockquote.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_blockquote.js new file mode 100644 index 00000000..dccd43b5 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_blockquote.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var x=t.CommandManager,m=t.Editor,k=t.Extension,b=t.InputRule,y=t.Mark,r=t.Node,h=t.NodePos,E=t.NodeView,R=t.PasteRule,f=t.Tracker,P=t.callOrReturn,C=t.canInsertNode,T=t.combineTransactionSteps,A=t.createChainableState,S=t.createDocument,B=t.createNodeFromContent,N=t.createStyleTag,O=t.defaultBlockAt,w=t.deleteProps,v=t.elementFromString,M=t.escapeForRegEx,I=t.extensions,q=t.findChildren,F=t.findChildrenInRange,D=t.findDuplicates,j=t.findParentNode,L=t.findParentNodeClosestToPos,K=t.fromString,H=t.generateHTML,G=t.generateJSON,z=t.generateText,J=t.getAttributes,U=t.getAttributesFromExtensions,V=t.getChangedRanges,Y=t.getDebugJSON,W=t.getExtensionField,$=t.getHTMLFromFragment,Q=t.getMarkAttributes,X=t.getMarkRange,Z=t.getMarkType,tt=t.getMarksBetween,et=t.getNodeAtPosition,nt=t.getNodeAttributes,ot=t.getNodeType,it=t.getRenderedAttributes,rt=t.getSchema,st=t.getSchemaByResolvedExtensions,lt=t.getSchemaTypeByName,at=t.getSchemaTypeNameByName,dt=t.getSplittedAttributes,pt=t.getText,ct=t.getTextBetween,ut=t.getTextContentFromNodes,gt=t.getTextSerializersFromSchema,_t=t.injectExtensionAttributesToParseRule,xt=t.inputRulesPlugin,mt=t.isActive,kt=t.isAtEndOfNode,bt=t.isAtStartOfNode,yt=t.isEmptyObject,ht=t.isExtensionRulesEnabled,Et=t.isFunction,Rt=t.isList,ft=t.isMacOS,Pt=t.isMarkActive,Ct=t.isNodeActive,Tt=t.isNodeEmpty,At=t.isNodeSelection,St=t.isNumber,Bt=t.isPlainObject,Nt=t.isRegExp,Ot=t.isSafari,wt=t.isString,vt=t.isTextSelection,Mt=t.isiOS,It=t.markInputRule,qt=t.markPasteRule,s=t.mergeAttributes,Ft=t.mergeDeep,Dt=t.minMax,jt=t.nodeInputRule,Lt=t.nodePasteRule,Kt=t.objectIncludes,Ht=t.pasteRulesPlugin,Gt=t.posToDOMRect,zt=t.removeDuplicates,Jt=t.resolveFocusPosition,Ut=t.rewriteUnknownContent,Vt=t.selectionToInsertionEnd,Yt=t.splitExtensions,Wt=t.textInputRule,$t=t.textPasteRule,Qt=t.textblockTypeInputRule,l=t.wrappingInputRule;var u=/^\s*>\s$/,a=r.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:e}){return["blockquote",s(this.options.HTMLAttributes,e),0]},addCommands(){return{setBlockquote:()=>({commands:e})=>e.wrapIn(this.name),toggleBlockquote:()=>({commands:e})=>e.toggleWrap(this.name),unsetBlockquote:()=>({commands:e})=>e.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[l({find:u,type:this.type})]}});var d="__LEPTOS_TIPTAP_BRIDGE__";function g(){let e=globalThis,o=e[d];if(o!=null)return o;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[d]=i,i}function p(){return g()}function c(e){p().registerExtension(e)}var _={name:"blockquote",create:()=>a,commands:{set_blockquote:e=>e.chain().focus().setBlockquote().run(),toggle_blockquote:e=>e.chain().focus().toggleBlockquote().run(),unset_blockquote:e=>e.chain().focus().unsetBlockquote().run()},selection_keys:["blockquote"],selection_state:e=>({blockquote:e.isActive("blockquote")})};function se(){c(_)}export{se as register_blockquote}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bold.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bold.js new file mode 100644 index 00000000..8a3feaa0 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bold.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var y=t.CommandManager,h=t.Editor,R=t.Extension,f=t.InputRule,l=t.Mark,E=t.Node,P=t.NodePos,A=t.NodeView,C=t.PasteRule,T=t.Tracker,S=t.callOrReturn,B=t.canInsertNode,N=t.combineTransactionSteps,O=t.createChainableState,w=t.createDocument,M=t.createNodeFromContent,v=t.createStyleTag,I=t.defaultBlockAt,F=t.deleteProps,D=t.elementFromString,j=t.escapeForRegEx,L=t.extensions,K=t.findChildren,H=t.findChildrenInRange,q=t.findDuplicates,G=t.findParentNode,z=t.findParentNodeClosestToPos,J=t.fromString,$=t.generateHTML,U=t.generateJSON,V=t.generateText,Y=t.getAttributes,W=t.getAttributesFromExtensions,Q=t.getChangedRanges,X=t.getDebugJSON,Z=t.getExtensionField,tt=t.getHTMLFromFragment,et=t.getMarkAttributes,nt=t.getMarkRange,ot=t.getMarkType,rt=t.getMarksBetween,it=t.getNodeAtPosition,st=t.getNodeAttributes,lt=t.getNodeType,at=t.getRenderedAttributes,dt=t.getSchema,pt=t.getSchemaByResolvedExtensions,ct=t.getSchemaTypeByName,ut=t.getSchemaTypeNameByName,gt=t.getSplittedAttributes,_t=t.getText,xt=t.getTextBetween,mt=t.getTextContentFromNodes,kt=t.getTextSerializersFromSchema,bt=t.injectExtensionAttributesToParseRule,yt=t.inputRulesPlugin,ht=t.isActive,Rt=t.isAtEndOfNode,ft=t.isAtStartOfNode,Et=t.isEmptyObject,Pt=t.isExtensionRulesEnabled,At=t.isFunction,Ct=t.isList,Tt=t.isMacOS,St=t.isMarkActive,Bt=t.isNodeActive,Nt=t.isNodeEmpty,Ot=t.isNodeSelection,wt=t.isNumber,Mt=t.isPlainObject,vt=t.isRegExp,It=t.isSafari,Ft=t.isString,Dt=t.isTextSelection,jt=t.isiOS,o=t.markInputRule,r=t.markPasteRule,a=t.mergeAttributes,Lt=t.mergeDeep,Kt=t.minMax,Ht=t.nodeInputRule,qt=t.nodePasteRule,Gt=t.objectIncludes,zt=t.pasteRulesPlugin,Jt=t.posToDOMRect,$t=t.removeDuplicates,Ut=t.resolveFocusPosition,Vt=t.rewriteUnknownContent,Yt=t.selectionToInsertionEnd,Wt=t.splitExtensions,Qt=t.textInputRule,Xt=t.textPasteRule,Zt=t.textblockTypeInputRule,te=t.wrappingInputRule;var g=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,_=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,x=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,m=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,d=l.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:e=>e.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:e=>e.type.name===this.name},{style:"font-weight",getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}]},renderHTML({HTMLAttributes:e}){return["strong",a(this.options.HTMLAttributes,e),0]},addCommands(){return{setBold:()=>({commands:e})=>e.setMark(this.name),toggleBold:()=>({commands:e})=>e.toggleMark(this.name),unsetBold:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[o({find:g,type:this.type}),o({find:x,type:this.type})]},addPasteRules(){return[r({find:_,type:this.type}),r({find:m,type:this.type})]}});var p="__LEPTOS_TIPTAP_BRIDGE__";function k(){let e=globalThis,i=e[p];if(i!=null)return i;let s={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[p]=s,s}function c(){return k()}function u(e){c().registerExtension(e)}var b={name:"bold",create:()=>d,commands:{set_bold:e=>e.chain().focus().setBold().run(),toggle_bold:e=>e.chain().focus().toggleBold().run(),unset_bold:e=>e.chain().focus().unsetBold().run()},selection_keys:["bold"],selection_state:e=>({bold:e.isActive("bold")})};function de(){u(b)}export{de as register_bold}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bullet_list.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bullet_list.js new file mode 100644 index 00000000..92912f57 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_bullet_list.js @@ -0,0 +1 @@ +var o=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(o==null||o.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=o.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var k=t.CommandManager,b=t.Editor,y=t.Extension,h=t.InputRule,E=t.Mark,s=t.Node,R=t.NodePos,f=t.NodeView,A=t.PasteRule,T=t.Tracker,P=t.callOrReturn,C=t.canInsertNode,S=t.combineTransactionSteps,N=t.createChainableState,B=t.createDocument,O=t.createNodeFromContent,w=t.createStyleTag,M=t.defaultBlockAt,v=t.deleteProps,I=t.elementFromString,F=t.escapeForRegEx,D=t.extensions,L=t.findChildren,j=t.findChildrenInRange,K=t.findDuplicates,H=t.findParentNode,q=t.findParentNodeClosestToPos,G=t.fromString,z=t.generateHTML,J=t.generateJSON,U=t.generateText,V=t.getAttributes,Y=t.getAttributesFromExtensions,$=t.getChangedRanges,Q=t.getDebugJSON,W=t.getExtensionField,X=t.getHTMLFromFragment,Z=t.getMarkAttributes,tt=t.getMarkRange,et=t.getMarkType,nt=t.getMarksBetween,ot=t.getNodeAtPosition,it=t.getNodeAttributes,rt=t.getNodeType,st=t.getRenderedAttributes,lt=t.getSchema,at=t.getSchemaByResolvedExtensions,pt=t.getSchemaTypeByName,dt=t.getSchemaTypeNameByName,ut=t.getSplittedAttributes,ct=t.getText,gt=t.getTextBetween,_t=t.getTextContentFromNodes,xt=t.getTextSerializersFromSchema,mt=t.injectExtensionAttributesToParseRule,kt=t.inputRulesPlugin,bt=t.isActive,yt=t.isAtEndOfNode,ht=t.isAtStartOfNode,Et=t.isEmptyObject,Rt=t.isExtensionRulesEnabled,ft=t.isFunction,At=t.isList,Tt=t.isMacOS,Pt=t.isMarkActive,Ct=t.isNodeActive,St=t.isNodeEmpty,Nt=t.isNodeSelection,Bt=t.isNumber,Ot=t.isPlainObject,wt=t.isRegExp,Mt=t.isSafari,vt=t.isString,It=t.isTextSelection,Ft=t.isiOS,Dt=t.markInputRule,Lt=t.markPasteRule,l=t.mergeAttributes,jt=t.mergeDeep,Kt=t.minMax,Ht=t.nodeInputRule,qt=t.nodePasteRule,Gt=t.objectIncludes,zt=t.pasteRulesPlugin,Jt=t.posToDOMRect,Ut=t.removeDuplicates,Vt=t.resolveFocusPosition,Yt=t.rewriteUnknownContent,$t=t.selectionToInsertionEnd,Qt=t.splitExtensions,Wt=t.textInputRule,Xt=t.textPasteRule,Zt=t.textblockTypeInputRule,i=t.wrappingInputRule;var _="listItem",a="textStyle",p=/^\s*([-+*])\s$/,d=s.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:e}){return["ul",l(this.options.HTMLAttributes,e),0]},addCommands(){return{toggleBulletList:()=>({commands:e,chain:n})=>this.options.keepAttributes?n().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(_,this.editor.getAttributes(a)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let e=i({find:p,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(e=i({find:p,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(a),editor:this.editor})),[e]}});var u="__LEPTOS_TIPTAP_BRIDGE__";function x(){let e=globalThis,n=e[u];if(n!=null)return n;let r={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[u]=r,r}function c(){return x()}function g(e){c().registerExtension(e)}var m={name:"bullet_list",create:()=>d,commands:{toggle_bullet_list:e=>e.chain().focus().toggleBulletList().run()},selection_keys:["bullet_list"],selection_state:e=>({bullet_list:e.isActive("bulletList")})};function ae(){g(m)}export{ae as register_bullet_list}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code.js new file mode 100644 index 00000000..335668c2 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var k=t.CommandManager,b=t.Editor,y=t.Extension,h=t.InputRule,i=t.Mark,R=t.Node,E=t.NodePos,f=t.NodeView,C=t.PasteRule,P=t.Tracker,T=t.callOrReturn,A=t.canInsertNode,S=t.combineTransactionSteps,N=t.createChainableState,O=t.createDocument,B=t.createNodeFromContent,w=t.createStyleTag,M=t.defaultBlockAt,v=t.deleteProps,I=t.elementFromString,F=t.escapeForRegEx,D=t.extensions,j=t.findChildren,L=t.findChildrenInRange,K=t.findDuplicates,H=t.findParentNode,q=t.findParentNodeClosestToPos,G=t.fromString,z=t.generateHTML,J=t.generateJSON,U=t.generateText,V=t.getAttributes,Y=t.getAttributesFromExtensions,Q=t.getChangedRanges,W=t.getDebugJSON,X=t.getExtensionField,Z=t.getHTMLFromFragment,$=t.getMarkAttributes,tt=t.getMarkRange,et=t.getMarkType,nt=t.getMarksBetween,ot=t.getNodeAtPosition,rt=t.getNodeAttributes,it=t.getNodeType,st=t.getRenderedAttributes,at=t.getSchema,lt=t.getSchemaByResolvedExtensions,dt=t.getSchemaTypeByName,pt=t.getSchemaTypeNameByName,ct=t.getSplittedAttributes,ut=t.getText,gt=t.getTextBetween,_t=t.getTextContentFromNodes,xt=t.getTextSerializersFromSchema,mt=t.injectExtensionAttributesToParseRule,kt=t.inputRulesPlugin,bt=t.isActive,yt=t.isAtEndOfNode,ht=t.isAtStartOfNode,Rt=t.isEmptyObject,Et=t.isExtensionRulesEnabled,ft=t.isFunction,Ct=t.isList,Pt=t.isMacOS,Tt=t.isMarkActive,At=t.isNodeActive,St=t.isNodeEmpty,Nt=t.isNodeSelection,Ot=t.isNumber,Bt=t.isPlainObject,wt=t.isRegExp,Mt=t.isSafari,vt=t.isString,It=t.isTextSelection,Ft=t.isiOS,s=t.markInputRule,a=t.markPasteRule,l=t.mergeAttributes,Dt=t.mergeDeep,jt=t.minMax,Lt=t.nodeInputRule,Kt=t.nodePasteRule,Ht=t.objectIncludes,qt=t.pasteRulesPlugin,Gt=t.posToDOMRect,zt=t.removeDuplicates,Jt=t.resolveFocusPosition,Ut=t.rewriteUnknownContent,Vt=t.selectionToInsertionEnd,Yt=t.splitExtensions,Qt=t.textInputRule,Wt=t.textPasteRule,Xt=t.textblockTypeInputRule,Zt=t.wrappingInputRule;var g=/(^|[^`])`([^`]+)`(?!`)/,_=/(^|[^`])`([^`]+)`(?!`)/g,d=i.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:e}){return["code",l(this.options.HTMLAttributes,e),0]},addCommands(){return{setCode:()=>({commands:e})=>e.setMark(this.name),toggleCode:()=>({commands:e})=>e.toggleMark(this.name),unsetCode:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[s({find:g,type:this.type})]},addPasteRules(){return[a({find:_,type:this.type})]}});var p="__LEPTOS_TIPTAP_BRIDGE__";function x(){let e=globalThis,o=e[p];if(o!=null)return o;let r={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[p]=r,r}function c(){return x()}function u(e){c().registerExtension(e)}var m={name:"code",create:()=>d,commands:{set_code:e=>e.chain().focus().setCode().run(),toggle_code:e=>e.chain().focus().toggleCode().run(),unset_code:e=>e.chain().focus().unsetCode().run()}};function ae(){u(m)}export{ae as register_code}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code_block.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code_block.js new file mode 100644 index 00000000..3ce13b8e --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_code_block.js @@ -0,0 +1,4 @@ +var p=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(p==null||p.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var e=p.modules["@tiptap/core"];if(e==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var B=e.CommandManager,O=e.Editor,w=e.Extension,v=e.InputRule,M=e.Mark,x=e.Node,D=e.NodePos,I=e.NodeView,F=e.PasteRule,j=e.Tracker,L=e.callOrReturn,K=e.canInsertNode,H=e.combineTransactionSteps,G=e.createChainableState,q=e.createDocument,z=e.createNodeFromContent,$=e.createStyleTag,J=e.defaultBlockAt,W=e.deleteProps,V=e.elementFromString,U=e.escapeForRegEx,Y=e.extensions,Q=e.findChildren,X=e.findChildrenInRange,Z=e.findDuplicates,ee=e.findParentNode,te=e.findParentNodeClosestToPos,ne=e.fromString,oe=e.generateHTML,re=e.generateJSON,ie=e.generateText,se=e.getAttributes,ae=e.getAttributesFromExtensions,le=e.getChangedRanges,de=e.getDebugJSON,pe=e.getExtensionField,ce=e.getHTMLFromFragment,ue=e.getMarkAttributes,ge=e.getMarkRange,xe=e.getMarkType,_e=e.getMarksBetween,me=e.getNodeAtPosition,ke=e.getNodeAttributes,be=e.getNodeType,ye=e.getRenderedAttributes,fe=e.getSchema,he=e.getSchemaByResolvedExtensions,Ee=e.getSchemaTypeByName,Se=e.getSchemaTypeNameByName,Pe=e.getSplittedAttributes,Ce=e.getText,Ae=e.getTextBetween,Re=e.getTextContentFromNodes,Te=e.getTextSerializersFromSchema,Ne=e.injectExtensionAttributesToParseRule,Be=e.inputRulesPlugin,Oe=e.isActive,we=e.isAtEndOfNode,ve=e.isAtStartOfNode,Me=e.isEmptyObject,De=e.isExtensionRulesEnabled,Ie=e.isFunction,Fe=e.isList,je=e.isMacOS,Le=e.isMarkActive,Ke=e.isNodeActive,He=e.isNodeEmpty,Ge=e.isNodeSelection,qe=e.isNumber,ze=e.isPlainObject,$e=e.isRegExp,Je=e.isSafari,We=e.isString,Ve=e.isTextSelection,Ue=e.isiOS,Ye=e.markInputRule,Qe=e.markPasteRule,_=e.mergeAttributes,Xe=e.mergeDeep,Ze=e.minMax,et=e.nodeInputRule,tt=e.nodePasteRule,nt=e.objectIncludes,ot=e.pasteRulesPlugin,rt=e.posToDOMRect,it=e.removeDuplicates,st=e.resolveFocusPosition,at=e.rewriteUnknownContent,lt=e.selectionToInsertionEnd,dt=e.splitExtensions,pt=e.textInputRule,ct=e.textPasteRule,c=e.textblockTypeInputRule,ut=e.wrappingInputRule;var u=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(u==null||u.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var a=u.modules["@tiptap/pm/state"];if(a==null)throw new Error('leptos-tiptap bridge module "@tiptap/pm/state" is unavailable');var xt=a.AllSelection,_t=a.EditorState,mt=a.NodeSelection,m=a.Plugin,k=a.PluginKey,b=a.Selection,kt=a.SelectionRange,y=a.TextSelection,bt=a.Transaction;var A=/^```([a-z]+)?[\s\n]$/,R=/^~~~([a-z]+)?[\s\n]$/,f=x.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var n;let{languageClassPrefix:o}=this.options,l=[...((n=t.firstElementChild)===null||n===void 0?void 0:n.classList)||[]].filter(r=>r.startsWith(o)).map(r=>r.replace(o,""))[0];return l||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:t,HTMLAttributes:n}){return["pre",_(this.options.HTMLAttributes,n),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},addCommands(){return{setCodeBlock:t=>({commands:n})=>n.setNode(this.name,t),toggleCodeBlock:t=>({commands:n})=>n.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{let{empty:t,$anchor:n}=this.editor.state.selection,o=n.pos===1;return!t||n.parent.type.name!==this.name?!1:o||!n.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;let{state:n}=t,{selection:o}=n,{$from:i,empty:s}=o;if(!s||i.parent.type!==this.type)return!1;let l=i.parentOffset===i.parent.nodeSize-2,r=i.parent.textContent.endsWith(` + +`);return!l||!r?!1:t.chain().command(({tr:d})=>(d.delete(i.pos-2,i.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;let{state:n}=t,{selection:o,doc:i}=n,{$from:s,empty:l}=o;if(!l||s.parent.type!==this.type||!(s.parentOffset===s.parent.nodeSize-2))return!1;let d=s.after();return d===void 0?!1:i.nodeAt(d)?t.commands.command(({tr:C})=>(C.setSelection(b.near(i.resolve(d))),!0)):t.commands.exitCode()}}},addInputRules(){return[c({find:A,type:this.type,getAttributes:t=>({language:t[1]})}),c({find:R,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new m({key:new k("codeBlockVSCodeHandler"),props:{handlePaste:(t,n)=>{if(!n.clipboardData||this.editor.isActive(this.type.name))return!1;let o=n.clipboardData.getData("text/plain"),i=n.clipboardData.getData("vscode-editor-data"),s=i?JSON.parse(i):void 0,l=s?.mode;if(!o||!l)return!1;let{tr:r,schema:d}=t.state,g=d.text(o.replace(/\r\n?/g,` +`));return r.replaceSelectionWith(this.type.create({language:l},g)),r.selection.$from.parent.type!==this.type&&r.setSelection(y.near(r.doc.resolve(Math.max(0,r.selection.from-2)))),r.setMeta("paste",!0),t.dispatch(r),!0}}})]}});var h="__LEPTOS_TIPTAP_BRIDGE__";function T(){let t=globalThis,n=t[h];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return t[h]=o,o}function E(){return T()}function S(t){E().registerExtension(t)}function P(t){if(t?.language!=null)return{language:t.language}}var N={name:"code_block",create:()=>f,commands:{set_code_block:(t,n)=>n.kind==="set_code_block"?t.chain().focus().setCodeBlock(P(n.attributes)).run():!1,toggle_code_block:(t,n)=>n.kind==="toggle_code_block"?t.chain().focus().toggleCodeBlock(P(n.attributes)).run():!1}};function Tt(){S(N)}export{Tt as register_code_block}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_document.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_document.js new file mode 100644 index 00000000..9948098d --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_document.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var u=t.CommandManager,g=t.Editor,_=t.Extension,x=t.InputRule,m=t.Mark,r=t.Node,k=t.NodePos,b=t.NodeView,y=t.PasteRule,E=t.Tracker,R=t.callOrReturn,h=t.canInsertNode,f=t.combineTransactionSteps,P=t.createChainableState,C=t.createDocument,S=t.createNodeFromContent,T=t.createStyleTag,A=t.defaultBlockAt,N=t.deleteProps,O=t.elementFromString,B=t.escapeForRegEx,w=t.extensions,v=t.findChildren,I=t.findChildrenInRange,M=t.findDuplicates,D=t.findParentNode,F=t.findParentNodeClosestToPos,j=t.fromString,L=t.generateHTML,K=t.generateJSON,q=t.generateText,G=t.getAttributes,H=t.getAttributesFromExtensions,z=t.getChangedRanges,J=t.getDebugJSON,U=t.getExtensionField,V=t.getHTMLFromFragment,Y=t.getMarkAttributes,Q=t.getMarkRange,W=t.getMarkType,X=t.getMarksBetween,Z=t.getNodeAtPosition,$=t.getNodeAttributes,tt=t.getNodeType,et=t.getRenderedAttributes,nt=t.getSchema,ot=t.getSchemaByResolvedExtensions,it=t.getSchemaTypeByName,rt=t.getSchemaTypeNameByName,st=t.getSplittedAttributes,lt=t.getText,at=t.getTextBetween,dt=t.getTextContentFromNodes,pt=t.getTextSerializersFromSchema,ct=t.injectExtensionAttributesToParseRule,ut=t.inputRulesPlugin,gt=t.isActive,_t=t.isAtEndOfNode,xt=t.isAtStartOfNode,mt=t.isEmptyObject,kt=t.isExtensionRulesEnabled,bt=t.isFunction,yt=t.isList,Et=t.isMacOS,Rt=t.isMarkActive,ht=t.isNodeActive,ft=t.isNodeEmpty,Pt=t.isNodeSelection,Ct=t.isNumber,St=t.isPlainObject,Tt=t.isRegExp,At=t.isSafari,Nt=t.isString,Ot=t.isTextSelection,Bt=t.isiOS,wt=t.markInputRule,vt=t.markPasteRule,It=t.mergeAttributes,Mt=t.mergeDeep,Dt=t.minMax,Ft=t.nodeInputRule,jt=t.nodePasteRule,Lt=t.objectIncludes,Kt=t.pasteRulesPlugin,qt=t.posToDOMRect,Gt=t.removeDuplicates,Ht=t.resolveFocusPosition,zt=t.rewriteUnknownContent,Jt=t.selectionToInsertionEnd,Ut=t.splitExtensions,Vt=t.textInputRule,Yt=t.textPasteRule,Qt=t.textblockTypeInputRule,Wt=t.wrappingInputRule;var s=r.create({name:"doc",topNode:!0,content:"block+"});var l="__LEPTOS_TIPTAP_BRIDGE__";function p(){let e=globalThis,o=e[l];if(o!=null)return o;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[l]=i,i}function a(){return p()}function d(e){a().registerExtension(e)}var c={name:"document",create:()=>s};function re(){d(c)}export{re as register_document}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_dropcursor.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_dropcursor.js new file mode 100644 index 00000000..2e21e1dc --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_dropcursor.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var x=t.CommandManager,m=t.Editor,s=t.Extension,k=t.InputRule,b=t.Mark,y=t.Node,E=t.NodePos,h=t.NodeView,R=t.PasteRule,P=t.Tracker,f=t.callOrReturn,C=t.canInsertNode,T=t.combineTransactionSteps,S=t.createChainableState,A=t.createDocument,O=t.createNodeFromContent,N=t.createStyleTag,w=t.defaultBlockAt,B=t.deleteProps,v=t.elementFromString,I=t.escapeForRegEx,M=t.extensions,D=t.findChildren,F=t.findChildrenInRange,j=t.findDuplicates,L=t.findParentNode,K=t.findParentNodeClosestToPos,G=t.fromString,q=t.generateHTML,H=t.generateJSON,z=t.generateText,J=t.getAttributes,U=t.getAttributesFromExtensions,V=t.getChangedRanges,Y=t.getDebugJSON,Q=t.getExtensionField,W=t.getHTMLFromFragment,X=t.getMarkAttributes,Z=t.getMarkRange,$=t.getMarkType,tt=t.getMarksBetween,et=t.getNodeAtPosition,nt=t.getNodeAttributes,ot=t.getNodeType,rt=t.getRenderedAttributes,it=t.getSchema,st=t.getSchemaByResolvedExtensions,lt=t.getSchemaTypeByName,at=t.getSchemaTypeNameByName,pt=t.getSplittedAttributes,dt=t.getText,ct=t.getTextBetween,ut=t.getTextContentFromNodes,gt=t.getTextSerializersFromSchema,_t=t.injectExtensionAttributesToParseRule,xt=t.inputRulesPlugin,mt=t.isActive,kt=t.isAtEndOfNode,bt=t.isAtStartOfNode,yt=t.isEmptyObject,Et=t.isExtensionRulesEnabled,ht=t.isFunction,Rt=t.isList,Pt=t.isMacOS,ft=t.isMarkActive,Ct=t.isNodeActive,Tt=t.isNodeEmpty,St=t.isNodeSelection,At=t.isNumber,Ot=t.isPlainObject,Nt=t.isRegExp,wt=t.isSafari,Bt=t.isString,vt=t.isTextSelection,It=t.isiOS,Mt=t.markInputRule,Dt=t.markPasteRule,Ft=t.mergeAttributes,jt=t.mergeDeep,Lt=t.minMax,Kt=t.nodeInputRule,Gt=t.nodePasteRule,qt=t.objectIncludes,Ht=t.pasteRulesPlugin,zt=t.posToDOMRect,Jt=t.removeDuplicates,Ut=t.resolveFocusPosition,Vt=t.rewriteUnknownContent,Yt=t.selectionToInsertionEnd,Qt=t.splitExtensions,Wt=t.textInputRule,Xt=t.textPasteRule,Zt=t.textblockTypeInputRule,$t=t.wrappingInputRule;var o=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(o==null||o.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var l=o.modules["@tiptap/pm/dropcursor"];if(l==null)throw new Error('leptos-tiptap bridge module "@tiptap/pm/dropcursor" is unavailable');var a=l.dropCursor;var p=s.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[a(this.options)]}});var d="__LEPTOS_TIPTAP_BRIDGE__";function g(){let e=globalThis,r=e[d];if(r!=null)return r;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[d]=i,i}function c(){return g()}function u(e){c().registerExtension(e)}var _={name:"dropcursor",create:()=>p};function de(){u(_)}export{de as register_dropcursor}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_gapcursor.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_gapcursor.js new file mode 100644 index 00000000..1bc9f17c --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_gapcursor.js @@ -0,0 +1 @@ +var r=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(r==null||r.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=r.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var k=t.CommandManager,b=t.Editor,a=t.Extension,y=t.InputRule,E=t.Mark,R=t.Node,h=t.NodePos,P=t.NodeView,f=t.PasteRule,C=t.Tracker,l=t.callOrReturn,T=t.canInsertNode,S=t.combineTransactionSteps,A=t.createChainableState,N=t.createDocument,O=t.createNodeFromContent,w=t.createStyleTag,B=t.defaultBlockAt,v=t.deleteProps,I=t.elementFromString,M=t.escapeForRegEx,F=t.extensions,D=t.findChildren,j=t.findChildrenInRange,G=t.findDuplicates,L=t.findParentNode,K=t.findParentNodeClosestToPos,q=t.fromString,H=t.generateHTML,z=t.generateJSON,J=t.generateText,U=t.getAttributes,V=t.getAttributesFromExtensions,Y=t.getChangedRanges,Q=t.getDebugJSON,p=t.getExtensionField,W=t.getHTMLFromFragment,X=t.getMarkAttributes,Z=t.getMarkRange,$=t.getMarkType,tt=t.getMarksBetween,et=t.getNodeAtPosition,nt=t.getNodeAttributes,ot=t.getNodeType,rt=t.getRenderedAttributes,it=t.getSchema,st=t.getSchemaByResolvedExtensions,at=t.getSchemaTypeByName,lt=t.getSchemaTypeNameByName,pt=t.getSplittedAttributes,dt=t.getText,ct=t.getTextBetween,ut=t.getTextContentFromNodes,gt=t.getTextSerializersFromSchema,_t=t.injectExtensionAttributesToParseRule,xt=t.inputRulesPlugin,mt=t.isActive,kt=t.isAtEndOfNode,bt=t.isAtStartOfNode,yt=t.isEmptyObject,Et=t.isExtensionRulesEnabled,Rt=t.isFunction,ht=t.isList,Pt=t.isMacOS,ft=t.isMarkActive,Ct=t.isNodeActive,Tt=t.isNodeEmpty,St=t.isNodeSelection,At=t.isNumber,Nt=t.isPlainObject,Ot=t.isRegExp,wt=t.isSafari,Bt=t.isString,vt=t.isTextSelection,It=t.isiOS,Mt=t.markInputRule,Ft=t.markPasteRule,Dt=t.mergeAttributes,jt=t.mergeDeep,Gt=t.minMax,Lt=t.nodeInputRule,Kt=t.nodePasteRule,qt=t.objectIncludes,Ht=t.pasteRulesPlugin,zt=t.posToDOMRect,Jt=t.removeDuplicates,Ut=t.resolveFocusPosition,Vt=t.rewriteUnknownContent,Yt=t.selectionToInsertionEnd,Qt=t.splitExtensions,Wt=t.textInputRule,Xt=t.textPasteRule,Zt=t.textblockTypeInputRule,$t=t.wrappingInputRule;var i=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(i==null||i.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var s=i.modules["@tiptap/pm/gapcursor"];if(s==null)throw new Error('leptos-tiptap bridge module "@tiptap/pm/gapcursor" is unavailable');var ee=s.GapCursor,d=s.gapCursor;var c=a.create({name:"gapCursor",addProseMirrorPlugins(){return[d()]},extendNodeSchema(e){var n;let o={name:e.name,options:e.options,storage:e.storage};return{allowGapCursor:(n=l(p(e,"allowGapCursor",o)))!==null&&n!==void 0?n:null}}});var u="__LEPTOS_TIPTAP_BRIDGE__";function x(){let e=globalThis,n=e[u];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[u]=o,o}function g(){return x()}function _(e){g().registerExtension(e)}var m={name:"gapcursor",create:()=>c};function ce(){_(m)}export{ce as register_gapcursor}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_hard_break.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_hard_break.js new file mode 100644 index 00000000..1f14707b --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_hard_break.js @@ -0,0 +1,2 @@ +var i=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(i==null||i.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=i.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var R=t.CommandManager,P=t.Editor,C=t.Extension,T=t.InputRule,S=t.Mark,a=t.Node,A=t.NodePos,B=t.NodeView,N=t.PasteRule,O=t.Tracker,M=t.callOrReturn,w=t.canInsertNode,v=t.combineTransactionSteps,I=t.createChainableState,F=t.createDocument,D=t.createNodeFromContent,j=t.createStyleTag,H=t.defaultBlockAt,L=t.deleteProps,K=t.elementFromString,q=t.escapeForRegEx,G=t.extensions,z=t.findChildren,J=t.findChildrenInRange,$=t.findDuplicates,U=t.findParentNode,V=t.findParentNodeClosestToPos,Y=t.fromString,Q=t.generateHTML,W=t.generateJSON,X=t.generateText,Z=t.getAttributes,tt=t.getAttributesFromExtensions,et=t.getChangedRanges,nt=t.getDebugJSON,ot=t.getExtensionField,rt=t.getHTMLFromFragment,it=t.getMarkAttributes,st=t.getMarkRange,at=t.getMarkType,lt=t.getMarksBetween,dt=t.getNodeAtPosition,pt=t.getNodeAttributes,ct=t.getNodeType,ut=t.getRenderedAttributes,gt=t.getSchema,_t=t.getSchemaByResolvedExtensions,xt=t.getSchemaTypeByName,mt=t.getSchemaTypeNameByName,kt=t.getSplittedAttributes,bt=t.getText,yt=t.getTextBetween,ft=t.getTextContentFromNodes,ht=t.getTextSerializersFromSchema,Et=t.injectExtensionAttributesToParseRule,Rt=t.inputRulesPlugin,Pt=t.isActive,Ct=t.isAtEndOfNode,Tt=t.isAtStartOfNode,St=t.isEmptyObject,At=t.isExtensionRulesEnabled,Bt=t.isFunction,Nt=t.isList,Ot=t.isMacOS,Mt=t.isMarkActive,wt=t.isNodeActive,vt=t.isNodeEmpty,It=t.isNodeSelection,Ft=t.isNumber,Dt=t.isPlainObject,jt=t.isRegExp,Ht=t.isSafari,Lt=t.isString,Kt=t.isTextSelection,qt=t.isiOS,Gt=t.markInputRule,zt=t.markPasteRule,l=t.mergeAttributes,Jt=t.mergeDeep,$t=t.minMax,Ut=t.nodeInputRule,Vt=t.nodePasteRule,Yt=t.objectIncludes,Qt=t.pasteRulesPlugin,Wt=t.posToDOMRect,Xt=t.removeDuplicates,Zt=t.resolveFocusPosition,te=t.rewriteUnknownContent,ee=t.selectionToInsertionEnd,ne=t.splitExtensions,oe=t.textInputRule,re=t.textPasteRule,ie=t.textblockTypeInputRule,se=t.wrappingInputRule;var d=a.create({name:"hardBreak",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:e}){return["br",l(this.options.HTMLAttributes,e)]},renderText(){return` +`},addCommands(){return{setHardBreak:()=>({commands:e,chain:n,state:o,editor:g})=>e.first([()=>e.exitCode(),()=>e.command(()=>{let{selection:r,storedMarks:_}=o;if(r.$from.parent.type.spec.isolating)return!1;let{keepMarks:x}=this.options,{splittableMarks:m}=g.extensionManager,s=_||r.$to.parentOffset&&r.$from.marks();return n().insertContent({type:this.name}).command(({tr:k,dispatch:b})=>{if(b&&s&&x){let y=s.filter(f=>m.includes(f.type.name));k.ensureMarks(y)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}});var p="__LEPTOS_TIPTAP_BRIDGE__";function h(){let e=globalThis,n=e[p];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[p]=o,o}function c(){return h()}function u(e){c().registerExtension(e)}var E={name:"hard_break",create:()=>d,commands:{set_hard_break:e=>e.chain().focus().setHardBreak().run()}};function xe(){u(E)}export{xe as register_hard_break}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_heading.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_heading.js new file mode 100644 index 00000000..77d66878 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_heading.js @@ -0,0 +1 @@ +var i=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(i==null||i.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var e=i.modules["@tiptap/core"];if(e==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var x=e.CommandManager,m=e.Editor,k=e.Extension,b=e.InputRule,y=e.Mark,r=e.Node,h=e.NodePos,f=e.NodeView,E=e.PasteRule,R=e.Tracker,A=e.callOrReturn,P=e.canInsertNode,v=e.combineTransactionSteps,T=e.createChainableState,C=e.createDocument,S=e.createNodeFromContent,N=e.createStyleTag,O=e.defaultBlockAt,B=e.deleteProps,w=e.elementFromString,M=e.escapeForRegEx,I=e.extensions,F=e.findChildren,D=e.findChildrenInRange,j=e.findDuplicates,H=e.findParentNode,L=e.findParentNodeClosestToPos,K=e.fromString,q=e.generateHTML,G=e.generateJSON,$=e.generateText,z=e.getAttributes,J=e.getAttributesFromExtensions,U=e.getChangedRanges,V=e.getDebugJSON,Y=e.getExtensionField,Q=e.getHTMLFromFragment,W=e.getMarkAttributes,X=e.getMarkRange,Z=e.getMarkType,ee=e.getMarksBetween,te=e.getNodeAtPosition,ne=e.getNodeAttributes,oe=e.getNodeType,ie=e.getRenderedAttributes,re=e.getSchema,se=e.getSchemaByResolvedExtensions,le=e.getSchemaTypeByName,ae=e.getSchemaTypeNameByName,de=e.getSplittedAttributes,pe=e.getText,ce=e.getTextBetween,ue=e.getTextContentFromNodes,ge=e.getTextSerializersFromSchema,_e=e.injectExtensionAttributesToParseRule,xe=e.inputRulesPlugin,me=e.isActive,ke=e.isAtEndOfNode,be=e.isAtStartOfNode,ye=e.isEmptyObject,he=e.isExtensionRulesEnabled,fe=e.isFunction,Ee=e.isList,Re=e.isMacOS,Ae=e.isMarkActive,Pe=e.isNodeActive,ve=e.isNodeEmpty,Te=e.isNodeSelection,Ce=e.isNumber,Se=e.isPlainObject,Ne=e.isRegExp,Oe=e.isSafari,Be=e.isString,we=e.isTextSelection,Me=e.isiOS,Ie=e.markInputRule,Fe=e.markPasteRule,s=e.mergeAttributes,De=e.mergeDeep,je=e.minMax,He=e.nodeInputRule,Le=e.nodePasteRule,Ke=e.objectIncludes,qe=e.pasteRulesPlugin,Ge=e.posToDOMRect,$e=e.removeDuplicates,ze=e.resolveFocusPosition,Je=e.rewriteUnknownContent,Ue=e.selectionToInsertionEnd,Ve=e.splitExtensions,Ye=e.textInputRule,Qe=e.textPasteRule,l=e.textblockTypeInputRule,We=e.wrappingInputRule;var a=r.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:n}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,s(this.options.HTMLAttributes,n),0]},addCommands(){return{setHeading:t=>({commands:n})=>this.options.levels.includes(t.level)?n.setNode(this.name,t):!1,toggleHeading:t=>({commands:n})=>this.options.levels.includes(t.level)?n.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,n)=>({...t,[`Mod-Alt-${n}`]:()=>this.editor.commands.toggleHeading({level:n})}),{})},addInputRules(){return this.options.levels.map(t=>l({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}});var d="__LEPTOS_TIPTAP_BRIDGE__";function u(){let t=globalThis,n=t[d];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return t[d]=o,o}function p(){return u()}function c(t){p().registerExtension(t)}var g={name:"heading",create:()=>a,commands:{set_heading:(t,n)=>n.kind==="set_heading"?t.chain().focus().setHeading({level:n.level}).run():!1,toggle_heading:(t,n)=>n.kind==="toggle_heading"?t.chain().focus().toggleHeading({level:n.level}).run():!1},selection_keys:["h1","h2","h3","h4","h5","h6"],selection_state:t=>({h1:t.isActive("heading",{level:1}),h2:t.isActive("heading",{level:2}),h3:t.isActive("heading",{level:3}),h4:t.isActive("heading",{level:4}),h5:t.isActive("heading",{level:5}),h6:t.isActive("heading",{level:6})})};function st(){c(g)}export{st as register_heading}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_highlight.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_highlight.js new file mode 100644 index 00000000..54825a15 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_highlight.js @@ -0,0 +1 @@ +var o=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(o==null||o.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=o.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var b=t.CommandManager,h=t.Editor,y=t.Extension,f=t.InputRule,r=t.Mark,R=t.Node,E=t.NodePos,P=t.NodeView,T=t.PasteRule,A=t.Tracker,C=t.callOrReturn,S=t.canInsertNode,N=t.combineTransactionSteps,O=t.createChainableState,B=t.createDocument,w=t.createNodeFromContent,M=t.createStyleTag,v=t.defaultBlockAt,I=t.deleteProps,F=t.elementFromString,D=t.escapeForRegEx,H=t.extensions,j=t.findChildren,L=t.findChildrenInRange,K=t.findDuplicates,q=t.findParentNode,G=t.findParentNodeClosestToPos,z=t.fromString,J=t.generateHTML,U=t.generateJSON,V=t.generateText,Y=t.getAttributes,$=t.getAttributesFromExtensions,Q=t.getChangedRanges,W=t.getDebugJSON,X=t.getExtensionField,Z=t.getHTMLFromFragment,tt=t.getMarkAttributes,et=t.getMarkRange,nt=t.getMarkType,ot=t.getMarksBetween,it=t.getNodeAtPosition,rt=t.getNodeAttributes,st=t.getNodeType,lt=t.getRenderedAttributes,at=t.getSchema,dt=t.getSchemaByResolvedExtensions,pt=t.getSchemaTypeByName,ut=t.getSchemaTypeNameByName,ct=t.getSplittedAttributes,gt=t.getText,_t=t.getTextBetween,xt=t.getTextContentFromNodes,mt=t.getTextSerializersFromSchema,kt=t.injectExtensionAttributesToParseRule,bt=t.inputRulesPlugin,ht=t.isActive,yt=t.isAtEndOfNode,ft=t.isAtStartOfNode,Rt=t.isEmptyObject,Et=t.isExtensionRulesEnabled,Pt=t.isFunction,Tt=t.isList,At=t.isMacOS,Ct=t.isMarkActive,St=t.isNodeActive,Nt=t.isNodeEmpty,Ot=t.isNodeSelection,Bt=t.isNumber,wt=t.isPlainObject,Mt=t.isRegExp,vt=t.isSafari,It=t.isString,Ft=t.isTextSelection,Dt=t.isiOS,s=t.markInputRule,l=t.markPasteRule,a=t.mergeAttributes,Ht=t.mergeDeep,jt=t.minMax,Lt=t.nodeInputRule,Kt=t.nodePasteRule,qt=t.objectIncludes,Gt=t.pasteRulesPlugin,zt=t.posToDOMRect,Jt=t.removeDuplicates,Ut=t.resolveFocusPosition,Vt=t.rewriteUnknownContent,Yt=t.selectionToInsertionEnd,$t=t.splitExtensions,Qt=t.textInputRule,Wt=t.textPasteRule,Xt=t.textblockTypeInputRule,Zt=t.wrappingInputRule;var _=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,x=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,d=r.create({name:"highlight",addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute("data-color")||e.style.backgroundColor,renderHTML:e=>e.color?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:"mark"}]},renderHTML({HTMLAttributes:e}){return["mark",a(this.options.HTMLAttributes,e),0]},addCommands(){return{setHighlight:e=>({commands:n})=>n.setMark(this.name,e),toggleHighlight:e=>({commands:n})=>n.toggleMark(this.name,e),unsetHighlight:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-h":()=>this.editor.commands.toggleHighlight()}},addInputRules(){return[s({find:_,type:this.type})]},addPasteRules(){return[l({find:x,type:this.type})]}});var p="__LEPTOS_TIPTAP_BRIDGE__";function m(){let e=globalThis,n=e[p];if(n!=null)return n;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[p]=i,i}function u(){return m()}function c(e){u().registerExtension(e)}function g(e){if(e?.color!=null)return{color:e.color}}var k={name:"highlight",create:()=>d.configure({multicolor:!0}),commands:{set_highlight:(e,n)=>n.kind==="set_highlight"?e.chain().focus().setHighlight(g(n.attributes)).run():!1,toggle_highlight:(e,n)=>n.kind==="toggle_highlight"?e.chain().focus().toggleHighlight(g(n.attributes)).run():!1,unset_highlight:e=>e.chain().focus().unsetHighlight().run()},selection_keys:["highlight"],selection_state:e=>({highlight:e.isActive("highlight")})};function ae(){c(k)}export{ae as register_highlight}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_history.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_history.js new file mode 100644 index 00000000..025df3f1 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_history.js @@ -0,0 +1 @@ +var r=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(r==null||r.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=r.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var k=t.CommandManager,b=t.Editor,l=t.Extension,y=t.InputRule,h=t.Mark,E=t.Node,f=t.NodePos,R=t.NodeView,P=t.PasteRule,S=t.Tracker,T=t.callOrReturn,C=t.canInsertNode,A=t.combineTransactionSteps,N=t.createChainableState,O=t.createDocument,w=t.createNodeFromContent,B=t.createStyleTag,v=t.defaultBlockAt,M=t.deleteProps,D=t.elementFromString,I=t.escapeForRegEx,F=t.extensions,j=t.findChildren,H=t.findChildrenInRange,L=t.findDuplicates,K=t.findParentNode,G=t.findParentNodeClosestToPos,q=t.fromString,z=t.generateHTML,J=t.generateJSON,U=t.generateText,V=t.getAttributes,Y=t.getAttributesFromExtensions,Q=t.getChangedRanges,W=t.getDebugJSON,X=t.getExtensionField,Z=t.getHTMLFromFragment,$=t.getMarkAttributes,tt=t.getMarkRange,et=t.getMarkType,nt=t.getMarksBetween,ot=t.getNodeAtPosition,rt=t.getNodeAttributes,it=t.getNodeType,st=t.getRenderedAttributes,lt=t.getSchema,at=t.getSchemaByResolvedExtensions,dt=t.getSchemaTypeByName,pt=t.getSchemaTypeNameByName,ct=t.getSplittedAttributes,ut=t.getText,gt=t.getTextBetween,_t=t.getTextContentFromNodes,xt=t.getTextSerializersFromSchema,mt=t.injectExtensionAttributesToParseRule,kt=t.inputRulesPlugin,bt=t.isActive,yt=t.isAtEndOfNode,ht=t.isAtStartOfNode,Et=t.isEmptyObject,ft=t.isExtensionRulesEnabled,Rt=t.isFunction,Pt=t.isList,St=t.isMacOS,Tt=t.isMarkActive,Ct=t.isNodeActive,At=t.isNodeEmpty,Nt=t.isNodeSelection,Ot=t.isNumber,wt=t.isPlainObject,Bt=t.isRegExp,vt=t.isSafari,Mt=t.isString,Dt=t.isTextSelection,It=t.isiOS,Ft=t.markInputRule,jt=t.markPasteRule,Ht=t.mergeAttributes,Lt=t.mergeDeep,Kt=t.minMax,Gt=t.nodeInputRule,qt=t.nodePasteRule,zt=t.objectIncludes,Jt=t.pasteRulesPlugin,Ut=t.posToDOMRect,Vt=t.removeDuplicates,Yt=t.resolveFocusPosition,Qt=t.rewriteUnknownContent,Wt=t.selectionToInsertionEnd,Xt=t.splitExtensions,Zt=t.textInputRule,$t=t.textPasteRule,te=t.textblockTypeInputRule,ee=t.wrappingInputRule;var i=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(i==null||i.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var n=i.modules["@tiptap/pm/history"];if(n==null)throw new Error('leptos-tiptap bridge module "@tiptap/pm/history" is unavailable');var oe=n.closeHistory,a=n.history,re=n.isHistoryTransaction,d=n.redo,ie=n.redoDepth,se=n.redoNoScroll,p=n.undo,le=n.undoDepth,ae=n.undoNoScroll;var c=l.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:e,dispatch:o})=>p(e,o),redo:()=>({state:e,dispatch:o})=>d(e,o)}},addProseMirrorPlugins(){return[a(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-\u044F":()=>this.editor.commands.undo(),"Shift-Mod-\u044F":()=>this.editor.commands.redo()}}});var u="__LEPTOS_TIPTAP_BRIDGE__";function x(){let e=globalThis,o=e[u];if(o!=null)return o;let s={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[u]=s,s}function g(){return x()}function _(e){g().registerExtension(e)}var m={name:"history",create:()=>c,commands:{undo:e=>e.chain().focus().undo().run(),redo:e=>e.chain().focus().redo().run()}};function be(){_(m)}export{be as register_history}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_horizontal_rule.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_horizontal_rule.js new file mode 100644 index 00000000..3bcb573f --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_horizontal_rule.js @@ -0,0 +1 @@ +var d=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(d==null||d.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var e=d.modules["@tiptap/core"];if(e==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var N=e.CommandManager,O=e.Editor,B=e.Extension,w=e.InputRule,v=e.Mark,m=e.Node,I=e.NodePos,M=e.NodeView,F=e.PasteRule,D=e.Tracker,j=e.callOrReturn,k=e.canInsertNode,L=e.combineTransactionSteps,H=e.createChainableState,K=e.createDocument,z=e.createNodeFromContent,G=e.createStyleTag,q=e.defaultBlockAt,$=e.deleteProps,J=e.elementFromString,V=e.escapeForRegEx,U=e.extensions,Y=e.findChildren,Q=e.findChildrenInRange,W=e.findDuplicates,X=e.findParentNode,Z=e.findParentNodeClosestToPos,ee=e.fromString,te=e.generateHTML,ne=e.generateJSON,oe=e.generateText,ie=e.getAttributes,re=e.getAttributesFromExtensions,se=e.getChangedRanges,le=e.getDebugJSON,ae=e.getExtensionField,pe=e.getHTMLFromFragment,de=e.getMarkAttributes,ce=e.getMarkRange,ue=e.getMarkType,ge=e.getMarksBetween,_e=e.getNodeAtPosition,xe=e.getNodeAttributes,me=e.getNodeType,ke=e.getRenderedAttributes,be=e.getSchema,ye=e.getSchemaByResolvedExtensions,fe=e.getSchemaTypeByName,he=e.getSchemaTypeNameByName,Ee=e.getSplittedAttributes,Re=e.getText,Se=e.getTextBetween,Te=e.getTextContentFromNodes,Pe=e.getTextSerializersFromSchema,Ae=e.injectExtensionAttributesToParseRule,Ce=e.inputRulesPlugin,Ne=e.isActive,Oe=e.isAtEndOfNode,Be=e.isAtStartOfNode,we=e.isEmptyObject,ve=e.isExtensionRulesEnabled,Ie=e.isFunction,Me=e.isList,Fe=e.isMacOS,De=e.isMarkActive,je=e.isNodeActive,Le=e.isNodeEmpty,b=e.isNodeSelection,He=e.isNumber,Ke=e.isPlainObject,ze=e.isRegExp,Ge=e.isSafari,qe=e.isString,$e=e.isTextSelection,Je=e.isiOS,Ve=e.markInputRule,Ue=e.markPasteRule,y=e.mergeAttributes,Ye=e.mergeDeep,Qe=e.minMax,f=e.nodeInputRule,We=e.nodePasteRule,Xe=e.objectIncludes,Ze=e.pasteRulesPlugin,et=e.posToDOMRect,tt=e.removeDuplicates,nt=e.resolveFocusPosition,ot=e.rewriteUnknownContent,it=e.selectionToInsertionEnd,rt=e.splitExtensions,st=e.textInputRule,lt=e.textPasteRule,at=e.textblockTypeInputRule,pt=e.wrappingInputRule;var c=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(c==null||c.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var o=c.modules["@tiptap/pm/state"];if(o==null)throw new Error('leptos-tiptap bridge module "@tiptap/pm/state" is unavailable');var ct=o.AllSelection,ut=o.EditorState,h=o.NodeSelection,gt=o.Plugin,_t=o.PluginKey,xt=o.Selection,mt=o.SelectionRange,a=o.TextSelection,kt=o.Transaction;var E=m.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:n}){return["hr",y(this.options.HTMLAttributes,n)]},addCommands(){return{setHorizontalRule:()=>({chain:n,state:r})=>{if(!k(r,r.schema.nodes[this.name]))return!1;let{selection:s}=r,{$from:u,$to:g}=s,l=n();return u.parentOffset===0?l.insertContentAt({from:Math.max(u.pos-1,0),to:g.pos},{type:this.name}):b(s)?l.insertContentAt(g.pos,{type:this.name}):l.insertContent({type:this.name}),l.command(({tr:t,dispatch:P})=>{var p;if(P){let{$to:i}=t.selection,_=i.end();if(i.nodeAfter)i.nodeAfter.isTextblock?t.setSelection(a.create(t.doc,i.pos+1)):i.nodeAfter.isBlock?t.setSelection(h.create(t.doc,i.pos)):t.setSelection(a.create(t.doc,i.pos));else{let x=(p=i.parent.type.contentMatch.defaultType)===null||p===void 0?void 0:p.create();x&&(t.insert(_,x),t.setSelection(a.create(t.doc,_+1)))}t.scrollIntoView()}return!0}).run()}}},addInputRules(){return[f({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}});var R="__LEPTOS_TIPTAP_BRIDGE__";function A(){let n=globalThis,r=n[R];if(r!=null)return r;let s={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return n[R]=s,s}function S(){return A()}function T(n){S().registerExtension(n)}var C={name:"horizontal_rule",create:()=>E,commands:{set_horizontal_rule:n=>n.chain().focus().setHorizontalRule().run()}};function At(){T(C)}export{At as register_horizontal_rule}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_image.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_image.js new file mode 100644 index 00000000..2ab16ac5 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_image.js @@ -0,0 +1 @@ +var i=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(i==null||i.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=i.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var k=t.CommandManager,b=t.Editor,y=t.Extension,f=t.InputRule,E=t.Mark,r=t.Node,h=t.NodePos,R=t.NodeView,P=t.PasteRule,C=t.Tracker,A=t.callOrReturn,T=t.canInsertNode,S=t.combineTransactionSteps,N=t.createChainableState,O=t.createDocument,B=t.createNodeFromContent,w=t.createStyleTag,I=t.defaultBlockAt,v=t.deleteProps,M=t.elementFromString,F=t.escapeForRegEx,D=t.extensions,j=t.findChildren,L=t.findChildrenInRange,H=t.findDuplicates,K=t.findParentNode,q=t.findParentNodeClosestToPos,G=t.fromString,z=t.generateHTML,J=t.generateJSON,U=t.generateText,V=t.getAttributes,Y=t.getAttributesFromExtensions,$=t.getChangedRanges,Q=t.getDebugJSON,W=t.getExtensionField,X=t.getHTMLFromFragment,Z=t.getMarkAttributes,tt=t.getMarkRange,et=t.getMarkType,nt=t.getMarksBetween,ot=t.getNodeAtPosition,it=t.getNodeAttributes,rt=t.getNodeType,st=t.getRenderedAttributes,lt=t.getSchema,at=t.getSchemaByResolvedExtensions,dt=t.getSchemaTypeByName,pt=t.getSchemaTypeNameByName,ut=t.getSplittedAttributes,ct=t.getText,gt=t.getTextBetween,_t=t.getTextContentFromNodes,xt=t.getTextSerializersFromSchema,mt=t.injectExtensionAttributesToParseRule,kt=t.inputRulesPlugin,bt=t.isActive,yt=t.isAtEndOfNode,ft=t.isAtStartOfNode,Et=t.isEmptyObject,ht=t.isExtensionRulesEnabled,Rt=t.isFunction,Pt=t.isList,Ct=t.isMacOS,At=t.isMarkActive,Tt=t.isNodeActive,St=t.isNodeEmpty,Nt=t.isNodeSelection,Ot=t.isNumber,Bt=t.isPlainObject,wt=t.isRegExp,It=t.isSafari,vt=t.isString,Mt=t.isTextSelection,Ft=t.isiOS,Dt=t.markInputRule,jt=t.markPasteRule,s=t.mergeAttributes,Lt=t.mergeDeep,Ht=t.minMax,l=t.nodeInputRule,Kt=t.nodePasteRule,qt=t.objectIncludes,Gt=t.pasteRulesPlugin,zt=t.posToDOMRect,Jt=t.removeDuplicates,Ut=t.resolveFocusPosition,Vt=t.rewriteUnknownContent,Yt=t.selectionToInsertionEnd,$t=t.splitExtensions,Qt=t.textInputRule,Wt=t.textPasteRule,Xt=t.textblockTypeInputRule,Zt=t.wrappingInputRule;var g=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,a=r.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{}}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:e}){return["img",s(this.options.HTMLAttributes,e)]},addCommands(){return{setImage:e=>({commands:n})=>n.insertContent({type:this.name,attrs:e})}},addInputRules(){return[l({find:g,type:this.type,getAttributes:e=>{let[,,n,o,c]=e;return{src:o,alt:n,title:c}}})]}});var d="__LEPTOS_TIPTAP_BRIDGE__";function _(){let e=globalThis,n=e[d];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[d]=o,o}function p(){return _()}function u(e){p().registerExtension(e)}function x(e){return{src:e.src,alt:e.alt??void 0,title:e.title??void 0}}var m={name:"image",create:()=>a,commands:{set_image:(e,n)=>n.kind==="set_image"?e.chain().focus().setImage(x(n)).run():!1}};function ae(){u(m)}export{ae as register_image}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_italic.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_italic.js new file mode 100644 index 00000000..b6d0e5e3 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_italic.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var y=t.CommandManager,h=t.Editor,R=t.Extension,f=t.InputRule,a=t.Mark,E=t.Node,P=t.NodePos,C=t.NodeView,T=t.PasteRule,A=t.Tracker,S=t.callOrReturn,N=t.canInsertNode,O=t.combineTransactionSteps,I=t.createChainableState,B=t.createDocument,w=t.createNodeFromContent,M=t.createStyleTag,v=t.defaultBlockAt,F=t.deleteProps,D=t.elementFromString,j=t.escapeForRegEx,L=t.extensions,K=t.findChildren,H=t.findChildrenInRange,q=t.findDuplicates,G=t.findParentNode,z=t.findParentNodeClosestToPos,J=t.fromString,U=t.generateHTML,V=t.generateJSON,Y=t.generateText,$=t.getAttributes,Q=t.getAttributesFromExtensions,W=t.getChangedRanges,X=t.getDebugJSON,Z=t.getExtensionField,tt=t.getHTMLFromFragment,et=t.getMarkAttributes,nt=t.getMarkRange,ot=t.getMarkType,it=t.getMarksBetween,rt=t.getNodeAtPosition,st=t.getNodeAttributes,at=t.getNodeType,lt=t.getRenderedAttributes,dt=t.getSchema,pt=t.getSchemaByResolvedExtensions,ct=t.getSchemaTypeByName,ut=t.getSchemaTypeNameByName,gt=t.getSplittedAttributes,_t=t.getText,xt=t.getTextBetween,mt=t.getTextContentFromNodes,kt=t.getTextSerializersFromSchema,bt=t.injectExtensionAttributesToParseRule,yt=t.inputRulesPlugin,ht=t.isActive,Rt=t.isAtEndOfNode,ft=t.isAtStartOfNode,Et=t.isEmptyObject,Pt=t.isExtensionRulesEnabled,Ct=t.isFunction,Tt=t.isList,At=t.isMacOS,St=t.isMarkActive,Nt=t.isNodeActive,Ot=t.isNodeEmpty,It=t.isNodeSelection,Bt=t.isNumber,wt=t.isPlainObject,Mt=t.isRegExp,vt=t.isSafari,Ft=t.isString,Dt=t.isTextSelection,jt=t.isiOS,o=t.markInputRule,i=t.markPasteRule,l=t.mergeAttributes,Lt=t.mergeDeep,Kt=t.minMax,Ht=t.nodeInputRule,qt=t.nodePasteRule,Gt=t.objectIncludes,zt=t.pasteRulesPlugin,Jt=t.posToDOMRect,Ut=t.removeDuplicates,Vt=t.resolveFocusPosition,Yt=t.rewriteUnknownContent,$t=t.selectionToInsertionEnd,Qt=t.splitExtensions,Wt=t.textInputRule,Xt=t.textPasteRule,Zt=t.textblockTypeInputRule,te=t.wrappingInputRule;var g=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,_=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,x=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,m=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,d=a.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:e=>e.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:e=>e.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:e}){return["em",l(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[o({find:g,type:this.type}),o({find:x,type:this.type})]},addPasteRules(){return[i({find:_,type:this.type}),i({find:m,type:this.type})]}});var p="__LEPTOS_TIPTAP_BRIDGE__";function k(){let e=globalThis,r=e[p];if(r!=null)return r;let s={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[p]=s,s}function c(){return k()}function u(e){c().registerExtension(e)}var b={name:"italic",create:()=>d,commands:{set_italic:e=>e.chain().focus().setItalic().run(),toggle_italic:e=>e.chain().focus().toggleItalic().run(),unset_italic:e=>e.chain().focus().unsetItalic().run()},selection_keys:["italic"],selection_state:e=>({italic:e.isActive("italic")})};function de(){u(b)}export{de as register_italic}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_link.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_link.js new file mode 100644 index 00000000..e62e8ab9 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_link.js @@ -0,0 +1,5 @@ +var Bt=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(Bt==null||Bt.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var r=Bt.modules["@tiptap/core"];if(r==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var kn=r.CommandManager,En=r.Editor,xn=r.Extension,bn=r.InputRule,fe=r.Mark,_n=r.Node,yn=r.NodePos,An=r.NodeView,Tn=r.PasteRule,Rn=r.Tracker,Cn=r.callOrReturn,Sn=r.canInsertNode,me=r.combineTransactionSteps,Ln=r.createChainableState,On=r.createDocument,Pn=r.createNodeFromContent,Nn=r.createStyleTag,In=r.defaultBlockAt,wn=r.deleteProps,vn=r.elementFromString,Dn=r.escapeForRegEx,Mn=r.extensions,Hn=r.findChildren,ke=r.findChildrenInRange,jn=r.findDuplicates,Bn=r.findParentNode,Un=r.findParentNodeClosestToPos,Fn=r.fromString,zn=r.generateHTML,Kn=r.generateJSON,Wn=r.generateText,Ee=r.getAttributes,Gn=r.getAttributesFromExtensions,xe=r.getChangedRanges,Qn=r.getDebugJSON,$n=r.getExtensionField,qn=r.getHTMLFromFragment,Jn=r.getMarkAttributes,Vn=r.getMarkRange,Yn=r.getMarkType,be=r.getMarksBetween,Xn=r.getNodeAtPosition,Zn=r.getNodeAttributes,to=r.getNodeType,eo=r.getRenderedAttributes,no=r.getSchema,oo=r.getSchemaByResolvedExtensions,io=r.getSchemaTypeByName,ro=r.getSchemaTypeNameByName,so=r.getSplittedAttributes,lo=r.getText,ao=r.getTextBetween,co=r.getTextContentFromNodes,uo=r.getTextSerializersFromSchema,po=r.injectExtensionAttributesToParseRule,go=r.inputRulesPlugin,ho=r.isActive,fo=r.isAtEndOfNode,mo=r.isAtStartOfNode,ko=r.isEmptyObject,Eo=r.isExtensionRulesEnabled,xo=r.isFunction,bo=r.isList,_o=r.isMacOS,yo=r.isMarkActive,Ao=r.isNodeActive,To=r.isNodeEmpty,Ro=r.isNodeSelection,Co=r.isNumber,So=r.isPlainObject,Lo=r.isRegExp,Oo=r.isSafari,Po=r.isString,No=r.isTextSelection,Io=r.isiOS,wo=r.markInputRule,_e=r.markPasteRule,Ut=r.mergeAttributes,vo=r.mergeDeep,Do=r.minMax,Mo=r.nodeInputRule,Ho=r.nodePasteRule,jo=r.objectIncludes,Bo=r.pasteRulesPlugin,Uo=r.posToDOMRect,Fo=r.removeDuplicates,zo=r.resolveFocusPosition,Ko=r.rewriteUnknownContent,Wo=r.selectionToInsertionEnd,Go=r.splitExtensions,Qo=r.textInputRule,$o=r.textPasteRule,qo=r.textblockTypeInputRule,Jo=r.wrappingInputRule;var Ge="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5m\xF6gensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Qe="\u03B5\u03BB1\u03C52\u0431\u04331\u0435\u043B3\u0434\u0435\u0442\u04384\u0435\u044E2\u043A\u0430\u0442\u043E\u043B\u0438\u043A6\u043E\u043C3\u043C\u043A\u04342\u043E\u043D1\u0441\u043A\u0432\u04306\u043E\u043D\u043B\u0430\u0439\u043D5\u0440\u04333\u0440\u0443\u04412\u04442\u0441\u0430\u0439\u04423\u0440\u04313\u0443\u043A\u04403\u049B\u0430\u04373\u0570\u0561\u05753\u05D9\u05E9\u05E8\u05D0\u05DC5\u05E7\u05D5\u05DD3\u0627\u0628\u0648\u0638\u0628\u064A5\u0631\u0627\u0645\u0643\u06485\u0644\u0627\u0631\u062F\u06464\u0628\u062D\u0631\u064A\u06465\u062C\u0632\u0627\u0626\u06315\u0633\u0639\u0648\u062F\u064A\u06296\u0639\u0644\u064A\u0627\u06465\u0645\u063A\u0631\u06285\u0645\u0627\u0631\u0627\u062A5\u06CC\u0631\u0627\u06465\u0628\u0627\u0631\u062A2\u0632\u0627\u06314\u064A\u062A\u06433\u06BE\u0627\u0631\u062A5\u062A\u0648\u0646\u06334\u0633\u0648\u062F\u0627\u06463\u0631\u064A\u06295\u0634\u0628\u0643\u06294\u0639\u0631\u0627\u06422\u06282\u0645\u0627\u06464\u0641\u0644\u0633\u0637\u064A\u06466\u0642\u0637\u06313\u0643\u0627\u062B\u0648\u0644\u064A\u06436\u0648\u06453\u0645\u0635\u06312\u0644\u064A\u0633\u064A\u06275\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u06277\u0642\u06394\u0647\u0645\u0631\u0627\u06475\u067E\u0627\u06A9\u0633\u062A\u0627\u06467\u0680\u0627\u0631\u062A4\u0915\u0949\u092E3\u0928\u0947\u091F3\u092D\u093E\u0930\u09240\u092E\u094D3\u094B\u09245\u0938\u0902\u0917\u0920\u09285\u09AC\u09BE\u0982\u09B2\u09BE5\u09AD\u09BE\u09B0\u09A42\u09F0\u09A44\u0A2D\u0A3E\u0A30\u0A244\u0AAD\u0ABE\u0AB0\u0AA44\u0B2D\u0B3E\u0B30\u0B244\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE6\u0BB2\u0B99\u0BCD\u0B95\u0BC86\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD11\u0C2D\u0C3E\u0C30\u0C24\u0C4D5\u0CAD\u0CBE\u0CB0\u0CA44\u0D2D\u0D3E\u0D30\u0D24\u0D025\u0DBD\u0D82\u0D9A\u0DCF4\u0E04\u0E2D\u0E213\u0E44\u0E17\u0E223\u0EA5\u0EB2\u0EA73\u10D2\u10D42\u307F\u3093\u306A3\u30A2\u30DE\u30BE\u30F34\u30AF\u30E9\u30A6\u30C94\u30B0\u30FC\u30B0\u30EB4\u30B3\u30E02\u30B9\u30C8\u30A23\u30BB\u30FC\u30EB3\u30D5\u30A1\u30C3\u30B7\u30E7\u30F36\u30DD\u30A4\u30F3\u30C84\u4E16\u754C2\u4E2D\u4FE11\u56FD1\u570B1\u6587\u7F513\u4E9A\u9A6C\u900A3\u4F01\u4E1A2\u4F5B\u5C712\u4FE1\u606F2\u5065\u5EB72\u516B\u53662\u516C\u53F81\u76CA2\u53F0\u6E7E1\u70632\u5546\u57CE1\u5E971\u68072\u5609\u91CC0\u5927\u9152\u5E975\u5728\u7EBF2\u5927\u62FF2\u5929\u4E3B\u65593\u5A31\u4E502\u5BB6\u96FB2\u5E7F\u4E1C2\u5FAE\u535A2\u6148\u55842\u6211\u7231\u4F603\u624B\u673A2\u62DB\u80582\u653F\u52A11\u5E9C2\u65B0\u52A0\u57612\u95FB2\u65F6\u5C1A2\u66F8\u7C4D2\u673A\u67842\u6DE1\u9A6C\u95213\u6E38\u620F2\u6FB3\u95802\u70B9\u770B2\u79FB\u52A82\u7EC4\u7EC7\u673A\u67844\u7F51\u57401\u5E971\u7AD91\u7EDC2\u8054\u901A2\u8C37\u6B4C2\u8D2D\u72692\u901A\u8CA92\u96C6\u56E22\u96FB\u8A0A\u76C8\u79D14\u98DE\u5229\u6D663\u98DF\u54C12\u9910\u53852\u9999\u683C\u91CC\u62C93\u6E2F2\uB2F7\uB1371\uCEF42\uC0BC\uC1312\uD55C\uAD6D2",$t="numeric",qt="ascii",Jt="alpha",G="asciinumeric",W="alphanumeric",Vt="domain",Le="emoji",$e="scheme",qe="slashscheme",Ft="whitespace";function Je(t,n){return t in n||(n[t]=[]),n[t]}function H(t,n,e){n[$t]&&(n[G]=!0,n[W]=!0),n[qt]&&(n[G]=!0,n[Jt]=!0),n[G]&&(n[W]=!0),n[Jt]&&(n[W]=!0),n[W]&&(n[Vt]=!0),n[Le]&&(n[Vt]=!0);for(let o in n){let i=Je(o,e);i.indexOf(t)<0&&i.push(t)}}function Ve(t,n){let e={};for(let o in n)n[o].indexOf(t)>=0&&(e[o]=!0);return e}function T(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}T.groups={};T.prototype={accepts(){return!!this.t},go(t){let n=this,e=n.j[t];if(e)return e;for(let o=0;ot.ta(n,e,o,i),x=(t,n,e,o,i)=>t.tr(n,e,o,i),ye=(t,n,e,o,i)=>t.ts(n,e,o,i),s=(t,n,e,o,i)=>t.tt(n,e,o,i),w="WORD",Yt="UWORD",Oe="ASCIINUMERICAL",Pe="ALPHANUMERICAL",Y="LOCALHOST",Xt="TLD",Zt="UTLD",ot="SCHEME",U="SLASH_SCHEME",ee="NUM",te="WS",ne="NL",Q="OPENBRACE",$="CLOSEBRACE",it="OPENBRACKET",rt="CLOSEBRACKET",st="OPENPAREN",lt="CLOSEPAREN",at="OPENANGLEBRACKET",ct="CLOSEANGLEBRACKET",ut="FULLWIDTHLEFTPAREN",dt="FULLWIDTHRIGHTPAREN",pt="LEFTCORNERBRACKET",gt="RIGHTCORNERBRACKET",ht="LEFTWHITECORNERBRACKET",ft="RIGHTWHITECORNERBRACKET",mt="FULLWIDTHLESSTHAN",kt="FULLWIDTHGREATERTHAN",Et="AMPERSAND",xt="APOSTROPHE",bt="ASTERISK",D="AT",_t="BACKSLASH",yt="BACKTICK",At="CARET",M="COLON",oe="COMMA",Tt="DOLLAR",L="DOT",Rt="EQUALS",ie="EXCLAMATION",S="HYPHEN",q="PERCENT",Ct="PIPE",St="PLUS",Lt="POUND",J="QUERY",re="QUOTE",Ne="FULLWIDTHMIDDLEDOT",se="SEMI",O="SLASH",V="TILDE",Ot="UNDERSCORE",Ie="EMOJI",Pt="SYM",we=Object.freeze({__proto__:null,ALPHANUMERICAL:Pe,AMPERSAND:Et,APOSTROPHE:xt,ASCIINUMERICAL:Oe,ASTERISK:bt,AT:D,BACKSLASH:_t,BACKTICK:yt,CARET:At,CLOSEANGLEBRACKET:ct,CLOSEBRACE:$,CLOSEBRACKET:rt,CLOSEPAREN:lt,COLON:M,COMMA:oe,DOLLAR:Tt,DOT:L,EMOJI:Ie,EQUALS:Rt,EXCLAMATION:ie,FULLWIDTHGREATERTHAN:kt,FULLWIDTHLEFTPAREN:ut,FULLWIDTHLESSTHAN:mt,FULLWIDTHMIDDLEDOT:Ne,FULLWIDTHRIGHTPAREN:dt,HYPHEN:S,LEFTCORNERBRACKET:pt,LEFTWHITECORNERBRACKET:ht,LOCALHOST:Y,NL:ne,NUM:ee,OPENANGLEBRACKET:at,OPENBRACE:Q,OPENBRACKET:it,OPENPAREN:st,PERCENT:q,PIPE:Ct,PLUS:St,POUND:Lt,QUERY:J,QUOTE:re,RIGHTCORNERBRACKET:gt,RIGHTWHITECORNERBRACKET:ft,SCHEME:ot,SEMI:se,SLASH:O,SLASH_SCHEME:U,SYM:Pt,TILDE:V,TLD:Xt,UNDERSCORE:Ot,UTLD:Zt,UWORD:Yt,WORD:w,WS:te}),N=/[a-z]/,K=/\p{L}/u,zt=/\p{Emoji}/u;var I=/\d/,Kt=/\s/;var Ae="\r",Wt=` +`,Ye="\uFE0F",Xe="\u200D",Gt="\uFFFC",tt=null,et=null;function Ze(t=[]){let n={};T.groups=n;let e=new T;tt==null&&(tt=Te(Ge)),et==null&&(et=Te(Qe)),s(e,"'",xt),s(e,"{",Q),s(e,"}",$),s(e,"[",it),s(e,"]",rt),s(e,"(",st),s(e,")",lt),s(e,"<",at),s(e,">",ct),s(e,"\uFF08",ut),s(e,"\uFF09",dt),s(e,"\u300C",pt),s(e,"\u300D",gt),s(e,"\u300E",ht),s(e,"\u300F",ft),s(e,"\uFF1C",mt),s(e,"\uFF1E",kt),s(e,"&",Et),s(e,"*",bt),s(e,"@",D),s(e,"`",yt),s(e,"^",At),s(e,":",M),s(e,",",oe),s(e,"$",Tt),s(e,".",L),s(e,"=",Rt),s(e,"!",ie),s(e,"-",S),s(e,"%",q),s(e,"|",Ct),s(e,"+",St),s(e,"#",Lt),s(e,"?",J),s(e,'"',re),s(e,"/",O),s(e,";",se),s(e,"~",V),s(e,"_",Ot),s(e,"\\",_t),s(e,"\u30FB",Ne);let o=x(e,I,ee,{[$t]:!0});x(o,I,o);let i=x(o,N,Oe,{[G]:!0}),l=x(o,K,Pe,{[W]:!0}),a=x(e,N,w,{[qt]:!0});x(a,I,i),x(a,N,a),x(i,I,i),x(i,N,i);let c=x(e,K,Yt,{[Jt]:!0});x(c,N),x(c,I,l),x(c,K,c),x(l,I,l),x(l,N),x(l,K,l);let g=s(e,Wt,ne,{[Ft]:!0}),u=s(e,Ae,te,{[Ft]:!0}),h=x(e,Kt,te,{[Ft]:!0});s(e,Gt,h),s(u,Wt,g),s(u,Gt,h),x(u,Kt,h),s(h,Ae),s(h,Wt),x(h,Kt,h),s(h,Gt,h);let p=x(e,zt,Ie,{[Le]:!0});s(p,"#"),x(p,zt,p),s(p,Ye,p);let m=s(p,Xe);s(m,"#"),x(m,zt,p);let k=[[N,a],[I,i]],R=[[N,null],[K,c],[I,l]];for(let b=0;bb[0]>y[0]?1:-1);for(let b=0;b=0?_[Vt]=!0:N.test(y)?I.test(y)?_[G]=!0:_[qt]=!0:_[$t]=!0,ye(e,y,y,_)}return ye(e,"localhost",Y,{ascii:!0}),e.jd=new T(Pt),{start:e,tokens:Object.assign({groups:n},we)}}function ve(t,n){let e=tn(n.replace(/[A-Z]/g,c=>c.toLowerCase())),o=e.length,i=[],l=0,a=0;for(;a=0&&(p+=e[a].length,m++),u+=e[a].length,l+=e[a].length,a++;l-=p,a-=m,u-=p,i.push({t:h.t,v:n.slice(l-u,l),s:l-u,e:l})}return i}function tn(t){let n=[],e=t.length,o=0;for(;o56319||o+1===e||(l=t.charCodeAt(o+1))<56320||l>57343?t[o]:t.slice(o,o+2);n.push(a),o+=a.length}return n}function v(t,n,e,o,i){let l,a=n.length;for(let c=0;c=0;)l++;if(l>0){n.push(e.join(""));for(let a=parseInt(t.substring(o,o+l),10);a>0;a--)e.pop();o+=l}else e.push(t[o]),o++}return n}var X={defaultProtocol:"http",events:null,format:Re,formatHref:Re,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function le(t,n=null){let e=Object.assign({},X);t&&(e=Object.assign(e,t instanceof le?t.o:t));let o=e.ignoreTags,i=[];for(let l=0;le?o.substring(0,e)+"\u2026":o},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=X.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){let n=this,e=this.toHref(t.get("defaultProtocol")),o=t.get("formatHref",e,this),i=t.get("tagName",e,n),l=this.toFormattedString(t),a={},c=t.get("className",e,n),g=t.get("target",e,n),u=t.get("rel",e,n),h=t.getObj("attributes",e,n),p=t.getObj("events",e,n);return a.href=o,c&&(a.class=c),g&&(a.target=g),u&&(a.rel=u),h&&Object.assign(a,h),{tagName:i,attributes:a,content:l,eventListeners:p}}};function Nt(t,n){class e extends De{constructor(i,l){super(i,l),this.t=t}}for(let o in n)e.prototype[o]=n[o];return e.t=t,e}var Ce=Nt("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Se=Nt("text"),en=Nt("nl"),nt=Nt("url",{isLink:!0,toHref(t=X.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){let t=this.tk;return t.length>=2&&t[0].t!==Y&&t[1].t===M}});var C=t=>new T(t);function nn({groups:t}){let n=t.domain.concat([Et,bt,D,_t,yt,At,Tt,Rt,S,ee,q,Ct,St,Lt,O,Pt,V,Ot]),e=[xt,M,oe,L,ie,q,J,re,se,at,ct,Q,$,rt,it,st,lt,ut,dt,pt,gt,ht,ft,mt,kt],o=[Et,xt,bt,_t,yt,At,Tt,Rt,S,Q,$,q,Ct,St,Lt,J,O,Pt,V,Ot],i=C(),l=s(i,V);d(l,o,l),d(l,t.domain,l);let a=C(),c=C(),g=C();d(i,t.domain,a),d(i,t.scheme,c),d(i,t.slashscheme,g),d(a,o,l),d(a,t.domain,a);let u=s(a,D);s(l,D,u),s(c,D,u),s(g,D,u);let h=s(l,L);d(h,o,l),d(h,t.domain,l);let p=C();d(u,t.domain,p),d(p,t.domain,p);let m=s(p,L);d(m,t.domain,p);let k=C(Ce);d(m,t.tld,k),d(m,t.utld,k),s(u,Y,k);let R=s(p,S);s(R,S,R),d(R,t.domain,p),d(k,t.domain,p),s(k,L,m),s(k,S,R);let b=s(k,M);d(b,t.numeric,Ce);let y=s(a,S),f=s(a,L);s(y,S,y),d(y,t.domain,a),d(f,o,l),d(f,t.domain,a);let _=C(nt);d(f,t.tld,_),d(f,t.utld,_),d(_,t.domain,a),d(_,o,l),s(_,L,f),s(_,S,y),s(_,D,u);let ze=s(_,M),pe=C(nt);d(ze,t.numeric,pe);let A=C(nt),F=C();d(A,n,A),d(A,e,F),d(F,n,A),d(F,e,F),s(_,O,A),s(pe,O,A);let Dt=s(c,M),Ke=s(g,M),We=s(Ke,O),Mt=s(We,O);d(c,t.domain,a),s(c,L,f),s(c,S,y),d(g,t.domain,a),s(g,L,f),s(g,S,y),d(Dt,t.domain,A),s(Dt,O,A),s(Dt,J,A),d(Mt,t.domain,A),d(Mt,n,A),s(Mt,O,A);let ge=[[Q,$],[it,rt],[st,lt],[at,ct],[ut,dt],[pt,gt],[ht,ft],[mt,kt]];for(let Ht=0;Ht=0&&m++,i++,h++;if(m<0)i-=h,i0&&(l.push(Qt(Se,n,a)),a=[]),i-=m,h-=m;let k=p.t,R=e.slice(i-h,i);l.push(Qt(k,n,R))}}return a.length>0&&l.push(Qt(Se,n,a)),l}function Qt(t,n,e){let o=e[0].s,i=e[e.length-1].e,l=n.slice(o,i);return new t(l,e)}var rn=typeof console<"u"&&console&&console.warn||(()=>{}),sn="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",E={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Me(){return T.groups={},E.scanner=null,E.parser=null,E.tokenQueue=[],E.pluginQueue=[],E.customSchemes=[],E.initialized=!1,E}function ae(t,n=!1){if(E.initialized&&rn(`linkifyjs: already initialized - will not register custom scheme "${t}" ${sn}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format. +1. Must only contain digits, lowercase ASCII letters or "-" +2. Cannot start or end with "-" +3. "-" cannot repeat`);E.customSchemes.push([t,n])}function ln(){E.scanner=Ze(E.customSchemes);for(let t=0;t{let i=n.some(u=>u.docChanged)&&!e.doc.eq(o.doc),l=n.some(u=>u.getMeta("preventAutolink"));if(!i||l)return;let{tr:a}=o,c=me(e.doc,[...n]);if(xe(c).forEach(({newRange:u})=>{let h=ke(o.doc,u,k=>k.isTextblock),p,m;if(h.length>1)p=h[0],m=o.doc.textBetween(p.pos,p.pos+p.node.nodeSize,void 0," ");else if(h.length){let k=o.doc.textBetween(u.from,u.to," "," ");if(!cn.test(k))return;p=h[0],m=o.doc.textBetween(p.pos,u.to,void 0," ")}if(p&&m){let k=m.split(an).filter(Boolean);if(k.length<=0)return!1;let R=k[k.length-1],b=p.pos+m.lastIndexOf(R);if(!R)return!1;let y=It(R).map(f=>f.toObject(t.defaultProtocol));if(!dn(y))return!1;y.filter(f=>f.isLink).map(f=>({...f,from:b+f.start+1,to:b+f.end+1})).filter(f=>o.schema.marks.code?!o.doc.rangeHasMark(f.from,f.to,o.schema.marks.code):!0).filter(f=>t.validate(f.value)).filter(f=>t.shouldAutoLink(f.value)).forEach(f=>{be(f.from,f.to,o.doc).some(_=>_.mark.type===t.type)||a.addMark(f.from,f.to,t.type.create({href:f.href}))})}}),!!a.steps.length)return a}})}function gn(t){return new wt({key:new vt("handleClickLink"),props:{handleClick:(n,e,o)=>{var i,l;if(o.button!==0||!n.editable)return!1;let a=o.target,c=[];for(;a.nodeName!=="DIV";)c.push(a),a=a.parentNode;if(!c.find(m=>m.nodeName==="A"))return!1;let g=Ee(n.state,t.type.name),u=o.target,h=(i=u?.href)!==null&&i!==void 0?i:g.href,p=(l=u?.target)!==null&&l!==void 0?l:g.target;return u&&h?(window.open(h,p),!0):!1}}})}function hn(t){return new wt({key:new vt("handlePasteLink"),props:{handlePaste:(n,e,o)=>{let{state:i}=n,{selection:l}=i,{empty:a}=l;if(a)return!1;let c="";o.content.forEach(u=>{c+=u.textContent});let g=ce(c,{defaultProtocol:t.defaultProtocol}).find(u=>u.isLink&&u.value===c);return!c||!g?!1:t.editor.commands.setMark(t.type,{href:g.href})}}})}function j(t,n){let e=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return n&&n.forEach(o=>{let i=typeof o=="string"?o:o.scheme;i&&e.push(i)}),!t||t.replace(un,"").match(new RegExp(`^(?:(?:${e.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var He=fe.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{if(typeof t=="string"){ae(t);return}ae(t.scheme,t.optionalSlashes)})},onDestroy(){Me()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,n)=>!!j(t,n.protocols),validate:t=>!!t,shouldAutoLink:t=>!!t}},addAttributes(){return{href:{default:null,parseHTML(t){return t.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{let n=t.getAttribute("href");return!n||!this.options.isAllowedUri(n,{defaultValidate:e=>!!j(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:n=>!!j(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Ut(this.options.HTMLAttributes,t),0]:["a",Ut(this.options.HTMLAttributes,{...t,href:""}),0]},addCommands(){return{setLink:t=>({chain:n})=>{let{href:e}=t;return this.options.isAllowedUri(e,{defaultValidate:o=>!!j(o,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?n().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:n})=>{let{href:e}=t;return this.options.isAllowedUri(e,{defaultValidate:o=>!!j(o,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?n().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run():!1},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[_e({find:t=>{let n=[];if(t){let{protocols:e,defaultProtocol:o}=this.options,i=ce(t).filter(l=>l.isLink&&this.options.isAllowedUri(l.value,{defaultValidate:a=>!!j(a,e),protocols:e,defaultProtocol:o}));i.length&&i.forEach(l=>n.push({text:l.value,data:{href:l.href},index:l.start}))}return n},type:this.type,getAttributes:t=>{var n;return{href:(n=t.data)===null||n===void 0?void 0:n.href}}})]},addProseMirrorPlugins(){let t=[],{protocols:n,defaultProtocol:e}=this.options;return this.options.autolink&&t.push(pn({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:o=>this.options.isAllowedUri(o,{defaultValidate:i=>!!j(i,n),protocols:n,defaultProtocol:e}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&t.push(gn({type:this.type})),this.options.linkOnPaste&&t.push(hn({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),t}});var je="__LEPTOS_TIPTAP_BRIDGE__";function fn(){let t=globalThis,n=t[je];if(n!=null)return n;let e={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return t[je]=e,e}function Be(){return fn()}function Ue(t){Be().registerExtension(t)}function Fe(t,n,e,o){let i={href:t};return n!=null&&(i.target=n),e!=null&&(i.rel=e),o!=null&&(i.class=o),i}var mn={name:"link",create:()=>He,commands:{set_link:(t,n)=>n.kind==="set_link"?t.chain().focus().setLink(Fe(n.href,n.target,n.rel,n.class)).run():!1,toggle_link:(t,n)=>n.kind==="toggle_link"?t.chain().focus().toggleLink(Fe(n.href,n.target,n.rel,n.class)).run():!1,unset_link:t=>t.chain().focus().unsetLink().run()},selection_keys:["link"],selection_state:t=>({link:t.isActive("link")})};function fi(){Ue(mn)}export{fi as register_link}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_list_item.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_list_item.js new file mode 100644 index 00000000..c0137d7c --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_list_item.js @@ -0,0 +1 @@ +var o=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(o==null||o.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=o.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var g=t.CommandManager,_=t.Editor,m=t.Extension,x=t.InputRule,k=t.Mark,r=t.Node,b=t.NodePos,y=t.NodeView,h=t.PasteRule,E=t.Tracker,f=t.callOrReturn,R=t.canInsertNode,P=t.combineTransactionSteps,T=t.createChainableState,A=t.createDocument,C=t.createNodeFromContent,S=t.createStyleTag,N=t.defaultBlockAt,O=t.deleteProps,I=t.elementFromString,B=t.escapeForRegEx,w=t.extensions,v=t.findChildren,M=t.findChildrenInRange,L=t.findDuplicates,F=t.findParentNode,D=t.findParentNodeClosestToPos,j=t.fromString,K=t.generateHTML,H=t.generateJSON,q=t.generateText,G=t.getAttributes,z=t.getAttributesFromExtensions,J=t.getChangedRanges,U=t.getDebugJSON,V=t.getExtensionField,Y=t.getHTMLFromFragment,Q=t.getMarkAttributes,W=t.getMarkRange,X=t.getMarkType,Z=t.getMarksBetween,$=t.getNodeAtPosition,tt=t.getNodeAttributes,et=t.getNodeType,nt=t.getRenderedAttributes,ot=t.getSchema,it=t.getSchemaByResolvedExtensions,rt=t.getSchemaTypeByName,st=t.getSchemaTypeNameByName,lt=t.getSplittedAttributes,at=t.getText,dt=t.getTextBetween,pt=t.getTextContentFromNodes,ct=t.getTextSerializersFromSchema,ut=t.injectExtensionAttributesToParseRule,gt=t.inputRulesPlugin,_t=t.isActive,mt=t.isAtEndOfNode,xt=t.isAtStartOfNode,kt=t.isEmptyObject,bt=t.isExtensionRulesEnabled,yt=t.isFunction,ht=t.isList,Et=t.isMacOS,ft=t.isMarkActive,Rt=t.isNodeActive,Pt=t.isNodeEmpty,Tt=t.isNodeSelection,At=t.isNumber,Ct=t.isPlainObject,St=t.isRegExp,Nt=t.isSafari,Ot=t.isString,It=t.isTextSelection,Bt=t.isiOS,wt=t.markInputRule,vt=t.markPasteRule,s=t.mergeAttributes,Mt=t.mergeDeep,Lt=t.minMax,Ft=t.nodeInputRule,Dt=t.nodePasteRule,jt=t.objectIncludes,Kt=t.pasteRulesPlugin,Ht=t.posToDOMRect,qt=t.removeDuplicates,Gt=t.resolveFocusPosition,zt=t.rewriteUnknownContent,Jt=t.selectionToInsertionEnd,Ut=t.splitExtensions,Vt=t.textInputRule,Yt=t.textPasteRule,Qt=t.textblockTypeInputRule,Wt=t.wrappingInputRule;var l=r.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:e}){return["li",s(this.options.HTMLAttributes,e),0]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}});var a="__LEPTOS_TIPTAP_BRIDGE__";function c(){let e=globalThis,n=e[a];if(n!=null)return n;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[a]=i,i}function d(){return c()}function p(e){d().registerExtension(e)}var u={name:"list_item",create:()=>l,commands:{split_list_item:(e,n)=>n.kind==="split_list_item"?e.chain().focus().splitListItem(e.isActive("taskList")?"taskItem":"listItem",n.attributes??{}).run():!1,sink_list_item:e=>e.chain().focus().sinkListItem(e.isActive("taskList")?"taskItem":"listItem").run(),lift_list_item:e=>e.chain().focus().liftListItem(e.isActive("taskList")?"taskItem":"listItem").run()}};function re(){p(u)}export{re as register_list_item}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_ordered_list.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_ordered_list.js new file mode 100644 index 00000000..7eeda273 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_ordered_list.js @@ -0,0 +1 @@ +var i=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(i==null||i.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=i.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var k=t.CommandManager,b=t.Editor,y=t.Extension,h=t.InputRule,f=t.Mark,a=t.Node,E=t.NodePos,R=t.NodeView,A=t.PasteRule,T=t.Tracker,P=t.callOrReturn,C=t.canInsertNode,S=t.combineTransactionSteps,N=t.createChainableState,O=t.createDocument,B=t.createNodeFromContent,M=t.createStyleTag,w=t.defaultBlockAt,I=t.deleteProps,v=t.elementFromString,F=t.escapeForRegEx,L=t.extensions,D=t.findChildren,j=t.findChildrenInRange,H=t.findDuplicates,K=t.findParentNode,q=t.findParentNodeClosestToPos,G=t.fromString,z=t.generateHTML,J=t.generateJSON,U=t.generateText,V=t.getAttributes,Y=t.getAttributesFromExtensions,$=t.getChangedRanges,W=t.getDebugJSON,Q=t.getExtensionField,X=t.getHTMLFromFragment,Z=t.getMarkAttributes,tt=t.getMarkRange,et=t.getMarkType,nt=t.getMarksBetween,ot=t.getNodeAtPosition,it=t.getNodeAttributes,rt=t.getNodeType,st=t.getRenderedAttributes,at=t.getSchema,lt=t.getSchemaByResolvedExtensions,dt=t.getSchemaTypeByName,pt=t.getSchemaTypeNameByName,ut=t.getSplittedAttributes,ct=t.getText,gt=t.getTextBetween,_t=t.getTextContentFromNodes,xt=t.getTextSerializersFromSchema,mt=t.injectExtensionAttributesToParseRule,kt=t.inputRulesPlugin,bt=t.isActive,yt=t.isAtEndOfNode,ht=t.isAtStartOfNode,ft=t.isEmptyObject,Et=t.isExtensionRulesEnabled,Rt=t.isFunction,At=t.isList,Tt=t.isMacOS,Pt=t.isMarkActive,Ct=t.isNodeActive,St=t.isNodeEmpty,Nt=t.isNodeSelection,Ot=t.isNumber,Bt=t.isPlainObject,Mt=t.isRegExp,wt=t.isSafari,It=t.isString,vt=t.isTextSelection,Ft=t.isiOS,Lt=t.markInputRule,Dt=t.markPasteRule,r=t.mergeAttributes,jt=t.mergeDeep,Ht=t.minMax,Kt=t.nodeInputRule,qt=t.nodePasteRule,Gt=t.objectIncludes,zt=t.pasteRulesPlugin,Jt=t.posToDOMRect,Ut=t.removeDuplicates,Vt=t.resolveFocusPosition,Yt=t.rewriteUnknownContent,$t=t.selectionToInsertionEnd,Wt=t.splitExtensions,Qt=t.textInputRule,Xt=t.textPasteRule,Zt=t.textblockTypeInputRule,s=t.wrappingInputRule;var _="listItem",l="textStyle",d=/^(\d+)\.\s$/,p=a.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:e=>e.hasAttribute("start")?parseInt(e.getAttribute("start")||"",10):1},type:{default:null,parseHTML:e=>e.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:e}){let{start:n,...o}=e;return n===1?["ol",r(this.options.HTMLAttributes,o),0]:["ol",r(this.options.HTMLAttributes,e),0]},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:n})=>this.options.keepAttributes?n().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(_,this.editor.getAttributes(l)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let e=s({find:d,type:this.type,getAttributes:n=>({start:+n[1]}),joinPredicate:(n,o)=>o.childCount+o.attrs.start===+n[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(e=s({find:d,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:n=>({start:+n[1],...this.editor.getAttributes(l)}),joinPredicate:(n,o)=>o.childCount+o.attrs.start===+n[1],editor:this.editor})),[e]}});var u="__LEPTOS_TIPTAP_BRIDGE__";function x(){let e=globalThis,n=e[u];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[u]=o,o}function c(){return x()}function g(e){c().registerExtension(e)}var m={name:"ordered_list",create:()=>p,commands:{toggle_ordered_list:e=>e.chain().focus().toggleOrderedList().run()},selection_keys:["ordered_list"],selection_state:e=>({ordered_list:e.isActive("orderedList")})};function le(){g(m)}export{le as register_ordered_list}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_paragraph.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_paragraph.js new file mode 100644 index 00000000..797f27d1 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_paragraph.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var g=t.CommandManager,_=t.Editor,x=t.Extension,m=t.InputRule,k=t.Mark,i=t.Node,b=t.NodePos,y=t.NodeView,h=t.PasteRule,E=t.Tracker,P=t.callOrReturn,R=t.canInsertNode,f=t.combineTransactionSteps,C=t.createChainableState,T=t.createDocument,A=t.createNodeFromContent,S=t.createStyleTag,N=t.defaultBlockAt,O=t.deleteProps,B=t.elementFromString,w=t.escapeForRegEx,v=t.extensions,M=t.findChildren,I=t.findChildrenInRange,F=t.findDuplicates,D=t.findParentNode,j=t.findParentNodeClosestToPos,L=t.fromString,K=t.generateHTML,H=t.generateJSON,q=t.generateText,G=t.getAttributes,z=t.getAttributesFromExtensions,J=t.getChangedRanges,U=t.getDebugJSON,V=t.getExtensionField,Y=t.getHTMLFromFragment,Q=t.getMarkAttributes,W=t.getMarkRange,X=t.getMarkType,Z=t.getMarksBetween,$=t.getNodeAtPosition,tt=t.getNodeAttributes,et=t.getNodeType,nt=t.getRenderedAttributes,ot=t.getSchema,rt=t.getSchemaByResolvedExtensions,it=t.getSchemaTypeByName,st=t.getSchemaTypeNameByName,at=t.getSplittedAttributes,lt=t.getText,pt=t.getTextBetween,dt=t.getTextContentFromNodes,ct=t.getTextSerializersFromSchema,ut=t.injectExtensionAttributesToParseRule,gt=t.inputRulesPlugin,_t=t.isActive,xt=t.isAtEndOfNode,mt=t.isAtStartOfNode,kt=t.isEmptyObject,bt=t.isExtensionRulesEnabled,yt=t.isFunction,ht=t.isList,Et=t.isMacOS,Pt=t.isMarkActive,Rt=t.isNodeActive,ft=t.isNodeEmpty,Ct=t.isNodeSelection,Tt=t.isNumber,At=t.isPlainObject,St=t.isRegExp,Nt=t.isSafari,Ot=t.isString,Bt=t.isTextSelection,wt=t.isiOS,vt=t.markInputRule,Mt=t.markPasteRule,s=t.mergeAttributes,It=t.mergeDeep,Ft=t.minMax,Dt=t.nodeInputRule,jt=t.nodePasteRule,Lt=t.objectIncludes,Kt=t.pasteRulesPlugin,Ht=t.posToDOMRect,qt=t.removeDuplicates,Gt=t.resolveFocusPosition,zt=t.rewriteUnknownContent,Jt=t.selectionToInsertionEnd,Ut=t.splitExtensions,Vt=t.textInputRule,Yt=t.textPasteRule,Qt=t.textblockTypeInputRule,Wt=t.wrappingInputRule;var a=i.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:e}){return["p",s(this.options.HTMLAttributes,e),0]},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}});var l="__LEPTOS_TIPTAP_BRIDGE__";function c(){let e=globalThis,o=e[l];if(o!=null)return o;let r={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[l]=r,r}function p(){return c()}function d(e){p().registerExtension(e)}var u={name:"paragraph",create:()=>a,commands:{set_paragraph:e=>e.chain().focus().setParagraph().run()},selection_keys:["paragraph"],selection_state:e=>({paragraph:e.isActive("paragraph")})};function ie(){d(u)}export{ie as register_paragraph}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_placeholder.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_placeholder.js new file mode 100644 index 00000000..39836f9e --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_placeholder.js @@ -0,0 +1 @@ +var a=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(a==null||a.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=a.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var O=t.CommandManager,N=t.Editor,m=t.Extension,B=t.InputRule,v=t.Mark,D=t.Node,I=t.NodePos,F=t.NodeView,M=t.PasteRule,j=t.Tracker,L=t.callOrReturn,K=t.canInsertNode,G=t.combineTransactionSteps,q=t.createChainableState,H=t.createDocument,z=t.createNodeFromContent,J=t.createStyleTag,V=t.defaultBlockAt,W=t.deleteProps,U=t.elementFromString,Y=t.escapeForRegEx,Q=t.extensions,X=t.findChildren,Z=t.findChildrenInRange,$=t.findDuplicates,tt=t.findParentNode,et=t.findParentNodeClosestToPos,nt=t.fromString,ot=t.generateHTML,it=t.generateJSON,rt=t.generateText,st=t.getAttributes,lt=t.getAttributesFromExtensions,at=t.getChangedRanges,pt=t.getDebugJSON,dt=t.getExtensionField,ct=t.getHTMLFromFragment,ut=t.getMarkAttributes,gt=t.getMarkRange,_t=t.getMarkType,xt=t.getMarksBetween,mt=t.getNodeAtPosition,kt=t.getNodeAttributes,bt=t.getNodeType,yt=t.getRenderedAttributes,ht=t.getSchema,Et=t.getSchemaByResolvedExtensions,Pt=t.getSchemaTypeByName,ft=t.getSchemaTypeNameByName,St=t.getSplittedAttributes,Rt=t.getText,Ct=t.getTextBetween,Tt=t.getTextContentFromNodes,At=t.getTextSerializersFromSchema,wt=t.injectExtensionAttributesToParseRule,Ot=t.inputRulesPlugin,Nt=t.isActive,Bt=t.isAtEndOfNode,vt=t.isAtStartOfNode,Dt=t.isEmptyObject,It=t.isExtensionRulesEnabled,Ft=t.isFunction,Mt=t.isList,jt=t.isMacOS,Lt=t.isMarkActive,Kt=t.isNodeActive,k=t.isNodeEmpty,Gt=t.isNodeSelection,qt=t.isNumber,Ht=t.isPlainObject,zt=t.isRegExp,Jt=t.isSafari,Vt=t.isString,Wt=t.isTextSelection,Ut=t.isiOS,Yt=t.markInputRule,Qt=t.markPasteRule,Xt=t.mergeAttributes,Zt=t.mergeDeep,$t=t.minMax,te=t.nodeInputRule,ee=t.nodePasteRule,ne=t.objectIncludes,oe=t.pasteRulesPlugin,ie=t.posToDOMRect,re=t.removeDuplicates,se=t.resolveFocusPosition,le=t.rewriteUnknownContent,ae=t.selectionToInsertionEnd,pe=t.splitExtensions,de=t.textInputRule,ce=t.textPasteRule,ue=t.textblockTypeInputRule,ge=t.wrappingInputRule;var p=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(p==null||p.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var n=p.modules["@tiptap/pm/state"];if(n==null)throw new Error('leptos-tiptap bridge module "@tiptap/pm/state" is unavailable');var xe=n.AllSelection,me=n.EditorState,ke=n.NodeSelection,b=n.Plugin,y=n.PluginKey,be=n.Selection,ye=n.SelectionRange,he=n.TextSelection,Ee=n.Transaction;var d=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(d==null||d.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var o=d.modules["@tiptap/pm/view"];if(o==null)throw new Error('leptos-tiptap bridge module "@tiptap/pm/view" is unavailable');var h=o.Decoration,E=o.DecorationSet,fe=o.EditorView,Se=o.__endComposition,Re=o.__parseFromClipboard;var c=m.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",placeholder:"Write something \u2026",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[new b({key:new y("placeholder"),props:{decorations:({doc:e,selection:s})=>{let l=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:u}=s,g=[];if(!l)return null;let R=this.editor.isEmpty;return e.descendants((i,r)=>{let _=u>=r&&u<=r+i.nodeSize,C=!i.isLeaf&&k(i);if((_||!this.options.showOnlyCurrent)&&C){let x=[this.options.emptyNodeClass];R&&x.push(this.options.emptyEditorClass);let T=h.node(r,r+i.nodeSize,{class:x.join(" "),"data-placeholder":typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:i,pos:r,hasAnchor:_}):this.options.placeholder});g.push(T)}return this.options.includeChildren}),E.create(e,g)}}})]}});var P="__LEPTOS_TIPTAP_BRIDGE__";function A(){let e=globalThis,s=e[P];if(s!=null)return s;let l={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[P]=l,l}function f(){return A()}function S(e){f().registerExtension(e)}var w={name:"placeholder",create:({placeholder:e})=>e==null?c:c.configure({placeholder:e})};function Fe(){S(w)}export{Fe as register_placeholder}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_strike.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_strike.js new file mode 100644 index 00000000..259157d5 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_strike.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var k=t.CommandManager,b=t.Editor,y=t.Extension,h=t.InputRule,r=t.Mark,R=t.Node,E=t.NodePos,f=t.NodeView,S=t.PasteRule,P=t.Tracker,C=t.callOrReturn,T=t.canInsertNode,A=t.combineTransactionSteps,N=t.createChainableState,O=t.createDocument,B=t.createNodeFromContent,w=t.createStyleTag,M=t.defaultBlockAt,v=t.deleteProps,I=t.elementFromString,F=t.escapeForRegEx,D=t.extensions,j=t.findChildren,L=t.findChildrenInRange,K=t.findDuplicates,H=t.findParentNode,q=t.findParentNodeClosestToPos,G=t.fromString,z=t.generateHTML,J=t.generateJSON,U=t.generateText,V=t.getAttributes,Y=t.getAttributesFromExtensions,$=t.getChangedRanges,Q=t.getDebugJSON,W=t.getExtensionField,X=t.getHTMLFromFragment,Z=t.getMarkAttributes,tt=t.getMarkRange,et=t.getMarkType,nt=t.getMarksBetween,ot=t.getNodeAtPosition,it=t.getNodeAttributes,rt=t.getNodeType,st=t.getRenderedAttributes,at=t.getSchema,lt=t.getSchemaByResolvedExtensions,dt=t.getSchemaTypeByName,pt=t.getSchemaTypeNameByName,ct=t.getSplittedAttributes,ut=t.getText,gt=t.getTextBetween,_t=t.getTextContentFromNodes,xt=t.getTextSerializersFromSchema,mt=t.injectExtensionAttributesToParseRule,kt=t.inputRulesPlugin,bt=t.isActive,yt=t.isAtEndOfNode,ht=t.isAtStartOfNode,Rt=t.isEmptyObject,Et=t.isExtensionRulesEnabled,ft=t.isFunction,St=t.isList,Pt=t.isMacOS,Ct=t.isMarkActive,Tt=t.isNodeActive,At=t.isNodeEmpty,Nt=t.isNodeSelection,Ot=t.isNumber,Bt=t.isPlainObject,wt=t.isRegExp,Mt=t.isSafari,vt=t.isString,It=t.isTextSelection,Ft=t.isiOS,s=t.markInputRule,a=t.markPasteRule,l=t.mergeAttributes,Dt=t.mergeDeep,jt=t.minMax,Lt=t.nodeInputRule,Kt=t.nodePasteRule,Ht=t.objectIncludes,qt=t.pasteRulesPlugin,Gt=t.posToDOMRect,zt=t.removeDuplicates,Jt=t.resolveFocusPosition,Ut=t.rewriteUnknownContent,Vt=t.selectionToInsertionEnd,Yt=t.splitExtensions,$t=t.textInputRule,Qt=t.textPasteRule,Wt=t.textblockTypeInputRule,Xt=t.wrappingInputRule;var g=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,_=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,d=r.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:e=>e.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:e}){return["s",l(this.options.HTMLAttributes,e),0]},addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[s({find:g,type:this.type})]},addPasteRules(){return[a({find:_,type:this.type})]}});var p="__LEPTOS_TIPTAP_BRIDGE__";function x(){let e=globalThis,o=e[p];if(o!=null)return o;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[p]=i,i}function c(){return x()}function u(e){c().registerExtension(e)}var m={name:"strike",create:()=>d,commands:{set_strike:e=>e.chain().focus().setStrike().run(),toggle_strike:e=>e.chain().focus().toggleStrike().run(),unset_strike:e=>e.chain().focus().unsetStrike().run()},selection_keys:["strike"],selection_state:e=>({strike:e.isActive("strike")})};function ae(){u(m)}export{ae as register_strike}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_item.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_item.js new file mode 100644 index 00000000..eaff37dc --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_item.js @@ -0,0 +1 @@ +var u=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(u==null||u.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=u.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var P=t.CommandManager,S=t.Editor,O=t.Extension,N=t.InputRule,v=t.Mark,x=t.Node,w=t.NodePos,B=t.NodeView,I=t.PasteRule,M=t.Tracker,D=t.callOrReturn,F=t.canInsertNode,L=t.combineTransactionSteps,j=t.createChainableState,H=t.createDocument,K=t.createNodeFromContent,q=t.createStyleTag,G=t.defaultBlockAt,z=t.deleteProps,J=t.elementFromString,V=t.escapeForRegEx,Y=t.extensions,$=t.findChildren,U=t.findChildrenInRange,W=t.findDuplicates,Q=t.findParentNode,X=t.findParentNodeClosestToPos,Z=t.fromString,tt=t.generateHTML,et=t.generateJSON,nt=t.generateText,ot=t.getAttributes,it=t.getAttributesFromExtensions,rt=t.getChangedRanges,st=t.getDebugJSON,at=t.getExtensionField,lt=t.getHTMLFromFragment,dt=t.getMarkAttributes,ct=t.getMarkRange,pt=t.getMarkType,ut=t.getMarksBetween,gt=t.getNodeAtPosition,mt=t.getNodeAttributes,_t=t.getNodeType,xt=t.getRenderedAttributes,kt=t.getSchema,bt=t.getSchemaByResolvedExtensions,yt=t.getSchemaTypeByName,ht=t.getSchemaTypeNameByName,ft=t.getSplittedAttributes,Et=t.getText,Rt=t.getTextBetween,Tt=t.getTextContentFromNodes,At=t.getTextSerializersFromSchema,Ct=t.injectExtensionAttributesToParseRule,Pt=t.inputRulesPlugin,St=t.isActive,Ot=t.isAtEndOfNode,Nt=t.isAtStartOfNode,vt=t.isEmptyObject,wt=t.isExtensionRulesEnabled,Bt=t.isFunction,It=t.isList,Mt=t.isMacOS,Dt=t.isMarkActive,Ft=t.isNodeActive,Lt=t.isNodeEmpty,jt=t.isNodeSelection,Ht=t.isNumber,Kt=t.isPlainObject,qt=t.isRegExp,Gt=t.isSafari,zt=t.isString,Jt=t.isTextSelection,Vt=t.isiOS,Yt=t.markInputRule,$t=t.markPasteRule,k=t.mergeAttributes,Ut=t.mergeDeep,Wt=t.minMax,Qt=t.nodeInputRule,Xt=t.nodePasteRule,Zt=t.objectIncludes,te=t.pasteRulesPlugin,ee=t.posToDOMRect,ne=t.removeDuplicates,oe=t.resolveFocusPosition,ie=t.rewriteUnknownContent,re=t.selectionToInsertionEnd,se=t.splitExtensions,ae=t.textInputRule,le=t.textPasteRule,de=t.textblockTypeInputRule,b=t.wrappingInputRule;var T=/^\s*(\[([( |x])?\])\s$/,y=x.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{let r=e.getAttribute("data-checked");return r===""||r==="true"},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:e,HTMLAttributes:r}){return["li",k(this.options.HTMLAttributes,r,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:e.attrs.checked?"checked":null}],["span"]],["div",0]]},addKeyboardShortcuts(){let e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:r,getPos:a,editor:l})=>{let s=document.createElement("li"),d=document.createElement("label"),R=document.createElement("span"),o=document.createElement("input"),g=document.createElement("div"),m=()=>{var n,i;o.ariaLabel=((i=(n=this.options.a11y)===null||n===void 0?void 0:n.checkboxLabel)===null||i===void 0?void 0:i.call(n,e,o.checked))||`Task item checkbox for ${e.textContent||"empty task item"}`};return m(),d.contentEditable="false",o.type="checkbox",o.addEventListener("mousedown",n=>n.preventDefault()),o.addEventListener("change",n=>{if(!l.isEditable&&!this.options.onReadOnlyChecked){o.checked=!o.checked;return}let{checked:i}=n.target;l.isEditable&&typeof a=="function"&&l.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:_})=>{let c=a();if(typeof c!="number")return!1;let p=_.doc.nodeAt(c);return _.setNodeMarkup(c,void 0,{...p?.attrs,checked:i}),!0}).run(),!l.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,i)||(o.checked=!o.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([n,i])=>{s.setAttribute(n,i)}),s.dataset.checked=e.attrs.checked,o.checked=e.attrs.checked,d.append(o,R),s.append(d,g),Object.entries(r).forEach(([n,i])=>{s.setAttribute(n,i)}),{dom:s,contentDOM:g,update:n=>n.type!==this.type?!1:(s.dataset.checked=n.attrs.checked,o.checked=n.attrs.checked,m(),!0)}}},addInputRules(){return[b({find:T,type:this.type,getAttributes:e=>({checked:e[e.length-1]==="x"})})]}});var h="__LEPTOS_TIPTAP_BRIDGE__";function A(){let e=globalThis,r=e[h];if(r!=null)return r;let a={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[h]=a,a}function f(){return A()}function E(e){f().registerExtension(e)}var C={name:"task_item",create:()=>y.configure({nested:!0})};function be(){E(C)}export{be as register_task_item}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_list.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_list.js new file mode 100644 index 00000000..c5af0900 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_task_list.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var g=t.CommandManager,_=t.Editor,x=t.Extension,m=t.InputRule,k=t.Mark,r=t.Node,b=t.NodePos,y=t.NodeView,h=t.PasteRule,E=t.Tracker,R=t.callOrReturn,T=t.canInsertNode,f=t.combineTransactionSteps,P=t.createChainableState,C=t.createDocument,A=t.createNodeFromContent,S=t.createStyleTag,N=t.defaultBlockAt,O=t.deleteProps,B=t.elementFromString,w=t.escapeForRegEx,v=t.extensions,M=t.findChildren,I=t.findChildrenInRange,F=t.findDuplicates,D=t.findParentNode,L=t.findParentNodeClosestToPos,j=t.fromString,K=t.generateHTML,H=t.generateJSON,q=t.generateText,G=t.getAttributes,z=t.getAttributesFromExtensions,J=t.getChangedRanges,U=t.getDebugJSON,V=t.getExtensionField,Y=t.getHTMLFromFragment,$=t.getMarkAttributes,Q=t.getMarkRange,W=t.getMarkType,X=t.getMarksBetween,Z=t.getNodeAtPosition,tt=t.getNodeAttributes,et=t.getNodeType,nt=t.getRenderedAttributes,ot=t.getSchema,it=t.getSchemaByResolvedExtensions,rt=t.getSchemaTypeByName,st=t.getSchemaTypeNameByName,at=t.getSplittedAttributes,lt=t.getText,dt=t.getTextBetween,pt=t.getTextContentFromNodes,ct=t.getTextSerializersFromSchema,ut=t.injectExtensionAttributesToParseRule,gt=t.inputRulesPlugin,_t=t.isActive,xt=t.isAtEndOfNode,mt=t.isAtStartOfNode,kt=t.isEmptyObject,bt=t.isExtensionRulesEnabled,yt=t.isFunction,ht=t.isList,Et=t.isMacOS,Rt=t.isMarkActive,Tt=t.isNodeActive,ft=t.isNodeEmpty,Pt=t.isNodeSelection,Ct=t.isNumber,At=t.isPlainObject,St=t.isRegExp,Nt=t.isSafari,Ot=t.isString,Bt=t.isTextSelection,wt=t.isiOS,vt=t.markInputRule,Mt=t.markPasteRule,s=t.mergeAttributes,It=t.mergeDeep,Ft=t.minMax,Dt=t.nodeInputRule,Lt=t.nodePasteRule,jt=t.objectIncludes,Kt=t.pasteRulesPlugin,Ht=t.posToDOMRect,qt=t.removeDuplicates,Gt=t.resolveFocusPosition,zt=t.rewriteUnknownContent,Jt=t.selectionToInsertionEnd,Ut=t.splitExtensions,Vt=t.textInputRule,Yt=t.textPasteRule,$t=t.textblockTypeInputRule,Qt=t.wrappingInputRule;var a=r.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:e}){return["ul",s(this.options.HTMLAttributes,e,{"data-type":this.name}),0]},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});var l="__LEPTOS_TIPTAP_BRIDGE__";function c(){let e=globalThis,o=e[l];if(o!=null)return o;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[l]=i,i}function d(){return c()}function p(e){d().registerExtension(e)}var u={name:"task_list",create:()=>a,commands:{toggle_task_list:e=>e.chain().focus().toggleTaskList().run()},selection_keys:["task_list"],selection_state:e=>({task_list:e.isActive("taskList")})};function re(){p(u)}export{re as register_task_list}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text.js new file mode 100644 index 00000000..5e0de069 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=n.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var u=t.CommandManager,g=t.Editor,_=t.Extension,x=t.InputRule,m=t.Mark,r=t.Node,k=t.NodePos,b=t.NodeView,y=t.PasteRule,E=t.Tracker,R=t.callOrReturn,h=t.canInsertNode,f=t.combineTransactionSteps,P=t.createChainableState,C=t.createDocument,T=t.createNodeFromContent,S=t.createStyleTag,A=t.defaultBlockAt,N=t.deleteProps,O=t.elementFromString,B=t.escapeForRegEx,w=t.extensions,v=t.findChildren,I=t.findChildrenInRange,M=t.findDuplicates,F=t.findParentNode,D=t.findParentNodeClosestToPos,j=t.fromString,L=t.generateHTML,K=t.generateJSON,q=t.generateText,G=t.getAttributes,H=t.getAttributesFromExtensions,z=t.getChangedRanges,J=t.getDebugJSON,U=t.getExtensionField,V=t.getHTMLFromFragment,Y=t.getMarkAttributes,Q=t.getMarkRange,W=t.getMarkType,X=t.getMarksBetween,Z=t.getNodeAtPosition,$=t.getNodeAttributes,tt=t.getNodeType,et=t.getRenderedAttributes,nt=t.getSchema,ot=t.getSchemaByResolvedExtensions,it=t.getSchemaTypeByName,rt=t.getSchemaTypeNameByName,st=t.getSplittedAttributes,lt=t.getText,at=t.getTextBetween,dt=t.getTextContentFromNodes,pt=t.getTextSerializersFromSchema,ct=t.injectExtensionAttributesToParseRule,ut=t.inputRulesPlugin,gt=t.isActive,_t=t.isAtEndOfNode,xt=t.isAtStartOfNode,mt=t.isEmptyObject,kt=t.isExtensionRulesEnabled,bt=t.isFunction,yt=t.isList,Et=t.isMacOS,Rt=t.isMarkActive,ht=t.isNodeActive,ft=t.isNodeEmpty,Pt=t.isNodeSelection,Ct=t.isNumber,Tt=t.isPlainObject,St=t.isRegExp,At=t.isSafari,Nt=t.isString,Ot=t.isTextSelection,Bt=t.isiOS,wt=t.markInputRule,vt=t.markPasteRule,It=t.mergeAttributes,Mt=t.mergeDeep,Ft=t.minMax,Dt=t.nodeInputRule,jt=t.nodePasteRule,Lt=t.objectIncludes,Kt=t.pasteRulesPlugin,qt=t.posToDOMRect,Gt=t.removeDuplicates,Ht=t.resolveFocusPosition,zt=t.rewriteUnknownContent,Jt=t.selectionToInsertionEnd,Ut=t.splitExtensions,Vt=t.textInputRule,Yt=t.textPasteRule,Qt=t.textblockTypeInputRule,Wt=t.wrappingInputRule;var s=r.create({name:"text",group:"inline"});var l="__LEPTOS_TIPTAP_BRIDGE__";function p(){let e=globalThis,o=e[l];if(o!=null)return o;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[l]=i,i}function a(){return p()}function d(e){a().registerExtension(e)}var c={name:"text",create:()=>s};function re(){d(c)}export{re as register_text}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_align.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_align.js new file mode 100644 index 00000000..e77db881 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_align.js @@ -0,0 +1 @@ +var i=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(i==null||i.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=i.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var u=t.CommandManager,x=t.Editor,r=t.Extension,_=t.InputRule,m=t.Mark,k=t.Node,b=t.NodePos,y=t.NodeView,f=t.PasteRule,h=t.Tracker,A=t.callOrReturn,E=t.canInsertNode,T=t.combineTransactionSteps,R=t.createChainableState,P=t.createDocument,S=t.createNodeFromContent,C=t.createStyleTag,N=t.defaultBlockAt,O=t.deleteProps,B=t.elementFromString,w=t.escapeForRegEx,v=t.extensions,M=t.findChildren,I=t.findChildrenInRange,j=t.findDuplicates,F=t.findParentNode,D=t.findParentNodeClosestToPos,L=t.fromString,K=t.generateHTML,G=t.generateJSON,H=t.generateText,q=t.getAttributes,z=t.getAttributesFromExtensions,J=t.getChangedRanges,U=t.getDebugJSON,V=t.getExtensionField,Y=t.getHTMLFromFragment,$=t.getMarkAttributes,Q=t.getMarkRange,W=t.getMarkType,X=t.getMarksBetween,Z=t.getNodeAtPosition,tt=t.getNodeAttributes,et=t.getNodeType,nt=t.getRenderedAttributes,ot=t.getSchema,it=t.getSchemaByResolvedExtensions,rt=t.getSchemaTypeByName,st=t.getSchemaTypeNameByName,lt=t.getSplittedAttributes,at=t.getText,dt=t.getTextBetween,pt=t.getTextContentFromNodes,gt=t.getTextSerializersFromSchema,ct=t.injectExtensionAttributesToParseRule,ut=t.inputRulesPlugin,xt=t.isActive,_t=t.isAtEndOfNode,mt=t.isAtStartOfNode,kt=t.isEmptyObject,bt=t.isExtensionRulesEnabled,yt=t.isFunction,ft=t.isList,ht=t.isMacOS,At=t.isMarkActive,Et=t.isNodeActive,Tt=t.isNodeEmpty,Rt=t.isNodeSelection,Pt=t.isNumber,St=t.isPlainObject,Ct=t.isRegExp,Nt=t.isSafari,Ot=t.isString,Bt=t.isTextSelection,wt=t.isiOS,vt=t.markInputRule,Mt=t.markPasteRule,It=t.mergeAttributes,jt=t.mergeDeep,Ft=t.minMax,Dt=t.nodeInputRule,Lt=t.nodePasteRule,Kt=t.objectIncludes,Gt=t.pasteRulesPlugin,Ht=t.posToDOMRect,qt=t.removeDuplicates,zt=t.resolveFocusPosition,Jt=t.rewriteUnknownContent,Ut=t.selectionToInsertionEnd,Vt=t.splitExtensions,Yt=t.textInputRule,$t=t.textPasteRule,Qt=t.textblockTypeInputRule,Wt=t.wrappingInputRule;var s=r.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let n=e.style.textAlign;return this.options.alignments.includes(n)?n:this.options.defaultAlignment},renderHTML:e=>e.textAlign?{style:`text-align: ${e.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:e=>({commands:n})=>this.options.alignments.includes(e)?this.options.types.map(o=>n.updateAttributes(o,{textAlign:e})).every(o=>o):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(n=>e.resetAttributes(n,"textAlign")).every(n=>n),toggleTextAlign:e=>({editor:n,commands:o})=>this.options.alignments.includes(e)?n.isActive({textAlign:e})?o.unsetTextAlign():o.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}});var l="__LEPTOS_TIPTAP_BRIDGE__";function g(){let e=globalThis,n=e[l];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[l]=o,o}function a(){return g()}function d(e){a().registerExtension(e)}var p=["left","center","right","justify"],c={name:"text_align",create:()=>s.configure({types:["heading","paragraph"]}),commands:{set_text_align:(e,n)=>n.kind==="set_text_align"&&p.includes(n.alignment)?e.chain().focus().setTextAlign(n.alignment).run():!1,toggle_text_align:(e,n)=>n.kind==="toggle_text_align"&&p.includes(n.alignment)?e.chain().focus().toggleTextAlign(n.alignment).run():!1,unset_text_align:e=>e.chain().focus().unsetTextAlign().run()},selection_keys:["align_left","align_center","align_right","align_justify"],selection_state:e=>({align_left:e.isActive({textAlign:"left"}),align_center:e.isActive({textAlign:"center"}),align_right:e.isActive({textAlign:"right"}),align_justify:e.isActive({textAlign:"justify"})})};function se(){d(c)}export{se as register_text_align}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_style.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_style.js new file mode 100644 index 00000000..33385c68 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_text_style.js @@ -0,0 +1 @@ +var l=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(l==null||l.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=l.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var f=t.CommandManager,h=t.Editor,a=t.Extension,E=t.InputRule,d=t.Mark,S=t.Node,R=t.NodePos,C=t.NodeView,T=t.PasteRule,A=t.Tracker,P=t.callOrReturn,N=t.canInsertNode,O=t.combineTransactionSteps,v=t.createChainableState,B=t.createDocument,w=t.createNodeFromContent,M=t.createStyleTag,I=t.defaultBlockAt,F=t.deleteProps,D=t.elementFromString,j=t.escapeForRegEx,L=t.extensions,H=t.findChildren,K=t.findChildrenInRange,q=t.findDuplicates,G=t.findParentNode,z=t.findParentNodeClosestToPos,J=t.fromString,$=t.generateHTML,U=t.generateJSON,V=t.generateText,Y=t.getAttributes,Q=t.getAttributesFromExtensions,W=t.getChangedRanges,X=t.getDebugJSON,Z=t.getExtensionField,tt=t.getHTMLFromFragment,et=t.getMarkAttributes,nt=t.getMarkRange,ot=t.getMarkType,rt=t.getMarksBetween,it=t.getNodeAtPosition,st=t.getNodeAttributes,lt=t.getNodeType,at=t.getRenderedAttributes,dt=t.getSchema,pt=t.getSchemaByResolvedExtensions,ct=t.getSchemaTypeByName,ut=t.getSchemaTypeNameByName,gt=t.getSplittedAttributes,_t=t.getText,xt=t.getTextBetween,mt=t.getTextContentFromNodes,kt=t.getTextSerializersFromSchema,bt=t.injectExtensionAttributesToParseRule,yt=t.inputRulesPlugin,ft=t.isActive,ht=t.isAtEndOfNode,Et=t.isAtStartOfNode,St=t.isEmptyObject,Rt=t.isExtensionRulesEnabled,Ct=t.isFunction,Tt=t.isList,At=t.isMacOS,Pt=t.isMarkActive,Nt=t.isNodeActive,Ot=t.isNodeEmpty,vt=t.isNodeSelection,Bt=t.isNumber,wt=t.isPlainObject,Mt=t.isRegExp,It=t.isSafari,Ft=t.isString,Dt=t.isTextSelection,jt=t.isiOS,Lt=t.markInputRule,Ht=t.markPasteRule,p=t.mergeAttributes,Kt=t.mergeDeep,qt=t.minMax,Gt=t.nodeInputRule,zt=t.nodePasteRule,Jt=t.objectIncludes,$t=t.pasteRulesPlugin,Ut=t.posToDOMRect,Vt=t.removeDuplicates,Yt=t.resolveFocusPosition,Qt=t.rewriteUnknownContent,Wt=t.selectionToInsertionEnd,Xt=t.splitExtensions,Zt=t.textInputRule,te=t.textPasteRule,ee=t.textblockTypeInputRule,ne=t.wrappingInputRule;var k=e=>{if(!e.children.length)return;let n=e.querySelectorAll("span");n&&n.forEach(o=>{var i,r;let s=o.getAttribute("style"),m=(r=(i=o.parentElement)===null||i===void 0?void 0:i.closest("span"))===null||r===void 0?void 0:r.getAttribute("style");o.setAttribute("style",`${m};${s}`)})},c=d.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:e=>e.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&k(e),{}):!1}]},renderHTML({HTMLAttributes:e}){return["span",p(this.options.HTMLAttributes,e),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:e})=>{let{selection:n}=e;return e.doc.nodesBetween(n.from,n.to,(o,i)=>{if(o.isTextblock)return!0;o.marks.filter(r=>r.type===this.type).some(r=>Object.values(r.attrs).some(s=>!!s))||e.removeMark(i,i+o.nodeSize,this.type)}),!0}}}});var u=a.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:e=>{var n;return(n=e.style.color)===null||n===void 0?void 0:n.replace(/['"]+/g,"")},renderHTML:e=>e.color?{style:`color: ${e.color}`}:{}}}}]},addCommands(){return{setColor:e=>({chain:n})=>n().setMark("textStyle",{color:e}).run(),unsetColor:()=>({chain:e})=>e().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}});var g="__LEPTOS_TIPTAP_BRIDGE__";function b(){let e=globalThis,n=e[g];if(n!=null)return n;let o={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[g]=o,o}function _(){return b()}function x(e){_().registerExtension(e)}var y={name:"text_style",create:()=>[c,u],commands:{set_color:(e,n)=>n.kind==="set_color"?e.chain().focus().setColor(n.attributes.color).run():!1,unset_color:e=>e.chain().focus().unsetColor().run()},selection_keys:["text_style"],selection_state:e=>({text_style:e.isActive("textStyle")})};function xe(){x(y)}export{xe as register_text_style}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_underline.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_underline.js new file mode 100644 index 00000000..4b6c1e5f --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_underline.js @@ -0,0 +1 @@ +var n=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(n==null||n.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var e=n.modules["@tiptap/core"];if(e==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var g=e.CommandManager,_=e.Editor,x=e.Extension,m=e.InputRule,r=e.Mark,k=e.Node,b=e.NodePos,y=e.NodeView,E=e.PasteRule,h=e.Tracker,R=e.callOrReturn,f=e.canInsertNode,P=e.combineTransactionSteps,C=e.createChainableState,T=e.createDocument,A=e.createNodeFromContent,S=e.createStyleTag,N=e.defaultBlockAt,O=e.deleteProps,B=e.elementFromString,w=e.escapeForRegEx,M=e.extensions,v=e.findChildren,I=e.findChildrenInRange,F=e.findDuplicates,D=e.findParentNode,j=e.findParentNodeClosestToPos,L=e.fromString,K=e.generateHTML,H=e.generateJSON,U=e.generateText,q=e.getAttributes,G=e.getAttributesFromExtensions,z=e.getChangedRanges,J=e.getDebugJSON,V=e.getExtensionField,Y=e.getHTMLFromFragment,Q=e.getMarkAttributes,W=e.getMarkRange,X=e.getMarkType,Z=e.getMarksBetween,$=e.getNodeAtPosition,ee=e.getNodeAttributes,te=e.getNodeType,ne=e.getRenderedAttributes,oe=e.getSchema,ie=e.getSchemaByResolvedExtensions,re=e.getSchemaTypeByName,se=e.getSchemaTypeNameByName,le=e.getSplittedAttributes,ae=e.getText,de=e.getTextBetween,pe=e.getTextContentFromNodes,ce=e.getTextSerializersFromSchema,ue=e.injectExtensionAttributesToParseRule,ge=e.inputRulesPlugin,_e=e.isActive,xe=e.isAtEndOfNode,me=e.isAtStartOfNode,ke=e.isEmptyObject,be=e.isExtensionRulesEnabled,ye=e.isFunction,Ee=e.isList,he=e.isMacOS,Re=e.isMarkActive,fe=e.isNodeActive,Pe=e.isNodeEmpty,Ce=e.isNodeSelection,Te=e.isNumber,Ae=e.isPlainObject,Se=e.isRegExp,Ne=e.isSafari,Oe=e.isString,Be=e.isTextSelection,we=e.isiOS,Me=e.markInputRule,ve=e.markPasteRule,s=e.mergeAttributes,Ie=e.mergeDeep,Fe=e.minMax,De=e.nodeInputRule,je=e.nodePasteRule,Le=e.objectIncludes,Ke=e.pasteRulesPlugin,He=e.posToDOMRect,Ue=e.removeDuplicates,qe=e.resolveFocusPosition,Ge=e.rewriteUnknownContent,ze=e.selectionToInsertionEnd,Je=e.splitExtensions,Ve=e.textInputRule,Ye=e.textPasteRule,Qe=e.textblockTypeInputRule,We=e.wrappingInputRule;var l=r.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["u",s(this.options.HTMLAttributes,t),0]},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});var a="__LEPTOS_TIPTAP_BRIDGE__";function c(){let t=globalThis,o=t[a];if(o!=null)return o;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return t[a]=i,i}function d(){return c()}function p(t){d().registerExtension(t)}var u={name:"underline",create:()=>l,selection_keys:["underline"],selection_state:t=>({underline:t.isActive("underline")})};function rt(){p(u)}export{rt as register_underline}; diff --git a/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_youtube.js b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_youtube.js new file mode 100644 index 00000000..56b8ed3a --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/generated/island/snippets/leptos-tiptap-c355e6ec24c3df4c/src/js/generated/tiptap_youtube.js @@ -0,0 +1 @@ +var s=globalThis.__LEPTOS_TIPTAP_BRIDGE__;if(s==null||s.modules==null)throw new Error("leptos-tiptap bridge bindings are unavailable");var t=s.modules["@tiptap/core"];if(t==null)throw new Error('leptos-tiptap bridge module "@tiptap/core" is unavailable');var G=t.CommandManager,H=t.Editor,q=t.Extension,V=t.InputRule,z=t.Mark,x=t.Node,J=t.NodePos,$=t.NodeView,X=t.PasteRule,Q=t.Tracker,W=t.callOrReturn,Z=t.canInsertNode,tt=t.combineTransactionSteps,et=t.createChainableState,nt=t.createDocument,ot=t.createNodeFromContent,it=t.createStyleTag,rt=t.defaultBlockAt,st=t.deleteProps,at=t.elementFromString,lt=t.escapeForRegEx,dt=t.extensions,pt=t.findChildren,ct=t.findChildrenInRange,ut=t.findDuplicates,gt=t.findParentNode,mt=t.findParentNodeClosestToPos,_t=t.fromString,bt=t.generateHTML,xt=t.generateJSON,kt=t.generateText,ht=t.getAttributes,yt=t.getAttributesFromExtensions,ft=t.getChangedRanges,Pt=t.getDebugJSON,Et=t.getExtensionField,Rt=t.getHTMLFromFragment,wt=t.getMarkAttributes,At=t.getMarkRange,Ct=t.getMarkType,Tt=t.getMarksBetween,St=t.getNodeAtPosition,Bt=t.getNodeAttributes,vt=t.getNodeType,Ot=t.getRenderedAttributes,Nt=t.getSchema,Lt=t.getSchemaByResolvedExtensions,Ft=t.getSchemaTypeByName,It=t.getSchemaTypeNameByName,Mt=t.getSplittedAttributes,Dt=t.getText,jt=t.getTextBetween,Kt=t.getTextContentFromNodes,Ut=t.getTextSerializersFromSchema,Yt=t.injectExtensionAttributesToParseRule,Gt=t.inputRulesPlugin,Ht=t.isActive,qt=t.isAtEndOfNode,Vt=t.isAtStartOfNode,zt=t.isEmptyObject,Jt=t.isExtensionRulesEnabled,$t=t.isFunction,Xt=t.isList,Qt=t.isMacOS,Wt=t.isMarkActive,Zt=t.isNodeActive,te=t.isNodeEmpty,ee=t.isNodeSelection,ne=t.isNumber,oe=t.isPlainObject,ie=t.isRegExp,re=t.isSafari,se=t.isString,ae=t.isTextSelection,le=t.isiOS,de=t.markInputRule,pe=t.markPasteRule,k=t.mergeAttributes,ce=t.mergeDeep,ue=t.minMax,ge=t.nodeInputRule,h=t.nodePasteRule,me=t.objectIncludes,_e=t.pasteRulesPlugin,be=t.posToDOMRect,xe=t.removeDuplicates,ke=t.resolveFocusPosition,he=t.rewriteUnknownContent,ye=t.selectionToInsertionEnd,fe=t.splitExtensions,Pe=t.textInputRule,Ee=t.textPasteRule,Re=t.textblockTypeInputRule,we=t.wrappingInputRule;var F=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,I=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/g,y=e=>e.match(F),M=(e,n)=>n?"https://www.youtube-nocookie.com/embed/videoseries?list=":e?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",D=e=>e.searchParams.has("v")?{id:e.searchParams.get("v")}:e.hostname==="youtu.be"||e.pathname.includes("shorts")||e.pathname.includes("live")?{id:e.pathname.split("/").pop()}:e.searchParams.has("list")?{id:e.searchParams.get("list"),isPlaylist:!0}:null,j=e=>{var n;let{url:i,allowFullscreen:w,autoplay:A,ccLanguage:a,ccLoadPolicy:C,controls:T,disableKBcontrols:S,enableIFrameApi:B,endTime:l,interfaceLanguage:d,ivLoadPolicy:p,loop:v,modestBranding:O,nocookie:N,origin:c,playlist:u,progressBarColor:g,startAt:m,rel:_}=e;if(!y(i))return null;if(i.includes("/embed/"))return i;let r=new URL(i),{id:b,isPlaylist:L}=(n=D(r))!==null&&n!==void 0?n:{};if(!b)return null;let o=new URL(`${M(N,L)}${b}`);return r.searchParams.has("t")&&o.searchParams.set("start",r.searchParams.get("t").replaceAll("s","")),w===!1&&o.searchParams.set("fs","0"),A&&o.searchParams.set("autoplay","1"),a&&o.searchParams.set("cc_lang_pref",a),C&&o.searchParams.set("cc_load_policy","1"),T||o.searchParams.set("controls","0"),S&&o.searchParams.set("disablekb","1"),B&&o.searchParams.set("enablejsapi","1"),l&&o.searchParams.set("end",l.toString()),d&&o.searchParams.set("hl",d),p&&o.searchParams.set("iv_load_policy",p.toString()),v&&o.searchParams.set("loop","1"),O&&o.searchParams.set("modestbranding","1"),c&&o.searchParams.set("origin",c),u&&o.searchParams.set("playlist",u),m&&o.searchParams.set("start",m.toString()),g&&o.searchParams.set("color",g),_!==void 0&&o.searchParams.set("rel",_.toString()),o.toString()},f=x.create({name:"youtube",addOptions(){return{addPasteHandler:!0,allowFullscreen:!0,autoplay:!1,ccLanguage:void 0,ccLoadPolicy:void 0,controls:!0,disableKBcontrols:!1,enableIFrameApi:!1,endTime:0,height:480,interfaceLanguage:void 0,ivLoadPolicy:0,loop:!1,modestBranding:!1,HTMLAttributes:{},inline:!1,nocookie:!1,origin:"",playlist:"",progressBarColor:void 0,width:640,rel:1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},start:{default:0},width:{default:this.options.width},height:{default:this.options.height}}},parseHTML(){return[{tag:"div[data-youtube-video] iframe"}]},addCommands(){return{setYoutubeVideo:e=>({commands:n})=>y(e.src)?n.insertContent({type:this.name,attrs:e}):!1}},addPasteRules(){return this.options.addPasteHandler?[h({find:I,type:this.type,getAttributes:e=>({src:e.input})})]:[]},renderHTML({HTMLAttributes:e}){let n=j({url:e.src,allowFullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,controls:this.options.controls,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,nocookie:this.options.nocookie,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,startAt:e.start||0,rel:this.options.rel});return e.src=n,["div",{"data-youtube-video":""},["iframe",k(this.options.HTMLAttributes,{width:this.options.width,height:this.options.height,allowfullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,rel:this.options.rel},e)]]}});var P="__LEPTOS_TIPTAP_BRIDGE__";function K(){let e=globalThis,n=e[P];if(n!=null)return n;let i={modules:{},registerExtension:()=>{throw new Error("leptos-tiptap bridge runtime is not initialized")}};return e[P]=i,i}function E(){return K()}function R(e){E().registerExtension(e)}function U(e){let n={src:e.src};return e.start!=null&&(n.start=e.start),e.width!=null&&(n.width=e.width),e.height!=null&&(n.height=e.height),n}var Y={name:"youtube",create:()=>f,commands:{set_youtube_video:(e,n)=>n.kind==="set_youtube_video"?e.chain().focus().setYoutubeVideo(U(n)).run():!1},selection_keys:["youtube"],selection_state:e=>({youtube:e.isActive("youtube")})};function Le(){R(Y)}export{Le as register_youtube}; diff --git a/rust/spikes/leptos-tiptap-spike/src/lib.rs b/rust/spikes/leptos-tiptap-spike/src/lib.rs new file mode 100644 index 00000000..bab31256 --- /dev/null +++ b/rust/spikes/leptos-tiptap-spike/src/lib.rs @@ -0,0 +1,5450 @@ +use leptos::ev; +use leptos::mount::{mount_to, mount_to_body, UnmountHandle}; +use leptos::prelude::*; +use leptos_dom::helpers::window_event_listener; +use leptos_tiptap::{ + TiptapCodeBlockAttributes, TiptapColorAttributes, TiptapContent, TiptapEditor, + TiptapEditorHandle, TiptapExtension, TiptapHeadingLevel, TiptapHighlightAttributes, + TiptapLinkResource, TiptapMarkName, TiptapRange, TiptapSelectionState, TiptapTextAlign, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::{ + any::Any, + cell::Cell, + collections::HashMap, + fmt::Display, +}; +use wasm_bindgen::{closure::Closure, prelude::*, JsCast, JsValue}; +use web_sys::{ + window, CustomEvent, CustomEventInit, DragEvent, Element, Event, EventTarget, HtmlElement, + MouseEvent, Node, Storage, WheelEvent, +}; + +const EDITOR_STAGE_SELECTOR: &str = "#editor-stage"; +const EDITOR_ROOT_SELECTOR: &str = ".editor-surface .ProseMirror"; +const HANDLE_SHELL_SELECTOR: &str = ".block-handle-shell"; +const SPIKE_STORAGE_KEY: &str = "mnote.leptos-tiptap-spike.document"; +const HANDLE_MULTILINE_HEIGHT: f64 = 40.0; +const HANDLE_GUTTER_WIDTH: f64 = 92.0; +const CONTENT_COLUMN_MAX_WIDTH: f64 = 708.0; +const CONTENT_COLUMN_HORIZONTAL_PADDING: f64 = 48.0; +const HANDLE_STAGE_PADDING_LEFT: f64 = 18.0; +const HANDLE_TRIGGER_WIDTH: f64 = 32.0; +const HANDLE_TRIGGER_GAP: f64 = 6.0; +const HANDLE_MENU_GAP: f64 = 10.0; +const RUNTIME_NAME: &str = "8123-leptos-tiptap-runtime"; +const RUNTIME_VERSION: &str = "1.1.0"; +const PROTOCOL: &str = "mnote.leptos_tiptap.bridge.v1"; +const EVENT_PREFIX: &str = "mnote:leptos-tiptap-spike"; +const READY_EVENT: &str = "mnote:leptos-tiptap-spike:ready"; +const CHANGE_EVENT: &str = "mnote:leptos-tiptap-spike:change"; +const STATE_EVENT: &str = "mnote:leptos-tiptap-spike:state"; +const STATUS_EVENT: &str = "mnote:leptos-tiptap-spike:status"; +const SELECTION_EVENT: &str = "mnote:leptos-tiptap-spike:selection"; +const COMMAND_EVENT: &str = "mnote:leptos-tiptap-spike:command"; +const HEIGHT_EVENT: &str = "mnote:leptos-tiptap-spike:height"; +const STANDALONE_ROOT_ID: &str = "mnote-leptos-tiptap-standalone-root"; + +#[derive(Clone, Copy)] +struct ToolbarColorOption { + id: &'static str, + label: &'static str, + value: &'static str, +} + +#[derive(Clone, Copy)] +struct ToolbarAlignOption { + id: &'static str, + label: &'static str, + alignment: TiptapTextAlign, +} + +const TOOLBAR_TEXT_COLORS: [ToolbarColorOption; 10] = [ + ToolbarColorOption { + id: "default", + label: "默认文字", + value: "#111827", + }, + ToolbarColorOption { + id: "gray", + label: "灰色", + value: "#6b7280", + }, + ToolbarColorOption { + id: "brown", + label: "棕色", + value: "#8b5e3c", + }, + ToolbarColorOption { + id: "orange", + label: "橙色", + value: "#c96b1f", + }, + ToolbarColorOption { + id: "yellow", + label: "黄色", + value: "#b7791f", + }, + ToolbarColorOption { + id: "green", + label: "绿色", + value: "#18794e", + }, + ToolbarColorOption { + id: "blue", + label: "蓝色", + value: "#1d4ed8", + }, + ToolbarColorOption { + id: "purple", + label: "紫色", + value: "#7c3aed", + }, + ToolbarColorOption { + id: "pink", + label: "粉色", + value: "#be185d", + }, + ToolbarColorOption { + id: "red", + label: "红色", + value: "#b91c1c", + }, +]; + +const TOOLBAR_HIGHLIGHT_COLORS: [ToolbarColorOption; 8] = [ + ToolbarColorOption { + id: "yellow", + label: "黄色背景", + value: "#fef3c7", + }, + ToolbarColorOption { + id: "green", + label: "绿色背景", + value: "#dcfce7", + }, + ToolbarColorOption { + id: "blue", + label: "蓝色背景", + value: "#dbeafe", + }, + ToolbarColorOption { + id: "purple", + label: "紫色背景", + value: "#ede9fe", + }, + ToolbarColorOption { + id: "pink", + label: "粉色背景", + value: "#fce7f3", + }, + ToolbarColorOption { + id: "red", + label: "红色背景", + value: "#fee2e2", + }, + ToolbarColorOption { + id: "orange", + label: "橙色背景", + value: "#ffedd5", + }, + ToolbarColorOption { + id: "gray", + label: "灰色背景", + value: "#e5e7eb", + }, +]; + +const TOOLBAR_ALIGN_OPTIONS: [ToolbarAlignOption; 4] = [ + ToolbarAlignOption { + id: "left", + label: "左对齐", + alignment: TiptapTextAlign::Left, + }, + ToolbarAlignOption { + id: "center", + label: "居中", + alignment: TiptapTextAlign::Center, + }, + ToolbarAlignOption { + id: "right", + label: "右对齐", + alignment: TiptapTextAlign::Right, + }, + ToolbarAlignOption { + id: "justify", + label: "两端对齐", + alignment: TiptapTextAlign::Justify, + }, +]; + +const SPIKE_STYLE: &str = r#" +:root { + --tt-color-text: #111827; + --tt-color-text-gray: #6b7280; + --tt-color-text-brown: #8b5e3c; + --tt-color-text-orange: #c96b1f; + --tt-color-text-yellow: #b7791f; + --tt-color-text-green: #18794e; + --tt-color-text-blue: #1d4ed8; + --tt-color-text-purple: #7c3aed; + --tt-color-text-pink: #be185d; + --tt-color-text-red: #b91c1c; + --tt-color-highlight-yellow: #fef3c7; + --tt-color-highlight-green: #dcfce7; + --tt-color-highlight-blue: #dbeafe; + --tt-color-highlight-purple: #ede9fe; + --tt-color-highlight-pink: #fce7f3; + --tt-color-highlight-red: #fee2e2; + --tt-color-highlight-orange: #ffedd5; + --tt-color-highlight-gray: #e5e7eb; +} + +.app-shell { + max-width: 1180px; + margin: 0 auto; + padding: 28px 20px 72px; +} + +.app-shell-embedded { + max-width: none; + margin: 0; + padding: 0; +} + +.app-shell-embedded .hero-bar, +.app-shell-embedded .title-input, +.app-shell-embedded .editor-subcopy, +.app-shell-embedded .footer-strip, +.app-shell-embedded .debug-drawer, +.app-shell-embedded .editor-crumbs:first-child, +.app-shell-embedded .editor-crumbs:last-child { + display: none; +} + +.app-shell-embedded .editor-card { + border: none; + border-radius: 0; + box-shadow: none; + background: transparent; + overflow: visible; +} + +.app-shell-embedded .editor-topbar { + display: none; +} + +.app-shell-embedded .editor-stage { + margin: 0; + border: none; + border-radius: 0; + background: transparent; + box-shadow: none; +} + +.hero-bar { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 18px; + margin-bottom: 20px; +} + +.hero-meta { + display: grid; + gap: 10px; +} + +.hero-tag { + display: inline-flex; + align-items: center; + gap: 8px; + width: fit-content; + padding: 6px 12px; + border-radius: 999px; + background: rgba(15, 118, 110, 0.12); + color: var(--accent-strong); + font-size: 12px; + letter-spacing: .08em; + text-transform: uppercase; +} + +.hero-title { + margin: 0; + font-size: 40px; + line-height: 1.04; +} + +.hero-copy { + margin: 0; + max-width: 680px; + color: var(--muted); + line-height: 1.75; +} + +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; + justify-content: flex-end; +} + +.hero-chip { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 14px; + border: 1px solid var(--line); + border-radius: 16px; + background: rgba(255, 255, 255, 0.92); + color: var(--ink); + font-size: 13px; + box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05); +} + +.hero-chip strong { + color: var(--accent-strong); +} + +.editor-card { + position: relative; + border: 1px solid rgba(100, 116, 139, 0.18); + border-radius: 30px; + background: + linear-gradient(180deg, rgba(255, 255, 255, 0.98) 0%, rgba(254, 251, 246, 0.98) 100%); + box-shadow: 0 28px 64px rgba(15, 23, 42, 0.08); + overflow: hidden; +} + +.editor-topbar { + display: flex; + justify-content: space-between; + align-items: center; + gap: 14px; + padding: 18px 22px 12px; +} + +.editor-crumbs { + display: flex; + align-items: center; + gap: 10px; + color: var(--muted); + font-size: 13px; +} + +.editor-crumbs strong { + color: var(--ink); +} + +.title-input { + width: 100%; + border: none; + outline: none; + background: transparent; + font-size: 48px; + line-height: 1.05; + font-weight: 700; + color: #0f172a; + padding: 8px 22px 6px; +} + +.title-input::placeholder { + color: #94a3b8; +} + +.editor-subcopy { + display: flex; + flex-wrap: wrap; + gap: 10px 16px; + align-items: center; + padding: 0 22px 18px; + color: var(--muted); + font-size: 14px; +} + +.hint-pill { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-radius: 999px; + background: rgba(15, 118, 110, 0.09); + color: var(--accent-strong); + font-size: 13px; +} + +.editor-stage { + position: relative; + width: min(100%, 900px); + margin: 0 auto 18px; + border: 1px solid rgba(100, 116, 139, 0.18); + border-radius: 26px; + background: rgba(255, 255, 255, 0.92); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8); +} + +.editor-stage[data-page-wide-layout="true"] { + width: min(100%, 1120px); +} + +.block-handle-shell { + position: absolute; + left: 12px; + z-index: 14; + display: inline-flex; + align-items: center; + gap: 6px; +} + +.block-handle-shell[data-dragging="true"] { + pointer-events: none; + opacity: 0.72; +} + +.block-handle-insert, +.block-handle-trigger { + width: 32px; + height: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 1px solid rgba(15, 23, 42, 0.12); + border-radius: 11px; + background: rgba(255, 255, 255, 0.98); + color: #334155; + box-shadow: 0 10px 24px rgba(15, 23, 42, 0.1); + transition: transform .12s ease, border-color .12s ease, box-shadow .12s ease; +} + +.block-handle-insert { + color: var(--accent-strong); + cursor: pointer; +} + +.block-handle-insert span { + font-size: 20px; + line-height: 1; +} + +.block-handle-insert:hover, +.block-handle-trigger:hover { + transform: translateY(-1px); + border-color: rgba(15, 118, 110, 0.34); + box-shadow: 0 18px 36px rgba(15, 23, 42, 0.16); +} + +.block-handle-trigger:active { + cursor: grabbing; +} + +.block-handle-trigger { + cursor: grab; + font-size: 18px; + letter-spacing: -0.08em; +} + +.block-drag-menu { + position: absolute; + top: 0; + left: calc(100% + 10px); + min-width: 248px; + display: grid; + gap: 8px; + padding: 12px; + border: 1px solid rgba(15, 23, 42, 0.1); + border-radius: 18px; + background: rgba(255, 255, 255, 0.98); + color: var(--ink); + box-shadow: 0 22px 48px rgba(15, 23, 42, 0.18); + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; +} + +.block-drag-menu-label { + display: grid; + gap: 4px; +} + +.block-drag-menu-label strong { + font-size: 14px; +} + +.block-drag-menu-label span { + color: var(--muted); + font-size: 12px; +} + +.block-drag-menu-back { + width: 100%; + display: inline-flex; + align-items: center; + gap: 8px; + border: none; + background: transparent; + color: var(--muted); + padding: 2px 2px 6px; + cursor: pointer; +} + +.block-drag-menu-back:hover { + color: var(--accent-strong); +} + +.block-drag-menu-actions { + display: grid; + gap: 6px; +} + +.block-drag-menu-section { + display: grid; + gap: 6px; +} + +.block-drag-menu-divider { + height: 1px; + background: rgba(148, 163, 184, 0.22); +} + +.block-drag-menu-item { + width: 100%; + display: flex; + align-items: center; + justify-content: flex-start; + gap: 12px; + text-align: left; + border: 1px solid transparent; + border-radius: 14px; + background: transparent; + color: inherit; + padding: 10px 12px; + cursor: pointer; + transition: background .12s ease, border-color .12s ease; +} + +.block-drag-menu-item:hover { + background: rgba(15, 118, 110, 0.08); + border-color: rgba(15, 118, 110, 0.18); +} + +.block-drop-indicator { + position: absolute; + left: 56px; + right: 34px; + height: 2px; + border-radius: 999px; + background: rgba(15, 118, 110, 0.78); + box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12); + z-index: 13; +} + +.floating-toolbar { + position: absolute; + left: 0; + top: 0; + transform: translate(-50%, calc(-100% - 14px)); + z-index: 12; + display: flex; + align-items: center; + gap: 2px; + flex-wrap: nowrap; + max-width: min(720px, calc(100% - 32px)); + padding: 3px; + border: 1px solid rgba(15, 23, 42, 0.08); + border-radius: 18px; + background: rgba(255, 255, 255, 0.98); + color: #0f172a; + box-shadow: 0 18px 40px rgba(15, 23, 42, 0.14); + backdrop-filter: blur(16px); +} + +.floating-toolbar-group { + display: flex; + align-items: center; + gap: 2px; +} + +.toolbar-popover-anchor { + position: relative; + display: inline-flex; + align-items: center; +} + +.toolbar-separator { + width: 1px; + align-self: stretch; + margin: 4px 3px; + background: rgba(148, 163, 184, 0.28); +} + +.toolbar-btn { + min-width: 34px; + height: 34px; + border: none; + border-radius: 12px; + background: transparent; + color: inherit; + padding: 0 10px; + cursor: pointer; + transition: background .12s ease, border-color .12s ease, transform .12s ease; + font-size: 14px; + font-weight: 600; +} + +.toolbar-btn:hover { + background: rgba(148, 163, 184, 0.16); +} + +.toolbar-btn[data-active="true"] { + background: rgba(15, 118, 110, 0.14); + color: var(--accent-strong); +} + +.toolbar-btn[data-wide="true"] { + min-width: 56px; + justify-content: space-between; +} + +.turn-into-panel { + position: absolute; + bottom: calc(100% + 10px); + left: 50%; + transform: translateX(-50%); + min-width: 220px; + max-height: min(420px, calc(100vh - 32px)); + display: grid; + gap: 6px; + padding: 10px; + border-radius: 18px; + border: 1px solid rgba(15, 23, 42, 0.1); + background: rgba(255, 255, 255, 0.98); + color: var(--ink); + box-shadow: 0 20px 44px rgba(15, 23, 42, 0.16); + overflow-y: auto; + overscroll-behavior: contain; + z-index: 2; +} + +.toolbar-popover-panel { + position: absolute; + bottom: calc(100% + 10px); + left: 50%; + transform: translateX(-50%); + min-width: 248px; + max-height: min(440px, calc(100vh - 32px)); + display: grid; + gap: 10px; + padding: 12px; + border-radius: 18px; + border: 1px solid rgba(15, 23, 42, 0.1); + background: rgba(255, 255, 255, 0.98); + color: var(--ink); + box-shadow: 0 20px 44px rgba(15, 23, 42, 0.16); + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + z-index: 2; +} + +.turn-into-item, +.slash-item, +.toolbar-menu-item { + width: 100%; + display: grid; + gap: 4px; + text-align: left; + border: 1px solid transparent; + border-radius: 14px; + background: transparent; + color: inherit; + padding: 10px 12px; + cursor: pointer; + transition: background .12s ease, border-color .12s ease; +} + +.turn-into-item:hover, +.slash-item:hover, +.slash-item[data-active="true"], +.toolbar-menu-item:hover, +.toolbar-menu-item[data-active="true"] { + background: rgba(15, 118, 110, 0.08); + border-color: rgba(15, 118, 110, 0.18); +} + +.turn-into-item span, +.slash-item span, +.toolbar-menu-item span { + color: var(--muted); + font-size: 12px; +} + +.toolbar-popover-section { + display: grid; + gap: 8px; +} + +.toolbar-popover-title { + color: var(--muted); + font-size: 12px; + font-weight: 700; + letter-spacing: 0.02em; +} + +.toolbar-color-grid { + display: grid; + gap: 6px; + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.toolbar-color-item { + display: flex; + align-items: center; + gap: 10px; +} + +.toolbar-color-chip { + width: 18px; + height: 18px; + flex: 0 0 18px; + border-radius: 999px; + border: 1px solid rgba(15, 23, 42, 0.14); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.6); +} + +.toolbar-more-list { + display: grid; + gap: 6px; +} + +.toolbar-more-item strong { + font-size: 14px; +} + +.slash-menu { + position: absolute; + top: 24px; + left: 24px; + z-index: 11; + width: min(360px, calc(100% - 48px)); + display: grid; + gap: 8px; + padding: 10px; + border: 1px solid rgba(15, 23, 42, 0.1); + border-radius: 22px; + background: rgba(255, 255, 255, 0.98); + box-shadow: 0 24px 48px rgba(15, 23, 42, 0.16); +} + +.slash-list { + display: grid; + gap: 6px; +} + +.editor-surface { + display: block; + width: 100%; + min-height: 580px; + padding: 76px 0 32px; +} + +.app-shell-embedded .editor-surface { + min-height: 640px; + padding: 18px 0 28vh; +} + +.editor-surface .ProseMirror { + outline: none; + min-height: 472px; + line-height: 1.78; + font-size: 17px; + color: #1f2937; +} + +.app-shell-embedded .editor-surface .ProseMirror { + min-height: 600px; + width: min(100%, 708px); + margin: 0 auto; + padding: 2.25rem 3rem 30vh; + font-family: "DM Sans", "Noto Sans SC", "PingFang SC", sans-serif; +} + +.app-shell-embedded .editor-surface[data-small-text="true"] .ProseMirror, +.editor-surface[data-small-text="true"] .ProseMirror { + font-size: 15px; + line-height: 1.66; +} + +.app-shell-embedded .editor-surface[data-layout-density="compact"] .ProseMirror, +.editor-surface[data-layout-density="compact"] .ProseMirror { + line-height: 1.54; +} + +.app-shell-embedded .editor-surface[data-layout-density="spacious"] .ProseMirror, +.editor-surface[data-layout-density="spacious"] .ProseMirror { + line-height: 1.92; +} + +.editor-surface .ProseMirror h1, +.editor-surface .ProseMirror h2, +.editor-surface .ProseMirror h3 { + line-height: 1.12; + color: #0f172a; + margin: 1.12em 0 0.46em; + letter-spacing: -0.02em; +} + +.editor-surface .ProseMirror h1 { + font-size: 2.1em; +} + +.editor-surface .ProseMirror h2 { + font-size: 1.56em; +} + +.editor-surface .ProseMirror h3 { + font-size: 1.28em; +} + +.editor-surface .ProseMirror ul, +.editor-surface .ProseMirror ol { + padding-left: 1.5em; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] { + list-style: none; + padding-left: 0.25em; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li { + display: flex; + flex-direction: row; + align-items: flex-start; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li:not(:has(> p:first-child)) { + list-style-type: none; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li[data-checked="true"] > div > p, +.editor-surface .ProseMirror ul[data-type="taskList"] li[data-checked="true"] > div > p span { + opacity: 0.5; + text-decoration: line-through; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li label { + position: relative; + padding-top: 0.375rem; + padding-right: 0.5rem; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li label input[type="checkbox"] { + position: absolute; + opacity: 0; + width: 0; + height: 0; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li label span { + display: block; + width: 1em; + height: 1em; + border: 1px solid rgba(148, 163, 184, 0.7); + border-radius: 0.25rem; + position: relative; + cursor: pointer; + background-color: rgba(255, 255, 255, 0.96); + transition: + background-color 80ms ease-out, + border-color 80ms ease-out; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li label span::before { + content: ""; + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + width: 0.75em; + height: 0.75em; + background-color: #ffffff; + opacity: 0; + -webkit-mask: url("data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22currentColor%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M21.4142%204.58579C22.1953%205.36683%2022.1953%206.63317%2021.4142%207.41421L10.4142%2018.4142C9.63317%2019.1953%208.36684%2019.1953%207.58579%2018.4142L2.58579%2013.4142C1.80474%2012.6332%201.80474%2011.3668%202.58579%2010.5858C3.36683%209.80474%204.63317%209.80474%205.41421%2010.5858L9%2014.1716L18.5858%204.58579C19.3668%203.80474%2020.6332%203.80474%2021.4142%204.58579Z%22%20fill%3D%22currentColor%22%2F%3E%3C%2Fsvg%3E") center/contain no-repeat; + mask: url("data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22currentColor%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M21.4142%204.58579C22.1953%205.36683%2022.1953%206.63317%2021.4142%207.41421L10.4142%2018.4142C9.63317%2019.1953%208.36684%2019.1953%207.58579%2018.4142L2.58579%2013.4142C1.80474%2012.6332%201.80474%2011.3668%202.58579%2010.5858C3.36683%209.80474%204.63317%209.80474%205.41421%2010.5858L9%2014.1716L18.5858%204.58579C19.3668%203.80474%2020.6332%203.80474%2021.4142%204.58579Z%22%20fill%3D%22currentColor%22%2F%3E%3C%2Fsvg%3E") center/contain no-repeat; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li label input[type="checkbox"]:checked + span { + background: var(--accent-strong); + border-color: var(--accent-strong); +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li label input[type="checkbox"]:checked + span::before { + opacity: 1; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li > div { + flex: 1 1 0%; + min-width: 0; +} + +.editor-surface .ProseMirror ul[data-type="taskList"] li > div > p { + margin: 0; +} + +.editor-surface .ProseMirror pre { + background: #14222b; + color: #f8fafc; + padding: 16px 18px; + border-radius: 18px; + overflow: auto; +} + +.editor-surface .ProseMirror blockquote { + margin: 1.1em 0; + padding-left: 16px; + border-left: 3px solid rgba(15, 118, 110, 0.5); + color: #334155; +} + +.editor-surface .ProseMirror hr { + margin: 1.6em 0; + border: none; + border-top: 1px solid rgba(100, 116, 139, 0.28); +} + +.editor-surface .ProseMirror p.is-editor-empty:first-child::before, +.editor-surface .ProseMirror p.is-empty::before { + color: #94a3b8; + content: attr(data-placeholder); + float: left; + height: 0; + pointer-events: none; +} + +.editor-surface .ProseMirror p.is-editor-empty, +.editor-surface .ProseMirror p.is-empty { + min-height: 1.6em; +} + +.footer-strip { + display: flex; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + padding: 0 22px 22px; + color: var(--muted); + font-size: 13px; +} + +.footer-strip code { + color: var(--accent-strong); +} + +.debug-drawer { + margin-top: 22px; + border: 1px solid rgba(100, 116, 139, 0.18); + border-radius: 22px; + background: rgba(255, 255, 255, 0.85); + overflow: hidden; +} + +.debug-drawer summary { + cursor: pointer; + list-style: none; + padding: 18px 20px; + display: flex; + justify-content: space-between; + align-items: center; + font-weight: 600; +} + +.debug-drawer summary::-webkit-details-marker { + display: none; +} + +.debug-grid { + display: grid; + gap: 16px; + padding: 0 20px 20px; + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + +.debug-card { + border: 1px solid rgba(100, 116, 139, 0.18); + border-radius: 18px; + background: rgba(255, 255, 255, 0.88); + padding: 16px; +} + +.debug-card h3 { + margin: 0 0 10px; + font-size: 14px; +} + +.debug-card pre { + margin: 0; + max-height: 260px; + overflow: auto; + white-space: pre-wrap; + word-break: break-word; + color: #1e293b; +} + +@media (max-width: 920px) { + .hero-bar, + .editor-topbar, + .footer-strip { + flex-direction: column; + align-items: flex-start; + } + + .title-input { + font-size: 34px; + } + + .editor-surface { + padding: 88px 0 24px; + min-height: 460px; + } + + .app-shell-embedded .editor-surface { + padding: 12px 0 24vh; + } + + .app-shell-embedded .editor-surface .ProseMirror { + padding: 1.5rem 1.5rem 24vh; + } + + .debug-grid { + grid-template-columns: 1fr; + } + + .floating-toolbar, + .slash-menu, + .block-drag-menu { + left: 16px; + right: 16px; + width: auto; + transform: none; + } + + .floating-toolbar { + top: 12px; + } +} + +@media (max-width: 768px) { + .editor-stage { + width: 100%; + } + + .block-handle-shell, + .block-drop-indicator { + display: none; + } + + .app-shell-embedded .editor-surface { + padding-left: 0; + } +} +"#; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SlashActionKind { + Paragraph, + Heading1, + Heading2, + Heading3, + BulletList, + OrderedList, + Todo, + Quote, + CodeBlock, + Divider, +} + +#[derive(Clone, Copy)] +struct SlashAction { + kind: SlashActionKind, + id: &'static str, + label: &'static str, + description: &'static str, +} + +const SLASH_ACTIONS: [SlashAction; 10] = [ + SlashAction { + kind: SlashActionKind::Paragraph, + id: "paragraph", + label: "段落", + description: "回到普通正文块", + }, + SlashAction { + kind: SlashActionKind::Heading1, + id: "heading-1", + label: "一级标题", + description: "建立页面主层级", + }, + SlashAction { + kind: SlashActionKind::Heading2, + id: "heading-2", + label: "二级标题", + description: "整理章节结构", + }, + SlashAction { + kind: SlashActionKind::Heading3, + id: "heading-3", + label: "三级标题", + description: "补细粒度小节", + }, + SlashAction { + kind: SlashActionKind::BulletList, + id: "bullet", + label: "无序列表", + description: "记录普通要点", + }, + SlashAction { + kind: SlashActionKind::OrderedList, + id: "ordered", + label: "有序列表", + description: "记录步骤顺序", + }, + SlashAction { + kind: SlashActionKind::Todo, + id: "todo", + label: "Todo 列表", + description: "切到真正的 taskList/taskItem", + }, + SlashAction { + kind: SlashActionKind::Quote, + id: "quote", + label: "引用块", + description: "包住注释与摘录", + }, + SlashAction { + kind: SlashActionKind::CodeBlock, + id: "code-block", + label: "代码块", + description: "插入带语义的代码块", + }, + SlashAction { + kind: SlashActionKind::Divider, + id: "divider", + label: "分割线", + description: "插入 horizontal rule", + }, +]; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct PersistedSpikeDocument { + #[serde(default)] + document_id: Option, + #[serde(default)] + workspace_id: Option, + title: String, + content: Value, + #[serde(default)] + html: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct PersistedDocumentIdentity { + document_id: Option, + workspace_id: Option, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct BridgeEnvelope +where + T: Serialize, +{ + protocol: &'static str, + runtime: &'static str, + version: &'static str, + source: &'static str, + event: &'static str, + payload: T, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct BridgeSelectorsPayload { + root: &'static str, + stage: &'static str, + editor: &'static str, + toolbar: &'static str, + slash_menu: &'static str, + handle: &'static str, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct HostStatusPayload { + document_id: Option, + workspace_id: Option, + title: String, + dirty_count: u32, + selected_block_index: Option, + current_block_id: Option, + editor_focused: bool, + read_only: bool, + slash_open: bool, + toolbar_open: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct ReadyPayload { + runtime_name: &'static str, + selectors: BridgeSelectorsPayload, + supported_commands: Vec<&'static str>, + supports_embedded_mode: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct StatePayload { + document_id: Option, + workspace_id: Option, + title: String, + dirty_count: u32, + selected_block_index: Option, + editor_focused: bool, + slash_open: bool, + toolbar_open: bool, + read_only: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct SelectionPayload { + selection: TiptapSelectionState, + summary: String, + editor_focused: bool, + current_block_index: Option, + current_block_id: Option, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct ChangeMetaPayload { + dirty_count: u32, + editor_focused: bool, + slash_open: bool, + toolbar_open: bool, + selected_block_index: Option, + revision: Option, + conflict_detection_key: Option, + read_only: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct ChangePayload { + document_id: Option, + workspace_id: Option, + title: String, + content: Value, + meta: ChangeMetaPayload, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct HeightPayload { + height: f64, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct HostCommandEnvelope { + protocol: Option, + runtime: Option, + version: Option, + source: Option, + event: Option, + payload: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct RuntimePageOptions { + wide_layout: Option, + small_text: Option, + layout_density: Option, + show_heading_numbers: Option, + embed_default_block_id: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct HostCommandPayload { + command: Option, + document_id: Option, + workspace_id: Option, + title: Option, + content: Option, + editable: Option, + page_options: Option, + block_id: Option, + block_index: Option, + text: Option, + reference_document_id: Option, + reference_block_id: Option, + current_block_id: Option, + selection: Option, + revision: Option, + conflict_detection_key: Option, + read_only: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct LegacyHostEnvelope { + protocol: Option, + runtime: Option, + version: Option, + source: Option, + event: Option, + payload: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct HostDocumentPayload { + document_id: Option, + workspace_id: Option, + title: Option, + content: Option, + revision: Option, + conflict_detection_key: Option, + read_only: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum HostCommandKind { + Undo, + Redo, + ReplaceContent, + SetPageOptions, + InsertInlineReference, + InsertEmbedReference, + RequestCurrentBlockId, + SetEditable, + Focus, + Bootstrap, +} + +impl HostCommandKind { + fn from_event_name(event_name: &str) -> Option { + match event_name { + "undo" => Some(Self::Undo), + "redo" => Some(Self::Redo), + "replaceContent" | "replace-document" => Some(Self::ReplaceContent), + "setPageOptions" | "set-page-options" => Some(Self::SetPageOptions), + "insertInlineReference" => Some(Self::InsertInlineReference), + "insertEmbedReference" => Some(Self::InsertEmbedReference), + "requestCurrentBlockId" => Some(Self::RequestCurrentBlockId), + "setEditable" | "set-editable" => Some(Self::SetEditable), + "focus" => Some(Self::Focus), + "bootstrap" => Some(Self::Bootstrap), + _ => None, + } + } + + fn from_payload(payload: &HostCommandPayload) -> Option { + payload + .command + .as_deref() + .and_then(Self::from_event_name) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct CurrentBlockInfo { + index: Option, + block_id: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_command_aliases_and_canonical_names() { + assert_eq!( + HostCommandKind::from_event_name("replace-document"), + Some(HostCommandKind::ReplaceContent) + ); + assert_eq!( + HostCommandKind::from_event_name("replaceContent"), + Some(HostCommandKind::ReplaceContent) + ); + assert_eq!( + HostCommandKind::from_event_name("requestCurrentBlockId"), + Some(HostCommandKind::RequestCurrentBlockId) + ); + } + + #[test] + fn reads_command_from_payload_field() { + let payload = HostCommandPayload { + command: Some("setEditable".to_string()), + document_id: None, + workspace_id: None, + title: None, + content: None, + editable: Some(true), + page_options: None, + block_id: None, + block_index: None, + text: None, + reference_document_id: None, + reference_block_id: None, + current_block_id: None, + selection: None, + revision: None, + conflict_detection_key: None, + read_only: None, + }; + + assert_eq!(HostCommandKind::from_payload(&payload), Some(HostCommandKind::SetEditable)); + } + + #[test] + fn resolves_embedded_mode_from_explicit_runtime_mode_first() { + assert_eq!( + resolve_runtime_delivery_mode(Some(RuntimeDeliveryMode::Embedded), false), + RuntimeDeliveryMode::Embedded + ); + assert_eq!( + resolve_runtime_delivery_mode(Some(RuntimeDeliveryMode::Standalone), true), + RuntimeDeliveryMode::Standalone + ); + } + + #[test] + fn resolves_embedded_mode_from_url_when_runtime_mode_absent() { + assert_eq!( + resolve_runtime_delivery_mode(None, true), + RuntimeDeliveryMode::Embedded + ); + assert_eq!( + resolve_runtime_delivery_mode(None, false), + RuntimeDeliveryMode::Standalone + ); + } + + #[test] + fn persisted_document_storage_key_isolated_per_document_identity() { + let doc_a = persisted_document_identity( + Some("doc-a".to_string()), + Some("ws-1".to_string()), + ); + let doc_b = persisted_document_identity( + Some("doc-b".to_string()), + Some("ws-1".to_string()), + ); + let doc_without_workspace = + persisted_document_identity(Some("doc-a".to_string()), None); + + assert_eq!( + persisted_document_storage_key(&doc_a), + "mnote.leptos-tiptap-spike.document:ws-1:doc-a" + ); + assert_eq!( + persisted_document_storage_key(&doc_b), + "mnote.leptos-tiptap-spike.document:ws-1:doc-b" + ); + assert_eq!( + persisted_document_storage_key(&doc_without_workspace), + "mnote.leptos-tiptap-spike.document:doc-a" + ); + assert_ne!( + persisted_document_storage_key(&doc_a), + persisted_document_storage_key(&doc_b) + ); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RuntimeDeliveryMode { + Standalone, + Embedded, +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct MountOptions { + document_id: Option, + workspace_id: Option, + title: Option, + content: Option, + html: Option, + editable: Option, + read_only: Option, + revision: Option, + conflict_detection_key: Option, + page_options: Option, +} + +struct RuntimeMountContext { + id: u32, + target: EventTarget, + mode: RuntimeDeliveryMode, +} + +#[derive(Clone, Debug)] +struct RuntimeMountOptions { + options: MountOptions, + mode: RuntimeDeliveryMode, +} + +struct MountedRuntimeListener { + target: EventTarget, + listener: Closure, +} + +struct MountedRuntime { + listeners: Vec, + mount_handle: Box, +} + +impl Drop for MountedRuntime { + fn drop(&mut self) { + for listener in &self.listeners { + let _ = listener.target.remove_event_listener_with_callback( + COMMAND_EVENT, + listener.listener.as_ref().unchecked_ref(), + ); + } + } +} + +thread_local! { + static RUNTIME_MOUNT_CONTEXT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + static RUNTIME_MOUNT_OPTIONS: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + static MOUNTED_HANDLES: std::cell::RefCell> = std::cell::RefCell::new(HashMap::new()); + static PENDING_RUNTIME_LISTENERS: std::cell::RefCell>> = std::cell::RefCell::new(HashMap::new()); + static NEXT_MOUNT_ID: Cell = const { Cell::new(1) }; +} + +fn next_mount_id() -> u32 { + NEXT_MOUNT_ID.with(|cell| { + let next = cell.get(); + cell.set(next.saturating_add(1).max(1)); + next + }) +} + +fn set_runtime_mount_context(context: Option) { + RUNTIME_MOUNT_CONTEXT.with(|cell| { + *cell.borrow_mut() = context; + }); +} + +fn runtime_mount_context() -> Option<(u32, EventTarget, RuntimeDeliveryMode)> { + RUNTIME_MOUNT_CONTEXT.with(|cell| { + cell.borrow() + .as_ref() + .map(|context| (context.id, context.target.clone(), context.mode)) + }) +} + +fn runtime_delivery_mode() -> RuntimeDeliveryMode { + resolve_runtime_delivery_mode( + runtime_mount_context().map(|(_, _, mode)| mode), + url_requests_embedded_mode(), + ) +} + +fn set_runtime_mount_options(options: Option) { + RUNTIME_MOUNT_OPTIONS.with(|cell| { + *cell.borrow_mut() = options; + }); +} + +fn runtime_mount_options() -> Option { + RUNTIME_MOUNT_OPTIONS.with(|cell| cell.borrow().clone()) +} + +fn runtime_event_target() -> Option { + if let Some((_, target, _)) = runtime_mount_context() { + return Some(target); + } + + window() + .and_then(|win| win.document()) + .and_then(|document| document.body()) + .map(|body| body.into()) +} + +fn runtime_block_id_from_index(index: usize) -> Option { + Some(format!("top-level-{index}")) +} + +fn current_runtime_block_info() -> CurrentBlockInfo { + hovered_block_from_selection() + .and_then(|block| { + Some(CurrentBlockInfo { + index: Some(block.index), + block_id: runtime_block_id_from_index(block.index), + }) + }) + .unwrap_or(CurrentBlockInfo { + index: None, + block_id: None, + }) +} + +fn current_runtime_block_info_from_hovered(hovered_block: Option) -> CurrentBlockInfo { + hovered_block + .map(|block| CurrentBlockInfo { + index: Some(block.index), + block_id: runtime_block_id_from_index(block.index), + }) + .unwrap_or(CurrentBlockInfo { + index: None, + block_id: None, + }) +} + +fn dispatch_runtime_event(event_name: &'static str, payload: &T) +where + T: Serialize, +{ + let envelope = BridgeEnvelope { + protocol: PROTOCOL, + runtime: RUNTIME_NAME, + version: RUNTIME_VERSION, + source: EVENT_PREFIX, + event: event_name, + payload, + }; + let Ok(detail_value) = serde_wasm_bindgen::to_value(&envelope) else { + return; + }; + + let Some(target) = runtime_event_target() else { + return; + }; + + let init = CustomEventInit::new(); + init.set_detail(&detail_value); + if let Ok(event) = CustomEvent::new_with_event_init_dict(event_name, &init) { + let _ = target.dispatch_event(&event); + } +} + +fn dispatch_custom_event_to_target(target: &EventTarget, event_name: &'static str, payload: &T) +where + T: Serialize, +{ + let envelope = BridgeEnvelope { + protocol: PROTOCOL, + runtime: RUNTIME_NAME, + version: RUNTIME_VERSION, + source: EVENT_PREFIX, + event: event_name, + payload, + }; + let Ok(detail_value) = serde_wasm_bindgen::to_value(&envelope) else { + return; + }; + + let init = CustomEventInit::new(); + init.set_detail(&detail_value); + init.set_bubbles(true); + if let Ok(event) = CustomEvent::new_with_event_init_dict(event_name, &init) { + let _ = target.dispatch_event(&event); + } +} + +fn dispatch_ready_event(payload: &ReadyPayload) { + dispatch_runtime_event(READY_EVENT, payload); +} + +fn dispatch_change_event(payload: &ChangePayload) { + dispatch_runtime_event(CHANGE_EVENT, payload); +} + +fn dispatch_state_event(payload: &StatePayload) { + dispatch_runtime_event(STATE_EVENT, payload); +} + +fn dispatch_status_event(payload: &HostStatusPayload) { + dispatch_runtime_event(STATUS_EVENT, payload); +} + +fn dispatch_selection_event(payload: &SelectionPayload) { + dispatch_runtime_event(SELECTION_EVENT, payload); +} + +fn register_unmount_handle( + id: u32, + target: EventTarget, + listener: Closure, + handle: UnmountHandle, +) { + let mut listeners = vec![MountedRuntimeListener { target, listener }]; + PENDING_RUNTIME_LISTENERS.with(|registry| { + if let Some(mut pending) = registry.borrow_mut().remove(&id) { + listeners.append(&mut pending); + } + }); + MOUNTED_HANDLES.with(|registry| { + registry.borrow_mut().insert( + id, + MountedRuntime { + listeners, + mount_handle: Box::new(handle), + }, + ); + }); +} + +fn register_runtime_listener( + id: u32, + target: EventTarget, + listener: Closure, +) { + MOUNTED_HANDLES.with(|registry| { + if let Some(runtime) = registry.borrow_mut().get_mut(&id) { + runtime + .listeners + .push(MountedRuntimeListener { target, listener }); + } else { + PENDING_RUNTIME_LISTENERS.with(|pending_registry| { + pending_registry + .borrow_mut() + .entry(id) + .or_default() + .push(MountedRuntimeListener { target, listener }); + }); + } + }); +} + +fn take_unmount_handle(id: u32) -> Option { + PENDING_RUNTIME_LISTENERS.with(|registry| { + registry.borrow_mut().remove(&id); + }); + MOUNTED_HANDLES.with(|registry| registry.borrow_mut().remove(&id)) +} + +#[wasm_bindgen] +pub fn mount(container: Element, options: JsValue) -> Result { + console_error_panic_hook::set_once(); + let options = if options.is_undefined() || options.is_null() { + MountOptions::default() + } else { + serde_wasm_bindgen::from_value(options)? + }; + let target = container + .dyn_into::() + .map_err(|_| JsValue::from_str("mount 目标必须是 HTML 元素"))?; + let mount_id = mount_app_into(target, options, RuntimeDeliveryMode::Embedded); + Ok(mount_id) +} + +#[wasm_bindgen] +pub fn unmount(mount_id: u32) -> Result<(), JsValue> { + if let Some(handle) = take_unmount_handle(mount_id) { + if runtime_mount_context().map(|(id, _, _)| id) == Some(mount_id) { + set_runtime_mount_context(None); + set_runtime_mount_options(None); + } + drop(handle); + Ok(()) + } else { + Err(JsValue::from_str("找不到对应的挂载句柄")) + } +} + +fn mount_app_into(target: HtmlElement, options: MountOptions, mode: RuntimeDeliveryMode) -> u32 { + let mount_id = next_mount_id(); + let context_target: EventTarget = target.clone().into(); + let mount_options = RuntimeMountOptions { + options: options.clone(), + mode, + }; + + set_runtime_mount_options(Some(mount_options.clone())); + set_runtime_mount_context(Some(RuntimeMountContext { + id: mount_id, + target: context_target.clone(), + mode, + })); + + let handle = mount_to(target, move || { + view! { + + } + }); + + let command_listener = build_command_listener(mount_id); + let _ = context_target.add_event_listener_with_callback( + COMMAND_EVENT, + command_listener.as_ref().unchecked_ref(), + ); + + register_unmount_handle(mount_id, context_target, command_listener, handle); + mount_id +} + +fn build_command_listener(mount_id: u32) -> Closure { + Closure::::wrap(Box::new(move |event: Event| { + let Some(custom_event) = event.dyn_ref::() else { + return; + }; + let detail = custom_event.detail(); + let Ok(envelope) = serde_wasm_bindgen::from_value::(detail) else { + return; + }; + if envelope.protocol.as_deref() != Some(PROTOCOL) { + return; + } + + let Some(payload) = envelope.payload else { + return; + }; + let Some(command_kind) = HostCommandKind::from_payload(&payload) else { + return; + }; + + let _ = mount_id; + let _ = command_kind; + })) +} + +#[derive(Clone, Debug, PartialEq)] +struct HoveredBlockState { + index: usize, + label: String, + top: f64, + height: f64, +} + +#[derive(Clone, Debug, PartialEq)] +struct FloatingToolbarAnchor { + top: f64, + left: f64, +} + +#[derive(Clone, Debug, PartialEq)] +struct BlockMenuLayout { + max_height: f64, + open_upward: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum DropPlacement { + Before, + After, +} + +#[derive(Clone, Debug, PartialEq)] +struct DropIndicatorState { + index: usize, + top: f64, + placement: DropPlacement, +} + +#[derive(Clone, Debug, PartialEq)] +struct PendingDragState { + index: usize, + anchor: HoveredBlockState, + start_x: i32, + start_y: i32, +} + +fn local_storage() -> Option { + window().and_then(|win| win.local_storage().ok().flatten()) +} + +fn default_title() -> String { + "Leptos Tiptap 主编辑器 P0".to_string() +} + +fn current_query_param(key: &str) -> Option { + window() + .and_then(|win| win.location().search().ok()) + .and_then(|search| { + let query = search.trim_start_matches('?'); + query.split('&').find_map(|pair| { + let (candidate_key, candidate_value) = pair.split_once('=')?; + if candidate_key == key && !candidate_value.trim().is_empty() { + Some(candidate_value.trim().to_string()) + } else { + None + } + }) + }) +} + +fn normalize_identity_value(value: Option) -> Option { + value.and_then(|value| { + let trimmed = value.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } + }) +} + +fn persisted_document_identity( + document_id: Option, + workspace_id: Option, +) -> PersistedDocumentIdentity { + PersistedDocumentIdentity { + document_id: normalize_identity_value(document_id), + workspace_id: normalize_identity_value(workspace_id), + } +} + +fn resolve_persisted_document_identity( + explicit_document_id: Option, + explicit_workspace_id: Option, +) -> PersistedDocumentIdentity { + persisted_document_identity( + explicit_document_id.or_else(|| current_query_param("documentId")), + explicit_workspace_id.or_else(|| current_query_param("workspaceId")), + ) +} + +fn persisted_document_storage_key(identity: &PersistedDocumentIdentity) -> String { + match (&identity.workspace_id, &identity.document_id) { + (Some(workspace_id), Some(document_id)) => { + format!("{SPIKE_STORAGE_KEY}:{workspace_id}:{document_id}") + } + (None, Some(document_id)) => format!("{SPIKE_STORAGE_KEY}:{document_id}"), + _ => SPIKE_STORAGE_KEY.to_string(), + } +} + +fn runtime_persisted_identity( + document_id: ReadSignal>, + workspace_id: ReadSignal>, +) -> PersistedDocumentIdentity { + persisted_document_identity( + document_id.get_untracked(), + workspace_id.get_untracked(), + ) +} + +fn persist_document_state( + identity: &PersistedDocumentIdentity, + title: &str, + content: &Value, + html: Option, +) -> Result<(), String> { + let payload = PersistedSpikeDocument { + document_id: identity.document_id.clone(), + workspace_id: identity.workspace_id.clone(), + title: title.to_string(), + content: content.clone(), + html, + }; + let raw = serde_json::to_string(&payload).map_err(|err| format!("序列化草稿失败:{err}"))?; + local_storage() + .ok_or_else(|| "浏览器 localStorage 不可用".to_string())? + .set_item(&persisted_document_storage_key(identity), &raw) + .map_err(|err| format!("写入 localStorage 失败:{err:?}")) +} + +fn load_persisted_document(identity: &PersistedDocumentIdentity) -> Option { + let raw = local_storage()? + .get_item(&persisted_document_storage_key(identity)) + .ok() + .flatten()?; + let document = serde_json::from_str::(&raw).ok()?; + let stored_identity = persisted_document_identity( + document.document_id.clone(), + document.workspace_id.clone(), + ); + if stored_identity == *identity || identity.document_id.is_none() { + Some(document) + } else { + None + } +} + +fn url_requests_embedded_mode() -> bool { + window() + .and_then(|win| win.location().search().ok()) + .map(|search| search.contains("embedded=1")) + .unwrap_or(false) +} + +fn resolve_runtime_delivery_mode( + explicit_mode: Option, + url_embedded: bool, +) -> RuntimeDeliveryMode { + if let Some(mode) = explicit_mode { + return mode; + } + + if url_embedded { + RuntimeDeliveryMode::Embedded + } else { + RuntimeDeliveryMode::Standalone + } +} + +fn is_embedded_mode() -> bool { + runtime_delivery_mode() == RuntimeDeliveryMode::Embedded +} + +fn current_document_id() -> Option { + current_query_param("documentId") +} + +fn current_workspace_id() -> Option { + current_query_param("workspaceId") +} + +fn selection_event_payload( + selection: &TiptapSelectionState, + editor_focused: bool, + hovered_block: Option, +) -> SelectionPayload { + SelectionPayload { + selection: selection.clone(), + summary: selection_summary(selection), + editor_focused, + current_block_index: hovered_block.as_ref().map(|block| block.index), + current_block_id: hovered_block.and_then(|block| runtime_block_id_from_index(block.index)), + } +} + +fn runtime_state_payload( + document_id: Option, + workspace_id: Option, + title: String, + dirty_count: u32, + hovered_block: Option, + editor_focused: bool, + slash_open: bool, + turn_into_open: bool, + color_menu_open: bool, + more_menu_open: bool, + read_only: bool, +) -> StatePayload { + StatePayload { + document_id, + workspace_id, + title, + dirty_count, + selected_block_index: hovered_block.map(|block| block.index), + editor_focused, + slash_open, + toolbar_open: toolbar_overlay_locked(turn_into_open, color_menu_open, more_menu_open), + read_only, + } +} + +fn runtime_status_payload( + document_id: Option, + workspace_id: Option, + title: String, + dirty_count: u32, + hovered_block: Option, + editor_focused: bool, + slash_open: bool, + turn_into_open: bool, + color_menu_open: bool, + more_menu_open: bool, + read_only: bool, +) -> HostStatusPayload { + let current_block_index = hovered_block.as_ref().map(|block| block.index); + HostStatusPayload { + document_id, + workspace_id, + title, + dirty_count, + selected_block_index: current_block_index, + current_block_id: current_block_index.and_then(runtime_block_id_from_index), + editor_focused, + read_only, + slash_open, + toolbar_open: toolbar_overlay_locked(turn_into_open, color_menu_open, more_menu_open), + } +} + +fn dispatch_bridge_event(event_name: &'static str, payload: &T) +where + T: Serialize, +{ + dispatch_runtime_event(event_name, payload); +} + +fn read_editor_snapshot(editor: TiptapEditorHandle) -> (String, Value, String) { + let html = editor + .get_html() + .unwrap_or_else(|err| format!("读取 HTML 失败:{err}")); + let json_value = editor.get_json().unwrap_or_else(|err| { + json!({ + "type": "error", + "message": format!("读取 JSON 失败:{err}"), + }) + }); + let json_text = serde_json::to_string_pretty(&json_value) + .unwrap_or_else(|err| format!("格式化 JSON 失败:{err}")); + (html, json_value, json_text) +} + +fn sync_editor_outputs( + editor: TiptapEditorHandle, + set_html_output: WriteSignal, + set_document_json: WriteSignal, + set_json_output: WriteSignal, +) -> Value { + let (html, json_value, json_text) = read_editor_snapshot(editor); + set_html_output.set(html); + set_document_json.set(json_value.clone()); + set_json_output.set(json_text); + json_value +} + +fn editor_root_element() -> Option { + window() + .and_then(|win| win.document()) + .and_then(|document| document.query_selector(EDITOR_ROOT_SELECTOR).ok().flatten()) +} + +fn editor_stage_element() -> Option { + window() + .and_then(|win| win.document()) + .and_then(|document| { + document + .query_selector(EDITOR_STAGE_SELECTOR) + .ok() + .flatten() + }) +} + +fn content_column_width(stage_rect_width: f64) -> f64 { + let available = (stage_rect_width - (CONTENT_COLUMN_HORIZONTAL_PADDING * 2.0)).max(0.0); + available.min(CONTENT_COLUMN_MAX_WIDTH) +} + +fn content_column_left(stage_rect_width: f64) -> f64 { + let column_width = content_column_width(stage_rect_width); + ((stage_rect_width - column_width) / 2.0).max(0.0) +} + +fn handle_lane_left(stage_rect_width: f64) -> f64 { + (content_column_left(stage_rect_width) + - HANDLE_TRIGGER_WIDTH + - HANDLE_TRIGGER_GAP + - HANDLE_MENU_GAP) + .max(HANDLE_STAGE_PADDING_LEFT) +} + +fn handle_corridor_width(stage_rect_width: f64) -> f64 { + let lane_left = handle_lane_left(stage_rect_width); + let content_left = content_column_left(stage_rect_width); + let content_gap = (content_left - lane_left).max(0.0); + (HANDLE_TRIGGER_WIDTH + HANDLE_TRIGGER_GAP + content_gap).max(HANDLE_GUTTER_WIDTH.min(stage_rect_width)) +} + +fn direct_block_from_element(mut element: Element, root: &Element) -> Option { + loop { + let parent = element.parent_element()?; + if parent.is_same_node(Some(root)) { + return Some(element); + } + element = parent; + } +} + +fn top_level_block_index(root: &Element, block: &Element) -> Option { + let children = root.children(); + (0..children.length()).find_map(|index| { + children + .item(index) + .filter(|child| child.is_same_node(Some(block))) + .map(|_| index as usize) + }) +} + +fn block_label_for_element(block: &Element) -> String { + match block.get_attribute("data-type").as_deref() { + Some("taskList") => "Todo 列表".to_string(), + Some("taskItem") => "Todo 项".to_string(), + _ => match block.tag_name().as_str() { + "H1" => "一级标题".to_string(), + "H2" => "二级标题".to_string(), + "H3" => "三级标题".to_string(), + "P" => "段落".to_string(), + "UL" => "无序列表".to_string(), + "OL" => "有序列表".to_string(), + "BLOCKQUOTE" => "引用块".to_string(), + "PRE" => "代码块".to_string(), + "HR" => "分割线".to_string(), + other => format!("块节点 {other}"), + }, + } +} + +fn target_element(target: web_sys::EventTarget) -> Option { + target.clone().dyn_into::().ok().or_else(|| { + target + .dyn_into::() + .ok() + .and_then(|node| node.parent_element()) + }) +} + +fn event_target_matches_selector(target: Option, selector: &str) -> bool { + target + .and_then(target_element) + .and_then(|element| element.closest(selector).ok().flatten()) + .is_some() +} + +fn current_target_html_element(event: &WheelEvent) -> Option { + event.current_target()?.dyn_into::().ok() +} + +fn trap_scroll_inside_menu(event: &WheelEvent) { + event.prevent_default(); + event.stop_propagation(); + + let Some(menu) = current_target_html_element(event) else { + return; + }; + + let current = f64::from(menu.scroll_top()); + let max_scroll = f64::from((menu.scroll_height() - menu.client_height()).max(0)); + let next = (current + event.delta_y()).clamp(0.0, max_scroll); + menu.set_scroll_top(next.round() as i32); +} + +fn hovered_block_from_target(target: web_sys::EventTarget) -> Option { + let root = editor_root_element()?; + let element = target_element(target)?; + + if element + .closest(HANDLE_SHELL_SELECTOR) + .ok() + .flatten() + .is_some() + { + return None; + } + + let block = direct_block_from_element(element, &root)?; + let index = top_level_block_index(&root, &block)?; + block_state_from_index(index) +} + +fn hovered_block_from_selection() -> Option { + let selection = window().and_then(|win| win.get_selection().ok().flatten())?; + let anchor_node = selection.anchor_node()?; + let element = anchor_node + .dyn_ref::() + .cloned() + .or_else(|| anchor_node.parent_element())?; + let root = editor_root_element()?; + let block = direct_block_from_element(element, &root)?; + let index = top_level_block_index(&root, &block)?; + block_state_from_index(index) +} + +fn block_state_from_index(index: usize) -> Option { + let root = editor_root_element()?; + let stage = editor_stage_element()?; + let block = root.children().item(index as u32)?; + let block_rect = block.get_bounding_client_rect(); + let stage_rect = stage.get_bounding_client_rect(); + let block_height = if block_rect.height() > 0.0 { + block_rect.height() + } else { + 28.0 + }; + + Some(HoveredBlockState { + index, + label: block_label_for_element(&block), + top: block_rect.top() - stage_rect.top(), + height: block_height, + }) +} + +fn prosemirror_node_size(node: &Value) -> Option { + match node.get("type").and_then(Value::as_str) { + Some("text") => Some( + node.get("text") + .and_then(Value::as_str) + .map(|text| text.encode_utf16().count() as u32) + .unwrap_or(0), + ), + Some("hardBreak") | Some("horizontalRule") => Some(1), + _ => { + let Some(children) = node.get("content").and_then(Value::as_array) else { + return Some(1); + }; + + let content_size = children.iter().try_fold(0_u32, |acc, child| { + prosemirror_node_size(child).map(|size| acc + size) + })?; + Some(content_size + 2) + } + } +} + +fn nested_edge_child_size(node: &Value, at_start: bool) -> Option { + let outer = node + .get("content") + .and_then(Value::as_array) + .and_then(|children| { + if at_start { + children.first() + } else { + children.last() + } + })?; + let inner = outer + .get("content") + .and_then(Value::as_array) + .and_then(|children| { + if at_start { + children.first() + } else { + children.last() + } + })?; + prosemirror_node_size(inner) +} + +fn top_level_block_range(document: &Value, index: usize) -> Option { + let content = document.get("content").and_then(Value::as_array)?; + let mut position = 0_u32; + + for (current_index, node) in content.iter().enumerate() { + let node_size = prosemirror_node_size(node)?; + if current_index == index { + let from = position + nested_edge_child_size(node, true).unwrap_or(1); + let mut to = position + + node_size.saturating_sub(nested_edge_child_size(node, false).unwrap_or(1)); + if to < from { + to = from; + } + return Some(TiptapRange { from, to }); + } + position += node_size; + } + + None +} + +fn node_is_within_root(node: Node, root: &Element) -> bool { + let mut current = Some(node); + while let Some(node) = current { + if node.is_same_node(Some(root)) { + return true; + } + current = node.parent_node(); + } + false +} + +fn active_editor_text_selection() -> Option { + let selection = window().and_then(|win| win.get_selection().ok().flatten())?; + if selection.is_collapsed() { + return None; + } + + let root = editor_root_element()?; + let anchor_inside = selection + .anchor_node() + .map(|node| node_is_within_root(node, &root)) + .unwrap_or(false); + let focus_inside = selection + .focus_node() + .map(|node| node_is_within_root(node, &root)) + .unwrap_or(false); + + if anchor_inside || focus_inside { + Some(selection) + } else { + None + } +} + +fn floating_toolbar_anchor_from_selection() -> Option { + let selection = active_editor_text_selection()?; + let range = selection.get_range_at(0).ok()?; + let rect = range.get_bounding_client_rect(); + if rect.width() <= 0.0 && rect.height() <= 0.0 { + return None; + } + + let stage = editor_stage_element()?; + let stage_rect = stage.get_bounding_client_rect(); + + Some(FloatingToolbarAnchor { + top: (rect.top() - stage_rect.top()).max(60.0), + left: rect.left() + (rect.width() / 2.0) - stage_rect.left(), + }) +} + +fn hover_anchor_top(block: &HoveredBlockState) -> f64 { + if block.height > HANDLE_MULTILINE_HEIGHT { + block.top + 12.0 + } else { + block.top + (block.height / 2.0) + } +} + +fn hover_anchor_transform(block: &HoveredBlockState) -> &'static str { + if block.height > HANDLE_MULTILINE_HEIGHT { + "translateY(0)" + } else { + "translateY(-50%)" + } +} + +fn pointer_in_handle_corridor(client_x: i32, client_y: i32, block: &HoveredBlockState) -> bool { + let Some(stage) = editor_stage_element() else { + return false; + }; + let stage_rect = stage.get_bounding_client_rect(); + let x = f64::from(client_x) - stage_rect.left(); + let y = f64::from(client_y) - stage_rect.top(); + let block_top = block.top; + let block_bottom = block.top + block.height; + let corridor_left = handle_lane_left(stage_rect.width()); + let corridor_right = corridor_left + handle_corridor_width(stage_rect.width()); + + x >= corridor_left + && x <= corridor_right + && y >= block_top - 8.0 + && y <= block_bottom + 8.0 +} + +fn block_menu_layout(block: &HoveredBlockState) -> Option { + let stage = editor_stage_element()?; + let stage_rect = stage.get_bounding_client_rect(); + let anchor_top = hover_anchor_top(block); + let stage_padding = 18.0; + let space_above = (anchor_top - stage_padding).max(0.0); + let space_below = (stage_rect.height() - anchor_top - stage_padding).max(0.0); + let open_upward = space_below < 340.0 && space_above > space_below; + let available_height = if open_upward { + space_above + } else { + space_below + }; + let max_height = if available_height >= 220.0 { + available_height + } else { + available_height.max(160.0) + }; + + Some(BlockMenuLayout { + max_height, + open_upward, + }) +} + +fn drop_indicator_from_target( + target: web_sys::EventTarget, + client_y: i32, +) -> Option { + let hovered = hovered_block_from_target(target)?; + let root = editor_root_element()?; + let block = root.children().item(hovered.index as u32)?; + let stage = editor_stage_element()?; + let block_rect = block.get_bounding_client_rect(); + let stage_rect = stage.get_bounding_client_rect(); + let midpoint = block_rect.top() + (block_rect.height() / 2.0); + let placement = if f64::from(client_y) <= midpoint { + DropPlacement::Before + } else { + DropPlacement::After + }; + let top = match placement { + DropPlacement::Before => block_rect.top() - stage_rect.top(), + DropPlacement::After => block_rect.bottom() - stage_rect.top(), + }; + + Some(DropIndicatorState { + index: hovered.index, + top, + placement, + }) +} + +fn drop_indicator_from_point(client_x: i32, client_y: i32) -> Option { + let target = window() + .and_then(|win| win.document()) + .and_then(|document| document.element_from_point(client_x as f32, client_y as f32))?; + let target: web_sys::EventTarget = target.into(); + drop_indicator_from_target(target, client_y) +} + +fn document_content_mut(document: &mut Value) -> Result<&mut Vec, String> { + document + .get_mut("content") + .and_then(Value::as_array_mut) + .ok_or_else(|| "文档 JSON 缺少顶层 content 数组".to_string()) +} + +fn node_with_attrs( + type_name: &str, + attrs: Option>, + content: Vec, +) -> Value { + let mut node = Map::new(); + node.insert("type".to_string(), Value::String(type_name.to_string())); + if let Some(attrs) = attrs.filter(|attrs| !attrs.is_empty()) { + node.insert("attrs".to_string(), Value::Object(attrs)); + } + if !content.is_empty() { + node.insert("content".to_string(), Value::Array(content)); + } + Value::Object(node) +} + +fn paragraph_node(content: Vec) -> Value { + node_with_attrs("paragraph", None, content) +} + +fn list_item_node(content: Vec) -> Value { + node_with_attrs("listItem", None, vec![paragraph_node(content)]) +} + +fn task_item_node(content: Vec) -> Value { + let mut attrs = Map::new(); + attrs.insert("checked".to_string(), Value::Bool(false)); + node_with_attrs("taskItem", Some(attrs), vec![paragraph_node(content)]) +} + +fn collect_plain_text(node: &Value) -> String { + match node.get("type").and_then(Value::as_str) { + Some("text") => node + .get("text") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + Some("hardBreak") => "\n".to_string(), + _ => node + .get("content") + .and_then(Value::as_array) + .map(|children| { + children + .iter() + .map(collect_plain_text) + .collect::>() + .join("") + }) + .unwrap_or_default(), + } +} + +fn inline_from_first_child(children: &[Value]) -> Vec { + children + .first() + .map(extract_inline_content) + .unwrap_or_default() +} + +fn extract_inline_content(node: &Value) -> Vec { + match node.get("type").and_then(Value::as_str) { + Some("paragraph") | Some("heading") => node + .get("content") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(), + Some("blockquote") => node + .get("content") + .and_then(Value::as_array) + .map(|children| inline_from_first_child(children)) + .unwrap_or_default(), + Some("bulletList") | Some("orderedList") | Some("taskList") => node + .get("content") + .and_then(Value::as_array) + .and_then(|items| items.first()) + .and_then(|item| item.get("content")) + .and_then(Value::as_array) + .map(|children| inline_from_first_child(children)) + .unwrap_or_default(), + Some("codeBlock") => { + let text = collect_plain_text(node); + if text.is_empty() { + Vec::new() + } else { + vec![json!({"type": "text", "text": text})] + } + } + Some("horizontalRule") => Vec::new(), + _ => node + .get("content") + .and_then(Value::as_array) + .map(|children| { + children + .iter() + .flat_map(extract_inline_content) + .collect::>() + }) + .unwrap_or_default(), + } +} + +fn turn_into_block(node: &Value, action: SlashActionKind) -> Value { + let inline = extract_inline_content(node); + match action { + SlashActionKind::Paragraph => paragraph_node(inline), + SlashActionKind::Heading1 => { + let mut attrs = Map::new(); + attrs.insert("level".to_string(), json!(1)); + node_with_attrs("heading", Some(attrs), inline) + } + SlashActionKind::Heading2 => { + let mut attrs = Map::new(); + attrs.insert("level".to_string(), json!(2)); + node_with_attrs("heading", Some(attrs), inline) + } + SlashActionKind::Heading3 => { + let mut attrs = Map::new(); + attrs.insert("level".to_string(), json!(3)); + node_with_attrs("heading", Some(attrs), inline) + } + SlashActionKind::BulletList => { + node_with_attrs("bulletList", None, vec![list_item_node(inline)]) + } + SlashActionKind::OrderedList => { + node_with_attrs("orderedList", None, vec![list_item_node(inline)]) + } + SlashActionKind::Todo => node_with_attrs("taskList", None, vec![task_item_node(inline)]), + SlashActionKind::Quote => node_with_attrs("blockquote", None, vec![paragraph_node(inline)]), + SlashActionKind::CodeBlock => { + let text = collect_plain_text(node); + let mut attrs = Map::new(); + attrs.insert("language".to_string(), Value::String("rust".to_string())); + let content = if text.is_empty() { + Vec::new() + } else { + vec![json!({"type": "text", "text": text})] + }; + node_with_attrs("codeBlock", Some(attrs), content) + } + SlashActionKind::Divider => node_with_attrs("horizontalRule", None, Vec::new()), + } +} + +fn duplicate_top_level_block(document: &mut Value, index: usize) -> Result<(), String> { + let content = document_content_mut(document)?; + let block = content + .get(index) + .cloned() + .ok_or_else(|| format!("找不到第 {index} 个块"))?; + content.insert(index + 1, block); + Ok(()) +} + +fn delete_top_level_block(document: &mut Value, index: usize) -> Result<(), String> { + let content = document_content_mut(document)?; + if index >= content.len() { + return Err(format!("找不到第 {index} 个块")); + } + + if content.len() == 1 { + content[0] = paragraph_node(Vec::new()); + return Ok(()); + } + + content.remove(index); + Ok(()) +} + +fn reorder_top_level_block( + document: &mut Value, + source: usize, + target: usize, + placement: DropPlacement, +) -> Result<(), String> { + let content = document_content_mut(document)?; + if source >= content.len() || target >= content.len() { + return Err("拖拽目标超出当前顶层块范围".to_string()); + } + + let block = content.remove(source); + let mut insert_at = match placement { + DropPlacement::Before => target, + DropPlacement::After => target + 1, + }; + + if source < insert_at { + insert_at = insert_at.saturating_sub(1); + } + + if insert_at > content.len() { + insert_at = content.len(); + } + + content.insert(insert_at, block); + Ok(()) +} + +fn replace_top_level_block_kind( + document: &mut Value, + index: usize, + action: SlashActionKind, +) -> Result<(), String> { + let content = document_content_mut(document)?; + let next = turn_into_block( + content + .get(index) + .ok_or_else(|| format!("找不到第 {index} 个块"))?, + action, + ); + content[index] = next; + Ok(()) +} + +fn has_active_text_selection() -> bool { + active_editor_text_selection().is_some() +} + +fn toolbar_overlay_locked( + turn_into_open: bool, + color_menu_open: bool, + more_menu_open: bool, +) -> bool { + turn_into_open || color_menu_open || more_menu_open +} + +fn sync_text_selection_overlay( + set_text_selection_active: WriteSignal, + set_floating_toolbar_anchor: WriteSignal>, +) -> bool { + let toolbar_anchor = floating_toolbar_anchor_from_selection(); + let has_text_selection = toolbar_anchor.is_some(); + set_text_selection_active.set(has_text_selection); + set_floating_toolbar_anchor.set(toolbar_anchor); + has_text_selection +} + +fn sync_editor_overlay_state( + set_editor_focused: WriteSignal, + set_text_selection_active: WriteSignal, + set_floating_toolbar_anchor: WriteSignal>, + set_slash_open: WriteSignal, + set_turn_into_open: WriteSignal, + set_hovered_block: WriteSignal>, + set_block_menu_anchor: WriteSignal>, + set_block_menu_open: WriteSignal, +) { + let focused = active_editor_stage(); + set_editor_focused.set(focused); + let has_text_selection = + sync_text_selection_overlay(set_text_selection_active, set_floating_toolbar_anchor); + + if focused && has_text_selection { + set_slash_open.set(false); + set_turn_into_open.set(false); + set_block_menu_open.set(false); + set_block_menu_anchor.set(None); + set_hovered_block.set(None); + } +} + +fn try_sync_editor_overlay_state( + set_editor_focused: WriteSignal, + set_text_selection_active: WriteSignal, + set_floating_toolbar_anchor: WriteSignal>, + set_slash_open: WriteSignal, + set_turn_into_open: WriteSignal, + set_hovered_block: WriteSignal>, + set_block_menu_anchor: WriteSignal>, + set_block_menu_open: WriteSignal, +) -> bool { + let focused = active_editor_stage(); + if set_editor_focused.try_set(focused).is_none() { + return false; + } + + let toolbar_anchor = floating_toolbar_anchor_from_selection(); + let has_text_selection = toolbar_anchor.is_some(); + if set_text_selection_active + .try_set(has_text_selection) + .is_none() + { + return false; + } + if set_floating_toolbar_anchor + .try_set(toolbar_anchor) + .is_none() + { + return false; + } + + if focused && has_text_selection { + if set_slash_open.try_set(false).is_none() { + return false; + } + if set_turn_into_open.try_set(false).is_none() { + return false; + } + if set_block_menu_open.try_set(false).is_none() { + return false; + } + if set_block_menu_anchor.try_set(None).is_none() { + return false; + } + if set_hovered_block.try_set(None).is_none() { + return false; + } + } + + true +} + +fn apply_document_update( + editor: TiptapEditorHandle, + persisted_identity: &PersistedDocumentIdentity, + next_document: Value, + set_dirty_count: WriteSignal, + set_html_output: WriteSignal, + set_document_json: WriteSignal, + set_json_output: WriteSignal, + title: ReadSignal, + set_command_feedback: WriteSignal, + success_message: impl Into, +) { + let success_message = success_message.into(); + let next_payload = next_document + .get("content") + .and_then(Value::as_array) + .cloned() + .map(Value::Array) + .unwrap_or_else(|| next_document.clone()); + match editor.set_content(TiptapContent::json(next_payload)) { + Ok(()) => { + set_dirty_count.update(|count| *count += 1); + let (html, snapshot, json_text) = read_editor_snapshot(editor); + set_html_output.set(html.clone()); + set_document_json.set(snapshot.clone()); + set_json_output.set(json_text); + match persist_document_state(persisted_identity, &title.get_untracked(), &snapshot, Some(html)) { + Ok(()) => { + set_command_feedback.set(format!("{success_message},并已写入本地草稿")); + } + Err(err) => { + set_command_feedback.set(format!("{success_message},但本地保存失败:{err}")); + } + } + } + Err(err) => { + set_command_feedback.set(format!("更新文档失败:{err}")); + } + } +} + +fn apply_html_update( + editor: TiptapEditorHandle, + persisted_identity: &PersistedDocumentIdentity, + next_html: String, + set_dirty_count: WriteSignal, + set_html_output: WriteSignal, + set_document_json: WriteSignal, + set_json_output: WriteSignal, + title: ReadSignal, + set_command_feedback: WriteSignal, + success_message: impl Into, +) { + let success_message = success_message.into(); + match editor.set_content(TiptapContent::html(next_html)) { + Ok(()) => { + set_dirty_count.update(|count| *count += 1); + let (html, snapshot, json_text) = read_editor_snapshot(editor); + set_html_output.set(html.clone()); + set_document_json.set(snapshot.clone()); + set_json_output.set(json_text); + match persist_document_state(persisted_identity, &title.get_untracked(), &snapshot, Some(html)) { + Ok(()) => { + set_command_feedback.set(format!("{success_message},并已写入本地草稿")); + } + Err(err) => { + set_command_feedback.set(format!("{success_message},但本地保存失败:{err}")); + } + } + } + Err(err) => { + set_command_feedback.set(format!("更新文档失败:{err}")); + } + } +} + +fn duplicate_top_level_block_html(current_html: &str, index: usize) -> Result { + let document = window() + .and_then(|win| win.document()) + .ok_or_else(|| "浏览器 document 不可用".to_string())?; + let container = document + .create_element("div") + .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; + container.set_inner_html(current_html); + + let children = container.children(); + let current = children + .item(index as u32) + .ok_or_else(|| format!("找不到第 {index} 个 HTML 顶层块"))?; + let cloned = current + .clone_node_with_deep(true) + .map_err(|err| format!("复制 HTML 块失败:{err:?}"))? + .dyn_into::() + .map_err(|_| "复制出的节点不是 Element".to_string())?; + + if let Some(next_sibling) = children.item(index as u32 + 1) { + container + .insert_before(&cloned, Some(&next_sibling)) + .map_err(|err| format!("插入复制块失败:{err:?}"))?; + } else { + container + .append_child(&cloned) + .map_err(|err| format!("追加复制块失败:{err:?}"))?; + } + + Ok(container.inner_html()) +} + +fn insert_top_level_paragraph_after_html( + current_html: &str, + index: usize, +) -> Result { + let document = window() + .and_then(|win| win.document()) + .ok_or_else(|| "浏览器 document 不可用".to_string())?; + let container = document + .create_element("div") + .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; + container.set_inner_html(current_html); + + let children = container.children(); + children + .item(index as u32) + .ok_or_else(|| format!("找不到第 {index} 个 HTML 顶层块"))?; + let paragraph = document + .create_element("p") + .map_err(|err| format!("创建空段落失败:{err:?}"))?; + + if let Some(next_sibling) = children.item(index as u32 + 1) { + container + .insert_before(¶graph, Some(&next_sibling)) + .map_err(|err| format!("插入新块失败:{err:?}"))?; + } else { + container + .append_child(¶graph) + .map_err(|err| format!("追加新块失败:{err:?}"))?; + } + + Ok(container.inner_html()) +} + +fn delete_top_level_block_html(current_html: &str, index: usize) -> Result { + let document = window() + .and_then(|win| win.document()) + .ok_or_else(|| "浏览器 document 不可用".to_string())?; + let container = document + .create_element("div") + .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; + container.set_inner_html(current_html); + + let children = container.children(); + if children.length() <= 1 { + container.set_inner_html("

"); + return Ok(container.inner_html()); + } + + let current = children + .item(index as u32) + .ok_or_else(|| format!("找不到第 {index} 个 HTML 顶层块"))?; + container + .remove_child(¤t) + .map_err(|err| format!("删除 HTML 块失败:{err:?}"))?; + Ok(container.inner_html()) +} + +fn reorder_top_level_block_html( + current_html: &str, + source: usize, + target: usize, + placement: DropPlacement, +) -> Result { + let document = window() + .and_then(|win| win.document()) + .ok_or_else(|| "浏览器 document 不可用".to_string())?; + let container = document + .create_element("div") + .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; + container.set_inner_html(current_html); + + let initial_children = container.children(); + let block_count = initial_children.length() as usize; + if source >= block_count || target >= block_count { + return Err("拖拽目标超出当前顶层块范围".to_string()); + } + + let current = initial_children + .item(source as u32) + .ok_or_else(|| format!("找不到第 {source} 个 HTML 顶层块"))?; + let moving = current + .clone_node_with_deep(true) + .map_err(|err| format!("复制拖拽块失败:{err:?}"))? + .dyn_into::() + .map_err(|_| "复制出的拖拽块不是 Element".to_string())?; + + container + .remove_child(¤t) + .map_err(|err| format!("移除原始拖拽块失败:{err:?}"))?; + + let mut insert_at = match placement { + DropPlacement::Before => target, + DropPlacement::After => target + 1, + }; + if source < insert_at { + insert_at = insert_at.saturating_sub(1); + } + + let current_children = container.children(); + let current_len = current_children.length() as usize; + if insert_at >= current_len { + container + .append_child(&moving) + .map_err(|err| format!("追加拖拽块失败:{err:?}"))?; + } else { + let next_sibling = current_children + .item(insert_at as u32) + .ok_or_else(|| format!("找不到第 {insert_at} 个 HTML 插入位置"))?; + container + .insert_before(&moving, Some(&next_sibling)) + .map_err(|err| format!("插入拖拽块失败:{err:?}"))?; + } + + Ok(container.inner_html()) +} + +fn p0_extensions() -> Vec { + vec![ + TiptapExtension::Document, + TiptapExtension::Dropcursor, + TiptapExtension::Gapcursor, + TiptapExtension::Text, + TiptapExtension::Paragraph, + TiptapExtension::Heading, + TiptapExtension::Bold, + TiptapExtension::Italic, + TiptapExtension::Strike, + TiptapExtension::Code, + TiptapExtension::Blockquote, + TiptapExtension::BulletList, + TiptapExtension::OrderedList, + TiptapExtension::ListItem, + TiptapExtension::TaskItem, + TiptapExtension::TaskList, + TiptapExtension::CodeBlock, + TiptapExtension::HorizontalRule, + TiptapExtension::History, + TiptapExtension::Underline, + TiptapExtension::TextStyle, + TiptapExtension::TextAlign, + TiptapExtension::Highlight, + TiptapExtension::Link, + TiptapExtension::Placeholder, + ] +} + +fn active_editor_stage() -> bool { + let active_element_inside_stage = window() + .and_then(|win| win.document()) + .and_then(|document| document.active_element()) + .and_then(|element| element.closest(EDITOR_STAGE_SELECTOR).ok().flatten()) + .is_some(); + + if active_element_inside_stage { + return true; + } + + let Some(root) = editor_root_element() else { + return false; + }; + let Some(selection) = window().and_then(|win| win.get_selection().ok().flatten()) else { + return false; + }; + + let anchor_inside = selection + .anchor_node() + .map(|node| node_is_within_root(node, &root)) + .unwrap_or(false); + let focus_inside = selection + .focus_node() + .map(|node| node_is_within_root(node, &root)) + .unwrap_or(false); + + anchor_inside || focus_inside +} + +fn selection_summary(selection: &TiptapSelectionState) -> String { + let block = if selection.h1 { + "一级标题" + } else if selection.h2 { + "二级标题" + } else if selection.h3 { + "三级标题" + } else if selection.task_list { + "Todo 列表" + } else if selection.ordered_list { + "有序列表" + } else if selection.bullet_list { + "无序列表" + } else if selection.blockquote { + "引用块" + } else if selection.paragraph { + "段落" + } else { + "未定位" + }; + + let mut marks = Vec::new(); + if selection.bold { + marks.push("Bold"); + } + if selection.italic { + marks.push("Italic"); + } + if selection.underline { + marks.push("Underline"); + } + if selection.strike { + marks.push("Strike"); + } + if selection.highlight { + marks.push("Highlight"); + } + if selection.text_style { + marks.push("Color"); + } + if selection.link { + marks.push("Link"); + } + + let mark_text = if marks.is_empty() { + "无行内样式".to_string() + } else { + marks.join(" / ") + }; + + format!("当前块:{block} | 行内样式:{mark_text}") +} + +fn current_block_info_from_index(index: Option) -> CurrentBlockInfo { + index + .map(|value| CurrentBlockInfo { + index: Some(value), + block_id: runtime_block_id_from_index(value), + }) + .unwrap_or(CurrentBlockInfo { + index: None, + block_id: None, + }) +} + +fn selection_payload( + selection: &TiptapSelectionState, + editor_focused: bool, + current_block_index: Option, +) -> SelectionPayload { + SelectionPayload { + selection: selection.clone(), + summary: selection_summary(selection), + editor_focused, + current_block_index, + current_block_id: current_block_index.and_then(runtime_block_id_from_index), + } +} + +fn state_payload( + document_id: Option, + workspace_id: Option, + title: String, + dirty_count: u32, + hovered_block: Option, + editor_focused: bool, + slash_open: bool, + turn_into_open: bool, + color_menu_open: bool, + more_menu_open: bool, + read_only: bool, +) -> StatePayload { + let toolbar_open = toolbar_overlay_locked(turn_into_open, color_menu_open, more_menu_open); + StatePayload { + document_id, + workspace_id, + title, + dirty_count, + selected_block_index: hovered_block.as_ref().map(|block| block.index), + editor_focused, + slash_open, + toolbar_open, + read_only, + } +} + +fn status_payload( + document_id: Option, + workspace_id: Option, + title: String, + dirty_count: u32, + hovered_block: Option, + editor_focused: bool, + slash_open: bool, + turn_into_open: bool, + color_menu_open: bool, + more_menu_open: bool, + read_only: bool, +) -> HostStatusPayload { + let current_block_index = hovered_block.as_ref().map(|block| block.index); + let current_block_id = current_block_index.and_then(runtime_block_id_from_index); + HostStatusPayload { + document_id, + workspace_id, + title, + dirty_count, + selected_block_index: current_block_index, + current_block_id, + editor_focused, + read_only, + slash_open, + toolbar_open: toolbar_overlay_locked(turn_into_open, color_menu_open, more_menu_open), + } +} + +fn dispatch_runtime_state( + document_id: Option, + workspace_id: Option, + title: String, + dirty_count: u32, + hovered_block: Option, + editor_focused: bool, + slash_open: bool, + turn_into_open: bool, + color_menu_open: bool, + more_menu_open: bool, + read_only: bool, +) { + let state = state_payload( + document_id.clone(), + workspace_id.clone(), + title.clone(), + dirty_count, + hovered_block.clone(), + editor_focused, + slash_open, + turn_into_open, + color_menu_open, + more_menu_open, + read_only, + ); + dispatch_state_event(&state); + dispatch_status_event(&status_payload( + document_id, + workspace_id, + title, + dirty_count, + hovered_block, + editor_focused, + slash_open, + turn_into_open, + color_menu_open, + more_menu_open, + read_only, + )); +} + +fn send_selection_state( + selection: &TiptapSelectionState, + editor_focused: bool, + current_block_index: Option, +) { + dispatch_selection_event(&selection_payload( + selection, + editor_focused, + current_block_index, + )); +} + +fn apply_host_document_payload( + editor: TiptapEditorHandle, + payload: HostDocumentPayload, + set_document_id: WriteSignal>, + set_workspace_id: WriteSignal>, + set_title: WriteSignal, + set_read_only: WriteSignal, + set_revision: WriteSignal>, + set_conflict_detection_key: WriteSignal>, + set_dirty_count: WriteSignal, + set_html_output: WriteSignal, + set_document_json: WriteSignal, + set_json_output: WriteSignal, + set_command_feedback: WriteSignal, +) { + let next_document_id = payload.document_id.clone(); + let next_workspace_id = payload.workspace_id.clone(); + let next_title = payload.title.clone(); + let next_revision = payload.revision; + let next_conflict_detection_key = payload.conflict_detection_key.clone(); + let next_read_only = payload.read_only.unwrap_or(false); + + set_document_id.set(next_document_id); + set_workspace_id.set(next_workspace_id); + if let Some(next_title_value) = next_title { + set_title.set(next_title_value); + } + set_read_only.set(next_read_only); + set_revision.set(next_revision); + set_conflict_detection_key.set(next_conflict_detection_key.clone()); + + if let Some(content) = payload.content { + let next_content = TiptapContent::json(content); + match editor.set_content(next_content) { + Ok(()) => { + let _snapshot = sync_editor_outputs( + editor, + set_html_output, + set_document_json, + set_json_output, + ); + set_dirty_count.set(0); + set_command_feedback.set("宿主文档已同步到编辑器".to_string()); + } + Err(err) => { + set_command_feedback.set(format!("宿主文档同步失败:{err}")); + } + } + } +} + +fn bridge_ready_payload() -> ReadyPayload { + ReadyPayload { + runtime_name: RUNTIME_NAME, + selectors: BridgeSelectorsPayload { + root: "[data-testid=\"mnote-leptos-tiptap-host\"]", + stage: "[data-testid=\"mnote-leptos-tiptap-editor-stage\"]", + editor: "[data-testid=\"mnote-leptos-tiptap-editor-root\"]", + toolbar: "[data-testid=\"mnote-leptos-tiptap-toolbar\"]", + slash_menu: "[data-testid=\"mnote-leptos-tiptap-slash-menu\"]", + handle: "[data-testid=\"mnote-leptos-tiptap-handle\"]", + }, + supported_commands: vec![ + "replaceContent", + "setPageOptions", + "setEditable", + "undo", + "redo", + "focus", + "requestCurrentBlockId", + ], + supports_embedded_mode: true, + } +} + +fn selection_has_rich_marks(selection: &TiptapSelectionState) -> bool { + selection.bold + || selection.italic + || selection.underline + || selection.strike + || selection.highlight + || selection.text_style + || selection.link +} + +fn apply_text_color(editor: TiptapEditorHandle, color: &str) -> Result<&'static str, String> { + editor + .set_color(TiptapColorAttributes { + color: color.to_string(), + }) + .map(|_| "已更新文字颜色") + .map_err(|err| format!("命令执行失败:{err}")) +} + +fn clear_text_color(editor: TiptapEditorHandle) -> Result<&'static str, String> { + editor + .unset_color() + .map(|_| "已清除文字颜色") + .map_err(|err| format!("命令执行失败:{err}")) +} + +fn apply_highlight_color( + editor: TiptapEditorHandle, + color: Option<&str>, +) -> Result<&'static str, String> { + match color { + Some(color) => editor + .set_highlight(Some(TiptapHighlightAttributes { + color: Some(color.to_string()), + })) + .map(|_| "已更新背景色") + .map_err(|err| format!("命令执行失败:{err}")), + None => editor + .unset_highlight() + .map(|_| "已清除背景色") + .map_err(|err| format!("命令执行失败:{err}")), + } +} + +fn apply_text_align( + editor: TiptapEditorHandle, + alignment: TiptapTextAlign, +) -> Result<&'static str, String> { + let message = match alignment { + TiptapTextAlign::Left => "已切到左对齐", + TiptapTextAlign::Center => "已切到居中", + TiptapTextAlign::Right => "已切到右对齐", + TiptapTextAlign::Justify => "已切到两端对齐", + }; + editor + .set_text_align(alignment) + .map(|_| message) + .map_err(|err| format!("命令执行失败:{err}")) +} + +fn run_slash_action( + editor: TiptapEditorHandle, + action: SlashActionKind, +) -> Result<&'static str, String> { + let result = match action { + SlashActionKind::Paragraph => editor.set_paragraph(), + SlashActionKind::Heading1 => editor.toggle_heading(TiptapHeadingLevel::H1), + SlashActionKind::Heading2 => editor.toggle_heading(TiptapHeadingLevel::H2), + SlashActionKind::Heading3 => editor.toggle_heading(TiptapHeadingLevel::H3), + SlashActionKind::BulletList => editor.toggle_bullet_list(), + SlashActionKind::OrderedList => editor.toggle_ordered_list(), + SlashActionKind::Todo => editor.toggle_task_list(), + SlashActionKind::Quote => editor.toggle_blockquote(), + SlashActionKind::CodeBlock => editor.toggle_code_block(Some(TiptapCodeBlockAttributes { + language: Some("rust".into()), + })), + SlashActionKind::Divider => editor.set_horizontal_rule(), + }; + + result + .map(|_| match action { + SlashActionKind::Paragraph => "已切到段落", + SlashActionKind::Heading1 => "已切到一级标题", + SlashActionKind::Heading2 => "已切到二级标题", + SlashActionKind::Heading3 => "已切到三级标题", + SlashActionKind::BulletList => "已切到无序列表", + SlashActionKind::OrderedList => "已切到有序列表", + SlashActionKind::Todo => "已切到 Todo 列表", + SlashActionKind::Quote => "已切到引用块", + SlashActionKind::CodeBlock => "已切到代码块", + SlashActionKind::Divider => "已插入分割线", + }) + .map_err(|err| format!("命令执行失败:{err}")) +} + +fn run_block_turn_into_action( + editor: TiptapEditorHandle, + block_index: usize, + action: SlashActionKind, +) -> Result<&'static str, String> { + let document = editor + .get_json() + .map_err(|err| format!("读取当前 JSON 失败:{err}"))?; + let range = top_level_block_range(&document, block_index) + .ok_or_else(|| format!("找不到第 {} 个块的选择范围", block_index + 1))?; + + match action { + SlashActionKind::Divider => editor + .insert_content_at( + range, + TiptapContent::json(json!({ "type": "horizontalRule" })), + None, + ) + .map(|_| "已把当前块转成分割线") + .map_err(|err| format!("命令执行失败:{err}")), + _ => { + editor + .set_text_selection(range) + .map_err(|err| format!("选中当前块失败:{err}"))?; + editor + .clear_nodes() + .map_err(|err| format!("清理当前块样式失败:{err}"))?; + + let message = run_slash_action(editor, action)?; + let _ = editor.focus(); + let _ = editor.select_textblock_end(); + Ok(message) + } + } +} + +fn apply_feedback_result(setter: WriteSignal, result: Result<&'static str, E>) +where + E: Display, +{ + match result { + Ok(message) => setter.set(message.to_string()), + Err(err) => setter.set(format!("命令执行失败:{err}")), + } +} + +fn apply_ok_feedback( + setter: WriteSignal, + result: Result<(), E>, + ok_message: &'static str, +) where + E: Display, +{ + apply_feedback_result(setter, result.map(|_| ok_message)); +} + +fn normalize_layout_density(value: Option) -> String { + match value.as_deref() { + Some("compact") => "compact".to_string(), + Some("spacious") => "spacious".to_string(), + _ => "normal".to_string(), + } +} + +#[component] +fn App(mount_options: MountOptions) -> impl IntoView { + let editor = TiptapEditorHandle::new(); + let initial_document_id = mount_options + .document_id + .clone() + .or_else(current_document_id); + let initial_workspace_id = mount_options + .workspace_id + .clone() + .or_else(current_workspace_id); + let persisted_identity = resolve_persisted_document_identity( + initial_document_id.clone(), + initial_workspace_id.clone(), + ); + let persisted = load_persisted_document(&persisted_identity); + let restored_from_storage = persisted.is_some(); + let restored_html = persisted + .as_ref() + .and_then(|document| document.html.clone()); + let initial_title_value = mount_options + .title + .clone() + .or_else(|| { + persisted + .as_ref() + .map(|document| document.title.clone()) + }) + .unwrap_or_else(default_title); + let initial_editor_content = mount_options + .html + .clone() + .map(TiptapContent::html) + .or_else(|| { + mount_options + .content + .clone() + .map(TiptapContent::json) + }) + .or_else(|| { + persisted.as_ref().map(|document| { + document + .html + .clone() + .map(TiptapContent::html) + .unwrap_or_else(|| TiptapContent::json(document.content.clone())) + }) + }) + .unwrap_or_else(initial_content); + + let (document_id, set_document_id) = signal(initial_document_id); + let (workspace_id, set_workspace_id) = signal(initial_workspace_id); + let (title, set_title) = signal(initial_title_value); + let (read_only, set_read_only) = signal(mount_options.read_only.unwrap_or(false)); + let (revision, set_revision) = signal(mount_options.revision); + let (conflict_detection_key, set_conflict_detection_key) = + signal(mount_options.conflict_detection_key.clone()); + let (html_output, set_html_output) = signal(String::new()); + let (document_json, set_document_json) = signal( + persisted + .as_ref() + .map(|document| document.content.clone()) + .unwrap_or_else(|| json!({"type": "doc", "content": []})), + ); + let (json_output, set_json_output) = signal(String::new()); + let (selection_state, set_selection_state) = signal(TiptapSelectionState::default()); + let (dirty_count, set_dirty_count) = signal(0_u32); + let (editor_focused, set_editor_focused) = signal(false); + let (text_selection_active, set_text_selection_active) = signal(false); + let (floating_toolbar_anchor, set_floating_toolbar_anchor) = + signal(None::); + let (locked_toolbar_anchor, set_locked_toolbar_anchor) = signal(None::); + let (slash_open, set_slash_open) = signal(false); + let (slash_index, set_slash_index) = signal(0_usize); + let (turn_into_open, set_turn_into_open) = signal(false); + let (color_menu_open, set_color_menu_open) = signal(false); + let (more_menu_open, set_more_menu_open) = signal(false); + let (hovered_block, set_hovered_block) = signal(None::); + let (block_menu_anchor, set_block_menu_anchor) = signal(None::); + let (block_menu_open, set_block_menu_open) = signal(false); + let (block_turn_into_open, set_block_turn_into_open) = signal(false); + let (pending_drag, set_pending_drag) = signal(None::); + let (dragging_block_index, set_dragging_block_index) = signal(None::); + let (dragging_block_anchor, set_dragging_block_anchor) = signal(None::); + let (drop_indicator, set_drop_indicator) = signal(None::); + let (suppress_handle_click, set_suppress_handle_click) = signal(false); + let (command_feedback, set_command_feedback) = signal("等待第一次编辑".to_string()); + let initial_editable = mount_options.editable.unwrap_or(!read_only.get_untracked()); + let (editor_editable, set_editor_editable) = signal(initial_editable); + let initial_page_options = mount_options.page_options.clone(); + let (wide_layout, set_wide_layout) = + signal(initial_page_options.as_ref().and_then(|opts| opts.wide_layout).unwrap_or(false)); + let (small_text, set_small_text) = + signal(initial_page_options.as_ref().and_then(|opts| opts.small_text).unwrap_or(false)); + let (layout_density, set_layout_density) = signal(normalize_layout_density( + initial_page_options + .as_ref() + .and_then(|opts| opts.layout_density.clone()), + )); + let (show_heading_numbers, set_show_heading_numbers) = signal( + initial_page_options + .as_ref() + .and_then(|opts| opts.show_heading_numbers) + .unwrap_or(true), + ); + let (embed_default_block_id, set_embed_default_block_id) = signal( + initial_page_options + .as_ref() + .and_then(|opts| opts.embed_default_block_id.clone()), + ); + + { + let block_menu_open = block_menu_open; + Effect::new(move |_| { + let Some(document) = window().and_then(|win| win.document()) else { + return; + }; + let Some(body) = document.body() else { + return; + }; + + if block_menu_open.get() { + let _ = body.style().set_property("overflow", "hidden"); + } else { + let _ = body.style().remove_property("overflow"); + } + }); + } + + { + Effect::new(move |_| { + let Some(stage) = editor_stage_element() else { + return; + }; + let height = stage.get_bounding_client_rect().height(); + if height > 0.0 { + dispatch_runtime_event(HEIGHT_EVENT, &HeightPayload { height }); + } + }); + } + + { + let block_menu_open = block_menu_open; + let set_block_turn_into_open = set_block_turn_into_open; + Effect::new(move |_| { + if !block_menu_open.get() { + set_block_turn_into_open.set(false); + } + }); + } + + Effect::new({ + let editor = editor; + let set_document_id = set_document_id; + let set_workspace_id = set_workspace_id; + let set_title = set_title; + let set_read_only = set_read_only; + let set_revision = set_revision; + let set_conflict_detection_key = set_conflict_detection_key; + let set_dirty_count = set_dirty_count; + let set_html_output = set_html_output; + let set_document_json = set_document_json; + let set_json_output = set_json_output; + let set_command_feedback = set_command_feedback; + let set_editor_editable = set_editor_editable; + let set_wide_layout = set_wide_layout; + let set_small_text = set_small_text; + let set_layout_density = set_layout_density; + let set_show_heading_numbers = set_show_heading_numbers; + let set_embed_default_block_id = set_embed_default_block_id; + move |_| { + let command_listener = Closure::::wrap(Box::new(move |event: Event| { + let Some(custom_event) = event.dyn_ref::() else { + return; + }; + let detail = custom_event.detail(); + let Ok(envelope) = serde_wasm_bindgen::from_value::(detail) else { + return; + }; + if envelope.protocol.as_deref() != Some(PROTOCOL) { + return; + } + + let Some(command_kind) = HostCommandKind::from_payload(envelope.payload.as_ref().unwrap_or(&HostCommandPayload { + command: None, + document_id: None, + workspace_id: None, + title: None, + content: None, + editable: None, + page_options: None, + block_id: None, + block_index: None, + text: None, + reference_document_id: None, + reference_block_id: None, + current_block_id: None, + selection: None, + revision: None, + conflict_detection_key: None, + read_only: None, + })) else { + return; + }; + + let Some(payload) = envelope.payload else { + return; + }; + + match command_kind { + HostCommandKind::Undo => { + let _ = editor.undo(); + } + HostCommandKind::Redo => { + let _ = editor.redo(); + } + HostCommandKind::ReplaceContent | HostCommandKind::Bootstrap => { + apply_host_document_payload( + editor, + HostDocumentPayload { + document_id: payload.document_id, + workspace_id: payload.workspace_id, + title: payload.title, + content: payload.content, + revision: payload.revision, + conflict_detection_key: payload.conflict_detection_key, + read_only: payload.read_only.or(payload.editable.map(|editable| !editable)), + }, + set_document_id, + set_workspace_id, + set_title, + set_read_only, + set_revision, + set_conflict_detection_key, + set_dirty_count, + set_html_output, + set_document_json, + set_json_output, + set_command_feedback, + ); + } + HostCommandKind::SetEditable => { + let editable = payload.editable.unwrap_or(true); + set_editor_editable.set(editable); + set_read_only.set(!editable); + dispatch_runtime_state( + document_id.get_untracked(), + workspace_id.get_untracked(), + title.get_untracked(), + dirty_count.get_untracked(), + hovered_block.get_untracked(), + editor_focused.get_untracked(), + slash_open.get_untracked(), + turn_into_open.get_untracked(), + color_menu_open.get_untracked(), + more_menu_open.get_untracked(), + read_only.get_untracked(), + ); + } + HostCommandKind::SetPageOptions => { + if let Some(page_options) = payload.page_options { + if let Some(value) = page_options.wide_layout { + set_wide_layout.set(value); + } + if let Some(value) = page_options.small_text { + set_small_text.set(value); + } + set_layout_density + .set(normalize_layout_density(page_options.layout_density)); + if let Some(value) = page_options.show_heading_numbers { + set_show_heading_numbers.set(value); + } + set_embed_default_block_id.set(page_options.embed_default_block_id); + set_command_feedback.set("页面布局选项已同步".to_string()); + } + } + HostCommandKind::Focus => { + let _ = editor.focus(); + } + HostCommandKind::RequestCurrentBlockId => { + let current_block = current_block_info_from_index(hovered_block.get_untracked().map(|block| block.index)); + dispatch_status_event(&HostStatusPayload { + document_id: document_id.get_untracked(), + workspace_id: workspace_id.get_untracked(), + title: title.get_untracked(), + dirty_count: dirty_count.get_untracked(), + selected_block_index: current_block.index, + current_block_id: current_block.block_id, + editor_focused: editor_focused.get_untracked(), + read_only: read_only.get_untracked(), + slash_open: slash_open.get_untracked(), + toolbar_open: toolbar_overlay_locked( + turn_into_open.get_untracked(), + color_menu_open.get_untracked(), + more_menu_open.get_untracked(), + ), + }); + } + HostCommandKind::InsertInlineReference | HostCommandKind::InsertEmbedReference => { + let reference_text = match ( + payload.reference_document_id.or(payload.document_id), + payload.reference_block_id.or(payload.block_id), + ) { + (Some(document_id), Some(block_id)) => format!( + "[[引用 {}:{}]]", + document_id, + block_id + ), + (Some(document_id), None) => format!("[[引用 {}]]", document_id), + _ => "[[引用]]".to_string(), + }; + let node = if matches!(command_kind, HostCommandKind::InsertEmbedReference) { + json!({ + "type": "blockquote", + "content": [ + { + "type": "paragraph", + "content": [ + { "type": "text", "text": reference_text } + ] + } + ] + }) + } else { + json!({ + "type": "paragraph", + "content": [ + { "type": "text", "text": reference_text } + ] + }) + }; + let _ = editor.insert_content(TiptapContent::json(node), None); + } + } + })); + + if let Some(document) = window().and_then(|win| win.document()) { + let listener_ref = command_listener.as_ref().unchecked_ref(); + let _ = document.add_event_listener_with_callback(COMMAND_EVENT, listener_ref); + if let Some((mount_id, _, _)) = runtime_mount_context() { + let target: EventTarget = document.into(); + register_runtime_listener(mount_id, target, command_listener); + } + } + } + }); + + { + let turn_into_open = turn_into_open; + let color_menu_open = color_menu_open; + let more_menu_open = more_menu_open; + let set_locked_toolbar_anchor = set_locked_toolbar_anchor; + Effect::new(move |_| { + if !(turn_into_open.get() || color_menu_open.get() || more_menu_open.get()) { + set_locked_toolbar_anchor.set(None); + } + }); + } + + { + let editor_focused = editor_focused; + let text_selection_active = text_selection_active; + let slash_open = slash_open; + let block_menu_open = block_menu_open; + let turn_into_open = turn_into_open; + let color_menu_open = color_menu_open; + let more_menu_open = more_menu_open; + let set_turn_into_open = set_turn_into_open; + let set_color_menu_open = set_color_menu_open; + let set_more_menu_open = set_more_menu_open; + Effect::new(move |_| { + let toolbar_locked = toolbar_overlay_locked( + turn_into_open.get_untracked(), + color_menu_open.get_untracked(), + more_menu_open.get_untracked(), + ); + if ((!editor_focused.get() || !text_selection_active.get()) && !toolbar_locked) + || slash_open.get() + || block_menu_open.get() + { + set_turn_into_open.set(false); + set_color_menu_open.set(false); + set_more_menu_open.set(false); + } + }); + } + + { + let set_editor_focused = set_editor_focused; + let set_text_selection_active = set_text_selection_active; + let set_floating_toolbar_anchor = set_floating_toolbar_anchor; + let set_slash_open = set_slash_open; + let set_turn_into_open = set_turn_into_open; + let set_hovered_block = set_hovered_block; + let set_block_menu_anchor = set_block_menu_anchor; + let set_block_menu_open = set_block_menu_open; + let set_pending_drag = set_pending_drag; + let set_dragging_block_index = set_dragging_block_index; + let set_dragging_block_anchor = set_dragging_block_anchor; + let set_drop_indicator = set_drop_indicator; + let set_command_feedback = set_command_feedback; + let set_suppress_handle_click = set_suppress_handle_click; + let pending_drag = pending_drag; + let dragging_block_index = dragging_block_index; + let mouseup_handle = window_event_listener(ev::mouseup, move |event: MouseEvent| { + if let Some(source_index) = dragging_block_index.try_get_untracked().flatten() { + let indicator = drop_indicator_from_point(event.client_x(), event.client_y()); + if let Some(indicator) = indicator { + match editor.get_html() { + Ok(current_html) => match reorder_top_level_block_html( + ¤t_html, + source_index, + indicator.index, + indicator.placement, + ) { + Ok(next_html) => { + apply_html_update( + editor, + &persisted_identity, + next_html, + set_dirty_count, + set_html_output, + set_document_json, + set_json_output, + title, + set_command_feedback, + "已通过块手柄拖拽重排", + ); + } + Err(err) => { + set_command_feedback.set(err); + } + }, + Err(err) => { + let _ = set_command_feedback.try_set(format!("读取当前 HTML 失败:{err}")); + } + } + } else { + let _ = set_command_feedback.try_set("块拖拽已取消".to_string()); + } + let _ = set_dragging_block_index.try_set(None); + let _ = set_dragging_block_anchor.try_set(None); + let _ = set_drop_indicator.try_set(None); + let _ = set_pending_drag.try_set(None); + let _ = set_block_menu_open.try_set(false); + let _ = set_block_menu_anchor.try_set(None); + let _ = set_hovered_block.try_set(None); + let _ = set_suppress_handle_click.try_set(true); + } else if pending_drag.try_get_untracked().flatten().is_some() { + let _ = set_pending_drag.try_set(None); + } + + if let Some(target) = event.target() { + if let Some(element) = target_element(target) { + if element + .closest(&format!("{HANDLE_SHELL_SELECTOR}, .floating-toolbar")) + .ok() + .flatten() + .is_some() + { + return; + } + } + } + let _ = try_sync_editor_overlay_state( + set_editor_focused, + set_text_selection_active, + set_floating_toolbar_anchor, + set_slash_open, + set_turn_into_open, + set_hovered_block, + set_block_menu_anchor, + set_block_menu_open, + ); + }); + let keyup_handle = window_event_listener(ev::keyup, move |_| { + let _ = try_sync_editor_overlay_state( + set_editor_focused, + set_text_selection_active, + set_floating_toolbar_anchor, + set_slash_open, + set_turn_into_open, + set_hovered_block, + set_block_menu_anchor, + set_block_menu_open, + ); + }); + + on_cleanup(move || { + drop(mouseup_handle); + drop(keyup_handle); + }); + } + + { + let set_editor_focused = set_editor_focused; + let set_slash_open = set_slash_open; + let set_turn_into_open = set_turn_into_open; + let set_hovered_block = set_hovered_block; + let set_block_menu_anchor = set_block_menu_anchor; + let set_block_menu_open = set_block_menu_open; + let set_pending_drag = set_pending_drag; + let set_dragging_block_index = set_dragging_block_index; + let set_dragging_block_anchor = set_dragging_block_anchor; + let set_drop_indicator = set_drop_indicator; + let set_command_feedback = set_command_feedback; + let pending_drag = pending_drag; + let dragging_block_index = dragging_block_index; + let dragging_block_anchor = dragging_block_anchor; + let mousemove_handle = window_event_listener(ev::mousemove, move |event: MouseEvent| { + if dragging_block_index.try_get_untracked().flatten().is_some() { + let _ = set_editor_focused.try_set(true); + let _ = set_drop_indicator.try_set(drop_indicator_from_point( + event.client_x(), + event.client_y(), + )); + return; + } + + let Some(pending) = pending_drag.try_get_untracked().flatten() else { + return; + }; + + if event.buttons() & 1 == 0 { + let _ = set_pending_drag.try_set(None); + return; + } + + let dx = (event.client_x() - pending.start_x).abs(); + let dy = (event.client_y() - pending.start_y).abs(); + if dx < 4 && dy < 4 { + return; + } + + let _ = set_editor_focused.try_set(true); + let _ = set_slash_open.try_set(false); + let _ = set_turn_into_open.try_set(false); + let _ = set_block_menu_open.try_set(false); + let _ = set_block_menu_anchor.try_set(None); + let _ = set_hovered_block.try_set(Some(pending.anchor.clone())); + let _ = set_dragging_block_index.try_set(Some(pending.index)); + let next_anchor = dragging_block_anchor + .try_get_untracked() + .flatten() + .unwrap_or_else(|| pending.anchor.clone()); + let _ = set_dragging_block_anchor.try_set(Some(next_anchor)); + let _ = set_pending_drag.try_set(None); + let _ = set_drop_indicator.try_set(drop_indicator_from_point( + event.client_x(), + event.client_y(), + )); + let _ = set_command_feedback.try_set(format!("开始拖拽:{}", pending.anchor.label)); + }); + + on_cleanup(move || drop(mousemove_handle)); + } + + { + let editor = editor; + let set_slash_open = set_slash_open; + let slash_open = slash_open; + let slash_index = slash_index; + let set_slash_index = set_slash_index; + let set_turn_into_open = set_turn_into_open; + let set_block_menu_open = set_block_menu_open; + let set_block_menu_anchor = set_block_menu_anchor; + let set_command_feedback = set_command_feedback; + let keydown_handle = window_event_listener(ev::keydown, move |event| { + let focused = active_editor_stage(); + if !focused { + return; + } + + if event.key() == "Escape" { + let _ = set_slash_open.try_set(false); + let _ = set_turn_into_open.try_set(false); + let _ = set_block_menu_open.try_set(false); + let _ = set_block_menu_anchor.try_set(None); + return; + } + + if event.key() == "/" && !event.ctrl_key() && !event.meta_key() && !event.alt_key() { + event.prevent_default(); + let _ = set_slash_open.try_set(true); + let _ = set_turn_into_open.try_set(false); + let _ = set_block_menu_open.try_set(false); + let _ = set_block_menu_anchor.try_set(None); + let _ = set_slash_index.try_set(0); + let _ = set_command_feedback.try_set("Slash 菜单已打开".to_string()); + return; + } + + if !slash_open.try_get_untracked().unwrap_or(false) { + return; + } + + match event.key().as_str() { + "ArrowDown" => { + event.prevent_default(); + let next = (slash_index.try_get_untracked().unwrap_or(0) + 1) % SLASH_ACTIONS.len(); + let _ = set_slash_index.try_set(next); + } + "ArrowUp" => { + event.prevent_default(); + let current = slash_index.try_get_untracked().unwrap_or(0); + let next = if current == 0 { + SLASH_ACTIONS.len() - 1 + } else { + current - 1 + }; + let _ = set_slash_index.try_set(next); + } + "Enter" => { + event.prevent_default(); + let action = SLASH_ACTIONS[slash_index.try_get_untracked().unwrap_or(0)].kind; + match run_slash_action(editor, action) { + Ok(message) => { + let _ = set_command_feedback.try_set(message.to_string()); + } + Err(message) => { + let _ = set_command_feedback.try_set(message); + } + } + let _ = set_slash_open.try_set(false); + } + "Escape" => { + event.prevent_default(); + let _ = set_slash_open.try_set(false); + let _ = set_command_feedback.try_set("Slash 菜单已关闭".to_string()); + } + _ => {} + } + }); + on_cleanup(move || drop(keydown_handle)); + } + + let has_task_schema = move || { + let snapshot = json_output.get(); + snapshot.contains("\"taskList\"") && snapshot.contains("\"taskItem\"") + }; + + let selection_text = move || selection_summary(&selection_state.get()); + let is_embedded = is_embedded_mode(); + + let on_link_click = { + let editor = editor; + let selection_state = selection_state; + let set_command_feedback = set_command_feedback; + move |_| { + if selection_state.get().link { + apply_feedback_result( + set_command_feedback, + editor.unset_link().map(|_| "已移除链接"), + ); + return; + } + + let href = window() + .and_then(|win| win.prompt_with_message("输入链接地址").ok().flatten()) + .filter(|value| !value.trim().is_empty()); + + match href { + Some(value) => apply_feedback_result( + set_command_feedback, + editor + .set_link(TiptapLinkResource { + href: value, + target: Some("_blank".into()), + rel: Some("noopener noreferrer".into()), + class: None, + }) + .map(|_| "已插入链接"), + ), + None => set_command_feedback.set("链接操作已取消".to_string()), + } + } + }; + + view! { + +
+ {move || { + if is_embedded { + ().into_any() + } else { + view! { +
+
+ "P0 / Tiptap-like 主编辑器体验" +

"把 Spike 收敛成能检验的最小产品页壳"

+

+ "这里继续只做 " + "8123" + " 的 Leptos + Tiptap P0 体验验证,不挪动正式 " + "/documents/[id]" + " 主链。目标是先把 slash、toolbar、todo schema、块手柄和 reload 做成可直接看得见、点得动、能刷新保留结构的网页。" +

+
+
+
+ "变更计数" + {move || dirty_count.get().to_string()} +
+
+ "Todo Schema" + {move || if has_task_schema() { "ready" } else { "pending" }} +
+
+ "Selection" + {selection_text} +
+
+
+ }.into_any() + } + }} + +
+ {move || { + if is_embedded { + ().into_any() + } else { + view! { + <> +
+
+ "空间 / 主文档 /" + "Editor Baseline Reset" +
+
+ "反馈:" + {move || command_feedback.get()} +
+
+ + set_command_feedback.set("标题已写入本地草稿".to_string()), + Err(err) => set_command_feedback.set(format!("标题保存失败:{err}")), + } + } + placeholder="给这篇页面起个标题" + aria-label="Spike 页面标题" + /> + +
+ "输入 “/” 打开真正的最小 slash 菜单" + "选中文本时会出现最小浮动工具条" + "Todo 现在走 taskList / taskItem,而不是占位 HTML" + "把鼠标移到块左侧,点击 ⠿ 打开块菜单并拖拽重排" + "本页会把 JSON 草稿写入 localStorage,刷新后不丢结构" +
+ + }.into_any() + } + }} + +
match reorder_top_level_block_html( + ¤t_html, + source_index, + indicator.index, + indicator.placement, + ) { + Ok(next_html) => { + apply_html_update( + editor, + &runtime_persisted_identity(document_id, workspace_id), + next_html, + set_dirty_count, + set_html_output, + set_document_json, + set_json_output, + title, + set_command_feedback, + "已通过块手柄拖拽重排", + ); + } + Err(err) => { + set_command_feedback.set(err); + } + }, + Err(err) => { + set_command_feedback.set(format!("读取当前 HTML 失败:{err}")); + } + } + + set_dragging_block_index.set(None); + set_dragging_block_anchor.set(None); + set_drop_indicator.set(None); + set_block_menu_open.set(false); + set_block_menu_anchor.set(None); + set_hovered_block.set(None); + } + > + {move || { + let toolbar_locked = toolbar_overlay_locked( + turn_into_open.get(), + color_menu_open.get(), + more_menu_open.get(), + ); + let toolbar_anchor = if toolbar_locked { + locked_toolbar_anchor + .get() + .or_else(|| floating_toolbar_anchor.get()) + } else { + floating_toolbar_anchor.get() + }; + if let Some(anchor) = toolbar_anchor { + if ((!editor_focused.get() || !text_selection_active.get()) && !toolbar_locked) + || slash_open.get() + || block_menu_open.get() + || dragging_block_index.get().is_some() + { + return ().into_any(); + } + view! { +
+
+
+ +
+ {SLASH_ACTIONS.iter().map(|action| { + let kind = action.kind; + let label = action.label; + let description = action.description; + let testid = format!("turn-into-{}", action.id); + view! { + + } + }).collect_view()} +
+
+
+ +
+ +
+ + + + + + +
+ +
+
+
"文字颜色"
+
+ {TOOLBAR_TEXT_COLORS.iter().map(|option| { + let value = option.value; + let label = option.label; + let testid = format!("toolbar-text-color-{}", option.id); + view! { + + } + }).collect_view()} +
+
+ +
+
"背景颜色"
+
+ {TOOLBAR_HIGHLIGHT_COLORS.iter().map(|option| { + let value = option.value; + let label = option.label; + let testid = format!("toolbar-highlight-color-{}", option.id); + view! { + + } + }).collect_view()} +
+
+ +
+ +
+
+
+
+ +
+ +
+
+ +
+
+
"对齐方式"
+
+ {TOOLBAR_ALIGN_OPTIONS.iter().map(|option| { + let label = option.label; + let alignment = option.alignment; + let testid = format!("toolbar-align-{}", option.id); + let active = match option.alignment { + TiptapTextAlign::Left => selection_state.get().align_left, + TiptapTextAlign::Center => selection_state.get().align_center, + TiptapTextAlign::Right => selection_state.get().align_right, + TiptapTextAlign::Justify => selection_state.get().align_justify, + }; + view! { + + } + }).collect_view()} +
+
+
+
+
+
+ }.into_any() + } else { + ().into_any() + } + }} + + {move || { + if let Some(indicator) = drop_indicator.get() { + let drop_indicator_left = editor_stage_element() + .map(|stage| { + let stage_rect = stage.get_bounding_client_rect(); + format!("{}px", content_column_left(stage_rect.width())) + }) + .unwrap_or_else(|| "56px".to_string()); + let drop_indicator_right = editor_stage_element() + .map(|stage| { + let stage_rect = stage.get_bounding_client_rect(); + let content_left = content_column_left(stage_rect.width()); + format!("{}px", content_left) + }) + .unwrap_or_else(|| "56px".to_string()); + view! { +
+ }.into_any() + } else { + ().into_any() + } + }} + + {move || { + let active_block = if block_menu_open.get() { + block_menu_anchor.get() + } else if dragging_block_index.get().is_some() { + dragging_block_anchor.get() + } else { + hovered_block.get().or_else(|| { + if editor_focused.get() && !text_selection_active.get() && !slash_open.get() { + block_state_from_index(0) + } else { + None + } + }) + }; + + if let Some(block) = active_block { + let dragging_index = dragging_block_index.get(); + let is_dragging = dragging_index + .map(|active| active == block.index) + .unwrap_or(false); + + if !editor_focused.get() + || text_selection_active.get() + || slash_open.get() + || (dragging_index.is_some() && !is_dragging) + { + return ().into_any(); + } + + let anchor_top = format!("{}px", hover_anchor_top(&block)); + let anchor_transform = hover_anchor_transform(&block); + let handle_left = editor_stage_element() + .map(|stage| { + let stage_rect = stage.get_bounding_client_rect(); + format!("{}px", handle_lane_left(stage_rect.width())) + }) + .unwrap_or_else(|| "12px".to_string()); + let block_index = block.index; + let block_label = block.label.clone(); + let click_block_label = block_label.clone(); + let menu_block_label = block_label.clone(); + let duplicate_block_label = block_label.clone(); + let delete_block_label = block_label.clone(); + let insert_block_label = block_label.clone(); + let click_anchor_block = block.clone(); + let drag_anchor_block = block.clone(); + + view! { +
+ + + + + {move || { + if block_menu_open.get() + && block_menu_anchor + .get() + .map(|current| current.index == block_index) + .unwrap_or(false) + { + let current_menu_label = menu_block_label.clone(); + let current_duplicate_label = duplicate_block_label.clone(); + let current_delete_label = delete_block_label.clone(); + let menu_layout = block_menu_layout(&block).unwrap_or(BlockMenuLayout { + max_height: 360.0, + open_upward: false, + }); + let menu_top = if menu_layout.open_upward { "auto" } else { "0" }; + let menu_bottom = if menu_layout.open_upward { "0" } else { "auto" }; + view! { +
+
+ {current_menu_label.clone()} + {format!("顶层块 #{}", block_index + 1)} +
+
+ {move || { + if block_turn_into_open.get() { + view! { +
+ + {SLASH_ACTIONS + .iter() + .filter(|action| action.kind != SlashActionKind::Divider) + .map(|action| { + let kind = action.kind; + let label = action.label; + let testid = format!("block-drag-menu-item-{}", action.id); + let action_menu_label = current_menu_label.clone(); + view! { + + } + }) + .collect_view()} +
+ }.into_any() + } else { + let duplicate_feedback_label = current_duplicate_label.clone(); + let delete_feedback_label = current_delete_label.clone(); + view! { + <> +
+ +
+
+
+ + +
+ + }.into_any() + } + }} +
+
+ }.into_any() + } else { + ().into_any() + } + }} +
+ }.into_any() + } else { + ().into_any() + } + }} + + {move || { + if slash_open.get() { + view! { +
+
+ {SLASH_ACTIONS.iter().enumerate().map(|(index, action)| { + let is_selected = move || slash_index.get() == index; + let kind = action.kind; + let label = action.label; + let description = action.description; + let testid = format!("slash-item-{}", action.id); + view! { + + } + }).collect_view()} +
+
+ } + .into_any() + } else { + ().into_any() + } + }} + + { + if restored_from_storage { + set_command_feedback.set("编辑器已准备就绪,并已恢复本地草稿".to_string()); + } else { + set_command_feedback.set("编辑器已准备就绪,当前内容已写入本地草稿".to_string()); + } + } + Err(err) => { + set_command_feedback.set(format!("编辑器已准备就绪,但草稿初始化失败:{err}")); + } + } + } + on_change=move |_| { + set_dirty_count.update(|count| *count += 1); + let snapshot = + sync_editor_outputs(editor, set_html_output, set_document_json, set_json_output); + dispatch_change_event(&ChangePayload { + document_id: document_id.get_untracked(), + workspace_id: workspace_id.get_untracked(), + title: title.get_untracked(), + content: snapshot.clone(), + meta: ChangeMetaPayload { + dirty_count: dirty_count.get_untracked(), + editor_focused: editor_focused.get_untracked(), + slash_open: slash_open.get_untracked(), + toolbar_open: toolbar_overlay_locked( + turn_into_open.get_untracked(), + color_menu_open.get_untracked(), + more_menu_open.get_untracked(), + ), + selected_block_index: hovered_block.get_untracked().map(|block| block.index), + revision: revision.get_untracked(), + conflict_detection_key: conflict_detection_key.get_untracked(), + read_only: read_only.get_untracked(), + }, + }); + dispatch_runtime_state( + document_id.get_untracked(), + workspace_id.get_untracked(), + title.get_untracked(), + dirty_count.get_untracked(), + hovered_block.get_untracked(), + editor_focused.get_untracked(), + slash_open.get_untracked(), + turn_into_open.get_untracked(), + color_menu_open.get_untracked(), + more_menu_open.get_untracked(), + read_only.get_untracked(), + ); + match persist_document_state( + &runtime_persisted_identity(document_id, workspace_id), + &title.get_untracked(), + &snapshot, + Some(html_output.get_untracked()), + ) { + Ok(()) => { + set_command_feedback.set("内容已变更,已同步观察值并写入本地草稿".to_string()); + } + Err(err) => { + set_command_feedback.set(format!("内容已变更,但本地保存失败:{err}")); + } + } + } + on_selection_change=move |selection: TiptapSelectionState| { + let selection_clone = selection.clone(); + set_selection_state.set(selection_clone.clone()); + let toolbar_locked = toolbar_overlay_locked( + turn_into_open.get_untracked(), + color_menu_open.get_untracked(), + more_menu_open.get_untracked(), + ); + let has_text_selection = if has_active_text_selection() { + sync_text_selection_overlay( + set_text_selection_active, + set_floating_toolbar_anchor, + ) + } else if toolbar_locked { + text_selection_active.get_untracked() + } else { + set_text_selection_active.set(false); + set_floating_toolbar_anchor.set(None); + false + }; + if has_text_selection { + if !toolbar_locked { + set_turn_into_open.set(false); + } + set_block_menu_open.set(false); + set_block_menu_anchor.set(None); + set_hovered_block.set(None); + } + send_selection_state( + &selection_clone, + editor_focused.get_untracked(), + hovered_block.get_untracked().map(|block| block.index), + ); + } + attr:class="editor-surface" + attr:data-testid="mnote-leptos-tiptap-editor-root" + attr:data-small-text=move || small_text.get().to_string() + attr:data-layout-density=move || layout_density.get() + attr:data-show-heading-numbers=move || show_heading_numbers.get().to_string() + attr:data-embed-default-block-id=move || embed_default_block_id.get().unwrap_or_default() + /> +
+ + {move || { + if is_embedded { + ().into_any() + } else { + view! { + + }.into_any() + } + }} +
+ + {move || { + if is_embedded { + ().into_any() + } else { + view! { +
+ + "调试抽屉:保留 HTML / JSON / Selection 观测,但不再主导页面" + "展开 / 收起" + +
+
+

"Selection"

+
{selection_text}
+
+
+

"HTML"

+
{move || html_output.get()}
+
+
+

"JSON"

+
{move || json_output.get()}
+
+
+
+ }.into_any() + } + }} +
+ } +} + +fn initial_content() -> TiptapContent { + TiptapContent::json(serde_json::json!({ + "type": "doc", + "content": [] + })) +} + +pub fn standalone_main() { + console_error_panic_hook::set_once(); + mount_to_body(|| { + view! { } + }); +} diff --git a/rust/spikes/leptos-tiptap-spike/src/main.rs b/rust/spikes/leptos-tiptap-spike/src/main.rs index 5e6c2466..f0b93b38 100644 --- a/rust/spikes/leptos-tiptap-spike/src/main.rs +++ b/rust/spikes/leptos-tiptap-spike/src/main.rs @@ -1,3773 +1,3 @@ -use leptos::ev; -use leptos::mount::mount_to_body; -use leptos::prelude::*; -use leptos_dom::helpers::window_event_listener; -use leptos_tiptap::{ - TiptapCodeBlockAttributes, TiptapColorAttributes, TiptapContent, TiptapEditor, - TiptapEditorHandle, TiptapExtension, TiptapHeadingLevel, TiptapHighlightAttributes, - TiptapLinkResource, TiptapMarkName, TiptapRange, TiptapSelectionState, TiptapTextAlign, -}; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Map, Value}; -use std::fmt::Display; -use wasm_bindgen::JsCast; -use web_sys::{window, DragEvent, Element, HtmlElement, MouseEvent, Node, Storage, WheelEvent}; - -const EDITOR_STAGE_SELECTOR: &str = "#editor-stage"; -const EDITOR_ROOT_SELECTOR: &str = ".editor-surface .ProseMirror"; -const HANDLE_SHELL_SELECTOR: &str = ".block-handle-shell"; -const SPIKE_STORAGE_KEY: &str = "mnote.leptos-tiptap-spike.document"; -const HANDLE_MULTILINE_HEIGHT: f64 = 40.0; -const HANDLE_GUTTER_WIDTH: f64 = 92.0; - -#[derive(Clone, Copy)] -struct ToolbarColorOption { - id: &'static str, - label: &'static str, - value: &'static str, -} - -#[derive(Clone, Copy)] -struct ToolbarAlignOption { - id: &'static str, - label: &'static str, - alignment: TiptapTextAlign, -} - -const TOOLBAR_TEXT_COLORS: [ToolbarColorOption; 10] = [ - ToolbarColorOption { - id: "default", - label: "默认文字", - value: "#111827", - }, - ToolbarColorOption { - id: "gray", - label: "灰色", - value: "#6b7280", - }, - ToolbarColorOption { - id: "brown", - label: "棕色", - value: "#8b5e3c", - }, - ToolbarColorOption { - id: "orange", - label: "橙色", - value: "#c96b1f", - }, - ToolbarColorOption { - id: "yellow", - label: "黄色", - value: "#b7791f", - }, - ToolbarColorOption { - id: "green", - label: "绿色", - value: "#18794e", - }, - ToolbarColorOption { - id: "blue", - label: "蓝色", - value: "#1d4ed8", - }, - ToolbarColorOption { - id: "purple", - label: "紫色", - value: "#7c3aed", - }, - ToolbarColorOption { - id: "pink", - label: "粉色", - value: "#be185d", - }, - ToolbarColorOption { - id: "red", - label: "红色", - value: "#b91c1c", - }, -]; - -const TOOLBAR_HIGHLIGHT_COLORS: [ToolbarColorOption; 8] = [ - ToolbarColorOption { - id: "yellow", - label: "黄色背景", - value: "#fef3c7", - }, - ToolbarColorOption { - id: "green", - label: "绿色背景", - value: "#dcfce7", - }, - ToolbarColorOption { - id: "blue", - label: "蓝色背景", - value: "#dbeafe", - }, - ToolbarColorOption { - id: "purple", - label: "紫色背景", - value: "#ede9fe", - }, - ToolbarColorOption { - id: "pink", - label: "粉色背景", - value: "#fce7f3", - }, - ToolbarColorOption { - id: "red", - label: "红色背景", - value: "#fee2e2", - }, - ToolbarColorOption { - id: "orange", - label: "橙色背景", - value: "#ffedd5", - }, - ToolbarColorOption { - id: "gray", - label: "灰色背景", - value: "#e5e7eb", - }, -]; - -const TOOLBAR_ALIGN_OPTIONS: [ToolbarAlignOption; 4] = [ - ToolbarAlignOption { - id: "left", - label: "左对齐", - alignment: TiptapTextAlign::Left, - }, - ToolbarAlignOption { - id: "center", - label: "居中", - alignment: TiptapTextAlign::Center, - }, - ToolbarAlignOption { - id: "right", - label: "右对齐", - alignment: TiptapTextAlign::Right, - }, - ToolbarAlignOption { - id: "justify", - label: "两端对齐", - alignment: TiptapTextAlign::Justify, - }, -]; - -const SPIKE_STYLE: &str = r#" -:root { - --tt-color-text: #111827; - --tt-color-text-gray: #6b7280; - --tt-color-text-brown: #8b5e3c; - --tt-color-text-orange: #c96b1f; - --tt-color-text-yellow: #b7791f; - --tt-color-text-green: #18794e; - --tt-color-text-blue: #1d4ed8; - --tt-color-text-purple: #7c3aed; - --tt-color-text-pink: #be185d; - --tt-color-text-red: #b91c1c; - --tt-color-highlight-yellow: #fef3c7; - --tt-color-highlight-green: #dcfce7; - --tt-color-highlight-blue: #dbeafe; - --tt-color-highlight-purple: #ede9fe; - --tt-color-highlight-pink: #fce7f3; - --tt-color-highlight-red: #fee2e2; - --tt-color-highlight-orange: #ffedd5; - --tt-color-highlight-gray: #e5e7eb; -} - -.app-shell { - max-width: 1180px; - margin: 0 auto; - padding: 28px 20px 72px; -} - -.app-shell-embedded { - max-width: none; - margin: 0; - padding: 0; -} - -.app-shell-embedded .hero-bar, -.app-shell-embedded .title-input, -.app-shell-embedded .editor-subcopy, -.app-shell-embedded .footer-strip, -.app-shell-embedded .debug-drawer, -.app-shell-embedded .editor-crumbs:first-child { - display: none; -} - -.app-shell-embedded .editor-card { - border: none; - border-radius: 0; - box-shadow: none; - background: transparent; -} - -.app-shell-embedded .editor-topbar { - padding: 8px 12px 0; -} - -.app-shell-embedded .editor-stage { - padding-top: 0; -} - -.hero-bar { - display: flex; - justify-content: space-between; - align-items: flex-start; - gap: 18px; - margin-bottom: 20px; -} - -.hero-meta { - display: grid; - gap: 10px; -} - -.hero-tag { - display: inline-flex; - align-items: center; - gap: 8px; - width: fit-content; - padding: 6px 12px; - border-radius: 999px; - background: rgba(15, 118, 110, 0.12); - color: var(--accent-strong); - font-size: 12px; - letter-spacing: .08em; - text-transform: uppercase; -} - -.hero-title { - margin: 0; - font-size: 40px; - line-height: 1.04; -} - -.hero-copy { - margin: 0; - max-width: 680px; - color: var(--muted); - line-height: 1.75; -} - -.hero-actions { - display: flex; - flex-wrap: wrap; - gap: 10px; - justify-content: flex-end; -} - -.hero-chip { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 10px 14px; - border: 1px solid var(--line); - border-radius: 16px; - background: rgba(255, 255, 255, 0.92); - color: var(--ink); - font-size: 13px; - box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05); -} - -.hero-chip strong { - color: var(--accent-strong); -} - -.editor-card { - position: relative; - border: 1px solid rgba(100, 116, 139, 0.18); - border-radius: 30px; - background: - linear-gradient(180deg, rgba(255, 255, 255, 0.98) 0%, rgba(254, 251, 246, 0.98) 100%); - box-shadow: 0 28px 64px rgba(15, 23, 42, 0.08); - overflow: hidden; -} - -.editor-topbar { - display: flex; - justify-content: space-between; - align-items: center; - gap: 14px; - padding: 18px 22px 12px; -} - -.editor-crumbs { - display: flex; - align-items: center; - gap: 10px; - color: var(--muted); - font-size: 13px; -} - -.editor-crumbs strong { - color: var(--ink); -} - -.title-input { - width: 100%; - border: none; - outline: none; - background: transparent; - font-size: 48px; - line-height: 1.05; - font-weight: 700; - color: #0f172a; - padding: 8px 22px 6px; -} - -.title-input::placeholder { - color: #94a3b8; -} - -.editor-subcopy { - display: flex; - flex-wrap: wrap; - gap: 10px 16px; - align-items: center; - padding: 0 22px 18px; - color: var(--muted); - font-size: 14px; -} - -.hint-pill { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 8px 12px; - border-radius: 999px; - background: rgba(15, 118, 110, 0.09); - color: var(--accent-strong); - font-size: 13px; -} - -.editor-stage { - position: relative; - margin: 0 18px 18px; - border: 1px solid rgba(100, 116, 139, 0.18); - border-radius: 26px; - background: rgba(255, 255, 255, 0.92); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8); -} - -.block-handle-shell { - position: absolute; - left: 18px; - z-index: 14; - display: inline-flex; - align-items: center; - gap: 6px; -} - -.block-handle-shell[data-dragging="true"] { - pointer-events: none; - opacity: 0.72; -} - -.block-handle-insert, -.block-handle-trigger { - width: 32px; - height: 32px; - display: inline-flex; - align-items: center; - justify-content: center; - border: 1px solid rgba(15, 23, 42, 0.12); - border-radius: 11px; - background: rgba(255, 255, 255, 0.98); - color: #334155; - box-shadow: 0 10px 24px rgba(15, 23, 42, 0.1); - transition: transform .12s ease, border-color .12s ease, box-shadow .12s ease; -} - -.block-handle-insert { - color: var(--accent-strong); - cursor: pointer; -} - -.block-handle-insert span { - font-size: 20px; - line-height: 1; -} - -.block-handle-insert:hover, -.block-handle-trigger:hover { - transform: translateY(-1px); - border-color: rgba(15, 118, 110, 0.34); - box-shadow: 0 18px 36px rgba(15, 23, 42, 0.16); -} - -.block-handle-trigger:active { - cursor: grabbing; -} - -.block-handle-trigger { - cursor: grab; - font-size: 18px; - letter-spacing: -0.08em; -} - -.block-drag-menu { - position: absolute; - top: 0; - left: calc(100% + 10px); - min-width: 248px; - display: grid; - gap: 8px; - padding: 12px; - border: 1px solid rgba(15, 23, 42, 0.1); - border-radius: 18px; - background: rgba(255, 255, 255, 0.98); - color: var(--ink); - box-shadow: 0 22px 48px rgba(15, 23, 42, 0.18); - overflow-y: auto; - overscroll-behavior: contain; - scrollbar-width: thin; -} - -.block-drag-menu-label { - display: grid; - gap: 4px; -} - -.block-drag-menu-label strong { - font-size: 14px; -} - -.block-drag-menu-label span { - color: var(--muted); - font-size: 12px; -} - -.block-drag-menu-back { - width: 100%; - display: inline-flex; - align-items: center; - gap: 8px; - border: none; - background: transparent; - color: var(--muted); - padding: 2px 2px 6px; - cursor: pointer; -} - -.block-drag-menu-back:hover { - color: var(--accent-strong); -} - -.block-drag-menu-actions { - display: grid; - gap: 6px; -} - -.block-drag-menu-section { - display: grid; - gap: 6px; -} - -.block-drag-menu-divider { - height: 1px; - background: rgba(148, 163, 184, 0.22); -} - -.block-drag-menu-item { - width: 100%; - display: flex; - align-items: center; - justify-content: flex-start; - gap: 12px; - text-align: left; - border: 1px solid transparent; - border-radius: 14px; - background: transparent; - color: inherit; - padding: 10px 12px; - cursor: pointer; - transition: background .12s ease, border-color .12s ease; -} - -.block-drag-menu-item:hover { - background: rgba(15, 118, 110, 0.08); - border-color: rgba(15, 118, 110, 0.18); -} - -.block-drop-indicator { - position: absolute; - left: 88px; - right: 34px; - height: 2px; - border-radius: 999px; - background: rgba(15, 118, 110, 0.78); - box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12); - z-index: 13; -} - -.floating-toolbar { - position: absolute; - left: 0; - top: 0; - transform: translate(-50%, calc(-100% - 14px)); - z-index: 12; - display: flex; - align-items: center; - gap: 2px; - flex-wrap: nowrap; - max-width: min(720px, calc(100% - 32px)); - padding: 3px; - border: 1px solid rgba(15, 23, 42, 0.08); - border-radius: 18px; - background: rgba(255, 255, 255, 0.98); - color: #0f172a; - box-shadow: 0 18px 40px rgba(15, 23, 42, 0.14); - backdrop-filter: blur(16px); -} - -.floating-toolbar-group { - display: flex; - align-items: center; - gap: 2px; -} - -.toolbar-popover-anchor { - position: relative; - display: inline-flex; - align-items: center; -} - -.toolbar-separator { - width: 1px; - align-self: stretch; - margin: 4px 3px; - background: rgba(148, 163, 184, 0.28); -} - -.toolbar-btn { - min-width: 34px; - height: 34px; - border: none; - border-radius: 12px; - background: transparent; - color: inherit; - padding: 0 10px; - cursor: pointer; - transition: background .12s ease, border-color .12s ease, transform .12s ease; - font-size: 14px; - font-weight: 600; -} - -.toolbar-btn:hover { - background: rgba(148, 163, 184, 0.16); -} - -.toolbar-btn[data-active="true"] { - background: rgba(15, 118, 110, 0.14); - color: var(--accent-strong); -} - -.toolbar-btn[data-wide="true"] { - min-width: 56px; - justify-content: space-between; -} - -.turn-into-panel { - position: absolute; - bottom: calc(100% + 10px); - left: 50%; - transform: translateX(-50%); - min-width: 220px; - max-height: min(420px, calc(100vh - 32px)); - display: grid; - gap: 6px; - padding: 10px; - border-radius: 18px; - border: 1px solid rgba(15, 23, 42, 0.1); - background: rgba(255, 255, 255, 0.98); - color: var(--ink); - box-shadow: 0 20px 44px rgba(15, 23, 42, 0.16); - overflow-y: auto; - overscroll-behavior: contain; - z-index: 2; -} - -.toolbar-popover-panel { - position: absolute; - bottom: calc(100% + 10px); - left: 50%; - transform: translateX(-50%); - min-width: 248px; - max-height: min(440px, calc(100vh - 32px)); - display: grid; - gap: 10px; - padding: 12px; - border-radius: 18px; - border: 1px solid rgba(15, 23, 42, 0.1); - background: rgba(255, 255, 255, 0.98); - color: var(--ink); - box-shadow: 0 20px 44px rgba(15, 23, 42, 0.16); - overflow-y: auto; - overscroll-behavior: contain; - scrollbar-width: thin; - z-index: 2; -} - -.turn-into-item, -.slash-item, -.toolbar-menu-item { - width: 100%; - display: grid; - gap: 4px; - text-align: left; - border: 1px solid transparent; - border-radius: 14px; - background: transparent; - color: inherit; - padding: 10px 12px; - cursor: pointer; - transition: background .12s ease, border-color .12s ease; -} - -.turn-into-item:hover, -.slash-item:hover, -.slash-item[data-active="true"], -.toolbar-menu-item:hover, -.toolbar-menu-item[data-active="true"] { - background: rgba(15, 118, 110, 0.08); - border-color: rgba(15, 118, 110, 0.18); -} - -.turn-into-item span, -.slash-item span, -.toolbar-menu-item span { - color: var(--muted); - font-size: 12px; -} - -.toolbar-popover-section { - display: grid; - gap: 8px; -} - -.toolbar-popover-title { - color: var(--muted); - font-size: 12px; - font-weight: 700; - letter-spacing: 0.02em; -} - -.toolbar-color-grid { - display: grid; - gap: 6px; - grid-template-columns: repeat(2, minmax(0, 1fr)); -} - -.toolbar-color-item { - display: flex; - align-items: center; - gap: 10px; -} - -.toolbar-color-chip { - width: 18px; - height: 18px; - flex: 0 0 18px; - border-radius: 999px; - border: 1px solid rgba(15, 23, 42, 0.14); - box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.6); -} - -.toolbar-more-list { - display: grid; - gap: 6px; -} - -.toolbar-more-item strong { - font-size: 14px; -} - -.slash-menu { - position: absolute; - top: 24px; - left: 24px; - z-index: 11; - width: min(360px, calc(100% - 48px)); - display: grid; - gap: 8px; - padding: 14px; - border: 1px solid rgba(15, 23, 42, 0.1); - border-radius: 22px; - background: rgba(255, 255, 255, 0.98); - box-shadow: 0 24px 48px rgba(15, 23, 42, 0.16); -} - -.slash-menu header { - display: grid; - gap: 4px; -} - -.slash-menu h2 { - margin: 0; - font-size: 15px; -} - -.slash-menu p { - margin: 0; - color: var(--muted); - line-height: 1.6; - font-size: 13px; -} - -.slash-list { - display: grid; - gap: 6px; -} - -.editor-surface { - display: block; - min-height: 580px; - padding: 76px 40px 32px 92px; -} - -.editor-surface .ProseMirror { - outline: none; - min-height: 472px; - line-height: 1.78; - font-size: 17px; - color: #1f2937; -} - -.editor-surface .ProseMirror h1, -.editor-surface .ProseMirror h2, -.editor-surface .ProseMirror h3 { - line-height: 1.12; - color: #0f172a; - margin: 1.12em 0 0.46em; - letter-spacing: -0.02em; -} - -.editor-surface .ProseMirror h1 { - font-size: 2.1em; -} - -.editor-surface .ProseMirror h2 { - font-size: 1.56em; -} - -.editor-surface .ProseMirror h3 { - font-size: 1.28em; -} - -.editor-surface .ProseMirror ul, -.editor-surface .ProseMirror ol { - padding-left: 1.5em; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] { - list-style: none; - padding-left: 0.25em; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li { - display: flex; - flex-direction: row; - align-items: flex-start; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li:not(:has(> p:first-child)) { - list-style-type: none; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li[data-checked="true"] > div > p, -.editor-surface .ProseMirror ul[data-type="taskList"] li[data-checked="true"] > div > p span { - opacity: 0.5; - text-decoration: line-through; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li label { - position: relative; - padding-top: 0.375rem; - padding-right: 0.5rem; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li label input[type="checkbox"] { - position: absolute; - opacity: 0; - width: 0; - height: 0; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li label span { - display: block; - width: 1em; - height: 1em; - border: 1px solid rgba(148, 163, 184, 0.7); - border-radius: 0.25rem; - position: relative; - cursor: pointer; - background-color: rgba(255, 255, 255, 0.96); - transition: - background-color 80ms ease-out, - border-color 80ms ease-out; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li label span::before { - content: ""; - position: absolute; - left: 50%; - top: 50%; - transform: translate(-50%, -50%); - width: 0.75em; - height: 0.75em; - background-color: #ffffff; - opacity: 0; - -webkit-mask: url("data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22currentColor%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M21.4142%204.58579C22.1953%205.36683%2022.1953%206.63317%2021.4142%207.41421L10.4142%2018.4142C9.63317%2019.1953%208.36684%2019.1953%207.58579%2018.4142L2.58579%2013.4142C1.80474%2012.6332%201.80474%2011.3668%202.58579%2010.5858C3.36683%209.80474%204.63317%209.80474%205.41421%2010.5858L9%2014.1716L18.5858%204.58579C19.3668%203.80474%2020.6332%203.80474%2021.4142%204.58579Z%22%20fill%3D%22currentColor%22%2F%3E%3C%2Fsvg%3E") center/contain no-repeat; - mask: url("data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22currentColor%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M21.4142%204.58579C22.1953%205.36683%2022.1953%206.63317%2021.4142%207.41421L10.4142%2018.4142C9.63317%2019.1953%208.36684%2019.1953%207.58579%2018.4142L2.58579%2013.4142C1.80474%2012.6332%201.80474%2011.3668%202.58579%2010.5858C3.36683%209.80474%204.63317%209.80474%205.41421%2010.5858L9%2014.1716L18.5858%204.58579C19.3668%203.80474%2020.6332%203.80474%2021.4142%204.58579Z%22%20fill%3D%22currentColor%22%2F%3E%3C%2Fsvg%3E") center/contain no-repeat; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li label input[type="checkbox"]:checked + span { - background: var(--accent-strong); - border-color: var(--accent-strong); -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li label input[type="checkbox"]:checked + span::before { - opacity: 1; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li > div { - flex: 1 1 0%; - min-width: 0; -} - -.editor-surface .ProseMirror ul[data-type="taskList"] li > div > p { - margin: 0; -} - -.editor-surface .ProseMirror pre { - background: #14222b; - color: #f8fafc; - padding: 16px 18px; - border-radius: 18px; - overflow: auto; -} - -.editor-surface .ProseMirror blockquote { - margin: 1.1em 0; - padding-left: 16px; - border-left: 3px solid rgba(15, 118, 110, 0.5); - color: #334155; -} - -.editor-surface .ProseMirror hr { - margin: 1.6em 0; - border: none; - border-top: 1px solid rgba(100, 116, 139, 0.28); -} - -.editor-surface .ProseMirror p.is-editor-empty:first-child::before, -.editor-surface .ProseMirror p.is-empty::before { - color: #94a3b8; - content: attr(data-placeholder); - float: left; - height: 0; - pointer-events: none; -} - -.footer-strip { - display: flex; - justify-content: space-between; - gap: 12px; - flex-wrap: wrap; - padding: 0 22px 22px; - color: var(--muted); - font-size: 13px; -} - -.footer-strip code { - color: var(--accent-strong); -} - -.debug-drawer { - margin-top: 22px; - border: 1px solid rgba(100, 116, 139, 0.18); - border-radius: 22px; - background: rgba(255, 255, 255, 0.85); - overflow: hidden; -} - -.debug-drawer summary { - cursor: pointer; - list-style: none; - padding: 18px 20px; - display: flex; - justify-content: space-between; - align-items: center; - font-weight: 600; -} - -.debug-drawer summary::-webkit-details-marker { - display: none; -} - -.debug-grid { - display: grid; - gap: 16px; - padding: 0 20px 20px; - grid-template-columns: repeat(3, minmax(0, 1fr)); -} - -.debug-card { - border: 1px solid rgba(100, 116, 139, 0.18); - border-radius: 18px; - background: rgba(255, 255, 255, 0.88); - padding: 16px; -} - -.debug-card h3 { - margin: 0 0 10px; - font-size: 14px; -} - -.debug-card pre { - margin: 0; - max-height: 260px; - overflow: auto; - white-space: pre-wrap; - word-break: break-word; - color: #1e293b; -} - -@media (max-width: 920px) { - .hero-bar, - .editor-topbar, - .footer-strip { - flex-direction: column; - align-items: flex-start; - } - - .title-input { - font-size: 34px; - } - - .editor-surface { - padding: 88px 20px 24px 28px; - min-height: 460px; - } - - .debug-grid { - grid-template-columns: 1fr; - } - - .floating-toolbar, - .slash-menu, - .block-drag-menu { - left: 16px; - right: 16px; - width: auto; - transform: none; - } - - .floating-toolbar { - top: 12px; - } -} - -@media (max-width: 768px) { - .block-handle-shell, - .block-drop-indicator { - display: none; - } -} -"#; - -#[derive(Clone, Copy, PartialEq, Eq)] -enum SlashActionKind { - Paragraph, - Heading1, - Heading2, - Heading3, - BulletList, - OrderedList, - Todo, - Quote, - CodeBlock, - Divider, -} - -#[derive(Clone, Copy)] -struct SlashAction { - kind: SlashActionKind, - id: &'static str, - label: &'static str, - description: &'static str, -} - -const SLASH_ACTIONS: [SlashAction; 10] = [ - SlashAction { - kind: SlashActionKind::Paragraph, - id: "paragraph", - label: "段落", - description: "回到普通正文块", - }, - SlashAction { - kind: SlashActionKind::Heading1, - id: "heading-1", - label: "一级标题", - description: "建立页面主层级", - }, - SlashAction { - kind: SlashActionKind::Heading2, - id: "heading-2", - label: "二级标题", - description: "整理章节结构", - }, - SlashAction { - kind: SlashActionKind::Heading3, - id: "heading-3", - label: "三级标题", - description: "补细粒度小节", - }, - SlashAction { - kind: SlashActionKind::BulletList, - id: "bullet", - label: "无序列表", - description: "记录普通要点", - }, - SlashAction { - kind: SlashActionKind::OrderedList, - id: "ordered", - label: "有序列表", - description: "记录步骤顺序", - }, - SlashAction { - kind: SlashActionKind::Todo, - id: "todo", - label: "Todo 列表", - description: "切到真正的 taskList/taskItem", - }, - SlashAction { - kind: SlashActionKind::Quote, - id: "quote", - label: "引用块", - description: "包住注释与摘录", - }, - SlashAction { - kind: SlashActionKind::CodeBlock, - id: "code-block", - label: "代码块", - description: "插入带语义的代码块", - }, - SlashAction { - kind: SlashActionKind::Divider, - id: "divider", - label: "分割线", - description: "插入 horizontal rule", - }, -]; - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -struct PersistedSpikeDocument { - title: String, - content: Value, - #[serde(default)] - html: Option, -} - -#[derive(Clone, Debug, PartialEq)] -struct HoveredBlockState { - index: usize, - label: String, - top: f64, - height: f64, -} - -#[derive(Clone, Debug, PartialEq)] -struct FloatingToolbarAnchor { - top: f64, - left: f64, -} - -#[derive(Clone, Debug, PartialEq)] -struct BlockMenuLayout { - max_height: f64, - open_upward: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum DropPlacement { - Before, - After, -} - -#[derive(Clone, Debug, PartialEq)] -struct DropIndicatorState { - index: usize, - top: f64, - placement: DropPlacement, -} - -#[derive(Clone, Debug, PartialEq)] -struct PendingDragState { - index: usize, - anchor: HoveredBlockState, - start_x: i32, - start_y: i32, -} - -fn local_storage() -> Option { - window().and_then(|win| win.local_storage().ok().flatten()) -} - -fn default_title() -> String { - "Leptos Tiptap 主编辑器 P0".to_string() -} - -fn persist_document_state( - title: &str, - content: &Value, - html: Option, -) -> Result<(), String> { - let payload = PersistedSpikeDocument { - title: title.to_string(), - content: content.clone(), - html, - }; - let raw = serde_json::to_string(&payload).map_err(|err| format!("序列化草稿失败:{err}"))?; - local_storage() - .ok_or_else(|| "浏览器 localStorage 不可用".to_string())? - .set_item(SPIKE_STORAGE_KEY, &raw) - .map_err(|err| format!("写入 localStorage 失败:{err:?}")) -} - -fn load_persisted_document() -> Option { - let raw = local_storage()? - .get_item(SPIKE_STORAGE_KEY) - .ok() - .flatten()?; - serde_json::from_str(&raw).ok() -} - -fn read_editor_snapshot(editor: TiptapEditorHandle) -> (String, Value, String) { - let html = editor - .get_html() - .unwrap_or_else(|err| format!("读取 HTML 失败:{err}")); - let json_value = editor.get_json().unwrap_or_else(|err| { - json!({ - "type": "error", - "message": format!("读取 JSON 失败:{err}"), - }) - }); - let json_text = serde_json::to_string_pretty(&json_value) - .unwrap_or_else(|err| format!("格式化 JSON 失败:{err}")); - (html, json_value, json_text) -} - -fn sync_editor_outputs( - editor: TiptapEditorHandle, - set_html_output: WriteSignal, - set_document_json: WriteSignal, - set_json_output: WriteSignal, -) -> Value { - let (html, json_value, json_text) = read_editor_snapshot(editor); - set_html_output.set(html); - set_document_json.set(json_value.clone()); - set_json_output.set(json_text); - json_value -} - -fn editor_root_element() -> Option { - window() - .and_then(|win| win.document()) - .and_then(|document| document.query_selector(EDITOR_ROOT_SELECTOR).ok().flatten()) -} - -fn editor_stage_element() -> Option { - window() - .and_then(|win| win.document()) - .and_then(|document| { - document - .query_selector(EDITOR_STAGE_SELECTOR) - .ok() - .flatten() - }) -} - -fn direct_block_from_element(mut element: Element, root: &Element) -> Option { - loop { - let parent = element.parent_element()?; - if parent.is_same_node(Some(root)) { - return Some(element); - } - element = parent; - } -} - -fn top_level_block_index(root: &Element, block: &Element) -> Option { - let children = root.children(); - (0..children.length()).find_map(|index| { - children - .item(index) - .filter(|child| child.is_same_node(Some(block))) - .map(|_| index as usize) - }) -} - -fn block_label_for_element(block: &Element) -> String { - match block.get_attribute("data-type").as_deref() { - Some("taskList") => "Todo 列表".to_string(), - Some("taskItem") => "Todo 项".to_string(), - _ => match block.tag_name().as_str() { - "H1" => "一级标题".to_string(), - "H2" => "二级标题".to_string(), - "H3" => "三级标题".to_string(), - "P" => "段落".to_string(), - "UL" => "无序列表".to_string(), - "OL" => "有序列表".to_string(), - "BLOCKQUOTE" => "引用块".to_string(), - "PRE" => "代码块".to_string(), - "HR" => "分割线".to_string(), - other => format!("块节点 {other}"), - }, - } -} - -fn target_element(target: web_sys::EventTarget) -> Option { - target.clone().dyn_into::().ok().or_else(|| { - target - .dyn_into::() - .ok() - .and_then(|node| node.parent_element()) - }) -} - -fn event_target_matches_selector(target: Option, selector: &str) -> bool { - target - .and_then(target_element) - .and_then(|element| element.closest(selector).ok().flatten()) - .is_some() -} - -fn current_target_html_element(event: &WheelEvent) -> Option { - event.current_target()?.dyn_into::().ok() -} - -fn trap_scroll_inside_menu(event: &WheelEvent) { - event.prevent_default(); - event.stop_propagation(); - - let Some(menu) = current_target_html_element(event) else { - return; - }; - - let current = f64::from(menu.scroll_top()); - let max_scroll = f64::from((menu.scroll_height() - menu.client_height()).max(0)); - let next = (current + event.delta_y()).clamp(0.0, max_scroll); - menu.set_scroll_top(next.round() as i32); -} - -fn hovered_block_from_target(target: web_sys::EventTarget) -> Option { - let root = editor_root_element()?; - let element = target_element(target)?; - - if element - .closest(HANDLE_SHELL_SELECTOR) - .ok() - .flatten() - .is_some() - { - return None; - } - - let block = direct_block_from_element(element, &root)?; - let index = top_level_block_index(&root, &block)?; - block_state_from_index(index) -} - -fn hovered_block_from_selection() -> Option { - let selection = window().and_then(|win| win.get_selection().ok().flatten())?; - let anchor_node = selection.anchor_node()?; - let element = anchor_node - .dyn_ref::() - .cloned() - .or_else(|| anchor_node.parent_element())?; - let root = editor_root_element()?; - let block = direct_block_from_element(element, &root)?; - let index = top_level_block_index(&root, &block)?; - block_state_from_index(index) -} - -fn block_state_from_index(index: usize) -> Option { - let root = editor_root_element()?; - let stage = editor_stage_element()?; - let block = root.children().item(index as u32)?; - let block_rect = block.get_bounding_client_rect(); - let stage_rect = stage.get_bounding_client_rect(); - - Some(HoveredBlockState { - index, - label: block_label_for_element(&block), - top: block_rect.top() - stage_rect.top(), - height: block_rect.height(), - }) -} - -fn prosemirror_node_size(node: &Value) -> Option { - match node.get("type").and_then(Value::as_str) { - Some("text") => Some( - node.get("text") - .and_then(Value::as_str) - .map(|text| text.encode_utf16().count() as u32) - .unwrap_or(0), - ), - Some("hardBreak") | Some("horizontalRule") => Some(1), - _ => { - let Some(children) = node.get("content").and_then(Value::as_array) else { - return Some(1); - }; - - let content_size = children.iter().try_fold(0_u32, |acc, child| { - prosemirror_node_size(child).map(|size| acc + size) - })?; - Some(content_size + 2) - } - } -} - -fn nested_edge_child_size(node: &Value, at_start: bool) -> Option { - let outer = node - .get("content") - .and_then(Value::as_array) - .and_then(|children| { - if at_start { - children.first() - } else { - children.last() - } - })?; - let inner = outer - .get("content") - .and_then(Value::as_array) - .and_then(|children| { - if at_start { - children.first() - } else { - children.last() - } - })?; - prosemirror_node_size(inner) -} - -fn top_level_block_range(document: &Value, index: usize) -> Option { - let content = document.get("content").and_then(Value::as_array)?; - let mut position = 0_u32; - - for (current_index, node) in content.iter().enumerate() { - let node_size = prosemirror_node_size(node)?; - if current_index == index { - let from = position + nested_edge_child_size(node, true).unwrap_or(1); - let mut to = position - + node_size.saturating_sub(nested_edge_child_size(node, false).unwrap_or(1)); - if to < from { - to = from; - } - return Some(TiptapRange { from, to }); - } - position += node_size; - } - - None -} - -fn node_is_within_root(node: Node, root: &Element) -> bool { - let mut current = Some(node); - while let Some(node) = current { - if node.is_same_node(Some(root)) { - return true; - } - current = node.parent_node(); - } - false -} - -fn active_editor_text_selection() -> Option { - let selection = window().and_then(|win| win.get_selection().ok().flatten())?; - if selection.is_collapsed() { - return None; - } - - let root = editor_root_element()?; - let anchor_inside = selection - .anchor_node() - .map(|node| node_is_within_root(node, &root)) - .unwrap_or(false); - let focus_inside = selection - .focus_node() - .map(|node| node_is_within_root(node, &root)) - .unwrap_or(false); - - if anchor_inside || focus_inside { - Some(selection) - } else { - None - } -} - -fn floating_toolbar_anchor_from_selection() -> Option { - let selection = active_editor_text_selection()?; - let range = selection.get_range_at(0).ok()?; - let rect = range.get_bounding_client_rect(); - if rect.width() <= 0.0 && rect.height() <= 0.0 { - return None; - } - - let stage = editor_stage_element()?; - let stage_rect = stage.get_bounding_client_rect(); - - Some(FloatingToolbarAnchor { - top: (rect.top() - stage_rect.top()).max(60.0), - left: rect.left() + (rect.width() / 2.0) - stage_rect.left(), - }) -} - -fn hover_anchor_top(block: &HoveredBlockState) -> f64 { - if block.height > HANDLE_MULTILINE_HEIGHT { - block.top + 12.0 - } else { - block.top + (block.height / 2.0) - } -} - -fn hover_anchor_transform(block: &HoveredBlockState) -> &'static str { - if block.height > HANDLE_MULTILINE_HEIGHT { - "translateY(0)" - } else { - "translateY(-50%)" - } -} - -fn pointer_in_handle_corridor(client_x: i32, client_y: i32, block: &HoveredBlockState) -> bool { - let Some(stage) = editor_stage_element() else { - return false; - }; - let stage_rect = stage.get_bounding_client_rect(); - let x = f64::from(client_x) - stage_rect.left(); - let y = f64::from(client_y) - stage_rect.top(); - let block_top = block.top; - let block_bottom = block.top + block.height; - - x >= 0.0 && x <= HANDLE_GUTTER_WIDTH && y >= block_top - 8.0 && y <= block_bottom + 8.0 -} - -fn block_menu_layout(block: &HoveredBlockState) -> Option { - let stage = editor_stage_element()?; - let stage_rect = stage.get_bounding_client_rect(); - let anchor_top = hover_anchor_top(block); - let stage_padding = 18.0; - let space_above = (anchor_top - stage_padding).max(0.0); - let space_below = (stage_rect.height() - anchor_top - stage_padding).max(0.0); - let open_upward = space_below < 340.0 && space_above > space_below; - let available_height = if open_upward { - space_above - } else { - space_below - }; - let max_height = if available_height >= 220.0 { - available_height - } else { - available_height.max(160.0) - }; - - Some(BlockMenuLayout { - max_height, - open_upward, - }) -} - -fn drop_indicator_from_target( - target: web_sys::EventTarget, - client_y: i32, -) -> Option { - let hovered = hovered_block_from_target(target)?; - let root = editor_root_element()?; - let block = root.children().item(hovered.index as u32)?; - let stage = editor_stage_element()?; - let block_rect = block.get_bounding_client_rect(); - let stage_rect = stage.get_bounding_client_rect(); - let midpoint = block_rect.top() + (block_rect.height() / 2.0); - let placement = if f64::from(client_y) <= midpoint { - DropPlacement::Before - } else { - DropPlacement::After - }; - let top = match placement { - DropPlacement::Before => block_rect.top() - stage_rect.top(), - DropPlacement::After => block_rect.bottom() - stage_rect.top(), - }; - - Some(DropIndicatorState { - index: hovered.index, - top, - placement, - }) -} - -fn drop_indicator_from_point(client_x: i32, client_y: i32) -> Option { - let target = window() - .and_then(|win| win.document()) - .and_then(|document| document.element_from_point(client_x as f32, client_y as f32))?; - let target: web_sys::EventTarget = target.into(); - drop_indicator_from_target(target, client_y) -} - -fn document_content_mut(document: &mut Value) -> Result<&mut Vec, String> { - document - .get_mut("content") - .and_then(Value::as_array_mut) - .ok_or_else(|| "文档 JSON 缺少顶层 content 数组".to_string()) -} - -fn node_with_attrs( - type_name: &str, - attrs: Option>, - content: Vec, -) -> Value { - let mut node = Map::new(); - node.insert("type".to_string(), Value::String(type_name.to_string())); - if let Some(attrs) = attrs.filter(|attrs| !attrs.is_empty()) { - node.insert("attrs".to_string(), Value::Object(attrs)); - } - if !content.is_empty() { - node.insert("content".to_string(), Value::Array(content)); - } - Value::Object(node) -} - -fn paragraph_node(content: Vec) -> Value { - node_with_attrs("paragraph", None, content) -} - -fn list_item_node(content: Vec) -> Value { - node_with_attrs("listItem", None, vec![paragraph_node(content)]) -} - -fn task_item_node(content: Vec) -> Value { - let mut attrs = Map::new(); - attrs.insert("checked".to_string(), Value::Bool(false)); - node_with_attrs("taskItem", Some(attrs), vec![paragraph_node(content)]) -} - -fn collect_plain_text(node: &Value) -> String { - match node.get("type").and_then(Value::as_str) { - Some("text") => node - .get("text") - .and_then(Value::as_str) - .unwrap_or_default() - .to_string(), - Some("hardBreak") => "\n".to_string(), - _ => node - .get("content") - .and_then(Value::as_array) - .map(|children| { - children - .iter() - .map(collect_plain_text) - .collect::>() - .join("") - }) - .unwrap_or_default(), - } -} - -fn inline_from_first_child(children: &[Value]) -> Vec { - children - .first() - .map(extract_inline_content) - .unwrap_or_default() -} - -fn extract_inline_content(node: &Value) -> Vec { - match node.get("type").and_then(Value::as_str) { - Some("paragraph") | Some("heading") => node - .get("content") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(), - Some("blockquote") => node - .get("content") - .and_then(Value::as_array) - .map(|children| inline_from_first_child(children)) - .unwrap_or_default(), - Some("bulletList") | Some("orderedList") | Some("taskList") => node - .get("content") - .and_then(Value::as_array) - .and_then(|items| items.first()) - .and_then(|item| item.get("content")) - .and_then(Value::as_array) - .map(|children| inline_from_first_child(children)) - .unwrap_or_default(), - Some("codeBlock") => { - let text = collect_plain_text(node); - if text.is_empty() { - Vec::new() - } else { - vec![json!({"type": "text", "text": text})] - } - } - Some("horizontalRule") => Vec::new(), - _ => node - .get("content") - .and_then(Value::as_array) - .map(|children| { - children - .iter() - .flat_map(extract_inline_content) - .collect::>() - }) - .unwrap_or_default(), - } -} - -fn turn_into_block(node: &Value, action: SlashActionKind) -> Value { - let inline = extract_inline_content(node); - match action { - SlashActionKind::Paragraph => paragraph_node(inline), - SlashActionKind::Heading1 => { - let mut attrs = Map::new(); - attrs.insert("level".to_string(), json!(1)); - node_with_attrs("heading", Some(attrs), inline) - } - SlashActionKind::Heading2 => { - let mut attrs = Map::new(); - attrs.insert("level".to_string(), json!(2)); - node_with_attrs("heading", Some(attrs), inline) - } - SlashActionKind::Heading3 => { - let mut attrs = Map::new(); - attrs.insert("level".to_string(), json!(3)); - node_with_attrs("heading", Some(attrs), inline) - } - SlashActionKind::BulletList => { - node_with_attrs("bulletList", None, vec![list_item_node(inline)]) - } - SlashActionKind::OrderedList => { - node_with_attrs("orderedList", None, vec![list_item_node(inline)]) - } - SlashActionKind::Todo => node_with_attrs("taskList", None, vec![task_item_node(inline)]), - SlashActionKind::Quote => node_with_attrs("blockquote", None, vec![paragraph_node(inline)]), - SlashActionKind::CodeBlock => { - let text = collect_plain_text(node); - let mut attrs = Map::new(); - attrs.insert("language".to_string(), Value::String("rust".to_string())); - let content = if text.is_empty() { - Vec::new() - } else { - vec![json!({"type": "text", "text": text})] - }; - node_with_attrs("codeBlock", Some(attrs), content) - } - SlashActionKind::Divider => node_with_attrs("horizontalRule", None, Vec::new()), - } -} - -fn duplicate_top_level_block(document: &mut Value, index: usize) -> Result<(), String> { - let content = document_content_mut(document)?; - let block = content - .get(index) - .cloned() - .ok_or_else(|| format!("找不到第 {index} 个块"))?; - content.insert(index + 1, block); - Ok(()) -} - -fn delete_top_level_block(document: &mut Value, index: usize) -> Result<(), String> { - let content = document_content_mut(document)?; - if index >= content.len() { - return Err(format!("找不到第 {index} 个块")); - } - - if content.len() == 1 { - content[0] = paragraph_node(Vec::new()); - return Ok(()); - } - - content.remove(index); - Ok(()) -} - -fn reorder_top_level_block( - document: &mut Value, - source: usize, - target: usize, - placement: DropPlacement, -) -> Result<(), String> { - let content = document_content_mut(document)?; - if source >= content.len() || target >= content.len() { - return Err("拖拽目标超出当前顶层块范围".to_string()); - } - - let block = content.remove(source); - let mut insert_at = match placement { - DropPlacement::Before => target, - DropPlacement::After => target + 1, - }; - - if source < insert_at { - insert_at = insert_at.saturating_sub(1); - } - - if insert_at > content.len() { - insert_at = content.len(); - } - - content.insert(insert_at, block); - Ok(()) -} - -fn replace_top_level_block_kind( - document: &mut Value, - index: usize, - action: SlashActionKind, -) -> Result<(), String> { - let content = document_content_mut(document)?; - let next = turn_into_block( - content - .get(index) - .ok_or_else(|| format!("找不到第 {index} 个块"))?, - action, - ); - content[index] = next; - Ok(()) -} - -fn has_active_text_selection() -> bool { - active_editor_text_selection().is_some() -} - -fn toolbar_overlay_locked( - turn_into_open: bool, - color_menu_open: bool, - more_menu_open: bool, -) -> bool { - turn_into_open || color_menu_open || more_menu_open -} - -fn sync_text_selection_overlay( - set_text_selection_active: WriteSignal, - set_floating_toolbar_anchor: WriteSignal>, -) -> bool { - let toolbar_anchor = floating_toolbar_anchor_from_selection(); - let has_text_selection = toolbar_anchor.is_some(); - set_text_selection_active.set(has_text_selection); - set_floating_toolbar_anchor.set(toolbar_anchor); - has_text_selection -} - -fn sync_editor_overlay_state( - set_editor_focused: WriteSignal, - set_text_selection_active: WriteSignal, - set_floating_toolbar_anchor: WriteSignal>, - set_slash_open: WriteSignal, - set_turn_into_open: WriteSignal, - set_hovered_block: WriteSignal>, - set_block_menu_anchor: WriteSignal>, - set_block_menu_open: WriteSignal, -) { - let focused = active_editor_stage(); - set_editor_focused.set(focused); - let has_text_selection = - sync_text_selection_overlay(set_text_selection_active, set_floating_toolbar_anchor); - - if focused && has_text_selection { - set_slash_open.set(false); - set_turn_into_open.set(false); - set_block_menu_open.set(false); - set_block_menu_anchor.set(None); - set_hovered_block.set(None); - } -} - -fn apply_document_update( - editor: TiptapEditorHandle, - next_document: Value, - set_dirty_count: WriteSignal, - set_html_output: WriteSignal, - set_document_json: WriteSignal, - set_json_output: WriteSignal, - title: ReadSignal, - set_command_feedback: WriteSignal, - success_message: impl Into, -) { - let success_message = success_message.into(); - let next_payload = next_document - .get("content") - .and_then(Value::as_array) - .cloned() - .map(Value::Array) - .unwrap_or_else(|| next_document.clone()); - match editor.set_content(TiptapContent::json(next_payload)) { - Ok(()) => { - set_dirty_count.update(|count| *count += 1); - let (html, snapshot, json_text) = read_editor_snapshot(editor); - set_html_output.set(html.clone()); - set_document_json.set(snapshot.clone()); - set_json_output.set(json_text); - match persist_document_state(&title.get_untracked(), &snapshot, Some(html)) { - Ok(()) => { - set_command_feedback.set(format!("{success_message},并已写入本地草稿")); - } - Err(err) => { - set_command_feedback.set(format!("{success_message},但本地保存失败:{err}")); - } - } - } - Err(err) => { - set_command_feedback.set(format!("更新文档失败:{err}")); - } - } -} - -fn apply_html_update( - editor: TiptapEditorHandle, - next_html: String, - set_dirty_count: WriteSignal, - set_html_output: WriteSignal, - set_document_json: WriteSignal, - set_json_output: WriteSignal, - title: ReadSignal, - set_command_feedback: WriteSignal, - success_message: impl Into, -) { - let success_message = success_message.into(); - match editor.set_content(TiptapContent::html(next_html)) { - Ok(()) => { - set_dirty_count.update(|count| *count += 1); - let (html, snapshot, json_text) = read_editor_snapshot(editor); - set_html_output.set(html.clone()); - set_document_json.set(snapshot.clone()); - set_json_output.set(json_text); - match persist_document_state(&title.get_untracked(), &snapshot, Some(html)) { - Ok(()) => { - set_command_feedback.set(format!("{success_message},并已写入本地草稿")); - } - Err(err) => { - set_command_feedback.set(format!("{success_message},但本地保存失败:{err}")); - } - } - } - Err(err) => { - set_command_feedback.set(format!("更新文档失败:{err}")); - } - } -} - -fn duplicate_top_level_block_html(current_html: &str, index: usize) -> Result { - let document = window() - .and_then(|win| win.document()) - .ok_or_else(|| "浏览器 document 不可用".to_string())?; - let container = document - .create_element("div") - .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; - container.set_inner_html(current_html); - - let children = container.children(); - let current = children - .item(index as u32) - .ok_or_else(|| format!("找不到第 {index} 个 HTML 顶层块"))?; - let cloned = current - .clone_node_with_deep(true) - .map_err(|err| format!("复制 HTML 块失败:{err:?}"))? - .dyn_into::() - .map_err(|_| "复制出的节点不是 Element".to_string())?; - - if let Some(next_sibling) = children.item(index as u32 + 1) { - container - .insert_before(&cloned, Some(&next_sibling)) - .map_err(|err| format!("插入复制块失败:{err:?}"))?; - } else { - container - .append_child(&cloned) - .map_err(|err| format!("追加复制块失败:{err:?}"))?; - } - - Ok(container.inner_html()) -} - -fn insert_top_level_paragraph_after_html( - current_html: &str, - index: usize, -) -> Result { - let document = window() - .and_then(|win| win.document()) - .ok_or_else(|| "浏览器 document 不可用".to_string())?; - let container = document - .create_element("div") - .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; - container.set_inner_html(current_html); - - let children = container.children(); - children - .item(index as u32) - .ok_or_else(|| format!("找不到第 {index} 个 HTML 顶层块"))?; - let paragraph = document - .create_element("p") - .map_err(|err| format!("创建空段落失败:{err:?}"))?; - - if let Some(next_sibling) = children.item(index as u32 + 1) { - container - .insert_before(¶graph, Some(&next_sibling)) - .map_err(|err| format!("插入新块失败:{err:?}"))?; - } else { - container - .append_child(¶graph) - .map_err(|err| format!("追加新块失败:{err:?}"))?; - } - - Ok(container.inner_html()) -} - -fn delete_top_level_block_html(current_html: &str, index: usize) -> Result { - let document = window() - .and_then(|win| win.document()) - .ok_or_else(|| "浏览器 document 不可用".to_string())?; - let container = document - .create_element("div") - .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; - container.set_inner_html(current_html); - - let children = container.children(); - if children.length() <= 1 { - container.set_inner_html("

"); - return Ok(container.inner_html()); - } - - let current = children - .item(index as u32) - .ok_or_else(|| format!("找不到第 {index} 个 HTML 顶层块"))?; - container - .remove_child(¤t) - .map_err(|err| format!("删除 HTML 块失败:{err:?}"))?; - Ok(container.inner_html()) -} - -fn reorder_top_level_block_html( - current_html: &str, - source: usize, - target: usize, - placement: DropPlacement, -) -> Result { - let document = window() - .and_then(|win| win.document()) - .ok_or_else(|| "浏览器 document 不可用".to_string())?; - let container = document - .create_element("div") - .map_err(|err| format!("创建 HTML 容器失败:{err:?}"))?; - container.set_inner_html(current_html); - - let initial_children = container.children(); - let block_count = initial_children.length() as usize; - if source >= block_count || target >= block_count { - return Err("拖拽目标超出当前顶层块范围".to_string()); - } - - let current = initial_children - .item(source as u32) - .ok_or_else(|| format!("找不到第 {source} 个 HTML 顶层块"))?; - let moving = current - .clone_node_with_deep(true) - .map_err(|err| format!("复制拖拽块失败:{err:?}"))? - .dyn_into::() - .map_err(|_| "复制出的拖拽块不是 Element".to_string())?; - - container - .remove_child(¤t) - .map_err(|err| format!("移除原始拖拽块失败:{err:?}"))?; - - let mut insert_at = match placement { - DropPlacement::Before => target, - DropPlacement::After => target + 1, - }; - if source < insert_at { - insert_at = insert_at.saturating_sub(1); - } - - let current_children = container.children(); - let current_len = current_children.length() as usize; - if insert_at >= current_len { - container - .append_child(&moving) - .map_err(|err| format!("追加拖拽块失败:{err:?}"))?; - } else { - let next_sibling = current_children - .item(insert_at as u32) - .ok_or_else(|| format!("找不到第 {insert_at} 个 HTML 插入位置"))?; - container - .insert_before(&moving, Some(&next_sibling)) - .map_err(|err| format!("插入拖拽块失败:{err:?}"))?; - } - - Ok(container.inner_html()) -} - -fn p0_extensions() -> Vec { - vec![ - TiptapExtension::Document, - TiptapExtension::Dropcursor, - TiptapExtension::Gapcursor, - TiptapExtension::Text, - TiptapExtension::Paragraph, - TiptapExtension::Heading, - TiptapExtension::Bold, - TiptapExtension::Italic, - TiptapExtension::Strike, - TiptapExtension::Code, - TiptapExtension::Blockquote, - TiptapExtension::BulletList, - TiptapExtension::OrderedList, - TiptapExtension::ListItem, - TiptapExtension::TaskItem, - TiptapExtension::TaskList, - TiptapExtension::CodeBlock, - TiptapExtension::HorizontalRule, - TiptapExtension::History, - TiptapExtension::Underline, - TiptapExtension::TextStyle, - TiptapExtension::TextAlign, - TiptapExtension::Highlight, - TiptapExtension::Link, - TiptapExtension::Placeholder, - ] -} - -fn active_editor_stage() -> bool { - window() - .and_then(|win| win.document()) - .and_then(|document| document.active_element()) - .and_then(|element| element.closest(EDITOR_STAGE_SELECTOR).ok().flatten()) - .is_some() -} - -fn selection_summary(selection: &TiptapSelectionState) -> String { - let block = if selection.h1 { - "一级标题" - } else if selection.h2 { - "二级标题" - } else if selection.h3 { - "三级标题" - } else if selection.task_list { - "Todo 列表" - } else if selection.ordered_list { - "有序列表" - } else if selection.bullet_list { - "无序列表" - } else if selection.blockquote { - "引用块" - } else if selection.paragraph { - "段落" - } else { - "未定位" - }; - - let mut marks = Vec::new(); - if selection.bold { - marks.push("Bold"); - } - if selection.italic { - marks.push("Italic"); - } - if selection.underline { - marks.push("Underline"); - } - if selection.strike { - marks.push("Strike"); - } - if selection.highlight { - marks.push("Highlight"); - } - if selection.text_style { - marks.push("Color"); - } - if selection.link { - marks.push("Link"); - } - - let mark_text = if marks.is_empty() { - "无行内样式".to_string() - } else { - marks.join(" / ") - }; - - format!("当前块:{block} | 行内样式:{mark_text}") -} - -fn selection_has_rich_marks(selection: &TiptapSelectionState) -> bool { - selection.bold - || selection.italic - || selection.underline - || selection.strike - || selection.highlight - || selection.text_style - || selection.link -} - -fn apply_text_color(editor: TiptapEditorHandle, color: &str) -> Result<&'static str, String> { - editor - .set_color(TiptapColorAttributes { - color: color.to_string(), - }) - .map(|_| "已更新文字颜色") - .map_err(|err| format!("命令执行失败:{err}")) -} - -fn clear_text_color(editor: TiptapEditorHandle) -> Result<&'static str, String> { - editor - .unset_color() - .map(|_| "已清除文字颜色") - .map_err(|err| format!("命令执行失败:{err}")) -} - -fn apply_highlight_color( - editor: TiptapEditorHandle, - color: Option<&str>, -) -> Result<&'static str, String> { - match color { - Some(color) => editor - .set_highlight(Some(TiptapHighlightAttributes { - color: Some(color.to_string()), - })) - .map(|_| "已更新背景色") - .map_err(|err| format!("命令执行失败:{err}")), - None => editor - .unset_highlight() - .map(|_| "已清除背景色") - .map_err(|err| format!("命令执行失败:{err}")), - } -} - -fn apply_text_align( - editor: TiptapEditorHandle, - alignment: TiptapTextAlign, -) -> Result<&'static str, String> { - let message = match alignment { - TiptapTextAlign::Left => "已切到左对齐", - TiptapTextAlign::Center => "已切到居中", - TiptapTextAlign::Right => "已切到右对齐", - TiptapTextAlign::Justify => "已切到两端对齐", - }; - editor - .set_text_align(alignment) - .map(|_| message) - .map_err(|err| format!("命令执行失败:{err}")) -} - -fn run_slash_action( - editor: TiptapEditorHandle, - action: SlashActionKind, -) -> Result<&'static str, String> { - let result = match action { - SlashActionKind::Paragraph => editor.set_paragraph(), - SlashActionKind::Heading1 => editor.toggle_heading(TiptapHeadingLevel::H1), - SlashActionKind::Heading2 => editor.toggle_heading(TiptapHeadingLevel::H2), - SlashActionKind::Heading3 => editor.toggle_heading(TiptapHeadingLevel::H3), - SlashActionKind::BulletList => editor.toggle_bullet_list(), - SlashActionKind::OrderedList => editor.toggle_ordered_list(), - SlashActionKind::Todo => editor.toggle_task_list(), - SlashActionKind::Quote => editor.toggle_blockquote(), - SlashActionKind::CodeBlock => editor.toggle_code_block(Some(TiptapCodeBlockAttributes { - language: Some("rust".into()), - })), - SlashActionKind::Divider => editor.set_horizontal_rule(), - }; - - result - .map(|_| match action { - SlashActionKind::Paragraph => "已切到段落", - SlashActionKind::Heading1 => "已切到一级标题", - SlashActionKind::Heading2 => "已切到二级标题", - SlashActionKind::Heading3 => "已切到三级标题", - SlashActionKind::BulletList => "已切到无序列表", - SlashActionKind::OrderedList => "已切到有序列表", - SlashActionKind::Todo => "已切到 Todo 列表", - SlashActionKind::Quote => "已切到引用块", - SlashActionKind::CodeBlock => "已切到代码块", - SlashActionKind::Divider => "已插入分割线", - }) - .map_err(|err| format!("命令执行失败:{err}")) -} - -fn run_block_turn_into_action( - editor: TiptapEditorHandle, - block_index: usize, - action: SlashActionKind, -) -> Result<&'static str, String> { - let document = editor - .get_json() - .map_err(|err| format!("读取当前 JSON 失败:{err}"))?; - let range = top_level_block_range(&document, block_index) - .ok_or_else(|| format!("找不到第 {} 个块的选择范围", block_index + 1))?; - - match action { - SlashActionKind::Divider => editor - .insert_content_at( - range, - TiptapContent::json(json!({ "type": "horizontalRule" })), - None, - ) - .map(|_| "已把当前块转成分割线") - .map_err(|err| format!("命令执行失败:{err}")), - _ => { - editor - .set_text_selection(range) - .map_err(|err| format!("选中当前块失败:{err}"))?; - editor - .clear_nodes() - .map_err(|err| format!("清理当前块样式失败:{err}"))?; - - let message = run_slash_action(editor, action)?; - let _ = editor.focus(); - let _ = editor.select_textblock_end(); - Ok(message) - } - } -} - -fn apply_feedback_result(setter: WriteSignal, result: Result<&'static str, E>) -where - E: Display, -{ - match result { - Ok(message) => setter.set(message.to_string()), - Err(err) => setter.set(format!("命令执行失败:{err}")), - } -} - -fn apply_ok_feedback( - setter: WriteSignal, - result: Result<(), E>, - ok_message: &'static str, -) where - E: Display, -{ - apply_feedback_result(setter, result.map(|_| ok_message)); -} - -#[component] -fn App() -> impl IntoView { - let editor = TiptapEditorHandle::new(); - let persisted = load_persisted_document(); - let restored_from_storage = persisted.is_some(); - let restored_html = persisted - .as_ref() - .and_then(|document| document.html.clone()); - let initial_title_value = persisted - .as_ref() - .map(|document| document.title.clone()) - .unwrap_or_else(default_title); - let initial_editor_content = persisted - .as_ref() - .map(|document| { - document - .html - .clone() - .map(TiptapContent::html) - .unwrap_or_else(|| TiptapContent::json(document.content.clone())) - }) - .unwrap_or_else(initial_content); - - let (title, set_title) = signal(initial_title_value); - let (html_output, set_html_output) = signal(String::new()); - let (document_json, set_document_json) = signal( - persisted - .as_ref() - .map(|document| document.content.clone()) - .unwrap_or_else(|| json!({"type": "doc", "content": []})), - ); - let (json_output, set_json_output) = signal(String::new()); - let (selection_state, set_selection_state) = signal(TiptapSelectionState::default()); - let (dirty_count, set_dirty_count) = signal(0_u32); - let (editor_focused, set_editor_focused) = signal(false); - let (text_selection_active, set_text_selection_active) = signal(false); - let (floating_toolbar_anchor, set_floating_toolbar_anchor) = - signal(None::); - let (locked_toolbar_anchor, set_locked_toolbar_anchor) = signal(None::); - let (slash_open, set_slash_open) = signal(false); - let (slash_index, set_slash_index) = signal(0_usize); - let (turn_into_open, set_turn_into_open) = signal(false); - let (color_menu_open, set_color_menu_open) = signal(false); - let (more_menu_open, set_more_menu_open) = signal(false); - let (hovered_block, set_hovered_block) = signal(None::); - let (block_menu_anchor, set_block_menu_anchor) = signal(None::); - let (block_menu_open, set_block_menu_open) = signal(false); - let (block_turn_into_open, set_block_turn_into_open) = signal(false); - let (pending_drag, set_pending_drag) = signal(None::); - let (dragging_block_index, set_dragging_block_index) = signal(None::); - let (dragging_block_anchor, set_dragging_block_anchor) = signal(None::); - let (drop_indicator, set_drop_indicator) = signal(None::); - let (suppress_handle_click, set_suppress_handle_click) = signal(false); - let (command_feedback, set_command_feedback) = signal("等待第一次编辑".to_string()); - - { - let block_menu_open = block_menu_open; - Effect::new(move |_| { - let Some(document) = window().and_then(|win| win.document()) else { - return; - }; - let Some(body) = document.body() else { - return; - }; - - if block_menu_open.get() { - let _ = body.style().set_property("overflow", "hidden"); - } else { - let _ = body.style().remove_property("overflow"); - } - }); - } - - { - let block_menu_open = block_menu_open; - let set_block_turn_into_open = set_block_turn_into_open; - Effect::new(move |_| { - if !block_menu_open.get() { - set_block_turn_into_open.set(false); - } - }); - } - - { - let turn_into_open = turn_into_open; - let color_menu_open = color_menu_open; - let more_menu_open = more_menu_open; - let set_locked_toolbar_anchor = set_locked_toolbar_anchor; - Effect::new(move |_| { - if !(turn_into_open.get() || color_menu_open.get() || more_menu_open.get()) { - set_locked_toolbar_anchor.set(None); - } - }); - } - - { - let editor_focused = editor_focused; - let text_selection_active = text_selection_active; - let slash_open = slash_open; - let block_menu_open = block_menu_open; - let turn_into_open = turn_into_open; - let color_menu_open = color_menu_open; - let more_menu_open = more_menu_open; - let set_turn_into_open = set_turn_into_open; - let set_color_menu_open = set_color_menu_open; - let set_more_menu_open = set_more_menu_open; - Effect::new(move |_| { - let toolbar_locked = toolbar_overlay_locked( - turn_into_open.get_untracked(), - color_menu_open.get_untracked(), - more_menu_open.get_untracked(), - ); - if ((!editor_focused.get() || !text_selection_active.get()) && !toolbar_locked) - || slash_open.get() - || block_menu_open.get() - { - set_turn_into_open.set(false); - set_color_menu_open.set(false); - set_more_menu_open.set(false); - } - }); - } - - { - let set_editor_focused = set_editor_focused; - let set_text_selection_active = set_text_selection_active; - let set_floating_toolbar_anchor = set_floating_toolbar_anchor; - let set_slash_open = set_slash_open; - let set_turn_into_open = set_turn_into_open; - let set_hovered_block = set_hovered_block; - let set_block_menu_anchor = set_block_menu_anchor; - let set_block_menu_open = set_block_menu_open; - let set_pending_drag = set_pending_drag; - let set_dragging_block_index = set_dragging_block_index; - let set_dragging_block_anchor = set_dragging_block_anchor; - let set_drop_indicator = set_drop_indicator; - let set_command_feedback = set_command_feedback; - let set_suppress_handle_click = set_suppress_handle_click; - let pending_drag = pending_drag; - let dragging_block_index = dragging_block_index; - let mouseup_handle = window_event_listener(ev::mouseup, move |event: MouseEvent| { - if let Some(source_index) = dragging_block_index.get_untracked() { - let indicator = drop_indicator_from_point(event.client_x(), event.client_y()); - if let Some(indicator) = indicator { - match editor.get_html() { - Ok(current_html) => match reorder_top_level_block_html( - ¤t_html, - source_index, - indicator.index, - indicator.placement, - ) { - Ok(next_html) => { - apply_html_update( - editor, - next_html, - set_dirty_count, - set_html_output, - set_document_json, - set_json_output, - title, - set_command_feedback, - "已通过块手柄拖拽重排", - ); - } - Err(err) => { - set_command_feedback.set(err); - } - }, - Err(err) => { - set_command_feedback.set(format!("读取当前 HTML 失败:{err}")); - } - } - } else { - set_command_feedback.set("块拖拽已取消".to_string()); - } - set_dragging_block_index.set(None); - set_dragging_block_anchor.set(None); - set_drop_indicator.set(None); - set_pending_drag.set(None); - set_block_menu_open.set(false); - set_block_menu_anchor.set(None); - set_hovered_block.set(None); - set_suppress_handle_click.set(true); - } else if pending_drag.get_untracked().is_some() { - set_pending_drag.set(None); - } - - if let Some(target) = event.target() { - if let Some(element) = target_element(target) { - if element - .closest(&format!("{HANDLE_SHELL_SELECTOR}, .floating-toolbar")) - .ok() - .flatten() - .is_some() - { - return; - } - } - } - sync_editor_overlay_state( - set_editor_focused, - set_text_selection_active, - set_floating_toolbar_anchor, - set_slash_open, - set_turn_into_open, - set_hovered_block, - set_block_menu_anchor, - set_block_menu_open, - ); - }); - let keyup_handle = window_event_listener(ev::keyup, move |_| { - sync_editor_overlay_state( - set_editor_focused, - set_text_selection_active, - set_floating_toolbar_anchor, - set_slash_open, - set_turn_into_open, - set_hovered_block, - set_block_menu_anchor, - set_block_menu_open, - ); - }); - - on_cleanup(move || { - drop(mouseup_handle); - drop(keyup_handle); - }); - } - - { - let set_editor_focused = set_editor_focused; - let set_slash_open = set_slash_open; - let set_turn_into_open = set_turn_into_open; - let set_hovered_block = set_hovered_block; - let set_block_menu_anchor = set_block_menu_anchor; - let set_block_menu_open = set_block_menu_open; - let set_pending_drag = set_pending_drag; - let set_dragging_block_index = set_dragging_block_index; - let set_dragging_block_anchor = set_dragging_block_anchor; - let set_drop_indicator = set_drop_indicator; - let set_command_feedback = set_command_feedback; - let pending_drag = pending_drag; - let dragging_block_index = dragging_block_index; - let dragging_block_anchor = dragging_block_anchor; - let mousemove_handle = window_event_listener(ev::mousemove, move |event: MouseEvent| { - if dragging_block_index.get_untracked().is_some() { - set_editor_focused.set(true); - set_drop_indicator.set(drop_indicator_from_point( - event.client_x(), - event.client_y(), - )); - return; - } - - let Some(pending) = pending_drag.get_untracked() else { - return; - }; - - if event.buttons() & 1 == 0 { - set_pending_drag.set(None); - return; - } - - let dx = (event.client_x() - pending.start_x).abs(); - let dy = (event.client_y() - pending.start_y).abs(); - if dx < 4 && dy < 4 { - return; - } - - set_editor_focused.set(true); - set_slash_open.set(false); - set_turn_into_open.set(false); - set_block_menu_open.set(false); - set_block_menu_anchor.set(None); - set_hovered_block.set(Some(pending.anchor.clone())); - set_dragging_block_index.set(Some(pending.index)); - set_dragging_block_anchor.set(Some( - dragging_block_anchor - .get_untracked() - .unwrap_or_else(|| pending.anchor.clone()), - )); - set_pending_drag.set(None); - set_drop_indicator.set(drop_indicator_from_point( - event.client_x(), - event.client_y(), - )); - set_command_feedback.set(format!("开始拖拽:{}", pending.anchor.label)); - }); - - on_cleanup(move || drop(mousemove_handle)); - } - - { - let editor = editor; - let set_slash_open = set_slash_open; - let slash_open = slash_open; - let slash_index = slash_index; - let set_slash_index = set_slash_index; - let set_turn_into_open = set_turn_into_open; - let set_block_menu_open = set_block_menu_open; - let set_block_menu_anchor = set_block_menu_anchor; - let set_command_feedback = set_command_feedback; - let keydown_handle = window_event_listener(ev::keydown, move |event| { - let focused = active_editor_stage(); - if !focused { - return; - } - - if event.key() == "Escape" { - set_slash_open.set(false); - set_turn_into_open.set(false); - set_block_menu_open.set(false); - set_block_menu_anchor.set(None); - return; - } - - if event.key() == "/" && !event.ctrl_key() && !event.meta_key() && !event.alt_key() { - event.prevent_default(); - set_slash_open.set(true); - set_turn_into_open.set(false); - set_block_menu_open.set(false); - set_block_menu_anchor.set(None); - set_slash_index.set(0); - set_command_feedback.set("Slash 菜单已打开".to_string()); - return; - } - - if !slash_open.get_untracked() { - return; - } - - match event.key().as_str() { - "ArrowDown" => { - event.prevent_default(); - let next = (slash_index.get_untracked() + 1) % SLASH_ACTIONS.len(); - set_slash_index.set(next); - } - "ArrowUp" => { - event.prevent_default(); - let current = slash_index.get_untracked(); - let next = if current == 0 { - SLASH_ACTIONS.len() - 1 - } else { - current - 1 - }; - set_slash_index.set(next); - } - "Enter" => { - event.prevent_default(); - let action = SLASH_ACTIONS[slash_index.get_untracked()].kind; - match run_slash_action(editor, action) { - Ok(message) => set_command_feedback.set(message.to_string()), - Err(message) => set_command_feedback.set(message), - } - set_slash_open.set(false); - } - "Escape" => { - event.prevent_default(); - set_slash_open.set(false); - set_command_feedback.set("Slash 菜单已关闭".to_string()); - } - _ => {} - } - }); - on_cleanup(move || drop(keydown_handle)); - } - - let has_task_schema = move || { - let snapshot = json_output.get(); - snapshot.contains("\"taskList\"") && snapshot.contains("\"taskItem\"") - }; - - let selection_text = move || selection_summary(&selection_state.get()); - let is_embedded = window() - .and_then(|win| win.location().search().ok()) - .map(|search| search.contains("embedded=1")) - .unwrap_or(false); - - let on_link_click = { - let editor = editor; - let selection_state = selection_state; - let set_command_feedback = set_command_feedback; - move |_| { - if selection_state.get().link { - apply_feedback_result( - set_command_feedback, - editor.unset_link().map(|_| "已移除链接"), - ); - return; - } - - let href = window() - .and_then(|win| win.prompt_with_message("输入链接地址").ok().flatten()) - .filter(|value| !value.trim().is_empty()); - - match href { - Some(value) => apply_feedback_result( - set_command_feedback, - editor - .set_link(TiptapLinkResource { - href: value, - target: Some("_blank".into()), - rel: Some("noopener noreferrer".into()), - class: None, - }) - .map(|_| "已插入链接"), - ), - None => set_command_feedback.set("链接操作已取消".to_string()), - } - } - }; - - view! { - -
-
-
- "P0 / Tiptap-like 主编辑器体验" -

"把 Spike 收敛成能检验的最小产品页壳"

-

- "这里继续只做 " - "8123" - " 的 Leptos + Tiptap P0 体验验证,不挪动正式 " - "/documents/[id]" - " 主链。目标是先把 slash、toolbar、todo schema、块手柄和 reload 做成可直接看得见、点得动、能刷新保留结构的网页。" -

-
-
-
- "变更计数" - {move || dirty_count.get().to_string()} -
-
- "Todo Schema" - {move || if has_task_schema() { "ready" } else { "pending" }} -
-
- "Selection" - {selection_text} -
-
-
- -
-
-
- "空间 / 主文档 /" - "Editor Baseline Reset" -
-
- "反馈:" - {move || command_feedback.get()} -
-
- - set_command_feedback.set("标题已写入本地草稿".to_string()), - Err(err) => set_command_feedback.set(format!("标题保存失败:{err}")), - } - } - placeholder="给这篇页面起个标题" - aria-label="Spike 页面标题" - /> - -
- "输入 “/” 打开真正的最小 slash 菜单" - "选中文本时会出现最小浮动工具条" - "Todo 现在走 taskList / taskItem,而不是占位 HTML" - "把鼠标移到块左侧,点击 ⠿ 打开块菜单并拖拽重排" - "本页会把 JSON 草稿写入 localStorage,刷新后不丢结构" -
- -
match reorder_top_level_block_html( - ¤t_html, - source_index, - indicator.index, - indicator.placement, - ) { - Ok(next_html) => { - apply_html_update( - editor, - next_html, - set_dirty_count, - set_html_output, - set_document_json, - set_json_output, - title, - set_command_feedback, - "已通过块手柄拖拽重排", - ); - } - Err(err) => { - set_command_feedback.set(err); - } - }, - Err(err) => { - set_command_feedback.set(format!("读取当前 HTML 失败:{err}")); - } - } - - set_dragging_block_index.set(None); - set_dragging_block_anchor.set(None); - set_drop_indicator.set(None); - set_block_menu_open.set(false); - set_block_menu_anchor.set(None); - set_hovered_block.set(None); - } - > - {move || { - let toolbar_locked = toolbar_overlay_locked( - turn_into_open.get(), - color_menu_open.get(), - more_menu_open.get(), - ); - let toolbar_anchor = if toolbar_locked { - locked_toolbar_anchor - .get() - .or_else(|| floating_toolbar_anchor.get()) - } else { - floating_toolbar_anchor.get() - }; - if let Some(anchor) = toolbar_anchor { - if ((!editor_focused.get() || !text_selection_active.get()) && !toolbar_locked) - || slash_open.get() - || block_menu_open.get() - || dragging_block_index.get().is_some() - { - return ().into_any(); - } - view! { -
-
-
- -
- {SLASH_ACTIONS.iter().map(|action| { - let kind = action.kind; - let label = action.label; - let description = action.description; - let testid = format!("turn-into-{}", action.id); - view! { - - } - }).collect_view()} -
-
-
- -
- -
- - - - - - -
- -
-
-
"文字颜色"
-
- {TOOLBAR_TEXT_COLORS.iter().map(|option| { - let value = option.value; - let label = option.label; - let testid = format!("toolbar-text-color-{}", option.id); - view! { - - } - }).collect_view()} -
-
- -
-
"背景颜色"
-
- {TOOLBAR_HIGHLIGHT_COLORS.iter().map(|option| { - let value = option.value; - let label = option.label; - let testid = format!("toolbar-highlight-color-{}", option.id); - view! { - - } - }).collect_view()} -
-
- -
- -
-
-
-
- -
- -
-
- -
-
-
"对齐方式"
-
- {TOOLBAR_ALIGN_OPTIONS.iter().map(|option| { - let label = option.label; - let alignment = option.alignment; - let testid = format!("toolbar-align-{}", option.id); - let active = match option.alignment { - TiptapTextAlign::Left => selection_state.get().align_left, - TiptapTextAlign::Center => selection_state.get().align_center, - TiptapTextAlign::Right => selection_state.get().align_right, - TiptapTextAlign::Justify => selection_state.get().align_justify, - }; - view! { - - } - }).collect_view()} -
-
-
-
-
-
- }.into_any() - } else { - ().into_any() - } - }} - - {move || { - if let Some(indicator) = drop_indicator.get() { - view! { -
- }.into_any() - } else { - ().into_any() - } - }} - - {move || { - let active_block = if block_menu_open.get() { - block_menu_anchor.get() - } else if dragging_block_index.get().is_some() { - dragging_block_anchor.get() - } else { - hovered_block.get() - }; - - if let Some(block) = active_block { - let dragging_index = dragging_block_index.get(); - let is_dragging = dragging_index - .map(|active| active == block.index) - .unwrap_or(false); - - if !editor_focused.get() - || text_selection_active.get() - || slash_open.get() - || (dragging_index.is_some() && !is_dragging) - { - return ().into_any(); - } - - let anchor_top = format!("{}px", hover_anchor_top(&block)); - let anchor_transform = hover_anchor_transform(&block); - let block_index = block.index; - let block_label = block.label.clone(); - let click_block_label = block_label.clone(); - let menu_block_label = block_label.clone(); - let duplicate_block_label = block_label.clone(); - let delete_block_label = block_label.clone(); - let insert_block_label = block_label.clone(); - let click_anchor_block = block.clone(); - let drag_anchor_block = block.clone(); - - view! { -
- - - - - {move || { - if block_menu_open.get() - && block_menu_anchor - .get() - .map(|current| current.index == block_index) - .unwrap_or(false) - { - let current_menu_label = menu_block_label.clone(); - let current_duplicate_label = duplicate_block_label.clone(); - let current_delete_label = delete_block_label.clone(); - let menu_layout = block_menu_layout(&block).unwrap_or(BlockMenuLayout { - max_height: 360.0, - open_upward: false, - }); - let menu_top = if menu_layout.open_upward { "auto" } else { "0" }; - let menu_bottom = if menu_layout.open_upward { "0" } else { "auto" }; - view! { -
-
- {current_menu_label.clone()} - {format!("顶层块 #{}", block_index + 1)} -
-
- {move || { - if block_turn_into_open.get() { - view! { -
- - {SLASH_ACTIONS - .iter() - .filter(|action| action.kind != SlashActionKind::Divider) - .map(|action| { - let kind = action.kind; - let label = action.label; - let testid = format!("block-drag-menu-item-{}", action.id); - let action_menu_label = current_menu_label.clone(); - view! { - - } - }) - .collect_view()} -
- }.into_any() - } else { - let duplicate_feedback_label = current_duplicate_label.clone(); - let delete_feedback_label = current_delete_label.clone(); - view! { - <> -
- -
-
-
- - -
- - }.into_any() - } - }} -
-
- }.into_any() - } else { - ().into_any() - } - }} -
- }.into_any() - } else { - ().into_any() - } - }} - - {move || { - if slash_open.get() { - view! { -
-
-

"Slash 菜单"

-

- "输入 " - "/" - " 后,用方向键选择,按回车执行。这里只保留 P0 需要的十个块命令。" -

-
-
- {SLASH_ACTIONS.iter().enumerate().map(|(index, action)| { - let is_selected = move || slash_index.get() == index; - let kind = action.kind; - let label = action.label; - let description = action.description; - let testid = format!("slash-item-{}", action.id); - view! { - - } - }).collect_view()} -
-
- } - .into_any() - } else { - ().into_any() - } - }} - - { - if restored_from_storage { - set_command_feedback.set("编辑器已准备就绪,并已恢复本地草稿".to_string()); - } else { - set_command_feedback.set("编辑器已准备就绪,当前内容已写入本地草稿".to_string()); - } - } - Err(err) => { - set_command_feedback.set(format!("编辑器已准备就绪,但草稿初始化失败:{err}")); - } - } - } - on_change=move |_| { - set_dirty_count.update(|count| *count += 1); - let snapshot = - sync_editor_outputs(editor, set_html_output, set_document_json, set_json_output); - match persist_document_state( - &title.get_untracked(), - &snapshot, - Some(html_output.get_untracked()), - ) { - Ok(()) => { - set_command_feedback.set("内容已变更,已同步观察值并写入本地草稿".to_string()); - } - Err(err) => { - set_command_feedback.set(format!("内容已变更,但本地保存失败:{err}")); - } - } - } - on_selection_change=move |selection: TiptapSelectionState| { - set_selection_state.set(selection); - let toolbar_locked = toolbar_overlay_locked( - turn_into_open.get_untracked(), - color_menu_open.get_untracked(), - more_menu_open.get_untracked(), - ); - let has_text_selection = if has_active_text_selection() { - sync_text_selection_overlay( - set_text_selection_active, - set_floating_toolbar_anchor, - ) - } else if toolbar_locked { - text_selection_active.get_untracked() - } else { - set_text_selection_active.set(false); - set_floating_toolbar_anchor.set(None); - false - }; - if has_text_selection { - if !toolbar_locked { - set_turn_into_open.set(false); - } - set_block_menu_open.set(false); - set_block_menu_anchor.set(None); - set_hovered_block.set(None); - } - } - attr:class="editor-surface" - /> -
- - -
- -
- - "调试抽屉:保留 HTML / JSON / Selection 观测,但不再主导页面" - "展开 / 收起" - -
-
-

"Selection"

-
{selection_text}
-
-
-

"HTML"

-
{move || html_output.get()}
-
-
-

"JSON"

-
{move || json_output.get()}
-
-
-
-
- } -} - -fn initial_content() -> TiptapContent { - TiptapContent::json(serde_json::json!({ - "type": "doc", - "content": [] - })) -} - fn main() { - console_error_panic_hook::set_once(); - mount_to_body(|| { - view! { } - }); + mnote_leptos_tiptap_spike::standalone_main(); } diff --git a/scripts/task108-document-default-editor-cutover-smoke.js b/scripts/task108-document-default-editor-cutover-smoke.js new file mode 100644 index 00000000..48cf4539 --- /dev/null +++ b/scripts/task108-document-default-editor-cutover-smoke.js @@ -0,0 +1,237 @@ +"use strict"; + +const { chromium } = require("playwright"); +const { + BASE_URL, + UI_TIMEOUT_MS, + assert, + createTempDocument, + ensureAuthenticated, + purgeDocument, +} = require("./tree-shell-smoke-helpers"); + +function readDocumentIdFromUrl(url) { + try { + const parsed = new URL(url); + const match = parsed.pathname.match(/^\/documents\/([^/]+)$/); + return match ? match[1] : null; + } catch { + return null; + } +} + +async function collectRuntimeIslandDiagnostics(page) { + return page.evaluate(() => { + const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]'); + const observability = document.querySelector("[data-editor-host-observability]"); + const editor = host?.querySelector(".editor-surface .ProseMirror"); + const textareaCount = host?.querySelectorAll("textarea").length ?? 0; + const contenteditableCount = host?.querySelectorAll(".editor-surface .ProseMirror[contenteditable]").length ?? 0; + return { + hostKind: host?.getAttribute("data-editor-host-kind") ?? null, + runtimeStatus: host?.getAttribute("data-runtime-editor-status") ?? null, + activeHostKind: observability?.getAttribute("data-editor-host-active") ?? null, + observability: observability?.getAttribute("data-editor-host-observability") ?? null, + editorTagName: editor instanceof HTMLElement ? editor.tagName : null, + editorIsContentEditable: editor instanceof HTMLElement ? editor.isContentEditable : false, + editorContentEditableAttr: editor instanceof HTMLElement ? editor.getAttribute("contenteditable") : null, + editorCount: host?.querySelectorAll(".editor-surface .ProseMirror").length ?? 0, + textareaCount, + contenteditableCount, + hostHTML: host?.innerHTML?.slice(0, 2000) ?? null, + }; + }); +} + +async function waitForRuntimeIsland(page) { + const root = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]'); + await root.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); + try { + await page.waitForFunction( + () => { + const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]'); + const observability = document.querySelector("[data-editor-host-observability]"); + const editor = host?.querySelector(".editor-surface .ProseMirror"); + return ( + host?.getAttribute("data-editor-host-kind") === "leptos_tiptap_island" && + observability?.getAttribute("data-editor-host-active") === "leptos_tiptap_island" && + host?.getAttribute("data-runtime-editor-status") !== "error" && + editor instanceof HTMLElement && + editor.isContentEditable === true + ); + }, + null, + { timeout: UI_TIMEOUT_MS }, + ); + } catch (error) { + const diagnostics = await collectRuntimeIslandDiagnostics(page).catch(() => null); + throw new Error( + `${error instanceof Error ? error.message : String(error)}\n${JSON.stringify(diagnostics, null, 2)}`, + ); + } + + const editorCount = await root.locator(".editor-surface .ProseMirror").count(); + const textareaCount = await root.locator("textarea").count(); + const contenteditableCount = await root.locator(".editor-surface .ProseMirror[contenteditable]").count(); + if (editorCount === 0 || contenteditableCount === 0 || textareaCount > 0) { + const diagnostics = await collectRuntimeIslandDiagnostics(page).catch(() => null); + throw new Error( + [ + editorCount === 0 ? "island 主编辑器根节点内缺少 `.editor-surface .ProseMirror` surface" : null, + contenteditableCount === 0 ? "island 主编辑器 surface 未暴露真实 contenteditable" : null, + textareaCount > 0 ? "island 主编辑器根节点内不应回退为 textarea" : null, + ] + .filter(Boolean) + .join(";") + + `\n${JSON.stringify(diagnostics, null, 2)}`, + ); + } +} + +async function waitForSaved(page) { + await page.waitForFunction( + () => + document + .querySelector('[data-editor-host-kind="leptos_tiptap_island"]') + ?.getAttribute("data-runtime-editor-status") === "saved", + null, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function readEditorText(page) { + return page.evaluate(() => { + const editor = document.querySelector( + '[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror', + ); + return editor?.textContent ?? ""; + }); +} + +async function main() { + const browser = await chromium.launch({ headless: true }); + const context = await browser.newContext({ + viewport: { width: 1440, height: 960 }, + }); + const page = await context.newPage(); + + let caughtError = null; + let createdDocumentId = null; + let createdWorkspaceId = null; + + try { + await ensureAuthenticated(page, context.request); + const created = await createTempDocument(context.request, null); + createdDocumentId = created.documentId; + createdWorkspaceId = created.workspaceId; + + await page.goto( + `${BASE_URL}/documents/${createdDocumentId}?workspaceId=${encodeURIComponent(createdWorkspaceId)}`, + { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }, + ); + assert( + page.url().includes(`/documents/${createdDocumentId}`), + `未进入新建页面:${page.url()}`, + ); + + await waitForRuntimeIsland(page); + + const editor = page + .locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]') + .first(); + const text = `task108-island-${Date.now().toString().slice(-6)}`; + + await editor.evaluate((el) => { + if (el instanceof HTMLElement) { + el.focus(); + } + }); + await page.keyboard.type(text, { delay: 30 }); + await waitForSaved(page); + assert((await readEditorText(page)).includes(text), "默认 runtime island 未写入文本"); + + await page.keyboard.press("Control+z"); + await page.waitForFunction( + (expected) => { + const editorNode = document.querySelector( + '[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]', + ); + return !(editorNode?.textContent ?? "").includes(expected); + }, + text, + { timeout: UI_TIMEOUT_MS }, + ); + + await page.keyboard.press("Control+y"); + await page.waitForFunction( + (expected) => { + const editorNode = document.querySelector( + '[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]', + ); + return (editorNode?.textContent ?? "").includes(expected); + }, + text, + { timeout: UI_TIMEOUT_MS }, + ); + await waitForSaved(page); + + await page.reload({ waitUntil: "commit", timeout: UI_TIMEOUT_MS }); + await waitForRuntimeIsland(page); + assert((await readEditorText(page)).includes(text), "刷新后未回填 runtime island 保存内容"); + + await page.goto( + `${BASE_URL}/documents/${createdDocumentId}?workspaceId=${encodeURIComponent(createdWorkspaceId)}&editorHost=blocknote`, + { waitUntil: "commit", timeout: UI_TIMEOUT_MS }, + ); + await page.waitForFunction( + () => + document + .querySelector("[data-editor-host-observability]") + ?.getAttribute("data-editor-host-active") === "blocknote", + null, + { timeout: UI_TIMEOUT_MS }, + ); + const runtimeIslandCount = await page + .locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]') + .count(); + assert(runtimeIslandCount === 0, "显式 blocknote 回退下不应继续挂载 island 主编辑器"); + + console.log( + JSON.stringify( + { + ok: true, + baseUrl: BASE_URL, + documentId: createdDocumentId, + workspaceId: createdWorkspaceId, + text, + }, + null, + 2, + ), + ); + } catch (error) { + caughtError = error; + } finally { + if (createdDocumentId) { + try { + await purgeDocument(context.request, createdDocumentId); + } catch (cleanupError) { + if (!caughtError) { + caughtError = cleanupError; + } + } + } + await page.close().catch(() => undefined); + await context.close().catch(() => undefined); + await browser.close().catch(() => undefined); + } + + if (caughtError) { + throw caughtError; + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.stack || error.message : String(error)); + process.exit(1); +}); diff --git a/scripts/task109-leptos-island-multipage-save-smoke.js b/scripts/task109-leptos-island-multipage-save-smoke.js new file mode 100644 index 00000000..02c50827 --- /dev/null +++ b/scripts/task109-leptos-island-multipage-save-smoke.js @@ -0,0 +1,217 @@ +"use strict"; + +const { chromium } = require("playwright"); +const { + BASE_URL, + UI_TIMEOUT_MS, + assert, + createTempDocument, + ensureAuthenticated, + purgeDocument, +} = require("./tree-shell-smoke-helpers"); + +async function waitForRuntimeIsland(page) { + await page.waitForFunction( + () => { + const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]'); + const editor = host?.querySelector(".editor-surface .ProseMirror[contenteditable='true']"); + return ( + host?.getAttribute("data-editor-host-kind") === "leptos_tiptap_island" && + host?.getAttribute("data-runtime-editor-status") !== "error" && + editor instanceof HTMLElement && + editor.isContentEditable + ); + }, + null, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function waitForSaved(page) { + await page.waitForFunction( + () => + document + .querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]') + ?.getAttribute("data-runtime-editor-status") === "saved", + null, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function waitForTextPresent(page, text) { + await page.waitForFunction( + (expected) => { + const editor = document.querySelector( + '[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror', + ); + return (editor?.textContent ?? "").includes(expected); + }, + text, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function waitForPersisted(page, saveRequests, documentId, expectedText) { + const deadline = Date.now() + UI_TIMEOUT_MS; + while (Date.now() < deadline) { + const editorText = await readEditorText(page); + const runtimeStatus = await page.evaluate(() => { + return ( + document + .querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]') + ?.getAttribute("data-runtime-editor-status") ?? null + ); + }); + const hasSaveRequest = saveRequests.some((item) => item.documentId === documentId); + if (editorText.includes(expectedText) && (runtimeStatus === "saved" || hasSaveRequest)) { + return; + } + await page.waitForTimeout(250); + } + throw new Error(`等待持久化超时:${documentId}`); +} + +async function typeIntoEditor(page, text) { + const editor = page + .locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]') + .first(); + await editor.click({ timeout: UI_TIMEOUT_MS }); + await page.keyboard.press("Control+a"); + await page.keyboard.press("Backspace"); + await page.keyboard.type(text, { delay: 30 }); +} + +async function readEditorText(page) { + return page.evaluate(() => { + const editor = document.querySelector( + '[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror', + ); + return editor?.textContent ?? ""; + }); +} + +async function openDocument(page, documentId, workspaceId) { + await page.goto( + `${BASE_URL}/documents/${documentId}?workspaceId=${encodeURIComponent(workspaceId)}`, + { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }, + ); + await waitForRuntimeIsland(page); +} + +async function main() { + const browser = await chromium.launch({ headless: true }); + const context = await browser.newContext({ + viewport: { width: 1440, height: 960 }, + }); + const page = await context.newPage(); + + let docA = null; + let docB = null; + let caughtError = null; + const saveRequests = []; + + page.on("request", (request) => { + if (!request.url().includes("/api/documents/save") || request.method() !== "POST") { + return; + } + const payload = request.postDataJSON(); + saveRequests.push({ + documentId: payload?.documentId ?? null, + workspaceId: payload?.workspaceId ?? null, + revision: payload?.revision ?? null, + }); + }); + + try { + await ensureAuthenticated(page, context.request); + docA = await createTempDocument(context.request, null); + docB = await createTempDocument(context.request, null); + + const textA = `doc-a-${Date.now().toString().slice(-6)}`; + const textB = `doc-b-${(Date.now() + 1).toString().slice(-6)}`; + + await openDocument(page, docA.documentId, docA.workspaceId); + await typeIntoEditor(page, textA); + await waitForTextPresent(page, textA); + await waitForPersisted(page, saveRequests, docA.documentId, textA); + assert((await readEditorText(page)).includes(textA), "A 页文本未进入编辑区"); + + await openDocument(page, docB.documentId, docB.workspaceId); + await typeIntoEditor(page, textB); + await waitForTextPresent(page, textB); + await waitForPersisted(page, saveRequests, docB.documentId, textB); + assert((await readEditorText(page)).includes(textB), "B 页文本未进入编辑区"); + + await openDocument(page, docA.documentId, docA.workspaceId); + assert((await readEditorText(page)).includes(textA), "切回 A 页后内容串页或丢失"); + + await page.reload({ waitUntil: "commit", timeout: UI_TIMEOUT_MS }); + await waitForRuntimeIsland(page); + assert((await readEditorText(page)).includes(textA), "A 页刷新后未回填"); + + await openDocument(page, docB.documentId, docB.workspaceId); + assert((await readEditorText(page)).includes(textB), "切回 B 页后内容串页或丢失"); + + await page.reload({ waitUntil: "commit", timeout: UI_TIMEOUT_MS }); + await waitForRuntimeIsland(page); + assert((await readEditorText(page)).includes(textB), "B 页刷新后未回填"); + + const savedDocumentIds = new Set(saveRequests.map((item) => item.documentId).filter(Boolean)); + assert(savedDocumentIds.has(docA.documentId), "未观察到 A 页保存请求"); + assert(savedDocumentIds.has(docB.documentId), "未观察到 B 页保存请求"); + assert( + saveRequests.some( + (item) => item.documentId === docA.documentId && item.workspaceId === docA.workspaceId, + ), + "A 页保存请求缺少正确 workspaceId/documentId 绑定", + ); + assert( + saveRequests.some( + (item) => item.documentId === docB.documentId && item.workspaceId === docB.workspaceId, + ), + "B 页保存请求缺少正确 workspaceId/documentId 绑定", + ); + + console.log( + JSON.stringify( + { + ok: true, + docA, + docB, + saveRequests, + textA, + textB, + }, + null, + 2, + ), + ); + } catch (error) { + caughtError = error; + } finally { + for (const doc of [docA, docB]) { + if (!doc?.documentId) { + continue; + } + try { + await purgeDocument(context.request, doc.documentId); + } catch (cleanupError) { + if (!caughtError) { + caughtError = cleanupError; + } + } + } + await page.close().catch(() => undefined); + await context.close().catch(() => undefined); + await browser.close().catch(() => undefined); + } + + if (caughtError) { + throw caughtError; + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.stack || error.message : String(error)); + process.exit(1); +}); diff --git a/scripts/task110-page-title-single-truth-smoke.js b/scripts/task110-page-title-single-truth-smoke.js new file mode 100644 index 00000000..1d486941 --- /dev/null +++ b/scripts/task110-page-title-single-truth-smoke.js @@ -0,0 +1,217 @@ +"use strict"; + +const { chromium } = require("playwright"); +const { + BASE_URL, + UI_TIMEOUT_MS, + assert, + cleanupDocuments, + createTempDocument, + ensureAuthenticated, + openDocument, + openFilesystemView, + openSectionView, + renameDocument, +} = require("./tree-shell-smoke-helpers"); + +async function waitForPageTitleInput(page) { + const input = page.getByLabel("页面标题"); + await input.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); + return input; +} + +async function waitForTitleSave(page, documentId, expectedTitle) { + await page.waitForResponse( + async (response) => { + if (!response.url().includes("/api/documents/title") || response.request().method() !== "POST") { + return false; + } + const payload = response.request().postDataJSON(); + return payload?.documentId === documentId && payload?.title === expectedTitle && response.ok(); + }, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function renameThroughPageHead(page, documentId, title) { + const titleInput = await waitForPageTitleInput(page); + await titleInput.click({ timeout: UI_TIMEOUT_MS }); + await page.keyboard.press("Control+a"); + await page.keyboard.type(title, { delay: 20 }); + await titleInput.blur(); + await waitForTitleSave(page, documentId, title); +} + +async function waitForBreadcrumbTitle(page, title) { + await page.waitForFunction( + (expectedTitle) => { + const nav = document.querySelector("header nav"); + return (nav?.textContent ?? "").includes(expectedTitle); + }, + title, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function waitForSidebarRowTitle(page, documentId, title) { + await page.waitForFunction( + ({ docId, expectedTitle }) => { + const row = document.querySelector(`aside a[href="/documents/${docId}"]`); + return (row?.textContent ?? "").includes(expectedTitle); + }, + { docId: documentId, expectedTitle: title }, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function waitForPageTreeTitle(page, documentId, title) { + await openSectionView(page); + const shellHost = page.getByTestId("sidebar-page-tree-shell"); + await shellHost.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); + await page.waitForFunction( + ({ nodeId, expectedTitle }) => { + const row = document.querySelector( + `[data-testid="page-tree-row"][data-node-id="${nodeId}"]`, + ); + return (row?.textContent ?? "").includes(expectedTitle); + }, + { nodeId: documentId, expectedTitle: title }, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function waitForFileTreeTitle(page, documentId, title) { + await openFilesystemView(page); + const shellHost = page.getByTestId("sidebar-file-tree-shell"); + await shellHost.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); + await page.waitForFunction( + ({ docId, expectedTitle }) => { + const row = document.querySelector( + `[data-testid="filetree-doc-row"][data-doc-id="${docId}"]`, + ); + return (row?.textContent ?? "").includes(expectedTitle); + }, + { docId: documentId, expectedTitle: title }, + { timeout: UI_TIMEOUT_MS }, + ); +} + +async function readVisibleTitle(page) { + const titleInput = page.getByLabel("页面标题"); + if (await titleInput.isVisible().catch(() => false)) { + return (await titleInput.inputValue()).trim(); + } + const heading = page.locator("h1").first(); + return ((await heading.textContent()) ?? "").trim(); +} + +async function main() { + const browser = await chromium.launch({ headless: true }); + const context = await browser.newContext({ + viewport: { width: 1440, height: 960 }, + }); + const page = await context.newPage(); + + let caughtError = null; + let fixture = null; + + try { + const viewer = await ensureAuthenticated(page, context.request); + const first = await createTempDocument(context.request, null); + const second = await createTempDocument(context.request, null); + const initialTitle = `phase-i-initial-${Date.now().toString().slice(-6)}`; + const renamedTitle = `phase-i-renamed-${(Date.now() + 1).toString().slice(-6)}`; + const siblingTitle = `phase-i-sibling-${(Date.now() + 2).toString().slice(-6)}`; + + await renameDocument(context.request, first.workspaceId, first.documentId, initialTitle); + await renameDocument(context.request, second.workspaceId, second.documentId, siblingTitle); + + fixture = { + workspaceId: first.workspaceId, + primaryId: first.documentId, + siblingId: second.documentId, + createdIds: [first.documentId, second.documentId], + initialTitle, + renamedTitle, + siblingTitle, + }; + + await openDocument(page, fixture.workspaceId, fixture.primaryId); + await waitForPageTitleInput(page); + assert((await readVisibleTitle(page)).includes(initialTitle), "页头未回填初始标题"); + + await renameThroughPageHead(page, fixture.primaryId, fixture.renamedTitle); + assert((await readVisibleTitle(page)).includes(fixture.renamedTitle), "页头未显示最新标题"); + + await waitForBreadcrumbTitle(page, fixture.renamedTitle); + await waitForSidebarRowTitle(page, fixture.primaryId, fixture.renamedTitle); + await waitForPageTreeTitle(page, fixture.primaryId, fixture.renamedTitle); + await waitForFileTreeTitle(page, fixture.primaryId, fixture.renamedTitle); + + await openDocument(page, fixture.workspaceId, fixture.siblingId); + await waitForPageTitleInput(page); + assert((await readVisibleTitle(page)).includes(fixture.siblingTitle), "切到兄弟页后标题不正确"); + + await openDocument(page, fixture.workspaceId, fixture.primaryId); + await waitForPageTitleInput(page); + await waitForBreadcrumbTitle(page, fixture.renamedTitle); + await waitForSidebarRowTitle(page, fixture.primaryId, fixture.renamedTitle); + assert((await readVisibleTitle(page)).includes(fixture.renamedTitle), "切页往返后页头标题回闪"); + + await page.reload({ waitUntil: "commit", timeout: UI_TIMEOUT_MS }); + await waitForPageTitleInput(page); + await waitForBreadcrumbTitle(page, fixture.renamedTitle); + await waitForSidebarRowTitle(page, fixture.primaryId, fixture.renamedTitle); + await waitForPageTreeTitle(page, fixture.primaryId, fixture.renamedTitle); + await waitForFileTreeTitle(page, fixture.primaryId, fixture.renamedTitle); + assert((await readVisibleTitle(page)).includes(fixture.renamedTitle), "刷新后页头标题未保持一致"); + + console.log( + JSON.stringify( + { + ok: true, + baseUrl: BASE_URL, + viewerUserId: viewer.userId, + workspaceId: fixture.workspaceId, + primaryId: fixture.primaryId, + siblingId: fixture.siblingId, + renamedTitle: fixture.renamedTitle, + }, + null, + 2, + ), + ); + } catch (error) { + caughtError = error; + } finally { + if (fixture) { + try { + await cleanupDocuments(context.request, fixture.createdIds); + } catch (cleanupError) { + if (!caughtError) { + caughtError = cleanupError; + } else { + console.error( + `清理临时页面失败:${ + cleanupError instanceof Error + ? cleanupError.stack || cleanupError.message + : String(cleanupError) + }`, + ); + } + } + } + await page.close().catch(() => undefined); + await context.close().catch(() => undefined); + await browser.close().catch(() => undefined); + } + + if (caughtError) { + throw caughtError; + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.stack || error.message : String(error)); + process.exit(1); +}); diff --git a/wolai-frontend/scripts/build-leptos-tiptap-island.js b/wolai-frontend/scripts/build-leptos-tiptap-island.js new file mode 100644 index 00000000..9337db9a --- /dev/null +++ b/wolai-frontend/scripts/build-leptos-tiptap-island.js @@ -0,0 +1,115 @@ +#!/usr/bin/env node +"use strict"; + +const fs = require("fs/promises"); +const path = require("path"); +const { spawnSync } = require("child_process"); + +const REPO_ROOT = path.resolve(__dirname, "..", ".."); +const SPIKE_ROOT = path.join(REPO_ROOT, "rust", "spikes", "leptos-tiptap-spike"); +const GENERATED_ROOT = path.join(SPIKE_ROOT, "generated", "island"); +const TOOLCHAIN = "1.89.0-x86_64-unknown-linux-gnu"; +const TARGET = "wasm32-unknown-unknown"; +const OUT_NAME = "mnote-leptos-tiptap-spike-island"; +const MANIFEST_PATH = path.join(SPIKE_ROOT, "Cargo.toml"); +const WASM_PATH = path.join( + SPIKE_ROOT, + "target", + TARGET, + "debug", + "mnote_leptos_tiptap_spike.wasm", +); +const ENTRY_PATH = path.join(GENERATED_ROOT, `${OUT_NAME}.js`); + +function run(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd ?? REPO_ROOT, + env: process.env, + encoding: "utf8", + stdio: "pipe", + }); + + if (result.status === 0) { + return result; + } + + const stdout = (result.stdout || "").trim(); + const stderr = (result.stderr || "").trim(); + const details = [stdout, stderr].filter(Boolean).join("\n"); + throw new Error( + [`命令失败:${command} ${args.join(" ")}`, details].filter(Boolean).join("\n"), + ); +} + +async function ensureGeneratedDir() { + await fs.rm(GENERATED_ROOT, { recursive: true, force: true }); + await fs.mkdir(GENERATED_ROOT, { recursive: true }); +} + +async function verifyEntry() { + const source = await fs.readFile(ENTRY_PATH, "utf8"); + if (!source.includes("export function mount(container, options)")) { + throw new Error("island 入口缺少 mount 导出"); + } + if (!source.includes("export function unmount(mount_id)")) { + throw new Error("island 入口缺少 unmount 导出"); + } +} + +async function buildLeptosTiptapIsland() { + // 说明:正式主链直接消费 lib.rs 的 wasm-bindgen 产物,不再把 trunk 演示页产物当作页面内 island 入口。 + run("rustup", ["target", "add", TARGET, "--toolchain", TOOLCHAIN]); + run( + "cargo", + [ + `+${TOOLCHAIN}`, + "build", + "--manifest-path", + MANIFEST_PATH, + "--lib", + "--target", + TARGET, + ], + { cwd: SPIKE_ROOT }, + ); + + await ensureGeneratedDir(); + + run( + "wasm-bindgen", + [ + WASM_PATH, + "--target", + "web", + "--out-dir", + GENERATED_ROOT, + "--out-name", + OUT_NAME, + ], + { cwd: SPIKE_ROOT }, + ); + + await verifyEntry(); + return { + generatedRoot: GENERATED_ROOT, + entryPath: ENTRY_PATH, + wasmPath: path.join(GENERATED_ROOT, `${OUT_NAME}_bg.wasm`), + }; +} + +module.exports = { + buildLeptosTiptapIsland, + GENERATED_ROOT, + OUT_NAME, +}; + +if (require.main === module) { + buildLeptosTiptapIsland() + .then(({ generatedRoot }) => { + process.stdout.write(`leptos-tiptap island 已生成:${generatedRoot}\n`); + }) + .catch((error) => { + process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); + process.exit(1); + }); +} diff --git a/wolai-frontend/scripts/dev-server.js b/wolai-frontend/scripts/dev-server.js index d5195038..7efa9019 100644 --- a/wolai-frontend/scripts/dev-server.js +++ b/wolai-frontend/scripts/dev-server.js @@ -12,11 +12,12 @@ * - ONLYOFFICE_INTERNAL_URL:可显式指定;未指定或失效时优先探测 8082,再回退 8081 */ -const http = require("http"); -const net = require("net"); -const path = require("path"); -const next = require("next"); -const { parse: parseUrl } = require("url"); +const http = require("http"); +const net = require("net"); +const path = require("path"); +const next = require("next"); +const { parse: parseUrl } = require("url"); +const { buildLeptosTiptapIsland } = require("./build-leptos-tiptap-island"); const ONLYOFFICE_PREFIX = "/onlyoffice-server"; const CONVEX_PREFIX = "/convex"; @@ -384,12 +385,15 @@ function proxyConvexHttp(req, res) { req.pipe(upstreamReq); } -async function main() { - const port = resolvePort(); - const hostname = resolveHostname(); - const dev = true; - - const app = next({ dev, dir: path.join(__dirname, "..") }); +async function main() { + const port = resolvePort(); + const hostname = resolveHostname(); + const dev = true; + + // 说明:3000 主链需要直接挂载正式 Leptos island,因此在 Next dev 启动前先生成 lib.rs 的 wasm-bindgen 产物。 + await buildLeptosTiptapIsland(); + + const app = next({ dev, dir: path.join(__dirname, "..") }); const handle = app.getRequestHandler(); await app.prepare(); diff --git a/wolai-frontend/src/app/(app)/documents/[id]/page.tsx b/wolai-frontend/src/app/(app)/documents/[id]/page.tsx index e0620a37..3248a831 100644 --- a/wolai-frontend/src/app/(app)/documents/[id]/page.tsx +++ b/wolai-frontend/src/app/(app)/documents/[id]/page.tsx @@ -9,7 +9,14 @@ import { buildDocumentBridgeContext, buildDocumentQueryEnvelope } from "@/lib/do import type { PageSubtreeProjection } from "@/lib/documents/page-subtree"; import { normalizeDocumentContentResponse } from "@/lib/documents/page-subtree-response"; import { executeRustBridgeQueryTransport, resolveRustBridgeQueryPlan } from "@/lib/documents/rust-runtime"; -import { normalizeEditorHostKind, type EditorHostKind } from "@/components/editor/editor-host-config"; +import { + DEFAULT_EDITOR_HOST_KIND, + normalizeEditorHostKind, + resolveEditorHostKind, + type EditorHostKind, +} from "@/components/editor/editor-host-config"; +import { getMnoteRuntimeConfig } from "@/lib/runtime-config"; +import { buildPageAggregate } from "@/lib/documents/page-aggregate"; interface DocumentPageProps { params: Promise<{ id: string }>; @@ -128,9 +135,36 @@ export default async function DocumentPage({ params, searchParams }: DocumentPag const resolvedSearch = (await searchParams) ?? {}; const openTableIdRaw = resolvedSearch?.openTableId; const openTableId = typeof openTableIdRaw === "string" ? openTableIdRaw : null; - const editorHostRaw = resolvedSearch?.editorHost; - const editorHostKind: EditorHostKind = - typeof editorHostRaw === "string" ? normalizeEditorHostKind(editorHostRaw) : "blocknote"; + const runtimeConfig = getMnoteRuntimeConfig(); + const queryEditorHostRaw = resolvedSearch?.editorHost; + const queryHostAliasRaw = resolvedSearch?.host; + const queryHostRaw = + typeof queryEditorHostRaw === "string" + ? queryEditorHostRaw + : typeof queryHostAliasRaw === "string" + ? queryHostAliasRaw + : undefined; + const runtimeHostRaw = runtimeConfig.documentEditorHost; + const runtimeBlocknoteKillSwitch = + runtimeConfig.documentEditorBlocknoteKillSwitch === true; + + // 说明:优先级保持稳定且可预期: + // 1) query(兼容 editorHost,并支持 host 别名); + // 2) 运行时配置 documentEditorHost; + // 3) kill switch(runtime/env)回退到 blocknote; + // 4) 默认正式主链 leptos_tiptap_island。 + const editorHostKind: EditorHostKind = (() => { + if (typeof queryHostRaw === "string") { + return resolveEditorHostKind({ + override: queryHostRaw, + runtimeDefault: runtimeHostRaw, + }); + } + if (runtimeBlocknoteKillSwitch) { + return "blocknote"; + } + return normalizeEditorHostKind(runtimeHostRaw, DEFAULT_EDITOR_HOST_KIND); + })(); if (isConvexEnabled()) { const workspaceIdRaw = resolvedSearch?.workspaceId; @@ -176,25 +210,29 @@ export default async function DocumentPage({ params, searchParams }: DocumentPag title: doc.title ?? "无标题", }); + const page = buildPageAggregate({ + documentId: doc.id, + workspaceId: doc.workspace_id, + title: doc.title ?? "无标题", + updatedAt: doc.updated_at, + readOnly, + disableDownload, + disableCopy, + pageOptions: initialOptions, + content: initialDocumentContent.content, + revision: initialDocumentContent.revision, + conflictDetectionKey: initialDocumentContent.conflictDetectionKey, + pageSubtree: initialDocumentContent.pageSubtree, + stats: initialStats, + }); + return (
diff --git a/wolai-frontend/src/app/(app)/layout.tsx b/wolai-frontend/src/app/(app)/layout.tsx index 019401b7..a43b0e3e 100644 --- a/wolai-frontend/src/app/(app)/layout.tsx +++ b/wolai-frontend/src/app/(app)/layout.tsx @@ -1,9 +1,6 @@ import { redirect } from "next/navigation"; import type { ReactNode } from "react"; -import { Sidebar } from "@/components/sidebar/sidebar"; -import { Breadcrumb } from "@/components/breadcrumb"; -import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"; -import { SearchPalette } from "@/components/search/search-palette"; +import { AppLayoutShell } from "@/components/app-layout-shell"; import { isConvexEnabled } from "@/lib/convex/enabled"; import { getAuthedConvexClient } from "@/lib/convex/route"; import { loadSidebarDataFromConvex } from "@/lib/server/sidebar-data"; @@ -12,25 +9,26 @@ export default async function AppLayout({ children }: { children: ReactNode }) { if (isConvexEnabled()) { const { auth, client } = await getAuthedConvexClient(); const { - documents, sidebarInitialData, } = await loadSidebarDataFromConvex({ client, fallbackName: auth.name ?? auth.email ?? "我的空间", }); - return ( -
- {sidebarInitialData && } -
-
- - -
-
{children}
- + if (!sidebarInitialData) { + return ( +
+
+
{children}
+
-
+ ); + } + + return ( + + {children} + ); } diff --git a/wolai-frontend/src/app/api/ai-agent/run/route.test.ts b/wolai-frontend/src/app/api/ai-agent/run/route.test.ts new file mode 100644 index 00000000..30563407 --- /dev/null +++ b/wolai-frontend/src/app/api/ai-agent/run/route.test.ts @@ -0,0 +1,123 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mockSafeGetJsonBody = vi.fn(); +const mockValidateRequestBody = vi.fn(); +const mockIsConvexEnabled = vi.fn(); +const mockGetAuthedConvexClient = vi.fn(); +const mockStartHermesRun = vi.fn(); +const mockStreamHermesRunEvents = vi.fn(); +const mockFetchHermesStructuredToolResultFromMnoteWeb = vi.fn(); + +vi.mock("@/lib/api-utils", async () => { + const actual = await vi.importActual("@/lib/api-utils"); + return { + ...actual, + safeGetJsonBody: mockSafeGetJsonBody, + validateRequestBody: mockValidateRequestBody, + }; +}); + +vi.mock("@/lib/convex/enabled", () => ({ + isConvexEnabled: mockIsConvexEnabled, +})); + +vi.mock("@/lib/convex/route", () => ({ + getAuthedConvexClient: mockGetAuthedConvexClient, +})); + +vi.mock("@/lib/ai-agent/hermes/bridge", () => ({ + startHermesRun: mockStartHermesRun, + streamHermesRunEvents: mockStreamHermesRunEvents, +})); + +vi.mock("@/lib/server/mnote-web-hermes", () => ({ + fetchHermesStructuredToolResultFromMnoteWeb: mockFetchHermesStructuredToolResultFromMnoteWeb, +})); + +describe("/api/ai-agent/run route", () => { + beforeEach(() => { + mockSafeGetJsonBody.mockReset(); + mockValidateRequestBody.mockReset(); + mockIsConvexEnabled.mockReset(); + mockGetAuthedConvexClient.mockReset(); + mockStartHermesRun.mockReset(); + mockStreamHermesRunEvents.mockReset(); + mockFetchHermesStructuredToolResultFromMnoteWeb.mockReset(); + }); + + it("应把 Hermes slash_run 完成事件恢复成结构化 tool_result", async () => { + mockSafeGetJsonBody.mockResolvedValue({ + stream: true, + scope: "document", + messages: [{ role: "user", content: "把标题改成 AI 标题" }], + context: { + documentId: "doc-1", + }, + options: { + ai: { + provider: "online", + }, + }, + }); + mockValidateRequestBody.mockReturnValue(null); + mockIsConvexEnabled.mockReturnValue(true); + mockGetAuthedConvexClient.mockResolvedValue({ + auth: { + userId: "user-1", + }, + }); + mockStartHermesRun.mockResolvedValue({ + runId: "run-1", + }); + mockStreamHermesRunEvents.mockImplementation(async (_runId, onEvent) => { + await onEvent({ + event: "tool.started", + tool: "slash_run", + preview: '{"text":"/rename doc-1 AI 标题"}', + }); + await onEvent({ + event: "tool.completed", + tool: "slash_run", + duration: 0.12, + error: false, + }); + await onEvent({ + event: "run.completed", + output: "已完成", + }); + }); + mockFetchHermesStructuredToolResultFromMnoteWeb.mockResolvedValue({ + ok: true, + parsed: { + command: "rename_doc", + params: { + documentId: "doc-1", + title: "AI 标题", + }, + }, + }); + + const { POST } = await import("./route"); + const response = await POST( + new Request("http://127.0.0.1:3000/api/ai-agent/run", { + method: "POST", + }), + ); + const text = await response.text(); + + expect(response.status).toBe(200); + expect(mockFetchHermesStructuredToolResultFromMnoteWeb).toHaveBeenCalledWith( + expect.objectContaining({ + userId: "user-1", + tool: "slash_run", + argsJson: { + text: "/rename doc-1 AI 标题", + }, + }), + ); + expect(text).toContain("event: tool_result"); + expect(text).toContain('"tool":"slash_run"'); + expect(text).toContain('"command":"rename_doc"'); + expect(text).toContain('"title":"AI 标题"'); + }); +}); diff --git a/wolai-frontend/src/app/api/ai-agent/run/route.ts b/wolai-frontend/src/app/api/ai-agent/run/route.ts index dd607269..36f285e0 100644 --- a/wolai-frontend/src/app/api/ai-agent/run/route.ts +++ b/wolai-frontend/src/app/api/ai-agent/run/route.ts @@ -13,6 +13,11 @@ import { startCodexJsonRun, } from "@/lib/ai/codex/codexExec"; import { startHermesRun, streamHermesRunEvents, type HermesRunEvent } from "@/lib/ai-agent/hermes/bridge"; +import { + readHermesToolArgsFromEvent, + readHermesToolResultFromEvent, +} from "@/lib/ai-agent/hermes/tool-result-recovery"; +import { fetchHermesStructuredToolResultFromMnoteWeb } from "@/lib/server/mnote-web-hermes"; export const dynamic = "force-dynamic"; @@ -223,15 +228,76 @@ const buildHermesInput = (messages: AgentMessage[]) => { .map((item) => ({ role: item.role, content: String(item.content ?? "") })); }; +type PendingHermesToolCall = { + preview: string; + argsJson: Record | null; +}; + +const recoverStructuredHermesToolResult = async (input: { + request: Request; + payload: RequestPayload; + userId: string; + tool: string; + argsJson: Record | null; + fallbackRequestId: string; + fallbackTraceId: string; +}): Promise => { + if (!input.argsJson) { + return null; + } + if ( + input.tool !== "slash_run" && + input.tool !== "doc_insert_blocks" && + input.tool !== "doc_replace_range" + ) { + return null; + } + + const documentId = String(input.payload.context?.documentId ?? "").trim() || null; + const data = + input.tool === "slash_run" + ? { source: "ai-agent-route" } + : input.payload.context?.documentBlocks ?? null; + + if ((input.tool === "doc_insert_blocks" || input.tool === "doc_replace_range") && data == null) { + return null; + } + + return fetchHermesStructuredToolResultFromMnoteWeb({ + request: input.request, + userId: input.userId, + tool: input.tool, + argsJson: input.argsJson, + data, + requestId: input.fallbackRequestId, + traceId: input.fallbackTraceId, + target: documentId + ? { + pageId: documentId, + blockId: + input.tool === "doc_replace_range" + ? String(input.argsJson.blockId ?? "").trim() || null + : null, + } + : null, + }).catch(() => null); +}; + const streamHermesLegacyEvents = async ({ messages, instructions, sessionId, + request, + payload, + userId, onEvent, }: { messages: AgentMessage[]; instructions: string; sessionId: string | null; + request: Request; + payload: RequestPayload; + userId: string; onEvent: (event: LegacyStreamEvent) => Promise | void; }) => { const input = buildHermesInput(messages); @@ -242,7 +308,7 @@ const streamHermesLegacyEvents = async ({ }); const pendingToolIds = new Map(); - const previewById = new Map(); + const pendingToolCalls = new Map(); let toolCount = 0; let assistantBuffer = ""; let failureMessage = ""; @@ -256,7 +322,10 @@ const streamHermesLegacyEvents = async ({ queue.push(id); pendingToolIds.set(tool, queue); const preview = typeof event.preview === "string" ? event.preview : ""; - previewById.set(id, preview); + pendingToolCalls.set(id, { + preview, + argsJson: readHermesToolArgsFromEvent(event, tool), + }); await onEvent({ type: "tool_call", data: { @@ -273,8 +342,22 @@ const streamHermesLegacyEvents = async ({ const queue = pendingToolIds.get(tool) ?? []; const id = queue.shift() ?? `hermes_${runId}_${toolCount}`; pendingToolIds.set(tool, queue); - const preview = previewById.get(id) ?? ""; + const pendingToolCall = pendingToolCalls.get(id) ?? null; + pendingToolCalls.delete(id); + const preview = pendingToolCall?.preview ?? ""; const duration = Number(event.duration ?? 0); + const structuredResultFromEvent = !Boolean(event.error) ? readHermesToolResultFromEvent(event) : null; + const recoveredResult = + structuredResultFromEvent ?? + (await recoverStructuredHermesToolResult({ + request, + payload, + userId, + tool, + argsJson: pendingToolCall?.argsJson ?? null, + fallbackRequestId: makeRunId(), + fallbackTraceId: makeRunId(), + })); await onEvent({ type: "tool_result", data: { @@ -282,7 +365,9 @@ const streamHermesLegacyEvents = async ({ tool, ok: !Boolean(event.error), ms: Number.isFinite(duration) ? Math.max(0, Math.round(duration * 1000)) : 0, - result: preview ? { preview, error: Boolean(event.error) } : { error: Boolean(event.error) }, + result: + recoveredResult ?? + (preview ? { preview, error: Boolean(event.error) } : { error: Boolean(event.error) }), }, }); return; @@ -551,6 +636,9 @@ export async function POST(request: Request) { messages: payload.messages, instructions, sessionId, + request, + payload, + userId, onEvent: (event) => { events.push(event); }, @@ -589,6 +677,9 @@ export async function POST(request: Request) { messages: payload.messages, instructions, sessionId, + request, + payload, + userId, onEvent: (event) => { send(event.type, event.data ?? null); }, diff --git a/wolai-frontend/src/app/api/leptos-tiptap-runtime/[...asset]/route.ts b/wolai-frontend/src/app/api/leptos-tiptap-runtime/[...asset]/route.ts index 0fd3de36..434b03ab 100644 --- a/wolai-frontend/src/app/api/leptos-tiptap-runtime/[...asset]/route.ts +++ b/wolai-frontend/src/app/api/leptos-tiptap-runtime/[...asset]/route.ts @@ -5,18 +5,24 @@ import { NextResponse } from "next/server"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; -type RuntimeManifest = { - bridgeRuntimePath: string | null; - extensionModulePaths: string[]; +type IslandManifest = { + entryAssetPath: string | null; + wasmAssetPath: string | null; + assetPaths: string[]; generatedRootPath: string | null; - entryScriptPath: string | null; - wasmPath: string | null; }; -const DIST_ROOT = path.resolve(process.cwd(), "..", "rust", "spikes", "leptos-tiptap-spike", "dist"); -const ENTRY_SCRIPT_PATTERN = /^mnote-leptos-tiptap-spike-.*\.js$/; -const WASM_PATTERN = /^mnote-leptos-tiptap-spike-.*_bg\.wasm$/; -const EXTENSION_MODULE_PATTERN = /^tiptap_[a-z0-9_]+\.js$/; +const GENERATED_ROOT = path.resolve( + process.cwd(), + "..", + "rust", + "spikes", + "leptos-tiptap-spike", + "generated", + "island", +); +const ENTRY_ASSET_PATTERN = /^mnote-leptos-tiptap-spike-island\.js$/; +const WASM_PATTERN = /^mnote-leptos-tiptap-spike-island_bg\.wasm$/; function toPosixPath(value: string): string { return value.split(path.sep).join("/"); @@ -65,29 +71,26 @@ async function walkFiles(rootDir: string): Promise { return output.sort((a, b) => a.localeCompare(b)); } -async function buildRuntimeManifest(): Promise { - const files = await walkFiles(DIST_ROOT); - const bridgeRuntimePath = files.find((item) => item.endsWith("/bridge_runtime.js") || item === "bridge_runtime.js") ?? null; - const generatedRootPath = bridgeRuntimePath ? path.posix.dirname(bridgeRuntimePath) : null; - const extensionModulePaths = generatedRootPath - ? files.filter((item) => { - if (!item.startsWith(`${generatedRootPath}/`)) { - return false; - } - const basename = path.posix.basename(item); - return EXTENSION_MODULE_PATTERN.test(basename); - }) - : []; - const entryScriptPath = - files.find((item) => ENTRY_SCRIPT_PATTERN.test(path.posix.basename(item))) ?? null; - const wasmPath = files.find((item) => WASM_PATTERN.test(path.posix.basename(item))) ?? null; +async function buildIslandManifest(): Promise { + const files = await walkFiles(GENERATED_ROOT); + const entryAssetPath = files.find((item) => ENTRY_ASSET_PATTERN.test(path.posix.basename(item))) ?? null; + const wasmAssetPath = files.find((item) => WASM_PATTERN.test(path.posix.basename(item))) ?? null; + const generatedRootPath = entryAssetPath ? path.posix.dirname(entryAssetPath) : null; + const assetPaths = files.filter((item) => { + const basename = path.posix.basename(item); + return ( + basename.endsWith(".js") || + basename.endsWith(".wasm") || + basename.endsWith(".css") || + basename.endsWith(".json") + ); + }); return { - bridgeRuntimePath, - extensionModulePaths, + entryAssetPath, + wasmAssetPath, + assetPaths, generatedRootPath, - entryScriptPath, - wasmPath, }; } @@ -120,14 +123,14 @@ export async function GET( if (asset.length === 1 && asset[0] === "manifest.json") { try { - const manifest = await buildRuntimeManifest(); + const manifest = await buildIslandManifest(); return NextResponse.json(manifest, { headers: { "Cache-Control": "no-store" }, }); } catch (error) { return NextResponse.json( { - error: "无法生成 leptos-tiptap runtime 清单", + error: "无法生成 leptos-tiptap island 清单", detail: error instanceof Error ? error.message : "unknown", }, { status: 500 }, @@ -137,12 +140,12 @@ export async function GET( const relativePath = sanitizeRelativePath(asset); if (!relativePath) { - return NextResponse.json({ error: "非法 runtime 资源路径" }, { status: 400 }); + return NextResponse.json({ error: "非法 island 资源路径" }, { status: 400 }); } - const absolutePath = path.resolve(DIST_ROOT, relativePath); - if (!absolutePath.startsWith(DIST_ROOT + path.sep)) { - return NextResponse.json({ error: "越界访问 runtime 资源被拒绝" }, { status: 403 }); + const absolutePath = path.resolve(GENERATED_ROOT, relativePath); + if (!absolutePath.startsWith(GENERATED_ROOT + path.sep)) { + return NextResponse.json({ error: "越界访问 island 资源被拒绝" }, { status: 403 }); } try { @@ -156,11 +159,11 @@ export async function GET( }); } catch (error) { if ((error as NodeJS.ErrnoException)?.code === "ENOENT") { - return NextResponse.json({ error: "runtime 资源不存在" }, { status: 404 }); + return NextResponse.json({ error: "island 资源不存在" }, { status: 404 }); } return NextResponse.json( { - error: "读取 runtime 资源失败", + error: "读取 island 资源失败", detail: error instanceof Error ? error.message : "unknown", }, { status: 500 }, diff --git a/wolai-frontend/src/app/api/mnote-web/stream/route.test.ts b/wolai-frontend/src/app/api/mnote-web/stream/route.test.ts new file mode 100644 index 00000000..7cca1de7 --- /dev/null +++ b/wolai-frontend/src/app/api/mnote-web/stream/route.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mockBuildMnoteWebForwardHeaders = vi.fn(); +const mockBuildMnoteWebStreamUrl = vi.fn(); +const mockDocumentBridgeErrorResponse = vi.fn((error: unknown) => + Response.json( + { + error: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, + ), +); + +vi.mock("@/lib/server/mnote-web", () => ({ + buildMnoteWebForwardHeaders: mockBuildMnoteWebForwardHeaders, + buildMnoteWebStreamUrl: mockBuildMnoteWebStreamUrl, +})); + +vi.mock("@/lib/documents/bridge", () => ({ + documentBridgeErrorResponse: mockDocumentBridgeErrorResponse, +})); + +describe("/api/mnote-web/stream route", () => { + beforeEach(() => { + mockBuildMnoteWebForwardHeaders.mockReset(); + mockBuildMnoteWebStreamUrl.mockReset(); + mockDocumentBridgeErrorResponse.mockClear(); + vi.unstubAllGlobals(); + }); + + it("透传上游 SSE 并去掉 set-cookie", async () => { + const upstreamHeaders = new Headers({ + "content-type": "text/event-stream; charset=utf-8", + "cache-control": "no-cache", + "set-cookie": "secret=1", + }); + const upstreamResponse = new Response("event: snapshot\ndata: {\"ok\":true}\n\n", { + status: 200, + headers: upstreamHeaders, + }); + + mockBuildMnoteWebForwardHeaders.mockResolvedValue(new Headers({ cookie: "a=1" })); + mockBuildMnoteWebStreamUrl.mockReturnValue( + new URL("http://127.0.0.1:3104/api/stream/events?stream=workspace&projection=sidebar_tree&workspaceId=ws_1"), + ); + + const fetchMock = vi.fn(async () => upstreamResponse); + vi.stubGlobal("fetch", fetchMock); + + const { GET } = await import("./route"); + const response = await GET( + new Request("http://127.0.0.1:3000/api/mnote-web/stream?workspaceId=ws_1", { + method: "GET", + headers: { cookie: "a=1" }, + }), + ); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledWith( + "http://127.0.0.1:3104/api/stream/events?stream=workspace&projection=sidebar_tree&workspaceId=ws_1", + expect.objectContaining({ + method: "GET", + cache: "no-store", + redirect: "follow", + headers: expect.any(Headers), + }), + ); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("text/event-stream"); + expect(response.headers.get("set-cookie")).toBeNull(); + await expect(response.text()).resolves.toContain("event: snapshot"); + }); +}); diff --git a/wolai-frontend/src/app/api/mnote-web/stream/route.ts b/wolai-frontend/src/app/api/mnote-web/stream/route.ts new file mode 100644 index 00000000..788d0bde --- /dev/null +++ b/wolai-frontend/src/app/api/mnote-web/stream/route.ts @@ -0,0 +1,43 @@ +import { documentBridgeErrorResponse } from "@/lib/documents/bridge"; +import { + buildMnoteWebForwardHeaders, + buildMnoteWebStreamUrl, +} from "@/lib/server/mnote-web"; + +export const dynamic = "force-dynamic"; + +export async function GET(request: Request) { + try { + const requestUrl = new URL(request.url); + const workspaceId = String(requestUrl.searchParams.get("workspaceId") || "").trim(); + const cursor = String(requestUrl.searchParams.get("cursor") || "").trim() || null; + + if (!workspaceId) { + return Response.json({ error: "缺少 workspaceId" }, { status: 400 }); + } + + const targetUrl = buildMnoteWebStreamUrl({ workspaceId, cursor }); + const headers = await buildMnoteWebForwardHeaders(request); + headers.set("accept", "text/event-stream"); + headers.set("x-mnote-workspace-id", workspaceId); + + const upstream = await fetch(targetUrl.toString(), { + method: "GET", + headers, + cache: "no-store", + redirect: "follow", + }); + + const responseHeaders = new Headers(upstream.headers); + responseHeaders.delete("set-cookie"); + responseHeaders.set("cache-control", "no-store"); + + return new Response(upstream.body, { + status: upstream.status, + statusText: upstream.statusText, + headers: responseHeaders, + }); + } catch (error) { + return documentBridgeErrorResponse(error); + } +} diff --git a/wolai-frontend/src/app/globals.css b/wolai-frontend/src/app/globals.css index 4c4cfc72..a4bf7698 100644 --- a/wolai-frontend/src/app/globals.css +++ b/wolai-frontend/src/app/globals.css @@ -130,12 +130,24 @@ body { } /* 调整编辑器内容宽度 */ -.bn-editor { - padding-left: 5rem; - padding-right: 5rem; - max-width: 900px; - margin: 0 auto; -} +.bn-editor { + padding-left: 5rem; + padding-right: 5rem; + max-width: 900px; + margin: 0 auto; +} + +/* 说明:leptos-tiptap / ProseMirror 需要最基础的 white-space 与换行样式, + 否则浏览器输入与光标行为会不稳定,并触发 ProseMirror 警告。 */ +.ProseMirror { + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; +} + +.ProseMirror pre { + white-space: pre-wrap; +} .dark { --background: oklch(0.145 0 0); diff --git a/wolai-frontend/src/app/layout.tsx b/wolai-frontend/src/app/layout.tsx index f5b2ab8e..6106542b 100644 --- a/wolai-frontend/src/app/layout.tsx +++ b/wolai-frontend/src/app/layout.tsx @@ -1,5 +1,4 @@ import type { Metadata } from "next"; -import { Inter } from "next/font/google"; import "./globals.css"; import { QueryProvider } from "@/components/providers/query-provider"; import { ConvexClientProvider } from "@/components/providers/convex-provider"; @@ -8,11 +7,6 @@ import { getMnoteRuntimeConfig } from "@/lib/runtime-config"; import { isConvexEnabled } from "@/lib/convex/enabled"; import { ConvexAuthNextjsServerProvider } from "@convex-dev/auth/nextjs/server"; -const inter = Inter({ - subsets: ["latin"], - variable: "--font-inter", -}); - export const metadata: Metadata = { title: "Wolai Clone", description: "Convex 自部署模式", @@ -40,7 +34,7 @@ export default async function RootLayout({ }} /> - + diff --git a/wolai-frontend/src/components/app-layout-shell.test.tsx b/wolai-frontend/src/components/app-layout-shell.test.tsx new file mode 100644 index 00000000..68ce7be2 --- /dev/null +++ b/wolai-frontend/src/components/app-layout-shell.test.tsx @@ -0,0 +1,205 @@ +import { act } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createRoot, type Root } from "react-dom/client"; +import type { SidebarInitialData } from "@/components/sidebar/types"; +import { usePreferredSidebarSnapshotData } from "@/components/sidebar/preferred-sidebar-snapshot-context"; +import { buildSidebarInitialData } from "@/lib/sidebar-data"; +import type { DocumentRecord } from "@/lib/documents"; +import { AppLayoutShell } from "./app-layout-shell"; + +const mockUseSidebarData = vi.fn(); +const mockUseSidebarTreeStream = vi.fn(); +const mockUsePreferredSidebarSnapshot = vi.fn(); + +let capturedSidebarProps: Record | null = null; +let capturedBreadcrumbProps: Record | null = null; +let capturedSearchPaletteProps: Record | null = null; + +vi.mock("@/hooks/use-sidebar-data", () => ({ + useSidebarData: (...args: unknown[]) => mockUseSidebarData(...args), +})); + +vi.mock("@/lib/tree-stream/use-sidebar-tree-stream", () => ({ + useSidebarTreeStream: (...args: unknown[]) => mockUseSidebarTreeStream(...args), +})); + +vi.mock("@/components/sidebar/use-preferred-sidebar-snapshot", () => ({ + usePreferredSidebarSnapshot: (...args: unknown[]) => mockUsePreferredSidebarSnapshot(...args), +})); + +vi.mock("@/components/sidebar/sidebar", () => ({ + Sidebar: (props: Record) => { + capturedSidebarProps = props; + return
; + }, +})); + +vi.mock("@/components/breadcrumb", () => ({ + Breadcrumb: (props: Record) => { + capturedBreadcrumbProps = props; + return
; + }, +})); + +vi.mock("@/components/mobile-sidebar-trigger", () => ({ + MobileSidebarTrigger: () =>
, +})); + +vi.mock("@/components/search/search-palette", () => ({ + SearchPalette: (props: Record) => { + capturedSearchPaletteProps = props; + return
; + }, +})); + +function buildDocument(overrides: Partial = {}): DocumentRecord { + return { + access_scope: "private", + id: "doc-1", + workspace_id: "ws-1", + title: "标题 A", + parent_id: null, + sort_order: 0, + is_starred: false, + is_template: false, + created_at: "2026-04-21T00:00:00.000Z", + updated_at: "2026-04-21T00:00:00.000Z", + ...overrides, + }; +} + +function buildSidebarData(documents: DocumentRecord[]): SidebarInitialData { + return buildSidebarInitialData({ + activeWorkspaceId: "ws-1", + workspaces: [], + documents, + trashedDocuments: [], + mindmaps: [], + mediaAssets: [], + trashedMediaAssets: [], + tables: [], + }); +} + +function SnapshotProbe() { + const snapshot = usePreferredSidebarSnapshotData(); + return
{snapshot.documents[0]?.title ?? "空"}
; +} + +describe("AppLayoutShell", () => { + let container: HTMLDivElement; + let root: Root; + + beforeEach(() => { + (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + capturedSidebarProps = null; + capturedBreadcrumbProps = null; + capturedSearchPaletteProps = null; + mockUseSidebarData.mockReset(); + mockUseSidebarTreeStream.mockReset(); + mockUsePreferredSidebarSnapshot.mockReset(); + }); + + afterEach(() => { + act(() => { + root.unmount(); + }); + container.remove(); + }); + + it("应把同一份 preferred sidebar snapshot 同时提供给 Sidebar 与 Breadcrumb", async () => { + const initialData = buildSidebarData([buildDocument({ title: "标题 A" })]); + const preferredData = buildSidebarData([ + buildDocument({ + title: "标题 B", + updated_at: "2026-04-21T00:00:01.000Z", + }), + ]); + const sidebarQuery = { + data: preferredData, + isLoading: false, + error: null, + refetch: vi.fn(async () => preferredData), + source: "convex-live" as const, + }; + const treeStream = { + data: preferredData, + status: "live" as const, + cursor: "evt-1", + error: null, + }; + + mockUseSidebarData.mockReturnValue(sidebarQuery); + mockUseSidebarTreeStream.mockReturnValue(treeStream); + mockUsePreferredSidebarSnapshot.mockReturnValue({ + data: preferredData, + source: "tree_stream", + syncKey: "sync-key-1", + }); + + await act(async () => { + root.render( + +
正文
+
, + ); + }); + + expect(capturedSidebarProps).toMatchObject({ + initialData, + sidebarQuery, + sidebarData: preferredData, + treeStream, + }); + expect(capturedBreadcrumbProps).toMatchObject({ + documents: preferredData.documents, + }); + expect(capturedSearchPaletteProps).toMatchObject({ + workspaceId: "ws-1", + }); + }); + + it("应把同一份 preferred sidebar snapshot 继续提供给页面 children", async () => { + const initialData = buildSidebarData([buildDocument({ title: "标题 A" })]); + const preferredData = buildSidebarData([ + buildDocument({ + title: "标题 B", + updated_at: "2026-04-21T00:00:01.000Z", + }), + ]); + + mockUseSidebarData.mockReturnValue({ + data: preferredData, + isLoading: false, + error: null, + refetch: vi.fn(async () => preferredData), + source: "convex-live" as const, + }); + mockUseSidebarTreeStream.mockReturnValue({ + data: preferredData, + status: "live" as const, + cursor: "evt-1", + error: null, + }); + mockUsePreferredSidebarSnapshot.mockReturnValue({ + data: preferredData, + source: "tree_stream", + syncKey: "sync-key-2", + }); + + await act(async () => { + root.render( + + + , + ); + }); + + const probe = container.querySelector("[data-testid='snapshot-probe']"); + expect(probe?.textContent).toBe("标题 B"); + }); +}); diff --git a/wolai-frontend/src/components/app-layout-shell.tsx b/wolai-frontend/src/components/app-layout-shell.tsx new file mode 100644 index 00000000..8aa93ead --- /dev/null +++ b/wolai-frontend/src/components/app-layout-shell.tsx @@ -0,0 +1,48 @@ +"use client"; + +import type { ReactNode } from "react"; +import { Breadcrumb } from "@/components/breadcrumb"; +import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"; +import { SearchPalette } from "@/components/search/search-palette"; +import { Sidebar } from "@/components/sidebar/sidebar"; +import { PreferredSidebarSnapshotProvider } from "@/components/sidebar/preferred-sidebar-snapshot-context"; +import type { SidebarInitialData } from "@/components/sidebar/types"; +import { usePreferredSidebarSnapshot } from "@/components/sidebar/use-preferred-sidebar-snapshot"; +import { useSidebarData } from "@/hooks/use-sidebar-data"; +import { useSidebarTreeStream } from "@/lib/tree-stream/use-sidebar-tree-stream"; + +interface AppLayoutShellProps { + initialData: SidebarInitialData; + children: ReactNode; +} + +export function AppLayoutShell({ initialData, children }: AppLayoutShellProps) { + const sidebarQuery = useSidebarData(initialData); + const treeStream = useSidebarTreeStream(initialData); + const preferredSidebarSnapshot = usePreferredSidebarSnapshot({ + initialData, + sidebarQueryData: sidebarQuery.data, + treeStreamData: treeStream.data, + }); + + return ( + +
+ +
+
+ + +
+
{children}
+ +
+
+
+ ); +} diff --git a/wolai-frontend/src/components/editor/DocumentAiAgentPanel.runtime.test.tsx b/wolai-frontend/src/components/editor/DocumentAiAgentPanel.runtime.test.tsx new file mode 100644 index 00000000..6a4768c0 --- /dev/null +++ b/wolai-frontend/src/components/editor/DocumentAiAgentPanel.runtime.test.tsx @@ -0,0 +1,177 @@ +import { describe, expect, it, vi } from "vitest"; +import type { Json } from "@/types/supabase"; +import { + applyDocWriteToolResultToPageBody, + buildAiAgentSessionsStoragePayload, + extractCurrentPageTitleFromSlashToolResult, + shouldSyncActiveSessionSnapshot, +} from "./DocumentAiAgentPanel.runtime"; + +type TestSession = { + id: string; + title: string; + createdAt: number; + updatedAt: number; + messages: Array<{ role: "user" | "assistant"; content: string }>; + toolLogs: Array<{ type: string; id?: string; tool?: string; ok?: boolean; ms?: number; result?: unknown }>; + codexSessionId?: string | null; + codexMode?: "chat" | "test" | "dev" | null; +}; + +function buildSession(overrides: Partial = {}): TestSession { + return { + id: "session-1", + title: "新会话", + createdAt: 1, + updatedAt: 2, + messages: [{ role: "assistant", content: "欢迎语" }], + toolLogs: [], + codexSessionId: null, + codexMode: null, + ...overrides, + }; +} + +describe("DocumentAiAgentPanel.runtime 会话回写保护", () => { + it("当前会话快照与本地消息和日志一致时,不应触发回写", () => { + const session = buildSession(); + expect(shouldSyncActiveSessionSnapshot(session, session.messages, session.toolLogs)).toBe(false); + }); + + it("当前会话快照与本地消息或日志不同时时,才应触发回写", () => { + const session = buildSession({ + messages: [{ role: "assistant", content: "旧内容" }], + toolLogs: [{ type: "info", message: "old" }], + }); + expect( + shouldSyncActiveSessionSnapshot( + session, + [{ role: "assistant", content: "新内容" }], + [{ type: "info", message: "new" }], + ), + ).toBe(true); + }); + + it("持久化 payload 应稳定包含标准化后的会话列表", () => { + const payload = buildAiAgentSessionsStoragePayload("session-1", [ + buildSession({ + updatedAt: 999, + messages: [{ role: "assistant", content: "欢迎语" }], + }), + ]); + + const parsed = JSON.parse(payload) as { + activeSessionId: string; + sessions: Array<{ id: string; title: string; createdAt: number; updatedAt: number; messages: Json; toolLogs: Json }>; + }; + expect(parsed.activeSessionId).toBe("session-1"); + expect(parsed.sessions).toHaveLength(1); + expect(parsed.sessions[0]?.id).toBe("session-1"); + expect(parsed.sessions[0]?.messages).toEqual([{ role: "assistant", content: "欢迎语" }]); + }); +}); + +describe("applyDocWriteToolResultToPageBody", () => { + it("doc 写工具成功时应按最新持久化元信息执行 page body save", async () => { + const applyPageBodyCommandImpl = vi.fn(async () => ({ + revision: 6, + conflictDetectionKey: "doc-1:6", + })); + const applyEditorSnapshot = vi.fn(); + const onPersistedMetaChange = vi.fn(); + + const applied = await applyDocWriteToolResultToPageBody({ + tool: "doc_insert_blocks", + ok: true, + result: { + data: [{ id: "block_1", type: "paragraph", content: "AI 正文" }], + }, + documentId: "doc-1", + getLatestPersistedMeta: () => ({ + workspaceId: "ws-1", + revision: 5, + conflictDetectionKey: "doc-1:5", + }), + applyEditorSnapshot, + onPersistedMetaChange, + applyPageBodyCommandImpl, + }); + + expect(applied).toBe(true); + expect(applyPageBodyCommandImpl).toHaveBeenCalledWith({ + documentId: "doc-1", + workspaceId: "ws-1", + revision: 5, + conflictDetectionKey: "doc-1:5", + blocks: [{ id: "block_1", type: "paragraph", content: "AI 正文" }], + applyEditorSnapshot, + }); + expect(onPersistedMetaChange).toHaveBeenCalledWith({ + revision: 6, + conflictDetectionKey: "doc-1:6", + }); + }); + + it("非 doc 写工具或无 data 时应直接忽略", async () => { + const applyPageBodyCommandImpl = vi.fn(); + + await expect( + applyDocWriteToolResultToPageBody({ + tool: "docs_read", + ok: true, + result: { data: [] }, + documentId: "doc-1", + getLatestPersistedMeta: () => ({ + workspaceId: "ws-1", + revision: 5, + conflictDetectionKey: "doc-1:5", + }), + applyEditorSnapshot: vi.fn(), + onPersistedMetaChange: vi.fn(), + applyPageBodyCommandImpl, + }), + ).resolves.toBe(false); + + expect(applyPageBodyCommandImpl).not.toHaveBeenCalled(); + }); +}); + +describe("extractCurrentPageTitleFromSlashToolResult", () => { + it("slash_run 成功重命名当前页时应返回新标题", () => { + expect( + extractCurrentPageTitleFromSlashToolResult({ + tool: "slash_run", + ok: true, + documentId: "doc-1", + result: { + parsed: { + command: "rename_doc", + params: { + documentId: "doc-1", + title: "AI 新标题", + }, + }, + }, + }), + ).toBe("AI 新标题"); + }); + + it("非当前页或非 rename 结果时应忽略", () => { + expect( + extractCurrentPageTitleFromSlashToolResult({ + tool: "slash_run", + ok: true, + documentId: "doc-1", + result: { + parsed: { + command: "rename_doc", + params: { + documentId: "doc-2", + title: "别的页面", + }, + }, + }, + }), + ).toBeNull(); + }); +}); diff --git a/wolai-frontend/src/components/editor/DocumentAiAgentPanel.runtime.tsx b/wolai-frontend/src/components/editor/DocumentAiAgentPanel.runtime.tsx index f6e12f70..c4493109 100644 --- a/wolai-frontend/src/components/editor/DocumentAiAgentPanel.runtime.tsx +++ b/wolai-frontend/src/components/editor/DocumentAiAgentPanel.runtime.tsx @@ -15,6 +15,12 @@ import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"; import { clamp, MIN_AGENT_STEPS, MAX_AGENT_STEPS } from "@/lib/constants"; import { parseSseChunks, readAiPanelPrefs, type AiProvider, writeAiPanelPrefs } from "@/components/ai-agent/panelShared"; import type { PageSubtreeProjection } from "@/lib/documents/page-subtree"; +import { + applyPageBodyCommand, + type ApplyPageBodyCommandInput, + type PageBodyPersistedMeta, + type PageBodyPersistedState, +} from "@/lib/documents/page-body-command"; type AgentMessage = { role: "user" | "assistant"; content: string }; type CodexMode = "chat" | "test" | "dev"; @@ -113,6 +119,110 @@ const normalizeSessions = (sessions: ChatSession[]) => { .sort((a, b) => b.updatedAt - a.updatedAt); }; +function buildSessionSnapshotKey(input: { + messages: ChatSession["messages"]; + toolLogs: ChatSession["toolLogs"]; +}): string { + return JSON.stringify({ + messages: input.messages, + toolLogs: input.toolLogs, + }); +} + +export function shouldSyncActiveSessionSnapshot( + session: Pick | null | undefined, + messages: ChatSession["messages"], + toolLogs: ChatSession["toolLogs"], +): boolean { + if (!session) { + return true; + } + return ( + buildSessionSnapshotKey({ + messages: session.messages, + toolLogs: session.toolLogs, + }) !== + buildSessionSnapshotKey({ + messages, + toolLogs, + }) + ); +} + +export function buildAiAgentSessionsStoragePayload( + activeSessionId: string, + sessions: ChatSession[], +): string { + return JSON.stringify({ + activeSessionId, + sessions: normalizeSessions(sessions), + }); +} + +export async function applyDocWriteToolResultToPageBody(input: { + tool: string; + ok: boolean; + result: unknown; + documentId: string; + getLatestPersistedMeta: () => PageBodyPersistedState; + applyEditorSnapshot?: (blocks: Json) => void; + onPersistedMetaChange?: (meta: PageBodyPersistedMeta) => void; + applyPageBodyCommandImpl?: (input: ApplyPageBodyCommandInput) => Promise; +}): Promise { + if (!input.ok || (input.tool !== "doc_insert_blocks" && input.tool !== "doc_replace_range")) { + return false; + } + const resultRecord = + input.result && typeof input.result === "object" ? (input.result as Record) : null; + const dataNode = resultRecord && "data" in resultRecord ? resultRecord.data : null; + if (dataNode == null) { + return false; + } + + const latestPersistedMeta = input.getLatestPersistedMeta(); + const applyPageBodyCommandImpl = input.applyPageBodyCommandImpl ?? applyPageBodyCommand; + const persistedMeta = await applyPageBodyCommandImpl({ + documentId: input.documentId, + workspaceId: latestPersistedMeta.workspaceId, + revision: latestPersistedMeta.revision, + conflictDetectionKey: latestPersistedMeta.conflictDetectionKey, + blocks: dataNode as Json, + applyEditorSnapshot: input.applyEditorSnapshot, + }); + input.onPersistedMetaChange?.(persistedMeta); + return true; +} + +export function extractCurrentPageTitleFromSlashToolResult(input: { + tool: string; + ok: boolean; + result: unknown; + documentId: string; +}): string | null { + if (!input.ok || input.tool !== "slash_run") { + return null; + } + + const resultRecord = + input.result && typeof input.result === "object" ? (input.result as Record) : null; + const parsed = + resultRecord?.parsed && typeof resultRecord.parsed === "object" + ? (resultRecord.parsed as Record) + : null; + if (!parsed || String(parsed.command ?? "") !== "rename_doc") { + return null; + } + + const params = + parsed.params && typeof parsed.params === "object" ? (parsed.params as Record) : null; + if (!params || String(params.documentId ?? "") !== input.documentId) { + return null; + } + + const title = String(params.title ?? "").trim(); + return title || null; +} + const safeJsonStringify = (value: unknown) => { try { return JSON.stringify(value); @@ -125,10 +235,16 @@ export function DocumentAiAgentPanelRuntime({ documentId, getLatestBlocks, getLatestPageSubtree, + getLatestPersistedMeta, + onPersistedMetaChange, + onPageHeadTitleChange, }: { documentId: string; getLatestBlocks: () => Json | null; getLatestPageSubtree: () => PageSubtreeProjection | null; + getLatestPersistedMeta: () => PageBodyPersistedState; + onPersistedMetaChange?: (meta: PageBodyPersistedMeta) => void; + onPageHeadTitleChange?: (title: string) => void; }) { const editorBridge = useEditorBridgeStore((s) => s.bridge); @@ -158,6 +274,7 @@ export function DocumentAiAgentPanelRuntime({ const abortRef = useRef(null); const syncTimerRef = useRef(null); + const hydratedSessionsRef = useRef(false); useEffect(() => { if (flightMode) { @@ -207,6 +324,7 @@ export function DocumentAiAgentPanelRuntime({ setActiveSessionId(id); setMessages(session.messages); setToolLogs([]); + hydratedSessionsRef.current = true; return; } @@ -237,8 +355,10 @@ export function DocumentAiAgentPanelRuntime({ const cur = loaded.find((s) => s.id === picked) ?? loaded[0]!; setMessages(cur.messages?.length ? cur.messages : DEFAULT_SESSION_MESSAGES); setToolLogs(cur.toolLogs ?? []); + hydratedSessionsRef.current = true; } catch { // ignore + hydratedSessionsRef.current = true; } // 只在 documentId 变化时读取一次 @@ -246,9 +366,14 @@ export function DocumentAiAgentPanelRuntime({ useEffect(() => { if (!activeSessionId) return; + if (!hydratedSessionsRef.current) return; if (syncTimerRef.current) window.clearTimeout(syncTimerRef.current); syncTimerRef.current = window.setTimeout(() => { setSessions((prev) => { + const current = prev.find((s) => s.id === activeSessionId) ?? null; + if (shouldSyncActiveSessionSnapshot(current, messages, toolLogs) === false) { + return prev; + } const now = Date.now(); const next = prev.some((s) => s.id === activeSessionId) ? prev.map((s) => @@ -277,9 +402,10 @@ export function DocumentAiAgentPanelRuntime({ useEffect(() => { if (!documentId) return; + if (!hydratedSessionsRef.current) return; try { const key = `doc_ai_sessions:${documentId}`; - const payload = JSON.stringify({ activeSessionId, sessions: normalizeSessions(sessions) }); + const payload = buildAiAgentSessionsStoragePayload(activeSessionId, sessions); if (payload.length <= 900_000) window.localStorage.setItem(key, payload); } catch { // ignore @@ -582,19 +708,32 @@ export function DocumentAiAgentPanelRuntime({ { type: "tool_result", id: String(obj.id ?? ""), tool, ok: Boolean(obj.ok), ms: Number(obj.ms ?? 0), result }, ]); - // doc 写工具返回 data=blocks 时,立即落入编辑器 - if ((tool === "doc_insert_blocks" || tool === "doc_replace_range") && obj.ok) { - const r = result as unknown; - const dataNode = - typeof r === "object" && r && "data" in (r as Record) ? (r as Record).data : null; - if (dataNode && editorBridge?.replaceWithSnapshot) { - try { - editorBridge.replaceWithSnapshot(dataNode as Json); - } catch { - // ignore - } - } + const nextPageTitle = extractCurrentPageTitleFromSlashToolResult({ + tool, + ok: Boolean(obj.ok), + result, + documentId, + }); + if (nextPageTitle) { + onPageHeadTitleChange?.(nextPageTitle); } + + void applyDocWriteToolResultToPageBody({ + tool, + ok: Boolean(obj.ok), + result, + documentId, + getLatestPersistedMeta, + applyEditorSnapshot: editorBridge?.replaceWithSnapshot + ? (blocks) => { + editorBridge.replaceWithSnapshot(blocks); + } + : undefined, + onPersistedMetaChange, + }).catch((error) => { + const message = error instanceof Error ? error.message : "AI 页面正文保存失败"; + setToolLogs((prev) => [...prev, { type: "error", message }]); + }); } catch { // ignore } diff --git a/wolai-frontend/src/components/editor/DocumentAiAgentPanel.tsx b/wolai-frontend/src/components/editor/DocumentAiAgentPanel.tsx index ef80f218..2a5f82c3 100644 --- a/wolai-frontend/src/components/editor/DocumentAiAgentPanel.tsx +++ b/wolai-frontend/src/components/editor/DocumentAiAgentPanel.tsx @@ -3,6 +3,7 @@ import dynamic from "next/dynamic"; import { useEffect } from "react"; import type { PageSubtreeProjection } from "@/lib/documents/page-subtree"; +import type { PageBodyPersistedMeta, PageBodyPersistedState } from "@/lib/documents/page-body-command"; import type { Json } from "@/types/supabase"; import { useAiAgentUiStore } from "@/store/ai-agent-ui"; @@ -10,6 +11,9 @@ type DocumentAiAgentPanelProps = { documentId: string; getLatestBlocks: () => Json | null; getLatestPageSubtree: () => PageSubtreeProjection | null; + getLatestPersistedMeta: () => PageBodyPersistedState; + onPersistedMetaChange?: (meta: PageBodyPersistedMeta) => void; + onPageHeadTitleChange?: (title: string) => void; }; const DocumentAiAgentPanelRuntime = dynamic( diff --git a/wolai-frontend/src/components/editor/document-content.test.ts b/wolai-frontend/src/components/editor/document-content.test.ts new file mode 100644 index 00000000..7235ab5e --- /dev/null +++ b/wolai-frontend/src/components/editor/document-content.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it, vi } from "vitest"; +import { persistPageTitleAndNotifyDocumentsChanged } from "@/components/editor/document-content"; + +describe("persistPageTitleAndNotifyDocumentsChanged", () => { + it("标题提交成功后应广播 documents-changed", async () => { + const persistTitleCommand = vi.fn(async () => ({ ok: true as const })); + const emitDocumentsChanged = vi.fn(); + + const result = await persistPageTitleAndNotifyDocumentsChanged({ + documentId: "doc-1", + workspaceId: "ws-1", + title: " 新标题 ", + persistTitleCommand, + notifyDocumentsChanged: emitDocumentsChanged, + }); + + expect(result).toBe("新标题"); + expect(persistTitleCommand).toHaveBeenCalledWith({ + documentId: "doc-1", + workspaceId: "ws-1", + title: "新标题", + }); + expect(emitDocumentsChanged).toHaveBeenCalledWith("doc-1"); + }); +}); diff --git a/wolai-frontend/src/components/editor/document-content.tsx b/wolai-frontend/src/components/editor/document-content.tsx index e2444fdc..c30f2f8c 100644 --- a/wolai-frontend/src/components/editor/document-content.tsx +++ b/wolai-frontend/src/components/editor/document-content.tsx @@ -20,15 +20,27 @@ import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { DocumentToc } from "@/components/editor/document-toc"; import { DocumentReadView } from "@/components/editor/document-read-view"; +import { emitDocumentsChanged } from "@/lib/events"; import { extractPageBlocks, type PageSubtreeProjection } from "@/lib/documents/page-subtree"; import { deleteDocumentCommand, embedDocumentCommand, moveDocumentCommand, - renameDocumentCommand, + updatePageOptionsCommand, + updatePageTitleCommand, } from "@/lib/documents/tree-command-client"; import { EditorHost } from "@/components/editor/editor-host"; -import type { EditorHostKind } from "@/components/editor/editor-host-config"; +import { + DEFAULT_EDITOR_HOST_KIND, + isLeptosTiptapHostKind, + type EditorHostKind, +} from "@/components/editor/editor-host-config"; +import type { + EditorHostEvent, + EditorHostFallbackReason, +} from "@/components/editor/editor-host-types"; +import type { PageAggregateProjection } from "@/lib/documents/page-aggregate"; +import { usePageHeadTitle } from "@/components/editor/use-page-head-title"; const BlockNoteEditor = dynamic( () => import("@/components/editor/blocknote-editor").then((mod) => mod.BlockNoteEditor), @@ -78,21 +90,9 @@ const DocumentCommentsDrawer = dynamic( ); export interface DocumentContentProps { - documentId: string; - workspaceId: string; - title: string | null; - updatedAt: string | null; - initialContent: unknown; - initialContentRevision?: number | null; - initialConflictDetectionKey?: string | null; - initialPageSubtree?: PageSubtreeProjection | null; - initialOptions: PageOptionsState; - initialStats: DocumentStats | null; + page: PageAggregateProjection; openTableId?: string | null; editorHostKind?: EditorHostKind; - readOnly?: boolean; - disableDownload?: boolean; - disableCopy?: boolean; } const defaultOptions: PageOptionsState = { @@ -112,24 +112,43 @@ const defaultOptions: PageOptionsState = { }; const defaultStats: DocumentStats = { wordCount: 0, characterCount: 0, blockCount: 0, todoTotal: 0, todoDone: 0 }; const EDITOR_UNMOUNT_GRACE_MS = 1000; +const FALLBACK_TRIGGER_HISTORY_LIMIT = 20; + +export async function persistPageTitleAndNotifyDocumentsChanged(input: { + documentId: string; + workspaceId: string; + title: string; + persistTitleCommand: (payload: { documentId: string; workspaceId: string; title: string }) => Promise; + notifyDocumentsChanged: (documentId?: string) => void; +}): Promise { + const payload = input.title.trim() || "无标题"; + await input.persistTitleCommand({ + documentId: input.documentId, + workspaceId: input.workspaceId, + title: payload, + }); + input.notifyDocumentsChanged(input.documentId); + return payload; +} export function DocumentContent({ - documentId, - workspaceId, - title, - updatedAt, - initialContent, - initialContentRevision = null, - initialConflictDetectionKey = null, - initialPageSubtree = null, - initialOptions, - initialStats, + page, openTableId, - editorHostKind = "blocknote", - readOnly = false, - disableDownload = false, - disableCopy = false, + editorHostKind = DEFAULT_EDITOR_HOST_KIND, }: DocumentContentProps) { + const documentId = page.identity.documentId; + const workspaceId = page.identity.workspaceId; + const initialTitle = page.head.title; + const updatedAt = page.head.updatedAt; + const readOnly = page.head.permissions.readOnly; + const disableDownload = page.head.permissions.disableDownload; + const disableCopy = page.head.permissions.disableCopy; + const initialOptions = page.layout.pageOptions; + const initialContent = page.body.content; + const initialContentRevision = page.body.revision; + const initialConflictDetectionKey = page.body.conflictDetectionKey; + const initialPageSubtree = page.tree.pageSubtree; + const initialStats = page.stats; const setCurrentDocument = useCurrentDocumentStore((state) => state.setCurrent); const clearIfMatch = useCurrentDocumentStore((state) => state.clearIfMatch); const canEditDocument = !readOnly; @@ -143,22 +162,42 @@ export function DocumentContent({ const openCommentsForPage = useCommentsUiStore((s) => s.openForPage); const spellCheck = useAppPreferencesStore((s) => s.spellCheck); const openMoveEmbedPicker = useMoveEmbedPickerStore((s) => s.openPicker); - const [pageTitle, setPageTitle] = useState(title ?? "无标题"); + const { + displayTitle: pageTitle, + committedTitle: committedPageTitle, + setDraftTitle: setPageTitleDraft, + commitPersistedTitle, + } = usePageHeadTitle({ + documentId, + fallbackTitle: initialTitle, + }); const [content, setContent] = useState(initialContent); const [serverContentSnapshot, setServerContentSnapshot] = useState(initialContent); const [serverPageSubtreeSnapshot, setServerPageSubtreeSnapshot] = useState( initialPageSubtree, ); - const [serverPageSubtreeTitle, setServerPageSubtreeTitle] = useState(title ?? "无标题"); + const [serverPageSubtreeTitle, setServerPageSubtreeTitle] = useState(initialTitle); const [contentRevision, setContentRevision] = useState(initialContentRevision); const [conflictDetectionKey, setConflictDetectionKey] = useState(initialConflictDetectionKey); const [contentLoading, setContentLoading] = useState(() => initialContent == null); const [contentError, setContentError] = useState(null); const [contentReloadKey, setContentReloadKey] = useState(0); const [showContentLoadingIndicator, setShowContentLoadingIndicator] = useState(false); - const shouldUseExperimentalHost = - editorHostKind === "leptos_tiptap_inline" || - editorHostKind === "leptos_tiptap_iframe_debug"; + const shouldUseRuntimeHost = isLeptosTiptapHostKind(editorHostKind); + const requestedHostKind = shouldUseRuntimeHost ? editorHostKind : "blocknote"; + const [activeHostKind, setActiveHostKind] = useState<"blocknote" | EditorHostKind>(() => + requestedHostKind === "blocknote" ? "blocknote" : requestedHostKind, + ); + const [hostRuntimeLoadFailure, setHostRuntimeLoadFailure] = useState(null); + const [hostInitFailure, setHostInitFailure] = useState(null); + const [hostCommandFailure, setHostCommandFailure] = useState(null); + const [hostSaveFailure, setHostSaveFailure] = useState(null); + const [hostFallbackCount, setHostFallbackCount] = useState(0); + const [lastFallbackReason, setLastFallbackReason] = useState(null); + const [lastFallbackAt, setLastFallbackAt] = useState(null); + const [hostStatus, setHostStatus] = useState("idle"); + const [hostEventAt, setHostEventAt] = useState(null); + const fallbackTriggerHistoryRef = useRef([]); const shouldStartEditing = canEditDocument; const [isEditing, setIsEditing] = useState(() => shouldStartEditing); const [keepEditorMounted, setKeepEditorMounted] = useState(() => shouldStartEditing); @@ -170,6 +209,51 @@ export function DocumentContent({ const readViewRootRef = useRef(null); const pendingRestoreSnapshotRef = useRef(null); const lastCopyBlockedAtRef = useRef(0); + const hasRequestedFallbackRef = useRef(false); + + const resetHostObservability = useCallback((nextHost: "blocknote" | EditorHostKind) => { + setHostStatus(nextHost === "blocknote" ? "blocknote_active" : "booting"); + setHostEventAt(new Date().toISOString()); + setHostRuntimeLoadFailure(null); + setHostInitFailure(null); + setHostCommandFailure(null); + setHostSaveFailure(null); + setHostFallbackCount(0); + setLastFallbackReason(null); + setLastFallbackAt(null); + fallbackTriggerHistoryRef.current = []; + hasRequestedFallbackRef.current = false; + }, []); + + const requestFallbackToBlockNote = useCallback( + (reason: EditorHostFallbackReason, error?: string | null) => { + if (hasRequestedFallbackRef.current) { + return; + } + hasRequestedFallbackRef.current = true; + const now = new Date().toISOString(); + setActiveHostKind("blocknote"); + setHostFallbackCount((prev) => prev + 1); + setLastFallbackReason(reason); + setLastFallbackAt(now); + setHostStatus("blocknote_fallback"); + setHostEventAt(now); + fallbackTriggerHistoryRef.current = [now, ...fallbackTriggerHistoryRef.current].slice( + 0, + FALLBACK_TRIGGER_HISTORY_LIMIT, + ); + if (reason === "runtime_load_failed") { + setHostRuntimeLoadFailure(error ?? "runtime 加载失败"); + } else if (reason === "host_init_failed") { + setHostInitFailure(error ?? "host 初始化失败"); + } else if (reason === "command_failed") { + setHostCommandFailure(error ?? "命令执行失败"); + } else if (reason === "save_failed") { + setHostSaveFailure(error ?? "保存失败"); + } + }, + [], + ); useEffect(() => { setCurrentDocument(documentId, readOnly, disableDownload, disableCopy); @@ -243,6 +327,11 @@ export function DocumentContent({ }; }, [disableCopy]); + useEffect(() => { + setActiveHostKind(requestedHostKind === "blocknote" ? "blocknote" : requestedHostKind); + resetHostObservability(requestedHostKind === "blocknote" ? "blocknote" : requestedHostKind); + }, [requestedHostKind, resetHostObservability]); + useEffect(() => { const tableId = (openTableId ?? "").trim(); if (!tableId) return; @@ -264,12 +353,8 @@ export function DocumentContent({ }, [documentId, editorBridge, openTableId, router]); useEffect(() => { - setPageTitle(title ?? "无标题"); - }, [title]); - - useEffect(() => { - setServerPageSubtreeTitle(title ?? "无标题"); - }, [title]); + setServerPageSubtreeTitle(committedPageTitle); + }, [committedPageTitle]); useEffect(() => { setServerPageSubtreeSnapshot(initialPageSubtree); @@ -393,7 +478,7 @@ export function DocumentContent({ typeof payload.pageSubtree?.rootNode.metadata.title === "string" && payload.pageSubtree.rootNode.metadata.title.trim() ? payload.pageSubtree.rootNode.metadata.title - : title ?? "无标题", + : committedPageTitle, ); } catch (error) { if (canceled) return; @@ -421,19 +506,36 @@ export function DocumentContent({ contentLoadingTimerRef.current = null; } }; - }, [documentId, initialContent, contentReloadKey, title, workspaceId]); + }, [committedPageTitle, contentReloadKey, documentId, initialContent, workspaceId]); const persistTitle = useCallback( async (nextTitle: string) => { if (readOnly) return; - const payload = nextTitle.trim() || "无标题"; try { - await renameDocumentCommand({ documentId, workspaceId, title: payload }); + const payload = await persistPageTitleAndNotifyDocumentsChanged({ + documentId, + workspaceId, + title: nextTitle, + persistTitleCommand: updatePageTitleCommand, + notifyDocumentsChanged: emitDocumentsChanged, + }); + commitPersistedTitle(payload); + setServerPageSubtreeTitle(payload); } catch (error) { console.error("更新页面标题失败", error); } }, - [documentId, readOnly, workspaceId], + [commitPersistedTitle, documentId, readOnly, workspaceId], + ); + + const handleAiPageHeadTitleChange = useCallback( + (nextTitle: string) => { + setPageTitleDraft(nextTitle); + commitPersistedTitle(nextTitle); + setServerPageSubtreeTitle(nextTitle); + emitDocumentsChanged(documentId); + }, + [commitPersistedTitle, documentId, setPageTitleDraft], ); const debouncedPersistTitle = useDebouncedCallback((value: string) => { @@ -443,7 +545,7 @@ export function DocumentContent({ const handleTitleChange = (event: ChangeEvent) => { if (!canEditDocument) return; const value = event.target.value; - setPageTitle(value); + setPageTitleDraft(value); debouncedPersistTitle(value); }; @@ -463,15 +565,11 @@ export function DocumentContent({ async (patch: Partial) => { if (readOnly) return; try { - const response = await fetch("/api/documents/options", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ documentId, workspaceId, options: patch }), + await updatePageOptionsCommand({ + documentId, + workspaceId, + pageOptions: patch, }); - if (!response.ok) { - const payload = await response.json().catch(() => null); - console.error(payload?.error ?? "更新页面选项失败"); - } } catch (error) { console.error(error); } @@ -742,10 +840,10 @@ export function DocumentContent({ const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; - anchor.download = `${title ?? "未命名页面"}-${new Date().toISOString()}.json`; + anchor.download = `${pageTitle ?? "未命名页面"}-${new Date().toISOString()}.json`; anchor.click(); URL.revokeObjectURL(url); - }, [disableDownload, history, title]); + }, [disableDownload, history, pageTitle]); const pageRootClass = cn( "flex h-full overflow-hidden bg-wolai-bg", @@ -784,6 +882,16 @@ export function DocumentContent({ })), [pageSubtree], ); + const getLatestBlocks = useCallback(() => latestBlocksRef.current, []); + const getLatestPageSubtree = useCallback(() => pageSubtree, [pageSubtree]); + const getLatestPersistedMeta = useCallback( + () => ({ + workspaceId, + revision: contentRevision, + conflictDetectionKey, + }), + [conflictDetectionKey, contentRevision, workspaceId], + ); const inspectorCanUseEditorBridge = canEditDocument && isEditing; const jumpToHeading = useCallback((headingId: string) => { @@ -861,6 +969,68 @@ export function DocumentContent({ editorBridge.replaceWithSnapshot(pendingSnapshot.blocks); setHistoryOpen(false); }, [editorBridge, isEditing]); + + const handleHostEvent = useCallback((event: EditorHostEvent) => { + setHostEventAt(event.at); + if (event.kind === "status_changed") { + setHostStatus(event.status); + return; + } + if (event.kind === "runtime_load_failed") { + setHostRuntimeLoadFailure(event.message); + return; + } + if (event.kind === "host_init_failed") { + setHostInitFailure(event.message); + return; + } + if (event.kind === "command_failed") { + setHostCommandFailure(event.message); + return; + } + if (event.kind === "save_failed") { + setHostSaveFailure(event.message); + return; + } + }, []); + + const hostObservability = useMemo( + () => ({ + requestedHostKind, + activeHostKind, + status: hostStatus, + runtimeLoadFailed: hostRuntimeLoadFailure, + hostInitFailed: hostInitFailure, + commandFailed: hostCommandFailure, + saveFailed: hostSaveFailure, + fallbackCount: hostFallbackCount, + lastFallbackReason, + lastFallbackAt, + lastEventAt: hostEventAt, + fallbackTimestamps: fallbackTriggerHistoryRef.current, + }), + [ + activeHostKind, + hostEventAt, + hostFallbackCount, + hostInitFailure, + hostCommandFailure, + hostRuntimeLoadFailure, + hostSaveFailure, + hostStatus, + lastFallbackAt, + lastFallbackReason, + requestedHostKind, + ], + ); + const activeHostFailureMessage = + hostRuntimeLoadFailure ?? hostInitFailure ?? hostCommandFailure ?? hostSaveFailure; + const showFallbackBanner = + requestedHostKind !== "blocknote" && activeHostKind === "blocknote" && lastFallbackReason != null; + const showFailureBanner = + requestedHostKind !== "blocknote" && + activeHostKind !== "blocknote" && + activeHostFailureMessage != null; return (
@@ -935,15 +1105,55 @@ export function DocumentContent({
) : (
+ {showFallbackBanner ? ( +
+
+
+ 默认 island 主编辑器已自动回退到 BlockNote +
+
+ 原因:{lastFallbackReason} + {lastFallbackAt ? `,时间:${lastFallbackAt}` : ""} +
+
+ +
+ ) : null} + {showFailureBanner ? ( +
+
+
island 主链出现错误
+
{activeHostFailureMessage}
+
+ +
+ ) : null} {keepEditorMounted && (
- {shouldUseExperimentalHost ? ( + {activeHostKind !== "blocknote" ? ( { + requestFallbackToBlockNote(payload.reason, payload.error); + }} /> ) : ( )} +
{!isEditing && (
latestBlocksRef.current} - getLatestPageSubtree={() => pageSubtree} + getLatestBlocks={getLatestBlocks} + getLatestPageSubtree={getLatestPageSubtree} + getLatestPersistedMeta={getLatestPersistedMeta} + onPersistedMetaChange={(meta) => { + setContentRevision(meta.revision); + setConflictDetectionKey(meta.conflictDetectionKey); + }} + onPageHeadTitleChange={handleAiPageHeadTitleChange} /> ); diff --git a/wolai-frontend/src/components/editor/document-shell.tsx b/wolai-frontend/src/components/editor/document-shell.tsx index 76bd8475..20238f50 100644 --- a/wolai-frontend/src/components/editor/document-shell.tsx +++ b/wolai-frontend/src/components/editor/document-shell.tsx @@ -3,6 +3,8 @@ import type { DocumentContentProps } from "@/components/editor/document-content"; import { DocumentContent } from "@/components/editor/document-content"; -export function DocumentShell(props: DocumentContentProps) { +export interface DocumentShellProps extends DocumentContentProps {} + +export function DocumentShell(props: DocumentShellProps) { return ; } diff --git a/wolai-frontend/src/components/editor/editor-host-config.test.ts b/wolai-frontend/src/components/editor/editor-host-config.test.ts new file mode 100644 index 00000000..d9b220fa --- /dev/null +++ b/wolai-frontend/src/components/editor/editor-host-config.test.ts @@ -0,0 +1,37 @@ +import { + DEFAULT_EDITOR_HOST_KIND, + normalizeEditorHostKind, + resolveEditorHostKind, +} from "@/components/editor/editor-host-config"; +import { describe, expect, it } from "vitest"; + +describe("editor-host-config", () => { + it("保持 island 为默认正式 host", () => { + expect(DEFAULT_EDITOR_HOST_KIND).toBe("leptos_tiptap_island"); + }); + + it("将 inline 和旧 runtime 兼容别名收敛到正式 island host", () => { + expect(normalizeEditorHostKind("leptos_tiptap_inline")).toBe("leptos_tiptap_island"); + expect(normalizeEditorHostKind("leptos_tiptap_runtime")).toBe("leptos_tiptap_island"); + expect(normalizeEditorHostKind("leptos_tiptap")).toBe("leptos_tiptap_island"); + }); + + it("保留 iframe debug 作为显式调试 host", () => { + expect(normalizeEditorHostKind("leptos_tiptap_iframe_debug")).toBe( + "leptos_tiptap_iframe_debug", + ); + expect(normalizeEditorHostKind("iframe_debug")).toBe("leptos_tiptap_iframe_debug"); + expect(normalizeEditorHostKind("leptos_tiptap_debug")).toBe( + "leptos_tiptap_iframe_debug", + ); + }); + + it("优先尊重 query override 的 debug host 选择", () => { + expect( + resolveEditorHostKind({ + override: "leptos_tiptap_iframe_debug", + runtimeDefault: "leptos_tiptap_island", + }), + ).toBe("leptos_tiptap_iframe_debug"); + }); +}); diff --git a/wolai-frontend/src/components/editor/editor-host-config.ts b/wolai-frontend/src/components/editor/editor-host-config.ts index 0a69b7ce..0af20d78 100644 --- a/wolai-frontend/src/components/editor/editor-host-config.ts +++ b/wolai-frontend/src/components/editor/editor-host-config.ts @@ -1,23 +1,59 @@ export type EditorHostKind = | "blocknote" - | "leptos_tiptap_inline" + | "leptos_tiptap_island" | "leptos_tiptap_iframe_debug"; export interface EditorHostConfig { kind: EditorHostKind; } -const DEFAULT_EDITOR_HOST_KIND: EditorHostKind = "blocknote"; +export const DEFAULT_EDITOR_HOST_KIND: EditorHostKind = "leptos_tiptap_island"; -export function normalizeEditorHostKind(value: unknown): EditorHostKind { +export function normalizeEditorHostKind( + value: unknown, + fallback: EditorHostKind = DEFAULT_EDITOR_HOST_KIND, +): EditorHostKind { const normalized = typeof value === "string" ? value.trim().toLowerCase() : ""; - if (normalized === "leptos_tiptap_inline") { - return "leptos_tiptap_inline"; + if (normalized === "blocknote") { + return "blocknote"; } - if (normalized === "leptos_tiptap_iframe_debug" || normalized === "leptos_tiptap") { + if ( + normalized === "leptos_tiptap_runtime" || + normalized === "leptos_tiptap_inline" || + normalized === "leptos_tiptap" + ) { + return "leptos_tiptap_island"; + } + // 说明:iframe 只保留给显式调试桥,不再混入正式 runtime 主链。 + if ( + normalized === "leptos_tiptap_iframe_debug" || + normalized === "leptos_tiptap_debug" || + normalized === "iframe_debug" + ) { return "leptos_tiptap_iframe_debug"; } - return DEFAULT_EDITOR_HOST_KIND; + // 说明:保留历史 query 值兼容;未显式声明 debug 时,一律回到正式 runtime host。 + return fallback; +} + +export function resolveEditorHostKind(input: { + override?: unknown; + runtimeDefault?: unknown; +}): EditorHostKind { + const runtimeDefault = normalizeEditorHostKind( + input.runtimeDefault, + DEFAULT_EDITOR_HOST_KIND, + ); + const hasOverride = + typeof input.override === "string" && input.override.trim().length > 0; + if (hasOverride) { + return normalizeEditorHostKind(input.override, runtimeDefault); + } + return runtimeDefault; +} + +export function isLeptosTiptapHostKind(kind: EditorHostKind): boolean { + return kind !== "blocknote"; } export function getEditorHostKindFromEnv(value?: unknown): EditorHostKind { diff --git a/wolai-frontend/src/components/editor/editor-host-types.ts b/wolai-frontend/src/components/editor/editor-host-types.ts index 6886a0b7..e66c10ae 100644 --- a/wolai-frontend/src/components/editor/editor-host-types.ts +++ b/wolai-frontend/src/components/editor/editor-host-types.ts @@ -22,10 +22,44 @@ export interface DocumentEditorHostProps { revision: number | null; conflictDetectionKey: string | null; }) => void; + onHostEvent?: (event: EditorHostEvent) => void; + onRequestFallback?: (payload: EditorHostFallbackRequest) => void; } export type BlockNoteEditorProps = DocumentEditorHostProps; +export type EditorHostFallbackReason = + | "runtime_load_failed" + | "host_init_failed" + | "command_failed" + | "save_failed" + | "explicit_fallback"; + +export type EditorHostFallbackRequest = { + reason: EditorHostFallbackReason; + error?: string | null; + at: string; +}; + +export type EditorHostEvent = + | { + kind: "status_changed"; + status: string; + at: string; + message?: string | null; + } + | { + kind: "runtime_load_failed" | "host_init_failed" | "command_failed" | "save_failed"; + at: string; + message: string; + } + | { + kind: "fallback_triggered"; + at: string; + reason: EditorHostFallbackReason; + message?: string | null; + }; + export type LeptosTiptapHostBridgeState = { ready: boolean; runtimeName: string; @@ -52,3 +86,8 @@ export type LeptosTiptapHostBridgeEventDetail = { error?: string | null; at?: string; }; + +export type LeptosTiptapRuntimePageOptions = Pick< + PageOptionsState, + "wideLayout" | "smallText" | "layoutDensity" | "showHeadingNumbers" | "embedDefaultBlockId" +>; diff --git a/wolai-frontend/src/components/editor/editor-host.test.tsx b/wolai-frontend/src/components/editor/editor-host.test.tsx new file mode 100644 index 00000000..6e89e4b1 --- /dev/null +++ b/wolai-frontend/src/components/editor/editor-host.test.tsx @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_EDITOR_HOST_KIND, + normalizeEditorHostKind, +} from "@/components/editor/editor-host-config"; + +describe("editor-host", () => { + it("默认正式主链是 island host", () => { + expect(DEFAULT_EDITOR_HOST_KIND).toBe("leptos_tiptap_island"); + expect(normalizeEditorHostKind("leptos_tiptap_runtime")).toBe("leptos_tiptap_island"); + }); +}); diff --git a/wolai-frontend/src/components/editor/editor-host.tsx b/wolai-frontend/src/components/editor/editor-host.tsx index a0afe01d..1db4f7bf 100644 --- a/wolai-frontend/src/components/editor/editor-host.tsx +++ b/wolai-frontend/src/components/editor/editor-host.tsx @@ -4,6 +4,19 @@ import dynamic from "next/dynamic"; import type { ComponentType } from "react"; import type { DocumentEditorHostProps } from "@/components/editor/editor-host-types"; +const LeptosTiptapIslandEditor = dynamic( + () => + import("@/components/editor/leptos-tiptap-island-editor-host").then( + (mod) => mod.LeptosTiptapIslandEditorHost, + ), + { + ssr: false, + loading: () => ( +
编辑器加载中...
+ ), + }, +) as ComponentType; + const LeptosTiptapIframeDebugEditor = dynamic( () => import("@/components/editor/leptos-tiptap-editor-host").then((mod) => mod.LeptosTiptapEditorHost), { @@ -14,22 +27,9 @@ const LeptosTiptapIframeDebugEditor = dynamic( }, ) as ComponentType; -const LeptosTiptapInlineEditor = dynamic( - () => - import("@/components/editor/leptos-tiptap-inline-editor-host").then( - (mod) => mod.LeptosTiptapInlineEditorHost, - ), - { - ssr: false, - loading: () => ( -
编辑器加载中...
- ), - }, -) as ComponentType; - export function EditorHost(props: DocumentEditorHostProps) { - if (props.hostKind === "leptos_tiptap_inline") { - return ; + if (props.hostKind === "leptos_tiptap_iframe_debug") { + return ; } - return ; + return ; } diff --git a/wolai-frontend/src/components/editor/leptos-tiptap-editor-host.tsx b/wolai-frontend/src/components/editor/leptos-tiptap-editor-host.tsx index deb8ceec..216d3f64 100644 --- a/wolai-frontend/src/components/editor/leptos-tiptap-editor-host.tsx +++ b/wolai-frontend/src/components/editor/leptos-tiptap-editor-host.tsx @@ -193,6 +193,9 @@ export function LeptosTiptapEditorHost(props: DocumentEditorHostProps) { const revisionRef = useRef(props.initialRevision ?? null); const conflictDetectionKeyRef = useRef(props.initialConflictDetectionKey ?? null); const bootstrapPayloadRef = useRef(null); + const runtimeDocRef = useRef( + normalizeRuntimeDoc(tiptapDocFromBlocks(props.initialContent as Json) as Json) as Json, + ); const [runtimeDoc, setRuntimeDoc] = useState(() => tiptapDocFromBlocks(props.initialContent as Json) as Json); const [reloadKey, setReloadKey] = useState(0); const [iframeHeight, setIframeHeight] = useState(FALLBACK_IFRAME_MIN_HEIGHT); @@ -222,6 +225,10 @@ export function LeptosTiptapEditorHost(props: DocumentEditorHostProps) { conflictDetectionKeyRef.current = props.initialConflictDetectionKey ?? null; }, [props.initialConflictDetectionKey, props.initialRevision, props.onPersistedMetaChange, props.onSnapshot, props.onStatsChange]); + useEffect(() => { + runtimeDocRef.current = runtimeDoc; + }, [runtimeDoc]); + useEffect(() => { const nextRuntimeDoc = tiptapDocFromBlocks(props.initialContent as Json) as Json; setRuntimeDoc(nextRuntimeDoc); @@ -246,15 +253,6 @@ export function LeptosTiptapEditorHost(props: DocumentEditorHostProps) { })); }, [props.documentId, props.initialContent, props.initialConflictDetectionKey, props.initialRevision, props.readOnly, props.title, props.workspaceId]); - useEffect(() => { - const iframeWindow = iframeRef.current?.contentWindow; - if (!iframeWindow) return; - const payload = bootstrapPayloadRef.current; - if (!payload) return; - postBridgeMessage(iframeWindow, REPLACE_DOCUMENT_EVENT, payload); - setBridgeState((prev) => ({ ...prev, status: prev.ready ? "reloading" : prev.status })); - }, [runtimeDoc]); - useEffect(() => { const bridge: EditorReferenceBridge = { insertInlineReference: () => ({ blockId: null }), @@ -304,7 +302,9 @@ export function LeptosTiptapEditorHost(props: DocumentEditorHostProps) { const publishSnapshot = (payload: HostDocumentPayload) => { const blocks = blocksFromTiptapDoc(payload.content) as Json; const stats = buildStats(blocks); - setRuntimeDoc(normalizeRuntimeDoc(payload.content as Json) as Json); + const nextRuntimeDoc = normalizeRuntimeDoc(payload.content as Json) as Json; + runtimeDocRef.current = nextRuntimeDoc; + setRuntimeDoc(nextRuntimeDoc); onSnapshotRef.current?.({ blocks, stats }); onStatsChangeRef.current?.(stats); return { blocks, stats }; @@ -423,14 +423,14 @@ export function LeptosTiptapEditorHost(props: DocumentEditorHostProps) { data-editor-host-kind="leptos_tiptap_iframe_debug" >
- 调试桥:`iframe + postMessage` prototype + 主编辑器:`leptos-tiptap` iframe debug host {bridgeState.status}