diff --git a/browser/components/smartwindow/content/chat.mjs b/browser/components/smartwindow/content/chat.mjs index cf0faa1fc2efb..e8e2868385173 100644 --- a/browser/components/smartwindow/content/chat.mjs +++ b/browser/components/smartwindow/content/chat.mjs @@ -981,11 +981,12 @@ class ChatBot extends MozLitElement { console.log("Mention dataset:", mentionElement.dataset); const url = - mentionElement.dataset.id || mentionElement.getAttribute("data-id"); + mentionElement.dataset.mentionId || + mentionElement.getAttribute("data-mention-id"); console.log("Extracted URL:", url); if (!url) { - console.warn("No URL found in mention data-id attribute"); + console.warn("No URL found in mention data-mention-id attribute"); return; } @@ -1509,7 +1510,7 @@ Today's date: ${currentDate}`; // Create the same HTML structure as renderHTML in smartbar.mjs const iconSrc = `page-icon:${url}`; const mentionHTML = - `` + + `` + `` + `${this.escapeHTML(title)}` + ``; diff --git a/browser/components/smartwindow/content/mentions.mjs b/browser/components/smartwindow/content/mentions.mjs index 6b5590baf9f48..6ba36da70d344 100644 --- a/browser/components/smartwindow/content/mentions.mjs +++ b/browser/components/smartwindow/content/mentions.mjs @@ -250,7 +250,9 @@ export class MentionDropdown { selectItem(index = this.selectedIndex) { if (index >= 0 && index < this.items.length) { this.onSelectCallback?.(this.items[index]); + return true; } + return false; } scrollToSelected() { @@ -278,8 +280,7 @@ export class MentionDropdown { if (event.key === "Enter") { event.preventDefault(); - this.selectItem(); - return true; + return this.selectItem(); } return false; diff --git a/browser/components/smartwindow/content/smartbar.mjs b/browser/components/smartwindow/content/smartbar.mjs index f34fea1af7ba9..b90c2fe63635f 100644 --- a/browser/components/smartwindow/content/smartbar.mjs +++ b/browser/components/smartwindow/content/smartbar.mjs @@ -168,7 +168,7 @@ export function attachToElement(element, options = {}) { const attrs = { ...HTMLAttributes, class: `${HTMLAttributes.class ?? ""} mention`.trim(), - "data-id": id, + "data-mention-id": id, "data-icon": icon || "", ...(source ? { "data-source": source } : {}), }; @@ -355,12 +355,12 @@ export function attachToElement(element, options = {}) { }); // Add click event listener for mention expansion toggle - element.addEventListener('click', (event) => { - const mentionElement = event.target.closest('.mention'); + element.addEventListener("click", event => { + const mentionElement = event.target.closest(".mention"); if (mentionElement) { event.preventDefault(); event.stopPropagation(); - mentionElement.classList.toggle('expanded'); + mentionElement.classList.toggle("expanded"); } }); diff --git a/browser/components/smartwindow/content/smartbar/index.mjs b/browser/components/smartwindow/content/smartbar/index.mjs new file mode 100644 index 0000000000000..1a823203a432e --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/index.mjs @@ -0,0 +1,272 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +import { + EditorState, + EditorView, + Plugin as PMPlugin, + PluginKey as PMPluginKey, + TextSelection, + baseKeymap, + history as PMHistory, + undo as PMHistoryUndo, + redo as PMHistoryRedo, + keymap, + suggestionsPlugin, + triggerCharacter, +} from "chrome://browser/content/smartwindow/prosemirror.bundle.js"; + +import { + PLACEHOLDER_TEXT, + buildExtractedTexts, + createDocFromText, + createPasteToPillPlugin, + createPlaceholderPlugin, + schema, +} from "chrome://browser/content/smartwindow/smartbar/smartbar-document.mjs"; + +import { MentionDropdownController } from "chrome://browser/content/smartwindow/smartbar/smartbar-mention-controller.mjs"; +import { SmartbarController } from "chrome://browser/content/smartwindow/smartbar/smartbar-controller.mjs"; +import { SmartbarSuggestions } from "chrome://browser/content/smartwindow/smartbar/smartbar-suggestions.mjs"; +import { switchToMatchingTab } from "chrome://browser/content/smartwindow/smartbar/smartbar-tabs.mjs"; +import { SuggestionController } from "chrome://browser/content/smartwindow/smartbar/smartbar-suggestion-controller.mjs"; +import { AutofillController } from "chrome://browser/content/smartwindow/smartbar/smartbar-autofill-controller.mjs"; + +/** + * Mounts the Smartbar editor into the provided element and returns its public API. + * + * @param {HTMLElement} element - Host element whose contents will be replaced with the editor. + * @param {object} [options] + * @param {(event: KeyboardEvent) => void} [options.onKeyDown] - Called before internal key handling. + * @param {(state: {text: string, isAutofilled: boolean}) => void} [options.onUpdate] - Runs on document changes. + * @param {(suggestion: object) => void} [options.onSuggestionSelect] - Fired after a suggestion is committed. + * @param {(type: string) => string} [options.getQueryTypeIcon] - Supplies fallback for suggestion icons. + * @returns {object} Smartbar controller helpers. + */ +export function attachToElement(element, options = {}) { + const { onKeyDown, onUpdate, onSuggestionSelect, getQueryTypeIcon } = options; + + const autofillController = new AutofillController(); + + const wrapper = document.createElement("div"); + wrapper.className = "smartbar-wrapper"; + + const parentNode = element.parentNode; + parentNode.replaceChild(wrapper, element); + wrapper.appendChild(element); + + const suggestionsView = new SmartbarSuggestions({ + parentNode, + getQueryTypeIcon, + onActionSuggestion: suggestion => { + switchToMatchingTab( + { + url: suggestion.url, + title: suggestion.title, + query: suggestion.query || suggestion.text, + }, + window + ); + }, + onSuggestionActivated: suggestion => { + setEditorContent(suggestion.text); + if (onSuggestionSelect) { + onSuggestionSelect(suggestion); + } + }, + }); + + const mentionDropdownKey = new PMPluginKey("mentionDropdown"); + const mentionDropdownStatePlugin = new PMPlugin({ + key: mentionDropdownKey, + state: { + init() { + return { + dropdown: null, + range: null, + isOpen: false, + abortController: null, + }; + }, + apply(tr, prev) { + const meta = tr.getMeta(mentionDropdownKey); + if (!meta) { + return prev; + } + return { ...prev, ...meta }; + }, + }, + }); + + const suggestionController = new SuggestionController({ + getEditorView: () => editorView, + mentionDropdownKey, + suggestionsView, + }); + + const mentionController = new MentionDropdownController({ + mentionDropdownKey, + hideSuggestions: () => suggestionController.hide(), + getEditorView: () => editorView, + }); + + const placeholderPlugin = createPlaceholderPlugin(PLACEHOLDER_TEXT); + const pasteToPillPlugin = createPasteToPillPlugin((item, range) => + mentionController.insertMentionCommand(item, range) + ); + + const mentionPlugin = suggestionsPlugin({ + matcher: triggerCharacter("@"), + onEnter: payload => mentionController.handleEnter(payload), + onChange: payload => mentionController.handleChange(payload), + onExit: payload => mentionController.handleExit(payload?.view), + onKeyDown: payload => + mentionController.handleKeyDown(payload?.view, payload?.event), + }); + + const state = EditorState.create({ + schema, + plugins: [ + PMHistory(), + keymap(baseKeymap), + keymap({ + "Mod-z": PMHistoryUndo, + "Mod-y": PMHistoryRedo, + "Shift-Mod-z": PMHistoryRedo, + }), + placeholderPlugin, + pasteToPillPlugin, + mentionPlugin, + mentionDropdownStatePlugin, + ], + }); + + let editable = true; + + const editorView = new EditorView( + { mount: element }, + { + state, + editable: () => editable, + dispatchTransaction(transaction) { + const newState = editorView.state.apply(transaction); + editorView.updateState(newState); + + if (transaction.docChanged) { + handleDocUpdate(); + } + }, + handleKeyDown(view, event) { + const ps = mentionDropdownKey.getState(view.state); + if (ps?.isOpen) { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + const inserted = ps?.dropdown?.selectItem?.(); + if (inserted) { + view.focus(); + } + return true; + } + return false; + } + + if (onKeyDown) { + onKeyDown(event); + } + + if (event.key === "Enter" && event.shiftKey) { + return insertHardBreak(view); + } + + const keysToPrevent = ["Enter", "ArrowUp", "ArrowDown", "Escape"]; + if (keysToPrevent.includes(event.key)) { + return true; + } + + // return false to let other plugins handle the event + return false; + }, + } + ); + + element.addEventListener("click", event => { + const mentionElement = event.target.closest(".mention"); + if (mentionElement) { + event.preventDefault(); + event.stopPropagation(); + mentionElement.classList.toggle("expanded"); + } + }); + + function handleDocUpdate() { + const json = editorView.state.doc.toJSON(); + const { plainText: text } = buildExtractedTexts(json); + + const { isAutofilled } = autofillController.handleTextChange(text); + suggestionController.handleDocUpdate({ text, docJSON: json }); + if (onUpdate) { + onUpdate({ text, isAutofilled }); + } + } + + function insertHardBreak(view) { + const hardBreak = schema.nodes.hard_break; + if (!hardBreak) { + return false; + } + + const { dispatch } = view; + const tr = view.state.tr + .replaceSelectionWith(hardBreak.create()) + .scrollIntoView(); + dispatch(tr); + return true; + } + + function setEditorContent(content, { moveToEnd = true } = {}) { + const text = typeof content === "string" ? content : ""; + const { state: viewState, dispatch } = editorView; + const newDoc = createDocFromText(text); + if (viewState.doc.eq(newDoc)) { + return; // content did not change + } + let tr = viewState.tr.replaceWith( + 0, + viewState.doc.content.size, + newDoc.content + ); + if (moveToEnd) { + tr = tr.setSelection(TextSelection.atEnd(tr.doc)); + } + dispatch(tr); + } + + function focusEditorAtEnd() { + const selection = TextSelection.atEnd(editorView.state.doc); + editorView.dispatch(editorView.state.tr.setSelection(selection)); + editorView.focus(); + } + + const controller = new SmartbarController({ + editorView, + suggestionController, + autofillController, + setEditorContent, + focusEditorAtEnd, + getDocJSON: () => editorView.state.doc.toJSON(), + destroyResources: () => { + editorView.destroy(); + suggestionsView.destroy(); + }, + setEditableState: isEditable => { + editable = isEditable; + editorView.setProps({ + editable: () => editable, + }); + }, + mentionController, + }); + + return controller; +} diff --git a/browser/components/smartwindow/content/smartbar/smartbar-autofill-controller.mjs b/browser/components/smartwindow/content/smartbar/smartbar-autofill-controller.mjs new file mode 100644 index 0000000000000..8d677e03c9452 --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/smartbar-autofill-controller.mjs @@ -0,0 +1,102 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +/** + * Controls lifecycle of inline autofill suggestions applied to the Smartbar input. + */ +class AutofillController { + constructor() { + this.reset(); + } + + reset() { + this._autofillState = null; + this._deletedQuery = ""; + this._previousText = ""; + this._mutationActive = false; + } + + /** + * Prepares applying an autofill suggestion if it is compatible with the current text. + * + * @param {object} params + * @param {{ value:string, selectionStart:number, selectionEnd:number }} params.autofillData + * @param {string} params.currentText - Plain-text representation of the editor contents. + * @returns {{ value:string, selectionStart:number, selectionEnd:number } | null} + */ + prepareAutofill({ autofillData, currentText }) { + if (!autofillData?.value) { + return null; + } + + const loweredCurrent = currentText.toLowerCase().trim(); + if ( + this._deletedQuery && + (loweredCurrent === this._deletedQuery || + this._deletedQuery.startsWith(loweredCurrent)) + ) { + return null; + } + + const expectedPrefix = autofillData.value.substring( + 0, + autofillData.selectionStart + ); + if (currentText !== expectedPrefix) { + return null; + } + + this._autofillState = { + value: autofillData.value.trim(), + originalPrefix: currentText, + }; + this._mutationActive = true; + + return { + value: autofillData.value, + selectionStart: autofillData.selectionStart, + selectionEnd: autofillData.selectionEnd, + }; + } + + finishAutofillMutation() { + this._mutationActive = false; + } + + /** + * Updates internal tracking based on the latest document text. + * + * @param {string} text + * @returns {{ isAutofilled: boolean }} + */ + handleTextChange(text) { + if (this._autofillState) { + if ( + text !== this._autofillState.value && + text.length < this._autofillState.value.length + ) { + this._deletedQuery = this._autofillState.originalPrefix + .toLowerCase() + .trim(); + this._autofillState = null; + } else if (text.length > this._autofillState.value.length) { + this._autofillState = null; + } + } + + if ( + this._deletedQuery && + this._previousText && + text.toLowerCase().startsWith(this._previousText.toLowerCase()) && + text.length > this._previousText.length + ) { + this._deletedQuery = ""; + } + + this._previousText = text; + return { isAutofilled: this._mutationActive }; + } +} + +export { AutofillController }; diff --git a/browser/components/smartwindow/content/smartbar/smartbar-controller.mjs b/browser/components/smartwindow/content/smartbar/smartbar-controller.mjs new file mode 100644 index 0000000000000..1b7f96a282464 --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/smartbar-controller.mjs @@ -0,0 +1,162 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +import { TextSelection } from "chrome://browser/content/smartwindow/prosemirror.bundle.js"; +import { + buildExtractedTexts, + docToHTML, + hasExistingMentions, +} from "chrome://browser/content/smartwindow/smartbar/smartbar-document.mjs"; + +/** + * Controller for the Smartbar. + * + * @class SmartbarController + * @param {object} options + * @param {import('prosemirror-view').EditorView} options.editorView - Active ProseMirror EditorView instance. + * @param {object} options.suggestionController - Controller handling suggestions UI. + * @param {object} options.autofillController - Controller encapsulating autofill preparation and mutation lifecycle. + * @param {Function} options.setEditorContent - Function(content:string, options?:{moveToEnd?:boolean}) -> void for controlled content replacement. + * @param {Function} options.focusEditorAtEnd - Focuses editor and moves cursor to end of document. + * @param {Function} options.getDocJSON - Returns the current editor doc as JSON. + * @param {Function} options.destroyResources - Callback to free resources on teardown. + * @param {Function} options.setEditableState - Toggles editor editable state. + * @param {import('./smartbar-mention-controller.mjs').MentionDropdownController} options.mentionController - Controller for mention dropdown lifecycle. + */ +class SmartbarController { + constructor({ + editorView, + suggestionController, + autofillController, + setEditorContent, + focusEditorAtEnd, + getDocJSON, + destroyResources, + setEditableState, + mentionController, + }) { + this.editor = editorView; + this._suggestionController = suggestionController; + this._autofillController = autofillController; + this._setEditorContent = setEditorContent; + this._focusEditorAtEnd = focusEditorAtEnd; + this._getDocJSON = getDocJSON; + this._destroyResources = destroyResources; + this._setEditableState = setEditableState; + this._mentionController = mentionController; + } + + focus() { + this._focusEditorAtEnd(); + } + + setAutofill(autofillData) { + const json = this._getDocJSON(); + const { plainText: currentText } = buildExtractedTexts(json); + const payload = this._autofillController.prepareAutofill({ + autofillData, + currentText, + }); + if (!payload) { + return; + } + this._setEditorContent(payload.value, { moveToEnd: false }); + const from = payload.selectionStart + 1; + const to = payload.selectionEnd + 1; + const selection = TextSelection.create(this.editor.state.doc, from, to); + this.editor.dispatch(this.editor.state.tr.setSelection(selection)); + this._autofillController.finishAutofillMutation(); + } + + getText() { + return buildExtractedTexts(this._getDocJSON()).labeledQueryText; + } + + getPlainText() { + return buildExtractedTexts(this._getDocJSON()).plainText; + } + + getQueryText() { + return buildExtractedTexts(this._getDocJSON()).queryText; + } + + getHTML() { + return docToHTML(this.editor.state.doc); + } + + getMentions() { + const mentions = []; + const json = this._getDocJSON(); + function collectMentions(node) { + if (!node) { + return; + } + if (node.type === "mention") { + mentions.push({ + id: node.attrs?.id || "", + label: node.attrs?.label || "", + source: node.attrs?.source || null, + }); + } + if (Array.isArray(node.content)) { + node.content.forEach(collectMentions); + } + } + if (Array.isArray(json?.content)) { + json.content.forEach(collectMentions); + } + return mentions; + } + + setContent(content) { + this._setEditorContent(content); + } + + clear() { + this._autofillController.reset(); + this._setEditorContent(""); + this._suggestionController.hide(); + this._focusEditorAtEnd(); + } + + setEditable(isEditable) { + this._setEditableState(isEditable); + } + + destroy() { + this._mentionController.destroyDropdown(this.editor); + this._destroyResources(); + } + + hasExistingMentions() { + return hasExistingMentions(this._getDocJSON()); + } + + showSuggestions(suggestions, title, isQuickPrompts, query) { + this._suggestionController.show({ + suggestions, + title, + isQuickPrompts, + query, + }); + } + + hideSuggestions() { + this._suggestionController.hide(); + } + + navigateSuggestions(direction) { + this._suggestionController.navigate(direction); + } + + getSelectedSuggestion() { + return this._suggestionController.getSelected(); + } + + hasSuggestions() { + return this._suggestionController.hasSuggestions(); + } +} + +export { SmartbarController }; diff --git a/browser/components/smartwindow/content/smartbar/smartbar-document.mjs b/browser/components/smartwindow/content/smartbar/smartbar-document.mjs new file mode 100644 index 0000000000000..1785000ea150b --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/smartbar-document.mjs @@ -0,0 +1,336 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +import { + DOMSerializer, + Decoration, + DecorationSet, + Plugin as PMPlugin, + Schema, + basicSchema, +} from "chrome://browser/content/smartwindow/prosemirror.bundle.js"; + +const PLACEHOLDER_TEXT = "Ask, search, or type a URL"; + +// matches http(s) URLs +const URL_REGEX = /^https?:\/\/[^\s]+$/i; + +function resolveMentionIcon({ id, icon }) { + if (!icon) { + return id ? `page-icon:${id}` : ""; + } + if (icon.startsWith("data:")) { + return id ? `page-icon:${id}` : ""; + } + return icon; +} + +const mentionNodeSpec = { + attrs: { + id: { default: "" }, + label: { default: "" }, + icon: { default: "" }, + source: { default: null }, + }, + group: "inline", + inline: true, + atom: true, + selectable: false, + parseDOM: [ + { + tag: "span[data-mention-id]", + getAttrs(dom) { + const element = dom; + return { + id: element.getAttribute("data-mention-id") || "", + label: element.getAttribute("data-mention-label") || "", + icon: element.getAttribute("data-icon") || "", + source: element.getAttribute("data-source") || null, + }; + }, + }, + ], + toDOM(node) { + const { id, label, icon, source } = node.attrs; + const finalLabel = label || id; + const iconSrc = resolveMentionIcon({ id, icon }); + const attrs = { + class: "mention", + "data-mention-id": id, + "data-mention-label": label || "", + "data-mention-suggestion-char": "@", + ...(source ? { "data-source": source } : {}), + contenteditable: "false", + "aria-label": id ? `${finalLabel} (${id})` : finalLabel, + }; + return [ + "span", + attrs, + [ + "img", + { + src: iconSrc, + alt: "", + class: "mention-icon", + width: "16", + height: "16", + }, + ], + [ + "span", + { class: "mention-label", title: `${finalLabel} (${id})` }, + finalLabel, + ], + ]; + }, +}; + +const schema = new Schema({ + nodes: basicSchema.spec.nodes.append({ mention: mentionNodeSpec }), + marks: basicSchema.spec.marks, +}); + +const serializer = DOMSerializer.fromSchema(schema); + +/** + * Returns a ProseMirror plugin that overlays placeholder text when the doc is empty. + * + * @param {string} [placeholder] + * @param {typeof PMPlugin} [pluginClass] + * @returns {PMPlugin} + */ +function createPlaceholderPlugin( + placeholder = PLACEHOLDER_TEXT, + pluginClass = PMPlugin +) { + return new pluginClass({ + props: { + decorations(state) { + const firstChild = state.doc.firstChild; + const isEmptyParagraph = + state.doc.childCount === 1 && + firstChild?.type.name === "paragraph" && + firstChild.content.size === 0; + + if (!isEmptyParagraph) { + return null; + } + + return DecorationSet.create(state.doc, [ + Decoration.node(0, firstChild.nodeSize, { + class: "is-editor-empty", + "data-placeholder": placeholder, + }), + ]); + }, + }, + }); +} + +/** + * Returns a ProseMirror plugin that converts pasted URLs to mention pills. + * + * @param {Function} insertMentionCommand - Command function from MentionDropdownController that inserts a mention. + * @param {typeof PMPlugin} [pluginClass] + * @returns {PMPlugin} + */ +function createPasteToPillPlugin(insertMentionCommand, pluginClass = PMPlugin) { + return new pluginClass({ + props: { + handlePaste(view, _event, slice) { + // Don’t intercept paste during composition + if (view.composing) { + return false; + } + + // Extract text from the pasted content + const pastedText = slice.content.textBetween( + 0, + slice.content.size, + "\n" + ); + const trimmed = pastedText.trim(); + + // Check URL + if (!URL_REGEX.test(trimmed)) { + return false; // Let default paste behavior handle it + } + + // Create a mention pill covering the current selection + const { from, to } = view.state.selection; + const cmd = insertMentionCommand({ + id: trimmed, + label: trimmed, + icon: "", + type: "paste", + }, { from, to }); + + // Execute the command with closeHistory to isolate as single undo step + cmd(view.state, tr => { + view.dispatch(tr.setMeta("closeHistory", true)); + }); + + return true; // prevents default paste + }, + }, + }); +} + +/** + * Serializes the document node to an HTML string. + * + * @param {ProseMirrorNode} doc + * @returns {string} + */ +function docToHTML(doc) { + const fragment = serializer.serializeFragment(doc.content); + const div = document.createElement("div"); + div.appendChild(fragment); + return div.innerHTML; +} + +/** + * Builds a doc node from newline-delimited text. + * + * @param {string} text + * @returns {ProseMirrorNode} + */ +function createDocFromText(text) { + const paragraphs = text + .split(/\n/) + .map(line => + schema.nodes.paragraph.create(null, line ? schema.text(line) : null) + ); + + return schema.node( + "doc", + null, + paragraphs.length ? paragraphs : [schema.nodes.paragraph.create()] + ); +} + +/** + * Computes the bounding rect for the mention trigger range. + * + * @param {EditorView} view + * @param {{from:number,to:number}} range + * @returns {{left:number,right:number,top:number,bottom:number,width:number,height:number}|null} + */ +function getMentionClientRect(view, range) { + if (!range) { + return null; + } + + const start = view.coordsAtPos(range.from); + const end = view.coordsAtPos(range.to); + + return { + left: start.left, + right: start.left, + top: start.bottom, + bottom: start.bottom, + width: Math.max(end.left - start.left, 1), + height: start.bottom - start.top, + }; +} + +/** + * Produces multiple textual versions of the doc: plain, query (ids), and labeled query. + * + * @param {object} json - ProseMirror JSON representation of the doc. + * @returns {{plainText: string, queryText: string, labeledQueryText: string}} + */ +function buildExtractedTexts(json) { + const plainParts = []; + const queryParts = []; + const labeledQueryParts = []; + + function walk(node) { + if (!node) { + return; + } + if (node.type === "text") { + const t = node.text || ""; + plainParts.push(t); + queryParts.push(t); + labeledQueryParts.push(t); + return; + } + if (node.type === "hard_break") { + plainParts.push("\n"); + queryParts.push("\n"); + labeledQueryParts.push("\n"); + return; + } + if (node.type === "mention") { + const label = node.attrs?.label || node.attrs?.id || ""; + const id = node.attrs?.id || ""; + plainParts.push(label); + queryParts.push(id); + labeledQueryParts.push(`@${label} (${id})`); + return; + } + if (Array.isArray(node.content)) { + node.content.forEach(walk); + } + } + + if (Array.isArray(json?.content)) { + json.content.forEach(walk); + } + + return { + plainText: plainParts.join("").replace(/\u00A0/g, " "), + queryText: queryParts.join("").replace(/\u00A0/g, " "), + labeledQueryText: labeledQueryParts.join("").replace(/\u00A0/g, " "), + }; +} + +/** + * Collects mention IDs present in the document. + * + * @param {object} json - ProseMirror JSON document. + * @returns {Set} + */ +function getExistingMentionIds(json) { + const mentionIds = new Set(); + if (!json?.content) { + return mentionIds; + } + + function extractMentionIds(node) { + if (node?.type === "mention" && node.attrs?.id) { + mentionIds.add(node.attrs.id); + } + if (node?.content) { + node.content.forEach(extractMentionIds); + } + } + + json.content.forEach(extractMentionIds); + return mentionIds; +} + +/** + * Indicates whether the doc already contains mention nodes. + * + * @param {object} json - ProseMirror JSON document. + * @returns {boolean} + */ +function hasExistingMentions(json) { + return getExistingMentionIds(json).size > 0; +} + +export { + PLACEHOLDER_TEXT, + buildExtractedTexts, + createDocFromText, + createPasteToPillPlugin, + createPlaceholderPlugin, + docToHTML, + getExistingMentionIds, + getMentionClientRect, + hasExistingMentions, + schema, +}; diff --git a/browser/components/smartwindow/content/smartbar/smartbar-mention-controller.mjs b/browser/components/smartwindow/content/smartbar/smartbar-mention-controller.mjs new file mode 100644 index 0000000000000..735aaee3a0873 --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/smartbar-mention-controller.mjs @@ -0,0 +1,175 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +import { TextSelection } from "chrome://browser/content/smartwindow/prosemirror.bundle.js"; +import { + MentionDropdown, + getMentionSuggestions, +} from "chrome://browser/content/smartwindow/mentions.mjs"; +import { + getExistingMentionIds, + getMentionClientRect, + schema, +} from "chrome://browser/content/smartwindow/smartbar/smartbar-document.mjs"; + +/** + * Controller for the mentions dropdown. + * + * @class MentionDropdownController + * @param {object} options - Construction options. + * @param {import("chrome://browser/content/smartwindow/prosemirror.bundle.js").PluginKey} options.mentionDropdownKey - PluginKey used to store dropdown state meta on transactions. + * @param {Function} options.hideSuggestions - Callback to hide any non-mention suggestions UI when opening the mention dropdown. + * @param {Function} options.getEditorView - Lazy getter returning the current EditorView if handlers are invoked without an explicit view. + */ +class MentionDropdownController { + constructor({ mentionDropdownKey, hideSuggestions, getEditorView }) { + this.key = mentionDropdownKey; + this.hideSuggestions = hideSuggestions; + this.getEditorView = getEditorView; + } + + dispatchMeta(view, meta) { + view.dispatch(view.state.tr.setMeta(this.key, meta)); + } + + destroyDropdown(view) { + if (!view) { + return; + } + const ps = this.key.getState(view.state); + ps?.dropdown?.destroy(); + if (ps?.abortController) { + ps.abortController.abort(); + } + this.dispatchMeta(view, { + dropdown: null, + range: null, + isOpen: false, + abortController: null, + }); + } + + async updateMentionSuggestions(view, text, range) { + if (!view) { + return; + } + const query = text.replace(/^@/, "").trim(); + const current = this.key.getState(view.state); + if (current?.abortController) { + current.abortController.abort(); + } + const abortController = new AbortController(); + const { signal } = abortController; + this.dispatchMeta(view, { abortController }); + + let items = []; + try { + items = await getMentionSuggestions(query, { signal }); + } catch (error) { + if (signal.aborted) { + return; + } + console.error("Mention suggestions error", error); + const ps = this.key.getState(view.state); + ps?.dropdown?.destroy(); + this.dispatchMeta(view, { + dropdown: null, + range: null, + isOpen: false, + abortController: null, + }); + return; + } + + if (signal.aborted) { + return; + } + + const postFetchJson = view.state.doc.toJSON(); + const postFetchMentionIds = getExistingMentionIds(postFetchJson); + const filtered = items.filter( + suggestion => !postFetchMentionIds.has(suggestion.id) + ); + + const ps = this.key.getState(view.state); + let dropdown = ps?.dropdown; + if (!dropdown) { + dropdown = new MentionDropdown(); + dropdown.create(filtered, item => { + const cmd = this.insertMentionCommand(item, ps?.range); + cmd(view.state, view.dispatch, view); + this.destroyDropdown(view); + requestAnimationFrame(() => view.focus()); + }); + this.dispatchMeta(view, { dropdown }); + } else { + dropdown.update(filtered); + } + + const rect = getMentionClientRect(view, range); + if (rect) { + dropdown.updatePosition(rect); + } + } + + insertMentionCommand(item, range) { + return (editorState, dispatch) => { + if (!range) { + return false; + } + const icon = + item.icon ?? item.favicon ?? (item.id ? `page-icon:${item.id}` : ""); + const mentionNode = schema.nodes.mention.create({ + id: item.id, + label: item.label || item.id || "", + icon, + source: item.type || null, + }); + const afterMention = range.from + mentionNode.nodeSize; + const tr = editorState.tr.replaceWith(range.from, range.to, mentionNode); + tr.setSelection(TextSelection.create(tr.doc, afterMention)) + .insertText("\u00A0", afterMention) + .setSelection(TextSelection.create(tr.doc, afterMention + 1)) + .scrollIntoView(); + if (dispatch) { + dispatch(tr); + } + return true; + }; + } + + handleEnter({ view, range, text }) { + const targetView = view || this.getEditorView?.(); + if (!targetView) { + return; + } + this.dispatchMeta(targetView, { isOpen: true, range }); + this.hideSuggestions?.(); + this.updateMentionSuggestions(targetView, text, range); + } + + handleChange({ view, range, text }) { + const targetView = view || this.getEditorView?.(); + if (!targetView) { + return; + } + this.dispatchMeta(targetView, { range }); + this.updateMentionSuggestions(targetView, text, range); + } + + handleExit(view) { + this.destroyDropdown(view || this.getEditorView?.()); + } + + handleKeyDown(view, event) { + const targetView = view || this.getEditorView?.(); + if (!targetView) { + return false; + } + const ps = this.key.getState(targetView.state); + return ps?.dropdown?.handleKeyDown(event) || false; + } +} + +export { MentionDropdownController }; diff --git a/browser/components/smartwindow/content/smartbar/smartbar-suggestion-controller.mjs b/browser/components/smartwindow/content/smartbar/smartbar-suggestion-controller.mjs new file mode 100644 index 0000000000000..630304487fddf --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/smartbar-suggestion-controller.mjs @@ -0,0 +1,78 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +import { + buildExtractedTexts, + hasExistingMentions, +} from "chrome://browser/content/smartwindow/smartbar/smartbar-document.mjs"; + +/** + * Controller for smartbar suggestions. + * + * @class SuggestionController + * @param {object} options + * @param {Function} options.getEditorView - Lazy getter returning the current ProseMirror EditorView. + * @param {import('chrome://browser/content/smartwindow/prosemirror.bundle.js').PluginKey} options.mentionDropdownKey - PluginKey for accessing mention dropdown plugin state. + * @param {object} options.suggestionsView - View adapter. + */ +class SuggestionController { + constructor({ getEditorView, mentionDropdownKey, suggestionsView }) { + this._getEditorView = getEditorView; + this._mentionDropdownKey = mentionDropdownKey; + this._suggestionsView = suggestionsView; + } + + show({ + suggestions, + title = "Suggestions:", + isQuickPrompts = false, + query = "", + }) { + const view = this._getEditorView?.(); + if (!view) { + return; + } + const docJSON = view.state.doc.toJSON(); + const { plainText } = buildExtractedTexts(docJSON); + const trimmed = plainText.trim(); + const ps = this._mentionDropdownKey.getState(view.state); + if (!trimmed || ps?.isOpen || hasExistingMentions(docJSON)) { + return; + } + this._suggestionsView.show({ + suggestions, + title, + isQuickPrompts, + query, + }); + } + + hide() { + this._suggestionsView.hide(); + } + + navigate(direction) { + this._suggestionsView.navigate(direction); + } + + getSelected() { + return this._suggestionsView.getSelected(); + } + + hasSuggestions() { + return this._suggestionsView.hasSuggestions(); + } + + isVisible() { + return this._suggestionsView.isVisible(); + } + + handleDocUpdate({ text, docJSON }) { + if ((!text.trim() && this.isVisible()) || hasExistingMentions(docJSON)) { + this.hide(); + } + } +} + +export { SuggestionController }; diff --git a/browser/components/smartwindow/content/smartbar/smartbar-suggestions.mjs b/browser/components/smartwindow/content/smartbar/smartbar-suggestions.mjs new file mode 100644 index 0000000000000..f4445b7d05ab4 --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/smartbar-suggestions.mjs @@ -0,0 +1,265 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +/** + * Renders the Smartbar suggestion list, manages selection state, + * and forwards activation callbacks. + */ +class SmartbarSuggestions { + constructor({ + parentNode, + getQueryTypeIcon, + onActionSuggestion, + onSuggestionActivated, + }) { + this._getQueryTypeIcon = getQueryTypeIcon; + this._onActionSuggestion = onActionSuggestion; + this._onSuggestionActivated = onSuggestionActivated; + this._suggestions = []; + this._selectedIndex = -1; + this._container = this.#createContainer(); + parentNode.appendChild(this._container); + this._list = this._container.querySelector(".suggestions-list"); + this._title = this._container.querySelector(".suggestions-title"); + + this._container.addEventListener("mouseleave", () => { + if (this._selectedIndex >= 0) { + this.select(-1); + } + }); + } + + get container() { + return this._container; + } + + destroy() { + this._container?.remove(); + this._container = null; + this._suggestions = []; + this._selectedIndex = -1; + } + + show({ + suggestions, + title = "Suggestions:", + isQuickPrompts = false, + query = "", + }) { + if (!this._container) { + return; + } + this._container.classList.remove("hidden"); + this._container.classList.toggle("quick-prompts", !!isQuickPrompts); + this._container.classList.toggle("user-edited", !isQuickPrompts); + + this._suggestions = suggestions; + this._selectedIndex = -1; + + if (this._title) { + this._title.textContent = title; + } + + this._list.textContent = ""; + suggestions.forEach((suggestion, index) => { + const button = this.#createSuggestionButton( + { ...suggestion, query: query.trim() }, + index + ); + this._list.appendChild(button); + }); + } + + hide() { + if (!this._container) { + return; + } + this._container.classList.add("hidden"); + this._container.classList.remove("quick-prompts", "user-edited"); + this._suggestions = []; + this._selectedIndex = -1; + } + + isVisible() { + return !!this._container && !this._container.classList.contains("hidden"); + } + + navigate(direction) { + if (!this._suggestions.length) { + return; + } + if (direction === "down") { + this._selectedIndex = Math.min( + this._selectedIndex + 1, + this._suggestions.length - 1 + ); + } else if (direction === "up") { + this._selectedIndex = Math.max(this._selectedIndex - 1, -1); + } + this.#updateSelection(); + } + + select(index) { + this._selectedIndex = index; + this.#updateSelection(); + } + + getSelected() { + return this._selectedIndex >= 0 + ? this._suggestions[this._selectedIndex] + : null; + } + + hasSuggestions() { + return !!this._suggestions.length; + } + + #createContainer() { + const container = document.createElement("div"); + container.id = "suggestions-container"; + container.className = "suggestions-container hidden"; + + const suggestionsHeader = document.createElement("div"); + suggestionsHeader.className = "suggestions-header"; + const suggestionsTitle = document.createElement("span"); + suggestionsTitle.className = "suggestions-title"; + suggestionsTitle.textContent = "Suggestions:"; + suggestionsHeader.appendChild(suggestionsTitle); + + const suggestionsList = document.createElement("div"); + suggestionsList.className = "suggestions-list"; + suggestionsList.id = "suggestions-list"; + suggestionsList.setAttribute("role", "listbox"); + suggestionsList.setAttribute("aria-label", "Suggestions"); + + container.appendChild(suggestionsHeader); + container.appendChild(suggestionsList); + return container; + } + + #createSuggestionButton(suggestion, index) { + const button = document.createElement("button"); + button.className = `suggestion-button suggestion-${suggestion.type}`; + button.dataset.index = index; + button.setAttribute("role", "option"); + button.setAttribute("aria-selected", "false"); + + const icon = document.createElement("span"); + icon.className = "suggestion-icon"; + const useProvidedIcon = + suggestion.type !== "action" && suggestion.type !== "search"; + + if (useProvidedIcon && suggestion.icon) { + const imgElement = document.createElement("img"); + imgElement.src = suggestion.icon; + imgElement.alt = ""; + icon.appendChild(imgElement); + } else { + icon.textContent = this._getQueryTypeIcon + ? this._getQueryTypeIcon(suggestion.type) + : "🔍"; + } + + const textContainer = document.createElement("div"); + textContainer.className = "suggestion-text-container"; + + if (suggestion.type === "navigate" && suggestion.title) { + const title = document.createElement("span"); + title.className = "suggestion-title"; + title.textContent = suggestion.title; + + const url = document.createElement("span"); + url.className = "suggestion-url"; + url.textContent = suggestion.text || suggestion.url; + + if (suggestion.query) { + this.#highlightQueryMatches(title, suggestion.query); + this.#highlightQueryMatches(url, suggestion.query); + } + + textContainer.appendChild(title); + textContainer.appendChild(url); + } else { + const text = document.createElement("span"); + text.className = "suggestion-text"; + text.textContent = suggestion.text; + + if (suggestion.query) { + this.#highlightQueryMatches(text, suggestion.query); + } + + textContainer.appendChild(text); + } + + button.appendChild(icon); + button.appendChild(textContainer); + + button.addEventListener("mouseenter", () => { + this.select(index); + }); + + button.addEventListener("click", event => { + event.preventDefault(); + if (suggestion.type === "action") { + this._onActionSuggestion?.(suggestion); + } else { + this._onSuggestionActivated?.(suggestion); + } + }); + + return button; + } + + #updateSelection() { + const buttons = + this._container?.querySelectorAll(".suggestion-button") || []; + buttons.forEach((button, index) => { + const selected = index === this._selectedIndex; + button.classList.toggle("selected", selected); + button.setAttribute("aria-selected", selected ? "true" : "false"); + }); + } + + #highlightQueryMatches(container, query) { + const raw = (query || "").trim(); + if (!raw || !container.textContent) { + return; + } + const source = container.textContent; + const words = raw + .split(/\s+/) + .filter(Boolean) + .map(w => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); + if (!words.length) { + return; + } + const regex = new RegExp(words.join("|"), "gi"); + const ranges = []; + let match; + while ((match = regex.exec(source))) { + ranges.push({ from: match.index, to: match.index + match[0].length }); + } + if (!ranges.length) { + return; + } + const frag = document.createDocumentFragment(); + let cursor = 0; + for (const r of ranges) { + if (cursor < r.from) { + frag.appendChild(document.createTextNode(source.slice(cursor, r.from))); + } + const mark = document.createElement("mark"); + mark.textContent = source.slice(r.from, r.to); + frag.appendChild(mark); + cursor = r.to; + } + if (cursor < source.length) { + frag.appendChild(document.createTextNode(source.slice(cursor))); + } + container.textContent = ""; + container.appendChild(frag); + } +} + +export { SmartbarSuggestions }; diff --git a/browser/components/smartwindow/content/smartbar/smartbar-tabs.mjs b/browser/components/smartwindow/content/smartbar/smartbar-tabs.mjs new file mode 100644 index 0000000000000..dd5a29b44079c --- /dev/null +++ b/browser/components/smartwindow/content/smartbar/smartbar-tabs.mjs @@ -0,0 +1,54 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +/** + * Finds an existing browser tab whose title or URL matches the provided query and focuses it. + * + * @param {{url?:string,title?:string,query?:string}} params + * @param {Window} [win] - Optional browser window; falls back to the most recent one. + */ +function switchToMatchingTab({ url, title, query } = {}, win = window) { + const searchTerm = (url || title || query || "").toLowerCase(); + if (!searchTerm) { + return; + } + + let browserWindow = + win && win.gBrowser + ? win + : Services.wm.getMostRecentWindow("navigator:browser"); + if (!browserWindow || !browserWindow.gBrowser) { + return; + } + + const { gBrowser } = browserWindow; + const tabs = Array.from(gBrowser.tabs); + + const match = tabs.find(tab => { + const linkedBrowser = tab.linkedBrowser; + const titleText = ( + linkedBrowser?.contentTitle || + tab.label || + "" + ).toLowerCase(); + const urlText = (linkedBrowser?.currentURI?.spec || "").toLowerCase(); + + if (url) { + return urlText.includes(searchTerm); + } + if (title) { + return titleText.includes(searchTerm); + } + return titleText.includes(searchTerm) || urlText.includes(searchTerm); + }); + + if (!match) { + return; + } + + browserWindow.focus(); + gBrowser.selectedTab = match; +} + +export { switchToMatchingTab }; diff --git a/browser/components/smartwindow/content/smartwindow.css b/browser/components/smartwindow/content/smartwindow.css index a47491aba6c4e..aff8bd1f11896 100644 --- a/browser/components/smartwindow/content/smartwindow.css +++ b/browser/components/smartwindow/content/smartwindow.css @@ -93,7 +93,7 @@ body { padding: var(--space-small) var(--space-medium); } -#tiptap-editor { +#editor { width: 100%; font-size: 15px; border: none; @@ -112,24 +112,25 @@ body { } /* Tiptap Editor Styles */ -#tiptap-editor { +#editor { flex: 1; min-height: 40px; overflow-y: auto; } -#tiptap-editor .ProseMirror { +#editor .ProseMirror { outline: none; padding: 0; min-height: var(--icon-size-medium); + white-space: pre-wrap; } -#tiptap-editor .ProseMirror p { +#editor .ProseMirror p { margin: 0; padding: 0; } -#tiptap-editor .ProseMirror p.is-editor-empty:first-child::before { +#editor .ProseMirror p.is-editor-empty:first-child::before { content: attr(data-placeholder); float: left; color: rgba(21, 20, 26, 0.69); @@ -137,12 +138,12 @@ body { height: 0; } -#tiptap-editor .ProseMirror:focus { +#editor .ProseMirror:focus { outline: none; } /* Ensure single line appearance by default */ -#tiptap-editor .ProseMirror p:not(:first-child) { +#editor .ProseMirror p:not(:first-child) { margin-top: 0.5em; } diff --git a/browser/components/smartwindow/content/smartwindow.html b/browser/components/smartwindow/content/smartwindow.html index cf571596f2393..fc042e78aca7b 100644 --- a/browser/components/smartwindow/content/smartwindow.html +++ b/browser/components/smartwindow/content/smartwindow.html @@ -132,7 +132,7 @@

Insights

-
+
diff --git a/browser/components/smartwindow/content/smartwindow.mjs b/browser/components/smartwindow/content/smartwindow.mjs index 1067fa2b70056..01f5f858883df 100644 --- a/browser/components/smartwindow/content/smartwindow.mjs +++ b/browser/components/smartwindow/content/smartwindow.mjs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import { detectQueryType, searchBrowserHistory } from "./utils.mjs"; -import { attachToElement } from "chrome://browser/content/smartwindow/smartbar.mjs"; +import { attachToElement } from "chrome://browser/content/smartwindow/smartbar/index.mjs"; import { generateLiveSuggestions, generateConversationStarters, @@ -702,7 +702,7 @@ class SmartWindowPage { async onDOMReady() { this.isSidebarMode = embedderElement.id == "smartwindow-browser"; - const editorDiv = document.getElementById("tiptap-editor"); + const editorDiv = document.getElementById("editor"); this.smartbar = attachToElement(editorDiv, { onKeyDown: event => this.handleKeyDown(event), @@ -1785,6 +1785,15 @@ class SmartWindowPage { // Mark that user has manually edited the query this.userHasEditedQuery = true; + // Don’t fetch live suggestions or autofill data while the user is + // interacting with mentions. The ProseMirror document length doesn’t map + // cleanly to the plain-text query once mentions are present, which causes + // autofill to move the caret unexpectedly after the next key press. + if (this.smartbar?.hasExistingMentions()) { + this.smartbar.hideSuggestions(); + return; + } + // Don’t show suggestions mid-conversation if (this.chatBot?.messages?.length > 0) { return; @@ -1806,6 +1815,12 @@ class SmartWindowPage { query, topChromeWindow ); + + if (this.smartbar?.hasExistingMentions()) { + this.smartbar.hideSuggestions(); + return; + } + if (this.smartbar) { this.smartbar.showSuggestions(suggestions, "Suggestions:", false, query); diff --git a/browser/components/smartwindow/jar.mn b/browser/components/smartwindow/jar.mn index 34e67304f076b..f47e11270af99 100644 --- a/browser/components/smartwindow/jar.mn +++ b/browser/components/smartwindow/jar.mn @@ -3,23 +3,32 @@ # file, You can obtain one at http://mozilla.org/MPL/2.0/. browser.jar: - content/browser/smartwindow/chat.mjs (content/chat.mjs) - content/browser/smartwindow/chat-history.mjs (content/chat-history.mjs) - content/browser/smartwindow/combined-button-select.mjs (content/combined-button-select.mjs) - content/browser/smartwindow/tool-log.mjs (content/tool-log.mjs) - content/browser/smartwindow/insights.mjs (content/insights.mjs) - content/browser/smartwindow/insights.html (content/insights.html) - content/browser/smartwindow/marked.js (vendor/marked.js) - content/browser/smartwindow/mentions.mjs (content/mentions.mjs) - content/browser/smartwindow/page-history.mjs (content/page-history.mjs) - content/browser/smartwindow/smartbar.mjs (content/smartbar.mjs) - content/browser/smartwindow/suggestions.mjs (content/suggestions.mjs) - content/browser/smartwindow/tiptap-bundle.js (vendor/tiptap-bundle.js) - content/browser/smartwindow/smartwindow.css (content/smartwindow.css) - content/browser/smartwindow/smartwindow.html (content/smartwindow.html) - content/browser/smartwindow/smartwindow.mjs (content/smartwindow.mjs) - content/browser/smartwindow/smart-fx-icon.svg (content/smart-fx-icon.svg) - content/browser/smartwindow/favicon.svg (content/favicon.svg) - content/browser/smartwindow/utils.mjs (content/utils.mjs) - content/browser/smartwindow/welcome.html (content/welcome.html) - content/browser/smartwindow/welcome.js (content/welcome.js) + content/browser/smartwindow/chat.mjs (content/chat.mjs) + content/browser/smartwindow/chat-history.mjs (content/chat-history.mjs) + content/browser/smartwindow/combined-button-select.mjs (content/combined-button-select.mjs) + content/browser/smartwindow/tool-log.mjs (content/tool-log.mjs) + content/browser/smartwindow/insights.mjs (content/insights.mjs) + content/browser/smartwindow/insights.html (content/insights.html) + content/browser/smartwindow/marked.js (vendor/marked.js) + content/browser/smartwindow/mentions.mjs (content/mentions.mjs) + content/browser/smartwindow/page-history.mjs (content/page-history.mjs) + content/browser/smartwindow/smartbar.mjs (content/smartbar.mjs) + content/browser/smartwindow/smartbar/index.mjs (content/smartbar/index.mjs) + content/browser/smartwindow/smartbar/smartbar-controller.mjs (content/smartbar/smartbar-controller.mjs) + content/browser/smartwindow/smartbar/smartbar-document.mjs (content/smartbar/smartbar-document.mjs) + content/browser/smartwindow/smartbar/smartbar-mention-controller.mjs (content/smartbar/smartbar-mention-controller.mjs) + content/browser/smartwindow/smartbar/smartbar-autofill-controller.mjs (content/smartbar/smartbar-autofill-controller.mjs) + content/browser/smartwindow/smartbar/smartbar-suggestion-controller.mjs (content/smartbar/smartbar-suggestion-controller.mjs) + content/browser/smartwindow/smartbar/smartbar-suggestions.mjs (content/smartbar/smartbar-suggestions.mjs) + content/browser/smartwindow/smartbar/smartbar-tabs.mjs (content/smartbar/smartbar-tabs.mjs) + content/browser/smartwindow/suggestions.mjs (content/suggestions.mjs) + content/browser/smartwindow/tiptap-bundle.js (vendor/tiptap-bundle.js) + content/browser/smartwindow/prosemirror.bundle.js (vendor/prosemirror.bundle.js) + content/browser/smartwindow/smartwindow.css (content/smartwindow.css) + content/browser/smartwindow/smartwindow.html (content/smartwindow.html) + content/browser/smartwindow/smartwindow.mjs (content/smartwindow.mjs) + content/browser/smartwindow/smart-fx-icon.svg (content/smart-fx-icon.svg) + content/browser/smartwindow/favicon.svg (content/favicon.svg) + content/browser/smartwindow/utils.mjs (content/utils.mjs) + content/browser/smartwindow/welcome.html (content/welcome.html) + content/browser/smartwindow/welcome.js (content/welcome.js) diff --git a/browser/components/smartwindow/vendor/prosemirror.bundle.js b/browser/components/smartwindow/vendor/prosemirror.bundle.js new file mode 100644 index 0000000000000..dba4797cb0560 --- /dev/null +++ b/browser/components/smartwindow/vendor/prosemirror.bundle.js @@ -0,0 +1,11 @@ +var zs=Object.defineProperty;var cr=(n,e)=>{for(var t in e)zs(n,t,{get:e[t],enumerable:!0})};function P(n){this.content=n}P.prototype={constructor:P,find:function(n){for(var e=0;e>1}};P.from=function(n){if(n instanceof P)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new P(e)};var _t=P;function br(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),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)t++;return t}if(i.content.size||s.content.size){let o=br(i.content,s.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function Sr(n,e,t,r){for(let i=n.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:t,b:r};let o=n.child(--i),l=e.child(--s),a=o.nodeSize;if(o==l){t-=a,r-=a;continue}if(!o.sameMarkup(l))return{a:t,b:r};if(o.isText&&o.text!=l.text){let c=0,f=Math.min(o.text.length,l.text.length);for(;ce&&r(a,i+l,s||null,o)!==!1&&a.content.size){let f=l+1;a.nodesBetween(Math.max(0,e-f),Math.min(a.content.size,t-f),r,i+f)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!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&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=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(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new n(i,s)}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),s=r+i.nodeSize;if(s>=e)return s==e?Mt(t+1,s):Mt(t,r);r=s}}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(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};C.none=[];var Me=class extends Error{},x=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=Mr(this.content,e+this.openStart,t);return r&&new n(r,this.openStart,this.openEnd)}removeBetween(e,t){return new n(kr(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(y.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new n(e,r,i)}};x.empty=new x(y.empty,0,0);function kr(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(kr(s.content,e-i-1,t-i-1)))}function Mr(n,e,t,r){let{index:i,offset:s}=n.findIndex(e),o=n.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,t)?null:n.cut(0,e).append(t).append(n.cut(e));let l=Mr(o.content,e-s-1,t,o);return l&&n.replaceChild(i,o.copy(l))}function Bs(n,e,t){if(t.openStart>n.depth)throw new Me("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new Me("Inconsistent open depths");return Cr(n,e,t,0)}function Cr(n,e,t,r){let i=n.index(r),s=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 et(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Se(n.nodeAfter,r),s++));for(let l=s;li&&en(n,e,i+1),o=r.depth>i&&en(t,r,i+1),l=[];return et(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Or(s,o),Se(ke(s,Nr(n,e,t,r,i+1)),l)):(s&&Se(ke(s,Nt(n,e,i+1)),l),et(e,t,i,l),o&&Se(ke(o,Nt(t,r,i+1)),l)),et(r,null,i,l),new y(l)}function Nt(n,e,t){let r=[];if(et(null,n,t,r),n.depth>t){let i=en(n,e,t+1);Se(ke(i,Nt(n,e,t+1)),r)}return et(e,null,t,r),new y(r)}function Fs(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(y.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}var Dt=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 s=0;s0;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 nn(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,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new n(t,r,s)}static resolveCached(e,t){let r=fr.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.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()+")"),Dr(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=y.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.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=y.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};_.prototype.text=void 0;var rn=class n extends _{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):Dr(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 Dr(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}var Ce=class n{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new sn(e,t);if(r.next==null)return n.empty;let i=wr(r);r.next&&r.err("Unexpected trailing text");let s=Hs(Ks(i));return js(s,r),s}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 s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` +`)}};Ce.empty=new Ce(!0);var sn=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 wr(n){let e=[];do e.push(Ls(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Ls(n){let e=[];do e.push(Ws(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Ws(n){let e=$s(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=Js(n,e);else break;return e}function hr(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function Js(n,e){let t=hr(n),r=t;return n.eat(",")&&(n.next!="}"?r=hr(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function qs(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function $s(n){if(n.eat("(")){let e=wr(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=qs(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 Ks(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let f=0;f{c||i.push([l,c=[]]),c.indexOf(f)==-1&&c.push(f)})})});let s=e[r.join(",")]=new Ce(r.indexOf(n.length-1)>-1);for(let o=0;o-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:Ar(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new _(this,this.computeAttrs(e),y.from(t),C.setFrom(r))}createChecked(e=null,t,r){return t=y.from(t),this.checkContent(t),new _(this,this.computeAttrs(e),t,C.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=y.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(y.empty,!0);return s?new _(this,e,t.append(s),C.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[s]=new n(s,t,o));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 s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Us(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}var on=class{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Us(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}},nt=class n{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=Rr(e,i.attrs),this.excluded=null;let s=Er(this.attrs);this.instance=s?new C(this,s):null}create(e=null){return!e&&this.instance?this.instance:new C(this,Ar(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new n(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}},rt=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=_t.from(e.nodes),t.marks=_t.from(e.marks||{}),this.nodes=wt.compile(this.spec.nodes,this),this.marks=nt.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 s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Ce.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?dr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:dr(this,o.split(" "))}this.nodeFromJSON=i=>_.fromJSON(this,i),this.markFromJSON=i=>C.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 wt){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 rn(r,r.defaultAttrs,e,C.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 dr(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Gs(n){return n.tag!=null}function Ys(n){return n.style!=null}var Ve=class n{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Gs(i))this.tags.push(i);else if(Ys(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Tt(this,t,!1);return r.addAll(e,C.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Tt(this,t,!0);return r.addAll(e,C.none,t.from,t.to),x.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(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=mr(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=mr(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new n(e,n.schemaRules(e)))}},Pr={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},Xs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},zr={ol:!0,ul:!0},it=1,ln=2,tt=4;function pr(n,e,t){return e!=null?(e?it:0)|(e==="full"?ln:0):n&&n.whitespace=="pre"?it|ln:t&~tt}var ve=class{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=C.none,this.match=s||(o&tt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(y.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&it)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=y.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(y.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&&!Pr.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},Tt=class{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=pr(null,t.preserveWhitespace,0)|(r?tt:0);i?s=new ve(i.type,i.attrs,C.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new ve(null,null,C.none,!0,null,o):s=new ve(e.schema.topNodeType,null,C.none,!0,null,o),this.nodes=[s],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,s=i.options&ln?"full":this.localPreserveWS||(i.options&it)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.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 s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.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)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):gr(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new ve(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|=it)}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),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let f=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!f||f.name!=c&&!f.isInGroup(c))return!1;a--}}return!0};return o(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 _s(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&zr.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Zs(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function mr(n){let e={};for(let t in n)e[t]=n[t];return e}function gr(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Ct(Qt(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return Ct(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=yr(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return yr(e.marks)}};function yr(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Qt(n){return n.document||window.document}var xr=new WeakMap;function Qs(n){let e=xr.get(n);return e===void 0&&xr.set(n,e=eo(n)),e}function eo(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 o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],f=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){f=2;for(let h in c)if(c[h]!=null){let u=h.indexOf(" ");u>0?a.setAttributeNS(h.slice(0,u),h.slice(u+1),c[h]):h=="style"&&a.style?a.style.cssText=c[h]:a.setAttribute(h,c[h])}}for(let h=f;hf)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else{let{dom:d,contentDOM:p}=Ct(n,u,t,r);if(a.appendChild(d),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}var _r={};cr(_r,{AddMarkStep:()=>Je,AddNodeMarkStep:()=>qe,AttrStep:()=>lt,DocAttrStep:()=>at,MapResult:()=>Le,Mapping:()=>We,RemoveMarkStep:()=>he,RemoveNodeMarkStep:()=>Oe,ReplaceAroundStep:()=>q,ReplaceStep:()=>J,Step:()=>T,StepMap:()=>Z,StepResult:()=>A,Transform:()=>ct,TransformError:()=>Ne,canJoin:()=>At,canSplit:()=>$e,dropPoint:()=>gn,findWrapping:()=>mn,insertPoint:()=>jr,joinPoint:()=>Hr,liftTarget:()=>ft,replaceStep:()=>ht});var vr=65535,Vr=Math.pow(2,16);function to(n,e){return n+e*Vr}function Br(n){return n&vr}function no(n){return(n-(n&vr))/Vr}var Lr=1,Wr=2,Et=4,Jr=8,Le=class{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&Jr)>0}get deletedBefore(){return(this.delInfo&(Lr|Et))>0}get deletedAfter(){return(this.delInfo&(Wr|Et))>0}get deletedAcross(){return(this.delInfo&Et)>0}},Z=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=Br(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],f=this.ranges[l+o],h=a+c;if(e<=h){let u=c?e==a?-1:e==h?1:t:t,d=a+i+(u<0?0:f);if(r)return d;let p=e==(t<0?a:h)?null:to(l/3,e-a),m=e==a?Wr:e==h?Lr:Et;return(t<0?e!=a:e!=h)&&(m|=Jr),new Le(d,m,p)}i+=f-c}return r?e+i:new Le(e+i,0,null)}touches(e,t){let r=0,i=Br(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],f=a+c;if(e<=f&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=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;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return A.fromReplace(e,this.from,this.to,s)}invert(){return new he(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))}};T.jsonID("addMark",Je);var he=class n extends T{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 x(dn(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return A.fromReplace(e,this.from,this.to,r)}invert(){return new Je(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))}};T.jsonID("removeMark",he);var qe=class n extends T{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return A.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return A.fromReplace(e,this.pos,this.pos+1,new x(y.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,s,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,x.fromJSON(e,t.slice),t.insert,!!t.structure)}};T.jsonID("replaceAround",q);function hn(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function ro(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,f)=>{if(!a.isInline)return;let h=a.marks;if(!r.isInSet(h)&&f.type.allowsMarkType(r.type)){let u=Math.max(c,e),d=Math.min(c+a.nodeSize,t),p=r.addToSet(h);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function io(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof nt){let c=o.marks,f;for(;f=r.isInSet(c);)(a||(a=[])).push(f),c=f.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let f=0;fn.step(new he(o.from,o.to,o.style)))}function pn(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function so(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function ft(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,f=y.from(r.node(p).copy(f)),h++):a--;let u=y.empty,d=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].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=y.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new q(i,s,i,s,new x(r,0,0),t.length,!0))}function fo(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&ho(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let d=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);d&&!p?c=!1:!d&&p&&(c=!0)}c===!1&&$r(n,o,l,s),pn(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let f=n.mapping.slice(s),h=f.map(l,1),u=f.map(l+o.nodeSize,1);return n.step(new q(h,u,h+1,u-1,new x(y.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&qr(n,o,l,s),!1}})}function qr(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function $r(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function ho(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function uo(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new q(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new x(y.from(o),0,0),1,!0))}function $e(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,f=t-2;c>s;c--,f--){let h=i.node(c),u=i.index(c);if(h.type.spec.isolating)return!1;let d=h.content.cutByIndex(u,h.childCount),p=r&&r[f+1];p&&(d=d.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[f]||h;if(!h.canReplace(u+1,h.childCount)||!m.type.validContent(d))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function po(n,e,t=1,r){let i=n.doc.resolve(e),s=y.empty,o=y.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=y.from(i.node(l).copy(s));let f=r&&r[c];o=y.from(f?f.type.create(f.attrs,o):i.node(l).copy(o))}n.step(new J(e,e,new x(s.append(o),t,t),!0))}function At(n,e){let t=n.resolve(e),r=t.index();return Kr(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function mo(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?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&Kr(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function go(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let f=o.whitespace=="pre",h=!!o.contentMatch.matchType(i);f&&!h?r=!1:!f&&h&&(r=!0)}let l=n.steps.length;if(r===!1){let f=n.doc.resolve(e+t);$r(n,f.node(),f.before(),l)}o.inlineContent&&pn(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new J(c,a.map(e+t,-1),x.empty,!0)),r===!0){let f=n.doc.resolve(c);qr(n,f.node(),f.before(),n.steps.length)}return n}function jr(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 s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),f=!1;if(s==1)f=c.canReplace(a,a,i);else{let h=c.contentMatchAt(a).findWrapping(i.firstChild.type);f=h&&c.canReplaceWith(a,a,h[0])}if(f)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function ht(n,e,t=e,r=x.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return Ur(i,s,r)?new J(e,t,r):new un(i,s,r).fit()}function Ur(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}var un=class{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=y.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=y.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 s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new x(s,o,l);return e>-1?new q(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new J(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),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=cn(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],f,h=null;if(t==1&&(o?c.matchType(o.type)||(h=c.fillBefore(y.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:h};if(t==2&&o&&(f=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:f};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=cn(e,t);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new x(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=cn(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new x(st(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new x(st(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(h=g,f.push(Gr(m.mark(u.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?d:-1)))}let p=c==l.childCount;p||(d=-1),this.placed=ot(this.placed,t,y.from(f)),this.frontier[t].match=h,p&&d<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],s=t=0;l--){let{match:a,type:c}=this.frontier[l],f=fn(e,l,c,a,!0);if(!f||f.childCount)continue e}return{depth:t,fit:o,move:s?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=ot(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=ot(this.placed,this.depth,y.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(y.empty,!0);t.childCount&&(this.placed=ot(this.placed,this.frontier.length,t))}};function st(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(st(n.firstChild.content,e-1,t)))}function ot(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(ot(n.lastChild.content,e-1,t)))}function cn(n,e){for(let t=0;t1&&(r=r.replaceChild(0,Gr(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(y.empty,!0)))),n.copy(r)}function fn(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!yo(t,s.content,o)?l:null}function yo(n,e,t){for(let r=t;r0;u--,d--){let p=i.node(u).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(u)>-1?l=u:i.before(u)==d&&o.splice(1,0,-u)}let a=o.indexOf(l),c=[],f=r.openStart;for(let u=r.content,d=0;;d++){let p=u.firstChild;if(c.push(p),d==r.openStart)break;u=p.content}for(let u=f-1;u>=0;u--){let d=c[u],p=xo(d.type);if(p&&!d.sameMarkup(i.node(Math.abs(l)-1)))f=u;else if(p||!d.type.isTextblock)break}for(let u=r.openStart;u>=0;u--){let d=(u+f+1)%(r.openStart+1),p=c[d];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>h));u--){let d=o[u];d<0||(e=i.before(d),t=s.after(d))}}function Yr(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(y.empty,!0))}return n}function So(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=jr(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new x(y.from(r),0,0))}function ko(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t),s=Xr(r,i);for(let o=0;o0&&(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 o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Xr(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}var lt=class n extends T{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 A.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return A.fromReplace(e,this.pos,this.pos+1,new x(y.from(i),0,t.isLeaf?0:1))}getMap(){return Z.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)}};T.jsonID("attr",lt);var at=class n extends T{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 A.ok(r)}getMap(){return Z.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)}};T.jsonID("docAttr",at);var Ne=class extends Error{};Ne=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Ne.prototype=Object.create(Error.prototype);Ne.prototype.constructor=Ne;Ne.prototype.name="TransformError";var ct=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new We}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new Ne(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}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=x.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 x(y.from(r),0,0))}delete(e,t){return this.replace(e,t,x.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return bo(this,e,t,r),this}replaceRangeWith(e,t,r){return So(this,e,t,r),this}deleteRange(e,t){return ko(this,e,t),this}lift(e,t){return oo(this,e,t),this}join(e,t=1){return go(this,e,t),this}wrap(e,t){return co(this,e,t),this}setBlockType(e,t=e,r,i=null){return fo(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return uo(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new lt(e,t,r)),this}setDocAttribute(e,t){return this.step(new at(e,t)),this}addNodeMark(e,t){return this.step(new qe(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 C)t.isInSet(r.marks)&&this.step(new Oe(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new Oe(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return po(this,e,t,r),this}addMark(e,t,r){return ro(this,e,t,r),this}removeMark(e,t,r){return io(this,e,t,r),this}clearIncompatible(e,t,r){return pn(this,e,t,r),this}};var yn=Object.create(null),M=class{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new He(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;s--){let o=t<0?Ke(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):Ke(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new K(e.node(0))}static atStart(e){return Ke(e,e,0,0,1)||new K(e)}static atEnd(e){return Ke(e,e,e.content.size,e.childCount,-1)||new K(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=yn[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 yn)throw new RangeError("Duplicate use of selection JSON ID "+e);return yn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return O.between(this.$anchor,this.$head).getBookmark()}};M.prototype.visible=!0;var He=class{constructor(e,t){this.$from=e,this.$to=t}},Zr=!1;function Qr(n){!Zr&&!n.parent.inlineContent&&(Zr=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}var O=class n extends M{constructor(e,t=e){Qr(e),Qr(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 M.near(r);let i=e.resolve(t.map(this.anchor));return new n(i.parent.inlineContent?i:r,r)}replace(e,t=x.empty){if(super.replace(e,t),t==x.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 Rt(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 s=M.findFrom(t,r,!0)||M.findFrom(t,-r,!0);if(s)t=s.$head;else return M.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(M.findFrom(e,-r,!0)||M.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&S.isSelectable(l))return S.create(n,t-(i<0?l.nodeSize:0))}else{let a=Ke(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function ei(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=f)}),n.setSelection(M.near(n.doc.resolve(o),t))}var ti=1,It=2,ni=4,Sn=class extends ct{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|=It,this}ensureMarks(e){return C.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&It)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~It,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)||C.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 s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(M.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|=ni,this}get scrolledIntoView(){return(this.updated&ni)>0}};function ri(n,e){return!e||!n?n:n.bind(e)}var De=class{constructor(e,t,r){this.name=e,this.init=ri(t.init,r),this.apply=ri(t.apply,r)}},Co=[new De("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new De("selection",{init(n,e){return n.selection||M.atStart(e.doc)},apply(n){return n.selection}}),new De("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new De("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})],ut=class{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Co.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 De(r.key,r.spec.state,r))})}},kn=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],s=i.spec.state;s&&s.toJSON&&(t[r]=s.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 ut(e.schema,e.plugins),s=new n(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=_.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=M.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.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==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}};function ii(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=ii(i,e,{})),t[r]=i}return t}var re=class{constructor(e){this.spec=e,this.props={},e.props&&ii(e.props,this,this.props),this.key=e.key?e.key.key:si("plugin")}getState(e){return e[this.key]}},xn=Object.create(null);function si(n){return n in xn?n+"$"+ ++xn[n]:(xn[n]=0,n+"$")}var ue=class{constructor(e="key"){this.key=si(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var I=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},Xe=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e},wn=null,se=function(n,e,t){let r=wn||(wn=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Oo=function(){wn=null},Pe=function(n,e,t,r){return t&&(oi(n,e,t,r,-1)||oi(n,e,t,r,1))},No=/^(img|br|input|textarea|hr)$/i;function oi(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:j(n))){let o=n.parentNode;if(!o||o.nodeType!=1||bt(n)||No.test(n.nodeName)||n.contentEditable=="false")return!1;e=I(n)+(i<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?j(n):0}else return!1}}function j(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Do(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=j(n)}else if(n.parentNode&&!bt(n))e=I(n),n=n.parentNode;else return null}}function wo(n,e){for(;;){if(n.nodeType==3&&e2),H=_e||(Q?/Mac/.test(Q.platform):!1),Io=Q?/Win/.test(Q.platform):!1,oe=/Android \d/.test(xe),St=!!li&&"webkitFontSmoothing"in li.documentElement.style,Ro=St?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Po(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 ie(n,e){return typeof n=="number"?n:n[e]}function zo(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 ai(n,e,t){let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=Xe(o);continue}let l=o,a=l==s.body,c=a?Po(s):zo(l),f=0,h=0;if(e.topc.bottom-ie(r,"bottom")&&(h=e.bottom-e.top>c.bottom-c.top?e.top+ie(i,"top")-c.top:e.bottom-c.bottom+ie(i,"bottom")),e.leftc.right-ie(r,"right")&&(f=e.right-c.right+ie(i,"right")),f||h)if(a)s.defaultView.scrollBy(f,h);else{let d=l.scrollLeft,p=l.scrollTop;h&&(l.scrollTop+=h),f&&(l.scrollLeft+=f);let m=l.scrollLeft-d,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let u=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(u))break;o=u=="absolute"?o.offsetParent:Xe(o)}}function Bo(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:Ji(n.dom)}}function Ji(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=Xe(r));return e}function Fo({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;qi(t,r==0?0:r-e)}function qi(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=f,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=h+1)}}return!t&&a&&(t=a,i=c,r=0),t&&t.nodeType==3?Vo(t,i):!t||r&&t.nodeType==1?{node:n,offset:s}:$i(t,i)}function Vo(n,e){let t=n.nodeValue.length,r=document.createRange();for(let i=0;i=(s.left+s.right)/2?1:0)}}return{node:n,offset:0}}function Hn(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Lo(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Jo(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!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)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function Ki(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;St&&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=Jo(n,r,i,e))}l==null&&(l=Wo(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function ci(n){return n.top=0&&i==r.nodeValue.length?(a--,f=1):t<0?a--:c++,dt(de(se(r,a,c),f),f<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==j(r))){let a=r.childNodes[i-1];if(a.nodeType==1)return Mn(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==j(r))){let a=r.childNodes[i-1],c=a.nodeType==3?se(a,j(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return dt(de(c,1),!1)}if(s==null&&i=0)}function dt(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 Mn(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 ji(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 Ko(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return ji(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=Hi(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=se(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cf.top+1&&(t=="up"?o.top-f.top>(f.bottom-o.top)*2:f.bottom-o.bottom>(o.bottom-f.top)*2))return!1}}return!0})}var Ho=/[\u0590-\u08ac]/;function jo(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ho.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:ji(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:f,anchorOffset:h}=n.domSelectionRange(),u=l.caretBidiLevel;l.modify("move",t,"character");let d=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!d.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(f,h),a&&(a!=f||c!=h)&&l.extend&&l.extend(a,c)}catch{}return u!=null&&(l.caretBidiLevel=u),g}):r.pos==r.start()||r.pos==r.end()}var fi=null,hi=null,ui=!1;function Uo(n,e,t){return fi==e&&hi==t?ui:(fi=e,hi=t,ui=t=="up"||t=="down"?Ko(n,e,t):jo(n,e,t))}var G=0,di=1,Te=2,ee=3,ze=class{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=G,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;tI(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 s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.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 s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}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 s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof Bt){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof Pt&&s.side>=0;r--);if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?I(s.dom)+1:0}}else{let s,o=!0;for(;s=r=f&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,f);e=o;for(let h=l;h>0;h--){let u=this.children[h-1];if(u.size&&u.dom.parentNode==this.contentDOM&&!u.emptyChildAt(1)){i=I(u.dom)+1;break}e-=u.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let f=l+1;fp&&ot){let p=l;l=a,a=p}let d=document.createRange();d.setEnd(a.node,a.offset),d.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(d)}}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+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Te:di,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=ee:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Te:ee}r=o}this.dirty=Te}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Te:di;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==G&&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}},In=class extends ze{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}},Ze=class n extends ze{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=fe.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new n(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&ee||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ee&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=G){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Bn(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),f=c&&c.dom,h=c&&c.contentDOM;if(t.isText){if(!f)f=document.createTextNode(t.text);else if(f.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else f||({dom:f,contentDOM:h}=fe.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!h&&!t.isText&&f.nodeName!="BR"&&(f.hasAttribute("contenteditable")||(f.contentEditable="false"),t.type.spec.draggable&&(f.draggable=!0));let u=f;return f=Yi(f,r,t),c?a=new Rn(e,t,r,i,f,h||null,u,c,s,o+1):t.isText?new zt(e,t,r,i,f,u,s):new n(e,t,r,i,f,h||null,u,s,o+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=()=>y.empty)}return e}matchesNode(e,t,r){return this.dirty==G&&e.eq(this.node)&&Ft(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,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new zn(this,o&&o.node,e);_o(this.node,this.innerDeco,(c,f,h)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e):c.type.side>=0&&!h&&a.syncToMarks(f==this.node.childCount?C.none:this.node.child(f).marks,r,e),a.placeWidget(c,e,i)},(c,f,h,u)=>{a.syncToMarks(c.marks,r,e);let d;a.findNodeMatch(c,f,h,u)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(c,f,h,d,e)||a.updateNextNode(c,f,h,e,u,i)||a.addNode(c,f,h,e,i),i+=c.nodeSize}),a.syncToMarks([],r,e),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Te)&&(o&&this.protectLocalComposition(e,o),Ui(this.contentDOM,this.children,e),_e&&Zo(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof O)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=Qo(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new In(this,s,t,i);e.input.compositionNodes.push(o),this.children=Bn(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==ee||!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=G}updateOuterDeco(e){if(Ft(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Gi(this.dom,this.nodeDOM,Pn(this.outerDeco,this.node,t),Pn(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 pi(n,e,t,r,i){Yi(r,e,n);let s=new ye(void 0,n,e,t,r,r,r,i,0);return s.contentDOM&&s.updateChildren(i,0),s}var zt=class n extends ye{constructor(e,t,r,i,s,o,l){super(e,t,r,i,s,null,o,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==ee||this.dirty!=G&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=G||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=G,!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),s=document.createTextNode(i.text);return new n(this.parent,i,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=ee)}get domAtom(){return!1}isText(e){return this.node.text==e}},Bt=class extends ze{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==G&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}},Rn=class extends ye{constructor(e,t,r,i,s,o,l,a,c,f){super(e,t,r,i,s,o,l,c,f),this.spec=a}update(e,t,r,i){if(this.dirty==ee)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}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 Ui(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,o=Math.min(s,e.length);for(;i-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let a=Ze.create(this.top,e[s],t,r);this.top.children.splice(this.index,0,a),this.top=a,this.changed=!0}this.index=0,s++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,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 Ze)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,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Xo(n,e){return n.type.side-e.type.side}function _o(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+u.nodeSize;if(u.isText){let g=p;o!g.inline):l.slice();r(u,m,e.forChild(s,u),d),s=p}}function Zo(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 Qo(n,e,t,r){for(let i=0,s=0;i=t){if(s>=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 Bn(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||f<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function jn(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Kt(t)){for(a=o;i&&!i.node;)i=i.parent;let h=i.node;if(i&&h.isAtom&&S.isSelectable(h)&&i.parent&&!(h.isInline&&To(t.focusNode,t.focusOffset,i.dom))){let u=i.posBefore;c=new S(o==u?l:r.resolve(u))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let h=o,u=o;for(let d=0;d{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Xi(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function tl(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,I(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&$&&ge<=11&&(t.disabled=!0,t.disabled=!1)}function _i(n,e){if(e instanceof S){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(bi(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else bi(n)}function bi(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function Un(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||O.between(e,t,r)}function Si(n){return n.editable&&!n.hasFocus()?!1:Zi(n)}function Zi(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 nl(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return Pe(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Fn(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&M.findFrom(s,e)}function pe(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function ki(n,e,t){let r=n.state.selection;if(r instanceof O)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return pe(n,new O(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Fn(n.state,e);return i&&i instanceof S?pe(n,i):!1}else if(!(H&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?S.isSelectable(s)?pe(n,new S(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):St?pe(n,new O(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof S&&r.node.isInline)return pe(n,new O(e>0?r.$to:r.$from));{let i=Fn(n.state,e);return i?pe(n,i):!1}}}function vt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function mt(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function Ue(n,e){return e<0?rl(n):il(n)}function rl(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(U&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(mt(l,-1))i=t,s=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(Qi(t))break;{let l=t.previousSibling;for(;l&&mt(l,-1);)i=t.parentNode,s=I(l),l=l.previousSibling;if(l)t=l,r=vt(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?vn(n,t,r):i&&vn(n,i,s)}function il(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=vt(t),s,o;for(;;)if(r{n.state==i&&le(n)},50)}function Mi(n,e){let t=n.state.doc.resolve(e);if(!(B||Io)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Ci(n,e,t){let r=n.state.selection;if(r instanceof O&&!r.empty||t.indexOf("s")>-1||H&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Fn(n.state,e);if(o&&o instanceof S)return pe(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof K?M.near(o,e):M.findFrom(o,e);return l?pe(n,l):!1}return!1}function Oi(n,e){if(!(n.state.selection instanceof O))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 s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Ni(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function ll(n){if(!v||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;Ni(n,r,"true"),setTimeout(()=>Ni(n,r,"false"),20)}return!1}function al(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function cl(n,e){let t=e.keyCode,r=al(e);if(t==8||H&&t==72&&r=="c")return Oi(n,-1)||Ue(n,-1);if(t==46&&!e.shiftKey||H&&t==68&&r=="c")return Oi(n,1)||Ue(n,1);if(t==13||t==27)return!0;if(t==37||H&&t==66&&r=="c"){let i=t==37?Mi(n,n.state.selection.from)=="ltr"?-1:1:-1;return ki(n,i,r)||Ue(n,i)}else if(t==39||H&&t==70&&r=="c"){let i=t==39?Mi(n,n.state.selection.from)=="ltr"?1:-1:1;return ki(n,i,r)||Ue(n,i)}else{if(t==38||H&&t==80&&r=="c")return Ci(n,-1,r)||Ue(n,-1);if(t==40||H&&t==78&&r=="c")return ll(n)||Ci(n,1,r)||Ue(n,1);if(r==(H?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function Gn(n,e){n.someProp("transformCopied",d=>{e=d(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let d=r.firstChild;t.push(d.type.name,d.attrs!=d.type.defaultAttrs?d.attrs:null),r=d.content}let o=n.someProp("clipboardSerializer")||fe.fromSchema(n.state.schema),l=ss(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,f,h=0;for(;c&&c.nodeType==1&&(f=is[c.nodeName.toLowerCase()]);){for(let d=f.length-1;d>=0;d--){let p=l.createElement(f[d]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),h++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${s}${h?` -${h}`:""} ${JSON.stringify(t)}`);let u=n.someProp("clipboardTextSerializer",d=>d(e,n))||e.content.textBetween(0,e.content.size,` + +`);return{dom:a,text:u,slice:e}}function es(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",u=>{e=u(e,s||r,n)}),s)return l=new x(y.from(n.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),n.someProp("transformPasted",u=>{l=u(l,n,!0)}),l;let h=n.someProp("clipboardTextParser",u=>u(e,i,r,n));if(h)l=h;else{let u=i.marks(),{schema:d}=n.state,p=fe.fromSchema(d);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(d.text(m,u)))})}}else n.someProp("transformPastedHTML",h=>{t=h(t,n)}),o=dl(t),St&&pl(o);let c=o&&o.querySelector("[data-pm-slice]"),f=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(f&&f[3])for(let h=+f[3];h>0;h--){let u=o.firstChild;for(;u&&u.nodeType!=1;)u=u.nextSibling;if(!u)break;o=u}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||Ve.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||f),context:i,ruleFromNode(u){return u.nodeName=="BR"&&!u.nextSibling&&u.parentNode&&!fl.test(u.parentNode.nodeName)?{ignore:!0}:null}})),f)l=ml(Di(l,+f[1],+f[2]),f[4]);else if(l=x.maxOpen(hl(l.content,i),!0),l.openStart||l.openEnd){let h=0,u=0;for(let d=l.content.firstChild;h{l=h(l,n,a)}),l}var fl=/^(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 hl(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)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&ns(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=rs(o[o.length-1],s.length));let f=ts(l,a);o.push(f),i=i.matchType(f.type),s=a}}),o)return y.from(o)}return n}function ts(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,y.from(n));return n}function ns(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(y.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Di(n,e,t){return et})),On.createHTML(n)):n}function dl(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=ss().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(n),i;if((i=r&&is[r[1].toLowerCase()])&&(n=i.map(s=>"<"+s+">").join("")+n+i.map(s=>"").reverse().join("")),t.innerHTML=ul(n),i)for(let s=0;s=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;i=y.from(a.create(r[l+1],i)),s++,o++}return new x(i,s,o)}var V={},L={},gl={touchstart:!0,touchmove:!0},Ln=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.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function yl(n){for(let e in V){let t=V[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{bl(n,r)&&!Yn(n,r)&&(n.editable||!(r.type in L))&&t(n,r)},gl[e]?{passive:!0}:void 0)}v&&n.dom.addEventListener("input",()=>null),Wn(n)}function me(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function xl(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 Wn(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>Yn(n,r))})}function Yn(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function bl(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 Sl(n,e){!Yn(n,e)&&V[e.type]&&(n.editable||!(e.type in L))&&V[e.type](n,e)}L.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!as(n,t)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(oe&&B&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),_e&&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,we(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||cl(n,t)?t.preventDefault():me(n,"key")};L.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)};L.keypress=(n,e)=>{let t=e;if(as(n,t)||!t.charCode||t.ctrlKey&&!t.altKey||H&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof O)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function Ht(n){return{left:n.clientX,top:n.clientY}}function kl(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function Xn(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function Ye(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 Ml(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&S.isSelectable(r)?(Ye(n,new S(t),"pointer"),!0):!1}function Cl(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof S&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(S.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(Ye(n,S.create(n.state.doc,i),"pointer"),!0):!1}function Ol(n,e,t,r,i){return Xn(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Cl(n,t):Ml(n,t))}function Nl(n,e,t,r){return Xn(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function Dl(n,e,t,r){return Xn(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||wl(n,t,r)}function wl(n,e,t){if(t.button!=0)return!1;let r=n.state.doc;if(e==-1)return r.inlineContent?(Ye(n,O.create(r,0,r.content.size),"pointer"),!0):!1;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)Ye(n,O.create(r,l+1,l+1+o.content.size),"pointer");else if(S.isSelectable(o))Ye(n,S.create(r,l),"pointer");else continue;return!0}}function _n(n){return Vt(n)}var ls=H?"metaKey":"ctrlKey";V.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=_n(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&kl(t,n.input.lastClick)&&!t[ls]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button};let o=n.posAtCoords(Ht(t));o&&(s=="singleClick"?(n.input.mouseDown&&n.input.mouseDown.done(),n.input.mouseDown=new Jn(n,o,t,!!r)):(s=="doubleClick"?Nl:Dl)(n,o.pos,o.inside,t)?t.preventDefault():me(n,"pointer"))};var Jn=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[ls],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let f=e.state.doc.resolve(t.pos);s=f.parent,o=f.depth?f.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&&s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof S&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&U&&!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)),me(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(()=>le(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(Ht(e))),this.updateAllowDefault(e),this.allowDefault||!t?me(this.view,"pointer"):Ol(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||v&&this.mightDrag&&!this.mightDrag.node.isAtom||B&&!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)?(Ye(this.view,M.near(this.view.state.doc.resolve(t.pos)),"pointer"),e.preventDefault()):me(this.view,"pointer")}move(e){this.updateAllowDefault(e),me(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)}};V.touchstart=n=>{n.input.lastTouch=Date.now(),_n(n),me(n,"pointer")};V.touchmove=n=>{n.input.lastTouch=Date.now(),me(n,"pointer")};V.contextmenu=n=>_n(n);function as(n,e){return n.composing?!0:v&&Math.abs(e.timeStamp-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}var Tl=oe?5e3:-1;L.compositionstart=L.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof O&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)))n.markCursor=n.state.storedMarks||t.marks(),Vt(n,!0),n.markCursor=null;else if(Vt(n,!e.selection.empty),U&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}cs(n,Tl)};L.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.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,cs(n,20))};function cs(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>Vt(n),e))}function fs(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Al());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function El(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Do(e.focusNode,e.focusOffset),r=wo(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function Al(){let n=document.createEvent("Event");return n.initEvent("event",!0,!0),n.timeStamp}function Vt(n,e=!1){if(!(oe&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),fs(n),e||n.docView&&n.docView.dirty){let t=jn(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 Il(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 gt=$&&ge<15||_e&&Ro<604;V.copy=L.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=gt?null:t.clipboardData,o=r.content(),{dom:l,text:a}=Gn(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Il(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Rl(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Pl(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?yt(n,r.value,null,i,e):yt(n,r.textContent,r.innerHTML,i,e)},50)}function yt(n,e,t,r,i){let s=es(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||x.empty)))return!0;if(!s)return!1;let o=Rl(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function hs(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," "):""}L.paste=(n,e)=>{let t=e;if(n.composing&&!oe)return;let r=gt?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&yt(n,hs(r),r.getData("text/html"),i,t)?t.preventDefault():Pl(n,t)};var Lt=class{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}},zl=H?"altKey":"ctrlKey";function us(n,e){let t=n.someProp("dragCopies",r=>!r(e));return t??!e[zl]}V.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(Ht(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof S?i.to-1:i.to))){if(r&&r.mightDrag)o=S.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let h=n.docView.nearestDesc(t.target,!0);h&&h.node.type.spec.draggable&&h!=n.docView&&(o=S.create(n.state.doc,h.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:f}=Gn(n,l);(!t.dataTransfer.files.length||!B||Wi>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(gt?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",gt||t.dataTransfer.setData("text/plain",c),n.dragging=new Lt(f,us(n,t),o)};V.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)};L.dragover=L.dragenter=(n,e)=>e.preventDefault();L.drop=(n,e)=>{let t=e,r=n.dragging;if(n.dragging=null,!t.dataTransfer)return;let i=n.posAtCoords(Ht(t));if(!i)return;let s=n.state.doc.resolve(i.pos),o=r&&r.slice;o?n.someProp("transformPasted",p=>{o=p(o,n,!1)}):o=es(n,hs(t.dataTransfer),gt?null:t.dataTransfer.getData("text/html"),!1,s);let l=!!(r&&us(n,t));if(n.someProp("handleDrop",p=>p(n,t,o||x.empty,l))){t.preventDefault();return}if(!o)return;t.preventDefault();let a=o?gn(n.state.doc,s.pos,o):s.pos;a==null&&(a=s.pos);let c=n.state.tr;if(l){let{node:p}=r;p?p.replace(c):c.deleteSelection()}let f=c.mapping.map(a),h=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,u=c.doc;if(h?c.replaceRangeWith(f,f,o.content.firstChild):c.replaceRange(f,f,o),c.doc.eq(u))return;let d=c.doc.resolve(f);if(h&&S.isSelectable(o.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(o.content.firstChild))c.setSelection(new S(d));else{let p=c.mapping.map(a);c.mapping.maps[c.mapping.maps.length-1].forEach((m,g,b,D)=>p=D),c.setSelection(Un(n,d,c.doc.resolve(p)))}n.focus(),n.dispatch(c.setMeta("uiEvent","drop"))};V.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())&&le(n)},20))};V.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)};V.beforeinput=(n,e)=>{if(B&&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",s=>s(n,we(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 L)V[n]=L[n];function xt(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 Wt=class n{constructor(e,t){this.toDOM=e,this.spec=t||Ie,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new Y(s-r,s-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&&xt(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},Ae=class n{constructor(e,t){this.attrs=e,this.spec=t||Ie}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new Y(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==z||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Ie)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,f;if(f=ps(t,l,c)){for(i||(i=this.children.slice());sl&&h.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ae){let c=Math.max(s,a.from)-s,f=Math.min(o,a.to)-s;ci.map(e,t,Ie));return n.from(r)}forChild(e,t){if(t.isLeaf)return F.empty;let r=[];for(let i=0;it instanceof F)?e:e.reduce((t,r)=>t.concat(r instanceof F?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(d-u);for(let b=0;bD+f-h)continue;let N=l[b]+f-h;d>=N?l[b+1]=u<=N?-2:-1:u>=f&&g&&(l[b]+=g,l[b+1]+=g)}h+=g}),f=t.maps[c].map(f,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let u=t.map(n[c+1]+s,-1),d=u-i,{index:p,offset:m}=r.content.findIndex(h),g=r.maybeChild(p);if(g&&m==h&&m+g.nodeSize==d){let b=l[c+2].mapInner(t,g,f+1,n[c]+s+1,o);b!=z?(l[c]=h,l[c+1]=d,l[c+2]=b):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Fl(l,n,e,t,i,s,o),f=qt(c,r,0,o);e=f.local;for(let h=0;ht&&o.to{let c=ps(n,l,a+t);if(c){s=!0;let f=qt(c,l,t+a+1,r);f!=z&&i.push(a,a+l.nodeSize,f)}});let o=ds(s?ms(n):n,-t).sort(Re);for(let l=0;l0;)e++;n.splice(e,0,t)}function Nn(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=z&&e.push(r)}),n.cursorWrapper&&e.push(F.create(n.state.doc,[n.cursorWrapper.deco])),Jt.from(e)}var vl={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Vl=$&&ge<=11,$n=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}},Kn=class{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new $n,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():this.flush()}),Vl&&(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,vl)),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(Si(this.view)){if(this.suppressingSelectionUpdates)return le(this.view);if($&&ge<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Pe(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 s=e.focusNode;s;s=Xe(s))t.add(s);for(let s=e.anchorNode;s;s=Xe(s))if(t.has(s)){r=s;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)&&Si(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let f=0;fh.nodeName=="BR");if(f.length==2){let[h,u]=f;h.parentNode&&h.parentNode.parentNode==u.parentNode?u.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let u of f){let d=u.parentNode;d&&d.nodeName=="LI"&&(!h||Jl(e,h)!=d)&&u.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),Ll(e)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||le(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 f=0;fi;g--){let b=r.childNodes[g-1],D=b.pmViewDesc;if(b.nodeName=="BR"&&!D){s=g;break}if(!D||D.size)break}let h=n.state.doc,u=n.someProp("domParser")||Ve.fromSchema(n.state.schema),d=h.resolve(o),p=null,m=u.parse(r,{topNode:d.parent,topMatch:d.parent.contentMatchAt(d.index()),topOpen:!0,from:i,to:s,preserveWhitespace:d.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:$l,context:d});if(c&&c[0].pos!=null){let g=c[0].pos,b=c[1]&&c[1].pos;b==null&&(b=g),p={anchor:g+o,head:b+o}}return{doc:m,sel:p,from:o,to:l}}function $l(n){let e=n.pmViewDesc;if(e)return e.parseRule();if(n.nodeName=="BR"&&n.parentNode){if(v&&/^(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||v&&/^(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 Kl=/^(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 Hl(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let k=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,E=jn(n,k);if(E&&!n.state.selection.eq(E)){if(B&&oe&&n.input.lastKeyCode===13&&Date.now()-100Ps(n,we(13,"Enter"))))return;let W=n.state.tr.setSelection(E);k=="pointer"?W.setMeta("pointer",!0):k=="key"&&W.scrollIntoView(),s&&W.setMeta("composition",s),n.dispatch(W)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=ql(n,e,t),f=n.state.doc,h=f.slice(c.from,c.to),u,d;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||oe)&&i.some(k=>k.nodeType==1&&!Kl.test(k.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",k=>k(n,we(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof O&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let k=Ri(n,n.state.doc,c.sel);if(k&&!k.eq(n.state.selection)){let E=n.state.tr.setSelection(k);s&&E.setMeta("composition",s),n.dispatch(E)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),$&&ge<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)==" \xA0"&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),b=f.resolve(p.start),D=m.sameParent(g)&&m.parent.inlineContent&&b.end()>=p.endA;if((_e&&n.input.lastIOSEnter>Date.now()-225&&(!D||i.some(k=>k.nodeName=="DIV"||k.nodeName=="P"))||!D&&m.posk(n,we(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&Ul(f,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",k=>k(n,we(8,"Backspace")))){oe&&B&&n.domObserver.suppressSelectionUpdates();return}B&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),oe&&!D&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(k){return k(n,we(13,"Enter"))})},20));let N=p.start,X=p.endA,be=k=>{let E=k||n.state.tr.replace(N,X,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let W=Ri(n,E.doc,c.sel);W&&!(B&&n.composing&&W.empty&&(p.start!=p.endB||n.input.lastChromeDeletele(n),20));let k=be(n.state.tr.delete(N,X)),E=f.resolve(p.start).marksAcross(f.resolve(p.endA));E&&k.ensureMarks(E),n.dispatch(k)}else if(p.endA==p.endB&&(kt=jl(m.parent.content.cut(m.parentOffset,g.parentOffset),b.parent.content.cut(b.parentOffset,p.endA-b.start())))){let k=be(n.state.tr);kt.type=="add"?k.addMark(N,X,kt.mark):k.removeMark(N,X,kt.mark),n.dispatch(k)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let k=m.parent.textBetween(m.parentOffset,g.parentOffset),E=()=>be(n.state.tr.insertText(k,N,X));n.someProp("handleTextInput",W=>W(n,N,X,k,E))||n.dispatch(E())}else n.dispatch(be());else n.dispatch(be())}function Ri(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:Un(n,e.resolve(t.anchor),e.resolve(t.head))}function jl(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let f=0;ff.mark(l.addToSet(f.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=f=>f.mark(l.removeFromSet(f.marks));else return null;let c=[];for(let f=0;ft||Dn(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function Gl(n,e,t,r,i){let s=n.findDiffStart(e,t);if(s==null)return null;let{a:o,b:l}=n.findDiffEnd(e,t+n.size,t+e.size);if(i=="end"){let a=Math.max(0,s-Math.min(o,l));r-=o+a-s}if(o=o?s-r:0;s-=a,s&&s=l?s-r:0;s-=a,s&&s=56320&&e<=57343&&t>=55296&&t<=56319}var $t=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 Ln,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(Vi),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=Fi(this),Bi(this),this.nodeViews=vi(this),this.docView=pi(this.state.doc,zi(this),Nn(this),this.dom,this),this.domObserver=new Kn(this,(r,i,s,o)=>Hl(this,r,i,s,o)),this.domObserver.start(),yl(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&&Wn(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Vi),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,s=!1,o=!1;e.storedMarks&&this.composing&&(fs(this),o=!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 d=vi(this);Xl(d,this.nodeViews)&&(this.nodeViews=d,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&Wn(this),this.editable=Fi(this),Bi(this);let a=Nn(this),c=zi(this),f=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",h=s||!this.docView.matchesNode(e.doc,c,a);(h||!e.selection.eq(i.selection))&&(o=!0);let u=f=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Bo(this);if(o){this.domObserver.stop();let d=h&&($||B)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&Yl(i.selection,e.selection);if(h){let p=B?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=El(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=pi(e.doc,c,a,this.dom,this)),p&&!this.trackWrites&&(d=!0)}d||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&nl(this))?le(this,d):(_i(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),f=="reset"?this.dom.scrollTop=0:f=="to selection"?this.scrollToSelection():u&&Fo(u)}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&&ai(this,t.getBoundingClientRect(),e)}else ai(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&&this.state.doc.nodeAt(s))==r.node&&(i=s)}this.dragging=new Lt(e.slice,e.move,i<0?void 0:S.create(this.state.doc,i))}someProp(e,t){let r=this._props&&this._props[e],i;if(r!=null&&(i=t?t(r):r))return i;for(let o=0;ot.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return qo(this,e)}coordsAtPos(e,t=1){return Hi(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 Uo(this,t||this.state,e)}pasteHTML(e,t){return yt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return yt(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return Gn(this,e)}destroy(){this.docView&&(xl(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Nn(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Oo())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Sl(this,e)}domSelectionRange(){let e=this.domSelection();return e?v&&this.root.nodeType===11&&Eo(this.dom.ownerDocument)==this.dom&&Wl(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};$t.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function zi(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"),[Y.node(0,n.state.doc.content.size,e)]}function Bi(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:Y.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function Fi(n){return!n.someProp("editable",e=>e(n.state)===!1)}function Yl(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 vi(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 Xl(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 Vi(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 jt=200,R=function(){};R.prototype.append=function(e){return e.length?(e=R.from(e),!this.length&&e||e.length=t?R.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};R.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};R.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)};R.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i};R.from=function(e){return e instanceof R?e:e&&e.length?new gs(e):R.empty};var gs=(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,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=jt)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=jt)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})(R);R.empty=new gs([]);var _l=(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,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},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})(R),Qn=R;var Zl=500,Fe=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,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((h,u)=>{if(!h.step){i||(i=this.remapping(r,u+1),s=i.maps.length),s--,f.push(h);return}if(i){f.push(new te(h.map));let d=h.step.map(i.slice(s)),p;d&&o.maybeStep(d).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new te(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(h.step);if(h.selection)return l=i?h.selection.map(i.slice(s)):h.selection,a=new n(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;fea&&(l=Ql(l,c),o-=c),new n(l.append(s),o)}remapping(e,t){let r=new We;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new n(this.items.append(e.map(t=>new te(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(u=>{u.selection&&l--},i);let a=t;this.items.forEach(u=>{let d=s.getMirror(--a);if(d==null)return;o=Math.min(o,d);let p=s.maps[d];if(u.step){let m=e.steps[d].invert(e.docs[d]),g=u.selection&&u.selection.map(s.slice(a+1,d));g&&l++,r.push(new te(p,m,g))}else r.push(new te(p))},i);let c=[];for(let u=t;uZl&&(h=h.compress(this.items.length-r.length)),h}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=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let h=new te(c.invert(),a,f),u,d=i.length-1;(u=i.length&&i[d].merge(h))?i[d]=u:i.push(h)}}else o.map&&r--},this.items.length,0),new n(Qn.from(i.reverse()),s)}};Fe.empty=new Fe(Qn.empty,0);function Ql(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}var te=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)}}},ne=class{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}},ea=20;function ta(n,e,t,r){let i=t.getMeta(Be),s;if(i)return i.historyState;t.getMeta(ia)&&(n=new ne(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(Be))return o.getMeta(Be).redo?new ne(n.done.addTransform(t,void 0,r,Ut(e)),n.undone,ys(t.mapping.maps),n.prevTime,n.prevComposition):new ne(n.done,n.undone.addTransform(t,void 0,r,Ut(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!na(t,n.prevRanges)),c=o?er(n.prevRanges,t.mapping):ys(t.mapping.maps);return new ne(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,Ut(e)),Fe.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new ne(n.done.rebased(t,s),n.undone.rebased(t,s),er(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ne(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),er(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function na(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function ys(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function er(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=Be.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=ra(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}var bs=Gt(!1,!0),Ss=Gt(!0,!0),hc=Gt(!1,!1),uc=Gt(!0,!1);var ae={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:"'"},Xt={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},oa=typeof navigator<"u"&&/Mac/.test(navigator.platform),la=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(w=0;w<10;w++)ae[48+w]=ae[96+w]=String(w);var w;for(w=1;w<=24;w++)ae[w+111]="F"+w;var w;for(w=65;w<=90;w++)ae[w]=String.fromCharCode(w+32),Xt[w]=String.fromCharCode(w);var w;for(Yt in ae)Xt.hasOwnProperty(Yt)||(Xt[Yt]=ae[Yt]);var Yt;function ks(n){var e=oa&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||la&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Xt:ae)[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 aa=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),ca=typeof navigator<"u"&&/Win/.test(navigator.platform);function fa(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;ln.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function pa(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}var ma=(n,e,t)=>{let r=pa(n,t);if(!r)return!1;let i=Os(r);if(!i){let o=r.blockRange(),l=o&&ft(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Ds(n,i,e,-1))return!0;if(r.parent.content.size==0&&(Qe(s,"end")||S.isSelectable(s)))for(let o=r.depth;;o--){let l=ht(n.doc,r.before(o),r.after(o),x.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1};function Qe(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 ga=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Os(r)}let o=s&&s.nodeBefore;return!o||!S.isSelectable(o)?!1:(e&&e(n.tr.setSelection(S.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Os(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 ya(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=ya(n,t);if(!r)return!1;let i=Ns(r);if(!i)return!1;let s=i.nodeAfter;if(Ds(n,i,e,1))return!0;if(r.parent.content.size==0&&(Qe(s,"start")||S.isSelectable(s))){let o=ht(n.doc,r.before(),r.after(),x.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=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{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function ir(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),s=t.indexAfter(-1),o=ir(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(M.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Ma=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof K||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=ir(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!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 s=t.before();if($e(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&ft(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function Oa(n){return(e,t)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof S&&e.selection.node.isBlock)return!r.parentOffset||!$e(e.doc,r.pos)?!1:(t&&t(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],o,l,a=!1,c=!1;for(let d=r.depth;;d--)if(r.node(d).isBlock){a=r.end(d)==r.pos+(r.depth-d),c=r.start(d)==r.pos-(r.depth-d),l=ir(r.node(d-1).contentMatchAt(r.indexAfter(d-1)));let m=n&&n(i.parent,a,r);s.unshift(m||(a&&l?{type:l}:null)),o=d;break}else{if(d==1)return!1;s.unshift(null)}let f=e.tr;(e.selection instanceof O||e.selection instanceof K)&&f.deleteSelection();let h=f.mapping.map(r.pos),u=$e(f.doc,h,s.length,s);if(u||(s[0]=l?{type:l}:null,u=$e(f.doc,h,s.length,s)),!u)return!1;if(f.split(h,s.length,s),!a&&c&&r.node(o).type!=l){let d=f.mapping.map(r.before(o)),p=f.doc.resolve(d);l&&r.node(o-1).canReplaceWith(p.index(),p.index()+1,l)&&f.setNodeMarkup(f.mapping.map(r.before(o)),l)}return t&&t(f.scrollIntoView()),!0}}var Na=Oa();var Da=(n,e)=>(e&&e(n.tr.setSelection(new K(n.doc))),!0);function wa(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||At(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Ds(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&wa(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let d=e.pos+s.nodeSize,p=y.empty;for(let b=o.length-1;b>=0;b--)p=y.from(o[b].create(null,p));p=y.from(i.copy(p));let m=n.tr.step(new q(e.pos-1,d,e.pos,d,new x(p,1,0),o.length,!0)),g=m.doc.resolve(d+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&At(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:M.findFrom(e,1),h=f&&f.$from.blockRange(f.$to),u=h&&ft(h);if(u!=null&&u>=e.depth)return t&&t(n.tr.lift(h,u).scrollIntoView()),!0;if(c&&Qe(s,"start",!0)&&Qe(i,"end")){let d=i,p=[];for(;p.push(d),!d.isTextblock;)d=d.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(d.canReplace(d.childCount,d.childCount,m.content)){if(t){let b=y.empty;for(let N=p.length-1;N>=0;N--)b=y.from(p[N].copy(b));let D=n.tr.step(new q(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new x(b,p.length,0),0,!0));t(D.scrollIntoView())}return!0}}return!1}function ws(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(O.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}var Ta=ws(-1),Ea=ws(1);function Aa(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&mn(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Ia(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),h=f.index();i=f.parent.canReplaceWith(h,h+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o{if(l||!r&&a.isAtom&&a.isInline&&c>=s.pos&&c+a.nodeSize<=o.pos)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Pa(n){let e=[];for(let t=0;t{if(s.isAtom&&s.content.size&&s.isInline&&o>=r.pos&&o+s.nodeSize<=i.pos)return o+1>r.pos&&e.push(new He(r,r.doc.resolve(o+1))),r=r.doc.resolve(o+1+s.content.size),!1}),r.poso.doc.rangeHasMark(d.$from.pos,d.$to.pos,n)):h=!f.every(d=>{let p=!1;return u.doc.nodesBetween(d.$from.pos,d.$to.pos,(m,g,b)=>{if(p)return!1;p=!n.isInSet(m.marks)&&!!b&&b.type.allowsMarkType(n)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,d.$from.pos-g),Math.min(m.nodeSize,d.$to.pos-g))))}),!p});for(let d=0;dn.type.name=="em"}],toDOM(){return $a}},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name=="strong"},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}],toDOM(){return Ka}},code:{code:!0,parseDOM:[{tag:"code"}],toDOM(){return Ha}}},Ua=new rt({nodes:qa,marks:ja});var Rs={};cr(Rs,{addMentionNodes:()=>Is,addTagNodes:()=>As,mentionNodeSpec:()=>ar,suggestionsPlugin:()=>Es,tagNodeSpec:()=>lr,triggerCharacter:()=>or});function or(n,e=!1){return t=>{let r=new RegExp(`\\s${n}$`),i=e?new RegExp(`${n}.*?(?=\\s${n}|$)`,"g"):new RegExp(`(?:^)?${n}[^\\s${n}]*`,"g"),s=t.before(),o=t.end(),l=t.doc.textBetween(s,o,"\0","\0"),a;for(;a=i.exec(l);){let c=a.input.slice(Math.max(0,a.index-1),a.index);if(!/^[\s\0]?$/.test(c))continue;let f=a.index+t.start(),h=f+a[0].length;if(e&&r.test(l.slice(h-1,h+1))&&(a[0]+=" ",h++),f=t.pos)return{range:{from:f,to:h},text:a[0]}}}}function Es({matcher:n=or("#"),suggestionClass:e="ProseMirror-suggestion",onEnter:t=()=>!1,onChange:r=()=>!1,onExit:i=()=>!1,onKeyDown:s=()=>!1,escapeOnSelectionChange:o=!0,escapeKeys:l=["Escape","ArrowRight","ArrowLeft"],debug:a=!1}){return new re({key:new ue("suggestions"),view(){return{update:(c,f)=>{let h=this.key.getState(f),u=this.key.getState(c.state),d=h.active&&u.active&&h.range.from!==u.range.from,p=!h.active&&u.active,m=h.active&&!u.active,g=!p&&!m&&h.text!==u.text;(m||d)&&i({view:c,range:h.range,text:h.text}),g&&!d&&r({view:c,range:u.range,text:u.text}),(p||d)&&t({view:c,range:u.range,text:u.text})}}},state:{init(){return{active:!1,range:{},text:null}},apply(c,f){let h=c.getMeta(this.key);if(h)return h;let{selection:u}=c,d={...f};if(o&&!c.docChanged&&c.selectionSet)d.active=!1;else if(u.from===u.to){(u.fromf.range.to)&&(d.active=!1);let p=u.$from,m=n(p);m?(d.active=!0,d.range=m.range,d.text=m.text):d.active=!1}else d.active=!1;return d.active||(d.range={},d.text=null),d}},props:{handleKeyDown(c,f){let{active:h}=this.getState(c.state);if(!h)return!1;if(l.includes(f.key)){let u=c.state.tr.setMeta(this.key,{active:!1,range:{},text:null});return c.dispatch(u),!1}return s({view:c,event:f})},decorations(c){let{active:f,range:h}=this.getState(c);return f?F.create(c.doc,[Y.inline(h.from,h.to,{nodeName:"span",class:e,style:a?"background: rgba(0, 0, 255, 0.05); color: blue; border: 2px solid blue;":null})]):null}}})}var lr={attrs:{id:{}},group:"inline",inline:!0,selectable:!1,atom:!0,toDOM:n=>["span",{class:"tag","data-tag-id":n.attrs.id},n.attrs.id],parseDOM:[{tag:"span[data-tag-id]",getAttrs:n=>({id:n.getAttribute("data-tag-id")})}]};function As(n){return n.append({tag:lr})}var ar={attrs:{type:{},id:{},label:{}},group:"inline",inline:!0,selectable:!1,atom:!0,toDOM:n=>["span",{class:"mention","data-mention-type":n.attrs.type,"data-mention-id":n.attrs.id},`@${n.attrs.label}`],parseDOM:[{tag:"span[data-mention-type][data-mention-id]",getAttrs:n=>{let e=n.getAttribute("data-mention-type"),t=n.getAttribute("data-mention-id"),r=n.innerText;return{type:e,id:t,label:r}}}]};function Is(n){return n.append({mention:ar})}export{Ve as DOMParser,fe as DOMSerializer,Y as Decoration,F as DecorationSet,kn as EditorState,$t as EditorView,re as Plugin,ue as PluginKey,rt as Schema,O as TextSelection,Is as addMentionNodes,As as addTagNodes,Fa as baseKeymap,Ua as basicSchema,sa as history,ua as keymap,ar as mentionNodeSpec,Ss as redo,Ia as setBlockType,Rs as suggestions,Es as suggestionsPlugin,lr as tagNodeSpec,za as toggleMark,_r as transform,or as triggerCharacter,bs as undo,Aa as wrapIn}; +//# sourceMappingURL=prosemirror.bundle.js.map