diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs index 1ed4f3db32..9e09f474e8 100644 --- a/apps/desktop/electron/main/plugin-host-process.mjs +++ b/apps/desktop/electron/main/plugin-host-process.mjs @@ -240,6 +240,7 @@ function buildApi() { ui: { openPanel: (options) => call("ui.openPanel", [options]), closePanel: () => call("ui.closePanel"), + openWorkPanelFile: (input) => call("ui.openWorkPanelFile", [input ?? {}]), showToast: (message, level) => call("ui.showToast", [message, level]), notify: (input) => call("ui.notify", [input]), getNotificationPermission: () => call("ui.getNotificationPermission"), diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts index a84f30d7ef..533c7fe09f 100644 --- a/apps/desktop/electron/main/plugin-runtime.ts +++ b/apps/desktop/electron/main/plugin-runtime.ts @@ -319,6 +319,8 @@ export type PluginHostServices = { readClipboardHistory: () => Promise; openPanel: (request: PluginPanelRequest) => Promise; closePanel: (pluginId: string) => Promise; + /** Ask the renderer to open a file through the normal work-panel router. */ + openWorkPanelFile?: (input: { path: string; mimeType?: string }) => void | Promise; fetch?: (input: { url: string; method?: string; @@ -457,6 +459,7 @@ const HOST_API_ALLOWLIST = new Set([ "plugin.getDataPath", "ui.openPanel", "ui.closePanel", + "ui.openWorkPanelFile", "ui.showToast", "ui.notify", "ui.getNotificationPermission", @@ -4750,6 +4753,29 @@ export class PluginRuntime { closePanel: async () => { await this.services.closePanel(pluginId); }, + openWorkPanelFile: async (input: { path: string; mimeType?: string }) => { + this.assertPermission(loaded, "ui.view"); + const path = typeof input?.path === "string" ? input.path.trim() : ""; + if (!path || path.length > 4096) { + throw apiError("INVALID_ARGUMENT", "file path must be a non-empty string"); + } + const service = this.services.openWorkPanelFile; + if (!service) { + throw apiError("UNSUPPORTED", "host api not available: ui.openWorkPanelFile"); + } + await service({ + path, + ...(typeof input?.mimeType === "string" && input.mimeType + ? { mimeType: input.mimeType } + : {}), + }); + this.services.audit?.({ + pluginId, + api: "ui.openWorkPanelFile", + ok: true, + ts: Date.now(), + }); + }, showToast: async (message: string, level?: "info" | "warn" | "error") => { this.services.showToast(message, level); }, diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts index cfada9d69e..288dbeaaa2 100644 --- a/apps/desktop/electron/main/services/plugin-services.ts +++ b/apps/desktop/electron/main/services/plugin-services.ts @@ -236,6 +236,12 @@ export function createPluginServices({ readClipboardHistory: async () => clipboardHistory.getHistory(), getLocale: () => getUpdaterLocale(), getAppearance: () => getAppearance(), + openWorkPanelFile: ({ path, mimeType }) => { + sendToRenderer(IPC.event.pluginOpenWorkPanelFile, { + path, + ...(mimeType ? { mimeType } : {}), + }); + }, openPanel: async (request) => { await pluginPanels.open({ ...request, diff --git a/apps/desktop/resources/plugins/pi.file-manager/UPSTREAM.md b/apps/desktop/resources/plugins/pi.file-manager/UPSTREAM.md index 5031896492..93dc8f5c4e 100644 --- a/apps/desktop/resources/plugins/pi.file-manager/UPSTREAM.md +++ b/apps/desktop/resources/plugins/pi.file-manager/UPSTREAM.md @@ -34,7 +34,7 @@ stores LF, and this repository's `.gitattributes` keeps it that way. | File | Bytes | sha256 | | --- | --- | --- | -| `main.js` | 63234 | `43cface10124728f16e72530e699678177f97353b57190532e89c03186e6960d` | +| `main.js` | 63507 | `195156e89d197a563e0a5fad1dbe0c8e4f866ae309ec05b049541d3e1a412d5f` | | `README.md` | 20039 | `8c524f6d13eac557e286fa0ec9b9cf5138bed0bd66d4a7914f3484443e627a01` | | `views/index.html` | 345 | `771fd3d8afdea7fca75ed1f1918c1ce93ad1c87babdb321cfb85e910465cd2c1` | | `views/assets/index.js` | 1345417 | `d0a1dc369764bed2ab12ce0e65fe983fe0b4f9919f2f8ff4546b736208d66dac` | @@ -45,7 +45,7 @@ directory carries the built view the plugin publishes, not its React source. ## Local changes -Two, so a re-sync stays a copy: +Three, so a re-sync stays a copy: - `manifest.json` gains `"license": "MIT"` (after `author`), making the vendored copy 14191 bytes @@ -62,6 +62,9 @@ Two, so a re-sync stays a copy: ancestor's `"module"`, which is why the marker cannot live one directory up. In a packaged app the file is inert, and deleting it only costs the developer experience, never a user. +- `main.js` routes `.docx` reads through the host's `ui.openWorkPanelFile` + bridge so the bundled Office view can own DOCX editing. Other extensions keep + the upstream file-manager behavior. ## Re-syncing a newer release diff --git a/apps/desktop/resources/plugins/pi.file-manager/main.js b/apps/desktop/resources/plugins/pi.file-manager/main.js index b2e00bbffe..d910c44af4 100644 --- a/apps/desktop/resources/plugins/pi.file-manager/main.js +++ b/apps/desktop/resources/plugins/pi.file-manager/main.js @@ -775,6 +775,15 @@ async function handleRead(payload) { const base = { path: rel, size: stat.size, mtimeMs: stat.mtimeMs }; const extension = path.extname(rel).toLowerCase(); + if (extension === ".docx" && typeof pi.ui.openWorkPanelFile === "function") { + await pi.ui + .openWorkPanelFile({ + path: abs, + mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }) + .catch(() => {}); + } + // 数据库:只读 100 字节的头部就能认出它,所以这一支**不做体积限制**—— // 几百 MB 的 .db 也会在这里秒开(真正的取数走 fm.sqlite.*,一次只拿一页)。 // 扩展名像但魔数不对的(比如 Windows 的 thumbs.db 其实是 OLE 文件)继续按普通文件走。 diff --git a/apps/desktop/resources/plugins/pi.office/FONTS-README.md b/apps/desktop/resources/plugins/pi.office/FONTS-README.md new file mode 100644 index 0000000000..ee9aa34d7b --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/FONTS-README.md @@ -0,0 +1,201 @@ +# Metric-compatible fallback fonts + +Source: fonts bundled with LibreOffice (`/Applications/LibreOffice.app/Contents/Resources/fonts/truetype`), +freely redistributable with the app. Licenses: Carlito and Liberation are +**SIL Open Font License 1.1** (see `LICENSE-OFL.txt`); Caladea is +**Apache License 2.0** (copyright Huerta Tipografica). + +| Font | License | Metric-compatible Word counterpart | +| ---------------- | ---------- | ---------------------------------- | +| Carlito GO | OFL 1.1 | Calibri (Word's default body font) | +| Caladea | Apache-2.0 | Cambria | +| Liberation Serif | OFL 1.1 | Times New Roman | +| Liberation Sans | OFL 1.1 | Arial | +| Liberation Mono | OFL 1.1 | Courier New | +| Aptos GO | OFL 1.1 | Aptos (Carlito, size-adjusted) | +| Aptos Display GO | OFL 1.1 | Aptos Display (Carlito, adjusted) | + +"Carlito GO" (`Carlito-*.ttf`) is a derivative of Carlito 1.103: a build-time patch +(`tools/patch-carlito-vi.py`) rebuilds Vietnamese precomposed glyphs whose above mark +(circumflex/breve) was dropped (Ậ/Ệ/Ộ in Regular/Bold); advance widths are unchanged. +Renamed per OFL 1.1 §2 — "Carlito" is a Reserved Font Name. The files live in +`packages/ui/src/fonts/` (shared with sheets and slides, which alias Calibri/Aptos +to the same faces) and are referenced here as `@genoffice/ui/fonts/Carlito-*.ttf`. + +Purpose: when a Word font declared by the document is missing on this machine, the +browser's silent fallback (Helvetica etc.) changes glyph widths, so line-break points +and pagination diverge from Word. Falling back to a metric-compatible font keeps +canvas line breaking aligned with Word, and stays consistent with the offline +pagination model (`tests/helpers/lo-fonts.ts` measures the same set of files). + +Registration lives in `fonts.css`; family-name mapping in `cssFontFamily()` of `line-metrics.ts`. + +"Aptos GO" / "Aptos Display GO" are not separate files: they are `size-adjust`ed +views of the Carlito faces (Word probe 2026-09-03 against Word's bundled Aptos). +Aptos letters run ~6.8% wider than Carlito's, digits +5.4%, the space 10% +narrower, so each weight registers three faces (general, `U+0030-0039`, +`U+0020/00A0`) — later faces win inside their unicode-range. Aptos Display is +close to Carlito for letters but shares the narrow space. Pitch stays Calibri's +1.22 (`lineHeightFactor`). `tests/aptos-alias-metrics.test.ts` holds the probed +sentence widths. + +## CJK fallback + +| Font | Role | +| --------------------------------------- | ------------------------------------------ | +| Noto Sans CJK SC (GB2312-subset woff2) | fallback for heiti-style (sans) families | +| Noto Serif CJK SC (GB2312-subset woff2) | fallback for songti-style (serif) families | + +Source: [notofonts/noto-cjk](https://github.com/notofonts/noto-cjk) (SIL OFL 1.1), +subset with fonttools to all 7,445 GB2312 Han characters + CJK punctuation/fullwidth +forms + basic Latin +(`pyftsubset --text-file=gb2312 --unicodes="U+0020-024F,U+2000-206F,U+3000-303F,U+FF00-FFEF" --flavor=woff2`). +Rare characters outside the subset still fall through to system fonts (shown as +missing glyphs in minimal environments); bold is synthesized by the browser. + +The serif subset also backs the `GenOffice Fullwidth TC` face (`fonts.css`), a +unicode-range shim (U+FF0D/FF0F/FF3C/FF3F/FF5E) slotted before Songti TC in the +Traditional Chinese serif chain: Songti TC draws those fullwidth glyphs at +~0.2-0.5em of ink inside the 1em advance, so a PMingLiU document's U+FF0F +rendered as a spaced half-width slash. Real PMingLiU (Windows) still wins by +chain order; advances are 1.0em everywhere, so line breaking is unchanged. + +## Korean fallback + +| Font | Role | +| ------------------------------------ | ----------------------------------------------------------- | +| GenOffice Serif KR (subset woff2) | Batang-metric stand-in for Korean serif families | +| GenOffice Sans KR (subset woff2) | fallback for Korean sans families (Malgun etc.) | +| GenOffice Che Latin KR (ASCII woff2) | half-width Latin for BatangChe/GulimChe/DotumChe/GungsuhChe | + +Source: Noto Serif/Sans CJK KR Regular from [notofonts/noto-cjk](https://github.com/notofonts/noto-cjk) +(SIL OFL 1.1), subset with fonttools to the 2,350 KS X 1001 syllables + jamo +(U+1100-11FF, U+3130-318F) + basic Latin/CJK punctuation/fullwidth forms +(`U+0020-024F,U+2000-206F,U+3000-303F,U+FF00-FFEF`), then hmtx-normalized to the +metrics of the Windows faces Word substitutes for missing Korean fonts: hangul +syllables/compatibility jamo → 1.0em (Noto CJK KR ships 0.92/0.966em, which +would shift line breaks ~8% vs Word), serif digits → 0.596em and space → +0.333em (measured Batang values), sans Basic Latin (U+0020-007E, U+00A0) → +measured Malgun Gothic advances (space 0.352em, digits 0.551em; Noto's 0.224em +space alone drifted Korean sans line breaks ~3%/line — +`tools/normalize-kr-sans-hmtx.py`, asserted by `tests/kr-font-metrics.test.ts`). +The printable Latin outlines are also horizontally transformed to the measured +ink widths and side bearings of Batang/Malgun +(`tools/normalize-kr-latin-metrics.py`, +`tools/scale-kr-sans-latin-ink.py`). + +`GenOfficeCheLatinKR.woff2` is an ASCII-only derivative of GenOffice Sans KR. +`tools/build-kr-che-latin-font.py` gives its Noto-derived outlines fixed 0.5em +advances and transforms them to measured DotumChe ink boxes. Microsoft Office +fonts are build-time measurement references only; no Microsoft outlines are +included. All three derivatives are renamed because the upstream OFL notices +reserve the name "Source"; "Noto" is the distribution family name, not the +Reserved Font Name. Conjoining jamo keep native advances (shaping). Word +counterpart line factors live in `lineHeightFactor()` of `line-metrics.ts`. +The Sans/Che source copyright (Adobe 2014–2021 and Google LLC), Serif source +copyright (Adobe 2017–2024), and full OFL 1.1 text are in `LICENSE-OFL.txt`. + +### GenOffice Gothic KR + +| Font | Role | +| ---------------------------------- | ----------------------------------------------- | +| GenOffice Gothic KR (subset woff2) | real-metric face for NanumGothic-declaring docs | + +Source: NanumGothic Regular from [google/fonts](https://github.com/google/fonts/tree/main/ofl/nanumgothic) +(SIL OFL 1.1). Word for Mac renders NanumGothic documents with the OS +_downloadable_ Nanum asset (FontServices subset Chromium cannot see): hangul +0.94em, space 0.28em, digits 0.606em (M3 probe 2026-08-14), while the +Batang-normalized subset above ships 1.0/0.333/0.596 — +6.4% per hangul line. +Subset to the same ranges as the KR fallbacks (KS X 1001 syllables + jamo + +Basic Latin/punctuation/fullwidth forms), advances **unmodified** +(`tools/build-gothic-kr-font.py`) and checked in as +`GenOfficeGothicKR-Regular-subset.woff2`. Renamed per OFL (the upstream +Reserved Font Names include "Nanum" and "NanumGothic"; subsetting is a +modification). The exact NHN copyright/Reserved Font Name notice and the full +OFL 1.1 text are in `LICENSE-OFL.txt`. + +### GenOffice UI Kana JP + +| Font | Role | +| ----------------------------------------- | --------------------------------------------------- | +| GenOffice UI Kana JP (Regular/Bold woff2) | Meiryo UI-advance kana/JP punctuation for the alias | + +Source: Noto Sans JP variable font from [notofonts/noto-cjk](https://github.com/notofonts/noto-cjk) +(SIL OFL 1.1), instanced at wght 400/700. Word for Mac renders Meiryo UI with +its private copy whose kana are proportional (Word probe 2026-09-03: あ +0.816em, う 0.639em, ア 0.754em, ideographic space and 、。 0.664em, corner +brackets and ・ 0.5em) at full glyph height; the Hiragino fallback keeps them +at 1em, and a size-adjust alias shrinks height along with width. Subset to +U+3000-30FF code points whose Meiryo UI advance differs from 1em, each glyph +given that exact advance (`tools/meiryo-ui-kana-advances.json`) with the +outline condensed horizontally to fit; vertical metrics set to the Hiragino +class (0.88/-0.12) the glyphs sit next to (`tools/build-meiryo-ui-kana-font.py`). +Renamed per OFL ("Source" is a Reserved Font Name of the upstream and the +outlines are modified). + +## Poppins (M365 cloud font) + +| Font | Role | +| -------------------------------- | ------------------------------------ | +| GenOffice Poppins (subset woff2) | real face for Poppins-declaring docs | + +Source: Poppins Regular/Bold from [google/fonts](https://github.com/google/fonts/tree/main/ofl/poppins) +(SIL OFL 1.1). Poppins is an M365 cloud font: Word downloads the real face and +lays out with its metrics (line box hhea = typo = 1.500em; Word probe +2026-09-01 measured factor exactly 1.500 at 10/12/16/28pt, regular and bold, +with the PDF embedding Poppins-Regular/Bold), while the Helvetica-class +fallback runs ~12.6% narrower per line and 1.172-spaced — a 13-page document +paginated as 11. Subset to Latin + Latin Extended + punctuation/currency, +advances and vertical metrics **unmodified** (`tools/build-poppins-font.py`), +checked in as `GenOfficePoppins-{Regular,Bold}-subset.woff2`. Renamed (no +Reserved Font Name upstream) so a locally installed Poppins wins by chain +order. Italic synthesizes oblique from these faces. + +## Tamil fallback + +| Font | Role | +| ----------------------- | ---------------------------------------- | +| GenOffice Tamil (woff2) | Latha-metric stand-in for Tamil families | + +Source: Noto Sans Tamil Regular from [notofonts](https://github.com/notofonts/notofonts.github.io) +(SIL OFL 1.1). Word substitutes missing Tamil families with Latha; Chromium's +macOS fallback (Tamil Sangam MN) shapes ~27% narrower (M3 probe: sentence R +0.728, space 0.39×), far past what size-adjust can fix without inflating glyph +ink (137%). Advances are rewritten to Latha's: the 109 cmap-shared codepoints +exactly, remaining glyphs (GSUB conjunct/matra outputs) by the median +Tamil-letter ratio (`tools/build-tamil-font.py`; shaped sentence R vs Latha +0.994, every probe sentence within ±2.3%). The face ships no Latin letters +(upstream Noto Sans Tamil has none); Latin falls through the chain. Renamed +per OFL ("Noto" is a Reserved Font Name; advances are modified). + +## Arabic fallback + +| Font | Role | +| -------------------------------- | -------------------------------------------------------- | +| Noto Naskh Arabic (subset woff2) | fallback for naskh/serif-class Arabic families (default) | +| Noto Sans Arabic (subset woff2) | fallback for kufi/sans-class Arabic families | + +Source: Noto Naskh/Sans Arabic Regular from [notofonts/arabic](https://github.com/notofonts/arabic) +(SIL OFL 1.1), subset with fonttools to the Arabic blocks + presentation forms + +digits/punctuation, keeping all shaping features +(`pyftsubset --unicodes="U+0020-024F,U+0600-06FF,U+0750-077F,U+08A0-08FF,U+FB50-FDFF,U+FE70-FEFF,U+2000-206F" --layout-features='*' --flavor=woff2`). +Names are kept ("Noto ..."): glyphs and advances are unmodified, so the OFL +Reserved Font Name clause does not apply. The upstream fonts carry no Latin +letters (only digits/punctuation); Latin text in a cs-font run falls through to +the rest of the chain. Word substitutes a missing Arabic font with a naskh-style +serif, so unknown Arabic families default to the Naskh chain. + +## PUA blanker + +| Font | Role | +| --------------------------------- | ------------------------------------------------ | +| GenOffice PUA Blank (woff2, 312B) | blank 1em glyph for all of U+E000-F8FF (BMP PUA) | + +Generated from scratch by `tools/build-pua-blank-font.py` (no upstream font; +two glyphs, both empty). Chromium never system-falls-back for Private Use +codepoints: an unmapped PUA character renders the chain's primary font's +`.notdef`. Chains headed by a real face (Calibri, Carlito GO) therefore draw +tofu boxes for AI-residue PUA tokens, while Word — and chains headed by the +bundled CJK subsets, whose subsetted `.notdef` is blank — show nothing. This +face sits in the Aptos chain and behind the range-limited `Noto Sans/Serif +CJK GO` aliases so PUA stays invisible there too. diff --git a/apps/desktop/resources/plugins/pi.office/LICENSE b/apps/desktop/resources/plugins/pi.office/LICENSE new file mode 100644 index 0000000000..3017411926 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Mainfunc, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/apps/desktop/resources/plugins/pi.office/LICENSE-OFL.txt b/apps/desktop/resources/plugins/pi.office/LICENSE-OFL.txt new file mode 100644 index 0000000000..0700f5a834 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/LICENSE-OFL.txt @@ -0,0 +1,116 @@ +Digitized data copyright (c) 2010 Google Corporation + with Reserved Font Arimo, Tinos and Cousine. +Copyright (c) 2012 Red Hat, Inc. + with Reserved Font Name Liberation. +Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic (team@latofonts.com) + with Reserved Font Name "Carlito". +Copyright 2014-2021 Adobe (http://www.adobe.com/), Google LLC + with Reserved Font Name "Source". (Noto Sans CJK) +Copyright 2017-2024 Adobe (http://www.adobe.com/) + with Reserved Font Name "Source". (Noto Serif CJK) +Copyright (c) 2010, NHN Corporation (http://www.nhncorp.com), +with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver +NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver +NanumBrush, NanumPen, Naver NanumPen. + +Note: the Caladea fonts in this directory are NOT under this license; +they are licensed under the Apache License 2.0 (see LICENSE at the +repository root; copyright Huerta Tipografica). + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE The goals of the Open Font License (OFL) are to stimulate +worldwide development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to provide +a free and open framework in which fonts may be shared and improved in +partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. +The fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + + + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. +This may include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components +as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting ? in part or in whole ? +any of the components of the Original Version, by changing formats or +by porting the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical writer +or other person who contributed to the Font Software. + + +PERMISSION & CONDITIONS + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components,in + Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, + redistributed and/or sold with any software, provided that each copy + contains the above copyright notice and this license. These can be + included either as stand-alone text files, human-readable headers or + in the appropriate machine-readable metadata fields within text or + binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font + Name(s) unless explicit written permission is granted by the + corresponding Copyright Holder. This restriction only applies to the + primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font + Software shall not be used to promote, endorse or advertise any + Modified Version, except to acknowledge the contribution(s) of the + Copyright Holder(s) and the Author(s) or with their explicit written + permission. + +5) The Font Software, modified or unmodified, in part or in whole, must + be distributed entirely under this license, and must not be distributed + under any other license. The requirement for fonts to remain under + this license does not apply to any document created using the Font + Software. + + + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + + + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. + diff --git a/apps/desktop/resources/plugins/pi.office/LICENSE-UNICODE.txt b/apps/desktop/resources/plugins/pi.office/LICENSE-UNICODE.txt new file mode 100644 index 0000000000..72d44603a4 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/LICENSE-UNICODE.txt @@ -0,0 +1,39 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in +the Data Files or Software without restriction, including without +limitation the rights to use, copy, modify, merge, publish, distribute, +and/or sell copies of the Data Files or Software, and to permit persons +to whom the Data Files or Software are furnished to do so, provided that +either (a) this copyright and permission notice appear with all copies of +the Data Files or Software, or (b) this copyright and permission notice +appear in associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or +other dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/apps/desktop/resources/plugins/pi.office/README.md b/apps/desktop/resources/plugins/pi.office/README.md new file mode 100644 index 0000000000..f08b083919 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/README.md @@ -0,0 +1,22 @@ +# `pi.office` + +`pi.office` is the bundled DOCX editor for PI-Desktop. It extracts the +browser-rendered editor from GenOffice and adapts its file lifecycle to the +PI plugin view bridge. + +The plugin deliberately does not ship the GenOffice Electron shell, AI +providers, account flows, remote services, MCP integrations, or network +access. The view receives a path from the host, asks the plugin process for +DOCX bytes, and saves through `office.save` with an optimistic +`mtime/size/SHA-256` check. + +The editor bundle is generated from the pinned upstream commit recorded in +`UPSTREAM.md`. Keep the generated files and provenance record together when +updating the upstream editor. + +Font attribution and license texts are kept beside the generated assets in +`FONTS-README.md`, `LICENSE-OFL.txt`, and `LICENSE-UNICODE.txt`. + +The editor supports 25%–200% zoom. Work-panel view recreation is synchronized +after plugin reloads so the native Office surface does not leave the host panel +in a stale, non-interactive state. diff --git a/apps/desktop/resources/plugins/pi.office/UPSTREAM.md b/apps/desktop/resources/plugins/pi.office/UPSTREAM.md new file mode 100644 index 0000000000..69fa0ffb08 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/UPSTREAM.md @@ -0,0 +1,25 @@ +# GenOffice provenance + +This plugin vendors the browser renderer built from the Apache-2.0 licensed +GenOffice repository: + +- Repository: https://github.com/genspark-ai/genoffice/ +- Pinned commit: `d1280d153362071de433a6439ca31585af4af8f7` +- Source package: `apps/docs/src/renderer` +- Build command: `npx vite build --config vite.renderer.config.ts` from `apps/docs` + +The PI integration keeps the generated browser assets and replaces the +Electron preload with `views/bridge-shim.js`. `views/pi-office-overrides.css` +is a PI-owned stylesheet that removes the unused Genspark and other AI entry +points, assistant dock, top-level file tab, file pane, and document-tab window +controls from the extracted UI without patching the vendor bundle. +GenOffice's `ee/` directory and the desktop shell are not +bundled. The upstream Apache-2.0 license is shipped as `LICENSE` in this +plugin directory. Bundled font notices are retained in `LICENSE-OFL.txt`, +`LICENSE-UNICODE.txt`, and `FONTS-README.md`. + +When refreshing the editor, rebuild the renderer from the pinned commit, copy +the generated `dist` contents into `views/`, restore the relative asset URLs, +the PI bridge script, and the PI-owned override stylesheet in `views/index.html`, +and review the generated diff for network or desktop-shell imports before +updating this record. diff --git a/apps/desktop/resources/plugins/pi.office/main.js b/apps/desktop/resources/plugins/pi.office/main.js new file mode 100644 index 0000000000..fd093c8a33 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/main.js @@ -0,0 +1,291 @@ +"use strict"; + +const crypto = require("node:crypto"); +const fs = require("node:fs/promises"); +const path = require("node:path"); + +// DOCX is a ZIP container, so the plugin keeps the byte limit explicit rather +// than letting an accidental path open turn into an unbounded memory read. +const MAX_DOCX_BYTES = 64 * 1024 * 1024; +const MAX_RECOVERY_BYTES = 64 * 1024 * 1024; + +const DENY_SEGMENTS = new Set([ + ".git", + ".ssh", + ".aws", + ".gnupg", + ".gpg", + ".npmrc", + ".git-credentials", + ".netrc", + "_netrc", +]); +const DENY_EXACT_NAMES = new Set([".env"]); +const DENY_NAME_PREFIXES = [".env.", "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"]; +const DENY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx", ".keystore", ".jks"]); + +let dataPath = null; + +function failure(code, message, extra = {}) { + const error = new Error(message); + error.code = code; + Object.assign(error, extra); + return error; +} + +function toFailure(error) { + return { + ok: false, + code: typeof error?.code === "string" ? error.code : "OFFICE_ERROR", + message: String(error?.message ?? error), + }; +} + +function isAbsolutePath(value) { + return path.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value); +} + +function isInside(root, target) { + const relative = path.relative(root, target); + return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); +} + +function denyReason(value) { + const normalized = String(value).replaceAll("\\", "/"); + const segments = normalized.split("/").filter(Boolean); + for (const segment of segments) { + const lower = segment.toLowerCase(); + if (DENY_SEGMENTS.has(lower) || DENY_EXACT_NAMES.has(lower)) return "credential path"; + if (DENY_NAME_PREFIXES.some((prefix) => lower.startsWith(prefix))) return "credential path"; + if (DENY_EXTENSIONS.has(path.posix.extname(lower))) return "credential path"; + } + return null; +} + +function assertDocxPath(abs) { + if (path.extname(abs).toLowerCase() !== ".docx") { + throw failure("UNSUPPORTED_TYPE", "pi.office only opens .docx files"); + } + const reason = denyReason(abs); + if (reason) throw failure("DENIED_PATH", `refused path: ${reason}`); +} + +async function workspaceRoot() { + const workspace = await pi.workspace.get().catch(() => null); + if (!workspace?.path || typeof workspace.path !== "string") { + throw failure("NO_WORKSPACE", "no project is open for a relative DOCX path"); + } + return path.resolve(workspace.path); +} + +async function assertContainedPath(root, abs) { + const realRoot = await fs.realpath(root).catch(() => root); + const targetProbe = await fs.realpath(abs).catch(async () => fs.realpath(path.dirname(abs)).catch(() => path.dirname(abs))); + if (!isInside(realRoot, targetProbe)) { + throw failure("SYMLINK_ESCAPE", "path escapes the project root"); + } +} + +async function resolveTarget(payload) { + const raw = typeof payload?.path === "string" ? payload.path.trim() : ""; + if (!raw) throw failure("INVALID_PATH", "path is required"); + + const external = payload?.external === true; + const absolute = isAbsolutePath(raw); + if (absolute && external) { + const abs = path.resolve(raw); + assertDocxPath(abs); + const real = await fs.realpath(abs).catch(() => null); + if (real) assertDocxPath(real); + return { abs, relative: null, external: true }; + } + + const root = await workspaceRoot(); + const abs = absolute ? path.resolve(raw) : path.resolve(root, raw); + if (!isInside(root, abs)) throw failure("ESCAPE", "path escapes the project root"); + await assertContainedPath(root, abs); + assertDocxPath(abs); + return { + abs, + relative: path.relative(root, abs).split(path.sep).join("/"), + external: false, + }; +} + +async function readBytes(abs) { + const stat = await fs.stat(abs).catch(() => null); + if (!stat) throw failure("NOT_FOUND", "DOCX file not found"); + if (!stat.isFile()) throw failure("INVALID_PATH", "path is not a file"); + if (stat.size > MAX_DOCX_BYTES) throw failure("TOO_LARGE", "DOCX exceeds the 64 MiB limit"); + const data = await fs.readFile(abs); + return { stat, data }; +} + +function hashBytes(data) { + return crypto.createHash("sha256").update(data).digest("hex"); +} + +function fileResult(target, stat, data) { + return { + ok: true, + path: target.abs, + name: path.basename(target.abs), + dataBase64: data.toString("base64"), + hash: hashBytes(data), + size: stat.size, + mtimeMs: stat.mtimeMs, + external: target.external, + }; +} + +async function handleRead(payload) { + const target = await resolveTarget(payload); + const { stat, data } = await readBytes(target.abs); + return fileResult(target, stat, data); +} + +async function atomicWrite(abs, data, mode) { + const temp = path.join( + path.dirname(abs), + `.${path.basename(abs)}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}.tmp`, + ); + let handle = null; + try { + handle = await fs.open(temp, "w"); + await handle.writeFile(data); + await handle.sync(); + await handle.close(); + handle = null; + if (mode != null) await fs.chmod(temp, mode).catch(() => {}); + for (let attempt = 0; ; attempt += 1) { + try { + await fs.rename(temp, abs); + return; + } catch (error) { + const transient = ["EPERM", "EBUSY", "EACCES"].includes(error?.code); + if (!transient || attempt >= 3) throw error; + await new Promise((resolve) => setTimeout(resolve, 40 * (attempt + 1))); + } + } + } catch (error) { + if (handle) await handle.close().catch(() => {}); + await fs.rm(temp, { force: true }).catch(() => {}); + throw error; + } +} + +async function handleSave(payload) { + const target = await resolveTarget(payload); + const encoded = typeof payload?.dataBase64 === "string" ? payload.dataBase64 : ""; + const data = Buffer.from(encoded, "base64"); + if (!data.length || data.length > MAX_DOCX_BYTES) { + throw failure("TOO_LARGE", "DOCX data is empty or exceeds the 64 MiB limit"); + } + + const current = await readBytes(target.abs); + const currentHash = hashBytes(current.data); + const mtimeChanged = + typeof payload?.expectedMtimeMs === "number" && + Math.abs(current.stat.mtimeMs - payload.expectedMtimeMs) > 0.5; + const sizeChanged = + typeof payload?.expectedSize === "number" && current.stat.size !== payload.expectedSize; + const hashChanged = + typeof payload?.expectedHash === "string" && currentHash !== payload.expectedHash; + if ((mtimeChanged || sizeChanged || hashChanged) && payload?.force !== true) { + return { + ok: false, + reason: "external-modified", + code: "CONFLICT", + message: "the DOCX changed on disk since it was opened", + mtimeMs: current.stat.mtimeMs, + size: current.stat.size, + hash: currentHash, + }; + } + + await atomicWrite(target.abs, data, current.stat.mode); + const next = await readBytes(target.abs); + return { + ok: true, + path: target.abs, + hash: hashBytes(next.data), + size: next.stat.size, + mtimeMs: next.stat.mtimeMs, + }; +} + +async function handleConflict(payload) { + const target = await resolveTarget(payload); + if (payload?.metadataOnly === true) { + const stat = await fs.stat(target.abs).catch(() => null); + if (!stat) throw failure("NOT_FOUND", "DOCX file not found"); + if (!stat.isFile()) throw failure("INVALID_PATH", "path is not a file"); + if (stat.size > MAX_DOCX_BYTES) throw failure("TOO_LARGE", "DOCX exceeds the 64 MiB limit"); + const mtimeChanged = + typeof payload?.expectedMtimeMs === "number" && + Math.abs(stat.mtimeMs - payload.expectedMtimeMs) > 0.5; + const sizeChanged = + typeof payload?.expectedSize === "number" && stat.size !== payload.expectedSize; + return { + ok: true, + conflict: mtimeChanged || sizeChanged, + mtimeMs: stat.mtimeMs, + size: stat.size, + }; + } + const current = await readBytes(target.abs); + const hash = hashBytes(current.data); + return { + ok: true, + conflict: + (typeof payload?.expectedMtimeMs === "number" && Math.abs(current.stat.mtimeMs - payload.expectedMtimeMs) > 0.5) || + (typeof payload?.expectedSize === "number" && current.stat.size !== payload.expectedSize) || + (typeof payload?.expectedHash === "string" && hash !== payload.expectedHash), + mtimeMs: current.stat.mtimeMs, + size: current.stat.size, + hash, + }; +} + +async function handleRecovery(payload) { + const encoded = typeof payload?.dataBase64 === "string" ? payload.dataBase64 : ""; + const data = Buffer.from(encoded, "base64"); + if (!data.length || data.length > MAX_RECOVERY_BYTES) { + throw failure("TOO_LARGE", "recovery DOCX is empty or too large"); + } + if (!dataPath) return { ok: false, error: "plugin data path unavailable" }; + const recoveryDir = path.join(dataPath, "recovery"); + await fs.mkdir(recoveryDir, { recursive: true }); + const source = typeof payload?.path === "string" ? payload.path : "untitled.docx"; + const key = crypto.createHash("sha256").update(source).digest("hex"); + const target = path.join(recoveryDir, `${key}.docx`); + await atomicWrite(target, data, null); + return { ok: true }; +} + +const CHANNELS = { + "office.read": handleRead, + "office.save": handleSave, + "office.checkConflict": handleConflict, + "office.recovery": handleRecovery, +}; + +async function onPanelInvoke(channel, payload) { + const handler = CHANNELS[channel]; + if (!handler) return { ok: false, code: "UNSUPPORTED", message: `unknown channel: ${channel}` }; + try { + return await handler(payload ?? {}); + } catch (error) { + return toFailure(error); + } +} + +async function onLoad() { + try { + dataPath = await pi.plugin.getDataPath(); + } catch { + dataPath = null; + } +} + +module.exports = { onLoad, onPanelInvoke }; diff --git a/apps/desktop/resources/plugins/pi.office/manifest.json b/apps/desktop/resources/plugins/pi.office/manifest.json new file mode 100644 index 0000000000..c353bac2f5 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/manifest.json @@ -0,0 +1,37 @@ +{ + "schemaVersion": 1, + "id": "pi.office", + "name": "Office", + "version": "0.1.0", + "description": "Edit and preview DOCX files in the work panel.", + "i18n": { + "en": { + "name": "Office", + "description": "Edit and preview DOCX files in the work panel.", + "safetyNotes": "This bundled plugin is a browser-only extraction of GenOffice's DOCX editor. File bytes are read and written by the plugin process through the PI plugin bridge. It accepts only DOCX files, refuses credential paths, uses optimistic conflict checks, and writes through a temporary file followed by fsync and replace. It declares no network domains and does not include GenOffice's AI, account, remote-service, or Electron shell features." + }, + "zh-CN": { + "name": "Office", + "description": "在工作面板中编辑和预览 DOCX 文件。", + "safetyNotes": "这个内置插件只抽取 GenOffice 的 DOCX 编辑器浏览器渲染层。文件字节由插件进程通过 PI 插件桥接读写,只接受 DOCX,拒绝凭据路径,保存前检查外部改动,并通过临时文件、fsync 和替换写入。不声明网络域名,也不包含 GenOffice 的 AI、账号、远程服务或独立 Electron 外壳。" + } + }, + "author": "PI-Desktop", + "license": "Apache-2.0", + "main": "main.js", + "enabledByDefault": true, + "contributes": { + "views": [ + { + "id": "editor", + "title": { "en": "Office", "zh-CN": "Office" }, + "icon": "book", + "entry": "views/index.html", + "order": 30 + } + ] + }, + "permissions": ["ui.view"], + "engines": { "piDesktop": ">=0.9.0" }, + "activationEvents": ["onStartup"] +} diff --git a/apps/desktop/resources/plugins/pi.office/package.json b/apps/desktop/resources/plugins/pi.office/package.json new file mode 100644 index 0000000000..67f7486d40 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/package.json @@ -0,0 +1,6 @@ +{ + "name": "pi.office", + "version": "0.1.0", + "private": true, + "type": "commonjs" +} diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Bold-D8qQyaGr.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Bold-D8qQyaGr.ttf new file mode 100644 index 0000000000..a41e29a6f8 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Bold-D8qQyaGr.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-BoldItalic-wZEKqfeH.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-BoldItalic-wZEKqfeH.ttf new file mode 100644 index 0000000000..ea72b2e43d Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-BoldItalic-wZEKqfeH.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Italic-B_Jy4Zu6.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Italic-B_Jy4Zu6.ttf new file mode 100644 index 0000000000..055a68faeb Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Italic-B_Jy4Zu6.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Regular-BTbwo_Qo.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Regular-BTbwo_Qo.ttf new file mode 100644 index 0000000000..a0802530de Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Caladea-Regular-BTbwo_Qo.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Bold-BhbXr__n.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Bold-BhbXr__n.ttf new file mode 100644 index 0000000000..0d2e3a7a35 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Bold-BhbXr__n.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-BoldItalic-0dXjwGA0.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-BoldItalic-0dXjwGA0.ttf new file mode 100644 index 0000000000..1877ead855 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-BoldItalic-0dXjwGA0.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Italic-KkZUqxJW.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Italic-KkZUqxJW.ttf new file mode 100644 index 0000000000..44becb9264 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Italic-KkZUqxJW.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Regular-Cbe9FLjp.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Regular-Cbe9FLjp.ttf new file mode 100644 index 0000000000..82d3b3f5c4 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/Carlito-Regular-Cbe9FLjp.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeCheLatinKR-CFVfemg_.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeCheLatinKR-CFVfemg_.woff2 new file mode 100644 index 0000000000..a5e2bcfe04 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeCheLatinKR-CFVfemg_.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeGothicKR-Regular-subset-Bkvj_MFZ.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeGothicKR-Regular-subset-Bkvj_MFZ.woff2 new file mode 100644 index 0000000000..cf6855cebd Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeGothicKR-Regular-subset-Bkvj_MFZ.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficePoppins-Bold-subset-CLJyStaw.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficePoppins-Bold-subset-CLJyStaw.woff2 new file mode 100644 index 0000000000..8e25c5102e Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficePoppins-Bold-subset-CLJyStaw.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficePoppins-Regular-subset-RElVmxhA.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficePoppins-Regular-subset-RElVmxhA.woff2 new file mode 100644 index 0000000000..9c4e3a70f2 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficePoppins-Regular-subset-RElVmxhA.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeSansKR-Regular-subset-CVxxonE8.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeSansKR-Regular-subset-CVxxonE8.woff2 new file mode 100644 index 0000000000..5201f0c153 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeSansKR-Regular-subset-CVxxonE8.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeSerifKR-Regular-subset-BkQyd75u.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeSerifKR-Regular-subset-BkQyd75u.woff2 new file mode 100644 index 0000000000..0942724146 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeSerifKR-Regular-subset-BkQyd75u.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeTamil-Regular-DLISHPmH.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeTamil-Regular-DLISHPmH.woff2 new file mode 100644 index 0000000000..8cffbd00f1 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeTamil-Regular-DLISHPmH.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeUIKanaJP-Bold-DbcaglVT.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeUIKanaJP-Bold-DbcaglVT.woff2 new file mode 100644 index 0000000000..48d16aa822 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeUIKanaJP-Bold-DbcaglVT.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeUIKanaJP-Regular-Bj_7JzTT.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeUIKanaJP-Regular-Bj_7JzTT.woff2 new file mode 100644 index 0000000000..c72e320987 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/GenOfficeUIKanaJP-Regular-Bj_7JzTT.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Bold-JpIqZVyK.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Bold-JpIqZVyK.ttf new file mode 100644 index 0000000000..2e46737ac7 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Bold-JpIqZVyK.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-BoldItalic-CW50-m9W.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-BoldItalic-CW50-m9W.ttf new file mode 100644 index 0000000000..d1f46d7cd8 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-BoldItalic-CW50-m9W.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Italic-BaW6sbi8.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Italic-BaW6sbi8.ttf new file mode 100644 index 0000000000..954c39436f Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Italic-BaW6sbi8.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Regular-CscJ8ftk.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Regular-CscJ8ftk.ttf new file mode 100644 index 0000000000..e774859cba Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationMono-Regular-CscJ8ftk.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Bold-CAnzDFU4.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Bold-CAnzDFU4.ttf new file mode 100644 index 0000000000..dc5d57f15f Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Bold-CAnzDFU4.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-BoldItalic-BC07J_j6.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-BoldItalic-BC07J_j6.ttf new file mode 100644 index 0000000000..158488a12e Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-BoldItalic-BC07J_j6.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Italic-D6GtLuAT.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Italic-D6GtLuAT.ttf new file mode 100644 index 0000000000..25970d9d57 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Italic-D6GtLuAT.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Regular-CqxnOoBp.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Regular-CqxnOoBp.ttf new file mode 100644 index 0000000000..e6339859d0 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSans-Regular-CqxnOoBp.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Bold-CT7WGLoV.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Bold-CT7WGLoV.ttf new file mode 100644 index 0000000000..3c7c55b575 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Bold-CT7WGLoV.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-BoldItalic-DHf5skZ4.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-BoldItalic-DHf5skZ4.ttf new file mode 100644 index 0000000000..6b35d9f7c1 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-BoldItalic-DHf5skZ4.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Italic-Bwtmn-ni.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Italic-Bwtmn-ni.ttf new file mode 100644 index 0000000000..54d516481c Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Italic-Bwtmn-ni.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Regular-DREh6cMU.ttf b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Regular-DREh6cMU.ttf new file mode 100644 index 0000000000..5e5550c0af Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/LiberationSerif-Regular-DREh6cMU.ttf differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/NotoNaskhArabic-Regular-subset-DQSqx2ZA.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/NotoNaskhArabic-Regular-subset-DQSqx2ZA.woff2 new file mode 100644 index 0000000000..81e1cda3f9 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/NotoNaskhArabic-Regular-subset-DQSqx2ZA.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/NotoSansArabic-Regular-subset-D207GVuU.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/NotoSansArabic-Regular-subset-D207GVuU.woff2 new file mode 100644 index 0000000000..0627418a7b Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/NotoSansArabic-Regular-subset-D207GVuU.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/NotoSansCJKsc-Regular-subset-BuHGXxnc.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/NotoSansCJKsc-Regular-subset-BuHGXxnc.woff2 new file mode 100644 index 0000000000..f1c892b0d2 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/NotoSansCJKsc-Regular-subset-BuHGXxnc.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/NotoSerifCJKsc-Regular-subset-CLPB6QGT.woff2 b/apps/desktop/resources/plugins/pi.office/views/assets/NotoSerifCJKsc-Regular-subset-CLPB6QGT.woff2 new file mode 100644 index 0000000000..8abafa0120 Binary files /dev/null and b/apps/desktop/resources/plugins/pi.office/views/assets/NotoSerifCJKsc-Regular-subset-CLPB6QGT.woff2 differ diff --git a/apps/desktop/resources/plugins/pi.office/views/assets/index-CiXp5RFk.js b/apps/desktop/resources/plugins/pi.office/views/assets/index-CiXp5RFk.js new file mode 100644 index 0000000000..cdc786c566 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/views/assets/index-CiXp5RFk.js @@ -0,0 +1,404 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var Tw=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Cx(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var yT={exports:{}},n0={};var $F;function CK(){if($F)return n0;$F=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,o){var a=null;if(o!==void 0&&(a=""+o),i.key!==void 0&&(a=""+i.key),"key"in i){o={};for(var s in i)s!=="key"&&(o[s]=i[s])}else o=i;return i=o.ref,{$$typeof:e,type:r,key:a,ref:i!==void 0?i:null,props:o}}return n0.Fragment=t,n0.jsx=n,n0.jsxs=n,n0}var _F;function PK(){return _F||(_F=1,yT.exports=CK()),yT.exports}var g=PK(),wT={exports:{}},r0={},vT={exports:{}},kT={};var HF;function AK(){return HF||(HF=1,(function(e){function t(O,z){var _=O.length;O.push(z);e:for(;0<_;){var W=_-1>>>1,Z=O[W];if(0>>1;W<$;){var V=2*(W+1)-1,Y=O[V],X=V+1,ie=O[X];if(0>i(Y,_))Xi(ie,Y)?(O[W]=ie,O[X]=_,W=X):(O[W]=Y,O[V]=_,W=V);else if(Xi(ie,_))O[W]=ie,O[X]=_,W=X;else break e}}return z}function i(O,z){var _=O.sortIndex-z.sortIndex;return _!==0?_:O.id-z.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,s=a.now();e.unstable_now=function(){return a.now()-s}}var l=[],p=[],c=1,u=null,d=3,h=!1,m=!1,S=!1,y=!1,w=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;function P(O){for(var z=n(p);z!==null;){if(z.callback===null)r(p);else if(z.startTime<=O)r(p),z.sortIndex=z.expirationTime,t(l,z);else break;z=n(p)}}function T(O){if(S=!1,P(O),!m)if(n(l)!==null)m=!0,C||(C=!0,F());else{var z=n(p);z!==null&&H(T,z.startTime-O)}}var C=!1,A=-1,R=5,N=-1;function M(){return y?!0:!(e.unstable_now()-NO&&M());){var W=u.callback;if(typeof W=="function"){u.callback=null,d=u.priorityLevel;var Z=W(u.expirationTime<=O);if(O=e.unstable_now(),typeof Z=="function"){u.callback=Z,P(O),z=!0;break t}u===n(l)&&r(l),P(O)}else r(l);u=n(l)}if(u!==null)z=!0;else{var $=n(p);$!==null&&H(T,$.startTime-O),z=!1}}break e}finally{u=null,d=_,h=!1}z=void 0}}finally{z?F():C=!1}}}var F;if(typeof x=="function")F=function(){x(L)};else if(typeof MessageChannel<"u"){var I=new MessageChannel,B=I.port2;I.port1.onmessage=L,F=function(){B.postMessage(null)}}else F=function(){w(L,0)};function H(O,z){A=w(function(){O(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(O){O.callback=null},e.unstable_forceFrameRate=function(O){0>O||125W?(O.sortIndex=_,t(p,O),n(l)===null&&O===n(p)&&(S?(v(A),A=-1):S=!0,H(T,_-W))):(O.sortIndex=Z,t(l,O),m||h||(m=!0,C||(C=!0,F()))),O},e.unstable_shouldYield=M,e.unstable_wrapCallback=function(O){var z=d;return function(){var _=d;d=z;try{return O.apply(this,arguments)}finally{d=_}}}})(kT)),kT}var WF;function EK(){return WF||(WF=1,vT.exports=AK()),vT.exports}var xT={exports:{}},Nn={};var GF;function RK(){if(GF)return Nn;GF=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),a=Symbol.for("react.context"),s=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),c=Symbol.for("react.lazy"),u=Symbol.for("react.activity"),d=Symbol.iterator;function h($){return $===null||typeof $!="object"?null:($=d&&$[d]||$["@@iterator"],typeof $=="function"?$:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,y={};function w($,V,Y){this.props=$,this.context=V,this.refs=y,this.updater=Y||m}w.prototype.isReactComponent={},w.prototype.setState=function($,V){if(typeof $!="object"&&typeof $!="function"&&$!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,$,V,"setState")},w.prototype.forceUpdate=function($){this.updater.enqueueForceUpdate(this,$,"forceUpdate")};function v(){}v.prototype=w.prototype;function x($,V,Y){this.props=$,this.context=V,this.refs=y,this.updater=Y||m}var P=x.prototype=new v;P.constructor=x,S(P,w.prototype),P.isPureReactComponent=!0;var T=Array.isArray;function C(){}var A={H:null,A:null,T:null,S:null},R=Object.prototype.hasOwnProperty;function N($,V,Y){var X=Y.ref;return{$$typeof:e,type:$,key:V,ref:X!==void 0?X:null,props:Y}}function M($,V){return N($.type,V,$.props)}function L($){return typeof $=="object"&&$!==null&&$.$$typeof===e}function F($){var V={"=":"=0",":":"=2"};return"$"+$.replace(/[=:]/g,function(Y){return V[Y]})}var I=/\/+/g;function B($,V){return typeof $=="object"&&$!==null&&$.key!=null?F(""+$.key):V.toString(36)}function H($){switch($.status){case"fulfilled":return $.value;case"rejected":throw $.reason;default:switch(typeof $.status=="string"?$.then(C,C):($.status="pending",$.then(function(V){$.status==="pending"&&($.status="fulfilled",$.value=V)},function(V){$.status==="pending"&&($.status="rejected",$.reason=V)})),$.status){case"fulfilled":return $.value;case"rejected":throw $.reason}}throw $}function O($,V,Y,X,ie){var ne=typeof $;(ne==="undefined"||ne==="boolean")&&($=null);var re=!1;if($===null)re=!0;else switch(ne){case"bigint":case"string":case"number":re=!0;break;case"object":switch($.$$typeof){case e:case t:re=!0;break;case c:return re=$._init,O(re($._payload),V,Y,X,ie)}}if(re)return ie=ie($),re=X===""?"."+B($,0):X,T(ie)?(Y="",re!=null&&(Y=re.replace(I,"$&/")+"/"),O(ie,V,Y,"",function(Re){return Re})):ie!=null&&(L(ie)&&(ie=M(ie,Y+(ie.key==null||$&&$.key===ie.key?"":(""+ie.key).replace(I,"$&/")+"/")+re)),V.push(ie)),1;re=0;var se=X===""?".":X+":";if(T($))for(var we=0;we<$.length;we++)X=$[we],ne=se+B(X,we),re+=O(X,V,Y,ne,ie);else if(we=h($),typeof we=="function")for($=we.call($),we=0;!(X=$.next()).done;)X=X.value,ne=se+B(X,we++),re+=O(X,V,Y,ne,ie);else if(ne==="object"){if(typeof $.then=="function")return O(H($),V,Y,X,ie);throw V=String($),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys($).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.")}return re}function z($,V,Y){if($==null)return $;var X=[],ie=0;return O($,X,"","",function(ne){return V.call(Y,ne,ie++)}),X}function _($){if($._status===-1){var V=$._result;V=V(),V.then(function(Y){($._status===0||$._status===-1)&&($._status=1,$._result=Y)},function(Y){($._status===0||$._status===-1)&&($._status=2,$._result=Y)}),$._status===-1&&($._status=0,$._result=V)}if($._status===1)return $._result.default;throw $._result}var W=typeof reportError=="function"?reportError:function($){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var V=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof $=="object"&&$!==null&&typeof $.message=="string"?String($.message):String($),error:$});if(!window.dispatchEvent(V))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",$);return}console.error($)},Z={map:z,forEach:function($,V,Y){z($,function(){V.apply(this,arguments)},Y)},count:function($){var V=0;return z($,function(){V++}),V},toArray:function($){return z($,function(V){return V})||[]},only:function($){if(!L($))throw Error("React.Children.only expected to receive a single React element child.");return $}};return Nn.Activity=u,Nn.Children=Z,Nn.Component=w,Nn.Fragment=n,Nn.Profiler=i,Nn.PureComponent=x,Nn.StrictMode=r,Nn.Suspense=l,Nn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,Nn.__COMPILER_RUNTIME={__proto__:null,c:function($){return A.H.useMemoCache($)}},Nn.cache=function($){return function(){return $.apply(null,arguments)}},Nn.cacheSignal=function(){return null},Nn.cloneElement=function($,V,Y){if($==null)throw Error("The argument must be a React element, but you passed "+$+".");var X=S({},$.props),ie=$.key;if(V!=null)for(ne in V.key!==void 0&&(ie=""+V.key),V)!R.call(V,ne)||ne==="key"||ne==="__self"||ne==="__source"||ne==="ref"&&V.ref===void 0||(X[ne]=V[ne]);var ne=arguments.length-2;if(ne===1)X.children=Y;else if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),TT.exports=MK(),TT.exports}var KF;function NK(){if(KF)return r0;KF=1;var e=EK(),t=ey(),n=K3();function r(b){var f="https://react.dev/errors/"+b;if(1Z||(b.current=W[Z],W[Z]=null,Z--)}function Y(b,f){Z++,W[Z]=b.current,b.current=f}var X=$(null),ie=$(null),ne=$(null),re=$(null);function se(b,f){switch(Y(ne,f),Y(ie,b),Y(X,null),f.nodeType){case 9:case 11:b=(b=f.documentElement)&&(b=b.namespaceURI)?cF(b):0;break;default:if(b=f.tagName,f=f.namespaceURI)f=cF(f),b=pF(f,b);else switch(b){case"svg":b=1;break;case"math":b=2;break;default:b=0}}V(X),Y(X,b)}function we(){V(X),V(ie),V(ne)}function Re(b){b.memoizedState!==null&&Y(re,b);var f=X.current,k=pF(f,b.type);f!==k&&(Y(ie,b),Y(X,k))}function Ne(b){ie.current===b&&(V(X),V(ie)),re.current===b&&(V(re),Jg._currentValue=_)}var Fe,Ae;function q(b){if(Fe===void 0)try{throw Error()}catch(k){var f=k.stack.trim().match(/\n( *(at )?)/);Fe=f&&f[1]||"",Ae=-1)":-1D||ze[E]!==et[D]){var gt=` +`+ze[E].replace(" at new "," at ");return b.displayName&>.includes("")&&(gt=gt.replace("",b.displayName)),gt}while(1<=E&&0<=D);break}}}finally{le=!1,Error.prepareStackTrace=k}return(k=b?b.displayName||b.name:"")?q(k):""}function pe(b,f){switch(b.tag){case 26:case 27:case 5:return q(b.type);case 16:return q("Lazy");case 13:return b.child!==f&&f!==null?q("Suspense Fallback"):q("Suspense");case 19:return q("SuspenseList");case 0:case 15:return ge(b.type,!1);case 11:return ge(b.type.render,!1);case 1:return ge(b.type,!0);case 31:return q("Activity");default:return""}}function J(b){try{var f="",k=null;do f+=pe(b,k),k=b,b=b.return;while(b);return f}catch(E){return` +Error generating stack: `+E.message+` +`+E.stack}}var ee=Object.prototype.hasOwnProperty,ve=e.unstable_scheduleCallback,he=e.unstable_cancelCallback,Se=e.unstable_shouldYield,Ee=e.unstable_requestPaint,$e=e.unstable_now,We=e.unstable_getCurrentPriorityLevel,rt=e.unstable_ImmediatePriority,bt=e.unstable_UserBlockingPriority,at=e.unstable_NormalPriority,kt=e.unstable_LowPriority,Gt=e.unstable_IdlePriority,ue=e.log,Ke=e.unstable_setDisableYieldValue,Me=null,qe=null;function xe(b){if(typeof ue=="function"&&Ke(b),qe&&typeof qe.setStrictMode=="function")try{qe.setStrictMode(Me,b)}catch{}}var Ie=Math.clz32?Math.clz32:tt,oe=Math.log,De=Math.LN2;function tt(b){return b>>>=0,b===0?32:31-(oe(b)/De|0)|0}var U=256,Ue=262144,Oe=4194304;function ae(b){var f=b&42;if(f!==0)return f;switch(b&-b){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return b&261888;case 262144:case 524288:case 1048576:case 2097152:return b&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return b&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return b}}function Te(b,f,k){var E=b.pendingLanes;if(E===0)return 0;var D=0,j=b.suspendedLanes,Q=b.pingedLanes;b=b.warmLanes;var me=E&134217727;return me!==0?(E=me&~j,E!==0?D=ae(E):(Q&=me,Q!==0?D=ae(Q):k||(k=me&~b,k!==0&&(D=ae(k))))):(me=E&~j,me!==0?D=ae(me):Q!==0?D=ae(Q):k||(k=E&~b,k!==0&&(D=ae(k)))),D===0?0:f!==0&&f!==D&&(f&j)===0&&(j=D&-D,k=f&-f,j>=k||j===32&&(k&4194048)!==0)?f:D}function He(b,f){return(b.pendingLanes&~(b.suspendedLanes&~b.pingedLanes)&f)===0}function Pt(b,f){switch(b){case 1:case 2:case 4:case 8:case 64:return f+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return f+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function yt(){var b=Oe;return Oe<<=1,(Oe&62914560)===0&&(Oe=4194304),b}function Je(b){for(var f=[],k=0;31>k;k++)f.push(b);return f}function ye(b,f){b.pendingLanes|=f,f!==268435456&&(b.suspendedLanes=0,b.pingedLanes=0,b.warmLanes=0)}function Pe(b,f,k,E,D,j){var Q=b.pendingLanes;b.pendingLanes=k,b.suspendedLanes=0,b.pingedLanes=0,b.warmLanes=0,b.expiredLanes&=k,b.entangledLanes&=k,b.errorRecoveryDisabledLanes&=k,b.shellSuspendCounter=0;var me=b.entanglements,ze=b.expirationTimes,et=b.hiddenUpdates;for(k=Q&~k;0"u")return null;try{return b.activeElement||b.body}catch{return b.body}}var It=/[\n"\\]/g;function Kt(b){return b.replace(It,function(f){return"\\"+f.charCodeAt(0).toString(16)+" "})}function sr(b,f,k,E,D,j,Q,me){b.name="",Q!=null&&typeof Q!="function"&&typeof Q!="symbol"&&typeof Q!="boolean"?b.type=Q:b.removeAttribute("type"),f!=null?Q==="number"?(f===0&&b.value===""||b.value!=f)&&(b.value=""+Wr(f)):b.value!==""+Wr(f)&&(b.value=""+Wr(f)):Q!=="submit"&&Q!=="reset"||b.removeAttribute("value"),f!=null?Li(b,Q,Wr(f)):k!=null?Li(b,Q,Wr(k)):E!=null&&b.removeAttribute("value"),D==null&&j!=null&&(b.defaultChecked=!!j),D!=null&&(b.checked=D&&typeof D!="function"&&typeof D!="symbol"),me!=null&&typeof me!="function"&&typeof me!="symbol"&&typeof me!="boolean"?b.name=""+Wr(me):b.removeAttribute("name")}function Fr(b,f,k,E,D,j,Q,me){if(j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"&&(b.type=j),f!=null||k!=null){if(!(j!=="submit"&&j!=="reset"||f!=null)){ft(b);return}k=k!=null?""+Wr(k):"",f=f!=null?""+Wr(f):k,me||f===b.value||(b.value=f),b.defaultValue=f}E=E??D,E=typeof E!="function"&&typeof E!="symbol"&&!!E,b.checked=me?b.checked:!!E,b.defaultChecked=!!E,Q!=null&&typeof Q!="function"&&typeof Q!="symbol"&&typeof Q!="boolean"&&(b.name=Q),ft(b)}function Li(b,f,k){f==="number"&&Ye(b.ownerDocument)===b||b.defaultValue===""+k||(b.defaultValue=""+k)}function eo(b,f,k,E){if(b=b.options,f){f={};for(var D=0;D"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),wl=!1;if(Kr)try{var vl={};Object.defineProperty(vl,"passive",{get:function(){wl=!0}}),window.addEventListener("test",vl,vl),window.removeEventListener("test",vl,vl)}catch{wl=!1}var to=null,Wo=null,Ra=null;function Qc(){if(Ra)return Ra;var b,f=Wo,k=f.length,E,D="value"in to?to.value:to.textContent,j=D.length;for(b=0;b=pt),vn=" ",pr=!1;function Pr(b,f){switch(b){case"keyup":return Xe.indexOf(f.keyCode)!==-1;case"keydown":return f.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Br(b){return b=b.detail,typeof b=="object"&&"data"in b?b.data:null}var Pn=!1;function Lr(b,f){switch(b){case"compositionend":return Br(f);case"keypress":return f.which!==32?null:(pr=!0,vn);case"textInput":return b=f.data,b===vn&&pr?null:b;default:return null}}function $n(b,f){if(Pn)return b==="compositionend"||!ot&&Pr(b,f)?(b=Qc(),Ra=Wo=to=null,Pn=!1,b):null;switch(b){case"paste":return null;case"keypress":if(!(f.ctrlKey||f.altKey||f.metaKey)||f.ctrlKey&&f.altKey){if(f.char&&1=f)return{node:k,offset:f-b};b=E}e:{for(;k;){if(k.nextSibling){k=k.nextSibling;break e}k=k.parentNode}k=void 0}k=Ly(k)}}function Dy(b,f){return b&&f?b===f?!0:b&&b.nodeType===3?!1:f&&f.nodeType===3?Dy(b,f.parentNode):"contains"in b?b.contains(f):b.compareDocumentPosition?!!(b.compareDocumentPosition(f)&16):!1:!1}function dg(b){b=b!=null&&b.ownerDocument!=null&&b.ownerDocument.defaultView!=null?b.ownerDocument.defaultView:window;for(var f=Ye(b.document);f instanceof b.HTMLIFrameElement;){try{var k=typeof f.contentWindow.location.href=="string"}catch{k=!1}if(k)b=f.contentWindow;else break;f=Ye(b.document)}return f}function bg(b){var f=b&&b.nodeName&&b.nodeName.toLowerCase();return f&&(f==="input"&&(b.type==="text"||b.type==="search"||b.type==="tel"||b.type==="url"||b.type==="password")||f==="textarea"||b.contentEditable==="true")}var zy=Kr&&"documentMode"in document&&11>=document.documentMode,ip=null,Yh=null,vu=null,Jh=!1;function Qh(b,f,k){var E=k.window===k?k.document:k.nodeType===9?k:k.ownerDocument;Jh||ip==null||ip!==Ye(E)||(E=ip,"selectionStart"in E&&bg(E)?E={start:E.selectionStart,end:E.selectionEnd}:(E=(E.ownerDocument&&E.ownerDocument.defaultView||window).getSelection(),E={anchorNode:E.anchorNode,anchorOffset:E.anchorOffset,focusNode:E.focusNode,focusOffset:E.focusOffset}),vu&&wu(vu,E)||(vu=E,E=cw(Yh,"onSelect"),0>=Q,D-=Q,Xo=1<<32-Ie(f)+D|k<zn?(Qn=tn,tn=null):Qn=tn.sibling;var cr=nt(Ze,tn,Qe[zn],St);if(cr===null){tn===null&&(tn=Qn);break}b&&tn&&cr.alternate===null&&f(Ze,tn),Ge=j(cr,Ge,zn),lr===null?pn=cr:lr.sibling=cr,lr=cr,tn=Qn}if(zn===Qe.length)return k(Ze,tn),Un&&us(Ze,zn),pn;if(tn===null){for(;znzn?(Qn=tn,tn=null):Qn=tn.sibling;var ld=nt(Ze,tn,cr.value,St);if(ld===null){tn===null&&(tn=Qn);break}b&&tn&&ld.alternate===null&&f(Ze,tn),Ge=j(ld,Ge,zn),lr===null?pn=ld:lr.sibling=ld,lr=ld,tn=Qn}if(cr.done)return k(Ze,tn),Un&&us(Ze,zn),pn;if(tn===null){for(;!cr.done;zn++,cr=Qe.next())cr=xt(Ze,cr.value,St),cr!==null&&(Ge=j(cr,Ge,zn),lr===null?pn=cr:lr.sibling=cr,lr=cr);return Un&&us(Ze,zn),pn}for(tn=E(tn);!cr.done;zn++,cr=Qe.next())cr=st(tn,Ze,zn,cr.value,St),cr!==null&&(b&&cr.alternate!==null&&tn.delete(cr.key===null?zn:cr.key),Ge=j(cr,Ge,zn),lr===null?pn=cr:lr.sibling=cr,lr=cr);return b&&tn.forEach(function(TK){return f(Ze,TK)}),Un&&us(Ze,zn),pn}function Mr(Ze,Ge,Qe,St){if(typeof Qe=="object"&&Qe!==null&&Qe.type===S&&Qe.key===null&&(Qe=Qe.props.children),typeof Qe=="object"&&Qe!==null){switch(Qe.$$typeof){case h:e:{for(var pn=Qe.key;Ge!==null;){if(Ge.key===pn){if(pn=Qe.type,pn===S){if(Ge.tag===7){k(Ze,Ge.sibling),St=D(Ge,Qe.props.children),St.return=Ze,Ze=St;break e}}else if(Ge.elementType===pn||typeof pn=="object"&&pn!==null&&pn.$$typeof===R&&Gs(pn)===Ge.type){k(Ze,Ge.sibling),St=D(Ge,Qe.props),Iu(St,Qe),St.return=Ze,Ze=St;break e}k(Ze,Ge);break}else f(Ze,Ge);Ge=Ge.sibling}Qe.type===S?(St=ps(Qe.props.children,Ze.mode,St,Qe.key),St.return=Ze,Ze=St):(St=cs(Qe.type,Qe.key,Qe.props,null,Ze.mode,St),Iu(St,Qe),St.return=Ze,Ze=St)}return Q(Ze);case m:e:{for(pn=Qe.key;Ge!==null;){if(Ge.key===pn)if(Ge.tag===4&&Ge.stateNode.containerInfo===Qe.containerInfo&&Ge.stateNode.implementation===Qe.implementation){k(Ze,Ge.sibling),St=D(Ge,Qe.children||[]),St.return=Ze,Ze=St;break e}else{k(Ze,Ge);break}else f(Ze,Ge);Ge=Ge.sibling}St=fg(Qe,Ze.mode,St),St.return=Ze,Ze=St}return Q(Ze);case R:return Qe=Gs(Qe),Mr(Ze,Ge,Qe,St)}if(H(Qe))return Zt(Ze,Ge,Qe,St);if(F(Qe)){if(pn=F(Qe),typeof pn!="function")throw Error(r(150));return Qe=pn.call(Qe),yn(Ze,Ge,Qe,St)}if(typeof Qe.then=="function")return Mr(Ze,Ge,Us(Qe),St);if(Qe.$$typeof===x)return Mr(Ze,Ge,lf(Ze,Qe),St);Bu(Ze,Qe)}return typeof Qe=="string"&&Qe!==""||typeof Qe=="number"||typeof Qe=="bigint"?(Qe=""+Qe,Ge!==null&&Ge.tag===6?(k(Ze,Ge.sibling),St=D(Ge,Qe),St.return=Ze,Ze=St):(k(Ze,Ge),St=cp(Qe,Ze.mode,St),St.return=Ze,Ze=St),Q(Ze)):k(Ze,Ge)}return function(Ze,Ge,Qe,St){try{Qo=0;var pn=Mr(Ze,Ge,Qe,St);return Bl=null,pn}catch(tn){if(tn===Nl||tn===di)throw tn;var lr=Ko(29,tn,null,Ze.mode);return lr.lanes=St,lr.return=Ze,lr}}}var qs=hb(!0),Gy=hb(!1),Ia=!1;function Lu(b){b.updateQueue={baseState:b.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function fb(b,f){b=b.updateQueue,f.updateQueue===b&&(f.updateQueue={baseState:b.baseState,firstBaseUpdate:b.firstBaseUpdate,lastBaseUpdate:b.lastBaseUpdate,shared:b.shared,callbacks:null})}function Vs(b){return{lane:b,tag:0,payload:null,callback:null,next:null}}function Cc(b,f,k){var E=b.updateQueue;if(E===null)return null;if(E=E.shared,(dr&2)!==0){var D=E.pending;return D===null?f.next=f:(f.next=D.next,D.next=f),E.pending=f,f=Al(b),lp(b,null,k),f}return vc(b,E,f,k),Al(b)}function mb(b,f,k){if(f=f.updateQueue,f!==null&&(f=f.shared,(k&4194048)!==0)){var E=f.lanes;E&=b.pendingLanes,k|=E,f.lanes=k,it(b,k)}}function vg(b,f){var k=b.updateQueue,E=b.alternate;if(E!==null&&(E=E.updateQueue,k===E)){var D=null,j=null;if(k=k.firstBaseUpdate,k!==null){do{var Q={lane:k.lane,tag:k.tag,payload:k.payload,callback:null,next:null};j===null?D=j=Q:j=j.next=Q,k=k.next}while(k!==null);j===null?D=j=f:j=j.next=f}else D=j=f;k={baseState:E.baseState,firstBaseUpdate:D,lastBaseUpdate:j,shared:E.shared,callbacks:E.callbacks},b.updateQueue=k;return}b=k.lastBaseUpdate,b===null?k.firstBaseUpdate=f:b.next=f,k.lastBaseUpdate=f}var kg=!1;function gb(){if(kg){var b=bp;if(b!==null)throw b}}function Sb(b,f,k,E){kg=!1;var D=b.updateQueue;Ia=!1;var j=D.firstBaseUpdate,Q=D.lastBaseUpdate,me=D.shared.pending;if(me!==null){D.shared.pending=null;var ze=me,et=ze.next;ze.next=null,Q===null?j=et:Q.next=et,Q=ze;var gt=b.alternate;gt!==null&&(gt=gt.updateQueue,me=gt.lastBaseUpdate,me!==Q&&(me===null?gt.firstBaseUpdate=et:me.next=et,gt.lastBaseUpdate=ze))}if(j!==null){var xt=D.baseState;Q=0,gt=et=ze=null,me=j;do{var nt=me.lane&-536870913,st=nt!==me.lane;if(st?(Jn&nt)===nt:(E&nt)===nt){nt!==0&&nt===Rl&&(kg=!0),gt!==null&&(gt=gt.next={lane:0,tag:me.tag,payload:me.payload,callback:null,next:null});e:{var Zt=b,yn=me;nt=f;var Mr=k;switch(yn.tag){case 1:if(Zt=yn.payload,typeof Zt=="function"){xt=Zt.call(Mr,xt,nt);break e}xt=Zt;break e;case 3:Zt.flags=Zt.flags&-65537|128;case 0:if(Zt=yn.payload,nt=typeof Zt=="function"?Zt.call(Mr,xt,nt):Zt,nt==null)break e;xt=u({},xt,nt);break e;case 2:Ia=!0}}nt=me.callback,nt!==null&&(b.flags|=64,st&&(b.flags|=8192),st=D.callbacks,st===null?D.callbacks=[nt]:st.push(nt))}else st={lane:nt,tag:me.tag,payload:me.payload,callback:me.callback,next:null},gt===null?(et=gt=st,ze=xt):gt=gt.next=st,Q|=nt;if(me=me.next,me===null){if(me=D.shared.pending,me===null)break;st=me,me=st.next,st.next=null,D.lastBaseUpdate=st,D.shared.pending=null}}while(!0);gt===null&&(ze=xt),D.baseState=ze,D.firstBaseUpdate=et,D.lastBaseUpdate=gt,j===null&&(D.shared.lanes=0),Ju|=Q,b.lanes=Q,b.memoizedState=xt}}function Uy(b,f){if(typeof b!="function")throw Error(r(191,b));b.call(f)}function xg(b,f){var k=b.callbacks;if(k!==null)for(b.callbacks=null,b=0;bj?j:8;var Q=O.T,me={};O.T=me,Cb(b,!1,f,k);try{var ze=D(),et=O.S;if(et!==null&&et(me,ze),ze!==null&&typeof ze=="object"&&typeof ze.then=="function"){var gt=wg(ze,E);Ou(b,f,gt,ws(b))}else Ou(b,f,E,ws(b))}catch(xt){Ou(b,f,{then:function(){},status:"rejected",reason:xt},ws())}finally{z.p=j,Q!==null&&me.types!==null&&(Q.types=me.types),O.T=Q}}function zl(){}function jl(b,f,k,E){if(b.tag!==5)throw Error(r(476));var D=Nc(b).queue;Dl(b,D,f,_,k===null?zl:function(){return xb(b),k(E)})}function Nc(b){var f=b.memoizedState;if(f!==null)return f;f={memoizedState:_,baseState:_,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:lt,lastRenderedState:_},next:null};var k={};return f.next={memoizedState:k,baseState:k,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:lt,lastRenderedState:k},next:null},b.memoizedState=f,b=b.alternate,b!==null&&(b.memoizedState=f),f}function xb(b){var f=Nc(b);f.next===null&&(f=b.alternate.memoizedState),Ou(b,f.next.queue,{},ws())}function Tb(){return zi(Jg)}function Oa(){return ce().memoizedState}function Sf(){return ce().memoizedState}function Ol(b){for(var f=b.return;f!==null;){switch(f.tag){case 24:case 3:var k=ws();b=Vs(k);var E=Cc(f,b,k);E!==null&&(Ua(E,f,k),mb(E,f,k)),f={cache:Nu()},b.payload=f;return}f=f.return}}function B1(b,f,k){var E=ws();k={lane:E,revertLane:0,gesture:null,action:k,hasEagerState:!1,eagerState:null,next:null},Pb(b)?Fg(f,k):(k=ba(b,f,k,E),k!==null&&(Ua(k,b,E),Ig(k,f,E)))}function Ng(b,f,k){var E=ws();Ou(b,f,k,E)}function Ou(b,f,k,E){var D={lane:E,revertLane:0,gesture:null,action:k,hasEagerState:!1,eagerState:null,next:null};if(Pb(b))Fg(f,D);else{var j=b.alternate;if(b.lanes===0&&(j===null||j.lanes===0)&&(j=f.lastRenderedReducer,j!==null))try{var Q=f.lastRenderedState,me=j(Q,k);if(D.hasEagerState=!0,D.eagerState=me,Uo(me,Q))return vc(b,f,D,0),$r===null&&js(),!1}catch{}if(k=ba(b,f,D,E),k!==null)return Ua(k,b,E),Ig(k,f,E),!0}return!1}function Cb(b,f,k,E){if(E={lane:2,revertLane:Z1(),gesture:null,action:E,hasEagerState:!1,eagerState:null,next:null},Pb(b)){if(f)throw Error(r(479))}else f=ba(b,k,E,2),f!==null&&Ua(f,b,2)}function Pb(b){var f=b.alternate;return b===Mn||f!==null&&f===Mn}function Fg(b,f){Ac=mp=!0;var k=b.pending;k===null?f.next=f:(f.next=k.next,k.next=f),b.pending=f}function Ig(b,f,k){if((k&4194048)!==0){var E=f.lanes;E&=b.pendingLanes,k|=E,f.lanes=k,it(b,k)}}var $u={readContext:zi,use:ct,useCallback:qr,useContext:qr,useEffect:qr,useImperativeHandle:qr,useLayoutEffect:qr,useInsertionEffect:qr,useMemo:qr,useReducer:qr,useRef:qr,useState:qr,useDebugValue:qr,useDeferredValue:qr,useTransition:qr,useSyncExternalStore:qr,useId:qr,useHostTransitionStatus:qr,useFormState:qr,useActionState:qr,useOptimistic:qr,useMemoCache:qr,useCacheRefresh:qr};$u.useEffectEvent=qr;var Bg={readContext:zi,use:ct,useCallback:function(b,f){return be().memoizedState=[b,f===void 0?null:f],b},useContext:zi,useEffect:Ky,useImperativeHandle:function(b,f,k){k=k!=null?k.concat([b]):null,Da(4194308,4,mi.bind(null,f,b),k)},useLayoutEffect:function(b,f){return Da(4194308,4,b,f)},useInsertionEffect:function(b,f){Da(4,2,b,f)},useMemo:function(b,f){var k=be();f=f===void 0?null:f;var E=b();if(gp){xe(!0);try{b()}finally{xe(!1)}}return k.memoizedState=[E,f],E},useReducer:function(b,f,k){var E=be();if(k!==void 0){var D=k(f);if(gp){xe(!0);try{k(f)}finally{xe(!1)}}}else D=f;return E.memoizedState=E.baseState=D,b={pending:null,lanes:0,dispatch:null,lastRenderedReducer:b,lastRenderedState:D},E.queue=b,b=b.dispatch=B1.bind(null,Mn,b),[E.memoizedState,b]},useRef:function(b){var f=be();return b={current:b},f.memoizedState=b},useState:function(b){b=Jr(b);var f=b.queue,k=Ng.bind(null,Mn,f);return f.dispatch=k,[b.memoizedState,k]},useDebugValue:ji,useDeferredValue:function(b,f){var k=be();return ta(k,b,f)},useTransition:function(){var b=Jr(!1);return b=Dl.bind(null,Mn,b.queue,!0,!1),be().memoizedState=b,[!1,b]},useSyncExternalStore:function(b,f,k){var E=Mn,D=be();if(Un){if(k===void 0)throw Error(r(407));k=k()}else{if(k=f(),$r===null)throw Error(r(349));(Jn&127)!==0||Yt(E,f,k)}D.memoizedState=k;var j={value:k,getSnapshot:f};return D.queue=j,Ky(An.bind(null,E,j,b),[b]),E.flags|=2048,Ai(9,{destroy:void 0},Wt.bind(null,E,j,k,f),null),k},useId:function(){var b=be(),f=$r.identifierPrefix;if(Un){var k=Os,E=Xo;k=(E&~(1<<32-Ie(E)-1)).toString(32)+k,f="_"+f+"R_"+k,k=hf++,0<\/script>",j=j.removeChild(j.firstChild);break;case"select":j=typeof E.is=="string"?Q.createElement("select",{is:E.is}):Q.createElement("select"),E.multiple?j.multiple=!0:E.size&&(j.size=E.size);break;default:j=typeof E.is=="string"?Q.createElement(D,{is:E.is}):Q.createElement(D)}}j[Ot]=f,j[ut]=E;e:for(Q=f.child;Q!==null;){if(Q.tag===5||Q.tag===6)j.appendChild(Q.stateNode);else if(Q.tag!==4&&Q.tag!==27&&Q.child!==null){Q.child.return=Q,Q=Q.child;continue}if(Q===f)break e;for(;Q.sibling===null;){if(Q.return===null||Q.return===f)break e;Q=Q.return}Q.sibling.return=Q.return,Q=Q.sibling}f.stateNode=j;e:switch(Eo(j,D,E),D){case"button":case"input":case"select":case"textarea":E=!!E.autoFocus;break e;case"img":E=!0;break e;default:E=!1}E&&ra(f)}}return Er(f),wa(f,f.type,b===null?null:b.memoizedProps,f.pendingProps,k),null;case 6:if(b&&f.stateNode!=null)b.memoizedProps!==E&&ra(f);else{if(typeof E!="string"&&f.stateNode===null)throw Error(r(166));if(b=ne.current,Yo(f)){if(b=f.stateNode,k=f.memoizedProps,E=null,D=Ci,D!==null)switch(D.tag){case 27:case 5:E=D.memoizedProps}b[Ot]=f,b=!!(b.nodeValue===k||E!==null&&E.suppressHydrationWarning===!0||sF(b.nodeValue,k)),b||El(f,!0)}else b=pw(b).createTextNode(E),b[Ot]=f,f.stateNode=b}return Er(f),null;case 31:if(k=f.memoizedState,b===null||b.memoizedState!==null){if(E=Yo(f),k!==null){if(b===null){if(!E)throw Error(r(318));if(b=f.memoizedState,b=b!==null?b.dehydrated:null,!b)throw Error(r(557));b[Ot]=f}else $s(),(f.flags&128)===0&&(f.memoizedState=null),f.flags|=4;Er(f),b=!1}else k=hr(),b!==null&&b.memoizedState!==null&&(b.memoizedState.hydrationErrors=k),b=!0;if(!b)return f.flags&256?(ma(f),f):(ma(f),null);if((f.flags&128)!==0)throw Error(r(558))}return Er(f),null;case 13:if(E=f.memoizedState,b===null||b.memoizedState!==null&&b.memoizedState.dehydrated!==null){if(D=Yo(f),E!==null&&E.dehydrated!==null){if(b===null){if(!D)throw Error(r(318));if(D=f.memoizedState,D=D!==null?D.dehydrated:null,!D)throw Error(r(317));D[Ot]=f}else $s(),(f.flags&128)===0&&(f.memoizedState=null),f.flags|=4;Er(f),D=!1}else D=hr(),b!==null&&b.memoizedState!==null&&(b.memoizedState.hydrationErrors=D),D=!0;if(!D)return f.flags&256?(ma(f),f):(ma(f),null)}return ma(f),(f.flags&128)!==0?(f.lanes=k,f):(k=E!==null,b=b!==null&&b.memoizedState!==null,k&&(E=f.child,D=null,E.alternate!==null&&E.alternate.memoizedState!==null&&E.alternate.memoizedState.cachePool!==null&&(D=E.alternate.memoizedState.cachePool.pool),j=null,E.memoizedState!==null&&E.memoizedState.cachePool!==null&&(j=E.memoizedState.cachePool.pool),j!==D&&(E.flags|=2048)),k!==b&&k&&(f.child.flags|=8192),Nb(f,f.updateQueue),Er(f),null);case 4:return we(),b===null&&Q1(f.stateNode.containerInfo),Er(f),null;case 10:return Jo(f.type),Er(f),null;case 19:if(V(ii),E=f.memoizedState,E===null)return Er(f),null;if(D=(f.flags&128)!==0,j=E.rendering,j===null)if(D)Ku(E,!1);else{if(Si!==0||b!==null&&(b.flags&128)!==0)for(b=f.child;b!==null;){if(j=yb(b),j!==null){for(f.flags|=128,Ku(E,!1),b=j.updateQueue,f.updateQueue=b,Nb(f,b),f.subtreeFlags=0,b=k,k=f.child;k!==null;)zr(k,b),k=k.sibling;return Y(ii,ii.current&1|2),Un&&us(f,E.treeForkCount),f.child}b=b.sibling}E.tail!==null&&$e()>ew&&(f.flags|=128,D=!0,Ku(E,!1),f.lanes=4194304)}else{if(!D)if(b=yb(j),b!==null){if(f.flags|=128,D=!0,b=b.updateQueue,f.updateQueue=b,Nb(f,b),Ku(E,!0),E.tail===null&&E.tailMode==="hidden"&&!j.alternate&&!Un)return Er(f),null}else 2*$e()-E.renderingStartTime>ew&&k!==536870912&&(f.flags|=128,D=!0,Ku(E,!1),f.lanes=4194304);E.isBackwards?(j.sibling=f.child,f.child=j):(b=E.last,b!==null?b.sibling=j:f.child=j,E.last=j)}return E.tail!==null?(b=E.tail,E.rendering=b,E.tail=b.sibling,E.renderingStartTime=$e(),b.sibling=null,k=ii.current,Y(ii,D?k&1|2:k&1),Un&&us(f,E.treeForkCount),b):(Er(f),null);case 22:case 23:return ma(f),Cg(),E=f.memoizedState!==null,b!==null?b.memoizedState!==null!==E&&(f.flags|=8192):E&&(f.flags|=8192),E?(k&536870912)!==0&&(f.flags&128)===0&&(Er(f),f.subtreeFlags&6&&(f.flags|=8192)):Er(f),k=f.updateQueue,k!==null&&Nb(f,k.retryQueue),k=null,b!==null&&b.memoizedState!==null&&b.memoizedState.cachePool!==null&&(k=b.memoizedState.cachePool.pool),E=null,f.memoizedState!==null&&f.memoizedState.cachePool!==null&&(E=f.memoizedState.cachePool.pool),E!==k&&(f.flags|=2048),b!==null&&V(xc),null;case 24:return k=null,b!==null&&(k=b.memoizedState.cache),f.memoizedState.cache!==k&&(f.flags|=2048),Jo(Ur),Er(f),null;case 25:return null;case 30:return null}throw Error(r(156,f.tag))}function Or(b,f){switch(Au(f),f.tag){case 1:return b=f.flags,b&65536?(f.flags=b&-65537|128,f):null;case 3:return Jo(Ur),we(),b=f.flags,(b&65536)!==0&&(b&128)===0?(f.flags=b&-65537|128,f):null;case 26:case 27:case 5:return Ne(f),null;case 31:if(f.memoizedState!==null){if(ma(f),f.alternate===null)throw Error(r(340));$s()}return b=f.flags,b&65536?(f.flags=b&-65537|128,f):null;case 13:if(ma(f),b=f.memoizedState,b!==null&&b.dehydrated!==null){if(f.alternate===null)throw Error(r(340));$s()}return b=f.flags,b&65536?(f.flags=b&-65537|128,f):null;case 19:return V(ii),null;case 4:return we(),null;case 10:return Jo(f.type),null;case 22:case 23:return ma(f),Cg(),b!==null&&V(xc),b=f.flags,b&65536?(f.flags=b&-65537|128,f):null;case 24:return Jo(Ur),null;case 25:return null;default:return null}}function Wl(b,f){switch(Au(f),f.tag){case 3:Jo(Ur),we();break;case 26:case 27:case 5:Ne(f);break;case 4:we();break;case 31:f.memoizedState!==null&&ma(f);break;case 13:ma(f);break;case 19:V(ii);break;case 10:Jo(f.type);break;case 22:case 23:ma(f),Cg(),b!==null&&V(xc);break;case 24:Jo(Ur)}}function Zu(b,f){try{var k=f.updateQueue,E=k!==null?k.lastEffect:null;if(E!==null){var D=E.next;k=D;do{if((k.tag&b)===b){E=void 0;var j=k.create,Q=k.inst;E=j(),Q.destroy=E}k=k.next}while(k!==D)}}catch(me){Sr(f,f.return,me)}}function Qr(b,f,k){try{var E=f.updateQueue,D=E!==null?E.lastEffect:null;if(D!==null){var j=D.next;E=j;do{if((E.tag&b)===b){var Q=E.inst,me=Q.destroy;if(me!==void 0){Q.destroy=void 0,D=f;var ze=k,et=me;try{et()}catch(gt){Sr(D,ze,gt)}}}E=E.next}while(E!==j)}}catch(gt){Sr(f,f.return,gt)}}function Js(b){var f=b.updateQueue;if(f!==null){var k=b.stateNode;try{xg(f,k)}catch(E){Sr(b,b.return,E)}}}function Fb(b,f,k){k.props=$l(b.type,b.memoizedProps),k.state=b.memoizedState;try{k.componentWillUnmount()}catch(E){Sr(b,f,E)}}function Gl(b,f){try{var k=b.ref;if(k!==null){switch(b.tag){case 26:case 27:case 5:var E=b.stateNode;break;case 30:E=b.stateNode;break;default:E=b.stateNode}typeof k=="function"?b.refCleanup=k(E):k.current=E}}catch(D){Sr(b,f,D)}}function Ao(b,f){var k=b.ref,E=b.refCleanup;if(k!==null)if(typeof E=="function")try{E()}catch(D){Sr(b,f,D)}finally{b.refCleanup=null,b=b.alternate,b!=null&&(b.refCleanup=null)}else if(typeof k=="function")try{k(null)}catch(D){Sr(b,f,D)}else k.current=null}function Ul(b){var f=b.type,k=b.memoizedProps,E=b.stateNode;try{e:switch(f){case"button":case"input":case"select":case"textarea":k.autoFocus&&E.focus();break e;case"img":k.src?E.src=k.src:k.srcSet&&(E.srcset=k.srcSet)}}catch(D){Sr(b,b.return,D)}}function $g(b,f,k){try{var E=b.stateNode;KV(E,b.type,k,f),E[ut]=f}catch(D){Sr(b,b.return,D)}}function va(b){return b.tag===5||b.tag===3||b.tag===26||b.tag===27&&rd(b.type)||b.tag===4}function ql(b){e:for(;;){for(;b.sibling===null;){if(b.return===null||va(b.return))return null;b=b.return}for(b.sibling.return=b.return,b=b.sibling;b.tag!==5&&b.tag!==6&&b.tag!==18;){if(b.tag===27&&rd(b.type)||b.flags&2||b.child===null||b.tag===4)continue e;b.child.return=b,b=b.child}if(!(b.flags&2))return b.stateNode}}function ms(b,f,k){var E=b.tag;if(E===5||E===6)b=b.stateNode,f?(k.nodeType===9?k.body:k.nodeName==="HTML"?k.ownerDocument.body:k).insertBefore(b,f):(f=k.nodeType===9?k.body:k.nodeName==="HTML"?k.ownerDocument.body:k,f.appendChild(b),k=k._reactRootContainer,k!=null||f.onclick!==null||(f.onclick=To));else if(E!==4&&(E===27&&rd(b.type)&&(k=b.stateNode,f=null),b=b.child,b!==null))for(ms(b,f,k),b=b.sibling;b!==null;)ms(b,f,k),b=b.sibling}function Ib(b,f,k){var E=b.tag;if(E===5||E===6)b=b.stateNode,f?k.insertBefore(b,f):k.appendChild(b);else if(E!==4&&(E===27&&rd(b.type)&&(k=b.stateNode),b=b.child,b!==null))for(Ib(b,f,k),b=b.sibling;b!==null;)Ib(b,f,k),b=b.sibling}function Xu(b){var f=b.stateNode,k=b.memoizedProps;try{for(var E=b.type,D=f.attributes;D.length;)f.removeAttributeNode(D[0]);Eo(f,E,k),f[Ot]=b,f[ut]=k}catch(j){Sr(b,b.return,j)}}var gs=!1,$i=!1,L1=!1,SN=typeof WeakSet=="function"?WeakSet:Set,ho=null;function AV(b,f){if(b=b.containerInfo,nT=gw,b=dg(b),bg(b)){if("selectionStart"in b)var k={start:b.selectionStart,end:b.selectionEnd};else e:{k=(k=b.ownerDocument)&&k.defaultView||window;var E=k.getSelection&&k.getSelection();if(E&&E.rangeCount!==0){k=E.anchorNode;var D=E.anchorOffset,j=E.focusNode;E=E.focusOffset;try{k.nodeType,j.nodeType}catch{k=null;break e}var Q=0,me=-1,ze=-1,et=0,gt=0,xt=b,nt=null;t:for(;;){for(var st;xt!==k||D!==0&&xt.nodeType!==3||(me=Q+D),xt!==j||E!==0&&xt.nodeType!==3||(ze=Q+E),xt.nodeType===3&&(Q+=xt.nodeValue.length),(st=xt.firstChild)!==null;)nt=xt,xt=st;for(;;){if(xt===b)break t;if(nt===k&&++et===D&&(me=Q),nt===j&&++gt===E&&(ze=Q),(st=xt.nextSibling)!==null)break;xt=nt,nt=xt.parentNode}xt=st}k=me===-1||ze===-1?null:{start:me,end:ze}}else k=null}k=k||{start:0,end:0}}else k=null;for(rT={focusedElem:b,selectionRange:k},gw=!1,ho=f;ho!==null;)if(f=ho,b=f.child,(f.subtreeFlags&1028)!==0&&b!==null)b.return=f,ho=b;else for(;ho!==null;){switch(f=ho,j=f.alternate,b=f.flags,f.tag){case 0:if((b&4)!==0&&(b=f.updateQueue,b=b!==null?b.events:null,b!==null))for(k=0;k title"))),Eo(j,E,k),j[Ot]=b,Tr(j),E=j;break e;case"link":var Q=TF("link","href",D).get(E+(k.href||""));if(Q){for(var me=0;meMr&&(Q=Mr,Mr=yn,yn=Q);var Ze=lb(me,yn),Ge=lb(me,Mr);if(Ze&&Ge&&(st.rangeCount!==1||st.anchorNode!==Ze.node||st.anchorOffset!==Ze.offset||st.focusNode!==Ge.node||st.focusOffset!==Ge.offset)){var Qe=xt.createRange();Qe.setStart(Ze.node,Ze.offset),st.removeAllRanges(),yn>Mr?(st.addRange(Qe),st.extend(Ge.node,Ge.offset)):(Qe.setEnd(Ge.node,Ge.offset),st.addRange(Qe))}}}}for(xt=[],st=me;st=st.parentNode;)st.nodeType===1&&xt.push({element:st,left:st.scrollLeft,top:st.scrollTop});for(typeof me.focus=="function"&&me.focus(),me=0;mek?32:k,O.T=null,k=H1,H1=null;var j=ed,Q=Pp;if(io=0,Ef=ed=null,Pp=0,(dr&6)!==0)throw Error(r(331));var me=dr;if(dr|=4,RN(j.current),PN(j,j.current,Q,k),dr=me,qg(0,!1),qe&&typeof qe.onPostCommitFiberRoot=="function")try{qe.onPostCommitFiberRoot(Me,j)}catch{}return!0}finally{z.p=D,O.T=E,VN(b,f)}}function ZN(b,f,k){f=Ma(k,f),f=Eb(b.stateNode,f,2),b=Cc(b,f,2),b!==null&&(ye(b,2),Fc(b))}function Sr(b,f,k){if(b.tag===3)ZN(b,b,k);else for(;f!==null;){if(f.tag===3){ZN(f,b,k);break}else if(f.tag===1){var E=f.stateNode;if(typeof f.type.getDerivedStateFromError=="function"||typeof E.componentDidCatch=="function"&&(Qu===null||!Qu.has(E))){b=Ma(k,b),k=Hu(2),E=Cc(f,k,2),E!==null&&(Xy(k,E,f,b),ye(E,2),Fc(E));break}}f=f.return}}function q1(b,f,k){var E=b.pingCache;if(E===null){E=b.pingCache=new MV;var D=new Set;E.set(f,D)}else D=E.get(f),D===void 0&&(D=new Set,E.set(f,D));D.has(k)||(j1=!0,D.add(k),b=LV.bind(null,b,f,k),f.then(b,b))}function LV(b,f,k){var E=b.pingCache;E!==null&&E.delete(f),b.pingedLanes|=b.suspendedLanes&k,b.warmLanes&=~k,$r===b&&(Jn&k)===k&&(Si===4||Si===3&&(Jn&62914560)===Jn&&300>$e()-Qy?(dr&2)===0&&Rf(b,0):O1|=k,Af===Jn&&(Af=0)),Fc(b)}function XN(b,f){f===0&&(f=yt()),b=sp(b,f),b!==null&&(ye(b,f),Fc(b))}function DV(b){var f=b.memoizedState,k=0;f!==null&&(k=f.retryLane),XN(b,k)}function zV(b,f){var k=0;switch(b.tag){case 31:case 13:var E=b.stateNode,D=b.memoizedState;D!==null&&(k=D.retryLane);break;case 19:E=b.stateNode;break;case 22:E=b.stateNode._retryCache;break;default:throw Error(r(314))}E!==null&&E.delete(f),XN(b,k)}function jV(b,f){return ve(b,f)}var aw=null,Nf=null,V1=!1,sw=!1,K1=!1,nd=0;function Fc(b){b!==Nf&&b.next===null&&(Nf===null?aw=Nf=b:Nf=Nf.next=b),sw=!0,V1||(V1=!0,$V())}function qg(b,f){if(!K1&&sw){K1=!0;do for(var k=!1,E=aw;E!==null;){if(b!==0){var D=E.pendingLanes;if(D===0)var j=0;else{var Q=E.suspendedLanes,me=E.pingedLanes;j=(1<<31-Ie(42|b)+1)-1,j&=D&~(Q&~me),j=j&201326741?j&201326741|1:j?j|2:0}j!==0&&(k=!0,eF(E,j))}else j=Jn,j=Te(E,E===$r?j:0,E.cancelPendingCommit!==null||E.timeoutHandle!==-1),(j&3)===0||He(E,j)||(k=!0,eF(E,j));E=E.next}while(k);K1=!1}}function OV(){YN()}function YN(){sw=V1=!1;var b=0;nd!==0&&XV()&&(b=nd);for(var f=$e(),k=null,E=aw;E!==null;){var D=E.next,j=JN(E,f);j===0?(E.next=null,k===null?aw=D:k.next=D,D===null&&(Nf=k)):(k=E,(b!==0||(j&3)!==0)&&(sw=!0)),E=D}io!==0&&io!==5||qg(b),nd!==0&&(nd=0)}function JN(b,f){for(var k=b.suspendedLanes,E=b.pingedLanes,D=b.expirationTimes,j=b.pendingLanes&-62914561;0me)break;var gt=ze.transferSize,xt=ze.initiatorType;gt&&lF(xt)&&(ze=ze.responseEnd,Q+=gt*(ze"u"?null:document;function wF(b,f,k){var E=Ff;if(E&&typeof f=="string"&&f){var D=Kt(f);D='link[rel="'+b+'"][href="'+D+'"]',typeof k=="string"&&(D+='[crossorigin="'+k+'"]'),yF.has(D)||(yF.add(D),b={rel:b,crossOrigin:k,href:f},E.querySelector(D)===null&&(f=E.createElement("link"),Eo(f,"link",b),Tr(f),E.head.appendChild(f)))}}function oK(b){Ap.D(b),wF("dns-prefetch",b,null)}function aK(b,f){Ap.C(b,f),wF("preconnect",b,f)}function sK(b,f,k){Ap.L(b,f,k);var E=Ff;if(E&&b&&f){var D='link[rel="preload"][as="'+Kt(f)+'"]';f==="image"&&k&&k.imageSrcSet?(D+='[imagesrcset="'+Kt(k.imageSrcSet)+'"]',typeof k.imageSizes=="string"&&(D+='[imagesizes="'+Kt(k.imageSizes)+'"]')):D+='[href="'+Kt(b)+'"]';var j=D;switch(f){case"style":j=If(b);break;case"script":j=Bf(b)}el.has(j)||(b=u({rel:"preload",href:f==="image"&&k&&k.imageSrcSet?void 0:b,as:f},k),el.set(j,b),E.querySelector(D)!==null||f==="style"&&E.querySelector(Xg(j))||f==="script"&&E.querySelector(Yg(j))||(f=E.createElement("link"),Eo(f,"link",b),Tr(f),E.head.appendChild(f)))}}function lK(b,f){Ap.m(b,f);var k=Ff;if(k&&b){var E=f&&typeof f.as=="string"?f.as:"script",D='link[rel="modulepreload"][as="'+Kt(E)+'"][href="'+Kt(b)+'"]',j=D;switch(E){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":j=Bf(b)}if(!el.has(j)&&(b=u({rel:"modulepreload",href:b},f),el.set(j,b),k.querySelector(D)===null)){switch(E){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(k.querySelector(Yg(j)))return}E=k.createElement("link"),Eo(E,"link",b),Tr(E),k.head.appendChild(E)}}}function cK(b,f,k){Ap.S(b,f,k);var E=Ff;if(E&&b){var D=so(E).hoistableStyles,j=If(b);f=f||"default";var Q=D.get(j);if(!Q){var me={loading:0,preload:null};if(Q=E.querySelector(Xg(j)))me.loading=5;else{b=u({rel:"stylesheet",href:b,"data-precedence":f},k),(k=el.get(j))&&pT(b,k);var ze=Q=E.createElement("link");Tr(ze),Eo(ze,"link",b),ze._p=new Promise(function(et,gt){ze.onload=et,ze.onerror=gt}),ze.addEventListener("load",function(){me.loading|=1}),ze.addEventListener("error",function(){me.loading|=2}),me.loading|=4,dw(Q,f,E)}Q={type:"stylesheet",instance:Q,count:1,state:me},D.set(j,Q)}}}function pK(b,f){Ap.X(b,f);var k=Ff;if(k&&b){var E=so(k).hoistableScripts,D=Bf(b),j=E.get(D);j||(j=k.querySelector(Yg(D)),j||(b=u({src:b,async:!0},f),(f=el.get(D))&&uT(b,f),j=k.createElement("script"),Tr(j),Eo(j,"link",b),k.head.appendChild(j)),j={type:"script",instance:j,count:1,state:null},E.set(D,j))}}function uK(b,f){Ap.M(b,f);var k=Ff;if(k&&b){var E=so(k).hoistableScripts,D=Bf(b),j=E.get(D);j||(j=k.querySelector(Yg(D)),j||(b=u({src:b,async:!0,type:"module"},f),(f=el.get(D))&&uT(b,f),j=k.createElement("script"),Tr(j),Eo(j,"link",b),k.head.appendChild(j)),j={type:"script",instance:j,count:1,state:null},E.set(D,j))}}function vF(b,f,k,E){var D=(D=ne.current)?uw(D):null;if(!D)throw Error(r(446));switch(b){case"meta":case"title":return null;case"style":return typeof k.precedence=="string"&&typeof k.href=="string"?(f=If(k.href),k=so(D).hoistableStyles,E=k.get(f),E||(E={type:"style",instance:null,count:0,state:null},k.set(f,E)),E):{type:"void",instance:null,count:0,state:null};case"link":if(k.rel==="stylesheet"&&typeof k.href=="string"&&typeof k.precedence=="string"){b=If(k.href);var j=so(D).hoistableStyles,Q=j.get(b);if(Q||(D=D.ownerDocument||D,Q={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},j.set(b,Q),(j=D.querySelector(Xg(b)))&&!j._p&&(Q.instance=j,Q.state.loading=5),el.has(b)||(k={rel:"preload",as:"style",href:k.href,crossOrigin:k.crossOrigin,integrity:k.integrity,media:k.media,hrefLang:k.hrefLang,referrerPolicy:k.referrerPolicy},el.set(b,k),j||dK(D,b,k,Q.state))),f&&E===null)throw Error(r(528,""));return Q}if(f&&E!==null)throw Error(r(529,""));return null;case"script":return f=k.async,k=k.src,typeof k=="string"&&f&&typeof f!="function"&&typeof f!="symbol"?(f=Bf(k),k=so(D).hoistableScripts,E=k.get(f),E||(E={type:"script",instance:null,count:0,state:null},k.set(f,E)),E):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,b))}}function If(b){return'href="'+Kt(b)+'"'}function Xg(b){return'link[rel="stylesheet"]['+b+"]"}function kF(b){return u({},b,{"data-precedence":b.precedence,precedence:null})}function dK(b,f,k,E){b.querySelector('link[rel="preload"][as="style"]['+f+"]")?E.loading=1:(f=b.createElement("link"),E.preload=f,f.addEventListener("load",function(){return E.loading|=1}),f.addEventListener("error",function(){return E.loading|=2}),Eo(f,"link",k),Tr(f),b.head.appendChild(f))}function Bf(b){return'[src="'+Kt(b)+'"]'}function Yg(b){return"script[async]"+b}function xF(b,f,k){if(f.count++,f.instance===null)switch(f.type){case"style":var E=b.querySelector('style[data-href~="'+Kt(k.href)+'"]');if(E)return f.instance=E,Tr(E),E;var D=u({},k,{"data-href":k.href,"data-precedence":k.precedence,href:null,precedence:null});return E=(b.ownerDocument||b).createElement("style"),Tr(E),Eo(E,"style",D),dw(E,k.precedence,b),f.instance=E;case"stylesheet":D=If(k.href);var j=b.querySelector(Xg(D));if(j)return f.state.loading|=4,f.instance=j,Tr(j),j;E=kF(k),(D=el.get(D))&&pT(E,D),j=(b.ownerDocument||b).createElement("link"),Tr(j);var Q=j;return Q._p=new Promise(function(me,ze){Q.onload=me,Q.onerror=ze}),Eo(j,"link",E),f.state.loading|=4,dw(j,k.precedence,b),f.instance=j;case"script":return j=Bf(k.src),(D=b.querySelector(Yg(j)))?(f.instance=D,Tr(D),D):(E=k,(D=el.get(j))&&(E=u({},k),uT(E,D)),b=b.ownerDocument||b,D=b.createElement("script"),Tr(D),Eo(D,"link",E),b.head.appendChild(D),f.instance=D);case"void":return null;default:throw Error(r(443,f.type))}else f.type==="stylesheet"&&(f.state.loading&4)===0&&(E=f.instance,f.state.loading|=4,dw(E,k.precedence,b));return f.instance}function dw(b,f,k){for(var E=k.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),D=E.length?E[E.length-1]:null,j=D,Q=0;Q title"):null)}function bK(b,f,k){if(k===1||f.itemProp!=null)return!1;switch(b){case"meta":case"title":return!0;case"style":if(typeof f.precedence!="string"||typeof f.href!="string"||f.href==="")break;return!0;case"link":if(typeof f.rel!="string"||typeof f.href!="string"||f.href===""||f.onLoad||f.onError)break;return f.rel==="stylesheet"?(b=f.disabled,typeof f.precedence=="string"&&b==null):!0;case"script":if(f.async&&typeof f.async!="function"&&typeof f.async!="symbol"&&!f.onLoad&&!f.onError&&f.src&&typeof f.src=="string")return!0}return!1}function PF(b){return!(b.type==="stylesheet"&&(b.state.loading&3)===0)}function hK(b,f,k,E){if(k.type==="stylesheet"&&(typeof E.media!="string"||matchMedia(E.media).matches!==!1)&&(k.state.loading&4)===0){if(k.instance===null){var D=If(E.href),j=f.querySelector(Xg(D));if(j){f=j._p,f!==null&&typeof f=="object"&&typeof f.then=="function"&&(b.count++,b=hw.bind(b),f.then(b,b)),k.state.loading|=4,k.instance=j,Tr(j);return}j=f.ownerDocument||f,E=kF(E),(D=el.get(D))&&pT(E,D),j=j.createElement("link"),Tr(j);var Q=j;Q._p=new Promise(function(me,ze){Q.onload=me,Q.onerror=ze}),Eo(j,"link",E),k.instance=j}b.stylesheets===null&&(b.stylesheets=new Map),b.stylesheets.set(k,f),(f=k.state.preload)&&(k.state.loading&3)===0&&(b.count++,k=hw.bind(b),f.addEventListener("load",k),f.addEventListener("error",k))}}var dT=0;function fK(b,f){return b.stylesheets&&b.count===0&&mw(b,b.stylesheets),0dT?50:800)+f);return b.unsuspend=k,function(){b.unsuspend=null,clearTimeout(E),clearTimeout(D)}}:null}function hw(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)mw(this,this.stylesheets);else if(this.unsuspend){var b=this.unsuspend;this.unsuspend=null,b()}}}var fw=null;function mw(b,f){b.stylesheets=null,b.unsuspend!==null&&(b.count++,fw=new Map,f.forEach(mK,b),fw=null,hw.call(b))}function mK(b,f){if(!(f.state.loading&4)){var k=fw.get(b);if(k)var E=k.get(null);else{k=new Map,fw.set(b,k);for(var D=b.querySelectorAll("link[data-precedence],style[data-precedence]"),j=0;j"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),wT.exports=NK(),wT.exports}var IK=FK();const BK={zh:"zh-CN",en:"en-US",ja:"ja-JP",ko:"ko-KR",fr:"fr-FR",de:"de-DE",es:"es-ES",th:"th-TH",id:"id-ID",ru:"ru-RU",ar:"ar-SA",pt:"pt-BR",it:"it-IT",pl:"pl-PL",cs:"cs-CZ",nl:"nl-NL",ms:"ms-MY",he:"he-IL",hi:"hi-IN","zh-TW":"zh-TW"};function Z3(e){return BK[e]}const X3={"⌫":"Backspace","⌦":"Delete","⏎":"Enter","↩":"Enter","␣":"Space"},LK=/[⌘⌃⌥⇧⌫⌦⏎↩␣]/,DK=/([⌘⌃⌥⇧]+)(F\d{1,2}|[A-Za-z0-9±=`'\\,./;[\]\-←↑→↓⌫⌦⏎↩␣]|\+)?/g;function XF(e,t){const n=[];return(e.includes("⌘")||e.includes("⌃"))&&n.push("Ctrl"),e.includes("⌥")&&n.push("Alt"),e.includes("⇧")&&n.push("Shift"),t&&n.push(X3[t]??t),n.join("+")}function Y3(e){return LK.test(e)?e.replace(new RegExp("⌘\\/(?=\\p{L}{2})","gu"),"").replace(DK,(t,n,r)=>r==="+"?`${XF(n,void 0)}+`:XF(n,r)).replace(/[⌫⌦⏎↩␣]/g,t=>X3[t]??t):e}const zK=(()=>{const e=globalThis;return e.navigator?.platform?/mac/i.test(e.navigator.platform):e.process?.platform==="darwin"})(),lR=zK?e=>e:Y3;function jK(e,t){return t?e.replace(/\{(\w+)\}/g,(n,r)=>Object.hasOwn(t,r)?String(t[r]):n):e}function J3(e){return(t,n,r)=>lR(jK(e[t][n],r))}var YF=Object.defineProperty,OK=(e,t)=>{let n={};for(var r in e)YF(n,r,{get:e[r],enumerable:!0});return YF(n,Symbol.toStringTag,{value:"Module"}),n};function Mo(e){this.content=e}Mo.prototype={constructor:Mo,find:function(e){for(var t=0;t>1}};Mo.from=function(e){if(e instanceof Mo)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new Mo(t)};function Q3(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let i=e.child(r),o=t.child(r);if(i==o){n+=i.nodeSize;continue}if(!i.sameMarkup(o))return n;if(i.isText&&i.text!=o.text){let a=i.text,s=o.text,l=0;for(;a[l]==s[l];l++)n++;return l&&l0&&d>0&&p[u-1]==c[d-1];)u--,d--,n--,r--;return u&&d&&u=56320&&e<57344}function n4(e){return e>=55296&&e<56320}class vt{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let r=0;rt&&r(l,i+s,o||null,a)!==!1&&l.content.size){let c=s+1;l.nodesBetween(Math.max(0,t-c),Math.min(l.content.size,n-c),r,i+c)}s=p}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,i){let o="",a=!0;return this.nodesBetween(t,n,(s,l)=>{let p=s.isText?s.text.slice(Math.max(t,l)-l,n-l):s.isLeaf?i?typeof i=="function"?i(s):i:s.type.spec.leafText?s.type.spec.leafText(s):"":"";s.isBlock&&(s.isLeaf&&p||s.isTextblock)&&r&&(a?a=!1:o+=r),o+=p},0),o}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),o=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),o=1);ot)for(let o=0,a=0;at&&((an)&&(s.isText?s=s.cut(Math.max(0,t-a),Math.min(s.text.length,n-a)):s=s.cut(Math.max(0,t-a-1),Math.min(s.content.size,n-a-1))),r.push(s),i+=s.nodeSize),a=l}return new vt(r,i)}cutByIndex(t,n){return t==n?vt.empty:t==0&&n==this.content.length?this:new vt(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),o=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new vt(i,o)}addToStart(t){return new vt([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new vt(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;nthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),o=r+i.nodeSize;if(o>=t)return o==t?Cw(n+1,o):Cw(n,r);r=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return vt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return vt.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return vt.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=t.slice(0,i)),n.push(this),r=!0),n&&n.push(o)}}return n||(n=t.slice()),r||n.push(this),n}removeFromSet(t){for(let n=0;nr.type.rank-i.type.rank),n}};Hr.none=[];class yS extends Error{}class Dt{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=i4(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new Dt(r,this.openStart,this.openEnd)}removeBetween(t,n){return new Dt(r4(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return Dt.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Dt(vt.fromJSON(t,n.content),r,i)}static maxOpen(t,n=!0){let r=0,i=0;for(let o=t.firstChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.firstChild)r++;for(let o=t.lastChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.lastChild)i++;return new Dt(t,r,i)}}Dt.empty=new Dt(vt.empty,0,0);function r4(e,t,n){let{index:r,offset:i}=e.findIndex(t),o=e.maybeChild(r),{index:a,offset:s}=e.findIndex(n);if(i==t||o.isText){if(s!=n&&!e.child(a).isText)throw new RangeError("Removing non-flat range");return e.cut(0,t).append(e.cut(n))}if(r!=a)throw new RangeError("Removing non-flat range");return e.replaceChild(r,o.copy(r4(o.content,t-i-1,n-i-1)))}function i4(e,t,n,r,i,o){let{index:a,offset:s}=e.findIndex(t),l=e.maybeChild(a);if(s==t||l.isText)return o&&r<=0&&i<=0&&!o.canReplace(a,a,n)?null:e.cut(0,t).append(n).append(e.cut(t));let p=i4(l.content,t-s-1,n,a==0?r-1:0,a==e.childCount-1?i-1:0,l);return p&&e.replaceChild(a,l.copy(p))}function $K(e,t,n){if(n.openStart>e.depth)throw new yS("Inserted content deeper than insertion position");if(e.depth-n.openStart!=t.depth-n.openEnd)throw new yS("Inconsistent open depths");return o4(e,t,n,0)}function o4(e,t,n,r){let i=e.index(r),o=e.node(r);if(i==t.index(r)&&r=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function K0(e,t,n,r){let i=(t||e).node(n),o=0,a=t?t.index(n):i.childCount;e&&(o=e.index(n),e.depth>n?o++:e.textOffset&&(bh(e.nodeAfter,r),o++));for(let s=o;si&&kP(e,t,i+1),a=r.depth>i&&kP(n,r,i+1),s=[];return K0(null,e,i,s),o&&a&&t.index(i)==n.index(i)?(a4(o,a),bh(hh(o,s4(e,t,n,r,i+1)),s)):(o&&bh(hh(o,ik(e,t,i+1)),s),K0(t,n,i,s),a&&bh(hh(a,ik(n,r,i+1)),s)),K0(r,null,i,s),new vt(s)}function ik(e,t,n){let r=[];if(K0(null,e,n,r),e.depth>n){let i=kP(e,t,n+1);bh(hh(i,ik(e,t,n+1)),r)}return K0(t,null,n,r),new vt(r)}function _K(e,t){let n=t.depth-e.openStart,i=t.node(n).copy(e.content);for(let o=n-1;o>=0;o--)i=t.node(o).copy(vt.from(i));return{start:i.resolveNoCache(e.openStart+n),end:i.resolveNoCache(i.content.size-e.openEnd-n)}}class wS{constructor(t,n,r){this.pos=t,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,n=this.index(this.depth);if(n==t.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=t.child(n);return r?t.child(n).cut(r):i}get nodeBefore(){let t=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(t).cut(0,n):t==0?null:this.parent.child(t-1)}posAtIndex(t,n){n=this.resolveDepth(n);let r=this.path[n*3],i=n==0?0:this.path[n*3-1]+1;for(let o=0;o0;n--)if(this.start(n)<=t&&this.end(n)>=t)return n;return 0}blockRange(t=this,n){if(t.pos=0;r--)if(t.pos<=this.end(r)&&(!n||n(this.node(r))))return new ok(this,t,r);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&n<=t.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,o=n;for(let a=t;;){let{index:s,offset:l}=a.content.findIndex(o),p=o-l;if(r.push(a,s,i+l),!p||(a=a.child(s),a.isText))break;o=p-1,i+=l+1}return new wS(n,r,o)}static resolveCached(t,n){let r=JF.get(t);if(r)for(let o=0;ot&&this.nodesBetween(t,n,o=>(r.isInSet(o.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),l4(this.marks,t)}contentMatchAt(t){let n=this.type.contentMatch.matchFragment(this.content,0,t);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(t,n,r=vt.empty,i=0,o=r.childCount){let a=this.contentMatchAt(t).matchFragment(r,i,o),s=a&&a.matchFragment(this.content,n);if(!s||!s.validEnd)return!1;for(let l=i;ln.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(n=>n.toJSON())),t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(t.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(n.text,r)}let i=vt.fromJSON(t,n.content),o=t.nodeType(n.type).create(n.attrs,i,r);return o.type.checkAttrs(o.attrs),o}};fh.prototype.text=void 0;class ak extends fh{constructor(t,n,r,i){if(super(t,n,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):l4(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,n){return this.text.slice(t,n)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new ak(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new ak(this.type,this.attrs,t,this.marks)}cut(t=0,n=this.text.length){return t==0&&n==this.text.length?this:this.withText(this.text.slice(t,n))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function l4(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+"("+t+")";return t}class kh{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new UK(t,n);if(r.next==null)return kh.empty;let i=c4(r);r.next&&r.err("Unexpected trailing text");let o=JK(YK(i));return QK(o,r),o}matchType(t){for(let n=0;np.createAndFill()));for(let p=0;p=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function n(r){t.push(r);for(let i=0;i{let o=i+(r.validEnd?"*":" ")+" ";for(let a=0;a"+t.indexOf(r.next[a].next);return o}).join(` +`)}}kh.empty=new kh(!0);class UK{constructor(t,n){this.string=t,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=t.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(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function c4(e){let t=[];do t.push(qK(e));while(e.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function qK(e){let t=[];do t.push(VK(e));while(e.next&&e.next!=")"&&e.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function VK(e){let t=XK(e);for(;;)if(e.eat("+"))t={type:"plus",expr:t};else if(e.eat("*"))t={type:"star",expr:t};else if(e.eat("?"))t={type:"opt",expr:t};else if(e.eat("{"))t=KK(e,t);else break;return t}function QF(e){/\D/.test(e.next)&&e.err("Expected number, got '"+e.next+"'");let t=Number(e.next);return e.pos++,t}function KK(e,t){let n=QF(e),r=n;return e.eat(",")&&(e.next!="}"?r=QF(e):r=-1),e.eat("}")||e.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function ZK(e,t){let n=e.nodeTypes,r=n[t];if(r)return[r];let i=[];for(let o in n){let a=n[o];a.isInGroup(t)&&i.push(a)}return i.length==0&&e.err("No node type or group '"+t+"' found"),i}function XK(e){if(e.eat("(")){let t=c4(e);return e.eat(")")||e.err("Missing closing paren"),t}else if(/\W/.test(e.next))e.err("Unexpected token '"+e.next+"'");else{let t=ZK(e,e.next).map(n=>(e.inline==null?e.inline=n.isInline:e.inline!=n.isInline&&e.err("Mixing inline and block content"),{type:"name",value:n}));return e.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function YK(e){let t=[[]];return i(o(e,0),n()),t;function n(){return t.push([])-1}function r(a,s,l){let p={term:l,to:s};return t[a].push(p),p}function i(a,s){a.forEach(l=>l.to=s)}function o(a,s){if(a.type=="choice")return a.exprs.reduce((l,p)=>l.concat(o(p,s)),[]);if(a.type=="seq")for(let l=0;;l++){let p=o(a.exprs[l],s);if(l==a.exprs.length-1)return p;i(p,s=n())}else if(a.type=="star"){let l=n();return r(s,l),i(o(a.expr,l),l),[r(l)]}else if(a.type=="plus"){let l=n();return i(o(a.expr,s),l),i(o(a.expr,l),l),[r(l)]}else{if(a.type=="opt")return[r(s)].concat(o(a.expr,s));if(a.type=="range"){let l=s;for(let p=0;p{e[a].forEach(({term:s,to:l})=>{if(!s)return;let p;for(let c=0;c{p||i.push([s,p=[]]),p.indexOf(c)==-1&&p.push(c)})})});let o=t[r.join(",")]=new kh(r.indexOf(e.length-1)>-1);for(let a=0;a-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:d4(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new fh(this,this.computeAttrs(t),vt.from(n),Hr.setFrom(r))}createChecked(t=null,n,r){return n=vt.from(n),this.checkContent(n),new fh(this,this.computeAttrs(t),n,Hr.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=vt.from(n),n.size){let a=this.contentMatch.fillBefore(n);if(!a)return null;n=a.append(n)}let i=this.contentMatch.matchFragment(n),o=i&&i.fillBefore(vt.empty,!0);return o?new fh(this,t,n.append(o),Hr.setFrom(r)):null}validContent(t){let n=this.contentMatch.matchFragment(t);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(t){if(this.markSet==null)return!0;for(let n=0;nr[o]=new f4(o,n,a));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let o in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function eZ(e,t,n){let r=n.split("|");return i=>{let o=i===null?"null":typeof i;if(r.indexOf(o)<0)throw new RangeError(`Expected value of type ${r} for attribute ${t} on type ${e}, got ${o}`)}}class tZ{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?eZ(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Px{constructor(t,n,r,i){this.name=t,this.rank=n,this.schema=r,this.spec=i,this.attrs=h4(t,i.attrs),this.excluded=null;let o=u4(this.attrs);this.instance=o?new Hr(this,o):null}create(t=null){return!t&&this.instance?this.instance:new Hr(this,d4(this.attrs,t))}static compile(t,n){let r=Object.create(null),i=0;return t.forEach((o,a)=>r[o]=new Px(o,i++,n,a)),r}removeFromSet(t){for(var n=0;n-1}}class m4{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in t)n[i]=t[i];n.nodes=Mo.from(t.nodes),n.marks=Mo.from(t.marks||{}),this.nodes=tI.compile(this.spec.nodes,this),this.marks=Px.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let o=this.nodes[i],a=o.spec.content||"",s=o.spec.marks;if(o.contentMatch=r[a]||(r[a]=kh.parse(a,this.nodes)),o.inlineContent=o.contentMatch.inlineContent,o.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!o.isInline||!o.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=o}o.markSet=s=="_"?null:s?nI(this,s.split(" ")):s==""||!o.inlineContent?[]:null}for(let i in this.marks){let o=this.marks[i],a=o.spec.excludes;o.excluded=a==null?[o]:a==""?[]:nI(this,a.split(" "))}this.nodeFromJSON=i=>fh.fromJSON(this,i),this.markFromJSON=i=>Hr.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,n=null,r,i){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof tI){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(n,r,i)}text(t,n){let r=this.nodes.text;return new ak(r,r.defaultAttrs,t,Hr.setFrom(n))}mark(t,n){return typeof t=="string"&&(t=this.marks[t]),t.create(n)}nodeType(t){let n=this.nodes[t];if(!n)throw new RangeError("Unknown node type: "+t);return n}}function nI(e,t){let n=[];for(let r=0;r-1)&&n.push(a=l)}if(!a)throw new SyntaxError("Unknown mark type: '"+t[r]+"'")}return n}function nZ(e){return e.tag!=null}function rZ(e){return e.style!=null}let mh=class TP{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(nZ(i))this.tags.push(i);else if(rZ(i)){let o=/[^=]*/.exec(i.style)[0];r.indexOf(o)<0&&r.push(o),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let o=t.nodes[i.node];return o.contentMatch.matchType(o)})}parse(t,n={}){let r=new iI(this,n,!1);return r.addAll(t,Hr.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new iI(this,n,!0);return r.addAll(t,Hr.none,n.from,n.to),Dt.maxOpen(r.finish())}matchTag(t,n,r){for(let i=r?this.tags.indexOf(r)+1:0;it.length&&(s.charCodeAt(t.length)!=61||s.slice(t.length+1)!=n))){if(a.getAttrs){let l=a.getAttrs(n);if(l===!1)continue;a.attrs=l||void 0}return a}}}static schemaRules(t){let n=[];function r(i){let o=i.priority==null?50:i.priority,a=0;for(;a{r(a=oI(a)),a.mark||a.ignore||a.clearMark||(a.mark=i)})}for(let i in t.nodes){let o=t.nodes[i].spec.parseDOM;o&&o.forEach(a=>{r(a=oI(a)),a.node||a.ignore||a.mark||(a.node=i)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new TP(t,TP.schemaRules(t)))}};const g4={address:!0,article:!0,aside:!0,blockquote:!0,body:!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},iZ={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},S4={ol:!0,ul:!0},vS=1,CP=2,Z0=4;function rI(e,t,n){return t!=null?(t?vS:0)|(t==="full"?CP:0):e&&e.whitespace=="pre"?vS|CP:n&~Z0}class Pw{constructor(t,n,r,i,o,a){this.type=t,this.attrs=n,this.marks=r,this.solid=i,this.options=a,this.content=[],this.activeMarks=Hr.none,this.match=o||(a&Z0?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(vt.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(t.type))?(this.match=r,i):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&vS)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let o=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=o.withText(o.text.slice(0,o.text.length-i[0].length))}}let n=vt.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(vt.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!g4.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class iI{constructor(t,n,r){this.parser=t,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,o,a=rI(null,n.preserveWhitespace,0)|(r?Z0:0);i?o=new Pw(i.type,i.attrs,Hr.none,!0,n.topMatch||i.type.contentMatch,a):r?o=new Pw(null,null,Hr.none,!0,null,a):o=new Pw(t.schema.topNodeType,null,Hr.none,!0,null,a),this.nodes=[o],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,n){t.nodeType==3?this.addTextNode(t,n):t.nodeType==1&&this.addElement(t,n)}addTextNode(t,n){let r=t.nodeValue,i=this.top,o=i.options&CP?"full":this.localPreserveWS||(i.options&vS)>0,{schema:a}=this.parser;if(o==="full"||i.inlineContext(t)||/[^ \t\r\n\u000c]/.test(r)){if(o)if(o==="full")r=r.replace(/\r\n?/g,` +`);else if(a.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(a.linebreakReplacement.create())){let s=r.split(/\r?\n|\r/);for(let l=0;l!l.clearMark(p)):n=n.concat(this.parser.schema.marks[l.mark].create(l.attrs)),l.consuming===!1)s=l;else break}}return n}addElementByRule(t,n,r,i){let o,a;if(n.node)if(a=this.parser.schema.nodes[n.node],a.isLeaf)this.insertNode(a.create(n.attrs),r,t.nodeName=="BR")||this.leafFallback(t,r);else{let l=this.enter(a,n.attrs||null,r,n.preserveWhitespace);l&&(o=!0,r=l)}else{let l=this.parser.schema.marks[n.mark];r=r.concat(l.create(n.attrs))}let s=this.top;if(a&&a.isLeaf)this.findInside(t);else if(i)this.addElement(t,r,i);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(l=>this.insertNode(l,r,!1));else{let l=t;typeof n.contentElement=="string"?l=t.querySelector(n.contentElement):typeof n.contentElement=="function"?l=n.contentElement(t):n.contentElement&&(l=n.contentElement),this.findAround(t,l,!0),this.addAll(l,r),this.findAround(t,l,!1)}o&&this.sync(s)&&this.open--}addAll(t,n,r,i){let o=r||0;for(let a=r?t.childNodes[r]:t.firstChild,s=i==null?null:t.childNodes[i];a!=s;a=a.nextSibling,++o)this.findAtPoint(t,o),this.addDOM(a,n);this.findAtPoint(t,o)}findPlace(t,n,r){let i,o;for(let a=this.open,s=0;a>=0;a--){let l=this.nodes[a],p=l.findWrapping(t);if(p&&(!i||i.length>p.length+s)&&(i=p,o=l,!p.length))break;if(l.solid){if(r)break;s+=2}}if(!i)return null;this.sync(o);for(let a=0;a(a.type?a.type.allowsMarkType(p.type):aI(p.type,t))?(l=p.addToSet(l),!1):!0),this.nodes.push(new Pw(t,n,l,i,null,s)),this.open++,r}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));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(t){for(let n=this.open;n>=0;n--){if(this.nodes[n]==t)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=vS)}return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)t+=r[i].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(i?0:1),a=(s,l)=>{for(;s>=0;s--){let p=n[s];if(p==""){if(s==n.length-1||s==0)continue;for(;l>=o;l--)if(a(s-1,l))return!0;return!1}else{let c=l>0||l==0&&i?this.nodes[l].type:r&&l>=o?r.node(l-o).type:null;if(!c||c.name!=p&&!c.isInGroup(p))return!1;l--}}return!0};return a(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function oZ(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&S4.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function aZ(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function oI(e){let t={};for(let n in e)t[n]=e[n];return t}function aI(e,t){let n=t.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(e))continue;let o=[],a=s=>{o.push(s);for(let l=0;l{if(o.length||a.marks.length){let s=0,l=0;for(;s=0;i--){let o=this.serializeMark(t.marks[i],t.isInline,n);o&&((o.contentDOM||o.dom).appendChild(r),r=o.dom)}return r}serializeMark(t,n,r={}){let i=this.marks[t.type.name];return i&&Rv(Aw(r),i(t,n),null,t.attrs)}static renderSpec(t,n,r=null,i){return typeof n=="string"?{dom:t.createTextNode(n)}:Rv(t,n,r,i)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new Xc(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=sI(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return sI(t.marks)}}function sI(e){let t={};for(let n in e){let r=e[n].spec.toDOM;r&&(t[n]=r)}return t}function Aw(e){return e.document||window.document}const lI=new WeakMap;function sZ(e){let t=lI.get(e);return t===void 0&&lI.set(e,t=lZ(e)),t}function lZ(e){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.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 a=i.indexOf(" ");a>0&&(n=i.slice(0,a),i=i.slice(a+1));let s,l=n?e.createElementNS(n,i):e.createElement(i),p=t[1],c=1;if(p&&typeof p=="object"&&p.nodeType==null&&!Array.isArray(p)){c=2;for(let u in p)if(p[u]!=null){let d=u.indexOf(" ");d>0?l.setAttributeNS(u.slice(0,d),u.slice(d+1),p[u]):u=="style"&&l.style?l.style.cssText=p[u]:l.setAttribute(u,p[u])}}for(let u=c;uc)throw new RangeError("Content hole must be the only child of its parent node");return{dom:l,contentDOM:l}}else if(typeof d=="string")l.appendChild(e.createTextNode(d));else{let{dom:h,contentDOM:m}=Rv(e,d,n,r);if(l.appendChild(h),m){if(s)throw new RangeError("Multiple content holes");s=m}}}return{dom:l,contentDOM:s}}const y4=65535,w4=Math.pow(2,16);function cZ(e,t){return e+t*w4}function cI(e){return e&y4}function pZ(e){return(e-(e&y4))/w4}const v4=1,k4=2,Mv=4,x4=8;class PP{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&x4)>0}get deletedBefore(){return(this.delInfo&(v4|Mv))>0}get deletedAfter(){return(this.delInfo&(k4|Mv))>0}get deletedAcross(){return(this.delInfo&Mv)>0}}class As{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&As.empty)return As.empty}recover(t){let n=0,r=cI(t);if(!this.inverted)for(let i=0;it)break;let p=this.ranges[s+o],c=this.ranges[s+a],u=l+p;if(t<=u){let d=p?t==l?-1:t==u?1:n:n,h=l+i+(d<0?0:c);if(r)return h;let m=t==(n<0?l:u)?null:cZ(s/3,t-l),S=t==l?k4:t==u?v4:Mv;return(n<0?t!=l:t!=u)&&(S|=x4),new PP(h,S,m)}i+=c-p}return r?t+i:new PP(t+i,0,null)}touches(t,n){let r=0,i=cI(n),o=this.inverted?2:1,a=this.inverted?1:2;for(let s=0;st)break;let p=this.ranges[s+o],c=l+p;if(t<=c&&s==i*3)return!0;r+=this.ranges[s+a]-p}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,o=0;i=0;n--){let i=t.getMirror(n);this.appendMap(t._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let t=new Vp;return t.appendMappingInverted(this),t}map(t,n=1){if(this.mirror)return this._map(t,n,!0);for(let r=this.from;ro&&l!a.isAtom||!s.type.allowsMarkType(this.mark.type)?a:a.mark(this.mark.addToSet(a.marks)),i),n.openStart,n.openEnd);return Zi.fromReplace(t,this.from,this.to,o)}invert(){return new Es(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Hc(n.pos,r.pos,this.mark)}merge(t){return t instanceof Hc&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Hc(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Hc(n.from,n.to,t.markFromJSON(n.mark))}}ua.jsonID("addMark",Hc);class Es extends ua{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new Dt(cR(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),t),n.openStart,n.openEnd);return Zi.fromReplace(t,this.from,this.to,r)}invert(){return new Hc(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Es(n.pos,r.pos,this.mark)}merge(t){return t instanceof Es&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Es(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Es(n.from,n.to,t.markFromJSON(n.mark))}}ua.jsonID("removeMark",Es);class Ad extends ua{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Zi.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Zi.fromReplace(t,this.pos,this.pos+1,new Dt(vt.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let i=0;ir.pos?null:new Xi(n.pos,r.pos,i,o,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Xi(n.from,n.to,n.gapFrom,n.gapTo,Dt.fromJSON(t,n.slice),n.insert,!!n.structure)}}ua.jsonID("replaceAround",Xi);function AP(e,t,n){let r=e.resolve(t),i=n-t,o=r.depth;for(;i>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,i--;if(i>0){let a=r.node(o).maybeChild(r.indexAfter(o));for(;i>0;){if(!a||a.isLeaf)return!0;a=a.firstChild,i--}}return!1}function uZ(e,t,n,r){let i=[],o=[],a,s;e.doc.nodesBetween(t,n,(l,p,c)=>{if(!l.isInline)return;let u=l.marks;if(!r.isInSet(u)&&c.type.allowsMarkType(r.type)){let d=Math.max(p,t),h=Math.min(p+l.nodeSize,n),m=r.addToSet(u);for(let S=0;Se.step(l)),o.forEach(l=>e.step(l))}function dZ(e,t,n,r){let i=[],o=0;e.doc.nodesBetween(t,n,(a,s)=>{if(!a.isInline)return;o++;let l=null;if(r instanceof Px){let p=a.marks,c;for(;c=r.isInSet(p);)(l||(l=[])).push(c),p=c.removeFromSet(p)}else r?r.isInSet(a.marks)&&(l=[r]):l=a.marks;if(l&&l.length){let p=Math.min(s+a.nodeSize,n);for(let c=0;ce.step(new Es(a.from,a.to,a.style)))}function pR(e,t,n,r=n.contentMatch,i=!0){let o=e.doc.nodeAt(t),a=[],s=t+1;for(let l=0;l=0;l--)e.step(a[l])}function bZ(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function tg(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let r=e.depth,i=0,o=0;;--r){let a=e.$from.node(r),s=e.$from.index(r)+i,l=e.$to.indexAfter(r)-o;if(rn;m--)S||r.index(m)>0?(S=!0,c=vt.from(r.node(m).copy(c)),u++):l--;let d=vt.empty,h=0;for(let m=o,S=!1;m>n;m--)S||i.after(m+1)=0;a--){if(r.size){let s=n[a].type.contentMatch.matchFragment(r);if(!s||!s.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=vt.from(n[a].type.create(n[a].attrs,r))}let i=t.start,o=t.end;e.step(new Xi(i,o,i,o,new Dt(r,0,0),n.length,!0))}function SZ(e,t,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=e.steps.length;e.doc.nodesBetween(t,n,(a,s)=>{let l=typeof i=="function"?i(a):i;if(a.isTextblock&&!a.hasMarkup(r,l)&&yZ(e.doc,e.mapping.slice(o).map(s),r)){let p=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",m=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!m?p=!1:!h&&m&&(p=!0)}p===!1&&P4(e,a,s,o),pR(e,e.mapping.slice(o).map(s,1),r,void 0,p===null);let c=e.mapping.slice(o),u=c.map(s,1),d=c.map(s+a.nodeSize,1);return e.step(new Xi(u,d,u+1,d-1,new Dt(vt.from(r.create(l,null,a.marks)),0,0),1,!0)),p===!0&&C4(e,a,s,o),!1}})}function C4(e,t,n,r){t.forEach((i,o)=>{if(i.isText){let a,s=/\r?\n|\r/g;for(;a=s.exec(i.text);){let l=e.mapping.slice(r).map(n+1+o+a.index);e.replaceWith(l,l+1,t.type.schema.linebreakReplacement.create())}}})}function P4(e,t,n,r){t.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let a=e.mapping.slice(r).map(n+1+o);e.replaceWith(a,a+1,t.type.schema.text(` +`))}})}function yZ(e,t,n){let r=e.resolve(t),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function wZ(e,t,n,r,i){let o=e.doc.nodeAt(t);if(!o)throw new RangeError("No node at given position");n||(n=o.type);let a=n.create(r,null,i||o.marks);if(o.isLeaf)return e.replaceWith(t,t+o.nodeSize,a);if(!n.validContent(o.content))throw new RangeError("Invalid content for node type "+n.name);e.step(new Xi(t,t+o.nodeSize,t+1,t+o.nodeSize-1,new Dt(vt.from(a),0,0),1,!0))}function Kp(e,t,n=1,r){let i=e.resolve(t),o=i.depth-n,a=r&&r[r.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!a.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let p=i.depth-1,c=n-2;p>o;p--,c--){let u=i.node(p),d=i.index(p);if(u.type.spec.isolating)return!1;let h=u.content.cutByIndex(d,u.childCount),m=r&&r[c+1];m&&(h=h.replaceChild(0,m.type.create(m.attrs)));let S=r&&r[c]||u;if(!u.canReplace(d+1,u.childCount)||!S.type.validContent(h))return!1}let s=i.indexAfter(o),l=r&&r[0];return i.node(o).canReplaceWith(s,s,l?l.type:i.node(o+1).type)}function vZ(e,t,n=1,r){let i=e.doc.resolve(t),o=vt.empty,a=vt.empty;for(let s=i.depth,l=i.depth-n,p=n-1;s>l;s--,p--){o=vt.from(i.node(s).copy(o));let c=r&&r[p];a=vt.from(c?c.type.create(c.attrs,a):i.node(s).copy(a))}e.step(new yi(t,t,new Dt(o.append(a),n,n),!0))}function Bh(e,t){let n=e.resolve(t),r=n.index();return A4(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function kZ(e,t){t.content.size||e.type.compatibleContent(t.type);let n=e.contentMatchAt(e.childCount),{linebreakReplacement:r}=e.type.schema;for(let i=0;i0?(o=r.node(i+1),s++,a=r.node(i).maybeChild(s)):(o=r.node(i).maybeChild(s-1),a=r.node(i+1)),o&&!o.isTextblock&&A4(o,a)&&r.node(i).canReplace(s,s+1))return t;if(i==0)break;t=n<0?r.before(i):r.after(i)}}function xZ(e,t,n){let r=null,{linebreakReplacement:i}=e.doc.type.schema,o=e.doc.resolve(t-n),a=o.node().type;if(i&&a.inlineContent){let c=a.whitespace=="pre",u=!!a.contentMatch.matchType(i);c&&!u?r=!1:!c&&u&&(r=!0)}let s=e.steps.length;if(r===!1){let c=e.doc.resolve(t+n);P4(e,c.node(),c.before(),s)}a.inlineContent&&pR(e,t+n-1,a,o.node().contentMatchAt(o.index()),r==null);let l=e.mapping.slice(s),p=l.map(t-n);if(e.step(new yi(p,l.map(t+n,-1),Dt.empty,!0)),r===!0){let c=e.doc.resolve(p);C4(e,c.node(),c.before(),e.steps.length)}return e}function TZ(e,t,n){let r=e.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let o=r.index(i);if(r.node(i).canReplaceWith(o,o,n))return r.before(i+1);if(o>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let o=r.indexAfter(i);if(r.node(i).canReplaceWith(o,o,n))return r.after(i+1);if(o=0;a--){let s=a==r.depth?0:r.pos<=(r.start(a+1)+r.end(a+1))/2?-1:1,l=r.index(a)+(s>0?1:0),p=r.node(a),c=!1;if(o==1)c=p.canReplace(l,l,i);else{let u=p.contentMatchAt(l).findWrapping(i.firstChild.type);c=u&&p.canReplaceWith(l,l,u[0])}if(c)return s==0?r.pos:s<0?r.before(a+1):r.after(a+1)}return null}function Ex(e,t,n=t,r=Dt.empty){if(t==n&&!r.size)return null;let i=e.resolve(t),o=e.resolve(n);return R4(i,o,r)?new yi(t,n,r):new CZ(i,o,r).fit()}function R4(e,t,n){return!n.openStart&&!n.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),n.content)}class CZ{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=vt.empty;for(let i=0;i<=t.depth;i++){let o=t.node(i);this.frontier.push({type:o.type,match:o.contentMatchAt(t.indexAfter(i))})}for(let i=t.depth;i>0;i--)this.placed=vt.from(t.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let p=this.findFittable();p?this.placeNodes(p):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(t<0?this.$to:r.doc.resolve(t));if(!i)return null;let o=this.placed,a=r.depth,s=i.depth;for(;a&&s&&o.childCount==1;)o=o.firstChild.content,a--,s--;let l=new Dt(o,a,s);return t>-1?new Xi(r.pos,t,this.$to.pos,this.$to.end(),l,n):l.size||r.pos!=this.$to.pos?new yi(r.pos,i.pos,l):null}findFittable(){let t=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),o.type.spec.isolating&&i<=r){t=r;break}n=o.content}for(let n=1;n<=2;n++)for(let r=n==1?t:this.unplaced.openStart;r>=0;r--){let i,o=null;r?(o=AT(this.unplaced.content,r-1).firstChild,i=o.content):i=this.unplaced.content;let a=i.firstChild;for(let s=this.depth;s>=0;s--){let{type:l,match:p}=this.frontier[s],c,u=null;if(n==1&&(a?p.matchType(a.type)||(u=p.fillBefore(vt.from(a),!1)):o&&l.compatibleContent(o.type)))return{sliceDepth:r,frontierDepth:s,parent:o,inject:u};if(n==2&&a&&(c=p.findWrapping(a.type)))return{sliceDepth:r,frontierDepth:s,parent:o,wrap:c};if(o&&p.matchType(o.type))break}}}openMore(){let{content:t,openStart:n,openEnd:r}=this.unplaced,i=AT(t,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new Dt(t,n+1,Math.max(r,i.size+n>=t.size-r?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,i=AT(t,n);if(i.childCount<=1&&n>0){let o=t.size-n<=n+i.size;this.unplaced=new Dt(E0(t,n-1,1),n-1,o?n-1:r)}else this.unplaced=new Dt(E0(t,n,1),n,r)}placeNodes({sliceDepth:t,frontierDepth:n,parent:r,inject:i,wrap:o}){for(;this.depth>n;)this.closeFrontierNode();if(o)for(let S=0;S1||l==0||S.content.size)&&(u=y,c.push(M4(S.mark(d.allowedMarks(S.marks)),p==1?l:0,p==s.childCount?h:-1)))}let m=p==s.childCount;m||(h=-1),this.placed=R0(this.placed,n,vt.from(c)),this.frontier[n].match=u,m&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let S=0,y=s;S1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],o=n=0;s--){let{match:l,type:p}=this.frontier[s],c=ET(t,s,p,l,!0);if(!c||c.childCount)continue e}return{depth:n,fit:a,move:o?t.doc.resolve(t.after(n+1)):t}}}}close(t){let n=this.findCloseLevel(t);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=R0(this.placed,n.depth,n.fit)),t=n.move;for(let r=n.depth+1;r<=t.depth;r++){let i=t.node(r),o=i.type.contentMatch.fillBefore(i.content,!0,t.index(r));this.openFrontierNode(i.type,i.attrs,o)}return t}openFrontierNode(t,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(t),this.placed=R0(this.placed,this.depth,vt.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(vt.empty,!0);n.childCount&&(this.placed=R0(this.placed,this.frontier.length,n))}}function E0(e,t,n){return t==0?e.cutByIndex(n,e.childCount):e.replaceChild(0,e.firstChild.copy(E0(e.firstChild.content,t-1,n)))}function R0(e,t,n){return t==0?e.append(n):e.replaceChild(e.childCount-1,e.lastChild.copy(R0(e.lastChild.content,t-1,n)))}function AT(e,t){for(let n=0;n1&&(r=r.replaceChild(0,M4(r.firstChild,t-1,r.childCount==1?n-1:0))),t>0&&(r=e.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(e.type.contentMatch.matchFragment(r).fillBefore(vt.empty,!0)))),e.copy(r)}function ET(e,t,n,r,i){let o=e.node(t),a=i?e.indexAfter(t):e.index(t);if(a==o.childCount&&!n.compatibleContent(o.type))return null;let s=r.fillBefore(o.content,!0,a);return s&&!PZ(n,o.content,a)?s:null}function PZ(e,t,n){for(let r=n;r0;d--,h--){let m=i.node(d).type.spec;if(m.defining||m.definingAsContext||m.isolating)break;a.indexOf(d)>-1?s=d:i.before(d)==h&&a.splice(1,0,-d)}let l=a.indexOf(s),p=[],c=r.openStart;for(let d=r.content,h=0;;h++){let m=d.firstChild;if(p.push(m),h==r.openStart)break;d=m.content}for(let d=c-1;d>=0;d--){let h=p[d],m=AZ(h.type);if(m&&!h.sameMarkup(i.node(Math.abs(s)-1)))c=d;else if(m||!h.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let h=(d+c+1)%(r.openStart+1),m=p[h];if(m)for(let S=0;S=0&&(e.replace(t,n,r),!(e.steps.length>u));d--){let h=a[d];h<0||(t=i.before(h),n=o.after(h))}}function N4(e,t,n,r,i){if(tr){let o=i.contentMatchAt(0),a=o.fillBefore(e).append(e);e=a.append(o.matchFragment(a).fillBefore(vt.empty,!0))}return e}function RZ(e,t,n,r){if(!r.isInline&&t==n&&e.doc.resolve(t).parent.content.size){let i=TZ(e.doc,t,r.type);i!=null&&(t=n=i)}e.replaceRange(t,n,new Dt(vt.from(r),0,0))}function MZ(e,t,n){let r=e.doc.resolve(t),i=e.doc.resolve(n);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let a=r.sharedDepth(n),s=!1;for(let l=r.depth;l>a;l--)r.node(l).type.spec.isolating&&(s=!0);for(let l=i.depth;l>a;l--)i.node(l).type.spec.isolating&&(s=!0);if(!s){for(let l=r.depth;l>0&&t==r.start(l);l--)t=r.before(l);for(let l=i.depth;l>0&&n==i.start(l);l--)n=i.before(l);r=e.doc.resolve(t),i=e.doc.resolve(n)}}let o=F4(r,i);for(let a=0;a0&&(l||r.node(s-1).canReplace(r.index(s-1),i.indexAfter(s-1))))return e.delete(r.before(s),i.after(s))}for(let a=1;a<=r.depth&&a<=i.depth;a++)if(t-r.start(a)==r.depth-a&&n>r.end(a)&&i.end(a)-n!=i.depth-a&&r.start(a-1)==i.start(a-1)&&r.node(a-1).canReplace(r.index(a-1),i.index(a-1)))return e.delete(r.before(a),n);e.delete(t,n)}function F4(e,t){let n=[],r=Math.min(e.depth,t.depth);for(let i=r;i>=0;i--){let o=e.start(i);if(ot.pos+(t.depth-i)||e.node(i).type.spec.isolating||t.node(i).type.spec.isolating)break;(o==t.start(i)||i==e.depth&&i==t.depth&&e.parent.inlineContent&&t.parent.inlineContent&&i&&t.start(i-1)==o-1)&&n.push(i)}return n}class Am extends ua{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return Zi.fail("No node at attribute step's position");let r=Object.create(null);for(let o in n.attrs)r[o]=n.attrs[o];r[this.attr]=this.value;let i=n.type.create(r,null,n.marks);return Zi.fromReplace(t,this.pos,this.pos+1,new Dt(vt.from(i),0,n.isLeaf?0:1))}getMap(){return As.empty}invert(t){return new Am(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new Am(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Am(n.pos,n.attr,n.value)}}ua.jsonID("attr",Am);class kS extends ua{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let i in t.attrs)n[i]=t.attrs[i];n[this.attr]=this.value;let r=t.type.create(n,t.content,t.marks);return Zi.ok(r)}getMap(){return As.empty}invert(t){return new kS(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new kS(n.attr,n.value)}}ua.jsonID("docAttr",kS);let jm=class extends Error{};jm=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n};jm.prototype=Object.create(Error.prototype);jm.prototype.constructor=jm;jm.prototype.name="TransformError";class uR{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new Vp}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new jm(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let r=0;r{t=Math.min(t,s),n=Math.max(n,l)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,r=Dt.empty){let i=Ex(this.doc,t,n,r);return i&&this.step(i),this}replaceWith(t,n,r){return this.replace(t,n,new Dt(vt.from(r),0,0))}delete(t,n){return this.replace(t,n,Dt.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return EZ(this,t,n,r),this}replaceRangeWith(t,n,r){return RZ(this,t,n,r),this}deleteRange(t,n){return MZ(this,t,n),this}lift(t,n){return hZ(this,t,n),this}join(t,n=1){return xZ(this,t,n),this}wrap(t,n){return gZ(this,t,n),this}setBlockType(t,n=t,r,i=null){return SZ(this,t,n,r,i),this}setNodeMarkup(t,n,r=null,i){return wZ(this,t,n,r,i),this}setNodeAttribute(t,n,r){return this.step(new Am(t,n,r)),this}setDocAttribute(t,n){return this.step(new kS(t,n)),this}addNodeMark(t,n){return this.step(new Ad(t,n)),this}removeNodeMark(t,n){let r=this.doc.nodeAt(t);if(!r)throw new RangeError("No node at position "+t);if(n instanceof Hr)n.isInSet(r.marks)&&this.step(new xh(t,n));else{let i=r.marks,o,a=[];for(;o=n.isInSet(i);)a.push(new xh(t,o)),i=o.removeFromSet(i);for(let s=a.length-1;s>=0;s--)this.step(a[s])}return this}split(t,n=1,r){return vZ(this,t,n,r),this}addMark(t,n,r){return uZ(this,t,n,r),this}removeMark(t,n,r){return dZ(this,t,n,r),this}clearIncompatible(t,n,r){return pR(this,t,n,r),this}}const RT=Object.create(null);class Sn{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new I4(t.min(n),t.max(n))]}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 t=this.ranges;for(let n=0;n=0;o--){let a=n<0?tm(t.node(0),t.node(o),t.before(o+1),t.index(o),n,r):tm(t.node(0),t.node(o),t.after(o+1),t.index(o)+1,n,r);if(a)return a}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new Qa(t.node(0))}static atStart(t){return tm(t,t,0,0,1)||new Qa(t)}static atEnd(t){return tm(t,t,t.content.size,t.childCount,-1)||new Qa(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=RT[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in RT)throw new RangeError("Duplicate use of selection JSON ID "+t);return RT[t]=n,n.prototype.jsonID=t,n}getBookmark(){return _t.between(this.$anchor,this.$head).getBookmark()}}Sn.prototype.visible=!0;class I4{constructor(t,n){this.$from=t,this.$to=n}}let uI=!1;function dI(e){!uI&&!e.parent.inlineContent&&(uI=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+e.parent.type.name+")"))}class _t extends Sn{constructor(t,n=t){dI(t),dI(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return Sn.near(r);let i=t.resolve(n.map(this.anchor));return new _t(i.parent.inlineContent?i:r,r)}replace(t,n=Dt.empty){if(super.replace(t,n),n==Dt.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof _t&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Rx(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new _t(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let i=t.resolve(n);return new this(i,r==n?i:t.resolve(r))}static between(t,n,r){let i=t.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let o=Sn.findFrom(n,r,!0)||Sn.findFrom(n,-r,!0);if(o)n=o.$head;else return Sn.near(n,r)}return t.parent.inlineContent||(i==0?t=n:(t=(Sn.findFrom(t,-r,!0)||Sn.findFrom(t,r,!0)).$anchor,t.pos0?0:1);i>0?a=0;a+=i){let s=t.child(a);if(s.isAtom){if(!o&&Vt.isSelectable(s))return Vt.create(e,n-(i<0?s.nodeSize:0))}else{let l=tm(e,s,n+i,i<0?s.childCount:0,i,o);if(l)return l}n+=s.nodeSize*i}return null}function bI(e,t,n){let r=e.steps.length-1;if(r{a==null&&(a=c)}),e.setSelection(Sn.near(e.doc.resolve(a),n))}const hI=1,Ew=2,fI=4;class FZ extends uR{constructor(t){super(t.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(t){return this.storedMarks=t,this.updated|=Ew,this}ensureMarks(t){return Hr.sameSet(this.storedMarks||this.selection.$from.marks(),t)||this.setStoredMarks(t),this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Ew)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~Ew,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,n=!0){let r=this.selection;return n&&(t=t.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||Hr.none))),r.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,n,r){let i=this.doc.type.schema;if(n==null)return t?this.replaceSelectionWith(i.text(t),!0):this.deleteSelection();{if(r==null&&(r=n),!t)return this.deleteRange(n,r);let o=this.storedMarks;if(!o){let a=this.doc.resolve(n);o=r==n?a.marks():a.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(t,o)),!this.selection.empty&&this.selection.to==n+t.length&&this.setSelection(Sn.near(this.selection.$to)),this}}setMeta(t,n){return this.meta[typeof t=="string"?t:t.key]=n,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=fI,this}get scrolledIntoView(){return(this.updated&fI)>0}}function mI(e,t){return!t||!e?e:e.bind(t)}class M0{constructor(t,n,r){this.name=t,this.init=mI(n.init,r),this.apply=mI(n.apply,r)}}const IZ=[new M0("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new M0("selection",{init(e,t){return e.selection||Sn.atStart(t.doc)},apply(e){return e.selection}}),new M0("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,r){return r.selection.$cursor?e.storedMarks:null}}),new M0("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}})];class MT{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=IZ.slice(),n&&n.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 M0(r.key,r.spec.state,r))})}}class Ed{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,n=-1){for(let r=0;rr.toJSON())),t&&typeof t=="object")for(let r in t){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=t[r],o=i.spec.state;o&&o.toJSON&&(n[r]=o.toJSON.call(i,this[i.key]))}return n}static fromJSON(t,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let i=new MT(t.schema,t.plugins),o=new Ed(i);return i.fields.forEach(a=>{if(a.name=="doc")o.doc=fh.fromJSON(t.schema,n.doc);else if(a.name=="selection")o.selection=Sn.fromJSON(o.doc,n.selection);else if(a.name=="storedMarks")n.storedMarks&&(o.storedMarks=n.storedMarks.map(t.schema.markFromJSON));else{if(r)for(let s in r){let l=r[s],p=l.spec.state;if(l.key==a.name&&p&&p.fromJSON&&Object.prototype.hasOwnProperty.call(n,s)){o[a.name]=p.fromJSON.call(l,t,n[s],o);return}}o[a.name]=a.init(t,o)}}),o}}function B4(e,t,n){for(let r in e){let i=e[r];i instanceof Function?i=i.bind(t):r=="handleDOMEvents"&&(i=B4(i,t,{})),n[r]=i}return n}class sn{constructor(t){this.spec=t,this.props={},t.props&&B4(t.props,this,this.props),this.key=t.key?t.key.key:L4("plugin")}getState(t){return t[this.key]}}const NT=Object.create(null);function L4(e){return e in NT?e+"$"+ ++NT[e]:(NT[e]=0,e+"$")}class wn{constructor(t="key"){this.key=L4(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const D4=(e,t)=>e.selection.empty?!1:(t&&t(e.tr.deleteSelection().scrollIntoView()),!0);function z4(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock("backward",e):n.parentOffset>0)?null:n}const j4=(e,t,n)=>{let r=z4(e,n);if(!r)return!1;let i=bR(r);if(!i){let a=r.blockRange(),s=a&&tg(a);return s==null?!1:(t&&t(e.tr.lift(a,s).scrollIntoView()),!0)}let o=i.nodeBefore;if(V4(e,i,t,-1))return!0;if(r.parent.content.size==0&&(Om(o,"end")||Vt.isSelectable(o)))for(let a=r.depth;;a--){let s=Ex(e.doc,r.before(a),r.after(a),Dt.empty);if(s&&s.slice.size1)break}return o.isAtom&&i.depth==r.depth-1?(t&&t(e.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView()),!0):!1},BZ=(e,t,n)=>{let r=z4(e,n);if(!r)return!1;let i=bR(r);return i?O4(e,i,t):!1},LZ=(e,t,n)=>{let r=_4(e,n);if(!r)return!1;let i=hR(r);return i?O4(e,i,t):!1};function O4(e,t,n){let r=t.nodeBefore,i=r,o=t.pos-1;for(;!i.isTextblock;o--){if(i.type.spec.isolating)return!1;let c=i.lastChild;if(!c)return!1;i=c}let a=t.nodeAfter,s=a,l=t.pos+1;for(;!s.isTextblock;l++){if(s.type.spec.isolating)return!1;let c=s.firstChild;if(!c)return!1;s=c}let p=Ex(e.doc,o,l,Dt.empty);if(!p||p.from!=o||p instanceof yi&&p.slice.size>=l-o)return!1;if(n){let c=e.tr.step(p);c.setSelection(_t.create(c.doc,o)),n(c.scrollIntoView())}return!0}function Om(e,t,n=!1){for(let r=e;r;r=t=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const $4=(e,t,n)=>{let{$head:r,empty:i}=e.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",e):r.parentOffset>0)return!1;o=bR(r)}let a=o&&o.nodeBefore;return!a||!Vt.isSelectable(a)?!1:(t&&t(e.tr.setSelection(Vt.create(e.doc,o.pos-a.nodeSize)).scrollIntoView()),!0)};function bR(e){if(!e.parent.type.spec.isolating)for(let t=e.depth-1;t>=0;t--){if(e.index(t)>0)return e.doc.resolve(e.before(t+1));if(e.node(t).type.spec.isolating)break}return null}function _4(e,t){let{$cursor:n}=e.selection;return!n||(t?!t.endOfTextblock("forward",e):n.parentOffset{let r=_4(e,n);if(!r)return!1;let i=hR(r);if(!i)return!1;let o=i.nodeAfter;if(V4(e,i,t,1))return!0;if(r.parent.content.size==0&&(Om(o,"start")||Vt.isSelectable(o))){let a=Ex(e.doc,r.before(),r.after(),Dt.empty);if(a&&a.slice.size{let{$head:r,empty:i}=e.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",e):r.parentOffset=0;t--){let n=e.node(t);if(e.index(t)+1{let n=e.selection,r=n instanceof Vt,i;if(r){if(n.node.isTextblock||!Bh(e.doc,n.from))return!1;i=n.from}else if(i=Ax(e.doc,n.from,-1),i==null)return!1;if(t){let o=e.tr.join(i);r&&o.setSelection(Vt.create(o.doc,i-e.doc.resolve(i).nodeBefore.nodeSize)),t(o.scrollIntoView())}return!0},zZ=(e,t)=>{let n=e.selection,r;if(n instanceof Vt){if(n.node.isTextblock||!Bh(e.doc,n.to))return!1;r=n.to}else if(r=Ax(e.doc,n.to,1),r==null)return!1;return t&&t(e.tr.join(r).scrollIntoView()),!0},jZ=(e,t)=>{let{$from:n,$to:r}=e.selection,i=n.blockRange(r),o=i&&tg(i);return o==null?!1:(t&&t(e.tr.lift(i,o).scrollIntoView()),!0)},G4=(e,t)=>{let{$head:n,$anchor:r}=e.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(t&&t(e.tr.insertText(` +`).scrollIntoView()),!0)};function fR(e){for(let t=0;t{let{$head:n,$anchor:r}=e.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),o=n.indexAfter(-1),a=fR(i.contentMatchAt(o));if(!a||!i.canReplaceWith(o,o,a))return!1;if(t){let s=n.after(),l=e.tr.replaceWith(s,s,a.createAndFill());l.setSelection(Sn.near(l.doc.resolve(s),1)),t(l.scrollIntoView())}return!0},U4=(e,t)=>{let n=e.selection,{$from:r,$to:i}=n;if(n instanceof Qa||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=fR(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(t){let a=(!r.parentOffset&&i.index(){let{$cursor:n}=e.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let o=n.before();if(Kp(e.doc,o))return t&&t(e.tr.split(o).scrollIntoView()),!0}let r=n.blockRange(),i=r&&tg(r);return i==null?!1:(t&&t(e.tr.lift(r,i).scrollIntoView()),!0)};function $Z(e){return(t,n)=>{let{$from:r,$to:i}=t.selection;if(t.selection instanceof Vt&&t.selection.node.isBlock)return!r.parentOffset||!Kp(t.doc,r.pos)?!1:(n&&n(t.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],a,s,l=!1,p=!1;for(let h=r.depth;;h--)if(r.node(h).isBlock){l=r.end(h)==r.pos+(r.depth-h),p=r.start(h)==r.pos-(r.depth-h),s=fR(r.node(h-1).contentMatchAt(r.indexAfter(h-1))),o.unshift(l&&s?{type:s}:null),a=h;break}else{if(h==1)return!1;o.unshift(null)}let c=t.tr;(t.selection instanceof _t||t.selection instanceof Qa)&&c.deleteSelection();let u=c.mapping.map(r.pos),d=Kp(c.doc,u,o.length,o);if(d||(o[0]=s?{type:s}:null,d=Kp(c.doc,u,o.length,o)),!d)return!1;if(c.split(u,o.length,o),!l&&p&&r.node(a).type!=s){let h=c.mapping.map(r.before(a)),m=c.doc.resolve(h);s&&r.node(a-1).canReplaceWith(m.index(),m.index()+1,s)&&c.setNodeMarkup(c.mapping.map(r.before(a)),s)}return n&&n(c.scrollIntoView()),!0}}const _Z=$Z(),HZ=(e,t)=>{let{$from:n,to:r}=e.selection,i,o=n.sharedDepth(r);return o==0?!1:(i=n.before(o),t&&t(e.tr.setSelection(Vt.create(e.doc,i))),!0)};function WZ(e,t,n){let r=t.nodeBefore,i=t.nodeAfter,o=t.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&t.parent.canReplace(o-1,o)?(n&&n(e.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(o,o+1)||!(i.isTextblock||Bh(e.doc,t.pos))?!1:(n&&n(e.tr.join(t.pos).scrollIntoView()),!0)}function V4(e,t,n,r){let i=t.nodeBefore,o=t.nodeAfter,a,s,l=i.type.spec.isolating||o.type.spec.isolating;if(!l&&WZ(e,t,n))return!0;let p=!l&&t.parent.canReplace(t.index(),t.index()+1);if(p&&(a=(s=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&s.matchType(a[0]||o.type).validEnd){if(n){let h=t.pos+o.nodeSize,m=vt.empty;for(let w=a.length-1;w>=0;w--)m=vt.from(a[w].create(null,m));m=vt.from(i.copy(m));let S=e.tr.step(new Xi(t.pos-1,h,t.pos,h,new Dt(m,1,0),a.length,!0)),y=S.doc.resolve(h+2*a.length);y.nodeAfter&&y.nodeAfter.type==i.type&&Bh(S.doc,y.pos)&&S.join(y.pos),n(S.scrollIntoView())}return!0}let c=o.type.spec.isolating||r>0&&l?null:Sn.findFrom(t,1),u=c&&c.$from.blockRange(c.$to),d=u&&tg(u);if(d!=null&&d>=t.depth)return n&&n(e.tr.lift(u,d).scrollIntoView()),!0;if(p&&Om(o,"start",!0)&&Om(i,"end")){let h=i,m=[];for(;m.push(h),!h.isTextblock;)h=h.lastChild;let S=o,y=1;for(;!S.isTextblock;S=S.firstChild)y++;if(h.canReplace(h.childCount,h.childCount,S.content)){if(n){let w=vt.empty;for(let x=m.length-1;x>=0;x--)w=vt.from(m[x].copy(w));let v=e.tr.step(new Xi(t.pos-m.length,t.pos+o.nodeSize,t.pos+y,t.pos+o.nodeSize-y,new Dt(w,m.length,0),0,!0));n(v.scrollIntoView())}return!0}}return!1}function K4(e){return function(t,n){let r=t.selection,i=e<0?r.$from:r.$to,o=i.depth;for(;i.node(o).isInline;){if(!o)return!1;o--}return i.node(o).isTextblock?(n&&n(t.tr.setSelection(_t.create(t.doc,e<0?i.start(o):i.end(o)))),!0):!1}}const GZ=K4(-1),UZ=K4(1);function qZ(e,t=null){return function(n,r){let{$from:i,$to:o}=n.selection,a=i.blockRange(o),s=a&&T4(a,e,t);return s?(r&&r(n.tr.wrap(a,s).scrollIntoView()),!0):!1}}function gI(e,t=null){return function(n,r){let i=!1;for(let o=0;o{if(i)return!1;if(!(!l.isTextblock||l.hasMarkup(e,t)))if(l.type==e)i=!0;else{let c=n.doc.resolve(p),u=c.index();i=c.parent.canReplaceWith(u,u+1,e)}})}if(!i)return!1;if(r){let o=n.tr;for(let a=0;a=2&&t.$from.node(t.depth-1).type.compatibleContent(n)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let l=a.resolve(t.start-2);o=new ok(l,l,t.depth),t.endIndex=0;c--)o=vt.from(n[c].type.create(n[c].attrs,o));e.step(new Xi(t.start-(r?2:0),t.end,t.start,t.end,new Dt(o,0,0),n.length,!0));let a=0;for(let c=0;ca.childCount>0&&a.firstChild.type==e);return o?n?r.node(o.depth-1).type==e?YZ(t,n,e,o):JZ(t,n,o):!0:!1}}function YZ(e,t,n,r){let i=e.tr,o=r.end,a=r.$to.end(r.depth);oS;m--)h-=i.child(m).nodeSize,r.delete(h-1,h+1);let o=r.doc.resolve(n.start),a=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let s=n.startIndex==0,l=n.endIndex==i.childCount,p=o.node(-1),c=o.index(-1);if(!p.canReplace(c+(s?0:1),c+1,a.content.append(l?vt.empty:vt.from(i))))return!1;let u=o.pos,d=u+a.nodeSize;return r.step(new Xi(u-(s?1:0),d+(l?1:0),u+1,d-1,new Dt((s?vt.empty:vt.from(i.copy(vt.empty))).append(l?vt.empty:vt.from(i.copy(vt.empty))),s?0:1,l?0:1),s?0:1)),t(r.scrollIntoView()),!0}function QZ(e){return function(t,n){let{$from:r,$to:i}=t.selection,o=r.blockRange(i,p=>p.childCount>0&&p.firstChild.type==e);if(!o)return!1;let a=o.startIndex;if(a==0)return!1;let s=o.parent,l=s.child(a-1);if(l.type!=e)return!1;if(n){let p=l.lastChild&&l.lastChild.type==s.type,c=vt.from(p?e.create():null),u=new Dt(vt.from(e.create(null,vt.from(s.type.create(null,c)))),p?3:1,0),d=o.start,h=o.end;n(t.tr.step(new Xi(d-(p?3:1),h,d,h,u,1,!0)).scrollIntoView())}return!0}}const Bo=function(e){for(var t=0;;t++)if(e=e.previousSibling,!e)return t},$m=function(e){let t=e.assignedSlot||e.parentNode;return t&&t.nodeType==11?t.host:t};let EP=null;const Fp=function(e,t,n){let r=EP||(EP=document.createRange());return r.setEnd(e,n??e.nodeValue.length),r.setStart(e,t||0),r},eX=function(){EP=null},Th=function(e,t,n,r){return n&&(SI(e,t,n,r,-1)||SI(e,t,n,r,1))},tX=/^(img|br|input|textarea|hr)$/i;function SI(e,t,n,r,i){for(var o;;){if(e==n&&t==r)return!0;if(t==(i<0?0:ll(e))){let a=e.parentNode;if(!a||a.nodeType!=1||ty(e)||tX.test(e.nodeName)||e.contentEditable=="false")return!1;t=Bo(e)+(i<0?0:1),e=a}else if(e.nodeType==1){let a=e.childNodes[t+(i<0?-1:0)];if(a.nodeType==1&&a.contentEditable=="false")if(!((o=a.pmViewDesc)===null||o===void 0)&&o.ignoreForSelection)t+=i;else return!1;else e=a,t=i<0?ll(e):0}else return!1}}function ll(e){return e.nodeType==3?e.nodeValue.length:e.childNodes.length}function nX(e,t){for(;;){if(e.nodeType==3&&t)return e;if(e.nodeType==1&&t>0){if(e.contentEditable=="false")return null;e=e.childNodes[t-1],t=ll(e)}else if(e.parentNode&&!ty(e))t=Bo(e),e=e.parentNode;else return null}}function rX(e,t){for(;;){if(e.nodeType==3&&t2),al=_m||(Vc?/Mac/.test(Vc.platform):!1),Y4=Vc?/Win/.test(Vc.platform):!1,Op=/Android \d/.test(Kd),ny=!!yI&&"webkitFontSmoothing"in yI.documentElement.style,sX=ny?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function lX(e){let t=e.defaultView&&e.defaultView.visualViewport;return t?{left:0,right:t.width,top:0,bottom:t.height}:{left:0,right:e.documentElement.clientWidth,top:0,bottom:e.documentElement.clientHeight}}function Ep(e,t){return typeof e=="number"?e:e[t]}function cX(e){let t=e.getBoundingClientRect(),n=t.width/e.offsetWidth||1,r=t.height/e.offsetHeight||1;return{left:t.left,right:t.left+e.clientWidth*n,top:t.top,bottom:t.top+e.clientHeight*r}}function wI(e,t,n){if(!FP(t)&&t.left==0)return;let r=e.someProp("scrollThreshold")||0,i=e.someProp("scrollMargin")||5,o=e.dom.ownerDocument;for(let a=n||e.dom;a;){if(a.nodeType!=1){a=$m(a);continue}let s=a,l=s==o.body,p=l?lX(o):cX(s),c=0,u=0;if(t.topp.bottom-Ep(r,"bottom")&&(u=t.bottom-t.top>p.bottom-p.top?t.top+Ep(i,"top")-p.top:t.bottom-p.bottom+Ep(i,"bottom")),t.leftp.right-Ep(r,"right")&&(c=t.right-p.right+Ep(i,"right")),c||u)if(l)o.defaultView.scrollBy(c,u);else{let h=s.scrollLeft,m=s.scrollTop;u&&(s.scrollTop+=u),c&&(s.scrollLeft+=c);let S=s.scrollLeft-h,y=s.scrollTop-m;t={left:t.left-S,top:t.top-y,right:t.right-S,bottom:t.bottom-y}}let d=l?"fixed":getComputedStyle(a).position;if(/^(fixed|sticky)$/.test(d))break;a=d=="absolute"?a.offsetParent:$m(a)}}function pX(e){let t=e.dom.getBoundingClientRect(),n=Math.max(0,t.top),r,i;for(let o=(t.left+t.right)/2,a=n+1;a=n-20){r=s,i=l.top;break}}return{refDOM:r,refTop:i,stack:J4(e.dom)}}function J4(e){let t=[],n=e.ownerDocument;for(let r=e;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),e!=n);r=$m(r));return t}function uX({refDOM:e,refTop:t,stack:n}){let r=e?e.getBoundingClientRect().top:0;Q4(n,r==0?0:r-t)}function Q4(e,t){for(let n=0;n=s){a=Math.max(m.bottom,a),s=Math.min(m.top,s);let S=m.left>t.left?m.left-t.left:m.right=(m.left+m.right)/2?1:0));continue}}else m.top>t.top&&!l&&m.left<=t.left&&m.right>=t.left&&(l=c,p={left:Math.max(m.left,Math.min(m.right,t.left)),top:m.top});!n&&(t.left>=m.right&&t.top>=m.top||t.left>=m.left&&t.top>=m.bottom)&&(o=u+1)}}return!n&&l&&(n=l,i=p,r=0),n&&n.nodeType==3?bX(n,i):!n||r&&n.nodeType==1?{node:e,offset:o}:e$(n,i)}function bX(e,t){let n=e.nodeValue.length,r=document.createRange(),i;for(let o=0;o=(a.left+a.right)/2?1:0)};break}}return r.detach(),i||{node:e,offset:0}}function gR(e,t){return e.left>=t.left-1&&e.left<=t.right+1&&e.top>=t.top-1&&e.top<=t.bottom+1}function hX(e,t){let n=e.parentNode;return n&&/^li$/i.test(n.nodeName)&&t.left(a.left+a.right)/2?1:-1}return e.docView.posFromDOM(r,i,o)}function mX(e,t,n,r){let i=-1;for(let o=t,a=!1;o!=e.dom;){let s=e.docView.nearestDesc(o,!0),l;if(!s)return null;if(s.dom.nodeType==1&&(s.node.isBlock&&s.parent||!s.contentDOM)&&((l=s.dom.getBoundingClientRect()).width||l.height)&&(s.node.isBlock&&s.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(s.dom.nodeName)&&(!a&&l.left>r.left||l.top>r.top?i=s.posBefore:(!a&&l.right-1?i:e.docView.posFromDOM(t,n,-1)}function t$(e,t,n){let r=e.childNodes.length;if(r&&n.topt.top&&i++}let p;ny&&i&&r.nodeType==1&&(p=r.childNodes[i-1]).nodeType==1&&p.contentEditable=="false"&&p.getBoundingClientRect().top>=t.top&&i--,r==e.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&t.top>r.lastChild.getBoundingClientRect().bottom?s=e.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(s=mX(e,r,i,t))}s==null&&(s=fX(e,a,t));let l=e.docView.nearestDesc(a,!0);return{pos:s,inside:l?l.posAtStart-l.border:-1}}function FP(e){return e.top=0&&i==r.nodeValue.length?(l--,c=1):n<0?l--:p++,i0(md(Fp(r,l,p),c),c<0)}if(!e.state.doc.resolve(t-(o||0)).parent.inlineContent){if(o==null&&i&&(n<0||i==ll(r))){let l=r.childNodes[i-1];if(l.nodeType==1)return FT(l.getBoundingClientRect(),!1)}if(o==null&&i=0)}if(o==null&&i&&(n<0||i==ll(r))){let l=r.childNodes[i-1],p=l.nodeType==3?Fp(l,ll(l)-(a?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(p)return i0(md(p,1),!1)}if(o==null&&i=0)}function i0(e,t){if(e.width==0)return e;let n=t?e.left:e.right;return{top:e.top,bottom:e.bottom,left:n,right:n}}function FT(e,t){if(e.height==0)return e;let n=t?e.top:e.bottom;return{top:n,bottom:n,left:e.left,right:e.right}}function r$(e,t,n){let r=e.state,i=e.root.activeElement;r!=t&&e.updateState(t),i!=e.dom&&e.focus();try{return n()}finally{r!=t&&e.updateState(r),i!=e.dom&&i&&i.focus()}}function yX(e,t,n){let r=t.selection,i=n=="up"?r.$from:r.$to;return r$(e,t,()=>{let{node:o}=e.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let s=e.docView.nearestDesc(o,!0);if(!s)break;if(s.node.isBlock){o=s.contentDOM||s.dom;break}o=s.dom.parentNode}let a=n$(e,i.pos,1);for(let s=o.firstChild;s;s=s.nextSibling){let l;if(s.nodeType==1)l=s.getClientRects();else if(s.nodeType==3)l=Fp(s,0,s.nodeValue.length).getClientRects();else continue;for(let p=0;pc.top+1&&(n=="up"?a.top-c.top>(c.bottom-a.top)*2:c.bottom-a.bottom>(a.bottom-c.top)*2))return!1}}return!0})}const wX=/[\u0590-\u08ac]/;function vX(e,t,n){let{$head:r}=t.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,o=!i,a=i==r.parent.content.size,s=e.domSelection();return s?!wX.test(r.parent.textContent)||!s.modify?n=="left"||n=="backward"?o:a:r$(e,t,()=>{let{focusNode:l,focusOffset:p,anchorNode:c,anchorOffset:u}=e.domSelectionRange(),d=s.caretBidiLevel;s.modify("move",n,"character");let h=r.depth?e.docView.domAfterPos(r.before()):e.dom,{focusNode:m,focusOffset:S}=e.domSelectionRange(),y=m&&!h.contains(m.nodeType==1?m:m.parentNode)||l==m&&p==S;try{s.collapse(c,u),l&&(l!=c||p!=u)&&s.extend&&s.extend(l,p)}catch{}return d!=null&&(s.caretBidiLevel=d),y}):r.pos==r.start()||r.pos==r.end()}let vI=null,kI=null,xI=!1;function kX(e,t,n){return vI==t&&kI==n?xI:(vI=t,kI=n,xI=n=="up"||n=="down"?yX(e,t,n):vX(e,t,n))}const fl=0,TI=1,oh=2,sc=3;class ry{constructor(t,n,r,i){this.parent=t,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=fl,r.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,n,r){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let n=0;nBo(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=t.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let o=t;;o=o.parentNode){if(o==this.dom){i=!1;break}if(o.previousSibling)break}if(i==null&&n==t.childNodes.length)for(let o=t;;o=o.parentNode){if(o==this.dom){i=!0;break}if(o.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(t,n=!1){for(let r=!0,i=t;i;i=i.parentNode){let o=this.getDesc(i),a;if(o&&(!n||o.node))if(r&&(a=o.nodeDOM)&&!(a.nodeType==1?a.contains(t.nodeType==1?t:t.parentNode):a==t))r=!1;else return o}}getDesc(t){let n=t.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(t,n,r){for(let i=t;i;i=i.parentNode){let o=this.getDesc(i);if(o)return o.localPosFromDOM(t,n,r)}return-1}descAt(t){for(let n=0,r=0;nt||a instanceof o$){i=t-o;break}o=s}if(i)return this.children[r].domFromPos(i-this.children[r].border,n);for(let o;r&&!(o=this.children[r-1]).size&&o instanceof i$&&o.side>=0;r--);if(n<=0){let o,a=!0;for(;o=r?this.children[r-1]:null,!(!o||o.dom.parentNode==this.contentDOM);r--,a=!1);return o&&n&&a&&!o.border&&!o.domAtom?o.domFromPos(o.size,n):{node:this.contentDOM,offset:o?Bo(o.dom)+1:0}}else{let o,a=!0;for(;o=r=c&&n<=p-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(t,n,c);t=a;for(let u=s;u>0;u--){let d=this.children[u-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=Bo(d.dom)+1;break}t-=d.size}i==-1&&(i=0)}if(i>-1&&(p>n||s==this.children.length-1)){n=p;for(let c=s+1;cm&&an){let m=s;s=l,l=m}let h=document.createRange();h.setEnd(l.node,l.offset),h.setStart(s.node,s.offset),p.removeAllRanges(),p.addRange(h)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,i=0;i=r:tr){let s=r+o.border,l=a-o.border;if(t>=s&&n<=l){this.dirty=t==r||n==a?oh:TI,t==s&&n==l&&(o.contentLost||o.dom.parentNode!=this.contentDOM)?o.dirty=sc:o.markDirty(t-s,n-s);return}else o.dirty=o.dom==o.contentDOM&&o.dom.parentNode==this.contentDOM&&!o.children.length?oh:sc}r=a}this.dirty=oh}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?oh:TI;n.dirty{if(!o)return i;if(o.parent)return o.parent.posBeforeChild(o)})),!n.type.spec.raw){if(a.nodeType!=1){let s=document.createElement("span");s.appendChild(a),a=s}a.contentEditable="false",a.classList.add("ProseMirror-widget")}super(t,[],a,null),this.widget=n,this.widget=n,o=this}matchesWidget(t){return this.dirty==fl&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let n=this.widget.spec.stopEvent;return n?n(t):!1}ignoreMutation(t){return t.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}}class xX extends ry{constructor(t,n,r,i){super(t,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(t,n){return t!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class Dd extends ry{constructor(t,n,r,i,o){super(t,[],r,i),this.mark=n,this.spec=o}static create(t,n,r,i){let o=i.nodeViews[n.type.name],a=o&&o(n,i,r);return(!a||!a.dom)&&(a=Xc.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Dd(t,n,a.dom,a.contentDOM||a.dom,a)}parseRule(){return this.dirty&sc||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=sc&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=fl){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(o=BP(o,0,t,r));for(let s=0;s{if(!l)return a;if(l.parent)return l.parent.posBeforeChild(l)},r,i),c=p&&p.dom,u=p&&p.contentDOM;if(n.isText){if(!c)c=document.createTextNode(n.text);else if(c.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else c||({dom:c,contentDOM:u}=Xc.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!u&&!n.isText&&c.nodeName!="BR"&&(c.hasAttribute("contenteditable")||(c.contentEditable="false"),n.type.spec.draggable&&(c.draggable=!0));let d=c;return c=l$(c,r,n),p?l=new TX(t,n,r,i,c,u||null,d,p):n.isText?new Nx(t,n,r,i,c,d):new zd(t,n,r,i,c,u||null,d)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){t.contentElement=r.dom.parentNode;break}}t.contentElement||(t.getContent=()=>vt.empty)}return t}matchesNode(t,n,r){return this.dirty==fl&&t.eq(this.node)&&sk(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,n){let r=this.node.inlineContent,i=n,o=t.composing?this.localCompositionInfo(t,n):null,a=o&&o.pos>-1?o:null,s=o&&o.pos<0,l=new PX(this,a&&a.node,t);RX(this.node,this.innerDeco,(p,c,u)=>{p.spec.marks?l.syncToMarks(p.spec.marks,r,t,c):p.type.side>=0&&!u&&l.syncToMarks(c==this.node.childCount?Hr.none:this.node.child(c).marks,r,t,c),l.placeWidget(p,t,i)},(p,c,u,d)=>{l.syncToMarks(p.marks,r,t,d);let h;l.findNodeMatch(p,c,u,d)||s&&t.state.selection.from>i&&t.state.selection.to-1&&l.updateNodeAt(p,c,u,h,t)||l.updateNextNode(p,c,u,t,d,i)||l.addNode(p,c,u,t,i),i+=p.nodeSize}),l.syncToMarks([],r,t,0),this.node.isTextblock&&l.addTextblockHacks(),l.destroyRest(),(l.changed||this.dirty==oh)&&(a&&this.protectLocalComposition(t,a),a$(this.contentDOM,this.children,t),_m&&MX(this.dom))}localCompositionInfo(t,n){let{from:r,to:i}=t.state.selection;if(!(t.state.selection instanceof _t)||rn+this.node.content.size)return null;let o=t.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let a=o.nodeValue,s=NX(this.node.content,a,r-n,i-n);return s<0?null:{node:o,pos:s,text:a}}else return{node:o,pos:-1,text:""}}protectLocalComposition(t,{node:n,pos:r,text:i}){if(this.getDesc(n))return;let o=n;for(;o.parentNode!=this.contentDOM;o=o.parentNode){for(;o.previousSibling;)o.parentNode.removeChild(o.previousSibling);for(;o.nextSibling;)o.parentNode.removeChild(o.nextSibling);o.pmViewDesc&&(o.pmViewDesc=void 0)}let a=new xX(this,o,n,i);t.input.compositionNodes.push(a),this.children=BP(this.children,r,r+i.length,t,a)}update(t,n,r,i){return this.dirty==sc||!t.sameMarkup(this.node)?!1:(this.updateInner(t,n,r,i),!0)}updateInner(t,n,r,i){this.updateOuterDeco(n),this.node=t,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=fl}updateOuterDeco(t){if(sk(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=s$(this.dom,this.nodeDOM,IP(this.outerDeco,this.node,n),IP(t,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}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 CI(e,t,n,r,i){l$(r,t,e);let o=new zd(void 0,e,t,n,r,r,r);return o.contentDOM&&o.updateChildren(i,0),o}class Nx extends zd{constructor(t,n,r,i,o,a){super(t,n,r,i,o,null,a)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,n,r,i){return this.dirty==sc||this.dirty!=fl&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=fl||t.text!=this.node.text)&&t.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=t.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=t,this.dirty=fl,!0)}inParent(){let t=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,n,r){return t==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(t,n,r)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,n,r){let i=this.node.cut(t,n),o=document.createTextNode(i.text);return new Nx(this.parent,i,this.outerDeco,this.innerDeco,o,o)}markDirty(t,n){super.markDirty(t,n),this.dom!=this.nodeDOM&&(t==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=sc)}get domAtom(){return!1}isText(t){return this.node.text==t}}class o$ extends ry{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==fl&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class TX extends zd{constructor(t,n,r,i,o,a,s,l){super(t,n,r,i,o,a,s),this.spec=l}update(t,n,r,i){if(this.dirty==sc)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let o=this.spec.update(t,n,r);return o&&this.updateInner(t,n,r,i),o}else return!this.contentDOM&&!t.isLeaf?!1:super.update(t,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,n,r,i){this.spec.setSelection?this.spec.setSelection(t,n,r.root):super.setSelection(t,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(t){return this.spec.stopEvent?this.spec.stopEvent(t):!1}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function a$(e,t,n){let r=e.firstChild,i=!1;for(let o=0;o>1,s=Math.min(a,t.length);for(;o-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let c=Dd.create(this.top,t[a],n,r);this.top.children.splice(this.index,0,c),this.top=c,this.changed=!0}this.index=0,a++}}findNodeMatch(t,n,r,i){let o=-1,a;if(i>=this.preMatch.index&&(a=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&a.matchesNode(t,n,r))o=this.top.children.indexOf(a,this.index);else for(let s=this.index,l=Math.min(this.top.children.length,s+5);s0;){let s;for(;;)if(r){let p=n.children[r-1];if(p instanceof Dd)n=p,r=p.children.length;else{s=p,r--;break}}else{if(n==t)break e;r=n.parent.children.indexOf(n),n=n.parent}let l=s.node;if(l){if(l!=e.child(i-1))break;--i,o.set(s,i),a.push(s)}}return{index:i,matched:o,matches:a.reverse()}}function EX(e,t){return e.type.side-t.type.side}function RX(e,t,n,r){let i=t.locals(e),o=0;if(i.length==0){for(let p=0;po;)s.push(i[a++]);let m=o+d.nodeSize;if(d.isText){let y=m;a!y.inline):s.slice();r(d,S,t.forChild(o,d),h),o=m}}function MX(e){if(e.nodeName=="UL"||e.nodeName=="OL"){let t=e.style.cssText;e.style.cssText=t+"; list-style: square !important",window.getComputedStyle(e).listStyle,e.style.cssText=t}}function NX(e,t,n,r){for(let i=0,o=0;i=n){if(o>=r&&l.slice(r-t.length-s,r-s)==t)return r-t.length;let p=s=0&&p+t.length+s>=n)return s+p;if(n==r&&l.length>=r+t.length-s&&l.slice(r-s,r-s+t.length)==t)return r}}return-1}function BP(e,t,n,r,i){let o=[];for(let a=0,s=0;a=n||c<=t?o.push(l):(pn&&o.push(l.slice(n-p,l.size,r)))}return o}function SR(e,t=null){let n=e.domSelectionRange(),r=e.state.doc;if(!n.focusNode)return null;let i=e.docView.nearestDesc(n.focusNode),o=i&&i.size==0,a=e.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(a<0)return null;let s=r.resolve(a),l,p;if(Mx(n)){for(l=a;i&&!i.node;)i=i.parent;let u=i.node;if(i&&u.isAtom&&Vt.isSelectable(u)&&i.parent&&!(u.isInline&&iX(n.focusNode,n.focusOffset,i.dom))){let d=i.posBefore;p=new Vt(a==d?s:r.resolve(d))}}else{if(n instanceof e.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let u=a,d=a;for(let h=0;h{(n.anchorNode!=r||n.anchorOffset!=i)&&(t.removeEventListener("selectionchange",e.input.hideSelectionGuard),setTimeout(()=>{(!c$(e)||e.state.selection.visible)&&e.dom.classList.remove("ProseMirror-hideselection")},20))})}function IX(e){let t=e.domSelection();if(!t)return;let n=e.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,Bo(n)+1):t.collapse(n,0),!r&&!e.state.selection.visible&&es&&Ld<=11&&(n.disabled=!0,n.disabled=!1)}function p$(e,t){if(t instanceof Vt){let n=e.docView.descAt(t.from);n!=e.lastSelectedViewDesc&&(MI(e),n&&n.selectNode(),e.lastSelectedViewDesc=n)}else MI(e)}function MI(e){e.lastSelectedViewDesc&&(e.lastSelectedViewDesc.parent&&e.lastSelectedViewDesc.deselectNode(),e.lastSelectedViewDesc=void 0)}function yR(e,t,n,r){return e.someProp("createSelectionBetween",i=>i(e,t,n))||_t.between(t,n,r)}function NI(e){return e.editable&&!e.hasFocus()?!1:u$(e)}function u$(e){let t=e.domSelectionRange();if(!t.anchorNode)return!1;try{return e.dom.contains(t.anchorNode.nodeType==3?t.anchorNode.parentNode:t.anchorNode)&&(e.editable||e.dom.contains(t.focusNode.nodeType==3?t.focusNode.parentNode:t.focusNode))}catch{return!1}}function BX(e){let t=e.docView.domFromPos(e.state.selection.anchor,0),n=e.domSelectionRange();return Th(t.node,t.offset,n.anchorNode,n.anchorOffset)}function LP(e,t){let{$anchor:n,$head:r}=e.selection,i=t>0?n.max(r):n.min(r),o=i.parent.inlineContent?i.depth?e.doc.resolve(t>0?i.after():i.before()):null:i;return o&&Sn.findFrom(o,t)}function Sd(e,t){return e.dispatch(e.state.tr.setSelection(t).scrollIntoView()),!0}function FI(e,t,n){let r=e.state.selection;if(r instanceof _t)if(n.indexOf("s")>-1){let{$head:i}=r,o=i.textOffset?null:t<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let a=e.state.doc.resolve(i.pos+o.nodeSize*(t<0?-1:1));return Sd(e,new _t(r.$anchor,a))}else if(r.empty){if(e.endOfTextblock(t>0?"forward":"backward")){let i=LP(e.state,t);return i&&i instanceof Vt?Sd(e,i):!1}else if(!(al&&n.indexOf("m")>-1)){let i=r.$head,o=i.textOffset?null:t<0?i.nodeBefore:i.nodeAfter,a;if(!o||o.isText)return!1;let s=t<0?i.pos-o.nodeSize:i.pos;return o.isAtom||(a=e.docView.descAt(s))&&!a.contentDOM?Vt.isSelectable(o)?Sd(e,new Vt(t<0?e.state.doc.resolve(i.pos-o.nodeSize):i)):ny?Sd(e,new _t(e.state.doc.resolve(t<0?s:s+o.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Vt&&r.node.isInline)return Sd(e,new _t(t>0?r.$to:r.$from));{let i=LP(e.state,t);return i?Sd(e,i):!1}}}function lk(e){return e.nodeType==3?e.nodeValue.length:e.childNodes.length}function Y0(e,t){let n=e.pmViewDesc;return n&&n.size==0&&(t<0||e.nextSibling||e.nodeName!="BR")}function zf(e,t){return t<0?LX(e):DX(e)}function LX(e){let t=e.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let i,o,a=!1;for(hl&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let s=n.childNodes[r-1];if(Y0(s,-1))i=n,o=--r;else if(s.nodeType==3)n=s,r=n.nodeValue.length;else break}}else{if(d$(n))break;{let s=n.previousSibling;for(;s&&Y0(s,-1);)i=n.parentNode,o=Bo(s),s=s.previousSibling;if(s)n=s,r=lk(n);else{if(n=n.parentNode,n==e.dom)break;r=0}}}a?DP(e,n,r):i&&DP(e,i,o)}function DX(e){let t=e.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let i=lk(n),o,a;for(;;)if(r{e.state==i&&Zp(e)},50)}function II(e,t){let n=e.state.doc.resolve(t);if(!(go||Y4)&&n.parent.inlineContent){let i=e.coordsAtPos(t);if(t>n.start()){let o=e.coordsAtPos(t-1),a=(o.top+o.bottom)/2;if(a>i.top&&a1)return o.lefti.top&&a1)return o.left>i.left?"ltr":"rtl"}}return getComputedStyle(e.dom).direction=="rtl"?"rtl":"ltr"}function BI(e,t,n){let r=e.state.selection;if(r instanceof _t&&!r.empty||n.indexOf("s")>-1||al&&n.indexOf("m")>-1)return!1;let{$from:i,$to:o}=r;if(!i.parent.inlineContent||e.endOfTextblock(t<0?"up":"down")){let a=LP(e.state,t);if(a&&a instanceof Vt)return Sd(e,a)}if(!i.parent.inlineContent){let a=t<0?i:o,s=r instanceof Qa?Sn.near(a,t):Sn.findFrom(a,t);return s?Sd(e,s):!1}return!1}function LI(e,t){if(!(e.state.selection instanceof _t))return!0;let{$head:n,$anchor:r,empty:i}=e.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(e.endOfTextblock(t>0?"forward":"backward"))return!0;let o=!n.textOffset&&(t<0?n.nodeBefore:n.nodeAfter);if(o&&!o.isText){let a=e.state.tr;return t<0?a.delete(n.pos-o.nodeSize,n.pos):a.delete(n.pos,n.pos+o.nodeSize),e.dispatch(a),!0}return!1}function DI(e,t,n){e.domObserver.stop(),t.contentEditable=n,e.domObserver.start()}function OX(e){if(!ca||e.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:n}=e.domSelectionRange();if(t&&t.nodeType==1&&n==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let r=t.firstChild;DI(e,r,"true"),setTimeout(()=>DI(e,r,"false"),20)}return!1}function $X(e){let t="";return e.ctrlKey&&(t+="c"),e.metaKey&&(t+="m"),e.altKey&&(t+="a"),e.shiftKey&&(t+="s"),t}function _X(e,t){let n=t.keyCode,r=$X(t);if(n==8||al&&n==72&&r=="c")return LI(e,-1)||zf(e,-1);if(n==46&&!t.shiftKey||al&&n==68&&r=="c")return LI(e,1)||zf(e,1);if(n==13||n==27)return!0;if(n==37||al&&n==66&&r=="c"){let i=n==37?II(e,e.state.selection.from)=="ltr"?-1:1:-1;return FI(e,i,r)||zf(e,i)}else if(n==39||al&&n==70&&r=="c"){let i=n==39?II(e,e.state.selection.from)=="ltr"?1:-1:1;return FI(e,i,r)||zf(e,i)}else{if(n==38||al&&n==80&&r=="c")return BI(e,-1,r)||zf(e,-1);if(n==40||al&&n==78&&r=="c")return OX(e)||BI(e,1,r)||zf(e,1);if(r==(al?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function wR(e,t){e.someProp("transformCopied",h=>{t=h(t,e)});let n=[],{content:r,openStart:i,openEnd:o}=t;for(;i>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,o--;let h=r.firstChild;n.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let a=e.someProp("clipboardSerializer")||Xc.fromSchema(e.state.schema),s=S$(),l=s.createElement("div");l.appendChild(a.serializeFragment(r,{document:s}));let p=l.firstChild,c,u=0;for(;p&&p.nodeType==1&&(c=g$[p.nodeName.toLowerCase()]);){for(let h=c.length-1;h>=0;h--){let m=s.createElement(c[h]);for(;l.firstChild;)m.appendChild(l.firstChild);l.appendChild(m),u++}p=l.firstChild}p&&p.nodeType==1&&p.setAttribute("data-pm-slice",`${i} ${o}${u?` -${u}`:""} ${JSON.stringify(n)}`);let d=e.someProp("clipboardTextSerializer",h=>h(t,e))||t.content.textBetween(0,t.content.size,` + +`);return{dom:l,text:d,slice:t}}function b$(e,t,n,r,i){let o=i.parent.type.spec.code,a,s;if(!n&&!t)return null;let l=!!t&&(r||o||!n);if(l){if(e.someProp("transformPastedText",d=>{t=d(t,o||r,e)}),o)return s=new Dt(vt.from(e.state.schema.text(t.replace(/\r\n?/g,` +`))),0,0),e.someProp("transformPasted",d=>{s=d(s,e,!0)}),s;let u=e.someProp("clipboardTextParser",d=>d(t,i,r,e));if(u)s=u;else{let d=i.marks(),{schema:h}=e.state,m=Xc.fromSchema(h);a=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(S=>{let y=a.appendChild(document.createElement("p"));S&&y.appendChild(m.serializeNode(h.text(S,d)))})}}else e.someProp("transformPastedHTML",u=>{n=u(n,e)}),a=UX(n),ny&&qX(a);let p=a&&a.querySelector("[data-pm-slice]"),c=p&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(p.getAttribute("data-pm-slice")||"");if(c&&c[3])for(let u=+c[3];u>0;u--){let d=a.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;a=d}if(s||(s=(e.someProp("clipboardParser")||e.someProp("domParser")||mh.fromSchema(e.state.schema)).parseSlice(a,{preserveWhitespace:!!(l||c),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!HX.test(d.parentNode.nodeName)?{ignore:!0}:null}})),c)s=VX(zI(s,+c[1],+c[2]),c[4]);else if(s=Dt.maxOpen(WX(s.content,i),!0),s.openStart||s.openEnd){let u=0,d=0;for(let h=s.content.firstChild;u{s=u(s,e,l)}),s}const HX=/^(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 WX(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let i=t.node(n).contentMatchAt(t.index(n)),o,a=[];if(e.forEach(s=>{if(!a)return;let l=i.findWrapping(s.type),p;if(!l)return a=null;if(p=a.length&&o.length&&f$(l,o,s,a[a.length-1],0))a[a.length-1]=p;else{a.length&&(a[a.length-1]=m$(a[a.length-1],o.length));let c=h$(s,l);a.push(c),i=i.matchType(c.type),o=l}}),a)return vt.from(a)}return e}function h$(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,vt.from(e));return e}function f$(e,t,n,r,i){if(i1&&(o=0),i=n&&(s=t<0?a.contentMatchAt(0).fillBefore(s,o<=i).append(s):s.append(a.contentMatchAt(a.childCount).fillBefore(vt.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,a.copy(s))}function zI(e,t,n){return tn})),BT.createHTML(e)):e}function UX(e){let t=/^(\s*]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let n=S$(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(e),o;if((o=i&&g$[i[1].toLowerCase()])&&(e=o.map(a=>"<"+a+">").join("")+e+o.map(a=>"").reverse().join("")),r.innerHTML=GX(e),o)for(let a=0;a=0;s-=2){let l=n.nodes[r[s]];if(!l||l.hasRequiredAttrs())break;i=vt.from(l.create(r[s+1],i)),o++,a++}return new Dt(i,o,a)}const Pa={},Aa={},KX={touchstart:!0,touchmove:!0};class ZX{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function XX(e){for(let t in Pa){let n=Pa[t];e.dom.addEventListener(t,e.input.eventHandlers[t]=r=>{JX(e,r)&&!vR(e,r)&&(e.editable||!(r.type in Aa))&&n(e,r)},KX[t]?{passive:!0}:void 0)}ca&&e.dom.addEventListener("input",()=>null),jP(e)}function $p(e,t){e.input.lastSelectionOrigin=t,e.input.lastSelectionTime=Date.now()}function YX(e){e.input.mouseDown&&e.input.mouseDown.done(),e.domObserver.stop();for(let t in e.input.eventHandlers)e.dom.removeEventListener(t,e.input.eventHandlers[t]);clearTimeout(e.input.composingTimeout),clearTimeout(e.input.lastIOSEnterFallbackTimeout)}function jP(e){e.someProp("handleDOMEvents",t=>{for(let n in t)e.input.eventHandlers[n]||e.dom.addEventListener(n,e.input.eventHandlers[n]=r=>vR(e,r))})}function vR(e,t){return e.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(e,t)||t.defaultPrevented:!1})}function JX(e,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let n=t.target;n!=e.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(t))return!1;return!0}function QX(e,t){!vR(e,t)&&Pa[t.type]&&(e.editable||!(t.type in Aa))&&Pa[t.type](e,t)}Aa.keydown=(e,t)=>{let n=t;if(e.input.shiftKey=n.keyCode==16||n.shiftKey,!k$(e)&&(e.input.lastKeyCode=n.keyCode,e.input.lastKeyCodeTime=Date.now(),!(Op&&go&&n.keyCode==13)))if(n.keyCode!=229&&e.domObserver.forceFlush(),_m&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();e.input.lastIOSEnter=r,e.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{e.input.lastIOSEnter==r&&(e.someProp("handleKeyDown",i=>i(e,eh(13,"Enter"))),e.input.lastIOSEnter=0)},200)}else e.someProp("handleKeyDown",r=>r(e,n))||_X(e,n)?n.preventDefault():$p(e,"key")};Aa.keyup=(e,t)=>{t.keyCode==16&&(e.input.shiftKey=!1)};Aa.keypress=(e,t)=>{let n=t;if(k$(e)||!n.charCode||n.ctrlKey&&!n.altKey||al&&n.metaKey)return;if(e.someProp("handleKeyPress",i=>i(e,n))){n.preventDefault();return}let r=e.state.selection;if(!(r instanceof _t)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),o=()=>e.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!e.someProp("handleTextInput",a=>a(e,r.$from.pos,r.$to.pos,i,o))&&e.dispatch(o()),n.preventDefault()}};function iy(e){return{left:e.clientX,top:e.clientY}}function eY(e,t){let n=t.x-e.clientX,r=t.y-e.clientY;return n*n+r*r<100}function kR(e,t,n,r,i){if(r==-1)return!1;let o=e.state.doc.resolve(r);for(let a=o.depth+1;a>0;a--)if(e.someProp(t,s=>a>o.depth?s(e,n,o.nodeAfter,o.before(a),i,!0):s(e,n,o.node(a),o.before(a),i,!1)))return!0;return!1}function oy(e,t,n){if(e.focused||e.focus(),e.state.selection.eq(t))return;let r=e.state.tr.setSelection(t);r.setMeta("pointer",!0),e.dispatch(r)}function tY(e,t){if(t==-1)return!1;let n=e.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Vt.isSelectable(r)?(oy(e,new Vt(n)),!0):!1}function nY(e,t){if(t==-1)return!1;let n=e.state.selection,r,i;n instanceof Vt&&(r=n.node);let o=e.state.doc.resolve(t);for(let a=o.depth+1;a>0;a--){let s=a>o.depth?o.nodeAfter:o.node(a);if(Vt.isSelectable(s)){r&&n.$from.depth>0&&a>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos?i=o.before(n.$from.depth):i=o.before(a);break}}return i!=null?(oy(e,Vt.create(e.state.doc,i)),!0):!1}function rY(e,t,n,r,i){return kR(e,"handleClickOn",t,n,r)||e.someProp("handleClick",o=>o(e,t,r))||(i?nY(e,n):tY(e,n))}function iY(e,t,n,r){return kR(e,"handleDoubleClickOn",t,n,r)||e.someProp("handleDoubleClick",i=>i(e,t,r))}function oY(e,t,n,r){return kR(e,"handleTripleClickOn",t,n,r)||e.someProp("handleTripleClick",i=>i(e,t,r))||aY(e,n,r)}function aY(e,t,n){if(n.button!=0)return!1;let r=y$(e,t,!0),i=e.state.doc;return r?(oy(e,r),r instanceof _t&&i.eq(e.state.doc)&&(e.input.mouseDown=new lY(e,r)),!0):!1}function y$(e,t,n){let r=e.state.doc;if(t==-1)return r.inlineContent?_t.create(r,0,r.content.size):null;let i=r.resolve(t);for(let o=i.depth+1;o>0;o--){let a=o>i.depth?i.nodeAfter:i.node(o),s=i.before(o);if(a.inlineContent)return _t.create(r,s+1,s+1+a.content.size);if(n&&Vt.isSelectable(a))return Vt.create(r,s)}return null}function xR(e){return ck(e)}const w$=al?"metaKey":"ctrlKey";Pa.mousedown=(e,t)=>{let n=t;e.input.shiftKey=n.shiftKey;let r=xR(e),i=Date.now(),o="singleClick";i-e.input.lastClick.time<500&&eY(n,e.input.lastClick)&&!n[w$]&&e.input.lastClick.button==n.button&&(e.input.lastClick.type=="singleClick"?o="doubleClick":e.input.lastClick.type=="doubleClick"&&(o="tripleClick")),e.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:o,button:n.button},e.input.mouseDown&&e.input.mouseDown.done();let a=e.posAtCoords(iy(n));a&&(o=="singleClick"?e.input.mouseDown=new sY(e,a,n,!!r):(o=="doubleClick"?iY:oY)(e,a.pos,a.inside,n)?n.preventDefault():$p(e,"pointer"))};class v${constructor(t){this.view=t,this.mightDrag=null,t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(t){this.done()}move(t){t.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class sY extends v${constructor(t,n,r,i){super(t),this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!r[w$],this.allowDefault=r.shiftKey;let o,a;if(n.inside>-1)o=t.state.doc.nodeAt(n.inside),a=n.inside;else{let c=t.state.doc.resolve(n.pos);o=c.parent,a=c.depth?c.before():0}const s=i?null:r.target,l=s?t.docView.nearestDesc(s,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:p}=t.state;r.button==0&&(o.type.spec.draggable&&o.type.spec.selectable!==!1||p instanceof Vt&&p.from<=a&&p.to>a)&&(this.mightDrag={node:o,pos:a,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&hl&&!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()),$p(t,"pointer")}done(){super.done(),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(()=>{this.view.isDestroyed||Zp(this.view)})}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(iy(t))),this.updateAllowDefault(t),this.allowDefault||!n?$p(this.view,"pointer"):rY(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||ca&&this.mightDrag&&!this.mightDrag.node.isAtom||go&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(oy(this.view,Sn.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):$p(this.view,"pointer")}move(t){this.updateAllowDefault(t),$p(this.view,"pointer"),super.move(t)}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class lY extends v${constructor(t,n){super(t),this.startSelection=n,this.startDoc=t.state.doc}move(t){if(t.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}t.preventDefault(),$p(this.view,"pointer");let n=this.view.posAtCoords(iy(t)),r=n&&y$(this.view,n.inside,!1);if(!r)return;let{doc:i}=this.view.state,o=this.startSelection,[a,s]=r.from{e.input.lastTouch=Date.now(),xR(e),$p(e,"pointer")};Pa.touchmove=e=>{e.input.lastTouch=Date.now(),$p(e,"pointer")};Pa.contextmenu=e=>xR(e);function k$(e,t){return e.composing?!0:ca&&Math.abs(Date.now()-e.input.compositionEndedAt)<500?(e.input.compositionEndedAt=-2e8,!0):!1}const cY=Op?5e3:-1;Aa.compositionstart=Aa.compositionupdate=e=>{if(!e.composing){e.domObserver.flush();let{state:t}=e,n=t.selection.$to;if(t.selection instanceof _t&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||go&&Y4&&pY(e)))e.markCursor=e.state.storedMarks||n.marks(),ck(e,!0),e.markCursor=null;else if(ck(e,!t.selection.empty),hl&&t.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=e.domSelectionRange();for(let i=r.focusNode,o=r.focusOffset;i&&i.nodeType==1&&o!=0;){let a=o<0?i.lastChild:i.childNodes[o-1];if(!a)break;if(a.nodeType==3){let s=e.domSelection();s&&s.collapse(a,a.nodeValue.length);break}else i=a,o=-1}}e.input.composing=!0}x$(e,cY)};function pY(e){let{focusNode:t,focusOffset:n}=e.domSelectionRange();if(!t||t.nodeType!=1||n>=t.childNodes.length)return!1;let r=t.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Aa.compositionend=(e,t)=>{e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=Date.now(),e.input.compositionPendingChanges=e.domObserver.pendingRecords().length?e.input.compositionID:0,e.input.compositionNode=null,e.input.badSafariComposition?e.domObserver.forceFlush():e.input.compositionPendingChanges&&Promise.resolve().then(()=>e.domObserver.flush()),e.input.compositionID++,x$(e,20))};function x$(e,t){clearTimeout(e.input.composingTimeout),t>-1&&(e.input.composingTimeout=setTimeout(()=>ck(e),t))}function T$(e){for(e.composing&&(e.input.composing=!1,e.input.compositionEndedAt=Date.now());e.input.compositionNodes.length>0;)e.input.compositionNodes.pop().markParentsDirty()}function uY(e){let t=e.domSelectionRange();if(!t.focusNode)return null;let n=nX(t.focusNode,t.focusOffset),r=rX(t.focusNode,t.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,o=e.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;if(e.input.compositionNode==r){let a=n.pmViewDesc;if(!(!a||!a.isText(n.nodeValue)))return r}}return n||r}function ck(e,t=!1){if(!(Op&&e.domObserver.flushingSoon>=0)){if(e.domObserver.forceFlush(),T$(e),t||e.docView&&e.docView.dirty){let n=SR(e),r=e.state.selection;return n&&!n.eq(r)?e.dispatch(e.state.tr.setSelection(n)):(e.markCursor||t)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?e.dispatch(e.state.tr.deleteSelection()):e.updateState(e.state),!0}return!1}}function dY(e,t){if(!e.dom.parentNode)return;let n=e.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(t),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(t),e.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),e.focus()},50)}const xS=es&&Ld<15||_m&&sX<604;Pa.copy=Aa.cut=(e,t)=>{let n=t,r=e.state.selection,i=n.type=="cut";if(r.empty)return;let o=xS?null:n.clipboardData,a=r.content(),{dom:s,text:l}=wR(e,a);o?(n.preventDefault(),o.clearData(),o.setData("text/html",s.innerHTML),o.setData("text/plain",l)):dY(e,s),i&&e.dispatch(e.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function bY(e){return e.openStart==0&&e.openEnd==0&&e.content.childCount==1?e.content.firstChild:null}function hY(e,t){if(!e.dom.parentNode)return;let n=e.input.shiftKey||e.state.selection.$from.parent.type.spec.code,r=e.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=e.input.shiftKey&&e.input.lastKeyCode!=45;setTimeout(()=>{e.focus(),r.parentNode&&r.parentNode.removeChild(r),n?TS(e,r.value,null,i,t):TS(e,r.textContent,r.innerHTML,i,t)},50)}function TS(e,t,n,r,i){let o=b$(e,t,n,r,e.state.selection.$from);if(e.someProp("handlePaste",l=>l(e,i,o||Dt.empty)))return!0;if(!o)return!1;let a=bY(o),s=a?e.state.tr.replaceSelectionWith(a,r):e.state.tr.replaceSelection(o);return e.dispatch(s.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function C$(e){let t=e.getData("text/plain")||e.getData("Text");if(t)return t;let n=e.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Aa.paste=(e,t)=>{let n=t;if(e.composing&&!Op)return;let r=xS?null:n.clipboardData,i=e.input.shiftKey&&e.input.lastKeyCode!=45;r&&TS(e,C$(r),r.getData("text/html"),i,n)?n.preventDefault():hY(e,n)};class P${constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const fY=al?"altKey":"ctrlKey";function A$(e,t){let n;return e.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[fY]}Pa.dragstart=(e,t)=>{let n=t,r=e.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=e.state.selection,o=i.empty?null:e.posAtCoords(iy(n)),a;if(!(o&&o.pos>=i.from&&o.pos<=(i instanceof Vt?i.to-1:i.to))){if(r&&r.mightDrag)a=Vt.create(e.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let u=e.docView.nearestDesc(n.target,!0);u&&u.node.type.spec.draggable&&u!=e.docView&&(a=Vt.create(e.state.doc,u.posBefore))}}let s=(a||e.state.selection).content(),{dom:l,text:p,slice:c}=wR(e,s);(!n.dataTransfer.files.length||!go||X4>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(xS?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",xS||n.dataTransfer.setData("text/plain",p),e.dragging=new P$(c,A$(e,n),a)};Pa.dragend=e=>{let t=e.dragging;window.setTimeout(()=>{e.dragging==t&&(e.dragging=null)},50)};Aa.dragover=Aa.dragenter=(e,t)=>t.preventDefault();Aa.drop=(e,t)=>{try{mY(e,t,e.dragging)}finally{e.dragging=null}};function mY(e,t,n){if(!t.dataTransfer)return;let r=e.posAtCoords(iy(t));if(!r)return;let i=e.state.doc.resolve(r.pos),o=n&&n.slice;o?e.someProp("transformPasted",h=>{o=h(o,e,!1)}):o=b$(e,C$(t.dataTransfer),xS?null:t.dataTransfer.getData("text/html"),!1,i);let a=!!(n&&A$(e,t));if(e.someProp("handleDrop",h=>h(e,t,o||Dt.empty,a))){t.preventDefault();return}if(!o)return;t.preventDefault();let s=o?E4(e.state.doc,i.pos,o):i.pos;s==null&&(s=i.pos);let l=e.state.tr;if(a){let{node:h}=n;h?h.replace(l):l.deleteSelection()}let p=l.mapping.map(s),c=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,u=l.doc;if(c?l.replaceRangeWith(p,p,o.content.firstChild):l.replaceRange(p,p,o),l.doc.eq(u))return;let d=l.doc.resolve(p);if(c&&Vt.isSelectable(o.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(o.content.firstChild))l.setSelection(new Vt(d));else{let h=l.mapping.map(s);l.mapping.maps[l.mapping.maps.length-1].forEach((m,S,y,w)=>h=w),l.setSelection(yR(e,d,l.doc.resolve(h)))}e.focus(),e.dispatch(l.setMeta("uiEvent","drop"))}Pa.focus=e=>{e.input.lastFocus=Date.now(),e.focused||(e.domObserver.stop(),e.dom.classList.add("ProseMirror-focused"),e.domObserver.start(),e.focused=!0,setTimeout(()=>{e.docView&&e.hasFocus()&&!e.domObserver.currentSelection.eq(e.domSelectionRange())&&Zp(e)},20))};Pa.blur=(e,t)=>{let n=t;e.focused&&(e.domObserver.stop(),e.dom.classList.remove("ProseMirror-focused"),e.domObserver.start(),n.relatedTarget&&e.dom.contains(n.relatedTarget)&&e.domObserver.currentSelection.clear(),e.focused=!1)};Pa.beforeinput=(e,t)=>{if(go&&Op&&t.inputType=="deleteContentBackward"){e.domObserver.flushSoon();let{domChangeCount:r}=e.input;setTimeout(()=>{if(e.input.domChangeCount!=r||(e.dom.blur(),e.focus(),e.someProp("handleKeyDown",o=>o(e,eh(8,"Backspace")))))return;let{$cursor:i}=e.state.selection;i&&i.pos>0&&e.dispatch(e.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let e in Aa)Pa[e]=Aa[e];function CS(e,t){if(e==t)return!0;for(let n in e)if(e[n]!==t[n])return!1;for(let n in t)if(!(n in e))return!1;return!0}class pk{constructor(t,n){this.toDOM=t,this.spec=n||gh,this.side=this.spec.side||0}map(t,n,r,i){let{pos:o,deleted:a}=t.mapResult(n.from+i,this.side<0?-1:1);return a?null:new dn(o-r,o-r,this)}valid(){return!0}eq(t){return this==t||t instanceof pk&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&CS(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class jd{constructor(t,n){this.attrs=t,this.spec=n||gh}map(t,n,r,i){let o=t.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,a=t.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return o>=a?null:new dn(o,a,this)}valid(t,n){return n.from=t&&(!o||o(s.spec))&&r.push(s.copy(s.from+i,s.to+i))}for(let a=0;at){let s=this.children[a]+1;this.children[a+2].findInner(t-s,n-s,r,i+s,o)}}map(t,n,r){return this==oa||t.maps.length==0?this:this.mapInner(t,n,0,0,r||gh)}mapInner(t,n,r,i,o){let a;for(let s=0;s{let p=l+r,c;if(c=R$(n,s,p)){for(i||(i=this.children.slice());os&&u.to=t){this.children[s]==t&&(r=this.children[s+2]);break}let o=t+1,a=o+n.content.size;for(let s=0;so&&l.type instanceof jd){let p=Math.max(o,l.from)-o,c=Math.min(a,l.to)-o;pi.map(t,n,gh));return kd.from(r)}forChild(t,n){if(n.isLeaf)return Mt.empty;let r=[];for(let i=0;in instanceof Mt)?t:t.reduce((n,r)=>n.concat(r instanceof Mt?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let y=S-m-(h-d);for(let w=0;wv+c-u)continue;let x=s[w]+c-u;h>=x?s[w+1]=d<=x?-2:-1:d>=c&&y&&(s[w]+=y,s[w+1]+=y)}u+=y}),c=n.maps[p].map(c,-1)}let l=!1;for(let p=0;p=r.content.size){l=!0;continue}let d=n.map(e[p+1]+o,-1),h=d-i,{index:m,offset:S}=r.content.findIndex(u),y=r.maybeChild(m);if(y&&S==u&&S+y.nodeSize==h){let w=s[p+2].mapInner(n,y,c+1,e[p]+o+1,a);w!=oa?(s[p]=u,s[p+1]=h,s[p+2]=w):(s[p+1]=-2,l=!0)}else l=!0}if(l){let p=SY(s,e,t,n,i,o,a),c=uk(p,r,0,a);t=c.local;for(let u=0;un&&a.to{let p=R$(e,s,l+n);if(p){o=!0;let c=uk(p,s,n+l+1,r);c!=oa&&i.push(l,l+s.nodeSize,c)}});let a=E$(o?M$(e):e,-n).sort(Sh);for(let s=0;s0;)t++;e.splice(t,0,n)}function LT(e){let t=[];return e.someProp("decorations",n=>{let r=n(e.state);r&&r!=oa&&t.push(r)}),e.cursorWrapper&&t.push(Mt.create(e.state.doc,[e.cursorWrapper.deco])),kd.from(t)}const yY={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},wY=es&&Ld<=11;class vY{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(t){this.anchorNode=t.anchorNode,this.anchorOffset=t.anchorOffset,this.focusNode=t.focusNode,this.focusOffset=t.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(t){return t.anchorNode==this.anchorNode&&t.anchorOffset==this.anchorOffset&&t.focusNode==this.focusNode&&t.focusOffset==this.focusOffset}}class kY{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new vY,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():ca&&t.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),wY&&(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,yY)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let n=0;nthis.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(NI(this.view)){if(this.suppressingSelectionUpdates)return Zp(this.view);if(es&&Ld<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&Th(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let n=new Set,r;for(let o=t.focusNode;o;o=$m(o))n.add(o);for(let o=t.anchorNode;o;o=$m(o))if(n.has(o)){r=o;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=t.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&NI(t)&&!this.ignoreSelectionChange(r),o=-1,a=-1,s=!1,l=[];if(t.editable)for(let c=0;cc.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46||go&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&n.some(c=>c.type=="childList"&&c.removedNodes.length))){for(let c of l)if(c.nodeName=="BR"&&c.parentNode){let u=c.nextSibling;for(;u&&u.nodeType==1;){if(u.contentEditable=="false"){c.parentNode.removeChild(c);break}u=u.firstChild}}}else if(hl&&l.length){let c=l.filter(u=>u.nodeName=="BR");if(c.length==2){let[u,d]=c;u.parentNode&&u.parentNode.parentNode==d.parentNode?d.remove():u.remove()}else{let{focusNode:u}=this.currentSelection;for(let d of c){let h=d.parentNode;h&&h.nodeName=="LI"&&(!u||CY(t,u)!=h)&&d.remove()}}}let p=null;o<0&&i&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||i)&&(o>-1&&(t.docView.markDirty(o,a),xY(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,PY(t,l)),this.handleDOMChange(o,a,s,l),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||Zp(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let c=0;ci;y--){let w=r.childNodes[y-1],v=w.pmViewDesc;if(w.nodeName=="BR"&&!v){o=y;break}if(!v||v.size)break}let u=e.state.doc,d=e.someProp("domParser")||mh.fromSchema(e.state.schema),h=u.resolve(a),m=null,S=d.parse(r,{topNode:h.parent,topMatch:h.parent.contentMatchAt(h.index()),topOpen:!0,from:i,to:o,preserveWhitespace:h.parent.type.whitespace=="pre"?"full":!0,findPositions:p,ruleFromNode:EY,context:h});if(p&&p[0].pos!=null){let y=p[0].pos,w=p[1]&&p[1].pos;w==null&&(w=y),m={anchor:y+a,head:w+a}}return{doc:S,sel:m,from:a,to:s}}function EY(e){let t=e.pmViewDesc;if(t)return t.parseRule();if(e.nodeName=="BR"&&e.parentNode){if(ca&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(e.parentNode.lastChild==e||ca&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null}const RY=/^(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 MY(e,t,n,r,i){let o=e.input.compositionPendingChanges||(e.composing?e.input.compositionID:0);if(e.input.compositionPendingChanges=0,t<0){let A=e.input.lastSelectionTime>Date.now()-50?e.input.lastSelectionOrigin:null,R=SR(e,A);if(R&&!e.state.selection.eq(R)){if(go&&Op&&e.input.lastKeyCode===13&&Date.now()-100M(e,eh(13,"Enter"))))return;let N=e.state.tr.setSelection(R);A=="pointer"?N.setMeta("pointer",!0):A=="key"&&N.scrollIntoView(),o&&N.setMeta("composition",o),e.dispatch(N)}return}let a=e.state.doc.resolve(t),s=a.sharedDepth(n);t=a.before(s+1),n=e.state.doc.resolve(n).after(s+1);let l=e.state.selection,p=AY(e,t,n),c=e.state.doc,u=c.slice(p.from,p.to),d,h;e.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Op)&&i.some(A=>A.nodeType==1&&!RY.test(A.nodeName))&&(!m||m.endA>=m.endB)&&e.someProp("handleKeyDown",A=>A(e,eh(13,"Enter")))){e.input.lastIOSEnter=0;return}if(!m)if(r&&l instanceof _t&&!l.empty&&l.$head.sameParent(l.$anchor)&&!e.composing&&!(p.sel&&p.sel.anchor!=p.sel.head))m={start:l.from,endA:l.to,endB:l.to};else{if(p.sel){let A=HI(e,e.state.doc,p.sel);if(A&&!A.eq(e.state.selection)){let R=e.state.tr.setSelection(A);o&&R.setMeta("composition",o),e.dispatch(R)}}return}e.state.selection.frome.state.selection.from&&m.start<=e.state.selection.from+2&&e.state.selection.from>=p.from?m.start=e.state.selection.from:m.endA=e.state.selection.to-2&&e.state.selection.to<=p.to&&(m.endB+=e.state.selection.to-m.endA,m.endA=e.state.selection.to)),es&&Ld<=11&&m.endB==m.start+1&&m.endA==m.start&&m.start>p.from&&p.doc.textBetween(m.start-p.from-1,m.start-p.from+1)=="  "&&(m.start--,m.endA--,m.endB--);let S=p.doc.resolveNoCache(m.start-p.from),y=p.doc.resolveNoCache(m.endB-p.from),w=c.resolve(m.start),v=S.sameParent(y)&&S.parent.inlineContent&&w.end()>=m.endA;if((_m&&e.input.lastIOSEnter>Date.now()-225&&(!v||i.some(A=>A.nodeName=="DIV"||A.nodeName=="P"))||!v&&S.posA(e,eh(13,"Enter")))){e.input.lastIOSEnter=0;return}if(e.state.selection.anchor>m.start&&FY(c,m.start,m.endA,S,y)&&e.someProp("handleKeyDown",A=>A(e,eh(8,"Backspace")))){Op&&go&&e.domObserver.suppressSelectionUpdates();return}go&&m.endB==m.start&&(e.input.lastChromeDelete=Date.now()),Op&&!v&&S.start()!=y.start()&&y.parentOffset==0&&S.depth==y.depth&&p.sel&&p.sel.anchor==p.sel.head&&p.sel.head==m.endA&&(m.endB-=2,y=p.doc.resolveNoCache(m.endB-p.from),setTimeout(()=>{e.someProp("handleKeyDown",function(A){return A(e,eh(13,"Enter"))})},20));let x=m.start,P=m.endA,T=A=>{let R=A||e.state.tr.replace(x,P,p.doc.slice(m.start-p.from,m.endB-p.from));if(p.sel){let N=HI(e,R.doc,p.sel);N&&!(go&&e.composing&&N.empty&&(m.start!=m.endB||e.input.lastChromeDeleteZp(e),20));let A=T(e.state.tr.delete(x,P)),R=c.resolve(m.start).marksAcross(c.resolve(m.endA));R&&A.ensureMarks(R),e.dispatch(A)}else if(m.endA==m.endB&&(C=NY(S.parent.content.cut(S.parentOffset,y.parentOffset),w.parent.content.cut(w.parentOffset,m.endA-w.start())))){let A=T(e.state.tr);C.type=="add"?A.addMark(x,P,C.mark):A.removeMark(x,P,C.mark),e.dispatch(A)}else if(S.parent.child(S.index()).isText&&S.index()==y.index()-(y.textOffset?0:1)){let A=S.parent.textBetween(S.parentOffset,y.parentOffset),R=()=>T(e.state.tr.insertText(A,x,P));e.someProp("handleTextInput",N=>N(e,x,P,A,R))||e.dispatch(R())}else e.dispatch(T());else e.dispatch(T())}function HI(e,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:yR(e,t.resolve(n.anchor),t.resolve(n.head))}function NY(e,t){let n=e.firstChild.marks,r=t.firstChild.marks,i=n,o=r,a,s,l;for(let c=0;cc.mark(s.addToSet(c.marks));else if(i.length==0&&o.length==1)s=o[0],a="remove",l=c=>c.mark(s.removeFromSet(c.marks));else return null;let p=[];for(let c=0;cn||DT(a,!0,!1)0&&(t||e.indexAfter(r)==e.node(r).childCount);)r--,i++,t=!1;if(n){let o=e.node(r).maybeChild(e.indexAfter(r));for(;o&&!o.isLeaf;)o=o.firstChild,i++}return i}function IY(e,t,n,r,i){let o=e.findDiffStart(t,n),a=n+e.size,s=n+t.size;if(o==null)return null;let{a:l,b:p}=e.findDiffEnd(t,a,s);if(i=="end"){let c=Math.max(0,o-Math.min(l,p));r-=l+c-o}if(l=l?o-r:0;o-=c,p=o+(p-l),l=o}else if(p=p?o-r:0;o-=c,l=o+(l-p),p=o}return{start:o,endA:l,endB:p}}class N${constructor(t,n){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 ZX,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(VI),this.dispatch=this.dispatch.bind(this),this.dom=t&&t.mount||document.createElement("div"),t&&(t.appendChild?t.appendChild(this.dom):typeof t=="function"?t(this.dom):t.mount&&(this.mounted=!0)),this.editable=UI(this),GI(this),this.nodeViews=qI(this),this.docView=CI(this.state.doc,WI(this),LT(this),this.dom,this),this.domObserver=new kY(this,(r,i,o,a)=>MY(this,r,i,o,a)),this.domObserver.start(),XX(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let n in t)this._props[n]=t[n];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&jP(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(VI),this.directPlugins=t.plugins),this.updateStateInner(t.state,n)}setProps(t){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in t)n[r]=t[r];this.update(n)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,n){var r;let i=this.state,o=!1,a=!1;t.storedMarks&&this.composing&&(T$(this),a=!0),this.state=t;let s=i.plugins!=t.plugins||this._props.plugins!=n.plugins;if(s||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let h=qI(this);LY(h,this.nodeViews)&&(this.nodeViews=h,o=!0)}(s||n.handleDOMEvents!=this._props.handleDOMEvents)&&jP(this),this.editable=UI(this),GI(this);let l=LT(this),p=WI(this),c=i.plugins!=t.plugins&&!i.doc.eq(t.doc)?"reset":t.scrollToSelection>i.scrollToSelection?"to selection":"preserve",u=o||!this.docView.matchesNode(t.doc,p,l);(u||!t.selection.eq(i.selection))&&(a=!0);let d=c=="preserve"&&a&&this.dom.style.overflowAnchor==null&&pX(this);if(a){this.domObserver.stop();let h=u&&(es||go)&&!this.composing&&!i.selection.empty&&!t.selection.empty&&BY(i.selection,t.selection);if(u){let S=go?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=uY(this)),(o||!this.docView.update(t.doc,p,l,this))&&(this.docView.updateOuterDeco(p),this.docView.destroy(),this.docView=CI(t.doc,p,l,this.dom,this)),S&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let m=this.input.mouseDown;h||!(m&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&BX(this)&&m.delaySelUpdate())?Zp(this,h):(p$(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,i),c=="reset"?this.dom.scrollTop=0:c=="to selection"?this.scrollToSelection():d&&uX(d)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof Vt){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&wI(this,n.getBoundingClientRect(),t)}else wI(this,this.coordsAtPos(this.state.selection.head,1),t)}}destroyPluginViews(){let t;for(;t=this.pluginViews.pop();)t.destroy&&t.destroy()}updatePluginViews(t){if(!t||t.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n0&&on.ownerDocument.getSelection()),this._root=n}return t||document}updateRoot(){this._root=null}posAtCoords(t){return gX(this,t)}coordsAtPos(t,n=1){return n$(this,t,n)}domAtPos(t,n=0){return this.docView.domFromPos(t,n)}nodeDOM(t){let n=this.docView.descAt(t);return n?n.nodeDOM:null}posAtDOM(t,n,r=-1){let i=this.docView.posFromDOM(t,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(t,n){return kX(this,n||this.state,t)}pasteHTML(t,n){return TS(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return TS(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return wR(this,t)}destroy(){this.docView&&(YX(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],LT(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,eX())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return QX(this,t)}domSelectionRange(){let t=this.domSelection();return t?ca&&this.root.nodeType===11&&oX(this.dom.ownerDocument)==this.dom&&TY(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}N$.prototype.dispatch=function(e){let t=this._props.dispatchTransaction;t?t.call(this,e):this.updateState(this.state.apply(e))};function WI(e){let t=Object.create(null);return t.class="ProseMirror",t.contenteditable=String(e.editable),e.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(e.state)),n)for(let r in n)r=="class"?t.class+=" "+n[r]:r=="style"?t.style=(t.style?t.style+";":"")+n[r]:!t[r]&&r!="contenteditable"&&r!="nodeName"&&(t[r]=String(n[r]))}),t.translate||(t.translate="no"),[dn.node(0,e.state.doc.content.size,t)]}function GI(e){if(e.markCursor){let t=document.createElement("img");t.className="ProseMirror-separator",t.setAttribute("mark-placeholder","true"),t.setAttribute("alt",""),e.cursorWrapper={dom:t,deco:dn.widget(e.state.selection.from,t,{raw:!0,marks:e.markCursor})}}else e.cursorWrapper=null}function UI(e){return!e.someProp("editable",t=>t(e.state)===!1)}function BY(e,t){let n=Math.min(e.$anchor.sharedDepth(e.head),t.$anchor.sharedDepth(t.head));return e.$anchor.start(n)!=t.$anchor.start(n)}function qI(e){let t=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(t,i)||(t[i]=r[i])}return e.someProp("nodeViews",n),e.someProp("markViews",n),t}function LY(e,t){let n=0,r=0;for(let i in e){if(e[i]!=t[i])return!0;n++}for(let i in t)r++;return n!=r}function VI(e){if(e.spec.state||e.spec.filterTransaction||e.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var Wd={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:"'"},dk={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},DY=typeof navigator<"u"&&/Mac/.test(navigator.platform),zY=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Lo=0;Lo<10;Lo++)Wd[48+Lo]=Wd[96+Lo]=String(Lo);for(var Lo=1;Lo<=24;Lo++)Wd[Lo+111]="F"+Lo;for(var Lo=65;Lo<=90;Lo++)Wd[Lo]=String.fromCharCode(Lo+32),dk[Lo]=String.fromCharCode(Lo);for(var zT in Wd)dk.hasOwnProperty(zT)||(dk[zT]=Wd[zT]);function jY(e){var t=DY&&e.metaKey&&e.shiftKey&&!e.ctrlKey&&!e.altKey||zY&&e.shiftKey&&e.key&&e.key.length==1||e.key=="Unidentified",n=!t&&e.key||(e.shiftKey?dk:Wd)[e.keyCode]||e.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const OY=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),$Y=typeof navigator<"u"&&/Win/.test(navigator.platform);function _Y(e){let t=e.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let r,i,o,a;for(let s=0;s[s,(...c)=>{const u=l(...c)(a);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(o),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:i,state:o}=this,{view:a}=i,s=[],l=!!t,p=t||o.tr,c=()=>(!l&&n&&!p.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(p),s.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(r).map(([d,h])=>[d,(...S)=>{const y=this.buildProps(p,n),w=h(...S)(y);return s.push(w),u}])),run:c};return u}static createFakeChain(){const t=new Proxy({},{get:(n,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>t}});return t}createCan(t){const{rawCommands:n,state:r}=this,i=!1,o=t||r.tr,a=this.buildProps(o,i);return{...Object.fromEntries(Object.entries(n).map(([s,l])=>[s,(...p)=>l(...p)({...a,dispatch:void 0})])),chain:()=>this.createChain(o,i)}}static createFallbackCan(){const t=F$.createFakeChain();return new Proxy({chain:()=>t},{get:(n,r)=>{if(r!=="then")return r==="chain"?n.chain:()=>!1}})}buildProps(t,n=!0){const{rawCommands:r,editor:i,state:o}=this,{view:a}=i,s={tr:t,editor:i,view:a,state:Fx({state:o,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t,n),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([l,p])=>[l,(...c)=>p(...c)(s)]))}};return s}};const GY=()=>({editor:e,view:t})=>(requestAnimationFrame(()=>{if(!e.isDestroyed){var n;t.dom.blur(),(n=window)===null||n===void 0||(n=n.getSelection())===null||n===void 0||n.removeAllRanges()}}),!0),UY=(e=!0)=>({commands:t})=>t.setContent("",{emitUpdate:e}),qY=()=>({state:e,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:i}=r;return n&&i.forEach(({$from:o,$to:a})=>{e.doc.nodesBetween(o.pos,a.pos,(s,l)=>{if(s.type.isText)return;const{doc:p,mapping:c}=t,u=p.resolve(c.map(l)),d=p.resolve(c.map(l+s.nodeSize)),h=u.blockRange(d);if(!h)return;const m=tg(h);if(s.type.isTextblock){const{defaultType:S}=u.parent.contentMatchAt(u.index());t.setNodeMarkup(h.start,S)}(m||m===0)&&t.lift(h,m)})}),!0},VY=e=>t=>e(t),KY=()=>({state:e,dispatch:t})=>U4(e,t),ZY=(e,t)=>({editor:n,tr:r})=>{const{state:i}=n,o=i.doc.slice(e.from,e.to);r.deleteRange(e.from,e.to);const a=r.mapping.map(t);return r.insert(a,o.content),r.setSelection(new _t(r.doc.resolve(Math.max(a-1,0)))),!0},XY=()=>({tr:e,dispatch:t})=>{const{selection:n}=e,r=n.$anchor.node();if(r.content.size>0)return!1;const i=e.selection.$anchor;for(let o=i.depth;o>0;o-=1)if(i.node(o).type===r.type){if(t){const a=i.before(o),s=i.after(o);e.delete(a,s).scrollIntoView()}return!0}return!1};function yo(e,t){if(typeof e=="string"){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}const YY=e=>({tr:t,state:n,dispatch:r})=>{const i=yo(e,n.schema),o=t.selection.$anchor;for(let a=o.depth;a>0;a-=1)if(o.node(a).type===i){if(r){const s=o.before(a),l=o.after(a);t.delete(s,l).scrollIntoView()}return!0}return!1},JY=e=>({tr:t,dispatch:n})=>{const{from:r,to:i}=e;return n&&t.delete(r,i),!0},QY=e=>e.content?/^text(\*|\+)/.test(e.content):!1,KI=(e,t,n)=>{if(!e.parent.isInline||n==="left"&&e.pos>e.start()||n==="right"&&e.pos({from:KI(e,n,"left"),to:KI(t,n,"right")}),tJ=()=>({state:e,dispatch:t})=>{if(e.selection.empty)return!1;if(t){const n=e.tr,{ranges:r}=e.selection,i=n.steps.length;r.forEach(o=>{const a=n.mapping.slice(i),s=n.doc.resolve(a.map(o.$from.pos)),l=n.doc.resolve(a.map(o.$to.pos)),{from:p,to:c}=eJ(s,l,e.schema);n.deleteRange(p,c)}),n.selection.empty||n.setSelection(_t.near(n.doc.resolve(n.selection.from))),n.scrollIntoView(),t(n)}return!0},nJ=()=>({commands:e})=>e.keyboardShortcut("Enter"),rJ=()=>({state:e,dispatch:t})=>OZ(e,t);function AR(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function bk(e,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(i=>n.strict?t[i]===e[i]:AR(t[i])?t[i].test(e[i]):t[i]===e[i]):!0}function I$(e,t,n={}){return e.find(r=>r.type===t&&bk(Object.fromEntries(Object.keys(n).map(i=>[i,r.attrs[i]])),n))}function ZI(e,t,n={}){return!!I$(e,t,n)}function ER(e,t,n){if(!e||!t)return;let r=e.parent.childAfter(e.parentOffset);if((!r.node||!r.node.marks.some(l=>l.type===t))&&(r=e.parent.childBefore(e.parentOffset)),!r.node||!r.node.marks.some(l=>l.type===t))return;if(!n){const l=r.node.marks.find(p=>p.type===t);l&&(n=l.attrs)}if(!I$([...r.node.marks],t,n))return;let i=r.index,o=e.start()+r.offset,a=i+1,s=o+r.node.nodeSize;for(;i>0&&ZI([...e.parent.child(i-1).marks],t,n);)i-=1,o-=e.parent.child(i).nodeSize;for(;a({tr:n,state:r,dispatch:i})=>{const o=su(e,r.schema),{doc:a,selection:s}=n,{$from:l,from:p,to:c}=s;if(i){const u=ER(l,o,t);if(u&&u.from<=p&&u.to>=c){const d=_t.create(a,u.from,u.to);n.setSelection(d)}}return!0},oJ=e=>t=>{const n=typeof e=="function"?e(t):e;for(let r=0;r({editor:n,view:r,tr:i,dispatch:o})=>{t={scrollIntoView:!0,...t};const a=()=>{(hk()||XI())&&r.dom.focus(),aJ()&&!hk()&&!XI()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),t?.scrollIntoView&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&e===null||e===!1)return!0}catch{return!1}if(o&&e===null&&!B$(n.state.selection))return a(),!0;const s=OP(i.doc,e)||n.state.selection,l=n.state.selection.eq(s);return o&&(l||i.setSelection(s),l&&i.storedMarks&&i.setStoredMarks(i.storedMarks),a()),!0},lJ=(e,t)=>n=>e.every((r,i)=>t(r,{...n,index:i})),cJ=(e,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},e,t),L$=e=>{const t=e.childNodes;for(let n=t.length-1;n>=0;n-=1){const r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?e.removeChild(r):r.nodeType===1&&L$(r)}return e};function Rw(e){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const t=`${e}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return L$(n)}function D$(e){return typeof e?.nodesBetween=="function"}function Hm(e,t,n){if(D$(e))return e;const r=typeof e=="object"&&e!==null;n={slice:!0,parseOptions:{},...n};const i=typeof e=="string";if(r)try{if(Array.isArray(e)&&e.length>0)return vt.fromArray(e.map(a=>t.nodeFromJSON(a)));const o=t.nodeFromJSON(e);return n.errorOnInvalidContent&&o.check(),o}catch(o){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:o});return console.warn("[tiptap warn]: Invalid content.","Passed value:",e,"Error:",o),Hm("",t,n)}if(i){if(n.errorOnInvalidContent){let a=!1,s="";const l=new m4({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:p=>(a=!0,s=typeof p=="string"?p:p.outerHTML,null)}]}})});if(n.slice?mh.fromSchema(l).parseSlice(Rw(e),n.parseOptions):mh.fromSchema(l).parse(Rw(e),n.parseOptions),n.errorOnInvalidContent&&a)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${s}`)})}const o=mh.fromSchema(t);return n.slice?o.parseSlice(Rw(e),n.parseOptions).content:o.parse(Rw(e),n.parseOptions)}return Hm("",t,n)}function z$(e){return!("type"in e)}function j$(e,t,n){const r=e.steps.length-1;if(r{a===0&&(a=c)}),e.setSelection(Sn.near(e.doc.resolve(a),n))}const pJ=(e,t,n)=>({tr:r,dispatch:i,editor:o})=>{if(i){n={parseOptions:o.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let s;const l=y=>{o.emit("contentError",{editor:o,error:y,disableCollaboration:()=>{"collaboration"in o.storage&&typeof o.storage.collaboration=="object"&&o.storage.collaboration&&(o.storage.collaboration.isDisabled=!0)}})},p={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!o.options.enableContentCheck&&o.options.emitContentError)try{Hm(t,o.schema,{parseOptions:p,errorOnInvalidContent:!0})}catch(y){l(y)}try{var a;s=Hm(t,o.schema,{parseOptions:p,errorOnInvalidContent:(a=n.errorOnInvalidContent)!==null&&a!==void 0?a:o.options.enableContentCheck})}catch(y){return l(y),!1}let{from:c,to:u}=typeof e=="number"?{from:e,to:e}:{from:e.from,to:e.to},d=!0,h=!0;const m=z$(s)?s.content:[s];if(m.forEach(y=>{y.check(),d=d?y.isText&&y.marks.length===0:!1,h=h?y.isBlock:!1}),c===u&&h){const{parent:y}=r.doc.resolve(c);y.isTextblock&&!y.type.spec.code&&!y.childCount&&(c-=1,u+=1)}let S;if(d)Array.isArray(t)?S=t.map(y=>y.text||"").join(""):D$(t)?S=m.map(y=>{var w;return(w=y.text)!==null&&w!==void 0?w:""}).join(""):typeof t=="object"&&t&&t.text?S=t.text:S=t,r.insertText(S,c,u);else{S=vt.from(m);const y=r.doc.resolve(c),w=y.node(),v=y.parentOffset===0,x=w.isText||w.isTextblock,P=w.content.size>0;v&&x&&P&&h&&(c=Math.max(0,c-1)),r.replaceWith(c,u,m)}n.updateSelection&&j$(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:c,text:S}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:c,text:S})}return!0};function O$(e){for(let t=0;t({tr:t,dispatch:n,editor:r})=>{const{pos:i,attrs:o,content:a,updateSelection:s=!0}=e;let l;typeof i=="number"?l=t.doc.resolve(i):i?l=i:l=t.selection.$from;const p=O$(l.parent.contentMatchAt(l.index()));if(!p)return!1;const c=Object.keys(p.spec.attrs||{}),u=o?Object.fromEntries(Object.entries(o).filter(([h])=>c.includes(h))):{};let d;if(a){const h=Hm(a,r.schema);d=p.createAndFill(u,h)}else d=p.createAndFill(u);return d?(n&&(t.insert(l.pos,d),s&&j$(t,t.steps.length-1,-1)),!0):!1},dJ=()=>({state:e,dispatch:t})=>DZ(e,t),bJ=()=>({state:e,dispatch:t})=>zZ(e,t),hJ=()=>({state:e,dispatch:t})=>j4(e,t),fJ=()=>({state:e,dispatch:t})=>H4(e,t),mJ=()=>({state:e,dispatch:t,tr:n})=>{try{const r=Ax(e.doc,e.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},gJ=()=>({state:e,dispatch:t,tr:n})=>{try{const r=Ax(e.doc,e.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},SJ=()=>({state:e,dispatch:t})=>BZ(e,t),yJ=()=>({state:e,dispatch:t})=>LZ(e,t);function $$(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function wJ(e){const t=e.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,i,o,a;for(let s=0;s({editor:t,view:n,tr:r,dispatch:i})=>{const o=wJ(e).split(/-(?!$)/),a=o.find(p=>!["Alt","Ctrl","Meta","Shift"].includes(p)),s=new KeyboardEvent("keydown",{key:a==="Space"?" ":a,altKey:o.includes("Alt"),ctrlKey:o.includes("Ctrl"),metaKey:o.includes("Meta"),shiftKey:o.includes("Shift"),bubbles:!0,cancelable:!0}),l=t.captureTransaction(()=>{n.someProp("handleKeyDown",p=>p(n,s))});return l?.steps.forEach(p=>{const c=p.map(r.mapping);c&&i&&r.maybeStep(c)}),!0};function PS(e,t,n={}){const{from:r,to:i,empty:o}=e.selection,a=t?yo(t,e.schema):null,s=[];e.doc.nodesBetween(r,i,(c,u)=>{if(c.isText)return;const d=Math.max(r,u),h=Math.min(i,u+c.nodeSize);s.push({node:c,from:d,to:h})});const l=i-r,p=s.filter(c=>a?a.name===c.node.type.name:!0).filter(c=>bk(c.node.attrs,n,{strict:!1}));return o?!!p.length:p.reduce((c,u)=>c+u.to-u.from,0)>=l}const kJ=(e,t={})=>({state:n,dispatch:r})=>PS(n,yo(e,n.schema),t)?jZ(n,r):!1,xJ=()=>({state:e,dispatch:t})=>q4(e,t),TJ=e=>({state:t,dispatch:n})=>{const r=yo(e,t.schema);return XZ(r)(t,n)},CJ=()=>({state:e,dispatch:t})=>G4(e,t);function Ix(e,t){return t.nodes[e]?"node":t.marks[e]?"mark":null}function YI(e,t){const n=typeof t=="string"?[t]:t;return Object.keys(e).reduce((r,i)=>(n.includes(i)||(r[i]=e[i]),r),{})}const PJ=(e,t)=>({tr:n,state:r,dispatch:i})=>{let o=null,a=null;const s=Ix(typeof e=="string"?e:e.name,r.schema);if(!s)return!1;s==="node"&&(o=yo(e,r.schema)),s==="mark"&&(a=su(e,r.schema));let l=!1;return n.selection.ranges.forEach(p=>{r.doc.nodesBetween(p.$from.pos,p.$to.pos,(c,u)=>{o&&o===c.type&&(l=!0,i&&n.setNodeMarkup(u,void 0,YI(c.attrs,t))),a&&c.marks.length&&c.marks.forEach(d=>{a===d.type&&(l=!0,i&&n.addMark(u,u+c.nodeSize,a.create(YI(d.attrs,t))))})})}),l},AJ=()=>({tr:e,dispatch:t})=>(t&&e.scrollIntoView(),!0),EJ=()=>({tr:e,dispatch:t})=>{if(t){const n=new Qa(e.doc);e.setSelection(n)}return!0},RJ=()=>({state:e,dispatch:t})=>$4(e,t),MJ=()=>({state:e,dispatch:t})=>W4(e,t),NJ=()=>({state:e,dispatch:t})=>HZ(e,t),FJ=()=>({state:e,dispatch:t})=>UZ(e,t),IJ=()=>({state:e,dispatch:t})=>GZ(e,t);function $P(e,t,n={},r={}){return Hm(e,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const BJ=(e,{errorOnInvalidContent:t,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:i,tr:o,dispatch:a,commands:s})=>{const{doc:l}=o;if(r.preserveWhitespace!=="full"){const p=$P(e,i.schema,r,{errorOnInvalidContent:t??i.options.enableContentCheck});if(a){const c=z$(p)?p.content:[p];o.replaceWith(0,l.content.size,c).setMeta("preventUpdate",!n)}return!0}return a&&o.setMeta("preventUpdate",!n),s.insertContentAt({from:0,to:l.content.size},e,{parseOptions:r,errorOnInvalidContent:t??i.options.enableContentCheck})};function _$(e,t){const n=su(t,e.schema),{from:r,to:i,empty:o}=e.selection,a=[];o?(e.storedMarks&&a.push(...e.storedMarks),a.push(...e.selection.$head.marks())):e.doc.nodesBetween(r,i,l=>{a.push(...l.marks)});const s=a.find(l=>l.type.name===n.name);return s?{...s.attrs}:{}}function LJ(e,t){const n=new uR(e);return t.forEach(r=>{r.steps.forEach(i=>{n.step(i)})}),n}function DJ(e,t){for(let n=e.depth;n>0;n-=1){const r=e.node(n);if(t(r))return{pos:n>0?e.before(n):0,start:e.start(n),depth:n,node:r}}}function RR(e){return t=>DJ(t.$from,e)}function on(e,t,n){return e.config[t]===void 0&&e.parent?on(e.parent,t,n):typeof e.config[t]=="function"?e.config[t].bind({...n,parent:e.parent?on(e.parent,t,n):null}):e.config[t]}function MR(e){return e.map(t=>{const n=on(t,"addExtensions",{name:t.name,options:t.options,storage:t.storage});return n?[t,...MR(n())]:t}).flat(10)}function NR(e,t){const n=Xc.fromSchema(t).serializeFragment(e),r=document.implementation.createHTMLDocument().createElement("div");return r.appendChild(n),r.innerHTML}function H$(e){return typeof e=="function"}function Yr(e,t=void 0,...n){return H$(e)?t?e.bind(t)(...n):e(...n):e}function zJ(e={}){return Object.keys(e).length===0&&e.constructor===Object}function Wm(e){return{baseExtensions:e.filter(t=>t.type==="extension"),nodeExtensions:e.filter(t=>t.type==="node"),markExtensions:e.filter(t=>t.type==="mark")}}function W$(e){const t=[],{nodeExtensions:n,markExtensions:r}=Wm(e),i=[...n,...r],o={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},a=n.filter(p=>p.name!=="text").map(p=>p.name),s=r.map(p=>p.name),l=[...a,...s];return e.forEach(p=>{const c=on(p,"addGlobalAttributes",{name:p.name,options:p.options,storage:p.storage,extensions:i});c&&c().forEach(u=>{let d;Array.isArray(u.types)?d=u.types:u.types==="*"?d=l:u.types==="nodes"?d=a:u.types==="marks"?d=s:d=[],d.forEach(h=>{Object.entries(u.attributes).forEach(([m,S])=>{t.push({type:h,name:m,attribute:{...o,...S}})})})})}),i.forEach(p=>{const c=on(p,"addAttributes",{name:p.name,options:p.options,storage:p.storage});if(!c)return;const u=c();Object.entries(u).forEach(([d,h])=>{const m={...o,...h};typeof m?.default=="function"&&(m.default=m.default()),m?.isRequired&&m?.default===void 0&&delete m.default,t.push({type:p.name,name:d,attribute:m})})}),t}function jJ(e){const t=[];let n="",r=!1,i=!1,o=0;const a=e.length;for(let s=0;s0){o-=1,n+=l;continue}if(l===";"&&o===0){t.push(n),n="";continue}}n+=l}return n&&t.push(n),t}function JI(e){const t=[],n=jJ(e||""),r=n.length;for(let i=0;i!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([i,o])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:o,writable:!0});return}if(!r[i]){r[i]=o;return}if(i==="class"){const a=o?String(o).split(" "):[],s=r[i]?r[i].split(" "):[],l=a.filter(p=>!s.includes(p));r[i]=[...s,...l].join(" ")}else if(i==="style"){const a=new Map([...JI(r[i]),...JI(o)]);r[i]=Array.from(a.entries()).map(([s,l])=>`${s}: ${l}`).join("; ")}else r[i]=o}),r},{})}function fk(e,t){return t.filter(n=>n.type===e.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(e.attrs)||{}:{[n.name]:e.attrs[n.name]}).reduce((n,r)=>OJ(n,r),{})}function $J(e){return typeof e!="string"?e:e.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(e):e==="true"?!0:e==="false"?!1:e}function QI(e,t){return"style"in e?e:{...e,getAttrs:n=>{const r=e.getAttrs?e.getAttrs(n):e.attrs;if(r===!1)return!1;const i=t.reduce((o,a)=>{const s=a.attribute.parseHTML?a.attribute.parseHTML(n):$J(n.getAttribute(a.name));return s==null?o:{...o,[a.name]:s}},{});return{...r,...i}}}}function eB(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>t==="attrs"&&zJ(n)?!1:n!=null))}function tB(e){var t,n;const r={};return!(!(e==null||(t=e.attribute)===null||t===void 0)&&t.isRequired)&&"default"in(e?.attribute||{})&&(r.default=e.attribute.default),(e==null||(n=e.attribute)===null||n===void 0?void 0:n.validate)!==void 0&&(r.validate=e.attribute.validate),[e.name,r]}function _J(e,t){var n;const r=W$(e),{nodeExtensions:i,markExtensions:o}=Wm(e),a=(n=i.find(p=>on(p,"topNode")))===null||n===void 0?void 0:n.name,s=Object.fromEntries(i.map(p=>{const c=r.filter(y=>y.type===p.name),u={name:p.name,options:p.options,storage:p.storage,editor:t},d=eB({...e.reduce((y,w)=>{const v=on(w,"extendNodeSchema",u);return{...y,...v?v(p):{}}},{}),content:Yr(on(p,"content",u)),marks:Yr(on(p,"marks",u)),group:Yr(on(p,"group",u)),inline:Yr(on(p,"inline",u)),atom:Yr(on(p,"atom",u)),selectable:Yr(on(p,"selectable",u)),draggable:Yr(on(p,"draggable",u)),code:Yr(on(p,"code",u)),whitespace:Yr(on(p,"whitespace",u)),linebreakReplacement:Yr(on(p,"linebreakReplacement",u)),defining:Yr(on(p,"defining",u)),isolating:Yr(on(p,"isolating",u)),attrs:Object.fromEntries(c.map(tB))}),h=Yr(on(p,"parseHTML",u));h&&(d.parseDOM=h.map(y=>QI(y,c)));const m=on(p,"renderHTML",u);m&&(d.toDOM=y=>m({node:y,HTMLAttributes:fk(y,c)}));const S=on(p,"renderText",u);return S&&(d.toText=S),[p.name,d]})),l=Object.fromEntries(o.map(p=>{const c=r.filter(S=>S.type===p.name),u={name:p.name,options:p.options,storage:p.storage,editor:t},d=eB({...e.reduce((S,y)=>{const w=on(y,"extendMarkSchema",u);return{...S,...w?w(p):{}}},{}),inclusive:Yr(on(p,"inclusive",u)),excludes:Yr(on(p,"excludes",u)),group:Yr(on(p,"group",u)),spanning:Yr(on(p,"spanning",u)),code:Yr(on(p,"code",u)),attrs:Object.fromEntries(c.map(tB))}),h=Yr(on(p,"parseHTML",u));h&&(d.parseDOM=h.map(S=>QI(S,c)));const m=on(p,"renderHTML",u);return m&&(d.toDOM=S=>m({mark:S,HTMLAttributes:fk(S,c)})),[p.name,d]}));return new m4({topNode:a,nodes:s,marks:l})}function HJ(e){const t=e.filter((n,r)=>e.indexOf(n)!==r);return Array.from(new Set(t))}function J0(e){return e.sort((n,r)=>{const i=on(n,"priority")||100,o=on(r,"priority")||100;return i>o?-1:ir.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),t}function U$(e,t,n){const{from:r,to:i}=t,{blockSeparator:o=` + +`,textSerializers:a={}}=n||{};let s="";return e.nodesBetween(r,i,(l,p,c,u)=>{l.isBlock&&p>r&&(s+=o);const d=a?.[l.type.name];if(d)return c&&(s+=d({node:l,pos:p,parent:c,index:u,range:t})),!1;if(l.isText){var h;s+=l==null||(h=l.text)===null||h===void 0?void 0:h.slice(Math.max(r,p)-p,i-p)}}),s}function WJ(e,t){return U$(e,{from:0,to:e.content.size},t)}function q$(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}function GJ(e,t){const n=yo(t,e.schema),{from:r,to:i}=e.selection,o=[];e.doc.nodesBetween(r,i,s=>{o.push(s)});const a=o.reverse().find(s=>s.type.name===n.name);return a?{...a.attrs}:{}}function UJ(e,t){const n=Ix(typeof t=="string"?t:t.name,e.schema);return n==="node"?GJ(e,t):n==="mark"?_$(e,t):{}}function qJ(e,t=JSON.stringify){const n={};return e.filter(r=>{const i=t(r);return Object.prototype.hasOwnProperty.call(n,i)?!1:n[i]=!0})}function VJ(e){const t=qJ(e);return t.length===1?t:t.filter((n,r)=>!t.filter((i,o)=>o!==r).some(i=>n.oldRange.from>=i.oldRange.from&&n.oldRange.to<=i.oldRange.to&&n.newRange.from>=i.newRange.from&&n.newRange.to<=i.newRange.to))}function FR(e){const{mapping:t,steps:n}=e,r=[];return t.maps.forEach((i,o)=>{const a=[];if(i.ranges.length)i.forEach((s,l)=>{a.push({from:s,to:l})});else{const{from:s,to:l}=n[o];if(s===void 0||l===void 0)return;a.push({from:s,to:l})}a.forEach(({from:s,to:l})=>{const p=t.slice(o).map(s,-1),c=t.slice(o).map(l),u=t.invert().map(p,-1),d=t.invert().map(c);r.push({oldRange:{from:u,to:d},newRange:{from:p,to:c}})})}),VJ(r)}function jf(e,t){return t.nodes[e]||t.marks[e]||null}function Nv(e,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const i=e.find(o=>o.type===t&&o.name===r);return i?i.attribute.keepOnSplit:!1}))}const KJ=(e,t=500)=>{let n="";const r=e.parentOffset;return e.parent.nodesBetween(Math.max(0,r-t),r,(i,o,a,s)=>{var l,p;const c=((l=(p=i.type.spec).toText)===null||l===void 0?void 0:l.call(p,{node:i,pos:o,parent:a,index:s}))||i.textContent||"%leaf%";n+=i.isAtom&&!i.isText?c:c.slice(0,Math.max(0,r-o))}),n};function _P(e,t,n={}){const{empty:r,ranges:i}=e.selection,o=t?su(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(c=>o?o.name===c.type.name:!0).find(c=>bk(c.attrs,n,{strict:!1}));let a=0;const s=[];if(i.forEach(({$from:c,$to:u})=>{const d=c.pos,h=u.pos;e.doc.nodesBetween(d,h,(m,S)=>{if(o&&m.inlineContent&&!m.type.allowsMarkType(o))return!1;if(!m.isText&&!m.marks.length)return;const y=Math.max(d,S),w=Math.min(h,S+m.nodeSize),v=w-y;a+=v,s.push(...m.marks.map(x=>({mark:x,from:y,to:w})))})}),a===0)return!1;const l=s.filter(c=>o?o.name===c.mark.type.name:!0).filter(c=>bk(c.mark.attrs,n,{strict:!1})).reduce((c,u)=>c+u.to-u.from,0),p=s.filter(c=>o?c.mark.type!==o&&c.mark.type.excludes(o):!0).reduce((c,u)=>c+u.to-u.from,0);return(l>0?l+p:l)>=a}function ZJ(e,t,n={}){if(!t)return PS(e,null,n)||_P(e,null,n);const r=Ix(t,e.schema);return r==="node"?PS(e,t,n):r==="mark"?_P(e,t,n):!1}function nB(e,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===e.name):t}function OT(e,t){const{nodeExtensions:n}=Wm(t),r=n.find(o=>o.name===e);if(!r)return!1;const i=Yr(on(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function ay(e,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){if(n){if(e.type.name==="hardBreak")return!0;if(e.isText){var r;return!/\S/.test((r=e.text)!==null&&r!==void 0?r:"")}}if(e.isText)return!e.text;if(e.isAtom||e.isLeaf)return!1;if(e.content.childCount===0)return!0;if(t){let i=!0;return e.content.forEach(o=>{i!==!1&&(ay(o,{ignoreWhitespace:n,checkChildren:t})||(i=!1))}),i}return!1}function XJ(e){return e instanceof Vt}var V$=class K${constructor(t){this.position=t}static fromJSON(t){return new K$(t.position)}toJSON(){return{position:this.position}}};function YJ(e,t){const n=t.mapping.mapResult(e.position);return{position:new V$(n.pos),mapResult:n}}function JJ(e){return new V$(e)}function QJ(e,t,n){const{selection:r}=t;let i=null;if(B$(r)&&(i=r.$cursor),i){var o;const s=(o=e.storedMarks)!==null&&o!==void 0?o:i.marks();return i.parent.type.allowsMarkType(n)&&(!!n.isInSet(s)||!s.some(l=>l.type.excludes(n)))}const{ranges:a}=r;return a.some(({$from:s,$to:l})=>{let p=s.depth===0?e.doc.inlineContent&&e.doc.type.allowsMarkType(n):!1;return e.doc.nodesBetween(s.pos,l.pos,(c,u,d)=>{if(p)return!1;if(c.isInline){const h=!d||d.type.allowsMarkType(n),m=!!n.isInSet(c.marks)||!c.marks.some(S=>S.type.excludes(n));p=h&&m}return!p}),p})}const eQ=(e,t={})=>({tr:n,state:r,dispatch:i})=>{const{selection:o}=n,{empty:a,ranges:s}=o,l=su(e,r.schema);if(i)if(a){const p=_$(r,l);n.addStoredMark(l.create({...p,...t}))}else s.forEach(p=>{const c=p.$from.pos,u=p.$to.pos;r.doc.nodesBetween(c,u,(d,h)=>{const m=Math.max(h,c),S=Math.min(h+d.nodeSize,u);d.marks.find(y=>y.type===l)?d.marks.forEach(y=>{l===y.type&&n.addMark(m,S,l.create({...y.attrs,...t}))}):n.addMark(m,S,l.create(t))})});return QJ(r,n,l)},tQ=(e,t)=>({tr:n})=>(n.setMeta(e,t),!0),nQ=(e,t={})=>({state:n,dispatch:r,chain:i})=>{const o=yo(e,n.schema);let a;return n.selection.$anchor.sameParent(n.selection.$head)&&(a=n.selection.$anchor.parent.attrs),o.isTextblock?i().command(({commands:s})=>gI(o,{...a,...t})(n)?!0:s.clearNodes()).command(({state:s})=>gI(o,{...a,...t})(s,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},rQ=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,i=sh(e,0,r.content.size),o=Vt.create(r,i);t.setSelection(o)}return!0},iQ=(e,t)=>({tr:n,state:r,dispatch:i})=>{const{selection:o}=r;let a,s;return typeof t=="number"?(a=t,s=t):t&&"from"in t&&"to"in t?(a=t.from,s=t.to):(a=o.from,s=o.to),i&&n.doc.nodesBetween(a,s,(l,p)=>{l.isText||n.setNodeMarkup(p,void 0,{...l.attrs,dir:e})}),!0},oQ=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:i,to:o}=typeof e=="number"?{from:e,to:e}:e,a=_t.atStart(r).from,s=_t.atEnd(r).to,l=sh(i,a,s),p=sh(o,a,s),c=_t.create(r,l,p);t.setSelection(c)}return!0},aQ=e=>({state:t,dispatch:n})=>{const r=yo(e,t.schema);return QZ(r)(t,n)};function rB(e,t){const n=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();if(n){const r=n.filter(i=>t?.includes(i.type.name));e.tr.ensureMarks(r)}}const sQ=({keepMarks:e=!0}={})=>({tr:t,state:n,dispatch:r,editor:i})=>{const{selection:o,doc:a}=t,{$from:s,$to:l}=o,p=i.extensionManager.attributes,c=Nv(p,s.node().type.name,s.node().attrs);if(o instanceof Vt&&o.node.isBlock)return!s.parentOffset||!Kp(a,s.pos)?!1:(r&&(e&&rB(n,i.extensionManager.splittableMarks),t.split(s.pos).scrollIntoView()),!0);if(!s.parent.isBlock)return!1;const u=l.parentOffset===l.parent.content.size,d=s.depth===0?void 0:O$(s.node(-1).contentMatchAt(s.indexAfter(-1)));let h=u&&d?[{type:d,attrs:c}]:void 0,m=Kp(t.doc,t.mapping.map(s.pos),1,h);if(!h&&!m&&Kp(t.doc,t.mapping.map(s.pos),1,d?[{type:d}]:void 0)&&(m=!0,h=d?[{type:d,attrs:c}]:void 0),r){if(m&&(o instanceof _t&&t.deleteSelection(),t.split(t.mapping.map(s.pos),1,h),d&&!u&&!s.parentOffset&&s.parent.type!==d)){const S=t.mapping.map(s.before()),y=t.doc.resolve(S);s.node(-1).canReplaceWith(y.index(),y.index()+1,d)&&t.setNodeMarkup(t.mapping.map(s.before()),d)}e&&rB(n,i.extensionManager.splittableMarks),t.scrollIntoView()}return m},lQ=(e,t={})=>({tr:n,state:r,dispatch:i,editor:o})=>{const a=yo(e,r.schema),{$from:s,$to:l}=r.selection,p=r.selection.node;if(p&&p.isBlock||s.depth<2||!s.sameParent(l))return!1;const c=s.node(-1);if(c.type!==a)return!1;const u=o.extensionManager.attributes;if(s.parent.content.size===0&&s.node(-1).childCount===s.indexAfter(-1)){if(s.depth===2||s.node(-3).type!==a||s.index(-2)!==s.node(-2).childCount-1)return!1;if(i){var d;let w=vt.empty;const v=s.index(-1)?1:s.index(-2)?2:3;for(let R=s.depth-v;R>=s.depth-3;R-=1)w=vt.from(s.node(R).copy(w));const x=s.indexAfter(-1){if(A>-1)return!1;R.isTextblock&&R.content.size===0&&(A=N+1)}),A>-1&&n.setSelection(_t.near(n.doc.resolve(A))),n.scrollIntoView()}return!0}const h=l.pos===s.end()?c.contentMatchAt(0).defaultType:null,m={...Nv(u,c.type.name,c.attrs),...t},S={...Nv(u,s.node().type.name,s.node().attrs),...t};n.delete(s.pos,l.pos);const y=h?[{type:a,attrs:m},{type:h,attrs:S}]:[{type:a,attrs:m}];if(!Kp(n.doc,s.pos,2))return!1;if(i){const{selection:w,storedMarks:v}=r,{splittableMarks:x}=o.extensionManager,P=v||w.$to.parentOffset&&w.$from.marks();if(n.split(s.pos,2,y).scrollIntoView(),!P||!i)return!0;const T=P.filter(C=>x.includes(C.type.name));n.ensureMarks(T)}return!0};function iB(e){return!e||e==="1"?null:e}function Z$(e,t){return iB(e)===iB(t)}const $T=(e,t)=>{const n=RR(o=>o.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const i=e.doc.nodeAt(r);return!(n.node.type===i?.type&&Bh(e.doc,n.pos))||!Z$(n.node.attrs.type,i?.attrs.type)||e.join(n.pos),!0},_T=(e,t)=>{const n=RR(o=>o.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const i=e.doc.nodeAt(r);return!(n.node.type===i?.type&&Bh(e.doc,r))||!Z$(n.node.attrs.type,i?.attrs.type)||e.join(r),!0};function cQ(e){const t=e.doc,n=t.firstChild;if(!n)return null;const r=t.resolve(1),i=t.resolve(n.nodeSize-1);return _t.between(r,i)}const pQ=(e,t,n,r={})=>({editor:i,tr:o,state:a,dispatch:s,chain:l,commands:p,can:c})=>{const{extensions:u,splittableMarks:d}=i.extensionManager,h=yo(e,a.schema),m=yo(t,a.schema),{selection:S,storedMarks:y}=a,{$from:w,$to:v}=S,x=w.blockRange(v),P=y||S.$to.parentOffset&&S.$from.marks();if(!x)return!1;const T=RR(I=>OT(I.type.name,u))(S),C=S.from===0&&S.to===a.doc.content.size,A=a.doc.content.content,R=A.length===1?A[0]:null,N=C&&R&&OT(R.type.name,u)?{node:R,pos:0}:null,M=T??N,L=!!T&&x.depth>=1&&x.depth-T.depth<=1,F=!!N;if((L||F)&&M){if(M.node.type===h)return C&&F?l().command(({tr:I,dispatch:B})=>{const H=cQ(I);return H?(I.setSelection(H),B&&B(I),!0):!1}).liftListItem(m).run():p.liftListItem(m);if(OT(M.node.type.name,u)&&h.validContent(M.node.content))return l().command(()=>(o.setNodeMarkup(M.pos,h),!0)).command(()=>$T(o,h)).command(()=>_T(o,h)).run()}return!n||!P||!s?l().command(()=>c().wrapInList(h,r)?!0:p.clearNodes()).wrapInList(h,r).command(()=>$T(o,h)).command(()=>_T(o,h)).run():l().command(()=>{const I=c().wrapInList(h,r),B=P.filter(H=>d.includes(H.type.name));return o.ensureMarks(B),I?!0:p.clearNodes()}).wrapInList(h,r).command(()=>$T(o,h)).command(()=>_T(o,h)).run()},uQ=(e,t={},n={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:o=!1}=n,a=su(e,r.schema);return _P(r,a,t)?i.unsetMark(a,{extendEmptyMarkRange:o}):i.setMark(a,t)},dQ=(e,t,n={})=>({state:r,commands:i})=>{const o=yo(e,r.schema),a=yo(t,r.schema),s=PS(r,o,n);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),s?i.setNode(a,l):i.setNode(o,{...l,...n})},bQ=(e,t={})=>({state:n,commands:r})=>{const i=yo(e,n.schema);return PS(n,i,t)?r.lift(i):r.wrapIn(i,t)},hQ=()=>({state:e,dispatch:t})=>{const n=e.plugins;for(let r=0;r=0;l-=1)a.step(s.steps[l].invert(s.docs[l]));if(o.text){const l=a.doc.resolve(o.from).marks();a.replaceWith(o.from,o.to,e.schema.text(o.text,l))}else a.delete(o.from,o.to)}return!0}}return!1},fQ=(e={})=>({tr:t,dispatch:n,editor:r})=>{const{ignoreClearable:i=!1}=e,{selection:o}=t,{empty:a,ranges:s}=o;if(a)return!0;const{nonClearableMarks:l}=r.extensionManager;if(n){const p=Object.values(r.schema.marks).filter(c=>i||!l.includes(c.name));s.forEach(c=>{for(const u of p)t.removeMark(c.$from.pos,c.$to.pos,u)})}return!0},mQ=(e,t={})=>({tr:n,state:r,dispatch:i})=>{const{extendEmptyMarkRange:o=!1}=t,{selection:a}=n,s=su(e,r.schema),{$from:l,empty:p,ranges:c}=a;if(!i)return!0;if(p&&o){var u;let{from:d,to:h}=a;const m=ER(l,s,(u=l.marks().find(S=>S.type===s))===null||u===void 0?void 0:u.attrs);m&&(d=m.from,h=m.to),n.removeMark(d,h,s)}else c.forEach(d=>{n.removeMark(d.$from.pos,d.$to.pos,s)});return n.removeStoredMark(s),!0},gQ=e=>({tr:t,state:n,dispatch:r})=>{const{selection:i}=n;let o,a;return typeof e=="number"?(o=e,a=e):e&&"from"in e&&"to"in e?(o=e.from,a=e.to):(o=i.from,a=i.to),r&&t.doc.nodesBetween(o,a,(s,l)=>{if(s.isText)return;const p={...s.attrs};delete p.dir,t.setNodeMarkup(l,void 0,p)}),!0},SQ=(e,t={})=>({tr:n,state:r,dispatch:i})=>{let o=null,a=null;const s=Ix(typeof e=="string"?e:e.name,r.schema);if(!s)return!1;s==="node"&&(o=yo(e,r.schema)),s==="mark"&&(a=su(e,r.schema));let l=!1;return n.selection.ranges.forEach(p=>{const c=p.$from.pos,u=p.$to.pos;let d,h,m,S;n.selection.empty?r.doc.nodesBetween(c,u,(y,w)=>{o&&o===y.type&&(l=!0,m=Math.max(w,c),S=Math.min(w+y.nodeSize,u),d=w,h=y)}):r.doc.nodesBetween(c,u,(y,w)=>{w=c&&w<=u&&(o&&o===y.type&&(l=!0,i&&n.setNodeMarkup(w,void 0,{...y.attrs,...t})),a&&y.marks.length&&y.marks.forEach(v=>{if(a===v.type&&(l=!0,i)){const x=Math.max(w,c),P=Math.min(w+y.nodeSize,u);n.addMark(x,P,a.create({...v.attrs,...t}))}}))}),h&&(d!==void 0&&i&&n.setNodeMarkup(d,void 0,{...h.attrs,...t}),a&&h.marks.length&&h.marks.forEach(y=>{a===y.type&&i&&n.addMark(m,S,a.create({...y.attrs,...t}))}))}),l},rm=new wn("__tiptap_decorations__"),yQ=e=>({tr:t,dispatch:n})=>(n&&t.setMeta(rm,{type:"force",name:e}),!0),wQ=(e,t={})=>({state:n,dispatch:r})=>{const i=yo(e,n.schema);return qZ(i,t)(n,r)},vQ=(e,t={})=>({state:n,dispatch:r})=>{const i=yo(e,n.schema);return VZ(i,t)(n,r)};var kQ=OK({blur:()=>GY,clearContent:()=>UY,clearNodes:()=>qY,command:()=>VY,createParagraphNear:()=>KY,cut:()=>ZY,deleteCurrentNode:()=>XY,deleteNode:()=>YY,deleteRange:()=>JY,deleteSelection:()=>tJ,enter:()=>nJ,exitCode:()=>rJ,extendMarkRange:()=>iJ,first:()=>oJ,focus:()=>sJ,forEach:()=>lJ,insertContent:()=>cJ,insertContentAt:()=>pJ,insertDefaultBlock:()=>uJ,joinBackward:()=>hJ,joinDown:()=>bJ,joinForward:()=>fJ,joinItemBackward:()=>mJ,joinItemForward:()=>gJ,joinTextblockBackward:()=>SJ,joinTextblockForward:()=>yJ,joinUp:()=>dJ,keyboardShortcut:()=>vJ,lift:()=>kJ,liftEmptyBlock:()=>xJ,liftListItem:()=>TJ,newlineInCode:()=>CJ,resetAttributes:()=>PJ,scrollIntoView:()=>AJ,selectAll:()=>EJ,selectNodeBackward:()=>RJ,selectNodeForward:()=>MJ,selectParentNode:()=>NJ,selectTextblockEnd:()=>FJ,selectTextblockStart:()=>IJ,setContent:()=>BJ,setMark:()=>eQ,setMeta:()=>tQ,setNode:()=>nQ,setNodeSelection:()=>rQ,setTextDirection:()=>iQ,setTextSelection:()=>oQ,sinkListItem:()=>aQ,splitBlock:()=>sQ,splitListItem:()=>lQ,toggleList:()=>pQ,toggleMark:()=>uQ,toggleNode:()=>dQ,toggleWrap:()=>bQ,undoInputRule:()=>hQ,unsetAllMarks:()=>fQ,unsetMark:()=>mQ,unsetTextDirection:()=>gQ,updateAttributes:()=>SQ,updateDecorations:()=>yQ,wrapIn:()=>wQ,wrapInList:()=>vQ});const o0=new WeakMap;function xQ(e,t){var n;o0.set(e,((n=o0.get(e))!==null&&n!==void 0?n:0)+1);try{return t()}finally{var r;const i=((r=o0.get(e))!==null&&r!==void 0?r:1)-1;i>0?o0.set(e,i):o0.delete(e)}}var TQ=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(r=>r.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(r=>r!==t):delete this.callbacks[e]),this}once(e,t){const n=(...r)=>{this.off(e,n),t.apply(this,r)};return this.on(e,n)}removeAllListeners(){this.callbacks={}}};function CQ(e){return e.kind==="widget"}function X$(e,t){const n=[],r=new Set;for(const i of e)i.kind==="widget"&&CQ(i)&&r.add(i.key),n.push(i.toPMDecoration(t));return{decorations:n,widgetKeys:r}}function PQ(e,t,n){const{decorations:r,widgetKeys:i}=X$(t,n);return{set:Mt.create(e,r),widgetKeys:i}}function Y$({position:e,from:t,to:n,docSize:r}){return eY$({position:a.anchor,from:t,to:n,docSize:r})?!0:(a.anchor===n||o.has(i)||(o.add(i),console.warn(`[tiptap warn]: Extension "${i}" returned a decoration outside the requested range [${t}, ${n}). It was ignored.`)),!1))}function EQ(e){var t;const n=(t=e.spec)===null||t===void 0?void 0:t.key;return typeof n=="string"?n:void 0}function J$(e){return e.jsonID==="attr"}function RQ(e){let t=!1;if(e.getMap().forEach(()=>{t=!0}),t||J$(e))return!0;const n=e;return typeof n.from=="number"&&typeof n.to=="number"}function MQ(e,t){let n=null,r=0,i=0;for(let o=0;ot.to);o+=1){const a=i+e.child(o).nodeSize;a>=t.from&&(n===null&&(n=i),r=a),i=a}return n===null?null:{from:n,to:r}}function NQ(e,t){if(e.steps.some(o=>!RQ(o)))return{type:"full"};const n=FR(e).map(({newRange:o})=>o);e.steps.forEach((o,a)=>{if(!J$(o))return;const s=e.mapping.slice(a);n.push({from:s.map(o.pos,-1),to:s.map(o.pos+1)})});const r=[];for(const o of n){const a=MQ(t,o);a&&r.push(a)}r.sort((o,a)=>o.from-a.from);const i=[];for(const o of r){const a=i[i.length-1];a&&o.from<=a.to?a.to=Math.max(a.to,o.to):i.push({...o})}return{type:"ranges",ranges:i}}function Q$(e,t,n,r){return e.map(t,n,{onRemove:i=>{const o=i?.key;typeof o=="string"&&r.delete(o)}})}function FQ(e,t,n){var r,i;const o=(r=t.decorationSetsByExtension[e])!==null&&r!==void 0?r:Mt.empty,a=new Set((i=t.widgetKeysByExtension[e])!==null&&i!==void 0?i:[]);return{set:Q$(o,n.mapping,n.doc,a),widgetKeys:a}}function oB(e,t){const n=Object.values(t).flatMap(r=>r.find());return Mt.create(e,n)}function aB(e){const t=new Set;for(const n of Object.values(e))for(const r of n)t.add(r);return t}function IQ(e,t){var n;switch((n=t.update)!==null&&n!==void 0?n:"document"){case"document":if(t.createInRange)throw new Error(`[tiptap error]: Extension "${e}" provides createInRange() but does not use the "changedRanges" decoration update strategy.`);return;case"changedRanges":if(!t.createInRange)throw new Error(`[tiptap error]: Extension "${e}" uses the "changedRanges" decoration update strategy but does not provide createInRange().`);return;case"manual":if(t.createInRange)throw new Error(`[tiptap error]: Extension "${e}" uses the "manual" decoration update strategy, which is not compatible with createInRange(). createInRange() requires the "changedRanges" strategy.`);if(t.shouldUpdate)throw new Error(`[tiptap error]: Extension "${e}" cannot combine the "manual" decoration update strategy with shouldUpdate().`);return;default:throw new Error(`[tiptap error]: Extension "${e}" uses an unknown decoration update strategy. Expected "document", "changedRanges", or "manual".`)}}function BQ(e,t,n){return n?!0:e.update==="manual"?!1:e.shouldUpdate?e.shouldUpdate(t):t.tr.docChanged}const LQ=new Set;var DQ=class{constructor(e){this.warnedWidgetKeys=new Set,this.warnedOutOfRangeExtensions=new Set,this.handleBeforeTransaction=({nextState:t})=>{const n=rm.getState(t);n&&this.warnDuplicateWidgetKeys(n)},this.editor=e.editor,this.entries=this.resolveEntries(e.entries),this.entries.forEach(({name:t,spec:n})=>IQ(t,n)),this.plugin=this.entries.length>0?this.createPlugin():null,this.editor.on("beforeTransaction",this.handleBeforeTransaction)}destroy(){this.editor.off("beforeTransaction",this.handleBeforeTransaction)}liveWidgetKeys(){var e,t;return(e=(t=rm.getState(this.editor.state))===null||t===void 0?void 0:t.widgetKeys)!==null&&e!==void 0?e:LQ}get mountedView(){return this.editor.isDestroyed?null:this.editor.view}resolveEntries(e){const t=[];for(const{name:n,addDecorations:r}of e){const i=r();i&&t.push({name:n,spec:i})}return t}createPlugin(){const{editor:e,entries:t}=this;return new sn({key:rm,state:{init:(n,r)=>{const i={},o={};for(const{name:s,spec:l}of t){const{set:p,widgetKeys:c}=this.buildFullSet(s,l,r);i[s]=p,o[s]=c}const a={decorationSetsByExtension:i,widgetKeysByExtension:o,mergedDecorationSet:this.buildMergedSet(r.doc,i),widgetKeys:aB(o)};return this.warnDuplicateWidgetKeys(a),a},apply:(n,r,i,o)=>{const a=n.getMeta(rm),s=a?.type==="force"&&!a.name,l=a?.type==="force"?a.name:void 0,p={},c={},u=new Set;return xQ(e,()=>{for(const{name:d,spec:h}of t){const m=s||l===d;if(BQ(h,{editor:e,tr:n,oldState:i,newState:o},m))if(h.update==="changedRanges"&&n.docChanged&&!m){const S=this.applyChangedRangesRecompute(d,h,r,n,o);p[d]=S.set,c[d]=S.widgetKeys,u.add(d)}else{const{set:S,widgetKeys:y}=this.buildFullSet(d,h,o);p[d]=S,c[d]=y,u.add(d)}else{const S=FQ(d,r,n);p[d]=S.set,c[d]=S.widgetKeys}}}),u.size===0&&!n.docChanged?r:{decorationSetsByExtension:p,widgetKeysByExtension:c,mergedDecorationSet:this.mergeAfterApply({entries:t,previous:r,tr:n,decorationSetsByExtension:p,recomputedNames:u}),widgetKeys:aB(c)}}},props:{decorations(n){var r,i;return(r=(i=rm.getState(n))===null||i===void 0?void 0:i.mergedDecorationSet)!==null&&r!==void 0?r:Mt.empty}}})}applyChangedRangesRecompute(e,t,n,r,i){const o=NQ(r,i.doc);return o.type==="full"?this.buildFullSet(e,t,i):this.rebuildRanges(e,t,n,r,i,o.ranges)}rebuildRanges(e,t,n,r,i,o){var a,s;const l=(a=n.decorationSetsByExtension[e])!==null&&a!==void 0?a:Mt.empty,p=new Set((s=n.widgetKeysByExtension[e])!==null&&s!==void 0?s:[]);let c=Q$(l,r.mapping,r.doc,p);const u=i.doc.content.size;for(const{from:d,to:h}of o){const m=c.find(d,h).filter(w=>Y$({position:w.from,from:d,to:h,docSize:u}));for(const w of m){const v=EQ(w);v&&p.delete(v)}c=c.remove(m);const{decorations:S,widgetKeys:y}=X$(AQ({decorations:this.runCreate(e,"createInRange",()=>t.createInRange({editor:this.editor,state:i,view:this.mountedView,from:d,to:h})),from:d,to:h,docSize:u,extensionName:e,warnedExtensions:this.warnedOutOfRangeExtensions}),e);c=c.add(i.doc,S);for(const w of y)p.add(w)}return{set:c,widgetKeys:p}}buildFullSet(e,t,n){const r=this.runCreate(e,"create",()=>t.create({editor:this.editor,state:n,view:this.mountedView}));return PQ(n.doc,r,e)}runCreate(e,t,n){try{return n()}catch(r){return console.error(`[tiptap error]: Extension "${e}" threw in \`addDecorations().${t}()\`. Its decorations were dropped for this update.`,r),[]}}warnDuplicateWidgetKeys(e){}buildMergedSet(e,t){const n=Object.keys(t);return n.length===1?t[n[0]]:oB(e,t)}mergeAfterApply({entries:e,previous:t,tr:n,decorationSetsByExtension:r,recomputedNames:i}){return e.length===1?r[e[0].name]:i.size===0?t.mergedDecorationSet.map(n.mapping,n.doc):oB(n.doc,r)}};function zQ(e,t,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return t&&i.setAttribute("nonce",t),i.setAttribute("data-tiptap-style",""),i.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(i),i}function jQ(e){return typeof e=="number"}function OQ(e){return Object.prototype.toString.call(e).slice(8,-1)}function Mw(e){return OQ(e)!=="Object"?!1:e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function e6(e,t){const n={...e};return Mw(e)&&Mw(t)&&Object.keys(t).forEach(r=>{Mw(t[r])&&Mw(e[r])?n[r]=e6(e[r],t[r]):n[r]=t[r]}),n}function $Q(e,t,n={}){const{state:r}=t,{doc:i,tr:o}=r,a=e;i.descendants((s,l)=>{const p=o.mapping.map(l),c=o.mapping.map(l)+s.nodeSize;let u=null;if(s.marks.forEach(h=>{if(h!==a)return!1;u=h}),!u)return;let d=!1;if(Object.keys(n).forEach(h=>{n[h]!==u.attrs[h]&&(d=!0)}),d){const h=e.type.create({...e.attrs,...n});o.removeMark(p,c,e.type),o.addMark(p,c,h)}}),o.docChanged&&t.view.dispatch(o)}const _Q=(e,t)=>{if(AR(t))return t.exec(e);const n=t(e);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=e,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function Nw(e){var t;const{editor:n,from:r,to:i,text:o,rules:a,plugin:s}=e,{view:l}=n;if(l.composing)return!1;const p=l.state.doc.resolve(r);if(p.parent.type.spec.code||!((t=p.nodeBefore||p.nodeAfter)===null||t===void 0)&&t.marks.find(d=>d.type.spec.code))return!1;let c=!1;const u=KJ(p)+o;return a.forEach(d=>{if(c)return;const h=_Q(u,d.find);if(!h)return;const m=h[0].length-o.length;if(m>0){const T=p.parentOffset-m;if(T<0||p.parent.textBetween(T,p.parentOffset)!==h[0].slice(0,m))return}const S=l.state.tr,y=Fx({state:l.state,transaction:S}),w={from:r-(h[0].length-o.length),to:i},{commands:v,chain:x,can:P}=new Em({editor:n,state:y});d.handler({state:y,range:w,match:h,commands:v,chain:x,can:P})===null||!S.steps.length||(d.undoable&&S.setMeta(s,{transform:S,from:r,to:i,text:o}),l.dispatch(S),c=!0)}),c}function HQ(e){const{editor:t,rules:n}=e,r=new sn({state:{init(){return null},apply(i,o,a){const s=i.getMeta(r);if(s)return s;const l=i.getMeta("applyInputRules");return l&&setTimeout(()=>{let{text:p}=l;typeof p=="string"?p=p:p=NR(vt.from(p),a.schema);const{from:c}=l,u=c+p.length;Nw({editor:t,from:c,to:u,text:p,rules:n,plugin:r})}),i.selectionSet||i.docChanged?null:o}},props:{handleTextInput(i,o,a,s){return Nw({editor:t,from:o,to:a,text:s,rules:n,plugin:r})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:o}=i.state.selection;o&&Nw({editor:t,from:o.pos,to:o.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(i,o){if(o.key!=="Enter")return!1;const{$cursor:a}=i.state.selection;return a?Nw({editor:t,from:a.pos,to:a.pos,text:` +`,rules:n,plugin:r}):!1}},isInputRules:!0});return r}var IR=class{constructor(e={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...e},this.name=this.config.name}get options(){return{...Yr(on(this,"addOptions",{name:this.name}))}}get storage(){return{...Yr(on(this,"addStorage",{name:this.name,options:this.options}))}}configure(e={}){const t=this.extend({...this.config,addOptions:()=>e6(this.options,e)});return t.name=this.name,t.parent=this.parent,this.child=null,t}extend(e={}){const t=new this.constructor({...this.config,...e});return t.parent=this,this.child=t,t.name="name"in e?e.name:t.parent.name,t}},Ea=class t6 extends IR{constructor(...t){super(...t),this.type="mark"}static create(t={}){const n=typeof t=="function"?t():t;return new t6(n)}static handleExit({editor:t,mark:n}){const{tr:r}=t.state,i=t.state.selection.$from;if(i.pos===i.end()){const o=i.marks();if(!o.find(s=>s?.type.name===n.name))return!1;const a=o.find(s=>s?.type.name===n.name);return a&&r.removeStoredMark(a),r.insertText(" ",i.pos),t.view.dispatch(r),!0}return!1}configure(t){return super.configure(t)}extend(t){const n=typeof t=="function"?t():t;return super.extend(n)}};const WQ=(e,t,n)=>{if(AR(t))return[...e.matchAll(t)];const r=t(e,n);return r?r.map(i=>{const o=[i.text];return o.index=i.index,o.input=e,o.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),o.push(i.replaceWith)),o}):[]};function GQ(e){const{editor:t,state:n,from:r,to:i,rule:o,pasteEvent:a,dropEvent:s}=e,{commands:l,chain:p,can:c}=new Em({editor:t,state:n}),u=[];return n.doc.nodesBetween(r,i,(d,h)=>{var m,S,y,w;if(!((m=d.type)===null||m===void 0||(m=m.spec)===null||m===void 0)&&m.code||!(d.isText||d.isTextblock||d.isInline))return;const v=(S=(y=(w=d.content)===null||w===void 0?void 0:w.size)!==null&&y!==void 0?y:d.nodeSize)!==null&&S!==void 0?S:0,x=Math.max(r,h),P=Math.min(i,h+v);if(x>=P)return;const T=d.isText?d.text||"":d.textBetween(x-h,P-h,void 0,"");WQ(T,o.find,a).forEach(C=>{if(C.index===void 0)return;const A=x+C.index+1,R=A+C[0].length,N={from:n.tr.mapping.map(A),to:n.tr.mapping.map(R)},M=o.handler({state:n,range:N,match:C,commands:l,chain:p,can:c,pasteEvent:a,dropEvent:s});u.push(M)})}),u.every(d=>d!==null)}let Fw=null;const UQ=e=>{var t;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(t=n.clipboardData)===null||t===void 0||t.setData("text/html",e),n};function qQ(e){const{editor:t,rules:n}=e;let r=null,i=!1,o=!1,a=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,s;try{s=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{s=null}const l=({state:p,from:c,to:u,rule:d,pasteEvt:h})=>{const m=p.tr,S=Fx({state:p,transaction:m});if(!(!GQ({editor:t,state:S,from:Math.max(c-1,0),to:u.b-1,rule:d,pasteEvent:h,dropEvent:s})||!m.steps.length)){try{s=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{s=null}return a=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,m}};return n.map(p=>new sn({view(c){const u=h=>{var m;r=!((m=c.dom.parentElement)===null||m===void 0)&&m.contains(h.target)?c.dom.parentElement:null,r&&(Fw=t)},d=()=>{Fw&&(Fw=null)};return window.addEventListener("dragstart",u),window.addEventListener("dragend",d),{destroy(){window.removeEventListener("dragstart",u),window.removeEventListener("dragend",d)}}},props:{handleDOMEvents:{drop:(c,u)=>{if(o=r===c.dom.parentElement,s=u,!o){const d=Fw;d?.isEditable&&setTimeout(()=>{const h=d.state.selection;h&&d.commands.deleteRange({from:h.from,to:h.to})},10)}return!1},paste:(c,u)=>{var d;const h=(d=u.clipboardData)===null||d===void 0?void 0:d.getData("text/html");return a=u,i=!!h?.includes("data-pm-slice"),!1}}},appendTransaction:(c,u,d)=>{const h=c[0],m=h.getMeta("uiEvent")==="paste"&&!i,S=h.getMeta("uiEvent")==="drop"&&!o,y=h.getMeta("applyPasteRules"),w=!!y;if(!m&&!S&&!w)return;if(w){let{text:P}=y;typeof P=="string"?P=P:P=NR(vt.from(P),d.schema);const{from:T}=y,C=T+P.length,A=UQ(P);return l({rule:p,state:d,from:T,to:{b:C},pasteEvt:A})}const v=u.doc.content.findDiffStart(d.doc.content),x=u.doc.content.findDiffEnd(d.doc.content);if(!(!jQ(v)||!x||v===x.b))return l({rule:p,state:d,from:v,to:x,pasteEvt:a})}}))}var Bx=class{constructor(e,t){this.splittableMarks=[],this.nonClearableMarks=[],this.decorationManager=null,this.editor=t,this.baseExtensions=e,this.extensions=G$(e),this.schema=_J(this.extensions,t),this.setupExtensions()}get commands(){return this.extensions.reduce((e,t)=>{const n=on(t,"addCommands",{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:this.editor,type:jf(t.name,this.schema)});return n?{...e,...n()}:e},{})}get plugins(){const{editor:e}=this,t=J0([...this.extensions].reverse()).flatMap(r=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:jf(r.name,this.schema)},o=[],a=on(r,"addKeyboardShortcuts",i);let s={};if(r.type==="mark"&&on(r,"exitable",i)&&(s.ArrowRight=()=>Ea.handleExit({editor:e,mark:r})),a){const d=Object.fromEntries(Object.entries(a()).map(([h,m])=>[h,()=>m({editor:e})]));s={...s,...d}}const l=WY(s);o.push(l);const p=on(r,"addInputRules",i);if(nB(r,e.options.enableInputRules)&&p){const d=p();if(d&&d.length){const h=HQ({editor:e,rules:d}),m=Array.isArray(h)?h:[h];o.push(...m)}}const c=on(r,"addPasteRules",i);if(nB(r,e.options.enablePasteRules)&&c){const d=c();if(d&&d.length){const h=qQ({editor:e,rules:d});o.push(...h)}}const u=on(r,"addProseMirrorPlugins",i);if(u){const d=u();o.push(...d)}return o}),n=this.createDecorationPlugin();return n&&t.push(n),t}createDecorationPlugin(){var e;const{editor:t}=this;(e=this.decorationManager)===null||e===void 0||e.destroy();const n=[];return this.extensions.forEach(r=>{const i=on(r,"addDecorations",{name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:jf(r.name,this.schema)});i&&n.push({name:r.name,addDecorations:i})}),this.decorationManager=new DQ({editor:t,entries:n}),this.decorationManager.plugin}get attributes(){return W$(this.extensions)}get nodeViews(){const{editor:e}=this,{nodeExtensions:t}=Wm(this.extensions);return Object.fromEntries(t.filter(n=>!!on(n,"addNodeView")).map(n=>{const r=this.attributes.filter(s=>s.type===n.name),i=on(n,"addNodeView",{name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:e,type:yo(n.name,this.schema)});if(!i)return[];const o=i();if(!o)return[];const a=(s,l,p,c,u)=>{const d=fk(s,r);return o({node:s,view:l,getPos:p,decorations:c,innerDecorations:u,editor:e,extension:n,HTMLAttributes:d})};return[n.name,a]}))}dispatchTransaction(e){const{editor:t}=this;return J0([...this.extensions].reverse()).reduceRight((n,r)=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:jf(r.name,this.schema)},o=on(r,"dispatchTransaction",i);return o?a=>{o.call(i,{transaction:a,next:n})}:n},e)}transformPastedHTML(e){const{editor:t}=this;return J0([...this.extensions]).reduce((n,r)=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:jf(r.name,this.schema)},o=on(r,"transformPastedHTML",i);return o?(a,s)=>{const l=n(a,s);return o.call(i,l)}:n},e||(n=>n))}get markViews(){const{editor:e}=this,{markExtensions:t}=Wm(this.extensions);return Object.fromEntries(t.filter(n=>!!on(n,"addMarkView")).map(n=>{const r=this.attributes.filter(a=>a.type===n.name),i=on(n,"addMarkView",{name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:e,type:su(n.name,this.schema)});if(!i)return[];const o=(a,s,l)=>{const p=fk(a,r);return i()({mark:a,view:s,inline:l,editor:e,extension:n,HTMLAttributes:p,updateAttributes:c=>{$Q(a,e,c)}})};return[n.name,o]}))}destroy(){var e;(e=this.decorationManager)===null||e===void 0||e.destroy(),this.extensions.forEach(t=>{let n=t;for(;n.parent;){const r=n.parent;r.child===n&&(r.child=null),n=r}}),this.extensions=[],this.baseExtensions=[],this.decorationManager=null,this.schema=null,this.editor=null}setupExtensions(){const e=this.extensions;this.editor.extensionStorage=Object.fromEntries(e.map(t=>[t.name,t.storage])),e.forEach(t=>{const n={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:this.editor,type:jf(t.name,this.schema)};if(t.type==="mark"){var r,i;(!((r=Yr(on(t,"keepOnSplit",n)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(t.name),!((i=Yr(on(t,"clearable",n)))!==null&&i!==void 0)||i||this.nonClearableMarks.push(t.name)}const o=on(t,"onBeforeCreate",n),a=on(t,"onCreate",n),s=on(t,"onUpdate",n),l=on(t,"onSelectionUpdate",n),p=on(t,"onTransaction",n),c=on(t,"onFocus",n),u=on(t,"onBlur",n),d=on(t,"onDestroy",n);o&&this.editor.on("beforeCreate",o),a&&this.editor.on("create",a),s&&this.editor.on("update",s),l&&this.editor.on("selectionUpdate",l),p&&this.editor.on("transaction",p),c&&this.editor.on("focus",c),u&&this.editor.on("blur",u),d&&this.editor.on("destroy",d)})}};Bx.resolve=G$;Bx.sort=J0;Bx.flatten=MR;var bn=class n6 extends IR{constructor(...t){super(...t),this.type="extension"}static create(t={}){const n=typeof t=="function"?t():t;return new n6(n)}configure(t){return super.configure(t)}extend(t){const n=typeof t=="function"?t():t;return super.extend(n)}};const VQ=bn.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new sn({key:new wn("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:e}=this,{state:t,schema:n}=e,{doc:r,selection:i}=t,o=q$(n),{blockSeparator:a}=this.options,s={...a!==void 0?{blockSeparator:a}:{},textSerializers:o};return[...i.ranges].sort((l,p)=>l.$from.pos-p.$from.pos).map(({$from:l,$to:p})=>U$(r,{from:l.pos,to:p.pos},s)).join(a??` + +`)}}})]}}),KQ=bn.create({name:"commands",addCommands(){return{...kQ}}}),ZQ=bn.create({name:"delete",onUpdate({transaction:e,appendedTransactions:t}){var n,r;const i=()=>{var o,a,s;if((o=(a=this.editor.options.coreExtensionOptions)===null||a===void 0||(a=a.delete)===null||a===void 0||(s=a.filterTransaction)===null||s===void 0?void 0:s.call(a,e))!==null&&o!==void 0?o:e.getMeta("y-sync$"))return;const l=LJ(e.before,[e,...t]);FR(l).forEach(c=>{l.mapping.mapResult(c.oldRange.from).deletedAfter&&l.mapping.mapResult(c.oldRange.to).deletedBefore&&l.before.nodesBetween(c.oldRange.from,c.oldRange.to,(u,d)=>{const h=d+u.nodeSize-2,m=c.oldRange.from<=d&&h<=c.oldRange.to;this.editor.emit("delete",{type:"node",node:u,from:d,to:h,newFrom:l.mapping.map(d),newTo:l.mapping.map(h),deletedRange:c.oldRange,newRange:c.newRange,partial:!m,editor:this.editor,transaction:e,combinedTransform:l})})});const p=l.mapping;l.steps.forEach((c,u)=>{if(c instanceof Es){var d,h;const m=p.slice(u).map(c.from,-1),S=p.slice(u).map(c.to),y=p.invert().map(m,-1),w=p.invert().map(S),v=m>0?(d=l.doc.nodeAt(m-1))===null||d===void 0?void 0:d.marks.some(P=>P.eq(c.mark)):!1,x=(h=l.doc.nodeAt(S))===null||h===void 0?void 0:h.marks.some(P=>P.eq(c.mark));this.editor.emit("delete",{type:"mark",mark:c.mark,from:c.from,to:c.to,deletedRange:{from:y,to:w},newRange:{from:m,to:S},partial:!!(x||v),editor:this.editor,transaction:e,combinedTransform:l})}})};!((n=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&n!==void 0)||n?setTimeout(i,0):i()}}),XQ=bn.create({name:"drop",addProseMirrorPlugins(){return[new sn({key:new wn("tiptapDrop"),props:{handleDrop:(e,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),YQ=bn.create({name:"editable",addProseMirrorPlugins(){return[new sn({key:new wn("editable"),props:{editable:()=>this.editor.options.editable}})]}}),JQ=new wn("focusEvents"),QQ=bn.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:e}=this;return[new sn({key:JQ,props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;const r=e.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;const r=e.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),eee=bn.create({name:"keymap",addKeyboardShortcuts(){const e=()=>this.editor.commands.first(({commands:a})=>[()=>a.undoInputRule(),()=>a.command(({tr:s})=>{const{selection:l,doc:p}=s,{empty:c,$anchor:u}=l,{pos:d,parent:h}=u,m=u.parent.isTextblock&&d>0?s.doc.resolve(d-1):u,S=m.parent.type.spec.isolating,y=u.pos-u.parentOffset,w=S&&m.parent.childCount===1?y===u.pos:Sn.atStart(p).from===d;return!c||!h.type.isTextblock||h.textContent.length||!w||w&&u.parent.type.name==="paragraph"?!1:a.clearNodes()}),()=>a.deleteSelection(),()=>a.joinBackward(),()=>a.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:a})=>[()=>a.deleteSelection(),()=>a.deleteCurrentNode(),()=>a.joinForward(),()=>a.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:a})=>[()=>a.newlineInCode(),()=>a.createParagraphNear(),()=>a.liftEmptyBlock(),()=>a.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},o={...r,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return hk()||$$()?o:i},addProseMirrorPlugins(){return[new sn({key:new wn("clearDocument"),appendTransaction:(e,t,n)=>{if(e.some(h=>h.getMeta("composition")))return;const r=e.some(h=>h.docChanged)&&!t.doc.eq(n.doc),i=e.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:o,from:a,to:s}=t.selection,l=Sn.atStart(t.doc).from,p=Sn.atEnd(t.doc).to;if(o||!(a===l&&s===p)||!ay(n.doc))return;const c=n.tr,u=Fx({state:n,transaction:c}),{commands:d}=new Em({editor:this.editor,state:u});if(d.clearNodes(),!!c.steps.length)return c}})]}}),tee=bn.create({name:"paste",addProseMirrorPlugins(){return[new sn({key:new wn("tiptapPaste"),props:{handlePaste:(e,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),nee=bn.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new sn({key:new wn("tabindex"),props:{attributes:()=>{var e;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(e=this.options.value)!==null&&e!==void 0?e:"0"}}}})]}}),ree=bn.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:e}=Wm(this.extensions);return[{types:e.filter(t=>t.name!=="text").map(t=>t.name),attributes:{dir:{default:this.options.direction,parseHTML:t=>{const n=t.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:t=>t.dir?{dir:t.dir}:{}}}}]},addProseMirrorPlugins(){return[new sn({key:new wn("textDirection"),props:{attributes:()=>{const e=this.options.direction;return e?{dir:e}:{}}}})]}});let sB=!1;function iee(e){if(sB)return;sB=!0;let t;try{t=yi.fromJSON(e,{from:0,to:0}).slice.content}catch{return}t instanceof vt||console.warn("[tiptap warn]: prosemirror-model is loaded more than once. Wrapping and splitting nodes will fail. Deduplicate it in your lock file, or alias it to a single copy in your bundler.")}var oee=class N0{get name(){return this.node.type.name}constructor(t,n,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=t,this.editor=n,this.currentNode=i}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var t;return(t=this.actualDepth)!==null&&t!==void 0?t:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(t){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},t)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const t=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(t);return new N0(n,this.editor)}get before(){let t=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return t.depth!==this.depth&&(t=this.resolvedPos.doc.resolve(this.from-3)),new N0(t,this.editor)}get after(){let t=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return t.depth!==this.depth&&(t=this.resolvedPos.doc.resolve(this.to+3)),new N0(t,this.editor)}get children(){const t=[];return this.node.content.forEach((n,r)=>{const i=n.isBlock&&!n.isTextblock,o=n.isAtom&&!n.isText,a=n.isInline,s=this.pos+r+(o?0:1);if(s<0||s>this.resolvedPos.doc.nodeSize-2)return;const l=this.resolvedPos.doc.resolve(s);if(!i&&!a&&l.depth<=this.depth)return;const p=new N0(l,this.editor,i,i||a?n:null);i&&(p.actualDepth=this.depth+1),t.push(p)}),t}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,n={}){let r=null,i=this.parent;for(;i&&!r;){if(i.node.type.name===t)if(Object.keys(n).length>0){const o=i.node.attrs,a=Object.keys(n);for(let s=0;s{r&&i.length>0||(a.node.type.name===t&&o.every(s=>n[s]===a.node.attrs[s])&&i.push(a),!(r&&i.length>0)&&(i=i.concat(a.querySelectorAll(t,n,r))))}),i}setAttribute(t){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(n)}};const aee=`.ProseMirror { + position: relative; +} + +.ProseMirror { + word-wrap: break-word; + white-space: pre-wrap; + white-space: break-spaces; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ +} + +.ProseMirror [contenteditable="false"] { + white-space: normal; +} + +.ProseMirror [contenteditable="false"] [contenteditable="true"] { + white-space: pre-wrap; +} + +.ProseMirror pre { + white-space: pre-wrap; +} + +img.ProseMirror-separator { + display: inline !important; + border: none !important; + margin: 0 !important; + width: 0 !important; + height: 0 !important; +} + +.ProseMirror-gapcursor { + display: none; + pointer-events: none; + position: absolute; + margin: 0; +} + +.ProseMirror-gapcursor:after { + content: ""; + display: block; + position: absolute; + top: -2px; + width: 20px; + border-top: 1px solid black; + animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; +} + +@keyframes ProseMirror-cursor-blink { + to { + visibility: hidden; + } +} + +.ProseMirror-hideselection *::selection { + background: transparent; +} + +.ProseMirror-hideselection *::-moz-selection { + background: transparent; +} + +.ProseMirror-hideselection * { + caret-color: transparent; +} + +.ProseMirror-focused .ProseMirror-gapcursor { + display: block; +}`;var r6=class extends TQ{constructor(e={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.hasWarnedStaleDecorationRead=!1,this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:n})=>{throw n},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:YJ,createMappablePosition:JJ},this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:n,slice:r,moved:i})=>this.options.onDrop(n,r,i)),this.on("paste",({event:n,slice:r})=>this.options.onPaste(n,r)),this.on("delete",this.options.onDelete);const t=this.createDoc();if(!this.editorState){const n=OP(t,this.options.autofocus);this.editorState=Ed.create({doc:t,schema:this.schema,selection:n||void 0})}iee(this.schema),this.options.element&&this.mount(this.options.element)}mount(e){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(e),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){this.editorState=this.editorView.state;const e=this.editorView.dom;e?.editor&&delete e.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(e){console.warn("Failed to remove CSS element:",e)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager?this.commandManager.chain():Em.createFakeChain()}can(){return this.commandManager?this.commandManager.can():Em.createFallbackCan()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=zQ(aee,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(e,t=!0){this.setOptions({editable:e}),t&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:e=>{this.editorState=e},dispatch:e=>{this.dispatchTransaction(e)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(e,t)=>{if(this.editorView)return this.editorView[t];if(t==="state")return this.editorState;if(t in e)return Reflect.get(e,t);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${t}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(e,t){const n=H$(t)?t(e,[...this.state.plugins]):[...this.state.plugins,e],r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}unregisterPlugin(e){if(this.isDestroyed)return;const t=this.state.plugins;let n=t;if([].concat(e).forEach(i=>{const o=typeof i=="string"?`${i}$`:i.key;n=n.filter(a=>!a.key.startsWith(o))}),t.length===n.length)return;const r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}createExtensionManager(){var e,t;const n=[...this.options.enableCoreExtensions?[YQ,VQ.configure({blockSeparator:(e=this.options.coreExtensionOptions)===null||e===void 0||(e=e.clipboardTextSerializer)===null||e===void 0?void 0:e.blockSeparator}),KQ,QQ,eee,nee.configure({value:(t=this.options.coreExtensionOptions)===null||t===void 0||(t=t.tabindex)===null||t===void 0?void 0:t.value}),XQ,tee,ZQ,ree.configure({direction:this.options.textDirection})].filter(r=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[r.name]!==!1:!0):[],...this.options.extensions].filter(r=>["extension","node","mark"].includes(r?.type));this.extensionManager=new Bx(n,this)}createCommandManager(){this.commandManager=new Em({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=$P(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(t){if(!(t instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(t.message))throw t;const n=$P(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1});return this.editorState=Ed.create({doc:n,schema:this.schema,selection:OP(n,this.options.autofocus)||void 0}),this.emit("contentError",{editor:this,error:t,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(r=>r.name!=="collaboration"),this.createExtensionManager()}}),this.editorState.doc}return e}createView(e){const{editorProps:t,enableExtensionDispatchTransaction:n}=this.options,r=t.dispatchTransaction||this.dispatchTransaction.bind(this),i=n?this.extensionManager.dispatchTransaction(r):r,o=t.transformPastedHTML,a=this.extensionManager.transformPastedHTML(o);this.editorView=new N$(e,{...t,attributes:{role:"textbox",...t?.attributes},dispatchTransaction:i,transformPastedHTML:a,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const s=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(s),this.prependClass(),this.injectCSS();const l=this.view.dom;l.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(e){this.isCapturingTransaction=!0,e(),this.isCapturingTransaction=!1;const t=this.capturedTransaction;return this.capturedTransaction=null,t}dispatchTransaction(e){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=e;return}e.steps.forEach(p=>{var c;return(c=this.capturedTransaction)===null||c===void 0?void 0:c.step(p)});return}const{state:t,transactions:n}=this.state.applyTransaction(e),r=!this.state.selection.eq(t.selection),i=n.includes(e),o=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:e,nextState:t}),!i)return;this.view.updateState(t),this.emit("transaction",{editor:this,transaction:e,appendedTransactions:n.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:e});const a=n.findLast(p=>p.getMeta("focus")||p.getMeta("blur")),s=a?.getMeta("focus"),l=a?.getMeta("blur");s&&this.emit("focus",{editor:this,event:s.event,transaction:a}),l&&this.emit("blur",{editor:this,event:l.event,transaction:a}),!(e.getMeta("preventUpdate")||!n.some(p=>p.docChanged)||o.doc.eq(t.doc))&&this.emit("update",{editor:this,transaction:e,appendedTransactions:n.slice(1)})}getAttributes(e){return UJ(this.state,e)}isActive(e,t){const n=typeof e=="string"?e:null,r=typeof e=="string"?t:e;return ZJ(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return NR(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:t=` + +`,textSerializers:n={}}=e||{};return WJ(this.state.doc,{blockSeparator:t,textSerializers:{...q$(this.schema),...n}})}get isEmpty(){return ay(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit("destroy"),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){var e,t;return(e=(t=this.editorView)===null||t===void 0?void 0:t.isDestroyed)!==null&&e!==void 0?e:!0}$node(e,t){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelector(e,t))||null}$nodes(e,t){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelectorAll(e,t))||null}$pos(e){const t=this.state.doc.resolve(e),n=e>0&&t.nodeAfter&&!t.nodeAfter.isText&&t.nodeAfter.isAtom?t.nodeAfter:null;return new oee(t,this,!1,n)}get $doc(){return this.$pos(0)}},Yi=class i6 extends IR{constructor(...t){super(...t),this.type="node"}static create(t={}){const n=typeof t=="function"?t():t;return new i6(n)}configure(t){return super.configure(t)}extend(t){const n=typeof t=="function"?t():t;return super.extend(n)}};const see='[class*="-wrap-square-"], [class*="-wrap-tight-"], [class*="-wrap-through-"], [class*="doc-table-float-"]:not(.doc-table-float-flow), .doc-cell-boxes';class mk{constructor(t,n=()=>!1){this.shift=t,this.stableNow=n}shift;stableNow;results=new Map;floatBands=[];gen=0;clear(){this.results.clear()}beginPass(t){this.gen++;for(const[n,r]of this.results)r.gen{const r=n.getBoundingClientRect(),i=getComputedStyle(n);return[r.top-(parseFloat(i.marginTop)||0),r.bottom+(parseFloat(i.marginBottom)||0)]})}static topLevelDom(t){const n=new Map;for(const r of Array.from(t.dom.childNodes)){const i=r.pmViewDesc;i?.node&&r instanceof HTMLElement&&n.set(i.node,r)}return n}measure(t,n,r,i,o){const a=o??t.nodeDOM(r);if(!(a instanceof HTMLElement))return null;let s=`${a.offsetHeight}:${a.offsetWidth}`;if(this.floatBands.length>0){const u=a.getBoundingClientRect();this.floatBands.some(([d,h])=>u.topd)&&(s=`${u.top}:${s}`)}const l=this.results.get(n);if(l&&(l.gen=this.gen),l?.settled&&l.rectKey===s)return l.pos===r?l.result:this.shift(l.result,r-l.pos);const p=i(a);if(p===null)return this.results.delete(n),null;const c=JSON.stringify(this.shift(p,-r));return this.results.set(n,{pos:r,key:c,rectKey:s,result:p,settled:l!==void 0&&l.key===c||this.stableNow(p),gen:this.gen}),p}}function Zd(){let e;return()=>e??=document.createRange()}const Ch="genoffice:phased-content-settled",lB=64,lee=128,cee=192;let Fv=0,o6=Promise.resolve(),AS=null;function sy(){return o6}function Lx(){return AS!==null}function a6(){Fv++,AS?.(),AS=null}const pee=e=>{requestAnimationFrame(()=>requestAnimationFrame(e))};function uee(e,t,n=pee){a6();const r=t.content??[],i=++Fv;if(r.length<=cee){e.setContent(t);return}e.setContent({...t,content:r.slice(0,lB)});let o;o6=new Promise(p=>o=p),e.setLoading(!0),AS=()=>{e.setLoading(!1),o()};let a=lB;const s=()=>{i===Fv&&(e.isDestroyed()||e.resetHistory(),AS=null,e.setLoading(!1),o(),typeof document<"u"&&document.dispatchEvent(new Event(Ch)))},l=()=>{if(i!==Fv)return;if(e.isDestroyed())return s();const p=r.slice(a,a+lee);a+=p.length;const c=e.getDirty();try{e.appendNodes(p)}catch{try{e.setContent(t)}catch{}return e.setDirty(c),s()}e.setDirty(c),a{const n=t.gaps.reduce((u,d)=>u+d.width,0),r=t.gaps.reduce((u,d)=>u+d.chars,0),i=t.wordWidths.reduce((u,d)=>u+d,0)+n,o=i-t.avail;if(o>pB)return r===0?null:{gaps:t.gaps,perChar:(o+cB)/r};const a=t.boundary,s=t.nextWordWidth;if(!a||a.chars===0||s==null)return null;const l=i+a.width+s-t.avail;if(l<=pB)return null;const p=r+a.chars,c=p-a.chars;return c<1||l>dee*(n+a.width)||l/p>bee*(s+a.width-l)/c?null:{gaps:[...t.gaps,a],perChar:(l+cB)/p}})}const xd=new wn("justifyShrink"),fee=new RegExp("[\\u0590-\\u08FF\\u200F\\uFB1D-\\uFDFF\\uFE70-\\uFEFF\\u1100-\\u11FF\\u2E80-\\u303F\\u3040-\\u30FF\\u3130-\\u318F\\u31F0-\\u4DBF\\u4E00-\\u9FFF\\uA960-\\uA97F\\uAC00-\\uD7FF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF]"),mee=10,gee=12;let a0;const See=Zd();function yee(e){return a0===void 0&&(a0=document.createElement("canvas").getContext("2d")),a0?(a0.font=`${e.fontStyle} ${e.fontWeight} ${e.fontSize} ${e.fontFamily}`,a0.measureText(" ").width+(parseFloat(e.letterSpacing)||0)):4}function HP(e,t){return Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)>Math.min(e.bottom-e.top,t.bottom-t.top)/2}class wee{constructor(t,n){this.view=t,this.storage=n,this.measure(),document.fonts?.addEventListener("loadingdone",this.onFontsLoaded),document.addEventListener(Ch,this.onPhasedSettled),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{const r=this.view.dom.offsetWidth;r!==this.lastDomWidth&&(this.lastDomWidth=r,this.invalidate(),this.measure())}),this.resizeObserver.observe(t.dom))}view;storage;lastSig="";seenSigs=new Set;frozen=!1;retryRaf=0;retries=0;resizeObserver;lastDomWidth=-1;results=new mk((t,n)=>t.map(r=>({...r,from:r.from+n,to:r.to+n})),t=>t.length===0);onFontsLoaded=()=>{this.invalidate(),this.measure()};onPhasedSettled=()=>{this.invalidate(),this.measure()};invalidate(){this.results.clear(),this.restartConvergence()}restartConvergence(){this.seenSigs.clear(),this.frozen=!1,this.lastSig=""}update(t,n){if(t.state.doc!==n.doc)this.restartConvergence();else if(xd.getState(t.state)===xd.getState(n))return;this.measure()}destroy(){document.fonts?.removeEventListener("loadingdone",this.onFontsLoaded),document.removeEventListener(Ch,this.onPhasedSettled),this.resizeObserver?.disconnect(),this.retryRaf&&cancelAnimationFrame(this.retryRaf)}scheduleRetry(){this.retryRaf||this.retries>=mee||(this.retries++,this.retryRaf=requestAnimationFrame(()=>{this.retryRaf=0,this.measure()}))}measure(){this.retryRaf&&(cancelAnimationFrame(this.retryRaf),this.retryRaf=0);const{view:t}=this;if(Lx())return;if(t.dom.closest(".app.pv-exporting")){this.retries=0,this.scheduleRetry();return}const n=xd.getState(t.state);if(!this.storage.enabled){n&&n!==Mt.empty&&t.dispatch(t.state.tr.setMeta(xd,[]).setMeta("addToHistory",!1));return}if(!t.dom.isConnected){this.scheduleRetry();return}const r=[];t.state.doc.descendants((p,c)=>{if(!p.isTextblock)return!0;if(p.attrs?.align!=="justify")return!1;const u=p.textContent;return!u.includes(" ")||fee.test(u)||u.lastIndexOf(" ")>u.indexOf(" ")||r.push({node:p,pos:c}),!1});const i=[];let o=r.length===0;this.results.beginPass(t);const a=mk.topLevelDom(t);for(const p of r){const c=this.results.measure(t,p.node,p.pos,u=>this.measureParagraph(p.node,p.pos,u),a.get(p.node));c&&(o=!0,i.push(...c))}if(!o){this.scheduleRetry();return}this.retries=0;const s=JSON.stringify(i.map(p=>[p.from,p.to,p.perChar]));if(s===this.lastSig||this.frozen)return;if(this.seenSigs.has(s)||this.seenSigs.size>=gee){this.frozen=!0,console.warn("[docs] justify-shrink layout did not converge; keeping current decorations");return}if(this.seenSigs.add(s),this.lastSig=s,i.length===0&&(!n||n===Mt.empty))return;const l=i.map(p=>dn.inline(p.from,p.to,{class:"doc-jshrink",style:`word-spacing:-${p.perChar}px`}));t.dispatch(t.state.tr.setMeta(xd,l).setMeta("addToHistory",!1))}measureParagraph(t,n,r){const{view:i}=this;if(r.offsetWidth===0)return null;const o=r.getBoundingClientRect();if(o.width===0)return null;const a=o.width/r.offsetWidth,s=window.getComputedStyle(r);if(s.direction==="rtl")return[];const l=r.clientWidth-(parseFloat(s.paddingLeft)||0)-(parseFloat(s.paddingRight)||0),p=parseFloat(s.textIndent)||0,c=[];t.forEach((M,L)=>{const F=n+1+L;if(M.isText&&M.text){const I=/( +)|[^ ]+/g;let B;for(;B=I.exec(M.text);)B[1]?c.push({kind:"space",from:F+B.index,to:F+B.index+B[1].length,chars:B[1].length}):c.push({kind:"word",from:F+B.index,to:F+B.index+B[0].length,atom:!1})}else M.type.name==="hardBreak"?c.push({kind:"break"}):c.push({kind:"word",from:F,to:F+M.nodeSize,atom:!0})});const u=new Map,d=new Map,h=M=>{let L=d.get(M);return L||d.set(M,L=i.domAtPos(M)),L},m=M=>{const L=h(M.from),F=L.node.nodeType===Node.TEXT_NODE?L.node.parentElement:L.node;let I=u.get(F??r);return I===void 0&&(I=yee(window.getComputedStyle(F??r)),u.set(F??r,I)),{width:I*M.chars,chars:M.chars,from:M.from,to:M.to}},S=M=>{let L;const F=M.atom?i.nodeDOM(M.from):null;if(F instanceof HTMLElement)L=[F.getBoundingClientRect()];else{const B=h(M.from),H=h(M.to),O=See();try{O.setStart(B.node,B.offset),O.setEnd(H.node,H.offset)}catch{return"wrapped"}L=Array.from(O.getClientRects()).filter(z=>z.width>.01)}if(L.length===0)return null;const I={width:0,top:1/0,bottom:-1/0,left:1/0,right:-1/0};for(const B of L)I.top=Math.min(I.top,B.top),I.bottom=Math.max(I.bottom,B.bottom),I.left=Math.min(I.left,B.left),I.right=Math.max(I.right,B.right);for(const B of L)if(B.top-I.top>B.height/2)return"wrapped";return I.width=(I.right-I.left)/a,I},y=[];let w=null,v=null,x=[],P=!1,T=null;const C=()=>{if(x.length===0)return null;const M=x.map(m);return{width:M.reduce((L,F)=>L+F.width,0),chars:M.reduce((L,F)=>L+F.chars,0),from:M[0].from,to:M[M.length-1].to}},A=()=>{if(!T)return;const M=T;T=null,w&&v&&HP(M,v)&&!P?(w.gaps.push(C()??{width:0,chars:0,from:0,to:0}),w.words.push(M),w.left=Math.min(w.left,M.left),w.right=Math.max(w.right,M.right)):(w&&(w.boundary=P?null:C()),w={words:[M],gaps:[],boundary:null,left:M.left,right:M.right},y.push(w)),v=M,x=[],P=!1};for(const M of c)if(M.kind==="space")A(),x.push(M);else if(M.kind==="break")A(),P=!0,x=[];else{const L=S(M);if(L==="wrapped")return[];if(L===null)continue;if(T){if(!HP(L,T))return[];T={width:T.width+L.width,top:Math.min(T.top,L.top),bottom:Math.max(T.bottom,L.bottom),left:Math.min(T.left,L.left),right:Math.max(T.right,L.right)}}else T=L}if(A(),y.length===0)return[];const R=y.map((M,L)=>({wordWidths:M.words.map(F=>F.width),gaps:M.gaps,boundary:M.boundary,avail:L===y.length-1?l-(L===0?p:0):(M.right-M.left)/a,nextWordWidth:M.boundary?y[L+1]?.words[0]?.width??null:null})),N=[];for(const M of hee(R)){if(!M)continue;const L=Math.round(M.perChar*100)/100;if(!(L<=0))for(const F of M.gaps)F.chars!==0&&N.push({from:F.from,to:F.to,perChar:L})}return N}}const vee=bn.create({name:"justifyShrink",addStorage(){return{enabled:!1}},addProseMirrorPlugins(){const e=this.storage;return[new sn({key:xd,state:{init:()=>Mt.empty,apply(t,n){const r=t.getMeta(xd);return r?r.length>0?Mt.create(t.doc,r):Mt.empty:n.map(t.mapping,t.doc)}},props:{decorations(t){return this.getState(t)}},view:t=>new wee(t,e)})]}}),BR=new Set("、。,.」)』】}〕》〉〗〙"),LR=new Set("「(『【{〔《〈〖〘"),s6=new Set([...BR,...LR]),l6=new Set([...BR,..."!?:;ー々",..."!%),.:;?]}’”"]),kee=new Set([...LR,..."([{‘“"]);function xee(e){return l6.has(e)}function Tee(e){return kee.has(e)}function Cee(e){return!e||/^(ja|zh)(-|$)/i.test(e)}function Pee(e,t,n){const r=i=>Math.round(i*100)/100;return LR.has(e)?`margin-left:${r(-t)}px`:`letter-spacing:${r(n-t)}px`}const Aee=/[⺀-〿぀-ヿㇰ-䶿一-鿿豈-﫿＀-￯]/,Eee=.27,HT=.5,Iw=.5,mm=.25,Ree=4e3,Mee=10,Nee=12,WP="genoffice:doc-css";function Fee(e,t){return e==="justify"||t}const yd=new wn("cjkPunctShrink"),Iee=(e,t)=>e.map(n=>({...n,from:n.from+t})),Bee=e=>e.ea&&s6.has(e.ch),Bw=e=>e.ea&&BR.has(e.ch),Lee=e=>e.ea&&l6.has(e.ch);function Dee(e){if(e.hungWidth!==null)return e.natural-e.hungWidth<=e.avail+mm?"keep":null;if(!e.candEndsWithStop||e.candWidths.length===0)return null;const t=e.candWidths.slice(0,-1).reduce((n,r)=>n+r,0);return e.natural+t<=e.avail+mm?"pull":null}function zee(e,t,n){return e.punctCount===0?n:t}function jee(e){return e.map(t=>{if(t.avgPunctW<=0)return null;const n=t.natural-t.avail;if(t.punctCount===0){if(n>mm||!t.forced||t.candPunctCount===0)return null;const s=n+t.candWidths.reduce((p,c)=>p+c,0);if(s<=mm)return null;const l=(s+Iw)/t.candPunctCount;return l<=HT*t.avgPunctW?l:null}const r=t.punctCount+(t.openCount??0);if(n>mm){const s=n+Iw;return s/t.punctCount<=HT*t.avgPunctW?s/r:null}if(t.candWidths.length===0)return null;const i=n+t.candWidths.reduce((s,l)=>s+l,0);if(i<=mm)return null;const o=t.punctCount+t.candPunctCount,a=t.forced?HT:Eee;return(i+Iw)/o>a*t.avgPunctW?null:(i+Iw)/r})}function Oee(e,t,n,r){const i=[],o=[];let a=!1;if(t.forEach((u,d)=>{u.isText&&u.text?i.push({text:u.text,from:n+1+d,ea:r(u)}):u.type.name==="hardBreak"?o.push(n+1+d):a=!0}),a)return null;const s=[];let l=0,p=0;const c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let u=c.nextNode();u;u=c.nextNode()){const d=u.data;if(!d)continue;const h=i[l];if(!h||p+d.length>h.text.length||h.text.substr(p,d.length)!==d)return null;s.push({dom:u,from:h.from+p,ea:h.ea}),p+=d.length,p===h.text.length&&(l++,p=0)}return l===i.length?{slots:s,breaks:o}:null}const $ee=Zd(),uB=new WeakMap;function _ee(e){let t=uB.get(e);if(t===void 0){const n=e.textContent;if(t=n.length<=Ree&&Aee.test(n),t){t=!1;for(const r of n)if(s6.has(r)){t=!0;break}}uB.set(e,t)}return t}let s0;const GP=new Map;function dB(e){return`${e.fontStyle} ${e.fontWeight} ${e.fontSize} ${e.fontFamily}`}function bB(e,t){if(s0===void 0&&(s0=document.createElement("canvas").getContext("2d")),!s0)return 0;let n=GP.get(e);n||GP.set(e,n=new Map);let r=n.get(t);return r===void 0&&(s0.font=e,r=Math.ceil(s0.measureText(t).width*64)/64,n.set(t,r)),r}class Hee{constructor(t,n){this.view=t,this.storage=n,this.measure(),document.fonts?.addEventListener("loadingdone",this.onFontsLoaded),document.addEventListener(WP,this.onDocCss),document.addEventListener(Ch,this.onPhasedSettled),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{const r=this.view.dom.offsetWidth;r!==this.lastDomWidth&&(this.lastDomWidth=r,this.invalidate(),this.measure())}),this.resizeObserver.observe(t.dom))}view;storage;lastSig="";results=new mk(Iee,t=>t.length===0);seenSigs=new Set;frozen=!1;retryRaf=0;retries=0;resizeObserver;lastDomWidth=-1;onFontsLoaded=()=>{GP.clear(),this.invalidate(),this.measure()};onDocCss=()=>{this.invalidate(),this.measure()};onPhasedSettled=()=>{this.invalidate(),this.measure()};invalidate(){this.results.clear(),this.restartConvergence()}restartConvergence(){this.seenSigs.clear(),this.frozen=!1,this.lastSig=""}update(t,n){if(t.state.doc!==n.doc)this.restartConvergence();else if(yd.getState(t.state)===yd.getState(n))return;this.measure()}destroy(){document.fonts?.removeEventListener("loadingdone",this.onFontsLoaded),document.removeEventListener(WP,this.onDocCss),document.removeEventListener(Ch,this.onPhasedSettled),this.resizeObserver?.disconnect(),this.retryRaf&&cancelAnimationFrame(this.retryRaf)}scheduleRetry(){this.retryRaf||this.retries>=Mee||(this.retries++,this.retryRaf=requestAnimationFrame(()=>{this.retryRaf=0,this.measure()}))}measure(){this.retryRaf&&(cancelAnimationFrame(this.retryRaf),this.retryRaf=0);const{view:t}=this;if(Lx())return;if(t.dom.closest(".app.pv-exporting")){this.retries=0,this.scheduleRetry();return}const n=yd.getState(t.state);if(!this.storage.enabled&&!this.storage.hangPunct){n&&n!==Mt.empty&&t.dispatch(t.state.tr.setMeta(yd,[]).setMeta("addToHistory",!1));return}if(!t.dom.isConnected){this.scheduleRetry();return}const r=[];t.state.doc.descendants((p,c)=>p.isTextblock?(_ee(p)&&r.push({node:p,pos:c}),!1):!0);const i=[];let o=r.length===0;this.results.beginPass(t);const a=mk.topLevelDom(t);for(const p of r){const c=this.results.measure(t,p.node,p.pos,u=>this.measureParagraph(p.node,p.pos,u),a.get(p.node));c&&(o=!0,i.push(...c))}if(!o){this.scheduleRetry();return}this.retries=0;const s=JSON.stringify(i.map(p=>[p.from,p.perChar,p.baseLs]));if(s===this.lastSig||this.frozen)return;if(this.seenSigs.has(s)||this.seenSigs.size>=Nee){this.frozen=!0,console.warn("[docs] cjk-punct-shrink layout did not converge; keeping current decorations");return}if(this.seenSigs.add(s),this.lastSig=s,i.length===0&&(!n||n===Mt.empty))return;const l=i.map(p=>dn.inline(p.from,p.from+1,{class:"doc-cjkshrink",style:Pee(p.ch,p.perChar,p.baseLs)}));t.dispatch(t.state.tr.setMeta(yd,l).setMeta("addToHistory",!1))}measureParagraph(t,n,r){const{view:i}=this;if(r.offsetWidth===0)return null;const o=r.getBoundingClientRect();if(o.width===0)return null;const a=o.width/r.offsetWidth,s=window.getComputedStyle(r);if(s.direction==="rtl")return[];if(!Fee(s.textAlign,this.storage.legacyLayout))return[];if(!this.storage.enabled&&t.attrs.overflowPunct===!1)return[];const l=s.textAlign==="justify",p=parseFloat(s.letterSpacing)||0,c=r.clientWidth-(parseFloat(s.paddingLeft)||0)-(parseFloat(s.paddingRight)||0),u=parseFloat(s.textIndent)||0,d=t.attrs.eaLang??this.storage.docEastAsiaLang,h=[];let m=[];const S=dB(s),y=new Map,w=O=>{if(!O)return S;let z=y.get(O);return z||(z=dB(window.getComputedStyle(O)),y.set(O,z)),z},v=O=>{const z=O.marks.find(_=>_.type.name==="docTextStyle")?.attrs.eaLang;return Cee(z??d)};let x=!1;const P=Oee(r,t,n,v);if(P){m=P.breaks;const O=$ee();for(const z of P.slots){const _=w(z.dom.parentElement),W=z.dom.data;for(let Z=0;Z{if(x||!O.isText||!O.text){!O.isText&&O.type.name!=="hardBreak"?x=!0:O.isText||m.push(n+1+z);return}const _=n+1+z,W=v(O);for(let Z=0;Z=A[0].left-1?A.push(O):(A=[O],C.push(A));if(C.length===0)return[];const R=yd.getState(i.state),N=O=>(R?.find(O.from,O.from+1).length??0)>0,M=[],L=[],F=[],I=C.map((O,z)=>{const _=O.reduce((le,ge)=>le+ge.width,0),W=Math.min(...O.map(le=>le.left)),Z=O[O.length-1];let $=Z.rendRight??Math.max(...O.map(le=>le.right));if(Z.rendRight===void 0)try{$=i.coordsAtPos(Z.from+1,-1).left}catch{}const V=O.filter(Bee),Y=V.filter(Bw);M.push(V);const X=C[z+1],ie=O[O.length-1].from,ne=X&&m.some(le=>le>ie&&le0&&!ne){re.push(X[0].width),Re=X[0];let le=1;for(;le0?Y:se,Ae=!l||z===C.length-1||ne?c-(z===0?u:0):($-W)/a,q=O[O.length-1];return F.push({natural:_,avail:Ae,hungWidth:Bw(q)&&N(q)?q.width:null,candWidths:z===C.length-1?[]:re,candEndsWithStop:Re!==null&&Bw(Re)}),{natural:_,avail:Ae,punctCount:Y.length,openCount:V.length-Y.length,avgPunctW:Ne.length>0?Ne.reduce((le,ge)=>le+ge.width,0)/Ne.length:0,candWidths:z===C.length-1?[]:re,candPunctCount:se.length,forced:we}}),B=[];if(!this.storage.enabled)return C.forEach((O,z)=>{const _=Dee(F[z]);if(_===null)return;const W=_==="keep"?O[O.length-1]:C[z+1][F[z].candWidths.length-1];B.push({from:W.from,ch:W.ch,perChar:W.width,baseLs:p})}),B;const H=jee(I);for(let O=0;OMt.empty,apply(t,n){const r=t.getMeta(yd);return r?r.length>0?Mt.create(t.doc,r):Mt.empty:n.map(t.mapping,t.doc)}},props:{decorations(t){return this.getState(t)}},view:t=>new Hee(t,e)})]}});var G=ey();const Gd=Cx(G);var Gee=K3();const Uee=Cx(Gee);var WT={exports:{}},GT={};var hB;function qee(){if(hB)return GT;hB=1;var e=ey();function t(u,d){return u===d&&(u!==0||1/u===1/d)||u!==u&&d!==d}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,i=e.useEffect,o=e.useLayoutEffect,a=e.useDebugValue;function s(u,d){var h=d(),m=r({inst:{value:h,getSnapshot:d}}),S=m[0].inst,y=m[1];return o(function(){S.value=h,S.getSnapshot=d,l(S)&&y({inst:S})},[u,h,d]),i(function(){return l(S)&&y({inst:S}),u(function(){l(S)&&y({inst:S})})},[u]),a(h),h}function l(u){var d=u.getSnapshot;u=u.value;try{var h=d();return!n(u,h)}catch{return!0}}function p(u,d){return d()}var c=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:s;return GT.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:c,GT}var fB;function c6(){return fB||(fB=1,WT.exports=qee()),WT.exports}var p6=c6();const{getOwnPropertyNames:Vee,getOwnPropertySymbols:Kee}=Object,{hasOwnProperty:Zee}=Object.prototype;function UT(e,t){return function(r,i,o){return e(r,i,o)&&t(r,i,o)}}function Lw(e){return function(n,r,i){if(!n||!r||typeof n!="object"||typeof r!="object")return e(n,r,i);const{cache:o}=i,a=o.get(n),s=o.get(r);if(a&&s)return a===r&&s===n;o.set(n,r),o.set(r,n);const l=e(n,r,i);return o.delete(n),o.delete(r),l}}function Xee(e){return e?.[Symbol.toStringTag]}function mB(e){return Vee(e).concat(Kee(e))}const Yee=Object.hasOwn||((e,t)=>Zee.call(e,t));function Lh(e,t){return e===t||!e&&!t&&e!==e&&t!==t}const Jee="__v",Qee="__o",ete="_owner",{getOwnPropertyDescriptor:gB,keys:SB}=Object;function tte(e,t){return e.byteLength===t.byteLength&&gk(new Uint8Array(e),new Uint8Array(t))}function nte(e,t,n){let r=e.length;if(t.length!==r)return!1;for(;r-- >0;)if(!n.equals(e[r],t[r],r,r,e,t,n))return!1;return!0}function rte(e,t){return e.byteLength===t.byteLength&&gk(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function ite(e,t){return Lh(e.getTime(),t.getTime())}function ote(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function ate(e,t){return e===t}function yB(e,t,n){const r=e.size;if(r!==t.size)return!1;if(!r)return!0;const i=new Array(r),o=e.entries();let a,s,l=0;for(;(a=o.next())&&!a.done;){const p=t.entries();let c=!1,u=0;for(;(s=p.next())&&!s.done;){if(i[u]){u++;continue}const d=a.value,h=s.value;if(n.equals(d[0],h[0],l,u,e,t,n)&&n.equals(d[1],h[1],d[0],h[0],e,t,n)){c=i[u]=!0;break}u++}if(!c)return!1;l++}return!0}const ste=Lh;function lte(e,t,n){const r=SB(e);let i=r.length;if(SB(t).length!==i)return!1;for(;i-- >0;)if(!u6(e,t,n,r[i]))return!1;return!0}function l0(e,t,n){const r=mB(e);let i=r.length;if(mB(t).length!==i)return!1;let o,a,s;for(;i-- >0;)if(o=r[i],!u6(e,t,n,o)||(a=gB(e,o),s=gB(t,o),(a||s)&&(!a||!s||a.configurable!==s.configurable||a.enumerable!==s.enumerable||a.writable!==s.writable)))return!1;return!0}function cte(e,t){return Lh(e.valueOf(),t.valueOf())}function pte(e,t){return e.source===t.source&&e.flags===t.flags}function wB(e,t,n){const r=e.size;if(r!==t.size)return!1;if(!r)return!0;const i=new Array(r),o=e.values();let a,s;for(;(a=o.next())&&!a.done;){const l=t.values();let p=!1,c=0;for(;(s=l.next())&&!s.done;){if(!i[c]&&n.equals(a.value,s.value,a.value,s.value,e,t,n)){p=i[c]=!0;break}c++}if(!p)return!1}return!0}function gk(e,t){let n=e.byteLength;if(t.byteLength!==n||e.byteOffset!==t.byteOffset)return!1;for(;n-- >0;)if(e[n]!==t[n])return!1;return!0}function ute(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function u6(e,t,n,r){return(r===ete||r===Qee||r===Jee)&&(e.$$typeof||t.$$typeof)?!0:Yee(t,r)&&n.equals(e[r],t[r],r,r,e,t,n)}const dte="[object ArrayBuffer]",bte="[object Arguments]",hte="[object Boolean]",fte="[object DataView]",mte="[object Date]",gte="[object Error]",Ste="[object Map]",yte="[object Number]",wte="[object Object]",vte="[object RegExp]",kte="[object Set]",xte="[object String]",Tte={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},Cte="[object URL]",Pte=Object.prototype.toString;function Ate({areArrayBuffersEqual:e,areArraysEqual:t,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:i,areFunctionsEqual:o,areMapsEqual:a,areNumbersEqual:s,areObjectsEqual:l,arePrimitiveWrappersEqual:p,areRegExpsEqual:c,areSetsEqual:u,areTypedArraysEqual:d,areUrlsEqual:h,unknownTagComparators:m}){return function(y,w,v){if(y===w)return!0;if(y==null||w==null)return!1;const x=typeof y;if(x!==typeof w)return!1;if(x!=="object")return x==="number"?s(y,w,v):x==="function"?o(y,w,v):!1;const P=y.constructor;if(P!==w.constructor)return!1;if(P===Object)return l(y,w,v);if(Array.isArray(y))return t(y,w,v);if(P===Date)return r(y,w,v);if(P===RegExp)return c(y,w,v);if(P===Map)return a(y,w,v);if(P===Set)return u(y,w,v);const T=Pte.call(y);if(T===mte)return r(y,w,v);if(T===vte)return c(y,w,v);if(T===Ste)return a(y,w,v);if(T===kte)return u(y,w,v);if(T===wte)return typeof y.then!="function"&&typeof w.then!="function"&&l(y,w,v);if(T===Cte)return h(y,w,v);if(T===gte)return i(y,w,v);if(T===bte)return l(y,w,v);if(Tte[T])return d(y,w,v);if(T===dte)return e(y,w,v);if(T===fte)return n(y,w,v);if(T===hte||T===yte||T===xte)return p(y,w,v);if(m){let C=m[T];if(!C){const A=Xee(y);A&&(C=m[A])}if(C)return C(y,w,v)}return!1}}function Ete({circular:e,createCustomConfig:t,strict:n}){let r={areArrayBuffersEqual:tte,areArraysEqual:n?l0:nte,areDataViewsEqual:rte,areDatesEqual:ite,areErrorsEqual:ote,areFunctionsEqual:ate,areMapsEqual:n?UT(yB,l0):yB,areNumbersEqual:ste,areObjectsEqual:n?l0:lte,arePrimitiveWrappersEqual:cte,areRegExpsEqual:pte,areSetsEqual:n?UT(wB,l0):wB,areTypedArraysEqual:n?UT(gk,l0):gk,areUrlsEqual:ute,unknownTagComparators:void 0};if(t&&(r=Object.assign({},r,t(r))),e){const i=Lw(r.areArraysEqual),o=Lw(r.areMapsEqual),a=Lw(r.areObjectsEqual),s=Lw(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:i,areMapsEqual:o,areObjectsEqual:a,areSetsEqual:s})}return r}function Rte(e){return function(t,n,r,i,o,a,s){return e(t,n,s)}}function Mte({circular:e,comparator:t,createState:n,equals:r,strict:i}){if(n)return function(s,l){const{cache:p=e?new WeakMap:void 0,meta:c}=n();return t(s,l,{cache:p,equals:r,meta:c,strict:i})};if(e)return function(s,l){return t(s,l,{cache:new WeakMap,equals:r,meta:void 0,strict:i})};const o={cache:void 0,equals:r,meta:void 0,strict:i};return function(s,l){return t(s,l,o)}}const Nte=Xd();Xd({strict:!0});Xd({circular:!0});Xd({circular:!0,strict:!0});Xd({createInternalComparator:()=>Lh});Xd({strict:!0,createInternalComparator:()=>Lh});Xd({circular:!0,createInternalComparator:()=>Lh});Xd({circular:!0,createInternalComparator:()=>Lh,strict:!0});function Xd(e={}){const{circular:t=!1,createInternalComparator:n,createState:r,strict:i=!1}=e,o=Ete(e),a=Ate(o),s=n?n(a):Rte(a);return Mte({circular:t,comparator:a,createState:r,equals:s,strict:i})}var qT={exports:{}},VT={};var vB;function Fte(){if(vB)return VT;vB=1;var e=ey(),t=c6();function n(p,c){return p===c&&(p!==0||1/p===1/c)||p!==p&&c!==c}var r=typeof Object.is=="function"?Object.is:n,i=t.useSyncExternalStore,o=e.useRef,a=e.useEffect,s=e.useMemo,l=e.useDebugValue;return VT.useSyncExternalStoreWithSelector=function(p,c,u,d,h){var m=o(null);if(m.current===null){var S={hasValue:!1,value:null};m.current=S}else S=m.current;m=s(function(){function w(C){if(!v){if(v=!0,x=C,C=d(C),h!==void 0&&S.hasValue){var A=S.value;if(h(A,C))return P=A}return P=C}if(A=P,r(x,C))return A;var R=d(C);return h!==void 0&&h(A,R)?(x=C,A):(x=C,P=R)}var v=!1,x,P,T=u===void 0?null:u;return[function(){return w(c())},T===null?void 0:function(){return w(T())}]},[c,u,d,h]);var y=i(p,m[0],m[1]);return a(function(){S.hasValue=!0,S.value=y},[y]),l(y),y},VT}var kB;function Ite(){return kB||(kB=1,qT.exports=Fte()),qT.exports}var Bte=Ite();const Lte=(...e)=>t=>{e.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},Dte=({contentComponent:e})=>{const t=p6.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getServerSnapshot);return g.jsx(g.Fragment,{children:Object.values(t)})};function zte(){const e=new Set;let t={},n=!1;const r=()=>{n||!e.size||(n=!0,queueMicrotask(()=>{n=!1,e.forEach(i=>i())}))};return{subscribe(i){return e.add(i),()=>{e.delete(i)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(i,o){t={...t,[i]:Uee.createPortal(o.reactElement,o.element,i)},r()},removeRenderer(i){const o={...t};delete o[i],t=o,r()}}}var jte=class extends Gd.Component{constructor(e){super(e),this.editorContentRef=Gd.createRef()}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){var e;const t=this.props.editor;if(t&&!t.isDestroyed&&(!((e=t.view.dom)===null||e===void 0)&&e.parentNode)){if(t.contentComponent)return;const n=this.editorContentRef.current;n.append(...t.view.dom.parentNode.childNodes),t.setOptions({element:n}),t.contentComponent=zte(),t.createNodeViews(),t.isEditorContentInitialized=!0,this.forceUpdate()}}componentWillUnmount(){const e=this.props.editor;if(e){e.isEditorContentInitialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),e.contentComponent=null;try{var t;if(!(!((t=e.view.dom)===null||t===void 0)&&t.parentNode))return;const n=document.createElement("div");n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n})}catch{}}}render(){const{editor:e,innerRef:t,...n}=this.props;return g.jsxs(g.Fragment,{children:[g.jsx("div",{ref:Lte(t,this.editorContentRef),...n}),e?.contentComponent&&g.jsx(Dte,{contentComponent:e.contentComponent})]})}};const Ote=G.forwardRef((e,t)=>{const n=Gd.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[e.editor]);return Gd.createElement(jte,{key:n,innerRef:t,...e})}),d6=Gd.memo(Ote),$te=typeof window<"u"?G.useLayoutEffect:G.useEffect;var _te=class{constructor(e){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=e,this.lastSnapshot={editor:e,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}watch(e){if(this.editor=e,this.editor){let t;const n=i=>{i?.transaction!==void 0&&i.transaction===t||(t=i?.transaction,this.transactionNumber+=1,this.subscribers.forEach(o=>o()))},r=this.editor;return r.on("transaction",n),r.on("update",n),()=>{r.off("transaction",n),r.off("update",n)}}}};function Hte(e){var t;const[n]=G.useState(()=>new _te(e.editor)),r=Bte.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,e.selector,(t=e.equalityFn)!==null&&t!==void 0?t:Nte);return $te(()=>n.watch(e.editor),[e.editor,n]),G.useDebugValue(r),r}const Wte=!1,b6=typeof window>"u",Gte=b6||!!(typeof window<"u"&&window.next);var Ute=class h6{constructor(t){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=t,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(t){this.editor=t,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){const t=this.options.current.immediatelyRender;let n=t??!0;return b6?(n&&Wte&&console.warn("SSR detected. `immediatelyRender` has been set to false to avoid hydration mismatches"),n=!1):Gte&&t===void 0&&(n=!1),n?this.createEditor():null}createEditor(){const t={...this.options.current,onBeforeCreate:(...n)=>{var r,i;return(r=(i=this.options.current).onBeforeCreate)===null||r===void 0?void 0:r.call(i,...n)},onBlur:(...n)=>{var r,i;return(r=(i=this.options.current).onBlur)===null||r===void 0?void 0:r.call(i,...n)},onCreate:(...n)=>{var r,i;return(r=(i=this.options.current).onCreate)===null||r===void 0?void 0:r.call(i,...n)},onDestroy:(...n)=>{var r,i;return(r=(i=this.options.current).onDestroy)===null||r===void 0?void 0:r.call(i,...n)},onFocus:(...n)=>{var r,i;return(r=(i=this.options.current).onFocus)===null||r===void 0?void 0:r.call(i,...n)},onSelectionUpdate:(...n)=>{var r,i;return(r=(i=this.options.current).onSelectionUpdate)===null||r===void 0?void 0:r.call(i,...n)},onTransaction:(...n)=>{var r,i;return(r=(i=this.options.current).onTransaction)===null||r===void 0?void 0:r.call(i,...n)},onUpdate:(...n)=>{var r,i;return(r=(i=this.options.current).onUpdate)===null||r===void 0?void 0:r.call(i,...n)},onContentError:(...n)=>{var r,i;return(r=(i=this.options.current).onContentError)===null||r===void 0?void 0:r.call(i,...n)},onDrop:(...n)=>{var r,i;return(r=(i=this.options.current).onDrop)===null||r===void 0?void 0:r.call(i,...n)},onPaste:(...n)=>{var r,i;return(r=(i=this.options.current).onPaste)===null||r===void 0?void 0:r.call(i,...n)},onDelete:(...n)=>{var r,i;return(r=(i=this.options.current).onDelete)===null||r===void 0?void 0:r.call(i,...n)},onMount:(...n)=>{var r,i;return(r=(i=this.options.current).onMount)===null||r===void 0?void 0:r.call(i,...n)},onUnmount:(...n)=>{var r,i;return(r=(i=this.options.current).onUnmount)===null||r===void 0?void 0:r.call(i,...n)}};return new r6(t)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,n){return Object.keys(t).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&t.extensions&&n.extensions?t.extensions.length!==n.extensions.length?!1:t.extensions.every((i,o)=>{var a;return i===((a=n.extensions)===null||a===void 0?void 0:a[o])}):t[r]===n[r])}onRender(t){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&t.length===0?h6.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(t),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(t){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=t;return}if(this.previousDeps.length===t.length&&this.previousDeps.every((n,r)=>n===t[r]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===t){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===t&&this.setEditor(null))},1)}};function qte(e={},t=[]){const n=G.useRef(e);n.current=e;const[r]=G.useState(()=>new Ute(n)),i=p6.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return G.useDebugValue(i),G.useEffect(r.onRender(t)),Hte({editor:i,selector:({transactionNumber:o})=>e.shouldRerenderOnTransaction===!1||e.shouldRerenderOnTransaction===void 0?null:e.immediatelyRender&&o===0?0:o+1}),i}const f6=G.createContext({editor:null});f6.Consumer;const Vte=G.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),Kte=()=>G.useContext(Vte);Gd.forwardRef((e,t)=>{const{onDragStart:n}=Kte(),r=e.as||"div";return g.jsx(r,{...e,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...e.style}})});Gd.createContext({markViewContentRef:()=>{}});const DR=G.createContext({get editor(){throw new Error("useTiptap must be used within a provider")}});DR.displayName="TiptapContext";const Zte=()=>G.useContext(DR);function m6({children:e,...t}){const n="editor"in t?t.editor:t.instance;if(!n)throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");const r=G.useMemo(()=>({editor:n}),[n]),i=G.useMemo(()=>({editor:n}),[n]);return g.jsx(f6.Provider,{value:i,children:g.jsx(DR.Provider,{value:r,children:e})})}m6.displayName="Tiptap";function g6({...e}){const{editor:t}=Zte();return g.jsx(d6,{editor:t,...e})}g6.displayName="Tiptap.Content";Object.assign(m6,{Content:g6});const Xp="",li="",S6=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Xte=S6+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Yte="["+S6+"]["+Xte+"]*",Jte=new RegExp("^"+Yte+"$");function y6(e,t){const n=[];let r=t.exec(e);for(;r;){const i=[];i.startIndex=t.lastIndex-r[0].length;const o=r.length;for(let a=0;a"u")};function Qte(e){return typeof e<"u"}const zR=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],v6=["__proto__","constructor","prototype"],ene={allowBooleanAttributes:!1,unpairedTags:[]};function tne(e,t){t=Object.assign({},ene,t);const n=[];let r=!1,i=!1;e[0]==="\uFEFF"&&(e=e.substr(1));for(let o=0;o"&&e[o]!==" "&&e[o]!==" "&&e[o]!==` +`&&e[o]!=="\r";o++)l+=e[o];if(l=l.trim(),l[l.length-1]==="/"&&(l=l.substring(0,l.length-1),o--),!cne(l)){let u;return l.trim().length===0?u="Invalid space after '<'.":u="Tag '"+l+"' is an invalid name.",Ri("InvalidTag",u,xa(e,o))}const p=ine(e,o);if(p===!1)return Ri("InvalidAttr","Attributes for '"+l+"' have open quote.",xa(e,o));let c=p.value;if(o=p.index,c[c.length-1]==="/"){const u=o-c.length;c=c.substring(0,c.length-1);const d=PB(c,t);if(d===!0)r=!0;else return Ri(d.err.code,d.err.msg,xa(e,u+d.err.line))}else if(s)if(p.tagClosed){if(c.trim().length>0)return Ri("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",xa(e,a));if(n.length===0)return Ri("InvalidTag","Closing tag '"+l+"' has not been opened.",xa(e,a));{const u=n.pop();if(l!==u.tagName){let d=xa(e,u.tagStartPos);return Ri("InvalidTag","Expected closing tag '"+u.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+l+"'.",xa(e,a))}n.length==0&&(i=!0)}}else return Ri("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",xa(e,o));else{const u=PB(c,t);if(u!==!0)return Ri(u.err.code,u.err.msg,xa(e,o-c.length+u.err.line));if(i===!0)return Ri("InvalidXml","Multiple possible root nodes found.",xa(e,o));t.unpairedTags.indexOf(l)!==-1||n.push({tagName:l,tagStartPos:a}),r=!0}for(o++;o0)return Ri("InvalidXml","Invalid '"+JSON.stringify(n.map(o=>o.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ri("InvalidXml","Start tag expected.",1);return!0}function xB(e){return e===" "||e===" "||e===` +`||e==="\r"}function TB(e,t){const n=t;for(;t5&&r==="xml")return Ri("InvalidXml","XML declaration allowed only at the start of the document.",xa(e,t));if(e[t]=="?"&&e[t+1]==">"){t++;break}else continue}return t}function CB(e,t){if(e.length>t+5&&e[t+1]==="-"&&e[t+2]==="-"){for(t+=3;t"){t+=2;break}}else if(e.length>t+8&&e[t+1]==="D"&&e[t+2]==="O"&&e[t+3]==="C"&&e[t+4]==="T"&&e[t+5]==="Y"&&e[t+6]==="P"&&e[t+7]==="E"){let n=1;for(t+=8;t"&&(n--,n===0))break}else if(e.length>t+9&&e[t+1]==="["&&e[t+2]==="C"&&e[t+3]==="D"&&e[t+4]==="A"&&e[t+5]==="T"&&e[t+6]==="A"&&e[t+7]==="["){for(t+=8;t"){t+=2;break}}return t}const nne='"',rne="'";function ine(e,t){let n="",r="",i=!1;for(;t"&&r===""){i=!0;break}n+=e[t]}return r!==""?!1:{value:n,index:t,tagClosed:i}}const one=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function PB(e,t){const n=y6(e,one),r={};for(let i=0;i",lt:"<",quot:'"'},une={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},Sk=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),dne=new Set("!?\\\\/[]$%{}^&*()<>|+");function AB(e){if(e[0]==="#")throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${e}"`);for(const t of e)if(dne.has(t))throw new Error(`[EntityReplacer] Invalid character '${t}' in entity name: "${e}"`);return e}function p0(...e){const t=Object.create(null);for(const n of e)if(n)for(const r of Object.keys(n)){const i=n[r];if(typeof i=="string")t[r]=i;else if(i&&typeof i=="object"&&i.val!==void 0){const o=i.val;typeof o=="string"&&(t[r]=o)}}return t}const lh="external",yk="base",UP="all";function bne(e){return!e||e===lh?new Set([lh]):e===UP?new Set([UP]):e===yk?new Set([yk]):Array.isArray(e)?new Set(e):new Set([lh])}const Za=Object.freeze({allow:0,leave:1,remove:2,throw:3}),hne=new Set([9,10,13]);function fne(e){if(!e)return{xmlVersion:1,onLevel:Za.allow,nullLevel:Za.remove};const t=e.xmlVersion===1.1?1.1:1,n=Za[e.onNCR]??Za.allow,r=Za[e.nullNCR]??Za.remove,i=Math.max(r,Za.remove);return{xmlVersion:t,onLevel:n,nullLevel:i}}class mne{constructor(t={}){this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck=typeof t.postCheck=="function"?t.postCheck:r=>r,this._limitTiers=bne(this._limit.applyLimitsTo??lh),this._numericAllowed=t.numericAllowed??!0,this._baseMap=p0(k6,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const n=fne(t.ncr);this._ncrXmlVersion=n.xmlVersion,this._ncrOnLevel=n.onLevel,this._ncrNullLevel=n.nullLevel,this._onExternalEntity=typeof t.onExternalEntity=="function"?t.onExternalEntity:null,this._onInputEntity=typeof t.onInputEntity=="function"?t.onInputEntity:null}_applyRegistrationHook(t,n,r,i){if(!t)return!0;const o=t(n,r);if(o===Sk.BLOCK)return!1;if(o===Sk.THROW)throw new Error(`[EntityDecoder] Registration of ${i} entity "&${n};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(const i of Object.keys(t))AB(i);if(!this._onExternalEntity){this._externalMap=p0(t);return}const n=p0(t),r=Object.create(null);for(const[i,o]of Object.entries(n))this._applyRegistrationHook(this._onExternalEntity,i,o,"external")&&(r[i]=o);this._externalMap=r}addExternalEntity(t,n){AB(t),typeof n=="string"&&n.indexOf("&")===-1&&this._applyRegistrationHook(this._onExternalEntity,t,n,"external")&&(this._externalMap[t]=n)}addInputEntities(t){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity){this._inputMap=p0(t);return}const n=p0(t),r=Object.create(null);for(const[i,o]of Object.entries(n))this._applyRegistrationHook(this._onInputEntity,i,o,"input")&&(r[i]=o);this._inputMap=r}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=t===1.1?1.1:1}decode(t){if(typeof t!="string"||t.length===0||t.indexOf("&")===-1)return t;const n=t,r=[],i=t.length;let o=0,a=0;const s=this._maxTotalExpansions>0,l=this._maxExpandedLength>0,p=s||l;for(;a=i||t.charCodeAt(u)!==59){a++;continue}const d=t.slice(a+1,u);if(d.length===0){a++;continue}let h,m;if(this._removeSet.has(d))h="",m===void 0&&(m=lh);else if(this._leaveSet.has(d)){a++;continue}else if(d.charCodeAt(0)===35){const S=this._resolveNCR(d);if(S===void 0){a++;continue}h=S,m=yk}else{const S=this._resolveName(d);h=S?.value,m=S?.tier}if(h===void 0){a++;continue}if(a>o&&r.push(t.slice(o,a)),r.push(h),o=u+1,a=o,p&&this._tierCounts(m)){if(s&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(l){const S=h.length-(d.length+2);if(S>0&&(this._expandedLength+=S,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}o=55296&&t<=57343||this._ncrXmlVersion===1&&t>=1&&t<=31&&!hne.has(t)?Za.remove:-1}_applyNCRAction(t,n,r){switch(t){case Za.allow:return String.fromCodePoint(r);case Za.remove:return"";case Za.leave:return;case Za.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${n}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(t){const n=t.charCodeAt(1);let r;if(n===120||n===88?r=parseInt(t.slice(2),16):r=parseInt(t.slice(1),10),Number.isNaN(r)||r<0||r>1114111)return;const i=this._classifyNCR(r);if(!this._numericAllowed&&izR.includes(e)?"__"+e:e,gne={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0,unicode:!1},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,n){return e},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:x6};function Sne(e,t){if(typeof e!="string")return;const n=e.toLowerCase();if(zR.some(r=>n===r.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);if(v6.some(r=>n===r.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}function T6(e,t){return typeof e=="boolean"?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:typeof e=="object"&&e!==null?{enabled:e.enabled!==!1,maxEntitySize:Math.max(1,e.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,e.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,e.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,e.maxExpandedLength??1e5),maxEntityCount:Math.max(1,e.maxEntityCount??1e3),allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null,appliesTo:e.appliesTo??"all"}:T6(!0)}const yne=function(e){const t=Object.assign({},gne,e),n=[{value:t.attributeNamePrefix,name:"attributeNamePrefix"},{value:t.attributesGroupName,name:"attributesGroupName"},{value:t.textNodeName,name:"textNodeName"},{value:t.cdataPropName,name:"cdataPropName"},{value:t.commentPropName,name:"commentPropName"}];for(const{value:r,name:i}of n)r&&Sne(r,i);return t.onDangerousProperty===null&&(t.onDangerousProperty=x6),t.processEntities=T6(t.processEntities,t.htmlEntities),t.unpairedTagsSet=new Set(t.unpairedTags),t.stopNodes&&Array.isArray(t.stopNodes)&&(t.stopNodes=t.stopNodes.map(r=>typeof r=="string"&&r.startsWith("*.")?".."+r.substring(2):r)),t};let wk;typeof Symbol!="function"?wk="@@xmlMetadata":wk=Symbol("XML Node Metadata");class wd{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,n){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:n})}addChild(t,n){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),n!==void 0&&(this.child[this.child.length-1][wk]={startIndex:n})}static getMetaDataSymbol(){return wk}}const C6=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�",wne=C6+"\\-\\.\\d·̀-ͯ‿-⁀",P6=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",vne=P6+"\\-\\.\\d·̀-ͯ҇‿-⁀",jR=(e,t,n="")=>{const r=e.replace(":",""),i=t.replace(":",""),o=`[${r}][${i}]*`;return{name:new RegExp(`^[${e}][${t}]*$`,n),ncName:new RegExp(`^${o}$`,n),qName:new RegExp(`^${o}(?::${o})?$`,n),nmToken:new RegExp(`^[${t}]+$`,n),nmTokens:new RegExp(`^[${t}]+(?:\\s+[${t}]+)*$`,n)}},kne=jR(C6,wne),xne=jR(P6,vne,"u"),A6=":A-Za-z_",Tne=A6+"\\-\\.\\d",Cne=jR(A6,Tne),Pne=(e="1.0",t=!1)=>t?Cne:e==="1.1"?xne:kne,E6=(e,{xmlVersion:t="1.0",asciiOnly:n=!1}={})=>Pne(t,n).qName.test(e);class Ane{constructor(t,n){this.suppressValidationErr=!t,this.options=t,this.xmlVersion=n||1}setXmlVersion(t=1){this.xmlVersion=t}readDocType(t,n){const r=Object.create(null);let i=0;if(t[n+3]==="O"&&t[n+4]==="C"&&t[n+5]==="T"&&t[n+6]==="Y"&&t[n+7]==="P"&&t[n+8]==="E"){n=n+9;let o=1,a=!1,s=!1,l="";for(;n=this.options.maxEntityCount)throw new Error(`Entity count (${i+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);r[p]=c,i++}}else if(a&&Db(t,"!ELEMENT",n)){n+=8;const{index:p}=this.readElementExp(t,n+1);n=p}else if(a&&Db(t,"!ATTLIST",n))n+=8;else if(a&&Db(t,"!NOTATION",n)){n+=9;const{index:p}=this.readNotationExp(t,n+1,this.suppressValidationErr);n=p}else if(Db(t,"!--",n))s=!0;else throw new Error("Invalid DOCTYPE");o++,l=""}else if(t[n]===">"){if(s?t[n-1]==="-"&&t[n-2]==="-"&&(s=!1,o--):o--,o===0)break}else t[n]==="["?a=!0:l+=t[n];if(o!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:r,i:n}}readEntityExp(t,n){n=qa(t,n);const r=n;for(;nthis.options.maxEntitySize)throw new Error(`Entity "${i}" size (${o.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return n--,[i,o,n]}readNotationExp(t,n){n=qa(t,n);const r=n;for(;n{for(;t=EB&&o<=RB||o===MB)){if(o=55296&&o<=56319){if(i+1=56320&&a<=57343){const s=65536+(o-55296<<10)+(a-56320);if(VP.has(s)){n=i;break}}}continue}if(KP[o-F0]!==qP||Dw.has(o)){n=i;break}}}if(n===-1)return e;const r=[];n>0&&r.push(e.slice(0,n));for(let i=n;i=EB&&o<=RB||o===MB){r.push(e[i]);continue}if(o=55296&&o<=56319){if(i+1=56320&&s<=57343){const l=65536+(o-55296<<10)+(s-56320),p=VP.get(l);if(p!==void 0){r.push(String.fromCharCode(p+48)),i++;continue}}}r.push(e[i]);continue}if(Dw.has(o)){r.push("-");continue}const a=KP[o-F0];r.push(a!==qP?String.fromCharCode(a+48):e[i])}return r.join("")}const Nne=/^[-+]?0x[a-fA-F0-9]+$/,Fne=/^0b[01]+$/,Ine=/^0o[0-7]+$/,Bne=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Lne={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function Dne(e,t={}){if(t=Object.assign({},Lne,t),!e||typeof e!="string")return e;let n=e.trim();if(n.length===0)return e;if(t.skipLike!==void 0&&t.skipLike.test(n))return e;if(n==="0"||t.unicode&&(n=Mne(n),n==="0"))return 0;if(t.hex&&Nne.test(n))return KT(n,16);if(t.binary&&Fne.test(n))return KT(n,2);if(t.octal&&Ine.test(n))return KT(n,8);if(isFinite(n)){if(n.includes("e")||n.includes("E"))return jne(e,n,t);{const r=Bne.exec(n);if(r){const i=r[1]||"",o=r[2];let a=One(r[3]);const s=i?e[o.length+1]===".":e[o.length]===".";if(!t.leadingZeros&&(o.length>1||o.length===1&&!s))return e;{const l=Number(n),p=String(l);if(l===0)return l;if(p.search(/[eE]/)!==-1)return t.eNotation?l:e;if(n.indexOf(".")!==-1)return p==="0"||p===a||p===`${i}${a}`?l:e;let c=o?a:n;return o?c===p||i+c===p?l:e:c===p||c===i+p?l:e}}else return e}}else return $ne(e,Number(n),t)}const zne=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function jne(e,t,n){if(!n.eNotation)return e;const r=t.match(zne);if(r){let i=r[1]||"";const o=r[3].indexOf("e")===-1?"E":"e",a=r[2],s=i?e[a.length+1]===o:e[a.length]===o;return a.length>1&&s?e:a.length===1&&(r[3].startsWith(`.${o}`)||r[3][0]===o)?Number(t):a.length>0?n.leadingZeros&&!s?(t=(r[1]||"")+r[3],Number(t)):e:Number(t)}else return e}function One(e){return e&&e.indexOf(".")!==-1&&(e=e.replace(/0+$/,""),e==="."?e="0":e[0]==="."?e="0"+e:e[e.length-1]==="."&&(e=e.substring(0,e.length-1))),e}function KT(e,t){const n=e.trim();if((t===2||t===8)&&(e=n.substring(2)),parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function $ne(e,t,n){const r=t===1/0;switch(n.infinity.toLowerCase()){case"null":return null;case"infinity":return t;case"string":return r?"Infinity":"-Infinity";default:return e}}function _ne(e){return typeof e=="function"?e:Array.isArray(e)?t=>{for(const n of e)if(typeof n=="string"&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}class NB{constructor(t,n={},r){this.pattern=t,this.separator=n.separator||".",this.segments=this._parse(t),this.data=r,this._hasDeepWildcard=this.segments.some(i=>i.type==="deep-wildcard"),this._hasAttributeCondition=this.segments.some(i=>i.attrName!==void 0),this._hasPositionSelector=this.segments.some(i=>i.position!==void 0)}_parse(t){const n=[];let r=0,i="";for(;r0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const n=this._matcher.path;if(n.length!==0)return n[n.length-1].values?.[t]}hasAttr(t){const n=this._matcher.path;if(n.length===0)return!1;const r=n[n.length-1];return r.values!==void 0&&t in r.values}getAnyParentAttr(t){return this._matcher.getAnyParentAttr(t)}hasAnyParentAttr(t){return this._matcher.hasAnyParentAttr(t)}getPosition(){const t=this._matcher.path;return t.length===0?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return t.length===0?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,n=!0){return this._matcher.toString(t,n)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class Gne{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new Wne(this),this._keptAttrs=[]}push(t,n=null,r=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const o=this.path.length;let a=this.siblingStacks[o];a||(a={counts:new Map,total:0},this.siblingStacks[o]=a);const s=r?`${r}:${t}`:t,l=a.counts.get(s)||0,p=a.total;a.counts.set(s,l+1),a.total++;const c={tag:t,position:p,counter:l};r!=null&&(c.namespace=r),n!=null&&(c.values=n),this.path.push(c);const u=this.path.length,d=i!==null?i.keep:null;if(d!=null&&d.length>0&&n)for(let h=0;hthis.path.length+1&&(this.siblingStacks.length=this.path.length+1);const n=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=n;)this._keptAttrs.pop();return t}updateCurrent(t){if(this.path.length>0){const n=this.path[this.path.length-1];t!=null&&(n.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(this.path.length!==0)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(this.path.length===0)return!1;const n=this.path[this.path.length-1];return n.values!==void 0&&t in n.values}getAnyParentAttr(t){const n=this._keptAttrs;for(let r=n.length-1;r>=0;r--)if(n[r].name===t)return n[r].value}hasAnyParentAttr(t){const n=this._keptAttrs;for(let r=n.length-1;r>=0;r--)if(n[r].name===t)return!0;return!1}getPosition(){return this.path.length===0?-1:this.path[this.path.length-1].position??0}getCounter(){return this.path.length===0?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,n=!0){const r=t||this.separator;if(r===this.separator&&n===!0){if(this._pathStringCache!==null)return this._pathStringCache;const o=this.path.map(a=>a.namespace?`${a.namespace}:${a.tag}`:a.tag).join(r);return this._pathStringCache=o,o}return this.path.map(o=>n&&o.namespace?`${o.namespace}:${o.tag}`:o.tag).join(r)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[],this._keptAttrs=[]}matches(t){const n=t.segments;return n.length===0?!1:t.hasDeepWildcard()?this._matchWithDeepWildcard(n):this._matchSimple(n)}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let n=0;n=0&&n>=0;){const i=t[r];if(i.type==="deep-wildcard"){if(r--,r<0)return!0;const o=t[r];let a=!1;for(let s=n;s>=0;s--)if(this._matchSegment(o,this.path[s],s===this.path.length-1)){n=s-1,r--,a=!0;break}if(!a)return!1}else{if(!this._matchSegment(i,this.path[n],n===this.path.length-1))return!1;n--,r--}}return r<0}_matchSegment(t,n,r){if(t.tag!=="*"&&t.tag!==n.tag||t.namespace!==void 0&&t.namespace!=="*"&&t.namespace!==n.namespace||t.attrName!==void 0&&(!r||!n.values||!(t.attrName in n.values)||t.attrValue!==void 0&&String(n.values[t.attrName])!==String(t.attrValue)))return!1;if(t.position!==void 0){if(!r)return!1;const i=n.counter??0;if(t.position==="first"&&i!==0)return!1;if(t.position==="odd"&&i%2!==1)return!1;if(t.position==="even"&&i%2!==0)return!1;if(t.position==="nth"&&i!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>t&&{counts:new Map(t.counts),total:t.total}),keptAttrs:this._keptAttrs.map(t=>({...t}))}}restore(t){this._pathStringCache=null,this.path=t.path.map(n=>({...n})),this.siblingStacks=t.siblingStacks.map(n=>n&&{counts:new Map(n.counts),total:n.total}),this._keptAttrs=(t.keptAttrs||[]).map(n=>({...n}))}readOnly(){return this._view}}const N6=[{id:"html-script-open",description:" + + + + + + + +
+ + diff --git a/apps/desktop/resources/plugins/pi.office/views/layout-stability.js b/apps/desktop/resources/plugins/pi.office/views/layout-stability.js new file mode 100644 index 0000000000..99e4774045 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/views/layout-stability.js @@ -0,0 +1,128 @@ +(function installOfficeLayoutStability() { + "use strict"; + + const RESIZE_SETTLE_MS = 96; + const attached = new WeakSet(); + let userGestureRevision = 0; + + function pageAnchor(scroller) { + const viewport = scroller.getBoundingClientRect(); + const pages = Array.from(scroller.querySelectorAll(".doc-page")); + const pageIndex = pages.findIndex((page) => { + const rect = page.getBoundingClientRect(); + return rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1; + }); + const page = pageIndex >= 0 ? pages[pageIndex] : null; + const pageRect = page?.getBoundingClientRect(); + const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight); + return { + pageIndex, + pageOffset: pageRect ? pageRect.top - viewport.top : null, + scrollTop: scroller.scrollTop, + scrollRatio: maxScrollTop > 0 ? scroller.scrollTop / maxScrollTop : 0, + scrollLeft: scroller.scrollLeft, + revision: userGestureRevision, + }; + } + + function restoreAnchor(scroller, anchor) { + if (anchor.revision !== userGestureRevision || !scroller.isConnected) return; + + const viewport = scroller.getBoundingClientRect(); + const pages = Array.from(scroller.querySelectorAll(".doc-page")); + const page = anchor.pageIndex >= 0 ? pages[anchor.pageIndex] : null; + let nextTop = anchor.scrollTop; + if (page && anchor.pageOffset !== null) { + const currentOffset = page.getBoundingClientRect().top - viewport.top; + nextTop = scroller.scrollTop + currentOffset - anchor.pageOffset; + } else { + const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight); + nextTop = maxScrollTop * anchor.scrollRatio; + } + + const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight); + scroller.scrollTop = Math.min(maxScrollTop, Math.max(0, nextTop)); + scroller.scrollLeft = anchor.scrollLeft; + } + + function stopResizeLock(state) { + state.resizing = false; + state.anchor = null; + if (state.frame) { + cancelAnimationFrame(state.frame); + state.frame = 0; + } + } + + function markUserGesture(state) { + userGestureRevision += 1; + stopResizeLock(state); + state.lastAnchor = pageAnchor(state.scroller); + } + + function scheduleResizeLock(state) { + if (state.frame || !state.resizing) return; + state.frame = requestAnimationFrame(() => { + state.frame = 0; + if (!state.resizing || !state.scroller.isConnected) return; + + // GenOffice recalculates fit-to-width asynchronously. Correct the anchor + // in the same rendering cycle, then keep doing so until the resize settles. + restoreAnchor(state.scroller, state.anchor); + if (performance.now() - state.lastResizeAt < RESIZE_SETTLE_MS) { + scheduleResizeLock(state); + return; + } + + restoreAnchor(state.scroller, state.anchor); + state.resizing = false; + state.anchor = null; + state.lastAnchor = pageAnchor(state.scroller); + }); + } + + function attach(scroller) { + if (attached.has(scroller)) return; + attached.add(scroller); + const state = { + scroller, + frame: 0, + lastResizeAt: 0, + lastAnchor: pageAnchor(scroller), + anchor: null, + resizing: false, + }; + let previousWidth = scroller.clientWidth; + scroller.style.overflowAnchor = "none"; + for (const event of ["wheel", "touchstart", "pointerdown", "keydown"]) { + scroller.addEventListener(event, () => markUserGesture(state), { passive: true }); + } + scroller.addEventListener("scroll", () => { + if (!state.resizing) state.lastAnchor = pageAnchor(scroller); + }, { passive: true }); + + const observer = new ResizeObserver((entries) => { + const width = entries[0]?.contentRect.width ?? scroller.clientWidth; + if (Math.abs(width - previousWidth) < 0.5) return; + previousWidth = width; + if (!state.resizing) { + state.anchor = state.lastAnchor ?? pageAnchor(scroller); + state.resizing = true; + } + state.lastResizeAt = performance.now(); + restoreAnchor(scroller, state.anchor); + scheduleResizeLock(state); + }); + observer.observe(scroller); + } + + function scan() { + document.querySelectorAll(".editor-scroll").forEach(attach); + } + + scan(); + new MutationObserver(scan).observe(document.documentElement, { + childList: true, + subtree: true, + }); +})(); diff --git a/apps/desktop/resources/plugins/pi.office/views/office-toolbar-navigation.js b/apps/desktop/resources/plugins/pi.office/views/office-toolbar-navigation.js new file mode 100644 index 0000000000..5a10cb9680 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/views/office-toolbar-navigation.js @@ -0,0 +1,434 @@ +(() => { + const NAVIGATION_CLASS = "pi-office-toolbar-nav"; + const OVERFLOW_CLASS = "pi-office-toolbar-overflow"; + const SCROLL_CLASS = "pi-office-toolbar-scroll"; + const HOST_CLASS = "pi-office-toolbar-host"; + const ORIGINAL_COLLAPSE_CLASS = "pi-office-original-collapse-control"; + const PARTIAL_ITEM_CLASS = "pi-office-toolbar-partial-item"; + const SINGLE_COLUMN_CLASS = "pi-office-toolbar-single-column"; + const PAGE_CONTROL_GUTTER = 6; + const attachedRibbons = new WeakMap(); + let updateScheduled = false; + + const clamp = (value, min, max) => Math.min(max, Math.max(min, value)); + + function getLabels() { + const language = document.documentElement.lang || ""; + const isChinese = language.toLowerCase().startsWith("zh"); + return isChinese + ? { + previous: "上一页工具", + next: "下一页工具", + } + : { + previous: "Previous toolbar page", + next: "Next toolbar page", + }; + } + + function createArrow(direction, getBody) { + const labels = getLabels(); + const button = document.createElement("button"); + const path = direction === "previous" ? "M14 5 8 12l6 7" : "m10 5 6 7-6 7"; + + button.type = "button"; + button.className = `${NAVIGATION_CLASS} ${NAVIGATION_CLASS}-${direction}`; + button.setAttribute("aria-label", labels[direction]); + button.title = labels[direction]; + button.addEventListener("pointerdown", (event) => { + event.preventDefault(); + event.stopPropagation(); + }); + button.addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + pageToolbar(getBody(), direction === "previous" ? -1 : 1); + }); + + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); + svg.setAttribute("aria-hidden", "true"); + svg.setAttribute("focusable", "false"); + svg.innerHTML = ``; + button.append(svg); + return button; + } + + function getToolbarItemBounds(container) { + const containerRect = container.getBoundingClientRect(); + return Array.from( + container.querySelectorAll( + "button, input, select, textarea, [role='button'], .ribbon-sep", + ), + ) + .filter((item) => item.offsetParent !== null) + .map((item) => { + const rect = item.getBoundingClientRect(); + return { + element: item, + left: rect.left - containerRect.left + container.scrollLeft, + right: + rect.right - containerRect.left + + container.scrollLeft + + PAGE_CONTROL_GUTTER, + }; + }) + .filter(({ left, right }) => Number.isFinite(left) && right > left) + .sort((a, b) => a.left - b.left || a.right - b.right); + } + + function getToolbarPageStarts(container) { + const pageWidth = Math.max(1, container.clientWidth); + const maxScroll = Math.max(0, container.scrollWidth - pageWidth); + if (maxScroll <= 1) return [0]; + + const items = getToolbarItemBounds(container); + if (items.length === 0) { + return [0, maxScroll]; + } + + const starts = [0]; + let start = 0; + while (start < maxScroll - 1) { + const viewportEnd = start + pageWidth; + const nextItem = items.find( + ({ left, right }) => left > start + 1 && right > viewportEnd + 1, + ); + const nextStart = clamp( + nextItem?.left ?? maxScroll, + start + 1, + maxScroll, + ); + starts.push(nextStart); + start = nextStart; + } + + if (starts.at(-1) !== maxScroll) starts.push(maxScroll); + return starts; + } + + function updatePartialToolbarItems(container) { + const leftEdge = container.scrollLeft + 1; + const rightEdge = container.scrollLeft + container.clientWidth - 1; + for (const { element, left, right } of getToolbarItemBounds(container)) { + element.classList.toggle( + PARTIAL_ITEM_CLASS, + left < leftEdge || right > rightEdge, + ); + } + } + + function getDirectToolbarChild(container, element) { + let current = element; + while (current && current.parentElement !== container) { + current = current.parentElement; + } + return current?.parentElement === container ? current : null; + } + + function centerSingleColumn(container) { + const containerRect = container.getBoundingClientRect(); + const viewportLeft = containerRect.left; + const viewportRight = viewportLeft + container.clientWidth; + const visibleItems = getToolbarItemBounds(container).filter(({ element, left, right }) => { + if (element.classList.contains(PARTIAL_ITEM_CLASS)) return false; + const itemLeft = left - container.scrollLeft + viewportLeft; + const itemRight = right - container.scrollLeft + viewportLeft; + return itemRight > viewportLeft + 1 && itemLeft < viewportRight - 1; + }); + const modules = new Set( + visibleItems + .map(({ element }) => getDirectToolbarChild(container, element)) + .filter( + (element) => + element?.classList.contains("ribbon-group") || + element?.classList.contains("table-ribbon-body"), + ), + ); + const isSingleColumn = modules.size === 1; + container.classList.toggle(SINGLE_COLUMN_CLASS, isSingleColumn); + if (!isSingleColumn) return; + + const [module] = modules; + const moduleRect = module.getBoundingClientRect(); + if (moduleRect.width > container.clientWidth + 1) return; + + const shift = + moduleRect.left + moduleRect.width / 2 - (viewportLeft + container.clientWidth / 2); + if (Math.abs(shift) <= 1) return; + + const maxScroll = Math.max(0, container.scrollWidth - container.clientWidth); + container.scrollLeft = clamp(container.scrollLeft + shift, 0, maxScroll); + updatePartialToolbarItems(container); + } + + function isRibbonExpanded(ribbon) { + const body = ribbon.querySelector(":scope > .ribbon-body"); + return Boolean(body && !body.hidden && body.offsetParent !== null); + } + + function toggleRibbonCollapse(ribbon) { + const original = ribbon.querySelector(`.${ORIGINAL_COLLAPSE_CLASS}`); + if (original) { + original.click(); + return; + } + + const isMac = (navigator.platform || "").toLowerCase().includes("mac"); + window.dispatchEvent( + new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + key: isMac ? "r" : "F1", + code: isMac ? "KeyR" : "F1", + ctrlKey: !isMac, + metaKey: isMac, + altKey: isMac, + }), + ); + } + + function bindCategoryToggle(ribbon) { + ribbon + .querySelectorAll(":scope > .ribbon-tabs > .ribbon-tab") + .forEach((tab) => { + if (tab.dataset.piOfficeCollapseBound === "true") return; + tab.dataset.piOfficeCollapseBound = "true"; + tab.addEventListener( + "click", + (event) => { + const isActive = + tab.classList.contains("active") || + tab.getAttribute("aria-selected") === "true"; + if (isActive) { + event.preventDefault(); + event.stopImmediatePropagation(); + toggleRibbonCollapse(ribbon); + return; + } + + if (!isRibbonExpanded(ribbon)) toggleRibbonCollapse(ribbon); + }, + true, + ); + }); + } + + function pageToolbar(container, direction) { + if (!container) return; + + const starts = getToolbarPageStarts(container); + const currentPage = starts.reduce( + (page, start, index) => + start <= container.scrollLeft + 1 ? index : page, + 0, + ); + const target = starts[clamp(currentPage + direction, 0, starts.length - 1)]; + if (Math.abs(target - container.scrollLeft) <= 1) return; + + container.scrollTo({ + left: target, + behavior: "auto", + }); + } + + function updateNavigation(container, state) { + if (!container) { + state.previous.hidden = false; + state.next.hidden = false; + state.previous.disabled = true; + state.next.disabled = true; + state.previous.setAttribute("aria-disabled", "true"); + state.next.setAttribute("aria-disabled", "true"); + return; + } + + updatePartialToolbarItems(container); + centerSingleColumn(container); + + const pageStarts = getToolbarPageStarts(container); + const hasOverflow = pageStarts.length > 1; + const currentPage = pageStarts.reduce( + (page, start, index) => + start <= container.scrollLeft + 1 ? index : page, + 0, + ); + const atStart = currentPage <= 0; + const atEnd = currentPage >= pageStarts.length - 1; + + container.classList.toggle(OVERFLOW_CLASS, hasOverflow); + state.previous.hidden = false; + state.next.hidden = false; + state.previous.disabled = !hasOverflow || atStart; + state.next.disabled = !hasOverflow || atEnd; + state.previous.setAttribute("aria-disabled", String(state.previous.disabled)); + state.next.setAttribute("aria-disabled", String(state.next.disabled)); + } + + function markOriginalCollapseControl(ribbon) { + ribbon.querySelectorAll(".ribbon-collapse-btn").forEach((button) => { + button.classList.add(ORIGINAL_COLLAPSE_CLASS); + }); + } + + function removeNavigationButtons(ribbon, body) { + ribbon + .querySelectorAll(`:scope > .${NAVIGATION_CLASS}`) + .forEach((button) => button.remove()); + body?.querySelectorAll(`:scope > .${NAVIGATION_CLASS}`).forEach((button) => { + button.remove(); + }); + } + + function detachNavigation(ribbon) { + const state = attachedRibbons.get(ribbon); + if (state) detachBodyBinding(state); + removeNavigationButtons(ribbon, state?.body); + ribbon.classList.remove(HOST_CLASS); + attachedRibbons.delete(ribbon); + } + + function getOrCreateNavigationState(ribbon) { + let state = attachedRibbons.get(ribbon); + if (state) return state; + + removeNavigationButtons(ribbon); + state = { + body: null, + previous: createArrow("previous", () => state.body), + next: createArrow("next", () => state.body), + onScroll: null, + resizeObserver: null, + }; + attachedRibbons.set(ribbon, state); + return state; + } + + function ensureNavigationControls(ribbon, state) { + ribbon.classList.add(HOST_CLASS); + if (!state.previous.isConnected || state.previous.parentElement !== ribbon) { + ribbon.append(state.previous); + } + if (!state.next.isConnected || state.next.parentElement !== ribbon) { + ribbon.append(state.next); + } + } + + function detachBodyBinding(state) { + if (state.resizeObserver) { + state.resizeObserver.disconnect(); + state.resizeObserver = null; + } + + if (state.onScroll && state.body) { + state.body.removeEventListener("scroll", state.onScroll); + state.body.classList.remove(SCROLL_CLASS, OVERFLOW_CLASS); + state.body + .querySelectorAll(`.${PARTIAL_ITEM_CLASS}`) + .forEach((item) => item.classList.remove(PARTIAL_ITEM_CLASS)); + } + + state.onScroll = null; + } + + function attachNavigation(ribbon, body) { + const state = getOrCreateNavigationState(ribbon); + ensureNavigationControls(ribbon, state); + + if ( + state.body === body && + state.previous.isConnected && + state.next.isConnected && + state.previous.parentElement === ribbon && + state.next.parentElement === ribbon + ) { + updateNavigation(body, state); + return; + } + + // Category changes replace .ribbon-body, but the fixed controls belong to + // the outer ribbon and must survive that replacement. + detachBodyBinding(state); + state.body = body; + body.classList.add(SCROLL_CLASS); + + state.onScroll = () => updateNavigation(state.body, state); + body.addEventListener("scroll", state.onScroll, { + passive: true, + }); + + if (typeof ResizeObserver === "function") { + const resizeObserver = new ResizeObserver(() => { + updateNavigation(state.body, state); + }); + resizeObserver.observe(ribbon); + resizeObserver.observe(body); + state.resizeObserver = resizeObserver; + } + + updateNavigation(body, state); + } + + function decorateToolbar(ribbon) { + const clipboardLabels = new Set([ + "粘贴", + "Paste", + "貼り付け", + "붙여넣기", + ]); + ribbon.querySelectorAll(".ribbon-body .ribbon-group").forEach((group) => { + const hasPaste = Array.from(group.querySelectorAll(".rb-big")).some((button) => + clipboardLabels.has(button.textContent.trim()), + ); + group.classList.toggle("pi-office-clipboard-group", hasPaste); + }); + + ribbon.querySelectorAll(".ribbon-body .layout-para").forEach((group) => { + group.classList.add("pi-office-layout-para"); + group.querySelectorAll(".layout-col").forEach((column) => { + column.classList.add("pi-office-layout-col"); + }); + }); + } + + function refresh() { + document.querySelectorAll(".ribbon").forEach((ribbon) => { + const tabs = ribbon.querySelector(".ribbon-tabs"); + const body = ribbon.querySelector(".ribbon-body"); + ribbon.classList.toggle("pi-office-ribbon-collapsed", !isRibbonExpanded(ribbon)); + if (tabs) { + // Category switching stays in the fixed first row. Only the command + // row is paged, so the arrows never cover save or tab controls. + tabs.classList.add("pi-office-toolbar-tabs"); + bindCategoryToggle(ribbon); + } + markOriginalCollapseControl(ribbon); + if (body) attachNavigation(ribbon, body); + else { + // A category switch can temporarily remove the command row before + // inserting its replacement. Keep the fixed controls on the outer + // ribbon and only pause the old row's listeners during that window. + const state = getOrCreateNavigationState(ribbon); + detachBodyBinding(state); + state.body = null; + ensureNavigationControls(ribbon, state); + updateNavigation(null, state); + } + decorateToolbar(ribbon); + }); + } + + function scheduleRefresh() { + if (updateScheduled) return; + updateScheduled = true; + requestAnimationFrame(() => { + updateScheduled = false; + refresh(); + }); + } + + const observer = new MutationObserver(scheduleRefresh); + observer.observe(document.documentElement, { childList: true, subtree: true }); + window.addEventListener("resize", scheduleRefresh, { passive: true }); + scheduleRefresh(); +})(); diff --git a/apps/desktop/resources/plugins/pi.office/views/pi-office-overrides.css b/apps/desktop/resources/plugins/pi.office/views/pi-office-overrides.css new file mode 100644 index 0000000000..009ea5f966 --- /dev/null +++ b/apps/desktop/resources/plugins/pi.office/views/pi-office-overrides.css @@ -0,0 +1,484 @@ +/* PI-Desktop does not expose GenOffice's Genspark AI entry points. */ +.ribbon-group:has(.ai-entry), +.ribbon-group:has(.ai-entry) + .ribbon-sep { + display: none !important; +} + +/* Remove AI actions that are mixed into otherwise useful Word groups. */ +.ribbon .rb-big:has(.ai-feature-icon), +.ribbon .rb-big[data-tip*="AI"], +.ribbon .rb-big[data-tip*="IA"], +.ribbon .rb-big[data-tip*="KI"], +.ribbon .rb-big[data-tip*="Genspark"] { + display: none !important; +} + +.ribbon-group:has(> .ribbon-group-items > .rb-split-wrap:only-child > .rb-big:has(.ai-feature-icon)), +.ribbon-group:has(> .ribbon-group-items > .rb-split-wrap:only-child > .rb-big:has(.ai-feature-icon)) + .ribbon-sep { + display: none !important; +} + +/* The view-tab AI toggle has no stable class in the extracted vendor UI. */ +.ribbon-group button[data-tip="显示/隐藏 AI 面板"], +.ribbon-group button[data-tip="Show/hide the AI panel"], +.ribbon-group button[data-tip="AI パネルの表示/非表示"], +.ribbon-group button[data-tip="AI 패널 표시/숨기기"] { + display: none !important; +} + +/* AI selection actions and queued edit controls can render outside the dock. */ +.ai-ask-pop, +.ai-ask-trigger, +.ai-queue, +.ai-scope-row, +.ai-scope-preview, +.ai-partial-card, +.ai-panel, +.ai-dock, +.ai-rail, +.ai-work-group, +.ai-login-btn, +.ai-header-btn, +.ai-panel-resizer, +.ai-track-btn, +.ai-attach-btn, +.copilot, +.copilot-btn, +.copilot-badge, +.genspark-badge, +.ctx-item:has(.copilot-badge) { + display: none !important; +} + +/* The extracted file-pane toggle depends on an unavailable desktop surface. */ +.file-tab-wrap, +.files-edge-tab, +.ribbon-group button[data-tip="文件"], +.ribbon-group button[data-tip="Files"], +.ribbon-group button[data-tip="ファイル"], +.ribbon-group button[data-tip="파일"], +.files-pane { + display: none !important; +} + +/* Opening another editor tab belongs to the desktop shell, not this view. */ +.ribbon-group button[data-tip*="新建标签"], +.ribbon-group button[data-tip*="切换标签"], +.ribbon-group button[data-tip*="New tab"], +.ribbon-group button[data-tip*="Switch tab"] { + display: none !important; +} + +/* Keep the two ribbon rows horizontal and compact inside the docked work panel. */ +.ribbon-tabs, +.ribbon-body { + position: relative; + scrollbar-width: none; + scroll-behavior: auto; +} + +.ribbon-tabs::-webkit-scrollbar, +.ribbon-body::-webkit-scrollbar { + display: none; + width: 0; + height: 0; +} + +.ribbon-tabs { + gap: 0; + padding: 2px 8px 0 !important; + flex-wrap: nowrap !important; + overflow-x: hidden !important; + overflow-y: hidden !important; +} + +/* The category row is fixed. Only the command row is paged. */ +.pi-office-toolbar-tabs { + flex: 0 0 auto; + min-width: 0; + overflow: hidden !important; +} + +.ribbon-tabs > .qa-btn, +.ribbon-tabs > .autosave-toggle, +.ribbon-tabs > .qa-sep, +.ribbon-tabs > .ribbon-tab, +.ribbon-tabs > .file-tab-wrap { + flex: 0 0 auto !important; +} + +.ribbon-tabs-win, +.ribbon-tabs-mac { + padding-left: 8px !important; + padding-right: 8px !important; +} + +.ribbon-tab { + flex: 0 0 auto; + white-space: nowrap; + padding: 5px 7px 4px !important; + font-size: 12px !important; + line-height: 18px; +} + +.ribbon-tab.active:after { + left: 9px; + right: 9px; +} + +.ribbon-tabs-spacer { + min-width: 0; +} + +.ribbon-body { + box-sizing: border-box; + height: 44px !important; + min-height: 44px; + padding: 2px 8px !important; + flex-wrap: nowrap !important; + overflow-x: hidden !important; + overflow-y: hidden !important; +} + +.ribbon-body > .ribbon-group, +.ribbon-body > .ribbon-sep, +.ribbon-body > .table-ribbon-body > .ribbon-group, +.ribbon-body > .table-ribbon-body > .ribbon-sep, +.ribbon-body > .table-ribbon-body > .table-tool-group { + flex: 0 0 auto; +} + +.ribbon-group { + flex-direction: row; + align-items: center; + min-width: max-content; + padding: 0 2px; +} + +.ribbon-group-items, +.rb-font-group { + align-items: center; + gap: 2px; + flex-wrap: nowrap !important; + min-width: max-content; + white-space: nowrap; +} + +.rb-font-group { + flex-direction: row !important; +} + +.rb-big { + flex-direction: row; + flex: 0 0 auto; + gap: 3px; + padding: 3px 5px 3px; + font-size: 11px; + line-height: 18px; +} + +.rb-big-icon, +.rb-big .rb-big-icon { + min-height: 20px; + flex: 0 0 auto; + padding: 1px 2px; + margin: 0; +} + +.rb-big-icon svg { + width: 16px; + height: 16px; +} + +.rb-small { + flex: 0 0 auto; + gap: 3px; + padding: 3px 5px; + font-size: 11px; +} + +/* GenOffice nests several compact commands in vertical columns. Keep the + commands in one horizontal row so the command bar never grows vertically. */ +.ribbon-body .rb-col, +.ribbon-body .rb-row, +.ribbon-body .layout-para, +.ribbon-body .layout-col, +.ribbon-body .layout-num, +.ribbon-body .table-tool-row, +.ribbon-body .table-tool-grid, +.ribbon-body .style-gallery-wrap, +.ribbon-body .style-gallery { + flex-wrap: nowrap !important; + white-space: nowrap; +} + +.ribbon .ribbon-body .pi-office-layout-para { + display: flex !important; + flex: 0 0 auto !important; + flex-flow: row nowrap !important; + align-items: center !important; + gap: 7px !important; + min-width: max-content; +} + +.ribbon .ribbon-body .pi-office-layout-col { + display: flex !important; + flex: 0 0 auto !important; + flex-flow: row nowrap !important; + align-items: center !important; + gap: 3px !important; + min-width: max-content; +} + +.ribbon-body .rb-col, +.ribbon-body .layout-col { + flex-direction: row !important; + align-items: center; + gap: 3px; +} + +.ribbon-body .layout-para { + gap: 7px; +} + +.ribbon-body .layout-num { + flex: 0 0 auto; + gap: 3px; + font-size: 11px; +} + +.ribbon-body .layout-num > span:first-child { + width: auto; + font-size: 11px; +} + +.ribbon-body .layout-num input { + width: 32px; + height: 24px; +} + +.ribbon-body .layout-unit { + font-size: 10px; +} + +.ribbon-body .table-tool-grid { + display: flex !important; + gap: 3px; +} + +.ribbon-body .style-gallery-wrap, +.ribbon-body .style-gallery { + height: 32px; + overflow: hidden; +} + +/* The compact toolbar gallery uses a horizontal preview-label card. The + vendor gallery is taller and stacked for its full ribbon, which clips when + the command row is paged into the narrow work-panel toolbar. */ +.ribbon-body .style-gallery .style-card { + display: inline-flex; + flex-direction: row !important; + align-items: baseline; + justify-content: flex-start; + gap: 4px; + width: 74px; + height: 28px; + padding: 2px 5px; +} + +.ribbon-body .style-gallery .style-card-preview { + flex: 0 0 auto; + font-size: 12px; + line-height: 1; +} + +.ribbon-body .style-gallery .style-card-preview.style-h1 { + font-size: 14px; +} + +.ribbon-body .style-gallery .style-card-preview.style-h2 { + font-size: 12px; +} + +.ribbon-body .style-gallery .style-card-preview.style-h3 { + font-size: 11px; +} + +.ribbon-body .style-gallery .style-card-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 9.5px; + line-height: 1; +} + +.ribbon-body .style-gallery-more { + height: 28px; +} + +/* Pages containing only one compact module should use the middle column as a + centered stage. This keeps the style gallery and color controls balanced + after the surrounding groups have paged out of view. */ +.ribbon-body.pi-office-toolbar-single-column > .ribbon-group, +.ribbon-body.pi-office-toolbar-single-column > .table-ribbon-body { + justify-content: center; +} + +.ribbon-body.pi-office-toolbar-single-column .style-gallery { + justify-content: center; +} + +.ribbon-body.pi-office-toolbar-single-column .rb-col, +.ribbon-body.pi-office-toolbar-single-column .rb-row { + justify-content: center; +} + +.ribbon-body.pi-office-toolbar-single-column .rb-col { + align-items: center; +} + +.ribbon-body .rb-split-wrap, +.ribbon-body .table-tool-group { + flex: 0 0 auto; +} + +/* A page boundary must never leave a partially visible command. Keep the + command's layout width so page stops remain stable, but hide the command + until the page containing it is active. */ +.ribbon-body .pi-office-toolbar-partial-item { + visibility: hidden !important; + pointer-events: none !important; +} + +/* The clipboard group is a high-frequency fixed-width cluster. Its labels + are available through aria-label/data-tip while the compact bar shows the + familiar icons without consuming a second line. */ +.ribbon-body .pi-office-clipboard-group { + min-width: max-content; +} + +.ribbon-body .pi-office-clipboard-group .rb-big > span:last-child { + display: none; +} + +.ribbon-body .pi-office-clipboard-group .rb-big-icon { + min-width: 22px; +} + +.rb-icon { + min-width: 26px; + height: 26px; + padding: 0 3px; +} + +.rb-select, +.rb-caret.rb-combo-caret { + height: 26px; +} + +.rb-font-family { + width: 112px; +} + +.rb-font-size { + width: 40px; +} + +.rb-caret.rb-combo-caret { + width: 16px; +} + +.rb-mini-sep { + height: 18px; + margin: 0 3px; +} + +.ribbon-sep { + margin: 0 4px; +} + +/* Keep paging controls outside the command row. They stay fixed while one full + toolbar page at a time moves horizontally inside .ribbon-body. */ +.ribbon.pi-office-toolbar-host { + display: grid; + grid-template-columns: 32px minmax(0, 1fr) 32px; + grid-template-rows: auto 44px; + align-items: stretch; +} + +.ribbon.pi-office-toolbar-host > .ribbon-tabs { + grid-column: 1 / -1; + grid-row: 1; + min-width: 0; +} + +.ribbon.pi-office-toolbar-host > .ribbon-body { + grid-column: 2; + grid-row: 2; + min-width: 0; + width: auto; + padding-left: 8px !important; + padding-right: 8px !important; + scroll-padding-inline: 8px; +} + +.ribbon.pi-office-toolbar-host > .pi-office-toolbar-nav { + position: static; + grid-row: 2; + align-self: stretch; + z-index: 2; + display: inline-flex; + align-items: center; + justify-content: center; + width: auto; + height: auto; + padding: 0; + border: 0; + border-radius: 0; + background: var(--chrome-bg); + color: var(--text-secondary); + cursor: pointer; + -webkit-app-region: no-drag; + box-shadow: none; +} + +.ribbon.pi-office-toolbar-host > .pi-office-toolbar-nav svg { + width: 15px; + height: 15px; +} + +.ribbon.pi-office-toolbar-host > .pi-office-toolbar-nav:hover:not(:disabled) { + background: var(--hover); + color: var(--text-primary); +} + +.ribbon.pi-office-toolbar-host > .pi-office-toolbar-nav:disabled { + opacity: 0.35; + cursor: default; +} + +.ribbon.pi-office-toolbar-host > .pi-office-toolbar-nav-previous { + grid-column: 1; +} + +.ribbon.pi-office-toolbar-host > .pi-office-toolbar-nav-next { + grid-column: 3; +} + +.ribbon.pi-office-toolbar-host .pi-office-original-collapse-control { + display: none !important; +} + +.ribbon.pi-office-toolbar-host > .pi-office-toolbar-nav[hidden] { + display: inline-flex !important; +} + +.ribbon.pi-office-toolbar-host.pi-office-ribbon-collapsed { + grid-template-rows: auto; +} + +.ribbon.pi-office-toolbar-host.pi-office-ribbon-collapsed > .ribbon-body, +.ribbon.pi-office-toolbar-host.pi-office-ribbon-collapsed > .pi-office-toolbar-nav { + display: none !important; +} diff --git a/apps/desktop/src/components/workpanel/PluginViewTab.tsx b/apps/desktop/src/components/workpanel/PluginViewTab.tsx index 669521a379..5604c1d2e2 100644 --- a/apps/desktop/src/components/workpanel/PluginViewTab.tsx +++ b/apps/desktop/src/components/workpanel/PluginViewTab.tsx @@ -42,15 +42,19 @@ export function PluginViewTab({ // the previous web contents while this tab stays open. useEffect(() => { let current = true; - const open = () => { - void api.pluginViewOpen(pluginId, viewId, { sessionId, location }).then( - () => { - if (current) setFailed(false); - }, - () => { - if (current) setFailed(true); - }, - ); + const open = async () => { + try { + await api.pluginViewOpen(pluginId, viewId, { sessionId, location }); + if (!current) return; + // A reload destroys the native WebContentsView before the renderer + // receives pluginChanged. Re-attach it only after open has completed; + // calling setVisible earlier races the host's view creation and leaves + // the work panel with a stale, non-interactive surface. + await api.pluginViewSetVisible(pluginId, viewId, !blocked, sessionId); + if (current) setFailed(false); + } catch { + if (current) setFailed(true); + } }; open(); const off = api.onPluginChanged((event) => { @@ -61,7 +65,7 @@ export function PluginViewTab({ current = false; off(); }; - }, [pluginId, viewId, sessionId, location]); + }, [blocked, pluginId, viewId, sessionId, location]); useEffect(() => { const surface = surfaceRef.current; diff --git a/apps/desktop/src/components/workpanel/WorkPanel.tsx b/apps/desktop/src/components/workpanel/WorkPanel.tsx index 882cfc1f4f..0668d36099 100644 --- a/apps/desktop/src/components/workpanel/WorkPanel.tsx +++ b/apps/desktop/src/components/workpanel/WorkPanel.tsx @@ -12,6 +12,7 @@ import { useTranslation } from "react-i18next"; import { useBlockingOverlayActive } from "../../lib/blocking-overlay"; import type { PluginViewMeta } from "@pi-desktop/shared"; import { + OFFICE_PLUGIN_TAB, isKnownWorkPanelTab, parsePluginViewRef, pluginWorkPanelTab, @@ -75,6 +76,13 @@ type WorkPanelTool = { shortcut?: string; }; +function locationBasename(location: string | undefined): string | null { + const normalized = location?.trim().replace(/[\\/]+$/, ""); + if (!normalized) return null; + const basename = normalized.split(/[\\/]/).filter(Boolean).pop(); + return basename || null; +} + function tabLabel( tab: WorkPanelTab, t: (key: string) => string, @@ -82,9 +90,13 @@ function tabLabel( ) { if (tab.kind === "plugin") { const view = pluginViews.find((candidate) => candidate.ref === tab.resource); + const documentName = + view?.pluginId === OFFICE_PLUGIN_TAB.pluginId + ? locationBasename(tab.location) + : null; // A view whose plugin was disabled mid-session no longer resolves; fall // back to its id rather than leaving the tab blank until it closes. - return view?.title ?? tab.resource ?? t("panel.tabs.plugin"); + return documentName ?? view?.title ?? tab.resource ?? t("panel.tabs.plugin"); } if (tab.kind === "new") return t("panel.new.title"); if (tab.kind !== "file") return t(`panel.tabs.${tab.kind}`); diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx index a3bf9ec566..6c2f1f3cb9 100644 --- a/apps/desktop/src/features/app/useAppShellRuntime.tsx +++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx @@ -574,6 +574,11 @@ export function useAppShellRuntime() { ...browserPluginTab(event.path ?? event.url), }); }); + const offPluginOpenWorkPanelFile = api.onPluginOpenWorkPanelFile((event) => { + const path = typeof event.path === "string" ? event.path.trim() : ""; + if (!path) return; + useAppStore.getState().openFileInWorkPanel(path, event.mimeType); + }); const offHostStatus = api.onHostStatus((status) => { if (status.archMismatch) setArchMismatch(status.archMismatch); if (status.ok) { @@ -760,6 +765,7 @@ export function useAppShellRuntime() { offPlansChanged(); offToast(); offBrowserPreview(); + offPluginOpenWorkPanelFile(); offHostStatus(); offNotificationChanged(); offSessionsChanged(); diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.ts index 313487cd67..d5d88b3869 100644 --- a/apps/desktop/src/hooks/use-preview-target.ts +++ b/apps/desktop/src/hooks/use-preview-target.ts @@ -6,8 +6,11 @@ import { isHtmlFilePath, toWorkspaceRel, type ChatPreviewTarget } from "../lib/c import { openHttpUrl } from "../lib/open-http-url"; import { FILE_MANAGER_PLUGIN_TAB, + OFFICE_PLUGIN_TAB, fileManagerPluginTab, hasPluginView, + isDocxFilePath, + officePluginTab, } from "../lib/work-panel-tabs"; /** @@ -69,6 +72,10 @@ export function useOpenChatFileRef() { () => hasPluginView(pluginViews, FILE_MANAGER_PLUGIN_TAB), [pluginViews], ); + const officeViewAvailable = useMemo( + () => hasPluginView(pluginViews, OFFICE_PLUGIN_TAB), + [pluginViews], + ); return useCallback( (path: string, baseDir?: string, mimeType?: string) => { @@ -103,6 +110,10 @@ export function useOpenChatFileRef() { openUrl(match.relativePath); return; } + if (officeViewAvailable && isDocxFilePath(target)) { + openTab(officePluginTab(target)); + return; + } if (fileViewAvailable) { openTab(fileManagerPluginTab(target)); return; @@ -115,6 +126,7 @@ export function useOpenChatFileRef() { }, [ fileViewAvailable, + officeViewAvailable, openFile, openTab, openUrl, diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts index dc0c39c9f0..27cc8c5733 100644 --- a/apps/desktop/src/lib/api.ts +++ b/apps/desktop/src/lib/api.ts @@ -1328,6 +1328,14 @@ export const api = { listener(payload as { sessionId: string; path?: string; url?: string }), ); }, + onPluginOpenWorkPanelFile: ( + listener: (event: { path: string; mimeType?: string }) => void, + ) => { + if (!window.piDesktop?.on) return () => undefined; + return window.piDesktop.on(IPC.event.pluginOpenWorkPanelFile, (payload) => + listener((payload ?? {}) as { path: string; mimeType?: string }), + ); + }, onAgentEvent: (listener: (event: AgentEventEnvelope) => void) => { if (!window.piDesktop?.on) return () => undefined; return window.piDesktop.on(IPC.event.agentMessage, (payload) => diff --git a/apps/desktop/src/lib/work-panel-tabs.ts b/apps/desktop/src/lib/work-panel-tabs.ts index d38e56d26e..9e89c07d7a 100644 --- a/apps/desktop/src/lib/work-panel-tabs.ts +++ b/apps/desktop/src/lib/work-panel-tabs.ts @@ -118,6 +118,23 @@ export const FILE_MANAGER_PLUGIN_TAB = { viewId: "manager", } as const; +export const OFFICE_PLUGIN_TAB = { + pluginId: "pi.office", + viewId: "editor", +} as const; + +export function isDocxFilePath(path: string): boolean { + return /\.docx$/i.test(path.trim()); +} + +/** A DOCX file uses the bundled Office editor when that view is available. */ +export function officePluginTab(location: string): WorkPanelTab { + return { + ...pluginWorkPanelTab(OFFICE_PLUGIN_TAB.pluginId, OFFICE_PLUGIN_TAB.viewId), + location, + }; +} + /** The file view, asked to show one file. */ export function fileManagerPluginTab(location: string): WorkPanelTab { return { diff --git a/apps/desktop/src/stores/slices/work-panel-slice.ts b/apps/desktop/src/stores/slices/work-panel-slice.ts index 2fc5ae354a..2c9f0ddbe5 100644 --- a/apps/desktop/src/stores/slices/work-panel-slice.ts +++ b/apps/desktop/src/stores/slices/work-panel-slice.ts @@ -5,7 +5,9 @@ import { closeWorkPanelTabState, emptyWorkPanelContext, fileWorkPanelTab, + isDocxFilePath, newWorkPanelTab, + officePluginTab, openWorkPanelTabState, replaceWorkPanelTabState, sanitizeWorkPanelTabsState, @@ -357,7 +359,15 @@ export function createWorkPanelSlice({ }, openFileInWorkPanel: (path, mimeType) => { - get().openWorkPanelTab(fileWorkPanelTab(path, mimeType)); + const state = get(); + const hasOfficeView = state.pluginViews.some( + (view) => view.pluginId === "pi.office" && view.viewId === "editor", + ); + if (hasOfficeView && isDocxFilePath(path)) { + state.openWorkPanelTab(officePluginTab(path)); + return; + } + state.openWorkPanelTab(fileWorkPanelTab(path, mimeType)); }, openUrlInWorkPanel: (url) => { const hasBrowser = get().pluginViews.some( diff --git a/apps/desktop/src/styles/model-config.css b/apps/desktop/src/styles/model-config.css index 0f16dd36c8..155a9b5787 100644 --- a/apps/desktop/src/styles/model-config.css +++ b/apps/desktop/src/styles/model-config.css @@ -1624,7 +1624,7 @@ flex: none; } - to the plugin, so the user supplies only the key. */ +/* Key entry shown when a provider delegates credential storage to a plugin. */ .model-provider-key-entry { display: flex; align-items: flex-end; diff --git a/apps/desktop/test/office-plugin.test.mjs b/apps/desktop/test/office-plugin.test.mjs new file mode 100644 index 0000000000..8eb19d39ee --- /dev/null +++ b/apps/desktop/test/office-plugin.test.mjs @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import test from "node:test"; + +const root = "resources/plugins/pi.office"; +const read = (file) => readFileSync(`${root}/${file}`, "utf8"); + +const manifest = JSON.parse(read("manifest.json")); +const view = read("views/index.html"); +const bridge = read("views/bridge-shim.js"); +const main = read("main.js"); +const editorBundle = read("views/assets/index-CiXp5RFk.js"); + +test("bundled Office is a browser-only DOCX plugin without chat selection UI", () => { + assert.equal(manifest.id, "pi.office"); + assert.deepEqual(manifest.permissions, ["ui.view"]); + assert.equal(manifest.net, undefined); + assert.match(view, /connect-src 'none'/); + assert.match(view, /bridge-shim\.js/); + assert.match(view, /office-toolbar-navigation\.js/); + assert.doesNotMatch(view, /selection-actions\.js/); + assert.doesNotMatch(view, /require\(|ipcRenderer/); + assert.doesNotMatch(bridge, /composer\.addSelection|composer\.appendDraft/); + assert.doesNotMatch(bridge, /require\(|ipcRenderer/); + assert.match(main, /office\.read/); + assert.match(main, /office\.save/); + assert.match(main, /office\.checkConflict/); + assert.match(main, /atomicWrite/); +}); + +test("bundled Office keeps its generated editor assets and attribution", () => { + assert.equal(existsSync(`${root}/views/assets/index-CiXp5RFk.js`), true); + assert.equal(existsSync(`${root}/views/assets/index-JQsJMU5H.css`), true); + assert.equal(existsSync(`${root}/FONTS-README.md`), true); + assert.equal(existsSync(`${root}/LICENSE-OFL.txt`), true); + assert.equal(existsSync(`${root}/LICENSE-UNICODE.txt`), true); +}); + +test("bundled Office allows zooming down to 25 percent", () => { + assert.match(editorBundle, /Math\.max\(25/); + assert.match(editorBundle, /min:25,max:200/); + assert.doesNotMatch(editorBundle, /min:50,max:200/); +}); diff --git a/apps/desktop/test/work-panel-tabs.test.mjs b/apps/desktop/test/work-panel-tabs.test.mjs index a2313d920c..519a7bb24d 100644 --- a/apps/desktop/test/work-panel-tabs.test.mjs +++ b/apps/desktop/test/work-panel-tabs.test.mjs @@ -3,6 +3,7 @@ import test from "node:test"; const { FILE_MANAGER_PLUGIN_TAB, + OFFICE_PLUGIN_TAB, activateWorkPanelTabState, browserPluginTab, closeWorkPanelTabState, @@ -10,10 +11,12 @@ const { fileWorkPanelTab, hasPluginView, isKnownWorkPanelTab, + isDocxFilePath, isToolWorkPanelTab, normalizeWorkPanelFilePath, newWorkPanelTab, openWorkPanelTabState, + officePluginTab, pluginWorkPanelTab, preferredFileWorkPanelTab, replaceWorkPanelTabState, @@ -166,6 +169,16 @@ test("a host-chosen project file prefers the bundled file view", () => { ); }); +test("DOCX files prefer the bundled Office view when available", () => { + assert.equal(isDocxFilePath("docs/contract.DOCX"), true); + assert.equal(isDocxFilePath("docs/contract.doc"), false); + const officeView = [OFFICE_PLUGIN_TAB]; + const tab = officePluginTab("docs/contract.docx"); + assert.equal(hasPluginView(officeView, OFFICE_PLUGIN_TAB), true); + assert.equal(tab.id, "plugin:pi.office/editor"); + assert.equal(tab.location, "docs/contract.docx"); +}); + test("empty work panel context has no visible or retained resource state", () => { assert.deepEqual(emptyWorkPanelContext(), { open: false, diff --git a/docs/adr/0283-office-docx-plugin.md b/docs/adr/0283-office-docx-plugin.md new file mode 100644 index 0000000000..cec9d3f6cc --- /dev/null +++ b/docs/adr/0283-office-docx-plugin.md @@ -0,0 +1,25 @@ +# ADR 0283: Ship the DOCX editor as a bundled plugin + +## Context + +DOCX editing needs a substantial browser renderer, but the host should retain +ownership of work-panel routing, plugin lifecycle, and file safety. + +## Decision + +Ship the renderer as the bundled `pi.office` plugin. Keep file reads, saves, +conflict checks, recovery copies, and path validation in the plugin process +behind the public plugin bridge. Route DOCX references through the existing +work-panel plugin-view mechanism. + +The first migration slice deliberately omits selection-to-chat and annotation +integration so Office editing can land without changing the Composer contract. + +## Consequences + +The editor remains isolated from Electron and network access, and non-DOCX +file behavior is unchanged. The application carries the generated editor +bundle and fonts, and the host must provide the `ui.openWorkPanelFile` bridge +and DOCX work-panel routing. The editor exposes 25%–200% zoom, and the host +re-attaches the native view only after plugin view creation completes so hot +reloads do not strand a stale surface over the work panel. diff --git a/docs/spec/03-runtime/15-workspace-ignore-rules.md b/docs/spec/03-runtime/15-workspace-ignore-rules.md index 97d40e63ce..b39cf78dc8 100644 --- a/docs/spec/03-runtime/15-workspace-ignore-rules.md +++ b/docs/spec/03-runtime/15-workspace-ignore-rules.md @@ -47,7 +47,7 @@ outside-path grant does not lift the denial. `Bash` is not filtered (§6). ## 4. Default ignore (app) -```gitignore +```text .git/ node_modules/ dist/ diff --git a/docs/spec/07-plugins/17-office-docx-plugin.md b/docs/spec/07-plugins/17-office-docx-plugin.md new file mode 100644 index 0000000000..1a392c97f1 --- /dev/null +++ b/docs/spec/07-plugins/17-office-docx-plugin.md @@ -0,0 +1,32 @@ +# Office DOCX plugin + +> Status: Accepted for the first migrated slice + +PI-Desktop ships a bundled `pi.office` plugin for opening, previewing, and +editing existing `.docx` files in the work panel. The editor is a browser +renderer extracted from the pinned GenOffice release recorded in the plugin's +`UPSTREAM.md`. + +The host owns file-reference completion and work-panel tabs. The plugin owns +DOCX parsing, rendering, editing, serialization, and file bytes. DOCX files +opened from the project file manager or chat are routed to `pi.office` when +the view is available; other file types keep their existing routes. + +The file lifecycle is bounded and optimistic: reads return a fingerprint, +saves reject unexpected mtime/size/hash changes unless the user explicitly +confirms an overwrite, and writes use a same-directory temporary file with +fsync followed by replacement. Recovery copies stay under the plugin data +directory. Non-DOCX files, credential-like paths, paths outside the workspace, +directories, and files over 64 MiB are rejected. + +The renderer has no Node or Electron access and the view CSP blocks network +connections. This migration intentionally excludes selection-to-chat actions, +comments, Composer annotations, and paragraph-anchor protocols. It also does +not include new-document creation, Save As, native Microsoft Office/COM, +GenOffice AI, accounts, remote services, or MCP integrations. + +The editor zoom range is 25%–200%. Opening a document keeps the editor's +normal zoom behavior; the user can use the page-width and whole-page commands +when an explicit fit mode is wanted. Rebuilding or reloading the plugin view +re-attaches the native work-panel surface after the view has been recreated so +the surrounding work-panel controls remain interactive. diff --git a/docs/zh-CN/spec/03-runtime/15-workspace-ignore-rules.md b/docs/zh-CN/spec/03-runtime/15-workspace-ignore-rules.md index 776a4e7305..479aeaf3ae 100644 --- a/docs/zh-CN/spec/03-runtime/15-workspace-ignore-rules.md +++ b/docs/zh-CN/spec/03-runtime/15-workspace-ignore-rules.md @@ -45,7 +45,7 @@ Goal/scanning/reading/writing/MVP/`.pi-desktopignore`/`~/.pi-desktop/ignore` 路 ## 4. 默认忽略(应用程序) -```gitignore +```text .git/ node_modules/ dist/ diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 33016d9fa9..1df23afe78 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -1016,6 +1016,8 @@ export type PluginHostApi = { ui: { openPanel: (opts?: { title?: string }) => Promise; closePanel: () => Promise; + /** Open a file in the host work panel, using the host's file-type routing. */ + openWorkPanelFile: (input: { path: string; mimeType?: string }) => Promise; showToast: (message: string, level?: "info" | "warn" | "error") => Promise; notify: (input: { title: string; body?: string }) => Promise; getNotificationPermission: () => Promise; diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index c1374ed4d1..f58d21b00b 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -308,6 +308,7 @@ export const IPC = { }, event: { pluginChanged: "pi-desktop/event/pluginChanged", + pluginOpenWorkPanelFile: "pi-desktop/plugin/event/openWorkPanelFile", /** Progress of an install or update, while it is still running. */ pluginInstallProgress: "pi-desktop/plugin/event/installProgress", /** Host-originated app settings mutation (e.g. plugin `app.setTheme`). */