From a76022bd2c491f7ec06a55f353296fe52943059b Mon Sep 17 00:00:00 2001 From: taekchef Date: Mon, 24 Aug 2026 04:49:48 +0800 Subject: [PATCH 1/8] =?UTF-8?q?fix:=20=E7=86=94=E6=96=AD=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E5=99=A8=E9=87=8D=E5=BB=BA=E5=B9=B6=E5=8D=8F=E8=B0=83=E7=AC=94?= =?UTF-8?q?=E8=AE=B0=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../WorkspaceStore+NotesPersistence.swift | 43 +++++++++++------ Sources/WeiBei/Views/NotesAgentView.swift | 46 ++++++++++++++++++- .../WeiBei/Views/RichMarkdownEditorView.swift | 4 ++ .../NoteEditingSessionTests.swift | 10 ++++ .../WriteGateSafetyTests.swift | 22 ++++++++- 5 files changed, 109 insertions(+), 16 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift index a1f00a6ba..e147b6e8a 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift @@ -654,21 +654,38 @@ extension WorkspaceStore { url: URL, expectedBaseline: String? ) throws { - if FileManager.default.fileExists(atPath: url.path) { - guard let expectedBaseline, - let diskDigest = Self.noteContentDigest(at: url) else { - throw NoteWriteGateError.writeRefusedKeepContent - } - if diskDigest != expectedBaseline { - _ = try? NoteBackupRing.capture( - content: Data(markdown.utf8), - itemID: itemID, - rootURL: noteBackupRootURL - ) - throw NoteWriteGateError.diskChangedAdoptDisk + var coordinationError: NSError? + var writeResult: Result? + NSFileCoordinator(filePresenter: nil).coordinate( + writingItemAt: url, + options: .forReplacing, + error: &coordinationError + ) { coordinatedURL in + writeResult = Result { + if FileManager.default.fileExists(atPath: coordinatedURL.path) { + guard let expectedBaseline, + let diskDigest = Self.noteContentDigest(at: coordinatedURL) else { + throw NoteWriteGateError.writeRefusedKeepContent + } + if diskDigest != expectedBaseline { + _ = try? NoteBackupRing.capture( + content: Data(markdown.utf8), + itemID: itemID, + rootURL: noteBackupRootURL + ) + throw NoteWriteGateError.diskChangedAdoptDisk + } + } + try notebookMarkdownWriter(markdown, coordinatedURL) } } - try notebookMarkdownWriter(markdown, url) + if let writeResult { + try writeResult.get() + } else if let coordinationError { + throw coordinationError + } else { + throw NoteWriteGateError.writeRefusedKeepContent + } let writtenDigest = Self.noteContentDigest(Data(markdown.utf8)) noteBackingContentDigestsByItemID[itemID] = writtenDigest lastSelfWrittenNoteDigestsByItemID[itemID] = writtenDigest diff --git a/Sources/WeiBei/Views/NotesAgentView.swift b/Sources/WeiBei/Views/NotesAgentView.swift index 42cb260a4..b6c238e01 100644 --- a/Sources/WeiBei/Views/NotesAgentView.swift +++ b/Sources/WeiBei/Views/NotesAgentView.swift @@ -397,6 +397,8 @@ struct NotePaneView: View { @State private var noteTabTitleDraft = "" @State private var editingNoteTabTitle = false @State private var editorRecoveryGeneration = 0 + @State private var editorRecoveryFailureDates: [Date] = [] + @State private var editorRecoveryStopped = false @State private var noteOutline: [NoteEditorOutlineItem] = [] @State private var activeNoteRailID: String? var showsPaneHeader = true @@ -475,6 +477,8 @@ struct NotePaneView: View { } .onChange(of: store.activeNoteItemID) { _, _ in editingNoteTabTitle = false + editorRecoveryFailureDates = [] + editorRecoveryStopped = false noteOutline = [] activeNoteRailID = nil } @@ -638,11 +642,34 @@ struct NotePaneView: View { .accessibilityLabel(Text(store.ui("正在载入笔记", "Loading note"))) } else { // 笔记固定为所见即所得(rich)写作,源码 / 对照模式入口已全部移除。 - richEditor + if editorRecoveryStopped { + editorRecoveryFailure + } else { + richEditor + } } } } + private var editorRecoveryFailure: some View { + VStack(spacing: 12) { + Text(store.ui( + "编辑器连续恢复失败,已停止自动重建。恢复草稿仍保留,可手动重试。", + "The editor repeatedly failed to recover, so automatic rebuilding stopped. The recovery draft is preserved; retry manually." + )) + .weiBeiText(13, weight: .medium) + .foregroundStyle(WeiBeiTheme.ink) + .multilineTextAlignment(.center) + Button(store.ui("重试编辑器", "Retry Editor")) { + editorRecoveryStopped = false + editorRecoveryGeneration &+= 1 + } + .buttonStyle(.bordered) + } + .padding(24) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + private var noteRailItems: [ContentRailItem] { noteOutline.map { heading in return ContentRailItem( @@ -716,8 +743,14 @@ struct NotePaneView: View { return store.handleAppShortcut(key: key, modifiers: modifiers) }, onRenderFailure: { store.noteEditingSession.invalidateBridgeGeneration() - editorRecoveryGeneration &+= 1 Task { await store.reconcileActiveNoteEditorWithBackingFile() } + if shouldAutomaticallyRecoverEditor( + failureDates: &editorRecoveryFailureDates + ) { + editorRecoveryGeneration &+= 1 + } else { + editorRecoveryStopped = true + } }) .id("\(store.activeNoteEditorDocumentID):\(editorRecoveryGeneration)") .background(WeiBeiTheme.paper) @@ -725,6 +758,15 @@ struct NotePaneView: View { } +func shouldAutomaticallyRecoverEditor( + failureDates: inout [Date], + now: Date = Date() +) -> Bool { + failureDates.removeAll { now.timeIntervalSince($0) >= 60 } + failureDates.append(now) + return failureDates.count <= 2 +} + private struct NotebookCreationPanel: View { @EnvironmentObject private var store: WorkspaceStore var draft: NotebookCreationDraft diff --git a/Sources/WeiBei/Views/RichMarkdownEditorView.swift b/Sources/WeiBei/Views/RichMarkdownEditorView.swift index 6dca02bb8..17b2681c2 100644 --- a/Sources/WeiBei/Views/RichMarkdownEditorView.swift +++ b/Sources/WeiBei/Views/RichMarkdownEditorView.swift @@ -1105,6 +1105,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { private var lastAppliedSelectionAskMarks = "" private var lastAppliedSelectionRemarkMarks = "" private var finalizedRenderGeneration = 0 + private var hasReportedRenderFailure = false init( documentID: String, @@ -1304,6 +1305,8 @@ struct RichMarkdownEditorView: NSViewRepresentable { } fileprivate func reportRenderFailure() { + guard !hasReportedRenderFailure else { return } + hasReportedRenderFailure = true // A failure can race the finalized JavaScript evaluation. Invalidate // that completion before exposing the native fallback so a broken // WebView cannot become ready again. @@ -1322,6 +1325,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { } switch message.name { case "editorReady": + hasReportedRenderFailure = false isReady = true bindEditingSession() setMarkdownBaseURL(markdownBaseURLString) diff --git a/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift b/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift index 2d9a9977e..6efd98448 100644 --- a/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift +++ b/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift @@ -2,6 +2,16 @@ import XCTest @testable import WeiBei final class NoteEditingSessionTests: XCTestCase { + func testEditorRecoveryLimitsTwoRetriesPerMinute() { + var failures: [Date] = [] + let start = Date(timeIntervalSince1970: 0) + + XCTAssertTrue(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start)) + XCTAssertTrue(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start.addingTimeInterval(10))) + XCTAssertFalse(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start.addingTimeInterval(20))) + XCTAssertTrue(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start.addingTimeInterval(81))) + } + @MainActor func testRejectsSnapshotFromStaleDocumentGeneration() throws { var commands: [NoteEditorSnapshotRequest] = [] diff --git a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift index f1161edae..c5663c12d 100644 --- a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift @@ -3,6 +3,24 @@ import Foundation import WeiBeiCore import XCTest +private final class CompetingNoteFilePresenter: NSObject, NSFilePresenter { + let presentedItemURL: URL? + let presentedItemOperationQueue = OperationQueue() + private let markdown: String + + init(url: URL, markdown: String) { + presentedItemURL = url + self.markdown = markdown + } + + func relinquishPresentedItem(toWriter writer: @escaping ((() -> Void)?) -> Void) { + if let presentedItemURL { + try? markdown.write(to: presentedItemURL, atomically: true, encoding: .utf8) + } + writer(nil) + } +} + /// 阶段1 写闸门专项验证(计划 §5 阶段1 第4步)。 @MainActor final class WriteGateSafetyTests: XCTestCase { @@ -108,7 +126,9 @@ final class WriteGateSafetyTests: XCTestCase { let (item, url) = try importNote(store, base: base, courseID: courseID, content: "基线内容") store.noteBackingContentDigestsByItemID[item.id] = Self.digest(of: "基线内容") - try "外部修改".write(to: url, atomically: true, encoding: .utf8) + let presenter = CompetingNoteFilePresenter(url: url, markdown: "外部修改") + NSFileCoordinator.addFilePresenter(presenter) + defer { NSFileCoordinator.removeFilePresenter(presenter) } let pendingInput = "用户未落盘的编辑" store.scheduleNotePersistence(pendingInput, for: item) From c570a7fbafe4ca0b071f3b2f3894a7f60a442db5 Mon Sep 17 00:00:00 2001 From: taekchef Date: Mon, 24 Aug 2026 05:21:50 +0800 Subject: [PATCH 2/8] =?UTF-8?q?fix:=20=E6=94=B6=E6=95=9B=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E5=99=A8=E6=81=A2=E5=A4=8D=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Views/NotesAgentView.swift | 52 ++++++++++++------- .../NoteEditingSessionTests.swift | 25 ++++++--- 2 files changed, 50 insertions(+), 27 deletions(-) diff --git a/Sources/WeiBei/Views/NotesAgentView.swift b/Sources/WeiBei/Views/NotesAgentView.swift index b6c238e01..62bcf0025 100644 --- a/Sources/WeiBei/Views/NotesAgentView.swift +++ b/Sources/WeiBei/Views/NotesAgentView.swift @@ -397,8 +397,7 @@ struct NotePaneView: View { @State private var noteTabTitleDraft = "" @State private var editingNoteTabTitle = false @State private var editorRecoveryGeneration = 0 - @State private var editorRecoveryFailureDates: [Date] = [] - @State private var editorRecoveryStopped = false + @State private var editorRecoveryState = EditorRecoveryState.idle @State private var noteOutline: [NoteEditorOutlineItem] = [] @State private var activeNoteRailID: String? var showsPaneHeader = true @@ -477,8 +476,7 @@ struct NotePaneView: View { } .onChange(of: store.activeNoteItemID) { _, _ in editingNoteTabTitle = false - editorRecoveryFailureDates = [] - editorRecoveryStopped = false + editorRecoveryState = .idle noteOutline = [] activeNoteRailID = nil } @@ -642,7 +640,7 @@ struct NotePaneView: View { .accessibilityLabel(Text(store.ui("正在载入笔记", "Loading note"))) } else { // 笔记固定为所见即所得(rich)写作,源码 / 对照模式入口已全部移除。 - if editorRecoveryStopped { + if editorRecoveryState == .stopped { editorRecoveryFailure } else { richEditor @@ -661,7 +659,7 @@ struct NotePaneView: View { .foregroundStyle(WeiBeiTheme.ink) .multilineTextAlignment(.center) Button(store.ui("重试编辑器", "Retry Editor")) { - editorRecoveryStopped = false + editorRecoveryState.retryManually() editorRecoveryGeneration &+= 1 } .buttonStyle(.bordered) @@ -705,7 +703,8 @@ struct NotePaneView: View { } private var richEditor: some View { - RichMarkdownEditorView(documentID: store.activeNoteEditorDocumentID, markdown: store.noteText, command: Binding(get: { + let recoveryGeneration = editorRecoveryGeneration + return RichMarkdownEditorView(documentID: store.activeNoteEditorDocumentID, markdown: store.noteText, command: Binding(get: { store.noteEditorCommand }, set: { value in store.noteEditorCommand = value @@ -741,15 +740,15 @@ struct NotePaneView: View { store.noteEditingSession.requestSnapshot() } return store.handleAppShortcut(key: key, modifiers: modifiers) + }, onRenderReady: { + guard recoveryGeneration == editorRecoveryGeneration else { return } + editorRecoveryState.renderBecameReady() }, onRenderFailure: { + guard recoveryGeneration == editorRecoveryGeneration else { return } store.noteEditingSession.invalidateBridgeGeneration() Task { await store.reconcileActiveNoteEditorWithBackingFile() } - if shouldAutomaticallyRecoverEditor( - failureDates: &editorRecoveryFailureDates - ) { + if editorRecoveryState.renderFailed() { editorRecoveryGeneration &+= 1 - } else { - editorRecoveryStopped = true } }) .id("\(store.activeNoteEditorDocumentID):\(editorRecoveryGeneration)") @@ -758,13 +757,28 @@ struct NotePaneView: View { } -func shouldAutomaticallyRecoverEditor( - failureDates: inout [Date], - now: Date = Date() -) -> Bool { - failureDates.removeAll { now.timeIntervalSince($0) >= 60 } - failureDates.append(now) - return failureDates.count <= 2 +enum EditorRecoveryState: Equatable { + case idle + case rebuilding + case stopped + + mutating func renderFailed() -> Bool { + guard self == .idle else { + self = .stopped + return false + } + self = .rebuilding + return true + } + + mutating func renderBecameReady() { + guard self != .stopped else { return } + self = .idle + } + + mutating func retryManually() { + self = .idle + } } private struct NotebookCreationPanel: View { diff --git a/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift b/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift index 6efd98448..b3c17651a 100644 --- a/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift +++ b/Tests/WeiBeiSafetyTests/NoteEditingSessionTests.swift @@ -2,14 +2,23 @@ import XCTest @testable import WeiBei final class NoteEditingSessionTests: XCTestCase { - func testEditorRecoveryLimitsTwoRetriesPerMinute() { - var failures: [Date] = [] - let start = Date(timeIntervalSince1970: 0) - - XCTAssertTrue(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start)) - XCTAssertTrue(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start.addingTimeInterval(10))) - XCTAssertFalse(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start.addingTimeInterval(20))) - XCTAssertTrue(shouldAutomaticallyRecoverEditor(failureDates: &failures, now: start.addingTimeInterval(81))) + func testEditorRecoveryStopsUntilManualRetryStartsANewRound() { + var state = EditorRecoveryState.idle + + XCTAssertTrue(state.renderFailed()) + XCTAssertEqual(state, .rebuilding) + XCTAssertFalse(state.renderFailed()) + XCTAssertEqual(state, .stopped) + + state.renderBecameReady() + XCTAssertEqual(state, .stopped) + + state.retryManually() + XCTAssertEqual(state, .idle) + state.renderBecameReady() + XCTAssertEqual(state, .idle) + XCTAssertTrue(state.renderFailed()) + XCTAssertEqual(state, .rebuilding) } @MainActor From a15c3cb5cd896abe8e68741f45d6a25521f843e0 Mon Sep 17 00:00:00 2001 From: taekchef Date: Mon, 24 Aug 2026 06:10:16 +0800 Subject: [PATCH 3/8] =?UTF-8?q?fix:=20=E4=BF=9D=E5=AD=98=E8=84=8F=E7=AC=94?= =?UTF-8?q?=E8=AE=B0=E5=90=8E=E5=86=8D=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 271 ++++++++++++++---- Sources/WeiBei/Views/ContentView.swift | 29 +- Sources/WeiBei/Views/NotesAgentView.swift | 2 - .../ImportedIdentitySelfCheck.swift | 101 +++++++ 4 files changed, 336 insertions(+), 67 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 19a6cd48c..3866564b7 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -584,6 +584,8 @@ final class WorkspaceStore: ObservableObject { @Published var noteEditorCommand: NoteEditorCommand? /// Success / info banner for note create/switch — separate from errors so it auto-dismisses cleanly. @Published var transientNoteStatus: String? + @Published private var noteSelectionTransitionState = NoteSelectionTransitionState.idle + private var pendingNoteSelection: PendingNoteSelection? /// Serious data-operation failures (note read/write/rename/restore/identity, /// security scope, course file move & rollback). Never auto-dismisses — only a /// user close or a newer important error replaces it. @@ -784,6 +786,16 @@ final class WorkspaceStore: ObservableObject { var threePaneOrder: [WorkspacePaneRole] } + private enum NoteSelectionTransitionState: Equatable { + case idle + case saving + case failed(NoteEditingSessionError) + } + + private struct PendingNoteSelection { + let apply: () -> Void + } + private enum NotebookNoteSeed { case blank case currentMaterial(StudyItem) @@ -8401,9 +8413,11 @@ final class WorkspaceStore: ObservableObject { } else if linked.isEmpty { beginBlankNoteDraft(for: material.id) } else { - blankNoteDraftMaterialID = nil - activeNotebookItemID = nil - noteText = "" + requestNoteSelectionTransition(to: nil) { [weak self] in + self?.blankNoteDraftMaterialID = nil + self?.activeNotebookItemID = nil + self?.noteText = "" + } } } @@ -8432,14 +8446,16 @@ final class WorkspaceStore: ObservableObject { private func beginBlankNoteDraft(for materialID: String) { guard item(withID: materialID)?.isNotebookNote == false else { return } - persistCurrentNote() - blankNoteMaterializationTask?.cancel() - blankNoteMaterializationTask = nil - blankNoteDraftMaterialID = materialID - pendingBlankNoteText = "" - activeNotebookItemID = nil - noteText = "" - focus(.notes) + requestNoteSelectionTransition(to: "draft:\(materialID)") { [weak self] in + guard let self else { return } + blankNoteMaterializationTask?.cancel() + blankNoteMaterializationTask = nil + blankNoteDraftMaterialID = materialID + pendingBlankNoteText = "" + activeNotebookItemID = nil + noteText = "" + focus(.notes) + } } var filteredItems: [StudyItem] { @@ -9753,17 +9769,21 @@ final class WorkspaceStore: ObservableObject { } func navigateBackInWorkspace() { - guard let previous = backNavigationStack.popLast() else { return } - persistCurrentNote() - forwardNavigationStack.append(navigationSnapshot()) - applyNavigationSnapshot(previous) + guard let target = backNavigationStack.last else { return } + requestNoteSelectionTransition(to: target.activeNotebookItemID) { [weak self] in + guard let self, let previous = backNavigationStack.popLast() else { return } + forwardNavigationStack.append(navigationSnapshot()) + applyNavigationSnapshot(previous) + } } func navigateForwardInWorkspace() { - guard let next = forwardNavigationStack.popLast() else { return } - persistCurrentNote() - backNavigationStack.append(navigationSnapshot()) - applyNavigationSnapshot(next) + guard let target = forwardNavigationStack.last else { return } + requestNoteSelectionTransition(to: target.activeNotebookItemID) { [weak self] in + guard let self, let next = forwardNavigationStack.popLast() else { return } + backNavigationStack.append(navigationSnapshot()) + applyNavigationSnapshot(next) + } } var canUseSelectedMarkdownAsNotebookNote: Bool { @@ -10158,10 +10178,126 @@ final class WorkspaceStore: ObservableObject { func select(itemID: String?) { WeiBeiPerf.measure("workspace.select") { - selectMeasured(itemID: itemID, opensNotebook: nil) + guard let itemID, + allItems.contains(where: { $0.id == itemID && $0.isNotebookNote }) else { + selectMeasured(itemID: itemID, opensNotebook: nil) + return + } + requestNoteSelectionTransition(to: itemID) { [weak self] in + self?.selectMeasured(itemID: itemID, opensNotebook: nil) + } + } + } + + var noteSelectionStatusMessage: String? { + switch noteSelectionTransitionState { + case .idle: + nil + case .saving: + ui("正在保存当前笔记…", "Saving the current note…") + case .failed(.snapshotTimedOut): + ui( + "当前正文仍在当前页面,尚未确认保存。请重试后再切换。", + "The current text remains on this page, but its save is not confirmed. Retry before switching." + ) + case .failed(.bridgeUnavailable): + ui( + "最近的持久恢复点仍在,但最后一段编辑无法确认。请重试编辑器连接后再切换。", + "The latest durable recovery point remains, but the final edits could not be confirmed. Retry the editor connection before switching." + ) + case .failed(.documentChanged): + ui( + "保存过程中当前笔记发生了变化,魏碑没有切换。请重试。", + "The current note changed while saving, so WeiBei did not switch. Please retry." + ) + } + } + + var canRetryPendingNoteSelection: Bool { + if case .failed = noteSelectionTransitionState { + return pendingNoteSelection != nil + } + return false + } + + func retryPendingNoteSelection() { + guard pendingNoteSelection != nil else { return } + requestPendingNoteSelectionSnapshot() + } + + private func requestNoteSelectionTransition( + to documentID: String?, + apply: @escaping () -> Void + ) { + guard noteEditingSession.dirty, + noteEditingSession.documentID != documentID else { + pendingNoteSelection = nil + noteSelectionTransitionState = .idle + apply() + return + } + + pendingNoteSelection = PendingNoteSelection(apply: apply) + guard noteSelectionTransitionState != .saving else { return } + requestPendingNoteSelectionSnapshot() + } + + private func requestPendingNoteSelectionSnapshot() { + guard pendingNoteSelection != nil else { return } + noteSelectionTransitionState = .saving + let sourceDocumentID = noteEditingSession.documentID + _ = noteEditingSession.requestSnapshot { [weak self] result in + self?.finishPendingNoteSelectionSnapshot( + result, + sourceDocumentID: sourceDocumentID + ) + } + } + + private func finishPendingNoteSelectionSnapshot( + _ result: Result, + sourceDocumentID: String + ) { + guard pendingNoteSelection != nil else { + noteSelectionTransitionState = .idle + return + } + switch result { + case .success(let snapshot): + guard snapshot.documentID == sourceDocumentID, + noteEditingSession.documentID == sourceDocumentID else { + failPendingNoteSelection(.documentChanged) + return + } + if snapshot.revision < noteEditingSession.currentRevision { + requestPendingNoteSelectionSnapshot() + return + } + let digest = Self.noteContentDigest(Data(snapshot.markdown.utf8)) + guard let accepted = latestNoteEditorSnapshot, + accepted.documentID == snapshot.documentID, + accepted.revision == snapshot.revision, + accepted.digest == digest else { + failPendingNoteSelection(.documentChanged) + return + } + let apply = pendingNoteSelection?.apply + pendingNoteSelection = nil + noteSelectionTransitionState = .idle + persistCurrentNote() + apply?() + case .failure(let error): + failPendingNoteSelection(error) } } + private func failPendingNoteSelection(_ error: NoteEditingSessionError) { + WeiBeiLog.noteRepair.error( + "note selection snapshot failed: \(String(describing: error), privacy: .private)" + ) + noteSelectionTransitionState = .failed(error) + } + func selectMeasured(itemID: String?, opensNotebook: Bool?) { invalidateAgentContext() persistCurrentNote() @@ -10978,16 +11114,19 @@ final class WorkspaceStore: ObservableObject { conflictResolution: conflictResolution ) if revealInWorkspace { - activeNotebookItemID = result.item.id - noteText = markdown - revealRichWritingSurface() - focus(.notes) - showTransientNoteStatus( - ui( - "已在课程“笔记”目录新建:\(result.item.subtitle)", - "Created in the course Notes folder: \(result.item.subtitle)" + requestNoteSelectionTransition(to: result.item.id) { [weak self] in + guard let self else { return } + activeNotebookItemID = result.item.id + noteText = markdown + revealRichWritingSurface() + focus(.notes) + showTransientNoteStatus( + ui( + "已在课程“笔记”目录新建:\(result.item.subtitle)", + "Created in the course Notes folder: \(result.item.subtitle)" + ) ) - ) + } } return result.item.id } catch { @@ -11212,21 +11351,23 @@ final class WorkspaceStore: ObservableObject { openDocumentPane(.notes) return } - persistCurrentNote() - blankNoteMaterializationTask?.cancel() - blankNoteMaterializationTask = nil - pendingBlankNoteText = "" - blankNoteDraftMaterialID = nil - activeNotebookItemID = nil - noteText = "" - notebookCreationDraft = nil - notebookRenameDraft = nil - linkedSourcesPresented = false - latestAgentNoteProposal = nil - latestAgentLearningUpdate = nil - syncActiveStudySession() - openDocumentPane(.notes) - save() + requestNoteSelectionTransition(to: nil) { [weak self] in + guard let self else { return } + blankNoteMaterializationTask?.cancel() + blankNoteMaterializationTask = nil + pendingBlankNoteText = "" + blankNoteDraftMaterialID = nil + activeNotebookItemID = nil + noteText = "" + notebookCreationDraft = nil + notebookRenameDraft = nil + linkedSourcesPresented = false + latestAgentNoteProposal = nil + latestAgentLearningUpdate = nil + syncActiveStudySession() + openDocumentPane(.notes) + save() + } } } @@ -12769,7 +12910,6 @@ final class WorkspaceStore: ObservableObject { return nil } - persistCurrentNote() guard courseLibraryRootURL != nil else { showTransientNoteStatus(ui("请先选择魏碑资料库。", "Choose a WeiBei library first.")) return nil @@ -12833,15 +12973,18 @@ final class WorkspaceStore: ObservableObject { addNoteSourceLink(noteItemID: item.id, sourceItemID: sourceItem.id) } invalidateAgentContext() - activeNotebookItemID = item.id - noteText = markdown - revealRichWritingSurface() - focus(.notes) save() let status = sourceItem == nil ? ui("已新建空白笔记:\(url.lastPathComponent)", "Created blank note: \(url.lastPathComponent)") : ui("已为当前资料新建笔记:\(url.lastPathComponent)", "Created note from current material: \(url.lastPathComponent)") - showTransientNoteStatus(status) + requestNoteSelectionTransition(to: item.id) { [weak self] in + guard let self else { return } + activeNotebookItemID = item.id + noteText = markdown + revealRichWritingSurface() + focus(.notes) + showTransientNoteStatus(status) + } return item } catch { showImportantOperationError(ui("无法创建笔记:\(error.localizedDescription)", "Could not create note: \(error.localizedDescription)")) @@ -12861,19 +13004,23 @@ final class WorkspaceStore: ObservableObject { func useSelectedMarkdownAsNotebookNote() { guard let selectedItemID, let index = importedItems.firstIndex(where: { $0.id == selectedItemID && $0.canBecomeNotebookNote }) else { return } - invalidateAgentContext() - persistCurrentNote() - importedItems[index].isNotebookNote = true - removeLinksWhereSourceItemID(importedItems[index].id) - activeNotebookItemID = importedItems[index].id - if selectedItemID == importedItems[index].id { - self.selectedItemID = nil - readerLocationTitle = selectedMaterialItem.map(displayTitle) + let itemID = importedItems[index].id + requestNoteSelectionTransition(to: itemID) { [weak self] in + guard let self, + let index = importedItems.firstIndex(where: { $0.id == itemID }) else { return } + invalidateAgentContext() + importedItems[index].isNotebookNote = true + removeLinksWhereSourceItemID(itemID) + activeNotebookItemID = itemID + if selectedItemID == itemID { + self.selectedItemID = nil + readerLocationTitle = selectedMaterialItem.map(displayTitle) + } + noteText = noteText(for: importedItems[index]) + revealRichWritingSurface() + focus(.notes) + save() } - noteText = noteText(for: importedItems[index]) - revealRichWritingSurface() - focus(.notes) - save() } func copyCurrentReference() { diff --git a/Sources/WeiBei/Views/ContentView.swift b/Sources/WeiBei/Views/ContentView.swift index b41d9798d..c28dfca29 100644 --- a/Sources/WeiBei/Views/ContentView.swift +++ b/Sources/WeiBei/Views/ContentView.swift @@ -85,7 +85,10 @@ struct ContentView: View { // persistent save failures, otherwise the transient note status. // Sits above the course space so it stays visible wherever the // user is; the old notes-pane-local copy is gone. - if store.importantOperationError != nil || store.workspaceSaveError != nil || store.transientNoteStatus != nil { + if store.importantOperationError != nil + || store.workspaceSaveError != nil + || store.noteSelectionStatusMessage != nil + || store.transientNoteStatus != nil { WorkspaceStatusBanner() .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) .padding(.top, WeiBeiMetric.topBarHeight * textScale + 10) @@ -104,6 +107,7 @@ struct ContentView: View { } .animation(WeiBeiMotion.panel, value: store.importantOperationError) .animation(WeiBeiMotion.panel, value: store.workspaceSaveError) + .animation(WeiBeiMotion.panel, value: store.noteSelectionStatusMessage) .animation(WeiBeiMotion.panel, value: store.transientNoteStatus) .background { LibraryAwareEscapeBridge( @@ -386,12 +390,20 @@ private struct WorkspaceStatusBanner: View { !isImportant && store.workspaceSaveError != nil } + private var isNoteSelectionFailure: Bool { + !isImportant && !isSaveFailure && store.canRetryPendingNoteSelection + } + private var isAlert: Bool { - isImportant || isSaveFailure + isImportant || isSaveFailure || isNoteSelectionFailure } private var message: String { - store.importantOperationError ?? store.workspaceSaveError ?? store.transientNoteStatus ?? "" + store.importantOperationError + ?? store.workspaceSaveError + ?? store.noteSelectionStatusMessage + ?? store.transientNoteStatus + ?? "" } var body: some View { @@ -416,6 +428,17 @@ private struct WorkspaceStatusBanner: View { } .buttonStyle(.plain) .accessibilityLabel(Text(store.ui("重试保存", "Retry save"))) + } else if isNoteSelectionFailure { + Button { + store.retryPendingNoteSelection() + } label: { + Text(store.ui("重试", "Retry")) + .weiBeiText(12, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(Text(store.ui("重试保存并切换笔记", "Retry saving and switching notes"))) } else if isImportant { Button { store.dismissImportantOperationError() diff --git a/Sources/WeiBei/Views/NotesAgentView.swift b/Sources/WeiBei/Views/NotesAgentView.swift index 62bcf0025..b0f29976d 100644 --- a/Sources/WeiBei/Views/NotesAgentView.swift +++ b/Sources/WeiBei/Views/NotesAgentView.swift @@ -730,10 +730,8 @@ struct NotePaneView: View { }, onOutlineChange: { items in noteOutline = items }, onWikiLink: { title in - store.noteEditingSession.requestSnapshot() store.openOrCreateWikiNote(title: title) }, onSourceReference: { reference in - store.noteEditingSession.requestSnapshot() store.openSourceReference(reference) }, onAppShortcut: { key, modifiers in if modifiers.contains(.command) { diff --git a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift index bbb60f52d..60f16eb4e 100644 --- a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift @@ -8,6 +8,7 @@ enum ImportedIdentitySelfCheck { @MainActor static func run() throws { try launchAndPrimaryEntriesStartBlank() + try dirtyEditorSelectionWaitsForAcceptedSnapshot() try paneAndInteractionStateDoNotInvalidateWorkspaceStore() try agentFailureMessagesExposeOnlyUserFacingDetails() try storageModelsDecodeLegacySnapshotsAndRoundTrip() @@ -22,6 +23,106 @@ enum ImportedIdentitySelfCheck { try courseResumePointRestoresOneAtomicLearningScene() } + @MainActor + private static func dirtyEditorSelectionWaitsForAcceptedSnapshot() throws { + let fixture = try WorkspaceFixture(name: "dirty-editor-selection") + defer { fixture.remove() } + + let noteAURL = fixture.importsDirectory.appendingPathComponent("A笔记.md") + let noteBURL = fixture.importsDirectory.appendingPathComponent("B笔记.md") + let noteCURL = fixture.importsDirectory.appendingPathComponent("C笔记.md") + try Data("# A笔记\n\n旧正文".utf8).write(to: noteAURL) + try Data("# B笔记\n\n正文".utf8).write(to: noteBURL) + try Data("# C笔记\n\n正文".utf8).write(to: noteCURL) + + let store = WorkspaceStore( + workspaceDirectory: fixture.workspaceDirectory, + selectionAskThreadDefaults: fixture.selectionAskThreadDefaults + ) + _ = importFilesAndWait( + store, + [noteAURL, noteBURL, noteCURL], + selectsFirstImportedItem: false, + markdownNotePaths: [noteAURL.path, noteBURL.path, noteCURL.path] + ) + let noteA = try require( + store.courseNotebookItems.first { $0.urlPath == noteAURL.path }, + "脏编辑器切换场景找不到 A 笔记" + ) + let noteB = try require( + store.courseNotebookItems.first { $0.urlPath == noteBURL.path }, + "脏编辑器切换场景找不到 B 笔记" + ) + let noteC = try require( + store.courseNotebookItems.first { $0.urlPath == noteCURL.path }, + "脏编辑器切换场景找不到 C 笔记" + ) + + store.select(itemID: noteA.id) + store.noteEditingSession.replaceDocument(with: noteA.id) + var requests = [NoteEditorSnapshotRequest]() + var bridgeToken = store.noteEditingSession.bindSnapshotRequestHandler { + requests.append($0) + } + try check( + store.noteEditingSession.receive(NoteEditorDirtyChangedEvent( + documentID: noteA.id, + documentGeneration: store.noteEditingSession.documentGeneration, + revision: 1, + dirty: true + )), + "脏编辑器切换场景没有接收正文变化" + ) + + store.select(itemID: noteC.id) + store.select(itemID: noteB.id) + try check( + store.activeNoteItemID == noteA.id + && store.noteSelectionStatusMessage?.contains("正在保存") == true + && requests.count == 1, + "脏编辑器切换没有保持 A,或没有合并为一次真实快照" + ) + + store.noteEditingSession.unbindSnapshotRequestHandler(bridgeToken) + try check( + store.activeNoteItemID == noteA.id + && store.canRetryPendingNoteSelection + && store.noteSelectionStatusMessage?.contains("持久恢复点") == true, + "快照失败后离开了 A,或没有提供带恢复来源说明的重试" + ) + + requests.removeAll() + bridgeToken = store.noteEditingSession.bindSnapshotRequestHandler { + requests.append($0) + } + store.retryPendingNoteSelection() + let retry = try require(requests.first, "重试没有重新请求真实快照") + try check(store.activeNoteItemID == noteA.id, "重试快照送达前离开了 A") + let latestA = "# A笔记\n\n最后一段编辑" + try check( + store.noteEditingSession.receive(NoteEditorSnapshotReadyEvent( + requestID: retry.requestID ?? "", + documentID: retry.documentID, + documentGeneration: retry.documentGeneration, + revision: 1, + markdown: latestA + )), + "重试快照没有被编辑会话接收" + ) + try check( + store.activeNoteItemID == noteB.id, + "快照接收后没有只切到最后点击的 B" + ) + + store.select(itemID: noteA.id) + let reopenedDiskA = try String(contentsOf: noteAURL, encoding: .utf8) + try check( + store.noteText == latestA && reopenedDiskA == latestA, + "重开 A 后最新正文不完整" + ) + store.noteEditingSession.unbindSnapshotRequestHandler(bridgeToken) + } + @MainActor private static func agentFailureMessagesExposeOnlyUserFacingDetails() throws { let internalFailure = PiAgentRuntimeError.protocolFailure( From b25b03797e21fe8ec7e8eb68f52a5224f8c5415f Mon Sep 17 00:00:00 2001 From: taekchef Date: Mon, 24 Aug 2026 06:23:54 +0800 Subject: [PATCH 4/8] =?UTF-8?q?fix:=20=E7=AD=89=E5=BE=85=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E5=99=A8=E5=91=BD=E4=BB=A4=E5=9B=9E=E6=89=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Editing/NoteEditorBridge.swift | 9 ++ .../WeiBei/Resources/Editor/editor-entry.js | 96 ++++++------- .../Resources/Editor/editor-resources.json | 8 +- .../WeiBei/Resources/Editor/viewer-entry.js | 22 +-- Sources/WeiBei/Stores/WorkspaceStore.swift | 39 +++++ Sources/WeiBei/Views/ContentView.swift | 23 ++- Sources/WeiBei/Views/NotesAgentView.swift | 2 + .../WeiBei/Views/RichMarkdownEditorView.swift | 100 ++++++++++--- Sources/WeiBei/WebEditor/src/editor.ts | 75 +++++++--- .../RichMarkdownEditorBridgeTests.swift | 134 ++++++++++++++++++ 10 files changed, 404 insertions(+), 104 deletions(-) diff --git a/Sources/WeiBei/Editing/NoteEditorBridge.swift b/Sources/WeiBei/Editing/NoteEditorBridge.swift index 16ce95118..92a12bab4 100644 --- a/Sources/WeiBei/Editing/NoteEditorBridge.swift +++ b/Sources/WeiBei/Editing/NoteEditorBridge.swift @@ -130,6 +130,15 @@ struct NoteEditorSnapshotReadyEvent: Codable, Equatable, Sendable { } } +struct NoteEditorCommandResultEvent: Codable, Equatable, Sendable { + let protocolVersion: Int + let commandID: String + let documentID: String + let documentGeneration: UInt64 + let revision: UInt64 + let reason: String? +} + struct NoteEditorOutlineItem: Codable, Equatable, Identifiable, Sendable { let id: String let index: Int diff --git a/Sources/WeiBei/Resources/Editor/editor-entry.js b/Sources/WeiBei/Resources/Editor/editor-entry.js index ab7897621..34e53153d 100644 --- a/Sources/WeiBei/Resources/Editor/editor-entry.js +++ b/Sources/WeiBei/Resources/Editor/editor-entry.js @@ -1,96 +1,96 @@ -"use strict";(()=>{var z1=Object.create;var jl=Object.defineProperty;var _1=Object.getOwnPropertyDescriptor;var $1=Object.getOwnPropertyNames;var H1=Object.getPrototypeOf,W1=Object.prototype.hasOwnProperty;var j1=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},V1=(t,e)=>{for(var n in e)jl(t,n,{get:e[n],enumerable:!0})},q1=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $1(e))!W1.call(t,i)&&i!==n&&jl(t,i,{get:()=>e[i],enumerable:!(r=_1(e,i))||r.enumerable});return t};var K1=(t,e,n)=>(n=t!=null?z1(H1(t)):{},q1(e||!t||!t.__esModule?jl(n,"default",{value:t,enumerable:!0}):n,t));var Tm=j1((J$,Em)=>{"use strict";var oa=Object.prototype.hasOwnProperty,Mm=Object.prototype.toString,km=Object.defineProperty,bm=Object.getOwnPropertyDescriptor,xm=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Mm.call(e)==="[object Array]"},wm=function(e){if(!e||Mm.call(e)!=="[object Object]")return!1;var n=oa.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&oa.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var i;for(i in e);return typeof i>"u"||oa.call(e,i)},Cm=function(e,n){km&&n.name==="__proto__"?km(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Sm=function(e,n){if(n==="__proto__")if(oa.call(e,n)){if(bm)return bm(e,n).value}else return;return e[n]};Em.exports=function t(){var e,n,r,i,o,s,a=arguments[0],l=1,c=arguments.length,u=!1;for(typeof a=="boolean"&&(u=a,a=arguments[1]||{},l=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});ltypeof e=="function"?"[Function]":e,Fs=t=>JSON.stringify(t,U1);function rh(t){return new dt(ft.docTypeError,`Doc type error, unsupported type: ${Fs(t)}`)}function ih(t){return new dt(ft.contextNotFound,`Context "${t}" not found, do you forget to inject it?`)}function oh(t){return new dt(ft.timerNotFound,`Timer "${t}" not found, do you forget to record it?`)}function ni(){return new dt(ft.ctxCallOutOfScope,"Should not call a context out of the plugin.")}function sh(t,e,n){let r=`Cannot create node for ${"name"in t?t.name:t}`,i=s=>{if(s==null)return"null";if(Array.isArray(s))return`[${s.map(i).join(", ")}]`;if(typeof s=="object")return"toJSON"in s&&typeof s.toJSON=="function"?JSON.stringify(s.toJSON()):"spec"in s?JSON.stringify(s.spec):JSON.stringify(s);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return JSON.stringify(s);if(typeof s=="function")return`[Function: ${s.name||"anonymous"}]`;try{return String(s)}catch{return"[Unserializable]"}},o=[["[Description]",r],["[Attributes]",e],["[Content]",(n??[]).map(s=>s?typeof s=="object"&&"type"in s?`${s}`:i(s):"null")]].reduce((s,[a,l])=>{let c=`${a}: ${i(l)}.`;return s.concat(c)},[]);return new dt(ft.createNodeInParserFail,o.join(` -`))}function Vl(){return new dt(ft.stackOverFlow,"Stack over flow, cannot pop on an empty stack.")}function ah(t){return new dt(ft.parserMatchError,`Cannot match target parser for node: ${Fs(t)}.`)}function lh(t){return new dt(ft.serializerMatchError,`Cannot match target serializer for node: ${Fs(t)}.`)}function ch(t,e){return new dt(ft.getAtomFromSchemaFail,`Cannot get ${t}: ${e} from schema.`)}function pt(t){return new dt(ft.expectDomTypeError,`Expect to be a dom, but get: ${Fs(t)}.`)}function zs(){return new dt(ft.callCommandBeforeEditorView,"You're trying to call a command before editor view initialized, make sure to get commandManager from ctx after editor view has been initialized")}function _s(t){return new dt(ft.missingNodeInSchema,`Missing node in schema, milkdown cannot find "${t}" in schema.`)}function uh(t){return new dt(ft.missingMarkInSchema,`Missing mark in schema, milkdown cannot find "${t}" in schema.`)}var ql=class{constructor(){this.sliceMap=new Map,this.get=t=>{let e=typeof t=="string"?[...this.sliceMap.values()].find(n=>n.type.name===t):this.sliceMap.get(t.id);if(!e)throw ih(typeof t=="string"?t:t.name);return e},this.remove=t=>{let e=typeof t=="string"?[...this.sliceMap.values()].find(n=>n.type.name===t):this.sliceMap.get(t.id);e&&this.sliceMap.delete(e.type.id)},this.has=t=>typeof t=="string"?[...this.sliceMap.values()].some(e=>e.type.name===t):this.sliceMap.has(t.id)}},J1=class{#t;#e;#r;constructor(t,e,n){this.#t=[],this.#r=()=>{this.#t.forEach(r=>r(this.#e))},this.set=r=>{this.#e=r,this.#r()},this.get=()=>this.#e,this.update=r=>{this.#e=r(this.#e),this.#r()},this.type=n,this.#e=e,t.set(n.id,this)}on(t){return this.#t.push(t),()=>{this.#t=this.#t.filter(e=>e!==t)}}once(t){let e=this.on(n=>{t(n),e()});return e}off(t){this.#t=this.#t.filter(e=>e!==t)}offAll(){this.#t=[]}},G1=class{constructor(t,e){this.id=Symbol(`Context-${e}`),this.name=e,this._defaultValue=t,this._typeInfo=()=>{throw ni()}}create(t,e=this._defaultValue){return new J1(t,e,this)}},Y=(t,e)=>new G1(t,e),X1=class{#t;#e;#r;#n;#s;#o;#i;constructor(t,e,n){this.#n=new Set,this.#s=new Set,this.#o=new Map,this.#i=new Map,this.read=()=>({metadata:this.#t,injectedSlices:[...this.#n].map(r=>({name:typeof r=="string"?r:r.name,value:this.#a(r)})),consumedSlices:[...this.#s].map(r=>({name:typeof r=="string"?r:r.name,value:this.#a(r)})),recordedTimers:[...this.#o].map(([r,{duration:i}])=>({name:r.name,duration:i,status:this.#l(r)})),waitTimers:[...this.#i].map(([r,{duration:i}])=>({name:r.name,duration:i,status:this.#l(r)}))}),this.onRecord=r=>{this.#o.set(r,{start:Date.now(),duration:0})},this.onClear=r=>{this.#o.delete(r)},this.onDone=r=>{let i=this.#o.get(r);i&&(i.duration=Date.now()-i.start)},this.onWait=(r,i)=>{let o=Date.now();i.finally(()=>{this.#i.set(r,{duration:Date.now()-o})}).catch(console.error)},this.onInject=r=>{this.#n.add(r)},this.onRemove=r=>{this.#n.delete(r)},this.onUse=r=>{this.#s.add(r)},this.#a=r=>this.#e.get(r).get(),this.#l=r=>this.#r.get(r).status,this.#e=t,this.#r=e,this.#t=n}#a;#l},fh=class dh{#t;#e;#r;#n;constructor(e,n,r){this.produce=i=>i&&Object.keys(i).length?new dh(this.#t,this.#e,{...i}):this,this.inject=(i,o)=>{let s=i.create(this.#t.sliceMap);return o!=null&&s.set(o),this.#n?.onInject(i),this},this.remove=i=>(this.#t.remove(i),this.#n?.onRemove(i),this),this.record=i=>(i.create(this.#e.store),this.#n?.onRecord(i),this),this.clearTimer=i=>(this.#e.remove(i),this.#n?.onClear(i),this),this.isInjected=i=>this.#t.has(i),this.isRecorded=i=>this.#e.has(i),this.use=i=>(this.#n?.onUse(i),this.#t.get(i)),this.get=i=>this.use(i).get(),this.set=(i,o)=>this.use(i).set(o),this.update=(i,o)=>this.use(i).update(o),this.timer=i=>this.#e.get(i),this.done=i=>{this.timer(i).done(),this.#n?.onDone(i)},this.wait=i=>{let o=this.timer(i).start();return this.#n?.onWait(i,o),o},this.waitTimers=async i=>{await Promise.all(this.get(i).map(o=>this.wait(o)))},this.#t=e,this.#e=n,this.#r=r,r&&(this.#n=new X1(e,n,r))}get meta(){return this.#r}get inspector(){return this.#n}},ph=class{constructor(){this.store=new Map,this.get=t=>{let e=this.store.get(t.id);if(!e)throw oh(t.name);return e},this.remove=t=>{this.store.delete(t.id)},this.has=t=>this.store.has(t.id)}},Y1=class{#t;#e;#r;#n;constructor(t,e){this.#t=null,this.#e=null,this.#n="pending",this.start=()=>(this.#t??=new Promise((n,r)=>{this.#e=i=>{i instanceof CustomEvent&&i.detail.id===this.#r&&(this.#n="resolved",this.#s(),i.stopImmediatePropagation(),n())},this.#o(()=>{this.#n==="pending"&&(this.#n="rejected"),this.#s(),r(new Error(`Timing ${this.type.name} timeout.`))}),this.#n="pending",addEventListener(this.type.name,this.#e)}),this.#t),this.done=()=>{let n=new CustomEvent(this.type.name,{detail:{id:this.#r}});dispatchEvent(n)},this.#s=()=>{this.#e&&removeEventListener(this.type.name,this.#e)},this.#o=n=>{setTimeout(()=>{n()},this.type.timeout)},this.#r=Symbol(e.name),this.type=e,t.set(e.id,this)}get status(){return this.#n}#s;#o},Q1=class{constructor(t,e=3e3){this.create=n=>new Y1(n,this),this.id=Symbol(`Timer-${t}`),this.name=t,this.timeout=e}},xt=(t,e=3e3)=>new Q1(t,e);var Z1={};function er(t,e){let n=e||Z1,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return mh(t,r,i)}function mh(t,e,n){if(eC(t)){if("value"in t)return t.type==="html"&&!n?"":t.value;if(e&&"alt"in t&&t.alt)return t.alt;if("children"in t)return hh(t.children,e,n)}return Array.isArray(t)?hh(t,e,n):""}function hh(t,e,n){let r=[],i=-1;for(;++ii?0:i+e:e=e>i?i:e,n=n>0?n:0,r.length<1e4)s=Array.from(r),s.unshift(e,n),t.splice(...s);else for(n&&t.splice(e,n);o0?(ke(t,t.length,0,e),t):e}var yh={}.hasOwnProperty;function $s(t){let e={},n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"\uFFFD":String.fromCodePoint(n)}function qe(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var Te=Tn(/[A-Za-z]/),ve=Tn(/[\dA-Za-z]/),kh=Tn(/[#-'*+\--9=?A-Z^-~]/);function tr(t){return t!==null&&(t<32||t===127)}var uo=Tn(/\d/),bh=Tn(/[\dA-Fa-f]/),xh=Tn(/[!-/:-@[-`{-~]/);function D(t){return t!==null&&t<-2}function Z(t){return t!==null&&(t<0||t===32)}function j(t){return t===-2||t===-1||t===32}var nr=Tn(/\p{P}|\p{S}/u),Wt=Tn(/\s/);function Tn(t){return e;function e(n){return n!==null&&n>-1&&t.test(String.fromCharCode(n))}}function _(t,e,n,r){let i=r?r-1:Number.POSITIVE_INFINITY,o=0;return s;function s(l){return j(l)?(t.enter(n),a(l)):e(l)}function a(l){return j(l)&&o++s))return;let N=e.events.length,P=N,O,S;for(;P--;)if(e.events[P][0]==="exit"&&e.events[P][1].type==="chunkFlow"){if(O){S=e.events[P][1].end;break}O=!0}for(y(r),w=N;wC;){let A=n[v];e.containerState=A[1],A[0].exit.call(e,t)}n.length=C}function b(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function oC(t,e,n){return _(t,t.attempt(this.parser.constructs.document,e,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function on(t){if(t===null||Z(t)||Wt(t))return 1;if(nr(t))return 2}function vn(t,e,n){let r=[],i=-1;for(;++i1&&t[n][1].end.offset-t[n][1].start.offset>1?2:1;let f={...t[r][1].end},d={...t[n][1].start};Mh(f,-l),Mh(d,l),s={type:l>1?"strongSequence":"emphasisSequence",start:f,end:{...t[r][1].end}},a={type:l>1?"strongSequence":"emphasisSequence",start:{...t[n][1].start},end:d},o={type:l>1?"strongText":"emphasisText",start:{...t[r][1].end},end:{...t[n][1].start}},i={type:l>1?"strong":"emphasis",start:{...s.start},end:{...a.end}},t[r][1].end={...s.start},t[n][1].start={...a.end},c=[],t[r][1].end.offset-t[r][1].start.offset&&(c=Xe(c,[["enter",t[r][1],e],["exit",t[r][1],e]])),c=Xe(c,[["enter",i,e],["enter",s,e],["exit",s,e],["enter",o,e]]),c=Xe(c,vn(e.parser.constructs.insideSpan.null,t.slice(r+1,n),e)),c=Xe(c,[["exit",o,e],["enter",a,e],["exit",a,e],["exit",i,e]]),t[n][1].end.offset-t[n][1].start.offset?(u=2,c=Xe(c,[["enter",t[n][1],e],["exit",t[n][1],e]])):u=0,ke(t,r-1,n-r+3,c),n=r+c.length-u-2;break}}for(n=-1;++n0&&j(w)?_(t,b,"linePrefix",o+1)(w):b(w)}function b(w){return w===null||D(w)?t.check(Eh,m,v)(w):(t.enter("codeFlowValue"),C(w))}function C(w){return w===null||D(w)?(t.exit("codeFlowValue"),b(w)):(t.consume(w),C)}function v(w){return t.exit("codeFenced"),e(w)}function A(w,N,P){let O=0;return S;function S(q){return w.enter("lineEnding"),w.consume(q),w.exit("lineEnding"),me}function me(q){return w.enter("codeFencedFence"),j(q)?_(w,te,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(q):te(q)}function te(q){return q===a?(w.enter("codeFencedFenceSequence"),F(q)):P(q)}function F(q){return q===a?(O++,w.consume(q),F):O>=s?(w.exit("codeFencedFenceSequence"),j(q)?_(w,W,"whitespace")(q):W(q)):P(q)}function W(q){return q===null||D(q)?(w.exit("codeFencedFence"),N(q)):P(q)}}}function gC(t,e,n){let r=this;return i;function i(s){return s===null?n(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}var po={name:"codeIndented",tokenize:kC},yC={partial:!0,tokenize:bC};function kC(t,e,n){let r=this;return i;function i(c){return t.enter("codeIndented"),_(t,o,"linePrefix",5)(c)}function o(c){let u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?s(c):n(c)}function s(c){return c===null?l(c):D(c)?t.attempt(yC,s,l)(c):(t.enter("codeFlowValue"),a(c))}function a(c){return c===null||D(c)?(t.exit("codeFlowValue"),s(c)):(t.consume(c),a)}function l(c){return t.exit("codeIndented"),e(c)}}function bC(t,e,n){let r=this;return i;function i(s){return r.parser.lazy[r.now().line]?n(s):D(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),i):_(t,o,"linePrefix",5)(s)}function o(s){let a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):D(s)?i(s):n(s)}}var Ul={name:"codeText",previous:wC,resolve:xC,tokenize:CC};function xC(t){let e=t.length-4,n=3,r,i;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(e,n,r){let i=n||0;this.setCursor(Math.trunc(e));let o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&ho(this.left,r),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),ho(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),ho(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e=4?e(s):t.interrupt(r.parser.constructs.flow,n,e)(s)}}function Js(t,e,n,r,i,o,s,a,l){let c=l||Number.POSITIVE_INFINITY,u=0;return f;function f(y){return y===60?(t.enter(r),t.enter(i),t.enter(o),t.consume(y),t.exit(o),d):y===null||y===32||y===41||tr(y)?n(y):(t.enter(r),t.enter(s),t.enter(a),t.enter("chunkString",{contentType:"string"}),m(y))}function d(y){return y===62?(t.enter(o),t.consume(y),t.exit(o),t.exit(i),t.exit(r),e):(t.enter(a),t.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(t.exit("chunkString"),t.exit(a),d(y)):y===null||y===60||D(y)?n(y):(t.consume(y),y===92?h:p)}function h(y){return y===60||y===62||y===92?(t.consume(y),p):p(y)}function m(y){return!u&&(y===null||y===41||Z(y))?(t.exit("chunkString"),t.exit(a),t.exit(s),t.exit(r),e(y)):u999||p===null||p===91||p===93&&!l||p===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?n(p):p===93?(t.exit(o),t.enter(i),t.consume(p),t.exit(i),t.exit(r),e):D(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),f(p))}function f(p){return p===null||p===91||p===93||D(p)||a++>999?(t.exit("chunkString"),u(p)):(t.consume(p),l||(l=!j(p)),p===92?d:f)}function d(p){return p===91||p===92||p===93?(t.consume(p),a++,f):f(p)}}function Xs(t,e,n,r,i,o){let s;return a;function a(d){return d===34||d===39||d===40?(t.enter(r),t.enter(i),t.consume(d),t.exit(i),s=d===40?41:d,l):n(d)}function l(d){return d===s?(t.enter(i),t.consume(d),t.exit(i),t.exit(r),e):(t.enter(o),c(d))}function c(d){return d===s?(t.exit(o),l(s)):d===null?n(d):D(d)?(t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),_(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(d))}function u(d){return d===s||d===null||D(d)?(t.exit("chunkString"),c(d)):(t.consume(d),d===92?f:u)}function f(d){return d===s||d===92?(t.consume(d),u):u(d)}}function rr(t,e){let n;return r;function r(i){return D(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),n=!0,r):j(i)?_(t,r,n?"linePrefix":"lineSuffix")(i):e(i)}}var Gl={name:"definition",tokenize:IC},AC={partial:!0,tokenize:NC};function IC(t,e,n){let r=this,i;return o;function o(p){return t.enter("definition"),s(p)}function s(p){return Gs.call(r,t,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return i=qe(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(t.enter("definitionMarker"),t.consume(p),t.exit("definitionMarker"),l):n(p)}function l(p){return Z(p)?rr(t,c)(p):c(p)}function c(p){return Js(t,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return t.attempt(AC,f,f)(p)}function f(p){return j(p)?_(t,d,"whitespace")(p):d(p)}function d(p){return p===null||D(p)?(t.exit("definition"),r.parser.defined.push(i),e(p)):n(p)}}function NC(t,e,n){return r;function r(a){return Z(a)?rr(t,i)(a):n(a)}function i(a){return Xs(t,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return j(a)?_(t,s,"whitespace")(a):s(a)}function s(a){return a===null||D(a)?e(a):n(a)}}var Xl={name:"hardBreakEscape",tokenize:RC};function RC(t,e,n){return r;function r(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return D(o)?(t.exit("hardBreakEscape"),e(o)):n(o)}}var Yl={name:"headingAtx",resolve:OC,tokenize:DC};function OC(t,e){let n=t.length-2,r=3,i,o;return t[r][1].type==="whitespace"&&(r+=2),n-2>r&&t[n][1].type==="whitespace"&&(n-=2),t[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&t[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:t[r][1].start,end:t[n][1].end},o={type:"chunkText",start:t[r][1].start,end:t[n][1].end,contentType:"text"},ke(t,r,n-r+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function DC(t,e,n){let r=0;return i;function i(u){return t.enter("atxHeading"),o(u)}function o(u){return t.enter("atxHeadingSequence"),s(u)}function s(u){return u===35&&r++<6?(t.consume(u),s):u===null||Z(u)?(t.exit("atxHeadingSequence"),a(u)):n(u)}function a(u){return u===35?(t.enter("atxHeadingSequence"),l(u)):u===null||D(u)?(t.exit("atxHeading"),e(u)):j(u)?_(t,a,"whitespace")(u):(t.enter("atxHeadingText"),c(u))}function l(u){return u===35?(t.consume(u),l):(t.exit("atxHeadingSequence"),a(u))}function c(u){return u===null||u===35||Z(u)?(t.exit("atxHeadingText"),a(u)):(t.consume(u),c)}}var Th=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Ql=["pre","script","style","textarea"];var Zl={concrete:!0,name:"htmlFlow",resolveTo:BC,tokenize:FC},LC={partial:!0,tokenize:_C},PC={partial:!0,tokenize:zC};function BC(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function FC(t,e,n){let r=this,i,o,s,a,l;return c;function c(x){return u(x)}function u(x){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(x),f}function f(x){return x===33?(t.consume(x),d):x===47?(t.consume(x),o=!0,m):x===63?(t.consume(x),i=3,r.interrupt?e:k):Te(x)?(t.consume(x),s=String.fromCharCode(x),g):n(x)}function d(x){return x===45?(t.consume(x),i=2,p):x===91?(t.consume(x),i=5,a=0,h):Te(x)?(t.consume(x),i=4,r.interrupt?e:k):n(x)}function p(x){return x===45?(t.consume(x),r.interrupt?e:k):n(x)}function h(x){let ct="CDATA[";return x===ct.charCodeAt(a++)?(t.consume(x),a===ct.length?r.interrupt?e:te:h):n(x)}function m(x){return Te(x)?(t.consume(x),s=String.fromCharCode(x),g):n(x)}function g(x){if(x===null||x===47||x===62||Z(x)){let ct=x===47,Yn=s.toLowerCase();return!ct&&!o&&Ql.includes(Yn)?(i=1,r.interrupt?e(x):te(x)):Th.includes(s.toLowerCase())?(i=6,ct?(t.consume(x),y):r.interrupt?e(x):te(x)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(x):o?b(x):C(x))}return x===45||ve(x)?(t.consume(x),s+=String.fromCharCode(x),g):n(x)}function y(x){return x===62?(t.consume(x),r.interrupt?e:te):n(x)}function b(x){return j(x)?(t.consume(x),b):S(x)}function C(x){return x===47?(t.consume(x),S):x===58||x===95||Te(x)?(t.consume(x),v):j(x)?(t.consume(x),C):S(x)}function v(x){return x===45||x===46||x===58||x===95||ve(x)?(t.consume(x),v):A(x)}function A(x){return x===61?(t.consume(x),w):j(x)?(t.consume(x),A):C(x)}function w(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(t.consume(x),l=x,N):j(x)?(t.consume(x),w):P(x)}function N(x){return x===l?(t.consume(x),l=null,O):x===null||D(x)?n(x):(t.consume(x),N)}function P(x){return x===null||x===34||x===39||x===47||x===60||x===61||x===62||x===96||Z(x)?A(x):(t.consume(x),P)}function O(x){return x===47||x===62||j(x)?C(x):n(x)}function S(x){return x===62?(t.consume(x),me):n(x)}function me(x){return x===null||D(x)?te(x):j(x)?(t.consume(x),me):n(x)}function te(x){return x===45&&i===2?(t.consume(x),se):x===60&&i===1?(t.consume(x),fe):x===62&&i===4?(t.consume(x),bt):x===63&&i===3?(t.consume(x),k):x===93&&i===5?(t.consume(x),Ee):D(x)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(LC,en,F)(x)):x===null||D(x)?(t.exit("htmlFlowData"),F(x)):(t.consume(x),te)}function F(x){return t.check(PC,W,en)(x)}function W(x){return t.enter("lineEnding"),t.consume(x),t.exit("lineEnding"),q}function q(x){return x===null||D(x)?F(x):(t.enter("htmlFlowData"),te(x))}function se(x){return x===45?(t.consume(x),k):te(x)}function fe(x){return x===47?(t.consume(x),s="",ye):te(x)}function ye(x){if(x===62){let ct=s.toLowerCase();return Ql.includes(ct)?(t.consume(x),bt):te(x)}return Te(x)&&s.length<8?(t.consume(x),s+=String.fromCharCode(x),ye):te(x)}function Ee(x){return x===93?(t.consume(x),k):te(x)}function k(x){return x===62?(t.consume(x),bt):x===45&&i===2?(t.consume(x),k):te(x)}function bt(x){return x===null||D(x)?(t.exit("htmlFlowData"),en(x)):(t.consume(x),bt)}function en(x){return t.exit("htmlFlow"),e(x)}}function zC(t,e,n){let r=this;return i;function i(s){return D(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o):n(s)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}function _C(t,e,n){return r;function r(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(jt,e,n)}}var ec={name:"htmlText",tokenize:$C};function $C(t,e,n){let r=this,i,o,s;return a;function a(k){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(k),l}function l(k){return k===33?(t.consume(k),c):k===47?(t.consume(k),A):k===63?(t.consume(k),C):Te(k)?(t.consume(k),P):n(k)}function c(k){return k===45?(t.consume(k),u):k===91?(t.consume(k),o=0,h):Te(k)?(t.consume(k),b):n(k)}function u(k){return k===45?(t.consume(k),p):n(k)}function f(k){return k===null?n(k):k===45?(t.consume(k),d):D(k)?(s=f,fe(k)):(t.consume(k),f)}function d(k){return k===45?(t.consume(k),p):f(k)}function p(k){return k===62?se(k):k===45?d(k):f(k)}function h(k){let bt="CDATA[";return k===bt.charCodeAt(o++)?(t.consume(k),o===bt.length?m:h):n(k)}function m(k){return k===null?n(k):k===93?(t.consume(k),g):D(k)?(s=m,fe(k)):(t.consume(k),m)}function g(k){return k===93?(t.consume(k),y):m(k)}function y(k){return k===62?se(k):k===93?(t.consume(k),y):m(k)}function b(k){return k===null||k===62?se(k):D(k)?(s=b,fe(k)):(t.consume(k),b)}function C(k){return k===null?n(k):k===63?(t.consume(k),v):D(k)?(s=C,fe(k)):(t.consume(k),C)}function v(k){return k===62?se(k):C(k)}function A(k){return Te(k)?(t.consume(k),w):n(k)}function w(k){return k===45||ve(k)?(t.consume(k),w):N(k)}function N(k){return D(k)?(s=N,fe(k)):j(k)?(t.consume(k),N):se(k)}function P(k){return k===45||ve(k)?(t.consume(k),P):k===47||k===62||Z(k)?O(k):n(k)}function O(k){return k===47?(t.consume(k),se):k===58||k===95||Te(k)?(t.consume(k),S):D(k)?(s=O,fe(k)):j(k)?(t.consume(k),O):se(k)}function S(k){return k===45||k===46||k===58||k===95||ve(k)?(t.consume(k),S):me(k)}function me(k){return k===61?(t.consume(k),te):D(k)?(s=me,fe(k)):j(k)?(t.consume(k),me):O(k)}function te(k){return k===null||k===60||k===61||k===62||k===96?n(k):k===34||k===39?(t.consume(k),i=k,F):D(k)?(s=te,fe(k)):j(k)?(t.consume(k),te):(t.consume(k),W)}function F(k){return k===i?(t.consume(k),i=void 0,q):k===null?n(k):D(k)?(s=F,fe(k)):(t.consume(k),F)}function W(k){return k===null||k===34||k===39||k===60||k===61||k===96?n(k):k===47||k===62||Z(k)?O(k):(t.consume(k),W)}function q(k){return k===47||k===62||Z(k)?O(k):n(k)}function se(k){return k===62?(t.consume(k),t.exit("htmlTextData"),t.exit("htmlText"),e):n(k)}function fe(k){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(k),t.exit("lineEnding"),ye}function ye(k){return j(k)?_(t,Ee,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):Ee(k)}function Ee(k){return t.enter("htmlTextData"),s(k)}}var ir={name:"labelEnd",resolveAll:VC,resolveTo:qC,tokenize:KC},HC={tokenize:UC},WC={tokenize:JC},jC={tokenize:GC};function VC(t){let e=-1,n=[];for(;++e=3&&(c===null||D(c))?(t.exit("thematicBreak"),e(c)):n(c)}function l(c){return c===i?(t.consume(c),r++,l):(t.exit("thematicBreakSequence"),j(c)?_(t,a,"whitespace")(c):a(c))}}var Ke={continuation:{tokenize:rS},exit:oS,name:"list",tokenize:nS},eS={partial:!0,tokenize:sS},tS={partial:!0,tokenize:iS};function nS(t,e,n){let r=this,i=r.events[r.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(p){let h=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(h==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:uo(p)){if(r.containerState.type||(r.containerState.type=h,t.enter(h,{_container:!0})),h==="listUnordered")return t.enter("listItemPrefix"),p===42||p===45?t.check(or,n,c)(p):c(p);if(!r.interrupt||p===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),l(p)}return n(p)}function l(p){return uo(p)&&++s<10?(t.consume(p),l):(!r.interrupt||s<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(t.exit("listItemValue"),c(p)):n(p)}function c(p){return t.enter("listItemMarker"),t.consume(p),t.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,t.check(jt,r.interrupt?n:u,t.attempt(eS,d,f))}function u(p){return r.containerState.initialBlankLine=!0,o++,d(p)}function f(p){return j(p)?(t.enter("listItemPrefixWhitespace"),t.consume(p),t.exit("listItemPrefixWhitespace"),d):n(p)}function d(p){return r.containerState.size=o+r.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(p)}}function rS(t,e,n){let r=this;return r.containerState._closeFlow=void 0,t.check(jt,i,o);function i(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,_(t,e,"listItemIndent",r.containerState.size+1)(a)}function o(a){return r.containerState.furtherBlankLines||!j(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,t.attempt(tS,e,s)(a))}function s(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,_(t,t.attempt(Ke,e,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function iS(t,e,n){let r=this;return _(t,i,"listItemIndent",r.containerState.size+1);function i(o){let s=r.events[r.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===r.containerState.size?e(o):n(o)}}function oS(t){t.exit(this.containerState.type)}function sS(t,e,n){let r=this;return _(t,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){let s=r.events[r.events.length-1];return!j(o)&&s&&s[1].type==="listItemPrefixWhitespace"?e(o):n(o)}}var Ys={name:"setextUnderline",resolveTo:aS,tokenize:lS};function aS(t,e){let n=t.length,r,i,o;for(;n--;)if(t[n][0]==="enter"){if(t[n][1].type==="content"){r=n;break}t[n][1].type==="paragraph"&&(i=n)}else t[n][1].type==="content"&&t.splice(n,1),!o&&t[n][1].type==="definition"&&(o=n);let s={type:"setextHeading",start:{...t[r][1].start},end:{...t[t.length-1][1].end}};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",s,e]),t.splice(o+1,0,["exit",t[r][1],e]),t[r][1].end={...t[o][1].end}):t[r][1]=s,t.push(["exit",s,e]),t}function lS(t,e,n){let r=this,i;return o;function o(c){let u=r.events.length,f;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){f=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||f)?(t.enter("setextHeadingLine"),i=c,s(c)):n(c)}function s(c){return t.enter("setextHeadingLineSequence"),a(c)}function a(c){return c===i?(t.consume(c),a):(t.exit("setextHeadingLineSequence"),j(c)?_(t,l,"lineSuffix")(c):l(c))}function l(c){return c===null||D(c)?(t.exit("setextHeadingLine"),e(c)):n(c)}}var vh={tokenize:cS};function cS(t){let e=this,n=t.attempt(jt,r,t.attempt(this.parser.constructs.flowInitial,i,_(t,t.attempt(this.parser.constructs.flow,i,t.attempt(Jl,i)),"linePrefix")));return n;function r(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,n}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,n}}var Ah={resolveAll:Oh()},Ih=Rh("string"),Nh=Rh("text");function Rh(t){return{resolveAll:Oh(t==="text"?uS:void 0),tokenize:e};function e(n){let r=this,i=this.parser.constructs[t],o=n.attempt(i,s,a);return s;function s(u){return c(u)?o(u):a(u)}function a(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),l}function l(u){return c(u)?(n.exit("data"),o(u)):(n.consume(u),l)}function c(u){if(u===null)return!0;let f=i[u],d=-1;if(f)for(;++dkS,contentInitial:()=>dS,disable:()=>bS,document:()=>fS,flow:()=>hS,flowInitial:()=>pS,insideSpan:()=>yS,string:()=>mS,text:()=>gS});var fS={42:Ke,43:Ke,45:Ke,48:Ke,49:Ke,50:Ke,51:Ke,52:Ke,53:Ke,54:Ke,55:Ke,56:Ke,57:Ke,62:Ws},dS={91:Gl},pS={[-2]:po,[-1]:po,32:po},hS={35:Yl,42:or,45:[Ys,or],60:Zl,61:Ys,95:or,96:qs,126:qs},mS={38:Vs,92:js},gS={[-5]:mo,[-4]:mo,[-3]:mo,33:tc,38:Vs,42:fo,60:[Kl,ec],91:nc,92:[Xl,js],93:ir,95:fo,96:Ul},yS={null:[fo,Ah]},kS={null:[42,95]},bS={null:[]};function Dh(t,e,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},o=[],s=[],a=[],l=!0,c={attempt:O(N),check:O(P),consume:v,enter:A,exit:w,interrupt:O(P,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:g,parser:t,previous:null,sliceSerialize:h,sliceStream:m,write:p},f=e.tokenize.call(u,c),d;return e.resolveAll&&o.push(e),u;function p(F){return s=Xe(s,F),b(),s[s.length-1]!==null?[]:(S(e,0),u.events=vn(o,u.events,u),u.events)}function h(F,W){return wS(m(F),W)}function m(F){return xS(s,F)}function g(){let{_bufferIndex:F,_index:W,line:q,column:se,offset:fe}=r;return{_bufferIndex:F,_index:W,line:q,column:se,offset:fe}}function y(F){i[F.line]=F.column,te()}function b(){let F;for(;r._index-1){let a=s[0];typeof a=="string"?s[0]=a.slice(r):s.shift()}o>0&&s.push(t[i].slice(0,o))}return s}function wS(t,e){let n=-1,r=[],i;for(;++n{var _1=Object.create;var jl=Object.defineProperty;var $1=Object.getOwnPropertyDescriptor;var H1=Object.getOwnPropertyNames;var W1=Object.getPrototypeOf,j1=Object.prototype.hasOwnProperty;var V1=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},q1=(t,e)=>{for(var n in e)jl(t,n,{get:e[n],enumerable:!0})},K1=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of H1(e))!j1.call(t,i)&&i!==n&&jl(t,i,{get:()=>e[i],enumerable:!(r=$1(e,i))||r.enumerable});return t};var U1=(t,e,n)=>(n=t!=null?_1(W1(t)):{},K1(e||!t||!t.__esModule?jl(n,"default",{value:t,enumerable:!0}):n,t));var vm=V1((G$,Tm)=>{"use strict";var oa=Object.prototype.hasOwnProperty,Em=Object.prototype.toString,bm=Object.defineProperty,xm=Object.getOwnPropertyDescriptor,wm=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Em.call(e)==="[object Array]"},Cm=function(e){if(!e||Em.call(e)!=="[object Object]")return!1;var n=oa.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&oa.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var i;for(i in e);return typeof i>"u"||oa.call(e,i)},Sm=function(e,n){bm&&n.name==="__proto__"?bm(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Mm=function(e,n){if(n==="__proto__")if(oa.call(e,n)){if(xm)return xm(e,n).value}else return;return e[n]};Tm.exports=function t(){var e,n,r,i,o,s,a=arguments[0],l=1,c=arguments.length,u=!1;for(typeof a=="boolean"&&(u=a,a=arguments[1]||{},l=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});ltypeof e=="function"?"[Function]":e,Fs=t=>JSON.stringify(t,J1);function ih(t){return new dt(ft.docTypeError,`Doc type error, unsupported type: ${Fs(t)}`)}function oh(t){return new dt(ft.contextNotFound,`Context "${t}" not found, do you forget to inject it?`)}function sh(t){return new dt(ft.timerNotFound,`Timer "${t}" not found, do you forget to record it?`)}function ni(){return new dt(ft.ctxCallOutOfScope,"Should not call a context out of the plugin.")}function ah(t,e,n){let r=`Cannot create node for ${"name"in t?t.name:t}`,i=s=>{if(s==null)return"null";if(Array.isArray(s))return`[${s.map(i).join(", ")}]`;if(typeof s=="object")return"toJSON"in s&&typeof s.toJSON=="function"?JSON.stringify(s.toJSON()):"spec"in s?JSON.stringify(s.spec):JSON.stringify(s);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return JSON.stringify(s);if(typeof s=="function")return`[Function: ${s.name||"anonymous"}]`;try{return String(s)}catch{return"[Unserializable]"}},o=[["[Description]",r],["[Attributes]",e],["[Content]",(n??[]).map(s=>s?typeof s=="object"&&"type"in s?`${s}`:i(s):"null")]].reduce((s,[a,l])=>{let c=`${a}: ${i(l)}.`;return s.concat(c)},[]);return new dt(ft.createNodeInParserFail,o.join(` +`))}function Vl(){return new dt(ft.stackOverFlow,"Stack over flow, cannot pop on an empty stack.")}function lh(t){return new dt(ft.parserMatchError,`Cannot match target parser for node: ${Fs(t)}.`)}function ch(t){return new dt(ft.serializerMatchError,`Cannot match target serializer for node: ${Fs(t)}.`)}function uh(t,e){return new dt(ft.getAtomFromSchemaFail,`Cannot get ${t}: ${e} from schema.`)}function pt(t){return new dt(ft.expectDomTypeError,`Expect to be a dom, but get: ${Fs(t)}.`)}function zs(){return new dt(ft.callCommandBeforeEditorView,"You're trying to call a command before editor view initialized, make sure to get commandManager from ctx after editor view has been initialized")}function _s(t){return new dt(ft.missingNodeInSchema,`Missing node in schema, milkdown cannot find "${t}" in schema.`)}function fh(t){return new dt(ft.missingMarkInSchema,`Missing mark in schema, milkdown cannot find "${t}" in schema.`)}var ql=class{constructor(){this.sliceMap=new Map,this.get=t=>{let e=typeof t=="string"?[...this.sliceMap.values()].find(n=>n.type.name===t):this.sliceMap.get(t.id);if(!e)throw oh(typeof t=="string"?t:t.name);return e},this.remove=t=>{let e=typeof t=="string"?[...this.sliceMap.values()].find(n=>n.type.name===t):this.sliceMap.get(t.id);e&&this.sliceMap.delete(e.type.id)},this.has=t=>typeof t=="string"?[...this.sliceMap.values()].some(e=>e.type.name===t):this.sliceMap.has(t.id)}},G1=class{#t;#e;#r;constructor(t,e,n){this.#t=[],this.#r=()=>{this.#t.forEach(r=>r(this.#e))},this.set=r=>{this.#e=r,this.#r()},this.get=()=>this.#e,this.update=r=>{this.#e=r(this.#e),this.#r()},this.type=n,this.#e=e,t.set(n.id,this)}on(t){return this.#t.push(t),()=>{this.#t=this.#t.filter(e=>e!==t)}}once(t){let e=this.on(n=>{t(n),e()});return e}off(t){this.#t=this.#t.filter(e=>e!==t)}offAll(){this.#t=[]}},X1=class{constructor(t,e){this.id=Symbol(`Context-${e}`),this.name=e,this._defaultValue=t,this._typeInfo=()=>{throw ni()}}create(t,e=this._defaultValue){return new G1(t,e,this)}},Y=(t,e)=>new X1(t,e),Y1=class{#t;#e;#r;#n;#s;#o;#i;constructor(t,e,n){this.#n=new Set,this.#s=new Set,this.#o=new Map,this.#i=new Map,this.read=()=>({metadata:this.#t,injectedSlices:[...this.#n].map(r=>({name:typeof r=="string"?r:r.name,value:this.#a(r)})),consumedSlices:[...this.#s].map(r=>({name:typeof r=="string"?r:r.name,value:this.#a(r)})),recordedTimers:[...this.#o].map(([r,{duration:i}])=>({name:r.name,duration:i,status:this.#l(r)})),waitTimers:[...this.#i].map(([r,{duration:i}])=>({name:r.name,duration:i,status:this.#l(r)}))}),this.onRecord=r=>{this.#o.set(r,{start:Date.now(),duration:0})},this.onClear=r=>{this.#o.delete(r)},this.onDone=r=>{let i=this.#o.get(r);i&&(i.duration=Date.now()-i.start)},this.onWait=(r,i)=>{let o=Date.now();i.finally(()=>{this.#i.set(r,{duration:Date.now()-o})}).catch(console.error)},this.onInject=r=>{this.#n.add(r)},this.onRemove=r=>{this.#n.delete(r)},this.onUse=r=>{this.#s.add(r)},this.#a=r=>this.#e.get(r).get(),this.#l=r=>this.#r.get(r).status,this.#e=t,this.#r=e,this.#t=n}#a;#l},dh=class ph{#t;#e;#r;#n;constructor(e,n,r){this.produce=i=>i&&Object.keys(i).length?new ph(this.#t,this.#e,{...i}):this,this.inject=(i,o)=>{let s=i.create(this.#t.sliceMap);return o!=null&&s.set(o),this.#n?.onInject(i),this},this.remove=i=>(this.#t.remove(i),this.#n?.onRemove(i),this),this.record=i=>(i.create(this.#e.store),this.#n?.onRecord(i),this),this.clearTimer=i=>(this.#e.remove(i),this.#n?.onClear(i),this),this.isInjected=i=>this.#t.has(i),this.isRecorded=i=>this.#e.has(i),this.use=i=>(this.#n?.onUse(i),this.#t.get(i)),this.get=i=>this.use(i).get(),this.set=(i,o)=>this.use(i).set(o),this.update=(i,o)=>this.use(i).update(o),this.timer=i=>this.#e.get(i),this.done=i=>{this.timer(i).done(),this.#n?.onDone(i)},this.wait=i=>{let o=this.timer(i).start();return this.#n?.onWait(i,o),o},this.waitTimers=async i=>{await Promise.all(this.get(i).map(o=>this.wait(o)))},this.#t=e,this.#e=n,this.#r=r,r&&(this.#n=new Y1(e,n,r))}get meta(){return this.#r}get inspector(){return this.#n}},hh=class{constructor(){this.store=new Map,this.get=t=>{let e=this.store.get(t.id);if(!e)throw sh(t.name);return e},this.remove=t=>{this.store.delete(t.id)},this.has=t=>this.store.has(t.id)}},Q1=class{#t;#e;#r;#n;constructor(t,e){this.#t=null,this.#e=null,this.#n="pending",this.start=()=>(this.#t??=new Promise((n,r)=>{this.#e=i=>{i instanceof CustomEvent&&i.detail.id===this.#r&&(this.#n="resolved",this.#s(),i.stopImmediatePropagation(),n())},this.#o(()=>{this.#n==="pending"&&(this.#n="rejected"),this.#s(),r(new Error(`Timing ${this.type.name} timeout.`))}),this.#n="pending",addEventListener(this.type.name,this.#e)}),this.#t),this.done=()=>{let n=new CustomEvent(this.type.name,{detail:{id:this.#r}});dispatchEvent(n)},this.#s=()=>{this.#e&&removeEventListener(this.type.name,this.#e)},this.#o=n=>{setTimeout(()=>{n()},this.type.timeout)},this.#r=Symbol(e.name),this.type=e,t.set(e.id,this)}get status(){return this.#n}#s;#o},Z1=class{constructor(t,e=3e3){this.create=n=>new Q1(n,this),this.id=Symbol(`Timer-${t}`),this.name=t,this.timeout=e}},xt=(t,e=3e3)=>new Z1(t,e);var eC={};function er(t,e){let n=e||eC,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return gh(t,r,i)}function gh(t,e,n){if(tC(t)){if("value"in t)return t.type==="html"&&!n?"":t.value;if(e&&"alt"in t&&t.alt)return t.alt;if("children"in t)return mh(t.children,e,n)}return Array.isArray(t)?mh(t,e,n):""}function mh(t,e,n){let r=[],i=-1;for(;++ii?0:i+e:e=e>i?i:e,n=n>0?n:0,r.length<1e4)s=Array.from(r),s.unshift(e,n),t.splice(...s);else for(n&&t.splice(e,n);o0?(be(t,t.length,0,e),t):e}var kh={}.hasOwnProperty;function $s(t){let e={},n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"\uFFFD":String.fromCodePoint(n)}function qe(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var ve=Tn(/[A-Za-z]/),Ae=Tn(/[\dA-Za-z]/),bh=Tn(/[#-'*+\--9=?A-Z^-~]/);function tr(t){return t!==null&&(t<32||t===127)}var uo=Tn(/\d/),xh=Tn(/[\dA-Fa-f]/),wh=Tn(/[!-/:-@[-`{-~]/);function D(t){return t!==null&&t<-2}function Z(t){return t!==null&&(t<0||t===32)}function j(t){return t===-2||t===-1||t===32}var nr=Tn(/\p{P}|\p{S}/u),Wt=Tn(/\s/);function Tn(t){return e;function e(n){return n!==null&&n>-1&&t.test(String.fromCharCode(n))}}function _(t,e,n,r){let i=r?r-1:Number.POSITIVE_INFINITY,o=0;return s;function s(l){return j(l)?(t.enter(n),a(l)):e(l)}function a(l){return j(l)&&o++s))return;let N=e.events.length,P=N,O,S;for(;P--;)if(e.events[P][0]==="exit"&&e.events[P][1].type==="chunkFlow"){if(O){S=e.events[P][1].end;break}O=!0}for(y(r),w=N;wC;){let A=n[v];e.containerState=A[1],A[0].exit.call(e,t)}n.length=C}function b(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function sC(t,e,n){return _(t,t.attempt(this.parser.constructs.document,e,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function on(t){if(t===null||Z(t)||Wt(t))return 1;if(nr(t))return 2}function vn(t,e,n){let r=[],i=-1;for(;++i1&&t[n][1].end.offset-t[n][1].start.offset>1?2:1;let f={...t[r][1].end},d={...t[n][1].start};Eh(f,-l),Eh(d,l),s={type:l>1?"strongSequence":"emphasisSequence",start:f,end:{...t[r][1].end}},a={type:l>1?"strongSequence":"emphasisSequence",start:{...t[n][1].start},end:d},o={type:l>1?"strongText":"emphasisText",start:{...t[r][1].end},end:{...t[n][1].start}},i={type:l>1?"strong":"emphasis",start:{...s.start},end:{...a.end}},t[r][1].end={...s.start},t[n][1].start={...a.end},c=[],t[r][1].end.offset-t[r][1].start.offset&&(c=Xe(c,[["enter",t[r][1],e],["exit",t[r][1],e]])),c=Xe(c,[["enter",i,e],["enter",s,e],["exit",s,e],["enter",o,e]]),c=Xe(c,vn(e.parser.constructs.insideSpan.null,t.slice(r+1,n),e)),c=Xe(c,[["exit",o,e],["enter",a,e],["exit",a,e],["exit",i,e]]),t[n][1].end.offset-t[n][1].start.offset?(u=2,c=Xe(c,[["enter",t[n][1],e],["exit",t[n][1],e]])):u=0,be(t,r-1,n-r+3,c),n=r+c.length-u-2;break}}for(n=-1;++n0&&j(w)?_(t,b,"linePrefix",o+1)(w):b(w)}function b(w){return w===null||D(w)?t.check(Th,m,v)(w):(t.enter("codeFlowValue"),C(w))}function C(w){return w===null||D(w)?(t.exit("codeFlowValue"),b(w)):(t.consume(w),C)}function v(w){return t.exit("codeFenced"),e(w)}function A(w,N,P){let O=0;return S;function S(q){return w.enter("lineEnding"),w.consume(q),w.exit("lineEnding"),me}function me(q){return w.enter("codeFencedFence"),j(q)?_(w,te,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(q):te(q)}function te(q){return q===a?(w.enter("codeFencedFenceSequence"),F(q)):P(q)}function F(q){return q===a?(O++,w.consume(q),F):O>=s?(w.exit("codeFencedFenceSequence"),j(q)?_(w,W,"whitespace")(q):W(q)):P(q)}function W(q){return q===null||D(q)?(w.exit("codeFencedFence"),N(q)):P(q)}}}function yC(t,e,n){let r=this;return i;function i(s){return s===null?n(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}var po={name:"codeIndented",tokenize:bC},kC={partial:!0,tokenize:xC};function bC(t,e,n){let r=this;return i;function i(c){return t.enter("codeIndented"),_(t,o,"linePrefix",5)(c)}function o(c){let u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?s(c):n(c)}function s(c){return c===null?l(c):D(c)?t.attempt(kC,s,l)(c):(t.enter("codeFlowValue"),a(c))}function a(c){return c===null||D(c)?(t.exit("codeFlowValue"),s(c)):(t.consume(c),a)}function l(c){return t.exit("codeIndented"),e(c)}}function xC(t,e,n){let r=this;return i;function i(s){return r.parser.lazy[r.now().line]?n(s):D(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),i):_(t,o,"linePrefix",5)(s)}function o(s){let a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):D(s)?i(s):n(s)}}var Ul={name:"codeText",previous:CC,resolve:wC,tokenize:SC};function wC(t){let e=t.length-4,n=3,r,i;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(e,n,r){let i=n||0;this.setCursor(Math.trunc(e));let o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&ho(this.left,r),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),ho(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),ho(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e=4?e(s):t.interrupt(r.parser.constructs.flow,n,e)(s)}}function Js(t,e,n,r,i,o,s,a,l){let c=l||Number.POSITIVE_INFINITY,u=0;return f;function f(y){return y===60?(t.enter(r),t.enter(i),t.enter(o),t.consume(y),t.exit(o),d):y===null||y===32||y===41||tr(y)?n(y):(t.enter(r),t.enter(s),t.enter(a),t.enter("chunkString",{contentType:"string"}),m(y))}function d(y){return y===62?(t.enter(o),t.consume(y),t.exit(o),t.exit(i),t.exit(r),e):(t.enter(a),t.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(t.exit("chunkString"),t.exit(a),d(y)):y===null||y===60||D(y)?n(y):(t.consume(y),y===92?h:p)}function h(y){return y===60||y===62||y===92?(t.consume(y),p):p(y)}function m(y){return!u&&(y===null||y===41||Z(y))?(t.exit("chunkString"),t.exit(a),t.exit(s),t.exit(r),e(y)):u999||p===null||p===91||p===93&&!l||p===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?n(p):p===93?(t.exit(o),t.enter(i),t.consume(p),t.exit(i),t.exit(r),e):D(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),f(p))}function f(p){return p===null||p===91||p===93||D(p)||a++>999?(t.exit("chunkString"),u(p)):(t.consume(p),l||(l=!j(p)),p===92?d:f)}function d(p){return p===91||p===92||p===93?(t.consume(p),a++,f):f(p)}}function Xs(t,e,n,r,i,o){let s;return a;function a(d){return d===34||d===39||d===40?(t.enter(r),t.enter(i),t.consume(d),t.exit(i),s=d===40?41:d,l):n(d)}function l(d){return d===s?(t.enter(i),t.consume(d),t.exit(i),t.exit(r),e):(t.enter(o),c(d))}function c(d){return d===s?(t.exit(o),l(s)):d===null?n(d):D(d)?(t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),_(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(d))}function u(d){return d===s||d===null||D(d)?(t.exit("chunkString"),c(d)):(t.consume(d),d===92?f:u)}function f(d){return d===s||d===92?(t.consume(d),u):u(d)}}function rr(t,e){let n;return r;function r(i){return D(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),n=!0,r):j(i)?_(t,r,n?"linePrefix":"lineSuffix")(i):e(i)}}var Gl={name:"definition",tokenize:NC},IC={partial:!0,tokenize:RC};function NC(t,e,n){let r=this,i;return o;function o(p){return t.enter("definition"),s(p)}function s(p){return Gs.call(r,t,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return i=qe(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(t.enter("definitionMarker"),t.consume(p),t.exit("definitionMarker"),l):n(p)}function l(p){return Z(p)?rr(t,c)(p):c(p)}function c(p){return Js(t,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return t.attempt(IC,f,f)(p)}function f(p){return j(p)?_(t,d,"whitespace")(p):d(p)}function d(p){return p===null||D(p)?(t.exit("definition"),r.parser.defined.push(i),e(p)):n(p)}}function RC(t,e,n){return r;function r(a){return Z(a)?rr(t,i)(a):n(a)}function i(a){return Xs(t,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return j(a)?_(t,s,"whitespace")(a):s(a)}function s(a){return a===null||D(a)?e(a):n(a)}}var Xl={name:"hardBreakEscape",tokenize:OC};function OC(t,e,n){return r;function r(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return D(o)?(t.exit("hardBreakEscape"),e(o)):n(o)}}var Yl={name:"headingAtx",resolve:DC,tokenize:LC};function DC(t,e){let n=t.length-2,r=3,i,o;return t[r][1].type==="whitespace"&&(r+=2),n-2>r&&t[n][1].type==="whitespace"&&(n-=2),t[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&t[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:t[r][1].start,end:t[n][1].end},o={type:"chunkText",start:t[r][1].start,end:t[n][1].end,contentType:"text"},be(t,r,n-r+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function LC(t,e,n){let r=0;return i;function i(u){return t.enter("atxHeading"),o(u)}function o(u){return t.enter("atxHeadingSequence"),s(u)}function s(u){return u===35&&r++<6?(t.consume(u),s):u===null||Z(u)?(t.exit("atxHeadingSequence"),a(u)):n(u)}function a(u){return u===35?(t.enter("atxHeadingSequence"),l(u)):u===null||D(u)?(t.exit("atxHeading"),e(u)):j(u)?_(t,a,"whitespace")(u):(t.enter("atxHeadingText"),c(u))}function l(u){return u===35?(t.consume(u),l):(t.exit("atxHeadingSequence"),a(u))}function c(u){return u===null||u===35||Z(u)?(t.exit("atxHeadingText"),a(u)):(t.consume(u),c)}}var vh=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Ql=["pre","script","style","textarea"];var Zl={concrete:!0,name:"htmlFlow",resolveTo:FC,tokenize:zC},PC={partial:!0,tokenize:$C},BC={partial:!0,tokenize:_C};function FC(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function zC(t,e,n){let r=this,i,o,s,a,l;return c;function c(x){return u(x)}function u(x){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(x),f}function f(x){return x===33?(t.consume(x),d):x===47?(t.consume(x),o=!0,m):x===63?(t.consume(x),i=3,r.interrupt?e:k):ve(x)?(t.consume(x),s=String.fromCharCode(x),g):n(x)}function d(x){return x===45?(t.consume(x),i=2,p):x===91?(t.consume(x),i=5,a=0,h):ve(x)?(t.consume(x),i=4,r.interrupt?e:k):n(x)}function p(x){return x===45?(t.consume(x),r.interrupt?e:k):n(x)}function h(x){let ct="CDATA[";return x===ct.charCodeAt(a++)?(t.consume(x),a===ct.length?r.interrupt?e:te:h):n(x)}function m(x){return ve(x)?(t.consume(x),s=String.fromCharCode(x),g):n(x)}function g(x){if(x===null||x===47||x===62||Z(x)){let ct=x===47,Yn=s.toLowerCase();return!ct&&!o&&Ql.includes(Yn)?(i=1,r.interrupt?e(x):te(x)):vh.includes(s.toLowerCase())?(i=6,ct?(t.consume(x),y):r.interrupt?e(x):te(x)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(x):o?b(x):C(x))}return x===45||Ae(x)?(t.consume(x),s+=String.fromCharCode(x),g):n(x)}function y(x){return x===62?(t.consume(x),r.interrupt?e:te):n(x)}function b(x){return j(x)?(t.consume(x),b):S(x)}function C(x){return x===47?(t.consume(x),S):x===58||x===95||ve(x)?(t.consume(x),v):j(x)?(t.consume(x),C):S(x)}function v(x){return x===45||x===46||x===58||x===95||Ae(x)?(t.consume(x),v):A(x)}function A(x){return x===61?(t.consume(x),w):j(x)?(t.consume(x),A):C(x)}function w(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(t.consume(x),l=x,N):j(x)?(t.consume(x),w):P(x)}function N(x){return x===l?(t.consume(x),l=null,O):x===null||D(x)?n(x):(t.consume(x),N)}function P(x){return x===null||x===34||x===39||x===47||x===60||x===61||x===62||x===96||Z(x)?A(x):(t.consume(x),P)}function O(x){return x===47||x===62||j(x)?C(x):n(x)}function S(x){return x===62?(t.consume(x),me):n(x)}function me(x){return x===null||D(x)?te(x):j(x)?(t.consume(x),me):n(x)}function te(x){return x===45&&i===2?(t.consume(x),se):x===60&&i===1?(t.consume(x),fe):x===62&&i===4?(t.consume(x),bt):x===63&&i===3?(t.consume(x),k):x===93&&i===5?(t.consume(x),Te):D(x)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(PC,en,F)(x)):x===null||D(x)?(t.exit("htmlFlowData"),F(x)):(t.consume(x),te)}function F(x){return t.check(BC,W,en)(x)}function W(x){return t.enter("lineEnding"),t.consume(x),t.exit("lineEnding"),q}function q(x){return x===null||D(x)?F(x):(t.enter("htmlFlowData"),te(x))}function se(x){return x===45?(t.consume(x),k):te(x)}function fe(x){return x===47?(t.consume(x),s="",ke):te(x)}function ke(x){if(x===62){let ct=s.toLowerCase();return Ql.includes(ct)?(t.consume(x),bt):te(x)}return ve(x)&&s.length<8?(t.consume(x),s+=String.fromCharCode(x),ke):te(x)}function Te(x){return x===93?(t.consume(x),k):te(x)}function k(x){return x===62?(t.consume(x),bt):x===45&&i===2?(t.consume(x),k):te(x)}function bt(x){return x===null||D(x)?(t.exit("htmlFlowData"),en(x)):(t.consume(x),bt)}function en(x){return t.exit("htmlFlow"),e(x)}}function _C(t,e,n){let r=this;return i;function i(s){return D(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o):n(s)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}function $C(t,e,n){return r;function r(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(jt,e,n)}}var ec={name:"htmlText",tokenize:HC};function HC(t,e,n){let r=this,i,o,s;return a;function a(k){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(k),l}function l(k){return k===33?(t.consume(k),c):k===47?(t.consume(k),A):k===63?(t.consume(k),C):ve(k)?(t.consume(k),P):n(k)}function c(k){return k===45?(t.consume(k),u):k===91?(t.consume(k),o=0,h):ve(k)?(t.consume(k),b):n(k)}function u(k){return k===45?(t.consume(k),p):n(k)}function f(k){return k===null?n(k):k===45?(t.consume(k),d):D(k)?(s=f,fe(k)):(t.consume(k),f)}function d(k){return k===45?(t.consume(k),p):f(k)}function p(k){return k===62?se(k):k===45?d(k):f(k)}function h(k){let bt="CDATA[";return k===bt.charCodeAt(o++)?(t.consume(k),o===bt.length?m:h):n(k)}function m(k){return k===null?n(k):k===93?(t.consume(k),g):D(k)?(s=m,fe(k)):(t.consume(k),m)}function g(k){return k===93?(t.consume(k),y):m(k)}function y(k){return k===62?se(k):k===93?(t.consume(k),y):m(k)}function b(k){return k===null||k===62?se(k):D(k)?(s=b,fe(k)):(t.consume(k),b)}function C(k){return k===null?n(k):k===63?(t.consume(k),v):D(k)?(s=C,fe(k)):(t.consume(k),C)}function v(k){return k===62?se(k):C(k)}function A(k){return ve(k)?(t.consume(k),w):n(k)}function w(k){return k===45||Ae(k)?(t.consume(k),w):N(k)}function N(k){return D(k)?(s=N,fe(k)):j(k)?(t.consume(k),N):se(k)}function P(k){return k===45||Ae(k)?(t.consume(k),P):k===47||k===62||Z(k)?O(k):n(k)}function O(k){return k===47?(t.consume(k),se):k===58||k===95||ve(k)?(t.consume(k),S):D(k)?(s=O,fe(k)):j(k)?(t.consume(k),O):se(k)}function S(k){return k===45||k===46||k===58||k===95||Ae(k)?(t.consume(k),S):me(k)}function me(k){return k===61?(t.consume(k),te):D(k)?(s=me,fe(k)):j(k)?(t.consume(k),me):O(k)}function te(k){return k===null||k===60||k===61||k===62||k===96?n(k):k===34||k===39?(t.consume(k),i=k,F):D(k)?(s=te,fe(k)):j(k)?(t.consume(k),te):(t.consume(k),W)}function F(k){return k===i?(t.consume(k),i=void 0,q):k===null?n(k):D(k)?(s=F,fe(k)):(t.consume(k),F)}function W(k){return k===null||k===34||k===39||k===60||k===61||k===96?n(k):k===47||k===62||Z(k)?O(k):(t.consume(k),W)}function q(k){return k===47||k===62||Z(k)?O(k):n(k)}function se(k){return k===62?(t.consume(k),t.exit("htmlTextData"),t.exit("htmlText"),e):n(k)}function fe(k){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(k),t.exit("lineEnding"),ke}function ke(k){return j(k)?_(t,Te,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):Te(k)}function Te(k){return t.enter("htmlTextData"),s(k)}}var ir={name:"labelEnd",resolveAll:qC,resolveTo:KC,tokenize:UC},WC={tokenize:JC},jC={tokenize:GC},VC={tokenize:XC};function qC(t){let e=-1,n=[];for(;++e=3&&(c===null||D(c))?(t.exit("thematicBreak"),e(c)):n(c)}function l(c){return c===i?(t.consume(c),r++,l):(t.exit("thematicBreakSequence"),j(c)?_(t,a,"whitespace")(c):a(c))}}var Ke={continuation:{tokenize:iS},exit:sS,name:"list",tokenize:rS},tS={partial:!0,tokenize:aS},nS={partial:!0,tokenize:oS};function rS(t,e,n){let r=this,i=r.events[r.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(p){let h=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(h==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:uo(p)){if(r.containerState.type||(r.containerState.type=h,t.enter(h,{_container:!0})),h==="listUnordered")return t.enter("listItemPrefix"),p===42||p===45?t.check(or,n,c)(p):c(p);if(!r.interrupt||p===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),l(p)}return n(p)}function l(p){return uo(p)&&++s<10?(t.consume(p),l):(!r.interrupt||s<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(t.exit("listItemValue"),c(p)):n(p)}function c(p){return t.enter("listItemMarker"),t.consume(p),t.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,t.check(jt,r.interrupt?n:u,t.attempt(tS,d,f))}function u(p){return r.containerState.initialBlankLine=!0,o++,d(p)}function f(p){return j(p)?(t.enter("listItemPrefixWhitespace"),t.consume(p),t.exit("listItemPrefixWhitespace"),d):n(p)}function d(p){return r.containerState.size=o+r.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(p)}}function iS(t,e,n){let r=this;return r.containerState._closeFlow=void 0,t.check(jt,i,o);function i(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,_(t,e,"listItemIndent",r.containerState.size+1)(a)}function o(a){return r.containerState.furtherBlankLines||!j(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,t.attempt(nS,e,s)(a))}function s(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,_(t,t.attempt(Ke,e,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function oS(t,e,n){let r=this;return _(t,i,"listItemIndent",r.containerState.size+1);function i(o){let s=r.events[r.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===r.containerState.size?e(o):n(o)}}function sS(t){t.exit(this.containerState.type)}function aS(t,e,n){let r=this;return _(t,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){let s=r.events[r.events.length-1];return!j(o)&&s&&s[1].type==="listItemPrefixWhitespace"?e(o):n(o)}}var Ys={name:"setextUnderline",resolveTo:lS,tokenize:cS};function lS(t,e){let n=t.length,r,i,o;for(;n--;)if(t[n][0]==="enter"){if(t[n][1].type==="content"){r=n;break}t[n][1].type==="paragraph"&&(i=n)}else t[n][1].type==="content"&&t.splice(n,1),!o&&t[n][1].type==="definition"&&(o=n);let s={type:"setextHeading",start:{...t[r][1].start},end:{...t[t.length-1][1].end}};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",s,e]),t.splice(o+1,0,["exit",t[r][1],e]),t[r][1].end={...t[o][1].end}):t[r][1]=s,t.push(["exit",s,e]),t}function cS(t,e,n){let r=this,i;return o;function o(c){let u=r.events.length,f;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){f=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||f)?(t.enter("setextHeadingLine"),i=c,s(c)):n(c)}function s(c){return t.enter("setextHeadingLineSequence"),a(c)}function a(c){return c===i?(t.consume(c),a):(t.exit("setextHeadingLineSequence"),j(c)?_(t,l,"lineSuffix")(c):l(c))}function l(c){return c===null||D(c)?(t.exit("setextHeadingLine"),e(c)):n(c)}}var Ah={tokenize:uS};function uS(t){let e=this,n=t.attempt(jt,r,t.attempt(this.parser.constructs.flowInitial,i,_(t,t.attempt(this.parser.constructs.flow,i,t.attempt(Jl,i)),"linePrefix")));return n;function r(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,n}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,n}}var Ih={resolveAll:Dh()},Nh=Oh("string"),Rh=Oh("text");function Oh(t){return{resolveAll:Dh(t==="text"?fS:void 0),tokenize:e};function e(n){let r=this,i=this.parser.constructs[t],o=n.attempt(i,s,a);return s;function s(u){return c(u)?o(u):a(u)}function a(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),l}function l(u){return c(u)?(n.exit("data"),o(u)):(n.consume(u),l)}function c(u){if(u===null)return!0;let f=i[u],d=-1;if(f)for(;++dbS,contentInitial:()=>pS,disable:()=>xS,document:()=>dS,flow:()=>mS,flowInitial:()=>hS,insideSpan:()=>kS,string:()=>gS,text:()=>yS});var dS={42:Ke,43:Ke,45:Ke,48:Ke,49:Ke,50:Ke,51:Ke,52:Ke,53:Ke,54:Ke,55:Ke,56:Ke,57:Ke,62:Ws},pS={91:Gl},hS={[-2]:po,[-1]:po,32:po},mS={35:Yl,42:or,45:[Ys,or],60:Zl,61:Ys,95:or,96:qs,126:qs},gS={38:Vs,92:js},yS={[-5]:mo,[-4]:mo,[-3]:mo,33:tc,38:Vs,42:fo,60:[Kl,ec],91:nc,92:[Xl,js],93:ir,95:fo,96:Ul},kS={null:[fo,Ih]},bS={null:[42,95]},xS={null:[]};function Lh(t,e,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},o=[],s=[],a=[],l=!0,c={attempt:O(N),check:O(P),consume:v,enter:A,exit:w,interrupt:O(P,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:g,parser:t,previous:null,sliceSerialize:h,sliceStream:m,write:p},f=e.tokenize.call(u,c),d;return e.resolveAll&&o.push(e),u;function p(F){return s=Xe(s,F),b(),s[s.length-1]!==null?[]:(S(e,0),u.events=vn(o,u.events,u),u.events)}function h(F,W){return CS(m(F),W)}function m(F){return wS(s,F)}function g(){let{_bufferIndex:F,_index:W,line:q,column:se,offset:fe}=r;return{_bufferIndex:F,_index:W,line:q,column:se,offset:fe}}function y(F){i[F.line]=F.column,te()}function b(){let F;for(;r._index-1){let a=s[0];typeof a=="string"?s[0]=a.slice(r):s.shift()}o>0&&s.push(t[i].slice(0,o))}return s}function CS(t,e){let n=-1,r=[],i;for(;++n0){let Nt=J.tokenStack[J.tokenStack.length-1];(Nt[1]||Fh).call(J,void 0,Nt[0])}for(L.position={start:In(T.length>0?T[0][1].start:{line:1,column:1,offset:0}),end:In(T.length>0?T[T.length-2][1].end:{line:1,column:1,offset:0})},de=-1;++de "),o.shift(2);let s=n.indentLines(n.containerFlow(t,o.current()),AS);return i(),s}function AS(t,e,n){return">"+(n?"":" ")+t}function Zs(t,e){return Vh(t,e.inConstruct,!0)&&!Vh(t,e.notInConstruct,!1)}function Vh(t,e,n){if(typeof e=="string"&&(e=[e]),!e||e.length===0)return n;let r=-1;for(;++r0){let Nt=J.tokenStack[J.tokenStack.length-1];(Nt[1]||zh).call(J,void 0,Nt[0])}for(L.position={start:In(T.length>0?T[0][1].start:{line:1,column:1,offset:0}),end:In(T.length>0?T[T.length-2][1].end:{line:1,column:1,offset:0})},de=-1;++de "),o.shift(2);let s=n.indentLines(n.containerFlow(t,o.current()),IS);return i(),s}function IS(t,e,n){return">"+(n?"":" ")+t}function Zs(t,e){return qh(t,e.inConstruct,!0)&&!qh(t,e.notInConstruct,!1)}function qh(t,e,n){if(typeof e=="string"&&(e=[e]),!e||e.length===0)return n;let r=-1;for(;++rs&&(s=o):o=1,i=r+e.length,r=n.indexOf(e,i);return s}function go(t,e){return!!(e.options.fences===!1&&t.value&&!t.lang&&/[^ \r\n]/.test(t.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(t.value))}function qh(t){let e=t.options.fence||"`";if(e!=="`"&&e!=="~")throw new Error("Cannot serialize code with `"+e+"` for `options.fence`, expected `` ` `` or `~`");return e}function Kh(t,e,n,r){let i=qh(n),o=t.value||"",s=i==="`"?"GraveAccent":"Tilde";if(go(t,n)){let f=n.enter("codeIndented"),d=n.indentLines(o,IS);return f(),d}let a=n.createTracker(r),l=i.repeat(Math.max(ea(o,i)+1,3)),c=n.enter("codeFenced"),u=a.move(l);if(t.lang){let f=n.enter(`codeFencedLang${s}`);u+=a.move(n.safe(t.lang,{before:u,after:" ",encode:["`"],...a.current()})),f()}if(t.lang&&t.meta){let f=n.enter(`codeFencedMeta${s}`);u+=a.move(" "),u+=a.move(n.safe(t.meta,{before:u,after:` +`}function ea(t,e){let n=String(t),r=n.indexOf(e),i=r,o=0,s=0;if(typeof e!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===i?++o>s&&(s=o):o=1,i=r+e.length,r=n.indexOf(e,i);return s}function go(t,e){return!!(e.options.fences===!1&&t.value&&!t.lang&&/[^ \r\n]/.test(t.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(t.value))}function Kh(t){let e=t.options.fence||"`";if(e!=="`"&&e!=="~")throw new Error("Cannot serialize code with `"+e+"` for `options.fence`, expected `` ` `` or `~`");return e}function Uh(t,e,n,r){let i=Kh(n),o=t.value||"",s=i==="`"?"GraveAccent":"Tilde";if(go(t,n)){let f=n.enter("codeIndented"),d=n.indentLines(o,NS);return f(),d}let a=n.createTracker(r),l=i.repeat(Math.max(ea(o,i)+1,3)),c=n.enter("codeFenced"),u=a.move(l);if(t.lang){let f=n.enter(`codeFencedLang${s}`);u+=a.move(n.safe(t.lang,{before:u,after:" ",encode:["`"],...a.current()})),f()}if(t.lang&&t.meta){let f=n.enter(`codeFencedMeta${s}`);u+=a.move(" "),u+=a.move(n.safe(t.meta,{before:u,after:` `,encode:["`"],...a.current()})),f()}return u+=a.move(` `),o&&(u+=a.move(o+` -`)),u+=a.move(l),c(),u}function IS(t,e,n){return(n?"":" ")+t}function oi(t){let e=t.options.quote||'"';if(e!=='"'&&e!=="'")throw new Error("Cannot serialize title with `"+e+"` for `options.quote`, expected `\"`, or `'`");return e}function Uh(t,e,n,r){let i=oi(n),o=i==='"'?"Quote":"Apostrophe",s=n.enter("definition"),a=n.enter("label"),l=n.createTracker(r),c=l.move("[");return c+=l.move(n.safe(n.associationId(t),{before:c,after:"]",...l.current()})),c+=l.move("]: "),a(),!t.url||/[\0- \u007F]/.test(t.url)?(a=n.enter("destinationLiteral"),c+=l.move("<"),c+=l.move(n.safe(t.url,{before:c,after:">",...l.current()})),c+=l.move(">")):(a=n.enter("destinationRaw"),c+=l.move(n.safe(t.url,{before:c,after:t.title?" ":` -`,...l.current()}))),a(),t.title&&(a=n.enter(`title${o}`),c+=l.move(" "+i),c+=l.move(n.safe(t.title,{before:c,after:i,...l.current()})),c+=l.move(i),a()),s(),c}function Jh(t){let e=t.options.emphasis||"*";if(e!=="*"&&e!=="_")throw new Error("Cannot serialize emphasis with `"+e+"` for `options.emphasis`, expected `*`, or `_`");return e}function ht(t){return"&#x"+t.toString(16).toUpperCase()+";"}function si(t,e,n){let r=on(t),i=on(e);return r===void 0?i===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}fc.peek=NS;function fc(t,e,n,r){let i=Jh(n),o=n.enter("emphasis"),s=n.createTracker(r),a=s.move(i),l=s.move(n.containerPhrasing(t,{after:i,before:a,...s.current()})),c=l.charCodeAt(0),u=si(r.before.charCodeAt(r.before.length-1),c,i);u.inside&&(l=ht(c)+l.slice(1));let f=l.charCodeAt(l.length-1),d=si(r.after.charCodeAt(0),f,i);d.inside&&(l=l.slice(0,-1)+ht(f));let p=s.move(i);return o(),n.attentionEncodeSurroundingInfo={after:d.outside,before:u.outside},a+l+p}function NS(t,e,n){return n.options.emphasis||"*"}var Nn=(function(t){if(t==null)return LS;if(typeof t=="function")return ta(t);if(typeof t=="object")return Array.isArray(t)?RS(t):OS(t);if(typeof t=="string")return DS(t);throw new Error("Expected function, string, or object as test")});function RS(t){let e=[],n=-1;for(;++n":""))+")"})}return d;function d(){let p=Gh,h,m,g;if((!e||o(l,c,u[u.length-1]||void 0))&&(p=BS(n(l,u)),p[0]===sr))return p;if("children"in l&&l.children){let y=l;if(y.children&&p[0]!==ar)for(m=(r?y.children.length:-1)+s,g=u.concat(y);m>-1&&m",...l.current()})),c+=l.move(">")):(a=n.enter("destinationRaw"),c+=l.move(n.safe(t.url,{before:c,after:t.title?" ":` +`,...l.current()}))),a(),t.title&&(a=n.enter(`title${o}`),c+=l.move(" "+i),c+=l.move(n.safe(t.title,{before:c,after:i,...l.current()})),c+=l.move(i),a()),s(),c}function Gh(t){let e=t.options.emphasis||"*";if(e!=="*"&&e!=="_")throw new Error("Cannot serialize emphasis with `"+e+"` for `options.emphasis`, expected `*`, or `_`");return e}function ht(t){return"&#x"+t.toString(16).toUpperCase()+";"}function si(t,e,n){let r=on(t),i=on(e);return r===void 0?i===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}fc.peek=RS;function fc(t,e,n,r){let i=Gh(n),o=n.enter("emphasis"),s=n.createTracker(r),a=s.move(i),l=s.move(n.containerPhrasing(t,{after:i,before:a,...s.current()})),c=l.charCodeAt(0),u=si(r.before.charCodeAt(r.before.length-1),c,i);u.inside&&(l=ht(c)+l.slice(1));let f=l.charCodeAt(l.length-1),d=si(r.after.charCodeAt(0),f,i);d.inside&&(l=l.slice(0,-1)+ht(f));let p=s.move(i);return o(),n.attentionEncodeSurroundingInfo={after:d.outside,before:u.outside},a+l+p}function RS(t,e,n){return n.options.emphasis||"*"}var Nn=(function(t){if(t==null)return PS;if(typeof t=="function")return ta(t);if(typeof t=="object")return Array.isArray(t)?OS(t):DS(t);if(typeof t=="string")return LS(t);throw new Error("Expected function, string, or object as test")});function OS(t){let e=[],n=-1;for(;++n":""))+")"})}return d;function d(){let p=Xh,h,m,g;if((!e||o(l,c,u[u.length-1]||void 0))&&(p=FS(n(l,u)),p[0]===sr))return p;if("children"in l&&l.children){let y=l;if(y.children&&p[0]!==ar)for(m=(r?y.children.length:-1)+s,g=u.concat(y);m>-1&&m",...l.current()})),c+=l.move(">")):(a=n.enter("destinationRaw"),c+=l.move(n.safe(t.url,{before:c,after:t.title?" ":")",...l.current()}))),a(),t.title&&(a=n.enter(`title${o}`),c+=l.move(" "+i),c+=l.move(n.safe(t.title,{before:c,after:i,...l.current()})),c+=l.move(i),a()),c+=l.move(")"),s(),c}function zS(){return"!"}hc.peek=_S;function hc(t,e,n,r){let i=t.referenceType,o=n.enter("imageReference"),s=n.enter("label"),a=n.createTracker(r),l=a.move("!["),c=n.safe(t.alt,{before:l,after:"]",...a.current()});l+=a.move(c+"]["),s();let u=n.stack;n.stack=[],s=n.enter("reference");let f=n.safe(n.associationId(t),{before:l,after:"]",...a.current()});return s(),n.stack=u,o(),i==="full"||!c||c!==f?l+=a.move(f+"]"):i==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function _S(){return"!"}mc.peek=$S;function mc(t,e,n){let r=t.value||"",i="`",o=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++o\u007F]/.test(t.url))}yc.peek=HS;function yc(t,e,n,r){let i=oi(n),o=i==='"'?"Quote":"Apostrophe",s=n.createTracker(r),a,l;if(gc(t,n)){let u=n.stack;n.stack=[],a=n.enter("autolink");let f=s.move("<");return f+=s.move(n.containerPhrasing(t,{before:f,after:">",...s.current()})),f+=s.move(">"),a(),n.stack=u,f}a=n.enter("link"),l=n.enter("label");let c=s.move("[");return c+=s.move(n.containerPhrasing(t,{before:c,after:"](",...s.current()})),c+=s.move("]("),l(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(l=n.enter("destinationLiteral"),c+=s.move("<"),c+=s.move(n.safe(t.url,{before:c,after:">",...s.current()})),c+=s.move(">")):(l=n.enter("destinationRaw"),c+=s.move(n.safe(t.url,{before:c,after:t.title?" ":")",...s.current()}))),l(),t.title&&(l=n.enter(`title${o}`),c+=s.move(" "+i),c+=s.move(n.safe(t.title,{before:c,after:i,...s.current()})),c+=s.move(i),l()),c+=s.move(")"),a(),c}function HS(t,e,n){return gc(t,n)?"<":"["}kc.peek=WS;function kc(t,e,n,r){let i=t.referenceType,o=n.enter("linkReference"),s=n.enter("label"),a=n.createTracker(r),l=a.move("["),c=n.containerPhrasing(t,{before:l,after:"]",...a.current()});l+=a.move(c+"]["),s();let u=n.stack;n.stack=[],s=n.enter("reference");let f=n.safe(n.associationId(t),{before:l,after:"]",...a.current()});return s(),n.stack=u,o(),i==="full"||!c||c!==f?l+=a.move(f+"]"):i==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function WS(){return"["}function ai(t){let e=t.options.bullet||"*";if(e!=="*"&&e!=="+"&&e!=="-")throw new Error("Cannot serialize items with `"+e+"` for `options.bullet`, expected `*`, `+`, or `-`");return e}function Yh(t){let e=ai(t),n=t.options.bulletOther;if(!n)return e==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===e)throw new Error("Expected `bullet` (`"+e+"`) and `bulletOther` (`"+n+"`) to be different");return n}function Qh(t){let e=t.options.bulletOrdered||".";if(e!=="."&&e!==")")throw new Error("Cannot serialize items with `"+e+"` for `options.bulletOrdered`, expected `.` or `)`");return e}function ia(t){let e=t.options.rule||"*";if(e!=="*"&&e!=="-"&&e!=="_")throw new Error("Cannot serialize rules with `"+e+"` for `options.rule`, expected `*`, `-`, or `_`");return e}function Zh(t,e,n,r){let i=n.enter("list"),o=n.bulletCurrent,s=t.ordered?Qh(n):ai(n),a=t.ordered?s==="."?")":".":Yh(n),l=e&&n.bulletLastUsed?s===n.bulletLastUsed:!1;if(!t.ordered){let u=t.children?t.children[0]:void 0;if((s==="*"||s==="-")&&u&&(!u.children||!u.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(l=!0),ia(n)===s&&u){let f=-1;for(;++f-1?e.start:1)+(n.options.incrementListMarker===!1?0:e.children.indexOf(t))+o);let s=o.length+1;(i==="tab"||i==="mixed"&&(e&&e.type==="list"&&e.spread||t.spread))&&(s=Math.ceil(s/4)*4);let a=n.createTracker(r);a.move(o+" ".repeat(s-o.length)),a.shift(s);let l=n.enter("listItem"),c=n.indentLines(n.containerFlow(t,a.current()),u);return l(),c;function u(f,d,p){return d?(p?"":" ".repeat(s))+f:(p?o:o+" ".repeat(s-o.length))+f}}function nm(t,e,n,r){let i=n.enter("paragraph"),o=n.enter("phrasing"),s=n.containerPhrasing(t,r);return o(),i(),s}var bc=Nn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function rm(t,e,n,r){return(t.children.some(function(s){return bc(s)})?n.containerPhrasing:n.containerFlow).call(n,t,r)}function im(t){let e=t.options.strong||"*";if(e!=="*"&&e!=="_")throw new Error("Cannot serialize strong with `"+e+"` for `options.strong`, expected `*`, or `_`");return e}xc.peek=jS;function xc(t,e,n,r){let i=im(n),o=n.enter("strong"),s=n.createTracker(r),a=s.move(i+i),l=s.move(n.containerPhrasing(t,{after:i,before:a,...s.current()})),c=l.charCodeAt(0),u=si(r.before.charCodeAt(r.before.length-1),c,i);u.inside&&(l=ht(c)+l.slice(1));let f=l.charCodeAt(l.length-1),d=si(r.after.charCodeAt(0),f,i);d.inside&&(l=l.slice(0,-1)+ht(f));let p=s.move(i+i);return o(),n.attentionEncodeSurroundingInfo={after:d.outside,before:u.outside},a+l+p}function jS(t,e,n){return n.options.strong||"*"}function om(t,e,n,r){return n.safe(t.value,r)}function sm(t){let e=t.options.ruleRepetition||3;if(e<3)throw new Error("Cannot serialize rules with repetition `"+e+"` for `options.ruleRepetition`, expected `3` or more");return e}function am(t,e,n){let r=(ia(n)+(n.options.ruleSpaces?" ":"")).repeat(sm(n));return n.options.ruleSpaces?r.slice(0,-1):r}var cr={blockquote:jh,break:uc,code:Kh,definition:Uh,emphasis:fc,hardBreak:uc,heading:Xh,html:dc,image:pc,imageReference:hc,inlineCode:mc,link:yc,linkReference:kc,list:Zh,listItem:tm,paragraph:nm,root:rm,strong:xc,text:om,thematicBreak:am};var lm=[VS];function VS(t,e,n,r){if(e.type==="code"&&go(e,r)&&(t.type==="list"||t.type===e.type&&go(t,r)))return!1;if("spread"in n&&typeof n.spread=="boolean")return t.type==="paragraph"&&(t.type===e.type||e.type==="definition"||e.type==="heading"&&ra(e,r))?void 0:n.spread?1:0}var ur=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"],cm=[{character:" ",after:"[\\r\\n]",inConstruct:"phrasing"},{character:" ",before:"[\\r\\n]",inConstruct:"phrasing"},{character:" ",inConstruct:["codeFencedLangGraveAccent","codeFencedLangTilde"]},{character:"\r",inConstruct:["codeFencedLangGraveAccent","codeFencedLangTilde","codeFencedMetaGraveAccent","codeFencedMetaTilde","destinationLiteral","headingAtx"]},{character:` +`,...o.current()});return/^[\t ]/.test(c)&&(c=ht(c.charCodeAt(0))+c.slice(1)),c=c?s+" "+c:s,n.options.closeAtx&&(c+=" "+s),l(),a(),c}dc.peek=zS;function dc(t){return t.value||""}function zS(){return"<"}pc.peek=_S;function pc(t,e,n,r){let i=oi(n),o=i==='"'?"Quote":"Apostrophe",s=n.enter("image"),a=n.enter("label"),l=n.createTracker(r),c=l.move("![");return c+=l.move(n.safe(t.alt,{before:c,after:"]",...l.current()})),c+=l.move("]("),a(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(a=n.enter("destinationLiteral"),c+=l.move("<"),c+=l.move(n.safe(t.url,{before:c,after:">",...l.current()})),c+=l.move(">")):(a=n.enter("destinationRaw"),c+=l.move(n.safe(t.url,{before:c,after:t.title?" ":")",...l.current()}))),a(),t.title&&(a=n.enter(`title${o}`),c+=l.move(" "+i),c+=l.move(n.safe(t.title,{before:c,after:i,...l.current()})),c+=l.move(i),a()),c+=l.move(")"),s(),c}function _S(){return"!"}hc.peek=$S;function hc(t,e,n,r){let i=t.referenceType,o=n.enter("imageReference"),s=n.enter("label"),a=n.createTracker(r),l=a.move("!["),c=n.safe(t.alt,{before:l,after:"]",...a.current()});l+=a.move(c+"]["),s();let u=n.stack;n.stack=[],s=n.enter("reference");let f=n.safe(n.associationId(t),{before:l,after:"]",...a.current()});return s(),n.stack=u,o(),i==="full"||!c||c!==f?l+=a.move(f+"]"):i==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function $S(){return"!"}mc.peek=HS;function mc(t,e,n){let r=t.value||"",i="`",o=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++o\u007F]/.test(t.url))}yc.peek=WS;function yc(t,e,n,r){let i=oi(n),o=i==='"'?"Quote":"Apostrophe",s=n.createTracker(r),a,l;if(gc(t,n)){let u=n.stack;n.stack=[],a=n.enter("autolink");let f=s.move("<");return f+=s.move(n.containerPhrasing(t,{before:f,after:">",...s.current()})),f+=s.move(">"),a(),n.stack=u,f}a=n.enter("link"),l=n.enter("label");let c=s.move("[");return c+=s.move(n.containerPhrasing(t,{before:c,after:"](",...s.current()})),c+=s.move("]("),l(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(l=n.enter("destinationLiteral"),c+=s.move("<"),c+=s.move(n.safe(t.url,{before:c,after:">",...s.current()})),c+=s.move(">")):(l=n.enter("destinationRaw"),c+=s.move(n.safe(t.url,{before:c,after:t.title?" ":")",...s.current()}))),l(),t.title&&(l=n.enter(`title${o}`),c+=s.move(" "+i),c+=s.move(n.safe(t.title,{before:c,after:i,...s.current()})),c+=s.move(i),l()),c+=s.move(")"),a(),c}function WS(t,e,n){return gc(t,n)?"<":"["}kc.peek=jS;function kc(t,e,n,r){let i=t.referenceType,o=n.enter("linkReference"),s=n.enter("label"),a=n.createTracker(r),l=a.move("["),c=n.containerPhrasing(t,{before:l,after:"]",...a.current()});l+=a.move(c+"]["),s();let u=n.stack;n.stack=[],s=n.enter("reference");let f=n.safe(n.associationId(t),{before:l,after:"]",...a.current()});return s(),n.stack=u,o(),i==="full"||!c||c!==f?l+=a.move(f+"]"):i==="shortcut"?l=l.slice(0,-1):l+=a.move("]"),l}function jS(){return"["}function ai(t){let e=t.options.bullet||"*";if(e!=="*"&&e!=="+"&&e!=="-")throw new Error("Cannot serialize items with `"+e+"` for `options.bullet`, expected `*`, `+`, or `-`");return e}function Qh(t){let e=ai(t),n=t.options.bulletOther;if(!n)return e==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===e)throw new Error("Expected `bullet` (`"+e+"`) and `bulletOther` (`"+n+"`) to be different");return n}function Zh(t){let e=t.options.bulletOrdered||".";if(e!=="."&&e!==")")throw new Error("Cannot serialize items with `"+e+"` for `options.bulletOrdered`, expected `.` or `)`");return e}function ia(t){let e=t.options.rule||"*";if(e!=="*"&&e!=="-"&&e!=="_")throw new Error("Cannot serialize rules with `"+e+"` for `options.rule`, expected `*`, `-`, or `_`");return e}function em(t,e,n,r){let i=n.enter("list"),o=n.bulletCurrent,s=t.ordered?Zh(n):ai(n),a=t.ordered?s==="."?")":".":Qh(n),l=e&&n.bulletLastUsed?s===n.bulletLastUsed:!1;if(!t.ordered){let u=t.children?t.children[0]:void 0;if((s==="*"||s==="-")&&u&&(!u.children||!u.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(l=!0),ia(n)===s&&u){let f=-1;for(;++f-1?e.start:1)+(n.options.incrementListMarker===!1?0:e.children.indexOf(t))+o);let s=o.length+1;(i==="tab"||i==="mixed"&&(e&&e.type==="list"&&e.spread||t.spread))&&(s=Math.ceil(s/4)*4);let a=n.createTracker(r);a.move(o+" ".repeat(s-o.length)),a.shift(s);let l=n.enter("listItem"),c=n.indentLines(n.containerFlow(t,a.current()),u);return l(),c;function u(f,d,p){return d?(p?"":" ".repeat(s))+f:(p?o:o+" ".repeat(s-o.length))+f}}function rm(t,e,n,r){let i=n.enter("paragraph"),o=n.enter("phrasing"),s=n.containerPhrasing(t,r);return o(),i(),s}var bc=Nn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function im(t,e,n,r){return(t.children.some(function(s){return bc(s)})?n.containerPhrasing:n.containerFlow).call(n,t,r)}function om(t){let e=t.options.strong||"*";if(e!=="*"&&e!=="_")throw new Error("Cannot serialize strong with `"+e+"` for `options.strong`, expected `*`, or `_`");return e}xc.peek=VS;function xc(t,e,n,r){let i=om(n),o=n.enter("strong"),s=n.createTracker(r),a=s.move(i+i),l=s.move(n.containerPhrasing(t,{after:i,before:a,...s.current()})),c=l.charCodeAt(0),u=si(r.before.charCodeAt(r.before.length-1),c,i);u.inside&&(l=ht(c)+l.slice(1));let f=l.charCodeAt(l.length-1),d=si(r.after.charCodeAt(0),f,i);d.inside&&(l=l.slice(0,-1)+ht(f));let p=s.move(i+i);return o(),n.attentionEncodeSurroundingInfo={after:d.outside,before:u.outside},a+l+p}function VS(t,e,n){return n.options.strong||"*"}function sm(t,e,n,r){return n.safe(t.value,r)}function am(t){let e=t.options.ruleRepetition||3;if(e<3)throw new Error("Cannot serialize rules with repetition `"+e+"` for `options.ruleRepetition`, expected `3` or more");return e}function lm(t,e,n){let r=(ia(n)+(n.options.ruleSpaces?" ":"")).repeat(am(n));return n.options.ruleSpaces?r.slice(0,-1):r}var cr={blockquote:Vh,break:uc,code:Uh,definition:Jh,emphasis:fc,hardBreak:uc,heading:Yh,html:dc,image:pc,imageReference:hc,inlineCode:mc,link:yc,linkReference:kc,list:em,listItem:nm,paragraph:rm,root:im,strong:xc,text:sm,thematicBreak:lm};var cm=[qS];function qS(t,e,n,r){if(e.type==="code"&&go(e,r)&&(t.type==="list"||t.type===e.type&&go(t,r)))return!1;if("spread"in n&&typeof n.spread=="boolean")return t.type==="paragraph"&&(t.type===e.type||e.type==="definition"||e.type==="heading"&&ra(e,r))?void 0:n.spread?1:0}var ur=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"],um=[{character:" ",after:"[\\r\\n]",inConstruct:"phrasing"},{character:" ",before:"[\\r\\n]",inConstruct:"phrasing"},{character:" ",inConstruct:["codeFencedLangGraveAccent","codeFencedLangTilde"]},{character:"\r",inConstruct:["codeFencedLangGraveAccent","codeFencedLangTilde","codeFencedMetaGraveAccent","codeFencedMetaTilde","destinationLiteral","headingAtx"]},{character:` `,inConstruct:["codeFencedLangGraveAccent","codeFencedLangTilde","codeFencedMetaGraveAccent","codeFencedMetaTilde","destinationLiteral","headingAtx"]},{character:" ",after:"[\\r\\n]",inConstruct:"phrasing"},{character:" ",before:"[\\r\\n]",inConstruct:"phrasing"},{character:" ",inConstruct:["codeFencedLangGraveAccent","codeFencedLangTilde"]},{character:"!",after:"\\[",inConstruct:"phrasing",notInConstruct:ur},{character:'"',inConstruct:"titleQuote"},{atBreak:!0,character:"#"},{character:"#",inConstruct:"headingAtx",after:`(?:[\r ]|$)`},{character:"&",after:"[#A-Za-z]",inConstruct:"phrasing"},{character:"'",inConstruct:"titleApostrophe"},{character:"(",inConstruct:"destinationRaw"},{before:"\\]",character:"(",inConstruct:"phrasing",notInConstruct:ur},{atBreak:!0,before:"\\d+",character:")"},{character:")",inConstruct:"destinationRaw"},{atBreak:!0,character:"*",after:`(?:[ \r *])`},{character:"*",inConstruct:"phrasing",notInConstruct:ur},{atBreak:!0,character:"+",after:`(?:[ \r ])`},{atBreak:!0,character:"-",after:`(?:[ \r -])`},{atBreak:!0,before:"\\d+",character:".",after:`(?:[ \r -]|$)`},{atBreak:!0,character:"<",after:"[!/?A-Za-z]"},{character:"<",after:"[!/?A-Za-z]",inConstruct:"phrasing",notInConstruct:ur},{character:"<",inConstruct:"destinationLiteral"},{atBreak:!0,character:"="},{atBreak:!0,character:">"},{character:">",inConstruct:"destinationLiteral"},{atBreak:!0,character:"["},{character:"[",inConstruct:"phrasing",notInConstruct:ur},{character:"[",inConstruct:["label","reference"]},{character:"\\",after:"[\\r\\n]",inConstruct:"phrasing"},{character:"]",inConstruct:["label","reference"]},{atBreak:!0,character:"_"},{character:"_",inConstruct:"phrasing",notInConstruct:ur},{atBreak:!0,character:"`"},{character:"`",inConstruct:["codeFencedLangGraveAccent","codeFencedMetaGraveAccent"]},{character:"`",inConstruct:"phrasing",notInConstruct:ur},{atBreak:!0,character:"~"}];function um(t){return t.label||!t.identifier?t.label||"":Qs(t.identifier)}function fm(t){if(!t._compiled){let e=(t.atBreak?"[\\r\\n][\\t ]*":"")+(t.before?"(?:"+t.before+")":"");t._compiled=new RegExp((e?"("+e+")":"")+(/[|\\{}()[\]^$+*?.-]/.test(t.character)?"\\":"")+t.character+(t.after?"(?:"+t.after+")":""),"g")}return t._compiled}function dm(t,e,n){let r=e.indexStack,i=t.children||[],o=[],s=-1,a=n.before,l;r.push(-1);let c=e.createTracker(n);for(;++s0&&(a==="\r"||a===` -`)&&u.type==="html"&&(o[o.length-1]=o[o.length-1].replace(/(\r?\n|\r)$/," "),a=" ",c=e.createTracker(n),c.move(o.join("")));let d=e.handle(u,t,e,{...c.current(),after:f,before:a});l&&l===d.slice(0,1)&&(d=ht(l.charCodeAt(0))+d.slice(1));let p=e.attentionEncodeSurroundingInfo;e.attentionEncodeSurroundingInfo=void 0,l=void 0,p&&(o.length>0&&p.before&&a===o[o.length-1].slice(-1)&&(o[o.length-1]=o[o.length-1].slice(0,-1)+ht(a.charCodeAt(0))),p.after&&(l=f)),c.move(d),o.push(d),a=d.slice(-1)}return r.pop(),o.join("")}function pm(t,e,n){let r=e.indexStack,i=t.children||[],o=e.createTracker(n),s=[],a=-1;for(r.push(-1);++a"},{character:">",inConstruct:"destinationLiteral"},{atBreak:!0,character:"["},{character:"[",inConstruct:"phrasing",notInConstruct:ur},{character:"[",inConstruct:["label","reference"]},{character:"\\",after:"[\\r\\n]",inConstruct:"phrasing"},{character:"]",inConstruct:["label","reference"]},{atBreak:!0,character:"_"},{character:"_",inConstruct:"phrasing",notInConstruct:ur},{atBreak:!0,character:"`"},{character:"`",inConstruct:["codeFencedLangGraveAccent","codeFencedMetaGraveAccent"]},{character:"`",inConstruct:"phrasing",notInConstruct:ur},{atBreak:!0,character:"~"}];function fm(t){return t.label||!t.identifier?t.label||"":Qs(t.identifier)}function dm(t){if(!t._compiled){let e=(t.atBreak?"[\\r\\n][\\t ]*":"")+(t.before?"(?:"+t.before+")":"");t._compiled=new RegExp((e?"("+e+")":"")+(/[|\\{}()[\]^$+*?.-]/.test(t.character)?"\\":"")+t.character+(t.after?"(?:"+t.after+")":""),"g")}return t._compiled}function pm(t,e,n){let r=e.indexStack,i=t.children||[],o=[],s=-1,a=n.before,l;r.push(-1);let c=e.createTracker(n);for(;++s0&&(a==="\r"||a===` +`)&&u.type==="html"&&(o[o.length-1]=o[o.length-1].replace(/(\r?\n|\r)$/," "),a=" ",c=e.createTracker(n),c.move(o.join("")));let d=e.handle(u,t,e,{...c.current(),after:f,before:a});l&&l===d.slice(0,1)&&(d=ht(l.charCodeAt(0))+d.slice(1));let p=e.attentionEncodeSurroundingInfo;e.attentionEncodeSurroundingInfo=void 0,l=void 0,p&&(o.length>0&&p.before&&a===o[o.length-1].slice(-1)&&(o[o.length-1]=o[o.length-1].slice(0,-1)+ht(a.charCodeAt(0))),p.after&&(l=f)),c.move(d),o.push(d),a=d.slice(-1)}return r.pop(),o.join("")}function hm(t,e,n){let r=e.indexStack,i=t.children||[],o=e.createTracker(n),s=[],a=-1;for(r.push(-1);++a `}return` -`}var KS=/\r?\n|\r/g;function hm(t,e){let n=[],r=0,i=0,o;for(;o=KS.exec(t);)s(t.slice(r,o.index)),n.push(o[0]),r=o.index+o[0].length,i++;return s(t.slice(r)),n.join("");function s(a){n.push(e(a,i,!a))}}function gm(t,e,n){let r=(n.before||"")+(e||"")+(n.after||""),i=[],o=[],s={},a=-1;for(;++a=c||u+1=c||u+1s.length,l;a&&s.push(i);try{l=t.apply(this,s)}catch(c){let u=c;if(a&&n)throw u;return i(u)}a||(l&&l.then&&typeof l.then=="function"?l.then(o,i):l instanceof Error?i(l):o(l))}function i(s,...a){n||(n=!0,e(s,...a))}function o(s){i(null,s)}}var Ne=class extends Error{constructor(e,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",o={},s=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof e=="string"?i=e:!o.cause&&e&&(s=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof r=="string"){let l=r.indexOf(":");l===-1?o.ruleId=r:(o.source=r.slice(0,l),o.ruleId=r.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){let l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}let a=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=a?a.line:void 0,this.name=An(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=s&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};Ne.prototype.file="";Ne.prototype.name="";Ne.prototype.reason="";Ne.prototype.message="";Ne.prototype.stack="";Ne.prototype.column=void 0;Ne.prototype.line=void 0;Ne.prototype.ancestors=void 0;Ne.prototype.cause=void 0;Ne.prototype.fatal=void 0;Ne.prototype.place=void 0;Ne.prototype.ruleId=void 0;Ne.prototype.source=void 0;var Ot={basename:eM,dirname:tM,extname:nM,join:rM,sep:"/"};function eM(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');ko(t);let n=0,r=-1,i=t.length,o;if(e===void 0||e.length===0||e.length>t.length){for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else r<0&&(o=!0,r=i+1);return r<0?"":t.slice(n,r)}if(e===t)return"";let s=-1,a=e.length-1;for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else s<0&&(o=!0,s=i+1),a>-1&&(t.codePointAt(i)===e.codePointAt(a--)?a<0&&(r=i):(a=-1,r=s));return n===r?r=s:r<0&&(r=t.length),t.slice(n,r)}function tM(t){if(ko(t),t.length===0)return".";let e=-1,n=t.length,r;for(;--n;)if(t.codePointAt(n)===47){if(r){e=n;break}}else r||(r=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function nM(t){ko(t);let e=t.length,n=-1,r=0,i=-1,o=0,s;for(;e--;){let a=t.codePointAt(e);if(a===47){if(s){r=e+1;break}continue}n<0&&(s=!0,n=e+1),a===46?i<0?i=e:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||n<0||o===0||o===1&&i===n-1&&i===r+1?"":t.slice(i,n)}function rM(...t){let e=-1,n;for(;++e0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function oM(t,e){let n="",r=0,i=-1,o=0,s=-1,a,l;for(;++s<=t.length;){if(s2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),i=s,o=0;continue}}else if(n.length>0){n="",r=0,i=s,o=0;continue}}e&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+t.slice(i+1,s):n=t.slice(i+1,s),r=s-i-1;i=s,o=0}else a===46&&o>-1?o++:o=-1}return n}function ko(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}var Am={cwd:sM};function sM(){return"/"}function ci(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function Im(t){if(typeof t=="string")t=new URL(t);else if(!ci(t)){let e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){let e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return aM(t)}function aM(t){if(t.hostname!==""){let r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}let e=t.pathname,n=-1;for(;++n0){let[p,...h]=u,m=r[d][1];yo(m)&&yo(p)&&(p=(0,aa.default)(!0,m,p)),r[d]=[c,p,...h]}}}},xo=new Nc().freeze();function vc(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Ac(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Ic(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Om(t){if(!yo(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Dm(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function sa(t){return uM(t)?t:new bo(t)}function uM(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function fM(t){return typeof t=="string"||dM(t)}function dM(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}function Ue(t){this.content=t}Ue.prototype={constructor:Ue,find:function(t){for(var e=0;e>1}};Ue.from=function(t){if(t instanceof Ue)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Ue(e)};var Rc=Ue;function jm(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),o=e.child(r);if(i==o){n+=i.nodeSize;continue}if(!i.sameMarkup(o))return n;if(i.isText&&i.text!=o.text){let s=i.text,a=o.text,l=0;for(;s[l]==a[l];l++)n++;return l&&l0&&d>0&&c[f-1]==u[d-1];)f--,d--,n--,r--;return f&&d&&f=56320&&t<57344}function Km(t){return t>=55296&&t<56320}var M=class t{constructor(e,n){if(this.content=e,this.size=n||0,n==null)for(let r=0;re&&r(l,i+a,o||null,s)!==!1&&l.content.size){let u=a+1;l.nodesBetween(Math.max(0,e-u),Math.min(l.content.size,n-u),r,i+u)}a=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let o="",s=!0;return this.nodesBetween(e,n,(a,l)=>{let c=a.isText?a.text.slice(Math.max(e,l)-l,n-l):a.isLeaf?i?typeof i=="function"?i(a):i:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&c||a.isTextblock)&&r&&(s?s=!1:o+=r),o+=c},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.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);oe)for(let o=0,s=0;se&&((sn)&&(a.isText?a=a.cut(Math.max(0,e-s),Math.min(a.text.length,n-s)):a=a.cut(Math.max(0,e-s-1),Math.min(a.content.size,n-s-1))),r.push(a),i+=a.nodeSize),s=l}return new t(r,i)}cutByIndex(e,n){return e==n?t.empty:e==0&&n==this.content.length?this:new t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),o=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new t(i,o)}addToStart(e){return new t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new t(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),o=r+i.nodeSize;if(o>=e)return o==e?la(n+1,o):la(n,r);r=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return t.fromArray(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return t.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(o)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};ne.none=[];var Rn=class extends Error{},R=class t{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Jm(this.content,e+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new t(r,this.openStart,this.openEnd)}removeBetween(e,n){return new t(Um(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return t.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 t(M.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let o=e.firstChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.firstChild)r++;for(let o=e.lastChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.lastChild)i++;return new t(e,r,i)}};R.empty=new R(M.empty,0,0);function Um(t,e,n){let{index:r,offset:i}=t.findIndex(e),o=t.maybeChild(r),{index:s,offset:a}=t.findIndex(n);if(i==e||o.isText){if(a!=n&&!t.child(s).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw new RangeError("Removing non-flat range");return t.replaceChild(r,o.copy(Um(o.content,e-i-1,n-i-1)))}function Jm(t,e,n,r,i,o){let{index:s,offset:a}=t.findIndex(e),l=t.maybeChild(s);if(a==e||l.isText)return o&&r<=0&&i<=0&&!o.canReplace(s,s,n)?null:t.cut(0,e).append(n).append(t.cut(e));let c=Jm(l.content,e-a-1,n,s==0?r-1:0,s==t.childCount-1?i-1:0,l);return c&&t.replaceChild(s,l.copy(c))}function pM(t,e,n){if(n.openStart>t.depth)throw new Rn("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Rn("Inconsistent open depths");return Gm(t,e,n,0)}function Gm(t,e,n,r){let i=t.index(r),o=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function wo(t,e,n,r){let i=(e||t).node(n),o=0,s=e?e.index(n):i.childCount;t&&(o=t.index(n),t.depth>n?o++:t.textOffset&&(fr(t.nodeAfter,r),o++));for(let a=o;ai&&Dc(t,e,i+1),s=r.depth>i&&Dc(n,r,i+1),a=[];return wo(null,t,i,a),o&&s&&e.index(i)==n.index(i)?(Xm(o,s),fr(dr(o,Ym(t,e,n,r,i+1)),a)):(o&&fr(dr(o,da(t,e,i+1)),a),wo(e,n,i,a),s&&fr(dr(s,da(n,r,i+1)),a)),wo(r,null,i,a),new M(a)}function da(t,e,n){let r=[];if(wo(null,t,n,r),t.depth>n){let i=Dc(t,e,n+1);fr(dr(i,da(t,e,n+1)),r)}return wo(e,null,n,r),new M(r)}function hM(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let o=n-1;o>=0;o--)i=e.node(o).copy(M.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}var pa=class t{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(n);return r?e.child(n).cut(r):i}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,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)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new So(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,o=n;for(let s=e;;){let{index:a,offset:l}=s.content.findIndex(o),c=o-l;if(r.push(s,a,i+l),!c||(s=s.child(a),s.isText))break;o=c-1,i+=l+1}return new t(n,r,o)}static resolveCached(e,n){let r=Lm.get(e);if(r)for(let o=0;oe&&this.nodesBetween(e,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 e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Qm(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=M.empty,i=0,o=r.childCount){let s=this.contentMatchAt(e).matchFragment(r,i,o),a=s&&s.matchFragment(this.content,n);if(!a||!a.validEnd)return!1;for(let l=i;ln.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,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(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=M.fromJSON(e,n.content),o=e.nodeType(n.type).create(n.attrs,i,r);return o.type.checkAttrs(o.attrs),o}};rt.prototype.text=void 0;var Pc=class t extends rt{constructor(e,n,r,i){if(super(e,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):Qm(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new t(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new t(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function Qm(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}var pr=class t{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new Bc(e,n);if(r.next==null)return t.empty;let i=Zm(r);r.next&&r.err("Unexpected trailing text");let o=SM(CM(i));return MM(o,r),o}matchType(e){for(let n=0;nc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let i=0;i{let o=i+(r.validEnd?"*":" ")+" ";for(let s=0;s"+e.indexOf(r.next[s].next);return o}).join(` -`)}};pr.empty=new pr(!0);var Bc=class{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}};function Zm(t){let e=[];do e.push(yM(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function yM(t){let e=[];do e.push(kM(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function kM(t){let e=wM(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=bM(t,e);else break;return e}function Pm(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function bM(t,e){let n=Pm(t),r=n;return t.eat(",")&&(t.next!="}"?r=Pm(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function xM(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let o in n){let s=n[o];s.isInGroup(e)&&i.push(s)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function wM(t){if(t.eat("(")){let e=Zm(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=xM(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function CM(t){let e=[[]];return i(o(t,0),n()),e;function n(){return e.push([])-1}function r(s,a,l){let c={term:l,to:a};return e[s].push(c),c}function i(s,a){s.forEach(l=>l.to=a)}function o(s,a){if(s.type=="choice")return s.exprs.reduce((l,c)=>l.concat(o(c,a)),[]);if(s.type=="seq")for(let l=0;;l++){let c=o(s.exprs[l],a);if(l==s.exprs.length-1)return c;i(c,a=n())}else if(s.type=="star"){let l=n();return r(a,l),i(o(s.expr,l),l),[r(l)]}else if(s.type=="plus"){let l=n();return i(o(s.expr,a),l),i(o(s.expr,l),l),[r(l)]}else{if(s.type=="opt")return[r(a)].concat(o(s.expr,a));if(s.type=="range"){let l=a;for(let c=0;c{t[s].forEach(({term:a,to:l})=>{if(!a)return;let c;for(let u=0;u{c||i.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let o=e[r.join(",")]=new pr(r.indexOf(t.length-1)>-1);for(let s=0;s-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:ng(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new rt(this,this.computeAttrs(e),M.from(n),ne.setFrom(r))}createChecked(e=null,n,r){return n=M.from(n),this.checkContent(n),new rt(this,this.computeAttrs(e),n,ne.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=M.from(n),n.size){let s=this.contentMatch.fillBefore(n);if(!s)return null;n=s.append(n)}let i=this.contentMatch.matchFragment(n),o=i&&i.fillBefore(M.empty,!0);return o?new rt(this,e,n.append(o),ne.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;nr[o]=new t(o,n,s));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 EM(t,e,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 ${e} on type ${t}, got ${o}`)}}var Fc=class{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?EM(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}},Eo=class t{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=ig(e,i.attrs),this.excluded=null;let o=tg(this.attrs);this.instance=o?new ne(this,o):null}create(e=null){return!e&&this.instance?this.instance:new ne(this,ng(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((o,s)=>r[o]=new t(o,i++,n,s)),r}removeFromSet(e){for(var n=0;n-1}},ha=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in e)n[i]=e[i];n.nodes=Rc.from(e.nodes),n.marks=Rc.from(e.marks||{}),this.nodes=Mo.compile(this.spec.nodes,this),this.marks=Eo.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let o=this.nodes[i],s=o.spec.content||"",a=o.spec.marks;if(o.contentMatch=r[s]||(r[s]=pr.parse(s,this.nodes)),o.inlineContent=o.contentMatch.inlineContent,o.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!o.isInline||!o.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=o}o.markSet=a=="_"?null:a?Fm(this,a.split(" ")):a==""||!o.inlineContent?[]:null}for(let i in this.marks){let o=this.marks[i],s=o.spec.excludes;o.excluded=s==null?[o]:s==""?[]:Fm(this,s.split(" "))}this.nodeFromJSON=i=>rt.fromJSON(this,i),this.markFromJSON=i=>ne.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Mo){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,i)}text(e,n){let r=this.nodes.text;return new Pc(r,r.defaultAttrs,e,ne.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}};function Fm(t,e){let n=[];for(let r=0;r-1)&&n.push(s=l)}if(!s)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function TM(t){return t.tag!=null}function vM(t){return t.style!=null}var wt=class t{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(TM(i))this.tags.push(i);else if(vM(i)){let o=/[^=]*/.exec(i.style)[0];r.indexOf(o)<0&&r.push(o),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let o=e.nodes[i.node];return o.contentMatch.matchType(o)})}parse(e,n={}){let r=new ma(this,n,!1);return r.addAll(e,ne.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new ma(this,n,!0);return r.addAll(e,ne.none,n.from,n.to),R.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=n))){if(s.getAttrs){let l=s.getAttrs(n);if(l===!1)continue;s.attrs=l||void 0}return s}}}static schemaRules(e){let n=[];function r(i){let o=i.priority==null?50:i.priority,s=0;for(;s{r(s=_m(s)),s.mark||s.ignore||s.clearMark||(s.mark=i)})}for(let i in e.nodes){let o=e.nodes[i].spec.parseDOM;o&&o.forEach(s=>{r(s=_m(s)),s.node||s.ignore||s.mark||(s.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new t(e,t.schemaRules(e)))}},og={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},AM={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},sg={ol:!0,ul:!0},To=1,zc=2,Co=4;function zm(t,e,n){return e!=null?(e?To:0)|(e==="full"?zc:0):t&&t.whitespace=="pre"?To|zc:n&~Co}var ui=class{constructor(e,n,r,i,o,s){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=s,this.content=[],this.activeMarks=ne.none,this.match=o||(s&Co?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(M.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&To)){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=M.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(M.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!og.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},ma=class{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,o,s=zm(null,n.preserveWhitespace,0)|(r?Co:0);i?o=new ui(i.type,i.attrs,ne.none,!0,n.topMatch||i.type.contentMatch,s):r?o=new ui(null,null,ne.none,!0,null,s):o=new ui(e.schema.topNodeType,null,ne.none,!0,null,s),this.nodes=[o],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,i=this.top,o=i.options&zc?"full":this.localPreserveWS||(i.options&To)>0,{schema:s}=this.parser;if(o==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(o)if(o==="full")r=r.replace(/\r\n?/g,` -`);else if(s.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(s.linebreakReplacement.create())){let a=r.split(/\r?\n|\r/);for(let l=0;l!l.clearMark(c)):n=n.concat(this.parser.schema.marks[l.mark].create(l.attrs)),l.consuming===!1)a=l;else break}}return n}addElementByRule(e,n,r,i){let o,s;if(n.node)if(s=this.parser.schema.nodes[n.node],s.isLeaf)this.insertNode(s.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let l=this.enter(s,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 a=this.top;if(s&&s.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(l=>this.insertNode(l,r,!1));else{let l=e;typeof n.contentElement=="string"?l=e.querySelector(n.contentElement):typeof n.contentElement=="function"?l=n.contentElement(e):n.contentElement&&(l=n.contentElement),this.findAround(e,l,!0),this.addAll(l,r),this.findAround(e,l,!1)}o&&this.sync(a)&&this.open--}addAll(e,n,r,i){let o=r||0;for(let s=r?e.childNodes[r]:e.firstChild,a=i==null?null:e.childNodes[i];s!=a;s=s.nextSibling,++o)this.findAtPoint(e,o),this.addDOM(s,n);this.findAtPoint(e,o)}findPlace(e,n,r){let i,o;for(let s=this.open,a=0;s>=0;s--){let l=this.nodes[s],c=l.findWrapping(e);if(c&&(!i||i.length>c.length+a)&&(i=c,o=l,!c.length))break;if(l.solid){if(r)break;a+=2}}if(!i)return null;this.sync(o);for(let s=0;s(s.type?s.type.allowsMarkType(c.type):$m(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new ui(e,n,l,i,null,a)),this.open++,r}closeExtra(e=!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(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=To)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(i?0:1),s=(a,l)=>{for(;a>=0;a--){let c=n[a];if(c==""){if(a==n.length-1||a==0)continue;for(;l>=o;l--)if(s(a-1,l))return!0;return!1}else{let u=l>0||l==0&&i?this.nodes[l].type:r&&l>=o?r.node(l-o).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;l--}}return!0};return s(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.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 IM(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&sg.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function NM(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function _m(t){let e={};for(let n in t)e[n]=t[n];return e}function $m(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let o=[],s=a=>{o.push(a);for(let l=0;l{if(o.length||s.marks.length){let a=0,l=0;for(;a=0;i--){let o=this.serializeMark(e.marks[i],e.isInline,n);o&&((o.contentDOM||o.dom).appendChild(r),r=o.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&ua(ca(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return typeof n=="string"?{dom:e.createTextNode(n)}:ua(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new t(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=Hm(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return Hm(e.marks)}};function Hm(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function ca(t){return t.document||window.document}var Wm=new WeakMap;function RM(t){let e=Wm.get(t);return e===void 0&&Wm.set(t,e=OM(t)),e}function OM(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let s=i.indexOf(" ");s>0&&(n=i.slice(0,s),i=i.slice(s+1));let a,l=n?t.createElementNS(n,i):t.createElement(i),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let f in c)if(c[f]!=null){let d=f.indexOf(" ");d>0?l.setAttributeNS(f.slice(0,d),f.slice(d+1),c[f]):f=="style"&&l.style?l.style.cssText=c[f]:l.setAttribute(f,c[f])}}for(let f=u;fu)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(t.createTextNode(d));else{let{dom:p,contentDOM:h}=ua(t,d,n,r);if(l.appendChild(p),h){if(a)throw new RangeError("Multiple content holes");a=h}}}return{dom:l,contentDOM:a}}var cg=65535,ug=Math.pow(2,16);function DM(t,e){return t+e*ug}function ag(t){return t&cg}function LM(t){return(t-(t&cg))/ug}var fg=1,dg=2,ga=4,pg=8,Io=class{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&pg)>0}get deletedBefore(){return(this.delInfo&(fg|ga))>0}get deletedAfter(){return(this.delInfo&(dg|ga))>0}get deletedAcross(){return(this.delInfo&ga)>0}},sn=class t{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&t.empty)return t.empty}recover(e){let n=0,r=ag(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[a+o],u=this.ranges[a+s],f=l+c;if(e<=f){let d=c?e==l?-1:e==f?1:n:n,p=l+i+(d<0?0:u);if(r)return p;let h=e==(n<0?l:f)?null:DM(a/3,e-l),m=e==l?dg:e==f?fg:ga;return(n<0?e!=l:e!=f)&&(m|=pg),new Io(p,m,h)}i+=u-c}return r?e+i:new Io(e+i,0,null)}touches(e,n){let r=0,i=ag(n),o=this.inverted?2:1,s=this.inverted?1:2;for(let a=0;ae)break;let c=this.ranges[a+o],u=l+c;if(e<=u&&a==i*3)return!0;r+=this.ranges[a+s]-c}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,o=0;i=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new t;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;ro&&l!s.isAtom||!a.type.allowsMarkType(this.mark.type)?s:s.mark(this.mark.addToSet(s.marks)),i),n.openStart,n.openEnd);return Fe.fromReplace(e,this.from,this.to,o)}invert(){return new mr(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};Re.jsonID("addMark",hr);var mr=class t extends Re{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new R(Vc(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return Fe.fromReplace(e,this.from,this.to,r)}invert(){return new hr(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};Re.jsonID("removeMark",mr);var Ro=class t extends Re{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Fe.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Fe.fromReplace(e,this.pos,this.pos+1,new R(M.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.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 t(n.pos,r.pos,i,o,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,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 t(n.from,n.to,n.gapFrom,n.gapTo,R.fromJSON(e,n.slice),n.insert,!!n.structure)}};Re.jsonID("replaceAround",ze);function Wc(t,e,n){let r=t.resolve(e),i=n-e,o=r.depth;for(;i>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,i--;if(i>0){let s=r.node(o).maybeChild(r.indexAfter(o));for(;i>0;){if(!s||s.isLeaf)return!0;s=s.firstChild,i--}}return!1}function PM(t,e,n,r){let i=[],o=[],s,a;t.doc.nodesBetween(e,n,(l,c,u)=>{if(!l.isInline)return;let f=l.marks;if(!r.isInSet(f)&&u.type.allowsMarkType(r.type)){let d=Math.max(c,e),p=Math.min(c+l.nodeSize,n),h=r.addToSet(f);for(let m=0;mt.step(l)),o.forEach(l=>t.step(l))}function BM(t,e,n,r){let i=[],o=0;t.doc.nodesBetween(e,n,(s,a)=>{if(!s.isInline)return;o++;let l=null;if(r instanceof Eo){let c=s.marks,u;for(;u=r.isInSet(c);)(l||(l=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(s.marks)&&(l=[r]):l=s.marks;if(l&&l.length){let c=Math.min(a+s.nodeSize,n);for(let u=0;ut.step(new mr(s.from,s.to,s.style)))}function qc(t,e,n,r=n.contentMatch,i=!0){let o=t.doc.nodeAt(e),s=[],a=e+1;for(let l=0;l=0;l--)t.step(s[l])}function FM(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function gr(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,o=0;;--r){let s=t.$from.node(r),a=t.$from.index(r)+i,l=t.$to.indexAfter(r)-o;if(rn;h--)m||r.index(h)>0?(m=!0,u=M.from(r.node(h).copy(u)),f++):l--;let d=M.empty,p=0;for(let h=o,m=!1;h>n;h--)m||i.after(h+1)=0;s--){if(r.size){let a=n[s].type.contentMatch.matchFragment(r);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=M.from(n[s].type.create(n[s].attrs,r))}let i=e.start,o=e.end;t.step(new ze(i,o,i,o,new R(r,0,0),n.length,!0))}function WM(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=t.steps.length;t.doc.nodesBetween(e,n,(s,a)=>{let l=typeof i=="function"?i(s):i;if(s.isTextblock&&!s.hasMarkup(r,l)&&jM(t.doc,t.mapping.slice(o).map(a),r)){let c=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",h=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!h?c=!1:!p&&h&&(c=!0)}c===!1&&mg(t,s,a,o),qc(t,t.mapping.slice(o).map(a,1),r,void 0,c===null);let u=t.mapping.slice(o),f=u.map(a,1),d=u.map(a+s.nodeSize,1);return t.step(new ze(f,d,f+1,d-1,new R(M.from(r.create(l,null,s.marks)),0,0),1,!0)),c===!0&&hg(t,s,a,o),!1}})}function hg(t,e,n,r){e.forEach((i,o)=>{if(i.isText){let s,a=/\r?\n|\r/g;for(;s=a.exec(i.text);){let l=t.mapping.slice(r).map(n+1+o+s.index);t.replaceWith(l,l+1,e.type.schema.linebreakReplacement.create())}}})}function mg(t,e,n,r){e.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let s=t.mapping.slice(r).map(n+1+o);t.replaceWith(s,s+1,e.type.schema.text(` -`))}})}function jM(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function VM(t,e,n,r,i){let o=t.doc.nodeAt(e);if(!o)throw new RangeError("No node at given position");n||(n=o.type);let s=n.create(r,null,i||o.marks);if(o.isLeaf)return t.replaceWith(e,e+o.nodeSize,s);if(!n.validContent(o.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new ze(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new R(M.from(s),0,0),1,!0))}function kr(t,e,n=1,r){let i=t.resolve(e),o=i.depth-n,s=r&&r[r.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!s.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,u=n-2;c>o;c--,u--){let f=i.node(c),d=i.index(c);if(f.type.spec.isolating)return!1;let p=f.content.cutByIndex(d,f.childCount),h=r&&r[u+1];h&&(p=p.replaceChild(0,h.type.create(h.attrs)));let m=r&&r[u]||f;if(!f.canReplace(d+1,f.childCount)||!m.type.validContent(p))return!1}let a=i.indexAfter(o),l=r&&r[0];return i.node(o).canReplaceWith(a,a,l?l.type:i.node(o+1).type)}function qM(t,e,n=1,r){let i=t.doc.resolve(e),o=M.empty,s=M.empty;for(let a=i.depth,l=i.depth-n,c=n-1;a>l;a--,c--){o=M.from(i.node(a).copy(o));let u=r&&r[c];s=M.from(u?u.type.create(u.attrs,s):i.node(a).copy(s))}t.step(new we(e,e,new R(o.append(s),n,n),!0))}function br(t,e){let n=t.resolve(e),r=n.index();return UM(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function KM(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;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;s--){let a=s==r.depth?0:r.pos<=(r.start(s+1)+r.end(s+1))/2?-1:1,l=r.index(s)+(a>0?1:0),c=r.node(s),u=!1;if(o==1)u=c.canReplace(l,l,i);else{let f=c.contentMatchAt(l).findWrapping(i.firstChild.type);u=f&&c.canReplaceWith(l,l,f[0])}if(u)return a==0?r.pos:a<0?r.before(s+1):r.after(s+1)}return null}function Oo(t,e,n=e,r=R.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),o=t.resolve(n);return yg(i,o,r)?new we(e,n,r):new jc(i,o,r).fit()}function yg(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}var jc=class{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=M.empty;for(let i=0;i<=e.depth;i++){let o=e.node(i);this.frontier.push({type:o.type,match:o.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=M.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let o=this.placed,s=r.depth,a=i.depth;for(;s&&a&&o.childCount==1;)o=o.firstChild.content,s--,a--;let l=new R(o,s,a);return e>-1?new ze(r.pos,e,this.$to.pos,this.$to.end(),l,n):l.size||r.pos!=this.$to.pos?new we(r.pos,i.pos,l):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),o.type.spec.isolating&&i<=r){e=r;break}n=o.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let i,o=null;r?(o=$c(this.unplaced.content,r-1).firstChild,i=o.content):i=this.unplaced.content;let s=i.firstChild;for(let a=this.depth;a>=0;a--){let{type:l,match:c}=this.frontier[a],u,f=null;if(n==1&&(s?c.matchType(s.type)||(f=c.fillBefore(M.from(s),!1)):o&&l.compatibleContent(o.type)))return{sliceDepth:r,frontierDepth:a,parent:o,inject:f};if(n==2&&s&&(u=c.findWrapping(s.type)))return{sliceDepth:r,frontierDepth:a,parent:o,wrap:u};if(o&&c.matchType(o.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=$c(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new R(e,n+1,Math.max(r,i.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=$c(e,n);if(i.childCount<=1&&n>0){let o=e.size-n<=n+i.size;this.unplaced=new R(vo(e,n-1,1),n-1,o?n-1:r)}else this.unplaced=new R(vo(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:i,wrap:o}){for(;this.depth>n;)this.closeFrontierNode();if(o)for(let m=0;m1||l==0||m.content.size)&&(f=g,u.push(kg(m.mark(d.allowedMarks(m.marks)),c==1?l:0,c==a.childCount?p:-1)))}let h=c==a.childCount;h||(p=-1),this.placed=Ao(this.placed,n,M.from(u)),this.frontier[n].match=f,h&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=a;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],o=n=0;a--){let{match:l,type:c}=this.frontier[a],u=Hc(e,a,c,l,!0);if(!u||u.childCount)continue e}return{depth:n,fit:s,move:o?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Ao(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),o=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,o)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=Ao(this.placed,this.depth,M.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(M.empty,!0);n.childCount&&(this.placed=Ao(this.placed,this.frontier.length,n))}};function vo(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(vo(t.firstChild.content,e-1,n)))}function Ao(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Ao(t.lastChild.content,e-1,n)))}function $c(t,e){for(let n=0;n1&&(r=r.replaceChild(0,kg(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(M.empty,!0)))),t.copy(r)}function Hc(t,e,n,r,i){let o=t.node(e),s=i?t.indexAfter(e):t.index(e);if(s==o.childCount&&!n.compatibleContent(o.type))return null;let a=r.fillBefore(o.content,!0,s);return a&&!XM(n,o.content,s)?a:null}function XM(t,e,n){for(let r=n;r0;d--,p--){let h=i.node(d).type.spec;if(h.defining||h.definingAsContext||h.isolating)break;s.indexOf(d)>-1?a=d:i.before(d)==p&&s.splice(1,0,-d)}let l=s.indexOf(a),c=[],u=r.openStart;for(let d=r.content,p=0;;p++){let h=d.firstChild;if(c.push(h),p==r.openStart)break;d=h.content}for(let d=u-1;d>=0;d--){let p=c[d],h=YM(p.type);if(h&&!p.sameMarkup(i.node(Math.abs(a)-1)))u=d;else if(h||!p.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let p=(d+u+1)%(r.openStart+1),h=c[p];if(h)for(let m=0;m=0&&(t.replace(e,n,r),!(t.steps.length>f));d--){let p=s[d];p<0||(e=i.before(p),n=o.after(p))}}function bg(t,e,n,r,i){if(er){let o=i.contentMatchAt(0),s=o.fillBefore(t).append(t);t=s.append(o.matchFragment(s).fillBefore(M.empty,!0))}return t}function ZM(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=GM(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new R(M.from(r),0,0))}function eE(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let s=r.sharedDepth(n),a=!1;for(let l=r.depth;l>s;l--)r.node(l).type.spec.isolating&&(a=!0);for(let l=i.depth;l>s;l--)i.node(l).type.spec.isolating&&(a=!0);if(!a){for(let l=r.depth;l>0&&e==r.start(l);l--)e=r.before(l);for(let l=i.depth;l>0&&n==i.start(l);l--)n=i.before(l);r=t.doc.resolve(e),i=t.doc.resolve(n)}}let o=xg(r,i);for(let s=0;s0&&(l||r.node(a-1).canReplace(r.index(a-1),i.indexAfter(a-1))))return t.delete(r.before(a),i.after(a))}for(let s=1;s<=r.depth&&s<=i.depth;s++)if(e-r.start(s)==r.depth-s&&n>r.end(s)&&i.end(s)-n!=i.depth-s&&r.start(s-1)==i.start(s-1)&&r.node(s-1).canReplace(r.index(s-1),i.index(s-1)))return t.delete(r.before(s),n);t.delete(e,n)}function xg(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let o=t.start(i);if(oe.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(o==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==o-1)&&n.push(i)}return n}var ya=class t extends Re{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return Fe.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 Fe.fromReplace(e,this.pos,this.pos+1,new R(M.from(i),0,n.isLeaf?0:1))}getMap(){return sn.empty}invert(e){return new t(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new t(n.pos,n.attr,n.value)}};Re.jsonID("attr",ya);var ka=class t extends Re{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return Fe.ok(r)}getMap(){return sn.empty}invert(e){return new t(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new t(n.attr,n.value)}};Re.jsonID("docAttr",ka);var di=class extends Error{};di=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};di.prototype=Object.create(Error.prototype);di.prototype.constructor=di;di.prototype.name="TransformError";var pi=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new No}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new di(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r{e=Math.min(e,a),n=Math.max(n,l)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=R.empty){let i=Oo(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new R(M.from(r),0,0))}delete(e,n){return this.replace(e,n,R.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return QM(this,e,n,r),this}replaceRangeWith(e,n,r){return ZM(this,e,n,r),this}deleteRange(e,n){return eE(this,e,n),this}lift(e,n){return zM(this,e,n),this}join(e,n=1){return JM(this,e,n),this}wrap(e,n){return HM(this,e,n),this}setBlockType(e,n=e,r,i=null){return WM(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return VM(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new ya(e,n,r)),this}setDocAttribute(e,n){return this.step(new ka(e,n)),this}addNodeMark(e,n){return this.step(new Ro(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof ne)n.isInSet(r.marks)&&this.step(new fi(e,n));else{let i=r.marks,o,s=[];for(;o=n.isInSet(i);)s.push(new fi(e,o)),i=o.removeFromSet(i);for(let a=s.length-1;a>=0;a--)this.step(s[a])}return this}split(e,n=1,r){return qM(this,e,n,r),this}addMark(e,n,r){return PM(this,e,n,r),this}removeMark(e,n,r){return BM(this,e,n,r),this}clearIncompatible(e,n,r){return qc(this,e,n,r),this}};var Kc=Object.create(null),$=class{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new On(e.min(n),e.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 e=this.ranges;for(let n=0;n=0;o--){let s=n<0?hi(e.node(0),e.node(o),e.before(o+1),e.index(o),n,r):hi(e.node(0),e.node(o),e.after(o+1),e.index(o)+1,n,r);if(s)return s}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new mt(e.node(0))}static atStart(e){return hi(e,e,0,0,1)||new mt(e)}static atEnd(e){return hi(e,e,e.content.size,e.childCount,-1)||new mt(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Kc[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in Kc)throw new RangeError("Duplicate use of selection JSON ID "+e);return Kc[e]=n,n.prototype.jsonID=e,n}getBookmark(){return B.between(this.$anchor,this.$head).getBookmark()}};$.prototype.visible=!0;var On=class{constructor(e,n){this.$from=e,this.$to=n}},wg=!1;function Cg(t){!wg&&!t.parent.inlineContent&&(wg=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var B=class t extends ${constructor(e,n=e){Cg(e),Cg(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return $.near(r);let i=e.resolve(n.map(this.anchor));return new t(i.parent.inlineContent?i:r,r)}replace(e,n=R.empty){if(super.replace(e,n),n==R.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof t&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new xa(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new t(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let o=$.findFrom(n,r,!0)||$.findFrom(n,-r,!0);if(o)n=o.$head;else return $.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=($.findFrom(e,-r,!0)||$.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?s=0;s+=i){let a=e.child(s);if(a.isAtom){if(!o&&H.isSelectable(a))return H.create(t,n-(i<0?a.nodeSize:0))}else{let l=hi(t,a,n+i,i<0?a.childCount:0,i,o);if(l)return l}n+=a.nodeSize*i}return null}function Sg(t,e,n){let r=t.steps.length-1;if(r{s==null&&(s=u)}),t.setSelection($.near(t.doc.resolve(s),n))}var Mg=1,ba=2,Eg=4,Gc=class extends pi{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=ba,this}ensureMarks(e){return ne.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&ba)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~ba,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||ne.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let o=this.storedMarks;if(!o){let s=this.doc.resolve(n);o=r==n?s.marks():s.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(e,o)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection($.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Eg,this}get scrolledIntoView(){return(this.updated&Eg)>0}};function Tg(t,e){return!e||!t?t:t.bind(e)}var xr=class{constructor(e,n,r){this.name=e,this.init=Tg(n.init,r),this.apply=Tg(n.apply,r)}},nE=[new xr("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new xr("selection",{init(t,e){return t.selection||$.atStart(e.doc)},apply(t){return t.selection}}),new xr("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new xr("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})],Do=class{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=nE.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 xr(r.key,r.spec.state,r))})}},mi=class t{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],o=i.spec.state;o&&o.toJSON&&(n[r]=o.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Do(e.schema,e.plugins),o=new t(i);return i.fields.forEach(s=>{if(s.name=="doc")o.doc=rt.fromJSON(e.schema,n.doc);else if(s.name=="selection")o.selection=$.fromJSON(o.doc,n.selection);else if(s.name=="storedMarks")n.storedMarks&&(o.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let a in r){let l=r[a],c=l.spec.state;if(l.key==s.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(n,a)){o[s.name]=c.fromJSON.call(l,e,n[a],o);return}}o[s.name]=s.init(e,o)}}),o}};function vg(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=vg(i,e,{})),n[r]=i}return n}var X=class{constructor(e){this.spec=e,this.props={},e.props&&vg(e.props,this,this.props),this.key=e.key?e.key.key:Ag("plugin")}getState(e){return e[this.key]}},Uc=Object.create(null);function Ag(t){return t in Uc?t+"$"+ ++Uc[t]:(Uc[t]=0,t+"$")}var ee=class{constructor(e="key"){this.key=Ag(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var wa=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Ng(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}var Yc=(t,e,n)=>{let r=Ng(t,n);if(!r)return!1;let i=Zc(r);if(!i){let s=r.blockRange(),a=s&&gr(s);return a==null?!1:(e&&e(t.tr.lift(s,a).scrollIntoView()),!0)}let o=i.nodeBefore;if(Lg(t,i,e,-1))return!0;if(r.parent.content.size==0&&(gi(o,"end")||H.isSelectable(o)))for(let s=r.depth;;s--){let a=Oo(t.doc,r.before(s),r.after(s),R.empty);if(a&&a.slice.size1)break}return o.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView()),!0):!1},Rg=(t,e,n)=>{let r=Ng(t,n);if(!r)return!1;let i=Zc(r);return i?rE(t,i,e):!1};function rE(t,e,n){let r=e.nodeBefore,i=r,o=e.pos-1;for(;!i.isTextblock;o--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let s=e.nodeAfter,a=s,l=e.pos+1;for(;!a.isTextblock;l++){if(a.type.spec.isolating)return!1;let u=a.firstChild;if(!u)return!1;a=u}let c=Oo(t.doc,o,l,R.empty);if(!c||c.from!=o||c instanceof we&&c.slice.size>=l-o)return!1;if(n){let u=t.tr.step(c);u.setSelection(B.create(u.doc,o)),n(u.scrollIntoView())}return!0}function gi(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}var Qc=(t,e,n)=>{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;o=Zc(r)}let s=o&&o.nodeBefore;return!s||!H.isSelectable(s)?!1:(e&&e(t.tr.setSelection(H.create(t.doc,o.pos-s.nodeSize)).scrollIntoView()),!0)};function Zc(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function iE(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=iE(t,n);if(!r)return!1;let i=Og(r);if(!i)return!1;let o=i.nodeAfter;if(Lg(t,i,e,1))return!0;if(r.parent.content.size==0&&(gi(o,"start")||H.isSelectable(o))){let s=Oo(t.doc,r.before(),r.after(),R.empty);if(s&&s.slice.size{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),o=i&&gr(i);return o==null?!1:(e&&e(t.tr.lift(i,o).scrollIntoView()),!0)},aE=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(` -`).scrollIntoView()),!0)};function eu(t){for(let e=0;e{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),o=n.indexAfter(-1),s=eu(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let a=n.after(),l=t.tr.replaceWith(a,a,s.createAndFill());l.setSelection($.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},lE=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof mt||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=eu(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let o=n.before();if(kr(t.doc,o))return e&&e(t.tr.split(o).scrollIntoView()),!0}let r=n.blockRange(),i=r&&gr(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function uE(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof H&&e.selection.node.isBlock)return!r.parentOffset||!kr(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],s,a,l=!1,c=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){l=r.end(p)==r.pos+(r.depth-p),c=r.start(p)==r.pos-(r.depth-p),a=eu(r.node(p-1).contentMatchAt(r.indexAfter(p-1)));let m=t&&t(i.parent,l,r);o.unshift(m||(l&&a?{type:a}:null)),s=p;break}else{if(p==1)return!1;o.unshift(null)}let u=e.tr;(e.selection instanceof B||e.selection instanceof mt)&&u.deleteSelection();let f=u.mapping.map(r.pos),d=kr(u.doc,f,o.length,o);if(d||(o[0]=a?{type:a}:null,d=kr(u.doc,f,o.length,o)),!d)return!1;if(u.split(f,o.length,o),!l&&c&&r.node(s).type!=a){let p=u.mapping.map(r.before(s)),h=u.doc.resolve(p);a&&r.node(s-1).canReplaceWith(h.index(),h.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(s)),a)}return n&&n(u.scrollIntoView()),!0}}var fE=uE();var dE=(t,e)=>(e&&e(t.tr.setSelection(new mt(t.doc))),!0);function pE(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,o=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||br(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Lg(t,e,n,r){let i=e.nodeBefore,o=e.nodeAfter,s,a,l=i.type.spec.isolating||o.type.spec.isolating;if(!l&&pE(t,e,n))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(s=(a=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&a.matchType(s[0]||o.type).validEnd){if(n){let p=e.pos+o.nodeSize,h=M.empty;for(let y=s.length-1;y>=0;y--)h=M.from(s[y].create(null,h));h=M.from(i.copy(h));let m=t.tr.step(new ze(e.pos-1,p,e.pos,p,new R(h,1,0),s.length,!0)),g=m.doc.resolve(p+2*s.length);g.nodeAfter&&g.nodeAfter.type==i.type&&br(m.doc,g.pos)&&m.join(g.pos),n(m.scrollIntoView())}return!0}let u=o.type.spec.isolating||r>0&&l?null:$.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),d=f&&gr(f);if(d!=null&&d>=e.depth)return n&&n(t.tr.lift(f,d).scrollIntoView()),!0;if(c&&gi(o,"start",!0)&&gi(i,"end")){let p=i,h=[];for(;h.push(p),!p.isTextblock;)p=p.lastChild;let m=o,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,m.content)){if(n){let y=M.empty;for(let C=h.length-1;C>=0;C--)y=M.from(h[C].copy(y));let b=t.tr.step(new ze(e.pos-h.length,e.pos+o.nodeSize,e.pos+g,e.pos+o.nodeSize-g,new R(y,h.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function Pg(t){return function(e,n){let r=e.selection,i=t<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(e.tr.setSelection(B.create(e.doc,t<0?i.start(o):i.end(o)))),!0):!1}}var hE=Pg(-1),mE=Pg(1);function yi(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o),a=s&&yr(s,t,e);return a?(r&&r(n.tr.wrap(s,a).scrollIntoView()),!0):!1}}function Dn(t,e=null){return function(n,r){let i=!1;for(let o=0;o{if(i)return!1;if(!(!l.isTextblock||l.hasMarkup(t,e)))if(l.type==t)i=!0;else{let u=n.doc.resolve(c),f=u.index();i=u.parent.canReplaceWith(f,f+1,t)}})}if(!i)return!1;if(r){let o=n.tr;for(let s=0;s{if(a||!r&&l.isAtom&&l.isInline&&c>=o.pos&&c+l.nodeSize<=s.pos)return!1;a=l.inlineContent&&l.type.allowsMarkType(n)}),a)return!0}return!1}function yE(t){let e=[];for(let n=0;n{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos)return s+1>r.pos&&e.push(new On(r,r.doc.resolve(s+1))),r=r.doc.resolve(s+1+o.content.size),!1}),r.poss.doc.rangeHasMark(p.$from.pos,p.$to.pos,t)):f=!u.every(p=>{let h=!1;return d.doc.nodesBetween(p.$from.pos,p.$to.pos,(m,g,y)=>{if(h)return!1;h=!t.isInSet(m.marks)&&!!y&&y.type.allowsMarkType(t)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,p.$from.pos-g),Math.min(m.nodeSize,p.$to.pos-g))))}),!h});for(let p=0;p0&&(o=n[0].slice(s-a,s)+o,r=i)}return e.tr.insertText(o,r,i)}}var zg=(t,e)=>{let n=t.plugins;for(let r=0;r=0;l--)s.step(a.steps[l].invert(a.docs[l]));if(o.text){let l=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,t.schema.text(o.text,l))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},$2=new be(/--$/,"\u2014",{inCodeMark:!1}),H2=new be(/\.\.\.$/,"\u2026",{inCodeMark:!1}),W2=new be(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"\u201C",{inCodeMark:!1}),j2=new be(/"$/,"\u201D",{inCodeMark:!1}),V2=new be(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"\u2018",{inCodeMark:!1}),q2=new be(/'$/,"\u2019",{inCodeMark:!1});function Ca(t,e,n=null,r){return new be(t,(i,o,s,a)=>{let l=n instanceof Function?n(o):n,c=i.tr.delete(s,a),u=c.doc.resolve(s),f=u.blockRange(),d=f&&yr(f,e,l);if(!d)return null;c.wrap(f,d);let p=c.doc.resolve(s-1).nodeBefore;return p&&p.type==e&&br(c.doc,s-1)&&(!r||r(o,p))&&c.join(s-1),c})}function nu(t,e,n=null){return new be(t,(r,i,o,s)=>{let a=r.doc.resolve(o),l=n instanceof Function?n(i):n;return a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),e)?r.tr.delete(o,s).setBlockType(o,o,e,l):null})}var Pn=typeof navigator<"u"?navigator:null,_g=typeof document<"u"?document:null,Bn=Pn&&Pn.userAgent||"",iu=/Edge\/(\d+)/.exec(Bn),jg=/MSIE \d/.exec(Bn),ou=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Bn),au=!!(jg||ou||iu),Y2=jg?document.documentMode:ou?+ou[1]:iu?+iu[1]:0,xE=!au&&/gecko\/(\d+)/i.test(Bn),Q2=xE&&+(/Firefox\/(\d+)/.exec(Bn)||[0,0])[1],su=!au&&/Chrome\/(\d+)/.exec(Bn),wE=!!su,Z2=su?+su[1]:0,CE=!au&&!!Pn&&/Apple Computer/.test(Pn.vendor),SE=CE&&(/Mobile\/\w+/.test(Bn)||!!Pn&&Pn.maxTouchPoints>2),eH=SE||(Pn?/Mac/.test(Pn.platform):!1),ME=/Android \d/.test(Bn),EE=!!_g&&"webkitFontSmoothing"in _g.documentElement.style,tH=EE?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function ru(t,e,n,r,i,o){if(t.composing)return!1;let s=t.state,a=s.doc.resolve(e);if(a.parent.type.spec.code)return!1;let l=a.parent.textBetween(Math.max(0,a.parentOffset-500),a.parentOffset,void 0,"\uFFFC")+r;for(let c of i){let u=c,f=u.match.exec(l),d=f&&f[0]&&u.handler(s,f,e-(f[0].length-r.length),n);if(d)return u.undoable!==!1&&d.setMeta(o,{transform:d,from:e,to:n,text:r}),t.dispatch(d),!0}return!1}var TE=new ee("MILKDOWN_CUSTOM_INPUTRULES");function Vg({rules:t}){let e=new X({key:TE,isInputRules:!0,state:{init(){return null},apply(n,r){let i=n.getMeta(this);return i||(n.selectionSet||n.docChanged?null:r)}},props:{handleTextInput(n,r,i,o){return ru(n,r,i,o,t,e)},handleDOMEvents:{compositionend:n=>(setTimeout(()=>{let{$cursor:r}=n.state.selection;r&&ru(n,r.pos,r.pos,"",t,e)}),!1),keydown:(n,r)=>!(ME&&wE&&r.key==="Enter")||n.composing?!1:n.someProp("handleKeyDown",i=>i(n,r))?(r.preventDefault(),!0):!1},handleKeyDown(n,r){if(r.key!=="Enter")return!1;let{$cursor:i}=n.state.selection;return i?ru(n,i.pos,i.pos,` -`,t,e):!1}}});return e}function ln(t,e,n={}){return new be(t,(r,i,o,s)=>{var a,l,c,u;let{tr:f}=r,d=i.length,p=i[d-1],h=i[0],m=[],g,y={group:p,fullMatch:h,start:o,end:s},b=(a=n.updateCaptured)==null?void 0:a.call(n,y);if(Object.assign(y,b),{group:p,fullMatch:h,start:o,end:s}=y,h===null||p?.trim()==="")return null;if(p){let C=h.search(/\S/),v=o+h.indexOf(p),A=v+p.length;m=(l=f.storedMarks)!=null?l:[],Ao&&f.delete(o+C,v),g=o+C+p.length;let w=(c=n.getAttr)==null?void 0:c.call(n,i);f.addMark(o,g,e.create(w)),f.setStoredMarks(m),(u=n.beforeDispatch)==null||u.call(n,{match:i,start:o,end:s,tr:f})}return f})}function ki(t,e,n={}){return new be(t,(r,i,o,s)=>{var a,l,c;let{tr:u}=r,f=i[1],d=i[0],p={group:f,fullMatch:d,start:o,end:s},h=(a=n.updateCaptured)==null?void 0:a.call(n,p);if(Object.assign(p,h),{group:f,fullMatch:d,start:o,end:s}=p,d===null||!f||f.trim()==="")return null;let m=(l=n.getAttr)==null?void 0:l.call(n,i),g=e.createAndFill(m);return g&&(u.replaceRangeWith(e.isBlock?u.doc.resolve(o).before():o,s,g),(c=n.beforeDispatch)==null||c.call(n,{match:[d,f],start:o,end:s,tr:u})),u})}var vE=Object.defineProperty,AE=Object.defineProperties,IE=Object.getOwnPropertyDescriptors,$g=Object.getOwnPropertySymbols,NE=Object.prototype.hasOwnProperty,RE=Object.prototype.propertyIsEnumerable,Hg=(t,e,n)=>e in t?vE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,OE=(t,e)=>{for(var n in e||(e={}))NE.call(e,n)&&Hg(t,n,e[n]);if($g)for(var n of $g(e))RE.call(e,n)&&Hg(t,n,e[n]);return t},DE=(t,e)=>AE(t,IE(e));function Wg(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function qg(t,e,n){let i=t.state.doc.content.size,o=Wg(e,0,i),s=Wg(n,0,i),a=t.coordsAtPos(o),l=t.coordsAtPos(s,-1),c=Math.min(a.top,l.top),u=Math.max(a.bottom,l.bottom),f=Math.min(a.left,l.left),d=Math.max(a.right,l.right),p=d-f,h=u-c,y={top:c,bottom:u,left:f,right:d,width:p,height:h,x:f,y:c};return DE(OE({},y),{toJSON:()=>y})}function lu(t){return Object.assign(Object.create(t),t).setTime(Date.now())}function LE(t,e){return Array.isArray(t)&&t.includes(e.type)||e.type===t}function Sa(t){if(t.content.childCount===1){let e=t.content.firstChild;if(e?.type.name==="text"&&e.marks.length===0)return e;if(e?.type.name==="paragraph"&&e.childCount===1){let n=e.firstChild;if(n?.type.name==="text"&&n.marks.length===0)return n}}return!1}function PE(t){return e=>{for(let n=e.depth;n>0;n-=1){let r=e.node(n);if(t(r)){let i=e.before(n),o=e.after(n);return{from:i,to:o,node:r}}}}}function Kg(t,e){return PE(n=>n.type===e)(t)}function Ug(t,e){let n=e.nodes[t];if(!n)throw ch("node",t);return n}function cu(t){return e=>{for(let n=e.depth;n>0;n--){let r=e.node(n);if(t(r))return{pos:e.before(n),start:e.start(n),depth:n,node:r}}}}function Jg(t){return e=>cu(t)(e.$from)}function Gg(t,e){if(!(t instanceof H))return;let{node:n,$from:r}=t;if(LE(e,n))return{node:n,pos:r.pos,start:r.start(r.depth),depth:r.depth}}var Xg=(t,e)=>{let{selection:n,doc:r}=t;if(n instanceof H)return{hasNode:n.node.type===e,pos:n.from,target:n.node};let{from:i,to:o}=n,s=!1,a=-1,l=null;return r.nodesBetween(i,o,(c,u)=>l?!1:c.type===e?(s=!0,a=u,l=c,!1):!0),{hasNode:s,pos:a,target:l}};var cn={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:"'"},Ea={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},BE=typeof navigator<"u"&&/Mac/.test(navigator.platform),FE=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(Ce=0;Ce<10;Ce++)cn[48+Ce]=cn[96+Ce]=String(Ce);var Ce;for(Ce=1;Ce<=24;Ce++)cn[Ce+111]="F"+Ce;var Ce;for(Ce=65;Ce<=90;Ce++)cn[Ce]=String.fromCharCode(Ce+32),Ea[Ce]=String.fromCharCode(Ce);var Ce;for(Ma in cn)Ea.hasOwnProperty(Ma)||(Ea[Ma]=cn[Ma]);var Ma;function Yg(t){var e=BE&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||FE&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?Ea:cn)[t.keyCode]||t.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}var zE=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),_E=typeof navigator<"u"&&/Win/.test(navigator.platform);function $E(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,i,o,s;for(let a=0;athis.elements.length,this.top=()=>this.elements.at(-1),this.push=t=>{this.top()?.push(t)},this.open=t=>{this.elements.push(t)},this.close=()=>{let t=this.elements.pop();if(!t)throw Vl();return t}}},WE=class ny extends ey{constructor(e,n,r){super(),this.type=e,this.content=n,this.attrs=r}push(e,...n){this.content.push(e,...n)}pop(){return this.content.pop()}static create(e,n,r){return new ny(e,n,r)}},ry=class extends ty{#t;static{this.create=(t,e)=>{let n=new this(t);return r=>(n.run(e,r),n.toDoc())}}constructor(t){super(),this.#t=ne.none,this.#e=e=>e.isText,this.#r=(e,n)=>{if(this.#e(e)&&this.#e(n)&&ne.sameSet(e.marks,n.marks))return this.schema.text(e.text+n.text,e.marks)},this.#n=e=>{let n=Object.values({...this.schema.nodes,...this.schema.marks}).find(r=>r.spec.parseMarkdown.match(e));if(!n)throw ah(e);return n},this.#s=e=>{let n=this.#n(e);n.spec.parseMarkdown.runner(this,e,n)},this.injectRoot=(e,n,r)=>(this.openNode(n,r),this.next(e.children),this),this.openNode=(e,n)=>(this.open(WE.create(e,[],n)),this),this.#o=()=>{this.#t=ne.none;let e=this.close();return this.#i(e.type,e.attrs,e.content)},this.closeNode=()=>{try{this.#o()}catch(e){console.error(e)}return this},this.#i=(e,n,r)=>{let i=e.createAndFill(n,r,this.#t);if(!i)throw sh(e,n,r);return this.push(i),i},this.addNode=(e,n,r)=>{try{this.#i(e,n,r)}catch(i){console.error(i)}return this},this.openMark=(e,n)=>{let r=e.create(n);return this.#t=r.addToSet(this.#t),this},this.closeMark=e=>(this.#t=e.removeFromSet(this.#t),this),this.addText=e=>{try{let n=this.top();if(!n)throw Vl();let r=n.pop(),i=this.schema.text(e,this.#t);if(!r)return n.push(i),this;let o=this.#r(r,i);return o?(n.push(o),this):(n.push(r,i),this)}catch(n){return console.error(n),this}},this.build=()=>{let e;do e=this.#o();while(this.size());return e},this.next=(e=[])=>([e].flat().forEach(n=>this.#s(n)),this),this.toDoc=()=>this.build(),this.run=(e,n)=>{let r=e.runSync(e.parse(n),n);return this.next(r),this},this.schema=t}#e;#r;#n;#s;#o;#i},Zg=class iy extends ey{constructor(e,n,r,i={}){super(),this.type=e,this.children=n,this.value=r,this.props=i,this.push=(o,...s)=>{this.children||(this.children=[]),this.children.push(o,...s)},this.pop=()=>this.children?.pop()}static{this.create=(e,n,r,i={})=>new iy(e,n,r,i)}},jE=t=>Object.prototype.hasOwnProperty.call(t,"size"),oy=class extends ty{#t;static{this.create=(t,e)=>{let n=new this(t);return r=>(n.run(r),n.toString(e))}}constructor(t){super(),this.#t=[],this.#e=e=>{let n=Object.values({...this.schema.nodes,...this.schema.marks}).find(r=>r.spec.toMarkdown.match(e));if(!n)throw lh(e.type);return n},this.#r=e=>this.#e(e).spec.toMarkdown.runner(this,e),this.#n=(e,n)=>this.#e(e).spec.toMarkdown.runner(this,e,n),this.#s=e=>{let n=o=>o.type.spec.priority??50,r=[...e].sort((o,s)=>n(o)-n(s)),i=[];return this.#t.forEach(({mark:o})=>{let s=r.findIndex(a=>a.eq(o));s>=0&&i.push(...r.splice(s,1))}),i.concat(r)},this.#o=e=>{let n=e?.marks,r=0;for(;rs.eq(i)))r++;else break}for(let i=this.#t.length-1;i>=r;i--)this.#f(this.#t[i].mark)},this.#i=(e,n)=>{this.#s(e.marks).every(r=>!this.#n(r,e))&&this.#r(e),this.#o(n)},this.#a=e=>{let{children:n}=e;return n&&(e.children=n.reduce((r,i,o)=>{if(o===0)return[i];let s=r.at(-1);if(s&&s.isMark&&i.isMark){let{children:a,...l}=i,{children:c,...u}=s;if(i.type===s.type&&a&&c&&JSON.stringify(l)===JSON.stringify(u)){let f={...u,children:[...c,...a]};return r.slice(0,-1).concat(this.#a(f))}}return r.concat(i)},[])),e},this.#l=e=>{let n={...e.props,type:e.type};return e.children&&(n.children=e.children),e.value&&(n.value=e.value),n},this.openNode=(e,n,r)=>(this.open(Zg.create(e,void 0,n,r)),this),this.#d=(e,n)=>{let r="",i="",o=e.children;if(o){let a=o[0],l=o.at(-1);if(l&&l.type==="text"&&l.value.endsWith(" ")){let c=l.value,u=c.trimEnd();i=c.slice(u.length),l.value=u}if(a&&a.type==="text"&&a.value.startsWith(" ")){let c=a.value,u=c.trimStart();r=c.slice(0,c.length-u.length),a.value=u}}r.length&&this.#u("text",void 0,r);let s=n();return i.length&&this.#u("text",void 0,i),s},this.#c=(e=!1)=>{let n=this.close(),r=()=>this.#u(n.type,n.children,n.value,n.props);return e?this.#d(n,r):r()},this.closeNode=()=>(this.#c(),this),this.#u=(e,n,r,i)=>{let o=Zg.create(e,n,r,i),s=this.#a(this.#l(o));return this.push(s),s},this.addNode=(e,n,r,i)=>(this.#u(e,n,r,i),this),this.#p=(e,n,r,i)=>this.#t.some(o=>o.mark.eq(e))?this:(this.#t.push({mark:e,spanning:r==null}),this.openNode(n,r,{...i,isMark:!0})),this.#f=e=>{let n=-1;for(let r=this.#t.length-1;r>=0;r--)if(this.#t[r].mark.eq(e)){n=r;break}n<0||(this.#t.splice(n,1),this.#c(!0))},this.withMark=(e,n,r,i)=>(this.#p(e,n,r,i),this),this.closeMark=e=>(this.#f(e),this),this.build=()=>{let e=null;do e=this.#c();while(this.size());return e},this.next=e=>jE(e)?(e.forEach((n,r,i)=>{this.#i(n,e.maybeChild(i+1)??void 0)}),this):(this.#i(e),this),this.toString=e=>e.stringify(this.build()),this.run=e=>(this.#t=[],this.next(e),this),this.schema=t}#e;#r;#n;#s;#o;#i;#a;#l;#d;#c;#u;#p;#f};var _e=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Ci=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e},yu=null,fn=function(t,e,n){let r=yu||(yu=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},VE=function(){yu=null},Ir=function(t,e,n,r){return n&&(sy(t,e,n,r,-1)||sy(t,e,n,r,1))},qE=/^(img|br|input|textarea|hr)$/i;function sy(t,e,n,r,i){for(var o;;){if(t==n&&e==r)return!0;if(e==(i<0?0:Mt(t))){let s=t.parentNode;if(!s||s.nodeType!=1||Ho(t)||qE.test(t.nodeName)||t.contentEditable=="false")return!1;e=_e(t)+(i<0?0:1),t=s}else if(t.nodeType==1){let s=t.childNodes[e+(i<0?-1:0)];if(s.nodeType==1&&s.contentEditable=="false")if(!((o=s.pmViewDesc)===null||o===void 0)&&o.ignoreForSelection)e+=i;else return!1;else t=s,e=i<0?Mt(t):0}else return!1}}function Mt(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function KE(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=Mt(t)}else if(t.parentNode&&!Ho(t))e=_e(t),t=t.parentNode;else return null}}function UE(t,e){for(;;){if(t.nodeType==3&&e2),St=Si||(Vt?/Mac/.test(Vt.platform):!1),zy=Vt?/Win/.test(Vt.platform):!1,dn=/Android \d/.test(Hn),Wo=!!ay&&"webkitFontSmoothing"in ay.documentElement.style,YE=Wo?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function QE(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function un(t,e){return typeof t=="number"?t:t[e]}function ZE(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function ly(t,e,n){if(!wu(e)&&e.left==0)return;let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,o=t.dom.ownerDocument;for(let s=n||t.dom;s;){if(s.nodeType!=1){s=Ci(s);continue}let a=s,l=a==o.body,c=l?QE(o):ZE(a),u=0,f=0;if(e.topc.bottom-un(r,"bottom")&&(f=e.bottom-e.top>c.bottom-c.top?e.top+un(i,"top")-c.top:e.bottom-c.bottom+un(i,"bottom")),e.leftc.right-un(r,"right")&&(u=e.right-c.right+un(i,"right")),u||f)if(l)o.defaultView.scrollBy(u,f);else{let p=a.scrollLeft,h=a.scrollTop;f&&(a.scrollTop+=f),u&&(a.scrollLeft+=u);let m=a.scrollLeft-p,g=a.scrollTop-h;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=l?"fixed":getComputedStyle(s).position;if(/^(fixed|sticky)$/.test(d))break;s=d=="absolute"?s.offsetParent:Ci(s)}}function eT(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let o=(e.left+e.right)/2,s=n+1;s=n-20){r=a,i=l.top;break}}return{refDOM:r,refTop:i,stack:_y(t.dom)}}function _y(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Ci(r));return e}function tT({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;$y(n,r==0?0:r-e)}function $y(t,e){for(let n=0;n=a){s=Math.max(h.bottom,s),a=Math.min(h.top,a);let m=h.left>e.left?h.left-e.left:h.right=(h.left+h.right)/2?1:0));continue}}else h.top>e.top&&!l&&h.left<=e.left&&h.right>=e.left&&(l=u,c={left:Math.max(h.left,Math.min(h.right,e.left)),top:h.top});!n&&(e.left>=h.right&&e.top>=h.top||e.left>=h.left&&e.top>=h.bottom)&&(o=f+1)}}return!n&&l&&(n=l,i=c,r=0),n&&n.nodeType==3?rT(n,i):!n||r&&n.nodeType==1?{node:t,offset:o}:Hy(n,i)}function rT(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let o=0;o=(s.left+s.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function Fu(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function iT(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left(s.left+s.right)/2?1:-1}return t.docView.posFromDOM(r,i,o)}function sT(t,e,n,r){let i=-1;for(let o=e,s=!1;o!=t.dom;){let a=t.docView.nearestDesc(o,!0),l;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((l=a.dom.getBoundingClientRect()).width||l.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!s&&l.left>r.left||l.top>r.top?i=a.posBefore:(!s&&l.right-1?i:t.docView.posFromDOM(e,n,-1)}function Wy(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top&&i++}let c;Wo&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?a=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(a=sT(t,r,i,e))}a==null&&(a=oT(t,s,e));let l=t.docView.nearestDesc(s,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function wu(t){return t.top=0&&i==r.nodeValue.length?(l--,u=1):n<0?l--:c++,Lo(Fn(fn(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&i&&(n<0||i==Mt(r))){let l=r.childNodes[i-1];if(l.nodeType==1)return du(l.getBoundingClientRect(),!1)}if(o==null&&i=0)}if(o==null&&i&&(n<0||i==Mt(r))){let l=r.childNodes[i-1],c=l.nodeType==3?fn(l,Mt(l)-(s?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return Lo(Fn(c,1),!1)}if(o==null&&i=0)}function Lo(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function du(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Vy(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function cT(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return Vy(t,e,()=>{let{node:o}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let a=t.docView.nearestDesc(o,!0);if(!a)break;if(a.node.isBlock){o=a.contentDOM||a.dom;break}o=a.dom.parentNode}let s=jy(t,i.pos,1);for(let a=o.firstChild;a;a=a.nextSibling){let l;if(a.nodeType==1)l=a.getClientRects();else if(a.nodeType==3)l=fn(a,0,a.nodeValue.length).getClientRects();else continue;for(let c=0;cu.top+1&&(n=="up"?s.top-u.top>(u.bottom-s.top)*2:u.bottom-s.bottom>(s.bottom-u.top)*2))return!1}}return!0})}var uT=/[\u0590-\u08ac]/;function fT(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,o=!i,s=i==r.parent.content.size,a=t.domSelection();return a?!uT.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?o:s:Vy(t,e,()=>{let{focusNode:l,focusOffset:c,anchorNode:u,anchorOffset:f}=t.domSelectionRange(),d=a.caretBidiLevel;a.modify("move",n,"character");let p=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:h,focusOffset:m}=t.domSelectionRange(),g=h&&!p.contains(h.nodeType==1?h:h.parentNode)||l==h&&c==m;try{a.collapse(u,f),l&&(l!=u||c!=f)&&a.extend&&a.extend(l,c)}catch{}return d!=null&&(a.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}var cy=null,uy=null,fy=!1;function dT(t,e,n){return cy==e&&uy==n?fy:(cy=e,uy=n,fy=n=="up"||n=="down"?cT(t,e,n):fT(t,e,n))}var Tt=0,dy=1,Sr=2,Dt=3,Nr=class{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=Tt,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n_e(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!1;break}if(o.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!0;break}if(o.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let o=this.getDesc(i),s;if(o&&(!n||o.node))if(r&&(s=o.nodeDOM)&&!(s.nodeType==1?s.contains(e.nodeType==1?e:e.parentNode):s==e))r=!1;else return o}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let i=e;i;i=i.parentNode){let o=this.getDesc(i);if(o)return o.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;ne||s instanceof Aa){i=e-o;break}o=a}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 Ta&&o.side>=0;r--);if(n<=0){let o,s=!0;for(;o=r?this.children[r-1]:null,!(!o||o.dom.parentNode==this.contentDOM);r--,s=!1);return o&&n&&s&&!o.border&&!o.domAtom?o.domFromPos(o.size,n):{node:this.contentDOM,offset:o?_e(o.dom)+1:0}}else{let o,s=!0;for(;o=r=u&&n<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(e,n,u);e=s;for(let f=a;f>0;f--){let d=this.children[f-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=_e(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>n||a==this.children.length-1)){n=c;for(let u=a+1;uh&&sn){let h=a;a=l,l=h}let p=document.createRange();p.setEnd(l.node,l.offset),p.setStart(a.node,a.offset),c.removeAllRanges(),c.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,i=0;i=r:er){let a=r+o.border,l=s-o.border;if(e>=a&&n<=l){this.dirty=e==r||n==s?Sr:dy,e==a&&n==l&&(o.contentLost||o.dom.parentNode!=this.contentDOM)?o.dirty=Dt:o.markDirty(e-a,n-a);return}else o.dirty=o.dom==o.contentDOM&&o.dom.parentNode==this.contentDOM&&!o.children.length?Sr:Dt}r=s}this.dirty=Sr}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Sr:dy;n.dirty{if(!o)return i;if(o.parent)return o.parent.posBeforeChild(o)})),!n.type.spec.raw){if(s.nodeType!=1){let a=document.createElement("span");a.appendChild(s),s=a}s.contentEditable="false",s.classList.add("ProseMirror-widget")}super(e,[],s,null),this.widget=n,this.widget=n,o=this}matchesWidget(e){return this.dirty==Tt&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},Cu=class extends Nr{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}},Er=class t extends Nr{constructor(e,n,r,i,o){super(e,[],r,i),this.mark=n,this.spec=o}static create(e,n,r,i){let o=i.nodeViews[n.type.name],s=o&&o(n,i,r);return(!s||!s.dom)&&(s=Ct.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new t(e,n,s.dom,s.contentDOM||s.dom,s)}parseRule(){return this.dirty&Dt||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Dt&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=Tt){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(o=Tu(o,0,e,r));for(let a=0;a{if(!l)return s;if(l.parent)return l.parent.posBeforeChild(l)},r,i),u=c&&c.dom,f=c&&c.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:f}=Ct.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!f&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let d=u;return u=Uy(u,r,n),c?l=new Su(e,n,r,i,u,f||null,d,c):n.isText?new va(e,n,r,i,u,d):new t(e,n,r,i,u,f||null,d)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>M.empty)}return e}matchesNode(e,n,r){return this.dirty==Tt&&e.eq(this.node)&&Ia(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,i=n,o=e.composing?this.localCompositionInfo(e,n):null,s=o&&o.pos>-1?o:null,a=o&&o.pos<0,l=new Eu(this,s&&s.node,e);gT(this.node,this.innerDeco,(c,u,f)=>{c.spec.marks?l.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!f&&l.syncToMarks(u==this.node.childCount?ne.none:this.node.child(u).marks,r,e,u),l.placeWidget(c,e,i)},(c,u,f,d)=>{l.syncToMarks(c.marks,r,e,d);let p;l.findNodeMatch(c,u,f,d)||a&&e.state.selection.from>i&&e.state.selection.to-1&&l.updateNodeAt(c,u,f,p,e)||l.updateNextNode(c,u,f,e,d,i)||l.addNode(c,u,f,e,i),i+=c.nodeSize}),l.syncToMarks([],r,e,0),this.node.isTextblock&&l.addTextblockHacks(),l.destroyRest(),(l.changed||this.dirty==Sr)&&(s&&this.protectLocalComposition(e,s),qy(this.contentDOM,this.children,e),Si&&yT(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof B)||rn+this.node.content.size)return null;let o=e.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let s=o.nodeValue,a=kT(this.node.content,s,r-n,i-n);return a<0?null:{node:o,pos:a,text:s}}else return{node:o,pos:-1,text:""}}protectLocalComposition(e,{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 s=new Cu(this,o,n,i);e.input.compositionNodes.push(s),this.children=Tu(this.children,r,r+i.length,e,s)}update(e,n,r,i){return this.dirty==Dt||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=Tt}updateOuterDeco(e){if(Ia(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Ky(this.dom,this.nodeDOM,Mu(this.outerDeco,this.node,n),Mu(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}};function py(t,e,n,r,i){Uy(r,e,t);let o=new $n(void 0,t,e,n,r,r,r);return o.contentDOM&&o.updateChildren(i,0),o}var va=class t extends $n{constructor(e,n,r,i,o,s){super(e,n,r,i,o,null,s)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,i){return this.dirty==Dt||this.dirty!=Tt&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Tt||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=Tt,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let i=this.node.cut(e,n),o=document.createTextNode(i.text);return new t(this.parent,i,this.outerDeco,this.innerDeco,o,o)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Dt)}get domAtom(){return!1}isText(e){return this.node.text==e}},Aa=class extends Nr{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Tt&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}},Su=class extends $n{constructor(e,n,r,i,o,s,a,l){super(e,n,r,i,o,s,a),this.spec=l}update(e,n,r,i){if(this.dirty==Dt)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let o=this.spec.update(e,n,r);return o&&this.updateInner(e,n,r,i),o}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}};function qy(t,e,n){let r=t.firstChild,i=!1;for(let o=0;o>1,a=Math.min(s,e.length);for(;o-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let u=Er.create(this.top,e[s],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,s++}}findNodeMatch(e,n,r,i){let o=-1,s;if(i>=this.preMatch.index&&(s=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&s.matchesNode(e,n,r))o=this.top.children.indexOf(s,this.index);else for(let a=this.index,l=Math.min(this.top.children.length,a+5);a0;){let a;for(;;)if(r){let c=n.children[r-1];if(c instanceof Er)n=c,r=c.children.length;else{a=c,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let l=a.node;if(l){if(l!=t.child(i-1))break;--i,o.set(a,i),s.push(a)}}return{index:i,matched:o,matches:s.reverse()}}function mT(t,e){return t.type.side-e.type.side}function gT(t,e,n,r){let i=e.locals(t),o=0;if(i.length==0){for(let c=0;co;)a.push(i[s++]);let h=o+d.nodeSize;if(d.isText){let g=h;s!g.inline):a.slice();r(d,m,e.forChild(o,d),p),o=h}}function yT(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function kT(t,e,n,r){for(let i=0,o=0;i=n){if(o>=r&&l.slice(r-e.length-a,r-a)==e)return r-e.length;let c=a=0&&c+e.length+a>=n)return a+c;if(n==r&&l.length>=r+e.length-a&&l.slice(r-a,r-a+e.length)==e)return r}}return-1}function Tu(t,e,n,r,i){let o=[];for(let s=0,a=0;s=n||u<=e?o.push(l):(cn&&o.push(l.slice(n-c,l.size,r)))}return o}function zu(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),o=i&&i.size==0,s=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(s<0)return null;let a=r.resolve(s),l,c;if(Fa(n)){for(l=s;i&&!i.node;)i=i.parent;let f=i.node;if(i&&f.isAtom&&H.isSelectable(f)&&i.parent&&!(f.isInline&&JE(n.focusNode,n.focusOffset,i.dom))){let d=i.posBefore;c=new H(s==d?a:r.resolve(d))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let f=s,d=s;for(let p=0;p{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Jy(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function xT(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,_e(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&it&&_n<=11&&(n.disabled=!0,n.disabled=!1)}function Gy(t,e){if(e instanceof H){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(ky(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else ky(t)}function ky(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function _u(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||B.between(e,n,r)}function by(t){return t.editable&&!t.hasFocus()?!1:Xy(t)}function Xy(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function wT(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Ir(e.node,e.offset,n.anchorNode,n.anchorOffset)}function vu(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),o=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return o&&$.findFrom(o,e)}function zn(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function xy(t,e,n){let r=t.state.selection;if(r instanceof B)if(n.indexOf("s")>-1){let{$head:i}=r,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let s=t.state.doc.resolve(i.pos+o.nodeSize*(e<0?-1:1));return zn(t,new B(r.$anchor,s))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=vu(t.state,e);return i&&i instanceof H?zn(t,i):!1}else if(!(St&&n.indexOf("m")>-1)){let i=r.$head,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,s;if(!o||o.isText)return!1;let a=e<0?i.pos-o.nodeSize:i.pos;return o.isAtom||(s=t.docView.descAt(a))&&!s.contentDOM?H.isSelectable(o)?zn(t,new H(e<0?t.state.doc.resolve(i.pos-o.nodeSize):i)):Wo?zn(t,new B(t.state.doc.resolve(e<0?a:a+o.nodeSize))):!1:!1}}else return!1;else{if(r instanceof H&&r.node.isInline)return zn(t,new B(e>0?r.$to:r.$from));{let i=vu(t.state,e);return i?zn(t,i):!1}}}function Na(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function Bo(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function xi(t,e){return e<0?CT(t):ST(t)}function CT(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,o,s=!1;for(Et&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(Bo(a,-1))i=n,o=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if(Yy(n))break;{let a=n.previousSibling;for(;a&&Bo(a,-1);)i=n.parentNode,o=_e(a),a=a.previousSibling;if(a)n=a,r=Na(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}s?Au(t,n,r):i&&Au(t,i,o)}function ST(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=Na(n),o,s;for(;;)if(r{t.state==i&&hn(t)},50)}function wy(t,e){let n=t.state.doc.resolve(e);if(!(Oe||zy)&&n.parent.inlineContent){let i=t.coordsAtPos(e);if(e>n.start()){let o=t.coordsAtPos(e-1),s=(o.top+o.bottom)/2;if(s>i.top&&s1)return o.lefti.top&&s1)return o.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function Cy(t,e,n){let r=t.state.selection;if(r instanceof B&&!r.empty||n.indexOf("s")>-1||St&&n.indexOf("m")>-1)return!1;let{$from:i,$to:o}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let s=vu(t.state,e);if(s&&s instanceof H)return zn(t,s)}if(!i.parent.inlineContent){let s=e<0?i:o,a=r instanceof mt?$.near(s,e):$.findFrom(s,e);return a?zn(t,a):!1}return!1}function Sy(t,e){if(!(t.state.selection instanceof B))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(o&&!o.isText){let s=t.state.tr;return e<0?s.delete(n.pos-o.nodeSize,n.pos):s.delete(n.pos,n.pos+o.nodeSize),t.dispatch(s),!0}return!1}function My(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function TT(t){if(!Ge||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;My(t,r,"true"),setTimeout(()=>My(t,r,"false"),20)}return!1}function vT(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function AT(t,e){let n=e.keyCode,r=vT(e);if(n==8||St&&n==72&&r=="c")return Sy(t,-1)||xi(t,-1);if(n==46&&!e.shiftKey||St&&n==68&&r=="c")return Sy(t,1)||xi(t,1);if(n==13||n==27)return!0;if(n==37||St&&n==66&&r=="c"){let i=n==37?wy(t,t.state.selection.from)=="ltr"?-1:1:-1;return xy(t,i,r)||xi(t,i)}else if(n==39||St&&n==70&&r=="c"){let i=n==39?wy(t,t.state.selection.from)=="ltr"?1:-1:1;return xy(t,i,r)||xi(t,i)}else{if(n==38||St&&n==80&&r=="c")return Cy(t,-1,r)||xi(t,-1);if(n==40||St&&n==78&&r=="c")return TT(t)||Cy(t,1,r)||xi(t,1);if(r==(St?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function $u(t,e){t.someProp("transformCopied",p=>{e=p(e,t)});let n=[],{content:r,openStart:i,openEnd:o}=e;for(;i>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,o--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let s=t.someProp("clipboardSerializer")||Ct.fromSchema(t.state.schema),a=rk(),l=a.createElement("div");l.appendChild(s.serializeFragment(r,{document:a}));let c=l.firstChild,u,f=0;for(;c&&c.nodeType==1&&(u=nk[c.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let h=a.createElement(u[p]);for(;l.firstChild;)h.appendChild(l.firstChild);l.appendChild(h),f++}c=l.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${o}${f?` -${f}`:""} ${JSON.stringify(n)}`);let d=t.someProp("clipboardTextSerializer",p=>p(e,t))||e.content.textBetween(0,e.content.size,` +`),i;function o(s){return r.stack.push(s),a;function a(){r.stack.pop()}}}function GS(t){throw new Error("Cannot handle value `"+t+"`, expected node")}function XS(t){let e=t;throw new Error("Cannot handle unknown node `"+e.type+"`")}function YS(t,e){if(t.type==="definition"&&t.type===e.type)return 0}function QS(t,e){return pm(t,this,e)}function ZS(t,e){return hm(t,this,e)}function eM(t,e){return ym(this,t,e)}function li(t){let e=this;e.compiler=n;function n(r){return wc(r,{...e.data("settings"),...t,extensions:e.data("toMarkdownExtensions")||[]})}}function Cc(t){if(t)throw t}var aa=U1(vm(),1);function yo(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function Sc(){let t=[],e={run:n,use:r};return e;function n(...i){let o=-1,s=i.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);a(null,...i);function a(l,...c){let u=t[++o],f=-1;if(l){s(l);return}for(;++fs.length,l;a&&s.push(i);try{l=t.apply(this,s)}catch(c){let u=c;if(a&&n)throw u;return i(u)}a||(l&&l.then&&typeof l.then=="function"?l.then(o,i):l instanceof Error?i(l):o(l))}function i(s,...a){n||(n=!0,e(s,...a))}function o(s){i(null,s)}}var Ne=class extends Error{constructor(e,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",o={},s=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof e=="string"?i=e:!o.cause&&e&&(s=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof r=="string"){let l=r.indexOf(":");l===-1?o.ruleId=r:(o.source=r.slice(0,l),o.ruleId=r.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){let l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}let a=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=a?a.line:void 0,this.name=An(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=s&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};Ne.prototype.file="";Ne.prototype.name="";Ne.prototype.reason="";Ne.prototype.message="";Ne.prototype.stack="";Ne.prototype.column=void 0;Ne.prototype.line=void 0;Ne.prototype.ancestors=void 0;Ne.prototype.cause=void 0;Ne.prototype.fatal=void 0;Ne.prototype.place=void 0;Ne.prototype.ruleId=void 0;Ne.prototype.source=void 0;var Ot={basename:tM,dirname:nM,extname:rM,join:iM,sep:"/"};function tM(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');ko(t);let n=0,r=-1,i=t.length,o;if(e===void 0||e.length===0||e.length>t.length){for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else r<0&&(o=!0,r=i+1);return r<0?"":t.slice(n,r)}if(e===t)return"";let s=-1,a=e.length-1;for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else s<0&&(o=!0,s=i+1),a>-1&&(t.codePointAt(i)===e.codePointAt(a--)?a<0&&(r=i):(a=-1,r=s));return n===r?r=s:r<0&&(r=t.length),t.slice(n,r)}function nM(t){if(ko(t),t.length===0)return".";let e=-1,n=t.length,r;for(;--n;)if(t.codePointAt(n)===47){if(r){e=n;break}}else r||(r=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function rM(t){ko(t);let e=t.length,n=-1,r=0,i=-1,o=0,s;for(;e--;){let a=t.codePointAt(e);if(a===47){if(s){r=e+1;break}continue}n<0&&(s=!0,n=e+1),a===46?i<0?i=e:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||n<0||o===0||o===1&&i===n-1&&i===r+1?"":t.slice(i,n)}function iM(...t){let e=-1,n;for(;++e0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function sM(t,e){let n="",r=0,i=-1,o=0,s=-1,a,l;for(;++s<=t.length;){if(s2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),i=s,o=0;continue}}else if(n.length>0){n="",r=0,i=s,o=0;continue}}e&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+t.slice(i+1,s):n=t.slice(i+1,s),r=s-i-1;i=s,o=0}else a===46&&o>-1?o++:o=-1}return n}function ko(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}var Im={cwd:aM};function aM(){return"/"}function ci(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function Nm(t){if(typeof t=="string")t=new URL(t);else if(!ci(t)){let e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){let e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return lM(t)}function lM(t){if(t.hostname!==""){let r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}let e=t.pathname,n=-1;for(;++n0){let[p,...h]=u,m=r[d][1];yo(m)&&yo(p)&&(p=(0,aa.default)(!0,m,p)),r[d]=[c,p,...h]}}}},xo=new Nc().freeze();function vc(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Ac(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Ic(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Dm(t){if(!yo(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Lm(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function sa(t){return fM(t)?t:new bo(t)}function fM(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function dM(t){return typeof t=="string"||pM(t)}function pM(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}function Ue(t){this.content=t}Ue.prototype={constructor:Ue,find:function(t){for(var e=0;e>1}};Ue.from=function(t){if(t instanceof Ue)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Ue(e)};var Rc=Ue;function Vm(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),o=e.child(r);if(i==o){n+=i.nodeSize;continue}if(!i.sameMarkup(o))return n;if(i.isText&&i.text!=o.text){let s=i.text,a=o.text,l=0;for(;s[l]==a[l];l++)n++;return l&&l0&&d>0&&c[f-1]==u[d-1];)f--,d--,n--,r--;return f&&d&&f=56320&&t<57344}function Um(t){return t>=55296&&t<56320}var M=class t{constructor(e,n){if(this.content=e,this.size=n||0,n==null)for(let r=0;re&&r(l,i+a,o||null,s)!==!1&&l.content.size){let u=a+1;l.nodesBetween(Math.max(0,e-u),Math.min(l.content.size,n-u),r,i+u)}a=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let o="",s=!0;return this.nodesBetween(e,n,(a,l)=>{let c=a.isText?a.text.slice(Math.max(e,l)-l,n-l):a.isLeaf?i?typeof i=="function"?i(a):i:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&c||a.isTextblock)&&r&&(s?s=!1:o+=r),o+=c},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.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);oe)for(let o=0,s=0;se&&((sn)&&(a.isText?a=a.cut(Math.max(0,e-s),Math.min(a.text.length,n-s)):a=a.cut(Math.max(0,e-s-1),Math.min(a.content.size,n-s-1))),r.push(a),i+=a.nodeSize),s=l}return new t(r,i)}cutByIndex(e,n){return e==n?t.empty:e==0&&n==this.content.length?this:new t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),o=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new t(i,o)}addToStart(e){return new t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new t(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),o=r+i.nodeSize;if(o>=e)return o==e?la(n+1,o):la(n,r);r=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return t.fromArray(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return t.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(o)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};ne.none=[];var Rn=class extends Error{},R=class t{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Gm(this.content,e+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new t(r,this.openStart,this.openEnd)}removeBetween(e,n){return new t(Jm(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return t.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 t(M.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let o=e.firstChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.firstChild)r++;for(let o=e.lastChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.lastChild)i++;return new t(e,r,i)}};R.empty=new R(M.empty,0,0);function Jm(t,e,n){let{index:r,offset:i}=t.findIndex(e),o=t.maybeChild(r),{index:s,offset:a}=t.findIndex(n);if(i==e||o.isText){if(a!=n&&!t.child(s).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw new RangeError("Removing non-flat range");return t.replaceChild(r,o.copy(Jm(o.content,e-i-1,n-i-1)))}function Gm(t,e,n,r,i,o){let{index:s,offset:a}=t.findIndex(e),l=t.maybeChild(s);if(a==e||l.isText)return o&&r<=0&&i<=0&&!o.canReplace(s,s,n)?null:t.cut(0,e).append(n).append(t.cut(e));let c=Gm(l.content,e-a-1,n,s==0?r-1:0,s==t.childCount-1?i-1:0,l);return c&&t.replaceChild(s,l.copy(c))}function hM(t,e,n){if(n.openStart>t.depth)throw new Rn("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Rn("Inconsistent open depths");return Xm(t,e,n,0)}function Xm(t,e,n,r){let i=t.index(r),o=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function wo(t,e,n,r){let i=(e||t).node(n),o=0,s=e?e.index(n):i.childCount;t&&(o=t.index(n),t.depth>n?o++:t.textOffset&&(fr(t.nodeAfter,r),o++));for(let a=o;ai&&Dc(t,e,i+1),s=r.depth>i&&Dc(n,r,i+1),a=[];return wo(null,t,i,a),o&&s&&e.index(i)==n.index(i)?(Ym(o,s),fr(dr(o,Qm(t,e,n,r,i+1)),a)):(o&&fr(dr(o,da(t,e,i+1)),a),wo(e,n,i,a),s&&fr(dr(s,da(n,r,i+1)),a)),wo(r,null,i,a),new M(a)}function da(t,e,n){let r=[];if(wo(null,t,n,r),t.depth>n){let i=Dc(t,e,n+1);fr(dr(i,da(t,e,n+1)),r)}return wo(e,null,n,r),new M(r)}function mM(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let o=n-1;o>=0;o--)i=e.node(o).copy(M.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}var pa=class t{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(n);return r?e.child(n).cut(r):i}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,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)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new So(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,o=n;for(let s=e;;){let{index:a,offset:l}=s.content.findIndex(o),c=o-l;if(r.push(s,a,i+l),!c||(s=s.child(a),s.isText))break;o=c-1,i+=l+1}return new t(n,r,o)}static resolveCached(e,n){let r=Pm.get(e);if(r)for(let o=0;oe&&this.nodesBetween(e,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 e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Zm(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=M.empty,i=0,o=r.childCount){let s=this.contentMatchAt(e).matchFragment(r,i,o),a=s&&s.matchFragment(this.content,n);if(!a||!a.validEnd)return!1;for(let l=i;ln.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,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(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=M.fromJSON(e,n.content),o=e.nodeType(n.type).create(n.attrs,i,r);return o.type.checkAttrs(o.attrs),o}};rt.prototype.text=void 0;var Pc=class t extends rt{constructor(e,n,r,i){if(super(e,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):Zm(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new t(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new t(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function Zm(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}var pr=class t{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new Bc(e,n);if(r.next==null)return t.empty;let i=eg(r);r.next&&r.err("Unexpected trailing text");let o=MM(SM(i));return EM(o,r),o}matchType(e){for(let n=0;nc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let i=0;i{let o=i+(r.validEnd?"*":" ")+" ";for(let s=0;s"+e.indexOf(r.next[s].next);return o}).join(` +`)}};pr.empty=new pr(!0);var Bc=class{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}};function eg(t){let e=[];do e.push(kM(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function kM(t){let e=[];do e.push(bM(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function bM(t){let e=CM(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=xM(t,e);else break;return e}function Bm(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function xM(t,e){let n=Bm(t),r=n;return t.eat(",")&&(t.next!="}"?r=Bm(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function wM(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let o in n){let s=n[o];s.isInGroup(e)&&i.push(s)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function CM(t){if(t.eat("(")){let e=eg(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=wM(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function SM(t){let e=[[]];return i(o(t,0),n()),e;function n(){return e.push([])-1}function r(s,a,l){let c={term:l,to:a};return e[s].push(c),c}function i(s,a){s.forEach(l=>l.to=a)}function o(s,a){if(s.type=="choice")return s.exprs.reduce((l,c)=>l.concat(o(c,a)),[]);if(s.type=="seq")for(let l=0;;l++){let c=o(s.exprs[l],a);if(l==s.exprs.length-1)return c;i(c,a=n())}else if(s.type=="star"){let l=n();return r(a,l),i(o(s.expr,l),l),[r(l)]}else if(s.type=="plus"){let l=n();return i(o(s.expr,a),l),i(o(s.expr,l),l),[r(l)]}else{if(s.type=="opt")return[r(a)].concat(o(s.expr,a));if(s.type=="range"){let l=a;for(let c=0;c{t[s].forEach(({term:a,to:l})=>{if(!a)return;let c;for(let u=0;u{c||i.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let o=e[r.join(",")]=new pr(r.indexOf(t.length-1)>-1);for(let s=0;s-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:rg(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new rt(this,this.computeAttrs(e),M.from(n),ne.setFrom(r))}createChecked(e=null,n,r){return n=M.from(n),this.checkContent(n),new rt(this,this.computeAttrs(e),n,ne.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=M.from(n),n.size){let s=this.contentMatch.fillBefore(n);if(!s)return null;n=s.append(n)}let i=this.contentMatch.matchFragment(n),o=i&&i.fillBefore(M.empty,!0);return o?new rt(this,e,n.append(o),ne.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;nr[o]=new t(o,n,s));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 TM(t,e,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 ${e} on type ${t}, got ${o}`)}}var Fc=class{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?TM(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}},Eo=class t{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=og(e,i.attrs),this.excluded=null;let o=ng(this.attrs);this.instance=o?new ne(this,o):null}create(e=null){return!e&&this.instance?this.instance:new ne(this,rg(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((o,s)=>r[o]=new t(o,i++,n,s)),r}removeFromSet(e){for(var n=0;n-1}},ha=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in e)n[i]=e[i];n.nodes=Rc.from(e.nodes),n.marks=Rc.from(e.marks||{}),this.nodes=Mo.compile(this.spec.nodes,this),this.marks=Eo.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let o=this.nodes[i],s=o.spec.content||"",a=o.spec.marks;if(o.contentMatch=r[s]||(r[s]=pr.parse(s,this.nodes)),o.inlineContent=o.contentMatch.inlineContent,o.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!o.isInline||!o.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=o}o.markSet=a=="_"?null:a?zm(this,a.split(" ")):a==""||!o.inlineContent?[]:null}for(let i in this.marks){let o=this.marks[i],s=o.spec.excludes;o.excluded=s==null?[o]:s==""?[]:zm(this,s.split(" "))}this.nodeFromJSON=i=>rt.fromJSON(this,i),this.markFromJSON=i=>ne.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Mo){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,i)}text(e,n){let r=this.nodes.text;return new Pc(r,r.defaultAttrs,e,ne.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}};function zm(t,e){let n=[];for(let r=0;r-1)&&n.push(s=l)}if(!s)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function vM(t){return t.tag!=null}function AM(t){return t.style!=null}var wt=class t{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(vM(i))this.tags.push(i);else if(AM(i)){let o=/[^=]*/.exec(i.style)[0];r.indexOf(o)<0&&r.push(o),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let o=e.nodes[i.node];return o.contentMatch.matchType(o)})}parse(e,n={}){let r=new ma(this,n,!1);return r.addAll(e,ne.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new ma(this,n,!0);return r.addAll(e,ne.none,n.from,n.to),R.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=n))){if(s.getAttrs){let l=s.getAttrs(n);if(l===!1)continue;s.attrs=l||void 0}return s}}}static schemaRules(e){let n=[];function r(i){let o=i.priority==null?50:i.priority,s=0;for(;s{r(s=$m(s)),s.mark||s.ignore||s.clearMark||(s.mark=i)})}for(let i in e.nodes){let o=e.nodes[i].spec.parseDOM;o&&o.forEach(s=>{r(s=$m(s)),s.node||s.ignore||s.mark||(s.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new t(e,t.schemaRules(e)))}},sg={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},IM={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},ag={ol:!0,ul:!0},To=1,zc=2,Co=4;function _m(t,e,n){return e!=null?(e?To:0)|(e==="full"?zc:0):t&&t.whitespace=="pre"?To|zc:n&~Co}var ui=class{constructor(e,n,r,i,o,s){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=s,this.content=[],this.activeMarks=ne.none,this.match=o||(s&Co?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(M.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&To)){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=M.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(M.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!sg.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},ma=class{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,o,s=_m(null,n.preserveWhitespace,0)|(r?Co:0);i?o=new ui(i.type,i.attrs,ne.none,!0,n.topMatch||i.type.contentMatch,s):r?o=new ui(null,null,ne.none,!0,null,s):o=new ui(e.schema.topNodeType,null,ne.none,!0,null,s),this.nodes=[o],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,i=this.top,o=i.options&zc?"full":this.localPreserveWS||(i.options&To)>0,{schema:s}=this.parser;if(o==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(o)if(o==="full")r=r.replace(/\r\n?/g,` +`);else if(s.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(s.linebreakReplacement.create())){let a=r.split(/\r?\n|\r/);for(let l=0;l!l.clearMark(c)):n=n.concat(this.parser.schema.marks[l.mark].create(l.attrs)),l.consuming===!1)a=l;else break}}return n}addElementByRule(e,n,r,i){let o,s;if(n.node)if(s=this.parser.schema.nodes[n.node],s.isLeaf)this.insertNode(s.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let l=this.enter(s,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 a=this.top;if(s&&s.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(l=>this.insertNode(l,r,!1));else{let l=e;typeof n.contentElement=="string"?l=e.querySelector(n.contentElement):typeof n.contentElement=="function"?l=n.contentElement(e):n.contentElement&&(l=n.contentElement),this.findAround(e,l,!0),this.addAll(l,r),this.findAround(e,l,!1)}o&&this.sync(a)&&this.open--}addAll(e,n,r,i){let o=r||0;for(let s=r?e.childNodes[r]:e.firstChild,a=i==null?null:e.childNodes[i];s!=a;s=s.nextSibling,++o)this.findAtPoint(e,o),this.addDOM(s,n);this.findAtPoint(e,o)}findPlace(e,n,r){let i,o;for(let s=this.open,a=0;s>=0;s--){let l=this.nodes[s],c=l.findWrapping(e);if(c&&(!i||i.length>c.length+a)&&(i=c,o=l,!c.length))break;if(l.solid){if(r)break;a+=2}}if(!i)return null;this.sync(o);for(let s=0;s(s.type?s.type.allowsMarkType(c.type):Hm(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new ui(e,n,l,i,null,a)),this.open++,r}closeExtra(e=!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(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=To)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(i?0:1),s=(a,l)=>{for(;a>=0;a--){let c=n[a];if(c==""){if(a==n.length-1||a==0)continue;for(;l>=o;l--)if(s(a-1,l))return!0;return!1}else{let u=l>0||l==0&&i?this.nodes[l].type:r&&l>=o?r.node(l-o).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;l--}}return!0};return s(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.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 NM(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&ag.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function RM(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function $m(t){let e={};for(let n in t)e[n]=t[n];return e}function Hm(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let o=[],s=a=>{o.push(a);for(let l=0;l{if(o.length||s.marks.length){let a=0,l=0;for(;a=0;i--){let o=this.serializeMark(e.marks[i],e.isInline,n);o&&((o.contentDOM||o.dom).appendChild(r),r=o.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&ua(ca(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return typeof n=="string"?{dom:e.createTextNode(n)}:ua(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new t(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=Wm(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return Wm(e.marks)}};function Wm(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function ca(t){return t.document||window.document}var jm=new WeakMap;function OM(t){let e=jm.get(t);return e===void 0&&jm.set(t,e=DM(t)),e}function DM(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let s=i.indexOf(" ");s>0&&(n=i.slice(0,s),i=i.slice(s+1));let a,l=n?t.createElementNS(n,i):t.createElement(i),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let f in c)if(c[f]!=null){let d=f.indexOf(" ");d>0?l.setAttributeNS(f.slice(0,d),f.slice(d+1),c[f]):f=="style"&&l.style?l.style.cssText=c[f]:l.setAttribute(f,c[f])}}for(let f=u;fu)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(t.createTextNode(d));else{let{dom:p,contentDOM:h}=ua(t,d,n,r);if(l.appendChild(p),h){if(a)throw new RangeError("Multiple content holes");a=h}}}return{dom:l,contentDOM:a}}var ug=65535,fg=Math.pow(2,16);function LM(t,e){return t+e*fg}function lg(t){return t&ug}function PM(t){return(t-(t&ug))/fg}var dg=1,pg=2,ga=4,hg=8,Io=class{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&hg)>0}get deletedBefore(){return(this.delInfo&(dg|ga))>0}get deletedAfter(){return(this.delInfo&(pg|ga))>0}get deletedAcross(){return(this.delInfo&ga)>0}},sn=class t{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&t.empty)return t.empty}recover(e){let n=0,r=lg(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[a+o],u=this.ranges[a+s],f=l+c;if(e<=f){let d=c?e==l?-1:e==f?1:n:n,p=l+i+(d<0?0:u);if(r)return p;let h=e==(n<0?l:f)?null:LM(a/3,e-l),m=e==l?pg:e==f?dg:ga;return(n<0?e!=l:e!=f)&&(m|=hg),new Io(p,m,h)}i+=u-c}return r?e+i:new Io(e+i,0,null)}touches(e,n){let r=0,i=lg(n),o=this.inverted?2:1,s=this.inverted?1:2;for(let a=0;ae)break;let c=this.ranges[a+o],u=l+c;if(e<=u&&a==i*3)return!0;r+=this.ranges[a+s]-c}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,o=0;i=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new t;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;ro&&l!s.isAtom||!a.type.allowsMarkType(this.mark.type)?s:s.mark(this.mark.addToSet(s.marks)),i),n.openStart,n.openEnd);return Fe.fromReplace(e,this.from,this.to,o)}invert(){return new mr(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};Re.jsonID("addMark",hr);var mr=class t extends Re{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new R(Vc(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return Fe.fromReplace(e,this.from,this.to,r)}invert(){return new hr(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};Re.jsonID("removeMark",mr);var Ro=class t extends Re{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Fe.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Fe.fromReplace(e,this.pos,this.pos+1,new R(M.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.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 t(n.pos,r.pos,i,o,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,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 t(n.from,n.to,n.gapFrom,n.gapTo,R.fromJSON(e,n.slice),n.insert,!!n.structure)}};Re.jsonID("replaceAround",ze);function Wc(t,e,n){let r=t.resolve(e),i=n-e,o=r.depth;for(;i>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,i--;if(i>0){let s=r.node(o).maybeChild(r.indexAfter(o));for(;i>0;){if(!s||s.isLeaf)return!0;s=s.firstChild,i--}}return!1}function BM(t,e,n,r){let i=[],o=[],s,a;t.doc.nodesBetween(e,n,(l,c,u)=>{if(!l.isInline)return;let f=l.marks;if(!r.isInSet(f)&&u.type.allowsMarkType(r.type)){let d=Math.max(c,e),p=Math.min(c+l.nodeSize,n),h=r.addToSet(f);for(let m=0;mt.step(l)),o.forEach(l=>t.step(l))}function FM(t,e,n,r){let i=[],o=0;t.doc.nodesBetween(e,n,(s,a)=>{if(!s.isInline)return;o++;let l=null;if(r instanceof Eo){let c=s.marks,u;for(;u=r.isInSet(c);)(l||(l=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(s.marks)&&(l=[r]):l=s.marks;if(l&&l.length){let c=Math.min(a+s.nodeSize,n);for(let u=0;ut.step(new mr(s.from,s.to,s.style)))}function qc(t,e,n,r=n.contentMatch,i=!0){let o=t.doc.nodeAt(e),s=[],a=e+1;for(let l=0;l=0;l--)t.step(s[l])}function zM(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function gr(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,o=0;;--r){let s=t.$from.node(r),a=t.$from.index(r)+i,l=t.$to.indexAfter(r)-o;if(rn;h--)m||r.index(h)>0?(m=!0,u=M.from(r.node(h).copy(u)),f++):l--;let d=M.empty,p=0;for(let h=o,m=!1;h>n;h--)m||i.after(h+1)=0;s--){if(r.size){let a=n[s].type.contentMatch.matchFragment(r);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=M.from(n[s].type.create(n[s].attrs,r))}let i=e.start,o=e.end;t.step(new ze(i,o,i,o,new R(r,0,0),n.length,!0))}function jM(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=t.steps.length;t.doc.nodesBetween(e,n,(s,a)=>{let l=typeof i=="function"?i(s):i;if(s.isTextblock&&!s.hasMarkup(r,l)&&VM(t.doc,t.mapping.slice(o).map(a),r)){let c=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",h=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!h?c=!1:!p&&h&&(c=!0)}c===!1&&gg(t,s,a,o),qc(t,t.mapping.slice(o).map(a,1),r,void 0,c===null);let u=t.mapping.slice(o),f=u.map(a,1),d=u.map(a+s.nodeSize,1);return t.step(new ze(f,d,f+1,d-1,new R(M.from(r.create(l,null,s.marks)),0,0),1,!0)),c===!0&&mg(t,s,a,o),!1}})}function mg(t,e,n,r){e.forEach((i,o)=>{if(i.isText){let s,a=/\r?\n|\r/g;for(;s=a.exec(i.text);){let l=t.mapping.slice(r).map(n+1+o+s.index);t.replaceWith(l,l+1,e.type.schema.linebreakReplacement.create())}}})}function gg(t,e,n,r){e.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let s=t.mapping.slice(r).map(n+1+o);t.replaceWith(s,s+1,e.type.schema.text(` +`))}})}function VM(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function qM(t,e,n,r,i){let o=t.doc.nodeAt(e);if(!o)throw new RangeError("No node at given position");n||(n=o.type);let s=n.create(r,null,i||o.marks);if(o.isLeaf)return t.replaceWith(e,e+o.nodeSize,s);if(!n.validContent(o.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new ze(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new R(M.from(s),0,0),1,!0))}function kr(t,e,n=1,r){let i=t.resolve(e),o=i.depth-n,s=r&&r[r.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!s.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,u=n-2;c>o;c--,u--){let f=i.node(c),d=i.index(c);if(f.type.spec.isolating)return!1;let p=f.content.cutByIndex(d,f.childCount),h=r&&r[u+1];h&&(p=p.replaceChild(0,h.type.create(h.attrs)));let m=r&&r[u]||f;if(!f.canReplace(d+1,f.childCount)||!m.type.validContent(p))return!1}let a=i.indexAfter(o),l=r&&r[0];return i.node(o).canReplaceWith(a,a,l?l.type:i.node(o+1).type)}function KM(t,e,n=1,r){let i=t.doc.resolve(e),o=M.empty,s=M.empty;for(let a=i.depth,l=i.depth-n,c=n-1;a>l;a--,c--){o=M.from(i.node(a).copy(o));let u=r&&r[c];s=M.from(u?u.type.create(u.attrs,s):i.node(a).copy(s))}t.step(new Ce(e,e,new R(o.append(s),n,n),!0))}function br(t,e){let n=t.resolve(e),r=n.index();return JM(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function UM(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;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;s--){let a=s==r.depth?0:r.pos<=(r.start(s+1)+r.end(s+1))/2?-1:1,l=r.index(s)+(a>0?1:0),c=r.node(s),u=!1;if(o==1)u=c.canReplace(l,l,i);else{let f=c.contentMatchAt(l).findWrapping(i.firstChild.type);u=f&&c.canReplaceWith(l,l,f[0])}if(u)return a==0?r.pos:a<0?r.before(s+1):r.after(s+1)}return null}function Oo(t,e,n=e,r=R.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),o=t.resolve(n);return kg(i,o,r)?new Ce(e,n,r):new jc(i,o,r).fit()}function kg(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}var jc=class{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=M.empty;for(let i=0;i<=e.depth;i++){let o=e.node(i);this.frontier.push({type:o.type,match:o.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=M.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let o=this.placed,s=r.depth,a=i.depth;for(;s&&a&&o.childCount==1;)o=o.firstChild.content,s--,a--;let l=new R(o,s,a);return e>-1?new ze(r.pos,e,this.$to.pos,this.$to.end(),l,n):l.size||r.pos!=this.$to.pos?new Ce(r.pos,i.pos,l):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),o.type.spec.isolating&&i<=r){e=r;break}n=o.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let i,o=null;r?(o=$c(this.unplaced.content,r-1).firstChild,i=o.content):i=this.unplaced.content;let s=i.firstChild;for(let a=this.depth;a>=0;a--){let{type:l,match:c}=this.frontier[a],u,f=null;if(n==1&&(s?c.matchType(s.type)||(f=c.fillBefore(M.from(s),!1)):o&&l.compatibleContent(o.type)))return{sliceDepth:r,frontierDepth:a,parent:o,inject:f};if(n==2&&s&&(u=c.findWrapping(s.type)))return{sliceDepth:r,frontierDepth:a,parent:o,wrap:u};if(o&&c.matchType(o.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=$c(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new R(e,n+1,Math.max(r,i.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=$c(e,n);if(i.childCount<=1&&n>0){let o=e.size-n<=n+i.size;this.unplaced=new R(vo(e,n-1,1),n-1,o?n-1:r)}else this.unplaced=new R(vo(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:i,wrap:o}){for(;this.depth>n;)this.closeFrontierNode();if(o)for(let m=0;m1||l==0||m.content.size)&&(f=g,u.push(bg(m.mark(d.allowedMarks(m.marks)),c==1?l:0,c==a.childCount?p:-1)))}let h=c==a.childCount;h||(p=-1),this.placed=Ao(this.placed,n,M.from(u)),this.frontier[n].match=f,h&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=a;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],o=n=0;a--){let{match:l,type:c}=this.frontier[a],u=Hc(e,a,c,l,!0);if(!u||u.childCount)continue e}return{depth:n,fit:s,move:o?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Ao(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),o=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,o)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=Ao(this.placed,this.depth,M.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(M.empty,!0);n.childCount&&(this.placed=Ao(this.placed,this.frontier.length,n))}};function vo(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(vo(t.firstChild.content,e-1,n)))}function Ao(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Ao(t.lastChild.content,e-1,n)))}function $c(t,e){for(let n=0;n1&&(r=r.replaceChild(0,bg(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(M.empty,!0)))),t.copy(r)}function Hc(t,e,n,r,i){let o=t.node(e),s=i?t.indexAfter(e):t.index(e);if(s==o.childCount&&!n.compatibleContent(o.type))return null;let a=r.fillBefore(o.content,!0,s);return a&&!YM(n,o.content,s)?a:null}function YM(t,e,n){for(let r=n;r0;d--,p--){let h=i.node(d).type.spec;if(h.defining||h.definingAsContext||h.isolating)break;s.indexOf(d)>-1?a=d:i.before(d)==p&&s.splice(1,0,-d)}let l=s.indexOf(a),c=[],u=r.openStart;for(let d=r.content,p=0;;p++){let h=d.firstChild;if(c.push(h),p==r.openStart)break;d=h.content}for(let d=u-1;d>=0;d--){let p=c[d],h=QM(p.type);if(h&&!p.sameMarkup(i.node(Math.abs(a)-1)))u=d;else if(h||!p.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let p=(d+u+1)%(r.openStart+1),h=c[p];if(h)for(let m=0;m=0&&(t.replace(e,n,r),!(t.steps.length>f));d--){let p=s[d];p<0||(e=i.before(p),n=o.after(p))}}function xg(t,e,n,r,i){if(er){let o=i.contentMatchAt(0),s=o.fillBefore(t).append(t);t=s.append(o.matchFragment(s).fillBefore(M.empty,!0))}return t}function eE(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=XM(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new R(M.from(r),0,0))}function tE(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let s=r.sharedDepth(n),a=!1;for(let l=r.depth;l>s;l--)r.node(l).type.spec.isolating&&(a=!0);for(let l=i.depth;l>s;l--)i.node(l).type.spec.isolating&&(a=!0);if(!a){for(let l=r.depth;l>0&&e==r.start(l);l--)e=r.before(l);for(let l=i.depth;l>0&&n==i.start(l);l--)n=i.before(l);r=t.doc.resolve(e),i=t.doc.resolve(n)}}let o=wg(r,i);for(let s=0;s0&&(l||r.node(a-1).canReplace(r.index(a-1),i.indexAfter(a-1))))return t.delete(r.before(a),i.after(a))}for(let s=1;s<=r.depth&&s<=i.depth;s++)if(e-r.start(s)==r.depth-s&&n>r.end(s)&&i.end(s)-n!=i.depth-s&&r.start(s-1)==i.start(s-1)&&r.node(s-1).canReplace(r.index(s-1),i.index(s-1)))return t.delete(r.before(s),n);t.delete(e,n)}function wg(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let o=t.start(i);if(oe.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(o==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==o-1)&&n.push(i)}return n}var ya=class t extends Re{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return Fe.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 Fe.fromReplace(e,this.pos,this.pos+1,new R(M.from(i),0,n.isLeaf?0:1))}getMap(){return sn.empty}invert(e){return new t(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new t(n.pos,n.attr,n.value)}};Re.jsonID("attr",ya);var ka=class t extends Re{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return Fe.ok(r)}getMap(){return sn.empty}invert(e){return new t(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new t(n.attr,n.value)}};Re.jsonID("docAttr",ka);var di=class extends Error{};di=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};di.prototype=Object.create(Error.prototype);di.prototype.constructor=di;di.prototype.name="TransformError";var pi=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new No}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new di(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r{e=Math.min(e,a),n=Math.max(n,l)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=R.empty){let i=Oo(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new R(M.from(r),0,0))}delete(e,n){return this.replace(e,n,R.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return ZM(this,e,n,r),this}replaceRangeWith(e,n,r){return eE(this,e,n,r),this}deleteRange(e,n){return tE(this,e,n),this}lift(e,n){return _M(this,e,n),this}join(e,n=1){return GM(this,e,n),this}wrap(e,n){return WM(this,e,n),this}setBlockType(e,n=e,r,i=null){return jM(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return qM(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new ya(e,n,r)),this}setDocAttribute(e,n){return this.step(new ka(e,n)),this}addNodeMark(e,n){return this.step(new Ro(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof ne)n.isInSet(r.marks)&&this.step(new fi(e,n));else{let i=r.marks,o,s=[];for(;o=n.isInSet(i);)s.push(new fi(e,o)),i=o.removeFromSet(i);for(let a=s.length-1;a>=0;a--)this.step(s[a])}return this}split(e,n=1,r){return KM(this,e,n,r),this}addMark(e,n,r){return BM(this,e,n,r),this}removeMark(e,n,r){return FM(this,e,n,r),this}clearIncompatible(e,n,r){return qc(this,e,n,r),this}};var Kc=Object.create(null),$=class{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new On(e.min(n),e.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 e=this.ranges;for(let n=0;n=0;o--){let s=n<0?hi(e.node(0),e.node(o),e.before(o+1),e.index(o),n,r):hi(e.node(0),e.node(o),e.after(o+1),e.index(o)+1,n,r);if(s)return s}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new mt(e.node(0))}static atStart(e){return hi(e,e,0,0,1)||new mt(e)}static atEnd(e){return hi(e,e,e.content.size,e.childCount,-1)||new mt(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Kc[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in Kc)throw new RangeError("Duplicate use of selection JSON ID "+e);return Kc[e]=n,n.prototype.jsonID=e,n}getBookmark(){return B.between(this.$anchor,this.$head).getBookmark()}};$.prototype.visible=!0;var On=class{constructor(e,n){this.$from=e,this.$to=n}},Cg=!1;function Sg(t){!Cg&&!t.parent.inlineContent&&(Cg=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var B=class t extends ${constructor(e,n=e){Sg(e),Sg(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return $.near(r);let i=e.resolve(n.map(this.anchor));return new t(i.parent.inlineContent?i:r,r)}replace(e,n=R.empty){if(super.replace(e,n),n==R.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof t&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new xa(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new t(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let o=$.findFrom(n,r,!0)||$.findFrom(n,-r,!0);if(o)n=o.$head;else return $.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=($.findFrom(e,-r,!0)||$.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?s=0;s+=i){let a=e.child(s);if(a.isAtom){if(!o&&H.isSelectable(a))return H.create(t,n-(i<0?a.nodeSize:0))}else{let l=hi(t,a,n+i,i<0?a.childCount:0,i,o);if(l)return l}n+=a.nodeSize*i}return null}function Mg(t,e,n){let r=t.steps.length-1;if(r{s==null&&(s=u)}),t.setSelection($.near(t.doc.resolve(s),n))}var Eg=1,ba=2,Tg=4,Gc=class extends pi{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=ba,this}ensureMarks(e){return ne.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&ba)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~ba,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||ne.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let o=this.storedMarks;if(!o){let s=this.doc.resolve(n);o=r==n?s.marks():s.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(e,o)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection($.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Tg,this}get scrolledIntoView(){return(this.updated&Tg)>0}};function vg(t,e){return!e||!t?t:t.bind(e)}var xr=class{constructor(e,n,r){this.name=e,this.init=vg(n.init,r),this.apply=vg(n.apply,r)}},rE=[new xr("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new xr("selection",{init(t,e){return t.selection||$.atStart(e.doc)},apply(t){return t.selection}}),new xr("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new xr("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})],Do=class{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=rE.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 xr(r.key,r.spec.state,r))})}},mi=class t{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],o=i.spec.state;o&&o.toJSON&&(n[r]=o.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Do(e.schema,e.plugins),o=new t(i);return i.fields.forEach(s=>{if(s.name=="doc")o.doc=rt.fromJSON(e.schema,n.doc);else if(s.name=="selection")o.selection=$.fromJSON(o.doc,n.selection);else if(s.name=="storedMarks")n.storedMarks&&(o.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let a in r){let l=r[a],c=l.spec.state;if(l.key==s.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(n,a)){o[s.name]=c.fromJSON.call(l,e,n[a],o);return}}o[s.name]=s.init(e,o)}}),o}};function Ag(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ag(i,e,{})),n[r]=i}return n}var X=class{constructor(e){this.spec=e,this.props={},e.props&&Ag(e.props,this,this.props),this.key=e.key?e.key.key:Ig("plugin")}getState(e){return e[this.key]}},Uc=Object.create(null);function Ig(t){return t in Uc?t+"$"+ ++Uc[t]:(Uc[t]=0,t+"$")}var ee=class{constructor(e="key"){this.key=Ig(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var wa=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Rg(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}var Yc=(t,e,n)=>{let r=Rg(t,n);if(!r)return!1;let i=Zc(r);if(!i){let s=r.blockRange(),a=s&&gr(s);return a==null?!1:(e&&e(t.tr.lift(s,a).scrollIntoView()),!0)}let o=i.nodeBefore;if(Pg(t,i,e,-1))return!0;if(r.parent.content.size==0&&(gi(o,"end")||H.isSelectable(o)))for(let s=r.depth;;s--){let a=Oo(t.doc,r.before(s),r.after(s),R.empty);if(a&&a.slice.size1)break}return o.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView()),!0):!1},Og=(t,e,n)=>{let r=Rg(t,n);if(!r)return!1;let i=Zc(r);return i?iE(t,i,e):!1};function iE(t,e,n){let r=e.nodeBefore,i=r,o=e.pos-1;for(;!i.isTextblock;o--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let s=e.nodeAfter,a=s,l=e.pos+1;for(;!a.isTextblock;l++){if(a.type.spec.isolating)return!1;let u=a.firstChild;if(!u)return!1;a=u}let c=Oo(t.doc,o,l,R.empty);if(!c||c.from!=o||c instanceof Ce&&c.slice.size>=l-o)return!1;if(n){let u=t.tr.step(c);u.setSelection(B.create(u.doc,o)),n(u.scrollIntoView())}return!0}function gi(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}var Qc=(t,e,n)=>{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;o=Zc(r)}let s=o&&o.nodeBefore;return!s||!H.isSelectable(s)?!1:(e&&e(t.tr.setSelection(H.create(t.doc,o.pos-s.nodeSize)).scrollIntoView()),!0)};function Zc(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function oE(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=oE(t,n);if(!r)return!1;let i=Dg(r);if(!i)return!1;let o=i.nodeAfter;if(Pg(t,i,e,1))return!0;if(r.parent.content.size==0&&(gi(o,"start")||H.isSelectable(o))){let s=Oo(t.doc,r.before(),r.after(),R.empty);if(s&&s.slice.size{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),o=i&&gr(i);return o==null?!1:(e&&e(t.tr.lift(i,o).scrollIntoView()),!0)},lE=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(` +`).scrollIntoView()),!0)};function eu(t){for(let e=0;e{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),o=n.indexAfter(-1),s=eu(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let a=n.after(),l=t.tr.replaceWith(a,a,s.createAndFill());l.setSelection($.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},cE=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof mt||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=eu(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let o=n.before();if(kr(t.doc,o))return e&&e(t.tr.split(o).scrollIntoView()),!0}let r=n.blockRange(),i=r&&gr(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function fE(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof H&&e.selection.node.isBlock)return!r.parentOffset||!kr(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],s,a,l=!1,c=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){l=r.end(p)==r.pos+(r.depth-p),c=r.start(p)==r.pos-(r.depth-p),a=eu(r.node(p-1).contentMatchAt(r.indexAfter(p-1)));let m=t&&t(i.parent,l,r);o.unshift(m||(l&&a?{type:a}:null)),s=p;break}else{if(p==1)return!1;o.unshift(null)}let u=e.tr;(e.selection instanceof B||e.selection instanceof mt)&&u.deleteSelection();let f=u.mapping.map(r.pos),d=kr(u.doc,f,o.length,o);if(d||(o[0]=a?{type:a}:null,d=kr(u.doc,f,o.length,o)),!d)return!1;if(u.split(f,o.length,o),!l&&c&&r.node(s).type!=a){let p=u.mapping.map(r.before(s)),h=u.doc.resolve(p);a&&r.node(s-1).canReplaceWith(h.index(),h.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(s)),a)}return n&&n(u.scrollIntoView()),!0}}var dE=fE();var pE=(t,e)=>(e&&e(t.tr.setSelection(new mt(t.doc))),!0);function hE(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,o=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||br(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Pg(t,e,n,r){let i=e.nodeBefore,o=e.nodeAfter,s,a,l=i.type.spec.isolating||o.type.spec.isolating;if(!l&&hE(t,e,n))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(s=(a=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&a.matchType(s[0]||o.type).validEnd){if(n){let p=e.pos+o.nodeSize,h=M.empty;for(let y=s.length-1;y>=0;y--)h=M.from(s[y].create(null,h));h=M.from(i.copy(h));let m=t.tr.step(new ze(e.pos-1,p,e.pos,p,new R(h,1,0),s.length,!0)),g=m.doc.resolve(p+2*s.length);g.nodeAfter&&g.nodeAfter.type==i.type&&br(m.doc,g.pos)&&m.join(g.pos),n(m.scrollIntoView())}return!0}let u=o.type.spec.isolating||r>0&&l?null:$.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),d=f&&gr(f);if(d!=null&&d>=e.depth)return n&&n(t.tr.lift(f,d).scrollIntoView()),!0;if(c&&gi(o,"start",!0)&&gi(i,"end")){let p=i,h=[];for(;h.push(p),!p.isTextblock;)p=p.lastChild;let m=o,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,m.content)){if(n){let y=M.empty;for(let C=h.length-1;C>=0;C--)y=M.from(h[C].copy(y));let b=t.tr.step(new ze(e.pos-h.length,e.pos+o.nodeSize,e.pos+g,e.pos+o.nodeSize-g,new R(y,h.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function Bg(t){return function(e,n){let r=e.selection,i=t<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(e.tr.setSelection(B.create(e.doc,t<0?i.start(o):i.end(o)))),!0):!1}}var mE=Bg(-1),gE=Bg(1);function yi(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o),a=s&&yr(s,t,e);return a?(r&&r(n.tr.wrap(s,a).scrollIntoView()),!0):!1}}function Dn(t,e=null){return function(n,r){let i=!1;for(let o=0;o{if(i)return!1;if(!(!l.isTextblock||l.hasMarkup(t,e)))if(l.type==t)i=!0;else{let u=n.doc.resolve(c),f=u.index();i=u.parent.canReplaceWith(f,f+1,t)}})}if(!i)return!1;if(r){let o=n.tr;for(let s=0;s{if(a||!r&&l.isAtom&&l.isInline&&c>=o.pos&&c+l.nodeSize<=s.pos)return!1;a=l.inlineContent&&l.type.allowsMarkType(n)}),a)return!0}return!1}function kE(t){let e=[];for(let n=0;n{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos)return s+1>r.pos&&e.push(new On(r,r.doc.resolve(s+1))),r=r.doc.resolve(s+1+o.content.size),!1}),r.poss.doc.rangeHasMark(p.$from.pos,p.$to.pos,t)):f=!u.every(p=>{let h=!1;return d.doc.nodesBetween(p.$from.pos,p.$to.pos,(m,g,y)=>{if(h)return!1;h=!t.isInSet(m.marks)&&!!y&&y.type.allowsMarkType(t)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,p.$from.pos-g),Math.min(m.nodeSize,p.$to.pos-g))))}),!h});for(let p=0;p0&&(o=n[0].slice(s-a,s)+o,r=i)}return e.tr.insertText(o,r,i)}}var _g=(t,e)=>{let n=t.plugins;for(let r=0;r=0;l--)s.step(a.steps[l].invert(a.docs[l]));if(o.text){let l=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,t.schema.text(o.text,l))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},H2=new xe(/--$/,"\u2014",{inCodeMark:!1}),W2=new xe(/\.\.\.$/,"\u2026",{inCodeMark:!1}),j2=new xe(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"\u201C",{inCodeMark:!1}),V2=new xe(/"$/,"\u201D",{inCodeMark:!1}),q2=new xe(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"\u2018",{inCodeMark:!1}),K2=new xe(/'$/,"\u2019",{inCodeMark:!1});function Ca(t,e,n=null,r){return new xe(t,(i,o,s,a)=>{let l=n instanceof Function?n(o):n,c=i.tr.delete(s,a),u=c.doc.resolve(s),f=u.blockRange(),d=f&&yr(f,e,l);if(!d)return null;c.wrap(f,d);let p=c.doc.resolve(s-1).nodeBefore;return p&&p.type==e&&br(c.doc,s-1)&&(!r||r(o,p))&&c.join(s-1),c})}function nu(t,e,n=null){return new xe(t,(r,i,o,s)=>{let a=r.doc.resolve(o),l=n instanceof Function?n(i):n;return a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),e)?r.tr.delete(o,s).setBlockType(o,o,e,l):null})}var Pn=typeof navigator<"u"?navigator:null,$g=typeof document<"u"?document:null,Bn=Pn&&Pn.userAgent||"",iu=/Edge\/(\d+)/.exec(Bn),Vg=/MSIE \d/.exec(Bn),ou=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Bn),au=!!(Vg||ou||iu),Q2=Vg?document.documentMode:ou?+ou[1]:iu?+iu[1]:0,wE=!au&&/gecko\/(\d+)/i.test(Bn),Z2=wE&&+(/Firefox\/(\d+)/.exec(Bn)||[0,0])[1],su=!au&&/Chrome\/(\d+)/.exec(Bn),CE=!!su,eH=su?+su[1]:0,SE=!au&&!!Pn&&/Apple Computer/.test(Pn.vendor),ME=SE&&(/Mobile\/\w+/.test(Bn)||!!Pn&&Pn.maxTouchPoints>2),tH=ME||(Pn?/Mac/.test(Pn.platform):!1),EE=/Android \d/.test(Bn),TE=!!$g&&"webkitFontSmoothing"in $g.documentElement.style,nH=TE?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function ru(t,e,n,r,i,o){if(t.composing)return!1;let s=t.state,a=s.doc.resolve(e);if(a.parent.type.spec.code)return!1;let l=a.parent.textBetween(Math.max(0,a.parentOffset-500),a.parentOffset,void 0,"\uFFFC")+r;for(let c of i){let u=c,f=u.match.exec(l),d=f&&f[0]&&u.handler(s,f,e-(f[0].length-r.length),n);if(d)return u.undoable!==!1&&d.setMeta(o,{transform:d,from:e,to:n,text:r}),t.dispatch(d),!0}return!1}var vE=new ee("MILKDOWN_CUSTOM_INPUTRULES");function qg({rules:t}){let e=new X({key:vE,isInputRules:!0,state:{init(){return null},apply(n,r){let i=n.getMeta(this);return i||(n.selectionSet||n.docChanged?null:r)}},props:{handleTextInput(n,r,i,o){return ru(n,r,i,o,t,e)},handleDOMEvents:{compositionend:n=>(setTimeout(()=>{let{$cursor:r}=n.state.selection;r&&ru(n,r.pos,r.pos,"",t,e)}),!1),keydown:(n,r)=>!(EE&&CE&&r.key==="Enter")||n.composing?!1:n.someProp("handleKeyDown",i=>i(n,r))?(r.preventDefault(),!0):!1},handleKeyDown(n,r){if(r.key!=="Enter")return!1;let{$cursor:i}=n.state.selection;return i?ru(n,i.pos,i.pos,` +`,t,e):!1}}});return e}function ln(t,e,n={}){return new xe(t,(r,i,o,s)=>{var a,l,c,u;let{tr:f}=r,d=i.length,p=i[d-1],h=i[0],m=[],g,y={group:p,fullMatch:h,start:o,end:s},b=(a=n.updateCaptured)==null?void 0:a.call(n,y);if(Object.assign(y,b),{group:p,fullMatch:h,start:o,end:s}=y,h===null||p?.trim()==="")return null;if(p){let C=h.search(/\S/),v=o+h.indexOf(p),A=v+p.length;m=(l=f.storedMarks)!=null?l:[],Ao&&f.delete(o+C,v),g=o+C+p.length;let w=(c=n.getAttr)==null?void 0:c.call(n,i);f.addMark(o,g,e.create(w)),f.setStoredMarks(m),(u=n.beforeDispatch)==null||u.call(n,{match:i,start:o,end:s,tr:f})}return f})}function ki(t,e,n={}){return new xe(t,(r,i,o,s)=>{var a,l,c;let{tr:u}=r,f=i[1],d=i[0],p={group:f,fullMatch:d,start:o,end:s},h=(a=n.updateCaptured)==null?void 0:a.call(n,p);if(Object.assign(p,h),{group:f,fullMatch:d,start:o,end:s}=p,d===null||!f||f.trim()==="")return null;let m=(l=n.getAttr)==null?void 0:l.call(n,i),g=e.createAndFill(m);return g&&(u.replaceRangeWith(e.isBlock?u.doc.resolve(o).before():o,s,g),(c=n.beforeDispatch)==null||c.call(n,{match:[d,f],start:o,end:s,tr:u})),u})}var AE=Object.defineProperty,IE=Object.defineProperties,NE=Object.getOwnPropertyDescriptors,Hg=Object.getOwnPropertySymbols,RE=Object.prototype.hasOwnProperty,OE=Object.prototype.propertyIsEnumerable,Wg=(t,e,n)=>e in t?AE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,DE=(t,e)=>{for(var n in e||(e={}))RE.call(e,n)&&Wg(t,n,e[n]);if(Hg)for(var n of Hg(e))OE.call(e,n)&&Wg(t,n,e[n]);return t},LE=(t,e)=>IE(t,NE(e));function jg(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function Kg(t,e,n){let i=t.state.doc.content.size,o=jg(e,0,i),s=jg(n,0,i),a=t.coordsAtPos(o),l=t.coordsAtPos(s,-1),c=Math.min(a.top,l.top),u=Math.max(a.bottom,l.bottom),f=Math.min(a.left,l.left),d=Math.max(a.right,l.right),p=d-f,h=u-c,y={top:c,bottom:u,left:f,right:d,width:p,height:h,x:f,y:c};return LE(DE({},y),{toJSON:()=>y})}function lu(t){return Object.assign(Object.create(t),t).setTime(Date.now())}function PE(t,e){return Array.isArray(t)&&t.includes(e.type)||e.type===t}function Sa(t){if(t.content.childCount===1){let e=t.content.firstChild;if(e?.type.name==="text"&&e.marks.length===0)return e;if(e?.type.name==="paragraph"&&e.childCount===1){let n=e.firstChild;if(n?.type.name==="text"&&n.marks.length===0)return n}}return!1}function BE(t){return e=>{for(let n=e.depth;n>0;n-=1){let r=e.node(n);if(t(r)){let i=e.before(n),o=e.after(n);return{from:i,to:o,node:r}}}}}function Ug(t,e){return BE(n=>n.type===e)(t)}function Jg(t,e){let n=e.nodes[t];if(!n)throw uh("node",t);return n}function cu(t){return e=>{for(let n=e.depth;n>0;n--){let r=e.node(n);if(t(r))return{pos:e.before(n),start:e.start(n),depth:n,node:r}}}}function Gg(t){return e=>cu(t)(e.$from)}function Xg(t,e){if(!(t instanceof H))return;let{node:n,$from:r}=t;if(PE(e,n))return{node:n,pos:r.pos,start:r.start(r.depth),depth:r.depth}}var Yg=(t,e)=>{let{selection:n,doc:r}=t;if(n instanceof H)return{hasNode:n.node.type===e,pos:n.from,target:n.node};let{from:i,to:o}=n,s=!1,a=-1,l=null;return r.nodesBetween(i,o,(c,u)=>l?!1:c.type===e?(s=!0,a=u,l=c,!1):!0),{hasNode:s,pos:a,target:l}};var cn={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:"'"},Ea={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},FE=typeof navigator<"u"&&/Mac/.test(navigator.platform),zE=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(Se=0;Se<10;Se++)cn[48+Se]=cn[96+Se]=String(Se);var Se;for(Se=1;Se<=24;Se++)cn[Se+111]="F"+Se;var Se;for(Se=65;Se<=90;Se++)cn[Se]=String.fromCharCode(Se+32),Ea[Se]=String.fromCharCode(Se);var Se;for(Ma in cn)Ea.hasOwnProperty(Ma)||(Ea[Ma]=cn[Ma]);var Ma;function Qg(t){var e=FE&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||zE&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?Ea:cn)[t.keyCode]||t.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}var _E=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),$E=typeof navigator<"u"&&/Win/.test(navigator.platform);function HE(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,i,o,s;for(let a=0;athis.elements.length,this.top=()=>this.elements.at(-1),this.push=t=>{this.top()?.push(t)},this.open=t=>{this.elements.push(t)},this.close=()=>{let t=this.elements.pop();if(!t)throw Vl();return t}}},jE=class ry extends ty{constructor(e,n,r){super(),this.type=e,this.content=n,this.attrs=r}push(e,...n){this.content.push(e,...n)}pop(){return this.content.pop()}static create(e,n,r){return new ry(e,n,r)}},iy=class extends ny{#t;static{this.create=(t,e)=>{let n=new this(t);return r=>(n.run(e,r),n.toDoc())}}constructor(t){super(),this.#t=ne.none,this.#e=e=>e.isText,this.#r=(e,n)=>{if(this.#e(e)&&this.#e(n)&&ne.sameSet(e.marks,n.marks))return this.schema.text(e.text+n.text,e.marks)},this.#n=e=>{let n=Object.values({...this.schema.nodes,...this.schema.marks}).find(r=>r.spec.parseMarkdown.match(e));if(!n)throw lh(e);return n},this.#s=e=>{let n=this.#n(e);n.spec.parseMarkdown.runner(this,e,n)},this.injectRoot=(e,n,r)=>(this.openNode(n,r),this.next(e.children),this),this.openNode=(e,n)=>(this.open(jE.create(e,[],n)),this),this.#o=()=>{this.#t=ne.none;let e=this.close();return this.#i(e.type,e.attrs,e.content)},this.closeNode=()=>{try{this.#o()}catch(e){console.error(e)}return this},this.#i=(e,n,r)=>{let i=e.createAndFill(n,r,this.#t);if(!i)throw ah(e,n,r);return this.push(i),i},this.addNode=(e,n,r)=>{try{this.#i(e,n,r)}catch(i){console.error(i)}return this},this.openMark=(e,n)=>{let r=e.create(n);return this.#t=r.addToSet(this.#t),this},this.closeMark=e=>(this.#t=e.removeFromSet(this.#t),this),this.addText=e=>{try{let n=this.top();if(!n)throw Vl();let r=n.pop(),i=this.schema.text(e,this.#t);if(!r)return n.push(i),this;let o=this.#r(r,i);return o?(n.push(o),this):(n.push(r,i),this)}catch(n){return console.error(n),this}},this.build=()=>{let e;do e=this.#o();while(this.size());return e},this.next=(e=[])=>([e].flat().forEach(n=>this.#s(n)),this),this.toDoc=()=>this.build(),this.run=(e,n)=>{let r=e.runSync(e.parse(n),n);return this.next(r),this},this.schema=t}#e;#r;#n;#s;#o;#i},ey=class oy extends ty{constructor(e,n,r,i={}){super(),this.type=e,this.children=n,this.value=r,this.props=i,this.push=(o,...s)=>{this.children||(this.children=[]),this.children.push(o,...s)},this.pop=()=>this.children?.pop()}static{this.create=(e,n,r,i={})=>new oy(e,n,r,i)}},VE=t=>Object.prototype.hasOwnProperty.call(t,"size"),sy=class extends ny{#t;static{this.create=(t,e)=>{let n=new this(t);return r=>(n.run(r),n.toString(e))}}constructor(t){super(),this.#t=[],this.#e=e=>{let n=Object.values({...this.schema.nodes,...this.schema.marks}).find(r=>r.spec.toMarkdown.match(e));if(!n)throw ch(e.type);return n},this.#r=e=>this.#e(e).spec.toMarkdown.runner(this,e),this.#n=(e,n)=>this.#e(e).spec.toMarkdown.runner(this,e,n),this.#s=e=>{let n=o=>o.type.spec.priority??50,r=[...e].sort((o,s)=>n(o)-n(s)),i=[];return this.#t.forEach(({mark:o})=>{let s=r.findIndex(a=>a.eq(o));s>=0&&i.push(...r.splice(s,1))}),i.concat(r)},this.#o=e=>{let n=e?.marks,r=0;for(;rs.eq(i)))r++;else break}for(let i=this.#t.length-1;i>=r;i--)this.#f(this.#t[i].mark)},this.#i=(e,n)=>{this.#s(e.marks).every(r=>!this.#n(r,e))&&this.#r(e),this.#o(n)},this.#a=e=>{let{children:n}=e;return n&&(e.children=n.reduce((r,i,o)=>{if(o===0)return[i];let s=r.at(-1);if(s&&s.isMark&&i.isMark){let{children:a,...l}=i,{children:c,...u}=s;if(i.type===s.type&&a&&c&&JSON.stringify(l)===JSON.stringify(u)){let f={...u,children:[...c,...a]};return r.slice(0,-1).concat(this.#a(f))}}return r.concat(i)},[])),e},this.#l=e=>{let n={...e.props,type:e.type};return e.children&&(n.children=e.children),e.value&&(n.value=e.value),n},this.openNode=(e,n,r)=>(this.open(ey.create(e,void 0,n,r)),this),this.#d=(e,n)=>{let r="",i="",o=e.children;if(o){let a=o[0],l=o.at(-1);if(l&&l.type==="text"&&l.value.endsWith(" ")){let c=l.value,u=c.trimEnd();i=c.slice(u.length),l.value=u}if(a&&a.type==="text"&&a.value.startsWith(" ")){let c=a.value,u=c.trimStart();r=c.slice(0,c.length-u.length),a.value=u}}r.length&&this.#u("text",void 0,r);let s=n();return i.length&&this.#u("text",void 0,i),s},this.#c=(e=!1)=>{let n=this.close(),r=()=>this.#u(n.type,n.children,n.value,n.props);return e?this.#d(n,r):r()},this.closeNode=()=>(this.#c(),this),this.#u=(e,n,r,i)=>{let o=ey.create(e,n,r,i),s=this.#a(this.#l(o));return this.push(s),s},this.addNode=(e,n,r,i)=>(this.#u(e,n,r,i),this),this.#p=(e,n,r,i)=>this.#t.some(o=>o.mark.eq(e))?this:(this.#t.push({mark:e,spanning:r==null}),this.openNode(n,r,{...i,isMark:!0})),this.#f=e=>{let n=-1;for(let r=this.#t.length-1;r>=0;r--)if(this.#t[r].mark.eq(e)){n=r;break}n<0||(this.#t.splice(n,1),this.#c(!0))},this.withMark=(e,n,r,i)=>(this.#p(e,n,r,i),this),this.closeMark=e=>(this.#f(e),this),this.build=()=>{let e=null;do e=this.#c();while(this.size());return e},this.next=e=>VE(e)?(e.forEach((n,r,i)=>{this.#i(n,e.maybeChild(i+1)??void 0)}),this):(this.#i(e),this),this.toString=e=>e.stringify(this.build()),this.run=e=>(this.#t=[],this.next(e),this),this.schema=t}#e;#r;#n;#s;#o;#i;#a;#l;#d;#c;#u;#p;#f};var _e=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Ci=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e},yu=null,fn=function(t,e,n){let r=yu||(yu=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},qE=function(){yu=null},Ir=function(t,e,n,r){return n&&(ay(t,e,n,r,-1)||ay(t,e,n,r,1))},KE=/^(img|br|input|textarea|hr)$/i;function ay(t,e,n,r,i){for(var o;;){if(t==n&&e==r)return!0;if(e==(i<0?0:Mt(t))){let s=t.parentNode;if(!s||s.nodeType!=1||Ho(t)||KE.test(t.nodeName)||t.contentEditable=="false")return!1;e=_e(t)+(i<0?0:1),t=s}else if(t.nodeType==1){let s=t.childNodes[e+(i<0?-1:0)];if(s.nodeType==1&&s.contentEditable=="false")if(!((o=s.pmViewDesc)===null||o===void 0)&&o.ignoreForSelection)e+=i;else return!1;else t=s,e=i<0?Mt(t):0}else return!1}}function Mt(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function UE(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=Mt(t)}else if(t.parentNode&&!Ho(t))e=_e(t),t=t.parentNode;else return null}}function JE(t,e){for(;;){if(t.nodeType==3&&e2),St=Si||(Vt?/Mac/.test(Vt.platform):!1),_y=Vt?/Win/.test(Vt.platform):!1,dn=/Android \d/.test(Hn),Wo=!!ly&&"webkitFontSmoothing"in ly.documentElement.style,QE=Wo?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function ZE(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function un(t,e){return typeof t=="number"?t:t[e]}function eT(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function cy(t,e,n){if(!wu(e)&&e.left==0)return;let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,o=t.dom.ownerDocument;for(let s=n||t.dom;s;){if(s.nodeType!=1){s=Ci(s);continue}let a=s,l=a==o.body,c=l?ZE(o):eT(a),u=0,f=0;if(e.topc.bottom-un(r,"bottom")&&(f=e.bottom-e.top>c.bottom-c.top?e.top+un(i,"top")-c.top:e.bottom-c.bottom+un(i,"bottom")),e.leftc.right-un(r,"right")&&(u=e.right-c.right+un(i,"right")),u||f)if(l)o.defaultView.scrollBy(u,f);else{let p=a.scrollLeft,h=a.scrollTop;f&&(a.scrollTop+=f),u&&(a.scrollLeft+=u);let m=a.scrollLeft-p,g=a.scrollTop-h;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=l?"fixed":getComputedStyle(s).position;if(/^(fixed|sticky)$/.test(d))break;s=d=="absolute"?s.offsetParent:Ci(s)}}function tT(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let o=(e.left+e.right)/2,s=n+1;s=n-20){r=a,i=l.top;break}}return{refDOM:r,refTop:i,stack:$y(t.dom)}}function $y(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Ci(r));return e}function nT({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Hy(n,r==0?0:r-e)}function Hy(t,e){for(let n=0;n=a){s=Math.max(h.bottom,s),a=Math.min(h.top,a);let m=h.left>e.left?h.left-e.left:h.right=(h.left+h.right)/2?1:0));continue}}else h.top>e.top&&!l&&h.left<=e.left&&h.right>=e.left&&(l=u,c={left:Math.max(h.left,Math.min(h.right,e.left)),top:h.top});!n&&(e.left>=h.right&&e.top>=h.top||e.left>=h.left&&e.top>=h.bottom)&&(o=f+1)}}return!n&&l&&(n=l,i=c,r=0),n&&n.nodeType==3?iT(n,i):!n||r&&n.nodeType==1?{node:t,offset:o}:Wy(n,i)}function iT(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let o=0;o=(s.left+s.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function Fu(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function oT(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left(s.left+s.right)/2?1:-1}return t.docView.posFromDOM(r,i,o)}function aT(t,e,n,r){let i=-1;for(let o=e,s=!1;o!=t.dom;){let a=t.docView.nearestDesc(o,!0),l;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((l=a.dom.getBoundingClientRect()).width||l.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!s&&l.left>r.left||l.top>r.top?i=a.posBefore:(!s&&l.right-1?i:t.docView.posFromDOM(e,n,-1)}function jy(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top&&i++}let c;Wo&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?a=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(a=aT(t,r,i,e))}a==null&&(a=sT(t,s,e));let l=t.docView.nearestDesc(s,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function wu(t){return t.top=0&&i==r.nodeValue.length?(l--,u=1):n<0?l--:c++,Lo(Fn(fn(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&i&&(n<0||i==Mt(r))){let l=r.childNodes[i-1];if(l.nodeType==1)return du(l.getBoundingClientRect(),!1)}if(o==null&&i=0)}if(o==null&&i&&(n<0||i==Mt(r))){let l=r.childNodes[i-1],c=l.nodeType==3?fn(l,Mt(l)-(s?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return Lo(Fn(c,1),!1)}if(o==null&&i=0)}function Lo(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function du(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function qy(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function uT(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return qy(t,e,()=>{let{node:o}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let a=t.docView.nearestDesc(o,!0);if(!a)break;if(a.node.isBlock){o=a.contentDOM||a.dom;break}o=a.dom.parentNode}let s=Vy(t,i.pos,1);for(let a=o.firstChild;a;a=a.nextSibling){let l;if(a.nodeType==1)l=a.getClientRects();else if(a.nodeType==3)l=fn(a,0,a.nodeValue.length).getClientRects();else continue;for(let c=0;cu.top+1&&(n=="up"?s.top-u.top>(u.bottom-s.top)*2:u.bottom-s.bottom>(s.bottom-u.top)*2))return!1}}return!0})}var fT=/[\u0590-\u08ac]/;function dT(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,o=!i,s=i==r.parent.content.size,a=t.domSelection();return a?!fT.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?o:s:qy(t,e,()=>{let{focusNode:l,focusOffset:c,anchorNode:u,anchorOffset:f}=t.domSelectionRange(),d=a.caretBidiLevel;a.modify("move",n,"character");let p=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:h,focusOffset:m}=t.domSelectionRange(),g=h&&!p.contains(h.nodeType==1?h:h.parentNode)||l==h&&c==m;try{a.collapse(u,f),l&&(l!=u||c!=f)&&a.extend&&a.extend(l,c)}catch{}return d!=null&&(a.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}var uy=null,fy=null,dy=!1;function pT(t,e,n){return uy==e&&fy==n?dy:(uy=e,fy=n,dy=n=="up"||n=="down"?uT(t,e,n):dT(t,e,n))}var Tt=0,py=1,Sr=2,Dt=3,Nr=class{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=Tt,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n_e(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!1;break}if(o.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!0;break}if(o.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let o=this.getDesc(i),s;if(o&&(!n||o.node))if(r&&(s=o.nodeDOM)&&!(s.nodeType==1?s.contains(e.nodeType==1?e:e.parentNode):s==e))r=!1;else return o}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let i=e;i;i=i.parentNode){let o=this.getDesc(i);if(o)return o.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;ne||s instanceof Aa){i=e-o;break}o=a}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 Ta&&o.side>=0;r--);if(n<=0){let o,s=!0;for(;o=r?this.children[r-1]:null,!(!o||o.dom.parentNode==this.contentDOM);r--,s=!1);return o&&n&&s&&!o.border&&!o.domAtom?o.domFromPos(o.size,n):{node:this.contentDOM,offset:o?_e(o.dom)+1:0}}else{let o,s=!0;for(;o=r=u&&n<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(e,n,u);e=s;for(let f=a;f>0;f--){let d=this.children[f-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=_e(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>n||a==this.children.length-1)){n=c;for(let u=a+1;uh&&sn){let h=a;a=l,l=h}let p=document.createRange();p.setEnd(l.node,l.offset),p.setStart(a.node,a.offset),c.removeAllRanges(),c.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,i=0;i=r:er){let a=r+o.border,l=s-o.border;if(e>=a&&n<=l){this.dirty=e==r||n==s?Sr:py,e==a&&n==l&&(o.contentLost||o.dom.parentNode!=this.contentDOM)?o.dirty=Dt:o.markDirty(e-a,n-a);return}else o.dirty=o.dom==o.contentDOM&&o.dom.parentNode==this.contentDOM&&!o.children.length?Sr:Dt}r=s}this.dirty=Sr}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Sr:py;n.dirty{if(!o)return i;if(o.parent)return o.parent.posBeforeChild(o)})),!n.type.spec.raw){if(s.nodeType!=1){let a=document.createElement("span");a.appendChild(s),s=a}s.contentEditable="false",s.classList.add("ProseMirror-widget")}super(e,[],s,null),this.widget=n,this.widget=n,o=this}matchesWidget(e){return this.dirty==Tt&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},Cu=class extends Nr{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}},Er=class t extends Nr{constructor(e,n,r,i,o){super(e,[],r,i),this.mark=n,this.spec=o}static create(e,n,r,i){let o=i.nodeViews[n.type.name],s=o&&o(n,i,r);return(!s||!s.dom)&&(s=Ct.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new t(e,n,s.dom,s.contentDOM||s.dom,s)}parseRule(){return this.dirty&Dt||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Dt&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=Tt){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(o=Tu(o,0,e,r));for(let a=0;a{if(!l)return s;if(l.parent)return l.parent.posBeforeChild(l)},r,i),u=c&&c.dom,f=c&&c.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:f}=Ct.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!f&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let d=u;return u=Jy(u,r,n),c?l=new Su(e,n,r,i,u,f||null,d,c):n.isText?new va(e,n,r,i,u,d):new t(e,n,r,i,u,f||null,d)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>M.empty)}return e}matchesNode(e,n,r){return this.dirty==Tt&&e.eq(this.node)&&Ia(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,i=n,o=e.composing?this.localCompositionInfo(e,n):null,s=o&&o.pos>-1?o:null,a=o&&o.pos<0,l=new Eu(this,s&&s.node,e);yT(this.node,this.innerDeco,(c,u,f)=>{c.spec.marks?l.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!f&&l.syncToMarks(u==this.node.childCount?ne.none:this.node.child(u).marks,r,e,u),l.placeWidget(c,e,i)},(c,u,f,d)=>{l.syncToMarks(c.marks,r,e,d);let p;l.findNodeMatch(c,u,f,d)||a&&e.state.selection.from>i&&e.state.selection.to-1&&l.updateNodeAt(c,u,f,p,e)||l.updateNextNode(c,u,f,e,d,i)||l.addNode(c,u,f,e,i),i+=c.nodeSize}),l.syncToMarks([],r,e,0),this.node.isTextblock&&l.addTextblockHacks(),l.destroyRest(),(l.changed||this.dirty==Sr)&&(s&&this.protectLocalComposition(e,s),Ky(this.contentDOM,this.children,e),Si&&kT(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof B)||rn+this.node.content.size)return null;let o=e.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let s=o.nodeValue,a=bT(this.node.content,s,r-n,i-n);return a<0?null:{node:o,pos:a,text:s}}else return{node:o,pos:-1,text:""}}protectLocalComposition(e,{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 s=new Cu(this,o,n,i);e.input.compositionNodes.push(s),this.children=Tu(this.children,r,r+i.length,e,s)}update(e,n,r,i){return this.dirty==Dt||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=Tt}updateOuterDeco(e){if(Ia(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Uy(this.dom,this.nodeDOM,Mu(this.outerDeco,this.node,n),Mu(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}};function hy(t,e,n,r,i){Jy(r,e,t);let o=new $n(void 0,t,e,n,r,r,r);return o.contentDOM&&o.updateChildren(i,0),o}var va=class t extends $n{constructor(e,n,r,i,o,s){super(e,n,r,i,o,null,s)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,i){return this.dirty==Dt||this.dirty!=Tt&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Tt||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=Tt,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let i=this.node.cut(e,n),o=document.createTextNode(i.text);return new t(this.parent,i,this.outerDeco,this.innerDeco,o,o)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Dt)}get domAtom(){return!1}isText(e){return this.node.text==e}},Aa=class extends Nr{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Tt&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}},Su=class extends $n{constructor(e,n,r,i,o,s,a,l){super(e,n,r,i,o,s,a),this.spec=l}update(e,n,r,i){if(this.dirty==Dt)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let o=this.spec.update(e,n,r);return o&&this.updateInner(e,n,r,i),o}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}};function Ky(t,e,n){let r=t.firstChild,i=!1;for(let o=0;o>1,a=Math.min(s,e.length);for(;o-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let u=Er.create(this.top,e[s],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,s++}}findNodeMatch(e,n,r,i){let o=-1,s;if(i>=this.preMatch.index&&(s=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&s.matchesNode(e,n,r))o=this.top.children.indexOf(s,this.index);else for(let a=this.index,l=Math.min(this.top.children.length,a+5);a0;){let a;for(;;)if(r){let c=n.children[r-1];if(c instanceof Er)n=c,r=c.children.length;else{a=c,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let l=a.node;if(l){if(l!=t.child(i-1))break;--i,o.set(a,i),s.push(a)}}return{index:i,matched:o,matches:s.reverse()}}function gT(t,e){return t.type.side-e.type.side}function yT(t,e,n,r){let i=e.locals(t),o=0;if(i.length==0){for(let c=0;co;)a.push(i[s++]);let h=o+d.nodeSize;if(d.isText){let g=h;s!g.inline):a.slice();r(d,m,e.forChild(o,d),p),o=h}}function kT(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function bT(t,e,n,r){for(let i=0,o=0;i=n){if(o>=r&&l.slice(r-e.length-a,r-a)==e)return r-e.length;let c=a=0&&c+e.length+a>=n)return a+c;if(n==r&&l.length>=r+e.length-a&&l.slice(r-a,r-a+e.length)==e)return r}}return-1}function Tu(t,e,n,r,i){let o=[];for(let s=0,a=0;s=n||u<=e?o.push(l):(cn&&o.push(l.slice(n-c,l.size,r)))}return o}function zu(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),o=i&&i.size==0,s=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(s<0)return null;let a=r.resolve(s),l,c;if(Fa(n)){for(l=s;i&&!i.node;)i=i.parent;let f=i.node;if(i&&f.isAtom&&H.isSelectable(f)&&i.parent&&!(f.isInline&&GE(n.focusNode,n.focusOffset,i.dom))){let d=i.posBefore;c=new H(s==d?a:r.resolve(d))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let f=s,d=s;for(let p=0;p{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Gy(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function wT(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,_e(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&it&&_n<=11&&(n.disabled=!0,n.disabled=!1)}function Xy(t,e){if(e instanceof H){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(by(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else by(t)}function by(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function _u(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||B.between(e,n,r)}function xy(t){return t.editable&&!t.hasFocus()?!1:Yy(t)}function Yy(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function CT(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Ir(e.node,e.offset,n.anchorNode,n.anchorOffset)}function vu(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),o=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return o&&$.findFrom(o,e)}function zn(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function wy(t,e,n){let r=t.state.selection;if(r instanceof B)if(n.indexOf("s")>-1){let{$head:i}=r,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let s=t.state.doc.resolve(i.pos+o.nodeSize*(e<0?-1:1));return zn(t,new B(r.$anchor,s))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=vu(t.state,e);return i&&i instanceof H?zn(t,i):!1}else if(!(St&&n.indexOf("m")>-1)){let i=r.$head,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,s;if(!o||o.isText)return!1;let a=e<0?i.pos-o.nodeSize:i.pos;return o.isAtom||(s=t.docView.descAt(a))&&!s.contentDOM?H.isSelectable(o)?zn(t,new H(e<0?t.state.doc.resolve(i.pos-o.nodeSize):i)):Wo?zn(t,new B(t.state.doc.resolve(e<0?a:a+o.nodeSize))):!1:!1}}else return!1;else{if(r instanceof H&&r.node.isInline)return zn(t,new B(e>0?r.$to:r.$from));{let i=vu(t.state,e);return i?zn(t,i):!1}}}function Na(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function Bo(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function xi(t,e){return e<0?ST(t):MT(t)}function ST(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,o,s=!1;for(Et&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(Bo(a,-1))i=n,o=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if(Qy(n))break;{let a=n.previousSibling;for(;a&&Bo(a,-1);)i=n.parentNode,o=_e(a),a=a.previousSibling;if(a)n=a,r=Na(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}s?Au(t,n,r):i&&Au(t,i,o)}function MT(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=Na(n),o,s;for(;;)if(r{t.state==i&&hn(t)},50)}function Cy(t,e){let n=t.state.doc.resolve(e);if(!(Oe||_y)&&n.parent.inlineContent){let i=t.coordsAtPos(e);if(e>n.start()){let o=t.coordsAtPos(e-1),s=(o.top+o.bottom)/2;if(s>i.top&&s1)return o.lefti.top&&s1)return o.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function Sy(t,e,n){let r=t.state.selection;if(r instanceof B&&!r.empty||n.indexOf("s")>-1||St&&n.indexOf("m")>-1)return!1;let{$from:i,$to:o}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let s=vu(t.state,e);if(s&&s instanceof H)return zn(t,s)}if(!i.parent.inlineContent){let s=e<0?i:o,a=r instanceof mt?$.near(s,e):$.findFrom(s,e);return a?zn(t,a):!1}return!1}function My(t,e){if(!(t.state.selection instanceof B))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(o&&!o.isText){let s=t.state.tr;return e<0?s.delete(n.pos-o.nodeSize,n.pos):s.delete(n.pos,n.pos+o.nodeSize),t.dispatch(s),!0}return!1}function Ey(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function vT(t){if(!Ge||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Ey(t,r,"true"),setTimeout(()=>Ey(t,r,"false"),20)}return!1}function AT(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function IT(t,e){let n=e.keyCode,r=AT(e);if(n==8||St&&n==72&&r=="c")return My(t,-1)||xi(t,-1);if(n==46&&!e.shiftKey||St&&n==68&&r=="c")return My(t,1)||xi(t,1);if(n==13||n==27)return!0;if(n==37||St&&n==66&&r=="c"){let i=n==37?Cy(t,t.state.selection.from)=="ltr"?-1:1:-1;return wy(t,i,r)||xi(t,i)}else if(n==39||St&&n==70&&r=="c"){let i=n==39?Cy(t,t.state.selection.from)=="ltr"?1:-1:1;return wy(t,i,r)||xi(t,i)}else{if(n==38||St&&n==80&&r=="c")return Sy(t,-1,r)||xi(t,-1);if(n==40||St&&n==78&&r=="c")return vT(t)||Sy(t,1,r)||xi(t,1);if(r==(St?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function $u(t,e){t.someProp("transformCopied",p=>{e=p(e,t)});let n=[],{content:r,openStart:i,openEnd:o}=e;for(;i>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,o--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let s=t.someProp("clipboardSerializer")||Ct.fromSchema(t.state.schema),a=ik(),l=a.createElement("div");l.appendChild(s.serializeFragment(r,{document:a}));let c=l.firstChild,u,f=0;for(;c&&c.nodeType==1&&(u=rk[c.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let h=a.createElement(u[p]);for(;l.firstChild;)h.appendChild(l.firstChild);l.appendChild(h),f++}c=l.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${o}${f?` -${f}`:""} ${JSON.stringify(n)}`);let d=t.someProp("clipboardTextSerializer",p=>p(e,t))||e.content.textBetween(0,e.content.size,` -`);return{dom:l,text:d,slice:e}}function Qy(t,e,n,r,i){let o=i.parent.type.spec.code,s,a;if(!n&&!e)return null;let l=!!e&&(r||o||!n);if(l){if(t.someProp("transformPastedText",d=>{e=d(e,o||r,t)}),o)return a=new R(M.from(t.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),t.someProp("transformPasted",d=>{a=d(a,t,!0)}),a;let f=t.someProp("clipboardTextParser",d=>d(e,i,r,t));if(f)a=f;else{let d=i.marks(),{schema:p}=t.state,h=Ct.fromSchema(p);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=s.appendChild(document.createElement("p"));m&&g.appendChild(h.serializeNode(p.text(m,d)))})}}else t.someProp("transformPastedHTML",f=>{n=f(n,t)}),s=OT(n),Wo&&DT(s);let c=s&&s.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let f=+u[3];f>0;f--){let d=s.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;s=d}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||wt.fromSchema(t.state.schema)).parseSlice(s,{preserveWhitespace:!!(l||u),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!IT.test(d.parentNode.nodeName)?{ignore:!0}:null}})),u)a=LT(Ey(a,+u[1],+u[2]),u[4]);else if(a=R.maxOpen(NT(a.content,i),!0),a.openStart||a.openEnd){let f=0,d=0;for(let p=a.content.firstChild;f{a=f(a,t,l)}),a}var IT=/^(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 NT(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),o,s=[];if(t.forEach(a=>{if(!s)return;let l=i.findWrapping(a.type),c;if(!l)return s=null;if(c=s.length&&o.length&&ek(l,o,a,s[s.length-1],0))s[s.length-1]=c;else{s.length&&(s[s.length-1]=tk(s[s.length-1],o.length));let u=Zy(a,l);s.push(u),i=i.matchType(u.type),o=l}}),s)return M.from(s)}return t}function Zy(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,M.from(t));return t}function ek(t,e,n,r,i){if(i1&&(o=0),i=n&&(a=e<0?s.contentMatchAt(0).fillBefore(a,o<=i).append(a):a.append(s.contentMatchAt(s.childCount).fillBefore(M.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,s.copy(a))}function Ey(t,e,n){return en})),hu.createHTML(t)):t}function OT(t){let e=/^(\s*]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=rk(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(t),o;if((o=i&&nk[i[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"").reverse().join("")),r.innerHTML=RT(t),o)for(let s=0;s=0;a-=2){let l=n.nodes[r[a]];if(!l||l.hasRequiredAttrs())break;i=M.from(l.create(r[a+1],i)),o++,s++}return new R(i,o,s)}var Ye={},Qe={},PT={touchstart:!0,touchmove:!0},Nu=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function BT(t){for(let e in Ye){let n=Ye[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{zT(t,r)&&!Hu(t,r)&&(t.editable||!(r.type in Qe))&&n(t,r)},PT[e]?{passive:!0}:void 0)}Ge&&t.dom.addEventListener("input",()=>null),Ru(t)}function pn(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function FT(t){t.input.mouseDown&&t.input.mouseDown.done(),t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function Ru(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>Hu(t,r))})}function Hu(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function zT(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function _T(t,e){!Hu(t,e)&&Ye[e.type]&&(t.editable||!(e.type in Qe))&&Ye[e.type](t,e)}Qe.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!sk(t)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(dn&&Oe&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Si&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",i=>i(t,Cr(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||AT(t,n)?n.preventDefault():pn(t,"key")};Qe.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Qe.keypress=(t,e)=>{let n=e;if(sk(t)||!n.charCode||n.ctrlKey&&!n.altKey||St&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof B)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),o=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",s=>s(t,r.$from.pos,r.$to.pos,i,o))&&t.dispatch(o()),n.preventDefault()}};function jo(t){return{left:t.clientX,top:t.clientY}}function $T(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function Wu(t,e,n,r,i){if(r==-1)return!1;let o=t.state.doc.resolve(r);for(let s=o.depth+1;s>0;s--)if(t.someProp(e,a=>s>o.depth?a(t,n,o.nodeAfter,o.before(s),i,!0):a(t,n,o.node(s),o.before(s),i,!1)))return!0;return!1}function Vo(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);n=="pointer"&&r.setMeta("pointer",!0),t.dispatch(r)}function HT(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&H.isSelectable(r)?(Vo(t,new H(n),"pointer"),!0):!1}function WT(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof H&&(r=n.node);let o=t.state.doc.resolve(e);for(let s=o.depth+1;s>0;s--){let a=s>o.depth?o.nodeAfter:o.node(s);if(H.isSelectable(a)){r&&n.$from.depth>0&&s>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos?i=o.before(n.$from.depth):i=o.before(s);break}}return i!=null?(Vo(t,H.create(t.state.doc,i),"pointer"),!0):!1}function jT(t,e,n,r,i){return Wu(t,"handleClickOn",e,n,r)||t.someProp("handleClick",o=>o(t,e,r))||(i?WT(t,n):HT(t,n))}function VT(t,e,n,r){return Wu(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function qT(t,e,n,r){return Wu(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||KT(t,n,r)}function KT(t,e,n){if(n.button!=0)return!1;let r=ik(t,e,!0),i=t.state.doc;return r?(Vo(t,r,"pointer"),r instanceof B&&i.eq(t.state.doc)&&(t.input.mouseDown=new Du(t,r)),!0):!1}function ik(t,e,n){let r=t.state.doc;if(e==-1)return r.inlineContent?B.create(r,0,r.content.size):null;let i=r.resolve(e);for(let o=i.depth+1;o>0;o--){let s=o>i.depth?i.nodeAfter:i.node(o),a=i.before(o);if(s.inlineContent)return B.create(r,a+1,a+1+s.content.size);if(n&&H.isSelectable(s))return H.create(r,a)}return null}function ju(t){return Oa(t)}var ok=St?"metaKey":"ctrlKey";Ye.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=ju(t),i=Date.now(),o="singleClick";i-t.input.lastClick.time<500&&$T(n,t.input.lastClick)&&!n[ok]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?o="doubleClick":t.input.lastClick.type=="doubleClick"&&(o="tripleClick")),t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:o,button:n.button},t.input.mouseDown&&t.input.mouseDown.done();let s=t.posAtCoords(jo(n));s&&(o=="singleClick"?t.input.mouseDown=new Ou(t,s,n,!!r):(o=="doubleClick"?VT:qT)(t,s.pos,s.inside,n)?n.preventDefault():pn(t,"pointer"))};var Ra=class{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.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}},Ou=class extends Ra{constructor(e,n,r,i){super(e),this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[ok],this.allowDefault=r.shiftKey;let o,s;if(n.inside>-1)o=e.state.doc.nodeAt(n.inside),s=n.inside;else{let u=e.state.doc.resolve(n.pos);o=u.parent,s=u.depth?u.before():0}let a=i?null:r.target,l=a?e.docView.nearestDesc(a,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(o.type.spec.draggable&&o.type.spec.selectable!==!1||c instanceof H&&c.from<=s&&c.to>s)&&(this.mightDrag={node:o,pos:s,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Et&&!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()),pn(e,"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||hn(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(jo(e))),this.updateAllowDefault(e),this.allowDefault||!n?pn(this.view,"pointer"):jT(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Ge&&this.mightDrag&&!this.mightDrag.node.isAtom||Oe&&!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)?(Vo(this.view,$.near(this.view.state.doc.resolve(n.pos)),"pointer"),e.preventDefault()):pn(this.view,"pointer")}move(e){this.updateAllowDefault(e),pn(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}},Du=class extends Ra{constructor(e,n){super(e),this.startSelection=n,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),pn(this.view,"pointer");let n=this.view.posAtCoords(jo(e)),r=n&&ik(this.view,n.inside,!1);if(!r)return;let{doc:i}=this.view.state,o=this.startSelection,[s,a]=r.from{t.input.lastTouch=Date.now(),ju(t),pn(t,"pointer")};Ye.touchmove=t=>{t.input.lastTouch=Date.now(),pn(t,"pointer")};Ye.contextmenu=t=>ju(t);function sk(t,e){return t.composing?!0:Ge&&Math.abs(Date.now()-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}var UT=dn?5e3:-1;Qe.compositionstart=Qe.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof B&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Oe&&zy&&JT(t)))t.markCursor=t.state.storedMarks||n.marks(),Oa(t,!0),t.markCursor=null;else if(Oa(t,!e.selection.empty),Et&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,o=r.focusOffset;i&&i.nodeType==1&&o!=0;){let s=o<0?i.lastChild:i.childNodes[o-1];if(!s)break;if(s.nodeType==3){let a=t.domSelection();a&&a.collapse(s,s.nodeValue.length);break}else i=s,o=-1}}t.input.composing=!0}ak(t,UT)};function JT(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Qe.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,ak(t,20))};function ak(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Oa(t),e))}function lk(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function GT(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=KE(e.focusNode,e.focusOffset),r=UE(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let s=n.pmViewDesc;if(!(!s||!s.isText(n.nodeValue)))return r}}return n||r}function Oa(t,e=!1){if(!(dn&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),lk(t),e||t.docView&&t.docView.dirty){let n=zu(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function XT(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}var Fo=it&&_n<15||Si&&YE<604;Ye.copy=Qe.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let o=Fo?null:n.clipboardData,s=r.content(),{dom:a,text:l}=$u(t,s);o?(n.preventDefault(),o.clearData(),o.setData("text/html",a.innerHTML),o.setData("text/plain",l)):XT(t,a),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function YT(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function QT(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.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=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?zo(t,r.value,null,i,e):zo(t,r.textContent,r.innerHTML,i,e)},50)}function zo(t,e,n,r,i){let o=Qy(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,i,o||R.empty)))return!0;if(!o)return!1;let s=YT(o),a=s?t.state.tr.replaceSelectionWith(s,r):t.state.tr.replaceSelection(o);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function ck(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Qe.paste=(t,e)=>{let n=e;if(t.composing&&!dn)return;let r=Fo?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&zo(t,ck(r),r.getData("text/html"),i,n)?n.preventDefault():QT(t,n)};var Da=class{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}},ZT=St?"altKey":"ctrlKey";function uk(t,e){let n;return t.someProp("dragCopies",r=>{n=n||r(e)}),n!=null?!n:!e[ZT]}Ye.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,o=i.empty?null:t.posAtCoords(jo(n)),s;if(!(o&&o.pos>=i.from&&o.pos<=(i instanceof H?i.to-1:i.to))){if(r&&r.mightDrag)s=H.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let f=t.docView.nearestDesc(n.target,!0);f&&f.node.type.spec.draggable&&f!=t.docView&&(s=H.create(t.state.doc,f.posBefore))}}let a=(s||t.state.selection).content(),{dom:l,text:c,slice:u}=$u(t,a);(!n.dataTransfer.files.length||!Oe||Fy>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Fo?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Fo||n.dataTransfer.setData("text/plain",c),t.dragging=new Da(u,uk(t,n),s)};Ye.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Qe.dragover=Qe.dragenter=(t,e)=>e.preventDefault();Qe.drop=(t,e)=>{try{ev(t,e,t.dragging)}finally{t.dragging=null}};function ev(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(jo(e));if(!r)return;let i=t.state.doc.resolve(r.pos),o=n&&n.slice;o?t.someProp("transformPasted",p=>{o=p(o,t,!1)}):o=Qy(t,ck(e.dataTransfer),Fo?null:e.dataTransfer.getData("text/html"),!1,i);let s=!!(n&&uk(t,e));if(t.someProp("handleDrop",p=>p(t,e,o||R.empty,s))){e.preventDefault();return}if(!o)return;e.preventDefault();let a=o?gg(t.state.doc,i.pos,o):i.pos;a==null&&(a=i.pos);let l=t.state.tr;if(s){let{node:p}=n;p?p.replace(l):l.deleteSelection()}let c=l.mapping.map(a),u=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,f=l.doc;if(u?l.replaceRangeWith(c,c,o.content.firstChild):l.replaceRange(c,c,o),l.doc.eq(f))return;let d=l.doc.resolve(c);if(u&&H.isSelectable(o.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(o.content.firstChild))l.setSelection(new H(d));else{let p=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((h,m,g,y)=>p=y),l.setSelection(_u(t,d,l.doc.resolve(p)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}Ye.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&hn(t)},20))};Ye.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};Ye.beforeinput=(t,e)=>{if(Oe&&dn&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",o=>o(t,Cr(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Qe)Ye[t]=Qe[t];function _o(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}var La=class t{constructor(e,n){this.toDOM=e,this.spec=n||vr,this.side=this.spec.side||0}map(e,n,r,i){let{pos:o,deleted:s}=e.mapResult(n.from+i,this.side<0?-1:1);return s?null:new le(o-r,o-r,this)}valid(){return!0}eq(e){return this==e||e instanceof t&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&_o(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},Tr=class t{constructor(e,n){this.attrs=e,this.spec=n||vr}map(e,n,r,i){let o=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,s=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return o>=s?null:new le(o,s,this)}valid(e,n){return n.from=e&&(!o||o(a.spec))&&r.push(a.copy(a.from+i,a.to+i))}for(let s=0;se){let a=this.children[s]+1;this.children[s+2].findInner(e-a,n-a,r,i+a,o)}}map(e,n,r){return this==Je||e.maps.length==0?this:this.mapInner(e,n,0,0,r||vr)}mapInner(e,n,r,i,o){let s;for(let a=0;a{let c=l+r,u;if(u=dk(n,a,c)){for(i||(i=this.children.slice());oa&&f.to=e){this.children[a]==e&&(r=this.children[a+2]);break}let o=e+1,s=o+n.content.size;for(let a=0;ao&&l.type instanceof Tr){let c=Math.max(o,l.from)-o,u=Math.min(s,l.to)-o;ci.map(e,n,vr));return t.from(r)}forChild(e,n){if(n.isLeaf)return ae.empty;let r=[];for(let i=0;in instanceof ae)?e:e.reduce((n,r)=>n.concat(r instanceof ae?r:r.members),[]))}}forEachSet(e){for(let n=0;n{let g=m-h-(p-d);for(let y=0;yb+u-f)continue;let C=a[y]+u-f;p>=C?a[y+1]=d<=C?-2:-1:d>=u&&g&&(a[y]+=g,a[y+1]+=g)}f+=g}),u=n.maps[c].map(u,-1)}let l=!1;for(let c=0;c=r.content.size){l=!0;continue}let d=n.map(t[c+1]+o,-1),p=d-i,{index:h,offset:m}=r.content.findIndex(f),g=r.maybeChild(h);if(g&&m==f&&m+g.nodeSize==p){let y=a[c+2].mapInner(n,g,u+1,t[c]+o+1,s);y!=Je?(a[c]=f,a[c+1]=p,a[c+2]=y):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=nv(a,t,e,n,i,o,s),u=Ba(c,r,0,s);e=u.local;for(let f=0;fn&&s.to{let c=dk(t,a,l+n);if(c){o=!0;let u=Ba(c,a,n+l+1,r);u!=Je&&i.push(l,l+a.nodeSize,u)}});let s=fk(o?pk(t):t,-n).sort(Ar);for(let a=0;a0;)e++;t.splice(e,0,n)}function mu(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Je&&e.push(r)}),t.cursorWrapper&&e.push(ae.create(t.state.doc,[t.cursorWrapper.deco])),Pa.from(e)}var rv={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},iv=it&&_n<=11,Pu=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},Bu=class{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Pu,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():Ge&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),iv&&(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,rv)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let 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(by(this.view)){if(this.suppressingSelectionUpdates)return hn(this.view);if(it&&_n<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ir(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let o=e.focusNode;o;o=Ci(o))n.add(o);for(let o=e.anchorNode;o;o=Ci(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 e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&by(e)&&!this.ignoreSelectionChange(r),o=-1,s=-1,a=!1,l=[];if(e.editable)for(let u=0;uu.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||Oe&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&n.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of l)if(u.nodeName=="BR"&&u.parentNode){let f=u.nextSibling;for(;f&&f.nodeType==1;){if(f.contentEditable=="false"){u.parentNode.removeChild(u);break}f=f.firstChild}}}else if(Et&&l.length){let u=l.filter(f=>f.nodeName=="BR");if(u.length==2){let[f,d]=u;f.parentNode&&f.parentNode.parentNode==d.parentNode?d.remove():f.remove()}else{let{focusNode:f}=this.currentSelection;for(let d of u){let p=d.parentNode;p&&p.nodeName=="LI"&&(!f||av(e,f)!=p)&&d.remove()}}}let c=null;o<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(o>-1&&(e.docView.markDirty(o,s),ov(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,lv(e,l)),this.handleDOMChange(o,s,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||hn(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;ui;g--){let y=r.childNodes[g-1],b=y.pmViewDesc;if(y.nodeName=="BR"&&!b){o=g;break}if(!b||b.size)break}let f=t.state.doc,d=t.someProp("domParser")||wt.fromSchema(t.state.schema),p=f.resolve(s),h=null,m=d.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:i,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:uv,context:p});if(c&&c[0].pos!=null){let g=c[0].pos,y=c[1]&&c[1].pos;y==null&&(y=g),h={anchor:g+s,head:y+s}}return{doc:m,sel:h,from:s,to:a}}function uv(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Ge&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||Ge&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}var fv=/^(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 dv(t,e,n,r,i){let o=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let N=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,P=zu(t,N);if(P&&!t.state.selection.eq(P)){if(Oe&&dn&&t.input.lastKeyCode===13&&Date.now()-100S(t,Cr(13,"Enter"))))return;let O=t.state.tr.setSelection(P);N=="pointer"?O.setMeta("pointer",!0):N=="key"&&O.scrollIntoView(),o&&O.setMeta("composition",o),t.dispatch(O)}return}let s=t.state.doc.resolve(e),a=s.sharedDepth(n);e=s.before(a+1),n=t.state.doc.resolve(n).after(a+1);let l=t.state.selection,c=cv(t,e,n),u=t.state.doc,f=u.slice(c.from,c.to),d,p;t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||dn)&&i.some(N=>N.nodeType==1&&!fv.test(N.nodeName))&&(!h||h.endA>=h.endB)&&t.someProp("handleKeyDown",N=>N(t,Cr(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!h)if(r&&l instanceof B&&!l.empty&&l.$head.sameParent(l.$anchor)&&!t.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))h={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let N=Ny(t,t.state.doc,c.sel);if(N&&!N.eq(t.state.selection)){let P=t.state.tr.setSelection(N);o&&P.setMeta("composition",o),t.dispatch(P)}}return}t.state.selection.fromt.state.selection.from&&h.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?h.start=t.state.selection.from:h.endA=t.state.selection.to-2&&t.state.selection.to<=c.to&&(h.endB+=t.state.selection.to-h.endA,h.endA=t.state.selection.to)),it&&_n<=11&&h.endB==h.start+1&&h.endA==h.start&&h.start>c.from&&c.doc.textBetween(h.start-c.from-1,h.start-c.from+1)==" \xA0"&&(h.start--,h.endA--,h.endB--);let m=c.doc.resolveNoCache(h.start-c.from),g=c.doc.resolveNoCache(h.endB-c.from),y=u.resolve(h.start),b=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=h.endA;if((Si&&t.input.lastIOSEnter>Date.now()-225&&(!b||i.some(N=>N.nodeName=="DIV"||N.nodeName=="P"))||!b&&m.posN(t,Cr(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>h.start&&hv(u,h.start,h.endA,m,g)&&t.someProp("handleKeyDown",N=>N(t,Cr(8,"Backspace")))){dn&&Oe&&t.domObserver.suppressSelectionUpdates();return}Oe&&h.endB==h.start&&(t.input.lastChromeDelete=Date.now()),dn&&!b&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==h.endA&&(h.endB-=2,g=c.doc.resolveNoCache(h.endB-c.from),setTimeout(()=>{t.someProp("handleKeyDown",function(N){return N(t,Cr(13,"Enter"))})},20));let C=h.start,v=h.endA,A=N=>{let P=N||t.state.tr.replace(C,v,c.doc.slice(h.start-c.from,h.endB-c.from));if(c.sel){let O=Ny(t,P.doc,c.sel);O&&!(Oe&&t.composing&&O.empty&&(h.start!=h.endB||t.input.lastChromeDeletehn(t),20));let N=A(t.state.tr.delete(C,v)),P=u.resolve(h.start).marksAcross(u.resolve(h.endA));P&&N.ensureMarks(P),t.dispatch(N)}else if(h.endA==h.endB&&(w=pv(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,h.endA-y.start())))){let N=A(t.state.tr);w.type=="add"?N.addMark(C,v,w.mark):N.removeMark(C,v,w.mark),t.dispatch(N)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let N=m.parent.textBetween(m.parentOffset,g.parentOffset),P=()=>A(t.state.tr.insertText(N,C,v));t.someProp("handleTextInput",O=>O(t,C,v,N,P))||t.dispatch(P())}else t.dispatch(A());else t.dispatch(A())}function Ny(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:_u(t,e.resolve(n.anchor),e.resolve(n.head))}function pv(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,o=r,s,a,l;for(let u=0;uu.mark(a.addToSet(u.marks));else if(i.length==0&&o.length==1)a=o[0],s="remove",l=u=>u.mark(a.removeFromSet(u.marks));else return null;let c=[];for(let u=0;un||gu(s,!0,!1)0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let o=t.node(r).maybeChild(t.indexAfter(r));for(;o&&!o.isLeaf;)o=o.firstChild,i++}return i}function mv(t,e,n,r,i){let o=t.findDiffStart(e,n),s=n+t.size,a=n+e.size;if(o==null)return null;let{a:l,b:c}=t.findDiffEnd(e,s,a);if(i=="end"){let u=Math.max(0,o-Math.min(l,c));r-=l+u-o}if(l=l?o-r:0;o-=u,c=o+(c-l),l=o}else if(c=c?o-r:0;o-=u,l=o+(l-c),c=o}return{start:o,endA:l,endB:c}}var $o=class{constructor(e,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 Nu,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Py),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=Dy(this),Oy(this),this.nodeViews=Ly(this),this.docView=py(this.state.doc,Ry(this),mu(this),this.dom,this),this.domObserver=new Bu(this,(r,i,o,s)=>dv(this,r,i,o,s)),this.domObserver.start(),BT(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&Ru(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Py),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let i=this.state,o=!1,s=!1;e.storedMarks&&this.composing&&(lk(this),s=!0),this.state=e;let a=i.plugins!=e.plugins||this._props.plugins!=n.plugins;if(a||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=Ly(this);yv(p,this.nodeViews)&&(this.nodeViews=p,o=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&Ru(this),this.editable=Dy(this),Oy(this);let l=mu(this),c=Ry(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",f=o||!this.docView.matchesNode(e.doc,c,l);(f||!e.selection.eq(i.selection))&&(s=!0);let d=u=="preserve"&&s&&this.dom.style.overflowAnchor==null&&eT(this);if(s){this.domObserver.stop();let p=f&&(it||Oe)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&gv(i.selection,e.selection);if(f){let m=Oe?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=GT(this)),(o||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=py(e.doc,c,l,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}let h=this.input.mouseDown;p||!(h&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&wT(this)&&h.delaySelUpdate())?hn(this,p):(Gy(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():d&&tT(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof H){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&ly(this,n.getBoundingClientRect(),e)}else ly(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n0&&on.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return aT(this,e)}coordsAtPos(e,n=1){return jy(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return dT(this,n||this.state,e)}pasteHTML(e,n){return zo(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return zo(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return $u(this,e)}destroy(){this.docView&&(FT(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],mu(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,VE())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return _T(this,e)}domSelectionRange(){let e=this.domSelection();return e?Ge&&this.root.nodeType===11&&GE(this.dom.ownerDocument)==this.dom&&sv(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};$o.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function Ry(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[le.node(0,t.state.doc.content.size,e)]}function Oy(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:le.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Dy(t){return!t.someProp("editable",e=>e(t.state)===!1)}function gv(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function Ly(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function yv(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function Py(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}function yn(t,e){return t.meta={package:"@milkdown/core",group:"System",...e},t}var gk={text:(t,e,n,r)=>{let i=t.value;return/^[^*_\\]*\s+$/.test(i)?i:n.safe(i,{...r,encode:[]})},strong:(t,e,n,r)=>{let i=t.marker||n.options.strong||"*",o=n.enter("strong"),s=n.createTracker(r),a=s.move(i+i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i+i),o(),a},emphasis:(t,e,n,r)=>{let i=t.marker||n.options.emphasis||"*",o=n.enter("emphasis"),s=n.createTracker(r),a=s.move(i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i),o(),a}},U=Y({},"editorView"),qo=Y({},"editorState"),qu=Y([],"initTimer"),hk=Y({},"editor"),Ni=Y([],"inputRules"),Lt=Y([],"prosePlugins"),Ri=Y([],"remarkPlugins"),Ua=Y([],"nodeView"),Ja=Y([],"markView"),Rr=Y(xo().use(ii).use(li),"remark"),Mi=Y({handlers:gk,encode:[]},"remarkStringifyOptions"),za=xt("ConfigReady");function kv(t){let e=n=>(n.record(za),async()=>(await t(n),n.done(za),()=>{n.clearTimer(za)}));return yn(e,{displayName:"Config"}),e}var mn=xt("InitReady");function bv(t){let e=n=>(n.inject(hk,t).inject(Lt,[]).inject(Ri,[]).inject(Ni,[]).inject(Ua,[]).inject(Ja,[]).inject(Mi,{handlers:gk,encode:[]}).inject(Rr,xo().use(ii).use(li)).inject(qu,[za]).record(mn),async()=>{await n.waitTimers(qu);let r=n.get(Mi);return n.set(Rr,xo().use(ii).use(li,r)),n.done(mn),()=>{n.remove(hk).remove(Lt).remove(Ri).remove(Ni).remove(Ua).remove(Ja).remove(Mi).remove(Rr).remove(qu).clearTimer(mn)}});return yn(e,{displayName:"Init"}),e}var Ze=xt("SchemaReady"),_a=Y([],"schemaTimer"),$e=Y({},"schema"),Ei=Y([],"nodes"),Ti=Y([],"marks");function mk(t){return{...t,parseDOM:t.parseDOM?.map(e=>({priority:t.priority,...e}))}}var yk=t=>(t.inject($e,{}).inject(Ei,[]).inject(Ti,[]).inject(_a,[mn]).record(Ze),async()=>{await t.waitTimers(_a);let e=t.get(Rr),n=t.get(Ri).reduce((i,o)=>i.use(o.plugin,o.options),e);t.set(Rr,n);let r=new ha({nodes:Object.fromEntries(t.get(Ei).map(([i,o])=>[i,mk(o)])),marks:Object.fromEntries(t.get(Ti).map(([i,o])=>[i,mk(o)]))});return t.set($e,r),t.done(Ze),()=>{t.remove($e).remove(Ei).remove(Ti).remove(_a).clearTimer(Ze)}});yn(yk,{displayName:"Schema"});var kk=class{constructor(){this.#t=new ql,this.#e=null,this.setCtx=t=>{this.#e=t},this.chain=()=>{if(this.#e==null)throw zs();let t=this.#e,e=[],n=this.get.bind(this),r={run:()=>{let o=wr(...e),s=t.get(U);return o(s.state,s.dispatch,s)},inline:o=>(e.push(o),r),pipe:i.bind(this)};function i(o,s){let a=n(o);return e.push(a(s)),r}return r}}#t;#e;get ctx(){return this.#e}create(t,e){let n=t.create(this.#t.sliceMap);return n.set(e),n}get(t){return this.#t.get(t).get()}remove(t){return this.#t.remove(t)}call(t,e){if(this.#e==null)throw zs();let n=this.get(t)(e),r=this.#e.get(U);return n(r.state,r.dispatch,r)}inline(t){if(this.#e==null)throw zs();let e=this.#e.get(U);return t(e.state,e.dispatch,e)}};function bk(t="cmdKey"){return Y((()=>()=>!1),t)}var Q=Y(new kk,"commands"),$a=Y([Ze],"commandsTimer"),vi=xt("CommandsReady"),xk=t=>{let e=new kk;return e.setCtx(t),t.inject(Q,e).inject($a,[Ze]).record(vi),async()=>(await t.waitTimers($a),t.done(vi),()=>{t.remove(Q).remove($a).clearTimer(vi)})};yn(xk,{displayName:"Commands"});function xv(t){return t.Backspace=wr(zg,wa,Rg,Qc),t}var wk=class{constructor(){this.#t=null,this.#e=[],this.setCtx=t=>{this.#t=t},this.add=t=>(this.#e.push(t),()=>{this.#e=this.#e.filter(e=>e!==t)}),this.addObjectKeymap=t=>{let e=[];return Object.entries(t).forEach(([n,r])=>{if(typeof r=="function"){let i={key:n,onRun:()=>r};this.#e.push(i),e.push(()=>{this.#e=this.#e.filter(o=>o!==i)})}else this.#e.push(r),e.push(()=>{this.#e=this.#e.filter(i=>i!==r)})}),()=>{e.forEach(n=>n())}},this.addBaseKeymap=()=>{let t=xv(Fg);return this.addObjectKeymap(t)},this.build=()=>{let t={};return this.#e.forEach(e=>{t[e.key]=[...t[e.key]||[],e]}),Object.fromEntries(Object.entries(t).map(([e,n])=>{let r=n.sort((o,s)=>(s.priority??50)-(o.priority??50));return[e,(o,s,a)=>{let l=this.#t;if(l==null)throw ni();return wr(...r.map(c=>c.onRun(l)))(o,s,a)}]}))}}#t;#e;get ctx(){return this.#t}},Xo=Y(new wk,"keymap"),Ku=Y([Ze],"keymapTimer"),Ai=xt("KeymapReady"),wv=t=>{let e=new wk;return e.setCtx(t),t.inject(Xo,e).inject(Ku,[Ze]).record(Ai),async()=>(await t.waitTimers(Ku),t.done(Ai),()=>{t.remove(Xo).remove(Ku).clearTimer(Ai)})},Ha=xt("ParserReady"),Ck=(()=>{throw ni()}),He=Y(Ck,"parser"),Uu=Y([],"parserTimer"),Sk=t=>(t.inject(He,Ck).inject(Uu,[Ze]).record(Ha),async()=>{await t.waitTimers(Uu);let e=t.get(Rr),n=t.get($e);return t.set(He,ry.create(n,e)),t.done(Ha),()=>{t.remove(He).remove(Uu).clearTimer(Ha)}});yn(Sk,{displayName:"Parser"});var Ii=xt("SerializerReady"),Ju=Y([],"serializerTimer"),Mk=(()=>{throw ni()}),gn=Y(Mk,"serializer"),Ek=t=>(t.inject(gn,Mk).inject(Ju,[Ze]).record(Ii),async()=>{await t.waitTimers(Ju);let e=t.get(Rr),n=t.get($e);return t.set(gn,oy.create(n,e)),t.done(Ii),()=>{t.remove(gn).remove(Ju).clearTimer(Ii)}});yn(Ek,{displayName:"Serializer"});var Ko=Y("","defaultValue"),Uo=Y(t=>t,"stateOptions"),Wa=Y([],"editorStateTimer"),ja=xt("EditorStateReady");function Cv(t,e,n){if(typeof t=="string")return e(t);if(t.type==="html")return wt.fromSchema(n).parse(t.dom);if(t.type==="json")return rt.fromJSON(n,t.value);throw rh(t)}var Sv=new ee("MILKDOWN_STATE_TRACKER"),Tk=t=>(t.inject(Ko,"").inject(qo,{}).inject(Uo,e=>e).inject(Wa,[Ha,Ii,vi,Ai]).record(ja),async()=>{await t.waitTimers(Wa);let e=t.get($e),n=t.get(He),r=t.get(Ni),i=t.get(Uo),o=t.get(Lt),s=Cv(t.get(Ko),n,e),a=t.get(Xo),l=a.addBaseKeymap(),c=[...o,new X({key:Sv,state:{init:()=>{},apply:(d,p,h,m)=>{t.set(qo,m)}}}),Vg({rules:r}),Qg(a.build())];t.set(Lt,c);let u=i({schema:e,doc:s,plugins:c}),f=mi.create(u);return t.set(qo,f),t.done(ja),()=>{l(),t.remove(Ko).remove(qo).remove(Uo).remove(Wa).clearTimer(ja)}});yn(Tk,{displayName:"EditorState"});var Oi=Y([],"pasteRule"),Va=Y([Ze],"pasteRuleTimer"),qa=xt("PasteRuleReady"),vk=t=>(t.inject(Oi,[]).inject(Va,[Ze]).record(qa),async()=>(await t.waitTimers(Va),t.done(qa),()=>{t.remove(Oi).remove(Va).clearTimer(qa)}));yn(vk,{displayName:"PasteRule"});var Jo=xt("EditorViewReady"),Ka=Y([],"editorViewTimer"),Or=Y({},"editorViewOptions"),Go=Y(null,"root"),Gu=Y(null,"rootDOM"),Xu=Y({},"rootAttrs");function Mv(t,e){let n=document.createElement("div");n.className="milkdown",t.appendChild(n),e.set(Gu,n);let r=e.get(Xu);return Object.entries(r).forEach(([i,o])=>n.setAttribute(i,o)),n}function Ev(t){t.classList.add("editor"),t.setAttribute("role","textbox")}var Tv=new ee("MILKDOWN_VIEW_CLEAR"),Ak=t=>(t.inject(Go,document.body).inject(U,{}).inject(Or,{}).inject(Gu,null).inject(Xu,{}).inject(Ka,[ja,qa]).record(Jo),async()=>{await t.wait(mn);let e=t.get(Go)||document.body,n=typeof e=="string"?document.querySelector(e):e;t.update(Lt,s=>[new X({key:Tv,view:a=>{let l=n?Mv(n,t):void 0;return(()=>{if(l&&n){let u=a.dom;n.replaceChild(l,u),l.appendChild(u)}})(),{destroy:()=>{l?.parentNode&&l?.parentNode.replaceChild(a.dom,l),l?.remove()}}}}),...s]),await t.waitTimers(Ka);let r=t.get(qo),i=t.get(Or),o=new $o(n,{state:r,nodeViews:Object.fromEntries(t.get(Ua)),markViews:Object.fromEntries(t.get(Ja)),transformPasted:(s,a,l)=>(t.get(Oi).sort((c,u)=>(u.priority??50)-(c.priority??50)).map(c=>c.run).forEach(c=>{s=c(s,a,l)}),s),...i});return Ev(o.dom),t.set(U,o),t.done(Jo),()=>{o?.destroy(),t.remove(Go).remove(U).remove(Or).remove(Gu).remove(Xu).remove(Ka).clearTimer(Jo)}});yn(Ak,{displayName:"EditorView"});var Ik=class Nk{constructor(){this.#t=!1,this.#e="Idle",this.#r=[],this.#n=()=>{},this.#s=new ql,this.#o=new ph,this.#i=new Map,this.#a=new Map,this.#l=new fh(this.#s,this.#o),this.#d=()=>{let e=kv(async r=>{await Promise.all(this.#r.map(i=>Promise.resolve(i(r))))}),n=[yk,Sk,Ek,xk,wv,vk,Tk,Ak,bv(this),e];this.#c(n,this.#a)},this.#c=(e,n)=>{e.forEach(r=>{let i=this.#l.produce(this.#t?r.meta:void 0),o=r(i);n.set(r,{ctx:i,handler:o,cleanup:void 0})})},this.#u=(e,n=!1)=>Promise.all([e].flat().map(async r=>{let i=this.#i.get(r)?.cleanup;return n?this.#i.delete(r):this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0}),typeof i=="function"?i():i})),this.#p=async()=>{await Promise.all([...this.#a.entries()].map(async([e,{cleanup:n}])=>typeof n=="function"?n():n)),this.#a.clear()},this.#f=e=>{this.#e=e,this.#n(e)},this.#h=e=>[...e.entries()].map(async([n,r])=>{let{ctx:i,handler:o}=r;if(!o)return;let s=await o();e.set(n,{ctx:i,handler:o,cleanup:s})}),this.enableInspector=(e=!0)=>(this.#t=e,this),this.onStatusChange=e=>(this.#n=e,this),this.config=e=>(this.#r.push(e),this),this.removeConfig=e=>(this.#r=this.#r.filter(n=>n!==e),this),this.use=e=>{let n=[e].flat();return n.flat().forEach(r=>{this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0})}),this.#e==="Created"&&this.#c(n,this.#i),this},this.remove=async e=>this.#e==="OnCreate"?(console.warn("[Milkdown]: You are trying to remove plugins when the editor is creating, this is not recommended, please check your code."),new Promise(n=>{setTimeout(()=>{n(this.remove(e))},50)})):(await this.#u([e].flat(),!0),this),this.create=async()=>this.#e==="OnCreate"?this:(this.#e==="Created"&&await this.destroy(),this.#f("OnCreate"),this.#d(),this.#c([...this.#i.keys()],this.#i),await Promise.all([this.#h(this.#a),this.#h(this.#i)].flat()),this.#f("Created"),this),this.destroy=async(e=!1)=>this.#e==="Destroyed"||this.#e==="OnDestroy"?this:this.#e==="OnCreate"?new Promise(n=>{setTimeout(()=>{n(this.destroy(e))},50)}):(e&&(this.#r=[]),this.#f("OnDestroy"),await this.#u([...this.#i.keys()],e),await this.#p(),this.#f("Destroyed"),this),this.action=e=>e(this.#l),this.inspect=()=>this.#t?[...this.#a.values(),...this.#i.values()].map(({ctx:e})=>e?.inspector?.read()).filter(e=>!!e):(console.warn("[Milkdown]: You are trying to collect inspection when inspector is disabled, please enable inspector by `editor.enableInspector()` first."),[])}static make(){return new Nk}#t;#e;#r;#n;#s;#o;#i;#a;#l;#d;#c;#u;#p;#f;#h;get ctx(){return this.#l}get status(){return this.#e}};var vv=t=>crypto.getRandomValues(new Uint8Array(t)),Av=(t,e,n)=>{let r=256-256%t.length;if(r===256){let o=t.length-1;return(s=e)=>{if(!s)return"";let a="";for(;;){let l=n(s),c=s;for(;c--;)if(a+=t[l[c]&o],a.length>=s)return a}}}let i=Math.ceil(1.6*256*e/r);return(o=e)=>{if(!o)return"";let s="";for(;;){let a=n(i),l=i;for(;l--;)if(a[l]=o))return s}}},Rk=(t,e=21)=>Av(t,e|0,vv);var WH=Rk("abcedfghicklmn",10);function z(t,e){let n=bk(t),r=i=>async()=>{r.key=n,await i.wait(vi);let o=e(i);return i.get(Q).create(n,o),r.run=s=>i.get(Q).call(t,s),()=>{i.get(Q).remove(n)}};return r}function ge(t){let e=n=>async()=>{await n.wait(Ze);let r=t(n);return n.update(Ni,i=>[...i,r]),e.inputRule=r,()=>{n.update(Ni,i=>i.filter(o=>o!==r))}};return e}function Ok(t){let e=n=>async()=>{await n.wait(Ze);let r=t(n);return n.update(Oi,i=>[...i,r]),e.pasteRule=r,()=>{n.update(Oi,i=>i.filter(o=>o!==r))}};return e}function Iv(t,e){let n=r=>async()=>{let i=e(r);return r.update(Ti,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update(Ti,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get($e).marks[t];if(!i)throw uh(t);return i},n}function Ga(t,e){let n=r=>async()=>{let i=e(r);return r.update(Ei,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update(Ei,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get($e).nodes[t];if(!i)throw _s(t);return i},n}function pe(t){let e,n=r=>async()=>(await r.wait(Ze),e=t(r),r.update(Lt,i=>[...i,e]),()=>{r.update(Lt,i=>i.filter(o=>o!==e))});return n.plugin=()=>e,n.key=()=>e.spec.key,n}function Nv(t){let e=n=>async()=>{await n.wait(Ai);let r=n.get(Xo),i=t(n),o=r.addObjectKeymap(i);return e.keymap=i,()=>{o()}};return e}function Ae(t,e){let n=Y(t,e),r=i=>(i.inject(n),()=>()=>{i.remove(n)});return r.key=n,r}function ce(t,e){let n=Ae(e,t),r=Ga(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.node=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>ce(t,o(e)),i}function Pt(t,e){let n=Ae(e,t),r=Iv(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.mark=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>Pt(t,o(e)),i}function We(t,e){let n=Ae(Object.fromEntries(Object.entries(e).map(([o,{shortcuts:s,priority:a}])=>[o,{shortcuts:s,priority:a}])),`${t}Keymap`),r=Nv(o=>{let s=o.get(n.key),a=Object.entries(e).flatMap(([l,{command:c}])=>{let u=s[l],f=[u.shortcuts].flat(),d=u.priority;return f.map(p=>[p,{key:p,onRun:c,priority:d}])});return Object.fromEntries(a)}),i=[n,r];return i.ctx=n,i.shortcuts=r,i.key=n.key,i.keymap=r.keymap,i}var vt=(t,e=()=>({}))=>Ae(e,`${t}Attr`),Dr=(t,e=()=>({}))=>Ae(e,`${t}Attr`);function gt(t,e,n){let r=Ae(n??{},t),i=s=>async()=>{await s.wait(mn);let a={plugin:e(s),options:s.get(r.key)};return s.update(Ri,l=>[...l,a]),()=>{s.update(Ri,l=>l.filter(c=>c!==a))}},o=[r,i];return o.id=t,o.plugin=i,o.options=r,o}function Dk(t){return e=>{let n=e.get(U),r=e.get($e),i=e.get(gn);if(!t)return i(n.state.doc);let o=n.state.doc.slice(t.from,t.to,!0),s=r.topNodeType.createAndFill(null,o.content);return s?i(s):(console.error("No document found"),"")}}function Yu(t,e=!1){return n=>{let r=n.get(U),i=n.get(He)(t);if(!i)return;if(!e){let c=r.state.selection.content();return r.dispatch(r.state.tr.replaceSelection(new R(i.content,c.openStart,c.openEnd)).scrollIntoView())}let o=n.get($e),s=Ct.fromSchema(o).serializeFragment(i.content),a=wt.fromSchema(o).parseSlice(s),l=Sa(a);if(l){r.dispatch(r.state.tr.replaceSelectionWith(l,!0));return}r.dispatch(r.state.tr.replaceSelection(a))}}function Lk(t,e=!1){return n=>{let r=n.get(U),i=n.get(He)(t);if(!i)return;if(!e){let{state:l}=r;return r.dispatch(l.tr.replace(0,l.doc.content.size,new R(i.content,0,0)))}let o=n.get($e),s=n.get(Uo)({schema:o,doc:i,plugins:n.get(Lt)}),a=mi.create(s);r.updateState(a)}}function Rv(t){return e=>{let n=e.get(He)(t),r=e.get($e),i=Ct.fromSchema(r).serializeFragment(n.content);return wt.fromSchema(r).parseSlice(i)}}function Qu(t,e){return n=>{let r=n.get(U),i=Rv(t)(n);r.dispatch(r.state.tr.replace(e.from,e.to,i))}}function Pk(t,e){return function(n,r){let{$from:i,$to:o,node:s}=n.selection;if(s&&s.isBlock||i.depth<2||!i.sameParent(o))return!1;let a=i.node(-1);if(a.type!=t)return!1;if(i.parent.content.size==0&&i.node(-1).childCount==i.indexAfter(-1)){if(i.depth==3||i.node(-3).type!=t||i.index(-2)!=i.node(-2).childCount-1)return!1;if(r){let f=M.empty,d=i.index(-1)?1:i.index(-2)?2:3;for(let y=i.depth-d;y>=i.depth-3;y--)f=M.from(i.node(y).copy(f));let p=i.indexAfter(-1){if(g>-1)return!1;y.isTextblock&&y.content.size==0&&(g=b+1)}),g>-1&&m.setSelection($.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let l=o.pos==i.end()?a.contentMatchAt(0).defaultType:null,c=n.tr.delete(i.pos,o.pos),u=l?[e?{type:t,attrs:e}:null,{type:l}]:void 0;return kr(c.doc,i.pos,2,u)?(r&&r(c.split(i.pos,2,u).scrollIntoView()),!0):!1}}function Xa(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,s=>s.childCount>0&&s.firstChild.type==t);return o?n?r.node(o.depth-1).type==t?Ov(e,n,t,o):Dv(e,n,o):!0:!1}}function Ov(t,e,n,r){let i=t.tr,o=r.end,s=r.$to.end(r.depth);om;h--)p-=i.child(h).nodeSize,r.delete(p-1,p+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let a=n.startIndex==0,l=n.endIndex==i.childCount,c=o.node(-1),u=o.index(-1);if(!c.canReplace(u+(a?0:1),u+1,s.content.append(l?M.empty:M.from(i))))return!1;let f=o.pos,d=f+s.nodeSize;return r.step(new ze(f-(a?1:0),d+(l?1:0),f+1,d-1,new R((a?M.empty:M.from(i.copy(M.empty))).append(l?M.empty:M.from(i.copy(M.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function Bk(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==t);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let a=o.parent,l=a.child(s-1);if(l.type!=t)return!1;if(n){let c=l.lastChild&&l.lastChild.type==a.type,u=M.from(c?t.create():null),f=new R(M.from(t.create(null,M.from(a.type.create(null,u)))),c?3:1,0),d=o.start,p=o.end;n(e.tr.step(new ze(d-(c?3:1),p,d,p,f,1,!0)).scrollIntoView())}return!0}}function Zu(t){let e=new Map;if(!t||!t.type)throw new Error("mdast-util-definitions expected node");return Rt(t,"definition",function(r){let i=Fk(r.identifier);i&&!e.get(i)&&e.set(i,r)}),n;function n(r){let i=Fk(r);return e.get(i)}}function Fk(t){return String(t||"").toUpperCase()}function Ya(){return function(t){let e=Zu(t);Rt(t,function(n,r,i){if(n.type==="definition"&&i!==void 0&&typeof r=="number")return i.children.splice(r,1),[ar,r];if(n.type==="imageReference"||n.type==="linkReference"){let o=e(n.identifier);if(o&&i&&typeof r=="number")return i.children[r]=n.type==="imageReference"?{type:"image",url:o.url,title:o.title,alt:n.alt}:{type:"link",url:o.url,title:o.title,children:n.children},[ar,r]}})}}function zk(t,e){if(!(e.childCount>=1&&e.lastChild?.type.name==="hardbreak")){t.next(e.content);return}let n=[];e.content.forEach((r,i,o)=>{o!==e.childCount-1&&n.push(r)}),t.next(M.fromArray(n))}function E(t,e){return Object.assign(t,{meta:{package:"@milkdown/preset-commonmark",...e}}),t}var ef=Dr("emphasis");E(ef,{displayName:"Attr",group:"Emphasis"});var Li=Pt("emphasis",t=>({attrs:{marker:{default:t.get(Mi).emphasis||"*",validate:"string"}},parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style",getAttrs:e=>e==="italic"}],toDOM:e=>["em",t.get(ef.key)(e)],parseMarkdown:{match:e=>e.type==="emphasis",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="emphasis",runner:(e,n)=>{e.withMark(n,"emphasis",void 0,{marker:n.attrs.marker})}}}));E(Li.mark,{displayName:"MarkSchema",group:"Emphasis"});E(Li.ctx,{displayName:"MarkSchemaCtx",group:"Emphasis"});var tf=z("ToggleEmphasis",t=>()=>Ln(Li.type(t)));E(tf,{displayName:"Command",group:"Emphasis"});var _k=ge(t=>ln(/(?:^|[^*])\*([^*]+)\*$/,Li.type(t),{getAttr:()=>({marker:"*"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("*")?{}:{fullMatch:e.slice(1),start:n+1}}));E(_k,{displayName:"InputRule|Star",group:"Emphasis"});var $k=ge(t=>ln(/\b_(?![_\s])(.*?[^_\s])_\b/,Li.type(t),{getAttr:()=>({marker:"_"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("_")?{}:{fullMatch:e.slice(1),start:n+1}}));E($k,{displayName:"InputRule|Underscore",group:"Emphasis"});var nf=We("emphasisKeymap",{ToggleEmphasis:{shortcuts:"Mod-i",command:t=>{let e=t.get(Q);return()=>e.call(tf.key)}}});E(nf.ctx,{displayName:"KeymapCtx",group:"Emphasis"});E(nf.shortcuts,{displayName:"Keymap",group:"Emphasis"});var rf=Dr("strong");E(rf,{displayName:"Attr",group:"Strong"});var Yo=Pt("strong",t=>({attrs:{marker:{default:t.get(Mi).strong||"*",validate:"string"}},parseDOM:[{tag:"b",getAttrs:e=>e.style.fontWeight!="normal"&&null},{tag:"strong"},{style:"font-style",getAttrs:e=>e==="bold"},{style:"font-weight=400",clearMark:e=>e.type.name=="strong"},{style:"font-weight",getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}],toDOM:e=>["strong",t.get(rf.key)(e)],parseMarkdown:{match:e=>e.type==="strong",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="strong",runner:(e,n)=>{e.withMark(n,"strong",void 0,{marker:n.attrs.marker})}}}));E(Yo.mark,{displayName:"MarkSchema",group:"Strong"});E(Yo.ctx,{displayName:"MarkSchemaCtx",group:"Strong"});var of=z("ToggleStrong",t=>()=>Ln(Yo.type(t)));E(of,{displayName:"Command",group:"Strong"});var Hk=ge(t=>ln(/(?({marker:e[0].startsWith("*")?"*":"_"})}));E(Hk,{displayName:"InputRule",group:"Strong"});var sf=We("strongKeymap",{ToggleBold:{shortcuts:["Mod-b"],command:t=>{let e=t.get(Q);return()=>e.call(of.key)}}});E(sf.ctx,{displayName:"KeymapCtx",group:"Strong"});E(sf.shortcuts,{displayName:"Keymap",group:"Strong"});var af=Dr("inlineCode");E(af,{displayName:"Attr",group:"InlineCode"});var jn=Pt("inlineCode",t=>({priority:100,code:!0,parseDOM:[{tag:"code"}],toDOM:e=>["code",t.get(af.key)(e)],parseMarkdown:{match:e=>e.type==="inlineCode",runner:(e,n,r)=>{e.openMark(r),e.addText(n.value),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="inlineCode",runner:(e,n,r)=>(e.withMark(n,"inlineCode",r.text||""),!0)}}));E(jn.mark,{displayName:"MarkSchema",group:"InlineCode"});E(jn.ctx,{displayName:"MarkSchemaCtx",group:"InlineCode"});var lf=z("ToggleInlineCode",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(r.empty)return!1;let{from:o,to:s}=r;return e.doc.rangeHasMark(o,s,jn.type(t))?(n?.(i.removeMark(o,s,jn.type(t))),!0):(Object.keys(e.schema.marks).filter(a=>a!==jn.type.name).map(a=>e.schema.marks[a]).forEach(a=>{i.removeMark(o,s,a)}),n?.(i.addMark(o,s,jn.type(t).create())),!0)});E(lf,{displayName:"Command",group:"InlineCode"});var Wk=ge(t=>ln(/(?:`)([^`]+)(?:`)$/,jn.type(t)));E(Wk,{displayName:"InputRule",group:"InlineCode"});var cf=We("inlineCodeKeymap",{ToggleInlineCode:{shortcuts:"Mod-e",command:t=>{let e=t.get(Q);return()=>e.call(lf.key)}}});E(cf.ctx,{displayName:"KeymapCtx",group:"InlineCode"});E(cf.shortcuts,{displayName:"Keymap",group:"InlineCode"});var Lv=new Set(["http:","https:","mailto:","tel:","ftp:"]);function Pv(t){return t<=32||t>=127&&t<=160||t>=8203&&t<=8205||t===8232||t===8233||t===65279}function Bv(t){let e="";for(let n of t)Pv(n.codePointAt(0)??0)||(e+=n);return e}function Fv(t){if(typeof t!="string")return"";let e=t.trim();if(!e)return"";let n=Bv(e),r=/^([a-z][a-z0-9+.-]*):/i.exec(n)?.[1];return!r||Lv.has(`${r.toLowerCase()}:`)?e:""}var uf=Dr("link");E(uf,{displayName:"Attr",group:"Link"});var Di=Pt("link",t=>({attrs:{href:{validate:"string"},title:{default:null,validate:"string|null"}},parseDOM:[{tag:"a[href]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{href:e.getAttribute("href"),title:e.getAttribute("title")}}}],toDOM:e=>["a",{...t.get(uf.key)(e),...e.attrs,href:Fv(e.attrs.href)}],parseMarkdown:{match:e=>e.type==="link",runner:(e,n,r)=>{let i=n.url,o=n.title;e.openMark(r,{href:i,title:o}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="link",runner:(e,n)=>{e.withMark(n,"link",void 0,{title:n.attrs.title,url:n.attrs.href})}}}));E(Di.mark,{displayName:"MarkSchema",group:"Link"});var jk=z("ToggleLink",t=>(e={})=>Ln(Di.type(t),e));E(jk,{displayName:"Command",group:"Link"});var Vk=z("UpdateLink",t=>(e={})=>(n,r)=>{if(!r)return!1;let i,o=-1,{selection:s}=n,{from:a,to:l}=s;if(n.doc.nodesBetween(a,a===l?l+1:l,(h,m)=>{if(Di.type(t).isInSet(h.marks))return i=h,o=m,!1}),!i)return!1;let c=i.marks.find(({type:h})=>h===Di.type(t));if(!c)return!1;let u=o,f=o+i.nodeSize,{tr:d}=n,p=Di.type(t).create({...c.attrs,...e});return p?(r(d.removeMark(u,f,c).addMark(u,f,p).setSelection(new B(d.selection.$anchor)).scrollIntoView()),!0):!1});E(Vk,{displayName:"Command",group:"Link"});var qk=Ga("doc",()=>({content:"block+",parseMarkdown:{match:({type:t})=>t==="root",runner:(t,e,n)=>{t.injectRoot(e,n)}},toMarkdown:{match:t=>t.type.name==="doc",runner:(t,e)=>{t.openNode("root"),t.next(e.content)}}}));E(qk,{displayName:"NodeSchema",group:"Doc"});function zv(t){return lr(t,e=>e.type==="html"&&["
","
","
","
"].includes(e.value?.trim()),(e,n)=>{if(!n.length)return;let r=n[n.length-1];if(!r)return;let i=r.children.indexOf(e);i!==-1&&r.children.splice(i,1)},!0)}var Za=gt("remark-preserve-empty-line",()=>()=>zv);E(Za.plugin,{displayName:"Remark",group:"Remark"});E(Za.options,{displayName:"RemarkConfig",group:"Remark"});var ff=vt("paragraph");E(ff,{displayName:"Attr",group:"Paragraph"});var Bt=ce("paragraph",t=>({content:"inline*",group:"block",parseDOM:[{tag:"p"}],toDOM:e=>["p",t.get(ff.key)(e),0],parseMarkdown:{match:e=>e.type==="paragraph",runner:(e,n,r)=>{e.openNode(r),n.children?e.next(n.children):e.addText(n.value||""),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="paragraph",runner:(e,n)=>{let r=t.get(U).state?.doc.lastChild;e.openNode("paragraph"),(!n.content||n.content.size===0)&&n!==r&&_v(t)?e.addNode("html",void 0,"
"):zk(e,n),e.closeNode()}}}));function _v(t){let e=!1;try{t.get(Za.id),e=!0}catch{e=!1}return e}E(Bt.node,{displayName:"NodeSchema",group:"Paragraph"});E(Bt.ctx,{displayName:"NodeSchemaCtx",group:"Paragraph"});var df=z("TurnIntoText",t=>()=>Dn(Bt.type(t)));E(df,{displayName:"Command",group:"Paragraph"});var pf=We("paragraphKeymap",{TurnIntoText:{shortcuts:"Mod-Alt-0",command:t=>{let e=t.get(Q);return()=>e.call(df.key)}}});E(pf.ctx,{displayName:"KeymapCtx",group:"Paragraph"});E(pf.shortcuts,{displayName:"Keymap",group:"Paragraph"});var $v=Array(6).fill(0).map((t,e)=>e+1);function Hv(t){return t.textContent.toLowerCase().trim().replace(/\s+/g,"-")}var el=Ae(Hv,"headingIdGenerator");E(el,{displayName:"Ctx",group:"Heading"});var hf=vt("heading");E(hf,{displayName:"Attr",group:"Heading"});var Pr=ce("heading",t=>{let e=t.get(el.key);return{content:"inline*",group:"block",defining:!0,attrs:{id:{default:"",validate:"string"},level:{default:1,validate:"number"}},parseDOM:$v.map(n=>({tag:`h${n}`,getAttrs:r=>{if(!(r instanceof HTMLElement))throw pt(r);return{level:n,id:r.id}}})),toDOM:n=>[`h${n.attrs.level}`,{...t.get(hf.key)(n),id:n.attrs.id||e(n)},0],parseMarkdown:{match:({type:n})=>n==="heading",runner:(n,r,i)=>{let o=r.depth;n.openNode(i,{level:o}),n.next(r.children),n.closeNode()}},toMarkdown:{match:n=>n.type.name==="heading",runner:(n,r)=>{n.openNode("heading",void 0,{depth:r.attrs.level}),zk(n,r),n.closeNode()}}}});E(Pr.node,{displayName:"NodeSchema",group:"Heading"});E(Pr.ctx,{displayName:"NodeSchemaCtx",group:"Heading"});var Kk=ge(t=>nu(/^(?#+)\s$/,Pr.type(t),e=>{let n=e.groups?.hashes?.length||0,{$from:r}=t.get(U).state.selection,i=r.node();if(i.type.name==="heading"){let o=Number(i.attrs.level)+Number(n);return o>6&&(o=6),{level:o}}return{level:n}}));E(Kk,{displayName:"InputRule",group:"Heading"});var Wn=z("WrapInHeading",t=>e=>(e??=1,e<1?Dn(Bt.type(t)):Dn(Pr.type(t),{level:e})));E(Wn,{displayName:"Command",group:"Heading"});var mf=z("DowngradeHeading",t=>()=>(e,n,r)=>{let{$from:i}=e.selection,o=i.node();if(o.type!==Pr.type(t)||!e.selection.empty||i.parentOffset!==0)return!1;let s=o.attrs.level-1;return s?(n?.(e.tr.setNodeMarkup(e.selection.$from.before(),void 0,{...o.attrs,level:s})),!0):Dn(Bt.type(t))(e,n,r)});E(mf,{displayName:"Command",group:"Heading"});var gf=We("headingKeymap",{TurnIntoH1:{shortcuts:"Mod-Alt-1",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,1)}},TurnIntoH2:{shortcuts:"Mod-Alt-2",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,2)}},TurnIntoH3:{shortcuts:"Mod-Alt-3",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,3)}},TurnIntoH4:{shortcuts:"Mod-Alt-4",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,4)}},TurnIntoH5:{shortcuts:"Mod-Alt-5",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,5)}},TurnIntoH6:{shortcuts:"Mod-Alt-6",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,6)}},DowngradeHeading:{shortcuts:["Delete","Backspace"],command:t=>{let e=t.get(Q);return()=>e.call(mf.key)}}});E(gf.ctx,{displayName:"KeymapCtx",group:"Heading"});E(gf.shortcuts,{displayName:"Keymap",group:"Heading"});var yf=vt("blockquote");E(yf,{displayName:"Attr
",group:"Blockquote"});var Qo=ce("blockquote",t=>({content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM:e=>["blockquote",t.get(yf.key)(e),0],parseMarkdown:{match:({type:e})=>e==="blockquote",runner:(e,n,r)=>{e.openNode(r).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="blockquote",runner:(e,n)=>{e.openNode("blockquote").next(n.content).closeNode()}}}));E(Qo.node,{displayName:"NodeSchema
",group:"Blockquote"});E(Qo.ctx,{displayName:"NodeSchemaCtx
",group:"Blockquote"});var Uk=ge(t=>Ca(/^\s*>\s$/,Qo.type(t)));E(Uk,{displayName:"InputRule",group:"Blockquote"});var kf=z("WrapInBlockquote",t=>()=>yi(Qo.type(t)));E(kf,{displayName:"Command",group:"Blockquote"});var bf=We("blockquoteKeymap",{WrapInBlockquote:{shortcuts:"Mod-Shift-b",command:t=>{let e=t.get(Q);return()=>e.call(kf.key)}}});E(bf.ctx,{displayName:"KeymapCtx
",group:"Blockquote"});E(bf.shortcuts,{displayName:"Keymap
",group:"Blockquote"});var xf=vt("codeBlock",()=>({pre:{},code:{}}));E(xf,{displayName:"Attr",group:"CodeBlock"});var Zo=ce("code_block",t=>({content:"text*",group:"block",marks:"",defining:!0,code:!0,attrs:{language:{default:"",validate:"string"}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{language:e.dataset.language}}}],toDOM:e=>{let n=t.get(xf.key)(e),r=e.attrs.language,i=r&&r.length>0?{"data-language":r}:void 0;return["pre",{...n.pre,...i},["code",n.code,0]]},parseMarkdown:{match:({type:e})=>e==="code",runner:(e,n,r)=>{let i=n.lang??"",o=n.value;e.openNode(r,{language:i}),o&&e.addText(o),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="code_block",runner:(e,n)=>{e.addNode("code",void 0,n.content.firstChild?.text||"",{lang:n.attrs.language})}}}));E(Zo.node,{displayName:"NodeSchema",group:"CodeBlock"});E(Zo.ctx,{displayName:"NodeSchemaCtx",group:"CodeBlock"});var Jk=ge(t=>nu(/^```(?[a-z]*)?[\s\n]$/,Zo.type(t),e=>({language:e.groups?.language??""})));E(Jk,{displayName:"InputRule",group:"CodeBlock"});var wf=z("CreateCodeBlock",t=>(e="")=>Dn(Zo.type(t),{language:e}));E(wf,{displayName:"Command",group:"CodeBlock"});var Wv=z("UpdateCodeBlockLanguage",()=>({pos:t,language:e}={pos:-1,language:""})=>(n,r)=>t>=0?(r?.(n.tr.setNodeAttribute(t,"language",e)),!0):!1);E(Wv,{displayName:"Command",group:"CodeBlock"});var Cf=We("codeBlockKeymap",{CreateCodeBlock:{shortcuts:"Mod-Alt-c",command:t=>{let e=t.get(Q);return()=>e.call(wf.key)}}});E(Cf.ctx,{displayName:"KeymapCtx",group:"CodeBlock"});E(Cf.shortcuts,{displayName:"Keymap",group:"CodeBlock"});var Sf=vt("image");E(Sf,{displayName:"Attr",group:"Image"});var Pi=ce("image",t=>({inline:!0,group:"inline",selectable:!0,draggable:!0,marks:"",atom:!0,defining:!0,isolating:!0,attrs:{src:{default:"",validate:"string"},alt:{default:"",validate:"string"},title:{default:"",validate:"string"}},parseDOM:[{tag:"img[src]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{src:e.getAttribute("src")||"",alt:e.getAttribute("alt")||"",title:e.getAttribute("title")||e.getAttribute("alt")||""}}}],toDOM:e=>["img",{...t.get(Sf.key)(e),...e.attrs}],parseMarkdown:{match:({type:e})=>e==="image",runner:(e,n,r)=>{let i=n.url,o=n.alt,s=n.title;e.addNode(r,{src:i,alt:o,title:s})}},toMarkdown:{match:e=>e.type.name==="image",runner:(e,n)=>{e.addNode("image",void 0,void 0,{title:n.attrs.title,url:n.attrs.src,alt:n.attrs.alt})}}}));E(Pi.node,{displayName:"NodeSchema",group:"Image"});E(Pi.ctx,{displayName:"NodeSchemaCtx",group:"Image"});var Gk=z("InsertImage",t=>(e={})=>(n,r)=>{if(!r)return!0;let{src:i="",alt:o="",title:s=""}=e,a=Pi.type(t).create({src:i,alt:o,title:s});return a&&r(n.tr.replaceSelectionWith(a).scrollIntoView()),!0});E(Gk,{displayName:"Command",group:"Image"});var Xk=z("UpdateImage",t=>(e={})=>(n,r)=>{let i=Gg(n.selection,Pi.type(t));if(!i)return!1;let{node:o,pos:s}=i,a={...o.attrs},{src:l,alt:c,title:u}=e;return l!==void 0&&(a.src=l),c!==void 0&&(a.alt=c),u!==void 0&&(a.title=u),r?.(n.tr.setNodeMarkup(s,void 0,a).scrollIntoView()),!0});E(Xk,{displayName:"Command",group:"Image"});var jv=ge(t=>new be(/!\[(?.*?)]\((?.*?)\s*(?="|\))"?(?[^"]+)?"?\)/,(e,n,r,i)=>{let[o,s,a="",l]=n;return o?e.tr.replaceWith(r,i,Pi.type(t).create({src:a,alt:s,title:l})):null}));E(jv,{displayName:"InputRule<insertImageInputRule>",group:"Image"});var Qa=vt("hardbreak",t=>({"data-type":"hardbreak","data-is-inline":t.attrs.isInline}));E(Qa,{displayName:"Attr<hardbreak>",group:"Hardbreak"});var Lr=ce("hardbreak",t=>({inline:!0,group:"inline",attrs:{isInline:{default:!1,validate:"boolean"}},selectable:!1,parseDOM:[{tag:"br"},{tag:'span[data-type="hardbreak"]',getAttrs:()=>({isInline:!0})}],toDOM:e=>e.attrs.isInline?["span",t.get(Qa.key)(e)," "]:["br",t.get(Qa.key)(e)],parseMarkdown:{match:({type:e})=>e==="break",runner:(e,n,r)=>{e.addNode(r,{isInline:!!n.data?.isInline})}},leafText:()=>` +`);return{dom:l,text:d,slice:e}}function Zy(t,e,n,r,i){let o=i.parent.type.spec.code,s,a;if(!n&&!e)return null;let l=!!e&&(r||o||!n);if(l){if(t.someProp("transformPastedText",d=>{e=d(e,o||r,t)}),o)return a=new R(M.from(t.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),t.someProp("transformPasted",d=>{a=d(a,t,!0)}),a;let f=t.someProp("clipboardTextParser",d=>d(e,i,r,t));if(f)a=f;else{let d=i.marks(),{schema:p}=t.state,h=Ct.fromSchema(p);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=s.appendChild(document.createElement("p"));m&&g.appendChild(h.serializeNode(p.text(m,d)))})}}else t.someProp("transformPastedHTML",f=>{n=f(n,t)}),s=DT(n),Wo&<(s);let c=s&&s.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let f=+u[3];f>0;f--){let d=s.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;s=d}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||wt.fromSchema(t.state.schema)).parseSlice(s,{preserveWhitespace:!!(l||u),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!NT.test(d.parentNode.nodeName)?{ignore:!0}:null}})),u)a=PT(Ty(a,+u[1],+u[2]),u[4]);else if(a=R.maxOpen(RT(a.content,i),!0),a.openStart||a.openEnd){let f=0,d=0;for(let p=a.content.firstChild;f<a.openStart&&!p.type.spec.isolating;f++,p=p.firstChild);for(let p=a.content.lastChild;d<a.openEnd&&!p.type.spec.isolating;d++,p=p.lastChild);a=Ty(a,f,d)}return t.someProp("transformPasted",f=>{a=f(a,t,l)}),a}var NT=/^(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 RT(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),o,s=[];if(t.forEach(a=>{if(!s)return;let l=i.findWrapping(a.type),c;if(!l)return s=null;if(c=s.length&&o.length&&tk(l,o,a,s[s.length-1],0))s[s.length-1]=c;else{s.length&&(s[s.length-1]=nk(s[s.length-1],o.length));let u=ek(a,l);s.push(u),i=i.matchType(u.type),o=l}}),s)return M.from(s)}return t}function ek(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,M.from(t));return t}function tk(t,e,n,r,i){if(i<t.length&&i<e.length&&t[i]==e[i]){let o=tk(t,e,n,r.lastChild,i+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(i==t.length-1?n.type:t[i+1]))return r.copy(r.content.append(M.from(ek(n,t,i+1))))}}function nk(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,nk(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(M.empty,!0);return t.copy(n.append(r))}function Iu(t,e,n,r,i,o){let s=e<0?t.firstChild:t.lastChild,a=s.content;return t.childCount>1&&(o=0),i<r-1&&(a=Iu(a,e,n,r,i+1,o)),i>=n&&(a=e<0?s.contentMatchAt(0).fillBefore(a,o<=i).append(a):a.append(s.contentMatchAt(s.childCount).fillBefore(M.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,s.copy(a))}function Ty(t,e,n){return e<t.openStart&&(t=new R(Iu(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new R(Iu(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}var rk={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};function ik(){return document.implementation.createHTMLDocument("title")}var hu=null;function OT(t){let e=window.trustedTypes;return e?(hu||(hu=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),hu.createHTML(t)):t}function DT(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=ik(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(t),o;if((o=i&&rk[i[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),r.innerHTML=OT(t),o)for(let s=0;s<o.length;s++)r=r.querySelector(o[s])||r;for(let s=0;s<n.styleSheets.length;s++){let a=n.styleSheets[s];for(let l=0;l<a.rules.length;l++){let c=a.rules[l];if(c instanceof CSSStyleRule){let u=r.querySelectorAll(c.selectorText);for(let f=0;f<u.length;f++)u[f].style.cssText+=c.style.cssText}}}return r}function LT(t){let e=t.querySelectorAll(Oe?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];r.childNodes.length==1&&r.textContent=="\xA0"&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function PT(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return t}let{content:i,openStart:o,openEnd:s}=t;for(let a=r.length-2;a>=0;a-=2){let l=n.nodes[r[a]];if(!l||l.hasRequiredAttrs())break;i=M.from(l.create(r[a+1],i)),o++,s++}return new R(i,o,s)}var Ye={},Qe={},BT={touchstart:!0,touchmove:!0},Nu=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function FT(t){for(let e in Ye){let n=Ye[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{_T(t,r)&&!Hu(t,r)&&(t.editable||!(r.type in Qe))&&n(t,r)},BT[e]?{passive:!0}:void 0)}Ge&&t.dom.addEventListener("input",()=>null),Ru(t)}function pn(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function zT(t){t.input.mouseDown&&t.input.mouseDown.done(),t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function Ru(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>Hu(t,r))})}function Hu(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function _T(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function $T(t,e){!Hu(t,e)&&Ye[e.type]&&(t.editable||!(e.type in Qe))&&Ye[e.type](t,e)}Qe.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!ak(t)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(dn&&Oe&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Si&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",i=>i(t,Cr(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||IT(t,n)?n.preventDefault():pn(t,"key")};Qe.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Qe.keypress=(t,e)=>{let n=e;if(ak(t)||!n.charCode||n.ctrlKey&&!n.altKey||St&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof B)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),o=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",s=>s(t,r.$from.pos,r.$to.pos,i,o))&&t.dispatch(o()),n.preventDefault()}};function jo(t){return{left:t.clientX,top:t.clientY}}function HT(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function Wu(t,e,n,r,i){if(r==-1)return!1;let o=t.state.doc.resolve(r);for(let s=o.depth+1;s>0;s--)if(t.someProp(e,a=>s>o.depth?a(t,n,o.nodeAfter,o.before(s),i,!0):a(t,n,o.node(s),o.before(s),i,!1)))return!0;return!1}function Vo(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);n=="pointer"&&r.setMeta("pointer",!0),t.dispatch(r)}function WT(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&H.isSelectable(r)?(Vo(t,new H(n),"pointer"),!0):!1}function jT(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof H&&(r=n.node);let o=t.state.doc.resolve(e);for(let s=o.depth+1;s>0;s--){let a=s>o.depth?o.nodeAfter:o.node(s);if(H.isSelectable(a)){r&&n.$from.depth>0&&s>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos?i=o.before(n.$from.depth):i=o.before(s);break}}return i!=null?(Vo(t,H.create(t.state.doc,i),"pointer"),!0):!1}function VT(t,e,n,r,i){return Wu(t,"handleClickOn",e,n,r)||t.someProp("handleClick",o=>o(t,e,r))||(i?jT(t,n):WT(t,n))}function qT(t,e,n,r){return Wu(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function KT(t,e,n,r){return Wu(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||UT(t,n,r)}function UT(t,e,n){if(n.button!=0)return!1;let r=ok(t,e,!0),i=t.state.doc;return r?(Vo(t,r,"pointer"),r instanceof B&&i.eq(t.state.doc)&&(t.input.mouseDown=new Du(t,r)),!0):!1}function ok(t,e,n){let r=t.state.doc;if(e==-1)return r.inlineContent?B.create(r,0,r.content.size):null;let i=r.resolve(e);for(let o=i.depth+1;o>0;o--){let s=o>i.depth?i.nodeAfter:i.node(o),a=i.before(o);if(s.inlineContent)return B.create(r,a+1,a+1+s.content.size);if(n&&H.isSelectable(s))return H.create(r,a)}return null}function ju(t){return Oa(t)}var sk=St?"metaKey":"ctrlKey";Ye.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=ju(t),i=Date.now(),o="singleClick";i-t.input.lastClick.time<500&&HT(n,t.input.lastClick)&&!n[sk]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?o="doubleClick":t.input.lastClick.type=="doubleClick"&&(o="tripleClick")),t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:o,button:n.button},t.input.mouseDown&&t.input.mouseDown.done();let s=t.posAtCoords(jo(n));s&&(o=="singleClick"?t.input.mouseDown=new Ou(t,s,n,!!r):(o=="doubleClick"?qT:KT)(t,s.pos,s.inside,n)?n.preventDefault():pn(t,"pointer"))};var Ra=class{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.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}},Ou=class extends Ra{constructor(e,n,r,i){super(e),this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[sk],this.allowDefault=r.shiftKey;let o,s;if(n.inside>-1)o=e.state.doc.nodeAt(n.inside),s=n.inside;else{let u=e.state.doc.resolve(n.pos);o=u.parent,s=u.depth?u.before():0}let a=i?null:r.target,l=a?e.docView.nearestDesc(a,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(o.type.spec.draggable&&o.type.spec.selectable!==!1||c instanceof H&&c.from<=s&&c.to>s)&&(this.mightDrag={node:o,pos:s,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Et&&!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()),pn(e,"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||hn(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(jo(e))),this.updateAllowDefault(e),this.allowDefault||!n?pn(this.view,"pointer"):VT(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Ge&&this.mightDrag&&!this.mightDrag.node.isAtom||Oe&&!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)?(Vo(this.view,$.near(this.view.state.doc.resolve(n.pos)),"pointer"),e.preventDefault()):pn(this.view,"pointer")}move(e){this.updateAllowDefault(e),pn(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}},Du=class extends Ra{constructor(e,n){super(e),this.startSelection=n,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),pn(this.view,"pointer");let n=this.view.posAtCoords(jo(e)),r=n&&ok(this.view,n.inside,!1);if(!r)return;let{doc:i}=this.view.state,o=this.startSelection,[s,a]=r.from<o.from?[o.to,r.from]:[o.from,r.to];Vo(this.view,B.create(i,s,a),"pointer")}};Ye.touchstart=t=>{t.input.lastTouch=Date.now(),ju(t),pn(t,"pointer")};Ye.touchmove=t=>{t.input.lastTouch=Date.now(),pn(t,"pointer")};Ye.contextmenu=t=>ju(t);function ak(t,e){return t.composing?!0:Ge&&Math.abs(Date.now()-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}var JT=dn?5e3:-1;Qe.compositionstart=Qe.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof B&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Oe&&_y&>(t)))t.markCursor=t.state.storedMarks||n.marks(),Oa(t,!0),t.markCursor=null;else if(Oa(t,!e.selection.empty),Et&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,o=r.focusOffset;i&&i.nodeType==1&&o!=0;){let s=o<0?i.lastChild:i.childNodes[o-1];if(!s)break;if(s.nodeType==3){let a=t.domSelection();a&&a.collapse(s,s.nodeValue.length);break}else i=s,o=-1}}t.input.composing=!0}lk(t,JT)};function GT(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Qe.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,lk(t,20))};function lk(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Oa(t),e))}function ck(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function XT(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=UE(e.focusNode,e.focusOffset),r=JE(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let s=n.pmViewDesc;if(!(!s||!s.isText(n.nodeValue)))return r}}return n||r}function Oa(t,e=!1){if(!(dn&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),ck(t),e||t.docView&&t.docView.dirty){let n=zu(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function YT(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}var Fo=it&&_n<15||Si&&QE<604;Ye.copy=Qe.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let o=Fo?null:n.clipboardData,s=r.content(),{dom:a,text:l}=$u(t,s);o?(n.preventDefault(),o.clearData(),o.setData("text/html",a.innerHTML),o.setData("text/plain",l)):YT(t,a),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function QT(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function ZT(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.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=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?zo(t,r.value,null,i,e):zo(t,r.textContent,r.innerHTML,i,e)},50)}function zo(t,e,n,r,i){let o=Zy(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,i,o||R.empty)))return!0;if(!o)return!1;let s=QT(o),a=s?t.state.tr.replaceSelectionWith(s,r):t.state.tr.replaceSelection(o);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function uk(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Qe.paste=(t,e)=>{let n=e;if(t.composing&&!dn)return;let r=Fo?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&zo(t,uk(r),r.getData("text/html"),i,n)?n.preventDefault():ZT(t,n)};var Da=class{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}},ev=St?"altKey":"ctrlKey";function fk(t,e){let n;return t.someProp("dragCopies",r=>{n=n||r(e)}),n!=null?!n:!e[ev]}Ye.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,o=i.empty?null:t.posAtCoords(jo(n)),s;if(!(o&&o.pos>=i.from&&o.pos<=(i instanceof H?i.to-1:i.to))){if(r&&r.mightDrag)s=H.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let f=t.docView.nearestDesc(n.target,!0);f&&f.node.type.spec.draggable&&f!=t.docView&&(s=H.create(t.state.doc,f.posBefore))}}let a=(s||t.state.selection).content(),{dom:l,text:c,slice:u}=$u(t,a);(!n.dataTransfer.files.length||!Oe||zy>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Fo?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Fo||n.dataTransfer.setData("text/plain",c),t.dragging=new Da(u,fk(t,n),s)};Ye.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Qe.dragover=Qe.dragenter=(t,e)=>e.preventDefault();Qe.drop=(t,e)=>{try{tv(t,e,t.dragging)}finally{t.dragging=null}};function tv(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(jo(e));if(!r)return;let i=t.state.doc.resolve(r.pos),o=n&&n.slice;o?t.someProp("transformPasted",p=>{o=p(o,t,!1)}):o=Zy(t,uk(e.dataTransfer),Fo?null:e.dataTransfer.getData("text/html"),!1,i);let s=!!(n&&fk(t,e));if(t.someProp("handleDrop",p=>p(t,e,o||R.empty,s))){e.preventDefault();return}if(!o)return;e.preventDefault();let a=o?yg(t.state.doc,i.pos,o):i.pos;a==null&&(a=i.pos);let l=t.state.tr;if(s){let{node:p}=n;p?p.replace(l):l.deleteSelection()}let c=l.mapping.map(a),u=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,f=l.doc;if(u?l.replaceRangeWith(c,c,o.content.firstChild):l.replaceRange(c,c,o),l.doc.eq(f))return;let d=l.doc.resolve(c);if(u&&H.isSelectable(o.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(o.content.firstChild))l.setSelection(new H(d));else{let p=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((h,m,g,y)=>p=y),l.setSelection(_u(t,d,l.doc.resolve(p)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}Ye.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&hn(t)},20))};Ye.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};Ye.beforeinput=(t,e)=>{if(Oe&&dn&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",o=>o(t,Cr(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Qe)Ye[t]=Qe[t];function _o(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}var La=class t{constructor(e,n){this.toDOM=e,this.spec=n||vr,this.side=this.spec.side||0}map(e,n,r,i){let{pos:o,deleted:s}=e.mapResult(n.from+i,this.side<0?-1:1);return s?null:new le(o-r,o-r,this)}valid(){return!0}eq(e){return this==e||e instanceof t&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&_o(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},Tr=class t{constructor(e,n){this.attrs=e,this.spec=n||vr}map(e,n,r,i){let o=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,s=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return o>=s?null:new le(o,s,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof t&&_o(this.attrs,e.attrs)&&_o(this.spec,e.spec)}static is(e){return e.type instanceof t}destroy(){}},Lu=class t{constructor(e,n){this.attrs=e,this.spec=n||vr}map(e,n,r,i){let o=e.mapResult(n.from+i,1);if(o.deleted)return null;let s=e.mapResult(n.to+i,-1);return s.deleted||s.pos<=o.pos?null:new le(o.pos-r,s.pos-r,this)}valid(e,n){let{index:r,offset:i}=e.content.findIndex(n.from),o;return i==n.from&&!(o=e.child(r)).isText&&i+o.nodeSize==n.to}eq(e){return this==e||e instanceof t&&_o(this.attrs,e.attrs)&&_o(this.spec,e.spec)}destroy(){}},le=class t{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new t(e,n,this.type)}eq(e,n=0){return this.type.eq(e.type)&&this.from+n==e.from&&this.to+n==e.to}map(e,n,r){return this.type.map(e,this,n,r)}static widget(e,n,r){return new t(e,e,new La(n,r))}static inline(e,n,r,i){return new t(e,n,new Tr(r,i))}static node(e,n,r,i){return new t(e,n,new Lu(r,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof Tr}get widget(){return this.type instanceof La}},wi=[],vr={},ae=class t{constructor(e,n){this.local=e.length?e:wi,this.children=n.length?n:wi}static create(e,n){return n.length?Ba(n,e,0,vr):Je}find(e,n,r){let i=[];return this.findInner(e??0,n??1e9,i,0,r),i}findInner(e,n,r,i,o){for(let s=0;s<this.local.length;s++){let a=this.local[s];a.from<=n&&a.to>=e&&(!o||o(a.spec))&&r.push(a.copy(a.from+i,a.to+i))}for(let s=0;s<this.children.length;s+=3)if(this.children[s]<n&&this.children[s+1]>e){let a=this.children[s]+1;this.children[s+2].findInner(e-a,n-a,r,i+a,o)}}map(e,n,r){return this==Je||e.maps.length==0?this:this.mapInner(e,n,0,0,r||vr)}mapInner(e,n,r,i,o){let s;for(let a=0;a<this.local.length;a++){let l=this.local[a].map(e,r,i);l&&l.type.valid(n,l)?(s||(s=[])).push(l):o.onRemove&&o.onRemove(this.local[a].spec)}return this.children.length?nv(this.children,s||[],e,n,r,i,o):s?new t(s.sort(Ar),wi):Je}add(e,n){return n.length?this==Je?t.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let i,o=0;e.forEach((a,l)=>{let c=l+r,u;if(u=pk(n,a,c)){for(i||(i=this.children.slice());o<i.length&&i[o]<l;)o+=3;i[o]==l?i[o+2]=i[o+2].addInner(a,u,c+1):i.splice(o,0,l,l+a.nodeSize,Ba(u,a,c+1,vr)),o+=3}});let s=dk(o?hk(n):n,-r);for(let a=0;a<s.length;a++)s[a].type.valid(e,s[a])||s.splice(a--,1);return new t(s.length?this.local.concat(s).sort(Ar):this.local,i||this.children)}remove(e){return e.length==0||this==Je?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,i=this.local;for(let o=0;o<r.length;o+=3){let s,a=r[o]+n,l=r[o+1]+n;for(let u=0,f;u<e.length;u++)(f=e[u])&&f.from>a&&f.to<l&&(e[u]=null,(s||(s=[])).push(f));if(!s)continue;r==this.children&&(r=this.children.slice());let c=r[o+2].removeInner(s,a+1);c!=Je?r[o+2]=c:(r.splice(o,3),o-=3)}if(i.length){for(let o=0,s;o<e.length;o++)if(s=e[o])for(let a=0;a<i.length;a++)i[a].eq(s,n)&&(i==this.local&&(i=this.local.slice()),i.splice(a--,1))}return r==this.children&&i==this.local?this:i.length||r.length?new t(i,r):Je}forChild(e,n){if(this==Je)return this;if(n.isLeaf)return t.empty;let r,i;for(let a=0;a<this.children.length;a+=3)if(this.children[a]>=e){this.children[a]==e&&(r=this.children[a+2]);break}let o=e+1,s=o+n.content.size;for(let a=0;a<this.local.length;a++){let l=this.local[a];if(l.from<s&&l.to>o&&l.type instanceof Tr){let c=Math.max(o,l.from)-o,u=Math.min(s,l.to)-o;c<u&&(i||(i=[])).push(l.copy(c,u))}}if(i){let a=new t(i.sort(Ar),wi);return r?new Pa([a,r]):a}return r||Je}eq(e){if(this==e)return!0;if(!(e instanceof t)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let n=0;n<this.local.length;n++)if(!this.local[n].eq(e.local[n]))return!1;for(let n=0;n<this.children.length;n+=3)if(this.children[n]!=e.children[n]||this.children[n+1]!=e.children[n+1]||!this.children[n+2].eq(e.children[n+2]))return!1;return!0}locals(e){return Vu(this.localsInner(e))}localsInner(e){if(this==Je)return wi;if(e.inlineContent||!this.local.some(Tr.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof Tr||n.push(this.local[r]);return n}forEachSet(e){e(this)}};ae.empty=new ae([],[]);ae.removeOverlap=Vu;var Je=ae.empty,Pa=class t{constructor(e){this.members=e}map(e,n){let r=this.members.map(i=>i.map(e,n,vr));return t.from(r)}forChild(e,n){if(n.isLeaf)return ae.empty;let r=[];for(let i=0;i<this.members.length;i++){let o=this.members[i].forChild(e,n);o!=Je&&(o instanceof t?r=r.concat(o.members):r.push(o))}return t.from(r)}eq(e){if(!(e instanceof t)||e.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(e.members[n]))return!1;return!0}locals(e){let n,r=!0;for(let i=0;i<this.members.length;i++){let o=this.members[i].localsInner(e);if(o.length)if(!n)n=o;else{r&&(n=n.slice(),r=!1);for(let s=0;s<o.length;s++)n.push(o[s])}}return n?Vu(r?n:n.sort(Ar)):wi}static from(e){switch(e.length){case 0:return Je;case 1:return e[0];default:return new t(e.every(n=>n instanceof ae)?e:e.reduce((n,r)=>n.concat(r instanceof ae?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}};function nv(t,e,n,r,i,o,s){let a=t.slice();for(let c=0,u=o;c<n.maps.length;c++){let f=0;n.maps[c].forEach((d,p,h,m)=>{let g=m-h-(p-d);for(let y=0;y<a.length;y+=3){let b=a[y+1];if(b<0||d>b+u-f)continue;let C=a[y]+u-f;p>=C?a[y+1]=d<=C?-2:-1:d>=u&&g&&(a[y]+=g,a[y+1]+=g)}f+=g}),u=n.maps[c].map(u,-1)}let l=!1;for(let c=0;c<a.length;c+=3)if(a[c+1]<0){if(a[c+1]==-2){l=!0,a[c+1]=-1;continue}let u=n.map(t[c]+o),f=u-i;if(f<0||f>=r.content.size){l=!0;continue}let d=n.map(t[c+1]+o,-1),p=d-i,{index:h,offset:m}=r.content.findIndex(f),g=r.maybeChild(h);if(g&&m==f&&m+g.nodeSize==p){let y=a[c+2].mapInner(n,g,u+1,t[c]+o+1,s);y!=Je?(a[c]=f,a[c+1]=p,a[c+2]=y):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=rv(a,t,e,n,i,o,s),u=Ba(c,r,0,s);e=u.local;for(let f=0;f<a.length;f+=3)a[f+1]<0&&(a.splice(f,3),f-=3);for(let f=0,d=0;f<u.children.length;f+=3){let p=u.children[f];for(;d<a.length&&a[d]<p;)d+=3;a.splice(d,0,u.children[f],u.children[f+1],u.children[f+2])}}return new ae(e.sort(Ar),a)}function dk(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let i=t[r];n.push(new le(i.from+e,i.to+e,i.type))}return n}function rv(t,e,n,r,i,o,s){function a(l,c){for(let u=0;u<l.local.length;u++){let f=l.local[u].map(r,i,c);f?n.push(f):s.onRemove&&s.onRemove(l.local[u].spec)}for(let u=0;u<l.children.length;u+=3)a(l.children[u+2],l.children[u]+c+1)}for(let l=0;l<t.length;l+=3)t[l+1]==-1&&a(t[l+2],e[l]+o+1);return n}function pk(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,i=null;for(let o=0,s;o<t.length;o++)(s=t[o])&&s.from>n&&s.to<r&&((i||(i=[])).push(s),t[o]=null);return i}function hk(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Ba(t,e,n,r){let i=[],o=!1;e.forEach((a,l)=>{let c=pk(t,a,l+n);if(c){o=!0;let u=Ba(c,a,n+l+1,r);u!=Je&&i.push(l,l+a.nodeSize,u)}});let s=dk(o?hk(t):t,-n).sort(Ar);for(let a=0;a<s.length;a++)s[a].type.valid(e,s[a])||(r.onRemove&&r.onRemove(s[a].spec),s.splice(a--,1));return s.length||i.length?new ae(s,i):Je}function Ar(t,e){return t.from-e.from||t.to-e.to}function Vu(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let i=n+1;i<e.length;i++){let o=e[i];if(o.from==r.from){o.to!=r.to&&(e==t&&(e=t.slice()),e[i]=o.copy(o.from,r.to),vy(e,i+1,o.copy(r.to,o.to)));continue}else{o.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,o.from),vy(e,i,r.copy(o.from,r.to)));break}}}return e}function vy(t,e,n){for(;e<t.length&&Ar(n,t[e])>0;)e++;t.splice(e,0,n)}function mu(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Je&&e.push(r)}),t.cursorWrapper&&e.push(ae.create(t.state.doc,[t.cursorWrapper.deco])),Pa.from(e)}var iv={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},ov=it&&_n<=11,Pu=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},Bu=class{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Pu,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;i<r.length;i++)this.queue.push(r[i]);it&&_n<=11&&r.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():Ge&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),ov&&(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,iv)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let n=0;n<e.length;n++)this.queue.push(e[n]);window.setTimeout(()=>this.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(xy(this.view)){if(this.suppressingSelectionUpdates)return hn(this.view);if(it&&_n<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ir(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let o=e.focusNode;o;o=Ci(o))n.add(o);for(let o=e.anchorNode;o;o=Ci(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 e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&xy(e)&&!this.ignoreSelectionChange(r),o=-1,s=-1,a=!1,l=[];if(e.editable)for(let u=0;u<n.length;u++){let f=this.registerMutation(n[u],l);f&&(o=o<0?f.from:Math.min(f.from,o),s=s<0?f.to:Math.max(f.to,s),f.typeOver&&(a=!0))}if(l.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||Oe&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&n.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of l)if(u.nodeName=="BR"&&u.parentNode){let f=u.nextSibling;for(;f&&f.nodeType==1;){if(f.contentEditable=="false"){u.parentNode.removeChild(u);break}f=f.firstChild}}}else if(Et&&l.length){let u=l.filter(f=>f.nodeName=="BR");if(u.length==2){let[f,d]=u;f.parentNode&&f.parentNode.parentNode==d.parentNode?d.remove():f.remove()}else{let{focusNode:f}=this.currentSelection;for(let d of u){let p=d.parentNode;p&&p.nodeName=="LI"&&(!f||lv(e,f)!=p)&&d.remove()}}}let c=null;o<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&Fa(r)&&(c=zu(e))&&c.eq($.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,hn(e),this.currentSelection.set(r),e.scrollToSelection()):(o>-1||i)&&(o>-1&&(e.docView.markDirty(o,s),sv(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,cv(e,l)),this.handleDOMChange(o,s,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||hn(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let f=e.addedNodes[u];n.push(f),f.nodeType==3&&(this.lastChangedTextNode=f)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let i=e.previousSibling,o=e.nextSibling;if(it&&_n<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:f,nextSibling:d}=e.addedNodes[u];(!f||Array.prototype.indexOf.call(e.addedNodes,f)<0)&&(i=f),(!d||Array.prototype.indexOf.call(e.addedNodes,d)<0)&&(o=d)}let s=i&&i.parentNode==e.target?_e(i)+1:0,a=r.localPosFromDOM(e.target,s,-1),l=o&&o.parentNode==e.target?_e(o):e.target.childNodes.length,c=r.localPosFromDOM(e.target,l,1);return{from:a,to:c}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}},Ay=new WeakMap,Iy=!1;function sv(t){if(!Ay.has(t)&&(Ay.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=Et,Iy)return;console.warn("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."),Iy=!0}}function Ny(t,e){let n=e.startContainer,r=e.startOffset,i=e.endContainer,o=e.endOffset,s=t.domAtPos(t.state.selection.anchor);return Ir(s.node,s.offset,i,o)&&([n,r,i,o]=[i,o,n,r]),{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:o}}function av(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return Ny(t,i)}let n;function r(i){i.preventDefault(),i.stopImmediatePropagation(),n=i.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?Ny(t,n):null}function lv(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function cv(t,e){var n;let{focusNode:r,focusOffset:i}=t.domSelectionRange();for(let o of e)if(((n=o.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let s=o.nextSibling;for(;s&&s.nodeName!="TD"&&s.nodeName!="TH";)s=s.nextSibling;if(s){let a=s;for(;;){let l=a.firstChild;if(!l||l.nodeType!=1||l.contentEditable=="false"||/^(BR|IMG)$/.test(l.nodeName))break;a=l}a.insertBefore(o,a.firstChild),r==o&&t.domSelection().collapse(o,i)}else o.parentNode.removeChild(o)}}function uv(t,e,n){let{node:r,fromOffset:i,toOffset:o,from:s,to:a}=t.docView.parseRange(e,n),l=t.domSelectionRange(),c,u=l.anchorNode;if(u&&t.dom.contains(u.nodeType==1?u:u.parentNode)&&(c=[{node:u,offset:l.anchorOffset}],Fa(l)||c.push({node:l.focusNode,offset:l.focusOffset})),Oe&&t.input.lastKeyCode===8)for(let g=o;g>i;g--){let y=r.childNodes[g-1],b=y.pmViewDesc;if(y.nodeName=="BR"&&!b){o=g;break}if(!b||b.size)break}let f=t.state.doc,d=t.someProp("domParser")||wt.fromSchema(t.state.schema),p=f.resolve(s),h=null,m=d.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:i,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:fv,context:p});if(c&&c[0].pos!=null){let g=c[0].pos,y=c[1]&&c[1].pos;y==null&&(y=g),h={anchor:g+s,head:y+s}}return{doc:m,sel:h,from:s,to:a}}function fv(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Ge&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||Ge&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}var dv=/^(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 pv(t,e,n,r,i){let o=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let N=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,P=zu(t,N);if(P&&!t.state.selection.eq(P)){if(Oe&&dn&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",S=>S(t,Cr(13,"Enter"))))return;let O=t.state.tr.setSelection(P);N=="pointer"?O.setMeta("pointer",!0):N=="key"&&O.scrollIntoView(),o&&O.setMeta("composition",o),t.dispatch(O)}return}let s=t.state.doc.resolve(e),a=s.sharedDepth(n);e=s.before(a+1),n=t.state.doc.resolve(n).after(a+1);let l=t.state.selection,c=uv(t,e,n),u=t.state.doc,f=u.slice(c.from,c.to),d,p;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(d=t.state.selection.to,p="end"):(d=t.state.selection.from,p="start"),t.input.lastKeyCode=null;let h=gv(f.content,c.doc.content,c.from,d,p);if(h&&t.input.domChangeCount++,(Si&&t.input.lastIOSEnter>Date.now()-225||dn)&&i.some(N=>N.nodeType==1&&!dv.test(N.nodeName))&&(!h||h.endA>=h.endB)&&t.someProp("handleKeyDown",N=>N(t,Cr(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!h)if(r&&l instanceof B&&!l.empty&&l.$head.sameParent(l.$anchor)&&!t.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))h={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let N=Ry(t,t.state.doc,c.sel);if(N&&!N.eq(t.state.selection)){let P=t.state.tr.setSelection(N);o&&P.setMeta("composition",o),t.dispatch(P)}}return}t.state.selection.from<t.state.selection.to&&h.start==h.endB&&t.state.selection instanceof B&&(h.start>t.state.selection.from&&h.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?h.start=t.state.selection.from:h.endA<t.state.selection.to&&h.endA>=t.state.selection.to-2&&t.state.selection.to<=c.to&&(h.endB+=t.state.selection.to-h.endA,h.endA=t.state.selection.to)),it&&_n<=11&&h.endB==h.start+1&&h.endA==h.start&&h.start>c.from&&c.doc.textBetween(h.start-c.from-1,h.start-c.from+1)==" \xA0"&&(h.start--,h.endA--,h.endB--);let m=c.doc.resolveNoCache(h.start-c.from),g=c.doc.resolveNoCache(h.endB-c.from),y=u.resolve(h.start),b=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=h.endA;if((Si&&t.input.lastIOSEnter>Date.now()-225&&(!b||i.some(N=>N.nodeName=="DIV"||N.nodeName=="P"))||!b&&m.pos<c.doc.content.size&&(!m.sameParent(g)||!m.parent.inlineContent)&&m.pos<g.pos&&!/\S/.test(c.doc.textBetween(m.pos,g.pos,"","")))&&t.someProp("handleKeyDown",N=>N(t,Cr(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>h.start&&mv(u,h.start,h.endA,m,g)&&t.someProp("handleKeyDown",N=>N(t,Cr(8,"Backspace")))){dn&&Oe&&t.domObserver.suppressSelectionUpdates();return}Oe&&h.endB==h.start&&(t.input.lastChromeDelete=Date.now()),dn&&!b&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==h.endA&&(h.endB-=2,g=c.doc.resolveNoCache(h.endB-c.from),setTimeout(()=>{t.someProp("handleKeyDown",function(N){return N(t,Cr(13,"Enter"))})},20));let C=h.start,v=h.endA,A=N=>{let P=N||t.state.tr.replace(C,v,c.doc.slice(h.start-c.from,h.endB-c.from));if(c.sel){let O=Ry(t,P.doc,c.sel);O&&!(Oe&&t.composing&&O.empty&&(h.start!=h.endB||t.input.lastChromeDelete<Date.now()-100)&&(O.head==C||O.head==P.mapping.map(v)-1)||it&&O.empty&&O.head==C)&&P.setSelection(O)}return o&&P.setMeta("composition",o),P.scrollIntoView()},w;if(b)if(m.pos==g.pos){it&&_n<=11&&m.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>hn(t),20));let N=A(t.state.tr.delete(C,v)),P=u.resolve(h.start).marksAcross(u.resolve(h.endA));P&&N.ensureMarks(P),t.dispatch(N)}else if(h.endA==h.endB&&(w=hv(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,h.endA-y.start())))){let N=A(t.state.tr);w.type=="add"?N.addMark(C,v,w.mark):N.removeMark(C,v,w.mark),t.dispatch(N)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let N=m.parent.textBetween(m.parentOffset,g.parentOffset),P=()=>A(t.state.tr.insertText(N,C,v));t.someProp("handleTextInput",O=>O(t,C,v,N,P))||t.dispatch(P())}else t.dispatch(A());else t.dispatch(A())}function Ry(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:_u(t,e.resolve(n.anchor),e.resolve(n.head))}function hv(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,o=r,s,a,l;for(let u=0;u<r.length;u++)i=r[u].removeFromSet(i);for(let u=0;u<n.length;u++)o=n[u].removeFromSet(o);if(i.length==1&&o.length==0)a=i[0],s="add",l=u=>u.mark(a.addToSet(u.marks));else if(i.length==0&&o.length==1)a=o[0],s="remove",l=u=>u.mark(a.removeFromSet(u.marks));else return null;let c=[];for(let u=0;u<e.childCount;u++)c.push(l(e.child(u)));if(M.from(c).eq(t))return{mark:a,type:s}}function mv(t,e,n,r,i){if(n-e<=i.pos-r.pos||gu(r,!0,!1)<i.pos)return!1;let o=t.resolve(e);if(!r.parent.isTextblock){let a=o.nodeAfter;return a!=null&&n==e+a.nodeSize}if(o.parentOffset<o.parent.content.size||!o.parent.isTextblock)return!1;let s=t.resolve(gu(o,!0,!0));return!s.parent.isTextblock||s.pos>n||gu(s,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(s.parent.content)}function gu(t,e,n){let r=t.depth,i=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let o=t.node(r).maybeChild(t.indexAfter(r));for(;o&&!o.isLeaf;)o=o.firstChild,i++}return i}function gv(t,e,n,r,i){let o=t.findDiffStart(e,n),s=n+t.size,a=n+e.size;if(o==null)return null;let{a:l,b:c}=t.findDiffEnd(e,s,a);if(i=="end"){let u=Math.max(0,o-Math.min(l,c));r-=l+u-o}if(l<o&&s<a){let u=r<=o&&r>=l?o-r:0;o-=u,c=o+(c-l),l=o}else if(c<o){let u=r<=o&&r>=c?o-r:0;o-=u,l=o+(l-c),c=o}return{start:o,endA:l,endB:c}}var $o=class{constructor(e,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 Nu,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(By),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=Ly(this),Dy(this),this.nodeViews=Py(this),this.docView=hy(this.state.doc,Oy(this),mu(this),this.dom,this),this.domObserver=new Bu(this,(r,i,o,s)=>pv(this,r,i,o,s)),this.domObserver.start(),FT(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&Ru(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(By),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let i=this.state,o=!1,s=!1;e.storedMarks&&this.composing&&(ck(this),s=!0),this.state=e;let a=i.plugins!=e.plugins||this._props.plugins!=n.plugins;if(a||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=Py(this);kv(p,this.nodeViews)&&(this.nodeViews=p,o=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&Ru(this),this.editable=Ly(this),Dy(this);let l=mu(this),c=Oy(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",f=o||!this.docView.matchesNode(e.doc,c,l);(f||!e.selection.eq(i.selection))&&(s=!0);let d=u=="preserve"&&s&&this.dom.style.overflowAnchor==null&&tT(this);if(s){this.domObserver.stop();let p=f&&(it||Oe)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&yv(i.selection,e.selection);if(f){let m=Oe?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=XT(this)),(o||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=hy(e.doc,c,l,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}let h=this.input.mouseDown;p||!(h&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&CT(this)&&h.delaySelUpdate())?hn(this,p):(Xy(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():d&&nT(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof H){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&cy(this,n.getBoundingClientRect(),e)}else cy(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let r=this.state.plugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let r=this.pluginViews[n];r.update&&r.update(this,e)}}updateDraggedNode(e,n){let r=e.node,i=-1;if(r.from<this.state.doc.content.size&&this.state.doc.nodeAt(r.from)==r.node)i=r.from;else{let o=r.from+(this.state.doc.content.size-n.doc.content.size);(o>0&&o<this.state.doc.content.size&&this.state.doc.nodeAt(o))==r.node&&(i=o)}this.dragging=new Da(e.slice,e.move,i<0?void 0:H.create(this.state.doc,i))}someProp(e,n){let r=this._props&&this._props[e],i;if(r!=null&&(i=n?n(r):r))return i;for(let s=0;s<this.directPlugins.length;s++){let a=this.directPlugins[s].props[e];if(a!=null&&(i=n?n(a):a))return i}let o=this.state.plugins;if(o)for(let s=0;s<o.length;s++){let a=o[s].props[e];if(a!=null&&(i=n?n(a):a))return i}}hasFocus(){if(it){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&rT(this.dom),hn(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let n=this.dom.parentNode;n;n=n.parentNode)if(n.nodeType==9||n.nodeType==11&&n.host)return n.getSelection||(Object.getPrototypeOf(n).getSelection=()=>n.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return lT(this,e)}coordsAtPos(e,n=1){return Vy(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return pT(this,n||this.state,e)}pasteHTML(e,n){return zo(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return zo(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return $u(this,e)}destroy(){this.docView&&(zT(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],mu(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,qE())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return $T(this,e)}domSelectionRange(){let e=this.domSelection();return e?Ge&&this.root.nodeType===11&&XE(this.dom.ownerDocument)==this.dom&&av(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};$o.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function Oy(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[le.node(0,t.state.doc.content.size,e)]}function Dy(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:le.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Ly(t){return!t.someProp("editable",e=>e(t.state)===!1)}function yv(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function Py(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function kv(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function By(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}function yn(t,e){return t.meta={package:"@milkdown/core",group:"System",...e},t}var yk={text:(t,e,n,r)=>{let i=t.value;return/^[^*_\\]*\s+$/.test(i)?i:n.safe(i,{...r,encode:[]})},strong:(t,e,n,r)=>{let i=t.marker||n.options.strong||"*",o=n.enter("strong"),s=n.createTracker(r),a=s.move(i+i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i+i),o(),a},emphasis:(t,e,n,r)=>{let i=t.marker||n.options.emphasis||"*",o=n.enter("emphasis"),s=n.createTracker(r),a=s.move(i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i),o(),a}},U=Y({},"editorView"),qo=Y({},"editorState"),qu=Y([],"initTimer"),mk=Y({},"editor"),Ni=Y([],"inputRules"),Lt=Y([],"prosePlugins"),Ri=Y([],"remarkPlugins"),Ua=Y([],"nodeView"),Ja=Y([],"markView"),Rr=Y(xo().use(ii).use(li),"remark"),Mi=Y({handlers:yk,encode:[]},"remarkStringifyOptions"),za=xt("ConfigReady");function bv(t){let e=n=>(n.record(za),async()=>(await t(n),n.done(za),()=>{n.clearTimer(za)}));return yn(e,{displayName:"Config"}),e}var mn=xt("InitReady");function xv(t){let e=n=>(n.inject(mk,t).inject(Lt,[]).inject(Ri,[]).inject(Ni,[]).inject(Ua,[]).inject(Ja,[]).inject(Mi,{handlers:yk,encode:[]}).inject(Rr,xo().use(ii).use(li)).inject(qu,[za]).record(mn),async()=>{await n.waitTimers(qu);let r=n.get(Mi);return n.set(Rr,xo().use(ii).use(li,r)),n.done(mn),()=>{n.remove(mk).remove(Lt).remove(Ri).remove(Ni).remove(Ua).remove(Ja).remove(Mi).remove(Rr).remove(qu).clearTimer(mn)}});return yn(e,{displayName:"Init"}),e}var Ze=xt("SchemaReady"),_a=Y([],"schemaTimer"),$e=Y({},"schema"),Ei=Y([],"nodes"),Ti=Y([],"marks");function gk(t){return{...t,parseDOM:t.parseDOM?.map(e=>({priority:t.priority,...e}))}}var kk=t=>(t.inject($e,{}).inject(Ei,[]).inject(Ti,[]).inject(_a,[mn]).record(Ze),async()=>{await t.waitTimers(_a);let e=t.get(Rr),n=t.get(Ri).reduce((i,o)=>i.use(o.plugin,o.options),e);t.set(Rr,n);let r=new ha({nodes:Object.fromEntries(t.get(Ei).map(([i,o])=>[i,gk(o)])),marks:Object.fromEntries(t.get(Ti).map(([i,o])=>[i,gk(o)]))});return t.set($e,r),t.done(Ze),()=>{t.remove($e).remove(Ei).remove(Ti).remove(_a).clearTimer(Ze)}});yn(kk,{displayName:"Schema"});var bk=class{constructor(){this.#t=new ql,this.#e=null,this.setCtx=t=>{this.#e=t},this.chain=()=>{if(this.#e==null)throw zs();let t=this.#e,e=[],n=this.get.bind(this),r={run:()=>{let o=wr(...e),s=t.get(U);return o(s.state,s.dispatch,s)},inline:o=>(e.push(o),r),pipe:i.bind(this)};function i(o,s){let a=n(o);return e.push(a(s)),r}return r}}#t;#e;get ctx(){return this.#e}create(t,e){let n=t.create(this.#t.sliceMap);return n.set(e),n}get(t){return this.#t.get(t).get()}remove(t){return this.#t.remove(t)}call(t,e){if(this.#e==null)throw zs();let n=this.get(t)(e),r=this.#e.get(U);return n(r.state,r.dispatch,r)}inline(t){if(this.#e==null)throw zs();let e=this.#e.get(U);return t(e.state,e.dispatch,e)}};function xk(t="cmdKey"){return Y((()=>()=>!1),t)}var Q=Y(new bk,"commands"),$a=Y([Ze],"commandsTimer"),vi=xt("CommandsReady"),wk=t=>{let e=new bk;return e.setCtx(t),t.inject(Q,e).inject($a,[Ze]).record(vi),async()=>(await t.waitTimers($a),t.done(vi),()=>{t.remove(Q).remove($a).clearTimer(vi)})};yn(wk,{displayName:"Commands"});function wv(t){return t.Backspace=wr(_g,wa,Og,Qc),t}var Ck=class{constructor(){this.#t=null,this.#e=[],this.setCtx=t=>{this.#t=t},this.add=t=>(this.#e.push(t),()=>{this.#e=this.#e.filter(e=>e!==t)}),this.addObjectKeymap=t=>{let e=[];return Object.entries(t).forEach(([n,r])=>{if(typeof r=="function"){let i={key:n,onRun:()=>r};this.#e.push(i),e.push(()=>{this.#e=this.#e.filter(o=>o!==i)})}else this.#e.push(r),e.push(()=>{this.#e=this.#e.filter(i=>i!==r)})}),()=>{e.forEach(n=>n())}},this.addBaseKeymap=()=>{let t=wv(zg);return this.addObjectKeymap(t)},this.build=()=>{let t={};return this.#e.forEach(e=>{t[e.key]=[...t[e.key]||[],e]}),Object.fromEntries(Object.entries(t).map(([e,n])=>{let r=n.sort((o,s)=>(s.priority??50)-(o.priority??50));return[e,(o,s,a)=>{let l=this.#t;if(l==null)throw ni();return wr(...r.map(c=>c.onRun(l)))(o,s,a)}]}))}}#t;#e;get ctx(){return this.#t}},Xo=Y(new Ck,"keymap"),Ku=Y([Ze],"keymapTimer"),Ai=xt("KeymapReady"),Cv=t=>{let e=new Ck;return e.setCtx(t),t.inject(Xo,e).inject(Ku,[Ze]).record(Ai),async()=>(await t.waitTimers(Ku),t.done(Ai),()=>{t.remove(Xo).remove(Ku).clearTimer(Ai)})},Ha=xt("ParserReady"),Sk=(()=>{throw ni()}),He=Y(Sk,"parser"),Uu=Y([],"parserTimer"),Mk=t=>(t.inject(He,Sk).inject(Uu,[Ze]).record(Ha),async()=>{await t.waitTimers(Uu);let e=t.get(Rr),n=t.get($e);return t.set(He,iy.create(n,e)),t.done(Ha),()=>{t.remove(He).remove(Uu).clearTimer(Ha)}});yn(Mk,{displayName:"Parser"});var Ii=xt("SerializerReady"),Ju=Y([],"serializerTimer"),Ek=(()=>{throw ni()}),gn=Y(Ek,"serializer"),Tk=t=>(t.inject(gn,Ek).inject(Ju,[Ze]).record(Ii),async()=>{await t.waitTimers(Ju);let e=t.get(Rr),n=t.get($e);return t.set(gn,sy.create(n,e)),t.done(Ii),()=>{t.remove(gn).remove(Ju).clearTimer(Ii)}});yn(Tk,{displayName:"Serializer"});var Ko=Y("","defaultValue"),Uo=Y(t=>t,"stateOptions"),Wa=Y([],"editorStateTimer"),ja=xt("EditorStateReady");function Sv(t,e,n){if(typeof t=="string")return e(t);if(t.type==="html")return wt.fromSchema(n).parse(t.dom);if(t.type==="json")return rt.fromJSON(n,t.value);throw ih(t)}var Mv=new ee("MILKDOWN_STATE_TRACKER"),vk=t=>(t.inject(Ko,"").inject(qo,{}).inject(Uo,e=>e).inject(Wa,[Ha,Ii,vi,Ai]).record(ja),async()=>{await t.waitTimers(Wa);let e=t.get($e),n=t.get(He),r=t.get(Ni),i=t.get(Uo),o=t.get(Lt),s=Sv(t.get(Ko),n,e),a=t.get(Xo),l=a.addBaseKeymap(),c=[...o,new X({key:Mv,state:{init:()=>{},apply:(d,p,h,m)=>{t.set(qo,m)}}}),qg({rules:r}),Zg(a.build())];t.set(Lt,c);let u=i({schema:e,doc:s,plugins:c}),f=mi.create(u);return t.set(qo,f),t.done(ja),()=>{l(),t.remove(Ko).remove(qo).remove(Uo).remove(Wa).clearTimer(ja)}});yn(vk,{displayName:"EditorState"});var Oi=Y([],"pasteRule"),Va=Y([Ze],"pasteRuleTimer"),qa=xt("PasteRuleReady"),Ak=t=>(t.inject(Oi,[]).inject(Va,[Ze]).record(qa),async()=>(await t.waitTimers(Va),t.done(qa),()=>{t.remove(Oi).remove(Va).clearTimer(qa)}));yn(Ak,{displayName:"PasteRule"});var Jo=xt("EditorViewReady"),Ka=Y([],"editorViewTimer"),Or=Y({},"editorViewOptions"),Go=Y(null,"root"),Gu=Y(null,"rootDOM"),Xu=Y({},"rootAttrs");function Ev(t,e){let n=document.createElement("div");n.className="milkdown",t.appendChild(n),e.set(Gu,n);let r=e.get(Xu);return Object.entries(r).forEach(([i,o])=>n.setAttribute(i,o)),n}function Tv(t){t.classList.add("editor"),t.setAttribute("role","textbox")}var vv=new ee("MILKDOWN_VIEW_CLEAR"),Ik=t=>(t.inject(Go,document.body).inject(U,{}).inject(Or,{}).inject(Gu,null).inject(Xu,{}).inject(Ka,[ja,qa]).record(Jo),async()=>{await t.wait(mn);let e=t.get(Go)||document.body,n=typeof e=="string"?document.querySelector(e):e;t.update(Lt,s=>[new X({key:vv,view:a=>{let l=n?Ev(n,t):void 0;return(()=>{if(l&&n){let u=a.dom;n.replaceChild(l,u),l.appendChild(u)}})(),{destroy:()=>{l?.parentNode&&l?.parentNode.replaceChild(a.dom,l),l?.remove()}}}}),...s]),await t.waitTimers(Ka);let r=t.get(qo),i=t.get(Or),o=new $o(n,{state:r,nodeViews:Object.fromEntries(t.get(Ua)),markViews:Object.fromEntries(t.get(Ja)),transformPasted:(s,a,l)=>(t.get(Oi).sort((c,u)=>(u.priority??50)-(c.priority??50)).map(c=>c.run).forEach(c=>{s=c(s,a,l)}),s),...i});return Tv(o.dom),t.set(U,o),t.done(Jo),()=>{o?.destroy(),t.remove(Go).remove(U).remove(Or).remove(Gu).remove(Xu).remove(Ka).clearTimer(Jo)}});yn(Ik,{displayName:"EditorView"});var Nk=class Rk{constructor(){this.#t=!1,this.#e="Idle",this.#r=[],this.#n=()=>{},this.#s=new ql,this.#o=new hh,this.#i=new Map,this.#a=new Map,this.#l=new dh(this.#s,this.#o),this.#d=()=>{let e=bv(async r=>{await Promise.all(this.#r.map(i=>Promise.resolve(i(r))))}),n=[kk,Mk,Tk,wk,Cv,Ak,vk,Ik,xv(this),e];this.#c(n,this.#a)},this.#c=(e,n)=>{e.forEach(r=>{let i=this.#l.produce(this.#t?r.meta:void 0),o=r(i);n.set(r,{ctx:i,handler:o,cleanup:void 0})})},this.#u=(e,n=!1)=>Promise.all([e].flat().map(async r=>{let i=this.#i.get(r)?.cleanup;return n?this.#i.delete(r):this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0}),typeof i=="function"?i():i})),this.#p=async()=>{await Promise.all([...this.#a.entries()].map(async([e,{cleanup:n}])=>typeof n=="function"?n():n)),this.#a.clear()},this.#f=e=>{this.#e=e,this.#n(e)},this.#h=e=>[...e.entries()].map(async([n,r])=>{let{ctx:i,handler:o}=r;if(!o)return;let s=await o();e.set(n,{ctx:i,handler:o,cleanup:s})}),this.enableInspector=(e=!0)=>(this.#t=e,this),this.onStatusChange=e=>(this.#n=e,this),this.config=e=>(this.#r.push(e),this),this.removeConfig=e=>(this.#r=this.#r.filter(n=>n!==e),this),this.use=e=>{let n=[e].flat();return n.flat().forEach(r=>{this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0})}),this.#e==="Created"&&this.#c(n,this.#i),this},this.remove=async e=>this.#e==="OnCreate"?(console.warn("[Milkdown]: You are trying to remove plugins when the editor is creating, this is not recommended, please check your code."),new Promise(n=>{setTimeout(()=>{n(this.remove(e))},50)})):(await this.#u([e].flat(),!0),this),this.create=async()=>this.#e==="OnCreate"?this:(this.#e==="Created"&&await this.destroy(),this.#f("OnCreate"),this.#d(),this.#c([...this.#i.keys()],this.#i),await Promise.all([this.#h(this.#a),this.#h(this.#i)].flat()),this.#f("Created"),this),this.destroy=async(e=!1)=>this.#e==="Destroyed"||this.#e==="OnDestroy"?this:this.#e==="OnCreate"?new Promise(n=>{setTimeout(()=>{n(this.destroy(e))},50)}):(e&&(this.#r=[]),this.#f("OnDestroy"),await this.#u([...this.#i.keys()],e),await this.#p(),this.#f("Destroyed"),this),this.action=e=>e(this.#l),this.inspect=()=>this.#t?[...this.#a.values(),...this.#i.values()].map(({ctx:e})=>e?.inspector?.read()).filter(e=>!!e):(console.warn("[Milkdown]: You are trying to collect inspection when inspector is disabled, please enable inspector by `editor.enableInspector()` first."),[])}static make(){return new Rk}#t;#e;#r;#n;#s;#o;#i;#a;#l;#d;#c;#u;#p;#f;#h;get ctx(){return this.#l}get status(){return this.#e}};var Av=t=>crypto.getRandomValues(new Uint8Array(t)),Iv=(t,e,n)=>{let r=256-256%t.length;if(r===256){let o=t.length-1;return(s=e)=>{if(!s)return"";let a="";for(;;){let l=n(s),c=s;for(;c--;)if(a+=t[l[c]&o],a.length>=s)return a}}}let i=Math.ceil(1.6*256*e/r);return(o=e)=>{if(!o)return"";let s="";for(;;){let a=n(i),l=i;for(;l--;)if(a[l]<r&&(s+=t[a[l]%t.length],s.length>=o))return s}}},Ok=(t,e=21)=>Iv(t,e|0,Av);var jH=Ok("abcedfghicklmn",10);function z(t,e){let n=xk(t),r=i=>async()=>{r.key=n,await i.wait(vi);let o=e(i);return i.get(Q).create(n,o),r.run=s=>i.get(Q).call(t,s),()=>{i.get(Q).remove(n)}};return r}function ge(t){let e=n=>async()=>{await n.wait(Ze);let r=t(n);return n.update(Ni,i=>[...i,r]),e.inputRule=r,()=>{n.update(Ni,i=>i.filter(o=>o!==r))}};return e}function Dk(t){let e=n=>async()=>{await n.wait(Ze);let r=t(n);return n.update(Oi,i=>[...i,r]),e.pasteRule=r,()=>{n.update(Oi,i=>i.filter(o=>o!==r))}};return e}function Nv(t,e){let n=r=>async()=>{let i=e(r);return r.update(Ti,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update(Ti,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get($e).marks[t];if(!i)throw fh(t);return i},n}function Ga(t,e){let n=r=>async()=>{let i=e(r);return r.update(Ei,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update(Ei,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get($e).nodes[t];if(!i)throw _s(t);return i},n}function pe(t){let e,n=r=>async()=>(await r.wait(Ze),e=t(r),r.update(Lt,i=>[...i,e]),()=>{r.update(Lt,i=>i.filter(o=>o!==e))});return n.plugin=()=>e,n.key=()=>e.spec.key,n}function Rv(t){let e=n=>async()=>{await n.wait(Ai);let r=n.get(Xo),i=t(n),o=r.addObjectKeymap(i);return e.keymap=i,()=>{o()}};return e}function Ie(t,e){let n=Y(t,e),r=i=>(i.inject(n),()=>()=>{i.remove(n)});return r.key=n,r}function ce(t,e){let n=Ie(e,t),r=Ga(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.node=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>ce(t,o(e)),i}function Pt(t,e){let n=Ie(e,t),r=Nv(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.mark=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>Pt(t,o(e)),i}function We(t,e){let n=Ie(Object.fromEntries(Object.entries(e).map(([o,{shortcuts:s,priority:a}])=>[o,{shortcuts:s,priority:a}])),`${t}Keymap`),r=Rv(o=>{let s=o.get(n.key),a=Object.entries(e).flatMap(([l,{command:c}])=>{let u=s[l],f=[u.shortcuts].flat(),d=u.priority;return f.map(p=>[p,{key:p,onRun:c,priority:d}])});return Object.fromEntries(a)}),i=[n,r];return i.ctx=n,i.shortcuts=r,i.key=n.key,i.keymap=r.keymap,i}var vt=(t,e=()=>({}))=>Ie(e,`${t}Attr`),Dr=(t,e=()=>({}))=>Ie(e,`${t}Attr`);function gt(t,e,n){let r=Ie(n??{},t),i=s=>async()=>{await s.wait(mn);let a={plugin:e(s),options:s.get(r.key)};return s.update(Ri,l=>[...l,a]),()=>{s.update(Ri,l=>l.filter(c=>c!==a))}},o=[r,i];return o.id=t,o.plugin=i,o.options=r,o}function Lk(t){return e=>{let n=e.get(U),r=e.get($e),i=e.get(gn);if(!t)return i(n.state.doc);let o=n.state.doc.slice(t.from,t.to,!0),s=r.topNodeType.createAndFill(null,o.content);return s?i(s):(console.error("No document found"),"")}}function Yu(t,e=!1){return n=>{let r=n.get(U),i=n.get(He)(t);if(!i)return;if(!e){let c=r.state.selection.content();return r.dispatch(r.state.tr.replaceSelection(new R(i.content,c.openStart,c.openEnd)).scrollIntoView())}let o=n.get($e),s=Ct.fromSchema(o).serializeFragment(i.content),a=wt.fromSchema(o).parseSlice(s),l=Sa(a);if(l){r.dispatch(r.state.tr.replaceSelectionWith(l,!0));return}r.dispatch(r.state.tr.replaceSelection(a))}}function Pk(t,e=!1){return n=>{let r=n.get(U),i=n.get(He)(t);if(!i)return;if(!e){let{state:l}=r;return r.dispatch(l.tr.replace(0,l.doc.content.size,new R(i.content,0,0)))}let o=n.get($e),s=n.get(Uo)({schema:o,doc:i,plugins:n.get(Lt)}),a=mi.create(s);r.updateState(a)}}function Ov(t){return e=>{let n=e.get(He)(t),r=e.get($e),i=Ct.fromSchema(r).serializeFragment(n.content);return wt.fromSchema(r).parseSlice(i)}}function Qu(t,e){return n=>{let r=n.get(U),i=Ov(t)(n);r.dispatch(r.state.tr.replace(e.from,e.to,i))}}function Bk(t,e){return function(n,r){let{$from:i,$to:o,node:s}=n.selection;if(s&&s.isBlock||i.depth<2||!i.sameParent(o))return!1;let a=i.node(-1);if(a.type!=t)return!1;if(i.parent.content.size==0&&i.node(-1).childCount==i.indexAfter(-1)){if(i.depth==3||i.node(-3).type!=t||i.index(-2)!=i.node(-2).childCount-1)return!1;if(r){let f=M.empty,d=i.index(-1)?1:i.index(-2)?2:3;for(let y=i.depth-d;y>=i.depth-3;y--)f=M.from(i.node(y).copy(f));let p=i.indexAfter(-1)<i.node(-2).childCount?1:i.indexAfter(-2)<i.node(-3).childCount?2:3;f=f.append(M.from(t.createAndFill()));let h=i.before(i.depth-(d-1)),m=n.tr.replace(h,i.after(-p),new R(f,4-d,0)),g=-1;m.doc.nodesBetween(h,m.doc.content.size,(y,b)=>{if(g>-1)return!1;y.isTextblock&&y.content.size==0&&(g=b+1)}),g>-1&&m.setSelection($.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let l=o.pos==i.end()?a.contentMatchAt(0).defaultType:null,c=n.tr.delete(i.pos,o.pos),u=l?[e?{type:t,attrs:e}:null,{type:l}]:void 0;return kr(c.doc,i.pos,2,u)?(r&&r(c.split(i.pos,2,u).scrollIntoView()),!0):!1}}function Xa(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,s=>s.childCount>0&&s.firstChild.type==t);return o?n?r.node(o.depth-1).type==t?Dv(e,n,t,o):Lv(e,n,o):!0:!1}}function Dv(t,e,n,r){let i=t.tr,o=r.end,s=r.$to.end(r.depth);o<s&&(i.step(new ze(o-1,s,o,s,new R(M.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new So(i.doc.resolve(r.$from.pos),i.doc.resolve(s),r.depth));let a=gr(r);if(a==null)return!1;i.lift(r,a);let l=i.doc.resolve(i.mapping.map(o,-1)-1);return br(i.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&i.join(l.pos),e(i.scrollIntoView()),!0}function Lv(t,e,n){let r=t.tr,i=n.parent;for(let p=n.end,h=n.endIndex-1,m=n.startIndex;h>m;h--)p-=i.child(h).nodeSize,r.delete(p-1,p+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let a=n.startIndex==0,l=n.endIndex==i.childCount,c=o.node(-1),u=o.index(-1);if(!c.canReplace(u+(a?0:1),u+1,s.content.append(l?M.empty:M.from(i))))return!1;let f=o.pos,d=f+s.nodeSize;return r.step(new ze(f-(a?1:0),d+(l?1:0),f+1,d-1,new R((a?M.empty:M.from(i.copy(M.empty))).append(l?M.empty:M.from(i.copy(M.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function Fk(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==t);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let a=o.parent,l=a.child(s-1);if(l.type!=t)return!1;if(n){let c=l.lastChild&&l.lastChild.type==a.type,u=M.from(c?t.create():null),f=new R(M.from(t.create(null,M.from(a.type.create(null,u)))),c?3:1,0),d=o.start,p=o.end;n(e.tr.step(new ze(d-(c?3:1),p,d,p,f,1,!0)).scrollIntoView())}return!0}}function Zu(t){let e=new Map;if(!t||!t.type)throw new Error("mdast-util-definitions expected node");return Rt(t,"definition",function(r){let i=zk(r.identifier);i&&!e.get(i)&&e.set(i,r)}),n;function n(r){let i=zk(r);return e.get(i)}}function zk(t){return String(t||"").toUpperCase()}function Ya(){return function(t){let e=Zu(t);Rt(t,function(n,r,i){if(n.type==="definition"&&i!==void 0&&typeof r=="number")return i.children.splice(r,1),[ar,r];if(n.type==="imageReference"||n.type==="linkReference"){let o=e(n.identifier);if(o&&i&&typeof r=="number")return i.children[r]=n.type==="imageReference"?{type:"image",url:o.url,title:o.title,alt:n.alt}:{type:"link",url:o.url,title:o.title,children:n.children},[ar,r]}})}}function _k(t,e){if(!(e.childCount>=1&&e.lastChild?.type.name==="hardbreak")){t.next(e.content);return}let n=[];e.content.forEach((r,i,o)=>{o!==e.childCount-1&&n.push(r)}),t.next(M.fromArray(n))}function E(t,e){return Object.assign(t,{meta:{package:"@milkdown/preset-commonmark",...e}}),t}var ef=Dr("emphasis");E(ef,{displayName:"Attr<emphasis>",group:"Emphasis"});var Li=Pt("emphasis",t=>({attrs:{marker:{default:t.get(Mi).emphasis||"*",validate:"string"}},parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style",getAttrs:e=>e==="italic"}],toDOM:e=>["em",t.get(ef.key)(e)],parseMarkdown:{match:e=>e.type==="emphasis",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="emphasis",runner:(e,n)=>{e.withMark(n,"emphasis",void 0,{marker:n.attrs.marker})}}}));E(Li.mark,{displayName:"MarkSchema<emphasis>",group:"Emphasis"});E(Li.ctx,{displayName:"MarkSchemaCtx<emphasis>",group:"Emphasis"});var tf=z("ToggleEmphasis",t=>()=>Ln(Li.type(t)));E(tf,{displayName:"Command<toggleEmphasisCommand>",group:"Emphasis"});var $k=ge(t=>ln(/(?:^|[^*])\*([^*]+)\*$/,Li.type(t),{getAttr:()=>({marker:"*"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("*")?{}:{fullMatch:e.slice(1),start:n+1}}));E($k,{displayName:"InputRule<emphasis>|Star",group:"Emphasis"});var Hk=ge(t=>ln(/\b_(?![_\s])(.*?[^_\s])_\b/,Li.type(t),{getAttr:()=>({marker:"_"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("_")?{}:{fullMatch:e.slice(1),start:n+1}}));E(Hk,{displayName:"InputRule<emphasis>|Underscore",group:"Emphasis"});var nf=We("emphasisKeymap",{ToggleEmphasis:{shortcuts:"Mod-i",command:t=>{let e=t.get(Q);return()=>e.call(tf.key)}}});E(nf.ctx,{displayName:"KeymapCtx<emphasis>",group:"Emphasis"});E(nf.shortcuts,{displayName:"Keymap<emphasis>",group:"Emphasis"});var rf=Dr("strong");E(rf,{displayName:"Attr<strong>",group:"Strong"});var Yo=Pt("strong",t=>({attrs:{marker:{default:t.get(Mi).strong||"*",validate:"string"}},parseDOM:[{tag:"b",getAttrs:e=>e.style.fontWeight!="normal"&&null},{tag:"strong"},{style:"font-style",getAttrs:e=>e==="bold"},{style:"font-weight=400",clearMark:e=>e.type.name=="strong"},{style:"font-weight",getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}],toDOM:e=>["strong",t.get(rf.key)(e)],parseMarkdown:{match:e=>e.type==="strong",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="strong",runner:(e,n)=>{e.withMark(n,"strong",void 0,{marker:n.attrs.marker})}}}));E(Yo.mark,{displayName:"MarkSchema<strong>",group:"Strong"});E(Yo.ctx,{displayName:"MarkSchemaCtx<strong>",group:"Strong"});var of=z("ToggleStrong",t=>()=>Ln(Yo.type(t)));E(of,{displayName:"Command<toggleStrongCommand>",group:"Strong"});var Wk=ge(t=>ln(/(?<![\w:/])(?:\*\*|__)([^*_]+?)(?:\*\*|__)(?![\w/])$/,Yo.type(t),{getAttr:e=>({marker:e[0].startsWith("*")?"*":"_"})}));E(Wk,{displayName:"InputRule<strong>",group:"Strong"});var sf=We("strongKeymap",{ToggleBold:{shortcuts:["Mod-b"],command:t=>{let e=t.get(Q);return()=>e.call(of.key)}}});E(sf.ctx,{displayName:"KeymapCtx<strong>",group:"Strong"});E(sf.shortcuts,{displayName:"Keymap<strong>",group:"Strong"});var af=Dr("inlineCode");E(af,{displayName:"Attr<inlineCode>",group:"InlineCode"});var jn=Pt("inlineCode",t=>({priority:100,code:!0,parseDOM:[{tag:"code"}],toDOM:e=>["code",t.get(af.key)(e)],parseMarkdown:{match:e=>e.type==="inlineCode",runner:(e,n,r)=>{e.openMark(r),e.addText(n.value),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="inlineCode",runner:(e,n,r)=>(e.withMark(n,"inlineCode",r.text||""),!0)}}));E(jn.mark,{displayName:"MarkSchema<inlineCode>",group:"InlineCode"});E(jn.ctx,{displayName:"MarkSchemaCtx<inlineCode>",group:"InlineCode"});var lf=z("ToggleInlineCode",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(r.empty)return!1;let{from:o,to:s}=r;return e.doc.rangeHasMark(o,s,jn.type(t))?(n?.(i.removeMark(o,s,jn.type(t))),!0):(Object.keys(e.schema.marks).filter(a=>a!==jn.type.name).map(a=>e.schema.marks[a]).forEach(a=>{i.removeMark(o,s,a)}),n?.(i.addMark(o,s,jn.type(t).create())),!0)});E(lf,{displayName:"Command<toggleInlineCodeCommand>",group:"InlineCode"});var jk=ge(t=>ln(/(?:`)([^`]+)(?:`)$/,jn.type(t)));E(jk,{displayName:"InputRule<inlineCodeInputRule>",group:"InlineCode"});var cf=We("inlineCodeKeymap",{ToggleInlineCode:{shortcuts:"Mod-e",command:t=>{let e=t.get(Q);return()=>e.call(lf.key)}}});E(cf.ctx,{displayName:"KeymapCtx<inlineCode>",group:"InlineCode"});E(cf.shortcuts,{displayName:"Keymap<inlineCode>",group:"InlineCode"});var Pv=new Set(["http:","https:","mailto:","tel:","ftp:"]);function Bv(t){return t<=32||t>=127&&t<=160||t>=8203&&t<=8205||t===8232||t===8233||t===65279}function Fv(t){let e="";for(let n of t)Bv(n.codePointAt(0)??0)||(e+=n);return e}function zv(t){if(typeof t!="string")return"";let e=t.trim();if(!e)return"";let n=Fv(e),r=/^([a-z][a-z0-9+.-]*):/i.exec(n)?.[1];return!r||Pv.has(`${r.toLowerCase()}:`)?e:""}var uf=Dr("link");E(uf,{displayName:"Attr<link>",group:"Link"});var Di=Pt("link",t=>({attrs:{href:{validate:"string"},title:{default:null,validate:"string|null"}},parseDOM:[{tag:"a[href]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{href:e.getAttribute("href"),title:e.getAttribute("title")}}}],toDOM:e=>["a",{...t.get(uf.key)(e),...e.attrs,href:zv(e.attrs.href)}],parseMarkdown:{match:e=>e.type==="link",runner:(e,n,r)=>{let i=n.url,o=n.title;e.openMark(r,{href:i,title:o}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="link",runner:(e,n)=>{e.withMark(n,"link",void 0,{title:n.attrs.title,url:n.attrs.href})}}}));E(Di.mark,{displayName:"MarkSchema<link>",group:"Link"});var Vk=z("ToggleLink",t=>(e={})=>Ln(Di.type(t),e));E(Vk,{displayName:"Command<toggleLinkCommand>",group:"Link"});var qk=z("UpdateLink",t=>(e={})=>(n,r)=>{if(!r)return!1;let i,o=-1,{selection:s}=n,{from:a,to:l}=s;if(n.doc.nodesBetween(a,a===l?l+1:l,(h,m)=>{if(Di.type(t).isInSet(h.marks))return i=h,o=m,!1}),!i)return!1;let c=i.marks.find(({type:h})=>h===Di.type(t));if(!c)return!1;let u=o,f=o+i.nodeSize,{tr:d}=n,p=Di.type(t).create({...c.attrs,...e});return p?(r(d.removeMark(u,f,c).addMark(u,f,p).setSelection(new B(d.selection.$anchor)).scrollIntoView()),!0):!1});E(qk,{displayName:"Command<updateLinkCommand>",group:"Link"});var Kk=Ga("doc",()=>({content:"block+",parseMarkdown:{match:({type:t})=>t==="root",runner:(t,e,n)=>{t.injectRoot(e,n)}},toMarkdown:{match:t=>t.type.name==="doc",runner:(t,e)=>{t.openNode("root"),t.next(e.content)}}}));E(Kk,{displayName:"NodeSchema<doc>",group:"Doc"});function _v(t){return lr(t,e=>e.type==="html"&&["<br />","<br>","<br >","<br/>"].includes(e.value?.trim()),(e,n)=>{if(!n.length)return;let r=n[n.length-1];if(!r)return;let i=r.children.indexOf(e);i!==-1&&r.children.splice(i,1)},!0)}var Za=gt("remark-preserve-empty-line",()=>()=>_v);E(Za.plugin,{displayName:"Remark<remarkPreserveEmptyLine>",group:"Remark"});E(Za.options,{displayName:"RemarkConfig<remarkPreserveEmptyLine>",group:"Remark"});var ff=vt("paragraph");E(ff,{displayName:"Attr<paragraph>",group:"Paragraph"});var Bt=ce("paragraph",t=>({content:"inline*",group:"block",parseDOM:[{tag:"p"}],toDOM:e=>["p",t.get(ff.key)(e),0],parseMarkdown:{match:e=>e.type==="paragraph",runner:(e,n,r)=>{e.openNode(r),n.children?e.next(n.children):e.addText(n.value||""),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="paragraph",runner:(e,n)=>{let r=t.get(U).state?.doc.lastChild;e.openNode("paragraph"),(!n.content||n.content.size===0)&&n!==r&&$v(t)?e.addNode("html",void 0,"<br />"):_k(e,n),e.closeNode()}}}));function $v(t){let e=!1;try{t.get(Za.id),e=!0}catch{e=!1}return e}E(Bt.node,{displayName:"NodeSchema<paragraph>",group:"Paragraph"});E(Bt.ctx,{displayName:"NodeSchemaCtx<paragraph>",group:"Paragraph"});var df=z("TurnIntoText",t=>()=>Dn(Bt.type(t)));E(df,{displayName:"Command<turnIntoTextCommand>",group:"Paragraph"});var pf=We("paragraphKeymap",{TurnIntoText:{shortcuts:"Mod-Alt-0",command:t=>{let e=t.get(Q);return()=>e.call(df.key)}}});E(pf.ctx,{displayName:"KeymapCtx<paragraph>",group:"Paragraph"});E(pf.shortcuts,{displayName:"Keymap<paragraph>",group:"Paragraph"});var Hv=Array(6).fill(0).map((t,e)=>e+1);function Wv(t){return t.textContent.toLowerCase().trim().replace(/\s+/g,"-")}var el=Ie(Wv,"headingIdGenerator");E(el,{displayName:"Ctx<HeadingIdGenerator>",group:"Heading"});var hf=vt("heading");E(hf,{displayName:"Attr<heading>",group:"Heading"});var Pr=ce("heading",t=>{let e=t.get(el.key);return{content:"inline*",group:"block",defining:!0,attrs:{id:{default:"",validate:"string"},level:{default:1,validate:"number"}},parseDOM:Hv.map(n=>({tag:`h${n}`,getAttrs:r=>{if(!(r instanceof HTMLElement))throw pt(r);return{level:n,id:r.id}}})),toDOM:n=>[`h${n.attrs.level}`,{...t.get(hf.key)(n),id:n.attrs.id||e(n)},0],parseMarkdown:{match:({type:n})=>n==="heading",runner:(n,r,i)=>{let o=r.depth;n.openNode(i,{level:o}),n.next(r.children),n.closeNode()}},toMarkdown:{match:n=>n.type.name==="heading",runner:(n,r)=>{n.openNode("heading",void 0,{depth:r.attrs.level}),_k(n,r),n.closeNode()}}}});E(Pr.node,{displayName:"NodeSchema<heading>",group:"Heading"});E(Pr.ctx,{displayName:"NodeSchemaCtx<heading>",group:"Heading"});var Uk=ge(t=>nu(/^(?<hashes>#+)\s$/,Pr.type(t),e=>{let n=e.groups?.hashes?.length||0,{$from:r}=t.get(U).state.selection,i=r.node();if(i.type.name==="heading"){let o=Number(i.attrs.level)+Number(n);return o>6&&(o=6),{level:o}}return{level:n}}));E(Uk,{displayName:"InputRule<wrapInHeadingInputRule>",group:"Heading"});var Wn=z("WrapInHeading",t=>e=>(e??=1,e<1?Dn(Bt.type(t)):Dn(Pr.type(t),{level:e})));E(Wn,{displayName:"Command<wrapInHeadingCommand>",group:"Heading"});var mf=z("DowngradeHeading",t=>()=>(e,n,r)=>{let{$from:i}=e.selection,o=i.node();if(o.type!==Pr.type(t)||!e.selection.empty||i.parentOffset!==0)return!1;let s=o.attrs.level-1;return s?(n?.(e.tr.setNodeMarkup(e.selection.$from.before(),void 0,{...o.attrs,level:s})),!0):Dn(Bt.type(t))(e,n,r)});E(mf,{displayName:"Command<downgradeHeadingCommand>",group:"Heading"});var gf=We("headingKeymap",{TurnIntoH1:{shortcuts:"Mod-Alt-1",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,1)}},TurnIntoH2:{shortcuts:"Mod-Alt-2",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,2)}},TurnIntoH3:{shortcuts:"Mod-Alt-3",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,3)}},TurnIntoH4:{shortcuts:"Mod-Alt-4",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,4)}},TurnIntoH5:{shortcuts:"Mod-Alt-5",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,5)}},TurnIntoH6:{shortcuts:"Mod-Alt-6",command:t=>{let e=t.get(Q);return()=>e.call(Wn.key,6)}},DowngradeHeading:{shortcuts:["Delete","Backspace"],command:t=>{let e=t.get(Q);return()=>e.call(mf.key)}}});E(gf.ctx,{displayName:"KeymapCtx<heading>",group:"Heading"});E(gf.shortcuts,{displayName:"Keymap<heading>",group:"Heading"});var yf=vt("blockquote");E(yf,{displayName:"Attr<blockquote>",group:"Blockquote"});var Qo=ce("blockquote",t=>({content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM:e=>["blockquote",t.get(yf.key)(e),0],parseMarkdown:{match:({type:e})=>e==="blockquote",runner:(e,n,r)=>{e.openNode(r).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="blockquote",runner:(e,n)=>{e.openNode("blockquote").next(n.content).closeNode()}}}));E(Qo.node,{displayName:"NodeSchema<blockquote>",group:"Blockquote"});E(Qo.ctx,{displayName:"NodeSchemaCtx<blockquote>",group:"Blockquote"});var Jk=ge(t=>Ca(/^\s*>\s$/,Qo.type(t)));E(Jk,{displayName:"InputRule<wrapInBlockquoteInputRule>",group:"Blockquote"});var kf=z("WrapInBlockquote",t=>()=>yi(Qo.type(t)));E(kf,{displayName:"Command<wrapInBlockquoteCommand>",group:"Blockquote"});var bf=We("blockquoteKeymap",{WrapInBlockquote:{shortcuts:"Mod-Shift-b",command:t=>{let e=t.get(Q);return()=>e.call(kf.key)}}});E(bf.ctx,{displayName:"KeymapCtx<blockquote>",group:"Blockquote"});E(bf.shortcuts,{displayName:"Keymap<blockquote>",group:"Blockquote"});var xf=vt("codeBlock",()=>({pre:{},code:{}}));E(xf,{displayName:"Attr<codeBlock>",group:"CodeBlock"});var Zo=ce("code_block",t=>({content:"text*",group:"block",marks:"",defining:!0,code:!0,attrs:{language:{default:"",validate:"string"}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{language:e.dataset.language}}}],toDOM:e=>{let n=t.get(xf.key)(e),r=e.attrs.language,i=r&&r.length>0?{"data-language":r}:void 0;return["pre",{...n.pre,...i},["code",n.code,0]]},parseMarkdown:{match:({type:e})=>e==="code",runner:(e,n,r)=>{let i=n.lang??"",o=n.value;e.openNode(r,{language:i}),o&&e.addText(o),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="code_block",runner:(e,n)=>{e.addNode("code",void 0,n.content.firstChild?.text||"",{lang:n.attrs.language})}}}));E(Zo.node,{displayName:"NodeSchema<codeBlock>",group:"CodeBlock"});E(Zo.ctx,{displayName:"NodeSchemaCtx<codeBlock>",group:"CodeBlock"});var Gk=ge(t=>nu(/^```(?<language>[a-z]*)?[\s\n]$/,Zo.type(t),e=>({language:e.groups?.language??""})));E(Gk,{displayName:"InputRule<createCodeBlockInputRule>",group:"CodeBlock"});var wf=z("CreateCodeBlock",t=>(e="")=>Dn(Zo.type(t),{language:e}));E(wf,{displayName:"Command<createCodeBlockCommand>",group:"CodeBlock"});var jv=z("UpdateCodeBlockLanguage",()=>({pos:t,language:e}={pos:-1,language:""})=>(n,r)=>t>=0?(r?.(n.tr.setNodeAttribute(t,"language",e)),!0):!1);E(jv,{displayName:"Command<updateCodeBlockLanguageCommand>",group:"CodeBlock"});var Cf=We("codeBlockKeymap",{CreateCodeBlock:{shortcuts:"Mod-Alt-c",command:t=>{let e=t.get(Q);return()=>e.call(wf.key)}}});E(Cf.ctx,{displayName:"KeymapCtx<codeBlock>",group:"CodeBlock"});E(Cf.shortcuts,{displayName:"Keymap<codeBlock>",group:"CodeBlock"});var Sf=vt("image");E(Sf,{displayName:"Attr<image>",group:"Image"});var Pi=ce("image",t=>({inline:!0,group:"inline",selectable:!0,draggable:!0,marks:"",atom:!0,defining:!0,isolating:!0,attrs:{src:{default:"",validate:"string"},alt:{default:"",validate:"string"},title:{default:"",validate:"string"}},parseDOM:[{tag:"img[src]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{src:e.getAttribute("src")||"",alt:e.getAttribute("alt")||"",title:e.getAttribute("title")||e.getAttribute("alt")||""}}}],toDOM:e=>["img",{...t.get(Sf.key)(e),...e.attrs}],parseMarkdown:{match:({type:e})=>e==="image",runner:(e,n,r)=>{let i=n.url,o=n.alt,s=n.title;e.addNode(r,{src:i,alt:o,title:s})}},toMarkdown:{match:e=>e.type.name==="image",runner:(e,n)=>{e.addNode("image",void 0,void 0,{title:n.attrs.title,url:n.attrs.src,alt:n.attrs.alt})}}}));E(Pi.node,{displayName:"NodeSchema<image>",group:"Image"});E(Pi.ctx,{displayName:"NodeSchemaCtx<image>",group:"Image"});var Xk=z("InsertImage",t=>(e={})=>(n,r)=>{if(!r)return!0;let{src:i="",alt:o="",title:s=""}=e,a=Pi.type(t).create({src:i,alt:o,title:s});return a&&r(n.tr.replaceSelectionWith(a).scrollIntoView()),!0});E(Xk,{displayName:"Command<insertImageCommand>",group:"Image"});var Yk=z("UpdateImage",t=>(e={})=>(n,r)=>{let i=Xg(n.selection,Pi.type(t));if(!i)return!1;let{node:o,pos:s}=i,a={...o.attrs},{src:l,alt:c,title:u}=e;return l!==void 0&&(a.src=l),c!==void 0&&(a.alt=c),u!==void 0&&(a.title=u),r?.(n.tr.setNodeMarkup(s,void 0,a).scrollIntoView()),!0});E(Yk,{displayName:"Command<updateImageCommand>",group:"Image"});var Vv=ge(t=>new xe(/!\[(?<alt>.*?)]\((?<filename>.*?)\s*(?="|\))"?(?<title>[^"]+)?"?\)/,(e,n,r,i)=>{let[o,s,a="",l]=n;return o?e.tr.replaceWith(r,i,Pi.type(t).create({src:a,alt:s,title:l})):null}));E(Vv,{displayName:"InputRule<insertImageInputRule>",group:"Image"});var Qa=vt("hardbreak",t=>({"data-type":"hardbreak","data-is-inline":t.attrs.isInline}));E(Qa,{displayName:"Attr<hardbreak>",group:"Hardbreak"});var Lr=ce("hardbreak",t=>({inline:!0,group:"inline",attrs:{isInline:{default:!1,validate:"boolean"}},selectable:!1,parseDOM:[{tag:"br"},{tag:'span[data-type="hardbreak"]',getAttrs:()=>({isInline:!0})}],toDOM:e=>e.attrs.isInline?["span",t.get(Qa.key)(e)," "]:["br",t.get(Qa.key)(e)],parseMarkdown:{match:({type:e})=>e==="break",runner:(e,n,r)=>{e.addNode(r,{isInline:!!n.data?.isInline})}},leafText:()=>` `,toMarkdown:{match:e=>e.type.name==="hardbreak",runner:(e,n)=>{n.attrs.isInline?e.addNode("text",void 0,` -`):e.addNode("break")}}}));E(Lr.node,{displayName:"NodeSchema<hardbreak>",group:"Hardbreak"});E(Lr.ctx,{displayName:"NodeSchemaCtx<hardbreak>",group:"Hardbreak"});var Mf=z("InsertHardbreak",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(!(r instanceof B))return!1;if(r.empty){let o=r.$from.node();if(o.childCount>0&&o.lastChild?.type.name==="hardbreak")return n?.(i.replaceRangeWith(r.to-1,r.to,e.schema.node("paragraph")).setSelection($.near(i.doc.resolve(r.to))).scrollIntoView()),!0}return n?.(i.setMeta("hardbreak",!0).replaceSelectionWith(Lr.type(t).create()).scrollIntoView()),!0});E(Mf,{displayName:"Command<insertHardbreakCommand>",group:"Hardbreak"});var Ef=We("hardbreakKeymap",{InsertHardbreak:{shortcuts:"Shift-Enter",command:t=>{let e=t.get(Q);return()=>e.call(Mf.key)}}});E(Ef.ctx,{displayName:"KeymapCtx<hardbreak>",group:"Hardbreak"});E(Ef.shortcuts,{displayName:"Keymap<hardbreak>",group:"Hardbreak"});var Tf=vt("hr");E(Tf,{displayName:"Attr<hr>",group:"Hr"});var es=ce("hr",t=>({group:"block",parseDOM:[{tag:"hr"}],toDOM:e=>["hr",t.get(Tf.key)(e)],parseMarkdown:{match:({type:e})=>e==="thematicBreak",runner:(e,n,r)=>{e.addNode(r)}},toMarkdown:{match:e=>e.type.name==="hr",runner:e=>{e.addNode("thematicBreak")}}}));E(es.node,{displayName:"NodeSchema<hr>",group:"Hr"});E(es.ctx,{displayName:"NodeSchemaCtx<hr>",group:"Hr"});var Yk=ge(t=>new be(/^(?:---|___\s|\*\*\*\s)$/,(e,n,r,i)=>{let{tr:o}=e;return n[0]&&o.replaceWith(r-1,i,es.type(t).create()),o}));E(Yk,{displayName:"InputRule<insertHrInputRule>",group:"Hr"});var Qk=z("InsertHr",t=>()=>(e,n)=>{if(!n)return!0;let r=Bt.node.type(t).create(),{tr:i,selection:o}=e,{from:s}=o,a=es.type(t).create();if(!a)return!0;let l=i.replaceSelectionWith(a).insert(s,r),c=$.findFrom(l.doc.resolve(s),1,!0);return c&&n(l.setSelection(c).scrollIntoView()),!0});E(Qk,{displayName:"Command<insertHrCommand>",group:"Hr"});var vf=vt("bulletList");E(vf,{displayName:"Attr<bulletList>",group:"BulletList"});var Bi=ce("bullet_list",t=>({content:"listItem+",group:"block",attrs:{spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ul",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{spread:e.dataset.spread==="true"}}}],toDOM:e=>["ul",{...t.get(vf.key)(e),"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"false";e.openNode(r,{spread:i}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="bullet_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!1,spread:n.attrs.spread}).next(n.content).closeNode()}}}));E(Bi.node,{displayName:"NodeSchema<bulletList>",group:"BulletList"});E(Bi.ctx,{displayName:"NodeSchemaCtx<bulletList>",group:"BulletList"});var Zk=ge(t=>Ca(/^\s*([-+*])\s$/,Bi.type(t)));E(Zk,{displayName:"InputRule<wrapInBulletListInputRule>",group:"BulletList"});var Af=z("WrapInBulletList",t=>()=>yi(Bi.type(t)));E(Af,{displayName:"Command<wrapInBulletListCommand>",group:"BulletList"});var If=We("bulletListKeymap",{WrapInBulletList:{shortcuts:"Mod-Alt-8",command:t=>{let e=t.get(Q);return()=>e.call(Af.key)}}});E(If.ctx,{displayName:"KeymapCtx<bulletListKeymap>",group:"BulletList"});E(If.shortcuts,{displayName:"Keymap<bulletListKeymap>",group:"BulletList"});var Nf=vt("orderedList");E(Nf,{displayName:"Attr<orderedList>",group:"OrderedList"});var Fi=ce("ordered_list",t=>({content:"listItem+",group:"block",attrs:{order:{default:1,validate:"number"},spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ol",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{spread:e.dataset.spread,order:e.hasAttribute("start")?Number(e.getAttribute("start")):1}}}],toDOM:e=>["ol",{...t.get(Nf.key)(e),...e.attrs.order===1?{}:{start:e.attrs.order},"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{spread:i,order:n.start??1}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="ordered_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!0,start:n.attrs.order??1,spread:n.attrs.spread==="true"}),e.next(n.content),e.closeNode()}}}));E(Fi.node,{displayName:"NodeSchema<orderedList>",group:"OrderedList"});E(Fi.ctx,{displayName:"NodeSchemaCtx<orderedList>",group:"OrderedList"});var eb=ge(t=>Ca(/^\s*(\d+)\.\s$/,Fi.type(t),e=>({order:Number(e[1])}),(e,n)=>n.childCount+n.attrs.order===Number(e[1])));E(eb,{displayName:"InputRule<wrapInOrderedListInputRule>",group:"OrderedList"});var Rf=z("WrapInOrderedList",t=>()=>yi(Fi.type(t)));E(Rf,{displayName:"Command<wrapInOrderedListCommand>",group:"OrderedList"});var Of=We("orderedListKeymap",{WrapInOrderedList:{shortcuts:"Mod-Alt-7",command:t=>{let e=t.get(Q);return()=>e.call(Rf.key)}}});E(Of.ctx,{displayName:"KeymapCtx<orderedList>",group:"OrderedList"});E(Of.shortcuts,{displayName:"Keymap<orderedList>",group:"OrderedList"});var Df=vt("listItem");E(Df,{displayName:"Attr<listItem>",group:"ListItem"});var qt=ce("list_item",t=>({group:"listItem",content:"paragraph block*",attrs:{label:{default:"\u2022",validate:"string"},listType:{default:"bullet",validate:"string"},spread:{default:!0,validate:"boolean"}},defining:!0,parseDOM:[{tag:"li",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{label:e.dataset.label,listType:e.dataset.listType,spread:e.dataset.spread==="true"}}}],toDOM:e=>["li",{...t.get(Df.key)(e),"data-label":e.attrs.label,"data-list-type":e.attrs.listType,"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e})=>e==="listItem",runner:(e,n,r)=>{let i=n.label!=null?`${n.label}.`:"\u2022",o=n.label!=null?"ordered":"bullet",s=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{label:i,listType:o,spread:s}),e.next(n.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="list_item",runner:(e,n)=>{e.openNode("listItem",void 0,{spread:n.attrs.spread}),e.next(n.content),e.closeNode()}}}));E(qt.node,{displayName:"NodeSchema<listItem>",group:"ListItem"});E(qt.ctx,{displayName:"NodeSchemaCtx<listItem>",group:"ListItem"});var Lf=z("SinkListItem",t=>()=>Bk(qt.type(t)));E(Lf,{displayName:"Command<sinkListItemCommand>",group:"ListItem"});var Pf=z("LiftListItem",t=>()=>Xa(qt.type(t)));E(Pf,{displayName:"Command<liftListItemCommand>",group:"ListItem"});var Bf=z("SplitListItem",t=>()=>Pk(qt.type(t)));E(Bf,{displayName:"Command<splitListItemCommand>",group:"ListItem"});function Vv(t){return(e,n,r)=>{let{selection:i}=e;if(!(i instanceof B))return!1;let{empty:o,$from:s}=i;return!o||s.parentOffset!==0||s.node(-1).type!==qt.type(t)?!1:Yc(e,n,r)}}var Ff=z("LiftFirstListItem",t=>()=>Vv(t));E(Ff,{displayName:"Command<liftFirstListItemCommand>",group:"ListItem"});var zf=We("listItemKeymap",{NextListItem:{shortcuts:"Enter",command:t=>{let e=t.get(Q);return()=>e.call(Bf.key)}},SinkListItem:{shortcuts:["Tab","Mod-]"],command:t=>{let e=t.get(Q);return()=>e.call(Lf.key)}},LiftListItem:{shortcuts:["Shift-Tab","Mod-["],command:t=>{let e=t.get(Q);return()=>e.call(Pf.key)}},LiftFirstListItem:{shortcuts:["Backspace","Delete"],command:t=>{let e=t.get(Q);return()=>e.call(Ff.key)}}});E(zf.ctx,{displayName:"KeymapCtx<listItem>",group:"ListItem"});E(zf.shortcuts,{displayName:"Keymap<listItem>",group:"ListItem"});var tb=Ga("text",()=>({group:"inline",parseMarkdown:{match:({type:t})=>t==="text",runner:(t,e)=>{t.addText(e.value)}},toMarkdown:{match:t=>t.type.name==="text",runner:(t,e)=>{t.addNode("text",void 0,e.text)}}}));E(tb,{displayName:"NodeSchema<text>",group:"Text"});var _f=vt("html");E(_f,{displayName:"Attr<html>",group:"Html"});var $f=ce("html",t=>({atom:!0,group:"inline",inline:!0,attrs:{value:{default:"",validate:"string"}},toDOM:e=>{let n=document.createElement("span"),r={...t.get(_f.key)(e),"data-value":e.attrs.value,"data-type":"html"};return n.textContent=e.attrs.value,["span",r,e.attrs.value]},parseDOM:[{tag:'span[data-type="html"]',getAttrs:e=>({value:e.dataset.value??""})}],parseMarkdown:{match:({type:e})=>e==="html",runner:(e,n,r)=>{e.addNode(r,{value:n.value})}},toMarkdown:{match:e=>e.type.name==="html",runner:(e,n)=>{e.addNode("html",void 0,n.attrs.value)}}}));E($f.node,{displayName:"NodeSchema<html>",group:"Html"});E($f.ctx,{displayName:"NodeSchemaCtx<html>",group:"Html"});var qv=[qk,ff,Bt,el,hf,Pr,Qa,Lr,yf,Qo,xf,Zo,Tf,es,Sf,Pi,vf,Bi,Nf,Fi,Df,qt,ef,Li,rf,Yo,af,jn,uf,Di,_f,$f,tb].flat(),Kv=[Uk,Zk,eb,Jk,Yk,Kk].flat(),Uv=[_k,$k,Wk,Hk],Jv=z("IsMarkSelected",()=>t=>e=>{if(!t)return!1;let{doc:n,selection:r}=e;return n.rangeHasMark(r.from,r.to,t)}),Gv=z("IsNoteSelected",()=>t=>e=>t?Xg(e,t).hasNode:!1),Xv=z("ClearTextInCurrentBlock",()=>()=>(t,e)=>{let n=t.tr,{$from:r,$to:i}=n.selection,{pos:o}=r,{pos:s}=i,a=o-r.node().content.size;return a<0?!1:(n=n.deleteRange(a,s),e?.(n),!0)}),Yv=z("SetBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr,{from:s,to:a}=o.selection;try{o.setBlockType(s,a,r,i)}catch{return!1}return n?.(o),!0}),Qv=z("WrapInBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let{$from:s,$to:a}=o.selection,l=s.blockRange(a),c=l&&yr(l,r,i);if(!c)return!1;o=o.wrap(l,c)}catch{return!1}return n?.(o),!0}),Zv=z("AddBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let s=r instanceof rt?r:r.createAndFill(i);if(!s)return!1;o.replaceSelectionWith(s)}catch{return!1}return n?.(o),!0}),eA=z("SelectTextNearPos",()=>t=>(e,n)=>{let{pos:r}=t??{};if(r==null)return!1;let i=(s,a,l)=>Math.min(Math.max(s,a),l),o=e.tr;try{let s=e.doc.resolve(i(r,0,e.doc.content.size));o.setSelection(B.near(s))}catch{return!1}return n?.(o.scrollIntoView()),!0}),tA=[df,kf,Wn,mf,wf,Mf,Qk,Gk,Xk,Rf,Af,Lf,Bf,Pf,Ff,tf,lf,of,jk,Vk,Jv,Gv,Xv,Yv,Qv,Zv,eA],nA=[bf,Cf,Ef,gf,zf,Of,If,pf,nf,cf,sf].flat(),Hf=gt("remarkAddOrderInList",()=>()=>t=>{Rt(t,"list",e=>{if(e.ordered){let n=e.start??1;e.children.forEach((r,i)=>{r.label=i+n})}})});E(Hf.plugin,{displayName:"Remark<remarkAddOrderInListPlugin>",group:"Remark"});E(Hf.options,{displayName:"RemarkConfig<remarkAddOrderInListPlugin>",group:"Remark"});var Wf=gt("remarkLineBreak",()=>()=>t=>{let e=/[\t ]*(?:\r?\n|\r)/g;Rt(t,"text",(n,r,i)=>{if(!n.value||typeof n.value!="string")return;let o=[],s=0;e.lastIndex=0;let a=e.exec(n.value);for(;a;){let l=a.index;s!==l&&o.push({type:"text",value:n.value.slice(s,l)}),o.push({type:"break",data:{isInline:!0}}),s=l+a[0].length,a=e.exec(n.value)}if(o.length>0&&i&&typeof r=="number")return s<n.value.length&&o.push({type:"text",value:n.value.slice(s)}),i.children.splice(r,1,...o),r+o.length})});E(Wf.plugin,{displayName:"Remark<remarkLineBreak>",group:"Remark"});E(Wf.options,{displayName:"RemarkConfig<remarkLineBreak>",group:"Remark"});var jf=gt("remarkInlineLink",()=>Ya);E(jf.plugin,{displayName:"Remark<remarkInlineLinkPlugin>",group:"Remark"});E(jf.options,{displayName:"RemarkConfig<remarkInlineLinkPlugin>",group:"Remark"});var rA=t=>!!t.children,iA=t=>t.type==="html";function oA(t,e){return n(t,0,null)[0];function n(r,i,o){if(rA(r)){let s=[];for(let a=0,l=r.children.length;a<l;a++){let c=r.children[a];if(c){let u=n(c,a,r);if(u)for(let f=0,d=u.length;f<d;f++){let p=u[f];p&&s.push(p)}}}r.children=s}return e(r,i,o)}}var sA=["root","blockquote","listItem"],Vf=gt("remarkHTMLTransformer",()=>()=>t=>{oA(t,(e,n,r)=>iA(e)?(r&&sA.includes(r.type)&&(e.children=[{...e}],delete e.value,e.type="paragraph"),[e]):[e])});E(Vf.plugin,{displayName:"Remark<remarkHtmlTransformer>",group:"Remark"});E(Vf.options,{displayName:"RemarkConfig<remarkHtmlTransformer>",group:"Remark"});var qf=gt("remarkMarker",()=>()=>(t,e)=>{let n=r=>e.value.charAt(r.position.start.offset);Rt(t,r=>["strong","emphasis"].includes(r.type),r=>{r.marker=n(r)})});E(qf.plugin,{displayName:"Remark<remarkMarker>",group:"Remark"});E(qf.options,{displayName:"RemarkConfig<remarkMarker>",group:"Remark"});var nb=pe(()=>{let t=!1,e=new X({key:new ee("MILKDOWN_INLINE_NODES_CURSOR"),state:{init(){return!1},apply(n){if(!n.selection.empty)return!1;let r=n.selection.$from,i=r.nodeBefore,o=r.nodeAfter;return!!(i&&o&&i.isInline&&!i.isText&&o.isInline&&!o.isText)}},props:{handleDOMEvents:{compositionend:(n,r)=>t?(t=!1,requestAnimationFrame(()=>{if(e.getState(n.state)){let i=n.state.selection.from;r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i))}}),!0):!1,compositionstart:n=>(e.getState(n.state)&&(t=!0),!1),beforeinput:(n,r)=>{if(e.getState(n.state)&&r instanceof InputEvent&&r.data&&!t){let i=n.state.selection.from;return r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i)),!0}return!1}},decorations(n){if(e.getState(n)){let r=n.selection.$from.pos,i=document.createElement("span"),o=le.widget(r,i,{side:-1}),s=document.createElement("span"),a=le.widget(r,s);return setTimeout(()=>{i.contentEditable="true",s.contentEditable="true"}),ae.create(n.doc,[o,a])}return ae.empty}}});return e});E(nb,{displayName:"Prose<inlineNodesCursorPlugin>",group:"Prose"});var rb=pe(t=>new X({key:new ee("MILKDOWN_HARDBREAK_MARKS"),appendTransaction:(e,n,r)=>{if(!e.length)return;let[i]=e;if(!i)return;let[o]=i.steps;if(i.getMeta("hardbreak")){if(!(o instanceof we))return;let{from:s}=o;return r.tr.setNodeMarkup(s,Lr.type(t),void 0,[])}if(o instanceof hr){let s=r.tr,{from:a,to:l}=o;return r.doc.nodesBetween(a,l,(c,u)=>{c.type===Lr.type(t)&&(s=s.setNodeMarkup(u,Lr.type(t),void 0,[]))}),s}}}));E(rb,{displayName:"Prose<hardbreakClearMarkPlugin>",group:"Prose"});var Kf=Ae(["table","code_block"],"hardbreakFilterNodes");E(Kf,{displayName:"Ctx<hardbreakFilterNodes>",group:"Prose"});var ib=pe(t=>{let e=t.get(Kf.key);return new X({key:new ee("MILKDOWN_HARDBREAK_FILTER"),filterTransaction:(n,r)=>{let i=n.getMeta("hardbreak"),[o]=n.steps;if(i&&o){let{from:s}=o,a=r.doc.resolve(s),l=a.depth,c=!0;for(;l>0;)e.includes(a.node(l).type.name)&&(c=!1),l--;return c}return!0}})});E(ib,{displayName:"Prose<hardbreakFilterPlugin>",group:"Prose"});var ob=pe(t=>{let e=new ee("MILKDOWN_HEADING_ID"),n=r=>{if(r.composing)return;let i=t.get(el.key),o=r.state.tr.setMeta("addToHistory",!1),s=!1,a={};r.state.doc.descendants((l,c)=>{if(l.type===Pr.type(t)){if(l.textContent.trim().length===0)return;let u=l.attrs,f=i(l);a[f]?(a[f]+=1,f+=`-#${a[f]}`):a[f]=1,u.id!==f&&(s=!0,o.setMeta(e,!0).setNodeMarkup(c,void 0,{...u,id:f}))}}),s&&r.dispatch(o)};return new X({key:e,view:r=>(n(r),{update:(i,o)=>{i.state.doc.eq(o.doc)||n(i)}})})});E(ob,{displayName:"Prose<syncHeadingIdPlugin>",group:"Prose"});var sb=pe(t=>{let e=(n,r,i)=>{if(!i.selection||n.some(f=>f.getMeta("addToHistory")===!1||!f.isGeneric))return null;let o=Fi.type(t),s=Bi.type(t),a=qt.type(t),l=(f,d,p=1)=>{let h=!1,m=`${d+p}.`;return f.label!==m&&(f.label=m,h=!0),h},c=i.tr,u=!1;return i.doc.descendants((f,d,p,h)=>{if(f.type===s){let m=f.maybeChild(0);m?.type===a&&m.attrs.listType==="ordered"&&(u=!0,c.setNodeMarkup(d,o,{spread:"true"}),f.descendants((g,y,b,C)=>{if(g.type===a){let v={...g.attrs};l(v,C)&&(c=c.setNodeMarkup(y,void 0,v))}return!1}))}else if(f.type===a&&p?.type===o){let m={...f.attrs},g=!1;m.listType!=="ordered"&&(m.listType="ordered",g=!0),p?.maybeChild(0)&&(g=l(m,h,p?.attrs.order??1)),g&&(c=c.setNodeMarkup(d,void 0,m),u=!0)}}),u?c.setMeta("addToHistory",!1):null};return new X({key:new ee("MILKDOWN_KEEP_LIST_ORDER"),appendTransaction:e})});E(sb,{displayName:"Prose<syncListOrderPlugin>",group:"Prose"});var aA=[rb,Kf,ib,nb,Hf,jf,Wf,Vf,qf,Za,ob,sb].flat(),ab=[qv,Kv,Uv,tA,nA,aA].flat();var Jf,Gf;if(typeof WeakMap<"u"){let t=new WeakMap;Jf=e=>t.get(e),Gf=(e,n)=>(t.set(e,n),n)}else{let t=[],n=0;Jf=r=>{for(let i=0;i<t.length;i+=2)if(t[i]==r)return t[i+1]},Gf=(r,i)=>(n==10&&(n=0),t[n++]=r,t[n++]=i)}var oe=class{constructor(t,e,n,r){this.width=t,this.height=e,this.map=n,this.problems=r}findCell(t){for(let e=0;e<this.map.length;e++){let n=this.map[e];if(n!=t)continue;let r=e%this.width,i=e/this.width|0,o=r+1,s=i+1;for(let a=1;o<this.width&&this.map[e+a]==n;a++)o++;for(let a=1;s<this.height&&this.map[e+this.width*a]==n;a++)s++;return{left:r,top:i,right:o,bottom:s}}throw new RangeError(`No cell with offset ${t} found`)}colCount(t){for(let e=0;e<this.map.length;e++)if(this.map[e]==t)return e%this.width;throw new RangeError(`No cell with offset ${t} found`)}nextCell(t,e,n){let{left:r,right:i,top:o,bottom:s}=this.findCell(t);return e=="horiz"?(n<0?r==0:i==this.width)?null:this.map[o*this.width+(n<0?r-1:i)]:(n<0?o==0:s==this.height)?null:this.map[r+this.width*(n<0?o-1:s)]}rectBetween(t,e){let{left:n,right:r,top:i,bottom:o}=this.findCell(t),{left:s,right:a,top:l,bottom:c}=this.findCell(e);return{left:Math.min(n,s),top:Math.min(i,l),right:Math.max(r,a),bottom:Math.max(o,c)}}cellsInRect(t){let e=[],n={};for(let r=t.top;r<t.bottom;r++)for(let i=t.left;i<t.right;i++){let o=r*this.width+i,s=this.map[o];n[s]||(n[s]=!0,!(i==t.left&&i&&this.map[o-1]==s||r==t.top&&r&&this.map[o-this.width]==s)&&e.push(s))}return e}positionAt(t,e,n){for(let r=0,i=0;;r++){let o=i+n.child(r).nodeSize;if(r==t){let s=e+t*this.width,a=(t+1)*this.width;for(;s<a&&this.map[s]<i;)s++;return s==a?o-1:this.map[s]}i=o}}static get(t){return Jf(t)||Gf(t,lA(t))}};function lA(t){if(t.type.spec.tableRole!="table")throw new RangeError("Not a table node: "+t.type.name);let e=cA(t),n=t.childCount,r=[],i=0,o=null,s=[];for(let c=0,u=e*n;c<u;c++)r[c]=0;for(let c=0,u=0;c<n;c++){let f=t.child(c);u++;for(let h=0;;h++){for(;i<r.length&&r[i]!=0;)i++;if(h==f.childCount)break;let m=f.child(h),{colspan:g,rowspan:y,colwidth:b}=m.attrs;for(let C=0;C<y;C++){if(C+c>=n){(o||(o=[])).push({type:"overlong_rowspan",pos:u,n:y-C});break}let v=i+C*e;for(let A=0;A<g;A++){r[v+A]==0?r[v+A]=u:(o||(o=[])).push({type:"collision",row:c,pos:u,n:g-A});let w=b&&b[A];if(w){let N=(v+A)%e*2,P=s[N];P==null||P!=w&&s[N+1]==1?(s[N]=w,s[N+1]=1):P==w&&s[N+1]++}}}i+=g,u+=m.nodeSize}let d=(c+1)*e,p=0;for(;i<d;)r[i++]==0&&p++;p&&(o||(o=[])).push({type:"missing",row:c,n:p}),u++}(e===0||n===0)&&(o||(o=[])).push({type:"zero_sized"});let a=new oe(e,n,r,o),l=!1;for(let c=0;!l&&c<s.length;c+=2)s[c]!=null&&s[c+1]<n&&(l=!0);return l&&uA(a,s,t),a}function cA(t){let e=-1,n=!1;for(let r=0;r<t.childCount;r++){let i=t.child(r),o=0;if(n)for(let s=0;s<r;s++){let a=t.child(s);for(let l=0;l<a.childCount;l++){let c=a.child(l);s+c.attrs.rowspan>r&&(o+=c.attrs.colspan)}}for(let s=0;s<i.childCount;s++){let a=i.child(s);o+=a.attrs.colspan,a.attrs.rowspan>1&&(n=!0)}e==-1?e=o:e!=o&&(e=Math.max(e,o))}return e}function uA(t,e,n){t.problems||(t.problems=[]);let r={};for(let i=0;i<t.map.length;i++){let o=t.map[i];if(r[o])continue;r[o]=!0;let s=n.nodeAt(o);if(!s)throw new RangeError(`No cell with offset ${o} found`);let a=null,l=s.attrs;for(let c=0;c<l.colspan;c++){let u=e[(i+c)%t.width*2];u!=null&&(!l.colwidth||l.colwidth[c]!=u)&&((a||(a=fA(l)))[c]=u)}a&&t.problems.unshift({type:"colwidth mismatch",pos:o,colwidth:a})}}function fA(t){if(t.colwidth)return t.colwidth.slice();let e=[];for(let n=0;n<t.colspan;n++)e.push(0);return e}function lb(t,e){if(typeof t=="string")return{};let n=t.getAttribute("data-colwidth"),r=n&&/^\d+(,\d+)*$/.test(n)?n.split(",").map(s=>Number(s)):null,i=Number(t.getAttribute("colspan")||1),o={colspan:i,rowspan:Number(t.getAttribute("rowspan")||1),colwidth:r&&r.length==i?r:null};for(let s in e){let a=e[s].getFromDOM,l=a&&a(t);l!=null&&(o[s]=l)}return o}function cb(t,e){let n={};t.attrs.colspan!=1&&(n.colspan=t.attrs.colspan),t.attrs.rowspan!=1&&(n.rowspan=t.attrs.rowspan),t.attrs.colwidth&&(n["data-colwidth"]=t.attrs.colwidth.join(","));for(let r in e){let i=e[r].setDOMAttr;i&&i(t.attrs[r],n)}return n}function dA(t){if(t!==null){if(!Array.isArray(t))throw new TypeError("colwidth must be null or an array");for(let e of t)if(typeof e!="number")throw new TypeError("colwidth must be null or an array of numbers")}}function wb(t){let e=t.cellAttributes||{},n={colspan:{default:1,validate:"number"},rowspan:{default:1,validate:"number"},colwidth:{default:null,validate:dA}};for(let r in e)n[r]={default:e[r].default,validate:e[r].validate};return{table:{content:"table_row+",tableRole:"table",isolating:!0,group:t.tableGroup,parseDOM:[{tag:"table"}],toDOM(){return["table",["tbody",0]]}},table_row:{content:"(table_cell | table_header)*",tableRole:"row",parseDOM:[{tag:"tr"}],toDOM(){return["tr",0]}},table_cell:{content:t.cellContent,attrs:n,tableRole:"cell",isolating:!0,parseDOM:[{tag:"td",getAttrs:r=>lb(r,e)}],toDOM(r){return["td",cb(r,e),0]}},table_header:{content:t.cellContent,attrs:n,tableRole:"header_cell",isolating:!0,parseDOM:[{tag:"th",getAttrs:r=>lb(r,e)}],toDOM(r){return["th",cb(r,e),0]}}}}function et(t){let e=t.cached.tableNodeTypes;if(!e){e=t.cached.tableNodeTypes={};for(let n in t.nodes){let r=t.nodes[n],i=r.spec.tableRole;i&&(e[i]=r)}}return e}var Vn=new ee("selectingCells");function $i(t){for(let e=t.depth-1;e>0;e--)if(t.node(e).type.spec.tableRole=="row")return t.node(0).resolve(t.before(e+1));return null}function De(t){let e=t.selection.$head;for(let n=e.depth;n>0;n--)if(e.node(n).type.spec.tableRole=="row")return!0;return!1}function sl(t){let e=t.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;let n=$i(e.$head)||pA(e.$head);if(n)return n;throw new RangeError(`No cell found around position ${e.head}`)}function pA(t){for(let e=t.nodeAfter,n=t.pos;e;e=e.firstChild,n++){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n)}for(let e=t.nodeBefore,n=t.pos;e;e=e.lastChild,n--){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n-e.nodeSize)}}function Xf(t){return t.parent.type.spec.tableRole=="row"&&!!t.nodeAfter}function hA(t){return t.node(0).resolve(t.pos+t.nodeAfter.nodeSize)}function Zf(t,e){return t.depth==e.depth&&t.pos>=e.start(-1)&&t.pos<=e.end(-1)}function Cb(t,e,n){let r=t.node(-1),i=oe.get(r),o=t.start(-1),s=i.nextCell(t.pos-o,e,n);return s==null?null:t.node(0).resolve(o+s)}function Br(t,e,n=1){let r={...t,colspan:t.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,n),r.colwidth.some(i=>i>0)||(r.colwidth=null)),r}function mA(t,e,n=1){let r={...t,colspan:t.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let i=0;i<n;i++)r.colwidth.splice(e,0,0)}return r}function gA(t,e,n){let r=et(e.type.schema).header_cell;for(let i=0;i<t.height;i++)if(e.nodeAt(t.map[n+i*t.width]).type!=r)return!1;return!0}var he=class kn extends ${constructor(e,n=e){let r=e.node(-1),i=oe.get(r),o=e.start(-1),s=i.rectBetween(e.pos-o,n.pos-o),a=e.node(0),l=i.cellsInRect(s).filter(u=>u!=n.pos-o);l.unshift(n.pos-o);let c=l.map(u=>{let f=r.nodeAt(u);if(!f)throw new RangeError(`No cell with offset ${u} found`);let d=o+u+1;return new On(a.resolve(d),a.resolve(d+f.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=n}map(e,n){let r=e.resolve(n.map(this.$anchorCell.pos)),i=e.resolve(n.map(this.$headCell.pos));if(Xf(r)&&Xf(i)&&Zf(r,i)){let o=this.$anchorCell.node(-1)!=r.node(-1);return o&&this.isRowSelection()?kn.rowSelection(r,i):o&&this.isColSelection()?kn.colSelection(r,i):new kn(r,i)}return B.between(r,i)}content(){let e=this.$anchorCell.node(-1),n=oe.get(e),r=this.$anchorCell.start(-1),i=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),o={},s=[];for(let l=i.top;l<i.bottom;l++){let c=[];for(let u=l*n.width+i.left,f=i.left;f<i.right;f++,u++){let d=n.map[u];if(o[d])continue;o[d]=!0;let p=n.findCell(d),h=e.nodeAt(d);if(!h)throw new RangeError(`No cell with offset ${d} found`);let m=i.left-p.left,g=p.right-i.right;if(m>0||g>0){let y=h.attrs;if(m>0&&(y=Br(y,0,m)),g>0&&(y=Br(y,y.colspan-g,g)),p.left<i.left){if(h=h.type.createAndFill(y),!h)throw new RangeError(`Could not create cell with attrs ${JSON.stringify(y)}`)}else h=h.type.create(y,h.content)}if(p.top<i.top||p.bottom>i.bottom){let y={...h.attrs,rowspan:Math.min(p.bottom,i.bottom)-Math.max(p.top,i.top)};p.top<i.top?h=h.type.createAndFill(y):h=h.type.create(y,h.content)}c.push(h)}s.push(e.child(l).copy(M.from(c)))}let a=this.isColSelection()&&this.isRowSelection()?e:s;return new R(M.from(a),1,1)}replace(e,n=R.empty){let r=e.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:a,$to:l}=i[s],c=e.mapping.slice(r);e.replace(c.map(a.pos),c.map(l.pos),s?R.empty:n)}let o=$.findFrom(e.doc.resolve(e.mapping.slice(r).map(this.to)),-1);o&&e.setSelection(o)}replaceWith(e,n){this.replace(e,new R(M.from(n),0,0))}forEachCell(e){let n=this.$anchorCell.node(-1),r=oe.get(n),i=this.$anchorCell.start(-1),o=r.cellsInRect(r.rectBetween(this.$anchorCell.pos-i,this.$headCell.pos-i));for(let s=0;s<o.length;s++)e(n.nodeAt(o[s]),i+o[s])}isColSelection(){let e=this.$anchorCell.index(-1),n=this.$headCell.index(-1);if(Math.min(e,n)>0)return!1;let r=e+this.$anchorCell.nodeAfter.attrs.rowspan,i=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,i)==this.$headCell.node(-1).childCount}static colSelection(e,n=e){let r=e.node(-1),i=oe.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.top<=a.top?(s.top>0&&(e=l.resolve(o+i.map[s.left])),a.bottom<i.height&&(n=l.resolve(o+i.map[i.width*(i.height-1)+a.right-1]))):(a.top>0&&(n=l.resolve(o+i.map[a.left])),s.bottom<i.height&&(e=l.resolve(o+i.map[i.width*(i.height-1)+s.right-1]))),new kn(e,n)}isRowSelection(){let e=this.$anchorCell.node(-1),n=oe.get(e),r=this.$anchorCell.start(-1),i=n.colCount(this.$anchorCell.pos-r),o=n.colCount(this.$headCell.pos-r);if(Math.min(i,o)>0)return!1;let s=i+this.$anchorCell.nodeAfter.attrs.colspan,a=o+this.$headCell.nodeAfter.attrs.colspan;return Math.max(s,a)==n.width}eq(e){return e instanceof kn&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,n=e){let r=e.node(-1),i=oe.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.left<=a.left?(s.left>0&&(e=l.resolve(o+i.map[s.top*i.width])),a.right<i.width&&(n=l.resolve(o+i.map[i.width*(a.top+1)-1]))):(a.left>0&&(n=l.resolve(o+i.map[a.top*i.width])),s.right<i.width&&(e=l.resolve(o+i.map[i.width*(s.top+1)-1]))),new kn(e,n)}toJSON(){return{type:"cell",anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(e,n){return new kn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){return new kn(e.resolve(n),e.resolve(r))}getBookmark(){return new yA(this.$anchorCell.pos,this.$headCell.pos)}};he.prototype.visible=!1;$.jsonID("cell",he);var yA=class Sb{constructor(e,n){this.anchor=e,this.head=n}map(e){return new Sb(e.map(this.anchor),e.map(this.head))}resolve(e){let n=e.resolve(this.anchor),r=e.resolve(this.head);return n.parent.type.spec.tableRole=="row"&&r.parent.type.spec.tableRole=="row"&&n.index()<n.parent.childCount&&r.index()<r.parent.childCount&&Zf(n,r)?new he(n,r):$.near(r,1)}};function kA(t){if(!(t.selection instanceof he))return null;let e=[];return t.selection.forEachCell((n,r)=>{e.push(le.node(r,r+n.nodeSize,{class:"selectedCell"}))}),ae.create(t.doc,e)}function bA({$from:t,$to:e}){if(t.pos==e.pos||t.pos<e.pos-6)return!1;let n=t.pos,r=e.pos,i=t.depth;for(;i>=0&&!(t.after(i+1)<t.end(i));i--,n++);for(let o=e.depth;o>=0&&!(e.before(o+1)>e.start(o));o--,r--);return n==r&&/row|table/.test(t.node(i).type.spec.tableRole)}function xA({$from:t,$to:e}){let n,r;for(let i=t.depth;i>0;i--){let o=t.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){n=o;break}}for(let i=e.depth;i>0;i--){let o=e.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){r=o;break}}return n!==r&&e.parentOffset===0}function wA(t,e,n){let r=(e||t).selection,i=(e||t).doc,o,s;if(r instanceof H&&(s=r.node.type.spec.tableRole)){if(s=="cell"||s=="header_cell")o=he.create(i,r.from);else if(s=="row"){let a=i.resolve(r.from+1);o=he.rowSelection(a,a)}else if(!n){let a=oe.get(r.node),l=r.from+1,c=l+a.map[a.width*a.height-1];o=he.create(i,l+1,c)}}else r instanceof B&&bA(r)?o=B.create(i,r.from):r instanceof B&&xA(r)&&(o=B.create(i,r.$from.start(),r.$from.end()));return o&&(e||(e=t.tr)).setSelection(o),e}var CA=new ee("fix-tables");function Mb(t,e,n,r){let i=t.childCount,o=e.childCount;e:for(let s=0,a=0;s<o;s++){let l=e.child(s);for(let c=a,u=Math.min(i,s+3);c<u;c++)if(t.child(c)==l){a=c+1,n+=l.nodeSize;continue e}r(l,n),a<i&&t.child(a).sameMarkup(l)?Mb(t.child(a),l,n+1,r):l.nodesBetween(0,l.content.size,r,n+1),n+=l.nodeSize}}function SA(t,e){let n,r=(i,o)=>{i.type.spec.tableRole=="table"&&(n=MA(t,i,o,n))};return e?e.doc!=t.doc&&Mb(e.doc,t.doc,0,r):t.doc.descendants(r),n}function MA(t,e,n,r){let i=oe.get(e);if(!i.problems)return r;r||(r=t.tr);let o=[];for(let l=0;l<i.height;l++)o.push(0);for(let l=0;l<i.problems.length;l++){let c=i.problems[l];if(c.type=="collision"){let u=e.nodeAt(c.pos);if(!u)continue;let f=u.attrs;for(let d=0;d<f.rowspan;d++)o[c.row+d]+=c.n;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,Br(f,f.colspan-c.n,c.n))}else if(c.type=="missing")o[c.row]+=c.n;else if(c.type=="overlong_rowspan"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,rowspan:u.attrs.rowspan-c.n})}else if(c.type=="colwidth mismatch"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,colwidth:c.colwidth})}else if(c.type=="zero_sized"){let u=r.mapping.map(n);r.delete(u,u+e.nodeSize)}}let s,a;for(let l=0;l<o.length;l++)o[l]&&(s==null&&(s=l),a=l);for(let l=0,c=n+1;l<i.height;l++){let u=e.child(l),f=c+u.nodeSize,d=o[l];if(d>0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);let h=[];for(let g=0;g<d;g++){let y=et(t.schema)[p].createAndFill();y&&h.push(y)}let m=(l==0||s==l-1)&&a==l?c+1:f-1;r.insert(r.mapping.map(m),h)}c=f}return r.setMeta(CA,{fixTables:!0})}function Eb(t){let e=oe.get(t),n=[],r=e.height,i=e.width;for(let o=0;o<r;o++){let s=[];for(let a=0;a<i;a++){let l=o*i+a,c=e.map[l];if(o>0){let u=l-i;if(c===e.map[u]){s.push(null);continue}}if(a>0){let u=l-1;if(c===e.map[u]){s.push(null);continue}}s.push(t.nodeAt(c))}n.push(s)}return n}function Tb(t,e){let n=[],r=oe.get(t),i=r.height,o=r.width;for(let s=0;s<i;s++){let a=t.child(s),l=[];for(let u=0;u<o;u++){let f=e[s][u];if(!f)continue;let d=r.map[s*r.width+u],p=t.nodeAt(d);if(!p)continue;let h=p.type.createChecked(f.attrs,f.content,f.marks);l.push(h)}let c=a.type.createChecked(a.attrs,l,a.marks);n.push(c)}return t.type.createChecked(t.attrs,n,t.marks)}function vb(t,e,n,r){let i=e[0]>n[0]?-1:1,o=t.splice(e[0],e.length),s=o.length%2===0?1:0,a;return r===-1&&i===1?a=n[0]-1:r===1&&i===-1?a=n[n.length-1]-s+1:a=i===-1?n[0]:n[n.length-1]-s,t.splice(a,0,...o),t}function Hi(t){return EA(e=>e.type.spec.tableRole==="table",t)}function EA(t,e){for(let n=e.depth;n>=0;n-=1){let r=e.node(n);if(t(r))return{node:r,pos:n===0?0:e.before(n),start:e.start(n),depth:n}}return null}function zi(t,e){let n=Hi(e.$from);if(!n)return;let r=oe.get(n.node);if(!(t<0||t>r.width-1))return r.cellsInRect({left:t,right:t+1,top:0,bottom:r.height}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function _i(t,e){let n=Hi(e.$from);if(!n)return;let r=oe.get(n.node);if(!(t<0||t>r.height-1))return r.cellsInRect({left:0,right:r.width,top:t,bottom:t+1}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function ub(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=zi(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=zi(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;d.node.attrs.colspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=zi(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=zi(r,t.selection),a=_i(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=zi(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function fb(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=_i(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=_i(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;d.node.attrs.rowspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=_i(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=_i(r,t.selection),a=zi(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=_i(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function db(t){return t[0].map((e,n)=>t.map(r=>r[n]))}function TA(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=Hi(r.doc.resolve(a));if(!l)return!1;let c=(e=ub(r,i))===null||e===void 0?void 0:e.indexes,u=(n=ub(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=vA(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=oe.get(f),p=l.start,h=o,m=d.positionAt(d.height-1,h,f),g=r.doc.resolve(p+m),y=d.positionAt(0,h,f),b=r.doc.resolve(p+y);return r.setSelection(he.colSelection(g,b)),!0}function vA(t,e,n,r){let i=db(Eb(t));return i=vb(i,e,n,r),i=db(i),Tb(t,i)}function AA(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=Hi(r.doc.resolve(a));if(!l)return!1;let c=(e=fb(r,i))===null||e===void 0?void 0:e.indexes,u=(n=fb(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=IA(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=oe.get(f),p=l.start,h=o,m=d.positionAt(h,d.width-1,f),g=r.doc.resolve(p+m),y=d.positionAt(h,0,f),b=r.doc.resolve(p+y);return r.setSelection(he.rowSelection(g,b)),!0}function IA(t,e,n,r){let i=Eb(t);return i=vb(i,e,n,r),Tb(t,i)}function At(t){let e=t.selection,n=sl(t),r=n.node(-1),i=n.start(-1),o=oe.get(r);return{...e instanceof he?o.rectBetween(e.$anchorCell.pos-i,e.$headCell.pos-i):o.findCell(n.pos-i),tableStart:i,map:o,table:r}}function Ab(t,{map:e,tableStart:n,table:r},i){let o=i>0?-1:0;gA(e,r,i+o)&&(o=i==0||i==e.width?null:0);for(let s=0;s<e.height;s++){let a=s*e.width+i;if(i>0&&i<e.width&&e.map[a-1]==e.map[a]){let l=e.map[a],c=r.nodeAt(l);t.setNodeMarkup(t.mapping.map(n+l),null,mA(c.attrs,i-e.colCount(l))),s+=c.attrs.rowspan-1}else{let l=o==null?et(r.type.schema).cell:r.nodeAt(e.map[a+o]).type,c=e.positionAt(s,i,r);t.insert(t.mapping.map(n+c),l.createAndFill())}}return t}function Ib(t,e){if(!De(t))return!1;if(e){let n=At(t);e(Ab(t.tr,n,n.left))}return!0}function al(t,e){if(!De(t))return!1;if(e){let n=At(t);e(Ab(t.tr,n,n.right))}return!0}function NA(t,{map:e,table:n,tableStart:r},i){let o=t.mapping.maps.length;for(let s=0;s<e.height;){let a=s*e.width+i,l=e.map[a],c=n.nodeAt(l),u=c.attrs;if(i>0&&e.map[a-1]==l||i<e.width-1&&e.map[a+1]==l)t.setNodeMarkup(t.mapping.slice(o).map(r+l),null,Br(u,i-e.colCount(l)));else{let f=t.mapping.slice(o).map(r+l);t.delete(f,f+c.nodeSize)}s+=u.rowspan}}function ll(t,e){if(!De(t))return!1;if(e){let n=At(t),r=t.tr;if(n.left==0&&n.right==n.map.width)return!1;for(let i=n.right-1;NA(r,n,i),i!=n.left;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=oe.get(o)}e(r)}return!0}function RA(t,e,n){var r;let i=et(e.type.schema).header_cell;for(let o=0;o<t.width;o++)if(((r=e.nodeAt(t.map[o+n*t.width]))===null||r===void 0?void 0:r.type)!=i)return!1;return!0}function OA(t,{map:e,tableStart:n,table:r},i){let o=n;for(let c=0;c<i;c++)o+=r.child(c).nodeSize;let s=[],a=i>0?-1:0;RA(e,r,i+a)&&(a=i==0||i==e.height?null:0);for(let c=0,u=e.width*i;c<e.width;c++,u++)if(i>0&&i<e.height&&e.map[u]==e.map[u-e.width]){let f=e.map[u],d=r.nodeAt(f).attrs;t.setNodeMarkup(n+f,null,{...d,rowspan:d.rowspan+1}),c+=d.colspan-1}else{var l;let f=a==null?et(r.type.schema).cell:(l=r.nodeAt(e.map[u+a*e.width]))===null||l===void 0?void 0:l.type,d=f?.createAndFill();d&&s.push(d)}return t.insert(o,et(r.type.schema).row.create(null,s)),t}function ed(t,e){if(!De(t))return!1;if(e){let n=At(t);e(OA(t.tr,n,n.bottom))}return!0}function DA(t,{map:e,table:n,tableStart:r},i){let o=0;for(let c=0;c<i;c++)o+=n.child(c).nodeSize;let s=o+n.child(i).nodeSize,a=t.mapping.maps.length;t.delete(o+r,s+r);let l=new Set;for(let c=0,u=i*e.width;c<e.width;c++,u++){let f=e.map[u];if(!l.has(f)){if(l.add(f),i>0&&f==e.map[u-e.width]){let d=n.nodeAt(f).attrs;t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d,rowspan:d.rowspan-1}),c+=d.colspan-1}else if(i<e.height&&f==e.map[u+e.width]){let d=n.nodeAt(f),p=d.attrs,h=d.type.create({...p,rowspan:d.attrs.rowspan-1},d.content),m=e.positionAt(i+1,c,n);t.insert(t.mapping.slice(a).map(r+m),h),c+=p.colspan-1}}}}function cl(t,e){if(!De(t))return!1;if(e){let n=At(t),r=t.tr;if(n.top==0&&n.bottom==n.map.height)return!1;for(let i=n.bottom-1;DA(r,n,i),i!=n.top;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=oe.get(n.table)}e(r)}return!0}function Nb(t,e){return function(n,r){if(!De(n))return!1;let i=sl(n);if(i.nodeAfter.attrs[t]===e)return!1;if(r){let o=n.tr;n.selection instanceof he?n.selection.forEachCell((s,a)=>{s.attrs[t]!==e&&o.setNodeMarkup(a,null,{...s.attrs,[t]:e})}):o.setNodeMarkup(i.pos,null,{...i.nodeAfter.attrs,[t]:e}),r(o)}return!0}}function LA(t){return function(e,n){if(!De(e))return!1;if(n){let r=et(e.schema),i=At(e),o=e.tr,s=i.map.cellsInRect(t=="column"?{left:i.left,top:0,right:i.right,bottom:i.map.height}:t=="row"?{left:0,top:i.top,right:i.map.width,bottom:i.bottom}:i),a=s.map(l=>i.table.nodeAt(l));for(let l=0;l<s.length;l++)a[l].type==r.header_cell&&o.setNodeMarkup(i.tableStart+s[l],r.cell,a[l].attrs);if(o.steps.length===0)for(let l=0;l<s.length;l++)o.setNodeMarkup(i.tableStart+s[l],r.header_cell,a[l].attrs);n(o)}return!0}}function pb(t,e,n){let r=e.map.cellsInRect({left:0,top:0,right:t=="row"?e.map.width:1,bottom:t=="column"?e.map.height:1});for(let i=0;i<r.length;i++){let o=e.table.nodeAt(r[i]);if(o&&o.type!==n.header_cell)return!1}return!0}function td(t,e){return e=e||{useDeprecatedLogic:!1},e.useDeprecatedLogic?LA(t):function(n,r){if(!De(n))return!1;if(r){let i=et(n.schema),o=At(n),s=n.tr,a=pb("row",o,i),l=pb("column",o,i),c=(t==="column"?a:t==="row"&&l)?1:0,u=t=="column"?{left:0,top:c,right:1,bottom:o.map.height}:t=="row"?{left:c,top:0,right:o.map.width,bottom:1}:o,f=t=="column"?l?i.cell:i.header_cell:t=="row"?a?i.cell:i.header_cell:i.cell;o.map.cellsInRect(u).forEach(d=>{let p=d+o.tableStart,h=s.doc.nodeAt(p);h&&s.setNodeMarkup(p,f,h.attrs)}),r(s)}return!0}}var SW=td("row",{useDeprecatedLogic:!0}),MW=td("column",{useDeprecatedLogic:!0}),EW=td("cell",{useDeprecatedLogic:!0});function PA(t,e){if(e<0){let n=t.nodeBefore;if(n)return t.pos-n.nodeSize;for(let r=t.index(-1)-1,i=t.before();r>=0;r--){let o=t.node(-1).child(r),s=o.lastChild;if(s)return i-1-s.nodeSize;i-=o.nodeSize}}else{if(t.index()<t.parent.childCount-1)return t.pos+t.nodeAfter.nodeSize;let n=t.node(-1);for(let r=t.indexAfter(-1),i=t.after();r<n.childCount;r++){let o=n.child(r);if(o.childCount)return i+1;i+=o.nodeSize}}return null}function ts(t){return function(e,n){if(!De(e))return!1;let r=PA(sl(e),t);if(r==null)return!1;if(n){let i=e.doc.resolve(r);n(e.tr.setSelection(B.between(i,hA(i))).scrollIntoView())}return!0}}function Rb(t,e){let n=t.selection.$anchor;for(let r=n.depth;r>0;r--)if(n.node(r).type.spec.tableRole=="table")return e&&e(t.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function tl(t,e){let n=t.selection;if(!(n instanceof he))return!1;if(e){let r=t.tr,i=et(t.schema).cell.createAndFill().content;n.forEachCell((o,s)=>{o.content.eq(i)||r.replace(r.mapping.map(s+1),r.mapping.map(s+o.nodeSize-1),new R(i,0,0))}),r.docChanged&&e(r)}return!0}function Ob(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return AA({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function Db(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return TA({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function BA(t){if(t.size===0)return null;let{content:e,openStart:n,openEnd:r}=t;for(;e.childCount==1&&(n>0&&r>0||e.child(0).type.spec.tableRole=="table");)n--,r--,e=e.child(0).content;let i=e.child(0),o=i.type.spec.tableRole,s=i.type.schema,a=[];if(o=="row")for(let l=0;l<e.childCount;l++){let c=e.child(l).content,u=l?0:Math.max(0,n-1),f=l<e.childCount-1?0:Math.max(0,r-1);(u||f)&&(c=Yf(et(s).row,new R(c,u,f)).content),a.push(c)}else if(o=="cell"||o=="header_cell")a.push(n||r?Yf(et(s).row,new R(e,n,r)).content:e);else return null;return FA(s,a)}function FA(t,e){let n=[];for(let i=0;i<e.length;i++){let o=e[i];for(let s=o.childCount-1;s>=0;s--){let{rowspan:a,colspan:l}=o.child(s).attrs;for(let c=i;c<i+a;c++)n[c]=(n[c]||0)+l}}let r=0;for(let i=0;i<n.length;i++)r=Math.max(r,n[i]);for(let i=0;i<n.length;i++)if(i>=e.length&&e.push(M.empty),n[i]<r){let o=et(t).cell.createAndFill(),s=[];for(let a=n[i];a<r;a++)s.push(o);e[i]=e[i].append(M.from(s))}return{height:e.length,width:r,rows:e}}function Yf(t,e){let n=t.createAndFill();return new pi(n).replace(0,n.content.size,e).doc}function zA({width:t,height:e,rows:n},r,i){if(t!=r){let o=[],s=[];for(let a=0;a<n.length;a++){let l=n[a],c=[];for(let u=o[a]||0,f=0;u<r;f++){let d=l.child(f%l.childCount);u+d.attrs.colspan>r&&(d=d.type.createChecked(Br(d.attrs,d.attrs.colspan,u+d.attrs.colspan-r),d.content)),c.push(d),u+=d.attrs.colspan;for(let p=1;p<d.attrs.rowspan;p++)o[a+p]=(o[a+p]||0)+d.attrs.colspan}s.push(M.from(c))}n=s,t=r}if(e!=i){let o=[];for(let s=0,a=0;s<i;s++,a++){let l=[],c=n[a%e];for(let u=0;u<c.childCount;u++){let f=c.child(u);s+f.attrs.rowspan>i&&(f=f.type.create({...f.attrs,rowspan:Math.max(1,i-f.attrs.rowspan)},f.content)),l.push(f)}o.push(M.from(l))}n=o,e=i}return{width:t,height:e,rows:n}}function _A(t,e,n,r,i,o,s){let a=t.doc.type.schema,l=et(a),c,u;if(i>e.width)for(let f=0,d=0;f<e.height;f++){let p=n.child(f);d+=p.nodeSize;let h=[],m;p.lastChild==null||p.lastChild.type==l.cell?m=c||(c=l.cell.createAndFill()):m=u||(u=l.header_cell.createAndFill());for(let g=e.width;g<i;g++)h.push(m);t.insert(t.mapping.slice(s).map(d-1+r),h)}if(o>e.height){let f=[];for(let h=0,m=(e.height-1)*e.width;h<Math.max(e.width,i);h++){let g=h>=e.width?!1:n.nodeAt(e.map[m+h]).type==l.header_cell;f.push(g?u||(u=l.header_cell.createAndFill()):c||(c=l.cell.createAndFill()))}let d=l.row.create(null,M.from(f)),p=[];for(let h=e.height;h<o;h++)p.push(d);t.insert(t.mapping.slice(s).map(r+n.nodeSize-2),p)}return!!(c||u)}function hb(t,e,n,r,i,o,s,a){if(s==0||s==e.height)return!1;let l=!1;for(let c=i;c<o;c++){let u=s*e.width+c,f=e.map[u];if(e.map[u-e.width]==f){l=!0;let d=n.nodeAt(f),{top:p,left:h}=e.findCell(f);t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d.attrs,rowspan:s-p}),t.insert(t.mapping.slice(a).map(e.positionAt(s,h,n)),d.type.createAndFill({...d.attrs,rowspan:p+d.attrs.rowspan-s})),c+=d.attrs.colspan-1}}return l}function mb(t,e,n,r,i,o,s,a){if(s==0||s==e.width)return!1;let l=!1;for(let c=i;c<o;c++){let u=c*e.width+s,f=e.map[u];if(e.map[u-1]==f){l=!0;let d=n.nodeAt(f),p=e.colCount(f),h=t.mapping.slice(a).map(f+r);t.setNodeMarkup(h,null,Br(d.attrs,s-p,d.attrs.colspan-(s-p))),t.insert(h+d.nodeSize,d.type.createAndFill(Br(d.attrs,0,s-p))),c+=d.attrs.rowspan-1}}return l}function gb(t,e,n,r,i){let o=n?t.doc.nodeAt(n-1):t.doc;if(!o)throw new Error("No table found");let s=oe.get(o),{top:a,left:l}=r,c=l+i.width,u=a+i.height,f=t.tr,d=0;function p(){if(o=n?f.doc.nodeAt(n-1):f.doc,!o)throw new Error("No table found");s=oe.get(o),d=f.mapping.maps.length}_A(f,s,o,n,c,u,d)&&p(),hb(f,s,o,n,l,c,a,d)&&p(),hb(f,s,o,n,l,c,u,d)&&p(),mb(f,s,o,n,a,u,l,d)&&p(),mb(f,s,o,n,a,u,c,d)&&p();for(let h=a;h<u;h++){let m=s.positionAt(h,l,o),g=s.positionAt(h,c,o);f.replace(f.mapping.slice(d).map(m+n),f.mapping.slice(d).map(g+n),new R(i.rows[h-a],0,0))}p(),f.setSelection(new he(f.doc.resolve(n+s.positionAt(a,l,o)),f.doc.resolve(n+s.positionAt(u-1,c-1,o)))),e(f)}var $A=fu({ArrowLeft:nl("horiz",-1),ArrowRight:nl("horiz",1),ArrowUp:nl("vert",-1),ArrowDown:nl("vert",1),"Shift-ArrowLeft":rl("horiz",-1),"Shift-ArrowRight":rl("horiz",1),"Shift-ArrowUp":rl("vert",-1),"Shift-ArrowDown":rl("vert",1),Backspace:tl,"Mod-Backspace":tl,Delete:tl,"Mod-Delete":tl});function il(t,e,n){return n.eq(t.selection)?!1:(e&&e(t.tr.setSelection(n).scrollIntoView()),!0)}function nl(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection;if(o instanceof he)return il(n,r,$.near(o.$headCell,e));if(t!="horiz"&&!o.empty)return!1;let s=Lb(i,t,e);if(s==null)return!1;if(t=="horiz")return il(n,r,$.near(n.doc.resolve(o.head+e),e));{let a=n.doc.resolve(s),l=Cb(a,t,e),c;return l?c=$.near(l,1):e<0?c=$.near(n.doc.resolve(a.before(-1)),-1):c=$.near(n.doc.resolve(a.after(-1)),1),il(n,r,c)}}}function rl(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection,s;if(o instanceof he)s=o;else{let l=Lb(i,t,e);if(l==null)return!1;s=new he(n.doc.resolve(l))}let a=Cb(s.$headCell,t,e);return a?il(n,r,new he(s.$anchorCell,a)):!1}}function HA(t,e){let n=t.state.doc,r=$i(n.resolve(e));return r?(t.dispatch(t.state.tr.setSelection(new he(r))),!0):!1}function WA(t,e,n){if(!De(t.state))return!1;let r=BA(n),i=t.state.selection;if(i instanceof he){r||(r={width:1,height:1,rows:[M.from(Yf(et(t.state.schema).cell,n))]});let o=i.$anchorCell.node(-1),s=i.$anchorCell.start(-1),a=oe.get(o).rectBetween(i.$anchorCell.pos-s,i.$headCell.pos-s);return r=zA(r,a.right-a.left,a.bottom-a.top),gb(t.state,t.dispatch,s,a,r),!0}else if(r){let o=sl(t.state),s=o.start(-1);return gb(t.state,t.dispatch,s,oe.get(o.node(-1)).findCell(o.pos-s),r),!0}else return!1}function jA(t,e){var n;if(e.button!=0||e.ctrlKey||e.metaKey)return;let r=yb(t,e.target),i;if(e.shiftKey&&t.state.selection instanceof he)o(t.state.selection.$anchorCell,e),e.preventDefault();else if(e.shiftKey&&r&&(i=$i(t.state.selection.$anchor))!=null&&((n=Uf(t,e))===null||n===void 0?void 0:n.pos)!=i.pos)o(i,e),e.preventDefault();else if(!r)return;function o(l,c){let u=Uf(t,c),f=Vn.getState(t.state)==null;if(!u||!Zf(l,u))if(f)u=l;else return;let d=new he(l,u);if(f||!t.state.selection.eq(d)){let p=t.state.tr.setSelection(d);f&&p.setMeta(Vn,l.pos),t.dispatch(p)}}function s(){t.root.removeEventListener("mouseup",s),t.root.removeEventListener("dragstart",s),t.root.removeEventListener("mousemove",a),Vn.getState(t.state)!=null&&t.dispatch(t.state.tr.setMeta(Vn,-1))}function a(l){let c=l,u=Vn.getState(t.state),f;if(u!=null)f=t.state.doc.resolve(u);else if(yb(t,c.target)!=r&&(f=Uf(t,e),!f))return s();f&&o(f,c)}t.root.addEventListener("mouseup",s),t.root.addEventListener("dragstart",s),t.root.addEventListener("mousemove",a)}function Lb(t,e,n){if(!(t.state.selection instanceof B))return null;let{$head:r}=t.state.selection;for(let i=r.depth-1;i>=0;i--){let o=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:o.childCount))return null;if(o.type.spec.tableRole=="cell"||o.type.spec.tableRole=="header_cell"){let s=r.before(i),a=e=="vert"?n>0?"down":"up":n>0?"right":"left";return t.endOfTextblock(a)?s:null}}return null}function yb(t,e){for(;e&&e!=t.dom;e=e.parentNode)if(e.nodeName=="TD"||e.nodeName=="TH")return e;return null}function Uf(t,e){let n=t.posAtCoords({left:e.clientX,top:e.clientY});if(!n)return null;let{inside:r,pos:i}=n;return r>=0&&$i(t.state.doc.resolve(r))||$i(t.state.doc.resolve(i))}var VA=class{constructor(t,e){this.node=t,this.defaultCellMinWidth=e,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${e}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),Qf(t,this.colgroup,this.table,e),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,Qf(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function Qf(t,e,n,r,i,o){let s=0,a=!0,l=e.firstChild,c=t.firstChild;if(c){for(let f=0,d=0;f<c.childCount;f++){let{colspan:p,colwidth:h}=c.child(f).attrs;for(let m=0;m<p;m++,d++){let g=i==d?o:h&&h[m],y=g?g+"px":"";if(s+=g||r,g||(a=!1),l)l.style.width!=y&&(l.style.width=y),l=l.nextSibling;else{let b=document.createElement("col");b.style.width=y,e.appendChild(b)}}}for(;l;){var u;let f=l.nextSibling;(u=l.parentNode)===null||u===void 0||u.removeChild(l),l=f}a?(n.style.width=s+"px",n.style.minWidth=""):(n.style.width="",n.style.minWidth=s+"px")}}var yt=new ee("tableColumnResizing");function Pb({handleWidth:t=5,cellMinWidth:e=25,defaultCellMinWidth:n=100,View:r=VA,lastColumnResizable:i=!0}={}){let o=new X({key:yt,state:{init(s,a){var l;let c=(l=o.spec)===null||l===void 0||(l=l.props)===null||l===void 0?void 0:l.nodeViews,u=et(a.schema).table.name;return r&&c&&(c[u]=(f,d)=>new r(f,n,d)),new qA(-1,!1)},apply(s,a){return a.apply(s)}},props:{attributes:s=>{let a=yt.getState(s);return a&&a.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(s,a)=>{KA(s,a,t,i)},mouseleave:s=>{UA(s)},mousedown:(s,a)=>{JA(s,a,e,n)}},decorations:s=>{let a=yt.getState(s);if(a&&a.activeHandle>-1)return ZA(s,a.activeHandle)},nodeViews:{}}});return o}var qA=class ol{constructor(e,n){this.activeHandle=e,this.dragging=n}apply(e){let n=this,r=e.getMeta(yt);if(r&&r.setHandle!=null)return new ol(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new ol(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&e.docChanged){let i=e.mapping.map(n.activeHandle,-1);return Xf(e.doc.resolve(i))||(i=-1),new ol(i,n.dragging)}return n}};function KA(t,e,n,r){if(!t.editable)return;let i=yt.getState(t.state);if(i&&!i.dragging){let o=XA(e.target),s=-1;if(o){let{left:a,right:l}=o.getBoundingClientRect();e.clientX-a<=n?s=kb(t,e,"left",n):l-e.clientX<=n&&(s=kb(t,e,"right",n))}if(s!=i.activeHandle){if(!r&&s!==-1){let a=t.state.doc.resolve(s),l=a.node(-1),c=oe.get(l),u=a.start(-1);if(c.colCount(a.pos-u)+a.nodeAfter.attrs.colspan-1==c.width-1)return}Bb(t,s)}}}function UA(t){if(!t.editable)return;let e=yt.getState(t.state);e&&e.activeHandle>-1&&!e.dragging&&Bb(t,-1)}function JA(t,e,n,r){var i;if(!t.editable)return!1;let o=(i=t.dom.ownerDocument.defaultView)!==null&&i!==void 0?i:window,s=yt.getState(t.state);if(!s||s.activeHandle==-1||s.dragging)return!1;let a=t.state.doc.nodeAt(s.activeHandle),l=GA(t,s.activeHandle,a.attrs);t.dispatch(t.state.tr.setMeta(yt,{setDragging:{startX:e.clientX,startWidth:l}}));function c(f){o.removeEventListener("mouseup",c),o.removeEventListener("mousemove",u);let d=yt.getState(t.state);d?.dragging&&(YA(t,d.activeHandle,bb(d.dragging,f,n)),t.dispatch(t.state.tr.setMeta(yt,{setDragging:null})))}function u(f){if(!f.which)return c(f);let d=yt.getState(t.state);if(d&&d.dragging){let p=bb(d.dragging,f,n);xb(t,d.activeHandle,p,r)}}return xb(t,s.activeHandle,l,r),o.addEventListener("mouseup",c),o.addEventListener("mousemove",u),e.preventDefault(),!0}function GA(t,e,{colspan:n,colwidth:r}){let i=r&&r[r.length-1];if(i)return i;let o=t.domAtPos(e),s=o.node.childNodes[o.offset].offsetWidth,a=n;if(r)for(let l=0;l<n;l++)r[l]&&(s-=r[l],a--);return s/a}function XA(t){for(;t&&t.nodeName!="TD"&&t.nodeName!="TH";)t=t.classList&&t.classList.contains("ProseMirror")?null:t.parentNode;return t}function kb(t,e,n,r){let i=n=="right"?-r:r,o=t.posAtCoords({left:e.clientX+i,top:e.clientY});if(!o)return-1;let{pos:s}=o,a=$i(t.state.doc.resolve(s));if(!a)return-1;if(n=="right")return a.pos;let l=oe.get(a.node(-1)),c=a.start(-1),u=l.map.indexOf(a.pos-c);return u%l.width==0?-1:c+l.map[u-1]}function bb(t,e,n){let r=e.clientX-t.startX;return Math.max(n,t.startWidth+r)}function Bb(t,e){t.dispatch(t.state.tr.setMeta(yt,{setHandle:e}))}function YA(t,e,n){let r=t.state.doc.resolve(e),i=r.node(-1),o=oe.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1,l=t.state.tr;for(let c=0;c<o.height;c++){let u=c*o.width+a;if(c&&o.map[u]==o.map[u-o.width])continue;let f=o.map[u],d=i.nodeAt(f).attrs,p=d.colspan==1?0:a-o.colCount(f);if(d.colwidth&&d.colwidth[p]==n)continue;let h=d.colwidth?d.colwidth.slice():QA(d.colspan);h[p]=n,l.setNodeMarkup(s+f,null,{...d,colwidth:h})}l.docChanged&&t.dispatch(l)}function xb(t,e,n,r){let i=t.state.doc.resolve(e),o=i.node(-1),s=i.start(-1),a=oe.get(o).colCount(i.pos-s)+i.nodeAfter.attrs.colspan-1,l=t.domAtPos(i.start(-1)).node;for(;l&&l.nodeName!="TABLE";)l=l.parentNode;l&&Qf(o,l.firstChild,l,r,a,n)}function QA(t){return Array(t).fill(0)}function ZA(t,e){let n=[],r=t.doc.resolve(e),i=r.node(-1);if(!i)return ae.empty;let o=oe.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1;for(let c=0;c<o.height;c++){let u=a+c*o.width;if((a==o.width-1||o.map[u]!=o.map[u+1])&&(c==0||o.map[u]!=o.map[u-o.width])){var l;let f=o.map[u],d=s+f+i.nodeAt(f).nodeSize-1,p=document.createElement("div");p.className="column-resize-handle",!((l=yt.getState(t))===null||l===void 0)&&l.dragging&&n.push(le.node(s+f,s+f+i.nodeAt(f).nodeSize,{class:"column-resize-dragging"})),n.push(le.widget(d,p))}}return ae.create(t.doc,n)}function Fb({allowTableNodeSelection:t=!1}={}){return new X({key:Vn,state:{init(){return null},apply(e,n){let r=e.getMeta(Vn);if(r!=null)return r==-1?null:r;if(n==null||!e.docChanged)return n;let{deleted:i,pos:o}=e.mapping.mapResult(n);return i?null:o}},props:{decorations:kA,handleDOMEvents:{mousedown:jA},createSelectionBetween(e){return Vn.getState(e.state)!=null?e.state.selection:null},handleTripleClick:HA,handleKeyDown:$A,handlePaste:WA},appendTransaction(e,n,r){return wA(r,SA(r,n),t)}})}var ul=typeof navigator<"u"?navigator:null,rd=ul&&ul.userAgent||"",eI=/Edge\/(\d+)/.exec(rd),tI=/MSIE \d/.exec(rd),nI=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(rd),rI=!!(tI||nI||eI),iI=!rI&&!!ul&&/Apple Computer/.test(ul.vendor),zb=new ee("safari-ime-span"),nd=!1,oI={key:zb,props:{decorations:sI,handleDOMEvents:{compositionstart:()=>{nd=!0},compositionend:()=>{nd=!1}}}};function sI(t){let{$from:e,$to:n,to:r}=t.selection;if(nd&&e.sameParent(n)){let i=le.widget(r,aI,{ignoreSelection:!0,key:"safari-ime-span"});return ae.create(t.doc,[i])}}function aI(t){let e=t.dom.ownerDocument.createElement("span");return e.className="ProseMirror-safari-ime-span",e}var _b=new X(iI?oI:{key:zb});function id(t,e){let n=String(t);if(typeof e!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(e);for(;i!==-1;)r++,i=n.indexOf(e,i+e.length);return r}function od(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function sd(t,e,n){let i=Nn((n||{}).ignore||[]),o=lI(e),s=-1;for(;++s<o.length;)lr(t,"text",a);function a(c,u){let f=-1,d;for(;++f<u.length;){let p=u[f],h=d?d.children:void 0;if(i(p,h?h.indexOf(p):void 0,d))return;d=p}if(d)return l(c,u)}function l(c,u){let f=u[u.length-1],d=o[s][0],p=o[s][1],h=0,g=f.children.indexOf(c),y=!1,b=[];d.lastIndex=0;let C=d.exec(c.value);for(;C;){let v=C.index,A={index:C.index,input:C.input,stack:[...u,c]},w=p(...C,A);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?d.lastIndex=v+1:(h!==v&&b.push({type:"text",value:c.value.slice(h,v)}),Array.isArray(w)?b.push(...w):w&&b.push(w),h=v+C[0].length,y=!0),!d.global)break;C=d.exec(c.value)}return y?(h<c.value.length&&b.push({type:"text",value:c.value.slice(h)}),f.children.splice(g,1,...b)):b=[c],g+b.length}}function lI(t){let e=[];if(!Array.isArray(t))throw new TypeError("Expected find and replace tuple or list of tuples");let n=!t[0]||Array.isArray(t[0])?t:[t],r=-1;for(;++r<n.length;){let i=n[r];e.push([cI(i[0]),uI(i[1])])}return e}function cI(t){return typeof t=="string"?new RegExp(od(t),"g"):t}function uI(t){return typeof t=="function"?t:function(){return t}}var ad="phrasing",ld=["autolink","link","image","label"];function ud(){return{transforms:[gI],enter:{literalAutolink:fI,literalAutolinkEmail:cd,literalAutolinkHttp:cd,literalAutolinkWww:cd},exit:{literalAutolink:mI,literalAutolinkEmail:hI,literalAutolinkHttp:dI,literalAutolinkWww:pI}}}function fd(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:ad,notInConstruct:ld},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:ad,notInConstruct:ld},{character:":",before:"[ps]",after:"\\/",inConstruct:ad,notInConstruct:ld}]}}function fI(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function cd(t){this.config.enter.autolinkProtocol.call(this,t)}function dI(t){this.config.exit.autolinkProtocol.call(this,t)}function pI(t){this.config.exit.data.call(this,t);let e=this.stack[this.stack.length-1];e.type,e.url="http://"+this.sliceSerialize(t)}function hI(t){this.config.exit.autolinkEmail.call(this,t)}function mI(t){this.exit(t)}function gI(t){sd(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,yI],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,kI]],{ignore:["link","linkReference"]})}function yI(t,e,n,r,i){let o="";if(!$b(i)||(/^w/i.test(e)&&(n=e+n,e="",o="http://"),!bI(n)))return!1;let s=xI(n+r);if(!s[0])return!1;let a={type:"link",title:null,url:o+e+s[0],children:[{type:"text",value:e+s[0]}]};return s[1]?[a,{type:"text",value:s[1]}]:a}function kI(t,e,n,r){return!$b(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+e+"@"+n,children:[{type:"text",value:e+"@"+n}]}}function bI(t){let e=t.split(".");return!(e.length<2||e[e.length-1]&&(/_/.test(e[e.length-1])||!/[a-zA-Z\d]/.test(e[e.length-1]))||e[e.length-2]&&(/_/.test(e[e.length-2])||!/[a-zA-Z\d]/.test(e[e.length-2])))}function xI(t){let e=/[!"&'),.:;<>?\]}]+$/.exec(t);if(!e)return[t,void 0];t=t.slice(0,e.index);let n=e[0],r=n.indexOf(")"),i=id(t,"("),o=id(t,")");for(;r!==-1&&i>o;)t+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),o++;return[t,n]}function $b(t,e){let n=t.input.charCodeAt(t.index-1);return(t.index===0||Wt(n)||nr(n))&&(!e||n!==47)}Hb.peek=II;function wI(){this.buffer()}function CI(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function SI(){this.buffer()}function MI(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function EI(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=qe(this.sliceSerialize(t)).toLowerCase(),n.label=e}function TI(t){this.exit(t)}function vI(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=qe(this.sliceSerialize(t)).toLowerCase(),n.label=e}function AI(t){this.exit(t)}function II(){return"["}function Hb(t,e,n,r){let i=n.createTracker(r),o=i.move("[^"),s=n.enter("footnoteReference"),a=n.enter("reference");return o+=i.move(n.safe(n.associationId(t),{after:"]",before:o})),a(),s(),o+=i.move("]"),o}function dd(){return{enter:{gfmFootnoteCallString:wI,gfmFootnoteCall:CI,gfmFootnoteDefinitionLabelString:SI,gfmFootnoteDefinition:MI},exit:{gfmFootnoteCallString:EI,gfmFootnoteCall:TI,gfmFootnoteDefinitionLabelString:vI,gfmFootnoteDefinition:AI}}}function pd(t){let e=!1;return t&&t.firstLineBlank&&(e=!0),{handlers:{footnoteDefinition:n,footnoteReference:Hb},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,o,s){let a=o.createTracker(s),l=a.move("[^"),c=o.enter("footnoteDefinition"),u=o.enter("label");return l+=a.move(o.safe(o.associationId(r),{before:l,after:"]"})),u(),l+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),l+=a.move((e?` -`:" ")+o.indentLines(o.containerFlow(r,a.current()),e?Wb:NI))),c(),l}}function NI(t,e,n){return e===0?t:Wb(t,e,n)}function Wb(t,e,n){return(n?"":" ")+t}var RI=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];jb.peek=LI;function hd(){return{canContainEols:["delete"],enter:{strikethrough:OI},exit:{strikethrough:DI}}}function md(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:RI}],handlers:{delete:jb}}}function OI(t){this.enter({type:"delete",children:[]},t)}function DI(t){this.exit(t)}function jb(t,e,n,r){let i=n.createTracker(r),o=n.enter("strikethrough"),s=i.move("~~");return s+=n.containerPhrasing(t,{...i.current(),before:s,after:"~"}),s+=i.move("~~"),o(),s}function LI(){return"~"}function PI(t){return t.length}function qb(t,e){let n=e||{},r=(n.align||[]).concat(),i=n.stringLength||PI,o=[],s=[],a=[],l=[],c=0,u=-1;for(;++u<t.length;){let m=[],g=[],y=-1;for(t[u].length>c&&(c=t[u].length);++y<t[u].length;){let b=BI(t[u][y]);if(n.alignDelimiters!==!1){let C=i(b);g[y]=C,(l[y]===void 0||C>l[y])&&(l[y]=C)}m.push(b)}s[u]=m,a[u]=g}let f=-1;if(typeof r=="object"&&"length"in r)for(;++f<c;)o[f]=Vb(r[f]);else{let m=Vb(r);for(;++f<c;)o[f]=m}f=-1;let d=[],p=[];for(;++f<c;){let m=o[f],g="",y="";m===99?(g=":",y=":"):m===108?g=":":m===114&&(y=":");let b=n.alignDelimiters===!1?1:Math.max(1,l[f]-g.length-y.length),C=g+"-".repeat(b)+y;n.alignDelimiters!==!1&&(b=g.length+b+y.length,b>l[f]&&(l[f]=b),p[f]=b),d[f]=C}s.splice(1,0,d),a.splice(1,0,p),u=-1;let h=[];for(;++u<s.length;){let m=s[u],g=a[u];f=-1;let y=[];for(;++f<c;){let b=m[f]||"",C="",v="";if(n.alignDelimiters!==!1){let A=l[f]-(g[f]||0),w=o[f];w===114?C=" ".repeat(A):w===99?A%2?(C=" ".repeat(A/2+.5),v=" ".repeat(A/2-.5)):(C=" ".repeat(A/2),v=C):v=" ".repeat(A)}n.delimiterStart!==!1&&!f&&y.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&b==="")&&(n.delimiterStart!==!1||f)&&y.push(" "),n.alignDelimiters!==!1&&y.push(C),y.push(b),n.alignDelimiters!==!1&&y.push(v),n.padding!==!1&&y.push(" "),(n.delimiterEnd!==!1||f!==c-1)&&y.push("|")}h.push(n.delimiterEnd===!1?y.join("").replace(/ +$/,""):y.join(""))}return h.join(` -`)}function BI(t){return t==null?"":String(t)}function Vb(t){let e=typeof t=="string"?t.codePointAt(0):0;return e===67||e===99?99:e===76||e===108?108:e===82||e===114?114:0}function yd(){return{enter:{table:FI,tableData:Kb,tableHeader:Kb,tableRow:_I},exit:{codeText:$I,table:zI,tableData:gd,tableHeader:gd,tableRow:gd}}}function FI(t){let e=t._align;this.enter({type:"table",align:e.map(function(n){return n==="none"?null:n}),children:[]},t),this.data.inTable=!0}function zI(t){this.exit(t),this.data.inTable=void 0}function _I(t){this.enter({type:"tableRow",children:[]},t)}function gd(t){this.exit(t)}function Kb(t){this.enter({type:"tableCell",children:[]},t)}function $I(t){let e=this.resume();this.data.inTable&&(e=e.replace(/\\([\\|])/g,HI));let n=this.stack[this.stack.length-1];n.type,n.value=e,this.exit(t)}function HI(t,e){return e==="|"?e:t}function kd(t){let e=t||{},n=e.tableCellPadding,r=e.tablePipeAlign,i=e.stringLength,o=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` +`):e.addNode("break")}}}));E(Lr.node,{displayName:"NodeSchema<hardbreak>",group:"Hardbreak"});E(Lr.ctx,{displayName:"NodeSchemaCtx<hardbreak>",group:"Hardbreak"});var Mf=z("InsertHardbreak",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(!(r instanceof B))return!1;if(r.empty){let o=r.$from.node();if(o.childCount>0&&o.lastChild?.type.name==="hardbreak")return n?.(i.replaceRangeWith(r.to-1,r.to,e.schema.node("paragraph")).setSelection($.near(i.doc.resolve(r.to))).scrollIntoView()),!0}return n?.(i.setMeta("hardbreak",!0).replaceSelectionWith(Lr.type(t).create()).scrollIntoView()),!0});E(Mf,{displayName:"Command<insertHardbreakCommand>",group:"Hardbreak"});var Ef=We("hardbreakKeymap",{InsertHardbreak:{shortcuts:"Shift-Enter",command:t=>{let e=t.get(Q);return()=>e.call(Mf.key)}}});E(Ef.ctx,{displayName:"KeymapCtx<hardbreak>",group:"Hardbreak"});E(Ef.shortcuts,{displayName:"Keymap<hardbreak>",group:"Hardbreak"});var Tf=vt("hr");E(Tf,{displayName:"Attr<hr>",group:"Hr"});var es=ce("hr",t=>({group:"block",parseDOM:[{tag:"hr"}],toDOM:e=>["hr",t.get(Tf.key)(e)],parseMarkdown:{match:({type:e})=>e==="thematicBreak",runner:(e,n,r)=>{e.addNode(r)}},toMarkdown:{match:e=>e.type.name==="hr",runner:e=>{e.addNode("thematicBreak")}}}));E(es.node,{displayName:"NodeSchema<hr>",group:"Hr"});E(es.ctx,{displayName:"NodeSchemaCtx<hr>",group:"Hr"});var Qk=ge(t=>new xe(/^(?:---|___\s|\*\*\*\s)$/,(e,n,r,i)=>{let{tr:o}=e;return n[0]&&o.replaceWith(r-1,i,es.type(t).create()),o}));E(Qk,{displayName:"InputRule<insertHrInputRule>",group:"Hr"});var Zk=z("InsertHr",t=>()=>(e,n)=>{if(!n)return!0;let r=Bt.node.type(t).create(),{tr:i,selection:o}=e,{from:s}=o,a=es.type(t).create();if(!a)return!0;let l=i.replaceSelectionWith(a).insert(s,r),c=$.findFrom(l.doc.resolve(s),1,!0);return c&&n(l.setSelection(c).scrollIntoView()),!0});E(Zk,{displayName:"Command<insertHrCommand>",group:"Hr"});var vf=vt("bulletList");E(vf,{displayName:"Attr<bulletList>",group:"BulletList"});var Bi=ce("bullet_list",t=>({content:"listItem+",group:"block",attrs:{spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ul",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{spread:e.dataset.spread==="true"}}}],toDOM:e=>["ul",{...t.get(vf.key)(e),"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"false";e.openNode(r,{spread:i}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="bullet_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!1,spread:n.attrs.spread}).next(n.content).closeNode()}}}));E(Bi.node,{displayName:"NodeSchema<bulletList>",group:"BulletList"});E(Bi.ctx,{displayName:"NodeSchemaCtx<bulletList>",group:"BulletList"});var eb=ge(t=>Ca(/^\s*([-+*])\s$/,Bi.type(t)));E(eb,{displayName:"InputRule<wrapInBulletListInputRule>",group:"BulletList"});var Af=z("WrapInBulletList",t=>()=>yi(Bi.type(t)));E(Af,{displayName:"Command<wrapInBulletListCommand>",group:"BulletList"});var If=We("bulletListKeymap",{WrapInBulletList:{shortcuts:"Mod-Alt-8",command:t=>{let e=t.get(Q);return()=>e.call(Af.key)}}});E(If.ctx,{displayName:"KeymapCtx<bulletListKeymap>",group:"BulletList"});E(If.shortcuts,{displayName:"Keymap<bulletListKeymap>",group:"BulletList"});var Nf=vt("orderedList");E(Nf,{displayName:"Attr<orderedList>",group:"OrderedList"});var Fi=ce("ordered_list",t=>({content:"listItem+",group:"block",attrs:{order:{default:1,validate:"number"},spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ol",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{spread:e.dataset.spread,order:e.hasAttribute("start")?Number(e.getAttribute("start")):1}}}],toDOM:e=>["ol",{...t.get(Nf.key)(e),...e.attrs.order===1?{}:{start:e.attrs.order},"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{spread:i,order:n.start??1}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="ordered_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!0,start:n.attrs.order??1,spread:n.attrs.spread==="true"}),e.next(n.content),e.closeNode()}}}));E(Fi.node,{displayName:"NodeSchema<orderedList>",group:"OrderedList"});E(Fi.ctx,{displayName:"NodeSchemaCtx<orderedList>",group:"OrderedList"});var tb=ge(t=>Ca(/^\s*(\d+)\.\s$/,Fi.type(t),e=>({order:Number(e[1])}),(e,n)=>n.childCount+n.attrs.order===Number(e[1])));E(tb,{displayName:"InputRule<wrapInOrderedListInputRule>",group:"OrderedList"});var Rf=z("WrapInOrderedList",t=>()=>yi(Fi.type(t)));E(Rf,{displayName:"Command<wrapInOrderedListCommand>",group:"OrderedList"});var Of=We("orderedListKeymap",{WrapInOrderedList:{shortcuts:"Mod-Alt-7",command:t=>{let e=t.get(Q);return()=>e.call(Rf.key)}}});E(Of.ctx,{displayName:"KeymapCtx<orderedList>",group:"OrderedList"});E(Of.shortcuts,{displayName:"Keymap<orderedList>",group:"OrderedList"});var Df=vt("listItem");E(Df,{displayName:"Attr<listItem>",group:"ListItem"});var qt=ce("list_item",t=>({group:"listItem",content:"paragraph block*",attrs:{label:{default:"\u2022",validate:"string"},listType:{default:"bullet",validate:"string"},spread:{default:!0,validate:"boolean"}},defining:!0,parseDOM:[{tag:"li",getAttrs:e=>{if(!(e instanceof HTMLElement))throw pt(e);return{label:e.dataset.label,listType:e.dataset.listType,spread:e.dataset.spread==="true"}}}],toDOM:e=>["li",{...t.get(Df.key)(e),"data-label":e.attrs.label,"data-list-type":e.attrs.listType,"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e})=>e==="listItem",runner:(e,n,r)=>{let i=n.label!=null?`${n.label}.`:"\u2022",o=n.label!=null?"ordered":"bullet",s=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{label:i,listType:o,spread:s}),e.next(n.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="list_item",runner:(e,n)=>{e.openNode("listItem",void 0,{spread:n.attrs.spread}),e.next(n.content),e.closeNode()}}}));E(qt.node,{displayName:"NodeSchema<listItem>",group:"ListItem"});E(qt.ctx,{displayName:"NodeSchemaCtx<listItem>",group:"ListItem"});var Lf=z("SinkListItem",t=>()=>Fk(qt.type(t)));E(Lf,{displayName:"Command<sinkListItemCommand>",group:"ListItem"});var Pf=z("LiftListItem",t=>()=>Xa(qt.type(t)));E(Pf,{displayName:"Command<liftListItemCommand>",group:"ListItem"});var Bf=z("SplitListItem",t=>()=>Bk(qt.type(t)));E(Bf,{displayName:"Command<splitListItemCommand>",group:"ListItem"});function qv(t){return(e,n,r)=>{let{selection:i}=e;if(!(i instanceof B))return!1;let{empty:o,$from:s}=i;return!o||s.parentOffset!==0||s.node(-1).type!==qt.type(t)?!1:Yc(e,n,r)}}var Ff=z("LiftFirstListItem",t=>()=>qv(t));E(Ff,{displayName:"Command<liftFirstListItemCommand>",group:"ListItem"});var zf=We("listItemKeymap",{NextListItem:{shortcuts:"Enter",command:t=>{let e=t.get(Q);return()=>e.call(Bf.key)}},SinkListItem:{shortcuts:["Tab","Mod-]"],command:t=>{let e=t.get(Q);return()=>e.call(Lf.key)}},LiftListItem:{shortcuts:["Shift-Tab","Mod-["],command:t=>{let e=t.get(Q);return()=>e.call(Pf.key)}},LiftFirstListItem:{shortcuts:["Backspace","Delete"],command:t=>{let e=t.get(Q);return()=>e.call(Ff.key)}}});E(zf.ctx,{displayName:"KeymapCtx<listItem>",group:"ListItem"});E(zf.shortcuts,{displayName:"Keymap<listItem>",group:"ListItem"});var nb=Ga("text",()=>({group:"inline",parseMarkdown:{match:({type:t})=>t==="text",runner:(t,e)=>{t.addText(e.value)}},toMarkdown:{match:t=>t.type.name==="text",runner:(t,e)=>{t.addNode("text",void 0,e.text)}}}));E(nb,{displayName:"NodeSchema<text>",group:"Text"});var _f=vt("html");E(_f,{displayName:"Attr<html>",group:"Html"});var $f=ce("html",t=>({atom:!0,group:"inline",inline:!0,attrs:{value:{default:"",validate:"string"}},toDOM:e=>{let n=document.createElement("span"),r={...t.get(_f.key)(e),"data-value":e.attrs.value,"data-type":"html"};return n.textContent=e.attrs.value,["span",r,e.attrs.value]},parseDOM:[{tag:'span[data-type="html"]',getAttrs:e=>({value:e.dataset.value??""})}],parseMarkdown:{match:({type:e})=>e==="html",runner:(e,n,r)=>{e.addNode(r,{value:n.value})}},toMarkdown:{match:e=>e.type.name==="html",runner:(e,n)=>{e.addNode("html",void 0,n.attrs.value)}}}));E($f.node,{displayName:"NodeSchema<html>",group:"Html"});E($f.ctx,{displayName:"NodeSchemaCtx<html>",group:"Html"});var Kv=[Kk,ff,Bt,el,hf,Pr,Qa,Lr,yf,Qo,xf,Zo,Tf,es,Sf,Pi,vf,Bi,Nf,Fi,Df,qt,ef,Li,rf,Yo,af,jn,uf,Di,_f,$f,nb].flat(),Uv=[Jk,eb,tb,Gk,Qk,Uk].flat(),Jv=[$k,Hk,jk,Wk],Gv=z("IsMarkSelected",()=>t=>e=>{if(!t)return!1;let{doc:n,selection:r}=e;return n.rangeHasMark(r.from,r.to,t)}),Xv=z("IsNoteSelected",()=>t=>e=>t?Yg(e,t).hasNode:!1),Yv=z("ClearTextInCurrentBlock",()=>()=>(t,e)=>{let n=t.tr,{$from:r,$to:i}=n.selection,{pos:o}=r,{pos:s}=i,a=o-r.node().content.size;return a<0?!1:(n=n.deleteRange(a,s),e?.(n),!0)}),Qv=z("SetBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr,{from:s,to:a}=o.selection;try{o.setBlockType(s,a,r,i)}catch{return!1}return n?.(o),!0}),Zv=z("WrapInBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let{$from:s,$to:a}=o.selection,l=s.blockRange(a),c=l&&yr(l,r,i);if(!c)return!1;o=o.wrap(l,c)}catch{return!1}return n?.(o),!0}),eA=z("AddBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let s=r instanceof rt?r:r.createAndFill(i);if(!s)return!1;o.replaceSelectionWith(s)}catch{return!1}return n?.(o),!0}),tA=z("SelectTextNearPos",()=>t=>(e,n)=>{let{pos:r}=t??{};if(r==null)return!1;let i=(s,a,l)=>Math.min(Math.max(s,a),l),o=e.tr;try{let s=e.doc.resolve(i(r,0,e.doc.content.size));o.setSelection(B.near(s))}catch{return!1}return n?.(o.scrollIntoView()),!0}),nA=[df,kf,Wn,mf,wf,Mf,Zk,Xk,Yk,Rf,Af,Lf,Bf,Pf,Ff,tf,lf,of,Vk,qk,Gv,Xv,Yv,Qv,Zv,eA,tA],rA=[bf,Cf,Ef,gf,zf,Of,If,pf,nf,cf,sf].flat(),Hf=gt("remarkAddOrderInList",()=>()=>t=>{Rt(t,"list",e=>{if(e.ordered){let n=e.start??1;e.children.forEach((r,i)=>{r.label=i+n})}})});E(Hf.plugin,{displayName:"Remark<remarkAddOrderInListPlugin>",group:"Remark"});E(Hf.options,{displayName:"RemarkConfig<remarkAddOrderInListPlugin>",group:"Remark"});var Wf=gt("remarkLineBreak",()=>()=>t=>{let e=/[\t ]*(?:\r?\n|\r)/g;Rt(t,"text",(n,r,i)=>{if(!n.value||typeof n.value!="string")return;let o=[],s=0;e.lastIndex=0;let a=e.exec(n.value);for(;a;){let l=a.index;s!==l&&o.push({type:"text",value:n.value.slice(s,l)}),o.push({type:"break",data:{isInline:!0}}),s=l+a[0].length,a=e.exec(n.value)}if(o.length>0&&i&&typeof r=="number")return s<n.value.length&&o.push({type:"text",value:n.value.slice(s)}),i.children.splice(r,1,...o),r+o.length})});E(Wf.plugin,{displayName:"Remark<remarkLineBreak>",group:"Remark"});E(Wf.options,{displayName:"RemarkConfig<remarkLineBreak>",group:"Remark"});var jf=gt("remarkInlineLink",()=>Ya);E(jf.plugin,{displayName:"Remark<remarkInlineLinkPlugin>",group:"Remark"});E(jf.options,{displayName:"RemarkConfig<remarkInlineLinkPlugin>",group:"Remark"});var iA=t=>!!t.children,oA=t=>t.type==="html";function sA(t,e){return n(t,0,null)[0];function n(r,i,o){if(iA(r)){let s=[];for(let a=0,l=r.children.length;a<l;a++){let c=r.children[a];if(c){let u=n(c,a,r);if(u)for(let f=0,d=u.length;f<d;f++){let p=u[f];p&&s.push(p)}}}r.children=s}return e(r,i,o)}}var aA=["root","blockquote","listItem"],Vf=gt("remarkHTMLTransformer",()=>()=>t=>{sA(t,(e,n,r)=>oA(e)?(r&&aA.includes(r.type)&&(e.children=[{...e}],delete e.value,e.type="paragraph"),[e]):[e])});E(Vf.plugin,{displayName:"Remark<remarkHtmlTransformer>",group:"Remark"});E(Vf.options,{displayName:"RemarkConfig<remarkHtmlTransformer>",group:"Remark"});var qf=gt("remarkMarker",()=>()=>(t,e)=>{let n=r=>e.value.charAt(r.position.start.offset);Rt(t,r=>["strong","emphasis"].includes(r.type),r=>{r.marker=n(r)})});E(qf.plugin,{displayName:"Remark<remarkMarker>",group:"Remark"});E(qf.options,{displayName:"RemarkConfig<remarkMarker>",group:"Remark"});var rb=pe(()=>{let t=!1,e=new X({key:new ee("MILKDOWN_INLINE_NODES_CURSOR"),state:{init(){return!1},apply(n){if(!n.selection.empty)return!1;let r=n.selection.$from,i=r.nodeBefore,o=r.nodeAfter;return!!(i&&o&&i.isInline&&!i.isText&&o.isInline&&!o.isText)}},props:{handleDOMEvents:{compositionend:(n,r)=>t?(t=!1,requestAnimationFrame(()=>{if(e.getState(n.state)){let i=n.state.selection.from;r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i))}}),!0):!1,compositionstart:n=>(e.getState(n.state)&&(t=!0),!1),beforeinput:(n,r)=>{if(e.getState(n.state)&&r instanceof InputEvent&&r.data&&!t){let i=n.state.selection.from;return r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i)),!0}return!1}},decorations(n){if(e.getState(n)){let r=n.selection.$from.pos,i=document.createElement("span"),o=le.widget(r,i,{side:-1}),s=document.createElement("span"),a=le.widget(r,s);return setTimeout(()=>{i.contentEditable="true",s.contentEditable="true"}),ae.create(n.doc,[o,a])}return ae.empty}}});return e});E(rb,{displayName:"Prose<inlineNodesCursorPlugin>",group:"Prose"});var ib=pe(t=>new X({key:new ee("MILKDOWN_HARDBREAK_MARKS"),appendTransaction:(e,n,r)=>{if(!e.length)return;let[i]=e;if(!i)return;let[o]=i.steps;if(i.getMeta("hardbreak")){if(!(o instanceof Ce))return;let{from:s}=o;return r.tr.setNodeMarkup(s,Lr.type(t),void 0,[])}if(o instanceof hr){let s=r.tr,{from:a,to:l}=o;return r.doc.nodesBetween(a,l,(c,u)=>{c.type===Lr.type(t)&&(s=s.setNodeMarkup(u,Lr.type(t),void 0,[]))}),s}}}));E(ib,{displayName:"Prose<hardbreakClearMarkPlugin>",group:"Prose"});var Kf=Ie(["table","code_block"],"hardbreakFilterNodes");E(Kf,{displayName:"Ctx<hardbreakFilterNodes>",group:"Prose"});var ob=pe(t=>{let e=t.get(Kf.key);return new X({key:new ee("MILKDOWN_HARDBREAK_FILTER"),filterTransaction:(n,r)=>{let i=n.getMeta("hardbreak"),[o]=n.steps;if(i&&o){let{from:s}=o,a=r.doc.resolve(s),l=a.depth,c=!0;for(;l>0;)e.includes(a.node(l).type.name)&&(c=!1),l--;return c}return!0}})});E(ob,{displayName:"Prose<hardbreakFilterPlugin>",group:"Prose"});var sb=pe(t=>{let e=new ee("MILKDOWN_HEADING_ID"),n=r=>{if(r.composing)return;let i=t.get(el.key),o=r.state.tr.setMeta("addToHistory",!1),s=!1,a={};r.state.doc.descendants((l,c)=>{if(l.type===Pr.type(t)){if(l.textContent.trim().length===0)return;let u=l.attrs,f=i(l);a[f]?(a[f]+=1,f+=`-#${a[f]}`):a[f]=1,u.id!==f&&(s=!0,o.setMeta(e,!0).setNodeMarkup(c,void 0,{...u,id:f}))}}),s&&r.dispatch(o)};return new X({key:e,view:r=>(n(r),{update:(i,o)=>{i.state.doc.eq(o.doc)||n(i)}})})});E(sb,{displayName:"Prose<syncHeadingIdPlugin>",group:"Prose"});var ab=pe(t=>{let e=(n,r,i)=>{if(!i.selection||n.some(f=>f.getMeta("addToHistory")===!1||!f.isGeneric))return null;let o=Fi.type(t),s=Bi.type(t),a=qt.type(t),l=(f,d,p=1)=>{let h=!1,m=`${d+p}.`;return f.label!==m&&(f.label=m,h=!0),h},c=i.tr,u=!1;return i.doc.descendants((f,d,p,h)=>{if(f.type===s){let m=f.maybeChild(0);m?.type===a&&m.attrs.listType==="ordered"&&(u=!0,c.setNodeMarkup(d,o,{spread:"true"}),f.descendants((g,y,b,C)=>{if(g.type===a){let v={...g.attrs};l(v,C)&&(c=c.setNodeMarkup(y,void 0,v))}return!1}))}else if(f.type===a&&p?.type===o){let m={...f.attrs},g=!1;m.listType!=="ordered"&&(m.listType="ordered",g=!0),p?.maybeChild(0)&&(g=l(m,h,p?.attrs.order??1)),g&&(c=c.setNodeMarkup(d,void 0,m),u=!0)}}),u?c.setMeta("addToHistory",!1):null};return new X({key:new ee("MILKDOWN_KEEP_LIST_ORDER"),appendTransaction:e})});E(ab,{displayName:"Prose<syncListOrderPlugin>",group:"Prose"});var lA=[ib,Kf,ob,rb,Hf,jf,Wf,Vf,qf,Za,sb,ab].flat(),lb=[Kv,Uv,Jv,nA,rA,lA].flat();var Jf,Gf;if(typeof WeakMap<"u"){let t=new WeakMap;Jf=e=>t.get(e),Gf=(e,n)=>(t.set(e,n),n)}else{let t=[],n=0;Jf=r=>{for(let i=0;i<t.length;i+=2)if(t[i]==r)return t[i+1]},Gf=(r,i)=>(n==10&&(n=0),t[n++]=r,t[n++]=i)}var oe=class{constructor(t,e,n,r){this.width=t,this.height=e,this.map=n,this.problems=r}findCell(t){for(let e=0;e<this.map.length;e++){let n=this.map[e];if(n!=t)continue;let r=e%this.width,i=e/this.width|0,o=r+1,s=i+1;for(let a=1;o<this.width&&this.map[e+a]==n;a++)o++;for(let a=1;s<this.height&&this.map[e+this.width*a]==n;a++)s++;return{left:r,top:i,right:o,bottom:s}}throw new RangeError(`No cell with offset ${t} found`)}colCount(t){for(let e=0;e<this.map.length;e++)if(this.map[e]==t)return e%this.width;throw new RangeError(`No cell with offset ${t} found`)}nextCell(t,e,n){let{left:r,right:i,top:o,bottom:s}=this.findCell(t);return e=="horiz"?(n<0?r==0:i==this.width)?null:this.map[o*this.width+(n<0?r-1:i)]:(n<0?o==0:s==this.height)?null:this.map[r+this.width*(n<0?o-1:s)]}rectBetween(t,e){let{left:n,right:r,top:i,bottom:o}=this.findCell(t),{left:s,right:a,top:l,bottom:c}=this.findCell(e);return{left:Math.min(n,s),top:Math.min(i,l),right:Math.max(r,a),bottom:Math.max(o,c)}}cellsInRect(t){let e=[],n={};for(let r=t.top;r<t.bottom;r++)for(let i=t.left;i<t.right;i++){let o=r*this.width+i,s=this.map[o];n[s]||(n[s]=!0,!(i==t.left&&i&&this.map[o-1]==s||r==t.top&&r&&this.map[o-this.width]==s)&&e.push(s))}return e}positionAt(t,e,n){for(let r=0,i=0;;r++){let o=i+n.child(r).nodeSize;if(r==t){let s=e+t*this.width,a=(t+1)*this.width;for(;s<a&&this.map[s]<i;)s++;return s==a?o-1:this.map[s]}i=o}}static get(t){return Jf(t)||Gf(t,cA(t))}};function cA(t){if(t.type.spec.tableRole!="table")throw new RangeError("Not a table node: "+t.type.name);let e=uA(t),n=t.childCount,r=[],i=0,o=null,s=[];for(let c=0,u=e*n;c<u;c++)r[c]=0;for(let c=0,u=0;c<n;c++){let f=t.child(c);u++;for(let h=0;;h++){for(;i<r.length&&r[i]!=0;)i++;if(h==f.childCount)break;let m=f.child(h),{colspan:g,rowspan:y,colwidth:b}=m.attrs;for(let C=0;C<y;C++){if(C+c>=n){(o||(o=[])).push({type:"overlong_rowspan",pos:u,n:y-C});break}let v=i+C*e;for(let A=0;A<g;A++){r[v+A]==0?r[v+A]=u:(o||(o=[])).push({type:"collision",row:c,pos:u,n:g-A});let w=b&&b[A];if(w){let N=(v+A)%e*2,P=s[N];P==null||P!=w&&s[N+1]==1?(s[N]=w,s[N+1]=1):P==w&&s[N+1]++}}}i+=g,u+=m.nodeSize}let d=(c+1)*e,p=0;for(;i<d;)r[i++]==0&&p++;p&&(o||(o=[])).push({type:"missing",row:c,n:p}),u++}(e===0||n===0)&&(o||(o=[])).push({type:"zero_sized"});let a=new oe(e,n,r,o),l=!1;for(let c=0;!l&&c<s.length;c+=2)s[c]!=null&&s[c+1]<n&&(l=!0);return l&&fA(a,s,t),a}function uA(t){let e=-1,n=!1;for(let r=0;r<t.childCount;r++){let i=t.child(r),o=0;if(n)for(let s=0;s<r;s++){let a=t.child(s);for(let l=0;l<a.childCount;l++){let c=a.child(l);s+c.attrs.rowspan>r&&(o+=c.attrs.colspan)}}for(let s=0;s<i.childCount;s++){let a=i.child(s);o+=a.attrs.colspan,a.attrs.rowspan>1&&(n=!0)}e==-1?e=o:e!=o&&(e=Math.max(e,o))}return e}function fA(t,e,n){t.problems||(t.problems=[]);let r={};for(let i=0;i<t.map.length;i++){let o=t.map[i];if(r[o])continue;r[o]=!0;let s=n.nodeAt(o);if(!s)throw new RangeError(`No cell with offset ${o} found`);let a=null,l=s.attrs;for(let c=0;c<l.colspan;c++){let u=e[(i+c)%t.width*2];u!=null&&(!l.colwidth||l.colwidth[c]!=u)&&((a||(a=dA(l)))[c]=u)}a&&t.problems.unshift({type:"colwidth mismatch",pos:o,colwidth:a})}}function dA(t){if(t.colwidth)return t.colwidth.slice();let e=[];for(let n=0;n<t.colspan;n++)e.push(0);return e}function cb(t,e){if(typeof t=="string")return{};let n=t.getAttribute("data-colwidth"),r=n&&/^\d+(,\d+)*$/.test(n)?n.split(",").map(s=>Number(s)):null,i=Number(t.getAttribute("colspan")||1),o={colspan:i,rowspan:Number(t.getAttribute("rowspan")||1),colwidth:r&&r.length==i?r:null};for(let s in e){let a=e[s].getFromDOM,l=a&&a(t);l!=null&&(o[s]=l)}return o}function ub(t,e){let n={};t.attrs.colspan!=1&&(n.colspan=t.attrs.colspan),t.attrs.rowspan!=1&&(n.rowspan=t.attrs.rowspan),t.attrs.colwidth&&(n["data-colwidth"]=t.attrs.colwidth.join(","));for(let r in e){let i=e[r].setDOMAttr;i&&i(t.attrs[r],n)}return n}function pA(t){if(t!==null){if(!Array.isArray(t))throw new TypeError("colwidth must be null or an array");for(let e of t)if(typeof e!="number")throw new TypeError("colwidth must be null or an array of numbers")}}function Cb(t){let e=t.cellAttributes||{},n={colspan:{default:1,validate:"number"},rowspan:{default:1,validate:"number"},colwidth:{default:null,validate:pA}};for(let r in e)n[r]={default:e[r].default,validate:e[r].validate};return{table:{content:"table_row+",tableRole:"table",isolating:!0,group:t.tableGroup,parseDOM:[{tag:"table"}],toDOM(){return["table",["tbody",0]]}},table_row:{content:"(table_cell | table_header)*",tableRole:"row",parseDOM:[{tag:"tr"}],toDOM(){return["tr",0]}},table_cell:{content:t.cellContent,attrs:n,tableRole:"cell",isolating:!0,parseDOM:[{tag:"td",getAttrs:r=>cb(r,e)}],toDOM(r){return["td",ub(r,e),0]}},table_header:{content:t.cellContent,attrs:n,tableRole:"header_cell",isolating:!0,parseDOM:[{tag:"th",getAttrs:r=>cb(r,e)}],toDOM(r){return["th",ub(r,e),0]}}}}function et(t){let e=t.cached.tableNodeTypes;if(!e){e=t.cached.tableNodeTypes={};for(let n in t.nodes){let r=t.nodes[n],i=r.spec.tableRole;i&&(e[i]=r)}}return e}var Vn=new ee("selectingCells");function $i(t){for(let e=t.depth-1;e>0;e--)if(t.node(e).type.spec.tableRole=="row")return t.node(0).resolve(t.before(e+1));return null}function De(t){let e=t.selection.$head;for(let n=e.depth;n>0;n--)if(e.node(n).type.spec.tableRole=="row")return!0;return!1}function sl(t){let e=t.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;let n=$i(e.$head)||hA(e.$head);if(n)return n;throw new RangeError(`No cell found around position ${e.head}`)}function hA(t){for(let e=t.nodeAfter,n=t.pos;e;e=e.firstChild,n++){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n)}for(let e=t.nodeBefore,n=t.pos;e;e=e.lastChild,n--){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n-e.nodeSize)}}function Xf(t){return t.parent.type.spec.tableRole=="row"&&!!t.nodeAfter}function mA(t){return t.node(0).resolve(t.pos+t.nodeAfter.nodeSize)}function Zf(t,e){return t.depth==e.depth&&t.pos>=e.start(-1)&&t.pos<=e.end(-1)}function Sb(t,e,n){let r=t.node(-1),i=oe.get(r),o=t.start(-1),s=i.nextCell(t.pos-o,e,n);return s==null?null:t.node(0).resolve(o+s)}function Br(t,e,n=1){let r={...t,colspan:t.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,n),r.colwidth.some(i=>i>0)||(r.colwidth=null)),r}function gA(t,e,n=1){let r={...t,colspan:t.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let i=0;i<n;i++)r.colwidth.splice(e,0,0)}return r}function yA(t,e,n){let r=et(e.type.schema).header_cell;for(let i=0;i<t.height;i++)if(e.nodeAt(t.map[n+i*t.width]).type!=r)return!1;return!0}var he=class kn extends ${constructor(e,n=e){let r=e.node(-1),i=oe.get(r),o=e.start(-1),s=i.rectBetween(e.pos-o,n.pos-o),a=e.node(0),l=i.cellsInRect(s).filter(u=>u!=n.pos-o);l.unshift(n.pos-o);let c=l.map(u=>{let f=r.nodeAt(u);if(!f)throw new RangeError(`No cell with offset ${u} found`);let d=o+u+1;return new On(a.resolve(d),a.resolve(d+f.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=n}map(e,n){let r=e.resolve(n.map(this.$anchorCell.pos)),i=e.resolve(n.map(this.$headCell.pos));if(Xf(r)&&Xf(i)&&Zf(r,i)){let o=this.$anchorCell.node(-1)!=r.node(-1);return o&&this.isRowSelection()?kn.rowSelection(r,i):o&&this.isColSelection()?kn.colSelection(r,i):new kn(r,i)}return B.between(r,i)}content(){let e=this.$anchorCell.node(-1),n=oe.get(e),r=this.$anchorCell.start(-1),i=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),o={},s=[];for(let l=i.top;l<i.bottom;l++){let c=[];for(let u=l*n.width+i.left,f=i.left;f<i.right;f++,u++){let d=n.map[u];if(o[d])continue;o[d]=!0;let p=n.findCell(d),h=e.nodeAt(d);if(!h)throw new RangeError(`No cell with offset ${d} found`);let m=i.left-p.left,g=p.right-i.right;if(m>0||g>0){let y=h.attrs;if(m>0&&(y=Br(y,0,m)),g>0&&(y=Br(y,y.colspan-g,g)),p.left<i.left){if(h=h.type.createAndFill(y),!h)throw new RangeError(`Could not create cell with attrs ${JSON.stringify(y)}`)}else h=h.type.create(y,h.content)}if(p.top<i.top||p.bottom>i.bottom){let y={...h.attrs,rowspan:Math.min(p.bottom,i.bottom)-Math.max(p.top,i.top)};p.top<i.top?h=h.type.createAndFill(y):h=h.type.create(y,h.content)}c.push(h)}s.push(e.child(l).copy(M.from(c)))}let a=this.isColSelection()&&this.isRowSelection()?e:s;return new R(M.from(a),1,1)}replace(e,n=R.empty){let r=e.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:a,$to:l}=i[s],c=e.mapping.slice(r);e.replace(c.map(a.pos),c.map(l.pos),s?R.empty:n)}let o=$.findFrom(e.doc.resolve(e.mapping.slice(r).map(this.to)),-1);o&&e.setSelection(o)}replaceWith(e,n){this.replace(e,new R(M.from(n),0,0))}forEachCell(e){let n=this.$anchorCell.node(-1),r=oe.get(n),i=this.$anchorCell.start(-1),o=r.cellsInRect(r.rectBetween(this.$anchorCell.pos-i,this.$headCell.pos-i));for(let s=0;s<o.length;s++)e(n.nodeAt(o[s]),i+o[s])}isColSelection(){let e=this.$anchorCell.index(-1),n=this.$headCell.index(-1);if(Math.min(e,n)>0)return!1;let r=e+this.$anchorCell.nodeAfter.attrs.rowspan,i=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,i)==this.$headCell.node(-1).childCount}static colSelection(e,n=e){let r=e.node(-1),i=oe.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.top<=a.top?(s.top>0&&(e=l.resolve(o+i.map[s.left])),a.bottom<i.height&&(n=l.resolve(o+i.map[i.width*(i.height-1)+a.right-1]))):(a.top>0&&(n=l.resolve(o+i.map[a.left])),s.bottom<i.height&&(e=l.resolve(o+i.map[i.width*(i.height-1)+s.right-1]))),new kn(e,n)}isRowSelection(){let e=this.$anchorCell.node(-1),n=oe.get(e),r=this.$anchorCell.start(-1),i=n.colCount(this.$anchorCell.pos-r),o=n.colCount(this.$headCell.pos-r);if(Math.min(i,o)>0)return!1;let s=i+this.$anchorCell.nodeAfter.attrs.colspan,a=o+this.$headCell.nodeAfter.attrs.colspan;return Math.max(s,a)==n.width}eq(e){return e instanceof kn&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,n=e){let r=e.node(-1),i=oe.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.left<=a.left?(s.left>0&&(e=l.resolve(o+i.map[s.top*i.width])),a.right<i.width&&(n=l.resolve(o+i.map[i.width*(a.top+1)-1]))):(a.left>0&&(n=l.resolve(o+i.map[a.top*i.width])),s.right<i.width&&(e=l.resolve(o+i.map[i.width*(s.top+1)-1]))),new kn(e,n)}toJSON(){return{type:"cell",anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(e,n){return new kn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){return new kn(e.resolve(n),e.resolve(r))}getBookmark(){return new kA(this.$anchorCell.pos,this.$headCell.pos)}};he.prototype.visible=!1;$.jsonID("cell",he);var kA=class Mb{constructor(e,n){this.anchor=e,this.head=n}map(e){return new Mb(e.map(this.anchor),e.map(this.head))}resolve(e){let n=e.resolve(this.anchor),r=e.resolve(this.head);return n.parent.type.spec.tableRole=="row"&&r.parent.type.spec.tableRole=="row"&&n.index()<n.parent.childCount&&r.index()<r.parent.childCount&&Zf(n,r)?new he(n,r):$.near(r,1)}};function bA(t){if(!(t.selection instanceof he))return null;let e=[];return t.selection.forEachCell((n,r)=>{e.push(le.node(r,r+n.nodeSize,{class:"selectedCell"}))}),ae.create(t.doc,e)}function xA({$from:t,$to:e}){if(t.pos==e.pos||t.pos<e.pos-6)return!1;let n=t.pos,r=e.pos,i=t.depth;for(;i>=0&&!(t.after(i+1)<t.end(i));i--,n++);for(let o=e.depth;o>=0&&!(e.before(o+1)>e.start(o));o--,r--);return n==r&&/row|table/.test(t.node(i).type.spec.tableRole)}function wA({$from:t,$to:e}){let n,r;for(let i=t.depth;i>0;i--){let o=t.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){n=o;break}}for(let i=e.depth;i>0;i--){let o=e.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){r=o;break}}return n!==r&&e.parentOffset===0}function CA(t,e,n){let r=(e||t).selection,i=(e||t).doc,o,s;if(r instanceof H&&(s=r.node.type.spec.tableRole)){if(s=="cell"||s=="header_cell")o=he.create(i,r.from);else if(s=="row"){let a=i.resolve(r.from+1);o=he.rowSelection(a,a)}else if(!n){let a=oe.get(r.node),l=r.from+1,c=l+a.map[a.width*a.height-1];o=he.create(i,l+1,c)}}else r instanceof B&&xA(r)?o=B.create(i,r.from):r instanceof B&&wA(r)&&(o=B.create(i,r.$from.start(),r.$from.end()));return o&&(e||(e=t.tr)).setSelection(o),e}var SA=new ee("fix-tables");function Eb(t,e,n,r){let i=t.childCount,o=e.childCount;e:for(let s=0,a=0;s<o;s++){let l=e.child(s);for(let c=a,u=Math.min(i,s+3);c<u;c++)if(t.child(c)==l){a=c+1,n+=l.nodeSize;continue e}r(l,n),a<i&&t.child(a).sameMarkup(l)?Eb(t.child(a),l,n+1,r):l.nodesBetween(0,l.content.size,r,n+1),n+=l.nodeSize}}function MA(t,e){let n,r=(i,o)=>{i.type.spec.tableRole=="table"&&(n=EA(t,i,o,n))};return e?e.doc!=t.doc&&Eb(e.doc,t.doc,0,r):t.doc.descendants(r),n}function EA(t,e,n,r){let i=oe.get(e);if(!i.problems)return r;r||(r=t.tr);let o=[];for(let l=0;l<i.height;l++)o.push(0);for(let l=0;l<i.problems.length;l++){let c=i.problems[l];if(c.type=="collision"){let u=e.nodeAt(c.pos);if(!u)continue;let f=u.attrs;for(let d=0;d<f.rowspan;d++)o[c.row+d]+=c.n;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,Br(f,f.colspan-c.n,c.n))}else if(c.type=="missing")o[c.row]+=c.n;else if(c.type=="overlong_rowspan"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,rowspan:u.attrs.rowspan-c.n})}else if(c.type=="colwidth mismatch"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,colwidth:c.colwidth})}else if(c.type=="zero_sized"){let u=r.mapping.map(n);r.delete(u,u+e.nodeSize)}}let s,a;for(let l=0;l<o.length;l++)o[l]&&(s==null&&(s=l),a=l);for(let l=0,c=n+1;l<i.height;l++){let u=e.child(l),f=c+u.nodeSize,d=o[l];if(d>0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);let h=[];for(let g=0;g<d;g++){let y=et(t.schema)[p].createAndFill();y&&h.push(y)}let m=(l==0||s==l-1)&&a==l?c+1:f-1;r.insert(r.mapping.map(m),h)}c=f}return r.setMeta(SA,{fixTables:!0})}function Tb(t){let e=oe.get(t),n=[],r=e.height,i=e.width;for(let o=0;o<r;o++){let s=[];for(let a=0;a<i;a++){let l=o*i+a,c=e.map[l];if(o>0){let u=l-i;if(c===e.map[u]){s.push(null);continue}}if(a>0){let u=l-1;if(c===e.map[u]){s.push(null);continue}}s.push(t.nodeAt(c))}n.push(s)}return n}function vb(t,e){let n=[],r=oe.get(t),i=r.height,o=r.width;for(let s=0;s<i;s++){let a=t.child(s),l=[];for(let u=0;u<o;u++){let f=e[s][u];if(!f)continue;let d=r.map[s*r.width+u],p=t.nodeAt(d);if(!p)continue;let h=p.type.createChecked(f.attrs,f.content,f.marks);l.push(h)}let c=a.type.createChecked(a.attrs,l,a.marks);n.push(c)}return t.type.createChecked(t.attrs,n,t.marks)}function Ab(t,e,n,r){let i=e[0]>n[0]?-1:1,o=t.splice(e[0],e.length),s=o.length%2===0?1:0,a;return r===-1&&i===1?a=n[0]-1:r===1&&i===-1?a=n[n.length-1]-s+1:a=i===-1?n[0]:n[n.length-1]-s,t.splice(a,0,...o),t}function Hi(t){return TA(e=>e.type.spec.tableRole==="table",t)}function TA(t,e){for(let n=e.depth;n>=0;n-=1){let r=e.node(n);if(t(r))return{node:r,pos:n===0?0:e.before(n),start:e.start(n),depth:n}}return null}function zi(t,e){let n=Hi(e.$from);if(!n)return;let r=oe.get(n.node);if(!(t<0||t>r.width-1))return r.cellsInRect({left:t,right:t+1,top:0,bottom:r.height}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function _i(t,e){let n=Hi(e.$from);if(!n)return;let r=oe.get(n.node);if(!(t<0||t>r.height-1))return r.cellsInRect({left:0,right:r.width,top:t,bottom:t+1}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function fb(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=zi(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=zi(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;d.node.attrs.colspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=zi(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=zi(r,t.selection),a=_i(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=zi(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function db(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=_i(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=_i(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;d.node.attrs.rowspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=_i(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=_i(r,t.selection),a=zi(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=_i(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function pb(t){return t[0].map((e,n)=>t.map(r=>r[n]))}function vA(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=Hi(r.doc.resolve(a));if(!l)return!1;let c=(e=fb(r,i))===null||e===void 0?void 0:e.indexes,u=(n=fb(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=AA(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=oe.get(f),p=l.start,h=o,m=d.positionAt(d.height-1,h,f),g=r.doc.resolve(p+m),y=d.positionAt(0,h,f),b=r.doc.resolve(p+y);return r.setSelection(he.colSelection(g,b)),!0}function AA(t,e,n,r){let i=pb(Tb(t));return i=Ab(i,e,n,r),i=pb(i),vb(t,i)}function IA(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=Hi(r.doc.resolve(a));if(!l)return!1;let c=(e=db(r,i))===null||e===void 0?void 0:e.indexes,u=(n=db(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=NA(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=oe.get(f),p=l.start,h=o,m=d.positionAt(h,d.width-1,f),g=r.doc.resolve(p+m),y=d.positionAt(h,0,f),b=r.doc.resolve(p+y);return r.setSelection(he.rowSelection(g,b)),!0}function NA(t,e,n,r){let i=Tb(t);return i=Ab(i,e,n,r),vb(t,i)}function At(t){let e=t.selection,n=sl(t),r=n.node(-1),i=n.start(-1),o=oe.get(r);return{...e instanceof he?o.rectBetween(e.$anchorCell.pos-i,e.$headCell.pos-i):o.findCell(n.pos-i),tableStart:i,map:o,table:r}}function Ib(t,{map:e,tableStart:n,table:r},i){let o=i>0?-1:0;yA(e,r,i+o)&&(o=i==0||i==e.width?null:0);for(let s=0;s<e.height;s++){let a=s*e.width+i;if(i>0&&i<e.width&&e.map[a-1]==e.map[a]){let l=e.map[a],c=r.nodeAt(l);t.setNodeMarkup(t.mapping.map(n+l),null,gA(c.attrs,i-e.colCount(l))),s+=c.attrs.rowspan-1}else{let l=o==null?et(r.type.schema).cell:r.nodeAt(e.map[a+o]).type,c=e.positionAt(s,i,r);t.insert(t.mapping.map(n+c),l.createAndFill())}}return t}function Nb(t,e){if(!De(t))return!1;if(e){let n=At(t);e(Ib(t.tr,n,n.left))}return!0}function al(t,e){if(!De(t))return!1;if(e){let n=At(t);e(Ib(t.tr,n,n.right))}return!0}function RA(t,{map:e,table:n,tableStart:r},i){let o=t.mapping.maps.length;for(let s=0;s<e.height;){let a=s*e.width+i,l=e.map[a],c=n.nodeAt(l),u=c.attrs;if(i>0&&e.map[a-1]==l||i<e.width-1&&e.map[a+1]==l)t.setNodeMarkup(t.mapping.slice(o).map(r+l),null,Br(u,i-e.colCount(l)));else{let f=t.mapping.slice(o).map(r+l);t.delete(f,f+c.nodeSize)}s+=u.rowspan}}function ll(t,e){if(!De(t))return!1;if(e){let n=At(t),r=t.tr;if(n.left==0&&n.right==n.map.width)return!1;for(let i=n.right-1;RA(r,n,i),i!=n.left;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=oe.get(o)}e(r)}return!0}function OA(t,e,n){var r;let i=et(e.type.schema).header_cell;for(let o=0;o<t.width;o++)if(((r=e.nodeAt(t.map[o+n*t.width]))===null||r===void 0?void 0:r.type)!=i)return!1;return!0}function DA(t,{map:e,tableStart:n,table:r},i){let o=n;for(let c=0;c<i;c++)o+=r.child(c).nodeSize;let s=[],a=i>0?-1:0;OA(e,r,i+a)&&(a=i==0||i==e.height?null:0);for(let c=0,u=e.width*i;c<e.width;c++,u++)if(i>0&&i<e.height&&e.map[u]==e.map[u-e.width]){let f=e.map[u],d=r.nodeAt(f).attrs;t.setNodeMarkup(n+f,null,{...d,rowspan:d.rowspan+1}),c+=d.colspan-1}else{var l;let f=a==null?et(r.type.schema).cell:(l=r.nodeAt(e.map[u+a*e.width]))===null||l===void 0?void 0:l.type,d=f?.createAndFill();d&&s.push(d)}return t.insert(o,et(r.type.schema).row.create(null,s)),t}function ed(t,e){if(!De(t))return!1;if(e){let n=At(t);e(DA(t.tr,n,n.bottom))}return!0}function LA(t,{map:e,table:n,tableStart:r},i){let o=0;for(let c=0;c<i;c++)o+=n.child(c).nodeSize;let s=o+n.child(i).nodeSize,a=t.mapping.maps.length;t.delete(o+r,s+r);let l=new Set;for(let c=0,u=i*e.width;c<e.width;c++,u++){let f=e.map[u];if(!l.has(f)){if(l.add(f),i>0&&f==e.map[u-e.width]){let d=n.nodeAt(f).attrs;t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d,rowspan:d.rowspan-1}),c+=d.colspan-1}else if(i<e.height&&f==e.map[u+e.width]){let d=n.nodeAt(f),p=d.attrs,h=d.type.create({...p,rowspan:d.attrs.rowspan-1},d.content),m=e.positionAt(i+1,c,n);t.insert(t.mapping.slice(a).map(r+m),h),c+=p.colspan-1}}}}function cl(t,e){if(!De(t))return!1;if(e){let n=At(t),r=t.tr;if(n.top==0&&n.bottom==n.map.height)return!1;for(let i=n.bottom-1;LA(r,n,i),i!=n.top;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=oe.get(n.table)}e(r)}return!0}function Rb(t,e){return function(n,r){if(!De(n))return!1;let i=sl(n);if(i.nodeAfter.attrs[t]===e)return!1;if(r){let o=n.tr;n.selection instanceof he?n.selection.forEachCell((s,a)=>{s.attrs[t]!==e&&o.setNodeMarkup(a,null,{...s.attrs,[t]:e})}):o.setNodeMarkup(i.pos,null,{...i.nodeAfter.attrs,[t]:e}),r(o)}return!0}}function PA(t){return function(e,n){if(!De(e))return!1;if(n){let r=et(e.schema),i=At(e),o=e.tr,s=i.map.cellsInRect(t=="column"?{left:i.left,top:0,right:i.right,bottom:i.map.height}:t=="row"?{left:0,top:i.top,right:i.map.width,bottom:i.bottom}:i),a=s.map(l=>i.table.nodeAt(l));for(let l=0;l<s.length;l++)a[l].type==r.header_cell&&o.setNodeMarkup(i.tableStart+s[l],r.cell,a[l].attrs);if(o.steps.length===0)for(let l=0;l<s.length;l++)o.setNodeMarkup(i.tableStart+s[l],r.header_cell,a[l].attrs);n(o)}return!0}}function hb(t,e,n){let r=e.map.cellsInRect({left:0,top:0,right:t=="row"?e.map.width:1,bottom:t=="column"?e.map.height:1});for(let i=0;i<r.length;i++){let o=e.table.nodeAt(r[i]);if(o&&o.type!==n.header_cell)return!1}return!0}function td(t,e){return e=e||{useDeprecatedLogic:!1},e.useDeprecatedLogic?PA(t):function(n,r){if(!De(n))return!1;if(r){let i=et(n.schema),o=At(n),s=n.tr,a=hb("row",o,i),l=hb("column",o,i),c=(t==="column"?a:t==="row"&&l)?1:0,u=t=="column"?{left:0,top:c,right:1,bottom:o.map.height}:t=="row"?{left:c,top:0,right:o.map.width,bottom:1}:o,f=t=="column"?l?i.cell:i.header_cell:t=="row"?a?i.cell:i.header_cell:i.cell;o.map.cellsInRect(u).forEach(d=>{let p=d+o.tableStart,h=s.doc.nodeAt(p);h&&s.setNodeMarkup(p,f,h.attrs)}),r(s)}return!0}}var MW=td("row",{useDeprecatedLogic:!0}),EW=td("column",{useDeprecatedLogic:!0}),TW=td("cell",{useDeprecatedLogic:!0});function BA(t,e){if(e<0){let n=t.nodeBefore;if(n)return t.pos-n.nodeSize;for(let r=t.index(-1)-1,i=t.before();r>=0;r--){let o=t.node(-1).child(r),s=o.lastChild;if(s)return i-1-s.nodeSize;i-=o.nodeSize}}else{if(t.index()<t.parent.childCount-1)return t.pos+t.nodeAfter.nodeSize;let n=t.node(-1);for(let r=t.indexAfter(-1),i=t.after();r<n.childCount;r++){let o=n.child(r);if(o.childCount)return i+1;i+=o.nodeSize}}return null}function ts(t){return function(e,n){if(!De(e))return!1;let r=BA(sl(e),t);if(r==null)return!1;if(n){let i=e.doc.resolve(r);n(e.tr.setSelection(B.between(i,mA(i))).scrollIntoView())}return!0}}function Ob(t,e){let n=t.selection.$anchor;for(let r=n.depth;r>0;r--)if(n.node(r).type.spec.tableRole=="table")return e&&e(t.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function tl(t,e){let n=t.selection;if(!(n instanceof he))return!1;if(e){let r=t.tr,i=et(t.schema).cell.createAndFill().content;n.forEachCell((o,s)=>{o.content.eq(i)||r.replace(r.mapping.map(s+1),r.mapping.map(s+o.nodeSize-1),new R(i,0,0))}),r.docChanged&&e(r)}return!0}function Db(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return IA({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function Lb(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return vA({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function FA(t){if(t.size===0)return null;let{content:e,openStart:n,openEnd:r}=t;for(;e.childCount==1&&(n>0&&r>0||e.child(0).type.spec.tableRole=="table");)n--,r--,e=e.child(0).content;let i=e.child(0),o=i.type.spec.tableRole,s=i.type.schema,a=[];if(o=="row")for(let l=0;l<e.childCount;l++){let c=e.child(l).content,u=l?0:Math.max(0,n-1),f=l<e.childCount-1?0:Math.max(0,r-1);(u||f)&&(c=Yf(et(s).row,new R(c,u,f)).content),a.push(c)}else if(o=="cell"||o=="header_cell")a.push(n||r?Yf(et(s).row,new R(e,n,r)).content:e);else return null;return zA(s,a)}function zA(t,e){let n=[];for(let i=0;i<e.length;i++){let o=e[i];for(let s=o.childCount-1;s>=0;s--){let{rowspan:a,colspan:l}=o.child(s).attrs;for(let c=i;c<i+a;c++)n[c]=(n[c]||0)+l}}let r=0;for(let i=0;i<n.length;i++)r=Math.max(r,n[i]);for(let i=0;i<n.length;i++)if(i>=e.length&&e.push(M.empty),n[i]<r){let o=et(t).cell.createAndFill(),s=[];for(let a=n[i];a<r;a++)s.push(o);e[i]=e[i].append(M.from(s))}return{height:e.length,width:r,rows:e}}function Yf(t,e){let n=t.createAndFill();return new pi(n).replace(0,n.content.size,e).doc}function _A({width:t,height:e,rows:n},r,i){if(t!=r){let o=[],s=[];for(let a=0;a<n.length;a++){let l=n[a],c=[];for(let u=o[a]||0,f=0;u<r;f++){let d=l.child(f%l.childCount);u+d.attrs.colspan>r&&(d=d.type.createChecked(Br(d.attrs,d.attrs.colspan,u+d.attrs.colspan-r),d.content)),c.push(d),u+=d.attrs.colspan;for(let p=1;p<d.attrs.rowspan;p++)o[a+p]=(o[a+p]||0)+d.attrs.colspan}s.push(M.from(c))}n=s,t=r}if(e!=i){let o=[];for(let s=0,a=0;s<i;s++,a++){let l=[],c=n[a%e];for(let u=0;u<c.childCount;u++){let f=c.child(u);s+f.attrs.rowspan>i&&(f=f.type.create({...f.attrs,rowspan:Math.max(1,i-f.attrs.rowspan)},f.content)),l.push(f)}o.push(M.from(l))}n=o,e=i}return{width:t,height:e,rows:n}}function $A(t,e,n,r,i,o,s){let a=t.doc.type.schema,l=et(a),c,u;if(i>e.width)for(let f=0,d=0;f<e.height;f++){let p=n.child(f);d+=p.nodeSize;let h=[],m;p.lastChild==null||p.lastChild.type==l.cell?m=c||(c=l.cell.createAndFill()):m=u||(u=l.header_cell.createAndFill());for(let g=e.width;g<i;g++)h.push(m);t.insert(t.mapping.slice(s).map(d-1+r),h)}if(o>e.height){let f=[];for(let h=0,m=(e.height-1)*e.width;h<Math.max(e.width,i);h++){let g=h>=e.width?!1:n.nodeAt(e.map[m+h]).type==l.header_cell;f.push(g?u||(u=l.header_cell.createAndFill()):c||(c=l.cell.createAndFill()))}let d=l.row.create(null,M.from(f)),p=[];for(let h=e.height;h<o;h++)p.push(d);t.insert(t.mapping.slice(s).map(r+n.nodeSize-2),p)}return!!(c||u)}function mb(t,e,n,r,i,o,s,a){if(s==0||s==e.height)return!1;let l=!1;for(let c=i;c<o;c++){let u=s*e.width+c,f=e.map[u];if(e.map[u-e.width]==f){l=!0;let d=n.nodeAt(f),{top:p,left:h}=e.findCell(f);t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d.attrs,rowspan:s-p}),t.insert(t.mapping.slice(a).map(e.positionAt(s,h,n)),d.type.createAndFill({...d.attrs,rowspan:p+d.attrs.rowspan-s})),c+=d.attrs.colspan-1}}return l}function gb(t,e,n,r,i,o,s,a){if(s==0||s==e.width)return!1;let l=!1;for(let c=i;c<o;c++){let u=c*e.width+s,f=e.map[u];if(e.map[u-1]==f){l=!0;let d=n.nodeAt(f),p=e.colCount(f),h=t.mapping.slice(a).map(f+r);t.setNodeMarkup(h,null,Br(d.attrs,s-p,d.attrs.colspan-(s-p))),t.insert(h+d.nodeSize,d.type.createAndFill(Br(d.attrs,0,s-p))),c+=d.attrs.rowspan-1}}return l}function yb(t,e,n,r,i){let o=n?t.doc.nodeAt(n-1):t.doc;if(!o)throw new Error("No table found");let s=oe.get(o),{top:a,left:l}=r,c=l+i.width,u=a+i.height,f=t.tr,d=0;function p(){if(o=n?f.doc.nodeAt(n-1):f.doc,!o)throw new Error("No table found");s=oe.get(o),d=f.mapping.maps.length}$A(f,s,o,n,c,u,d)&&p(),mb(f,s,o,n,l,c,a,d)&&p(),mb(f,s,o,n,l,c,u,d)&&p(),gb(f,s,o,n,a,u,l,d)&&p(),gb(f,s,o,n,a,u,c,d)&&p();for(let h=a;h<u;h++){let m=s.positionAt(h,l,o),g=s.positionAt(h,c,o);f.replace(f.mapping.slice(d).map(m+n),f.mapping.slice(d).map(g+n),new R(i.rows[h-a],0,0))}p(),f.setSelection(new he(f.doc.resolve(n+s.positionAt(a,l,o)),f.doc.resolve(n+s.positionAt(u-1,c-1,o)))),e(f)}var HA=fu({ArrowLeft:nl("horiz",-1),ArrowRight:nl("horiz",1),ArrowUp:nl("vert",-1),ArrowDown:nl("vert",1),"Shift-ArrowLeft":rl("horiz",-1),"Shift-ArrowRight":rl("horiz",1),"Shift-ArrowUp":rl("vert",-1),"Shift-ArrowDown":rl("vert",1),Backspace:tl,"Mod-Backspace":tl,Delete:tl,"Mod-Delete":tl});function il(t,e,n){return n.eq(t.selection)?!1:(e&&e(t.tr.setSelection(n).scrollIntoView()),!0)}function nl(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection;if(o instanceof he)return il(n,r,$.near(o.$headCell,e));if(t!="horiz"&&!o.empty)return!1;let s=Pb(i,t,e);if(s==null)return!1;if(t=="horiz")return il(n,r,$.near(n.doc.resolve(o.head+e),e));{let a=n.doc.resolve(s),l=Sb(a,t,e),c;return l?c=$.near(l,1):e<0?c=$.near(n.doc.resolve(a.before(-1)),-1):c=$.near(n.doc.resolve(a.after(-1)),1),il(n,r,c)}}}function rl(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection,s;if(o instanceof he)s=o;else{let l=Pb(i,t,e);if(l==null)return!1;s=new he(n.doc.resolve(l))}let a=Sb(s.$headCell,t,e);return a?il(n,r,new he(s.$anchorCell,a)):!1}}function WA(t,e){let n=t.state.doc,r=$i(n.resolve(e));return r?(t.dispatch(t.state.tr.setSelection(new he(r))),!0):!1}function jA(t,e,n){if(!De(t.state))return!1;let r=FA(n),i=t.state.selection;if(i instanceof he){r||(r={width:1,height:1,rows:[M.from(Yf(et(t.state.schema).cell,n))]});let o=i.$anchorCell.node(-1),s=i.$anchorCell.start(-1),a=oe.get(o).rectBetween(i.$anchorCell.pos-s,i.$headCell.pos-s);return r=_A(r,a.right-a.left,a.bottom-a.top),yb(t.state,t.dispatch,s,a,r),!0}else if(r){let o=sl(t.state),s=o.start(-1);return yb(t.state,t.dispatch,s,oe.get(o.node(-1)).findCell(o.pos-s),r),!0}else return!1}function VA(t,e){var n;if(e.button!=0||e.ctrlKey||e.metaKey)return;let r=kb(t,e.target),i;if(e.shiftKey&&t.state.selection instanceof he)o(t.state.selection.$anchorCell,e),e.preventDefault();else if(e.shiftKey&&r&&(i=$i(t.state.selection.$anchor))!=null&&((n=Uf(t,e))===null||n===void 0?void 0:n.pos)!=i.pos)o(i,e),e.preventDefault();else if(!r)return;function o(l,c){let u=Uf(t,c),f=Vn.getState(t.state)==null;if(!u||!Zf(l,u))if(f)u=l;else return;let d=new he(l,u);if(f||!t.state.selection.eq(d)){let p=t.state.tr.setSelection(d);f&&p.setMeta(Vn,l.pos),t.dispatch(p)}}function s(){t.root.removeEventListener("mouseup",s),t.root.removeEventListener("dragstart",s),t.root.removeEventListener("mousemove",a),Vn.getState(t.state)!=null&&t.dispatch(t.state.tr.setMeta(Vn,-1))}function a(l){let c=l,u=Vn.getState(t.state),f;if(u!=null)f=t.state.doc.resolve(u);else if(kb(t,c.target)!=r&&(f=Uf(t,e),!f))return s();f&&o(f,c)}t.root.addEventListener("mouseup",s),t.root.addEventListener("dragstart",s),t.root.addEventListener("mousemove",a)}function Pb(t,e,n){if(!(t.state.selection instanceof B))return null;let{$head:r}=t.state.selection;for(let i=r.depth-1;i>=0;i--){let o=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:o.childCount))return null;if(o.type.spec.tableRole=="cell"||o.type.spec.tableRole=="header_cell"){let s=r.before(i),a=e=="vert"?n>0?"down":"up":n>0?"right":"left";return t.endOfTextblock(a)?s:null}}return null}function kb(t,e){for(;e&&e!=t.dom;e=e.parentNode)if(e.nodeName=="TD"||e.nodeName=="TH")return e;return null}function Uf(t,e){let n=t.posAtCoords({left:e.clientX,top:e.clientY});if(!n)return null;let{inside:r,pos:i}=n;return r>=0&&$i(t.state.doc.resolve(r))||$i(t.state.doc.resolve(i))}var qA=class{constructor(t,e){this.node=t,this.defaultCellMinWidth=e,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${e}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),Qf(t,this.colgroup,this.table,e),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,Qf(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function Qf(t,e,n,r,i,o){let s=0,a=!0,l=e.firstChild,c=t.firstChild;if(c){for(let f=0,d=0;f<c.childCount;f++){let{colspan:p,colwidth:h}=c.child(f).attrs;for(let m=0;m<p;m++,d++){let g=i==d?o:h&&h[m],y=g?g+"px":"";if(s+=g||r,g||(a=!1),l)l.style.width!=y&&(l.style.width=y),l=l.nextSibling;else{let b=document.createElement("col");b.style.width=y,e.appendChild(b)}}}for(;l;){var u;let f=l.nextSibling;(u=l.parentNode)===null||u===void 0||u.removeChild(l),l=f}a?(n.style.width=s+"px",n.style.minWidth=""):(n.style.width="",n.style.minWidth=s+"px")}}var yt=new ee("tableColumnResizing");function Bb({handleWidth:t=5,cellMinWidth:e=25,defaultCellMinWidth:n=100,View:r=qA,lastColumnResizable:i=!0}={}){let o=new X({key:yt,state:{init(s,a){var l;let c=(l=o.spec)===null||l===void 0||(l=l.props)===null||l===void 0?void 0:l.nodeViews,u=et(a.schema).table.name;return r&&c&&(c[u]=(f,d)=>new r(f,n,d)),new KA(-1,!1)},apply(s,a){return a.apply(s)}},props:{attributes:s=>{let a=yt.getState(s);return a&&a.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(s,a)=>{UA(s,a,t,i)},mouseleave:s=>{JA(s)},mousedown:(s,a)=>{GA(s,a,e,n)}},decorations:s=>{let a=yt.getState(s);if(a&&a.activeHandle>-1)return eI(s,a.activeHandle)},nodeViews:{}}});return o}var KA=class ol{constructor(e,n){this.activeHandle=e,this.dragging=n}apply(e){let n=this,r=e.getMeta(yt);if(r&&r.setHandle!=null)return new ol(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new ol(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&e.docChanged){let i=e.mapping.map(n.activeHandle,-1);return Xf(e.doc.resolve(i))||(i=-1),new ol(i,n.dragging)}return n}};function UA(t,e,n,r){if(!t.editable)return;let i=yt.getState(t.state);if(i&&!i.dragging){let o=YA(e.target),s=-1;if(o){let{left:a,right:l}=o.getBoundingClientRect();e.clientX-a<=n?s=bb(t,e,"left",n):l-e.clientX<=n&&(s=bb(t,e,"right",n))}if(s!=i.activeHandle){if(!r&&s!==-1){let a=t.state.doc.resolve(s),l=a.node(-1),c=oe.get(l),u=a.start(-1);if(c.colCount(a.pos-u)+a.nodeAfter.attrs.colspan-1==c.width-1)return}Fb(t,s)}}}function JA(t){if(!t.editable)return;let e=yt.getState(t.state);e&&e.activeHandle>-1&&!e.dragging&&Fb(t,-1)}function GA(t,e,n,r){var i;if(!t.editable)return!1;let o=(i=t.dom.ownerDocument.defaultView)!==null&&i!==void 0?i:window,s=yt.getState(t.state);if(!s||s.activeHandle==-1||s.dragging)return!1;let a=t.state.doc.nodeAt(s.activeHandle),l=XA(t,s.activeHandle,a.attrs);t.dispatch(t.state.tr.setMeta(yt,{setDragging:{startX:e.clientX,startWidth:l}}));function c(f){o.removeEventListener("mouseup",c),o.removeEventListener("mousemove",u);let d=yt.getState(t.state);d?.dragging&&(QA(t,d.activeHandle,xb(d.dragging,f,n)),t.dispatch(t.state.tr.setMeta(yt,{setDragging:null})))}function u(f){if(!f.which)return c(f);let d=yt.getState(t.state);if(d&&d.dragging){let p=xb(d.dragging,f,n);wb(t,d.activeHandle,p,r)}}return wb(t,s.activeHandle,l,r),o.addEventListener("mouseup",c),o.addEventListener("mousemove",u),e.preventDefault(),!0}function XA(t,e,{colspan:n,colwidth:r}){let i=r&&r[r.length-1];if(i)return i;let o=t.domAtPos(e),s=o.node.childNodes[o.offset].offsetWidth,a=n;if(r)for(let l=0;l<n;l++)r[l]&&(s-=r[l],a--);return s/a}function YA(t){for(;t&&t.nodeName!="TD"&&t.nodeName!="TH";)t=t.classList&&t.classList.contains("ProseMirror")?null:t.parentNode;return t}function bb(t,e,n,r){let i=n=="right"?-r:r,o=t.posAtCoords({left:e.clientX+i,top:e.clientY});if(!o)return-1;let{pos:s}=o,a=$i(t.state.doc.resolve(s));if(!a)return-1;if(n=="right")return a.pos;let l=oe.get(a.node(-1)),c=a.start(-1),u=l.map.indexOf(a.pos-c);return u%l.width==0?-1:c+l.map[u-1]}function xb(t,e,n){let r=e.clientX-t.startX;return Math.max(n,t.startWidth+r)}function Fb(t,e){t.dispatch(t.state.tr.setMeta(yt,{setHandle:e}))}function QA(t,e,n){let r=t.state.doc.resolve(e),i=r.node(-1),o=oe.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1,l=t.state.tr;for(let c=0;c<o.height;c++){let u=c*o.width+a;if(c&&o.map[u]==o.map[u-o.width])continue;let f=o.map[u],d=i.nodeAt(f).attrs,p=d.colspan==1?0:a-o.colCount(f);if(d.colwidth&&d.colwidth[p]==n)continue;let h=d.colwidth?d.colwidth.slice():ZA(d.colspan);h[p]=n,l.setNodeMarkup(s+f,null,{...d,colwidth:h})}l.docChanged&&t.dispatch(l)}function wb(t,e,n,r){let i=t.state.doc.resolve(e),o=i.node(-1),s=i.start(-1),a=oe.get(o).colCount(i.pos-s)+i.nodeAfter.attrs.colspan-1,l=t.domAtPos(i.start(-1)).node;for(;l&&l.nodeName!="TABLE";)l=l.parentNode;l&&Qf(o,l.firstChild,l,r,a,n)}function ZA(t){return Array(t).fill(0)}function eI(t,e){let n=[],r=t.doc.resolve(e),i=r.node(-1);if(!i)return ae.empty;let o=oe.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1;for(let c=0;c<o.height;c++){let u=a+c*o.width;if((a==o.width-1||o.map[u]!=o.map[u+1])&&(c==0||o.map[u]!=o.map[u-o.width])){var l;let f=o.map[u],d=s+f+i.nodeAt(f).nodeSize-1,p=document.createElement("div");p.className="column-resize-handle",!((l=yt.getState(t))===null||l===void 0)&&l.dragging&&n.push(le.node(s+f,s+f+i.nodeAt(f).nodeSize,{class:"column-resize-dragging"})),n.push(le.widget(d,p))}}return ae.create(t.doc,n)}function zb({allowTableNodeSelection:t=!1}={}){return new X({key:Vn,state:{init(){return null},apply(e,n){let r=e.getMeta(Vn);if(r!=null)return r==-1?null:r;if(n==null||!e.docChanged)return n;let{deleted:i,pos:o}=e.mapping.mapResult(n);return i?null:o}},props:{decorations:bA,handleDOMEvents:{mousedown:VA},createSelectionBetween(e){return Vn.getState(e.state)!=null?e.state.selection:null},handleTripleClick:WA,handleKeyDown:HA,handlePaste:jA},appendTransaction(e,n,r){return CA(r,MA(r,n),t)}})}var ul=typeof navigator<"u"?navigator:null,rd=ul&&ul.userAgent||"",tI=/Edge\/(\d+)/.exec(rd),nI=/MSIE \d/.exec(rd),rI=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(rd),iI=!!(nI||rI||tI),oI=!iI&&!!ul&&/Apple Computer/.test(ul.vendor),_b=new ee("safari-ime-span"),nd=!1,sI={key:_b,props:{decorations:aI,handleDOMEvents:{compositionstart:()=>{nd=!0},compositionend:()=>{nd=!1}}}};function aI(t){let{$from:e,$to:n,to:r}=t.selection;if(nd&&e.sameParent(n)){let i=le.widget(r,lI,{ignoreSelection:!0,key:"safari-ime-span"});return ae.create(t.doc,[i])}}function lI(t){let e=t.dom.ownerDocument.createElement("span");return e.className="ProseMirror-safari-ime-span",e}var $b=new X(oI?sI:{key:_b});function id(t,e){let n=String(t);if(typeof e!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(e);for(;i!==-1;)r++,i=n.indexOf(e,i+e.length);return r}function od(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function sd(t,e,n){let i=Nn((n||{}).ignore||[]),o=cI(e),s=-1;for(;++s<o.length;)lr(t,"text",a);function a(c,u){let f=-1,d;for(;++f<u.length;){let p=u[f],h=d?d.children:void 0;if(i(p,h?h.indexOf(p):void 0,d))return;d=p}if(d)return l(c,u)}function l(c,u){let f=u[u.length-1],d=o[s][0],p=o[s][1],h=0,g=f.children.indexOf(c),y=!1,b=[];d.lastIndex=0;let C=d.exec(c.value);for(;C;){let v=C.index,A={index:C.index,input:C.input,stack:[...u,c]},w=p(...C,A);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?d.lastIndex=v+1:(h!==v&&b.push({type:"text",value:c.value.slice(h,v)}),Array.isArray(w)?b.push(...w):w&&b.push(w),h=v+C[0].length,y=!0),!d.global)break;C=d.exec(c.value)}return y?(h<c.value.length&&b.push({type:"text",value:c.value.slice(h)}),f.children.splice(g,1,...b)):b=[c],g+b.length}}function cI(t){let e=[];if(!Array.isArray(t))throw new TypeError("Expected find and replace tuple or list of tuples");let n=!t[0]||Array.isArray(t[0])?t:[t],r=-1;for(;++r<n.length;){let i=n[r];e.push([uI(i[0]),fI(i[1])])}return e}function uI(t){return typeof t=="string"?new RegExp(od(t),"g"):t}function fI(t){return typeof t=="function"?t:function(){return t}}var ad="phrasing",ld=["autolink","link","image","label"];function ud(){return{transforms:[yI],enter:{literalAutolink:dI,literalAutolinkEmail:cd,literalAutolinkHttp:cd,literalAutolinkWww:cd},exit:{literalAutolink:gI,literalAutolinkEmail:mI,literalAutolinkHttp:pI,literalAutolinkWww:hI}}}function fd(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:ad,notInConstruct:ld},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:ad,notInConstruct:ld},{character:":",before:"[ps]",after:"\\/",inConstruct:ad,notInConstruct:ld}]}}function dI(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function cd(t){this.config.enter.autolinkProtocol.call(this,t)}function pI(t){this.config.exit.autolinkProtocol.call(this,t)}function hI(t){this.config.exit.data.call(this,t);let e=this.stack[this.stack.length-1];e.type,e.url="http://"+this.sliceSerialize(t)}function mI(t){this.config.exit.autolinkEmail.call(this,t)}function gI(t){this.exit(t)}function yI(t){sd(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,kI],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,bI]],{ignore:["link","linkReference"]})}function kI(t,e,n,r,i){let o="";if(!Hb(i)||(/^w/i.test(e)&&(n=e+n,e="",o="http://"),!xI(n)))return!1;let s=wI(n+r);if(!s[0])return!1;let a={type:"link",title:null,url:o+e+s[0],children:[{type:"text",value:e+s[0]}]};return s[1]?[a,{type:"text",value:s[1]}]:a}function bI(t,e,n,r){return!Hb(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+e+"@"+n,children:[{type:"text",value:e+"@"+n}]}}function xI(t){let e=t.split(".");return!(e.length<2||e[e.length-1]&&(/_/.test(e[e.length-1])||!/[a-zA-Z\d]/.test(e[e.length-1]))||e[e.length-2]&&(/_/.test(e[e.length-2])||!/[a-zA-Z\d]/.test(e[e.length-2])))}function wI(t){let e=/[!"&'),.:;<>?\]}]+$/.exec(t);if(!e)return[t,void 0];t=t.slice(0,e.index);let n=e[0],r=n.indexOf(")"),i=id(t,"("),o=id(t,")");for(;r!==-1&&i>o;)t+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),o++;return[t,n]}function Hb(t,e){let n=t.input.charCodeAt(t.index-1);return(t.index===0||Wt(n)||nr(n))&&(!e||n!==47)}Wb.peek=NI;function CI(){this.buffer()}function SI(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function MI(){this.buffer()}function EI(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function TI(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=qe(this.sliceSerialize(t)).toLowerCase(),n.label=e}function vI(t){this.exit(t)}function AI(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=qe(this.sliceSerialize(t)).toLowerCase(),n.label=e}function II(t){this.exit(t)}function NI(){return"["}function Wb(t,e,n,r){let i=n.createTracker(r),o=i.move("[^"),s=n.enter("footnoteReference"),a=n.enter("reference");return o+=i.move(n.safe(n.associationId(t),{after:"]",before:o})),a(),s(),o+=i.move("]"),o}function dd(){return{enter:{gfmFootnoteCallString:CI,gfmFootnoteCall:SI,gfmFootnoteDefinitionLabelString:MI,gfmFootnoteDefinition:EI},exit:{gfmFootnoteCallString:TI,gfmFootnoteCall:vI,gfmFootnoteDefinitionLabelString:AI,gfmFootnoteDefinition:II}}}function pd(t){let e=!1;return t&&t.firstLineBlank&&(e=!0),{handlers:{footnoteDefinition:n,footnoteReference:Wb},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,o,s){let a=o.createTracker(s),l=a.move("[^"),c=o.enter("footnoteDefinition"),u=o.enter("label");return l+=a.move(o.safe(o.associationId(r),{before:l,after:"]"})),u(),l+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),l+=a.move((e?` +`:" ")+o.indentLines(o.containerFlow(r,a.current()),e?jb:RI))),c(),l}}function RI(t,e,n){return e===0?t:jb(t,e,n)}function jb(t,e,n){return(n?"":" ")+t}var OI=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Vb.peek=PI;function hd(){return{canContainEols:["delete"],enter:{strikethrough:DI},exit:{strikethrough:LI}}}function md(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:OI}],handlers:{delete:Vb}}}function DI(t){this.enter({type:"delete",children:[]},t)}function LI(t){this.exit(t)}function Vb(t,e,n,r){let i=n.createTracker(r),o=n.enter("strikethrough"),s=i.move("~~");return s+=n.containerPhrasing(t,{...i.current(),before:s,after:"~"}),s+=i.move("~~"),o(),s}function PI(){return"~"}function BI(t){return t.length}function Kb(t,e){let n=e||{},r=(n.align||[]).concat(),i=n.stringLength||BI,o=[],s=[],a=[],l=[],c=0,u=-1;for(;++u<t.length;){let m=[],g=[],y=-1;for(t[u].length>c&&(c=t[u].length);++y<t[u].length;){let b=FI(t[u][y]);if(n.alignDelimiters!==!1){let C=i(b);g[y]=C,(l[y]===void 0||C>l[y])&&(l[y]=C)}m.push(b)}s[u]=m,a[u]=g}let f=-1;if(typeof r=="object"&&"length"in r)for(;++f<c;)o[f]=qb(r[f]);else{let m=qb(r);for(;++f<c;)o[f]=m}f=-1;let d=[],p=[];for(;++f<c;){let m=o[f],g="",y="";m===99?(g=":",y=":"):m===108?g=":":m===114&&(y=":");let b=n.alignDelimiters===!1?1:Math.max(1,l[f]-g.length-y.length),C=g+"-".repeat(b)+y;n.alignDelimiters!==!1&&(b=g.length+b+y.length,b>l[f]&&(l[f]=b),p[f]=b),d[f]=C}s.splice(1,0,d),a.splice(1,0,p),u=-1;let h=[];for(;++u<s.length;){let m=s[u],g=a[u];f=-1;let y=[];for(;++f<c;){let b=m[f]||"",C="",v="";if(n.alignDelimiters!==!1){let A=l[f]-(g[f]||0),w=o[f];w===114?C=" ".repeat(A):w===99?A%2?(C=" ".repeat(A/2+.5),v=" ".repeat(A/2-.5)):(C=" ".repeat(A/2),v=C):v=" ".repeat(A)}n.delimiterStart!==!1&&!f&&y.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&b==="")&&(n.delimiterStart!==!1||f)&&y.push(" "),n.alignDelimiters!==!1&&y.push(C),y.push(b),n.alignDelimiters!==!1&&y.push(v),n.padding!==!1&&y.push(" "),(n.delimiterEnd!==!1||f!==c-1)&&y.push("|")}h.push(n.delimiterEnd===!1?y.join("").replace(/ +$/,""):y.join(""))}return h.join(` +`)}function FI(t){return t==null?"":String(t)}function qb(t){let e=typeof t=="string"?t.codePointAt(0):0;return e===67||e===99?99:e===76||e===108?108:e===82||e===114?114:0}function yd(){return{enter:{table:zI,tableData:Ub,tableHeader:Ub,tableRow:$I},exit:{codeText:HI,table:_I,tableData:gd,tableHeader:gd,tableRow:gd}}}function zI(t){let e=t._align;this.enter({type:"table",align:e.map(function(n){return n==="none"?null:n}),children:[]},t),this.data.inTable=!0}function _I(t){this.exit(t),this.data.inTable=void 0}function $I(t){this.enter({type:"tableRow",children:[]},t)}function gd(t){this.exit(t)}function Ub(t){this.enter({type:"tableCell",children:[]},t)}function HI(t){let e=this.resume();this.data.inTable&&(e=e.replace(/\\([\\|])/g,WI));let n=this.stack[this.stack.length-1];n.type,n.value=e,this.exit(t)}function WI(t,e){return e==="|"?e:t}function kd(t){let e=t||{},n=e.tableCellPadding,r=e.tablePipeAlign,i=e.stringLength,o=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:d,table:s,tableCell:l,tableRow:a}};function s(p,h,m,g){return c(u(p,m,g),p.align)}function a(p,h,m,g){let y=f(p,m,g),b=c([y]);return b.slice(0,b.indexOf(` -`))}function l(p,h,m,g){let y=m.enter("tableCell"),b=m.enter("phrasing"),C=m.containerPhrasing(p,{...g,before:o,after:o});return b(),y(),C}function c(p,h){return qb(p,{align:h,alignDelimiters:r,padding:n,stringLength:i})}function u(p,h,m){let g=p.children,y=-1,b=[],C=h.enter("table");for(;++y<g.length;)b[y]=f(g[y],h,m);return C(),b}function f(p,h,m){let g=p.children,y=-1,b=[],C=h.enter("tableRow");for(;++y<g.length;)b[y]=l(g[y],p,h,m);return C(),b}function d(p,h,m){let g=cr.inlineCode(p,h,m);return m.stack.includes("tableCell")&&(g=g.replace(/\|/g,"\\$&")),g}}function bd(){return{exit:{taskListCheckValueChecked:Ub,taskListCheckValueUnchecked:Ub,paragraph:WI}}}function xd(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:jI}}}function Ub(t){let e=this.stack[this.stack.length-2];e.type,e.checked=t.type==="taskListCheckValueChecked"}function WI(t){let e=this.stack[this.stack.length-2];if(e&&e.type==="listItem"&&typeof e.checked=="boolean"){let n=this.stack[this.stack.length-1];n.type;let r=n.children[0];if(r&&r.type==="text"){let i=e.children,o=-1,s;for(;++o<i.length;){let a=i[o];if(a.type==="paragraph"){s=a;break}}s===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(t)}function jI(t,e,n,r){let i=t.children[0],o=typeof t.checked=="boolean"&&i&&i.type==="paragraph",s="["+(t.checked?"x":" ")+"] ",a=n.createTracker(r);o&&a.move(s);let l=cr.listItem(t,e,n,{...r,...a.current()});return o&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,c)),l;function c(u){return u+s}}function wd(){return[ud(),dd(),hd(),yd(),bd()]}function Cd(t){return{extensions:[fd(),pd(t),md(),kd(t),xd()]}}var VI={tokenize:GI,partial:!0},Jb={tokenize:XI,partial:!0},Gb={tokenize:YI,partial:!0},Xb={tokenize:QI,partial:!0},qI={tokenize:ZI,partial:!0},Yb={name:"wwwAutolink",tokenize:UI,previous:Zb},Qb={name:"protocolAutolink",tokenize:JI,previous:ex},bn={name:"emailAutolink",tokenize:KI,previous:tx},Kt={};function Md(){return{text:Kt}}var Fr=48;for(;Fr<123;)Kt[Fr]=bn,Fr++,Fr===58?Fr=65:Fr===91&&(Fr=97);Kt[43]=bn;Kt[45]=bn;Kt[46]=bn;Kt[95]=bn;Kt[72]=[bn,Qb];Kt[104]=[bn,Qb];Kt[87]=[bn,Yb];Kt[119]=[bn,Yb];function KI(t,e,n){let r=this,i,o;return s;function s(f){return!Sd(f)||!tx.call(r,r.previous)||Ed(r.events)?n(f):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),a(f))}function a(f){return Sd(f)?(t.consume(f),a):f===64?(t.consume(f),l):n(f)}function l(f){return f===46?t.check(qI,u,c)(f):f===45||f===95||ve(f)?(o=!0,t.consume(f),l):u(f)}function c(f){return t.consume(f),i=!0,l}function u(f){return o&&i&&Te(r.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),e(f)):n(f)}}function UI(t,e,n){let r=this;return i;function i(s){return s!==87&&s!==119||!Zb.call(r,r.previous)||Ed(r.events)?n(s):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(VI,t.attempt(Jb,t.attempt(Gb,o),n),n)(s))}function o(s){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),e(s)}}function JI(t,e,n){let r=this,i="",o=!1;return s;function s(f){return(f===72||f===104)&&ex.call(r,r.previous)&&!Ed(r.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),i+=String.fromCodePoint(f),t.consume(f),a):n(f)}function a(f){if(Te(f)&&i.length<5)return i+=String.fromCodePoint(f),t.consume(f),a;if(f===58){let d=i.toLowerCase();if(d==="http"||d==="https")return t.consume(f),l}return n(f)}function l(f){return f===47?(t.consume(f),o?c:(o=!0,l)):n(f)}function c(f){return f===null||tr(f)||Z(f)||Wt(f)||nr(f)?n(f):t.attempt(Jb,t.attempt(Gb,u),n)(f)}function u(f){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),e(f)}}function GI(t,e,n){let r=0;return i;function i(s){return(s===87||s===119)&&r<3?(r++,t.consume(s),i):s===46&&r===3?(t.consume(s),o):n(s)}function o(s){return s===null?n(s):e(s)}}function XI(t,e,n){let r,i,o;return s;function s(c){return c===46||c===95?t.check(Xb,l,a)(c):c===null||Z(c)||Wt(c)||c!==45&&nr(c)?l(c):(o=!0,t.consume(c),s)}function a(c){return c===95?r=!0:(i=r,r=void 0),t.consume(c),s}function l(c){return i||r||!o?n(c):e(c)}}function YI(t,e){let n=0,r=0;return i;function i(s){return s===40?(n++,t.consume(s),i):s===41&&r<n?o(s):s===33||s===34||s===38||s===39||s===41||s===42||s===44||s===46||s===58||s===59||s===60||s===63||s===93||s===95||s===126?t.check(Xb,e,o)(s):s===null||Z(s)||Wt(s)?e(s):(t.consume(s),i)}function o(s){return s===41&&r++,t.consume(s),i}}function QI(t,e,n){return r;function r(a){return a===33||a===34||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===63||a===95||a===126?(t.consume(a),r):a===38?(t.consume(a),o):a===93?(t.consume(a),i):a===60||a===null||Z(a)||Wt(a)?e(a):n(a)}function i(a){return a===null||a===40||a===91||Z(a)||Wt(a)?e(a):r(a)}function o(a){return Te(a)?s(a):n(a)}function s(a){return a===59?(t.consume(a),r):Te(a)?(t.consume(a),s):n(a)}}function ZI(t,e,n){return r;function r(o){return t.consume(o),i}function i(o){return ve(o)?n(o):e(o)}}function Zb(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Z(t)}function ex(t){return!Te(t)}function tx(t){return!(t===47||Sd(t))}function Sd(t){return t===43||t===45||t===46||t===95||ve(t)}function Ed(t){let e=t.length,n=!1;for(;e--;){let r=t[e][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return t.length>0&&!n&&(t[t.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var eN={tokenize:aN,partial:!0};function Td(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:iN,continuation:{tokenize:oN},exit:sN}},text:{91:{name:"gfmFootnoteCall",tokenize:rN},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:tN,resolveTo:nN}}}}function tN(t,e,n){let r=this,i=r.events.length,o=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),s;for(;i--;){let l=r.events[i][1];if(l.type==="labelImage"){s=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return a;function a(l){if(!s||!s._balanced)return n(l);let c=qe(r.sliceSerialize({start:s.end,end:r.now()}));return c.codePointAt(0)!==94||!o.includes(c.slice(1))?n(l):(t.enter("gfmFootnoteCallLabelMarker"),t.consume(l),t.exit("gfmFootnoteCallLabelMarker"),e(l))}}function nN(t,e){let n=t.length,r;for(;n--;)if(t[n][1].type==="labelImage"&&t[n][0]==="enter"){r=t[n][1];break}t[n+1][1].type="data",t[n+3][1].type="gfmFootnoteCallLabelMarker";let i={type:"gfmFootnoteCall",start:Object.assign({},t[n+3][1].start),end:Object.assign({},t[t.length-1][1].end)},o={type:"gfmFootnoteCallMarker",start:Object.assign({},t[n+3][1].end),end:Object.assign({},t[n+3][1].end)};o.end.column++,o.end.offset++,o.end._bufferIndex++;let s={type:"gfmFootnoteCallString",start:Object.assign({},o.end),end:Object.assign({},t[t.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},l=[t[n+1],t[n+2],["enter",i,e],t[n+3],t[n+4],["enter",o,e],["exit",o,e],["enter",s,e],["enter",a,e],["exit",a,e],["exit",s,e],t[t.length-2],t[t.length-1],["exit",i,e]];return t.splice(n,t.length-n+1,...l),t}function rN(t,e,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o=0,s;return a;function a(f){return t.enter("gfmFootnoteCall"),t.enter("gfmFootnoteCallLabelMarker"),t.consume(f),t.exit("gfmFootnoteCallLabelMarker"),l}function l(f){return f!==94?n(f):(t.enter("gfmFootnoteCallMarker"),t.consume(f),t.exit("gfmFootnoteCallMarker"),t.enter("gfmFootnoteCallString"),t.enter("chunkString").contentType="string",c)}function c(f){if(o>999||f===93&&!s||f===null||f===91||Z(f))return n(f);if(f===93){t.exit("chunkString");let d=t.exit("gfmFootnoteCallString");return i.includes(qe(r.sliceSerialize(d)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(f),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),e):n(f)}return Z(f)||(s=!0),o++,t.consume(f),f===92?u:c}function u(f){return f===91||f===92||f===93?(t.consume(f),o++,c):c(f)}}function iN(t,e,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o,s=0,a;return l;function l(h){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(h){return h===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",u):n(h)}function u(h){if(s>999||h===93&&!a||h===null||h===91||Z(h))return n(h);if(h===93){t.exit("chunkString");let m=t.exit("gfmFootnoteDefinitionLabelString");return o=qe(r.sliceSerialize(m)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),d}return Z(h)||(a=!0),s++,t.consume(h),h===92?f:u}function f(h){return h===91||h===92||h===93?(t.consume(h),s++,u):u(h)}function d(h){return h===58?(t.enter("definitionMarker"),t.consume(h),t.exit("definitionMarker"),i.includes(o)||i.push(o),_(t,p,"gfmFootnoteDefinitionWhitespace")):n(h)}function p(h){return e(h)}}function oN(t,e,n){return t.check(jt,e,t.attempt(eN,e,n))}function sN(t){t.exit("gfmFootnoteDefinition")}function aN(t,e,n){let r=this;return _(t,i,"gfmFootnoteDefinitionIndent",5);function i(o){let s=r.events[r.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?e(o):n(o)}}function vd(t){let n=(t||{}).singleTilde,r={name:"strikethrough",tokenize:o,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(s,a){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let c=l;for(;c--;)if(s[c][0]==="exit"&&s[c][1].type==="strikethroughSequenceTemporary"&&s[c][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[c][1].end.offset-s[c][1].start.offset){s[l][1].type="strikethroughSequence",s[c][1].type="strikethroughSequence";let u={type:"strikethrough",start:Object.assign({},s[c][1].start),end:Object.assign({},s[l][1].end)},f={type:"strikethroughText",start:Object.assign({},s[c][1].end),end:Object.assign({},s[l][1].start)},d=[["enter",u,a],["enter",s[c][1],a],["exit",s[c][1],a],["enter",f,a]],p=a.parser.constructs.insideSpan.null;p&&ke(d,d.length,0,vn(p,s.slice(c+1,l),a)),ke(d,d.length,0,[["exit",f,a],["enter",s[l][1],a],["exit",s[l][1],a],["exit",u,a]]),ke(s,c-1,l-c+3,d),l=c+d.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type="data");return s}function o(s,a,l){let c=this.previous,u=this.events,f=0;return d;function d(h){return c===126&&u[u.length-1][1].type!=="characterEscape"?l(h):(s.enter("strikethroughSequenceTemporary"),p(h))}function p(h){let m=on(c);if(h===126)return f>1?l(h):(s.consume(h),f++,p);if(f<2&&!n)return l(h);let g=s.exit("strikethroughSequenceTemporary"),y=on(h);return g._open=!y||y===2&&!!m,g._close=!m||m===2&&!!y,a(h)}}}var fl=class{constructor(){this.map=[]}add(e,n,r){lN(this,e,n,r)}consume(e){if(this.map.sort(function(o,s){return o[0]-s[0]}),this.map.length===0)return;let n=this.map.length,r=[];for(;n>0;)n-=1,r.push(e.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),e.length=this.map[n][0];r.push(e.slice()),e.length=0;let i=r.pop();for(;i;){for(let o of i)e.push(o);i=r.pop()}this.map.length=0}};function lN(t,e,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i<t.map.length;){if(t.map[i][0]===e){t.map[i][1]+=n,t.map[i][2].push(...r);return}i+=1}t.map.push([e,n,r])}}function nx(t,e){let n=!1,r=[];for(;e<t.length;){let i=t[e];if(n){if(i[0]==="enter")i[1].type==="tableContent"&&r.push(t[e+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(t[e-1][1].type==="tableDelimiterMarker"){let o=r.length-1;r[o]=r[o]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(n=!0);e+=1}return r}function Ad(){return{flow:{null:{name:"table",tokenize:cN,resolveAll:uN}}}}function cN(t,e,n){let r=this,i=0,o=0,s;return a;function a(S){let me=r.events.length-1;for(;me>-1;){let W=r.events[me][1].type;if(W==="lineEnding"||W==="linePrefix")me--;else break}let te=me>-1?r.events[me][1].type:null,F=te==="tableHead"||te==="tableRow"?w:l;return F===w&&r.parser.lazy[r.now().line]?n(S):F(S)}function l(S){return t.enter("tableHead"),t.enter("tableRow"),c(S)}function c(S){return S===124||(s=!0,o+=1),u(S)}function u(S){return S===null?n(S):D(S)?o>1?(o=0,r.interrupt=!0,t.exit("tableRow"),t.enter("lineEnding"),t.consume(S),t.exit("lineEnding"),p):n(S):j(S)?_(t,u,"whitespace")(S):(o+=1,s&&(s=!1,i+=1),S===124?(t.enter("tableCellDivider"),t.consume(S),t.exit("tableCellDivider"),s=!0,u):(t.enter("data"),f(S)))}function f(S){return S===null||S===124||Z(S)?(t.exit("data"),u(S)):(t.consume(S),S===92?d:f)}function d(S){return S===92||S===124?(t.consume(S),f):f(S)}function p(S){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(S):(t.enter("tableDelimiterRow"),s=!1,j(S)?_(t,h,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):h(S))}function h(S){return S===45||S===58?g(S):S===124?(s=!0,t.enter("tableCellDivider"),t.consume(S),t.exit("tableCellDivider"),m):A(S)}function m(S){return j(S)?_(t,g,"whitespace")(S):g(S)}function g(S){return S===58?(o+=1,s=!0,t.enter("tableDelimiterMarker"),t.consume(S),t.exit("tableDelimiterMarker"),y):S===45?(o+=1,y(S)):S===null||D(S)?v(S):A(S)}function y(S){return S===45?(t.enter("tableDelimiterFiller"),b(S)):A(S)}function b(S){return S===45?(t.consume(S),b):S===58?(s=!0,t.exit("tableDelimiterFiller"),t.enter("tableDelimiterMarker"),t.consume(S),t.exit("tableDelimiterMarker"),C):(t.exit("tableDelimiterFiller"),C(S))}function C(S){return j(S)?_(t,v,"whitespace")(S):v(S)}function v(S){return S===124?h(S):S===null||D(S)?!s||i!==o?A(S):(t.exit("tableDelimiterRow"),t.exit("tableHead"),e(S)):A(S)}function A(S){return n(S)}function w(S){return t.enter("tableRow"),N(S)}function N(S){return S===124?(t.enter("tableCellDivider"),t.consume(S),t.exit("tableCellDivider"),N):S===null||D(S)?(t.exit("tableRow"),e(S)):j(S)?_(t,N,"whitespace")(S):(t.enter("data"),P(S))}function P(S){return S===null||S===124||Z(S)?(t.exit("data"),N(S)):(t.consume(S),S===92?O:P)}function O(S){return S===92||S===124?(t.consume(S),P):P(S)}}function uN(t,e){let n=-1,r=!0,i=0,o=[0,0,0,0],s=[0,0,0,0],a=!1,l=0,c,u,f,d=new fl;for(;++n<t.length;){let p=t[n],h=p[1];p[0]==="enter"?h.type==="tableHead"?(a=!1,l!==0&&(rx(d,e,l,c,u),u=void 0,l=0),c={type:"table",start:Object.assign({},h.start),end:Object.assign({},h.end)},d.add(n,0,[["enter",c,e]])):h.type==="tableRow"||h.type==="tableDelimiterRow"?(r=!0,f=void 0,o=[0,0,0,0],s=[0,n+1,0,0],a&&(a=!1,u={type:"tableBody",start:Object.assign({},h.start),end:Object.assign({},h.end)},d.add(n,0,[["enter",u,e]])),i=h.type==="tableDelimiterRow"?2:u?3:1):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")?(r=!1,s[2]===0&&(o[1]!==0&&(s[0]=s[1],f=dl(d,e,o,i,void 0,f),o=[0,0,0,0]),s[2]=n)):h.type==="tableCellDivider"&&(r?r=!1:(o[1]!==0&&(s[0]=s[1],f=dl(d,e,o,i,void 0,f)),o=s,s=[o[1],n,0,0])):h.type==="tableHead"?(a=!0,l=n):h.type==="tableRow"||h.type==="tableDelimiterRow"?(l=n,o[1]!==0?(s[0]=s[1],f=dl(d,e,o,i,n,f)):s[1]!==0&&(f=dl(d,e,s,i,n,f)),i=0):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")&&(s[3]=n)}for(l!==0&&rx(d,e,l,c,u),d.consume(e.events),n=-1;++n<e.events.length;){let p=e.events[n];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=nx(e.events,n))}return t}function dl(t,e,n,r,i,o){let s=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",a="tableContent";n[0]!==0&&(o.end=Object.assign({},Wi(e.events,n[0])),t.add(n[0],0,[["exit",o,e]]));let l=Wi(e.events,n[1]);if(o={type:s,start:Object.assign({},l),end:Object.assign({},l)},t.add(n[1],0,[["enter",o,e]]),n[2]!==0){let c=Wi(e.events,n[2]),u=Wi(e.events,n[3]),f={type:a,start:Object.assign({},c),end:Object.assign({},u)};if(t.add(n[2],0,[["enter",f,e]]),r!==2){let d=e.events[n[2]],p=e.events[n[3]];if(d[1].end=Object.assign({},p[1].end),d[1].type="chunkText",d[1].contentType="text",n[3]>n[2]+1){let h=n[2]+1,m=n[3]-n[2]-1;t.add(h,m,[])}}t.add(n[3]+1,0,[["exit",f,e]])}return i!==void 0&&(o.end=Object.assign({},Wi(e.events,i)),t.add(i,0,[["exit",o,e]]),o=void 0),o}function rx(t,e,n,r,i){let o=[],s=Wi(e.events,n);i&&(i.end=Object.assign({},s),o.push(["exit",i,e])),r.end=Object.assign({},s),o.push(["exit",r,e]),t.add(n+1,0,o)}function Wi(t,e){let n=t[e],r=n[0]==="enter"?"start":"end";return n[1][r]}var fN={name:"tasklistCheck",tokenize:dN};function Id(){return{text:{91:fN}}}function dN(t,e,n){let r=this;return i;function i(l){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(l):(t.enter("taskListCheck"),t.enter("taskListCheckMarker"),t.consume(l),t.exit("taskListCheckMarker"),o)}function o(l){return Z(l)?(t.enter("taskListCheckValueUnchecked"),t.consume(l),t.exit("taskListCheckValueUnchecked"),s):l===88||l===120?(t.enter("taskListCheckValueChecked"),t.consume(l),t.exit("taskListCheckValueChecked"),s):n(l)}function s(l){return l===93?(t.enter("taskListCheckMarker"),t.consume(l),t.exit("taskListCheckMarker"),t.exit("taskListCheck"),a):n(l)}function a(l){return D(l)?e(l):j(l)?t.check({tokenize:pN},e,n)(l):n(l)}}function pN(t,e,n){return _(t,r,"whitespace");function r(i){return i===null?n(i):e(i)}}function ix(t){return $s([Md(),Td(),vd(t),Ad(),Id()])}var hN={};function pl(t){let e=this,n=t||hN,r=e.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),o=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),s=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(ix(n)),o.push(wd()),s.push(Cd(n))}function K(t,e){return Object.assign(t,{meta:{package:"@milkdown/preset-gfm",...e}}),t}var Od=Dr("strike_through");K(Od,{displayName:"Attr<strikethrough>",group:"Strikethrough"});var ns=Pt("strike_through",t=>({parseDOM:[{tag:"del"},{style:"text-decoration",getAttrs:e=>e==="line-through"}],toDOM:e=>["del",t.get(Od.key)(e)],parseMarkdown:{match:e=>e.type==="delete",runner:(e,n,r)=>{e.openMark(r),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="strike_through",runner:(e,n)=>{e.withMark(n,"delete")}}}));K(ns.mark,{displayName:"MarkSchema<strikethrough>",group:"Strikethrough"});K(ns.ctx,{displayName:"MarkSchemaCtx<strikethrough>",group:"Strikethrough"});var Dd=z("ToggleStrikeThrough",t=>()=>Ln(ns.type(t)));K(Dd,{displayName:"Command<ToggleStrikethrough>",group:"Strikethrough"});var sx=ge(t=>ln(/(?<![\w:/])(~{1,2})(.+?)\1(?!\w|\/)/,ns.type(t)));K(sx,{displayName:"InputRule<strikethrough>",group:"Strikethrough"});var Ld=We("strikeThroughKeymap",{ToggleStrikethrough:{shortcuts:"Mod-Alt-x",command:t=>{let e=t.get(Q);return()=>e.call(Dd.key)}}});K(Ld.ctx,{displayName:"KeymapCtx<strikethrough>",group:"Strikethrough"});K(Ld.shortcuts,{displayName:"Keymap<strikethrough>",group:"Strikethrough"});var rs=wb({tableGroup:"block",cellContent:"paragraph",cellAttributes:{alignment:{default:"left",getFromDOM:t=>t.style.textAlign||"left",setDOMAttr:(t,e)=>{e.style=`text-align: ${t||"left"}`}}}}),xn=ce("table",()=>({...rs.table,content:"table_header_row table_row+",disableDropCursor:!0,parseMarkdown:{match:t=>t.type==="table",runner:(t,e,n)=>{let r=e.align,i=e.children.map((o,s)=>({...o,align:r,isHeader:s===0}));t.openNode(n),t.next(i),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table",runner:(t,e)=>{let n=e.content.firstChild?.content;if(!n)return;let r=[];n.forEach(i=>{r.push(i.attrs.alignment)}),t.openNode("table",void 0,{align:r}),t.next(e.content),t.closeNode()}}}));K(xn.node,{displayName:"NodeSchema<table>",group:"Table"});K(xn.ctx,{displayName:"NodeSchemaCtx<table>",group:"Table"});var is=ce("table_header_row",()=>({...rs.table_row,disableDropCursor:!0,content:"(table_header)*",parseDOM:[{tag:"tr[data-is-header]"},{tag:"tr",getAttrs:t=>t instanceof HTMLElement&&t.querySelector("th")?{}:!1}],toDOM(){return["tr",{"data-is-header":!0},0]},parseMarkdown:{match:t=>!!(t.type==="tableRow"&&t.isHeader),runner:(t,e,n)=>{let r=e.align,i=e.children.map((o,s)=>({...o,align:r[s],isHeader:e.isHeader}));t.openNode(n),t.next(i),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table_header_row",runner:(t,e)=>{e.content.size!==0&&(t.openNode("tableRow",void 0,{isHeader:!0}),t.next(e.content),t.closeNode())}}}));K(is.node,{displayName:"NodeSchema<tableHeaderRow>",group:"Table"});K(is.ctx,{displayName:"NodeSchemaCtx<tableHeaderRow>",group:"Table"});var Vi=ce("table_row",()=>({...rs.table_row,disableDropCursor:!0,content:"(table_cell)*",parseMarkdown:{match:t=>t.type==="tableRow",runner:(t,e,n)=>{let r=e.align,i=e.children.map((o,s)=>({...o,align:r[s]}));t.openNode(n),t.next(i),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table_row",runner:(t,e)=>{e.content.size!==0&&(t.openNode("tableRow"),t.next(e.content),t.closeNode())}}}));K(Vi.node,{displayName:"NodeSchema<tableRow>",group:"Table"});K(Vi.ctx,{displayName:"NodeSchemaCtx<tableRow>",group:"Table"});var ss=ce("table_cell",()=>({...rs.table_cell,disableDropCursor:!0,parseMarkdown:{match:t=>t.type==="tableCell"&&!t.isHeader,runner:(t,e,n)=>{let r=e.align;t.openNode(n,{alignment:r}).openNode(t.schema.nodes.paragraph).next(e.children).closeNode().closeNode()}},toMarkdown:{match:t=>t.type.name==="table_cell",runner:(t,e)=>{t.openNode("tableCell").next(e.content).closeNode()}}}));K(ss.node,{displayName:"NodeSchema<tableCell>",group:"Table"});K(ss.ctx,{displayName:"NodeSchemaCtx<tableCell>",group:"Table"});var ji=ce("table_header",()=>({...rs.table_header,disableDropCursor:!0,parseMarkdown:{match:t=>t.type==="tableCell"&&!!t.isHeader,runner:(t,e,n)=>{let r=e.align;t.openNode(n,{alignment:r}),t.openNode(t.schema.nodes.paragraph),t.next(e.children),t.closeNode(),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table_header",runner:(t,e)=>{t.openNode("tableCell"),t.next(e.content),t.closeNode()}}}));K(ji.node,{displayName:"NodeSchema<tableHeader>",group:"Table"});K(ji.ctx,{displayName:"NodeSchemaCtx<tableHeader>",group:"Table"});function ax(t,e=3,n=3){let r=Array(n).fill(0).map(()=>ss.type(t).createAndFill()),i=Array(n).fill(0).map(()=>ji.type(t).createAndFill()),o=Array(e).fill(0).map((s,a)=>a===0?is.type(t).create(null,i):Vi.type(t).create(null,r));return xn.type(t).create(null,o)}function lx(t){return(e,n)=>r=>{n=n??r.selection.from;let i=r.doc.resolve(n),o=cu(l=>l.type.name==="table")(i),s=o?{node:o.node,from:o.start}:void 0,a=t==="row";if(s){let l=oe.get(s.node);if(e>=0&&e<(a?l.height:l.width)){let c=l.positionAt(a?e:l.height-1,a?l.width-1:e,s.node),u=r.doc.resolve(s.from+c),f=a?he.rowSelection:he.colSelection,d=l.positionAt(a?e:0,a?0:e,s.node),p=r.doc.resolve(s.from+d);return lu(r.setSelection(f(u,p)))}}return r}}var mN=lx("row"),gN=lx("col");function cx(t,e,{map:n,tableStart:r,table:i},o){let s=Array(o).fill(0).reduce((l,c,u)=>l+i.child(u).nodeSize,r),a=Array(n.width).fill(0).map((l,c)=>{let u=i.nodeAt(n.map[c]);return ss.type(t).createAndFill({alignment:u?.attrs.alignment})});return e.insert(s,Vi.type(t).create(null,a)),e}function yN(t){let e=Hi(t.$from);if(!e)return;let n=oe.get(e.node);return n.cellsInRect({left:0,right:n.width,top:0,bottom:n.height}).map(r=>{let i=e.node.nodeAt(r),o=r+e.start;return{pos:o,start:o+1,node:i}})}function kN(t){let e=yN(t.selection);if(e&&e[0]){let n=t.doc.resolve(e[0].pos),r=e[e.length-1];if(r){let i=t.doc.resolve(r.pos);return lu(t.setSelection(new he(i,n)))}}return t}var Pd=z("GoToPrevTableCell",()=>()=>ts(-1));K(Pd,{displayName:"Command<goToPrevTableCellCommand>",group:"Table"});var Bd=z("GoToNextTableCell",()=>()=>ts(1));K(Bd,{displayName:"Command<goToNextTableCellCommand>",group:"Table"});var Fd=z("ExitTable",t=>()=>(e,n)=>{if(!De(e))return!1;let{$head:r}=e.selection,i=Kg(r,xn.type(t));if(!i)return!1;let{to:o}=i,s=e.tr.replaceWith(o,o,Bt.type(t).createAndFill());return s.setSelection($.near(s.doc.resolve(o),1)).scrollIntoView(),n?.(s),!0});K(Fd,{displayName:"Command<breakTableCommand>",group:"Table"});var ux=z("InsertTable",t=>({row:e,col:n}={})=>(r,i)=>{let{selection:o,tr:s}=r,{from:a}=o,l=ax(t,e,n),c=s.replaceSelectionWith(l),u=$.findFrom(c.doc.resolve(a),1,!0);return u&&c.setSelection(u),i?.(c),!0});K(ux,{displayName:"Command<insertTableCommand>",group:"Table"});var fx=z("MoveRow",()=>({from:t,to:e,pos:n}={})=>Ob({from:t??0,to:e??0,pos:n}));K(fx,{displayName:"Command<moveRowCommand>",group:"Table"});var dx=z("MoveCol",()=>({from:t,to:e,pos:n}={})=>Db({from:t??0,to:e??0,pos:n}));K(dx,{displayName:"Command<moveColCommand>",group:"Table"});var px=z("SelectRow",()=>(t={index:0})=>(e,n)=>{let{tr:r}=e;return!!n?.(mN(t.index,t.pos)(r))});K(px,{displayName:"Command<selectRowCommand>",group:"Table"});var hx=z("SelectCol",()=>(t={index:0})=>(e,n)=>{let{tr:r}=e;return!!n?.(gN(t.index,t.pos)(r))});K(hx,{displayName:"Command<selectColCommand>",group:"Table"});var mx=z("SelectTable",()=>()=>(t,e)=>{let{tr:n}=t;return!!e?.(kN(n))});K(mx,{displayName:"Command<selectTableCommand>",group:"Table"});var gx=z("DeleteSelectedCells",()=>()=>(t,e)=>{let{selection:n}=t;if(!(n instanceof he))return!1;let r=n.isRowSelection(),i=n.isColSelection();return r&&i?Rb(t,e):i?ll(t,e):cl(t,e)});K(gx,{displayName:"Command<deleteSelectedCellsCommand>",group:"Table"});var yx=z("AddColBefore",()=>()=>Ib);K(yx,{displayName:"Command<addColBeforeCommand>",group:"Table"});var kx=z("AddColAfter",()=>()=>al);K(kx,{displayName:"Command<addColAfterCommand>",group:"Table"});var bx=z("AddRowBefore",t=>()=>(e,n)=>{if(!De(e))return!1;if(n){let r=At(e);n(cx(t,e.tr,r,r.top))}return!0});K(bx,{displayName:"Command<addRowBeforeCommand>",group:"Table"});var xx=z("AddRowAfter",t=>()=>(e,n)=>{if(!De(e))return!1;if(n){let r=At(e);n(cx(t,e.tr,r,r.bottom))}return!0});K(xx,{displayName:"Command<addRowAfterCommand>",group:"Table"});var wx=z("SetAlign",()=>(t="left")=>Nb("alignment",t));K(wx,{displayName:"Command<setAlignCommand>",group:"Table"});var Cx=ge(t=>new be(/^\|(?<col>\d+)[xX](?<row>\d+)\|\s$/,(e,n,r,i)=>{let o=e.doc.resolve(r);if(!o.node(-1).canReplaceWith(o.index(-1),o.indexAfter(-1),xn.type(t)))return null;let s=ax(t,Math.max(Number(n.groups?.row??0),2),Number(n.groups?.col)),a=e.tr.replaceRangeWith(r,i,s);return a.setSelection(B.create(a.doc,r+3)).scrollIntoView()}));K(Cx,{displayName:"InputRule<insertTableInputRule>",group:"Table"});var Sx=Ok(t=>({run:(e,n,r)=>{if(r)return e;function i(c){let u=c.childCount,f=c.lastChild?.childCount??0;if(u===0||f===0)return Bt.type(t).create();let d=c.firstChild;if(!(f>0&&d&&d.childCount===0))return c;if(u>=3){let g=c.child(1),y=[];for(let v=0;v<g.childCount;v++){let A=g.child(v);y.push(ji.type(t).create(A.attrs,A.content,A.marks))}let b=d.type.create(d.attrs,y),C=[];for(let v=2;v<u;v++)C.push(c.child(v));return c.type.create(c.attrs,[b,...C])}let p=Array(f).fill(0).map(()=>ji.type(t).createAndFill()),h=new R(M.from(p),0,0),m=d.replace(0,0,h);return c.replace(0,d.nodeSize,new R(M.from(m),0,0))}function o(c){let u=Vi.type(t),f=[],d=[],p=!1;function h(){if(d.length===0)return;let m=is.type(t).createAndFill(),g=xn.type(t).create(null,[m,...d]);f.push(i(g)),d=[]}return c.forEach(m=>{m.type===u?(p=!0,d.push(m)):(h(),f.push(m))}),h(),p?M.from(f):c}function s(c){let u=o(c),f=u!==c,d=[];return u.forEach(p=>{if(p.type===xn.type(t)){let h=i(p);h!==p&&(f=!0),d.push(h)}else if(p.childCount>0){let h=s(p.content);h!==p.content?(f=!0,d.push(p.copy(h))):d.push(p)}else d.push(p)}),f?M.from(d):c}function a(c){let u=[],f=[];c.forEach(d=>f.push(d));for(let d=0;d<f.length;d++){let p=f[d],h=f[d+1];p.type===Bt.type(t)&&p.content.size===0&&h&&h.type===xn.type(t)||u.push(p)}return u.length<f.length?M.from(u):c}let l=s(e.content);return l=a(l),new R(M.from(l),e.openStart,e.openEnd)}}));K(Sx,{displayName:"PasteRule<table>",group:"Table"});var zd=We("tableKeymap",{NextCell:{priority:100,shortcuts:["Mod-]","Tab"],command:t=>{let e=t.get(Q);return()=>e.call(Bd.key)}},PrevCell:{shortcuts:["Mod-[","Shift-Tab"],command:t=>{let e=t.get(Q);return()=>e.call(Pd.key)}},ExitTable:{shortcuts:["Mod-Enter","Enter"],command:t=>{let e=t.get(Q);return()=>e.call(Fd.key)}}});K(zd.ctx,{displayName:"KeymapCtx<table>",group:"Table"});K(zd.shortcuts,{displayName:"Keymap<table>",group:"Table"});var Nd="footnote_definition",ox="footnoteDefinition",_d=ce("footnote_definition",()=>({group:"block",content:"block+",defining:!0,attrs:{label:{default:"",validate:"string"}},parseDOM:[{tag:`dl[data-type="${Nd}"]`,getAttrs:t=>{if(!(t instanceof HTMLElement))throw pt(t);return{label:t.dataset.label}},contentElement:"dd"}],toDOM:t=>{let e=t.attrs.label;return["dl",{"data-label":e,"data-type":Nd},["dt",e],["dd",0]]},parseMarkdown:{match:({type:t})=>t===ox,runner:(t,e,n)=>{t.openNode(n,{label:e.label}).next(e.children).closeNode()}},toMarkdown:{match:t=>t.type.name===Nd,runner:(t,e)=>{t.openNode(ox,void 0,{label:e.attrs.label,identifier:e.attrs.label}).next(e.content).closeNode()}}}));K(_d.ctx,{displayName:"NodeSchemaCtx<footnodeDef>",group:"footnote"});K(_d.node,{displayName:"NodeSchema<footnodeDef>",group:"footnote"});var Rd="footnote_reference",$d=ce("footnote_reference",()=>({group:"inline",inline:!0,atom:!0,attrs:{label:{default:"",validate:"string"}},parseDOM:[{tag:`sup[data-type="${Rd}"]`,getAttrs:t=>{if(!(t instanceof HTMLElement))throw pt(t);return{label:t.dataset.label}}}],toDOM:t=>{let e=t.attrs.label;return["sup",{"data-label":e,"data-type":Rd},e]},parseMarkdown:{match:({type:t})=>t==="footnoteReference",runner:(t,e,n)=>{t.addNode(n,{label:e.label})}},toMarkdown:{match:t=>t.type.name===Rd,runner:(t,e)=>{t.addNode("footnoteReference",void 0,void 0,{label:e.attrs.label,identifier:e.attrs.label})}}}));K($d.ctx,{displayName:"NodeSchemaCtx<footnodeRef>",group:"footnote"});K($d.node,{displayName:"NodeSchema<footnodeRef>",group:"footnote"});var Hd=qt.extendSchema(t=>e=>{let n=t(e);return{...n,attrs:{...n.attrs,checked:{default:null,validate:"boolean|null"}},parseDOM:[{tag:'li[data-item-type="task"]',getAttrs:r=>{if(!(r instanceof HTMLElement))throw pt(r);return{label:r.dataset.label,listType:r.dataset.listType,spread:r.dataset.spread,checked:r.dataset.checked?r.dataset.checked==="true":null}}},...n?.parseDOM||[]],toDOM:r=>n.toDOM&&r.attrs.checked==null?n.toDOM(r):["li",{"data-item-type":"task","data-label":r.attrs.label,"data-list-type":r.attrs.listType,"data-spread":r.attrs.spread,"data-checked":r.attrs.checked},0],parseMarkdown:{match:({type:r})=>r==="listItem",runner:(r,i,o)=>{if(i.checked==null){n.parseMarkdown.runner(r,i,o);return}let s=i.label!=null?`${i.label}.`:"\u2022",a=i.checked!=null?!!i.checked:null,l=i.label!=null?"ordered":"bullet",c=i.spread!=null?`${i.spread}`:"true";r.openNode(o,{label:s,listType:l,spread:c,checked:a}),r.next(i.children),r.closeNode()}},toMarkdown:{match:r=>r.type.name==="list_item",runner:(r,i)=>{if(i.attrs.checked==null){n.toMarkdown.runner(r,i);return}let o=i.attrs.label,s=i.attrs.listType,a=i.attrs.spread==="true",l=i.attrs.checked;r.openNode("listItem",void 0,{label:o,listType:s,spread:a,checked:l}),r.next(i.content),r.closeNode()}}}});K(Hd.node,{displayName:"NodeSchema<taskListItem>",group:"ListItem"});K(Hd.ctx,{displayName:"NodeSchemaCtx<taskListItem>",group:"ListItem"});var Mx=ge(()=>new be(/^\[(?<checked>\s|x)\]\s$/,(t,e,n,r)=>{let i=t.doc.resolve(n),o=0,s=i.node(o);for(;s&&s.type.name!=="list_item";)o--,s=i.node(o);if(!s||s.attrs.checked!=null)return null;let a=e.groups?.checked==="x",l=i.before(o),c=t.tr;return c.deleteRange(n,r).setNodeMarkup(l,void 0,{...s.attrs,checked:a}),c}));K(Mx,{displayName:"InputRule<wrapInTaskListInputRule>",group:"ListItem"});var bN=[Ld,zd].flat(),xN=[Cx,Mx],wN=[sx],CN=[Sx],Ex=pe(()=>_b);K(Ex,{displayName:"Prose<autoInsertSpanPlugin>",group:"Prose"});var SN=pe(()=>Pb({}));K(SN,{displayName:"Prose<columnResizingPlugin>",group:"Prose"});var Tx=pe(()=>Fb({allowTableNodeSelection:!0}));K(Tx,{displayName:"Prose<tableEditingPlugin>",group:"Prose"});var Wd=gt("remarkGFM",()=>pl);K(Wd.plugin,{displayName:"Remark<remarkGFMPlugin>",group:"Remark"});K(Wd.options,{displayName:"RemarkConfig<remarkGFMPlugin>",group:"Remark"});var MN=new ee("MILKDOWN_KEEP_TABLE_ALIGN_PLUGIN");function EN(t,e){let n=0;return e.forEach((r,i,o)=>{r===t&&(n=o)}),n}var vx=pe(()=>new X({key:MN,appendTransaction:(t,e,n)=>{let r,i=(o,s)=>{if(r||(r=n.tr),o.type.name!=="table_cell")return;let a=n.doc.resolve(s),l=a.node(a.depth),c=a.node(a.depth-1).firstChild;if(!c)return;let u=EN(o,l),f=c.maybeChild(u);if(!f)return;let d=f.attrs.alignment;d!==o.attrs.alignment&&r.setNodeMarkup(s,void 0,{...o.attrs,alignment:d})};return e.doc!==n.doc&&n.doc.descendants(i),r}}));K(vx,{displayName:"Prose<keepTableAlignPlugin>",group:"Prose"});var TN=[vx,Ex,Wd,Tx].flat(),vN=[Hd,xn,is,Vi,ji,ss,_d,$d,Od,ns].flat(),AN=[Bd,Pd,Fd,ux,fx,dx,px,hx,mx,gx,bx,xx,yx,kx,wx,Dd],Ax=[vN,xN,CN,wN,bN,AN,TN].flat();var IN=typeof global=="object"&&global&&global.Object===Object&&global,Ix=IN;var NN=typeof self=="object"&&self&&self.Object===Object&&self,RN=Ix||NN||Function("return this")(),hl=RN;var ON=hl.Symbol,qi=ON;var Nx=Object.prototype,DN=Nx.hasOwnProperty,LN=Nx.toString,as=qi?qi.toStringTag:void 0;function PN(t){var e=DN.call(t,as),n=t[as];try{t[as]=void 0;var r=!0}catch{}var i=LN.call(t);return r&&(e?t[as]=n:delete t[as]),i}var Rx=PN;var BN=Object.prototype,FN=BN.toString;function zN(t){return FN.call(t)}var Ox=zN;var _N="[object Null]",$N="[object Undefined]",Dx=qi?qi.toStringTag:void 0;function HN(t){return t==null?t===void 0?$N:_N:Dx&&Dx in Object(t)?Rx(t):Ox(t)}var Lx=HN;function WN(t){return t!=null&&typeof t=="object"}var Px=WN;var jN="[object Symbol]";function VN(t){return typeof t=="symbol"||Px(t)&&Lx(t)==jN}var Bx=VN;var qN=/\s/;function KN(t){for(var e=t.length;e--&&qN.test(t.charAt(e)););return e}var Fx=KN;var UN=/^\s+/;function JN(t){return t&&t.slice(0,Fx(t)+1).replace(UN,"")}var zx=JN;function GN(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var ls=GN;var _x=NaN,XN=/^[-+]0x[0-9a-f]+$/i,YN=/^0b[01]+$/i,QN=/^0o[0-7]+$/i,ZN=parseInt;function eR(t){if(typeof t=="number")return t;if(Bx(t))return _x;if(ls(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=ls(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=zx(t);var n=YN.test(t);return n||QN.test(t)?ZN(t.slice(2),n?2:8):XN.test(t)?_x:+t}var jd=eR;var tR=function(){return hl.Date.now()},ml=tR;var nR="Expected a function",rR=Math.max,iR=Math.min;function oR(t,e,n){var r,i,o,s,a,l,c=0,u=!1,f=!1,d=!0;if(typeof t!="function")throw new TypeError(nR);e=jd(e)||0,ls(n)&&(u=!!n.leading,f="maxWait"in n,o=f?rR(jd(n.maxWait)||0,e):o,d="trailing"in n?!!n.trailing:d);function p(w){var N=r,P=i;return r=i=void 0,c=w,s=t.apply(P,N),s}function h(w){return c=w,a=setTimeout(y,e),u?p(w):s}function m(w){var N=w-l,P=w-c,O=e-N;return f?iR(O,o-P):O}function g(w){var N=w-l,P=w-c;return l===void 0||N>=e||N<0||f&&P>=o}function y(){var w=ml();if(g(w))return b(w);a=setTimeout(y,m(w))}function b(w){return a=void 0,d&&r?p(w):(r=i=void 0,s)}function C(){a!==void 0&&clearTimeout(a),c=0,r=l=i=a=void 0}function v(){return a===void 0?s:b(ml())}function A(){var w=ml(),N=g(w);if(r=arguments,i=this,l=w,N){if(a===void 0)return h(l);if(f)return clearTimeout(a),a=setTimeout(y,e),p(l)}return a===void 0&&(a=setTimeout(y,e)),s}return A.cancel=C,A.flush=v,A}var cs=oR;var $x=class{constructor(){this.beforeMountedListeners=[],this.mountedListeners=[],this.updatedListeners=[],this.selectionUpdatedListeners=[],this.markdownUpdatedListeners=[],this.blurListeners=[],this.focusListeners=[],this.destroyListeners=[],this.beforeMount=t=>(this.beforeMountedListeners.push(t),this),this.mounted=t=>(this.mountedListeners.push(t),this),this.updated=t=>(this.updatedListeners.push(t),this)}get listeners(){return{beforeMount:this.beforeMountedListeners,mounted:this.mountedListeners,updated:this.updatedListeners,markdownUpdated:this.markdownUpdatedListeners,blur:this.blurListeners,focus:this.focusListeners,destroy:this.destroyListeners,selectionUpdated:this.selectionUpdatedListeners}}markdownUpdated(t){return this.markdownUpdatedListeners.push(t),this}blur(t){return this.blurListeners.push(t),this}focus(t){return this.focusListeners.push(t),this}destroy(t){return this.destroyListeners.push(t),this}selectionUpdated(t){return this.selectionUpdatedListeners.push(t),this}},gl=Y(new $x,"listener"),sR=new ee("MILKDOWN_LISTENER"),Vd=t=>(t.inject(gl,new $x),async()=>{await t.wait(mn);let{listeners:e}=t.get(gl);e.beforeMount.forEach(c=>c(t)),await t.wait(Ii);let n=t.get(gn),r=null,i=null,o=null,s=null,a=cs(()=>{if(!s)return;let{doc:c}=s;if(e.updated.length>0&&r&&!r.eq(c)&&e.updated.forEach(u=>{u(t,c,r)}),e.markdownUpdated.length>0&&r&&!r.eq(c)){let u=n(c);e.markdownUpdated.forEach(f=>{f(t,u,i)}),i=u}r=c,s=null},200),l=new X({key:sR,view:()=>({destroy:()=>{a.cancel(),e.destroy.forEach(c=>c(t))}}),props:{handleDOMEvents:{focus:()=>(e.focus.forEach(c=>c(t)),!1),blur:()=>(e.blur.forEach(c=>c(t)),!1)}},state:{init:(c,u)=>{r=u.doc,i=n(u.doc)},apply:c=>{let u=c.selection;(!o&&u||o&&!u.eq(o))&&(e.selectionUpdated.forEach(f=>{f(t,u,o)}),o=u),!(!(c.docChanged||c.storedMarksSet)||c.getMeta("addToHistory")===!1)&&(s=c,a())}}});t.update(Lt,c=>c.concat(l)),await t.wait(Jo),e.mounted.forEach(c=>c(t))});Vd.meta={package:"@milkdown/plugin-listener",displayName:"Listener"};var yl=200,je=function(){};je.prototype.append=function(e){return e.length?(e=je.from(e),!this.length&&e||e.length<yl&&this.leafAppend(e)||this.length<yl&&e.leafPrepend(this)||this.appendInner(e)):this};je.prototype.prepend=function(e){return e.length?je.from(e).append(this):this};je.prototype.appendInner=function(e){return new aR(this,e)};je.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?je.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};je.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};je.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)};je.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(o,s){return i.push(e(o,s))},n,r),i};je.from=function(e){return e instanceof je?e:e&&e.length?new Hx(e):je.empty};var Hx=(function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,o){return i==0&&o==this.length?this:new e(this.values.slice(i,o))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,o,s,a){for(var l=o;l<s;l++)if(i(this.values[l],a+l)===!1)return!1},e.prototype.forEachInvertedInner=function(i,o,s,a){for(var l=o-1;l>=s;l--)if(i(this.values[l],a+l)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=yl)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=yl)return new e(i.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e})(je);je.empty=new Hx([]);var aR=(function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,i,o,s){var a=this.left.length;if(i<a&&this.left.forEachInner(r,i,Math.min(o,a),s)===!1||o>a&&this.right.forEachInner(r,Math.max(i-a,0),Math.min(this.length,o)-a,s+a)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,o,s){var a=this.left.length;if(i>a&&this.right.forEachInvertedInner(r,i-a,Math.max(o,a)-a,s+a)===!1||o<a&&this.left.forEachInvertedInner(r,Math.min(i,a),o,s)===!1)return!1},e.prototype.sliceInner=function(r,i){if(r==0&&i==this.length)return this;var o=this.left.length;return i<=o?this.left.slice(r,i):r>=o?this.right.slice(r-o,i-o):this.left.slice(r,o).append(this.right.slice(0,i-o))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(je),qd=je;var lR=500,_r=class t{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,o;n&&(i=this.remapping(r,this.items.length),o=i.maps.length);let s=e.tr,a,l,c=[],u=[];return this.items.forEach((f,d)=>{if(!f.step){i||(i=this.remapping(r,d+1),o=i.maps.length),o--,u.push(f);return}if(i){u.push(new Ut(f.map));let p=f.step.map(i.slice(o)),h;p&&s.maybeStep(p).doc&&(h=s.mapping.maps[s.mapping.maps.length-1],c.push(new Ut(h,void 0,void 0,c.length+u.length))),o--,h&&i.appendMap(h,o)}else s.maybeStep(f.step);if(f.selection)return a=i?f.selection.map(i.slice(o)):f.selection,l=new t(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:l,transform:s,selection:a}}addTransform(e,n,r,i){let o=[],s=this.eventCount,a=this.items,l=!i&&a.length?a.get(a.length-1):null;for(let u=0;u<e.steps.length;u++){let f=e.steps[u].invert(e.docs[u]),d=new Ut(e.mapping.maps[u],f,n),p;(p=l&&l.merge(d))&&(d=p,u?o.pop():a=a.slice(0,a.length-1)),o.push(d),n&&(s++,n=void 0),i||(l=d)}let c=s-r.depth;return c>uR&&(a=cR(a,c),s-=c),new t(a.append(o),s)}remapping(e,n){let r=new No;return this.items.forEach((i,o)=>{let s=i.mirrorOffset!=null&&o-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,s)},e,n),r}addMaps(e){return this.eventCount==0?this:new t(this.items.append(e.map(n=>new Ut(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-n),o=e.mapping,s=e.steps.length,a=this.eventCount;this.items.forEach(d=>{d.selection&&a--},i);let l=n;this.items.forEach(d=>{let p=o.getMirror(--l);if(p==null)return;s=Math.min(s,p);let h=o.maps[p];if(d.step){let m=e.steps[p].invert(e.docs[p]),g=d.selection&&d.selection.map(o.slice(l+1,p));g&&a++,r.push(new Ut(h,m,g))}else r.push(new Ut(h))},i);let c=[];for(let d=n;d<s;d++)c.push(new Ut(o.maps[d]));let u=this.items.slice(0,i).append(c).append(r),f=new t(u,a);return f.emptyItemCount()>lR&&(f=f.compress(this.items.length-r.length)),f}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,i=[],o=0;return this.items.forEach((s,a)=>{if(a>=e)i.push(s),s.selection&&o++;else if(s.step){let l=s.step.map(n.slice(r)),c=l&&l.getMap();if(r--,c&&n.appendMap(c,r),l){let u=s.selection&&s.selection.map(n.slice(r));u&&o++;let f=new Ut(c.invert(),l,u),d,p=i.length-1;(d=i.length&&i[p].merge(f))?i[p]=d:i.push(f)}}else s.map&&r--},this.items.length,0),new t(qd.from(i.reverse()),o)}};_r.empty=new _r(qd.empty,0);function cR(t,e){let n;return t.forEach((r,i)=>{if(r.selection&&e--==0)return n=i,!1}),t.slice(n)}var Ut=class t{constructor(e,n,r,i){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new t(n.getMap().invert(),n,this.selection)}}},Jt=class{constructor(e,n,r,i,o){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=i,this.prevComposition=o}},uR=20;function fR(t,e,n,r){let i=n.getMeta(zr),o;if(i)return i.historyState;n.getMeta(Vx)&&(t=new Jt(t.done,t.undone,null,0,-1));let s=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(s&&s.getMeta(zr))return s.getMeta(zr).redo?new Jt(t.done.addTransform(n,void 0,r,kl(e)),t.undone,Wx(n.mapping.maps),t.prevTime,t.prevComposition):new Jt(t.done,t.undone.addTransform(n,void 0,r,kl(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(s&&s.getMeta("addToHistory")===!1)){let a=n.getMeta("composition"),l=t.prevTime==0||!s&&t.prevComposition!=a&&(t.prevTime<(n.time||0)-r.newGroupDelay||!dR(n,t.prevRanges)),c=s?Kd(t.prevRanges,n.mapping):Wx(n.mapping.maps);return new Jt(t.done.addTransform(n,l?e.selection.getBookmark():void 0,r,kl(e)),_r.empty,c,n.time,a??t.prevComposition)}else return(o=n.getMeta("rebased"))?new Jt(t.done.rebased(n,o),t.undone.rebased(n,o),Kd(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new Jt(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),Kd(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function dR(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,i)=>{for(let o=0;o<e.length;o+=2)r<=e[o+1]&&i>=e[o]&&(n=!0)}),n}function Wx(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,i,o,s)=>e.push(o,s));return e}function Kd(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let i=e.map(t[r],1),o=e.map(t[r+1],-1);i<=o&&n.push(i,o)}return n}function pR(t,e,n){let r=kl(e),i=zr.get(e).spec.config,o=(n?t.undone:t.done).popEvent(e,r);if(!o)return null;let s=o.selection.resolve(o.transform.doc),a=(n?t.done:t.undone).addTransform(o.transform,e.selection.getBookmark(),i,r),l=new Jt(n?a:o.remaining,n?o.remaining:a,null,0,-1);return o.transform.setSelection(s).setMeta(zr,{redo:n,historyState:l})}var Ud=!1,jx=null;function kl(t){let e=t.plugins;if(jx!=e){Ud=!1,jx=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){Ud=!0;break}}return Ud}function us(t){return t.setMeta(Vx,!0)}var zr=new ee("history"),Vx=new ee("closeHistory");function qx(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new X({key:zr,state:{init(){return new Jt(_r.empty,_r.empty,null,0,-1)},apply(e,n,r){return fR(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,i=r=="historyUndo"?fs:r=="historyRedo"?ds:null;return!i||!e.editable?!1:(n.preventDefault(),i(e.state,e.dispatch))}}}})}function bl(t,e){return(n,r)=>{let i=zr.getState(n);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(r){let o=pR(i,n,t);o&&r(e?o.scrollIntoView():o)}return!0}}var fs=bl(!1,!0),ds=bl(!0,!0),p3=bl(!1,!1),h3=bl(!0,!1);function Ki(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-history",...e}}),t}var Jd=z("Undo",()=>()=>fs);Ki(Jd,{displayName:"Command<undo>"});var Gd=z("Redo",()=>()=>ds);Ki(Gd,{displayName:"Command<redo>"});var Xd=Ae({},"historyProviderConfig");Ki(Xd,{displayName:"Ctx<historyProviderConfig>"});var Kx=pe(t=>qx(t.get(Xd.key)));Ki(Kx,{displayName:"Ctx<historyProviderPlugin>"});var Yd=We("historyKeymap",{Undo:{shortcuts:"Mod-z",command:t=>{let e=t.get(Q);return()=>e.call(Jd.key)}},Redo:{shortcuts:["Mod-y","Shift-Mod-z"],command:t=>{let e=t.get(Q);return()=>e.call(Gd.key)}}});Ki(Yd.ctx,{displayName:"KeymapCtx<history>"});Ki(Yd.shortcuts,{displayName:"Keymap<history>"});var Ux=[Xd,Kx,Yd,Jd,Gd].flat();function Qd(t){if(!t)return!1;if(Array.isArray(t))return t.length>1?!1:Qd(t[0]);let e=t.content;return e?Qd(e):t.type==="text"}function hR(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-clipboard",...e}}),t}function Jx(t,e){let n=Sa(e);if(n)return t.dispatch(t.state.tr.replaceSelectionWith(n,!0)),!0;try{return t.dispatch(t.state.tr.replaceSelection(e)),!0}catch{return!1}}var Zd=pe(t=>{let e=t.get($e);return t.update(Or,n=>({...n,editable:n.editable??(()=>!0),transformPastedHTML:(r,i)=>{let o=n.transformPastedHTML;return o&&(r=o(r,i)),r.includes("docs-internal-guid")&&(r=r.replace(/<b[^>]*id="docs-internal-guid[^"]*"[^>]*>([\s\S]*)<\/b>/,"$1"),r=r.replace(/<div[^>]*>(<table[\s\S]*?<\/table>)<\/div>/g,"$1")),r}})),new X({key:new ee("MILKDOWN_CLIPBOARD"),props:{handlePaste:(n,r,i)=>{let o=t.get(He),s=n.props.editable?.(n.state),{clipboardData:a}=r;if(!s||!a||n.state.selection.$from.node().type.spec.code)return!1;let l=a.getData("text/plain"),c=a.getData("vscode-editor-data");if(c){let p=JSON.parse(c)?.mode;if(l&&p){let{tr:h}=n.state,m=Ug("code_block",e);return h.replaceSelectionWith(m.create({language:p})).setSelection(B.near(h.doc.resolve(Math.max(0,h.selection.from-2)))).insertText(l.replace(/\r\n?/g,` -`)),n.dispatch(h),!0}}let u=a.getData("text/html");if(u.length===0&&l.length===0)return!1;if(u.length>0&&i)return Jx(n,i);let f=wt.fromSchema(e),d;if(u.length===0){let p=o(l);if(!p||typeof p=="string")return!1;d=Ct.fromSchema(e).serializeFragment(p.content)}else{let p=document.createElement("template");p.innerHTML=u,d=p.content.cloneNode(!0),p.remove()}return Jx(n,f.parseSlice(d))},clipboardTextSerializer:n=>{let r=t.get(gn);if(Qd(n.content.toJSON()))return n.content.textBetween(0,n.content.size,` +`))}function l(p,h,m,g){let y=m.enter("tableCell"),b=m.enter("phrasing"),C=m.containerPhrasing(p,{...g,before:o,after:o});return b(),y(),C}function c(p,h){return Kb(p,{align:h,alignDelimiters:r,padding:n,stringLength:i})}function u(p,h,m){let g=p.children,y=-1,b=[],C=h.enter("table");for(;++y<g.length;)b[y]=f(g[y],h,m);return C(),b}function f(p,h,m){let g=p.children,y=-1,b=[],C=h.enter("tableRow");for(;++y<g.length;)b[y]=l(g[y],p,h,m);return C(),b}function d(p,h,m){let g=cr.inlineCode(p,h,m);return m.stack.includes("tableCell")&&(g=g.replace(/\|/g,"\\$&")),g}}function bd(){return{exit:{taskListCheckValueChecked:Jb,taskListCheckValueUnchecked:Jb,paragraph:jI}}}function xd(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:VI}}}function Jb(t){let e=this.stack[this.stack.length-2];e.type,e.checked=t.type==="taskListCheckValueChecked"}function jI(t){let e=this.stack[this.stack.length-2];if(e&&e.type==="listItem"&&typeof e.checked=="boolean"){let n=this.stack[this.stack.length-1];n.type;let r=n.children[0];if(r&&r.type==="text"){let i=e.children,o=-1,s;for(;++o<i.length;){let a=i[o];if(a.type==="paragraph"){s=a;break}}s===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(t)}function VI(t,e,n,r){let i=t.children[0],o=typeof t.checked=="boolean"&&i&&i.type==="paragraph",s="["+(t.checked?"x":" ")+"] ",a=n.createTracker(r);o&&a.move(s);let l=cr.listItem(t,e,n,{...r,...a.current()});return o&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,c)),l;function c(u){return u+s}}function wd(){return[ud(),dd(),hd(),yd(),bd()]}function Cd(t){return{extensions:[fd(),pd(t),md(),kd(t),xd()]}}var qI={tokenize:XI,partial:!0},Gb={tokenize:YI,partial:!0},Xb={tokenize:QI,partial:!0},Yb={tokenize:ZI,partial:!0},KI={tokenize:eN,partial:!0},Qb={name:"wwwAutolink",tokenize:JI,previous:ex},Zb={name:"protocolAutolink",tokenize:GI,previous:tx},bn={name:"emailAutolink",tokenize:UI,previous:nx},Kt={};function Md(){return{text:Kt}}var Fr=48;for(;Fr<123;)Kt[Fr]=bn,Fr++,Fr===58?Fr=65:Fr===91&&(Fr=97);Kt[43]=bn;Kt[45]=bn;Kt[46]=bn;Kt[95]=bn;Kt[72]=[bn,Zb];Kt[104]=[bn,Zb];Kt[87]=[bn,Qb];Kt[119]=[bn,Qb];function UI(t,e,n){let r=this,i,o;return s;function s(f){return!Sd(f)||!nx.call(r,r.previous)||Ed(r.events)?n(f):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),a(f))}function a(f){return Sd(f)?(t.consume(f),a):f===64?(t.consume(f),l):n(f)}function l(f){return f===46?t.check(KI,u,c)(f):f===45||f===95||Ae(f)?(o=!0,t.consume(f),l):u(f)}function c(f){return t.consume(f),i=!0,l}function u(f){return o&&i&&ve(r.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),e(f)):n(f)}}function JI(t,e,n){let r=this;return i;function i(s){return s!==87&&s!==119||!ex.call(r,r.previous)||Ed(r.events)?n(s):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(qI,t.attempt(Gb,t.attempt(Xb,o),n),n)(s))}function o(s){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),e(s)}}function GI(t,e,n){let r=this,i="",o=!1;return s;function s(f){return(f===72||f===104)&&tx.call(r,r.previous)&&!Ed(r.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),i+=String.fromCodePoint(f),t.consume(f),a):n(f)}function a(f){if(ve(f)&&i.length<5)return i+=String.fromCodePoint(f),t.consume(f),a;if(f===58){let d=i.toLowerCase();if(d==="http"||d==="https")return t.consume(f),l}return n(f)}function l(f){return f===47?(t.consume(f),o?c:(o=!0,l)):n(f)}function c(f){return f===null||tr(f)||Z(f)||Wt(f)||nr(f)?n(f):t.attempt(Gb,t.attempt(Xb,u),n)(f)}function u(f){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),e(f)}}function XI(t,e,n){let r=0;return i;function i(s){return(s===87||s===119)&&r<3?(r++,t.consume(s),i):s===46&&r===3?(t.consume(s),o):n(s)}function o(s){return s===null?n(s):e(s)}}function YI(t,e,n){let r,i,o;return s;function s(c){return c===46||c===95?t.check(Yb,l,a)(c):c===null||Z(c)||Wt(c)||c!==45&&nr(c)?l(c):(o=!0,t.consume(c),s)}function a(c){return c===95?r=!0:(i=r,r=void 0),t.consume(c),s}function l(c){return i||r||!o?n(c):e(c)}}function QI(t,e){let n=0,r=0;return i;function i(s){return s===40?(n++,t.consume(s),i):s===41&&r<n?o(s):s===33||s===34||s===38||s===39||s===41||s===42||s===44||s===46||s===58||s===59||s===60||s===63||s===93||s===95||s===126?t.check(Yb,e,o)(s):s===null||Z(s)||Wt(s)?e(s):(t.consume(s),i)}function o(s){return s===41&&r++,t.consume(s),i}}function ZI(t,e,n){return r;function r(a){return a===33||a===34||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===63||a===95||a===126?(t.consume(a),r):a===38?(t.consume(a),o):a===93?(t.consume(a),i):a===60||a===null||Z(a)||Wt(a)?e(a):n(a)}function i(a){return a===null||a===40||a===91||Z(a)||Wt(a)?e(a):r(a)}function o(a){return ve(a)?s(a):n(a)}function s(a){return a===59?(t.consume(a),r):ve(a)?(t.consume(a),s):n(a)}}function eN(t,e,n){return r;function r(o){return t.consume(o),i}function i(o){return Ae(o)?n(o):e(o)}}function ex(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Z(t)}function tx(t){return!ve(t)}function nx(t){return!(t===47||Sd(t))}function Sd(t){return t===43||t===45||t===46||t===95||Ae(t)}function Ed(t){let e=t.length,n=!1;for(;e--;){let r=t[e][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return t.length>0&&!n&&(t[t.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var tN={tokenize:lN,partial:!0};function Td(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:oN,continuation:{tokenize:sN},exit:aN}},text:{91:{name:"gfmFootnoteCall",tokenize:iN},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:nN,resolveTo:rN}}}}function nN(t,e,n){let r=this,i=r.events.length,o=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),s;for(;i--;){let l=r.events[i][1];if(l.type==="labelImage"){s=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return a;function a(l){if(!s||!s._balanced)return n(l);let c=qe(r.sliceSerialize({start:s.end,end:r.now()}));return c.codePointAt(0)!==94||!o.includes(c.slice(1))?n(l):(t.enter("gfmFootnoteCallLabelMarker"),t.consume(l),t.exit("gfmFootnoteCallLabelMarker"),e(l))}}function rN(t,e){let n=t.length,r;for(;n--;)if(t[n][1].type==="labelImage"&&t[n][0]==="enter"){r=t[n][1];break}t[n+1][1].type="data",t[n+3][1].type="gfmFootnoteCallLabelMarker";let i={type:"gfmFootnoteCall",start:Object.assign({},t[n+3][1].start),end:Object.assign({},t[t.length-1][1].end)},o={type:"gfmFootnoteCallMarker",start:Object.assign({},t[n+3][1].end),end:Object.assign({},t[n+3][1].end)};o.end.column++,o.end.offset++,o.end._bufferIndex++;let s={type:"gfmFootnoteCallString",start:Object.assign({},o.end),end:Object.assign({},t[t.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},l=[t[n+1],t[n+2],["enter",i,e],t[n+3],t[n+4],["enter",o,e],["exit",o,e],["enter",s,e],["enter",a,e],["exit",a,e],["exit",s,e],t[t.length-2],t[t.length-1],["exit",i,e]];return t.splice(n,t.length-n+1,...l),t}function iN(t,e,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o=0,s;return a;function a(f){return t.enter("gfmFootnoteCall"),t.enter("gfmFootnoteCallLabelMarker"),t.consume(f),t.exit("gfmFootnoteCallLabelMarker"),l}function l(f){return f!==94?n(f):(t.enter("gfmFootnoteCallMarker"),t.consume(f),t.exit("gfmFootnoteCallMarker"),t.enter("gfmFootnoteCallString"),t.enter("chunkString").contentType="string",c)}function c(f){if(o>999||f===93&&!s||f===null||f===91||Z(f))return n(f);if(f===93){t.exit("chunkString");let d=t.exit("gfmFootnoteCallString");return i.includes(qe(r.sliceSerialize(d)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(f),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),e):n(f)}return Z(f)||(s=!0),o++,t.consume(f),f===92?u:c}function u(f){return f===91||f===92||f===93?(t.consume(f),o++,c):c(f)}}function oN(t,e,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o,s=0,a;return l;function l(h){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(h){return h===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",u):n(h)}function u(h){if(s>999||h===93&&!a||h===null||h===91||Z(h))return n(h);if(h===93){t.exit("chunkString");let m=t.exit("gfmFootnoteDefinitionLabelString");return o=qe(r.sliceSerialize(m)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(h),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),d}return Z(h)||(a=!0),s++,t.consume(h),h===92?f:u}function f(h){return h===91||h===92||h===93?(t.consume(h),s++,u):u(h)}function d(h){return h===58?(t.enter("definitionMarker"),t.consume(h),t.exit("definitionMarker"),i.includes(o)||i.push(o),_(t,p,"gfmFootnoteDefinitionWhitespace")):n(h)}function p(h){return e(h)}}function sN(t,e,n){return t.check(jt,e,t.attempt(tN,e,n))}function aN(t){t.exit("gfmFootnoteDefinition")}function lN(t,e,n){let r=this;return _(t,i,"gfmFootnoteDefinitionIndent",5);function i(o){let s=r.events[r.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?e(o):n(o)}}function vd(t){let n=(t||{}).singleTilde,r={name:"strikethrough",tokenize:o,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(s,a){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let c=l;for(;c--;)if(s[c][0]==="exit"&&s[c][1].type==="strikethroughSequenceTemporary"&&s[c][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[c][1].end.offset-s[c][1].start.offset){s[l][1].type="strikethroughSequence",s[c][1].type="strikethroughSequence";let u={type:"strikethrough",start:Object.assign({},s[c][1].start),end:Object.assign({},s[l][1].end)},f={type:"strikethroughText",start:Object.assign({},s[c][1].end),end:Object.assign({},s[l][1].start)},d=[["enter",u,a],["enter",s[c][1],a],["exit",s[c][1],a],["enter",f,a]],p=a.parser.constructs.insideSpan.null;p&&be(d,d.length,0,vn(p,s.slice(c+1,l),a)),be(d,d.length,0,[["exit",f,a],["enter",s[l][1],a],["exit",s[l][1],a],["exit",u,a]]),be(s,c-1,l-c+3,d),l=c+d.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type="data");return s}function o(s,a,l){let c=this.previous,u=this.events,f=0;return d;function d(h){return c===126&&u[u.length-1][1].type!=="characterEscape"?l(h):(s.enter("strikethroughSequenceTemporary"),p(h))}function p(h){let m=on(c);if(h===126)return f>1?l(h):(s.consume(h),f++,p);if(f<2&&!n)return l(h);let g=s.exit("strikethroughSequenceTemporary"),y=on(h);return g._open=!y||y===2&&!!m,g._close=!m||m===2&&!!y,a(h)}}}var fl=class{constructor(){this.map=[]}add(e,n,r){cN(this,e,n,r)}consume(e){if(this.map.sort(function(o,s){return o[0]-s[0]}),this.map.length===0)return;let n=this.map.length,r=[];for(;n>0;)n-=1,r.push(e.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),e.length=this.map[n][0];r.push(e.slice()),e.length=0;let i=r.pop();for(;i;){for(let o of i)e.push(o);i=r.pop()}this.map.length=0}};function cN(t,e,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i<t.map.length;){if(t.map[i][0]===e){t.map[i][1]+=n,t.map[i][2].push(...r);return}i+=1}t.map.push([e,n,r])}}function rx(t,e){let n=!1,r=[];for(;e<t.length;){let i=t[e];if(n){if(i[0]==="enter")i[1].type==="tableContent"&&r.push(t[e+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(t[e-1][1].type==="tableDelimiterMarker"){let o=r.length-1;r[o]=r[o]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(n=!0);e+=1}return r}function Ad(){return{flow:{null:{name:"table",tokenize:uN,resolveAll:fN}}}}function uN(t,e,n){let r=this,i=0,o=0,s;return a;function a(S){let me=r.events.length-1;for(;me>-1;){let W=r.events[me][1].type;if(W==="lineEnding"||W==="linePrefix")me--;else break}let te=me>-1?r.events[me][1].type:null,F=te==="tableHead"||te==="tableRow"?w:l;return F===w&&r.parser.lazy[r.now().line]?n(S):F(S)}function l(S){return t.enter("tableHead"),t.enter("tableRow"),c(S)}function c(S){return S===124||(s=!0,o+=1),u(S)}function u(S){return S===null?n(S):D(S)?o>1?(o=0,r.interrupt=!0,t.exit("tableRow"),t.enter("lineEnding"),t.consume(S),t.exit("lineEnding"),p):n(S):j(S)?_(t,u,"whitespace")(S):(o+=1,s&&(s=!1,i+=1),S===124?(t.enter("tableCellDivider"),t.consume(S),t.exit("tableCellDivider"),s=!0,u):(t.enter("data"),f(S)))}function f(S){return S===null||S===124||Z(S)?(t.exit("data"),u(S)):(t.consume(S),S===92?d:f)}function d(S){return S===92||S===124?(t.consume(S),f):f(S)}function p(S){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(S):(t.enter("tableDelimiterRow"),s=!1,j(S)?_(t,h,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):h(S))}function h(S){return S===45||S===58?g(S):S===124?(s=!0,t.enter("tableCellDivider"),t.consume(S),t.exit("tableCellDivider"),m):A(S)}function m(S){return j(S)?_(t,g,"whitespace")(S):g(S)}function g(S){return S===58?(o+=1,s=!0,t.enter("tableDelimiterMarker"),t.consume(S),t.exit("tableDelimiterMarker"),y):S===45?(o+=1,y(S)):S===null||D(S)?v(S):A(S)}function y(S){return S===45?(t.enter("tableDelimiterFiller"),b(S)):A(S)}function b(S){return S===45?(t.consume(S),b):S===58?(s=!0,t.exit("tableDelimiterFiller"),t.enter("tableDelimiterMarker"),t.consume(S),t.exit("tableDelimiterMarker"),C):(t.exit("tableDelimiterFiller"),C(S))}function C(S){return j(S)?_(t,v,"whitespace")(S):v(S)}function v(S){return S===124?h(S):S===null||D(S)?!s||i!==o?A(S):(t.exit("tableDelimiterRow"),t.exit("tableHead"),e(S)):A(S)}function A(S){return n(S)}function w(S){return t.enter("tableRow"),N(S)}function N(S){return S===124?(t.enter("tableCellDivider"),t.consume(S),t.exit("tableCellDivider"),N):S===null||D(S)?(t.exit("tableRow"),e(S)):j(S)?_(t,N,"whitespace")(S):(t.enter("data"),P(S))}function P(S){return S===null||S===124||Z(S)?(t.exit("data"),N(S)):(t.consume(S),S===92?O:P)}function O(S){return S===92||S===124?(t.consume(S),P):P(S)}}function fN(t,e){let n=-1,r=!0,i=0,o=[0,0,0,0],s=[0,0,0,0],a=!1,l=0,c,u,f,d=new fl;for(;++n<t.length;){let p=t[n],h=p[1];p[0]==="enter"?h.type==="tableHead"?(a=!1,l!==0&&(ix(d,e,l,c,u),u=void 0,l=0),c={type:"table",start:Object.assign({},h.start),end:Object.assign({},h.end)},d.add(n,0,[["enter",c,e]])):h.type==="tableRow"||h.type==="tableDelimiterRow"?(r=!0,f=void 0,o=[0,0,0,0],s=[0,n+1,0,0],a&&(a=!1,u={type:"tableBody",start:Object.assign({},h.start),end:Object.assign({},h.end)},d.add(n,0,[["enter",u,e]])),i=h.type==="tableDelimiterRow"?2:u?3:1):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")?(r=!1,s[2]===0&&(o[1]!==0&&(s[0]=s[1],f=dl(d,e,o,i,void 0,f),o=[0,0,0,0]),s[2]=n)):h.type==="tableCellDivider"&&(r?r=!1:(o[1]!==0&&(s[0]=s[1],f=dl(d,e,o,i,void 0,f)),o=s,s=[o[1],n,0,0])):h.type==="tableHead"?(a=!0,l=n):h.type==="tableRow"||h.type==="tableDelimiterRow"?(l=n,o[1]!==0?(s[0]=s[1],f=dl(d,e,o,i,n,f)):s[1]!==0&&(f=dl(d,e,s,i,n,f)),i=0):i&&(h.type==="data"||h.type==="tableDelimiterMarker"||h.type==="tableDelimiterFiller")&&(s[3]=n)}for(l!==0&&ix(d,e,l,c,u),d.consume(e.events),n=-1;++n<e.events.length;){let p=e.events[n];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=rx(e.events,n))}return t}function dl(t,e,n,r,i,o){let s=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",a="tableContent";n[0]!==0&&(o.end=Object.assign({},Wi(e.events,n[0])),t.add(n[0],0,[["exit",o,e]]));let l=Wi(e.events,n[1]);if(o={type:s,start:Object.assign({},l),end:Object.assign({},l)},t.add(n[1],0,[["enter",o,e]]),n[2]!==0){let c=Wi(e.events,n[2]),u=Wi(e.events,n[3]),f={type:a,start:Object.assign({},c),end:Object.assign({},u)};if(t.add(n[2],0,[["enter",f,e]]),r!==2){let d=e.events[n[2]],p=e.events[n[3]];if(d[1].end=Object.assign({},p[1].end),d[1].type="chunkText",d[1].contentType="text",n[3]>n[2]+1){let h=n[2]+1,m=n[3]-n[2]-1;t.add(h,m,[])}}t.add(n[3]+1,0,[["exit",f,e]])}return i!==void 0&&(o.end=Object.assign({},Wi(e.events,i)),t.add(i,0,[["exit",o,e]]),o=void 0),o}function ix(t,e,n,r,i){let o=[],s=Wi(e.events,n);i&&(i.end=Object.assign({},s),o.push(["exit",i,e])),r.end=Object.assign({},s),o.push(["exit",r,e]),t.add(n+1,0,o)}function Wi(t,e){let n=t[e],r=n[0]==="enter"?"start":"end";return n[1][r]}var dN={name:"tasklistCheck",tokenize:pN};function Id(){return{text:{91:dN}}}function pN(t,e,n){let r=this;return i;function i(l){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(l):(t.enter("taskListCheck"),t.enter("taskListCheckMarker"),t.consume(l),t.exit("taskListCheckMarker"),o)}function o(l){return Z(l)?(t.enter("taskListCheckValueUnchecked"),t.consume(l),t.exit("taskListCheckValueUnchecked"),s):l===88||l===120?(t.enter("taskListCheckValueChecked"),t.consume(l),t.exit("taskListCheckValueChecked"),s):n(l)}function s(l){return l===93?(t.enter("taskListCheckMarker"),t.consume(l),t.exit("taskListCheckMarker"),t.exit("taskListCheck"),a):n(l)}function a(l){return D(l)?e(l):j(l)?t.check({tokenize:hN},e,n)(l):n(l)}}function hN(t,e,n){return _(t,r,"whitespace");function r(i){return i===null?n(i):e(i)}}function ox(t){return $s([Md(),Td(),vd(t),Ad(),Id()])}var mN={};function pl(t){let e=this,n=t||mN,r=e.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),o=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),s=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(ox(n)),o.push(wd()),s.push(Cd(n))}function K(t,e){return Object.assign(t,{meta:{package:"@milkdown/preset-gfm",...e}}),t}var Od=Dr("strike_through");K(Od,{displayName:"Attr<strikethrough>",group:"Strikethrough"});var ns=Pt("strike_through",t=>({parseDOM:[{tag:"del"},{style:"text-decoration",getAttrs:e=>e==="line-through"}],toDOM:e=>["del",t.get(Od.key)(e)],parseMarkdown:{match:e=>e.type==="delete",runner:(e,n,r)=>{e.openMark(r),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="strike_through",runner:(e,n)=>{e.withMark(n,"delete")}}}));K(ns.mark,{displayName:"MarkSchema<strikethrough>",group:"Strikethrough"});K(ns.ctx,{displayName:"MarkSchemaCtx<strikethrough>",group:"Strikethrough"});var Dd=z("ToggleStrikeThrough",t=>()=>Ln(ns.type(t)));K(Dd,{displayName:"Command<ToggleStrikethrough>",group:"Strikethrough"});var ax=ge(t=>ln(/(?<![\w:/])(~{1,2})(.+?)\1(?!\w|\/)/,ns.type(t)));K(ax,{displayName:"InputRule<strikethrough>",group:"Strikethrough"});var Ld=We("strikeThroughKeymap",{ToggleStrikethrough:{shortcuts:"Mod-Alt-x",command:t=>{let e=t.get(Q);return()=>e.call(Dd.key)}}});K(Ld.ctx,{displayName:"KeymapCtx<strikethrough>",group:"Strikethrough"});K(Ld.shortcuts,{displayName:"Keymap<strikethrough>",group:"Strikethrough"});var rs=Cb({tableGroup:"block",cellContent:"paragraph",cellAttributes:{alignment:{default:"left",getFromDOM:t=>t.style.textAlign||"left",setDOMAttr:(t,e)=>{e.style=`text-align: ${t||"left"}`}}}}),xn=ce("table",()=>({...rs.table,content:"table_header_row table_row+",disableDropCursor:!0,parseMarkdown:{match:t=>t.type==="table",runner:(t,e,n)=>{let r=e.align,i=e.children.map((o,s)=>({...o,align:r,isHeader:s===0}));t.openNode(n),t.next(i),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table",runner:(t,e)=>{let n=e.content.firstChild?.content;if(!n)return;let r=[];n.forEach(i=>{r.push(i.attrs.alignment)}),t.openNode("table",void 0,{align:r}),t.next(e.content),t.closeNode()}}}));K(xn.node,{displayName:"NodeSchema<table>",group:"Table"});K(xn.ctx,{displayName:"NodeSchemaCtx<table>",group:"Table"});var is=ce("table_header_row",()=>({...rs.table_row,disableDropCursor:!0,content:"(table_header)*",parseDOM:[{tag:"tr[data-is-header]"},{tag:"tr",getAttrs:t=>t instanceof HTMLElement&&t.querySelector("th")?{}:!1}],toDOM(){return["tr",{"data-is-header":!0},0]},parseMarkdown:{match:t=>!!(t.type==="tableRow"&&t.isHeader),runner:(t,e,n)=>{let r=e.align,i=e.children.map((o,s)=>({...o,align:r[s],isHeader:e.isHeader}));t.openNode(n),t.next(i),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table_header_row",runner:(t,e)=>{e.content.size!==0&&(t.openNode("tableRow",void 0,{isHeader:!0}),t.next(e.content),t.closeNode())}}}));K(is.node,{displayName:"NodeSchema<tableHeaderRow>",group:"Table"});K(is.ctx,{displayName:"NodeSchemaCtx<tableHeaderRow>",group:"Table"});var Vi=ce("table_row",()=>({...rs.table_row,disableDropCursor:!0,content:"(table_cell)*",parseMarkdown:{match:t=>t.type==="tableRow",runner:(t,e,n)=>{let r=e.align,i=e.children.map((o,s)=>({...o,align:r[s]}));t.openNode(n),t.next(i),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table_row",runner:(t,e)=>{e.content.size!==0&&(t.openNode("tableRow"),t.next(e.content),t.closeNode())}}}));K(Vi.node,{displayName:"NodeSchema<tableRow>",group:"Table"});K(Vi.ctx,{displayName:"NodeSchemaCtx<tableRow>",group:"Table"});var ss=ce("table_cell",()=>({...rs.table_cell,disableDropCursor:!0,parseMarkdown:{match:t=>t.type==="tableCell"&&!t.isHeader,runner:(t,e,n)=>{let r=e.align;t.openNode(n,{alignment:r}).openNode(t.schema.nodes.paragraph).next(e.children).closeNode().closeNode()}},toMarkdown:{match:t=>t.type.name==="table_cell",runner:(t,e)=>{t.openNode("tableCell").next(e.content).closeNode()}}}));K(ss.node,{displayName:"NodeSchema<tableCell>",group:"Table"});K(ss.ctx,{displayName:"NodeSchemaCtx<tableCell>",group:"Table"});var ji=ce("table_header",()=>({...rs.table_header,disableDropCursor:!0,parseMarkdown:{match:t=>t.type==="tableCell"&&!!t.isHeader,runner:(t,e,n)=>{let r=e.align;t.openNode(n,{alignment:r}),t.openNode(t.schema.nodes.paragraph),t.next(e.children),t.closeNode(),t.closeNode()}},toMarkdown:{match:t=>t.type.name==="table_header",runner:(t,e)=>{t.openNode("tableCell"),t.next(e.content),t.closeNode()}}}));K(ji.node,{displayName:"NodeSchema<tableHeader>",group:"Table"});K(ji.ctx,{displayName:"NodeSchemaCtx<tableHeader>",group:"Table"});function lx(t,e=3,n=3){let r=Array(n).fill(0).map(()=>ss.type(t).createAndFill()),i=Array(n).fill(0).map(()=>ji.type(t).createAndFill()),o=Array(e).fill(0).map((s,a)=>a===0?is.type(t).create(null,i):Vi.type(t).create(null,r));return xn.type(t).create(null,o)}function cx(t){return(e,n)=>r=>{n=n??r.selection.from;let i=r.doc.resolve(n),o=cu(l=>l.type.name==="table")(i),s=o?{node:o.node,from:o.start}:void 0,a=t==="row";if(s){let l=oe.get(s.node);if(e>=0&&e<(a?l.height:l.width)){let c=l.positionAt(a?e:l.height-1,a?l.width-1:e,s.node),u=r.doc.resolve(s.from+c),f=a?he.rowSelection:he.colSelection,d=l.positionAt(a?e:0,a?0:e,s.node),p=r.doc.resolve(s.from+d);return lu(r.setSelection(f(u,p)))}}return r}}var gN=cx("row"),yN=cx("col");function ux(t,e,{map:n,tableStart:r,table:i},o){let s=Array(o).fill(0).reduce((l,c,u)=>l+i.child(u).nodeSize,r),a=Array(n.width).fill(0).map((l,c)=>{let u=i.nodeAt(n.map[c]);return ss.type(t).createAndFill({alignment:u?.attrs.alignment})});return e.insert(s,Vi.type(t).create(null,a)),e}function kN(t){let e=Hi(t.$from);if(!e)return;let n=oe.get(e.node);return n.cellsInRect({left:0,right:n.width,top:0,bottom:n.height}).map(r=>{let i=e.node.nodeAt(r),o=r+e.start;return{pos:o,start:o+1,node:i}})}function bN(t){let e=kN(t.selection);if(e&&e[0]){let n=t.doc.resolve(e[0].pos),r=e[e.length-1];if(r){let i=t.doc.resolve(r.pos);return lu(t.setSelection(new he(i,n)))}}return t}var Pd=z("GoToPrevTableCell",()=>()=>ts(-1));K(Pd,{displayName:"Command<goToPrevTableCellCommand>",group:"Table"});var Bd=z("GoToNextTableCell",()=>()=>ts(1));K(Bd,{displayName:"Command<goToNextTableCellCommand>",group:"Table"});var Fd=z("ExitTable",t=>()=>(e,n)=>{if(!De(e))return!1;let{$head:r}=e.selection,i=Ug(r,xn.type(t));if(!i)return!1;let{to:o}=i,s=e.tr.replaceWith(o,o,Bt.type(t).createAndFill());return s.setSelection($.near(s.doc.resolve(o),1)).scrollIntoView(),n?.(s),!0});K(Fd,{displayName:"Command<breakTableCommand>",group:"Table"});var fx=z("InsertTable",t=>({row:e,col:n}={})=>(r,i)=>{let{selection:o,tr:s}=r,{from:a}=o,l=lx(t,e,n),c=s.replaceSelectionWith(l),u=$.findFrom(c.doc.resolve(a),1,!0);return u&&c.setSelection(u),i?.(c),!0});K(fx,{displayName:"Command<insertTableCommand>",group:"Table"});var dx=z("MoveRow",()=>({from:t,to:e,pos:n}={})=>Db({from:t??0,to:e??0,pos:n}));K(dx,{displayName:"Command<moveRowCommand>",group:"Table"});var px=z("MoveCol",()=>({from:t,to:e,pos:n}={})=>Lb({from:t??0,to:e??0,pos:n}));K(px,{displayName:"Command<moveColCommand>",group:"Table"});var hx=z("SelectRow",()=>(t={index:0})=>(e,n)=>{let{tr:r}=e;return!!n?.(gN(t.index,t.pos)(r))});K(hx,{displayName:"Command<selectRowCommand>",group:"Table"});var mx=z("SelectCol",()=>(t={index:0})=>(e,n)=>{let{tr:r}=e;return!!n?.(yN(t.index,t.pos)(r))});K(mx,{displayName:"Command<selectColCommand>",group:"Table"});var gx=z("SelectTable",()=>()=>(t,e)=>{let{tr:n}=t;return!!e?.(bN(n))});K(gx,{displayName:"Command<selectTableCommand>",group:"Table"});var yx=z("DeleteSelectedCells",()=>()=>(t,e)=>{let{selection:n}=t;if(!(n instanceof he))return!1;let r=n.isRowSelection(),i=n.isColSelection();return r&&i?Ob(t,e):i?ll(t,e):cl(t,e)});K(yx,{displayName:"Command<deleteSelectedCellsCommand>",group:"Table"});var kx=z("AddColBefore",()=>()=>Nb);K(kx,{displayName:"Command<addColBeforeCommand>",group:"Table"});var bx=z("AddColAfter",()=>()=>al);K(bx,{displayName:"Command<addColAfterCommand>",group:"Table"});var xx=z("AddRowBefore",t=>()=>(e,n)=>{if(!De(e))return!1;if(n){let r=At(e);n(ux(t,e.tr,r,r.top))}return!0});K(xx,{displayName:"Command<addRowBeforeCommand>",group:"Table"});var wx=z("AddRowAfter",t=>()=>(e,n)=>{if(!De(e))return!1;if(n){let r=At(e);n(ux(t,e.tr,r,r.bottom))}return!0});K(wx,{displayName:"Command<addRowAfterCommand>",group:"Table"});var Cx=z("SetAlign",()=>(t="left")=>Rb("alignment",t));K(Cx,{displayName:"Command<setAlignCommand>",group:"Table"});var Sx=ge(t=>new xe(/^\|(?<col>\d+)[xX](?<row>\d+)\|\s$/,(e,n,r,i)=>{let o=e.doc.resolve(r);if(!o.node(-1).canReplaceWith(o.index(-1),o.indexAfter(-1),xn.type(t)))return null;let s=lx(t,Math.max(Number(n.groups?.row??0),2),Number(n.groups?.col)),a=e.tr.replaceRangeWith(r,i,s);return a.setSelection(B.create(a.doc,r+3)).scrollIntoView()}));K(Sx,{displayName:"InputRule<insertTableInputRule>",group:"Table"});var Mx=Dk(t=>({run:(e,n,r)=>{if(r)return e;function i(c){let u=c.childCount,f=c.lastChild?.childCount??0;if(u===0||f===0)return Bt.type(t).create();let d=c.firstChild;if(!(f>0&&d&&d.childCount===0))return c;if(u>=3){let g=c.child(1),y=[];for(let v=0;v<g.childCount;v++){let A=g.child(v);y.push(ji.type(t).create(A.attrs,A.content,A.marks))}let b=d.type.create(d.attrs,y),C=[];for(let v=2;v<u;v++)C.push(c.child(v));return c.type.create(c.attrs,[b,...C])}let p=Array(f).fill(0).map(()=>ji.type(t).createAndFill()),h=new R(M.from(p),0,0),m=d.replace(0,0,h);return c.replace(0,d.nodeSize,new R(M.from(m),0,0))}function o(c){let u=Vi.type(t),f=[],d=[],p=!1;function h(){if(d.length===0)return;let m=is.type(t).createAndFill(),g=xn.type(t).create(null,[m,...d]);f.push(i(g)),d=[]}return c.forEach(m=>{m.type===u?(p=!0,d.push(m)):(h(),f.push(m))}),h(),p?M.from(f):c}function s(c){let u=o(c),f=u!==c,d=[];return u.forEach(p=>{if(p.type===xn.type(t)){let h=i(p);h!==p&&(f=!0),d.push(h)}else if(p.childCount>0){let h=s(p.content);h!==p.content?(f=!0,d.push(p.copy(h))):d.push(p)}else d.push(p)}),f?M.from(d):c}function a(c){let u=[],f=[];c.forEach(d=>f.push(d));for(let d=0;d<f.length;d++){let p=f[d],h=f[d+1];p.type===Bt.type(t)&&p.content.size===0&&h&&h.type===xn.type(t)||u.push(p)}return u.length<f.length?M.from(u):c}let l=s(e.content);return l=a(l),new R(M.from(l),e.openStart,e.openEnd)}}));K(Mx,{displayName:"PasteRule<table>",group:"Table"});var zd=We("tableKeymap",{NextCell:{priority:100,shortcuts:["Mod-]","Tab"],command:t=>{let e=t.get(Q);return()=>e.call(Bd.key)}},PrevCell:{shortcuts:["Mod-[","Shift-Tab"],command:t=>{let e=t.get(Q);return()=>e.call(Pd.key)}},ExitTable:{shortcuts:["Mod-Enter","Enter"],command:t=>{let e=t.get(Q);return()=>e.call(Fd.key)}}});K(zd.ctx,{displayName:"KeymapCtx<table>",group:"Table"});K(zd.shortcuts,{displayName:"Keymap<table>",group:"Table"});var Nd="footnote_definition",sx="footnoteDefinition",_d=ce("footnote_definition",()=>({group:"block",content:"block+",defining:!0,attrs:{label:{default:"",validate:"string"}},parseDOM:[{tag:`dl[data-type="${Nd}"]`,getAttrs:t=>{if(!(t instanceof HTMLElement))throw pt(t);return{label:t.dataset.label}},contentElement:"dd"}],toDOM:t=>{let e=t.attrs.label;return["dl",{"data-label":e,"data-type":Nd},["dt",e],["dd",0]]},parseMarkdown:{match:({type:t})=>t===sx,runner:(t,e,n)=>{t.openNode(n,{label:e.label}).next(e.children).closeNode()}},toMarkdown:{match:t=>t.type.name===Nd,runner:(t,e)=>{t.openNode(sx,void 0,{label:e.attrs.label,identifier:e.attrs.label}).next(e.content).closeNode()}}}));K(_d.ctx,{displayName:"NodeSchemaCtx<footnodeDef>",group:"footnote"});K(_d.node,{displayName:"NodeSchema<footnodeDef>",group:"footnote"});var Rd="footnote_reference",$d=ce("footnote_reference",()=>({group:"inline",inline:!0,atom:!0,attrs:{label:{default:"",validate:"string"}},parseDOM:[{tag:`sup[data-type="${Rd}"]`,getAttrs:t=>{if(!(t instanceof HTMLElement))throw pt(t);return{label:t.dataset.label}}}],toDOM:t=>{let e=t.attrs.label;return["sup",{"data-label":e,"data-type":Rd},e]},parseMarkdown:{match:({type:t})=>t==="footnoteReference",runner:(t,e,n)=>{t.addNode(n,{label:e.label})}},toMarkdown:{match:t=>t.type.name===Rd,runner:(t,e)=>{t.addNode("footnoteReference",void 0,void 0,{label:e.attrs.label,identifier:e.attrs.label})}}}));K($d.ctx,{displayName:"NodeSchemaCtx<footnodeRef>",group:"footnote"});K($d.node,{displayName:"NodeSchema<footnodeRef>",group:"footnote"});var Hd=qt.extendSchema(t=>e=>{let n=t(e);return{...n,attrs:{...n.attrs,checked:{default:null,validate:"boolean|null"}},parseDOM:[{tag:'li[data-item-type="task"]',getAttrs:r=>{if(!(r instanceof HTMLElement))throw pt(r);return{label:r.dataset.label,listType:r.dataset.listType,spread:r.dataset.spread,checked:r.dataset.checked?r.dataset.checked==="true":null}}},...n?.parseDOM||[]],toDOM:r=>n.toDOM&&r.attrs.checked==null?n.toDOM(r):["li",{"data-item-type":"task","data-label":r.attrs.label,"data-list-type":r.attrs.listType,"data-spread":r.attrs.spread,"data-checked":r.attrs.checked},0],parseMarkdown:{match:({type:r})=>r==="listItem",runner:(r,i,o)=>{if(i.checked==null){n.parseMarkdown.runner(r,i,o);return}let s=i.label!=null?`${i.label}.`:"\u2022",a=i.checked!=null?!!i.checked:null,l=i.label!=null?"ordered":"bullet",c=i.spread!=null?`${i.spread}`:"true";r.openNode(o,{label:s,listType:l,spread:c,checked:a}),r.next(i.children),r.closeNode()}},toMarkdown:{match:r=>r.type.name==="list_item",runner:(r,i)=>{if(i.attrs.checked==null){n.toMarkdown.runner(r,i);return}let o=i.attrs.label,s=i.attrs.listType,a=i.attrs.spread==="true",l=i.attrs.checked;r.openNode("listItem",void 0,{label:o,listType:s,spread:a,checked:l}),r.next(i.content),r.closeNode()}}}});K(Hd.node,{displayName:"NodeSchema<taskListItem>",group:"ListItem"});K(Hd.ctx,{displayName:"NodeSchemaCtx<taskListItem>",group:"ListItem"});var Ex=ge(()=>new xe(/^\[(?<checked>\s|x)\]\s$/,(t,e,n,r)=>{let i=t.doc.resolve(n),o=0,s=i.node(o);for(;s&&s.type.name!=="list_item";)o--,s=i.node(o);if(!s||s.attrs.checked!=null)return null;let a=e.groups?.checked==="x",l=i.before(o),c=t.tr;return c.deleteRange(n,r).setNodeMarkup(l,void 0,{...s.attrs,checked:a}),c}));K(Ex,{displayName:"InputRule<wrapInTaskListInputRule>",group:"ListItem"});var xN=[Ld,zd].flat(),wN=[Sx,Ex],CN=[ax],SN=[Mx],Tx=pe(()=>$b);K(Tx,{displayName:"Prose<autoInsertSpanPlugin>",group:"Prose"});var MN=pe(()=>Bb({}));K(MN,{displayName:"Prose<columnResizingPlugin>",group:"Prose"});var vx=pe(()=>zb({allowTableNodeSelection:!0}));K(vx,{displayName:"Prose<tableEditingPlugin>",group:"Prose"});var Wd=gt("remarkGFM",()=>pl);K(Wd.plugin,{displayName:"Remark<remarkGFMPlugin>",group:"Remark"});K(Wd.options,{displayName:"RemarkConfig<remarkGFMPlugin>",group:"Remark"});var EN=new ee("MILKDOWN_KEEP_TABLE_ALIGN_PLUGIN");function TN(t,e){let n=0;return e.forEach((r,i,o)=>{r===t&&(n=o)}),n}var Ax=pe(()=>new X({key:EN,appendTransaction:(t,e,n)=>{let r,i=(o,s)=>{if(r||(r=n.tr),o.type.name!=="table_cell")return;let a=n.doc.resolve(s),l=a.node(a.depth),c=a.node(a.depth-1).firstChild;if(!c)return;let u=TN(o,l),f=c.maybeChild(u);if(!f)return;let d=f.attrs.alignment;d!==o.attrs.alignment&&r.setNodeMarkup(s,void 0,{...o.attrs,alignment:d})};return e.doc!==n.doc&&n.doc.descendants(i),r}}));K(Ax,{displayName:"Prose<keepTableAlignPlugin>",group:"Prose"});var vN=[Ax,Tx,Wd,vx].flat(),AN=[Hd,xn,is,Vi,ji,ss,_d,$d,Od,ns].flat(),IN=[Bd,Pd,Fd,fx,dx,px,hx,mx,gx,yx,xx,wx,kx,bx,Cx,Dd],Ix=[AN,wN,SN,CN,xN,IN,vN].flat();var NN=typeof global=="object"&&global&&global.Object===Object&&global,Nx=NN;var RN=typeof self=="object"&&self&&self.Object===Object&&self,ON=Nx||RN||Function("return this")(),hl=ON;var DN=hl.Symbol,qi=DN;var Rx=Object.prototype,LN=Rx.hasOwnProperty,PN=Rx.toString,as=qi?qi.toStringTag:void 0;function BN(t){var e=LN.call(t,as),n=t[as];try{t[as]=void 0;var r=!0}catch{}var i=PN.call(t);return r&&(e?t[as]=n:delete t[as]),i}var Ox=BN;var FN=Object.prototype,zN=FN.toString;function _N(t){return zN.call(t)}var Dx=_N;var $N="[object Null]",HN="[object Undefined]",Lx=qi?qi.toStringTag:void 0;function WN(t){return t==null?t===void 0?HN:$N:Lx&&Lx in Object(t)?Ox(t):Dx(t)}var Px=WN;function jN(t){return t!=null&&typeof t=="object"}var Bx=jN;var VN="[object Symbol]";function qN(t){return typeof t=="symbol"||Bx(t)&&Px(t)==VN}var Fx=qN;var KN=/\s/;function UN(t){for(var e=t.length;e--&&KN.test(t.charAt(e)););return e}var zx=UN;var JN=/^\s+/;function GN(t){return t&&t.slice(0,zx(t)+1).replace(JN,"")}var _x=GN;function XN(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var ls=XN;var $x=NaN,YN=/^[-+]0x[0-9a-f]+$/i,QN=/^0b[01]+$/i,ZN=/^0o[0-7]+$/i,eR=parseInt;function tR(t){if(typeof t=="number")return t;if(Fx(t))return $x;if(ls(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=ls(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=_x(t);var n=QN.test(t);return n||ZN.test(t)?eR(t.slice(2),n?2:8):YN.test(t)?$x:+t}var jd=tR;var nR=function(){return hl.Date.now()},ml=nR;var rR="Expected a function",iR=Math.max,oR=Math.min;function sR(t,e,n){var r,i,o,s,a,l,c=0,u=!1,f=!1,d=!0;if(typeof t!="function")throw new TypeError(rR);e=jd(e)||0,ls(n)&&(u=!!n.leading,f="maxWait"in n,o=f?iR(jd(n.maxWait)||0,e):o,d="trailing"in n?!!n.trailing:d);function p(w){var N=r,P=i;return r=i=void 0,c=w,s=t.apply(P,N),s}function h(w){return c=w,a=setTimeout(y,e),u?p(w):s}function m(w){var N=w-l,P=w-c,O=e-N;return f?oR(O,o-P):O}function g(w){var N=w-l,P=w-c;return l===void 0||N>=e||N<0||f&&P>=o}function y(){var w=ml();if(g(w))return b(w);a=setTimeout(y,m(w))}function b(w){return a=void 0,d&&r?p(w):(r=i=void 0,s)}function C(){a!==void 0&&clearTimeout(a),c=0,r=l=i=a=void 0}function v(){return a===void 0?s:b(ml())}function A(){var w=ml(),N=g(w);if(r=arguments,i=this,l=w,N){if(a===void 0)return h(l);if(f)return clearTimeout(a),a=setTimeout(y,e),p(l)}return a===void 0&&(a=setTimeout(y,e)),s}return A.cancel=C,A.flush=v,A}var cs=sR;var Hx=class{constructor(){this.beforeMountedListeners=[],this.mountedListeners=[],this.updatedListeners=[],this.selectionUpdatedListeners=[],this.markdownUpdatedListeners=[],this.blurListeners=[],this.focusListeners=[],this.destroyListeners=[],this.beforeMount=t=>(this.beforeMountedListeners.push(t),this),this.mounted=t=>(this.mountedListeners.push(t),this),this.updated=t=>(this.updatedListeners.push(t),this)}get listeners(){return{beforeMount:this.beforeMountedListeners,mounted:this.mountedListeners,updated:this.updatedListeners,markdownUpdated:this.markdownUpdatedListeners,blur:this.blurListeners,focus:this.focusListeners,destroy:this.destroyListeners,selectionUpdated:this.selectionUpdatedListeners}}markdownUpdated(t){return this.markdownUpdatedListeners.push(t),this}blur(t){return this.blurListeners.push(t),this}focus(t){return this.focusListeners.push(t),this}destroy(t){return this.destroyListeners.push(t),this}selectionUpdated(t){return this.selectionUpdatedListeners.push(t),this}},gl=Y(new Hx,"listener"),aR=new ee("MILKDOWN_LISTENER"),Vd=t=>(t.inject(gl,new Hx),async()=>{await t.wait(mn);let{listeners:e}=t.get(gl);e.beforeMount.forEach(c=>c(t)),await t.wait(Ii);let n=t.get(gn),r=null,i=null,o=null,s=null,a=cs(()=>{if(!s)return;let{doc:c}=s;if(e.updated.length>0&&r&&!r.eq(c)&&e.updated.forEach(u=>{u(t,c,r)}),e.markdownUpdated.length>0&&r&&!r.eq(c)){let u=n(c);e.markdownUpdated.forEach(f=>{f(t,u,i)}),i=u}r=c,s=null},200),l=new X({key:aR,view:()=>({destroy:()=>{a.cancel(),e.destroy.forEach(c=>c(t))}}),props:{handleDOMEvents:{focus:()=>(e.focus.forEach(c=>c(t)),!1),blur:()=>(e.blur.forEach(c=>c(t)),!1)}},state:{init:(c,u)=>{r=u.doc,i=n(u.doc)},apply:c=>{let u=c.selection;(!o&&u||o&&!u.eq(o))&&(e.selectionUpdated.forEach(f=>{f(t,u,o)}),o=u),!(!(c.docChanged||c.storedMarksSet)||c.getMeta("addToHistory")===!1)&&(s=c,a())}}});t.update(Lt,c=>c.concat(l)),await t.wait(Jo),e.mounted.forEach(c=>c(t))});Vd.meta={package:"@milkdown/plugin-listener",displayName:"Listener"};var yl=200,je=function(){};je.prototype.append=function(e){return e.length?(e=je.from(e),!this.length&&e||e.length<yl&&this.leafAppend(e)||this.length<yl&&e.leafPrepend(this)||this.appendInner(e)):this};je.prototype.prepend=function(e){return e.length?je.from(e).append(this):this};je.prototype.appendInner=function(e){return new lR(this,e)};je.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?je.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};je.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};je.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)};je.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(o,s){return i.push(e(o,s))},n,r),i};je.from=function(e){return e instanceof je?e:e&&e.length?new Wx(e):je.empty};var Wx=(function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,o){return i==0&&o==this.length?this:new e(this.values.slice(i,o))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,o,s,a){for(var l=o;l<s;l++)if(i(this.values[l],a+l)===!1)return!1},e.prototype.forEachInvertedInner=function(i,o,s,a){for(var l=o-1;l>=s;l--)if(i(this.values[l],a+l)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=yl)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=yl)return new e(i.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e})(je);je.empty=new Wx([]);var lR=(function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,i,o,s){var a=this.left.length;if(i<a&&this.left.forEachInner(r,i,Math.min(o,a),s)===!1||o>a&&this.right.forEachInner(r,Math.max(i-a,0),Math.min(this.length,o)-a,s+a)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,o,s){var a=this.left.length;if(i>a&&this.right.forEachInvertedInner(r,i-a,Math.max(o,a)-a,s+a)===!1||o<a&&this.left.forEachInvertedInner(r,Math.min(i,a),o,s)===!1)return!1},e.prototype.sliceInner=function(r,i){if(r==0&&i==this.length)return this;var o=this.left.length;return i<=o?this.left.slice(r,i):r>=o?this.right.slice(r-o,i-o):this.left.slice(r,o).append(this.right.slice(0,i-o))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(je),qd=je;var cR=500,_r=class t{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,o;n&&(i=this.remapping(r,this.items.length),o=i.maps.length);let s=e.tr,a,l,c=[],u=[];return this.items.forEach((f,d)=>{if(!f.step){i||(i=this.remapping(r,d+1),o=i.maps.length),o--,u.push(f);return}if(i){u.push(new Ut(f.map));let p=f.step.map(i.slice(o)),h;p&&s.maybeStep(p).doc&&(h=s.mapping.maps[s.mapping.maps.length-1],c.push(new Ut(h,void 0,void 0,c.length+u.length))),o--,h&&i.appendMap(h,o)}else s.maybeStep(f.step);if(f.selection)return a=i?f.selection.map(i.slice(o)):f.selection,l=new t(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:l,transform:s,selection:a}}addTransform(e,n,r,i){let o=[],s=this.eventCount,a=this.items,l=!i&&a.length?a.get(a.length-1):null;for(let u=0;u<e.steps.length;u++){let f=e.steps[u].invert(e.docs[u]),d=new Ut(e.mapping.maps[u],f,n),p;(p=l&&l.merge(d))&&(d=p,u?o.pop():a=a.slice(0,a.length-1)),o.push(d),n&&(s++,n=void 0),i||(l=d)}let c=s-r.depth;return c>fR&&(a=uR(a,c),s-=c),new t(a.append(o),s)}remapping(e,n){let r=new No;return this.items.forEach((i,o)=>{let s=i.mirrorOffset!=null&&o-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,s)},e,n),r}addMaps(e){return this.eventCount==0?this:new t(this.items.append(e.map(n=>new Ut(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-n),o=e.mapping,s=e.steps.length,a=this.eventCount;this.items.forEach(d=>{d.selection&&a--},i);let l=n;this.items.forEach(d=>{let p=o.getMirror(--l);if(p==null)return;s=Math.min(s,p);let h=o.maps[p];if(d.step){let m=e.steps[p].invert(e.docs[p]),g=d.selection&&d.selection.map(o.slice(l+1,p));g&&a++,r.push(new Ut(h,m,g))}else r.push(new Ut(h))},i);let c=[];for(let d=n;d<s;d++)c.push(new Ut(o.maps[d]));let u=this.items.slice(0,i).append(c).append(r),f=new t(u,a);return f.emptyItemCount()>cR&&(f=f.compress(this.items.length-r.length)),f}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,i=[],o=0;return this.items.forEach((s,a)=>{if(a>=e)i.push(s),s.selection&&o++;else if(s.step){let l=s.step.map(n.slice(r)),c=l&&l.getMap();if(r--,c&&n.appendMap(c,r),l){let u=s.selection&&s.selection.map(n.slice(r));u&&o++;let f=new Ut(c.invert(),l,u),d,p=i.length-1;(d=i.length&&i[p].merge(f))?i[p]=d:i.push(f)}}else s.map&&r--},this.items.length,0),new t(qd.from(i.reverse()),o)}};_r.empty=new _r(qd.empty,0);function uR(t,e){let n;return t.forEach((r,i)=>{if(r.selection&&e--==0)return n=i,!1}),t.slice(n)}var Ut=class t{constructor(e,n,r,i){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new t(n.getMap().invert(),n,this.selection)}}},Jt=class{constructor(e,n,r,i,o){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=i,this.prevComposition=o}},fR=20;function dR(t,e,n,r){let i=n.getMeta(zr),o;if(i)return i.historyState;n.getMeta(qx)&&(t=new Jt(t.done,t.undone,null,0,-1));let s=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(s&&s.getMeta(zr))return s.getMeta(zr).redo?new Jt(t.done.addTransform(n,void 0,r,kl(e)),t.undone,jx(n.mapping.maps),t.prevTime,t.prevComposition):new Jt(t.done,t.undone.addTransform(n,void 0,r,kl(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(s&&s.getMeta("addToHistory")===!1)){let a=n.getMeta("composition"),l=t.prevTime==0||!s&&t.prevComposition!=a&&(t.prevTime<(n.time||0)-r.newGroupDelay||!pR(n,t.prevRanges)),c=s?Kd(t.prevRanges,n.mapping):jx(n.mapping.maps);return new Jt(t.done.addTransform(n,l?e.selection.getBookmark():void 0,r,kl(e)),_r.empty,c,n.time,a??t.prevComposition)}else return(o=n.getMeta("rebased"))?new Jt(t.done.rebased(n,o),t.undone.rebased(n,o),Kd(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new Jt(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),Kd(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function pR(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,i)=>{for(let o=0;o<e.length;o+=2)r<=e[o+1]&&i>=e[o]&&(n=!0)}),n}function jx(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,i,o,s)=>e.push(o,s));return e}function Kd(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let i=e.map(t[r],1),o=e.map(t[r+1],-1);i<=o&&n.push(i,o)}return n}function hR(t,e,n){let r=kl(e),i=zr.get(e).spec.config,o=(n?t.undone:t.done).popEvent(e,r);if(!o)return null;let s=o.selection.resolve(o.transform.doc),a=(n?t.done:t.undone).addTransform(o.transform,e.selection.getBookmark(),i,r),l=new Jt(n?a:o.remaining,n?o.remaining:a,null,0,-1);return o.transform.setSelection(s).setMeta(zr,{redo:n,historyState:l})}var Ud=!1,Vx=null;function kl(t){let e=t.plugins;if(Vx!=e){Ud=!1,Vx=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){Ud=!0;break}}return Ud}function us(t){return t.setMeta(qx,!0)}var zr=new ee("history"),qx=new ee("closeHistory");function Kx(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new X({key:zr,state:{init(){return new Jt(_r.empty,_r.empty,null,0,-1)},apply(e,n,r){return dR(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,i=r=="historyUndo"?fs:r=="historyRedo"?ds:null;return!i||!e.editable?!1:(n.preventDefault(),i(e.state,e.dispatch))}}}})}function bl(t,e){return(n,r)=>{let i=zr.getState(n);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(r){let o=hR(i,n,t);o&&r(e?o.scrollIntoView():o)}return!0}}var fs=bl(!1,!0),ds=bl(!0,!0),h3=bl(!1,!1),m3=bl(!0,!1);function Ki(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-history",...e}}),t}var Jd=z("Undo",()=>()=>fs);Ki(Jd,{displayName:"Command<undo>"});var Gd=z("Redo",()=>()=>ds);Ki(Gd,{displayName:"Command<redo>"});var Xd=Ie({},"historyProviderConfig");Ki(Xd,{displayName:"Ctx<historyProviderConfig>"});var Ux=pe(t=>Kx(t.get(Xd.key)));Ki(Ux,{displayName:"Ctx<historyProviderPlugin>"});var Yd=We("historyKeymap",{Undo:{shortcuts:"Mod-z",command:t=>{let e=t.get(Q);return()=>e.call(Jd.key)}},Redo:{shortcuts:["Mod-y","Shift-Mod-z"],command:t=>{let e=t.get(Q);return()=>e.call(Gd.key)}}});Ki(Yd.ctx,{displayName:"KeymapCtx<history>"});Ki(Yd.shortcuts,{displayName:"Keymap<history>"});var Jx=[Xd,Ux,Yd,Jd,Gd].flat();function Qd(t){if(!t)return!1;if(Array.isArray(t))return t.length>1?!1:Qd(t[0]);let e=t.content;return e?Qd(e):t.type==="text"}function mR(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-clipboard",...e}}),t}function Gx(t,e){let n=Sa(e);if(n)return t.dispatch(t.state.tr.replaceSelectionWith(n,!0)),!0;try{return t.dispatch(t.state.tr.replaceSelection(e)),!0}catch{return!1}}var Zd=pe(t=>{let e=t.get($e);return t.update(Or,n=>({...n,editable:n.editable??(()=>!0),transformPastedHTML:(r,i)=>{let o=n.transformPastedHTML;return o&&(r=o(r,i)),r.includes("docs-internal-guid")&&(r=r.replace(/<b[^>]*id="docs-internal-guid[^"]*"[^>]*>([\s\S]*)<\/b>/,"$1"),r=r.replace(/<div[^>]*>(<table[\s\S]*?<\/table>)<\/div>/g,"$1")),r}})),new X({key:new ee("MILKDOWN_CLIPBOARD"),props:{handlePaste:(n,r,i)=>{let o=t.get(He),s=n.props.editable?.(n.state),{clipboardData:a}=r;if(!s||!a||n.state.selection.$from.node().type.spec.code)return!1;let l=a.getData("text/plain"),c=a.getData("vscode-editor-data");if(c){let p=JSON.parse(c)?.mode;if(l&&p){let{tr:h}=n.state,m=Jg("code_block",e);return h.replaceSelectionWith(m.create({language:p})).setSelection(B.near(h.doc.resolve(Math.max(0,h.selection.from-2)))).insertText(l.replace(/\r\n?/g,` +`)),n.dispatch(h),!0}}let u=a.getData("text/html");if(u.length===0&&l.length===0)return!1;if(u.length>0&&i)return Gx(n,i);let f=wt.fromSchema(e),d;if(u.length===0){let p=o(l);if(!p||typeof p=="string")return!1;d=Ct.fromSchema(e).serializeFragment(p.content)}else{let p=document.createElement("template");p.innerHTML=u,d=p.content.cloneNode(!0),p.remove()}return Gx(n,f.parseSlice(d))},clipboardTextSerializer:n=>{let r=t.get(gn);if(Qd(n.content.toJSON()))return n.content.textBetween(0,n.content.size,` -`);let i=e.topNodeType.createAndFill(void 0,n.content);return i?r(i):""}}})});hR(Zd,{displayName:"Prose<clipboard>"});function mR(t){let e=t.schema.cached.changeSetIDs||(t.schema.cached.changeSetIDs=Object.create(null)),n=e[t.name];return n==null&&(e[t.name]=n=Object.keys(t.schema.nodes).indexOf(t.name)+1),n}var Yx={encodeCharacter:t=>t,encodeNodeStart:t=>t.type.name,encodeNodeEnd:t=>-mR(t.type),compareTokens:(t,e)=>t===e};function ep(t,e,n,r,i){for(let o=0,s=0;o<t.childCount;o++){let a=t.child(o),l=s+a.nodeSize,c=Math.max(s,n),u=Math.min(l,r);if(c<u)if(a.isText)for(let f=c;f<u;f++)i.push(e.encodeCharacter(a.text.charCodeAt(f-s),a.marks));else a.isLeaf?i.push(e.encodeNodeStart(a)):(c==s&&i.push(e.encodeNodeStart(a)),ep(a.content,e,Math.max(s+1,c)-s-1,Math.min(l-1,u)-s-1,i),u==l&&i.push(e.encodeNodeEnd(a)));s=l}return i}var gR=5e3;function yR(t,e){return Math.min(15,Math.max(2,Math.floor(Math.max(t,e)/10)))}function Qx(t,e,n,r=Yx){let i=ep(t,r,n.fromA,n.toA,[]),o=ep(e,r,n.fromB,n.toB,[]),s=0,a=i.length,l=o.length,c=r.compareTokens;for(;s<i.length&&s<o.length&&c(i[s],o[s]);)s++;if(s==i.length&&s==o.length)return[];for(;a>s&&l>s&&c(i[a-1],o[l-1]);)a--,l--;if(a==s||l==s||a==l&&a==s+1)return[n.slice(s,a,s,l)];let u=a-s,f=l-s,d=Math.min(gR,u+f),p=d+1,h=[],m=[];for(let g=p*2,y=0;y<g;y++)m[y]=-1;for(let g=0;g<=d;g++){for(let y=-g;y<=g;y+=2){let b=m[y+1+d],C=m[y-1+d],v=b<C?C:b+1,A=v+y;for(;v<u&&A<f&&c(i[s+v],o[s+A]);)v++,A++;if(m[y+d]=v,v>=u&&A>=f){let w=[],N=yR(a-s,l-s),P=-1,O=-1,S=-1,me=-1,te=(F,W,q,se)=>{P>-1&&P<W+N?(P=F,S=q):(P>-1&&w.push(n.slice(P,O,S,me)),P=F,O=W,S=q,me=se)};for(let F=g-1;F>=0;F--){let W=m[y+1+d],q=m[y-1+d];W<q?(y--,v=q+s,A=v+y,te(v,v,A,A+1)):(y++,v=W+s,A=v+y,te(v,v+1,A,A)),m=h[F>>1]}return P>-1&&w.push(n.slice(P,O,S,me)),w.reverse()}}g%2==0&&h.push(m.slice())}return[n.slice(s,a,s,l)]}var Se=class t{constructor(e,n){this.length=e,this.data=n}cut(e){return e==this.length?this:new t(e,this.data)}static slice(e,n,r){if(n==r)return t.none;if(n==0&&r==t.len(e))return e;let i=[];for(let o=0,s=0;s<r;o++){let a=e[o],l=s+a.length,c=Math.min(r,l)-Math.max(n,s);c>0&&i.push(a.cut(c)),s=l}return i}static join(e,n,r){if(e.length==0)return n;if(n.length==0)return e;let i=r(e[e.length-1].data,n[0].data);if(i==null)return e.concat(n);let o=e.slice(0,e.length-1);o.push(new t(e[e.length-1].length+n[0].length,i));for(let s=1;s<n.length;s++)o.push(n[s]);return o}static len(e){let n=0;for(let r=0;r<e.length;r++)n+=e[r].length;return n}};Se.none=[];var Gt=class t{constructor(e,n,r,i,o,s){this.fromA=e,this.toA=n,this.fromB=r,this.toB=i,this.deleted=o,this.inserted=s}get lenA(){return this.toA-this.fromA}get lenB(){return this.toB-this.fromB}slice(e,n,r,i){return e==0&&r==0&&n==this.toA-this.fromA&&i==this.toB-this.fromB?this:new t(this.fromA+e,this.fromA+n,this.fromB+r,this.fromB+i,Se.slice(this.deleted,e,n),Se.slice(this.inserted,r,i))}static merge(e,n,r){if(e.length==0)return n;if(n.length==0)return e;let i=[];for(let o=0,s=0,a=e[0],l=n[0];;){if(!a&&!l)return i;if(a&&(!l||a.toB<l.fromA)){let c=s?n[s-1].toB-n[s-1].toA:0;i.push(c==0?a:new t(a.fromA,a.toA,a.fromB+c,a.toB+c,a.deleted,a.inserted)),a=o++==e.length?null:e[o]}else if(l&&(!a||l.toA<a.fromB)){let c=o?e[o-1].toB-e[o-1].toA:0;i.push(c==0?l:new t(l.fromA-c,l.toA-c,l.fromB,l.toB,l.deleted,l.inserted)),l=s++==n.length?null:n[s]}else{let c=Math.min(a.fromB,l.fromA),u=Math.min(a.fromA,l.fromA-(o?e[o-1].toB-e[o-1].toA:0)),f=u,d=Math.min(l.fromB,a.fromB+(s?n[s-1].toB-n[s-1].toA:0)),p=d,h=Se.none,m=Se.none,g=!1,y=!1;for(;;){let b=a?c>=a.fromB?a.toB:a.fromB:2e8,C=l?c>=l.fromA?l.toA:l.fromA:2e8,v=Math.min(b,C),A=a&&c>=a.fromB,w=l&&c>=l.fromA;if(!A&&!w)break;A&&c==a.fromB&&!g&&(h=Se.join(h,a.deleted,r),f+=a.lenA,g=!0),A&&!w&&(m=Se.join(m,Se.slice(a.inserted,c-a.fromB,v-a.fromB),r),p+=v-c),w&&c==l.fromA&&!y&&(m=Se.join(m,l.inserted,r),p+=l.lenB,y=!0),w&&!A&&(h=Se.join(h,Se.slice(l.deleted,c-l.fromA,v-l.fromA),r),f+=v-c),A&&v==a.toB&&(a=o++==e.length?null:e[o],g=!1),w&&v==l.toA&&(l=s++==n.length?null:n[s],y=!1),c=v}(u<f||d<p)&&i.push(new t(u,f,d,p,h,m))}}}static fromJSON(e){return new t(e.fromA,e.toA,e.fromB,e.toB,e.deleted.map(n=>new Se(n.length,n.data)),e.inserted.map(n=>new Se(n.length,n.data)))}toJSON(){return this}},kR;try{kR=new RegExp("[\\p{Alphabetic}_]","u")}catch{}var Ui=class t{constructor(e,n){this.config=e,this.changes=n}addSteps(e,n,r){let i=[];for(let l=0;l<n.length;l++){let c=Array.isArray(r)?r[l]:r,u=0;n[l].forEach((f,d,p,h)=>{i.push(new Gt(f+u,d+u,p,h,f==d?Se.none:[new Se(d-f,c)],p==h?Se.none:[new Se(h-p,c)])),u=h-p-(d-f)})}if(i.length==0)return this;let o=tp(i,this.config.combine),s=Gt.merge(this.changes,o,this.config.combine),a=s;for(let l=0;l<a.length;l++){let c=a[l];if(c.fromA==c.toA||c.fromB==c.toB||!o.some(f=>f.toB>c.fromB&&f.fromB<c.toB))continue;let u=Qx(this.config.doc.content,e.content,c,this.config.encoder);u.length==1&&u[0].fromB==0&&u[0].toB==c.toB-c.fromB||(a==s&&(a=s.slice()),u.length==1?a[l]=u[0]:(a.splice(l,1,...u),l+=u.length-1))}return new t(this.config,a)}get startDoc(){return this.config.doc}map(e){let n=r=>{let i=e(r);return i===r.data?r:new Se(r.length,i)};return new t(this.config,this.changes.map(r=>new Gt(r.fromA,r.toA,r.fromB,r.toB,r.deleted.map(n),r.inserted.map(n))))}changedRange(e,n){if(e==this)return null;let r=n&&bR(n),i=r?r.toB-r.fromB-(r.toA-r.fromA):0;function o(f){return!r||f<=r.fromA?f:f+i}let s=r?r.fromB:2e8,a=r?r.toB:-2e8;function l(f,d=f){s=Math.min(f,s),a=Math.max(d,a)}let c=this.changes,u=e.changes;for(let f=0,d=0;f<c.length&&d<u.length;){let p=c[f],h=u[d];p&&h&&xR(p,h,o)?(f++,d++):h&&(!p||o(p.fromB)>=h.fromB)?(l(h.fromB,h.toB),d++):(l(o(p.fromB),o(p.toB)),f++)}return s<=a?{from:s,to:a}:null}static create(e,n=(o,s)=>o===s?o:null,r=Yx,i=[]){return new t({combine:n,doc:e,encoder:r},i)}};Ui.computeDiff=Qx;function tp(t,e,n=0,r=t.length){if(r==n+1)return[t[n]];let i=n+r>>1;return Gt.merge(tp(t,e,n,i),tp(t,e,i,r),e)}function Gx(t){let e=2e8,n=-2e8;for(let r=0;r<t.length;r++){let i=t[r];e!=2e8&&(e=i.map(e,-1),n=i.map(n,1)),i.forEach((o,s,a,l)=>{e=Math.min(e,a),n=Math.max(n,l)})}return e==2e8?null:{from:e,to:n}}function bR(t){let e=Gx(t);if(!e)return null;let n=Gx(t.map(r=>r.invert()).reverse());return{fromA:n.from,toA:n.to,fromB:e.from,toB:e.to}}function xR(t,e,n){return n(t.fromB)==e.fromB&&n(t.toB)==e.toB&&Xx(t.deleted,e.deleted)&&Xx(t.inserted,e.inserted)}function Xx(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(t[n].length!=e[n].length||t[n].data!==e[n].data)return!1;return!0}function Xt(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-diff",...e}}),t}var Zx=500;function wR(t={}){let e=new WeakMap,n=new WeakMap;function r(i){let o=e.get(i);if(o!=null)return o;let s=i.attrs,a=s?Object.keys(s).filter(l=>s[l]!=null).sort():[];if(a.length===0)o=i.type.name;else{let l={};for(let c of a)l[c]=s[c];o=`${i.type.name}:${JSON.stringify(l)}`}return e.set(i,o),o}return{encodeCharacter:(i,o)=>{if(o.length===0)return i;let s=n.get(o);return s==null&&(s=o.map(r).join(","),n.set(o,s)),`${i}:${s}`},encodeNodeStart:i=>{let o=i.attrs;if(o&&Object.keys(o).length>0){let s=t[i.type.name]??[],a=Object.keys(o).filter(l=>{if(s.includes(l))return!1;let c=i.type.spec.attrs?.[l]?.default;return o[l]!==c});if(a.length>0){let l={};for(let c of a.sort())l[c]=o[c];return`${i.type.name}:${JSON.stringify(l)}`}}return i.type.name},encodeNodeEnd:i=>{let o=i.type.schema,s=o.cached.changeSetIDs||(o.cached.changeSetIDs=Object.create(null)),a=s[i.type.name];return a==null&&(s[i.type.name]=a=Object.keys(o.nodes).indexOf(i.type.name)+1),-a},compareTokens:(i,o)=>i===o}}function rw(t,e,n){let r=n.get(t);if(r!=null)return r;let i=[String(e.encodeNodeStart(t))];if(t.isText){let s=t.text;for(let a=0;a<s.length;a++)i.push(":"+String(e.encodeCharacter(s.charCodeAt(a),t.marks)))}else t.content.forEach(s=>{i.push("/"+rw(s,e,n))});i.push("\\"+String(e.encodeNodeEnd(t)));let o=i.join("");return n.set(t,o),o}function ew(t,e,n){let r=[],i=0;return t.content.forEach(o=>{r.push({node:o,offset:i,size:o.nodeSize,signature:rw(o,n.encoder,n.sigCache)}),i+=o.nodeSize}),{node:t,contentStart:e,content:r}}function CR(t,e){let n=t.length,r=e.length,i=Array.from({length:n+1},()=>Array.from({length:r+1},()=>0));for(let l=n-1;l>=0;l--)for(let c=r-1;c>=0;c--)t[l].signature===e[c].signature?i[l][c]=i[l+1][c+1]+1:i[l][c]=Math.max(i[l+1][c],i[l][c+1]);let o=[],s=0,a=0;for(;s<n&&a<r;)t[s].signature===e[a].signature?(o.push([s,a]),s++,a++):i[s+1][a]>=i[s][a+1]?s++:a++;return o}function SR(t,e){if(t.type!==e.type)return!1;let n=t.type;return!(n.isTextblock||n.isAtom||n.spec.code===!0||!n.isBlock)}function iw(t,e,n){return Gt.fromJSON({fromA:t.fromA+e,toA:t.toA+e,fromB:t.fromB+n,toB:t.toB+n,deleted:t.deleted.map(r=>({length:r.length,data:r.data})),inserted:t.inserted.map(r=>({length:r.length,data:r.data}))})}function MR(t,e,n){let r=t.parent.copy(M.from(t.node)),i=e.parent.copy(M.from(e.node)),o=new we(0,r.content.size,new R(i.content,0,0));return Ui.create(r,void 0,n.encoder).addSteps(i,[o.getMap()],null).changes.map(s=>iw(s,t.abs,e.abs))}function tw(t,e){let n=t.content;if(e<n.length)return t.contentStart+n[e].offset;if(e>0){let r=n[e-1];return t.contentStart+r.offset+r.size}return t.contentStart+t.node.content.size}function ER(t,e,n){return Gt.fromJSON({fromA:e,toA:e+t.size,fromB:n,toB:n,deleted:[{length:t.size,data:null}],inserted:[]})}function TR(t,e,n){return Gt.fromJSON({fromA:e,toA:e,fromB:n,toB:n+t.size,deleted:[],inserted:[{length:t.size,data:null}]})}function vR(t,e,n,r,i){let o=new we(0,t.content.size,new R(e.content,0,0));return Ui.create(t,void 0,i.encoder).addSteps(e,[o.getMap()],null).changes.map(s=>iw(s,n,r))}function xl(t,e,n,r,i){if(t.childCount>Zx||e.childCount>Zx)return vR(t,e,n,r,i);let o=ew(t,n,i),s=ew(e,r,i),a=CR(o.content,s.content),l=[],c=0,u=0;for(let[f,d]of a)nw(o,s,{oldStart:c,oldEnd:f,newStart:u,newEnd:d},i,l),c=f+1,u=d+1;return nw(o,s,{oldStart:c,oldEnd:o.content.length,newStart:u,newEnd:s.content.length},i,l),l}function nw(t,e,n,r,i){let o=t.content,s=e.content,a=n.oldStart,l=n.newStart;for(;a<n.oldEnd||l<n.newEnd;){let c=a<n.oldEnd?o[a]:null,u=l<n.newEnd?s[l]:null,f=c&&u&&c.node.type===u.node.type;if(c&&u&&f){i.push(...AR(t,e,c,u,r)),a++,l++;continue}if(c&&(!u||!f)){let d=t.contentStart+c.offset;i.push(ER(c,d,tw(e,l))),a++;continue}if(u){let d=e.contentStart+u.offset;i.push(TR(u,tw(t,a),d)),l++}}}function AR(t,e,n,r,i){let o=t.contentStart+n.offset,s=e.contentStart+r.offset;return SR(n.node,r.node)&&IR(n.node,r.node,i.encoder)?xl(n.node,r.node,o+1,s+1,i):MR({node:n.node,parent:t.node,abs:o},{node:r.node,parent:e.node,abs:s},i)}function IR(t,e,n){return n.encodeNodeStart(t)===n.encodeNodeStart(e)}function NR(t,e,n,r,i){let o=t.resolve(n),s=t.resolve(r),a=e.resolve(n),l=e.resolve(r),c=o.sharedDepth(r);if(a.sharedDepth(r)!==c)throw new RangeError(`computeDocDiff: range [${n}, ${r}) resolves to different sharedDepth in old and new docs`);for(let m=0;m<=c;m++){if(i.encodeNodeStart(o.node(m))!==i.encodeNodeStart(a.node(m)))throw new RangeError(`computeDocDiff: ancestor at depth ${m} differs in type or non-ignored attrs along the path to the shared ancestor`);if(o.start(m)!==a.start(m))throw new RangeError(`computeDocDiff: ancestor at depth ${m} starts at different absolute positions in old and new docs (content before the range differs in size)`)}let u=o.node(c);if(u.isTextblock)throw new RangeError(`computeDocDiff: range [${n}, ${r}) lands inside a textblock; widen the range to a block boundary`);if(o.depth!==c||s.depth!==c||a.depth!==c||l.depth!==c)throw new RangeError(`computeDocDiff: range [${n}, ${r}) endpoints must be aligned to child boundaries of the shared ancestor`);let f=a.node(c),d=o.start(c),p=n-d,h=r-d;return{oldCut:u.copy(u.content.cut(p,h)),newCut:f.copy(f.content.cut(p,h)),cutAbsStart:n}}function ps(t,e,n){let r=wR(n?.ignoreAttrs),i={encoder:r,sigCache:new WeakMap},o=t.content.size,s=e.content.size,a=n?.range;if(a==null)return xl(t,e,0,0,i);let l=Math.min(o,s),c=Math.max(0,Math.min(a.from??0,l)),u=Math.max(c,Math.min(a.to??l,l));if(c===u)return[];if(c===0&&u===l&&o===s)return xl(t,e,0,0,i);let f=NR(t,e,c,u,r);return xl(f.oldCut,f.newCut,f.cutAbsStart,f.cutAbsStart,i)}var ow=Ae({ignoreAttrs:{heading:["id"]}},"diffConfig");Xt(ow,{displayName:"Ctx<diffConfig>",group:"Diff"});var Le=new ee("MILKDOWN_DIFF");function RR(t,e,n){let r=ps(t,e.newDoc,n);return{...e,changes:r}}function OR(t,e){return e.some(n=>t.fromB<n.toB&&t.toB>n.fromB)}function wl(t){return t.changes.filter(e=>!OR(e,t.rejectedRanges))}var DR=pe(t=>{let e=t.get(ow.key);return new X({key:Le,state:{init:()=>null,apply(n,r,i,o){let s=n.getMeta(Le);if(!r){if(s?.type==="start"){let c=ps(o.doc,s.newDoc,{ignoreAttrs:e.ignoreAttrs});return{newDoc:s.newDoc,changes:c,rejectedRanges:[],active:!0}}return null}let a=r;if(n.docChanged&&a.active&&(a=RR(o.doc,a,{ignoreAttrs:e.ignoreAttrs})),!s)return a;let l;switch(s.type){case"start":{let c=ps(o.doc,s.newDoc,{ignoreAttrs:e.ignoreAttrs});return{newDoc:s.newDoc,changes:c,rejectedRanges:[],active:!0}}case"accept":case"acceptRange":l=a;break;case"reject":l={...a,rejectedRanges:[...a.rejectedRanges,{fromB:s.fromB,toB:s.toB}]};break;case"rejectRange":l={...a,rejectedRanges:[...a.rejectedRanges,{fromB:s.range.fromB,toB:s.range.toB}]};break;case"acceptAll":case"clear":return null;default:return a}return l.active&&wl(l).length===0?null:l}},filterTransaction(n,r){return!Le.getState(r)?.active||n.getMeta(Le)?!0:!n.docChanged}})});Xt(DR,{displayName:"Prose<diff>",group:"Diff"});function LR(t,e){let n=wl(e);for(let r=n.length-1;r>=0;r--){let i=n[r],o=e.newDoc.slice(i.fromB,i.toB);t=t.replace(i.fromA,i.toA,o)}return t}var PR=z("StartDiffReview",t=>e=>(n,r)=>{if(e==null)return!1;let i=t.get(He)(e);return i?(r&&r(n.tr.setMeta(Le,{type:"start",newDoc:i})),!0):!1});Xt(PR,{displayName:"Command<startDiffReview>",group:"Diff"});var np=z("StartDiffReviewFromDoc",()=>t=>(e,n)=>!t||t.type!==e.doc.type?!1:(n&&n(e.tr.setMeta(Le,{type:"start",newDoc:t})),!0));Xt(np,{displayName:"Command<startDiffReviewFromDoc>",group:"Diff"});var BR=z("AcceptDiffChunk",()=>t=>(e,n)=>{if(t==null)return!1;let r=Le.getState(e);if(!r)return!1;let i=wl(r)[t];if(!i)return!1;if(n){let o=r.newDoc.slice(i.fromB,i.toB),s=e.tr.replace(i.fromA,i.toA,o);s=s.setMeta(Le,{type:"accept",changeIndex:t}),n(s)}return!0});Xt(BR,{displayName:"Command<acceptDiffChunk>",group:"Diff"});var FR=z("RejectDiffChunk",()=>t=>(e,n)=>{if(t==null)return!1;let r=Le.getState(e);if(!r)return!1;let i=wl(r)[t];return i?(n&&n(e.tr.setMeta(Le,{type:"reject",fromB:i.fromB,toB:i.toB})),!0):!1});Xt(FR,{displayName:"Command<rejectDiffChunk>",group:"Diff"});var zR=z("AcceptDiffRange",()=>t=>(e,n)=>{if(!t)return!1;let r=Le.getState(e);if(!r)return!1;if(n){let i=r.newDoc.slice(t.fromB,t.toB),o=e.tr.replace(t.fromA,t.toA,i);o=o.setMeta(Le,{type:"acceptRange",range:t}),n(o)}return!0});Xt(zR,{displayName:"Command<acceptDiffRange>",group:"Diff"});var _R=z("RejectDiffRange",()=>t=>(e,n)=>!t||!Le.getState(e)?!1:(n&&n(e.tr.setMeta(Le,{type:"rejectRange",range:t})),!0));Xt(_R,{displayName:"Command<rejectDiffRange>",group:"Diff"});var $R=z("AcceptAllDiffs",()=>()=>(t,e)=>{let n=Le.getState(t);return n?(e&&e((n.rejectedRanges.length===0?t.tr.replaceWith(0,t.doc.content.size,n.newDoc.content):LR(t.tr,n)).setMeta(Le,{type:"acceptAll"})),!0):!1});Xt($R,{displayName:"Command<acceptAllDiffs>",group:"Diff"});var HR=z("ClearDiffReview",()=>()=>(t,e)=>Le.getState(t)?(e&&e(t.tr.setMeta(Le,{type:"clear"})),!0):!1);Xt(HR,{displayName:"Command<clearDiffReview>",group:"Diff"});function Ji(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-streaming",...e}}),t}var qn=Ae({throttleMs:100,scrollFollow:!0,diffReviewOnEnd:!1,ignoreAttrs:{heading:["id"]}},"streamingConfig");Ji(qn,{displayName:"Ctx<streamingConfig>",group:"Streaming"});function WR(t,e,n){let r=t.get(He)(n);if(!r)return{tr:e,newDoc:null};let i=t.get(qn.key).ignoreAttrs,o=ps(e.doc,r,i?{ignoreAttrs:i}:void 0);for(let s=o.length-1;s>=0;s--){let a=o[s],l=r.slice(a.fromB,a.toB);e=e.replace(a.fromA,a.toA,l)}return{tr:e,newDoc:r}}function jR(t){if(t.parent.type.spec.code)return{type:"plain-text",preserveNewlines:!0};for(let e=t.depth;e>0;e--)if(t.node(e).type.name==="table")return{type:"plain-text",preserveNewlines:!1};return t.depth>=1?{type:"split-block"}:{type:"block"}}function sw(t){if(t.childCount===0)return t;let e=t.lastChild;return e.type.name==="paragraph"&&e.content.size===0?t.cut(0,t.size-e.nodeSize):t}function VR(t,e,n){let{insertPos:r,currentEndPos:i}=n,o=n.buffer.replace(/\r\n?/g,` -`);if(!o)return{tr:e,applied:!1,insertEndPos:i};let s=e.doc.content.size,a=Math.max(0,Math.min(r,s)),l=Math.max(a,Math.min(i,s)),c=e.doc.resolve(a),u=(t.get(qn.key).insertStrategy??jR)(c),f={ctx:t,tr:e,buffer:o,from:a,to:l,resolved:c};switch(u.type){case"plain-text":return qR(f,u.preserveNewlines??!1);case"split-block":return UR(f);case"block":return JR(f)}}function qR({tr:t,buffer:e,from:n,to:r},i){let o=i?e:e.replace(/\n/g," "),s=t.doc.type.schema.text(o);return t=t.replaceWith(n,r,s),{tr:t,applied:!0,insertEndPos:n+o.length}}var KR=/[*_~`[\\<]/;function rp(t,e,n){if(!n)return M.empty;if(!KR.test(n))return M.from(e.text(n));let r=t.get(He)(n)?.firstChild;if(r?.type.name!=="paragraph"||r.content.size===0)return M.from(e.text(n));let i=!1;if(r.content.forEach(l=>{(!l.isText||l.marks.length>0)&&(i=!0)}),!i)return M.from(e.text(n));let o=r.content,s=/^\s+/.exec(n)?.[0];s&&((o.firstChild?.isText?o.firstChild.text??"":"").startsWith(s)||(o=M.from(e.text(s)).append(o)));let a=/\s+$/.exec(n)?.[0];return a&&((o.lastChild?.isText?o.lastChild.text??"":"").endsWith(a)||(o=o.append(M.from(e.text(a))))),o}function UR({ctx:t,tr:e,buffer:n,from:r,to:i,resolved:o}){let s=e.doc.type.schema,a=n.indexOf(` -`);if(a<0){let A=rp(t,s,n);return e=e.replaceWith(r,i,A),{tr:e,applied:!0,insertEndPos:r+A.size}}let l=n.substring(0,a),c=n.substring(a+1),u=t.get(He),f=c.trim()?u(c):null,d=f?sw(f.content):M.empty;if(d.childCount===0){let A=rp(t,s,n.replace(/\n/g," "));return e=e.replaceWith(r,i,A),{tr:e,applied:!0,insertEndPos:r+A.size}}let p=o.depth,h=rp(t,s,l);for(let A=p;A>0;A--)h=M.from(o.node(A).copy(h));let m=h.append(d),g=new R(m,p,0),y=e.doc.content.size,b=e.doc.resolve(Math.min(i,y)),C=i;p>0&&b.depth===p&&b.parentOffset===b.parent.content.size&&(C=b.after(p)),e=e.replace(r,C,g);let v=m.size-p;return{tr:e,applied:!0,insertEndPos:r+v}}function JR({ctx:t,tr:e,buffer:n,from:r,to:i}){let o=t.get(He)(n);if(!o)return{tr:e,applied:!1,insertEndPos:i};let s=sw(o.content);return s.size===0?{tr:e,applied:!1,insertEndPos:i}:(e=e.replace(r,i,new R(s,0,0)),{tr:e,applied:!0,insertEndPos:r+s.size})}function ip(t,e,n){if(n.insertPos!=null){let r=n.insertPos,i=VR(t,e,{buffer:n.buffer,insertPos:r,currentEndPos:n.insertEndPos??r});return{tr:i.tr,newDoc:i.applied?i.tr.doc:null,insertEndPos:i.insertEndPos}}return WR(t,e,n.buffer)}var tt=new ee("MILKDOWN_STREAMING");function GR(t,e){if(!t&&e?.type!=="start")return null;if(!e)return t;switch(e.type){case"start":return{buffer:"",originalDoc:e.originalDoc,active:!0,lastApplyTime:e.lastApplyTime,insertPos:e.insertPos??null,insertEndPos:e.insertEndPos??e.insertPos??null};case"push":return t?{...t,buffer:t.buffer+e.token}:null;case"apply":return t?{...t,lastApplyTime:e.lastApplyTime,insertEndPos:e.insertEndPos??t.insertEndPos}:null;case"end":case"abort":return null;default:return t}}var aw=pe(t=>{let e=t.get(qn.key);return new X({key:tt,state:{init:()=>null,apply(n,r){return GR(r,n.getMeta(tt))}},filterTransaction(n,r){return!tt.getState(r)?.active||n.getMeta(tt)?!0:!n.docChanged},view(){return XR(t,e)}})});Ji(aw,{displayName:"Prose<streaming>",group:"Streaming"});function XR(t,e){let n=null,r=-1,i=null;function o(){if(!i)return;let a=tt.getState(i.state);if(!a?.active||a.buffer.length===r)return;r=a.buffer.length;let l=ip(t,i.state.tr,a);if(!l.newDoc)return;let c=l.tr;!c.docChanged&&l.insertEndPos==null||(c=c.setMeta(tt,{type:"apply",lastApplyTime:Date.now(),insertEndPos:l.insertEndPos}),e.scrollFollow&&(c=c.scrollIntoView()),i.dispatch(c))}function s(){n!=null&&clearTimeout(n),n=setTimeout(o,e.throttleMs)}return{update(a){i=a;let l=tt.getState(a.state);if(!l?.active){n!=null&&(clearTimeout(n),n=null),r=-1;return}l.buffer.length!==r&&(Date.now()-l.lastApplyTime>=e.throttleMs?o():s())},destroy(){n!=null&&(clearTimeout(n),n=null),i=null}}}var $r=z("StartStreaming",()=>t=>(e,n)=>{if(tt.getState(e)?.active)return!1;if(n){let r,i;if(t?.insertAt!=null)if(t.insertAt==="selection"){if(r=e.selection.from,i=e.selection.to,e.selection.empty){let o=e.doc.resolve(r);o.parent.isTextblock&&!o.parent.type.spec.code&&o.parent.content.size===0&&o.depth===1&&(r=o.before(o.depth),i=o.after(o.depth))}}else{let o=t.insertAt==="cursor"?e.selection.head:t.insertAt;if(!Number.isFinite(o))return!1;r=Math.max(0,Math.min(Math.round(o),e.doc.content.size));let s=e.doc.resolve(r);s.parent.isTextblock&&!s.parent.type.spec.code&&s.parent.content.size===0&&s.depth===1&&(r=s.before(s.depth),i=s.after(s.depth))}n(e.tr.setMeta(tt,{type:"start",originalDoc:e.doc,insertPos:r,insertEndPos:i,lastApplyTime:Date.now()}))}return!0});Ji($r,{displayName:"Command<startStreaming>",group:"Streaming"});var hs=z("PushChunk",()=>t=>(e,n)=>t==null||!tt.getState(e)?.active?!1:(n&&n(e.tr.setMeta(tt,{type:"push",token:t})),!0));Ji(hs,{displayName:"Command<pushChunk>",group:"Streaming"});var Gi=z("EndStreaming",t=>e=>(n,r)=>{let i=tt.getState(n);if(!i?.active)return!1;if(r){let o=t.get(qn.key),s=e?.diffReview??o.diffReviewOnEnd,a=ip(t,n.tr,i),l=a.tr;if(l=l.setMeta(tt,{type:"end"}),s&&a.newDoc){let c=l.doc;l=l.replace(0,l.doc.content.size,new R(i.originalDoc.content,0,0)),r(l);try{t.get(Q).call(np.key,c)}catch(u){console.warn("[milkdown/streaming] diff review handoff skipped:",u)}return!0}r(l)}return!0});Ji(Gi,{displayName:"Command<endStreaming>",group:"Streaming"});var ms=z("AbortStreaming",t=>e=>(n,r)=>{let i=tt.getState(n);if(!i?.active)return!1;if(r){let o=e?.keep??!1,s=n.tr;o?s=ip(t,s,i).tr:s=s.replace(0,n.doc.content.size,new R(i.originalDoc.content,0,0)),s=s.setMeta(tt,{type:"abort"}),r(s)}return!0});Ji(ms,{displayName:"Command<abortStreaming>",group:"Streaming"});var lw=[qn,aw,$r,hs,Gi,ms];var cw=new ee("weibeiStreamingAppearance"),YR={class:"wb-stream-in"},QR={side:1},ZR=260,eO=400,tO=24;function nO(){let t=document.createElement("span");return t.className="wb-stream-caret",t}function uw(t){return new X({key:cw,state:{init:()=>({fades:[],caretPosition:null,caretExpiresAt:0,set:ae.empty}),apply(e,n){let r=Date.now(),i=[],o=e.doc.content.size;for(let c of n.fades){let u=Math.min(e.mapping.map(c.from),o),f=Math.min(e.mapping.map(c.to),o);u>=f||r>=c.expiresAt||e.doc.resolve(u).parent===e.doc.resolve(f).parent&&i.push({from:u,to:f,expiresAt:c.expiresAt})}let s=n.caretPosition===null?null:Math.min(e.mapping.map(n.caretPosition),o),a=n.caretExpiresAt;e.docChanged&&t()&&e.steps.forEach((c,u)=>{let f=e.mapping.slice(u+1);e.mapping.maps[u].forEach((d,p,h,m)=>{if(m<=h)return;let g=f.map(h),y=f.map(m);if(y-g>tO)return;let b=e.doc.resolve(g);b.parent===e.doc.resolve(y).parent&&b.parent.isTextblock&&(i.push({from:g,to:y,expiresAt:r+ZR}),s=y,a=r+eO)})}),s!==null&&r>=a&&(s=null);let l=i.map(c=>le.inline(c.from,c.to,YR));return s!==null&&l.push(le.widget(s,nO,QR)),{fades:i,caretPosition:s,caretExpiresAt:a,set:ae.create(e.doc,l)}}},props:{decorations(e){let n=cw.getState(e);return!n||!t()?ae.empty:n.set}}})}var Sl=Math.min,Hr=Math.max,ys=Math.round;var Yt=t=>({x:t,y:t}),rO={left:"right",right:"left",bottom:"top",top:"bottom"};function Ml(t,e){return typeof t=="function"?t(e):t}function Wr(t){return t.split("-")[0]}function ks(t){return t.split("-")[1]}function pw(t){return t==="x"?"y":"x"}function op(t){return t==="y"?"height":"width"}function Kn(t){let e=t[0];return e==="t"||e==="b"?"y":"x"}function sp(t){return pw(Kn(t))}function hw(t,e,n){n===void 0&&(n=!1);let r=ks(t),i=sp(t),o=op(i),s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(s=gs(s)),[s,gs(s)]}function mw(t){let e=gs(t);return[Cl(t),e,Cl(e)]}function Cl(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}var fw=["left","right"],dw=["right","left"],iO=["top","bottom"],oO=["bottom","top"];function sO(t,e,n){switch(t){case"top":case"bottom":return n?e?dw:fw:e?fw:dw;case"left":case"right":return e?iO:oO;default:return[]}}function gw(t,e,n,r){let i=ks(t),o=sO(Wr(t),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),e&&(o=o.concat(o.map(Cl)))),o}function gs(t){let e=Wr(t);return rO[e]+t.slice(e.length)}function aO(t){var e,n,r,i;return{top:(e=t.top)!=null?e:0,right:(n=t.right)!=null?n:0,bottom:(r=t.bottom)!=null?r:0,left:(i=t.left)!=null?i:0}}function yw(t){return typeof t!="number"?aO(t):{top:t,right:t,bottom:t,left:t}}function jr(t){let{x:e,y:n,width:r,height:i}=t;return{width:r,height:i,top:n,left:e,right:e+r,bottom:n+i,x:e,y:n}}function kw(t,e,n){let{reference:r,floating:i}=t,o=Kn(e),s=sp(e),a=op(s),l=Wr(e),c=o==="y",u=r.x+r.width/2-i.width/2,f=r.y+r.height/2-i.height/2,d=r[a]/2-i[a]/2,p;switch(l){case"top":p={x:u,y:r.y-i.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-i.width,y:f};break;default:p={x:r.x,y:r.y}}let h=ks(e);return h&&(p[s]+=d*(h==="end"?1:-1)*(n&&c?-1:1)),p}async function bw(t,e){var n;e===void 0&&(e={});let{x:r,y:i,platform:o,rects:s,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:f="floating",altBoundary:d=!1,padding:p=0}=Ml(e,t),h=yw(p),g=a[d?f==="floating"?"reference":"floating":f],y=jr(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(g)))==null||n?g:g.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),b=f==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,C=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),v=await(o.isElement==null?void 0:o.isElement(C))&&await(o.getScale==null?void 0:o.getScale(C))||{x:1,y:1},A=jr(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:C,strategy:l}):b);return{top:(y.top-A.top+h.top)/v.y,bottom:(A.bottom-y.bottom+h.bottom)/v.y,left:(y.left-A.left+h.left)/v.x,right:(A.right-y.right+h.right)/v.x}}var lO=50,xw=async(t,e,n)=>{let{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,a=s.detectOverflow?s:{...s,detectOverflow:bw},l=await(s.isRTL==null?void 0:s.isRTL(e)),c=await s.getElementRects({reference:t,floating:e,strategy:i}),{x:u,y:f}=kw(c,r,l),d=r,p=0,h={};for(let m=0;m<o.length;m++){let g=o[m];if(!g)continue;let{name:y,fn:b}=g,{x:C,y:v,data:A,reset:w}=await b({x:u,y:f,initialPlacement:r,placement:d,strategy:i,middlewareData:h,rects:c,platform:a,elements:{reference:t,floating:e}});u=C??u,f=v??f,h[y]={...h[y],...A},w&&p<lO&&(p++,typeof w=="object"&&(w.placement&&(d=w.placement),w.rects&&(c=w.rects===!0?await s.getElementRects({reference:t,floating:e,strategy:i}):w.rects),{x:u,y:f}=kw(c,d,l)),m=-1)}return{x:u,y:f,placement:d,strategy:i,middlewareData:h}};var ww=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;let{placement:i,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:f=!0,fallbackPlacements:d,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:m=!0,...g}=Ml(t,e);if((n=o.arrow)!=null&&n.alignmentOffset)return{};let y=Wr(i),b=Kn(a),C=Wr(a)===a,v=await(l.isRTL==null?void 0:l.isRTL(c.floating)),A=d||(C||!m?[gs(a)]:mw(a)),w=h!=="none";!d&&w&&A.push(...gw(a,m,h,v));let N=[a,...A],P=await l.detectOverflow(e,g),O=[],S=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&O.push(P[y]),f){let W=hw(i,s,v);O.push(P[W[0]],P[W[1]])}if(S=[...S,{placement:i,overflows:O}],!O.every(W=>W<=0)){var me,te;let W=(((me=o.flip)==null?void 0:me.index)||0)+1,q=N[W];if(q&&(!(f==="alignment"?b!==Kn(q):!1)||S.every(ye=>Kn(ye.placement)===b?ye.overflows[0]>0:!0)))return{data:{index:W,overflows:S},reset:{placement:q}};let se=(te=S.filter(fe=>fe.overflows[0]<=0).sort((fe,ye)=>fe.overflows[1]-ye.overflows[1])[0])==null?void 0:te.placement;if(!se)switch(p){case"bestFit":{var F;let fe=(F=S.filter(ye=>{if(w){let Ee=Kn(ye.placement);return Ee===b||Ee==="y"}return!0}).map(ye=>[ye.placement,ye.overflows.filter(Ee=>Ee>0).reduce((Ee,k)=>Ee+k,0)]).sort((ye,Ee)=>ye[1]-Ee[1])[0])==null?void 0:F[0];fe&&(se=fe);break}case"initialPlacement":se=a;break}if(i!==se)return{reset:{placement:se}}}return{}}}};var cO=new Set(["left","top"]);async function uO(t,e){let{placement:n,platform:r,elements:i}=t,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=Wr(n),a=ks(n),l=Kn(n)==="y",c=cO.has(s)?-1:1,u=o&&l?-1:1,f=Ml(e,t),{mainAxis:d,crossAxis:p,alignmentAxis:h}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof h=="number"&&(p=a==="end"?h*-1:h),l?{x:p*u,y:d*c}:{x:d*c,y:p*u}}var Cw=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;let{x:i,y:o,placement:s,middlewareData:a}=e,l=await uO(e,t);return s===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}};function Tl(){return typeof window<"u"}function qr(t){return Mw(t)?(t.nodeName||"").toLowerCase():"#document"}function ot(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function wn(t){var e;return(e=(Mw(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Mw(t){return Tl()?t instanceof Node||t instanceof ot(t).Node:!1}function Ft(t){return Tl()?t instanceof Element||t instanceof ot(t).Element:!1}function Cn(t){return Tl()?t instanceof HTMLElement||t instanceof ot(t).HTMLElement:!1}function Sw(t){return!Tl()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof ot(t).ShadowRoot}function bs(t){let{overflow:e,overflowX:n,overflowY:r,display:i}=zt(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&i!=="inline"&&i!=="contents"}function Ew(t){return/^(table|td|th)$/.test(qr(t))}function xs(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}var fO=/transform|translate|scale|rotate|perspective|filter/,dO=/paint|layout|strict|content/,Vr=t=>!!t&&t!=="none",ap;function vl(t){let e=Ft(t)?zt(t):t;return Vr(e.transform)||Vr(e.translate)||Vr(e.scale)||Vr(e.rotate)||Vr(e.perspective)||!Al()&&(Vr(e.backdropFilter)||Vr(e.filter))||fO.test(e.willChange||"")||dO.test(e.contain||"")}function Tw(t){let e=Un(t);for(;Cn(e)&&!Xi(e);){if(vl(e))return e;if(xs(e))return null;e=Un(e)}return null}function Al(){return ap==null&&(ap=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),ap}function Xi(t){return/^(html|body|#document)$/.test(qr(t))}function zt(t){return ot(t).getComputedStyle(t)}function ws(t){return Ft(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Un(t){if(qr(t)==="html")return t;let e=t.assignedSlot||t.parentNode||Sw(t)&&t.host||wn(t);return Sw(e)?e.host:e}function vw(t){let e=Un(t);return Xi(e)?(t.ownerDocument||t).body:Cn(e)&&bs(e)?e:vw(e)}function El(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);let i=vw(t),o=i===((r=t.ownerDocument)==null?void 0:r.body),s=ot(i);if(o){let a=Il(s);return e.concat(s,s.visualViewport||[],bs(i)?i:[],a&&n?El(a):[])}else return e.concat(i,El(i,[],n))}function Il(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Nw(t){let e=zt(t),n=parseFloat(e.width)||0,r=parseFloat(e.height)||0,i=Cn(t),o=i?t.offsetWidth:n,s=i?t.offsetHeight:r,a=ys(n)!==o||ys(r)!==s;return a&&(n=o,r=s),{width:n,height:r,$:a}}function Rw(t){return Ft(t)?t:t.contextElement}function Yi(t){let e=Rw(t);if(!Cn(e))return Yt(1);let n=e.getBoundingClientRect(),{width:r,height:i,$:o}=Nw(e),s=(o?ys(n.width):n.width)/r,a=(o?ys(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}var pO=Yt(0);function Ow(t){let e=ot(t);return!Al()||!e.visualViewport?pO:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function hO(t,e,n){return e===void 0&&(e=!1),!!n&&e&&n===ot(t)}function Cs(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);let i=t.getBoundingClientRect(),o=Rw(t),s=Yt(1);e&&(r?Ft(r)&&(s=Yi(r)):s=Yi(t));let a=hO(o,n,r)?Ow(o):Yt(0),l=(i.left+a.x)/s.x,c=(i.top+a.y)/s.y,u=i.width/s.x,f=i.height/s.y;if(o&&r){let d=ot(o),p=Ft(r)?ot(r):r,h=d,m=Il(h);for(;m&&p!==h;){let g=Yi(m),y=m.getBoundingClientRect(),b=zt(m),C=y.left+(m.clientLeft+parseFloat(b.paddingLeft))*g.x,v=y.top+(m.clientTop+parseFloat(b.paddingTop))*g.y;l*=g.x,c*=g.y,u*=g.x,f*=g.y,l+=C,c+=v,h=ot(m),m=Il(h)}}return jr({width:u,height:f,x:l,y:c})}function Nl(t,e){let n=ws(t).scrollLeft;return e?e.left+n:Cs(wn(t)).left+n}function Dw(t,e){let n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-Nl(t,n),i=n.top+e.scrollTop;return{x:r,y:i}}function mO(t){let{elements:e,rect:n,offsetParent:r,strategy:i}=t,o=i==="fixed",s=wn(r),a=e?xs(e.floating):!1;if(r===s||a&&o)return n;let l={scrollLeft:0,scrollTop:0},c=Yt(1),u=Yt(0),f=Cn(r);if((f||!o)&&((qr(r)!=="body"||bs(s))&&(l=ws(r)),f)){let p=Cs(r);c=Yi(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}let d=s&&!f&&!o?Dw(s,l):Yt(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+d.x,y:n.y*c.y-l.scrollTop*c.y+u.y+d.y}}function gO(t){return t.getClientRects?Array.from(t.getClientRects()):[]}function yO(t){let e=ws(t),n=t.ownerDocument.body,r=Hr(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=Hr(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight),o=-e.scrollLeft+Nl(t),s=-e.scrollTop;return zt(n).direction==="rtl"&&(o+=Hr(t.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:s}}var kO=25;function bO(t,e,n){n===void 0&&(n="viewport");let r=n==="layoutViewport",i=ot(t),o=wn(t),s=i.visualViewport,a=o.clientWidth,l=o.clientHeight,c=0,u=0;if(s){let d=!Al()||e==="fixed";r?d||(c=-s.offsetLeft,u=-s.offsetTop):(a=s.width,l=s.height,d&&(c=s.offsetLeft,u=s.offsetTop))}if(Nl(o)<=0){let d=o.ownerDocument,p=d.body,h=getComputedStyle(p),m=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,g=Math.abs(o.clientWidth-p.clientWidth-m),y=getComputedStyle(o).scrollbarGutter==="stable both-edges"?g/2:g;y<=kO&&(a-=y)}return{width:a,height:l,x:c,y:u}}function xO(t,e){let n=Cs(t,!0,e==="fixed"),r=n.top+t.clientTop,i=n.left+t.clientLeft,o=Yi(t),s=t.clientWidth*o.x,a=t.clientHeight*o.y,l=i*o.x,c=r*o.y;return{width:s,height:a,x:l,y:c}}function Aw(t,e,n){let r;if(e==="viewport"||e==="layoutViewport")r=bO(t,n,e);else if(e==="document")r=yO(wn(t));else if(Ft(e))r=xO(e,n);else{let i=Ow(t);r={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return jr(r)}function wO(t,e){let n=e.get(t);if(n)return n;let r=El(t,[],!1).filter(a=>Ft(a)&&qr(a)!=="body"),i=null,o=zt(t).position==="fixed",s=o?Un(t):t;for(;Ft(s)&&!Xi(s);){let a=zt(s),l=vl(s),c=i?i.position:o?"fixed":"";!l&&(c==="fixed"||c==="absolute"&&a.position==="static")?r=r.filter(f=>f!==s):i=a,s=Un(s)}return e.set(t,r),r}function CO(t){let{element:e,boundary:n,rootBoundary:r,strategy:i}=t,s=[...n==="clippingAncestors"?xs(e)?[]:wO(e,this._c):[].concat(n),r],a=Aw(e,s[0],i),l=a.top,c=a.right,u=a.bottom,f=a.left;for(let d=1;d<s.length;d++){let p=Aw(e,s[d],i);l=Hr(p.top,l),c=Sl(p.right,c),u=Sl(p.bottom,u),f=Hr(p.left,f)}return{width:c-f,height:u-l,x:f,y:l}}function SO(t){let{width:e,height:n}=Nw(t);return{width:e,height:n}}function MO(t,e,n){let r=Cn(e),i=wn(e),o=n==="fixed",s=Cs(t,!0,o,e),a={scrollLeft:0,scrollTop:0},l=Yt(0);if((r||!o)&&((qr(e)!=="body"||bs(i))&&(a=ws(e)),r)){let d=Cs(e,!0,o,e);l.x=d.x+e.clientLeft,l.y=d.y+e.clientTop}!r&&i&&(l.x=Nl(i));let c=i&&!r&&!o?Dw(i,a):Yt(0),u=s.left+a.scrollLeft-l.x-c.x,f=s.top+a.scrollTop-l.y-c.y;return{x:u,y:f,width:s.width,height:s.height}}function lp(t){return zt(t).position==="static"}function Iw(t,e){if(!Cn(t)||zt(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return wn(t)===n&&(n=n.ownerDocument.body),n}function Lw(t,e){let n=ot(t);if(xs(t))return n;if(!Cn(t)){let i=Un(t);for(;i&&!Xi(i);){if(Ft(i)&&!lp(i))return i;i=Un(i)}return n}let r=Iw(t,e);for(;r&&Ew(r)&&lp(r);)r=Iw(r,e);return r&&Xi(r)&&lp(r)&&!vl(r)?n:r||Tw(t)||n}var EO=async function(t){let e=this.getOffsetParent||Lw,n=this.getDimensions,r=await n(t.floating);return{reference:MO(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function TO(t){return zt(t).direction==="rtl"}var vO={convertOffsetParentRelativeRectToViewportRelativeRect:mO,getDocumentElement:wn,getClippingRect:CO,getOffsetParent:Lw,getElementRects:EO,getClientRects:gO,getDimensions:SO,getScale:Yi,isElement:Ft,isRTL:TO};var Pw=Cw;var Bw=ww;var Fw=(t,e,n)=>{let r=new Map,i=n??{},o={...vO,...i.platform,_c:r};return xw(t,e,{...i,platform:o})};function zw(t){let e=Ae({},`${t}_SLASH_SPEC`),n=pe(i=>{let o=i.get(e.key);return new X({key:new ee(`${t}_SLASH`),...o})}),r=[e,n];return r.key=e.key,r.pluginKey=n.key,e.meta={package:"@milkdown/plugin-slash",displayName:`Ctx<slashSpec>|${t}`},n.meta={package:"@milkdown/plugin-slash",displayName:`Prose<slash>|${t}`},r}var _w=class{#t;#e;#r;#n;#s;#o;#i;#a;#l;constructor(t){this.#t=!1,this.onShow=()=>{},this.onHide=()=>{},this.#d=(e,n)=>{let{state:r,composing:i}=e,{selection:o,doc:s}=r,{ranges:a}=o,l=Math.min(...a.map(f=>f.$from.pos)),c=Math.max(...a.map(f=>f.$to.pos)),u=n&&n.doc.eq(s)&&n.selection.eq(o);if(this.#t||((this.#n??e.dom.parentElement??document.body).appendChild(this.element),this.#t=!0),!(i||u)){if(!this.#i(e,n)){this.hide();return}Fw({getBoundingClientRect:()=>qg(e,l,c)},this.element,{placement:"bottom-start",middleware:[Bw(),Pw(this.#l),...this.#e],...this.#r}).then(({x:f,y:d})=>{Object.assign(this.element.style,{left:`${f}px`,top:`${d}px`})}).catch(console.error),this.show()}},this.#c=e=>{let n=this.getContent(e);if(!n)return!1;let r=n.at(-1);return r?Array.isArray(this.#o)?this.#o.includes(r):this.#o===r:!1},this.update=(e,n)=>{this.#a(e,n)},this.getContent=(e,n=r=>r.type.name==="paragraph")=>{let{selection:r}=e.state,{empty:i,$from:o}=r,s=e.state.selection instanceof B;if(typeof document>"u")return;let a=this.element.contains(document.activeElement),l=!e.hasFocus()&&!a,c=!e.editable,u=!Jg(n)(e.state.selection);if(!(l||c||!i||!s||u))return o.parent.textBetween(Math.max(0,o.parentOffset-500),o.parentOffset,void 0,"\uFFFC")},this.destroy=()=>{this.#a.cancel()},this.show=()=>{this.element.dataset.show="true",this.onShow()},this.hide=()=>{this.element.dataset.show="false",this.onHide()},this.element=t.content,this.#s=t.debounce??200,this.#i=t.shouldShow??this.#c,this.#o=t.trigger??"/",this.#l=t.offset,this.#e=t.middleware??[],this.#r=t.floatingUIOptions??{},this.#n=t.root,this.#a=cs(this.#d,this.#s)}#d;#c};function cp(t){return new Promise(e=>{let n=new FileReader;n.addEventListener("load",()=>{e({alt:t.name,src:n.result})},!1),n.readAsDataURL(t)})}var AO=async(t,e)=>{let n=[];for(let i=0;i<t.length;i++){let o=t.item(i);o&&o.type.includes("image")&&n.push(o)}let{image:r}=e.nodes;if(!r)throw _s("image");return(await Promise.all(n.map(i=>cp(i)))).map(({alt:i,src:o})=>r.createAndFill({src:o,alt:i}))},Kr=Ae({uploader:AO,enableHtmlFileUploader:!1,uploadWidgetFactory:(t,e)=>{let n=document.createElement("span");return n.textContent="Upload in progress...",le.widget(t,n,e)}},"uploadConfig");Kr.meta={package:"@milkdown/plugin-upload",displayName:"Ctx<uploadConfig>"};var $w=pe(t=>{let e=new ee("MILKDOWN_UPLOAD"),n=(i,o)=>{let s=e.getState(i);if(!s)return-1;let a=s.find(void 0,void 0,l=>l.id===o);return a.length?a[0]?.from??-1:-1},r=(i,o,s)=>{if(!s||s.length<=0)return!1;let a=Symbol("upload symbol"),l=t.get($e),{uploader:c,getInsertPos:u}=t.get(Kr.key),{tr:f}=i.state,d=o instanceof DragEvent?i.posAtCoords({left:o.clientX,top:o.clientY})?.pos??f.selection.from:f.selection.from,p=typeof u=="function"?u(o,t,d):d;return i.dispatch(f.setMeta(e,{add:{id:a,pos:p}})),c(s,l,t,p).then(h=>{let m=n(i.state,a);m<0||i.dispatch(i.state.tr.replaceWith(m,m,h).setMeta(e,{remove:{id:a}}))}).catch(h=>{console.error(h)}),!0};return new X({key:e,state:{init(){return ae.empty},apply(i,o){let s=o.map(i.mapping,i.doc),a=i.getMeta(this);if(!a)return s;if(a.add){let{uploadWidgetFactory:l}=t.get(Kr.key),c=l(a.add.pos,{id:a.add.id});return s.add(i.doc,[c])}if(a.remove){let l=s.find(void 0,void 0,c=>c.id===a.remove.id);return s.remove(l)}return s}},props:{decorations(i){return this.getState(i)},handlePaste:(i,o)=>{let{enableHtmlFileUploader:s}=t.get(Kr.key);return!(o instanceof ClipboardEvent)||!s&&o.clipboardData?.getData("text/html")?!1:r(i,o,o.clipboardData?.files)},handleDrop:(i,o)=>o instanceof DragEvent?r(i,o,o.dataTransfer?.files):!1}})});$w.meta={package:"@milkdown/plugin-upload",displayName:"Prose<upload>"};var Hw=[Kr,$w];function up(){return{enter:{mathFlow:t,mathFlowFenceMeta:e,mathText:o},exit:{mathFlow:i,mathFlowFence:r,mathFlowFenceMeta:n,mathFlowValue:a,mathText:s,mathTextData:a}};function t(l){let c={type:"element",tagName:"code",properties:{className:["language-math","math-display"]},children:[]};this.enter({type:"math",meta:null,value:"",data:{hName:"pre",hChildren:[c]}},l)}function e(){this.buffer()}function n(){let l=this.resume(),c=this.stack[this.stack.length-1];c.type,c.meta=l}function r(){this.data.mathFlowInside||(this.buffer(),this.data.mathFlowInside=!0)}function i(l){let c=this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c;let f=u.data.hChildren[0];f.type,f.tagName,f.children.push({type:"text",value:c}),this.data.mathFlowInside=void 0}function o(l){this.enter({type:"inlineMath",value:"",data:{hName:"code",hProperties:{className:["language-math","math-inline"]},hChildren:[]}},l),this.buffer()}function s(l){let c=this.resume(),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c,u.data.hChildren.push({type:"text",value:c})}function a(l){this.config.enter.data.call(this,l),this.config.exit.data.call(this,l)}}function fp(t){let e=(t||{}).singleDollarTextMath;return e==null&&(e=!0),r.peek=i,{unsafe:[{character:"\r",inConstruct:"mathFlowMeta"},{character:` +`);let i=e.topNodeType.createAndFill(void 0,n.content);return i?r(i):""}}})});mR(Zd,{displayName:"Prose<clipboard>"});function gR(t){let e=t.schema.cached.changeSetIDs||(t.schema.cached.changeSetIDs=Object.create(null)),n=e[t.name];return n==null&&(e[t.name]=n=Object.keys(t.schema.nodes).indexOf(t.name)+1),n}var Qx={encodeCharacter:t=>t,encodeNodeStart:t=>t.type.name,encodeNodeEnd:t=>-gR(t.type),compareTokens:(t,e)=>t===e};function ep(t,e,n,r,i){for(let o=0,s=0;o<t.childCount;o++){let a=t.child(o),l=s+a.nodeSize,c=Math.max(s,n),u=Math.min(l,r);if(c<u)if(a.isText)for(let f=c;f<u;f++)i.push(e.encodeCharacter(a.text.charCodeAt(f-s),a.marks));else a.isLeaf?i.push(e.encodeNodeStart(a)):(c==s&&i.push(e.encodeNodeStart(a)),ep(a.content,e,Math.max(s+1,c)-s-1,Math.min(l-1,u)-s-1,i),u==l&&i.push(e.encodeNodeEnd(a)));s=l}return i}var yR=5e3;function kR(t,e){return Math.min(15,Math.max(2,Math.floor(Math.max(t,e)/10)))}function Zx(t,e,n,r=Qx){let i=ep(t,r,n.fromA,n.toA,[]),o=ep(e,r,n.fromB,n.toB,[]),s=0,a=i.length,l=o.length,c=r.compareTokens;for(;s<i.length&&s<o.length&&c(i[s],o[s]);)s++;if(s==i.length&&s==o.length)return[];for(;a>s&&l>s&&c(i[a-1],o[l-1]);)a--,l--;if(a==s||l==s||a==l&&a==s+1)return[n.slice(s,a,s,l)];let u=a-s,f=l-s,d=Math.min(yR,u+f),p=d+1,h=[],m=[];for(let g=p*2,y=0;y<g;y++)m[y]=-1;for(let g=0;g<=d;g++){for(let y=-g;y<=g;y+=2){let b=m[y+1+d],C=m[y-1+d],v=b<C?C:b+1,A=v+y;for(;v<u&&A<f&&c(i[s+v],o[s+A]);)v++,A++;if(m[y+d]=v,v>=u&&A>=f){let w=[],N=kR(a-s,l-s),P=-1,O=-1,S=-1,me=-1,te=(F,W,q,se)=>{P>-1&&P<W+N?(P=F,S=q):(P>-1&&w.push(n.slice(P,O,S,me)),P=F,O=W,S=q,me=se)};for(let F=g-1;F>=0;F--){let W=m[y+1+d],q=m[y-1+d];W<q?(y--,v=q+s,A=v+y,te(v,v,A,A+1)):(y++,v=W+s,A=v+y,te(v,v+1,A,A)),m=h[F>>1]}return P>-1&&w.push(n.slice(P,O,S,me)),w.reverse()}}g%2==0&&h.push(m.slice())}return[n.slice(s,a,s,l)]}var Me=class t{constructor(e,n){this.length=e,this.data=n}cut(e){return e==this.length?this:new t(e,this.data)}static slice(e,n,r){if(n==r)return t.none;if(n==0&&r==t.len(e))return e;let i=[];for(let o=0,s=0;s<r;o++){let a=e[o],l=s+a.length,c=Math.min(r,l)-Math.max(n,s);c>0&&i.push(a.cut(c)),s=l}return i}static join(e,n,r){if(e.length==0)return n;if(n.length==0)return e;let i=r(e[e.length-1].data,n[0].data);if(i==null)return e.concat(n);let o=e.slice(0,e.length-1);o.push(new t(e[e.length-1].length+n[0].length,i));for(let s=1;s<n.length;s++)o.push(n[s]);return o}static len(e){let n=0;for(let r=0;r<e.length;r++)n+=e[r].length;return n}};Me.none=[];var Gt=class t{constructor(e,n,r,i,o,s){this.fromA=e,this.toA=n,this.fromB=r,this.toB=i,this.deleted=o,this.inserted=s}get lenA(){return this.toA-this.fromA}get lenB(){return this.toB-this.fromB}slice(e,n,r,i){return e==0&&r==0&&n==this.toA-this.fromA&&i==this.toB-this.fromB?this:new t(this.fromA+e,this.fromA+n,this.fromB+r,this.fromB+i,Me.slice(this.deleted,e,n),Me.slice(this.inserted,r,i))}static merge(e,n,r){if(e.length==0)return n;if(n.length==0)return e;let i=[];for(let o=0,s=0,a=e[0],l=n[0];;){if(!a&&!l)return i;if(a&&(!l||a.toB<l.fromA)){let c=s?n[s-1].toB-n[s-1].toA:0;i.push(c==0?a:new t(a.fromA,a.toA,a.fromB+c,a.toB+c,a.deleted,a.inserted)),a=o++==e.length?null:e[o]}else if(l&&(!a||l.toA<a.fromB)){let c=o?e[o-1].toB-e[o-1].toA:0;i.push(c==0?l:new t(l.fromA-c,l.toA-c,l.fromB,l.toB,l.deleted,l.inserted)),l=s++==n.length?null:n[s]}else{let c=Math.min(a.fromB,l.fromA),u=Math.min(a.fromA,l.fromA-(o?e[o-1].toB-e[o-1].toA:0)),f=u,d=Math.min(l.fromB,a.fromB+(s?n[s-1].toB-n[s-1].toA:0)),p=d,h=Me.none,m=Me.none,g=!1,y=!1;for(;;){let b=a?c>=a.fromB?a.toB:a.fromB:2e8,C=l?c>=l.fromA?l.toA:l.fromA:2e8,v=Math.min(b,C),A=a&&c>=a.fromB,w=l&&c>=l.fromA;if(!A&&!w)break;A&&c==a.fromB&&!g&&(h=Me.join(h,a.deleted,r),f+=a.lenA,g=!0),A&&!w&&(m=Me.join(m,Me.slice(a.inserted,c-a.fromB,v-a.fromB),r),p+=v-c),w&&c==l.fromA&&!y&&(m=Me.join(m,l.inserted,r),p+=l.lenB,y=!0),w&&!A&&(h=Me.join(h,Me.slice(l.deleted,c-l.fromA,v-l.fromA),r),f+=v-c),A&&v==a.toB&&(a=o++==e.length?null:e[o],g=!1),w&&v==l.toA&&(l=s++==n.length?null:n[s],y=!1),c=v}(u<f||d<p)&&i.push(new t(u,f,d,p,h,m))}}}static fromJSON(e){return new t(e.fromA,e.toA,e.fromB,e.toB,e.deleted.map(n=>new Me(n.length,n.data)),e.inserted.map(n=>new Me(n.length,n.data)))}toJSON(){return this}},bR;try{bR=new RegExp("[\\p{Alphabetic}_]","u")}catch{}var Ui=class t{constructor(e,n){this.config=e,this.changes=n}addSteps(e,n,r){let i=[];for(let l=0;l<n.length;l++){let c=Array.isArray(r)?r[l]:r,u=0;n[l].forEach((f,d,p,h)=>{i.push(new Gt(f+u,d+u,p,h,f==d?Me.none:[new Me(d-f,c)],p==h?Me.none:[new Me(h-p,c)])),u=h-p-(d-f)})}if(i.length==0)return this;let o=tp(i,this.config.combine),s=Gt.merge(this.changes,o,this.config.combine),a=s;for(let l=0;l<a.length;l++){let c=a[l];if(c.fromA==c.toA||c.fromB==c.toB||!o.some(f=>f.toB>c.fromB&&f.fromB<c.toB))continue;let u=Zx(this.config.doc.content,e.content,c,this.config.encoder);u.length==1&&u[0].fromB==0&&u[0].toB==c.toB-c.fromB||(a==s&&(a=s.slice()),u.length==1?a[l]=u[0]:(a.splice(l,1,...u),l+=u.length-1))}return new t(this.config,a)}get startDoc(){return this.config.doc}map(e){let n=r=>{let i=e(r);return i===r.data?r:new Me(r.length,i)};return new t(this.config,this.changes.map(r=>new Gt(r.fromA,r.toA,r.fromB,r.toB,r.deleted.map(n),r.inserted.map(n))))}changedRange(e,n){if(e==this)return null;let r=n&&xR(n),i=r?r.toB-r.fromB-(r.toA-r.fromA):0;function o(f){return!r||f<=r.fromA?f:f+i}let s=r?r.fromB:2e8,a=r?r.toB:-2e8;function l(f,d=f){s=Math.min(f,s),a=Math.max(d,a)}let c=this.changes,u=e.changes;for(let f=0,d=0;f<c.length&&d<u.length;){let p=c[f],h=u[d];p&&h&&wR(p,h,o)?(f++,d++):h&&(!p||o(p.fromB)>=h.fromB)?(l(h.fromB,h.toB),d++):(l(o(p.fromB),o(p.toB)),f++)}return s<=a?{from:s,to:a}:null}static create(e,n=(o,s)=>o===s?o:null,r=Qx,i=[]){return new t({combine:n,doc:e,encoder:r},i)}};Ui.computeDiff=Zx;function tp(t,e,n=0,r=t.length){if(r==n+1)return[t[n]];let i=n+r>>1;return Gt.merge(tp(t,e,n,i),tp(t,e,i,r),e)}function Xx(t){let e=2e8,n=-2e8;for(let r=0;r<t.length;r++){let i=t[r];e!=2e8&&(e=i.map(e,-1),n=i.map(n,1)),i.forEach((o,s,a,l)=>{e=Math.min(e,a),n=Math.max(n,l)})}return e==2e8?null:{from:e,to:n}}function xR(t){let e=Xx(t);if(!e)return null;let n=Xx(t.map(r=>r.invert()).reverse());return{fromA:n.from,toA:n.to,fromB:e.from,toB:e.to}}function wR(t,e,n){return n(t.fromB)==e.fromB&&n(t.toB)==e.toB&&Yx(t.deleted,e.deleted)&&Yx(t.inserted,e.inserted)}function Yx(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(t[n].length!=e[n].length||t[n].data!==e[n].data)return!1;return!0}function Xt(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-diff",...e}}),t}var ew=500;function CR(t={}){let e=new WeakMap,n=new WeakMap;function r(i){let o=e.get(i);if(o!=null)return o;let s=i.attrs,a=s?Object.keys(s).filter(l=>s[l]!=null).sort():[];if(a.length===0)o=i.type.name;else{let l={};for(let c of a)l[c]=s[c];o=`${i.type.name}:${JSON.stringify(l)}`}return e.set(i,o),o}return{encodeCharacter:(i,o)=>{if(o.length===0)return i;let s=n.get(o);return s==null&&(s=o.map(r).join(","),n.set(o,s)),`${i}:${s}`},encodeNodeStart:i=>{let o=i.attrs;if(o&&Object.keys(o).length>0){let s=t[i.type.name]??[],a=Object.keys(o).filter(l=>{if(s.includes(l))return!1;let c=i.type.spec.attrs?.[l]?.default;return o[l]!==c});if(a.length>0){let l={};for(let c of a.sort())l[c]=o[c];return`${i.type.name}:${JSON.stringify(l)}`}}return i.type.name},encodeNodeEnd:i=>{let o=i.type.schema,s=o.cached.changeSetIDs||(o.cached.changeSetIDs=Object.create(null)),a=s[i.type.name];return a==null&&(s[i.type.name]=a=Object.keys(o.nodes).indexOf(i.type.name)+1),-a},compareTokens:(i,o)=>i===o}}function iw(t,e,n){let r=n.get(t);if(r!=null)return r;let i=[String(e.encodeNodeStart(t))];if(t.isText){let s=t.text;for(let a=0;a<s.length;a++)i.push(":"+String(e.encodeCharacter(s.charCodeAt(a),t.marks)))}else t.content.forEach(s=>{i.push("/"+iw(s,e,n))});i.push("\\"+String(e.encodeNodeEnd(t)));let o=i.join("");return n.set(t,o),o}function tw(t,e,n){let r=[],i=0;return t.content.forEach(o=>{r.push({node:o,offset:i,size:o.nodeSize,signature:iw(o,n.encoder,n.sigCache)}),i+=o.nodeSize}),{node:t,contentStart:e,content:r}}function SR(t,e){let n=t.length,r=e.length,i=Array.from({length:n+1},()=>Array.from({length:r+1},()=>0));for(let l=n-1;l>=0;l--)for(let c=r-1;c>=0;c--)t[l].signature===e[c].signature?i[l][c]=i[l+1][c+1]+1:i[l][c]=Math.max(i[l+1][c],i[l][c+1]);let o=[],s=0,a=0;for(;s<n&&a<r;)t[s].signature===e[a].signature?(o.push([s,a]),s++,a++):i[s+1][a]>=i[s][a+1]?s++:a++;return o}function MR(t,e){if(t.type!==e.type)return!1;let n=t.type;return!(n.isTextblock||n.isAtom||n.spec.code===!0||!n.isBlock)}function ow(t,e,n){return Gt.fromJSON({fromA:t.fromA+e,toA:t.toA+e,fromB:t.fromB+n,toB:t.toB+n,deleted:t.deleted.map(r=>({length:r.length,data:r.data})),inserted:t.inserted.map(r=>({length:r.length,data:r.data}))})}function ER(t,e,n){let r=t.parent.copy(M.from(t.node)),i=e.parent.copy(M.from(e.node)),o=new Ce(0,r.content.size,new R(i.content,0,0));return Ui.create(r,void 0,n.encoder).addSteps(i,[o.getMap()],null).changes.map(s=>ow(s,t.abs,e.abs))}function nw(t,e){let n=t.content;if(e<n.length)return t.contentStart+n[e].offset;if(e>0){let r=n[e-1];return t.contentStart+r.offset+r.size}return t.contentStart+t.node.content.size}function TR(t,e,n){return Gt.fromJSON({fromA:e,toA:e+t.size,fromB:n,toB:n,deleted:[{length:t.size,data:null}],inserted:[]})}function vR(t,e,n){return Gt.fromJSON({fromA:e,toA:e,fromB:n,toB:n+t.size,deleted:[],inserted:[{length:t.size,data:null}]})}function AR(t,e,n,r,i){let o=new Ce(0,t.content.size,new R(e.content,0,0));return Ui.create(t,void 0,i.encoder).addSteps(e,[o.getMap()],null).changes.map(s=>ow(s,n,r))}function xl(t,e,n,r,i){if(t.childCount>ew||e.childCount>ew)return AR(t,e,n,r,i);let o=tw(t,n,i),s=tw(e,r,i),a=SR(o.content,s.content),l=[],c=0,u=0;for(let[f,d]of a)rw(o,s,{oldStart:c,oldEnd:f,newStart:u,newEnd:d},i,l),c=f+1,u=d+1;return rw(o,s,{oldStart:c,oldEnd:o.content.length,newStart:u,newEnd:s.content.length},i,l),l}function rw(t,e,n,r,i){let o=t.content,s=e.content,a=n.oldStart,l=n.newStart;for(;a<n.oldEnd||l<n.newEnd;){let c=a<n.oldEnd?o[a]:null,u=l<n.newEnd?s[l]:null,f=c&&u&&c.node.type===u.node.type;if(c&&u&&f){i.push(...IR(t,e,c,u,r)),a++,l++;continue}if(c&&(!u||!f)){let d=t.contentStart+c.offset;i.push(TR(c,d,nw(e,l))),a++;continue}if(u){let d=e.contentStart+u.offset;i.push(vR(u,nw(t,a),d)),l++}}}function IR(t,e,n,r,i){let o=t.contentStart+n.offset,s=e.contentStart+r.offset;return MR(n.node,r.node)&&NR(n.node,r.node,i.encoder)?xl(n.node,r.node,o+1,s+1,i):ER({node:n.node,parent:t.node,abs:o},{node:r.node,parent:e.node,abs:s},i)}function NR(t,e,n){return n.encodeNodeStart(t)===n.encodeNodeStart(e)}function RR(t,e,n,r,i){let o=t.resolve(n),s=t.resolve(r),a=e.resolve(n),l=e.resolve(r),c=o.sharedDepth(r);if(a.sharedDepth(r)!==c)throw new RangeError(`computeDocDiff: range [${n}, ${r}) resolves to different sharedDepth in old and new docs`);for(let m=0;m<=c;m++){if(i.encodeNodeStart(o.node(m))!==i.encodeNodeStart(a.node(m)))throw new RangeError(`computeDocDiff: ancestor at depth ${m} differs in type or non-ignored attrs along the path to the shared ancestor`);if(o.start(m)!==a.start(m))throw new RangeError(`computeDocDiff: ancestor at depth ${m} starts at different absolute positions in old and new docs (content before the range differs in size)`)}let u=o.node(c);if(u.isTextblock)throw new RangeError(`computeDocDiff: range [${n}, ${r}) lands inside a textblock; widen the range to a block boundary`);if(o.depth!==c||s.depth!==c||a.depth!==c||l.depth!==c)throw new RangeError(`computeDocDiff: range [${n}, ${r}) endpoints must be aligned to child boundaries of the shared ancestor`);let f=a.node(c),d=o.start(c),p=n-d,h=r-d;return{oldCut:u.copy(u.content.cut(p,h)),newCut:f.copy(f.content.cut(p,h)),cutAbsStart:n}}function ps(t,e,n){let r=CR(n?.ignoreAttrs),i={encoder:r,sigCache:new WeakMap},o=t.content.size,s=e.content.size,a=n?.range;if(a==null)return xl(t,e,0,0,i);let l=Math.min(o,s),c=Math.max(0,Math.min(a.from??0,l)),u=Math.max(c,Math.min(a.to??l,l));if(c===u)return[];if(c===0&&u===l&&o===s)return xl(t,e,0,0,i);let f=RR(t,e,c,u,r);return xl(f.oldCut,f.newCut,f.cutAbsStart,f.cutAbsStart,i)}var sw=Ie({ignoreAttrs:{heading:["id"]}},"diffConfig");Xt(sw,{displayName:"Ctx<diffConfig>",group:"Diff"});var Le=new ee("MILKDOWN_DIFF");function OR(t,e,n){let r=ps(t,e.newDoc,n);return{...e,changes:r}}function DR(t,e){return e.some(n=>t.fromB<n.toB&&t.toB>n.fromB)}function wl(t){return t.changes.filter(e=>!DR(e,t.rejectedRanges))}var LR=pe(t=>{let e=t.get(sw.key);return new X({key:Le,state:{init:()=>null,apply(n,r,i,o){let s=n.getMeta(Le);if(!r){if(s?.type==="start"){let c=ps(o.doc,s.newDoc,{ignoreAttrs:e.ignoreAttrs});return{newDoc:s.newDoc,changes:c,rejectedRanges:[],active:!0}}return null}let a=r;if(n.docChanged&&a.active&&(a=OR(o.doc,a,{ignoreAttrs:e.ignoreAttrs})),!s)return a;let l;switch(s.type){case"start":{let c=ps(o.doc,s.newDoc,{ignoreAttrs:e.ignoreAttrs});return{newDoc:s.newDoc,changes:c,rejectedRanges:[],active:!0}}case"accept":case"acceptRange":l=a;break;case"reject":l={...a,rejectedRanges:[...a.rejectedRanges,{fromB:s.fromB,toB:s.toB}]};break;case"rejectRange":l={...a,rejectedRanges:[...a.rejectedRanges,{fromB:s.range.fromB,toB:s.range.toB}]};break;case"acceptAll":case"clear":return null;default:return a}return l.active&&wl(l).length===0?null:l}},filterTransaction(n,r){return!Le.getState(r)?.active||n.getMeta(Le)?!0:!n.docChanged}})});Xt(LR,{displayName:"Prose<diff>",group:"Diff"});function PR(t,e){let n=wl(e);for(let r=n.length-1;r>=0;r--){let i=n[r],o=e.newDoc.slice(i.fromB,i.toB);t=t.replace(i.fromA,i.toA,o)}return t}var BR=z("StartDiffReview",t=>e=>(n,r)=>{if(e==null)return!1;let i=t.get(He)(e);return i?(r&&r(n.tr.setMeta(Le,{type:"start",newDoc:i})),!0):!1});Xt(BR,{displayName:"Command<startDiffReview>",group:"Diff"});var np=z("StartDiffReviewFromDoc",()=>t=>(e,n)=>!t||t.type!==e.doc.type?!1:(n&&n(e.tr.setMeta(Le,{type:"start",newDoc:t})),!0));Xt(np,{displayName:"Command<startDiffReviewFromDoc>",group:"Diff"});var FR=z("AcceptDiffChunk",()=>t=>(e,n)=>{if(t==null)return!1;let r=Le.getState(e);if(!r)return!1;let i=wl(r)[t];if(!i)return!1;if(n){let o=r.newDoc.slice(i.fromB,i.toB),s=e.tr.replace(i.fromA,i.toA,o);s=s.setMeta(Le,{type:"accept",changeIndex:t}),n(s)}return!0});Xt(FR,{displayName:"Command<acceptDiffChunk>",group:"Diff"});var zR=z("RejectDiffChunk",()=>t=>(e,n)=>{if(t==null)return!1;let r=Le.getState(e);if(!r)return!1;let i=wl(r)[t];return i?(n&&n(e.tr.setMeta(Le,{type:"reject",fromB:i.fromB,toB:i.toB})),!0):!1});Xt(zR,{displayName:"Command<rejectDiffChunk>",group:"Diff"});var _R=z("AcceptDiffRange",()=>t=>(e,n)=>{if(!t)return!1;let r=Le.getState(e);if(!r)return!1;if(n){let i=r.newDoc.slice(t.fromB,t.toB),o=e.tr.replace(t.fromA,t.toA,i);o=o.setMeta(Le,{type:"acceptRange",range:t}),n(o)}return!0});Xt(_R,{displayName:"Command<acceptDiffRange>",group:"Diff"});var $R=z("RejectDiffRange",()=>t=>(e,n)=>!t||!Le.getState(e)?!1:(n&&n(e.tr.setMeta(Le,{type:"rejectRange",range:t})),!0));Xt($R,{displayName:"Command<rejectDiffRange>",group:"Diff"});var HR=z("AcceptAllDiffs",()=>()=>(t,e)=>{let n=Le.getState(t);return n?(e&&e((n.rejectedRanges.length===0?t.tr.replaceWith(0,t.doc.content.size,n.newDoc.content):PR(t.tr,n)).setMeta(Le,{type:"acceptAll"})),!0):!1});Xt(HR,{displayName:"Command<acceptAllDiffs>",group:"Diff"});var WR=z("ClearDiffReview",()=>()=>(t,e)=>Le.getState(t)?(e&&e(t.tr.setMeta(Le,{type:"clear"})),!0):!1);Xt(WR,{displayName:"Command<clearDiffReview>",group:"Diff"});function Ji(t,e){return Object.assign(t,{meta:{package:"@milkdown/plugin-streaming",...e}}),t}var qn=Ie({throttleMs:100,scrollFollow:!0,diffReviewOnEnd:!1,ignoreAttrs:{heading:["id"]}},"streamingConfig");Ji(qn,{displayName:"Ctx<streamingConfig>",group:"Streaming"});function jR(t,e,n){let r=t.get(He)(n);if(!r)return{tr:e,newDoc:null};let i=t.get(qn.key).ignoreAttrs,o=ps(e.doc,r,i?{ignoreAttrs:i}:void 0);for(let s=o.length-1;s>=0;s--){let a=o[s],l=r.slice(a.fromB,a.toB);e=e.replace(a.fromA,a.toA,l)}return{tr:e,newDoc:r}}function VR(t){if(t.parent.type.spec.code)return{type:"plain-text",preserveNewlines:!0};for(let e=t.depth;e>0;e--)if(t.node(e).type.name==="table")return{type:"plain-text",preserveNewlines:!1};return t.depth>=1?{type:"split-block"}:{type:"block"}}function aw(t){if(t.childCount===0)return t;let e=t.lastChild;return e.type.name==="paragraph"&&e.content.size===0?t.cut(0,t.size-e.nodeSize):t}function qR(t,e,n){let{insertPos:r,currentEndPos:i}=n,o=n.buffer.replace(/\r\n?/g,` +`);if(!o)return{tr:e,applied:!1,insertEndPos:i};let s=e.doc.content.size,a=Math.max(0,Math.min(r,s)),l=Math.max(a,Math.min(i,s)),c=e.doc.resolve(a),u=(t.get(qn.key).insertStrategy??VR)(c),f={ctx:t,tr:e,buffer:o,from:a,to:l,resolved:c};switch(u.type){case"plain-text":return KR(f,u.preserveNewlines??!1);case"split-block":return JR(f);case"block":return GR(f)}}function KR({tr:t,buffer:e,from:n,to:r},i){let o=i?e:e.replace(/\n/g," "),s=t.doc.type.schema.text(o);return t=t.replaceWith(n,r,s),{tr:t,applied:!0,insertEndPos:n+o.length}}var UR=/[*_~`[\\<]/;function rp(t,e,n){if(!n)return M.empty;if(!UR.test(n))return M.from(e.text(n));let r=t.get(He)(n)?.firstChild;if(r?.type.name!=="paragraph"||r.content.size===0)return M.from(e.text(n));let i=!1;if(r.content.forEach(l=>{(!l.isText||l.marks.length>0)&&(i=!0)}),!i)return M.from(e.text(n));let o=r.content,s=/^\s+/.exec(n)?.[0];s&&((o.firstChild?.isText?o.firstChild.text??"":"").startsWith(s)||(o=M.from(e.text(s)).append(o)));let a=/\s+$/.exec(n)?.[0];return a&&((o.lastChild?.isText?o.lastChild.text??"":"").endsWith(a)||(o=o.append(M.from(e.text(a))))),o}function JR({ctx:t,tr:e,buffer:n,from:r,to:i,resolved:o}){let s=e.doc.type.schema,a=n.indexOf(` +`);if(a<0){let A=rp(t,s,n);return e=e.replaceWith(r,i,A),{tr:e,applied:!0,insertEndPos:r+A.size}}let l=n.substring(0,a),c=n.substring(a+1),u=t.get(He),f=c.trim()?u(c):null,d=f?aw(f.content):M.empty;if(d.childCount===0){let A=rp(t,s,n.replace(/\n/g," "));return e=e.replaceWith(r,i,A),{tr:e,applied:!0,insertEndPos:r+A.size}}let p=o.depth,h=rp(t,s,l);for(let A=p;A>0;A--)h=M.from(o.node(A).copy(h));let m=h.append(d),g=new R(m,p,0),y=e.doc.content.size,b=e.doc.resolve(Math.min(i,y)),C=i;p>0&&b.depth===p&&b.parentOffset===b.parent.content.size&&(C=b.after(p)),e=e.replace(r,C,g);let v=m.size-p;return{tr:e,applied:!0,insertEndPos:r+v}}function GR({ctx:t,tr:e,buffer:n,from:r,to:i}){let o=t.get(He)(n);if(!o)return{tr:e,applied:!1,insertEndPos:i};let s=aw(o.content);return s.size===0?{tr:e,applied:!1,insertEndPos:i}:(e=e.replace(r,i,new R(s,0,0)),{tr:e,applied:!0,insertEndPos:r+s.size})}function ip(t,e,n){if(n.insertPos!=null){let r=n.insertPos,i=qR(t,e,{buffer:n.buffer,insertPos:r,currentEndPos:n.insertEndPos??r});return{tr:i.tr,newDoc:i.applied?i.tr.doc:null,insertEndPos:i.insertEndPos}}return jR(t,e,n.buffer)}var tt=new ee("MILKDOWN_STREAMING");function XR(t,e){if(!t&&e?.type!=="start")return null;if(!e)return t;switch(e.type){case"start":return{buffer:"",originalDoc:e.originalDoc,active:!0,lastApplyTime:e.lastApplyTime,insertPos:e.insertPos??null,insertEndPos:e.insertEndPos??e.insertPos??null};case"push":return t?{...t,buffer:t.buffer+e.token}:null;case"apply":return t?{...t,lastApplyTime:e.lastApplyTime,insertEndPos:e.insertEndPos??t.insertEndPos}:null;case"end":case"abort":return null;default:return t}}var lw=pe(t=>{let e=t.get(qn.key);return new X({key:tt,state:{init:()=>null,apply(n,r){return XR(r,n.getMeta(tt))}},filterTransaction(n,r){return!tt.getState(r)?.active||n.getMeta(tt)?!0:!n.docChanged},view(){return YR(t,e)}})});Ji(lw,{displayName:"Prose<streaming>",group:"Streaming"});function YR(t,e){let n=null,r=-1,i=null;function o(){if(!i)return;let a=tt.getState(i.state);if(!a?.active||a.buffer.length===r)return;r=a.buffer.length;let l=ip(t,i.state.tr,a);if(!l.newDoc)return;let c=l.tr;!c.docChanged&&l.insertEndPos==null||(c=c.setMeta(tt,{type:"apply",lastApplyTime:Date.now(),insertEndPos:l.insertEndPos}),e.scrollFollow&&(c=c.scrollIntoView()),i.dispatch(c))}function s(){n!=null&&clearTimeout(n),n=setTimeout(o,e.throttleMs)}return{update(a){i=a;let l=tt.getState(a.state);if(!l?.active){n!=null&&(clearTimeout(n),n=null),r=-1;return}l.buffer.length!==r&&(Date.now()-l.lastApplyTime>=e.throttleMs?o():s())},destroy(){n!=null&&(clearTimeout(n),n=null),i=null}}}var $r=z("StartStreaming",()=>t=>(e,n)=>{if(tt.getState(e)?.active)return!1;if(n){let r,i;if(t?.insertAt!=null)if(t.insertAt==="selection"){if(r=e.selection.from,i=e.selection.to,e.selection.empty){let o=e.doc.resolve(r);o.parent.isTextblock&&!o.parent.type.spec.code&&o.parent.content.size===0&&o.depth===1&&(r=o.before(o.depth),i=o.after(o.depth))}}else{let o=t.insertAt==="cursor"?e.selection.head:t.insertAt;if(!Number.isFinite(o))return!1;r=Math.max(0,Math.min(Math.round(o),e.doc.content.size));let s=e.doc.resolve(r);s.parent.isTextblock&&!s.parent.type.spec.code&&s.parent.content.size===0&&s.depth===1&&(r=s.before(s.depth),i=s.after(s.depth))}n(e.tr.setMeta(tt,{type:"start",originalDoc:e.doc,insertPos:r,insertEndPos:i,lastApplyTime:Date.now()}))}return!0});Ji($r,{displayName:"Command<startStreaming>",group:"Streaming"});var hs=z("PushChunk",()=>t=>(e,n)=>t==null||!tt.getState(e)?.active?!1:(n&&n(e.tr.setMeta(tt,{type:"push",token:t})),!0));Ji(hs,{displayName:"Command<pushChunk>",group:"Streaming"});var Gi=z("EndStreaming",t=>e=>(n,r)=>{let i=tt.getState(n);if(!i?.active)return!1;if(r){let o=t.get(qn.key),s=e?.diffReview??o.diffReviewOnEnd,a=ip(t,n.tr,i),l=a.tr;if(l=l.setMeta(tt,{type:"end"}),s&&a.newDoc){let c=l.doc;l=l.replace(0,l.doc.content.size,new R(i.originalDoc.content,0,0)),r(l);try{t.get(Q).call(np.key,c)}catch(u){console.warn("[milkdown/streaming] diff review handoff skipped:",u)}return!0}r(l)}return!0});Ji(Gi,{displayName:"Command<endStreaming>",group:"Streaming"});var ms=z("AbortStreaming",t=>e=>(n,r)=>{let i=tt.getState(n);if(!i?.active)return!1;if(r){let o=e?.keep??!1,s=n.tr;o?s=ip(t,s,i).tr:s=s.replace(0,n.doc.content.size,new R(i.originalDoc.content,0,0)),s=s.setMeta(tt,{type:"abort"}),r(s)}return!0});Ji(ms,{displayName:"Command<abortStreaming>",group:"Streaming"});var cw=[qn,lw,$r,hs,Gi,ms];var uw=new ee("weibeiStreamingAppearance"),QR={class:"wb-stream-in"},ZR={side:1},eO=260,tO=400,nO=24;function rO(){let t=document.createElement("span");return t.className="wb-stream-caret",t}function fw(t){return new X({key:uw,state:{init:()=>({fades:[],caretPosition:null,caretExpiresAt:0,set:ae.empty}),apply(e,n){let r=Date.now(),i=[],o=e.doc.content.size;for(let c of n.fades){let u=Math.min(e.mapping.map(c.from),o),f=Math.min(e.mapping.map(c.to),o);u>=f||r>=c.expiresAt||e.doc.resolve(u).parent===e.doc.resolve(f).parent&&i.push({from:u,to:f,expiresAt:c.expiresAt})}let s=n.caretPosition===null?null:Math.min(e.mapping.map(n.caretPosition),o),a=n.caretExpiresAt;e.docChanged&&t()&&e.steps.forEach((c,u)=>{let f=e.mapping.slice(u+1);e.mapping.maps[u].forEach((d,p,h,m)=>{if(m<=h)return;let g=f.map(h),y=f.map(m);if(y-g>nO)return;let b=e.doc.resolve(g);b.parent===e.doc.resolve(y).parent&&b.parent.isTextblock&&(i.push({from:g,to:y,expiresAt:r+eO}),s=y,a=r+tO)})}),s!==null&&r>=a&&(s=null);let l=i.map(c=>le.inline(c.from,c.to,QR));return s!==null&&l.push(le.widget(s,rO,ZR)),{fades:i,caretPosition:s,caretExpiresAt:a,set:ae.create(e.doc,l)}}},props:{decorations(e){let n=uw.getState(e);return!n||!t()?ae.empty:n.set}}})}var Sl=Math.min,Hr=Math.max,ys=Math.round;var Yt=t=>({x:t,y:t}),iO={left:"right",right:"left",bottom:"top",top:"bottom"};function Ml(t,e){return typeof t=="function"?t(e):t}function Wr(t){return t.split("-")[0]}function ks(t){return t.split("-")[1]}function hw(t){return t==="x"?"y":"x"}function op(t){return t==="y"?"height":"width"}function Kn(t){let e=t[0];return e==="t"||e==="b"?"y":"x"}function sp(t){return hw(Kn(t))}function mw(t,e,n){n===void 0&&(n=!1);let r=ks(t),i=sp(t),o=op(i),s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(s=gs(s)),[s,gs(s)]}function gw(t){let e=gs(t);return[Cl(t),e,Cl(e)]}function Cl(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}var dw=["left","right"],pw=["right","left"],oO=["top","bottom"],sO=["bottom","top"];function aO(t,e,n){switch(t){case"top":case"bottom":return n?e?pw:dw:e?dw:pw;case"left":case"right":return e?oO:sO;default:return[]}}function yw(t,e,n,r){let i=ks(t),o=aO(Wr(t),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),e&&(o=o.concat(o.map(Cl)))),o}function gs(t){let e=Wr(t);return iO[e]+t.slice(e.length)}function lO(t){var e,n,r,i;return{top:(e=t.top)!=null?e:0,right:(n=t.right)!=null?n:0,bottom:(r=t.bottom)!=null?r:0,left:(i=t.left)!=null?i:0}}function kw(t){return typeof t!="number"?lO(t):{top:t,right:t,bottom:t,left:t}}function jr(t){let{x:e,y:n,width:r,height:i}=t;return{width:r,height:i,top:n,left:e,right:e+r,bottom:n+i,x:e,y:n}}function bw(t,e,n){let{reference:r,floating:i}=t,o=Kn(e),s=sp(e),a=op(s),l=Wr(e),c=o==="y",u=r.x+r.width/2-i.width/2,f=r.y+r.height/2-i.height/2,d=r[a]/2-i[a]/2,p;switch(l){case"top":p={x:u,y:r.y-i.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-i.width,y:f};break;default:p={x:r.x,y:r.y}}let h=ks(e);return h&&(p[s]+=d*(h==="end"?1:-1)*(n&&c?-1:1)),p}async function xw(t,e){var n;e===void 0&&(e={});let{x:r,y:i,platform:o,rects:s,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:f="floating",altBoundary:d=!1,padding:p=0}=Ml(e,t),h=kw(p),g=a[d?f==="floating"?"reference":"floating":f],y=jr(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(g)))==null||n?g:g.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),b=f==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,C=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),v=await(o.isElement==null?void 0:o.isElement(C))&&await(o.getScale==null?void 0:o.getScale(C))||{x:1,y:1},A=jr(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:C,strategy:l}):b);return{top:(y.top-A.top+h.top)/v.y,bottom:(A.bottom-y.bottom+h.bottom)/v.y,left:(y.left-A.left+h.left)/v.x,right:(A.right-y.right+h.right)/v.x}}var cO=50,ww=async(t,e,n)=>{let{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,a=s.detectOverflow?s:{...s,detectOverflow:xw},l=await(s.isRTL==null?void 0:s.isRTL(e)),c=await s.getElementRects({reference:t,floating:e,strategy:i}),{x:u,y:f}=bw(c,r,l),d=r,p=0,h={};for(let m=0;m<o.length;m++){let g=o[m];if(!g)continue;let{name:y,fn:b}=g,{x:C,y:v,data:A,reset:w}=await b({x:u,y:f,initialPlacement:r,placement:d,strategy:i,middlewareData:h,rects:c,platform:a,elements:{reference:t,floating:e}});u=C??u,f=v??f,h[y]={...h[y],...A},w&&p<cO&&(p++,typeof w=="object"&&(w.placement&&(d=w.placement),w.rects&&(c=w.rects===!0?await s.getElementRects({reference:t,floating:e,strategy:i}):w.rects),{x:u,y:f}=bw(c,d,l)),m=-1)}return{x:u,y:f,placement:d,strategy:i,middlewareData:h}};var Cw=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;let{placement:i,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:f=!0,fallbackPlacements:d,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:m=!0,...g}=Ml(t,e);if((n=o.arrow)!=null&&n.alignmentOffset)return{};let y=Wr(i),b=Kn(a),C=Wr(a)===a,v=await(l.isRTL==null?void 0:l.isRTL(c.floating)),A=d||(C||!m?[gs(a)]:gw(a)),w=h!=="none";!d&&w&&A.push(...yw(a,m,h,v));let N=[a,...A],P=await l.detectOverflow(e,g),O=[],S=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&O.push(P[y]),f){let W=mw(i,s,v);O.push(P[W[0]],P[W[1]])}if(S=[...S,{placement:i,overflows:O}],!O.every(W=>W<=0)){var me,te;let W=(((me=o.flip)==null?void 0:me.index)||0)+1,q=N[W];if(q&&(!(f==="alignment"?b!==Kn(q):!1)||S.every(ke=>Kn(ke.placement)===b?ke.overflows[0]>0:!0)))return{data:{index:W,overflows:S},reset:{placement:q}};let se=(te=S.filter(fe=>fe.overflows[0]<=0).sort((fe,ke)=>fe.overflows[1]-ke.overflows[1])[0])==null?void 0:te.placement;if(!se)switch(p){case"bestFit":{var F;let fe=(F=S.filter(ke=>{if(w){let Te=Kn(ke.placement);return Te===b||Te==="y"}return!0}).map(ke=>[ke.placement,ke.overflows.filter(Te=>Te>0).reduce((Te,k)=>Te+k,0)]).sort((ke,Te)=>ke[1]-Te[1])[0])==null?void 0:F[0];fe&&(se=fe);break}case"initialPlacement":se=a;break}if(i!==se)return{reset:{placement:se}}}return{}}}};var uO=new Set(["left","top"]);async function fO(t,e){let{placement:n,platform:r,elements:i}=t,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=Wr(n),a=ks(n),l=Kn(n)==="y",c=uO.has(s)?-1:1,u=o&&l?-1:1,f=Ml(e,t),{mainAxis:d,crossAxis:p,alignmentAxis:h}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof h=="number"&&(p=a==="end"?h*-1:h),l?{x:p*u,y:d*c}:{x:d*c,y:p*u}}var Sw=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;let{x:i,y:o,placement:s,middlewareData:a}=e,l=await fO(e,t);return s===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}};function Tl(){return typeof window<"u"}function qr(t){return Ew(t)?(t.nodeName||"").toLowerCase():"#document"}function ot(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function wn(t){var e;return(e=(Ew(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Ew(t){return Tl()?t instanceof Node||t instanceof ot(t).Node:!1}function Ft(t){return Tl()?t instanceof Element||t instanceof ot(t).Element:!1}function Cn(t){return Tl()?t instanceof HTMLElement||t instanceof ot(t).HTMLElement:!1}function Mw(t){return!Tl()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof ot(t).ShadowRoot}function bs(t){let{overflow:e,overflowX:n,overflowY:r,display:i}=zt(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&i!=="inline"&&i!=="contents"}function Tw(t){return/^(table|td|th)$/.test(qr(t))}function xs(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}var dO=/transform|translate|scale|rotate|perspective|filter/,pO=/paint|layout|strict|content/,Vr=t=>!!t&&t!=="none",ap;function vl(t){let e=Ft(t)?zt(t):t;return Vr(e.transform)||Vr(e.translate)||Vr(e.scale)||Vr(e.rotate)||Vr(e.perspective)||!Al()&&(Vr(e.backdropFilter)||Vr(e.filter))||dO.test(e.willChange||"")||pO.test(e.contain||"")}function vw(t){let e=Un(t);for(;Cn(e)&&!Xi(e);){if(vl(e))return e;if(xs(e))return null;e=Un(e)}return null}function Al(){return ap==null&&(ap=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),ap}function Xi(t){return/^(html|body|#document)$/.test(qr(t))}function zt(t){return ot(t).getComputedStyle(t)}function ws(t){return Ft(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Un(t){if(qr(t)==="html")return t;let e=t.assignedSlot||t.parentNode||Mw(t)&&t.host||wn(t);return Mw(e)?e.host:e}function Aw(t){let e=Un(t);return Xi(e)?(t.ownerDocument||t).body:Cn(e)&&bs(e)?e:Aw(e)}function El(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);let i=Aw(t),o=i===((r=t.ownerDocument)==null?void 0:r.body),s=ot(i);if(o){let a=Il(s);return e.concat(s,s.visualViewport||[],bs(i)?i:[],a&&n?El(a):[])}else return e.concat(i,El(i,[],n))}function Il(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Rw(t){let e=zt(t),n=parseFloat(e.width)||0,r=parseFloat(e.height)||0,i=Cn(t),o=i?t.offsetWidth:n,s=i?t.offsetHeight:r,a=ys(n)!==o||ys(r)!==s;return a&&(n=o,r=s),{width:n,height:r,$:a}}function Ow(t){return Ft(t)?t:t.contextElement}function Yi(t){let e=Ow(t);if(!Cn(e))return Yt(1);let n=e.getBoundingClientRect(),{width:r,height:i,$:o}=Rw(e),s=(o?ys(n.width):n.width)/r,a=(o?ys(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}var hO=Yt(0);function Dw(t){let e=ot(t);return!Al()||!e.visualViewport?hO:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function mO(t,e,n){return e===void 0&&(e=!1),!!n&&e&&n===ot(t)}function Cs(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);let i=t.getBoundingClientRect(),o=Ow(t),s=Yt(1);e&&(r?Ft(r)&&(s=Yi(r)):s=Yi(t));let a=mO(o,n,r)?Dw(o):Yt(0),l=(i.left+a.x)/s.x,c=(i.top+a.y)/s.y,u=i.width/s.x,f=i.height/s.y;if(o&&r){let d=ot(o),p=Ft(r)?ot(r):r,h=d,m=Il(h);for(;m&&p!==h;){let g=Yi(m),y=m.getBoundingClientRect(),b=zt(m),C=y.left+(m.clientLeft+parseFloat(b.paddingLeft))*g.x,v=y.top+(m.clientTop+parseFloat(b.paddingTop))*g.y;l*=g.x,c*=g.y,u*=g.x,f*=g.y,l+=C,c+=v,h=ot(m),m=Il(h)}}return jr({width:u,height:f,x:l,y:c})}function Nl(t,e){let n=ws(t).scrollLeft;return e?e.left+n:Cs(wn(t)).left+n}function Lw(t,e){let n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-Nl(t,n),i=n.top+e.scrollTop;return{x:r,y:i}}function gO(t){let{elements:e,rect:n,offsetParent:r,strategy:i}=t,o=i==="fixed",s=wn(r),a=e?xs(e.floating):!1;if(r===s||a&&o)return n;let l={scrollLeft:0,scrollTop:0},c=Yt(1),u=Yt(0),f=Cn(r);if((f||!o)&&((qr(r)!=="body"||bs(s))&&(l=ws(r)),f)){let p=Cs(r);c=Yi(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}let d=s&&!f&&!o?Lw(s,l):Yt(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+d.x,y:n.y*c.y-l.scrollTop*c.y+u.y+d.y}}function yO(t){return t.getClientRects?Array.from(t.getClientRects()):[]}function kO(t){let e=ws(t),n=t.ownerDocument.body,r=Hr(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=Hr(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight),o=-e.scrollLeft+Nl(t),s=-e.scrollTop;return zt(n).direction==="rtl"&&(o+=Hr(t.clientWidth,n.clientWidth)-r),{width:r,height:i,x:o,y:s}}var bO=25;function xO(t,e,n){n===void 0&&(n="viewport");let r=n==="layoutViewport",i=ot(t),o=wn(t),s=i.visualViewport,a=o.clientWidth,l=o.clientHeight,c=0,u=0;if(s){let d=!Al()||e==="fixed";r?d||(c=-s.offsetLeft,u=-s.offsetTop):(a=s.width,l=s.height,d&&(c=s.offsetLeft,u=s.offsetTop))}if(Nl(o)<=0){let d=o.ownerDocument,p=d.body,h=getComputedStyle(p),m=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,g=Math.abs(o.clientWidth-p.clientWidth-m),y=getComputedStyle(o).scrollbarGutter==="stable both-edges"?g/2:g;y<=bO&&(a-=y)}return{width:a,height:l,x:c,y:u}}function wO(t,e){let n=Cs(t,!0,e==="fixed"),r=n.top+t.clientTop,i=n.left+t.clientLeft,o=Yi(t),s=t.clientWidth*o.x,a=t.clientHeight*o.y,l=i*o.x,c=r*o.y;return{width:s,height:a,x:l,y:c}}function Iw(t,e,n){let r;if(e==="viewport"||e==="layoutViewport")r=xO(t,n,e);else if(e==="document")r=kO(wn(t));else if(Ft(e))r=wO(e,n);else{let i=Dw(t);r={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return jr(r)}function CO(t,e){let n=e.get(t);if(n)return n;let r=El(t,[],!1).filter(a=>Ft(a)&&qr(a)!=="body"),i=null,o=zt(t).position==="fixed",s=o?Un(t):t;for(;Ft(s)&&!Xi(s);){let a=zt(s),l=vl(s),c=i?i.position:o?"fixed":"";!l&&(c==="fixed"||c==="absolute"&&a.position==="static")?r=r.filter(f=>f!==s):i=a,s=Un(s)}return e.set(t,r),r}function SO(t){let{element:e,boundary:n,rootBoundary:r,strategy:i}=t,s=[...n==="clippingAncestors"?xs(e)?[]:CO(e,this._c):[].concat(n),r],a=Iw(e,s[0],i),l=a.top,c=a.right,u=a.bottom,f=a.left;for(let d=1;d<s.length;d++){let p=Iw(e,s[d],i);l=Hr(p.top,l),c=Sl(p.right,c),u=Sl(p.bottom,u),f=Hr(p.left,f)}return{width:c-f,height:u-l,x:f,y:l}}function MO(t){let{width:e,height:n}=Rw(t);return{width:e,height:n}}function EO(t,e,n){let r=Cn(e),i=wn(e),o=n==="fixed",s=Cs(t,!0,o,e),a={scrollLeft:0,scrollTop:0},l=Yt(0);if((r||!o)&&((qr(e)!=="body"||bs(i))&&(a=ws(e)),r)){let d=Cs(e,!0,o,e);l.x=d.x+e.clientLeft,l.y=d.y+e.clientTop}!r&&i&&(l.x=Nl(i));let c=i&&!r&&!o?Lw(i,a):Yt(0),u=s.left+a.scrollLeft-l.x-c.x,f=s.top+a.scrollTop-l.y-c.y;return{x:u,y:f,width:s.width,height:s.height}}function lp(t){return zt(t).position==="static"}function Nw(t,e){if(!Cn(t)||zt(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return wn(t)===n&&(n=n.ownerDocument.body),n}function Pw(t,e){let n=ot(t);if(xs(t))return n;if(!Cn(t)){let i=Un(t);for(;i&&!Xi(i);){if(Ft(i)&&!lp(i))return i;i=Un(i)}return n}let r=Nw(t,e);for(;r&&Tw(r)&&lp(r);)r=Nw(r,e);return r&&Xi(r)&&lp(r)&&!vl(r)?n:r||vw(t)||n}var TO=async function(t){let e=this.getOffsetParent||Pw,n=this.getDimensions,r=await n(t.floating);return{reference:EO(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function vO(t){return zt(t).direction==="rtl"}var AO={convertOffsetParentRelativeRectToViewportRelativeRect:gO,getDocumentElement:wn,getClippingRect:SO,getOffsetParent:Pw,getElementRects:TO,getClientRects:yO,getDimensions:MO,getScale:Yi,isElement:Ft,isRTL:vO};var Bw=Sw;var Fw=Cw;var zw=(t,e,n)=>{let r=new Map,i=n??{},o={...AO,...i.platform,_c:r};return ww(t,e,{...i,platform:o})};function _w(t){let e=Ie({},`${t}_SLASH_SPEC`),n=pe(i=>{let o=i.get(e.key);return new X({key:new ee(`${t}_SLASH`),...o})}),r=[e,n];return r.key=e.key,r.pluginKey=n.key,e.meta={package:"@milkdown/plugin-slash",displayName:`Ctx<slashSpec>|${t}`},n.meta={package:"@milkdown/plugin-slash",displayName:`Prose<slash>|${t}`},r}var $w=class{#t;#e;#r;#n;#s;#o;#i;#a;#l;constructor(t){this.#t=!1,this.onShow=()=>{},this.onHide=()=>{},this.#d=(e,n)=>{let{state:r,composing:i}=e,{selection:o,doc:s}=r,{ranges:a}=o,l=Math.min(...a.map(f=>f.$from.pos)),c=Math.max(...a.map(f=>f.$to.pos)),u=n&&n.doc.eq(s)&&n.selection.eq(o);if(this.#t||((this.#n??e.dom.parentElement??document.body).appendChild(this.element),this.#t=!0),!(i||u)){if(!this.#i(e,n)){this.hide();return}zw({getBoundingClientRect:()=>Kg(e,l,c)},this.element,{placement:"bottom-start",middleware:[Fw(),Bw(this.#l),...this.#e],...this.#r}).then(({x:f,y:d})=>{Object.assign(this.element.style,{left:`${f}px`,top:`${d}px`})}).catch(console.error),this.show()}},this.#c=e=>{let n=this.getContent(e);if(!n)return!1;let r=n.at(-1);return r?Array.isArray(this.#o)?this.#o.includes(r):this.#o===r:!1},this.update=(e,n)=>{this.#a(e,n)},this.getContent=(e,n=r=>r.type.name==="paragraph")=>{let{selection:r}=e.state,{empty:i,$from:o}=r,s=e.state.selection instanceof B;if(typeof document>"u")return;let a=this.element.contains(document.activeElement),l=!e.hasFocus()&&!a,c=!e.editable,u=!Gg(n)(e.state.selection);if(!(l||c||!i||!s||u))return o.parent.textBetween(Math.max(0,o.parentOffset-500),o.parentOffset,void 0,"\uFFFC")},this.destroy=()=>{this.#a.cancel()},this.show=()=>{this.element.dataset.show="true",this.onShow()},this.hide=()=>{this.element.dataset.show="false",this.onHide()},this.element=t.content,this.#s=t.debounce??200,this.#i=t.shouldShow??this.#c,this.#o=t.trigger??"/",this.#l=t.offset,this.#e=t.middleware??[],this.#r=t.floatingUIOptions??{},this.#n=t.root,this.#a=cs(this.#d,this.#s)}#d;#c};function cp(t){return new Promise(e=>{let n=new FileReader;n.addEventListener("load",()=>{e({alt:t.name,src:n.result})},!1),n.readAsDataURL(t)})}var IO=async(t,e)=>{let n=[];for(let i=0;i<t.length;i++){let o=t.item(i);o&&o.type.includes("image")&&n.push(o)}let{image:r}=e.nodes;if(!r)throw _s("image");return(await Promise.all(n.map(i=>cp(i)))).map(({alt:i,src:o})=>r.createAndFill({src:o,alt:i}))},Kr=Ie({uploader:IO,enableHtmlFileUploader:!1,uploadWidgetFactory:(t,e)=>{let n=document.createElement("span");return n.textContent="Upload in progress...",le.widget(t,n,e)}},"uploadConfig");Kr.meta={package:"@milkdown/plugin-upload",displayName:"Ctx<uploadConfig>"};var Hw=pe(t=>{let e=new ee("MILKDOWN_UPLOAD"),n=(i,o)=>{let s=e.getState(i);if(!s)return-1;let a=s.find(void 0,void 0,l=>l.id===o);return a.length?a[0]?.from??-1:-1},r=(i,o,s)=>{if(!s||s.length<=0)return!1;let a=Symbol("upload symbol"),l=t.get($e),{uploader:c,getInsertPos:u}=t.get(Kr.key),{tr:f}=i.state,d=o instanceof DragEvent?i.posAtCoords({left:o.clientX,top:o.clientY})?.pos??f.selection.from:f.selection.from,p=typeof u=="function"?u(o,t,d):d;return i.dispatch(f.setMeta(e,{add:{id:a,pos:p}})),c(s,l,t,p).then(h=>{let m=n(i.state,a);m<0||i.dispatch(i.state.tr.replaceWith(m,m,h).setMeta(e,{remove:{id:a}}))}).catch(h=>{console.error(h)}),!0};return new X({key:e,state:{init(){return ae.empty},apply(i,o){let s=o.map(i.mapping,i.doc),a=i.getMeta(this);if(!a)return s;if(a.add){let{uploadWidgetFactory:l}=t.get(Kr.key),c=l(a.add.pos,{id:a.add.id});return s.add(i.doc,[c])}if(a.remove){let l=s.find(void 0,void 0,c=>c.id===a.remove.id);return s.remove(l)}return s}},props:{decorations(i){return this.getState(i)},handlePaste:(i,o)=>{let{enableHtmlFileUploader:s}=t.get(Kr.key);return!(o instanceof ClipboardEvent)||!s&&o.clipboardData?.getData("text/html")?!1:r(i,o,o.clipboardData?.files)},handleDrop:(i,o)=>o instanceof DragEvent?r(i,o,o.dataTransfer?.files):!1}})});Hw.meta={package:"@milkdown/plugin-upload",displayName:"Prose<upload>"};var Ww=[Kr,Hw];function up(){return{enter:{mathFlow:t,mathFlowFenceMeta:e,mathText:o},exit:{mathFlow:i,mathFlowFence:r,mathFlowFenceMeta:n,mathFlowValue:a,mathText:s,mathTextData:a}};function t(l){let c={type:"element",tagName:"code",properties:{className:["language-math","math-display"]},children:[]};this.enter({type:"math",meta:null,value:"",data:{hName:"pre",hChildren:[c]}},l)}function e(){this.buffer()}function n(){let l=this.resume(),c=this.stack[this.stack.length-1];c.type,c.meta=l}function r(){this.data.mathFlowInside||(this.buffer(),this.data.mathFlowInside=!0)}function i(l){let c=this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c;let f=u.data.hChildren[0];f.type,f.tagName,f.children.push({type:"text",value:c}),this.data.mathFlowInside=void 0}function o(l){this.enter({type:"inlineMath",value:"",data:{hName:"code",hProperties:{className:["language-math","math-inline"]},hChildren:[]}},l),this.buffer()}function s(l){let c=this.resume(),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c,u.data.hChildren.push({type:"text",value:c})}function a(l){this.config.enter.data.call(this,l),this.config.exit.data.call(this,l)}}function fp(t){let e=(t||{}).singleDollarTextMath;return e==null&&(e=!0),r.peek=i,{unsafe:[{character:"\r",inConstruct:"mathFlowMeta"},{character:` `,inConstruct:"mathFlowMeta"},{character:"$",after:e?void 0:"\\$",inConstruct:"phrasing"},{character:"$",inConstruct:"mathFlowMeta"},{atBreak:!0,character:"$",after:"\\$"}],handlers:{math:n,inlineMath:r}};function n(o,s,a,l){let c=o.value||"",u=a.createTracker(l),f="$".repeat(Math.max(ea(c,"$")+1,2)),d=a.enter("mathFlow"),p=u.move(f);if(o.meta){let h=a.enter("mathFlowMeta");p+=u.move(a.safe(o.meta,{after:` `,before:p,encode:["$"],...u.current()})),h()}return p+=u.move(` `),c&&(p+=u.move(c+` -`)),p+=u.move(f),d(),p}function r(o,s,a){let l=o.value||"",c=1;for(e||c++;new RegExp("(^|[^$])"+"\\$".repeat(c)+"([^$]|$)").test(l);)c++;let u="$".repeat(c);/[^ \r\n]/.test(l)&&(/^[ \r\n]/.test(l)&&/[ \r\n]$/.test(l)||/^\$|\$$/.test(l))&&(l=" "+l+" ");let f=-1;for(;++f<a.unsafe.length;){let d=a.unsafe[f];if(!d.atBreak)continue;let p=a.compilePattern(d),h;for(;h=p.exec(l);){let m=h.index;l.codePointAt(m)===10&&l.codePointAt(m-1)===13&&m--,l=l.slice(0,m)+" "+l.slice(h.index+1)}}return u+l+u}function i(){return"$"}}var jw={tokenize:IO,concrete:!0,name:"mathFlow"},Ww={tokenize:NO,partial:!0};function IO(t,e,n){let r=this,i=r.events[r.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(b){return t.enter("mathFlow"),t.enter("mathFlowFence"),t.enter("mathFlowFenceSequence"),l(b)}function l(b){return b===36?(t.consume(b),s++,l):s<2?n(b):(t.exit("mathFlowFenceSequence"),_(t,c,"whitespace")(b))}function c(b){return b===null||D(b)?f(b):(t.enter("mathFlowFenceMeta"),t.enter("chunkString",{contentType:"string"}),u(b))}function u(b){return b===null||D(b)?(t.exit("chunkString"),t.exit("mathFlowFenceMeta"),f(b)):b===36?n(b):(t.consume(b),u)}function f(b){return t.exit("mathFlowFence"),r.interrupt?e(b):t.attempt(Ww,d,g)(b)}function d(b){return t.attempt({tokenize:y,partial:!0},g,p)(b)}function p(b){return(o?_(t,h,"linePrefix",o+1):h)(b)}function h(b){return b===null?g(b):D(b)?t.attempt(Ww,d,g)(b):(t.enter("mathFlowValue"),m(b))}function m(b){return b===null||D(b)?(t.exit("mathFlowValue"),h(b)):(t.consume(b),m)}function g(b){return t.exit("mathFlow"),e(b)}function y(b,C,v){let A=0;return _(b,w,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4);function w(O){return b.enter("mathFlowFence"),b.enter("mathFlowFenceSequence"),N(O)}function N(O){return O===36?(A++,b.consume(O),N):A<s?v(O):(b.exit("mathFlowFenceSequence"),_(b,P,"whitespace")(O))}function P(O){return O===null||D(O)?(b.exit("mathFlowFence"),C(O)):v(O)}}}function NO(t,e,n){let r=this;return i;function i(s){return s===null?e(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}function Vw(t){let n=(t||{}).singleDollarTextMath;return n==null&&(n=!0),{tokenize:r,resolve:RO,previous:OO,name:"mathText"};function r(i,o,s){let a=this,l=0,c,u;return f;function f(g){return i.enter("mathText"),i.enter("mathTextSequence"),d(g)}function d(g){return g===36?(i.consume(g),l++,d):l<2&&!n?s(g):(i.exit("mathTextSequence"),p(g))}function p(g){return g===null?s(g):g===36?(u=i.enter("mathTextSequence"),c=0,m(g)):g===32?(i.enter("space"),i.consume(g),i.exit("space"),p):D(g)?(i.enter("lineEnding"),i.consume(g),i.exit("lineEnding"),p):(i.enter("mathTextData"),h(g))}function h(g){return g===null||g===32||g===36||D(g)?(i.exit("mathTextData"),p(g)):(i.consume(g),h)}function m(g){return g===36?(i.consume(g),c++,m):c===l?(i.exit("mathTextSequence"),i.exit("mathText"),o(g)):(u.type="mathTextData",h(g))}}}function RO(t){let e=t.length-4,n=3,r,i;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(r=n;++r<e;)if(t[r][1].type==="mathTextData"){t[e][1].type="mathTextPadding",t[n][1].type="mathTextPadding",n+=2,e-=2;break}}for(r=n-1,e++;++r<=e;)i===void 0?r!==e&&t[r][1].type!=="lineEnding"&&(i=r):(r===e||t[r][1].type==="lineEnding")&&(t[i][1].type="mathTextData",r!==i+2&&(t[i][1].end=t[r-1][1].end,t.splice(i+2,r-i-2),e-=r-i-2,r=i+2),i=void 0);return t}function OO(t){return t!==36||this.events[this.events.length-1][1].type==="characterEscape"}function dp(t){return{flow:{36:jw},text:{36:Vw(t)}}}var DO={};function Rl(t){let e=this,n=t||DO,r=e.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),o=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),s=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(dp(n)),o.push(up()),s.push(fp(n))}var qw=gt("weiBeiRemarkMath",()=>Rl),pp=ce("math_inline",()=>({group:"inline",content:"text*",inline:!0,atom:!0,parseDOM:[{tag:'span[data-type="math_inline"]',getContent:(t,e)=>M.from(e.text(t.dataset.value||""))}],toDOM:t=>["span",{"data-type":"math_inline","data-value":t.textContent},t.textContent],parseMarkdown:{match:t=>t.type==="inlineMath",runner:(t,e,n)=>t.openNode(n).addText(e.value).closeNode()},toMarkdown:{match:t=>t.type.name==="math_inline",runner:(t,e)=>t.addNode("inlineMath",void 0,e.textContent)}})),Ol=ce("math_block",()=>({content:"text*",group:"block",marks:"",defining:!0,atom:!0,isolating:!0,attrs:{value:{default:""}},parseDOM:[{tag:'div[data-type="math_block"]',preserveWhitespace:"full",getAttrs:t=>({value:t.dataset.value||""})}],toDOM:t=>["div",{"data-type":"math_block","data-value":t.attrs.value},t.attrs.value],parseMarkdown:{match:t=>t.type==="math",runner:(t,e,n)=>t.addNode(n,{value:e.value})},toMarkdown:{match:t=>t.type.name==="math_block",runner:(t,e)=>t.addNode("math",void 0,e.attrs.value)}})),Kw=ge(t=>new be(/^\$\$\s$/,(e,n,r,i)=>{let o=e.doc.resolve(r);return o.node(-1).canReplaceWith(o.index(-1),o.indexAfter(-1),Ol.type(t))?e.tr.delete(r,i).setBlockType(r,r,Ol.type(t)):null}));var Uw=new Map,hp=t=>{let e=Uw.get(t);if(e)return e;let n=new Promise((r,i)=>{let o=document.createElement("script");o.src=new URL(t,document.baseURI).href,o.onload=()=>r(),o.onerror=()=>i(new Error(`Unable to load local editor runtime: ${t}`)),document.head.appendChild(o)});return Uw.set(t,n),n},Jw=()=>hp("katex-runtime.js").then(()=>window.WeiBeiKaTeX),Gw=()=>window.WeiBeiKaTeX,Xw=()=>hp("mermaid-runtime.js").then(()=>window.WeiBeiMermaid),Yw=()=>hp("prism-runtime.js").then(()=>window.WeiBeiPrism);var mp="[A-Za-z][A-Za-z0-9_-]*",LO=(t,e)=>{let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r-=1)n+=1;return n%2===1},Qw=(t,e,n)=>{let r=t.indexOf(e,n);for(;r>=0&&LO(t,r);)r=t.indexOf(e,r+e.length);return r},PO=(t,e)=>{let n=String(t||""),r="",i=0;for(;i<n.length;){let o=Qw(n,"`",i);if(o<0){r+=e(n.slice(i));break}r+=e(n.slice(i,o));let s=n.slice(o).match(/^`+/)?.[0]||"`",a=Qw(n,s,o+s.length);if(a<0){r+=e(n.slice(o));break}r+=n.slice(o,a+s.length),i=a+s.length}return r},BO=t=>String(t||"").replace(/(?<!\\)`/g,"\\`").replace(/\\\[\\\[/g,"[[").replace(/\\\]\\\]/g,"]]").replace(/\\=\\=([^=\n]+?)\\=\\=/g,"==$1==").replace(/\^\\\[/g,"^[").replace(/(^|\s)\\#(?=[\p{L}\p{N}_/-])/gu,"$1#").replace(/\\\$(?=\d)/g,"$").replace(new RegExp(`^(\\s*(?:>\\s*)*)\\\\(\\[!(?:${mp})\\])`,"gim"),"$1$2"),Ss=(t,e)=>{let n=String(t||"").split(/(\r?\n)/),r=!1,i="",o=0,s="";for(let a=0;a<n.length;a+=2){let l=n[a]||"",c=n[a+1]||"",u=l.match(/^\s*(?:>\s*)*(`{3,}|~{3,})/);if(u){r?u[1][0]===i&&u[1].length>=o&&(r=!1,o=0):(r=!0,i=u[1][0],o=u[1].length),s+=l+c;continue}if(r){s+=l+c;continue}let f=PO(l,e);s+=f,f.endsWith(` -`)&&c||(s+=c)}return s},FO=t=>Ss(t,BO),zO=t=>/^\s*(?:>\s*)*<br\s*\/?>\s*$/i.test(t)?t:String(t||"").replace(/<br\s*\/?>[ \t]*/gi,` -`.padStart(3)),_O=t=>Ss(t,zO),Zw=/(?<!\\)\$((?!\d)[^$\n]+)\$$/,$O=t=>String(t||"").replace(/(^|[^\\])\$(?=\d)/g,"$1\\$"),HO=t=>Ss(t,$O),WO=t=>Ss(t,e=>e.replace(/\\\[([\s\S]*?)\\\]/g,(n,r)=>`$$ +`)),p+=u.move(f),d(),p}function r(o,s,a){let l=o.value||"",c=1;for(e||c++;new RegExp("(^|[^$])"+"\\$".repeat(c)+"([^$]|$)").test(l);)c++;let u="$".repeat(c);/[^ \r\n]/.test(l)&&(/^[ \r\n]/.test(l)&&/[ \r\n]$/.test(l)||/^\$|\$$/.test(l))&&(l=" "+l+" ");let f=-1;for(;++f<a.unsafe.length;){let d=a.unsafe[f];if(!d.atBreak)continue;let p=a.compilePattern(d),h;for(;h=p.exec(l);){let m=h.index;l.codePointAt(m)===10&&l.codePointAt(m-1)===13&&m--,l=l.slice(0,m)+" "+l.slice(h.index+1)}}return u+l+u}function i(){return"$"}}var Vw={tokenize:NO,concrete:!0,name:"mathFlow"},jw={tokenize:RO,partial:!0};function NO(t,e,n){let r=this,i=r.events[r.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(b){return t.enter("mathFlow"),t.enter("mathFlowFence"),t.enter("mathFlowFenceSequence"),l(b)}function l(b){return b===36?(t.consume(b),s++,l):s<2?n(b):(t.exit("mathFlowFenceSequence"),_(t,c,"whitespace")(b))}function c(b){return b===null||D(b)?f(b):(t.enter("mathFlowFenceMeta"),t.enter("chunkString",{contentType:"string"}),u(b))}function u(b){return b===null||D(b)?(t.exit("chunkString"),t.exit("mathFlowFenceMeta"),f(b)):b===36?n(b):(t.consume(b),u)}function f(b){return t.exit("mathFlowFence"),r.interrupt?e(b):t.attempt(jw,d,g)(b)}function d(b){return t.attempt({tokenize:y,partial:!0},g,p)(b)}function p(b){return(o?_(t,h,"linePrefix",o+1):h)(b)}function h(b){return b===null?g(b):D(b)?t.attempt(jw,d,g)(b):(t.enter("mathFlowValue"),m(b))}function m(b){return b===null||D(b)?(t.exit("mathFlowValue"),h(b)):(t.consume(b),m)}function g(b){return t.exit("mathFlow"),e(b)}function y(b,C,v){let A=0;return _(b,w,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4);function w(O){return b.enter("mathFlowFence"),b.enter("mathFlowFenceSequence"),N(O)}function N(O){return O===36?(A++,b.consume(O),N):A<s?v(O):(b.exit("mathFlowFenceSequence"),_(b,P,"whitespace")(O))}function P(O){return O===null||D(O)?(b.exit("mathFlowFence"),C(O)):v(O)}}}function RO(t,e,n){let r=this;return i;function i(s){return s===null?e(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}function qw(t){let n=(t||{}).singleDollarTextMath;return n==null&&(n=!0),{tokenize:r,resolve:OO,previous:DO,name:"mathText"};function r(i,o,s){let a=this,l=0,c,u;return f;function f(g){return i.enter("mathText"),i.enter("mathTextSequence"),d(g)}function d(g){return g===36?(i.consume(g),l++,d):l<2&&!n?s(g):(i.exit("mathTextSequence"),p(g))}function p(g){return g===null?s(g):g===36?(u=i.enter("mathTextSequence"),c=0,m(g)):g===32?(i.enter("space"),i.consume(g),i.exit("space"),p):D(g)?(i.enter("lineEnding"),i.consume(g),i.exit("lineEnding"),p):(i.enter("mathTextData"),h(g))}function h(g){return g===null||g===32||g===36||D(g)?(i.exit("mathTextData"),p(g)):(i.consume(g),h)}function m(g){return g===36?(i.consume(g),c++,m):c===l?(i.exit("mathTextSequence"),i.exit("mathText"),o(g)):(u.type="mathTextData",h(g))}}}function OO(t){let e=t.length-4,n=3,r,i;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(r=n;++r<e;)if(t[r][1].type==="mathTextData"){t[e][1].type="mathTextPadding",t[n][1].type="mathTextPadding",n+=2,e-=2;break}}for(r=n-1,e++;++r<=e;)i===void 0?r!==e&&t[r][1].type!=="lineEnding"&&(i=r):(r===e||t[r][1].type==="lineEnding")&&(t[i][1].type="mathTextData",r!==i+2&&(t[i][1].end=t[r-1][1].end,t.splice(i+2,r-i-2),e-=r-i-2,r=i+2),i=void 0);return t}function DO(t){return t!==36||this.events[this.events.length-1][1].type==="characterEscape"}function dp(t){return{flow:{36:Vw},text:{36:qw(t)}}}var LO={};function Rl(t){let e=this,n=t||LO,r=e.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),o=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),s=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(dp(n)),o.push(up()),s.push(fp(n))}var Kw=gt("weiBeiRemarkMath",()=>Rl),pp=ce("math_inline",()=>({group:"inline",content:"text*",inline:!0,atom:!0,parseDOM:[{tag:'span[data-type="math_inline"]',getContent:(t,e)=>M.from(e.text(t.dataset.value||""))}],toDOM:t=>["span",{"data-type":"math_inline","data-value":t.textContent},t.textContent],parseMarkdown:{match:t=>t.type==="inlineMath",runner:(t,e,n)=>t.openNode(n).addText(e.value).closeNode()},toMarkdown:{match:t=>t.type.name==="math_inline",runner:(t,e)=>t.addNode("inlineMath",void 0,e.textContent)}})),Ol=ce("math_block",()=>({content:"text*",group:"block",marks:"",defining:!0,atom:!0,isolating:!0,attrs:{value:{default:""}},parseDOM:[{tag:'div[data-type="math_block"]',preserveWhitespace:"full",getAttrs:t=>({value:t.dataset.value||""})}],toDOM:t=>["div",{"data-type":"math_block","data-value":t.attrs.value},t.attrs.value],parseMarkdown:{match:t=>t.type==="math",runner:(t,e,n)=>t.addNode(n,{value:e.value})},toMarkdown:{match:t=>t.type.name==="math_block",runner:(t,e)=>t.addNode("math",void 0,e.attrs.value)}})),Uw=ge(t=>new xe(/^\$\$\s$/,(e,n,r,i)=>{let o=e.doc.resolve(r);return o.node(-1).canReplaceWith(o.index(-1),o.indexAfter(-1),Ol.type(t))?e.tr.delete(r,i).setBlockType(r,r,Ol.type(t)):null}));var Jw=new Map,hp=t=>{let e=Jw.get(t);if(e)return e;let n=new Promise((r,i)=>{let o=document.createElement("script");o.src=new URL(t,document.baseURI).href,o.onload=()=>r(),o.onerror=()=>i(new Error(`Unable to load local editor runtime: ${t}`)),document.head.appendChild(o)});return Jw.set(t,n),n},Gw=()=>hp("katex-runtime.js").then(()=>window.WeiBeiKaTeX),Xw=()=>window.WeiBeiKaTeX,Yw=()=>hp("mermaid-runtime.js").then(()=>window.WeiBeiMermaid),Qw=()=>hp("prism-runtime.js").then(()=>window.WeiBeiPrism);var mp="[A-Za-z][A-Za-z0-9_-]*",PO=(t,e)=>{let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r-=1)n+=1;return n%2===1},Zw=(t,e,n)=>{let r=t.indexOf(e,n);for(;r>=0&&PO(t,r);)r=t.indexOf(e,r+e.length);return r},BO=(t,e)=>{let n=String(t||""),r="",i=0;for(;i<n.length;){let o=Zw(n,"`",i);if(o<0){r+=e(n.slice(i));break}r+=e(n.slice(i,o));let s=n.slice(o).match(/^`+/)?.[0]||"`",a=Zw(n,s,o+s.length);if(a<0){r+=e(n.slice(o));break}r+=n.slice(o,a+s.length),i=a+s.length}return r},FO=t=>String(t||"").replace(/(?<!\\)`/g,"\\`").replace(/\\\[\\\[/g,"[[").replace(/\\\]\\\]/g,"]]").replace(/\\=\\=([^=\n]+?)\\=\\=/g,"==$1==").replace(/\^\\\[/g,"^[").replace(/(^|\s)\\#(?=[\p{L}\p{N}_/-])/gu,"$1#").replace(/\\\$(?=\d)/g,"$").replace(new RegExp(`^(\\s*(?:>\\s*)*)\\\\(\\[!(?:${mp})\\])`,"gim"),"$1$2"),Ss=(t,e)=>{let n=String(t||"").split(/(\r?\n)/),r=!1,i="",o=0,s="";for(let a=0;a<n.length;a+=2){let l=n[a]||"",c=n[a+1]||"",u=l.match(/^\s*(?:>\s*)*(`{3,}|~{3,})/);if(u){r?u[1][0]===i&&u[1].length>=o&&(r=!1,o=0):(r=!0,i=u[1][0],o=u[1].length),s+=l+c;continue}if(r){s+=l+c;continue}let f=BO(l,e);s+=f,f.endsWith(` +`)&&c||(s+=c)}return s},zO=t=>Ss(t,FO),_O=t=>/^\s*(?:>\s*)*<br\s*\/?>\s*$/i.test(t)?t:String(t||"").replace(/<br\s*\/?>[ \t]*/gi,` +`.padStart(3)),$O=t=>Ss(t,_O),e0=/(?<!\\)\$((?!\d)[^$\n]+)\$$/,HO=t=>String(t||"").replace(/(^|[^\\])\$(?=\d)/g,"$1\\$"),WO=t=>Ss(t,HO),jO=t=>Ss(t,e=>e.replace(/\\\[([\s\S]*?)\\\]/g,(n,r)=>`$$ ${String(r).trim()} -$$`).replace(/\\\(([^\n]*?)\\\)/g,(n,r)=>`$${String(r).trim()}$`)),jO=t=>Ss(t,e=>e.replace(/^[ \t]*\[\s*([^\n\]]*?\\[A-Za-z]+[^\n\]]*?)\s*\][ \t]*$/gm,(n,r)=>`$$ +$$`).replace(/\\\(([^\n]*?)\\\)/g,(n,r)=>`$${String(r).trim()}$`)),VO=t=>Ss(t,e=>e.replace(/^[ \t]*\[\s*([^\n\]]*?\\[A-Za-z]+[^\n\]]*?)\s*\][ \t]*$/gm,(n,r)=>`$$ ${String(r).trim()} $$`).replace(/^[ \t]*\$\$([^$\n]+)\$\$[ \t]*$/gm,(n,r)=>`$$ ${String(r).trim()} -$$`).replace(/\\hat\s+(\\[A-Za-z]+|[A-Za-z])/g,"\\hat{$1}").replace(/\\hat(?!\{)(\\[A-Za-z]+|[A-Za-z])/g,"\\hat{$1}")),Jn=(t,e)=>{let n=_O(t);return(e==="userPaste"||e==="agentGenerated")&&(n=WO(n)),e==="agentGenerated"&&(n=jO(n)),HO(n)},VO=[/^#{1,6}\s+\S/,/^>\s+\S/,/^>\s*\[![A-Za-z][A-Za-z0-9_-]*\]/,/^\s*[-*+]\s+\S/,/^\s*\d{1,9}[.)]\s+\S/,/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/,/^\s*(?:>\s*)*(?:```|~~~)/,/^\|.*\|\s*$/,/!?\[[^\]\n]*\]\([^)\n]+\)/,/\[\[[^\]\n]+(?:\|[^\]\n]*)?\]\]/],qO=[/\*\*|__/,/~~/,/==/,/`[^`\n]+`/,/\$\$/,/\$(?![\d\s$])[^$\n]+\$/],e0=t=>{let e=String(t||"");if(!e.trim())return!1;if(/^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/.test(e))return!0;for(let n of e.split(/\r?\n/)){for(let r of VO)if(r.test(n))return!0;for(let r of qO)if(r.test(n))return!0}return!1},Ms=t=>{let e=t||"",n=e.match(/^(---\n[\s\S]*?\n---)(?:\n+|$)/);return n?{frontmatter:n[1],body:e.slice(n[0].length)}:{frontmatter:"",body:e}},t0=(t,e)=>{let n=FO(e),r=t?n.replace(/^\n+/,""):n;return t?`${t} +$$`).replace(/\\hat\s+(\\[A-Za-z]+|[A-Za-z])/g,"\\hat{$1}").replace(/\\hat(?!\{)(\\[A-Za-z]+|[A-Za-z])/g,"\\hat{$1}")),Jn=(t,e)=>{let n=$O(t);return(e==="userPaste"||e==="agentGenerated")&&(n=jO(n)),e==="agentGenerated"&&(n=VO(n)),WO(n)},qO=[/^#{1,6}\s+\S/,/^>\s+\S/,/^>\s*\[![A-Za-z][A-Za-z0-9_-]*\]/,/^\s*[-*+]\s+\S/,/^\s*\d{1,9}[.)]\s+\S/,/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/,/^\s*(?:>\s*)*(?:```|~~~)/,/^\|.*\|\s*$/,/!?\[[^\]\n]*\]\([^)\n]+\)/,/\[\[[^\]\n]+(?:\|[^\]\n]*)?\]\]/],KO=[/\*\*|__/,/~~/,/==/,/`[^`\n]+`/,/\$\$/,/\$(?![\d\s$])[^$\n]+\$/],t0=t=>{let e=String(t||"");if(!e.trim())return!1;if(/^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/.test(e))return!0;for(let n of e.split(/\r?\n/)){for(let r of qO)if(r.test(n))return!0;for(let r of KO)if(r.test(n))return!0}return!1},Ms=t=>{let e=t||"",n=e.match(/^(---\n[\s\S]*?\n---)(?:\n+|$)/);return n?{frontmatter:n[1],body:e.slice(n[0].length)}:{frontmatter:"",body:e}},n0=(t,e)=>{let n=zO(e),r=t?n.replace(/^\n+/,""):n;return t?`${t} -${r}`:r};var n0=["transactions","fullSerializations","bridgeMessages","bridgeBytes","decorationNodes","decorationCacheHits","katexRenders","mermaidRenders","imageScans","imageNodeUpdates","codeTokenizations","outlineReports"],r0=()=>Object.fromEntries(n0.map(t=>[t,0])),It=(t,e,n=1)=>{t&&(t[e]+=n)},i0=t=>{if(t)for(let e of n0)t[e]=0};var o0=t=>JSON.stringify(t.map(({level:e,title:n})=>[e,n]));var KO=["loadDocument","requestSnapshot","setTheme","setLanguage","setEditable","focus","scrollToHeading","applyMarkdownFragment","replaceSelection","executeSelectionCommand","insertStructuredBlock","restoreCheckpoint"],s0=t=>Number.isInteger(t)&&Number(t)>=0,gp=t=>typeof t=="string"&&t.length>0,a0=t=>{if(!t||typeof t!="object")return null;let e=t;return e.protocolVersion!==2||!gp(e.commandID)||typeof e.documentID!="string"||!s0(e.documentGeneration)||!KO.includes(e.type)||!e.payload||typeof e.payload!="object"||Array.isArray(e.payload)||e.minimumRevision!==void 0&&!s0(e.minimumRevision)||e.requestID!==void 0&&!gp(e.requestID)||e.type==="requestSnapshot"&&!gp(e.requestID)?null:e},l0=(t,e)=>t.type==="loadDocument"?t.documentGeneration>e.documentGeneration||t.documentGeneration===e.documentGeneration&&(!e.documentID||t.documentID===e.documentID):t.documentID===e.documentID&&t.documentGeneration===e.documentGeneration&&(t.minimumRevision===void 0||t.minimumRevision<=e.revision),c0=(t,e)=>e?{revision:t.revision+1,dirty:!0,changed:!0}:{...t,changed:!1},u0=(t,e)=>({...e,protocolVersion:2,documentID:t.documentID,documentGeneration:t.documentGeneration,revision:t.revision});var UO=(t,e)=>{let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r-=1)n+=1;return n%2===1},f0=t=>{let e=[],n=/!\[\[([^\]\n]+)\]\]|\[\[([^\]\n]+)\]\]|==([^=\n]+)==|\^\[([^\]\n]+)\]/g,r=0;for(let i of t.matchAll(n)){let o=i.index||0;if(UO(t,o))continue;o>r&&e.push({type:"text",value:t.slice(r,o)});let s=i[1]??i[2];if(s!==void 0){let a=s.indexOf("|"),l=(a<0?s:s.slice(0,a)).trim(),c=(a<0?"":s.slice(a+1)).trim();e.push({type:i[1]===void 0?"wikiLink":"embed",raw:s,target:l,label:c})}else i[3]!==void 0?e.push({type:"highlight",value:i[3]}):e.push({type:"inlineFootnote",value:i[4]});r=o+i[0].length}return r<t.length&&e.push({type:"text",value:t.slice(r)}),e.length?e:[{type:"text",value:t}]};var d0=t=>{let e=t.match(/^\[!([A-Za-z][A-Za-z0-9_-]*)\]([+-]?)(?:[ \t]+(.+))?$/);return e?{calloutType:e[1].toLowerCase(),fold:e[2]||"",title:(e[3]||"").trim()}:null},p0=t=>`[!${t.calloutType}]${t.fold}${t.title?` ${t.title}`:""}`;var yp=new Set(["system","serif","literary"]),JO=t=>{let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],i=r.type==="html"?String(r.value||"").match(/^<span data-weibei-font="(system|serif|literary)">$/):null;if(!i){e.push(r);continue}let o=t.findIndex((s,a)=>a>n&&s.type==="html"&&String(s.value||"")==="</span>");if(o<0){e.push(r);continue}e.push({type:"writingFont",font:i[1],children:t.slice(n+1,o)}),n=o}return e},GO=t=>t.type==="text"?{type:"text",value:t.value}:t.type==="highlight"?{type:"highlight",children:[{type:"text",value:t.value}]}:t.type==="inlineFootnote"?{type:"inlineFootnote",value:t.value}:{type:t.type,raw:t.raw,target:t.target,label:t.label},h0=t=>{if(!t.children||["code","inlineCode","html"].includes(t.type))return;if(t.type==="blockquote"){let n=t.children[0],r=n?.type==="paragraph"&&n.children?.length===1&&n.children[0].type==="text"?String(n.children[0].value||""):"",i=d0(r);if(i){t.type="callout",t.calloutType=i.calloutType,t.fold=i.fold,t.title=i.title,t.children=t.children.slice(1),t.children.length===0&&t.children.push({type:"paragraph",children:[]});let o=t.children[0]?.type==="paragraph"?t.children[0].children?.[0]:null;o?.type==="text"&&(o.value=String(o.value||"").replace(/^\[![A-Za-z][A-Za-z0-9_-]*\][+-]?[ \t]*/,""))}}let e=t.children.flatMap(n=>n.type!=="text"?(h0(n),[n]):f0(String(n.value||"")).map(GO));t.children=JO(e)},XO=gt("weiBeiStructuredMarkdown",()=>(function(){let e=this.data();return(e.toMarkdownExtensions||(e.toMarkdownExtensions=[])).push({handlers:{wikiLink:(r,i,o,s)=>`[[${o.safe(r.raw,{...s,before:"[[",after:"]]"})}]]`,embed:(r,i,o,s)=>`![[${o.safe(r.raw,{...s,before:"![[",after:"]]"})}]]`,inlineFootnote:(r,i,o,s)=>`^[${o.safe(r.value,{...s,before:"^[",after:"]"})}]`,highlight:(r,i,o,s)=>`==${o.containerPhrasing(r,{...s,before:"==",after:"=="})}==`,writingFont:(r,i,o,s)=>{let a=yp.has(r.font)?r.font:"serif",l=o.containerPhrasing(r,{...s,before:">",after:"<"});return`<span data-weibei-font="${a}">${l}</span>`},callout:(r,i,o,s)=>{let l={type:"blockquote",children:[{type:"paragraph",children:[{type:"text",value:p0({calloutType:r.calloutType,fold:r.fold||"",title:r.title||""})}]},...r.children||[]]},c=o.enter("blockquote"),u=o.createTracker(s);u.move("> "),u.shift(2);let f=o.indentLines(o.containerFlow(l,u.current()),(d,p,h)=>`>${h?"":" "}${d}`);return c(),f}}}),r=>h0(r)})),m0=ce("wiki_link",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="wiki_link"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"wiki_link","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-wikilink weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="wikiLink",runner:(t,e,n)=>{t.addNode(n,{raw:e.raw,target:e.target,label:e.label})}},toMarkdown:{match:t=>t.type.name==="wiki_link",runner:(t,e)=>t.addNode("wikiLink",void 0,void 0,e.attrs)}})),g0=ce("embed",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="embed"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"embed","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-embed-note weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="embed",runner:(t,e,n)=>t.addNode(n,{raw:e.raw,target:e.target,label:e.label})},toMarkdown:{match:t=>t.type.name==="embed",runner:(t,e)=>t.addNode("embed",void 0,void 0,e.attrs)}})),y0=ce("inline_footnote",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{value:{default:""}},parseDOM:[{tag:'span[data-type="inline_footnote"]',getAttrs:t=>t instanceof HTMLElement?{value:t.dataset.value||""}:!1}],toDOM:t=>["span",{"data-type":"inline_footnote","data-value":t.attrs.value,class:"weibei-inline-footnote weibei-structured-node"},t.attrs.value],parseMarkdown:{match:t=>t.type==="inlineFootnote",runner:(t,e,n)=>t.addNode(n,{value:e.value})},toMarkdown:{match:t=>t.type.name==="inline_footnote",runner:(t,e)=>t.addNode("inlineFootnote",void 0,void 0,{value:e.attrs.value})}})),YO=ge(t=>ki(/!\[\[([^\]\n]+)\]\]$/,g0.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),QO=ge(t=>ki(/(?<!!)\[\[([^\]\n]+)\]\]$/,m0.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),ZO=ge(t=>ki(/\^\[([^\]\n]+)\]$/,y0.type(t),{getAttr:e=>({value:e[1]||""})})),k0=Pt("highlight",()=>({parseDOM:[{tag:"mark.weibei-highlight"}],toDOM:()=>["mark",{class:"weibei-highlight"},0],parseMarkdown:{match:t=>t.type==="highlight",runner:(t,e,n)=>t.openMark(n).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="highlight",runner:(t,e)=>{t.withMark(e,"highlight")}}})),eD=Pt("writing_font",()=>({attrs:{font:{default:"serif"}},excludes:"writing_font",priority:10,parseDOM:[{tag:"span[data-weibei-font]",getAttrs:t=>{let e=t instanceof HTMLElement?t.dataset.weibeiFont:"";return e&&yp.has(e)?{font:e}:!1}}],toDOM:t=>["span",{"data-weibei-font":yp.has(t.attrs.font)?t.attrs.font:"serif"},0],parseMarkdown:{match:t=>t.type==="writingFont",runner:(t,e,n)=>t.openMark(n,{font:e.font}).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="writing_font",runner:(t,e)=>{t.withMark(e,"writingFont",void 0,{font:e.attrs.font})}}})),tD=ge(t=>ln(/(?:^|[^\\=])==([^=\n]+)==$/,k0.type(t))),nD=ce("callout",()=>({content:"block+",group:"block",defining:!0,selectable:!0,attrs:{calloutType:{default:"note"},title:{default:""},fold:{default:""}},parseDOM:[{tag:'blockquote[data-type="callout"]',getAttrs:t=>t instanceof HTMLElement?{calloutType:t.dataset.callout||"note",title:t.dataset.calloutTitle||"",fold:t.dataset.calloutFold||""}:!1}],toDOM:t=>["blockquote",{"data-type":"callout","data-callout":t.attrs.calloutType,"data-callout-title":t.attrs.title,"data-callout-fold":t.attrs.fold,class:`weibei-callout weibei-callout-${t.attrs.calloutType}`},0],parseMarkdown:{match:t=>t.type==="callout",runner:(t,e,n)=>t.openNode(n,{calloutType:e.calloutType,title:e.title,fold:e.fold}).next(e.children).closeNode()},toMarkdown:{match:t=>t.type.name==="callout",runner:(t,e)=>{t.openNode("callout",void 0,e.attrs).next(e.content).closeNode()}}})),b0=[XO,m0,g0,y0,eD,k0,tD,nD,YO,QO,ZO].flat();var q0=window.webkit?.messageHandlers,at=window.weiBeiEditorCheckMode?r0():null,V,Zr="",zl=null,Ts=null,Pl=!1,Zt=null,Qi={text:null,rectKey:null,detailKey:null},oo="",re=window.weiBeiMarkdownEditable!==!1,_l=window.weiBeiMarkdownCompactPreview===!0,nt=window.weiBeiDocumentID||"",Ve=window.weiBeiDocumentGeneration||0,Mn={revision:0,dirty:!1},Ep=!1,K0=!1,Tp=0,U0=window.weiBeiMarkdownBaseURL||"",iD=window.weiBeiLocalImageScheme||"weibeiimage",zp=0,oD=0,x0=0,Zi=0,Gn=new Map,_t=new Map,J0=zw("WEIBEI_BLOCK_COMMAND"),sD=ge(t=>ki(Zw,pp.type(t),{beforeDispatch:({tr:e,match:n,start:r})=>e.insertText(n[1]||"",r+1)})),aD=[qw,pp,Ol,Kw,sD].flat(),Xn=0,xe=null,Qt=null,so=null,vp=[],Ap=[],Yr=0,w0="{{WEIBEI_CURSOR}}",kp="{{WEIBEI_SELECT_START}}",C0="{{WEIBEI_SELECT_END}}",bp=new Set(["note","tip","important","warning","caution","summary","abstract","quote","question","example","info","success","failure","danger","bug","todo"]);var G0=t=>t==="en"?"en":"zh-Hans",Jr=G0(window.weiBeiInterfaceLanguage),S0={"zh-Hans":{note:"\u672D\u8BB0",tip:"\u63D0\u793A",important:"\u91CD\u70B9",warning:"\u7559\u5FC3",caution:"\u8C28\u614E",summary:"\u63D0\u8981",abstract:"\u6458\u8981",quote:"\u5F15\u6587",question:"\u95EE\u9898",example:"\u4F8B\u5B50",info:"\u4FE1\u606F",success:"\u53EF\u884C",failure:"\u5931\u8D25",danger:"\u98CE\u9669",bug:"\u95EE\u9898",todo:"\u5F85\u529E"},en:{note:"Note",tip:"Tip",important:"Important",warning:"Warning",caution:"Caution",summary:"Summary",abstract:"Abstract",quote:"Quote",question:"Question",example:"Example",info:"Info",success:"Success",failure:"Failure",danger:"Danger",bug:"Bug",todo:"Todo"}},M0=t=>S0[Jr]?.[t]||S0["zh-Hans"][t]||t,Bl={"zh-Hans":{properties:"\u5C5E\u6027",bootFailed:"Milkdown \u521D\u59CB\u5316\u5931\u8D25",imageMissing:"\u56FE\u7247\u672A\u627E\u5230",inlineFootnote:"\u884C\u5185\u811A\u6CE8\uFF1A{value}",openOrCreateNote:"\u6253\u5F00\u6216\u521B\u5EFA\u7B14\u8BB0\uFF1A{value}",openSource:"\u6253\u5F00\u6765\u6E90\uFF1A{value}",embed:"\u5D4C\u5165\uFF1A{value}",mermaidRendering:"\u6B63\u5728\u6E32\u67D3 Mermaid \u56FE\u8868...",mermaidFailed:`Mermaid \u56FE\u8868\u672A\u89E3\u6790 +${r}`:r};var r0=["transactions","fullSerializations","bridgeMessages","bridgeBytes","decorationNodes","decorationCacheHits","katexRenders","mermaidRenders","imageScans","imageNodeUpdates","codeTokenizations","outlineReports"],i0=()=>Object.fromEntries(r0.map(t=>[t,0])),It=(t,e,n=1)=>{t&&(t[e]+=n)},o0=t=>{if(t)for(let e of r0)t[e]=0};var s0=t=>JSON.stringify(t.map(({level:e,title:n})=>[e,n]));var UO=["loadDocument","requestSnapshot","setTheme","setLanguage","setEditable","focus","scrollToHeading","applyMarkdownFragment","replaceSelection","executeSelectionCommand","insertStructuredBlock","restoreCheckpoint"],a0=t=>Number.isInteger(t)&&Number(t)>=0,gp=t=>typeof t=="string"&&t.length>0,l0=t=>{if(!t||typeof t!="object")return null;let e=t;return e.protocolVersion!==2||!gp(e.commandID)||typeof e.documentID!="string"||!a0(e.documentGeneration)||!UO.includes(e.type)||!e.payload||typeof e.payload!="object"||Array.isArray(e.payload)||e.minimumRevision!==void 0&&!a0(e.minimumRevision)||e.requestID!==void 0&&!gp(e.requestID)||e.type==="requestSnapshot"&&!gp(e.requestID)?null:e},c0=(t,e)=>t.type==="loadDocument"?t.documentGeneration>e.documentGeneration||t.documentGeneration===e.documentGeneration&&(!e.documentID||t.documentID===e.documentID):t.documentID===e.documentID&&t.documentGeneration===e.documentGeneration&&(t.minimumRevision===void 0||t.minimumRevision<=e.revision),u0=(t,e)=>e?{revision:t.revision+1,dirty:!0,changed:!0}:{...t,changed:!1},f0=(t,e)=>({...e,protocolVersion:2,documentID:t.documentID,documentGeneration:t.documentGeneration,revision:t.revision});var JO=(t,e)=>{let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r-=1)n+=1;return n%2===1},d0=t=>{let e=[],n=/!\[\[([^\]\n]+)\]\]|\[\[([^\]\n]+)\]\]|==([^=\n]+)==|\^\[([^\]\n]+)\]/g,r=0;for(let i of t.matchAll(n)){let o=i.index||0;if(JO(t,o))continue;o>r&&e.push({type:"text",value:t.slice(r,o)});let s=i[1]??i[2];if(s!==void 0){let a=s.indexOf("|"),l=(a<0?s:s.slice(0,a)).trim(),c=(a<0?"":s.slice(a+1)).trim();e.push({type:i[1]===void 0?"wikiLink":"embed",raw:s,target:l,label:c})}else i[3]!==void 0?e.push({type:"highlight",value:i[3]}):e.push({type:"inlineFootnote",value:i[4]});r=o+i[0].length}return r<t.length&&e.push({type:"text",value:t.slice(r)}),e.length?e:[{type:"text",value:t}]};var p0=t=>{let e=t.match(/^\[!([A-Za-z][A-Za-z0-9_-]*)\]([+-]?)(?:[ \t]+(.+))?$/);return e?{calloutType:e[1].toLowerCase(),fold:e[2]||"",title:(e[3]||"").trim()}:null},h0=t=>`[!${t.calloutType}]${t.fold}${t.title?` ${t.title}`:""}`;var yp=new Set(["system","serif","literary"]),GO=t=>{let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],i=r.type==="html"?String(r.value||"").match(/^<span data-weibei-font="(system|serif|literary)">$/):null;if(!i){e.push(r);continue}let o=t.findIndex((s,a)=>a>n&&s.type==="html"&&String(s.value||"")==="</span>");if(o<0){e.push(r);continue}e.push({type:"writingFont",font:i[1],children:t.slice(n+1,o)}),n=o}return e},XO=t=>t.type==="text"?{type:"text",value:t.value}:t.type==="highlight"?{type:"highlight",children:[{type:"text",value:t.value}]}:t.type==="inlineFootnote"?{type:"inlineFootnote",value:t.value}:{type:t.type,raw:t.raw,target:t.target,label:t.label},m0=t=>{if(!t.children||["code","inlineCode","html"].includes(t.type))return;if(t.type==="blockquote"){let n=t.children[0],r=n?.type==="paragraph"&&n.children?.length===1&&n.children[0].type==="text"?String(n.children[0].value||""):"",i=p0(r);if(i){t.type="callout",t.calloutType=i.calloutType,t.fold=i.fold,t.title=i.title,t.children=t.children.slice(1),t.children.length===0&&t.children.push({type:"paragraph",children:[]});let o=t.children[0]?.type==="paragraph"?t.children[0].children?.[0]:null;o?.type==="text"&&(o.value=String(o.value||"").replace(/^\[![A-Za-z][A-Za-z0-9_-]*\][+-]?[ \t]*/,""))}}let e=t.children.flatMap(n=>n.type!=="text"?(m0(n),[n]):d0(String(n.value||"")).map(XO));t.children=GO(e)},YO=gt("weiBeiStructuredMarkdown",()=>(function(){let e=this.data();return(e.toMarkdownExtensions||(e.toMarkdownExtensions=[])).push({handlers:{wikiLink:(r,i,o,s)=>`[[${o.safe(r.raw,{...s,before:"[[",after:"]]"})}]]`,embed:(r,i,o,s)=>`![[${o.safe(r.raw,{...s,before:"![[",after:"]]"})}]]`,inlineFootnote:(r,i,o,s)=>`^[${o.safe(r.value,{...s,before:"^[",after:"]"})}]`,highlight:(r,i,o,s)=>`==${o.containerPhrasing(r,{...s,before:"==",after:"=="})}==`,writingFont:(r,i,o,s)=>{let a=yp.has(r.font)?r.font:"serif",l=o.containerPhrasing(r,{...s,before:">",after:"<"});return`<span data-weibei-font="${a}">${l}</span>`},callout:(r,i,o,s)=>{let l={type:"blockquote",children:[{type:"paragraph",children:[{type:"text",value:h0({calloutType:r.calloutType,fold:r.fold||"",title:r.title||""})}]},...r.children||[]]},c=o.enter("blockquote"),u=o.createTracker(s);u.move("> "),u.shift(2);let f=o.indentLines(o.containerFlow(l,u.current()),(d,p,h)=>`>${h?"":" "}${d}`);return c(),f}}}),r=>m0(r)})),g0=ce("wiki_link",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="wiki_link"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"wiki_link","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-wikilink weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="wikiLink",runner:(t,e,n)=>{t.addNode(n,{raw:e.raw,target:e.target,label:e.label})}},toMarkdown:{match:t=>t.type.name==="wiki_link",runner:(t,e)=>t.addNode("wikiLink",void 0,void 0,e.attrs)}})),y0=ce("embed",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="embed"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"embed","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-embed-note weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="embed",runner:(t,e,n)=>t.addNode(n,{raw:e.raw,target:e.target,label:e.label})},toMarkdown:{match:t=>t.type.name==="embed",runner:(t,e)=>t.addNode("embed",void 0,void 0,e.attrs)}})),k0=ce("inline_footnote",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{value:{default:""}},parseDOM:[{tag:'span[data-type="inline_footnote"]',getAttrs:t=>t instanceof HTMLElement?{value:t.dataset.value||""}:!1}],toDOM:t=>["span",{"data-type":"inline_footnote","data-value":t.attrs.value,class:"weibei-inline-footnote weibei-structured-node"},t.attrs.value],parseMarkdown:{match:t=>t.type==="inlineFootnote",runner:(t,e,n)=>t.addNode(n,{value:e.value})},toMarkdown:{match:t=>t.type.name==="inline_footnote",runner:(t,e)=>t.addNode("inlineFootnote",void 0,void 0,{value:e.attrs.value})}})),QO=ge(t=>ki(/!\[\[([^\]\n]+)\]\]$/,y0.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),ZO=ge(t=>ki(/(?<!!)\[\[([^\]\n]+)\]\]$/,g0.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),eD=ge(t=>ki(/\^\[([^\]\n]+)\]$/,k0.type(t),{getAttr:e=>({value:e[1]||""})})),b0=Pt("highlight",()=>({parseDOM:[{tag:"mark.weibei-highlight"}],toDOM:()=>["mark",{class:"weibei-highlight"},0],parseMarkdown:{match:t=>t.type==="highlight",runner:(t,e,n)=>t.openMark(n).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="highlight",runner:(t,e)=>{t.withMark(e,"highlight")}}})),tD=Pt("writing_font",()=>({attrs:{font:{default:"serif"}},excludes:"writing_font",priority:10,parseDOM:[{tag:"span[data-weibei-font]",getAttrs:t=>{let e=t instanceof HTMLElement?t.dataset.weibeiFont:"";return e&&yp.has(e)?{font:e}:!1}}],toDOM:t=>["span",{"data-weibei-font":yp.has(t.attrs.font)?t.attrs.font:"serif"},0],parseMarkdown:{match:t=>t.type==="writingFont",runner:(t,e,n)=>t.openMark(n,{font:e.font}).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="writing_font",runner:(t,e)=>{t.withMark(e,"writingFont",void 0,{font:e.attrs.font})}}})),nD=ge(t=>ln(/(?:^|[^\\=])==([^=\n]+)==$/,b0.type(t))),rD=ce("callout",()=>({content:"block+",group:"block",defining:!0,selectable:!0,attrs:{calloutType:{default:"note"},title:{default:""},fold:{default:""}},parseDOM:[{tag:'blockquote[data-type="callout"]',getAttrs:t=>t instanceof HTMLElement?{calloutType:t.dataset.callout||"note",title:t.dataset.calloutTitle||"",fold:t.dataset.calloutFold||""}:!1}],toDOM:t=>["blockquote",{"data-type":"callout","data-callout":t.attrs.calloutType,"data-callout-title":t.attrs.title,"data-callout-fold":t.attrs.fold,class:`weibei-callout weibei-callout-${t.attrs.calloutType}`},0],parseMarkdown:{match:t=>t.type==="callout",runner:(t,e,n)=>t.openNode(n,{calloutType:e.calloutType,title:e.title,fold:e.fold}).next(e.children).closeNode()},toMarkdown:{match:t=>t.type.name==="callout",runner:(t,e)=>{t.openNode("callout",void 0,e.attrs).next(e.content).closeNode()}}})),x0=[YO,g0,y0,k0,tD,b0,nD,rD,QO,ZO,eD].flat();var K0=window.webkit?.messageHandlers,at=window.weiBeiEditorCheckMode?i0():null,V,Zr="",zl=null,Ts=null,Pl=!1,Zt=null,Qi={text:null,rectKey:null,detailKey:null},oo="",re=window.weiBeiMarkdownEditable!==!1,_l=window.weiBeiMarkdownCompactPreview===!0,nt=window.weiBeiDocumentID||"",Ve=window.weiBeiDocumentGeneration||0,Mn={revision:0,dirty:!1},Ep=new Set,Tp=!1,U0=!1,vp=0,J0=window.weiBeiMarkdownBaseURL||"",oD=window.weiBeiLocalImageScheme||"weibeiimage",_p=0,sD=0,w0=0,Zi=0,Gn=new Map,_t=new Map,G0=_w("WEIBEI_BLOCK_COMMAND"),aD=ge(t=>ki(e0,pp.type(t),{beforeDispatch:({tr:e,match:n,start:r})=>e.insertText(n[1]||"",r+1)})),lD=[Kw,pp,Ol,Uw,aD].flat(),Xn=0,we=null,Qt=null,so=null,Ap=[],Ip=[],Yr=0,C0="{{WEIBEI_CURSOR}}",kp="{{WEIBEI_SELECT_START}}",S0="{{WEIBEI_SELECT_END}}",bp=new Set(["note","tip","important","warning","caution","summary","abstract","quote","question","example","info","success","failure","danger","bug","todo"]);var X0=t=>t==="en"?"en":"zh-Hans",Jr=X0(window.weiBeiInterfaceLanguage),M0={"zh-Hans":{note:"\u672D\u8BB0",tip:"\u63D0\u793A",important:"\u91CD\u70B9",warning:"\u7559\u5FC3",caution:"\u8C28\u614E",summary:"\u63D0\u8981",abstract:"\u6458\u8981",quote:"\u5F15\u6587",question:"\u95EE\u9898",example:"\u4F8B\u5B50",info:"\u4FE1\u606F",success:"\u53EF\u884C",failure:"\u5931\u8D25",danger:"\u98CE\u9669",bug:"\u95EE\u9898",todo:"\u5F85\u529E"},en:{note:"Note",tip:"Tip",important:"Important",warning:"Warning",caution:"Caution",summary:"Summary",abstract:"Abstract",quote:"Quote",question:"Question",example:"Example",info:"Info",success:"Success",failure:"Failure",danger:"Danger",bug:"Bug",todo:"Todo"}},E0=t=>M0[Jr]?.[t]||M0["zh-Hans"][t]||t,Bl={"zh-Hans":{properties:"\u5C5E\u6027",bootFailed:"Milkdown \u521D\u59CB\u5316\u5931\u8D25",imageMissing:"\u56FE\u7247\u672A\u627E\u5230",inlineFootnote:"\u884C\u5185\u811A\u6CE8\uFF1A{value}",openOrCreateNote:"\u6253\u5F00\u6216\u521B\u5EFA\u7B14\u8BB0\uFF1A{value}",openSource:"\u6253\u5F00\u6765\u6E90\uFF1A{value}",embed:"\u5D4C\u5165\uFF1A{value}",mermaidRendering:"\u6B63\u5728\u6E32\u67D3 Mermaid \u56FE\u8868...",mermaidFailed:`Mermaid \u56FE\u8868\u672A\u89E3\u6790 {value}`,uploadingImage:"\u6B63\u5728\u6536\u7EB3\u56FE\u7247...",emptyNotePlaceholder:"\u4ECE\u8FD9\u91CC\u5F00\u59CB\u5199\u4E0B\u7B2C\u4E00\u53E5\u2026",slashNoResults:"\u6CA1\u6709\u5339\u914D\u547D\u4EE4",slashStructure:"\u7ED3\u6784",slashLists:"\u5217\u8868",slashContent:"\u5185\u5BB9",slashRichContent:"\u4E30\u5BCC\u5185\u5BB9",slashFonts:"\u5B57\u4F53",slashHeading1:"\u4E00\u7EA7\u6807\u9898",slashHeading2:"\u4E8C\u7EA7\u6807\u9898",slashHeading3:"\u4E09\u7EA7\u6807\u9898",slashHeading4:"\u56DB\u7EA7\u6807\u9898",slashHeading5:"\u4E94\u7EA7\u6807\u9898",slashHeading6:"\u516D\u7EA7\u6807\u9898",slashBulletList:"\u65E0\u5E8F\u5217\u8868",slashOrderedList:"\u6709\u5E8F\u5217\u8868",slashTaskList:"\u5F85\u529E\u5217\u8868",slashQuote:"\u5F15\u7528",slashCallout:"\u63D0\u793A\u5757",slashCode:"\u4EE3\u7801\u5757",slashDivider:"\u5206\u9694\u7EBF",slashTable:"\u8868\u683C",slashImage:"\u56FE\u7247",slashMermaid:"Mermaid \u56FE\u8868",slashLink:"\u94FE\u63A5",slashWikiLink:"\u7B14\u8BB0\u94FE\u63A5",slashFootnote:"\u811A\u6CE8",slashInlineMath:"\u884C\u5185\u516C\u5F0F",slashBlockMath:"\u5757\u7EA7\u516C\u5F0F",slashFontSystem:"\u5B57\u4F53\uFF1ASF Pro / PingFang SC",slashFontSerif:"\u5B57\u4F53\uFF1ASongti SC",slashFontLiterary:"\u5B57\u4F53\uFF1AWeiBeiStele",slashRows:"\u884C",slashColumns:"\u5217",slashInsertTable:"\u63D2\u5165\u8868\u683C",slashImageFailed:"\u56FE\u7247\u8BFB\u53D6\u6216\u4FDD\u5B58\u5931\u8D25",tableAddRow:"\uFF0B\u884C",tableDeleteRow:"\u2212\u884C",tableAddColumn:"\uFF0B\u5217",tableDeleteColumn:"\u2212\u5217",tableHeader:"\u8868\u5934",linkPlaceholder:"\u94FE\u63A5\u6587\u5B57",wikiLinkPlaceholder:"\u7B14\u8BB0\u6807\u9898",footnotePlaceholder:"\u811A\u6CE8\u5185\u5BB9",codeLanguage:"\u4EE3\u7801\u8BED\u8A00",codeLanguagePlaceholder:"text"},en:{properties:"Properties",bootFailed:"Milkdown failed to initialize",imageMissing:"Image not found",inlineFootnote:"Inline footnote: {value}",openOrCreateNote:"Open or create note: {value}",openSource:"Open source: {value}",embed:"Embed: {value}",mermaidRendering:"Rendering Mermaid diagram...",mermaidFailed:`Mermaid diagram did not parse -{value}`,uploadingImage:"Saving image...",emptyNotePlaceholder:"Start writing here\u2026",slashNoResults:"No matching commands",slashStructure:"Structure",slashLists:"Lists",slashContent:"Content",slashRichContent:"Rich content",slashFonts:"Fonts",slashHeading1:"Heading 1",slashHeading2:"Heading 2",slashHeading3:"Heading 3",slashHeading4:"Heading 4",slashHeading5:"Heading 5",slashHeading6:"Heading 6",slashBulletList:"Bulleted list",slashOrderedList:"Numbered list",slashTaskList:"To-do list",slashQuote:"Quote",slashCallout:"Callout",slashCode:"Code block",slashDivider:"Divider",slashTable:"Table",slashImage:"Image",slashMermaid:"Mermaid diagram",slashLink:"Link",slashWikiLink:"Note link",slashFootnote:"Footnote",slashInlineMath:"Inline formula",slashBlockMath:"Block formula",slashFontSystem:"Font: SF Pro / PingFang SC",slashFontSerif:"Font: Songti SC",slashFontLiterary:"Font: WeiBeiStele",slashRows:"Rows",slashColumns:"Columns",slashInsertTable:"Insert table",slashImageFailed:"Image could not be read or saved",tableAddRow:"+ Row",tableDeleteRow:"\u2212 Row",tableAddColumn:"+ Column",tableDeleteColumn:"\u2212 Column",tableHeader:"Header",linkPlaceholder:"Link text",wikiLinkPlaceholder:"Note title",footnotePlaceholder:"Footnote",codeLanguage:"Code language",codeLanguagePlaceholder:"text"}},ue=(t,e={})=>{let n=Bl[Jr]?.[t]||Bl["zh-Hans"][t]||t;for(let[r,i]of Object.entries(e))n=n.split(`{${r}}`).join(String(i));return n},lD=()=>ue("properties"),cD=new RegExp(`(^|\\n)\\s*(?:>\\s*)*\\\\?\\[!(?:${mp})\\][+-]?[ \\t]*`,"gi"),uD=/<br\s*\/?>/gi,X0=t=>String(t||"").replace(uD,` -`).replace(/%%[\s\S]*?%%\n?/g,"").replace(/!\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=RD(n);return r.label||r.target}).replace(/\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=u1(n);return r.display||r.target}).replace(/!\[([^\]\n]*)\]\([^\)\n]+\)/g,(e,n)=>Fl(n).alt||"").replace(/\[([^\]\n]+)\]\([^\)\n]+\)/g,"$1").replace(/==([^=\n]+)==/g,"$1").replace(/~~([^~\n]+)~~/g,"$1").replace(/`([^`\n]+)`/g,"$1").replace(/\^\[([^\]\n]+)\]/g,"$1").replace(cD,"$1").replace(/(^|\n)\s*>\s?/g,"$1").replace(/(^|\n)\s*[-*+]\s+\[[ xX]\]\s*/g,"$1").replace(/[ \t]+\n/g,` +{value}`,uploadingImage:"Saving image...",emptyNotePlaceholder:"Start writing here\u2026",slashNoResults:"No matching commands",slashStructure:"Structure",slashLists:"Lists",slashContent:"Content",slashRichContent:"Rich content",slashFonts:"Fonts",slashHeading1:"Heading 1",slashHeading2:"Heading 2",slashHeading3:"Heading 3",slashHeading4:"Heading 4",slashHeading5:"Heading 5",slashHeading6:"Heading 6",slashBulletList:"Bulleted list",slashOrderedList:"Numbered list",slashTaskList:"To-do list",slashQuote:"Quote",slashCallout:"Callout",slashCode:"Code block",slashDivider:"Divider",slashTable:"Table",slashImage:"Image",slashMermaid:"Mermaid diagram",slashLink:"Link",slashWikiLink:"Note link",slashFootnote:"Footnote",slashInlineMath:"Inline formula",slashBlockMath:"Block formula",slashFontSystem:"Font: SF Pro / PingFang SC",slashFontSerif:"Font: Songti SC",slashFontLiterary:"Font: WeiBeiStele",slashRows:"Rows",slashColumns:"Columns",slashInsertTable:"Insert table",slashImageFailed:"Image could not be read or saved",tableAddRow:"+ Row",tableDeleteRow:"\u2212 Row",tableAddColumn:"+ Column",tableDeleteColumn:"\u2212 Column",tableHeader:"Header",linkPlaceholder:"Link text",wikiLinkPlaceholder:"Note title",footnotePlaceholder:"Footnote",codeLanguage:"Code language",codeLanguagePlaceholder:"text"}},ue=(t,e={})=>{let n=Bl[Jr]?.[t]||Bl["zh-Hans"][t]||t;for(let[r,i]of Object.entries(e))n=n.split(`{${r}}`).join(String(i));return n},cD=()=>ue("properties"),uD=new RegExp(`(^|\\n)\\s*(?:>\\s*)*\\\\?\\[!(?:${mp})\\][+-]?[ \\t]*`,"gi"),fD=/<br\s*\/?>/gi,Y0=t=>String(t||"").replace(fD,` +`).replace(/%%[\s\S]*?%%\n?/g,"").replace(/!\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=OD(n);return r.label||r.target}).replace(/\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=f1(n);return r.display||r.target}).replace(/!\[([^\]\n]*)\]\([^\)\n]+\)/g,(e,n)=>Fl(n).alt||"").replace(/\[([^\]\n]+)\]\([^\)\n]+\)/g,"$1").replace(/==([^=\n]+)==/g,"$1").replace(/~~([^~\n]+)~~/g,"$1").replace(/`([^`\n]+)`/g,"$1").replace(/\^\[([^\]\n]+)\]/g,"$1").replace(uD,"$1").replace(/(^|\n)\s*>\s?/g,"$1").replace(/(^|\n)\s*[-*+]\s+\[[ xX]\]\s*/g,"$1").replace(/[ \t]+\n/g,` `).replace(/\n{2,}/g,` -`).trim(),Y0=t=>t==="glassLight"||t==="glassMist"?"xuan":t==="glassDark"||t==="glassSlate"?"stele":t==="xuan"||t==="inkstone"||t==="stele"||t==="paper"?t:"paper",fD=t=>["glassLight","glassDark","glassMist","glassSlate"].includes(t)?t:"",eo=Y0(window.weiBeiTheme),dD=()=>{switch(eo){case"inkstone":return{background:"#151515",primaryColor:"#1c1c1c",primaryTextColor:"#d7cbb0",primaryBorderColor:"#3a3328",lineColor:"#8b5e3c",secondaryColor:"#222222",tertiaryColor:"#171717",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"stele":return{background:"#1e2228",primaryColor:"#252a32",primaryTextColor:"#d2d6dc",primaryBorderColor:"#3a414c",lineColor:"#8a7a5c",secondaryColor:"#2a3038",tertiaryColor:"#1a1e24",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"xuan":return{background:"#f7f4ef",primaryColor:"#fcfbf8",primaryTextColor:"#25231f",primaryBorderColor:"#d8d2c6",lineColor:"#6e634f",secondaryColor:"#ebe6dc",tertiaryColor:"#f7f4ef",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};default:return{background:"#fbf5e8",primaryColor:"#f6eddc",primaryTextColor:"#2e261f",primaryBorderColor:"#cbb79b",lineColor:"#7a6250",secondaryColor:"#efe4d2",tertiaryColor:"#f8f0e1",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'}}},pD=t=>{t.initialize({startOnLoad:!1,securityLevel:"strict",theme:"base",themeVariables:dD()})},Q0=t=>{eo=Y0(t);let e=fD(t);document.documentElement.dataset.weibeiTheme=eo,document.body&&(document.body.dataset.weibeiTheme=eo),e?(document.documentElement.dataset.weibeiGlass=e,document.body&&(document.body.dataset.weibeiGlass=e)):(delete document.documentElement.dataset.weibeiGlass,document.body&&delete document.body.dataset.weibeiGlass),Zi+=1};Q0(window.weiBeiTheme);var no=t=>{if(window.WeiBeiEditorBootFailed){window.WeiBeiEditorBootFailed(t);return}let e=document.querySelector("#editor");e&&(e.innerHTML=`<pre style="white-space:pre-wrap;color:#9f3427;padding:24px;font:13px/1.5 SFMono-Regular,Menlo,monospace;">${ue("bootFailed")} -${String(t?.stack||t)}</pre>`)};window.addEventListener("error",t=>no(t.error||t.message));window.addEventListener("unhandledrejection",t=>no(t.reason));var Ie=(t,e={})=>{let n=q0?.[t];if(!n)return;let r=u0({documentID:nt,documentGeneration:Ve,revision:Mn.revision},e);typeof r.markdown=="string"&&(Tp+=1),It(at,"bridgeMessages"),at&&It(at,"bridgeBytes",new TextEncoder().encode(JSON.stringify(r)).byteLength),n.postMessage(r)},G=document.createElement("div"),Gr=document.createElement("div"),st=document.createElement("button"),Me=document.createElement("div");G.className="weibei-slash-menu",G.dataset.show="false",G.dataset.state="closed",G.setAttribute("role","listbox"),G.setAttribute("aria-label","Slash commands"),Gr.className="weibei-visually-hidden",Gr.setAttribute("role","status"),Gr.setAttribute("aria-live","polite"),st.type="button",st.className="weibei-line-plus",st.textContent="\uFF0B",st.setAttribute("aria-label","\u63D2\u5165\u5185\u5BB9"),st.hidden=!0,Me.className="weibei-table-toolbar",Me.dataset.state="closed",Me.setAttribute("aria-hidden","true"),Me.setAttribute("role","toolbar");for(let[t,e]of[["addRow","tableAddRow"],["deleteRow","tableDeleteRow"],["addColumn","tableAddColumn"],["deleteColumn","tableDeleteColumn"],["header","tableHeader"]]){let n=document.createElement("button");n.type="button",n.dataset.action=t,n.dataset.label=e,Me.append(n)}var As=null,hD=[{id:"structure",label:"slashStructure"},{id:"lists",label:"slashLists"},{id:"content",label:"slashContent"},{id:"rich",label:"slashRichContent"},{id:"fonts",label:"slashFonts"}],mD=[{id:"heading1",group:"structure",label:"slashHeading1",aliases:["h1","heading_1","yjbt","yijibiaoti","\u4E00\u7EA7","\u6807\u98981"]},{id:"heading2",group:"structure",label:"slashHeading2",aliases:["h2","heading_2","ejbt","erjibiaoti","\u4E8C\u7EA7","\u6807\u98982"]},{id:"heading3",group:"structure",label:"slashHeading3",aliases:["h3","heading_3","sjbt","sanjibiaoti","\u4E09\u7EA7","\u6807\u98983"]},{id:"heading4",group:"structure",label:"slashHeading4",aliases:["h4","heading_4","sijbt","sijibiaoti","\u56DB\u7EA7","\u6807\u98984"]},{id:"heading5",group:"structure",label:"slashHeading5",aliases:["h5","heading_5","wjbt","wujibiaoti","\u4E94\u7EA7","\u6807\u98985"]},{id:"heading6",group:"structure",label:"slashHeading6",aliases:["h6","heading_6","ljbt","liujibiaoti","\u516D\u7EA7","\u6807\u98986"]},{id:"bulletList",group:"lists",label:"slashBulletList",aliases:["bullet_list","bullet","ul","wxlb","wuxuliebiao","\u65E0\u5E8F","\u9879\u76EE\u7B26\u53F7"]},{id:"orderedList",group:"lists",label:"slashOrderedList",aliases:["ordered_list","ol","yxlb","youxuliebiao","\u6709\u5E8F","\u7F16\u53F7"]},{id:"taskList",group:"lists",label:"slashTaskList",aliases:["task_list","todo","task","checklist","dblb","daibanliebiao","\u5F85\u529E","\u4EFB\u52A1"]},{id:"quote",group:"lists",label:"slashQuote",aliases:["quote","blockquote","yy","yinyong","\u5F15\u7528"]},{id:"callout",group:"content",label:"slashCallout",aliases:["callout","note","tsk","tishikuai","\u63D0\u793A","\u672D\u8BB0"]},{id:"code",group:"content",label:"slashCode",aliases:["code","code_block","dmk","daimakuai","\u4EE3\u7801"]},{id:"divider",group:"content",label:"slashDivider",aliases:["divider","horizontal_rule","hr","fgx","fengexian","\u5206\u9694","\u6A2A\u7EBF"]},{id:"link",group:"content",label:"slashLink",aliases:["link","url","lj","lianjie","\u94FE\u63A5","\u7F51\u5740"]},{id:"wikiLink",group:"content",label:"slashWikiLink",aliases:["wiki","note_link","bjl","bijilianjie","\u7B14\u8BB0","\u53CC\u94FE"]},{id:"footnote",group:"content",label:"slashFootnote",aliases:["footnote","note_ref","jz","jiaozhu","\u811A\u6CE8","\u6CE8\u91CA"]},{id:"table",group:"rich",label:"slashTable",aliases:["table","grid","bg","biaoge","\u8868\u683C"]},{id:"image",group:"rich",label:"slashImage",aliases:["image","photo","picture","tp","tupian","\u56FE\u7247","\u7167\u7247"]},{id:"mermaid",group:"rich",label:"slashMermaid",aliases:["mermaid","diagram","flowchart","lct","liuchengtu","\u56FE\u8868","\u6D41\u7A0B\u56FE"]},{id:"inlineMath",group:"rich",label:"slashInlineMath",aliases:["math","formula","inline_math","hngs","hangneigongshi","\u516C\u5F0F","\u884C\u5185"]},{id:"blockMath",group:"rich",label:"slashBlockMath",aliases:["display_math","equation","block_math","kjgs","kuaijigongshi","\u65B9\u7A0B","\u5757\u7EA7"]},{id:"fontSystem",group:"fonts",label:"slashFontSystem",aliases:["font","system","sf pro","pingfang sc","ziti","\u5B57\u4F53","\u82F9\u65B9"]},{id:"fontSerif",group:"fonts",label:"slashFontSerif",aliases:["font","serif","songti sc","ziti","\u5B57\u4F53","\u5B8B\u4F53"]},{id:"fontLiterary",group:"fonts",label:"slashFontLiterary",aliases:["font","weibeistele","wei bei stele","ziti","\u5B57\u4F53","\u9B4F\u7891"]}],Z0=new Set(["system","serif","literary"]),Ip={fontSystem:"system",fontSerif:"serif",fontLiterary:"literary"},I={provider:null,view:null,context:null,commands:[],activeIndex:0,dismissedContext:"",activationContext:"",tableOpen:!1,tableFocus:"rows",tableRows:3,tableColumns:3,tableMenuBaseLeft:"",error:""},e1=new Set(["list_item","task_list_item","table","table_row","table_header_row","table_cell","table_header","code_block","math_block"]),Pe={state:"closed",generation:0,timer:0,frame:0},Np=()=>document.documentElement.dataset.weibeiReduceMotion==="true",t1=t=>{document.documentElement.dataset.weibeiReduceMotion=t===!0||t==="true"?"true":"false"},n1=t=>{let e=Number(t),n=Number.isFinite(e)&&e>0?e:1;document.documentElement.style.setProperty("--weibei-text-scale",String(n))},ro=t=>{if(!re||t.composing)return null;let{selection:e}=t.state;if(!(e instanceof B)||!e.empty)return null;let{$from:n}=e;if(n.parent.type.name!=="paragraph")return null;for(let u=n.depth;u>0;u-=1)if(e1.has(n.node(u).type.name))return null;let r=n.parent.textBetween(0,n.parentOffset,"\uFFFC","\uFFFC"),i=r.lastIndexOf("/");if(i<0)return null;let o=r.slice(i+1);if(/[\s/]/u.test(o))return null;let s=/^[\u200B\uFEFF]*$/u.test(r.slice(0,i))?0:i,a=n.depth,l=n.before(a),c=n.start(a)+s;return{query:o,parent:n.parent,triggerFrom:c,triggerTo:n.pos,triggerStartOffset:s,triggerEndOffset:n.parentOffset,blockFrom:l,blockTo:n.after(a),index:n.index(a-1),container:n.node(a-1),key:`${c}:${o}`}},r1=t=>{if(!re||t.composing)return null;let{selection:e}=t.state;if(!(e instanceof B)||!e.empty||e.$from.parent.type.name!=="paragraph"||e.$from.parent.content.size!==0)return null;for(let n=e.$from.depth;n>0;n-=1)if(e1.has(e.$from.node(n).type.name))return null;return e.$from},E0=t=>{let e=r1(t);if(st.hidden=!e,!e)return;let n=t.coordsAtPos(e.pos);st.style.left=`${Math.max(6,n.left-30)}px`,st.style.top=`${Math.max(6,n.top-2)}px`},_p=(t,e,n={})=>{let r=e.nodes.paragraph;if(!r)return null;if(t.startsWith("heading")){let i=e.nodes.heading;return i?{content:M.from(i.create({level:Number(t.at(-1))})),selectionOffset:1}:null}if(["bulletList","orderedList","taskList"].includes(t)){let i=t==="orderedList"?e.nodes.ordered_list:e.nodes.bullet_list,o=e.nodes.list_item?.createAndFill(t==="taskList"?{checked:!1}:null,r.create()),s=o&&i?.createAndFill(null,o);return s?{content:M.from(s),selectionOffset:3}:null}if(t==="callout"){let o=e.nodes.callout?.create({calloutType:"note",title:"",fold:""},r.create());return o?{content:M.from(o),selectionOffset:2}:null}if(t==="quote"){let i=e.nodes.blockquote||e.nodes.block_quote;if(!i)return null;let o=i.create(null,r.create());return{content:M.from(o),selectionOffset:2}}if(t==="code"||t==="mermaid"){let i=e.nodes.code_block;if(!i)return null;let o=t==="mermaid"?`graph TD - A --> B`:"";return{content:M.from(i.create({language:t==="mermaid"?"mermaid":""},o?e.text(o):null)),selectionOffset:o.length+1}}if(t==="inlineMath"){let o=e.nodes.math_inline?.create(null,e.text("x"));return o?{content:M.from(r.create(null,o)),selectionOffset:1}:null}if(t==="link"){let i=e.marks.link,o=ue("linkPlaceholder"),s=i?r.create(null,e.text(o,[i.create({href:""})])):null;return s?{content:M.from(s),selectionFromOffset:1,selectionToOffset:o.length+1}:null}if(t==="wikiLink"){let i=e.nodes.wiki_link,o=ue("wikiLinkPlaceholder"),s=i?.create({raw:o,target:o,label:""});return s?{content:M.from(r.create(null,s)),selectionOffset:1,activateEvent:"weibei-edit-structured"}:null}if(t==="footnote"){let o=e.nodes.inline_footnote?.create({value:ue("footnotePlaceholder")});return o?{content:M.from(r.create(null,o)),selectionOffset:1,activateEvent:"weibei-edit-structured"}:null}if(t==="blockMath"){let o=e.nodes.math_block?.create({value:"x"});return o?{content:M.from(o),selectionOffset:0}:null}if(t==="divider"){let o=(e.nodes.hr||e.nodes.horizontal_rule)?.create();return o?{content:M.from([o,r.create()]),selectionOffset:o.nodeSize+1}:null}if(t==="table"){let{table:i,table_header_row:o,table_row:s,table_header:a,table_cell:l}=e.nodes,c=Math.min(20,Math.max(1,Number(n.rows)||3)),u=Math.min(12,Math.max(1,Number(n.columns)||3));if(!i||!o||!s||!a||!l)return null;let f=Array.from({length:u},()=>a.createAndFill()),d=Array.from({length:c-1},()=>s.create(null,Array.from({length:u},()=>l.createAndFill())));return f.some(p=>!p)||d.some(p=>!p)?null:{content:M.from(i.create(null,[o.create(null,f),...d])),selectionOffset:4}}if(t==="image"){let i=e.nodes.image;return i&&n.src?{content:M.from(r.create(null,i.create({src:n.src,alt:n.alt||"image"}))),selectionOffset:2}:null}return null},i1=(t,e)=>{let n=e?.content?.firstChild;if(!t||!n)return null;if(e.content.childCount===1&&n.type===t.parent.type){let a=t.parent.content.cut(0,t.triggerStartOffset).append(n.content).append(t.parent.content.cut(t.triggerEndOffset));return{content:M.from(t.parent.type.create(t.parent.attrs,a,t.parent.marks)),selectionBase:t.triggerFrom-1}}let r=[],i=t.parent.content.cut(0,t.triggerStartOffset),o=t.parent.content.cut(t.triggerEndOffset);i.size&&r.push(t.parent.type.create(t.parent.attrs,i,t.parent.marks));let s=t.blockFrom+r.reduce((a,l)=>a+l.nodeSize,0);return e.content.forEach(a=>r.push(a)),o.size&&r.push(t.parent.type.create(t.parent.attrs,o,t.parent.marks)),{content:M.from(r),selectionBase:s}},gD=(t,e,n)=>{if(!e)return!1;if(Ip[t.id])return!!n.marks.writing_font;if(t.id==="image")return!!n.nodes.image;let r=_p(t.id,n,{rows:3,columns:3}),i=i1(e,r);return!!(i&&e.container.canReplace(e.index,e.index+1,i.content))},yD=(t,e,n)=>{let r=String(t||"").toLocaleLowerCase();return mD.filter(i=>gD(i,e,n)&&(!r||[Bl["zh-Hans"][i.label],Bl.en[i.label],...i.aliases].some(o=>String(o).toLocaleLowerCase().includes(r))))},o1=(t,e,n)=>{if(!e||!n)return!1;let r=t.state.doc.nodeAt(e.blockFrom),i=i1(e,n);if(!r?.eq(e.parent)||!i||!e.container.canReplace(e.index,e.index+1,i.content))return!1;let o=us(t.state.tr.replaceWith(e.blockFrom,e.blockTo,i.content)),s=n.activateEvent?H.create(o.doc,i.selectionBase+n.selectionOffset):Number.isInteger(n.selectionFromOffset)&&Number.isInteger(n.selectionToOffset)?B.create(o.doc,i.selectionBase+n.selectionFromOffset,i.selectionBase+n.selectionToOffset):$.findFrom(o.doc.resolve(Math.min(i.selectionBase+n.selectionOffset,o.doc.content.size)),1,!0);return s&&o.setSelection(s),t.dispatch(o.scrollIntoView()),I.dismissedContext="",I.provider?.hide(),t.focus(),n.activateEvent&&s&&window.requestAnimationFrame(()=>{t.nodeDOM(s.from)?.dispatchEvent(new CustomEvent(n.activateEvent))}),window.requestAnimationFrame(to),!0},kD=(t,e)=>{let n=`image-picker-${Date.now()}-${zp+=1}`;_t.set(n,{mode:"insert",view:t,context:e,documentID:nt,documentGeneration:Ve}),I.dismissedContext=e.key,I.provider?.hide(),Ie("imagePickerRequested",{id:n})},bD=(t,e,n)=>{let r=t.state.schema.marks.writing_font;if(!r||!Z0.has(n))return!1;let i=t.state.storedMarks||t.state.selection.$from.marks(),o=us(t.state.tr.delete(e.triggerFrom,e.triggerTo));return o.setSelection(B.create(o.doc,e.triggerFrom)),o.setStoredMarks([...i.filter(s=>s.type!==r),r.create({font:n})]),t.dispatch(o.scrollIntoView()),I.dismissedContext="",I.provider?.hide(),t.focus(),window.requestAnimationFrame(to),!0},Xr=t=>{let e=I.view,n=e&&ro(e);return!e||!n?!1:t==="image"?(kD(e,n),!0):Ip[t]?bD(e,n,Ip[t]):o1(e,n,_p(t,e.state.schema,{rows:I.tableRows,columns:I.tableColumns}))},$p=()=>{let t=I.view?.dom,e=I.commands[I.activeIndex];if(!t||G.dataset.show!=="true"||!e){t?.removeAttribute("aria-controls"),t?.removeAttribute("aria-expanded"),t?.removeAttribute("aria-activedescendant");return}G.id="weibei-slash-menu",t.setAttribute("aria-controls",G.id),t.setAttribute("aria-expanded","true"),t.setAttribute("aria-activedescendant",`weibei-slash-command-${e.id}`),G.setAttribute("aria-activedescendant",`weibei-slash-command-${e.id}`),Gr.textContent=`${ue(e.label)}\uFF0C${I.activeIndex+1}/${I.commands.length}`},xD=()=>`${Jr}::${I.error?"!":""}::${I.commands.length}::${I.commands.map(t=>t.id).join(",")}`,T0=null,wD=()=>{if(G.replaceChildren(),I.error){let t=document.createElement("div");t.className="weibei-slash-error",t.textContent=I.error,G.appendChild(t)}if(!I.commands.length){let t=document.createElement("div");t.className="weibei-slash-empty",t.textContent=ue("slashNoResults"),G.appendChild(t);return}for(let t of hD){let e=I.commands.filter(i=>i.group===t.id);if(!e.length)continue;let n=document.createElement("section");n.className="weibei-slash-section";let r=document.createElement("div");r.className="weibei-slash-group",r.textContent=ue(t.label),n.appendChild(r);for(let i of e){let o=I.commands.indexOf(i),s=document.createElement("div");s.id=`weibei-slash-command-${i.id}`,s.className=`weibei-slash-command${o===I.activeIndex?" is-active":""}`,s.setAttribute("role","option"),s.setAttribute("aria-selected",String(o===I.activeIndex)),s.setAttribute("aria-posinset",String(o+1)),s.setAttribute("aria-setsize",String(I.commands.length));let a=document.createElement("button");a.type="button",a.tabIndex=-1,a.className="weibei-slash-command-button",a.textContent=ue(i.label),a.addEventListener("pointerdown",l=>l.preventDefault()),a.addEventListener("pointermove",l=>{!Number(l.movementX)&&!Number(l.movementY)||(I.activeIndex=o,I.tableOpen=i.id==="table",Hp(),Sn())}),a.addEventListener("click",()=>{i.id!=="table"&&Xr(i.id)}),s.appendChild(a),n.appendChild(s)}G.appendChild(n)}},Hp=()=>{G.querySelectorAll(".weibei-slash-command").forEach((t,e)=>{t.classList.toggle("is-active",e===I.activeIndex),t.setAttribute("aria-selected",String(e===I.activeIndex))}),G.querySelector(".weibei-slash-command.is-active")?.scrollIntoView({block:"nearest"}),$p()},Rp=null,s1=()=>{As?.remove(),As=null,Rp=null,I.tableMenuBaseLeft&&(G.style.left=I.tableMenuBaseLeft,I.tableMenuBaseLeft="")},Sn=()=>{let t=G.querySelector("#weibei-slash-command-table .weibei-slash-command-button");if(!I.tableOpen||G.dataset.show!=="true"||!t){s1();return}let e=Rp;if(!e){let f=document.createElement("div");f.className="weibei-slash-table-panel",f.setAttribute("role","group");let d=g=>{let y=g==="rows",b=document.createElement("div");b.className=`weibei-slash-stepper${I.tableFocus===g?" is-focused":""}`;let C=document.createElement("span");C.className="weibei-slash-stepper-label",C.textContent=ue(y?"slashRows":"slashColumns"),b.appendChild(C);let v=()=>y?I.tableRows:I.tableColumns,A=O=>{y?I.tableRows=O:I.tableColumns=O},w=document.createElement("button");w.type="button",w.textContent="\u2212",w.setAttribute("aria-label",`${C.textContent} \u2212`),w.addEventListener("pointerdown",O=>O.preventDefault()),w.addEventListener("click",()=>{A(Math.max(1,v()-1)),I.tableFocus=g,Sn()}),b.appendChild(w);let N=document.createElement("input");N.className="weibei-slash-stepper-input",N.type="number",N.inputMode="numeric",N.min="1",N.max=String(y?20:12),N.step="1",N.setAttribute("aria-label",C.textContent),N.addEventListener("focus",()=>{I.tableFocus=g,f.querySelectorAll(".weibei-slash-stepper.is-focused").forEach(O=>O.classList.remove("is-focused")),b.classList.add("is-focused")}),N.addEventListener("input",()=>{let O=Number.parseInt(N.value,10);Number.isFinite(O)&&A(Math.min(y?20:12,Math.max(1,O)))}),N.addEventListener("change",()=>{let O=Math.min(y?20:12,Math.max(1,Number.parseInt(N.value,10)||1));N.value=String(O),A(O)}),N.addEventListener("keydown",O=>{if(O.stopPropagation(),O.key==="Enter"){let S=Math.min(y?20:12,Math.max(1,Number.parseInt(N.value,10)||1));A(S),Xr("table"),O.preventDefault()}}),b.appendChild(N);let P=document.createElement("button");return P.type="button",P.textContent="+",P.setAttribute("aria-label",`${C.textContent} +`),P.addEventListener("pointerdown",O=>O.preventDefault()),P.addEventListener("click",()=>{A(Math.min(y?20:12,v()+1)),I.tableFocus=g,Sn()}),b.appendChild(P),{stepper:b,input:N,decrement:w,increment:P}},p=d("rows"),h=d("columns"),m=document.createElement("button");m.type="button",m.className="weibei-slash-table-insert",m.textContent=ue("slashInsertTable"),m.addEventListener("pointerdown",g=>g.preventDefault()),m.addEventListener("click",()=>Xr("table")),f.append(p.stepper,h.stepper,m),document.body.appendChild(f),e={panel:f,rowsInput:p.input,rowsDecrement:p.decrement,rowsIncrement:p.increment,rowsStepper:p.stepper,columnsInput:h.input,columnsDecrement:h.decrement,columnsIncrement:h.increment,columnsStepper:h.stepper},As=f,Rp=e}document.activeElement!==e.rowsInput&&(e.rowsInput.value=String(I.tableRows)),document.activeElement!==e.columnsInput&&(e.columnsInput.value=String(I.tableColumns)),e.rowsDecrement.disabled=I.tableRows<=1,e.rowsIncrement.disabled=I.tableRows>=20,e.columnsDecrement.disabled=I.tableColumns<=1,e.columnsIncrement.disabled=I.tableColumns>=12,e.rowsStepper.classList.toggle("is-focused",I.tableFocus==="rows"),e.columnsStepper.classList.toggle("is-focused",I.tableFocus==="columns");let n=8,r=6,i=e.panel.offsetWidth,o=G.getBoundingClientRect(),s=o.right+r+i<=window.innerWidth-n,a=o.left-r-i>=n;!s&&!a&&o.width+r+i<=window.innerWidth-n*2&&(I.tableMenuBaseLeft||(I.tableMenuBaseLeft=G.style.left),G.style.left=`${n}px`,o=G.getBoundingClientRect());let l=o.right+r+i<=window.innerWidth-n;e.panel.dataset.side=l?"right":"left";let c=l?o.right+r:o.left-r-i;e.panel.style.left=`${Math.max(n,Math.min(window.innerWidth-i-n,c))}px`;let u=t.getBoundingClientRect();e.panel.style.top=`${Math.max(n,Math.min(window.innerHeight-e.panel.offsetHeight-n,u.top))}px`},Is=()=>{let t=I.view,e=t&&ro(t);if(!t||!e||I.dismissedContext===e.key){I.provider?.hide(),$p();return}I.activationContext!==`${e.blockFrom}:${nt}`&&Object.assign(I,{activationContext:`${e.blockFrom}:${nt}`,activeIndex:0,tableOpen:!1,tableFocus:"rows",tableRows:3,tableColumns:3,tableMenuBaseLeft:"",error:""}),I.context=e,I.commands=yD(e.query,e,t.state.schema),I.activeIndex=Math.min(I.activeIndex,Math.max(0,I.commands.length-1));let n=xD();n!==T0&&(T0=n,wD()),Hp(),Sn()},CD=(t,e)=>{let n=ro(t);if(G.dataset.show!=="true"||!n||e.isComposing||e.keyCode===229)return!1;if(e.key==="Escape")return I.dismissedContext=n.key,I.provider?.hide(),e.preventDefault(),!0;if(I.tableOpen){if(e.key==="ArrowLeft"||e.key==="ArrowRight"){let i=e.key==="ArrowLeft"?-1:1;return I.tableFocus==="rows"?I.tableRows=Math.min(20,Math.max(1,I.tableRows+i)):I.tableColumns=Math.min(12,Math.max(1,I.tableColumns+i)),Sn(),e.preventDefault(),!0}if(["Tab","ArrowUp","ArrowDown"].includes(e.key))return I.tableFocus=I.tableFocus==="rows"?"columns":"rows",Sn(),e.preventDefault(),!0;if(e.key==="Enter")return Xr("table"),e.preventDefault(),!0}if(e.key==="ArrowUp"||e.key==="ArrowDown")return I.commands.length&&(I.activeIndex=(I.activeIndex+(e.key==="ArrowUp"?-1:1)+I.commands.length)%I.commands.length,I.tableOpen=!1,Hp(),Sn(),e.preventDefault()),!0;let r=I.commands[I.activeIndex];return e.key==="ArrowRight"&&r?.id==="table"?(I.tableOpen=!0,Sn(),e.preventDefault(),!0):e.key==="Enter"&&r?(r.id==="table"?(I.tableOpen=!0,Sn()):Xr(r.id),e.preventDefault(),!0):e.key==="Tab"&&r?.id!=="table"?(Xr(r.id),e.preventDefault(),!0):!1};document.documentElement.dataset.weibeiCompactPreview=_l?"true":"false";window.weiBeiEditorCheckMode&&(document.documentElement.dataset.weibeiCheckMode="true");var v0=0,xp=0,A0=0,I0=0,a1=()=>[document.querySelector("#editor"),document.querySelector(".milkdown"),document.querySelector(".ProseMirror")].filter(Boolean),SD=t=>{let e=t.getBoundingClientRect?.();return Math.max(0,t.scrollHeight||0,t.offsetHeight||0,t.clientHeight||0,e?.height||0)},Op=()=>{let t=a1(),e=Math.ceil(Math.max(1,...t.map(SD))),n=Math.ceil(Math.max(1,...t.map(r=>r.getBoundingClientRect?.().width||r.clientWidth||0)));window.WeiBeiCompactPreviewHeight=e,window.WeiBeiCompactPreviewMeasuredAt=Date.now(),!(Math.abs(e-A0)<1&&Math.abs(n-I0)<1)&&(A0=e,I0=n,Ie("contentHeightChanged",{height:e}))},MD=()=>{!_l||!K0||(Op(),window.cancelAnimationFrame(v0),v0=window.requestAnimationFrame(Op))},lt=()=>{if(!_l||xp)return;let t=xe!==null?100:40;xp=window.setTimeout(()=>{xp=0,MD()},t)},ED=()=>{if(_l){if(window.ResizeObserver){let t=new ResizeObserver(lt);a1().forEach(e=>t.observe(e))}lt(),document.fonts?.ready?.then(lt).catch(()=>{})}},TD=()=>{let t=window.getSelection();if(!t||t.rangeCount===0)return null;let e=t.getRangeAt(0).getBoundingClientRect();return!e||e.width+e.height===0?null:{x:e.left+e.width/2,y:e.bottom,width:e.width,height:e.height}},Ds=t=>t0(oo,t),vD=t=>String(t||"").split(/\r?\n/).slice(1,-1).map(e=>{let n=e.match(/^\s*([^:#][^:]*):\s*(.*)$/);return n?{key:n[1].trim(),value:n[2].trim()||" "}:null}).filter(Boolean),Ls=()=>{let t=document.querySelector("#frontmatter-panel");if(!t)return;let e=vD(oo);t.dataset.visible=e.length>0?"true":"false",t.innerHTML=e.length>0?`<div class="frontmatter-title">${lD()}</div>${e.map(n=>`<div class="frontmatter-row"><span class="frontmatter-key">${Dp(n.key)}</span><span>${Dp(n.value)}</span></div>`).join("")}`:""},Dp=t=>String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),N0=t=>`${iD}://image?src=${encodeURIComponent(t)}`,AD=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|tiff?)(?:$|[?#])/i,l1=t=>{let n=(t||"").trim().match(/^(\d{1,4})(?:x(\d{1,4}))?$/i);return n?{width:Math.max(1,Number(n[1])),height:n[2]?Math.max(1,Number(n[2])):null}:null},ID=(t,e)=>{t.style.width=e?`${e.width}px`:"",t.style.maxWidth=e?"100%":"",t.style.height=e?.height?`${e.height}px`:""},Fl=t=>{let e=String(t||"").split("|"),n=e.length>1?l1(e.at(-1)):null;return{alt:n?e.slice(0,-1).join("|").trim():String(t||""),size:n}},ND=(t,e,n)=>{let r=e,i=n;for(;r<i&&/\s/.test(t[r]);)r+=1;for(;i>r&&/\s/.test(t[i-1]);)i-=1;return{start:r,end:i}},c1=t=>{let e=String(t||""),n=[],r=0,i="";for(let o=0;o<e.length;o+=1){let s=e[o],a=e[o+1];if(s==="\\"&&a==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+2,i="",o+=1;continue}if(s==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+1,i="";continue}i+=s}return n.push({raw:e.slice(r),value:i,start:r,end:e.length}),n},u1=t=>{let e=String(t||"").trim(),n=c1(e),i=(n.shift()||{value:"",start:0,end:0}).value.trim(),o=n,s=o.map(u=>u.value).join("|").trim(),a=o.length>0?ND(e,o[0].start,o.at(-1).end):null,l=i.indexOf("#"),c=l>=0?i.slice(0,l).trim():i;return{source:e,target:i,noteTitle:c,display:s||i,alias:s,aliasRange:a}},RD=t=>{let e=c1(String(t||"").trim()),n=(e.shift()?.value||"").trim(),r=e.at(-1),i=r?l1(r.value):null,o=i?e.slice(0,-1):e;return{target:n,size:i,label:o.map(s=>s.value).join("|").trim()}},f1=()=>{let t=eo==="inkstone"?{background:"#151515",accent:"#a6362b",text:"#d7cbb0"}:{background:"#efe6d8",accent:"#9f3b2f",text:"#6b5148"},e=`<svg xmlns="http://www.w3.org/2000/svg" width="156" height="34" viewBox="0 0 156 34"> +`).trim(),Q0=t=>t==="glassLight"||t==="glassMist"?"xuan":t==="glassDark"||t==="glassSlate"?"stele":t==="xuan"||t==="inkstone"||t==="stele"||t==="paper"?t:"paper",dD=t=>["glassLight","glassDark","glassMist","glassSlate"].includes(t)?t:"",eo=Q0(window.weiBeiTheme),pD=()=>{switch(eo){case"inkstone":return{background:"#151515",primaryColor:"#1c1c1c",primaryTextColor:"#d7cbb0",primaryBorderColor:"#3a3328",lineColor:"#8b5e3c",secondaryColor:"#222222",tertiaryColor:"#171717",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"stele":return{background:"#1e2228",primaryColor:"#252a32",primaryTextColor:"#d2d6dc",primaryBorderColor:"#3a414c",lineColor:"#8a7a5c",secondaryColor:"#2a3038",tertiaryColor:"#1a1e24",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"xuan":return{background:"#f7f4ef",primaryColor:"#fcfbf8",primaryTextColor:"#25231f",primaryBorderColor:"#d8d2c6",lineColor:"#6e634f",secondaryColor:"#ebe6dc",tertiaryColor:"#f7f4ef",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};default:return{background:"#fbf5e8",primaryColor:"#f6eddc",primaryTextColor:"#2e261f",primaryBorderColor:"#cbb79b",lineColor:"#7a6250",secondaryColor:"#efe4d2",tertiaryColor:"#f8f0e1",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'}}},hD=t=>{t.initialize({startOnLoad:!1,securityLevel:"strict",theme:"base",themeVariables:pD()})},Z0=t=>{eo=Q0(t);let e=dD(t);document.documentElement.dataset.weibeiTheme=eo,document.body&&(document.body.dataset.weibeiTheme=eo),e?(document.documentElement.dataset.weibeiGlass=e,document.body&&(document.body.dataset.weibeiGlass=e)):(delete document.documentElement.dataset.weibeiGlass,document.body&&delete document.body.dataset.weibeiGlass),Zi+=1};Z0(window.weiBeiTheme);var no=t=>{if(window.WeiBeiEditorBootFailed){window.WeiBeiEditorBootFailed(t);return}let e=document.querySelector("#editor");e&&(e.innerHTML=`<pre style="white-space:pre-wrap;color:#9f3427;padding:24px;font:13px/1.5 SFMono-Regular,Menlo,monospace;">${ue("bootFailed")} +${String(t?.stack||t)}</pre>`)};window.addEventListener("error",t=>no(t.error||t.message));window.addEventListener("unhandledrejection",t=>no(t.reason));var ye=(t,e={})=>{let n=K0?.[t];if(!n)return;let r=f0({documentID:nt,documentGeneration:Ve,revision:Mn.revision},e);typeof r.markdown=="string"&&(vp+=1),It(at,"bridgeMessages"),at&&It(at,"bridgeBytes",new TextEncoder().encode(JSON.stringify(r)).byteLength),n.postMessage(r)},G=document.createElement("div"),Gr=document.createElement("div"),st=document.createElement("button"),Ee=document.createElement("div");G.className="weibei-slash-menu",G.dataset.show="false",G.dataset.state="closed",G.setAttribute("role","listbox"),G.setAttribute("aria-label","Slash commands"),Gr.className="weibei-visually-hidden",Gr.setAttribute("role","status"),Gr.setAttribute("aria-live","polite"),st.type="button",st.className="weibei-line-plus",st.textContent="\uFF0B",st.setAttribute("aria-label","\u63D2\u5165\u5185\u5BB9"),st.hidden=!0,Ee.className="weibei-table-toolbar",Ee.dataset.state="closed",Ee.setAttribute("aria-hidden","true"),Ee.setAttribute("role","toolbar");for(let[t,e]of[["addRow","tableAddRow"],["deleteRow","tableDeleteRow"],["addColumn","tableAddColumn"],["deleteColumn","tableDeleteColumn"],["header","tableHeader"]]){let n=document.createElement("button");n.type="button",n.dataset.action=t,n.dataset.label=e,Ee.append(n)}var As=null,mD=[{id:"structure",label:"slashStructure"},{id:"lists",label:"slashLists"},{id:"content",label:"slashContent"},{id:"rich",label:"slashRichContent"},{id:"fonts",label:"slashFonts"}],gD=[{id:"heading1",group:"structure",label:"slashHeading1",aliases:["h1","heading_1","yjbt","yijibiaoti","\u4E00\u7EA7","\u6807\u98981"]},{id:"heading2",group:"structure",label:"slashHeading2",aliases:["h2","heading_2","ejbt","erjibiaoti","\u4E8C\u7EA7","\u6807\u98982"]},{id:"heading3",group:"structure",label:"slashHeading3",aliases:["h3","heading_3","sjbt","sanjibiaoti","\u4E09\u7EA7","\u6807\u98983"]},{id:"heading4",group:"structure",label:"slashHeading4",aliases:["h4","heading_4","sijbt","sijibiaoti","\u56DB\u7EA7","\u6807\u98984"]},{id:"heading5",group:"structure",label:"slashHeading5",aliases:["h5","heading_5","wjbt","wujibiaoti","\u4E94\u7EA7","\u6807\u98985"]},{id:"heading6",group:"structure",label:"slashHeading6",aliases:["h6","heading_6","ljbt","liujibiaoti","\u516D\u7EA7","\u6807\u98986"]},{id:"bulletList",group:"lists",label:"slashBulletList",aliases:["bullet_list","bullet","ul","wxlb","wuxuliebiao","\u65E0\u5E8F","\u9879\u76EE\u7B26\u53F7"]},{id:"orderedList",group:"lists",label:"slashOrderedList",aliases:["ordered_list","ol","yxlb","youxuliebiao","\u6709\u5E8F","\u7F16\u53F7"]},{id:"taskList",group:"lists",label:"slashTaskList",aliases:["task_list","todo","task","checklist","dblb","daibanliebiao","\u5F85\u529E","\u4EFB\u52A1"]},{id:"quote",group:"lists",label:"slashQuote",aliases:["quote","blockquote","yy","yinyong","\u5F15\u7528"]},{id:"callout",group:"content",label:"slashCallout",aliases:["callout","note","tsk","tishikuai","\u63D0\u793A","\u672D\u8BB0"]},{id:"code",group:"content",label:"slashCode",aliases:["code","code_block","dmk","daimakuai","\u4EE3\u7801"]},{id:"divider",group:"content",label:"slashDivider",aliases:["divider","horizontal_rule","hr","fgx","fengexian","\u5206\u9694","\u6A2A\u7EBF"]},{id:"link",group:"content",label:"slashLink",aliases:["link","url","lj","lianjie","\u94FE\u63A5","\u7F51\u5740"]},{id:"wikiLink",group:"content",label:"slashWikiLink",aliases:["wiki","note_link","bjl","bijilianjie","\u7B14\u8BB0","\u53CC\u94FE"]},{id:"footnote",group:"content",label:"slashFootnote",aliases:["footnote","note_ref","jz","jiaozhu","\u811A\u6CE8","\u6CE8\u91CA"]},{id:"table",group:"rich",label:"slashTable",aliases:["table","grid","bg","biaoge","\u8868\u683C"]},{id:"image",group:"rich",label:"slashImage",aliases:["image","photo","picture","tp","tupian","\u56FE\u7247","\u7167\u7247"]},{id:"mermaid",group:"rich",label:"slashMermaid",aliases:["mermaid","diagram","flowchart","lct","liuchengtu","\u56FE\u8868","\u6D41\u7A0B\u56FE"]},{id:"inlineMath",group:"rich",label:"slashInlineMath",aliases:["math","formula","inline_math","hngs","hangneigongshi","\u516C\u5F0F","\u884C\u5185"]},{id:"blockMath",group:"rich",label:"slashBlockMath",aliases:["display_math","equation","block_math","kjgs","kuaijigongshi","\u65B9\u7A0B","\u5757\u7EA7"]},{id:"fontSystem",group:"fonts",label:"slashFontSystem",aliases:["font","system","sf pro","pingfang sc","ziti","\u5B57\u4F53","\u82F9\u65B9"]},{id:"fontSerif",group:"fonts",label:"slashFontSerif",aliases:["font","serif","songti sc","ziti","\u5B57\u4F53","\u5B8B\u4F53"]},{id:"fontLiterary",group:"fonts",label:"slashFontLiterary",aliases:["font","weibeistele","wei bei stele","ziti","\u5B57\u4F53","\u9B4F\u7891"]}],e1=new Set(["system","serif","literary"]),Np={fontSystem:"system",fontSerif:"serif",fontLiterary:"literary"},I={provider:null,view:null,context:null,commands:[],activeIndex:0,dismissedContext:"",activationContext:"",tableOpen:!1,tableFocus:"rows",tableRows:3,tableColumns:3,tableMenuBaseLeft:"",error:""},t1=new Set(["list_item","task_list_item","table","table_row","table_header_row","table_cell","table_header","code_block","math_block"]),Pe={state:"closed",generation:0,timer:0,frame:0},Rp=()=>document.documentElement.dataset.weibeiReduceMotion==="true",n1=t=>{document.documentElement.dataset.weibeiReduceMotion=t===!0||t==="true"?"true":"false"},r1=t=>{let e=Number(t),n=Number.isFinite(e)&&e>0?e:1;document.documentElement.style.setProperty("--weibei-text-scale",String(n))},ro=t=>{if(!re||t.composing)return null;let{selection:e}=t.state;if(!(e instanceof B)||!e.empty)return null;let{$from:n}=e;if(n.parent.type.name!=="paragraph")return null;for(let u=n.depth;u>0;u-=1)if(t1.has(n.node(u).type.name))return null;let r=n.parent.textBetween(0,n.parentOffset,"\uFFFC","\uFFFC"),i=r.lastIndexOf("/");if(i<0)return null;let o=r.slice(i+1);if(/[\s/]/u.test(o))return null;let s=/^[\u200B\uFEFF]*$/u.test(r.slice(0,i))?0:i,a=n.depth,l=n.before(a),c=n.start(a)+s;return{query:o,parent:n.parent,triggerFrom:c,triggerTo:n.pos,triggerStartOffset:s,triggerEndOffset:n.parentOffset,blockFrom:l,blockTo:n.after(a),index:n.index(a-1),container:n.node(a-1),key:`${c}:${o}`}},i1=t=>{if(!re||t.composing)return null;let{selection:e}=t.state;if(!(e instanceof B)||!e.empty||e.$from.parent.type.name!=="paragraph"||e.$from.parent.content.size!==0)return null;for(let n=e.$from.depth;n>0;n-=1)if(t1.has(e.$from.node(n).type.name))return null;return e.$from},T0=t=>{let e=i1(t);if(st.hidden=!e,!e)return;let n=t.coordsAtPos(e.pos);st.style.left=`${Math.max(6,n.left-30)}px`,st.style.top=`${Math.max(6,n.top-2)}px`},$p=(t,e,n={})=>{let r=e.nodes.paragraph;if(!r)return null;if(t.startsWith("heading")){let i=e.nodes.heading;return i?{content:M.from(i.create({level:Number(t.at(-1))})),selectionOffset:1}:null}if(["bulletList","orderedList","taskList"].includes(t)){let i=t==="orderedList"?e.nodes.ordered_list:e.nodes.bullet_list,o=e.nodes.list_item?.createAndFill(t==="taskList"?{checked:!1}:null,r.create()),s=o&&i?.createAndFill(null,o);return s?{content:M.from(s),selectionOffset:3}:null}if(t==="callout"){let o=e.nodes.callout?.create({calloutType:"note",title:"",fold:""},r.create());return o?{content:M.from(o),selectionOffset:2}:null}if(t==="quote"){let i=e.nodes.blockquote||e.nodes.block_quote;if(!i)return null;let o=i.create(null,r.create());return{content:M.from(o),selectionOffset:2}}if(t==="code"||t==="mermaid"){let i=e.nodes.code_block;if(!i)return null;let o=t==="mermaid"?`graph TD + A --> B`:"";return{content:M.from(i.create({language:t==="mermaid"?"mermaid":""},o?e.text(o):null)),selectionOffset:o.length+1}}if(t==="inlineMath"){let o=e.nodes.math_inline?.create(null,e.text("x"));return o?{content:M.from(r.create(null,o)),selectionOffset:1}:null}if(t==="link"){let i=e.marks.link,o=ue("linkPlaceholder"),s=i?r.create(null,e.text(o,[i.create({href:""})])):null;return s?{content:M.from(s),selectionFromOffset:1,selectionToOffset:o.length+1}:null}if(t==="wikiLink"){let i=e.nodes.wiki_link,o=ue("wikiLinkPlaceholder"),s=i?.create({raw:o,target:o,label:""});return s?{content:M.from(r.create(null,s)),selectionOffset:1,activateEvent:"weibei-edit-structured"}:null}if(t==="footnote"){let o=e.nodes.inline_footnote?.create({value:ue("footnotePlaceholder")});return o?{content:M.from(r.create(null,o)),selectionOffset:1,activateEvent:"weibei-edit-structured"}:null}if(t==="blockMath"){let o=e.nodes.math_block?.create({value:"x"});return o?{content:M.from(o),selectionOffset:0}:null}if(t==="divider"){let o=(e.nodes.hr||e.nodes.horizontal_rule)?.create();return o?{content:M.from([o,r.create()]),selectionOffset:o.nodeSize+1}:null}if(t==="table"){let{table:i,table_header_row:o,table_row:s,table_header:a,table_cell:l}=e.nodes,c=Math.min(20,Math.max(1,Number(n.rows)||3)),u=Math.min(12,Math.max(1,Number(n.columns)||3));if(!i||!o||!s||!a||!l)return null;let f=Array.from({length:u},()=>a.createAndFill()),d=Array.from({length:c-1},()=>s.create(null,Array.from({length:u},()=>l.createAndFill())));return f.some(p=>!p)||d.some(p=>!p)?null:{content:M.from(i.create(null,[o.create(null,f),...d])),selectionOffset:4}}if(t==="image"){let i=e.nodes.image;return i&&n.src?{content:M.from(r.create(null,i.create({src:n.src,alt:n.alt||"image"}))),selectionOffset:2}:null}return null},o1=(t,e)=>{let n=e?.content?.firstChild;if(!t||!n)return null;if(e.content.childCount===1&&n.type===t.parent.type){let a=t.parent.content.cut(0,t.triggerStartOffset).append(n.content).append(t.parent.content.cut(t.triggerEndOffset));return{content:M.from(t.parent.type.create(t.parent.attrs,a,t.parent.marks)),selectionBase:t.triggerFrom-1}}let r=[],i=t.parent.content.cut(0,t.triggerStartOffset),o=t.parent.content.cut(t.triggerEndOffset);i.size&&r.push(t.parent.type.create(t.parent.attrs,i,t.parent.marks));let s=t.blockFrom+r.reduce((a,l)=>a+l.nodeSize,0);return e.content.forEach(a=>r.push(a)),o.size&&r.push(t.parent.type.create(t.parent.attrs,o,t.parent.marks)),{content:M.from(r),selectionBase:s}},yD=(t,e,n)=>{if(!e)return!1;if(Np[t.id])return!!n.marks.writing_font;if(t.id==="image")return!!n.nodes.image;let r=$p(t.id,n,{rows:3,columns:3}),i=o1(e,r);return!!(i&&e.container.canReplace(e.index,e.index+1,i.content))},kD=(t,e,n)=>{let r=String(t||"").toLocaleLowerCase();return gD.filter(i=>yD(i,e,n)&&(!r||[Bl["zh-Hans"][i.label],Bl.en[i.label],...i.aliases].some(o=>String(o).toLocaleLowerCase().includes(r))))},s1=(t,e,n)=>{if(!e||!n)return!1;let r=t.state.doc.nodeAt(e.blockFrom),i=o1(e,n);if(!r?.eq(e.parent)||!i||!e.container.canReplace(e.index,e.index+1,i.content))return!1;let o=us(t.state.tr.replaceWith(e.blockFrom,e.blockTo,i.content)),s=n.activateEvent?H.create(o.doc,i.selectionBase+n.selectionOffset):Number.isInteger(n.selectionFromOffset)&&Number.isInteger(n.selectionToOffset)?B.create(o.doc,i.selectionBase+n.selectionFromOffset,i.selectionBase+n.selectionToOffset):$.findFrom(o.doc.resolve(Math.min(i.selectionBase+n.selectionOffset,o.doc.content.size)),1,!0);return s&&o.setSelection(s),t.dispatch(o.scrollIntoView()),I.dismissedContext="",I.provider?.hide(),t.focus(),n.activateEvent&&s&&window.requestAnimationFrame(()=>{t.nodeDOM(s.from)?.dispatchEvent(new CustomEvent(n.activateEvent))}),window.requestAnimationFrame(to),!0},bD=(t,e)=>{let n=`image-picker-${Date.now()}-${_p+=1}`;_t.set(n,{mode:"insert",view:t,context:e,documentID:nt,documentGeneration:Ve}),I.dismissedContext=e.key,I.provider?.hide(),ye("imagePickerRequested",{id:n})},xD=(t,e,n)=>{let r=t.state.schema.marks.writing_font;if(!r||!e1.has(n))return!1;let i=t.state.storedMarks||t.state.selection.$from.marks(),o=us(t.state.tr.delete(e.triggerFrom,e.triggerTo));return o.setSelection(B.create(o.doc,e.triggerFrom)),o.setStoredMarks([...i.filter(s=>s.type!==r),r.create({font:n})]),t.dispatch(o.scrollIntoView()),I.dismissedContext="",I.provider?.hide(),t.focus(),window.requestAnimationFrame(to),!0},Xr=t=>{let e=I.view,n=e&&ro(e);return!e||!n?!1:t==="image"?(bD(e,n),!0):Np[t]?xD(e,n,Np[t]):s1(e,n,$p(t,e.state.schema,{rows:I.tableRows,columns:I.tableColumns}))},Hp=()=>{let t=I.view?.dom,e=I.commands[I.activeIndex];if(!t||G.dataset.show!=="true"||!e){t?.removeAttribute("aria-controls"),t?.removeAttribute("aria-expanded"),t?.removeAttribute("aria-activedescendant");return}G.id="weibei-slash-menu",t.setAttribute("aria-controls",G.id),t.setAttribute("aria-expanded","true"),t.setAttribute("aria-activedescendant",`weibei-slash-command-${e.id}`),G.setAttribute("aria-activedescendant",`weibei-slash-command-${e.id}`),Gr.textContent=`${ue(e.label)}\uFF0C${I.activeIndex+1}/${I.commands.length}`},wD=()=>`${Jr}::${I.error?"!":""}::${I.commands.length}::${I.commands.map(t=>t.id).join(",")}`,v0=null,CD=()=>{if(G.replaceChildren(),I.error){let t=document.createElement("div");t.className="weibei-slash-error",t.textContent=I.error,G.appendChild(t)}if(!I.commands.length){let t=document.createElement("div");t.className="weibei-slash-empty",t.textContent=ue("slashNoResults"),G.appendChild(t);return}for(let t of mD){let e=I.commands.filter(i=>i.group===t.id);if(!e.length)continue;let n=document.createElement("section");n.className="weibei-slash-section";let r=document.createElement("div");r.className="weibei-slash-group",r.textContent=ue(t.label),n.appendChild(r);for(let i of e){let o=I.commands.indexOf(i),s=document.createElement("div");s.id=`weibei-slash-command-${i.id}`,s.className=`weibei-slash-command${o===I.activeIndex?" is-active":""}`,s.setAttribute("role","option"),s.setAttribute("aria-selected",String(o===I.activeIndex)),s.setAttribute("aria-posinset",String(o+1)),s.setAttribute("aria-setsize",String(I.commands.length));let a=document.createElement("button");a.type="button",a.tabIndex=-1,a.className="weibei-slash-command-button",a.textContent=ue(i.label),a.addEventListener("pointerdown",l=>l.preventDefault()),a.addEventListener("pointermove",l=>{!Number(l.movementX)&&!Number(l.movementY)||(I.activeIndex=o,I.tableOpen=i.id==="table",Wp(),Sn())}),a.addEventListener("click",()=>{i.id!=="table"&&Xr(i.id)}),s.appendChild(a),n.appendChild(s)}G.appendChild(n)}},Wp=()=>{G.querySelectorAll(".weibei-slash-command").forEach((t,e)=>{t.classList.toggle("is-active",e===I.activeIndex),t.setAttribute("aria-selected",String(e===I.activeIndex))}),G.querySelector(".weibei-slash-command.is-active")?.scrollIntoView({block:"nearest"}),Hp()},Op=null,a1=()=>{As?.remove(),As=null,Op=null,I.tableMenuBaseLeft&&(G.style.left=I.tableMenuBaseLeft,I.tableMenuBaseLeft="")},Sn=()=>{let t=G.querySelector("#weibei-slash-command-table .weibei-slash-command-button");if(!I.tableOpen||G.dataset.show!=="true"||!t){a1();return}let e=Op;if(!e){let f=document.createElement("div");f.className="weibei-slash-table-panel",f.setAttribute("role","group");let d=g=>{let y=g==="rows",b=document.createElement("div");b.className=`weibei-slash-stepper${I.tableFocus===g?" is-focused":""}`;let C=document.createElement("span");C.className="weibei-slash-stepper-label",C.textContent=ue(y?"slashRows":"slashColumns"),b.appendChild(C);let v=()=>y?I.tableRows:I.tableColumns,A=O=>{y?I.tableRows=O:I.tableColumns=O},w=document.createElement("button");w.type="button",w.textContent="\u2212",w.setAttribute("aria-label",`${C.textContent} \u2212`),w.addEventListener("pointerdown",O=>O.preventDefault()),w.addEventListener("click",()=>{A(Math.max(1,v()-1)),I.tableFocus=g,Sn()}),b.appendChild(w);let N=document.createElement("input");N.className="weibei-slash-stepper-input",N.type="number",N.inputMode="numeric",N.min="1",N.max=String(y?20:12),N.step="1",N.setAttribute("aria-label",C.textContent),N.addEventListener("focus",()=>{I.tableFocus=g,f.querySelectorAll(".weibei-slash-stepper.is-focused").forEach(O=>O.classList.remove("is-focused")),b.classList.add("is-focused")}),N.addEventListener("input",()=>{let O=Number.parseInt(N.value,10);Number.isFinite(O)&&A(Math.min(y?20:12,Math.max(1,O)))}),N.addEventListener("change",()=>{let O=Math.min(y?20:12,Math.max(1,Number.parseInt(N.value,10)||1));N.value=String(O),A(O)}),N.addEventListener("keydown",O=>{if(O.stopPropagation(),O.key==="Enter"){let S=Math.min(y?20:12,Math.max(1,Number.parseInt(N.value,10)||1));A(S),Xr("table"),O.preventDefault()}}),b.appendChild(N);let P=document.createElement("button");return P.type="button",P.textContent="+",P.setAttribute("aria-label",`${C.textContent} +`),P.addEventListener("pointerdown",O=>O.preventDefault()),P.addEventListener("click",()=>{A(Math.min(y?20:12,v()+1)),I.tableFocus=g,Sn()}),b.appendChild(P),{stepper:b,input:N,decrement:w,increment:P}},p=d("rows"),h=d("columns"),m=document.createElement("button");m.type="button",m.className="weibei-slash-table-insert",m.textContent=ue("slashInsertTable"),m.addEventListener("pointerdown",g=>g.preventDefault()),m.addEventListener("click",()=>Xr("table")),f.append(p.stepper,h.stepper,m),document.body.appendChild(f),e={panel:f,rowsInput:p.input,rowsDecrement:p.decrement,rowsIncrement:p.increment,rowsStepper:p.stepper,columnsInput:h.input,columnsDecrement:h.decrement,columnsIncrement:h.increment,columnsStepper:h.stepper},As=f,Op=e}document.activeElement!==e.rowsInput&&(e.rowsInput.value=String(I.tableRows)),document.activeElement!==e.columnsInput&&(e.columnsInput.value=String(I.tableColumns)),e.rowsDecrement.disabled=I.tableRows<=1,e.rowsIncrement.disabled=I.tableRows>=20,e.columnsDecrement.disabled=I.tableColumns<=1,e.columnsIncrement.disabled=I.tableColumns>=12,e.rowsStepper.classList.toggle("is-focused",I.tableFocus==="rows"),e.columnsStepper.classList.toggle("is-focused",I.tableFocus==="columns");let n=8,r=6,i=e.panel.offsetWidth,o=G.getBoundingClientRect(),s=o.right+r+i<=window.innerWidth-n,a=o.left-r-i>=n;!s&&!a&&o.width+r+i<=window.innerWidth-n*2&&(I.tableMenuBaseLeft||(I.tableMenuBaseLeft=G.style.left),G.style.left=`${n}px`,o=G.getBoundingClientRect());let l=o.right+r+i<=window.innerWidth-n;e.panel.dataset.side=l?"right":"left";let c=l?o.right+r:o.left-r-i;e.panel.style.left=`${Math.max(n,Math.min(window.innerWidth-i-n,c))}px`;let u=t.getBoundingClientRect();e.panel.style.top=`${Math.max(n,Math.min(window.innerHeight-e.panel.offsetHeight-n,u.top))}px`},Is=()=>{let t=I.view,e=t&&ro(t);if(!t||!e||I.dismissedContext===e.key){I.provider?.hide(),Hp();return}I.activationContext!==`${e.blockFrom}:${nt}`&&Object.assign(I,{activationContext:`${e.blockFrom}:${nt}`,activeIndex:0,tableOpen:!1,tableFocus:"rows",tableRows:3,tableColumns:3,tableMenuBaseLeft:"",error:""}),I.context=e,I.commands=kD(e.query,e,t.state.schema),I.activeIndex=Math.min(I.activeIndex,Math.max(0,I.commands.length-1));let n=wD();n!==v0&&(v0=n,CD()),Wp(),Sn()},SD=(t,e)=>{let n=ro(t);if(G.dataset.show!=="true"||!n||e.isComposing||e.keyCode===229)return!1;if(e.key==="Escape")return I.dismissedContext=n.key,I.provider?.hide(),e.preventDefault(),!0;if(I.tableOpen){if(e.key==="ArrowLeft"||e.key==="ArrowRight"){let i=e.key==="ArrowLeft"?-1:1;return I.tableFocus==="rows"?I.tableRows=Math.min(20,Math.max(1,I.tableRows+i)):I.tableColumns=Math.min(12,Math.max(1,I.tableColumns+i)),Sn(),e.preventDefault(),!0}if(["Tab","ArrowUp","ArrowDown"].includes(e.key))return I.tableFocus=I.tableFocus==="rows"?"columns":"rows",Sn(),e.preventDefault(),!0;if(e.key==="Enter")return Xr("table"),e.preventDefault(),!0}if(e.key==="ArrowUp"||e.key==="ArrowDown")return I.commands.length&&(I.activeIndex=(I.activeIndex+(e.key==="ArrowUp"?-1:1)+I.commands.length)%I.commands.length,I.tableOpen=!1,Wp(),Sn(),e.preventDefault()),!0;let r=I.commands[I.activeIndex];return e.key==="ArrowRight"&&r?.id==="table"?(I.tableOpen=!0,Sn(),e.preventDefault(),!0):e.key==="Enter"&&r?(r.id==="table"?(I.tableOpen=!0,Sn()):Xr(r.id),e.preventDefault(),!0):e.key==="Tab"&&r?.id!=="table"?(Xr(r.id),e.preventDefault(),!0):!1};document.documentElement.dataset.weibeiCompactPreview=_l?"true":"false";window.weiBeiEditorCheckMode&&(document.documentElement.dataset.weibeiCheckMode="true");var A0=0,xp=0,I0=0,N0=0,l1=()=>[document.querySelector("#editor"),document.querySelector(".milkdown"),document.querySelector(".ProseMirror")].filter(Boolean),MD=t=>{let e=t.getBoundingClientRect?.();return Math.max(0,t.scrollHeight||0,t.offsetHeight||0,t.clientHeight||0,e?.height||0)},Dp=()=>{let t=l1(),e=Math.ceil(Math.max(1,...t.map(MD))),n=Math.ceil(Math.max(1,...t.map(r=>r.getBoundingClientRect?.().width||r.clientWidth||0)));window.WeiBeiCompactPreviewHeight=e,window.WeiBeiCompactPreviewMeasuredAt=Date.now(),!(Math.abs(e-I0)<1&&Math.abs(n-N0)<1)&&(I0=e,N0=n,ye("contentHeightChanged",{height:e}))},ED=()=>{!_l||!U0||(Dp(),window.cancelAnimationFrame(A0),A0=window.requestAnimationFrame(Dp))},lt=()=>{if(!_l||xp)return;let t=we!==null?100:40;xp=window.setTimeout(()=>{xp=0,ED()},t)},TD=()=>{if(_l){if(window.ResizeObserver){let t=new ResizeObserver(lt);l1().forEach(e=>t.observe(e))}lt(),document.fonts?.ready?.then(lt).catch(()=>{})}},vD=()=>{let t=window.getSelection();if(!t||t.rangeCount===0)return null;let e=t.getRangeAt(0).getBoundingClientRect();return!e||e.width+e.height===0?null:{x:e.left+e.width/2,y:e.bottom,width:e.width,height:e.height}},Ds=t=>n0(oo,t),AD=t=>String(t||"").split(/\r?\n/).slice(1,-1).map(e=>{let n=e.match(/^\s*([^:#][^:]*):\s*(.*)$/);return n?{key:n[1].trim(),value:n[2].trim()||" "}:null}).filter(Boolean),Ls=()=>{let t=document.querySelector("#frontmatter-panel");if(!t)return;let e=AD(oo);t.dataset.visible=e.length>0?"true":"false",t.innerHTML=e.length>0?`<div class="frontmatter-title">${cD()}</div>${e.map(n=>`<div class="frontmatter-row"><span class="frontmatter-key">${Lp(n.key)}</span><span>${Lp(n.value)}</span></div>`).join("")}`:""},Lp=t=>String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),R0=t=>`${oD}://image?src=${encodeURIComponent(t)}`,ID=/\.(?:png|jpe?g|gif|webp|svg|avif|bmp|tiff?)(?:$|[?#])/i,c1=t=>{let n=(t||"").trim().match(/^(\d{1,4})(?:x(\d{1,4}))?$/i);return n?{width:Math.max(1,Number(n[1])),height:n[2]?Math.max(1,Number(n[2])):null}:null},ND=(t,e)=>{t.style.width=e?`${e.width}px`:"",t.style.maxWidth=e?"100%":"",t.style.height=e?.height?`${e.height}px`:""},Fl=t=>{let e=String(t||"").split("|"),n=e.length>1?c1(e.at(-1)):null;return{alt:n?e.slice(0,-1).join("|").trim():String(t||""),size:n}},RD=(t,e,n)=>{let r=e,i=n;for(;r<i&&/\s/.test(t[r]);)r+=1;for(;i>r&&/\s/.test(t[i-1]);)i-=1;return{start:r,end:i}},u1=t=>{let e=String(t||""),n=[],r=0,i="";for(let o=0;o<e.length;o+=1){let s=e[o],a=e[o+1];if(s==="\\"&&a==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+2,i="",o+=1;continue}if(s==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+1,i="";continue}i+=s}return n.push({raw:e.slice(r),value:i,start:r,end:e.length}),n},f1=t=>{let e=String(t||"").trim(),n=u1(e),i=(n.shift()||{value:"",start:0,end:0}).value.trim(),o=n,s=o.map(u=>u.value).join("|").trim(),a=o.length>0?RD(e,o[0].start,o.at(-1).end):null,l=i.indexOf("#"),c=l>=0?i.slice(0,l).trim():i;return{source:e,target:i,noteTitle:c,display:s||i,alias:s,aliasRange:a}},OD=t=>{let e=u1(String(t||"").trim()),n=(e.shift()?.value||"").trim(),r=e.at(-1),i=r?c1(r.value):null,o=i?e.slice(0,-1):e;return{target:n,size:i,label:o.map(s=>s.value).join("|").trim()}},d1=()=>{let t=eo==="inkstone"?{background:"#151515",accent:"#a6362b",text:"#d7cbb0"}:{background:"#efe6d8",accent:"#9f3b2f",text:"#6b5148"},e=`<svg xmlns="http://www.w3.org/2000/svg" width="156" height="34" viewBox="0 0 156 34"> <rect width="156" height="34" rx="3" fill="${t.background}"/> <path d="M18 22l5-6 4 4 3-3 6 5" fill="none" stroke="${t.accent}" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/> <rect x="17" y="11" width="20" height="14" rx="2" fill="none" stroke="${t.accent}" stroke-width="1.2"/> - <text x="48" y="22" fill="${t.text}" font-family="-apple-system, BlinkMacSystemFont, 'Songti SC', serif" font-size="13">${Dp(ue("imageMissing"))}</text> -</svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`},d1=t=>{if(!t||/^(?:data:|blob:|weibeiimage:)/i.test(t))return t;if(/^https:/i.test(t))return N0(t);if(/^http:/i.test(t))return"";try{let e=new URL(t,U0||window.location.href).href;return/^(?:file:|https:)/i.test(e)?N0(e):/^(?:data:|blob:|weibeiimage:)/i.test(e)?e:""}catch{return""}},Wp=()=>{document.body.dataset.editable=re?"true":"false",document.querySelectorAll(".weibei-code-language-input").forEach(t=>{t instanceof HTMLInputElement&&(t.readOnly=!re,t.tabIndex=re?0:-1,t.setAttribute("aria-readonly",t.readOnly?"true":"false"),t.setAttribute("aria-label",ue("codeLanguage")),t.placeholder=ue("codeLanguagePlaceholder"))})},Lp=new Set,Ns=new Set;var OD=(t,e,n)=>{let r=t,i=document.createElement("span"),o=document.createElement("img"),s=document.createElement("span"),a=document.createElement("button"),l=document.createElement("button"),c=document.createElement("select");i.className="weibei-image-node",i.contentEditable="false",o.className="weibei-image",s.className="weibei-image-controls",a.type=l.type="button",a.textContent="\u66F4\u6362",l.textContent="\u5220\u9664",a.setAttribute("aria-label","\u66F4\u6362\u56FE\u7247"),l.setAttribute("aria-label","\u5220\u9664\u56FE\u7247");for(let[g,y]of[["","\u539F\u5C3A\u5BF8"],["320","\u5C0F"],["560","\u4E2D"],["900","\u5927"]]){let b=document.createElement("option");b.value=g,b.textContent=y,c.append(b)}c.setAttribute("aria-label","\u56FE\u7247\u5C3A\u5BF8"),s.append(a,l,c),i.append(o,s),s.dataset.state="closed",s.setAttribute("aria-hidden","true");let u=()=>{o.dataset.weibeiImageMissingFor=o.dataset.weibeiResolvedSrc||o.getAttribute("src")||"",o.dataset.weibeiImagePlaceholder="true",o.classList.add("weibei-image-missing"),o.title=ue("imageMissing"),lt()},f=()=>{o.dataset.weibeiImagePlaceholder!=="true"&&(o.classList.remove("weibei-image-missing"),lt())},d=()=>{It(at,"imageNodeUpdates");let g=String(r.attrs.src||""),y=d1(g),b=Fl(r.attrs.alt||"");if(o.alt=b.alt,o.title=String(r.attrs.title||""),o.dataset.weibeiMarkdownSrc=g,c.value=b.size&&["320","560","900"].includes(String(b.size.width))?String(b.size.width):"",ID(o,b.size),!(o.dataset.weibeiImagePlaceholder==="true"&&o.dataset.weibeiImageMissingFor===y)){if(!y){o.dataset.weibeiImageMissingFor=y,o.dataset.weibeiImagePlaceholder="true",o.classList.add("weibei-image-missing"),o.setAttribute("src",f1());return}o.dataset.weibeiResolvedSrc=y,delete o.dataset.weibeiImagePlaceholder,o.classList.remove("weibei-image-missing"),o.setAttribute("src",y)}},p=()=>{let g=`image-picker-${Date.now()}-${zp+=1}`;_t.set(g,{mode:"replace",view:e,getPos:n,documentID:nt,documentGeneration:Ve}),Ie("imagePickerRequested",{id:g})},h=()=>{let g=n(),y=typeof g=="number"?e.state.doc.nodeAt(g):null;y?.type===r.type&&e.dispatch(e.state.tr.delete(g,g+y.nodeSize).scrollIntoView())},m=()=>{let g=n(),y=typeof g=="number"?e.state.doc.nodeAt(g):null;if(y?.type!==r.type)return;let C=`${Fl(y.attrs.alt||"").alt}${c.value?`|${c.value}`:""}`;e.dispatch(e.state.tr.setNodeMarkup(g,void 0,{...y.attrs,alt:C}).scrollIntoView()),e.focus()};return o.addEventListener("error",u),o.addEventListener("load",f),a.addEventListener("click",p),l.addEventListener("click",h),c.addEventListener("change",m),Lp.add(d),d(),{dom:i,update(g){if(g.type!==r.type)return!1;let y=g.attrs.src!==r.attrs.src||g.attrs.alt!==r.attrs.alt||g.attrs.title!==r.attrs.title;return r=g,y&&d(),!0},selectNode(){i.classList.add("ProseMirror-selectednode"),o.classList.add("ProseMirror-selectednode"),s.dataset.state="open",s.setAttribute("aria-hidden","false")},deselectNode(){i.classList.remove("ProseMirror-selectednode"),o.classList.remove("ProseMirror-selectednode"),s.dataset.state="closed",s.setAttribute("aria-hidden","true")},stopEvent(g){return s.contains(g.target)},ignoreMutation(g){return s.contains(g.target)},destroy(){Lp.delete(d),o.removeEventListener("error",u),o.removeEventListener("load",f),a.removeEventListener("click",p),l.removeEventListener("click",h),c.removeEventListener("change",m)}}},p1=()=>Lp.forEach(t=>t()),jp=()=>{if(!V)return null;let t=V.action(e=>e.get(U).state.selection);return!t||t.empty?null:{from:t.from,to:t.to}},h1=()=>V?V.action(t=>{let{selection:e}=t.get(U).state;if(!e||e.empty)return"";let n=e.content().content;return X0(n.textBetween(0,n.size,` -`))}):"",DD=()=>X0(window.getSelection()?.toString()||h1()),Ht=(t,e,n,r,i={})=>{n<=e||t.push(le.inline(e,n,{...i,class:r}))},LD=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=4),PD=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=2),BD=(t,e,n,r)=>{re||Ap.length===0||Ap.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ht(t,n+a,n+a+i.text.length,"weibei-remark-mark",{"data-record-id":i.id,title:"\u56DE\u8BBF\u8FD9\u53E5\u7684\u672D\u8BB0"}),s+=1,o=a+i.text.length}r.set(i.id,s)})},FD=(t,e,n,r)=>{re||vp.length===0||vp.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ht(t,n+a,n+a+i.text.length,"weibei-selection-ask-mark",{"data-thread-id":i.id,title:"\u6253\u5F00\u5F53\u65F6\u7684\u9009\u533A\u95EE\u7B54"}),s+=1,o=a+i.text.length}r.set(i.id,s)})};var zD=(t,e,n)=>{for(let r of e.matchAll(/(?:^|[\s`])((?:来源:|Source:)[^`\n]+)/g)){let i=r[0].startsWith(r[1])?0:1,o=r[1].startsWith("\u6765\u6E90\uFF1A")?"\u6765\u6E90\uFF1A":"Source:",s=n+(r.index||0)+i,a=s+r[1].length;Ht(t,s,a,"weibei-source-reference",{role:"link",tabindex:"0",title:ue("openSource",{value:r[1].slice(o.length).trim()}),"data-source-reference":r[1]})}},_D=(t,e,n,r)=>{let i=0;for(;i<e.length;){if(r.open){let a=e.indexOf("%%",i);if(a<0){Ht(t,n+i,n+e.length,"weibei-comment");return}Ht(t,n+i,n+a+2,"weibei-comment"),r.open=!1,i=a+2;continue}let o=e.indexOf("%%",i);if(o<0)return;let s=e.indexOf("%%",o+2);if(s<0){Ht(t,n+o,n+e.length,"weibei-comment"),r.open=!0;return}Ht(t,n+o,n+s+2,"weibei-comment"),i=s+2}},$D=(t,e,n)=>{for(let r of e.matchAll(/(^|\s)(#[\p{L}\p{N}_/-]+)\b/gu)){let i=n+(r.index||0)+r[1].length;Ht(t,i,i+r[2].length,"weibei-tag")}for(let r of e.matchAll(/(^|\s)(\^[A-Za-z0-9-]+)\s*$/g)){let i=n+(r.index||0)+r[1].length;Ht(t,i,i+r[2].length,"weibei-block-id")}},HD=(t,e,n)=>{for(let r of e.matchAll(/<br\s*\/?>/gi)){let i=n+(r.index||0),o=i+r[0].length;Ht(t,i,o,"weibei-html-break-source"),t.push(le.widget(o,()=>{let s=document.createElement("br");return s.className="weibei-html-break-preview",s},{side:1}))}},R0=t=>{let e=document.createElement("div");e.className="weibei-mermaid-render",e.textContent=ue("mermaidRendering");let n="\0",r=0,i=0,o=(s,a=!1)=>{let l=String(s||"");if(l===n)return;n=l;let c=i+=1;window.clearTimeout(r),r=window.setTimeout(async()=>{if(!(!e.isConnected||c!==i)){e.classList.remove("weibei-mermaid-error");try{let u=await Xw();pD(u);let f=`weibei-mermaid-${oD+=1}`;It(at,"mermaidRenders");let{svg:d,bindFunctions:p}=await u.render(f,l,e);if(!e.isConnected||c!==i)return;e.innerHTML=d,p?.(e),e.dataset.rendered="true"}catch(u){if(!e.isConnected||c!==i)return;e.classList.add("weibei-mermaid-error"),e.textContent=ue("mermaidFailed",{value:String(u?.message||u)})}lt()}},a?300:0)};return o(t),{element:e,updateSource:o}},Ll=new WeakMap,$t=null,Es=!1,WD=t=>{if(!Es||!(t.selection instanceof B))return null;let{$from:e}=t.selection;for(let n=e.depth;n>0;n-=1){let r=e.node(n);if(r.type.name==="code_block")return Vp(r.attrs.language||"")!=="mermaid"?null:{node:r,pos:e.before(n)}}return null},jD=t=>{$t&&($t.documentGeneration!==Ve||$t.contentGeneration!==Xn||$t.generation!==Zi||t?.pos!==$t.pos)&&($t=null)},VD=(t,e,n)=>{let r=n?.pos===e;if(r&&!$t){let s=Ll.get(t);$t=s?.generation===Zi?{...s,pos:e,documentGeneration:Ve,contentGeneration:Xn}:{...R0(t.textContent),generation:Zi,key:`mermaid-preview-${x0+=1}`,pos:e,documentGeneration:Ve,contentGeneration:Xn}}if(r)return $t.updateSource(t.textContent,!0),$t;let i=Ll.get(t);if(i?.generation===Zi)return i.updateSource(t.textContent),i;let o={...R0(t.textContent),generation:Zi,key:`mermaid-preview-${x0+=1}`};return Ll.set(t,o),o},qD=(t,e,n,r)=>{if(Vp(e.attrs.language||"")!=="mermaid")return!1;t.push(le.node(n,n+e.nodeSize,{class:"weibei-code-block weibei-mermaid-block","data-language":"mermaid"}));let i=VD(e,n,r);return t.push(le.widget(n+e.nodeSize,()=>i.element,{side:-1,key:i.key})),!0},KD=t=>{let e=u1(t);return e.target||e.noteTitle},UD=t=>{let e=t instanceof Element?t.closest(".weibei-wikilink, .weibei-embed-note[data-wikilink-title]"):null;return e?.getAttribute("data-wikilink-title")||e?.textContent?.trim()||""},Pp=t=>{let e=UD(t);return e?(Ie("wikiLinkActivated",{title:e}),!0):!1},JD=t=>(t instanceof Element?t.closest(".weibei-source-reference[data-source-reference]"):null)?.getAttribute("data-source-reference")||"",Bp=t=>{let e=JD(t);return e?(Ie("sourceReferenceActivated",{reference:e}),!0):!1},m1=t=>{let e=t instanceof Element?t.closest(".weibei-selection-ask-mark[data-thread-id]"):null,n=e?.getAttribute("data-thread-id")||"";return n?(Ie("selectionAskMark",{threadId:n,text:e.textContent||""}),!0):!1},g1=t=>{let e=t instanceof Element?t.closest(".weibei-remark-mark[data-record-id]"):null,n=e?.getAttribute("data-record-id")||"";return n?(Ie("remarkMark",{recordId:n,text:e.textContent||""}),!0):!1},y1=t=>{if(re||!(t instanceof Element))return!1;let e=t.closest('blockquote.weibei-callout[data-callout-fold="-"]');return e?(e.classList.toggle("weibei-callout-open"),!0):!1},Vp=t=>{let e=(t||"").trim().toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",sh:"bash",shell:"bash",zsh:"bash",md:"markdown",yml:"yaml"}[e]||e},k1=t=>typeof t=="string"?t.length:Array.isArray(t.content)?t.content.reduce((e,n)=>e+k1(n),0):String(t.content||"").length,GD=t=>{let e=Array.isArray(t.alias)?t.alias:t.alias?[t.alias]:[];return["weibei-prism-token","token",t.type,...e].filter(Boolean).join(" ")},O0=new WeakMap,XD=new Set(["bash","css","do","java","javascript","json","jsx","markdown","python","r","ruby","rust","sql","stata","swift","tsx","typescript","yaml"]),vs=null,D0=!1,YD=()=>{vs||D0||(D0=!0,Yw().then(t=>{vs=t,Yr+=1,V?.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiPrismReady",!0))})}).catch(no))},b1=(t,e,n)=>{let r=n;for(let i of e){let o=k1(i);typeof i!="string"&&o>0&&(t.push({from:r,to:r+o,className:GD(i)}),Array.isArray(i.content)&&b1(t,i.content,r)),r+=o}},QD=(t,e,n)=>{let r=Vp(e.attrs.language||"");if(!XD.has(r))return;if(!vs){YD();return}let i=O0.get(e);try{i||(It(at,"codeTokenizations"),i=[],b1(i,vs.tokenize(e.textContent,vs.languages[r]),0),O0.set(e,i)),i.forEach(o=>Ht(t,n+1+o.from,n+1+o.to,o.className))}catch{}};var L0=(t,e,n)=>{let r=t,i=r.type.name==="math_block",o=document.createElement(i?"div":"span");o.className=`weibei-math-node ${i?"weibei-math-block":"weibei-math-inline"}`,o.dataset.type=r.type.name,o.contentEditable="false",o.tabIndex=0;let s=document.createElement(i?"div":"span");s.className="weibei-math-preview";let a=document.createElement(i?"textarea":"input");a.className="weibei-math-source",a.setAttribute("aria-label",ue(i?"slashBlockMath":"slashInlineMath")),a.setAttribute("autocapitalize","none"),a.setAttribute("autocomplete","off"),a.setAttribute("spellcheck","false"),a instanceof HTMLInputElement&&(a.type="text"),o.append(s,a);let l=!1,c=0,u=()=>i?String(r.attrs.value||""):r.textContent,f=async(h=u())=>{let m=c+=1;o.dataset.value=h,s.replaceChildren(),s.textContent=h||"\u516C\u5F0F";let g=(y,b=!1)=>{m!==c||b&&!o.isConnected||(s.replaceChildren(),It(at,"katexRenders"),y.render(h,s,{throwOnError:!0,strict:!1,trust:!1,displayMode:i}),o.classList.remove("weibei-math-invalid"),o.removeAttribute("title"))};try{let y=Gw();y?g(y):g(await Jw(),!0)}catch{if(m!==c)return;s.textContent=h||"\u516C\u5F0F",o.classList.add("weibei-math-invalid"),o.title=Jr==="en"?"Not displayable yet; keep editing.":"\u6682\u65F6\u65E0\u6CD5\u663E\u793A\uFF0C\u7EE7\u7EED\u7F16\u8F91\u5373\u53EF"}},d=h=>{!re&&h||(l=h,o.classList.toggle("weibei-math-editing",h),h&&(a.value=u(),a.focus(),a.select()))},p=()=>{let h=a.value;d(!1);let m=n();if(typeof m!="number")return;if(h===u()){e.dispatch(e.state.tr.setSelection(H.create(e.state.doc,m))),f(),e.focus();return}let g=i?r.type.create({...r.attrs,value:h}):r.type.create(r.attrs,h?e.state.schema.text(h):null,r.marks),y=e.state.tr.replaceWith(m,m+r.nodeSize,g);y.setSelection(H.create(y.doc,m)),e.dispatch(y.scrollIntoView()),e.focus()};return o.addEventListener("click",h=>{!l&&h.target!==a&&d(!0)}),o.addEventListener("weibei-edit-math",()=>d(!0)),o.addEventListener("keydown",h=>{let m=h;if(!l&&m.key==="Enter"){h.preventDefault(),d(!0);return}l&&(m.key==="Escape"||m.key==="Enter"&&(!i||m.metaKey))&&(h.preventDefault(),p())}),a.addEventListener("input",()=>f(a.value)),a.addEventListener("blur",p),f(),{dom:o,update(h){if(h.type!==r.type)return!1;let m=(i?h.attrs.value:h.textContent)!==u();return r=h,m&&!l&&f(),!0},selectNode(){o.classList.add("ProseMirror-selectednode")},deselectNode(){o.classList.remove("ProseMirror-selectednode")},stopEvent(h){return h.target===a||a.contains(h.target)},ignoreMutation(){return!0}}},ZD=(t,e,n)=>{let r=document.createElement("pre");r.className="weibei-code-block";let i=document.createElement("input");i.type="text",i.className="weibei-code-language-input",i.maxLength=32,i.setAttribute("autocomplete","off"),i.setAttribute("autocapitalize","none"),i.setAttribute("spellcheck","false");let o=document.createElement("code");o.setAttribute("autocapitalize","none"),o.setAttribute("autocorrect","off"),o.setAttribute("spellcheck","false"),r.append(i,o);let s=String(t.attrs.language||""),a=nt,l=Ve,c=Xn,u=()=>{r.dataset.language=s,i.value=s,i.placeholder=ue("codeLanguagePlaceholder"),i.setAttribute("aria-label",ue("codeLanguage")),i.readOnly=!re,i.tabIndex=re?0:-1,i.setAttribute("aria-readonly",i.readOnly?"true":"false")},f=()=>{let p=i.value.trim().split(/\s+/u)[0]?.slice(0,32)||"";if(i.value=p,!re||p===s||a!==nt||l!==Ve||c!==Xn){i.value=s;return}let h=n(),m=e.state.doc.nodeAt(h);if(m?.type.name!=="code_block"||String(m.attrs.language||"")!==s){i.value=s;return}e.dispatch(e.state.tr.setNodeMarkup(h,void 0,{...m.attrs,language:p}))},d=p=>{if(p.key==="Escape"){i.value=s,i.blur();return}p.key==="Enter"&&(p.preventDefault(),f(),i.blur(),e.focus())};return i.addEventListener("change",f),i.addEventListener("blur",f),i.addEventListener("keydown",d),u(),{dom:r,contentDOM:o,update(p){return p.type.name!=="code_block"||a!==nt||l!==Ve||c!==Xn?!1:(s=String(p.attrs.language||""),u(),!0)},stopEvent(p){return p.target===i||p.target instanceof Node&&i.contains(p.target)},ignoreMutation(p){return p.target===i||i.contains(p.target)},destroy(){i.removeEventListener("change",f),i.removeEventListener("blur",f),i.removeEventListener("keydown",d)}}},wp=(t,e,n)=>{let r=t,i=!1,o=document.createElement("span");o.contentEditable="false";let s=()=>{i=!1;let l=r.type.name;if(o.className=`weibei-structured-node ${l==="wiki_link"?"weibei-wikilink":l==="embed"?"weibei-embed-preview weibei-embed-note":"weibei-inline-footnote"}`,o.dataset.type=l,o.dataset.wikilinkTarget=l==="inline_footnote"?"":r.attrs.target,o.dataset.wikilinkTitle=l==="inline_footnote"?"":r.attrs.target,o.setAttribute("role",l==="inline_footnote"?"note":"link"),o.tabIndex=0,o.replaceChildren(),l==="embed"&&AD.test(r.attrs.target)){let c=document.createElement("img");c.className="weibei-embed-image",c.alt=r.attrs.label||r.attrs.target,c.src=d1(r.attrs.target),c.addEventListener("error",()=>{c.src=f1(),c.classList.add("weibei-image-missing")},{once:!0}),o.append(c)}else o.textContent=l==="inline_footnote"?r.attrs.value:r.attrs.label||r.attrs.target;o.title=l==="inline_footnote"?ue("inlineFootnote",{value:r.attrs.value}):ue(l==="embed"?"embed":"openOrCreateNote",{value:r.attrs.target})},a=()=>{if(!re||i)return;i=!0;let l=r.type.name==="inline_footnote",c=document.createElement("input"),u=document.createElement("input");c.className=u.className="weibei-structured-input",c.value=l?r.attrs.value:r.attrs.target,u.value=l?"":r.attrs.label,c.setAttribute("aria-label",l?"\u811A\u6CE8":"\u76EE\u6807"),u.setAttribute("aria-label","\u6807\u9898"),u.placeholder="\u6807\u9898";let f=p=>{if(i)if(i=!1,p){let h=n();if((typeof h=="number"?e.state.doc.nodeAt(h):null)?.type===r.type){let g=l?{value:c.value}:{target:c.value.trim(),label:u.value.trim(),raw:`${c.value.trim()}${u.value.trim()?`|${u.value.trim()}`:""}`};e.dispatch(e.state.tr.setNodeMarkup(h,void 0,g))}}else s()},d=p=>{p.key==="Enter"&&(p.preventDefault(),f(!0)),p.key==="Escape"&&(p.preventDefault(),f(!1))};c.addEventListener("keydown",d),u.addEventListener("keydown",d),o.replaceChildren(c),l||o.append(u),o.addEventListener("focusout",()=>window.setTimeout(()=>{o.contains(document.activeElement)||f(!0)}),{once:!0}),c.focus(),c.select()};return o.addEventListener("click",l=>{re&&(l.preventDefault(),l.stopPropagation(),a())}),o.addEventListener("weibei-edit-structured",a),Ns.add(s),s(),{dom:o,update(l){return l.type!==r.type?!1:(r=l,i||s(),!0)},selectNode(){o.classList.add("ProseMirror-selectednode")},deselectNode(){o.classList.remove("ProseMirror-selectednode")},stopEvent(l){return l.target instanceof HTMLInputElement},ignoreMutation(){return!0},destroy(){Ns.delete(s)}}},eL=(t,e,n)=>{let r=t,i=document.createElement("blockquote"),o=document.createElement("div"),s=document.createElement("select"),a=document.createElement("input"),l=document.createElement("div"),c=document.createElement("div");o.className="weibei-callout-header",s.className="weibei-callout-type",a.className="weibei-callout-title",a.placeholder="\u6807\u9898",l.className="weibei-callout-content",c.className="weibei-callout-collapse",o.append(s,a),c.append(l),i.append(o,c);let u=()=>{let d=String(r.attrs.calloutType||"note"),p=bp.has(d)?Array.from(bp):[d,...bp];s.replaceChildren(...p.map(h=>{let m=document.createElement("option");return m.value=h,m.textContent=M0(h),m})),s.value=d,a.value=r.attrs.title||"",s.disabled=!re,a.readOnly=!re,i.className=`weibei-callout weibei-callout-has-heading weibei-callout-${d}`,i.dataset.type="callout",i.dataset.callout=d,i.dataset.calloutFold=r.attrs.fold||"",i.dataset.calloutTitle=r.attrs.title||M0(d)},f=()=>{let d=n();(re&&typeof d=="number"?e.state.doc.nodeAt(d):null)?.type===r.type&&e.dispatch(e.state.tr.setNodeMarkup(d,void 0,{...r.attrs,calloutType:s.value,title:a.value.trim()}))};return s.addEventListener("change",f),a.addEventListener("blur",f),a.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),f(),a.blur()),d.key==="Escape"&&(d.preventDefault(),u(),a.blur())}),Ns.add(u),u(),{dom:i,contentDOM:l,update(d){return d.type!==r.type?!1:(r=d,u(),!0)},stopEvent(d){return d.target===s||d.target===a},ignoreMutation(d){return o.contains(d.target)},destroy(){Ns.delete(u)}}},tL=()=>V?V.action(t=>{let e=t.get(U),n=e.state.selection.from,r="";return e.state.doc.descendants((i,o)=>{if(!i.isText||r)return!0;let s=i.text||"",a=o,l=o+s.length;if(n<a||n>l)return!0;for(let c of s.matchAll(/\[\[([^\]\n]+)\]\]/g)){let u=a+(c.index||0),f=u+c[0].length;if(n>=u&&n<=f)return r=KD(c[1]),!1}return!0}),r}):"",x1=async t=>{let{alt:e,src:n}=await cp(t);if(!q0?.imageAttachmentRequested)return{alt:e,src:n};let r=`attachment-${Date.now()}-${zp+=1}`;return new Promise((i,o)=>{Gn.set(r,{resolve:i,reject:o}),Ie("imageAttachmentRequested",{id:r,name:t.name||e||"image",mime:t.type||"image/png",dataURL:n}),window.setTimeout(()=>{Gn.has(r)&&(Gn.delete(r),o(new Error("Attachment save timed out")))},15e3)})},nL=t=>{let e=String(t||""),n=e.trim();return n?e.includes(` -`)?!0:/^(?:#{1,6}\s|[-*+]\s|\d+\.\s|>\s|```|~~~|\$\$|\|.*\||---$)/.test(n):!1},rL=t=>{let e=String(t||"");return nL(e)?` + <text x="48" y="22" fill="${t.text}" font-family="-apple-system, BlinkMacSystemFont, 'Songti SC', serif" font-size="13">${Lp(ue("imageMissing"))}</text> +</svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`},p1=t=>{if(!t||/^(?:data:|blob:|weibeiimage:)/i.test(t))return t;if(/^https:/i.test(t))return R0(t);if(/^http:/i.test(t))return"";try{let e=new URL(t,J0||window.location.href).href;return/^(?:file:|https:)/i.test(e)?R0(e):/^(?:data:|blob:|weibeiimage:)/i.test(e)?e:""}catch{return""}},jp=()=>{document.body.dataset.editable=re?"true":"false",document.querySelectorAll(".weibei-code-language-input").forEach(t=>{t instanceof HTMLInputElement&&(t.readOnly=!re,t.tabIndex=re?0:-1,t.setAttribute("aria-readonly",t.readOnly?"true":"false"),t.setAttribute("aria-label",ue("codeLanguage")),t.placeholder=ue("codeLanguagePlaceholder"))})},Pp=new Set,Ns=new Set;var DD=(t,e,n)=>{let r=t,i=document.createElement("span"),o=document.createElement("img"),s=document.createElement("span"),a=document.createElement("button"),l=document.createElement("button"),c=document.createElement("select");i.className="weibei-image-node",i.contentEditable="false",o.className="weibei-image",s.className="weibei-image-controls",a.type=l.type="button",a.textContent="\u66F4\u6362",l.textContent="\u5220\u9664",a.setAttribute("aria-label","\u66F4\u6362\u56FE\u7247"),l.setAttribute("aria-label","\u5220\u9664\u56FE\u7247");for(let[g,y]of[["","\u539F\u5C3A\u5BF8"],["320","\u5C0F"],["560","\u4E2D"],["900","\u5927"]]){let b=document.createElement("option");b.value=g,b.textContent=y,c.append(b)}c.setAttribute("aria-label","\u56FE\u7247\u5C3A\u5BF8"),s.append(a,l,c),i.append(o,s),s.dataset.state="closed",s.setAttribute("aria-hidden","true");let u=()=>{o.dataset.weibeiImageMissingFor=o.dataset.weibeiResolvedSrc||o.getAttribute("src")||"",o.dataset.weibeiImagePlaceholder="true",o.classList.add("weibei-image-missing"),o.title=ue("imageMissing"),lt()},f=()=>{o.dataset.weibeiImagePlaceholder!=="true"&&(o.classList.remove("weibei-image-missing"),lt())},d=()=>{It(at,"imageNodeUpdates");let g=String(r.attrs.src||""),y=p1(g),b=Fl(r.attrs.alt||"");if(o.alt=b.alt,o.title=String(r.attrs.title||""),o.dataset.weibeiMarkdownSrc=g,c.value=b.size&&["320","560","900"].includes(String(b.size.width))?String(b.size.width):"",ND(o,b.size),!(o.dataset.weibeiImagePlaceholder==="true"&&o.dataset.weibeiImageMissingFor===y)){if(!y){o.dataset.weibeiImageMissingFor=y,o.dataset.weibeiImagePlaceholder="true",o.classList.add("weibei-image-missing"),o.setAttribute("src",d1());return}o.dataset.weibeiResolvedSrc=y,delete o.dataset.weibeiImagePlaceholder,o.classList.remove("weibei-image-missing"),o.setAttribute("src",y)}},p=()=>{let g=`image-picker-${Date.now()}-${_p+=1}`;_t.set(g,{mode:"replace",view:e,getPos:n,documentID:nt,documentGeneration:Ve}),ye("imagePickerRequested",{id:g})},h=()=>{let g=n(),y=typeof g=="number"?e.state.doc.nodeAt(g):null;y?.type===r.type&&e.dispatch(e.state.tr.delete(g,g+y.nodeSize).scrollIntoView())},m=()=>{let g=n(),y=typeof g=="number"?e.state.doc.nodeAt(g):null;if(y?.type!==r.type)return;let C=`${Fl(y.attrs.alt||"").alt}${c.value?`|${c.value}`:""}`;e.dispatch(e.state.tr.setNodeMarkup(g,void 0,{...y.attrs,alt:C}).scrollIntoView()),e.focus()};return o.addEventListener("error",u),o.addEventListener("load",f),a.addEventListener("click",p),l.addEventListener("click",h),c.addEventListener("change",m),Pp.add(d),d(),{dom:i,update(g){if(g.type!==r.type)return!1;let y=g.attrs.src!==r.attrs.src||g.attrs.alt!==r.attrs.alt||g.attrs.title!==r.attrs.title;return r=g,y&&d(),!0},selectNode(){i.classList.add("ProseMirror-selectednode"),o.classList.add("ProseMirror-selectednode"),s.dataset.state="open",s.setAttribute("aria-hidden","false")},deselectNode(){i.classList.remove("ProseMirror-selectednode"),o.classList.remove("ProseMirror-selectednode"),s.dataset.state="closed",s.setAttribute("aria-hidden","true")},stopEvent(g){return s.contains(g.target)},ignoreMutation(g){return s.contains(g.target)},destroy(){Pp.delete(d),o.removeEventListener("error",u),o.removeEventListener("load",f),a.removeEventListener("click",p),l.removeEventListener("click",h),c.removeEventListener("change",m)}}},h1=()=>Pp.forEach(t=>t()),Vp=()=>{if(!V)return null;let t=V.action(e=>e.get(U).state.selection);return!t||t.empty?null:{from:t.from,to:t.to}},m1=()=>V?V.action(t=>{let{selection:e}=t.get(U).state;if(!e||e.empty)return"";let n=e.content().content;return Y0(n.textBetween(0,n.size,` +`))}):"",LD=()=>Y0(window.getSelection()?.toString()||m1()),Ht=(t,e,n,r,i={})=>{n<=e||t.push(le.inline(e,n,{...i,class:r}))},PD=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=4),BD=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=2),FD=(t,e,n,r)=>{re||Ip.length===0||Ip.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ht(t,n+a,n+a+i.text.length,"weibei-remark-mark",{"data-record-id":i.id,title:"\u56DE\u8BBF\u8FD9\u53E5\u7684\u672D\u8BB0"}),s+=1,o=a+i.text.length}r.set(i.id,s)})},zD=(t,e,n,r)=>{re||Ap.length===0||Ap.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ht(t,n+a,n+a+i.text.length,"weibei-selection-ask-mark",{"data-thread-id":i.id,title:"\u6253\u5F00\u5F53\u65F6\u7684\u9009\u533A\u95EE\u7B54"}),s+=1,o=a+i.text.length}r.set(i.id,s)})};var _D=(t,e,n)=>{for(let r of e.matchAll(/(?:^|[\s`])((?:来源:|Source:)[^`\n]+)/g)){let i=r[0].startsWith(r[1])?0:1,o=r[1].startsWith("\u6765\u6E90\uFF1A")?"\u6765\u6E90\uFF1A":"Source:",s=n+(r.index||0)+i,a=s+r[1].length;Ht(t,s,a,"weibei-source-reference",{role:"link",tabindex:"0",title:ue("openSource",{value:r[1].slice(o.length).trim()}),"data-source-reference":r[1]})}},$D=(t,e,n,r)=>{let i=0;for(;i<e.length;){if(r.open){let a=e.indexOf("%%",i);if(a<0){Ht(t,n+i,n+e.length,"weibei-comment");return}Ht(t,n+i,n+a+2,"weibei-comment"),r.open=!1,i=a+2;continue}let o=e.indexOf("%%",i);if(o<0)return;let s=e.indexOf("%%",o+2);if(s<0){Ht(t,n+o,n+e.length,"weibei-comment"),r.open=!0;return}Ht(t,n+o,n+s+2,"weibei-comment"),i=s+2}},HD=(t,e,n)=>{for(let r of e.matchAll(/(^|\s)(#[\p{L}\p{N}_/-]+)\b/gu)){let i=n+(r.index||0)+r[1].length;Ht(t,i,i+r[2].length,"weibei-tag")}for(let r of e.matchAll(/(^|\s)(\^[A-Za-z0-9-]+)\s*$/g)){let i=n+(r.index||0)+r[1].length;Ht(t,i,i+r[2].length,"weibei-block-id")}},WD=(t,e,n)=>{for(let r of e.matchAll(/<br\s*\/?>/gi)){let i=n+(r.index||0),o=i+r[0].length;Ht(t,i,o,"weibei-html-break-source"),t.push(le.widget(o,()=>{let s=document.createElement("br");return s.className="weibei-html-break-preview",s},{side:1}))}},O0=t=>{let e=document.createElement("div");e.className="weibei-mermaid-render",e.textContent=ue("mermaidRendering");let n="\0",r=0,i=0,o=(s,a=!1)=>{let l=String(s||"");if(l===n)return;n=l;let c=i+=1;window.clearTimeout(r),r=window.setTimeout(async()=>{if(!(!e.isConnected||c!==i)){e.classList.remove("weibei-mermaid-error");try{let u=await Yw();hD(u);let f=`weibei-mermaid-${sD+=1}`;It(at,"mermaidRenders");let{svg:d,bindFunctions:p}=await u.render(f,l,e);if(!e.isConnected||c!==i)return;e.innerHTML=d,p?.(e),e.dataset.rendered="true"}catch(u){if(!e.isConnected||c!==i)return;e.classList.add("weibei-mermaid-error"),e.textContent=ue("mermaidFailed",{value:String(u?.message||u)})}lt()}},a?300:0)};return o(t),{element:e,updateSource:o}},Ll=new WeakMap,$t=null,Es=!1,jD=t=>{if(!Es||!(t.selection instanceof B))return null;let{$from:e}=t.selection;for(let n=e.depth;n>0;n-=1){let r=e.node(n);if(r.type.name==="code_block")return qp(r.attrs.language||"")!=="mermaid"?null:{node:r,pos:e.before(n)}}return null},VD=t=>{$t&&($t.documentGeneration!==Ve||$t.contentGeneration!==Xn||$t.generation!==Zi||t?.pos!==$t.pos)&&($t=null)},qD=(t,e,n)=>{let r=n?.pos===e;if(r&&!$t){let s=Ll.get(t);$t=s?.generation===Zi?{...s,pos:e,documentGeneration:Ve,contentGeneration:Xn}:{...O0(t.textContent),generation:Zi,key:`mermaid-preview-${w0+=1}`,pos:e,documentGeneration:Ve,contentGeneration:Xn}}if(r)return $t.updateSource(t.textContent,!0),$t;let i=Ll.get(t);if(i?.generation===Zi)return i.updateSource(t.textContent),i;let o={...O0(t.textContent),generation:Zi,key:`mermaid-preview-${w0+=1}`};return Ll.set(t,o),o},KD=(t,e,n,r)=>{if(qp(e.attrs.language||"")!=="mermaid")return!1;t.push(le.node(n,n+e.nodeSize,{class:"weibei-code-block weibei-mermaid-block","data-language":"mermaid"}));let i=qD(e,n,r);return t.push(le.widget(n+e.nodeSize,()=>i.element,{side:-1,key:i.key})),!0},UD=t=>{let e=f1(t);return e.target||e.noteTitle},JD=t=>{let e=t instanceof Element?t.closest(".weibei-wikilink, .weibei-embed-note[data-wikilink-title]"):null;return e?.getAttribute("data-wikilink-title")||e?.textContent?.trim()||""},Bp=t=>{let e=JD(t);return e?(ye("wikiLinkActivated",{title:e}),!0):!1},GD=t=>(t instanceof Element?t.closest(".weibei-source-reference[data-source-reference]"):null)?.getAttribute("data-source-reference")||"",Fp=t=>{let e=GD(t);return e?(ye("sourceReferenceActivated",{reference:e}),!0):!1},g1=t=>{let e=t instanceof Element?t.closest(".weibei-selection-ask-mark[data-thread-id]"):null,n=e?.getAttribute("data-thread-id")||"";return n?(ye("selectionAskMark",{threadId:n,text:e.textContent||""}),!0):!1},y1=t=>{let e=t instanceof Element?t.closest(".weibei-remark-mark[data-record-id]"):null,n=e?.getAttribute("data-record-id")||"";return n?(ye("remarkMark",{recordId:n,text:e.textContent||""}),!0):!1},k1=t=>{if(re||!(t instanceof Element))return!1;let e=t.closest('blockquote.weibei-callout[data-callout-fold="-"]');return e?(e.classList.toggle("weibei-callout-open"),!0):!1},qp=t=>{let e=(t||"").trim().toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",sh:"bash",shell:"bash",zsh:"bash",md:"markdown",yml:"yaml"}[e]||e},b1=t=>typeof t=="string"?t.length:Array.isArray(t.content)?t.content.reduce((e,n)=>e+b1(n),0):String(t.content||"").length,XD=t=>{let e=Array.isArray(t.alias)?t.alias:t.alias?[t.alias]:[];return["weibei-prism-token","token",t.type,...e].filter(Boolean).join(" ")},D0=new WeakMap,YD=new Set(["bash","css","do","java","javascript","json","jsx","markdown","python","r","ruby","rust","sql","stata","swift","tsx","typescript","yaml"]),vs=null,L0=!1,QD=()=>{vs||L0||(L0=!0,Qw().then(t=>{vs=t,Yr+=1,V?.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiPrismReady",!0))})}).catch(no))},x1=(t,e,n)=>{let r=n;for(let i of e){let o=b1(i);typeof i!="string"&&o>0&&(t.push({from:r,to:r+o,className:XD(i)}),Array.isArray(i.content)&&x1(t,i.content,r)),r+=o}},ZD=(t,e,n)=>{let r=qp(e.attrs.language||"");if(!YD.has(r))return;if(!vs){QD();return}let i=D0.get(e);try{i||(It(at,"codeTokenizations"),i=[],x1(i,vs.tokenize(e.textContent,vs.languages[r]),0),D0.set(e,i)),i.forEach(o=>Ht(t,n+1+o.from,n+1+o.to,o.className))}catch{}};var P0=(t,e,n)=>{let r=t,i=r.type.name==="math_block",o=document.createElement(i?"div":"span");o.className=`weibei-math-node ${i?"weibei-math-block":"weibei-math-inline"}`,o.dataset.type=r.type.name,o.contentEditable="false",o.tabIndex=0;let s=document.createElement(i?"div":"span");s.className="weibei-math-preview";let a=document.createElement(i?"textarea":"input");a.className="weibei-math-source",a.setAttribute("aria-label",ue(i?"slashBlockMath":"slashInlineMath")),a.setAttribute("autocapitalize","none"),a.setAttribute("autocomplete","off"),a.setAttribute("spellcheck","false"),a instanceof HTMLInputElement&&(a.type="text"),o.append(s,a);let l=!1,c=0,u=()=>i?String(r.attrs.value||""):r.textContent,f=async(h=u())=>{let m=c+=1;o.dataset.value=h,s.replaceChildren(),s.textContent=h||"\u516C\u5F0F";let g=(y,b=!1)=>{m!==c||b&&!o.isConnected||(s.replaceChildren(),It(at,"katexRenders"),y.render(h,s,{throwOnError:!0,strict:!1,trust:!1,displayMode:i}),o.classList.remove("weibei-math-invalid"),o.removeAttribute("title"))};try{let y=Xw();y?g(y):g(await Gw(),!0)}catch{if(m!==c)return;s.textContent=h||"\u516C\u5F0F",o.classList.add("weibei-math-invalid"),o.title=Jr==="en"?"Not displayable yet; keep editing.":"\u6682\u65F6\u65E0\u6CD5\u663E\u793A\uFF0C\u7EE7\u7EED\u7F16\u8F91\u5373\u53EF"}},d=h=>{!re&&h||(l=h,o.classList.toggle("weibei-math-editing",h),h&&(a.value=u(),a.focus(),a.select()))},p=()=>{let h=a.value;d(!1);let m=n();if(typeof m!="number")return;if(h===u()){e.dispatch(e.state.tr.setSelection(H.create(e.state.doc,m))),f(),e.focus();return}let g=i?r.type.create({...r.attrs,value:h}):r.type.create(r.attrs,h?e.state.schema.text(h):null,r.marks),y=e.state.tr.replaceWith(m,m+r.nodeSize,g);y.setSelection(H.create(y.doc,m)),e.dispatch(y.scrollIntoView()),e.focus()};return o.addEventListener("click",h=>{!l&&h.target!==a&&d(!0)}),o.addEventListener("weibei-edit-math",()=>d(!0)),o.addEventListener("keydown",h=>{let m=h;if(!l&&m.key==="Enter"){h.preventDefault(),d(!0);return}l&&(m.key==="Escape"||m.key==="Enter"&&(!i||m.metaKey))&&(h.preventDefault(),p())}),a.addEventListener("input",()=>f(a.value)),a.addEventListener("blur",p),f(),{dom:o,update(h){if(h.type!==r.type)return!1;let m=(i?h.attrs.value:h.textContent)!==u();return r=h,m&&!l&&f(),!0},selectNode(){o.classList.add("ProseMirror-selectednode")},deselectNode(){o.classList.remove("ProseMirror-selectednode")},stopEvent(h){return h.target===a||a.contains(h.target)},ignoreMutation(){return!0}}},eL=(t,e,n)=>{let r=document.createElement("pre");r.className="weibei-code-block";let i=document.createElement("input");i.type="text",i.className="weibei-code-language-input",i.maxLength=32,i.setAttribute("autocomplete","off"),i.setAttribute("autocapitalize","none"),i.setAttribute("spellcheck","false");let o=document.createElement("code");o.setAttribute("autocapitalize","none"),o.setAttribute("autocorrect","off"),o.setAttribute("spellcheck","false"),r.append(i,o);let s=String(t.attrs.language||""),a=nt,l=Ve,c=Xn,u=()=>{r.dataset.language=s,i.value=s,i.placeholder=ue("codeLanguagePlaceholder"),i.setAttribute("aria-label",ue("codeLanguage")),i.readOnly=!re,i.tabIndex=re?0:-1,i.setAttribute("aria-readonly",i.readOnly?"true":"false")},f=()=>{let p=i.value.trim().split(/\s+/u)[0]?.slice(0,32)||"";if(i.value=p,!re||p===s||a!==nt||l!==Ve||c!==Xn){i.value=s;return}let h=n(),m=e.state.doc.nodeAt(h);if(m?.type.name!=="code_block"||String(m.attrs.language||"")!==s){i.value=s;return}e.dispatch(e.state.tr.setNodeMarkup(h,void 0,{...m.attrs,language:p}))},d=p=>{if(p.key==="Escape"){i.value=s,i.blur();return}p.key==="Enter"&&(p.preventDefault(),f(),i.blur(),e.focus())};return i.addEventListener("change",f),i.addEventListener("blur",f),i.addEventListener("keydown",d),u(),{dom:r,contentDOM:o,update(p){return p.type.name!=="code_block"||a!==nt||l!==Ve||c!==Xn?!1:(s=String(p.attrs.language||""),u(),!0)},stopEvent(p){return p.target===i||p.target instanceof Node&&i.contains(p.target)},ignoreMutation(p){return p.target===i||i.contains(p.target)},destroy(){i.removeEventListener("change",f),i.removeEventListener("blur",f),i.removeEventListener("keydown",d)}}},wp=(t,e,n)=>{let r=t,i=!1,o=document.createElement("span");o.contentEditable="false";let s=()=>{i=!1;let l=r.type.name;if(o.className=`weibei-structured-node ${l==="wiki_link"?"weibei-wikilink":l==="embed"?"weibei-embed-preview weibei-embed-note":"weibei-inline-footnote"}`,o.dataset.type=l,o.dataset.wikilinkTarget=l==="inline_footnote"?"":r.attrs.target,o.dataset.wikilinkTitle=l==="inline_footnote"?"":r.attrs.target,o.setAttribute("role",l==="inline_footnote"?"note":"link"),o.tabIndex=0,o.replaceChildren(),l==="embed"&&ID.test(r.attrs.target)){let c=document.createElement("img");c.className="weibei-embed-image",c.alt=r.attrs.label||r.attrs.target,c.src=p1(r.attrs.target),c.addEventListener("error",()=>{c.src=d1(),c.classList.add("weibei-image-missing")},{once:!0}),o.append(c)}else o.textContent=l==="inline_footnote"?r.attrs.value:r.attrs.label||r.attrs.target;o.title=l==="inline_footnote"?ue("inlineFootnote",{value:r.attrs.value}):ue(l==="embed"?"embed":"openOrCreateNote",{value:r.attrs.target})},a=()=>{if(!re||i)return;i=!0;let l=r.type.name==="inline_footnote",c=document.createElement("input"),u=document.createElement("input");c.className=u.className="weibei-structured-input",c.value=l?r.attrs.value:r.attrs.target,u.value=l?"":r.attrs.label,c.setAttribute("aria-label",l?"\u811A\u6CE8":"\u76EE\u6807"),u.setAttribute("aria-label","\u6807\u9898"),u.placeholder="\u6807\u9898";let f=p=>{if(i)if(i=!1,p){let h=n();if((typeof h=="number"?e.state.doc.nodeAt(h):null)?.type===r.type){let g=l?{value:c.value}:{target:c.value.trim(),label:u.value.trim(),raw:`${c.value.trim()}${u.value.trim()?`|${u.value.trim()}`:""}`};e.dispatch(e.state.tr.setNodeMarkup(h,void 0,g))}}else s()},d=p=>{p.key==="Enter"&&(p.preventDefault(),f(!0)),p.key==="Escape"&&(p.preventDefault(),f(!1))};c.addEventListener("keydown",d),u.addEventListener("keydown",d),o.replaceChildren(c),l||o.append(u),o.addEventListener("focusout",()=>window.setTimeout(()=>{o.contains(document.activeElement)||f(!0)}),{once:!0}),c.focus(),c.select()};return o.addEventListener("click",l=>{re&&(l.preventDefault(),l.stopPropagation(),a())}),o.addEventListener("weibei-edit-structured",a),Ns.add(s),s(),{dom:o,update(l){return l.type!==r.type?!1:(r=l,i||s(),!0)},selectNode(){o.classList.add("ProseMirror-selectednode")},deselectNode(){o.classList.remove("ProseMirror-selectednode")},stopEvent(l){return l.target instanceof HTMLInputElement},ignoreMutation(){return!0},destroy(){Ns.delete(s)}}},tL=(t,e,n)=>{let r=t,i=document.createElement("blockquote"),o=document.createElement("div"),s=document.createElement("select"),a=document.createElement("input"),l=document.createElement("div"),c=document.createElement("div");o.className="weibei-callout-header",s.className="weibei-callout-type",a.className="weibei-callout-title",a.placeholder="\u6807\u9898",l.className="weibei-callout-content",c.className="weibei-callout-collapse",o.append(s,a),c.append(l),i.append(o,c);let u=()=>{let d=String(r.attrs.calloutType||"note"),p=bp.has(d)?Array.from(bp):[d,...bp];s.replaceChildren(...p.map(h=>{let m=document.createElement("option");return m.value=h,m.textContent=E0(h),m})),s.value=d,a.value=r.attrs.title||"",s.disabled=!re,a.readOnly=!re,i.className=`weibei-callout weibei-callout-has-heading weibei-callout-${d}`,i.dataset.type="callout",i.dataset.callout=d,i.dataset.calloutFold=r.attrs.fold||"",i.dataset.calloutTitle=r.attrs.title||E0(d)},f=()=>{let d=n();(re&&typeof d=="number"?e.state.doc.nodeAt(d):null)?.type===r.type&&e.dispatch(e.state.tr.setNodeMarkup(d,void 0,{...r.attrs,calloutType:s.value,title:a.value.trim()}))};return s.addEventListener("change",f),a.addEventListener("blur",f),a.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),f(),a.blur()),d.key==="Escape"&&(d.preventDefault(),u(),a.blur())}),Ns.add(u),u(),{dom:i,contentDOM:l,update(d){return d.type!==r.type?!1:(r=d,u(),!0)},stopEvent(d){return d.target===s||d.target===a},ignoreMutation(d){return o.contains(d.target)},destroy(){Ns.delete(u)}}},nL=()=>V?V.action(t=>{let e=t.get(U),n=e.state.selection.from,r="";return e.state.doc.descendants((i,o)=>{if(!i.isText||r)return!0;let s=i.text||"",a=o,l=o+s.length;if(n<a||n>l)return!0;for(let c of s.matchAll(/\[\[([^\]\n]+)\]\]/g)){let u=a+(c.index||0),f=u+c[0].length;if(n>=u&&n<=f)return r=UD(c[1]),!1}return!0}),r}):"",w1=async t=>{let{alt:e,src:n}=await cp(t);if(!K0?.imageAttachmentRequested)return{alt:e,src:n};let r=`attachment-${Date.now()}-${_p+=1}`;return new Promise((i,o)=>{Gn.set(r,{resolve:i,reject:o}),ye("imageAttachmentRequested",{id:r,name:t.name||e||"image",mime:t.type||"image/png",dataURL:n}),window.setTimeout(()=>{Gn.has(r)&&(Gn.delete(r),o(new Error("Attachment save timed out")))},15e3)})},rL=t=>{let e=String(t||""),n=e.trim();return n?e.includes(` +`)?!0:/^(?:#{1,6}\s|[-*+]\s|\d+\.\s|>\s|```|~~~|\$\$|\|.*\||---$)/.test(n):!1},iL=t=>{let e=String(t||"");return rL(e)?` ${e.trim()} -`:e},iL=()=>V.action(t=>{let e=t.get(U),n=null,r=null;if(e.state.doc.descendants((s,a)=>{if(!s.isText||n||r)return!0;let l=s.text||"",c=l.indexOf(kp),u=l.indexOf(C0);if(c>=0&&u>c)return n={startFrom:a+c,startTo:a+c+kp.length,endFrom:a+u,endTo:a+u+C0.length},!1;let f=l.indexOf(w0);return f<0?!0:(r={from:a+f,to:a+f+w0.length},!1)}),n){let s=e.state.tr.delete(n.endFrom,n.endTo).delete(n.startFrom,n.startTo),a=Math.min(n.startFrom,s.doc.content.size),l=Math.min(Math.max(a,n.endFrom-kp.length),s.doc.content.size);return s.setSelection(B.create(s.doc,a,l)),e.dispatch(s),!0}if(!r)return!1;let i=e.state.tr.delete(r.from,r.to),o=Math.min(r.from,i.doc.content.size);return i.setSelection(B.create(i.doc,o)),e.dispatch(i),!0}),oL=()=>V.action(t=>{let e=t.get(U),n=Math.min(e.state.selection.to,e.state.doc.content.size);e.dispatch(e.state.tr.setSelection(B.create(e.state.doc,n)))}),sL=async(t,e)=>{if(!re)return[];let n=[];for(let o=0;o<t.length;o+=1){let s=t.item(o);s&&s.type.includes("image")&&n.push(s)}let r=e.nodes.image;return!r||n.length===0?[]:(await Promise.all(n.map(x1))).map(({alt:o,src:s})=>r.createAndFill({alt:o,src:s})).filter(Boolean)},P0=t=>Array.from(t||[]).map(e=>e.getAsFile?.()).filter(e=>e&&e.type.includes("image")),aL=({alt:t,src:e})=>{let n=(t||"image").replace(/[\[\]\n\r]/g," ").trim()||"image",r=String(e||"").replace(/\s/g,"%20").replace(/\)/g,"%29");return`![${n}](${r})`},B0=async t=>{if(!re)return;let e=await Promise.all(t.map(x1));Rs(e.map(aL).join(` +`:e},oL=()=>V.action(t=>{let e=t.get(U),n=null,r=null;if(e.state.doc.descendants((s,a)=>{if(!s.isText||n||r)return!0;let l=s.text||"",c=l.indexOf(kp),u=l.indexOf(S0);if(c>=0&&u>c)return n={startFrom:a+c,startTo:a+c+kp.length,endFrom:a+u,endTo:a+u+S0.length},!1;let f=l.indexOf(C0);return f<0?!0:(r={from:a+f,to:a+f+C0.length},!1)}),n){let s=e.state.tr.delete(n.endFrom,n.endTo).delete(n.startFrom,n.startTo),a=Math.min(n.startFrom,s.doc.content.size),l=Math.min(Math.max(a,n.endFrom-kp.length),s.doc.content.size);return s.setSelection(B.create(s.doc,a,l)),e.dispatch(s),!0}if(!r)return!1;let i=e.state.tr.delete(r.from,r.to),o=Math.min(r.from,i.doc.content.size);return i.setSelection(B.create(i.doc,o)),e.dispatch(i),!0}),sL=()=>V.action(t=>{let e=t.get(U),n=Math.min(e.state.selection.to,e.state.doc.content.size);e.dispatch(e.state.tr.setSelection(B.create(e.state.doc,n)))}),aL=async(t,e)=>{if(!re)return[];let n=[];for(let o=0;o<t.length;o+=1){let s=t.item(o);s&&s.type.includes("image")&&n.push(s)}let r=e.nodes.image;return!r||n.length===0?[]:(await Promise.all(n.map(w1))).map(({alt:o,src:s})=>r.createAndFill({alt:o,src:s})).filter(Boolean)},B0=t=>Array.from(t||[]).map(e=>e.getAsFile?.()).filter(e=>e&&e.type.includes("image")),lL=({alt:t,src:e})=>{let n=(t||"image").replace(/[\[\]\n\r]/g," ").trim()||"image",r=String(e||"").replace(/\s/g,"%20").replace(/\)/g,"%29");return`![${n}](${r})`},F0=async t=>{if(!re)return;let e=await Promise.all(t.map(w1));Rs(e.map(lL).join(` -`))},lL="#editor, .ProseMirror pre, .weibei-math-block",Cp=new WeakMap,cL=t=>{if(!(t instanceof Element))return;t.classList.add("weibei-scroll-active");let e=Cp.get(t);e&&window.clearTimeout(e),Cp.set(t,window.setTimeout(()=>{t.classList.remove("weibei-scroll-active"),Cp.delete(t)},850))},uL=()=>{document.addEventListener("scroll",t=>{let e=t.target instanceof Element?t.target.closest(lL):null;e&&cL(e)},!0)},fL=new Set(["list_item","task_list_item"]),w1=t=>(t.textContent||"").replace(/[\u200B\uFEFF]/g,"").trim(),F0=t=>{let{selection:e}=t;if(!e.empty)return null;let{$from:n}=e;for(let r=n.depth;r>0;r-=1){let i=n.node(r);if(fL.has(i.type.name))return w1(i).length>0?null:i.type}return null},dL=t=>{let{state:e}=t,{$from:n}=e.selection,r=n.parent;if(r?.isTextblock!==!0||!r.textContent||w1(r).length>0)return;let i=n.start(),o=n.end(),s=e.tr.delete(i,o);s.setSelection(B.create(s.doc,Math.min(i,s.doc.content.size))),t.dispatch(s)},pL=t=>{let e=F0(t.state);return e?(dL(t),e=F0(t.state)||e,Xa(e)(t.state,t.dispatch,t)):!1},hL=(t,e)=>{if(!re||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||!["Backspace","Delete"].includes(e.key))return!1;let{selection:n,schema:r}=t.state;return n instanceof B&&n.empty&&n.$from.parent.type.spec.code===!0&&n.$from.parent.content.size===0&&!!(r.nodes.paragraph&&Dn(r.nodes.paragraph)(t.state,t.dispatch))},mL=(t,e)=>{if(!re||e.key!=="Tab"||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof B)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(" "));return t.dispatch(r.setSelection(B.create(r.doc,n.from+1)).scrollIntoView()),!0},gL=new Set(["-","'",'"']),yL=(t,e)=>{if(!re||!gL.has(e.key)||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof B)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(e.key));return t.dispatch(r.setSelection(B.create(r.doc,n.from+e.key.length)).scrollIntoView()),!0},kL=(t,e)=>{if(!re||e.inputType!=="insertReplacementText"||e.isComposing||!e.cancelable)return!1;let{selection:n}=t.state;return!(n instanceof B)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0?!1:(e.preventDefault(),e.stopImmediatePropagation(),!0)},bL=(t,e)=>{if(!re||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||!["ArrowRight","ArrowDown"].includes(e.key))return!1;let{selection:n}=t.state;if(!(n instanceof B)||!n.empty||n.$from.parent.type.spec.code!==!0)return!1;let{$from:r}=n;return r.indexAfter(-1)!==r.node(-1).childCount||e.key==="ArrowRight"&&r.parentOffset!==r.parent.content.size||e.key==="ArrowDown"&&!t.endOfTextblock("down")&&r.parentOffset!==r.parent.content.size?!1:tu(t.state,t.dispatch)},xL=(t,e)=>{if(!re||e.key!=="Tab"||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||!De(t.state))return!1;let n=At(t.state);if(n.bottom!==n.map.height||n.right!==n.map.width)return!1;let r=!1;return ed(t.state,i=>{t.dispatch(i),r=!0}),r&&ts(1)(t.state,t.dispatch,t),r},wL=(t,e)=>{if(!re||!De(t.state))return!1;if(e==="addRow")return ed(t.state,t.dispatch);if(e==="deleteRow")return cl(t.state,t.dispatch);if(e==="addColumn")return al(t.state,t.dispatch);if(e==="deleteColumn")return ll(t.state,t.dispatch);if(e==="header"){let{$from:n}=t.state.selection;for(let r=n.depth;r>0;r-=1){if(n.node(r).type.name!=="table")continue;let i=Math.min(n.before(r)+4,t.state.doc.content.size);return t.dispatch(t.state.tr.setSelection($.near(t.state.doc.resolve(i),1)).scrollIntoView()),!0}}return!1},Sp=t=>{t?(Me.dataset.state="open",Me.setAttribute("aria-hidden","false")):Me.dataset.state!=="closed"&&(Me.dataset.state="closed",Me.setAttribute("aria-hidden","true"))},Mp=t=>{if(Me.querySelectorAll("button").forEach(i=>{let o=ue(i.dataset.label);i.textContent=o,i.setAttribute("aria-label",o)}),!re||!De(t.state)){Sp(!1);return}let e=t.domAtPos(t.state.selection.from).node,n=(e instanceof Element?e:e.parentElement)?.closest("td, th");if(!(n instanceof HTMLElement)){Sp(!1);return}let r=n.getBoundingClientRect();Me.style.left=`${Math.max(8,Math.min(window.innerWidth-Me.offsetWidth-8,r.left))}px`,Me.style.top=`${Math.max(8,r.top-32)}px`,Sp(!0)},z0={doc:null,focusedMermaidPos:null,generation:-1,decorations:ae.empty},_0=(t,e,n)=>{let r=!1,i=Math.max(0,Math.min(t.content.size,e-1)),o=Math.max(i,Math.min(t.content.size,Math.max(n,e+1)+1));return t.nodesBetween(i,o,s=>(s.type.name==="heading"&&(r=!0),!r)),r},CL=t=>t.steps.some((e,n)=>{let r=t.docs[n],i=t.docs[n+1]||t.doc,o=!1;return e.getMap().forEach((s,a,l,c)=>{(_0(r,s,a)||_0(i,l,c))&&(o=!0)}),o}),SL=pe(()=>new X({state:{init:()=>null,apply:(t,e,n,r)=>(It(at,"transactions"),t.docChanged&&!Ep&&(Mn=c0(Mn,!0),Ie("dirtyChanged",{dirty:Mn.dirty})),t.docChanged&&CL(t)&&Up(r.doc),e)},view(t){let e={autocapitalize:"none",autocorrect:"off",spellcheck:"false"},n=new Map(Object.keys(e).map(h=>[h,t.dom.getAttribute(h)])),r=h=>{if(h.state.selection.$from.parent.type.spec.code===!0){for(let[m,g]of Object.entries(e))h.dom.setAttribute(m,g);return}for(let[m,g]of n)g===null?h.dom.removeAttribute(m):h.dom.setAttribute(m,g)},i=h=>{let m=h.state.doc;h.dom.classList.toggle("weibei-empty-document",m.childCount===1&&m.firstChild?.type.name==="paragraph"&&m.firstChild.content.size===0),h.dom.dataset.emptyPlaceholder=ue("emptyNotePlaceholder")},o=h=>{Es!==h&&(Es=h,t.dispatch(t.state.tr.setMeta("weibeiMermaidFocusChanged",h)))},s=h=>o(h.target===t.dom),a=h=>{h.target===t.dom&&o(!1)},l=()=>{zl=Zr,Pl=!1;let{$from:h}=t.state.selection;Ts=h.parent.isTextblock&&h.parent.content.size===0?h.before(h.depth):null},c=()=>{Pl=!0,setTimeout(EL)},u=h=>{h.target!==t.dom||!t.hasFocus()||!mL(t,h)&&!yL(t,h)||(h.preventDefault(),h.stopImmediatePropagation())},f=h=>{h.target===t.dom&&kL(t,h)},d=h=>h.preventDefault(),p=h=>{let m=h.target instanceof Element?h.target.closest("button[data-action]"):null;m instanceof HTMLElement&&(wL(t,m.dataset.action||""),t.focus(),window.requestAnimationFrame(()=>Mp(t)))};return t.dom.addEventListener("focus",s,!0),t.dom.addEventListener("blur",a,!0),t.dom.addEventListener("compositionstart",l,!0),t.dom.addEventListener("compositionend",c,!0),t.dom.addEventListener("keydown",u,!0),t.dom.addEventListener("beforeinput",f,!0),Me.addEventListener("mousedown",d),Me.addEventListener("click",p),document.body.appendChild(Me),r(t),i(t),Mp(t),Es=t.hasFocus(),{update(h,m){r(h),i(h),Mp(h),!h.state.doc.eq(m.doc)&&(lt(),io())},destroy(){t.dom.removeEventListener("focus",s,!0),t.dom.removeEventListener("blur",a,!0),t.dom.removeEventListener("compositionstart",l,!0),t.dom.removeEventListener("compositionend",c,!0),t.dom.removeEventListener("keydown",u,!0),t.dom.removeEventListener("beforeinput",f,!0),Me.removeEventListener("mousedown",d),Me.removeEventListener("click",p),Me.remove();for(let[h,m]of n)m===null?t.dom.removeAttribute(h):t.dom.setAttribute(h,m);Es=!1,$t=null,Ll=new WeakMap}}},props:{handlePaste:(t,e)=>{if(!re)return!1;let n=P0(e.clipboardData?.items);if(n.length>0)return e.preventDefault(),B0(n).catch(no),!0;if(DL(t))return!1;let r=e.clipboardData?.getData("text/plain")||"",i=Jn(r,"userPaste");return!r||i===r&&!e0(i)?!1:(e.preventDefault(),Rs(i),!0)},handleDrop:(t,e)=>{if(!re)return!1;let n=P0(e.dataTransfer?.items);return n.length===0?!1:(e.preventDefault(),B0(n).catch(no),!0)},handleTextInput:(t,e,n,r)=>{if(!re)return!1;let i=String(r||"");if(!i)return!1;let o=Math.min(12,e),a=`${t.state.doc.textBetween(e-o,e,` +`))},cL="#editor, .ProseMirror pre, .weibei-math-block",Cp=new WeakMap,uL=t=>{if(!(t instanceof Element))return;t.classList.add("weibei-scroll-active");let e=Cp.get(t);e&&window.clearTimeout(e),Cp.set(t,window.setTimeout(()=>{t.classList.remove("weibei-scroll-active"),Cp.delete(t)},850))},fL=()=>{document.addEventListener("scroll",t=>{let e=t.target instanceof Element?t.target.closest(cL):null;e&&uL(e)},!0)},dL=new Set(["list_item","task_list_item"]),C1=t=>(t.textContent||"").replace(/[\u200B\uFEFF]/g,"").trim(),z0=t=>{let{selection:e}=t;if(!e.empty)return null;let{$from:n}=e;for(let r=n.depth;r>0;r-=1){let i=n.node(r);if(dL.has(i.type.name))return C1(i).length>0?null:i.type}return null},pL=t=>{let{state:e}=t,{$from:n}=e.selection,r=n.parent;if(r?.isTextblock!==!0||!r.textContent||C1(r).length>0)return;let i=n.start(),o=n.end(),s=e.tr.delete(i,o);s.setSelection(B.create(s.doc,Math.min(i,s.doc.content.size))),t.dispatch(s)},hL=t=>{let e=z0(t.state);return e?(pL(t),e=z0(t.state)||e,Xa(e)(t.state,t.dispatch,t)):!1},mL=(t,e)=>{if(!re||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||!["Backspace","Delete"].includes(e.key))return!1;let{selection:n,schema:r}=t.state;return n instanceof B&&n.empty&&n.$from.parent.type.spec.code===!0&&n.$from.parent.content.size===0&&!!(r.nodes.paragraph&&Dn(r.nodes.paragraph)(t.state,t.dispatch))},gL=(t,e)=>{if(!re||e.key!=="Tab"||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof B)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(" "));return t.dispatch(r.setSelection(B.create(r.doc,n.from+1)).scrollIntoView()),!0},yL=new Set(["-","'",'"']),kL=(t,e)=>{if(!re||!yL.has(e.key)||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof B)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(e.key));return t.dispatch(r.setSelection(B.create(r.doc,n.from+e.key.length)).scrollIntoView()),!0},bL=(t,e)=>{if(!re||e.inputType!=="insertReplacementText"||e.isComposing||!e.cancelable)return!1;let{selection:n}=t.state;return!(n instanceof B)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0?!1:(e.preventDefault(),e.stopImmediatePropagation(),!0)},xL=(t,e)=>{if(!re||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||!["ArrowRight","ArrowDown"].includes(e.key))return!1;let{selection:n}=t.state;if(!(n instanceof B)||!n.empty||n.$from.parent.type.spec.code!==!0)return!1;let{$from:r}=n;return r.indexAfter(-1)!==r.node(-1).childCount||e.key==="ArrowRight"&&r.parentOffset!==r.parent.content.size||e.key==="ArrowDown"&&!t.endOfTextblock("down")&&r.parentOffset!==r.parent.content.size?!1:tu(t.state,t.dispatch)},wL=(t,e)=>{if(!re||e.key!=="Tab"||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||!De(t.state))return!1;let n=At(t.state);if(n.bottom!==n.map.height||n.right!==n.map.width)return!1;let r=!1;return ed(t.state,i=>{t.dispatch(i),r=!0}),r&&ts(1)(t.state,t.dispatch,t),r},CL=(t,e)=>{if(!re||!De(t.state))return!1;if(e==="addRow")return ed(t.state,t.dispatch);if(e==="deleteRow")return cl(t.state,t.dispatch);if(e==="addColumn")return al(t.state,t.dispatch);if(e==="deleteColumn")return ll(t.state,t.dispatch);if(e==="header"){let{$from:n}=t.state.selection;for(let r=n.depth;r>0;r-=1){if(n.node(r).type.name!=="table")continue;let i=Math.min(n.before(r)+4,t.state.doc.content.size);return t.dispatch(t.state.tr.setSelection($.near(t.state.doc.resolve(i),1)).scrollIntoView()),!0}}return!1},Sp=t=>{t?(Ee.dataset.state="open",Ee.setAttribute("aria-hidden","false")):Ee.dataset.state!=="closed"&&(Ee.dataset.state="closed",Ee.setAttribute("aria-hidden","true"))},Mp=t=>{if(Ee.querySelectorAll("button").forEach(i=>{let o=ue(i.dataset.label);i.textContent=o,i.setAttribute("aria-label",o)}),!re||!De(t.state)){Sp(!1);return}let e=t.domAtPos(t.state.selection.from).node,n=(e instanceof Element?e:e.parentElement)?.closest("td, th");if(!(n instanceof HTMLElement)){Sp(!1);return}let r=n.getBoundingClientRect();Ee.style.left=`${Math.max(8,Math.min(window.innerWidth-Ee.offsetWidth-8,r.left))}px`,Ee.style.top=`${Math.max(8,r.top-32)}px`,Sp(!0)},_0={doc:null,focusedMermaidPos:null,generation:-1,decorations:ae.empty},$0=(t,e,n)=>{let r=!1,i=Math.max(0,Math.min(t.content.size,e-1)),o=Math.max(i,Math.min(t.content.size,Math.max(n,e+1)+1));return t.nodesBetween(i,o,s=>(s.type.name==="heading"&&(r=!0),!r)),r},SL=t=>t.steps.some((e,n)=>{let r=t.docs[n],i=t.docs[n+1]||t.doc,o=!1;return e.getMap().forEach((s,a,l,c)=>{($0(r,s,a)||$0(i,l,c))&&(o=!0)}),o}),ML=pe(()=>new X({state:{init:()=>null,apply:(t,e,n,r)=>(It(at,"transactions"),t.docChanged&&!Tp&&(Mn=u0(Mn,!0),ye("dirtyChanged",{dirty:Mn.dirty})),t.docChanged&&SL(t)&&Jp(r.doc),e)},view(t){let e={autocapitalize:"none",autocorrect:"off",spellcheck:"false"},n=new Map(Object.keys(e).map(h=>[h,t.dom.getAttribute(h)])),r=h=>{if(h.state.selection.$from.parent.type.spec.code===!0){for(let[m,g]of Object.entries(e))h.dom.setAttribute(m,g);return}for(let[m,g]of n)g===null?h.dom.removeAttribute(m):h.dom.setAttribute(m,g)},i=h=>{let m=h.state.doc;h.dom.classList.toggle("weibei-empty-document",m.childCount===1&&m.firstChild?.type.name==="paragraph"&&m.firstChild.content.size===0),h.dom.dataset.emptyPlaceholder=ue("emptyNotePlaceholder")},o=h=>{Es!==h&&(Es=h,t.dispatch(t.state.tr.setMeta("weibeiMermaidFocusChanged",h)))},s=h=>o(h.target===t.dom),a=h=>{h.target===t.dom&&o(!1)},l=()=>{zl=Zr,Pl=!1;let{$from:h}=t.state.selection;Ts=h.parent.isTextblock&&h.parent.content.size===0?h.before(h.depth):null},c=()=>{Pl=!0,setTimeout(TL)},u=h=>{h.target!==t.dom||!t.hasFocus()||!gL(t,h)&&!kL(t,h)||(h.preventDefault(),h.stopImmediatePropagation())},f=h=>{h.target===t.dom&&bL(t,h)},d=h=>h.preventDefault(),p=h=>{let m=h.target instanceof Element?h.target.closest("button[data-action]"):null;m instanceof HTMLElement&&(CL(t,m.dataset.action||""),t.focus(),window.requestAnimationFrame(()=>Mp(t)))};return t.dom.addEventListener("focus",s,!0),t.dom.addEventListener("blur",a,!0),t.dom.addEventListener("compositionstart",l,!0),t.dom.addEventListener("compositionend",c,!0),t.dom.addEventListener("keydown",u,!0),t.dom.addEventListener("beforeinput",f,!0),Ee.addEventListener("mousedown",d),Ee.addEventListener("click",p),document.body.appendChild(Ee),r(t),i(t),Mp(t),Es=t.hasFocus(),{update(h,m){r(h),i(h),Mp(h),!h.state.doc.eq(m.doc)&&(lt(),io())},destroy(){t.dom.removeEventListener("focus",s,!0),t.dom.removeEventListener("blur",a,!0),t.dom.removeEventListener("compositionstart",l,!0),t.dom.removeEventListener("compositionend",c,!0),t.dom.removeEventListener("keydown",u,!0),t.dom.removeEventListener("beforeinput",f,!0),Ee.removeEventListener("mousedown",d),Ee.removeEventListener("click",p),Ee.remove();for(let[h,m]of n)m===null?t.dom.removeAttribute(h):t.dom.setAttribute(h,m);Es=!1,$t=null,Ll=new WeakMap}}},props:{handlePaste:(t,e)=>{if(!re)return!1;let n=B0(e.clipboardData?.items);if(n.length>0)return e.preventDefault(),F0(n).catch(no),!0;if(LL(t))return!1;let r=e.clipboardData?.getData("text/plain")||"",i=Jn(r,"userPaste");return!r||i===r&&!t0(i)?!1:(e.preventDefault(),Rs(i),!0)},handleDrop:(t,e)=>{if(!re)return!1;let n=B0(e.dataTransfer?.items);return n.length===0?!1:(e.preventDefault(),F0(n).catch(no),!0)},handleTextInput:(t,e,n,r)=>{if(!re)return!1;let i=String(r||"");if(!i)return!1;let o=Math.min(12,e),a=`${t.state.doc.textBetween(e-o,e,` `,` -`)}${i}`.match(/<br\s*\/?>$/i);if(!a)return!1;let l=t.state.schema.nodes.hardbreak||t.state.schema.nodes.hard_break;if(!l)return!1;let c=e-(a[0].length-i.length),u=t.state.tr.replaceWith(c,n,l.create()).scrollIntoView();return u.setSelection(B.create(u.doc,Math.min(c+1,u.doc.content.size))),t.dispatch(u),!0},handleClick(t,e,n){return g1(n.target)||m1(n.target)||Pp(n.target)||Bp(n.target)||y1(n.target)},handleKeyDown(t,e){if(xL(t,e))return e.preventDefault(),!0;if(CD(t,e))return!0;if(e.key==="Enter"&&t.state.selection instanceof H){let r=t.state.selection.node;if(r.type.name==="math_inline"||r.type.name==="math_block")return t.nodeDOM(t.state.selection.from)?.dispatchEvent(new CustomEvent("weibei-edit-math")),e.preventDefault(),!0}if(hL(t,e)||bL(t,e)||e.key==="Enter"&&re&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey&&pL(t))return e.preventDefault(),!0;if(e.key!=="Enter"&&e.key!==" ")return!1;if(Bp(e.target))return e.preventDefault(),!0;if(!e.metaKey&&!e.ctrlKey)return!1;let n=tL();return n?(Ie("wikiLinkActivated",{title:n}),e.preventDefault(),!0):!1},decorations(t){let e=WD(t);jD(e);let n=e?.pos??null,r=z0;if(r.doc===t.doc&&r.focusedMermaidPos===n&&r.generation===Yr)return It(at,"decorationCacheHits"),r.decorations;let i=[],o={open:!1},s=new Map,a=new Map;t.doc.descendants((c,u,f)=>{if(It(at,"decorationNodes"),c.type.name==="code_block")return qD(i,c,u,e)||(i.push(le.node(u,u+c.nodeSize,{class:"weibei-code-block","data-language":c.attrs.language||""})),QD(i,c,u)),!1;if(c.isText){let p=u,h=c.text||"";if((c.marks||[]).some(g=>g.type.name.toLowerCase().includes("code"))||xe!==null)return!0;HD(i,h,p),_D(i,h,p,o),zD(i,h,p),$D(i,h,p),FD(i,h,p,s),BD(i,h,p,a)}return!0});let l=ae.create(t.doc,i);return z0={doc:t.doc,focusedMermaidPos:n,generation:Yr,decorations:l},l}}})),to=()=>{if(window.weiBeiSuppressSelectionReport)return;let t=DD(),e=t?TD():null,n=t&&V?V.action(o=>{let{state:s}=o.get(U),{selection:a}=s,c=["strong","emphasis","highlight","link","inlineCode"].filter(y=>s.schema.marks[y]&&s.doc.rangeHasMark(a.from,a.to,s.schema.marks[y])),u=s.schema.marks.writing_font,f,d=!1;u&&s.doc.nodesBetween(a.from,a.to,y=>{if(!y.isText)return!0;let b=u.isInSet(y.marks||[])?.attrs.font||"serif";return f===void 0?f=b:f!==b&&(d=!0),!0}),f&&!d&&c.push(`font:${f}`);let p=a instanceof H&&a.node.type.name==="math_inline";p&&c.push("inlineMath");let h=a.$from.parent.type.name;for(let y=a.$from.depth;y>0;y-=1){let b=a.$from.node(y).type.name;if(b==="blockquote"||b==="block_quote"){h="blockquote";break}}h==="heading"&&(h=`heading${a.$from.parent.attrs.level||""}`);let m="",g=s.schema.marks.link;return g&&s.doc.nodesBetween(a.from,a.to,y=>{let b=g.isInSet(y.marks||[]);return b&&!m&&(m=String(b.attrs.href||"")),!m}),{activeMarks:c,blockType:h,canConvertToMath:p||a instanceof B&&!a.empty&&a.$from.parent===a.$to.parent&&a.$from.parent.isTextblock,linkTarget:m}}):{activeMarks:[],blockType:"",canConvertToMath:!1,linkTarget:""},r=e?`${Math.round(e.x)}:${Math.round(e.y)}:${Math.round(e.width)}:${Math.round(e.height)}`:"",i=JSON.stringify(n);if(!(t===Qi.text&&r===Qi.rectKey&&i===Qi.detailKey)){if(Qi={text:t,rectKey:r,detailKey:i},!t){Zt=null,Ie("selectionChanged",{text:"",rect:null,...n});return}Zt=jp(),Ie("selectionChanged",{text:t,rect:e,...n})}},C1=(t,e="")=>!V||!re||typeof t!="string"?!1:V.action(n=>{let r=n.get(U);if(r.state.selection.empty&&Zt){let l=Math.min(Zt.from,r.state.doc.content.size),c=Math.min(Zt.to,r.state.doc.content.size);l<c&&r.dispatch(r.state.tr.setSelection(B.create(r.state.doc,l,c)))}let{state:i}=r,{selection:o}=i;if(o.empty)return!1;let s=!1,a=l=>{let c=i.schema.marks[l];return!!(c&&Ln(c)(r.state,r.dispatch,r))};switch(t){case"bold":s=a("strong");break;case"italic":s=a("emphasis");break;case"highlight":s=a("highlight");break;case"inlineCode":s=a("inlineCode");break;case"font":{let l=typeof e=="string"&&Z0.has(e)?e:"",c=i.schema.marks.writing_font;if(!l||!c)break;let u=i.tr.removeMark(o.from,o.to,c).addMark(o.from,o.to,c.create({font:l}));r.dispatch(u.scrollIntoView()),s=!0;break}case"link":{let l=i.schema.marks.link;if(!l)break;let c=typeof e=="string"?e.trim():"",u=i.tr.removeMark(o.from,o.to,l);c&&u.addMark(o.from,o.to,l.create({href:c})),r.dispatch(u.scrollIntoView()),s=!0;break}case"inlineMath":{let l=i.schema.nodes.math_inline,c=o instanceof H?o.node:i.doc.nodeAt(o.from);if(c?.type===l&&o.to===o.from+c.nodeSize){let p=c.textContent,h=us(p?i.tr.replaceWith(o.from,o.to,i.schema.text(p)):i.tr.delete(o.from,o.to));h.setSelection(p?B.create(h.doc,o.from,o.from+p.length):$.near(h.doc.resolve(Math.min(o.from,h.doc.content.size)))),r.dispatch(h.scrollIntoView()),s=!0;break}let u=i.doc.textBetween(o.from,o.to,` +`)}${i}`.match(/<br\s*\/?>$/i);if(!a)return!1;let l=t.state.schema.nodes.hardbreak||t.state.schema.nodes.hard_break;if(!l)return!1;let c=e-(a[0].length-i.length),u=t.state.tr.replaceWith(c,n,l.create()).scrollIntoView();return u.setSelection(B.create(u.doc,Math.min(c+1,u.doc.content.size))),t.dispatch(u),!0},handleClick(t,e,n){return y1(n.target)||g1(n.target)||Bp(n.target)||Fp(n.target)||k1(n.target)},handleKeyDown(t,e){if(wL(t,e))return e.preventDefault(),!0;if(SD(t,e))return!0;if(e.key==="Enter"&&t.state.selection instanceof H){let r=t.state.selection.node;if(r.type.name==="math_inline"||r.type.name==="math_block")return t.nodeDOM(t.state.selection.from)?.dispatchEvent(new CustomEvent("weibei-edit-math")),e.preventDefault(),!0}if(mL(t,e)||xL(t,e)||e.key==="Enter"&&re&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey&&hL(t))return e.preventDefault(),!0;if(e.key!=="Enter"&&e.key!==" ")return!1;if(Fp(e.target))return e.preventDefault(),!0;if(!e.metaKey&&!e.ctrlKey)return!1;let n=nL();return n?(ye("wikiLinkActivated",{title:n}),e.preventDefault(),!0):!1},decorations(t){let e=jD(t);VD(e);let n=e?.pos??null,r=_0;if(r.doc===t.doc&&r.focusedMermaidPos===n&&r.generation===Yr)return It(at,"decorationCacheHits"),r.decorations;let i=[],o={open:!1},s=new Map,a=new Map;t.doc.descendants((c,u,f)=>{if(It(at,"decorationNodes"),c.type.name==="code_block")return KD(i,c,u,e)||(i.push(le.node(u,u+c.nodeSize,{class:"weibei-code-block","data-language":c.attrs.language||""})),ZD(i,c,u)),!1;if(c.isText){let p=u,h=c.text||"";if((c.marks||[]).some(g=>g.type.name.toLowerCase().includes("code"))||we!==null)return!0;WD(i,h,p),$D(i,h,p,o),_D(i,h,p),HD(i,h,p),zD(i,h,p,s),FD(i,h,p,a)}return!0});let l=ae.create(t.doc,i);return _0={doc:t.doc,focusedMermaidPos:n,generation:Yr,decorations:l},l}}})),to=()=>{if(window.weiBeiSuppressSelectionReport)return;let t=LD(),e=t?vD():null,n=t&&V?V.action(o=>{let{state:s}=o.get(U),{selection:a}=s,c=["strong","emphasis","highlight","link","inlineCode"].filter(y=>s.schema.marks[y]&&s.doc.rangeHasMark(a.from,a.to,s.schema.marks[y])),u=s.schema.marks.writing_font,f,d=!1;u&&s.doc.nodesBetween(a.from,a.to,y=>{if(!y.isText)return!0;let b=u.isInSet(y.marks||[])?.attrs.font||"serif";return f===void 0?f=b:f!==b&&(d=!0),!0}),f&&!d&&c.push(`font:${f}`);let p=a instanceof H&&a.node.type.name==="math_inline";p&&c.push("inlineMath");let h=a.$from.parent.type.name;for(let y=a.$from.depth;y>0;y-=1){let b=a.$from.node(y).type.name;if(b==="blockquote"||b==="block_quote"){h="blockquote";break}}h==="heading"&&(h=`heading${a.$from.parent.attrs.level||""}`);let m="",g=s.schema.marks.link;return g&&s.doc.nodesBetween(a.from,a.to,y=>{let b=g.isInSet(y.marks||[]);return b&&!m&&(m=String(b.attrs.href||"")),!m}),{activeMarks:c,blockType:h,canConvertToMath:p||a instanceof B&&!a.empty&&a.$from.parent===a.$to.parent&&a.$from.parent.isTextblock,linkTarget:m}}):{activeMarks:[],blockType:"",canConvertToMath:!1,linkTarget:""},r=e?`${Math.round(e.x)}:${Math.round(e.y)}:${Math.round(e.width)}:${Math.round(e.height)}`:"",i=JSON.stringify(n);if(!(t===Qi.text&&r===Qi.rectKey&&i===Qi.detailKey)){if(Qi={text:t,rectKey:r,detailKey:i},!t){Zt=null,ye("selectionChanged",{text:"",rect:null,...n});return}Zt=Vp(),ye("selectionChanged",{text:t,rect:e,...n})}},S1=(t,e="")=>!V||!re||typeof t!="string"?!1:V.action(n=>{let r=n.get(U);if(r.state.selection.empty&&Zt){let l=Math.min(Zt.from,r.state.doc.content.size),c=Math.min(Zt.to,r.state.doc.content.size);l<c&&r.dispatch(r.state.tr.setSelection(B.create(r.state.doc,l,c)))}let{state:i}=r,{selection:o}=i;if(o.empty)return!1;let s=!1,a=l=>{let c=i.schema.marks[l];return!!(c&&Ln(c)(r.state,r.dispatch,r))};switch(t){case"bold":s=a("strong");break;case"italic":s=a("emphasis");break;case"highlight":s=a("highlight");break;case"inlineCode":s=a("inlineCode");break;case"font":{let l=typeof e=="string"&&e1.has(e)?e:"",c=i.schema.marks.writing_font;if(!l||!c)break;let u=i.tr.removeMark(o.from,o.to,c).addMark(o.from,o.to,c.create({font:l}));r.dispatch(u.scrollIntoView()),s=!0;break}case"link":{let l=i.schema.marks.link;if(!l)break;let c=typeof e=="string"?e.trim():"",u=i.tr.removeMark(o.from,o.to,l);c&&u.addMark(o.from,o.to,l.create({href:c})),r.dispatch(u.scrollIntoView()),s=!0;break}case"inlineMath":{let l=i.schema.nodes.math_inline,c=o instanceof H?o.node:i.doc.nodeAt(o.from);if(c?.type===l&&o.to===o.from+c.nodeSize){let p=c.textContent,h=us(p?i.tr.replaceWith(o.from,o.to,i.schema.text(p)):i.tr.delete(o.from,o.to));h.setSelection(p?B.create(h.doc,o.from,o.from+p.length):$.near(h.doc.resolve(Math.min(o.from,h.doc.content.size)))),r.dispatch(h.scrollIntoView()),s=!0;break}let u=i.doc.textBetween(o.from,o.to,` `,` -`);if(!l||!u||!(o instanceof B)||o.$from.parent!==o.$to.parent)break;let f=l.create(null,i.schema.text(u)),d=us(i.tr.replaceRangeWith(o.from,o.to,f));d.setSelection(H.create(d.doc,o.from)),r.dispatch(d.scrollIntoView()),s=!0;break}case"quote":{let l=i.schema.nodes.blockquote||i.schema.nodes.block_quote;if(!l)break;s=!!(Array.from({length:o.$from.depth},(u,f)=>o.$from.node(f+1)).some(u=>u.type===l)?Dg:yi(l))(r.state,r.dispatch,r);break}default:return!1}return s&&(r.focus(),window.requestAnimationFrame(to)),s}),En=()=>{if(!V)throw new Error("WeiBei editor is not ready")},S1=t=>{vp=LD(t),Yr+=1,V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},M1=t=>{Ap=PD(t),Yr+=1,V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},ML=()=>{if(!V||Ts===null)return;let t=Ts;Ts=null,V.action(e=>{let n=e.get(U);n.domObserver?.flush();let r=n.state.doc.nodeAt(t);if(!r?.isTextblock||!r.textContent)return;let i=n.state.schema.nodes.hardbreak||n.state.schema.nodes.hard_break,o=[];for(let a=0;a<r.childCount;a+=1){let l=r.child(a);l.type!==i&&o.push(l)}if(o.length!==r.childCount){let a=r.type.create(r.attrs,M.fromArray(o),r.marks),l=n.state.tr.replaceWith(t,t+r.nodeSize,a).scrollIntoView();l.setSelection(B.create(l.doc,Math.min(t+1+a.content.size,l.doc.content.size))),n.dispatch(l)}let s=n.nodeDOM(t);s instanceof HTMLElement&&(s.querySelectorAll("br").forEach(a=>a.remove()),n.domObserver?.flush())})},EL=()=>{V&&(ML(),Pl=!1,zl=null,lt(),io())},Ps=()=>V.action(t=>t.get(Q)),TL=(t=!0)=>{$l(),xe!==null&&(Ps().call(ms.key,{keep:t}),xe=null,Qt=null,so=null)},E1=t=>{En(),$l();let e=String(t||"");so=e;let n=Ms(e);oo=n.frontmatter,Ls();let r=n.body,i=Qt!==null&&xe===Qt&&r.startsWith(Qt)?r.slice(Qt.length):null,o;i!==null&&!/[$<>\\`\r]/.test(i)?(o=r,Qt=r):(o=Jn(r,"agentGenerated"),Qt=o===r?r:null,Zr=Ds(o));let s=Ps();xe===null?(s.call($r.key),xe=""):o.startsWith(xe)||(s.call(Gi.key,{diffReview:!1}),s.call($r.key),xe="");let a=o.slice(xe.length);a&&s.call(hs.key,a),xe=o,lt()},vL=t=>{let e=String(t||"");if(!e)return;let n=so;E1(n===null?e:n+e)},Ur=null,AL=24,IL=12,$0=33,NL=3e3,RL=240,$l=()=>{Ur!=null&&(window.clearTimeout(Ur),Ur=null)},H0=t=>{let e=Ps();xe===null?(e.call($r.key),xe=""):t.startsWith(xe)||(e.call(Gi.key,{diffReview:!1}),e.call($r.key),xe="");let n=t.slice(xe.length);n&&e.call(hs.key,n),xe=t,lt()},W0=()=>{Ps().call(Gi.key,{diffReview:!1}),Qt=null,xe=null,so=null,$l();try{V?.action(t=>{t.get(U).updateState(t.get(U).state)})}catch{}Op(),lt()},OL=(t,e)=>{$l(),Qt=null;let n=String(t||""),r=Ms(n);oo=r.frontmatter,Ls();let i=Jn(r.body,"agentGenerated");Zr=Ds(i),so=n;let o=xe,s=e?.paced===!0&&o!==null&&i.startsWith(o)&&i.length-o.length>AL;if(o!==null&&s){let a=o.length,l=0,c=Date.now(),u=()=>{Ur=null;let f=Date.now();l+=1,a=Math.min(i.length,a+IL);let d=a>=i.length||f-c>=NL||l>=RL;try{if(H0(d?i:i.slice(0,a)),!d){Ur=window.setTimeout(u,$0);return}W0()}catch{Ur=null,xe=null,Qt=null;try{Ps().call(ms.key,{keep:!1})}catch{}try{qp(n)}catch{}lt()}};Ur=window.setTimeout(u,$0),lt();return}H0(i),W0()},qp=t=>{En(),TL(),so=null,zl=null,Ts=null,Pl=!1,Xn+=1;let e=Ms(t||""),n=Jn(e.body,"userDocument");oo=e.frontmatter,Ls(),V.action(Lk(n)),Zr=Ds(n),V.action(r=>Up(r.get(U).state.doc)),lt()},j0=(t,e=0,n=!1)=>{Ep=!0,Mn={revision:e,dirty:n};try{qp(t)}finally{Ep=!1}Ie("dirtyChanged",{dirty:n})},T1=()=>(En(),It(at,"fullSerializations"),Ds(V.action(Dk()))),DL=t=>{let e=t?.state?.selection;return e?.$from?e.$from.parent.type.spec.code?!0:(e.$from.marks()||[]).some(r=>String(r?.type?.name||"").toLowerCase().includes("code")):!1},Rs=t=>{En();let e=Jn(t||"","internalFragment"),n=Zt||jp();n?V.action(Qu(e,n)):V.action(Yu(e)),Zt=null},Kp=(t,e="internalFragment")=>{En();let n=jp(),r=rL(Jn(t,e));n?V.action(Qu(r,n)):V.action(Yu(r)),iL()||oL(),Zt=null},v1=t=>{En(),V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setSelection($.atEnd(n.state.doc)))}),Kp(t,"agentGenerated")},LL=t=>(En(),!window.weiBeiEditorCheckMode||!t?!1:V.action(e=>{let n=e.get(U),r=null;return n.state.doc.descendants((i,o)=>{if(!i.isText||r)return!0;let s=(i.text||"").indexOf(t);return s<0?!0:(r={from:o+s,to:o+s+t.length},!1)}),r?(n.dispatch(n.state.tr.setSelection(B.create(n.state.doc,r.from,r.to))),Zt=r,!0):!1})),PL=t=>(En(),window.weiBeiEditorCheckMode?V.action(e=>{let n=e.get(U);n.focus();for(let r of String(t||"")){let{from:i,to:o}=n.state.selection,s=!1;n.someProp("handleTextInput",a=>s?!0:(s=a(n,i,o,r)===!0,s)),s||n.dispatch(n.state.tr.insertText(r,i,o))}return!0}):!1),BL=(t,e={})=>(En(),window.weiBeiEditorCheckMode?V.action(n=>{let r=n.get(U);r.focus();let i=new KeyboardEvent("keydown",{key:t,bubbles:!0,cancelable:!0,shiftKey:e.shiftKey===!0,altKey:e.altKey===!0,metaKey:e.metaKey===!0,ctrlKey:e.ctrlKey===!0});return r.dom.dispatchEvent(i),!0}):!1),A1=()=>Array.from(document.querySelectorAll(".ProseMirror h1, .ProseMirror h2, .ProseMirror h3, .ProseMirror h4, .ProseMirror h5, .ProseMirror h6")),V0=0,Dl=-2,Fp=null,Up=t=>{let e=[],n=Math.max(1,t.content.size);t.descendants((i,o)=>{if(i.type.name!=="heading")return!0;let s=i.textContent.trim();if(!s)return!1;let a=e.length;return e.push({id:`note-heading-${a}`,index:a,level:Number(i.attrs.level||1),title:s,position:Math.max(0,Math.min(1,o/n))}),!1});let r=o0(e);r!==Fp&&(Fp=r,It(at,"outlineReports"),Ie("outlineChanged",{items:e}))},io=()=>{window.cancelAnimationFrame(V0),V0=window.requestAnimationFrame(()=>{let t=A1();if(t.length===0){Dl!==-1&&(Dl=-1,Ie("activeHeadingChanged",{index:null}));return}let e=Math.max(0,window.innerHeight*.32),n=0;t.forEach((r,i)=>{r.getBoundingClientRect().top<=e&&(n=i)}),n!==Dl&&(Dl=n,Ie("activeHeadingChanged",{index:n}))})},Jp=t=>{let e=Number(t),n=A1(),r=Number.isFinite(e)?n[Math.max(0,Math.floor(e))]:null;if(!r)return!1;let i=Np();return r.scrollIntoView({block:"start",behavior:i?"auto":"smooth"}),i?io():window.setTimeout(io,180),!0},I1=(t,e)=>{let n=t!==nt||e!==Ve;nt=t,Ve=e,n&&(Fp=null,Xn+=1,_t.clear(),Gn.clear(),S1([]),M1([]))},N1=t=>{re=t!==!1,Wp(),V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiEditableChanged",re))})},Gp=t=>{Q0(t),Yr+=1,p1(),V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiThemeChanged",eo))})},Xp=t=>{Jr=G0(t),Yr+=1,document.documentElement.dataset.weibeiLanguage=Jr,Ls(),Wp(),Ns.forEach(e=>e()),G.dataset.show==="true"&&Is(),V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiLanguageChanged",Jr))})},Yp=()=>V?(V.action(t=>t.get(U).focus()),!0):!1,kt=(t,e)=>t.payload[e]??t.payload.value,FL=t=>{let e=a0(t);if(!e||!l0(e,{documentID:nt,documentGeneration:Ve,revision:Mn.revision}))return!1;switch(e.type){case"loadDocument":{let n=kt(e,"markdown"),r=kt(e,"initialRevision");return typeof n!="string"||r!==void 0&&!Number.isInteger(r)?!1:(I1(e.documentID,e.documentGeneration),j0(n,Number(r??0)),!0)}case"requestSnapshot":{let n=T1();return Zr=n,Ie("snapshotReady",{requestID:e.requestID,markdown:n}),!0}case"setTheme":return Gp(kt(e,"theme")),!0;case"setLanguage":return Xp(kt(e,"language")),!0;case"setEditable":return N1(kt(e,"editable")),!0;case"focus":return Yp();case"scrollToHeading":return Jp(kt(e,"index"));case"applyMarkdownFragment":{let n=kt(e,"markdown");return typeof n!="string"?!1:(v1(n),!0)}case"replaceSelection":{let n=kt(e,"markdown");return typeof n!="string"?!1:(Rs(n),!0)}case"executeSelectionCommand":return C1(kt(e,"action"),kt(e,"value"));case"insertStructuredBlock":{let n=kt(e,"markdown");return typeof n!="string"?!1:(Kp(n),!0)}case"restoreCheckpoint":{let n=kt(e,"markdown"),r=kt(e,"revision");return typeof n!="string"||r!==void 0&&(!Number.isInteger(r)||Number(r)<0)?!1:(j0(n,r===void 0?Mn.revision:Number(r),!0),!0)}}};window.WeiBeiEditor={dispatchCommand:FL,resolveAttachment:(t,e,n)=>{let r=Gn.get(t);r&&(Gn.delete(t),r.resolve({src:e,alt:n}))},rejectAttachment:(t,e)=>{let n=Gn.get(t);n&&(Gn.delete(t),n.reject(new Error(e||"Attachment save failed")))},resolveImagePicker:(t,e,n)=>{let r=_t.get(t);if(!r||(_t.delete(t),r.documentID!==nt||r.documentGeneration!==Ve))return!1;if(r.mode==="replace"){let i=r.getPos(),o=typeof i=="number"?r.view.state.doc.nodeAt(i):null;if(o?.type.name!=="image")return!1;let s=Fl(o.attrs.alt||"").size,a=`${String(n||"image")}${s?`|${s.width}${s.height?`x${s.height}`:""}`:""}`;return r.view.dispatch(r.view.state.tr.setNodeMarkup(i,void 0,{...o.attrs,src:e,alt:a}).scrollIntoView()),r.view.focus(),!0}return o1(r.view,r.context,_p("image",r.view.state.schema,{src:e,alt:n}))},cancelImagePicker:t=>{let e=_t.get(t);return e?(_t.delete(t),e.mode==="replace"&&e.view.focus(),e.documentID===nt&&e.documentGeneration===Ve):!1},discardImagePicker:t=>_t.delete(t),rejectImagePicker:(t,e)=>{let n=_t.get(t);return!n||(_t.delete(t),n.documentID!==nt||n.documentGeneration!==Ve)?!1:n.mode==="replace"?(n.view.focus(),!0):(I.dismissedContext="",I.error=e||ue("slashImageFailed"),I.view=n.view,I.provider?.show(),Is(),!0)},setTheme:Gp,setInterfaceLanguage:Xp,setReduceMotion:t1,setTextScale:n1,focus:Yp,scrollToHeading:Jp,setSelectionAskMarks:S1,setSelectionRemarkMarks:M1,setMarkdownBaseURL:t=>{U0=t||"",p1()}};window.weiBeiEditorCheckMode&&(Object.assign(window.WeiBeiEditor,{getMarkdown:T1,setMarkdown:qp,updateStreamingMarkdown:E1,appendStreamingMarkdown:vL,finishStreamingMarkdown:(t,e)=>(OL(t,e),!0),replaceSelection:Rs,executeSelectionCommand:C1,applyAgentPatch:v1,insertMarkdownImage:Rs,insertMarkdown:Kp,setEditable:N1,setDocumentID:t=>I1(String(t||""),Ve+1),setTheme:Gp,setInterfaceLanguage:Xp,setReduceMotion:t1,setTextScale:n1,focus:Yp,scrollToHeading:Jp}),window.WeiBeiEditor.getCheckMetrics=()=>({...at,fullBridgeMessages:Tp}),window.WeiBeiEditor.resetCheckMetrics=()=>{i0(at),Tp=0},window.WeiBeiEditor.getBridgeSessionForCheck=()=>({protocolVersion:2,documentID:nt,documentGeneration:Ve,revision:Mn.revision,dirty:Mn.dirty}),window.WeiBeiEditor.selectFirstTextForCheck=LL,window.WeiBeiEditor.selectedTextForCheck=h1,window.WeiBeiEditor.typeTextForCheck=PL,window.WeiBeiEditor.pressKeyForCheck=BL,window.WeiBeiEditor.compositionStateForCheck=()=>({start:zl,last:Zr,composing:V.action(t=>t.get(U).composing)}),window.WeiBeiEditor.openSlashMenuForCheck=()=>{let t=I.view;return!t||!ro(t)?!1:(I.dismissedContext="",I.provider?.show(),Is(),G.dataset.show==="true")},window.WeiBeiEditor.slashStateForCheck=()=>({show:G.dataset.show==="true",commands:Array.from(G.querySelectorAll(".weibei-slash-command-button")).map(t=>t.textContent),groups:Array.from(G.querySelectorAll(".weibei-slash-group")).map(t=>t.textContent),rows:I.tableRows,columns:I.tableColumns,tableOpen:I.tableOpen,tableSide:As?.dataset.side||"",activeDescendant:I.view?.dom.getAttribute("aria-activedescendant")||"",announcement:Gr.textContent,error:I.error}),window.WeiBeiEditor.renderSlashMenuForCheck=Is,window.WeiBeiEditor.executeSlashCommandForCheck=t=>Xr(t),window.WeiBeiEditor.pendingImagePickerIDsForCheck=()=>Array.from(_t.keys()),window.WeiBeiEditor.undoForCheck=()=>V.action(t=>fs(t.get(U).state,t.get(U).dispatch)),window.WeiBeiEditor.redoForCheck=()=>V.action(t=>ds(t.get(U).state,t.get(U).dispatch)),window.WeiBeiEditor.selectFirstCodeBlockEndForCheck=()=>V.action(t=>{let e=t.get(U),n=null;return e.state.doc.descendants((r,i)=>n!==null||r.type.name!=="code_block"?!0:(n=i+r.content.size+1,!1)),n===null?!1:(e.dispatch(e.state.tr.setSelection(B.create(e.state.doc,n))),e.focus(),!0)}),window.WeiBeiEditor.selectDocumentEndForCheck=()=>V.action(t=>{let e=t.get(U);return e.dispatch(e.state.tr.setSelection($.atEnd(e.state.doc))),e.focus(),!0}),window.WeiBeiEditor.selectionForCheck=()=>V.action(t=>{let e=t.get(U).state.selection;return{from:e.from,to:e.to,parent:e.$from.parent.type.name,parentOffset:e.$from.parentOffset}}));var Os=Ms(window.initialMarkdown||"");Os.body=Jn(Os.body,"userDocument");oo=Os.frontmatter;Zr=Ds(Os.body);Ls();var Qr=Ik.make().config(t=>{t.set(Go,document.querySelector("#editor")),t.set(Ko,Os.body),t.set(Or,{editable:()=>re,nodeViews:{code_block:ZD,image:OD,math_inline:L0,math_block:L0,wiki_link:wp,embed:wp,inline_footnote:wp,callout:eL}}),t.set(qn.key,{throttleMs:0,scrollFollow:!1,diffReviewOnEnd:!1,ignoreAttrs:{heading:["id"]}})});Qr=Qr.config(t=>{t.set(Kr.key,{uploader:sL,enableHtmlFileUploader:!0,uploadWidgetFactory:(e,n)=>{let r=document.createElement("span");return r.className="weibei-uploading",r.textContent=ue("uploadingImage"),le.widget(e,r,n)}}),t.set(J0.key,{view(e){let n=l=>l.preventDefault(),r=()=>{let l=r1(e);l&&(e.dispatch(e.state.tr.insertText("/",l.pos).scrollIntoView()),e.focus(),I.dismissedContext="")};st.addEventListener("mousedown",n),st.addEventListener("click",r),document.body.append(Gr,st);let i=new _w({content:G,debounce:0,offset:6,root:document.body,shouldShow:l=>{let c=ro(l);return!!(c&&I.dismissedContext!==c.key)}});I.provider=i,I.view=e;let o=i.show.bind(i),s=i.hide.bind(i),a=l=>{Pe.generation===l&&(Pe.state="closed",G.dataset.state="closed",s())};return i.show=()=>{if(Pe.generation+=1,window.clearTimeout(Pe.timer),window.weiBeiEditorCheckMode||Np()){Pe.state="open",G.dataset.state="open",o();return}o(),Pe.state="opening",G.dataset.state="opening";let l=Pe.generation;Pe.frame=window.requestAnimationFrame(()=>{Pe.generation===l&&(Pe.state="open",G.dataset.state="open")})},i.hide=()=>{if(Pe.generation+=1,window.clearTimeout(Pe.timer),window.cancelAnimationFrame(Pe.frame),G.dataset.show!=="true"||window.weiBeiEditorCheckMode||Np()){a(Pe.generation);return}Pe.state="closing",G.dataset.state="closing",G.setAttribute("aria-hidden","true");let l=Pe.generation,c=()=>{Pe.generation===l&&(G.removeAttribute("aria-hidden"),a(l))};G.addEventListener("transitionend",function u(f){f.target!==G||f.propertyName!=="opacity"||(G.removeEventListener("transitionend",u),c())}),Pe.timer=window.setTimeout(c,200)},i.onShow=()=>{I.view=e,Is()},i.onHide=()=>{I.context=null,I.tableOpen=!1,s1(),$p()},i.update(e),E0(e),{update(l,c){I.view=l;let u=ro(l);I.dismissedContext&&u?.key!==I.dismissedContext&&(I.dismissedContext=""),i.update(l,c),E0(l)},destroy(){i.destroy(),st.removeEventListener("mousedown",n),st.removeEventListener("click",r),G.remove(),Gr.remove(),st.remove(),As?.remove(),I.provider=null,I.view=null}}}})});Qr=Qr.use(SL).use(ab).use(Ax).use(b0).use(aD).use(lw).use(pe(()=>uw(()=>xe!==null)));Qr=Qr.use(J0).use(Ux).use(Zd).use(Hw);Qr.use(Vd).config(t=>{t.get(gl).selectionUpdated(()=>{requestAnimationFrame(to)})}).create().then(t=>{V=t,Wp(),uL(),document.querySelector("#editor-status")?.remove(),document.addEventListener("mouseup",to),document.addEventListener("pointerdown",()=>{window.weiBeiSuppressSelectionReport||(Zt=null,Qi.text="",Qi.rectKey="",Ie("selectionChanged",{text:"",rect:null}))},!0),document.addEventListener("click",e=>{re&&e.target instanceof Element&&e.target.closest(".weibei-structured-node")||!g1(e.target)&&!m1(e.target)&&!Pp(e.target)&&!Bp(e.target)&&!y1(e.target)||(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keydown",e=>{e.key!=="Enter"&&e.key!==" "||Pp(e.target)&&(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keyup",e=>{to()}),document.addEventListener("scroll",io,!0),Ie("editorReady",{}),window.setTimeout(()=>{K0=!0,ED(),V.action(e=>Up(e.get(U).state.doc)),io()})}).catch(no);})(); +`);if(!l||!u||!(o instanceof B)||o.$from.parent!==o.$to.parent)break;let f=l.create(null,i.schema.text(u)),d=us(i.tr.replaceRangeWith(o.from,o.to,f));d.setSelection(H.create(d.doc,o.from)),r.dispatch(d.scrollIntoView()),s=!0;break}case"quote":{let l=i.schema.nodes.blockquote||i.schema.nodes.block_quote;if(!l)break;s=!!(Array.from({length:o.$from.depth},(u,f)=>o.$from.node(f+1)).some(u=>u.type===l)?Lg:yi(l))(r.state,r.dispatch,r);break}default:return!1}return s&&(r.focus(),window.requestAnimationFrame(to)),s}),En=()=>{if(!V)throw new Error("WeiBei editor is not ready")},M1=t=>{Ap=PD(t),Yr+=1,V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},E1=t=>{Ip=BD(t),Yr+=1,V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},EL=()=>{if(!V||Ts===null)return;let t=Ts;Ts=null,V.action(e=>{let n=e.get(U);n.domObserver?.flush();let r=n.state.doc.nodeAt(t);if(!r?.isTextblock||!r.textContent)return;let i=n.state.schema.nodes.hardbreak||n.state.schema.nodes.hard_break,o=[];for(let a=0;a<r.childCount;a+=1){let l=r.child(a);l.type!==i&&o.push(l)}if(o.length!==r.childCount){let a=r.type.create(r.attrs,M.fromArray(o),r.marks),l=n.state.tr.replaceWith(t,t+r.nodeSize,a).scrollIntoView();l.setSelection(B.create(l.doc,Math.min(t+1+a.content.size,l.doc.content.size))),n.dispatch(l)}let s=n.nodeDOM(t);s instanceof HTMLElement&&(s.querySelectorAll("br").forEach(a=>a.remove()),n.domObserver?.flush())})},TL=()=>{V&&(EL(),Pl=!1,zl=null,lt(),io())},Ps=()=>V.action(t=>t.get(Q)),vL=(t=!0)=>{$l(),we!==null&&(Ps().call(ms.key,{keep:t}),we=null,Qt=null,so=null)},T1=t=>{En(),$l();let e=String(t||"");so=e;let n=Ms(e);oo=n.frontmatter,Ls();let r=n.body,i=Qt!==null&&we===Qt&&r.startsWith(Qt)?r.slice(Qt.length):null,o;i!==null&&!/[$<>\\`\r]/.test(i)?(o=r,Qt=r):(o=Jn(r,"agentGenerated"),Qt=o===r?r:null,Zr=Ds(o));let s=Ps();we===null?(s.call($r.key),we=""):o.startsWith(we)||(s.call(Gi.key,{diffReview:!1}),s.call($r.key),we="");let a=o.slice(we.length);a&&s.call(hs.key,a),we=o,lt()},AL=t=>{let e=String(t||"");if(!e)return;let n=so;T1(n===null?e:n+e)},Ur=null,IL=24,NL=12,H0=33,RL=3e3,OL=240,$l=()=>{Ur!=null&&(window.clearTimeout(Ur),Ur=null)},W0=t=>{let e=Ps();we===null?(e.call($r.key),we=""):t.startsWith(we)||(e.call(Gi.key,{diffReview:!1}),e.call($r.key),we="");let n=t.slice(we.length);n&&e.call(hs.key,n),we=t,lt()},j0=()=>{Ps().call(Gi.key,{diffReview:!1}),Qt=null,we=null,so=null,$l();try{V?.action(t=>{t.get(U).updateState(t.get(U).state)})}catch{}Dp(),lt()},DL=(t,e)=>{$l(),Qt=null;let n=String(t||""),r=Ms(n);oo=r.frontmatter,Ls();let i=Jn(r.body,"agentGenerated");Zr=Ds(i),so=n;let o=we,s=e?.paced===!0&&o!==null&&i.startsWith(o)&&i.length-o.length>IL;if(o!==null&&s){let a=o.length,l=0,c=Date.now(),u=()=>{Ur=null;let f=Date.now();l+=1,a=Math.min(i.length,a+NL);let d=a>=i.length||f-c>=RL||l>=OL;try{if(W0(d?i:i.slice(0,a)),!d){Ur=window.setTimeout(u,H0);return}j0()}catch{Ur=null,we=null,Qt=null;try{Ps().call(ms.key,{keep:!1})}catch{}try{Kp(n)}catch{}lt()}};Ur=window.setTimeout(u,H0),lt();return}W0(i),j0()},Kp=t=>{En(),vL(),so=null,zl=null,Ts=null,Pl=!1,Xn+=1;let e=Ms(t||""),n=Jn(e.body,"userDocument");oo=e.frontmatter,Ls(),V.action(Pk(n)),Zr=Ds(n),V.action(r=>Jp(r.get(U).state.doc)),lt()},V0=(t,e=0,n=!1)=>{Tp=!0,Mn={revision:e,dirty:n};try{Kp(t)}finally{Tp=!1}ye("dirtyChanged",{dirty:n})},v1=()=>(En(),It(at,"fullSerializations"),Ds(V.action(Lk()))),LL=t=>{let e=t?.state?.selection;return e?.$from?e.$from.parent.type.spec.code?!0:(e.$from.marks()||[]).some(r=>String(r?.type?.name||"").toLowerCase().includes("code")):!1},Rs=t=>{En();let e=Jn(t||"","internalFragment"),n=Zt||Vp();n?V.action(Qu(e,n)):V.action(Yu(e)),Zt=null},Up=(t,e="internalFragment")=>{En();let n=Vp(),r=iL(Jn(t,e));n?V.action(Qu(r,n)):V.action(Yu(r)),oL()||sL(),Zt=null},A1=t=>{En(),V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setSelection($.atEnd(n.state.doc)))}),Up(t,"agentGenerated")},PL=t=>(En(),!window.weiBeiEditorCheckMode||!t?!1:V.action(e=>{let n=e.get(U),r=null;return n.state.doc.descendants((i,o)=>{if(!i.isText||r)return!0;let s=(i.text||"").indexOf(t);return s<0?!0:(r={from:o+s,to:o+s+t.length},!1)}),r?(n.dispatch(n.state.tr.setSelection(B.create(n.state.doc,r.from,r.to))),Zt=r,!0):!1})),BL=t=>(En(),window.weiBeiEditorCheckMode?V.action(e=>{let n=e.get(U);n.focus();for(let r of String(t||"")){let{from:i,to:o}=n.state.selection,s=!1;n.someProp("handleTextInput",a=>s?!0:(s=a(n,i,o,r)===!0,s)),s||n.dispatch(n.state.tr.insertText(r,i,o))}return!0}):!1),FL=(t,e={})=>(En(),window.weiBeiEditorCheckMode?V.action(n=>{let r=n.get(U);r.focus();let i=new KeyboardEvent("keydown",{key:t,bubbles:!0,cancelable:!0,shiftKey:e.shiftKey===!0,altKey:e.altKey===!0,metaKey:e.metaKey===!0,ctrlKey:e.ctrlKey===!0});return r.dom.dispatchEvent(i),!0}):!1),I1=()=>Array.from(document.querySelectorAll(".ProseMirror h1, .ProseMirror h2, .ProseMirror h3, .ProseMirror h4, .ProseMirror h5, .ProseMirror h6")),q0=0,Dl=-2,zp=null,Jp=t=>{let e=[],n=Math.max(1,t.content.size);t.descendants((i,o)=>{if(i.type.name!=="heading")return!0;let s=i.textContent.trim();if(!s)return!1;let a=e.length;return e.push({id:`note-heading-${a}`,index:a,level:Number(i.attrs.level||1),title:s,position:Math.max(0,Math.min(1,o/n))}),!1});let r=s0(e);r!==zp&&(zp=r,It(at,"outlineReports"),ye("outlineChanged",{items:e}))},io=()=>{window.cancelAnimationFrame(q0),q0=window.requestAnimationFrame(()=>{let t=I1();if(t.length===0){Dl!==-1&&(Dl=-1,ye("activeHeadingChanged",{index:null}));return}let e=Math.max(0,window.innerHeight*.32),n=0;t.forEach((r,i)=>{r.getBoundingClientRect().top<=e&&(n=i)}),n!==Dl&&(Dl=n,ye("activeHeadingChanged",{index:n}))})},Gp=t=>{let e=Number(t),n=I1(),r=Number.isFinite(e)?n[Math.max(0,Math.floor(e))]:null;if(!r)return!1;let i=Rp();return r.scrollIntoView({block:"start",behavior:i?"auto":"smooth"}),i?io():window.setTimeout(io,180),!0},N1=(t,e)=>{let n=t!==nt||e!==Ve;nt=t,Ve=e,n&&(Ep.clear(),zp=null,Xn+=1,_t.clear(),Gn.clear(),M1([]),E1([]))},R1=t=>{re=t!==!1,jp(),V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiEditableChanged",re))})},Xp=t=>{Z0(t),Yr+=1,h1(),V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiThemeChanged",eo))})},Yp=t=>{Jr=X0(t),Yr+=1,document.documentElement.dataset.weibeiLanguage=Jr,Ls(),jp(),Ns.forEach(e=>e()),G.dataset.show==="true"&&Is(),V&&V.action(e=>{let n=e.get(U);n.dispatch(n.state.tr.setMeta("weibeiLanguageChanged",Jr))})},Qp=()=>V?(V.action(t=>t.get(U).focus()),!0):!1,kt=(t,e)=>t.payload[e]??t.payload.value,zL=t=>{let e=l0(t);if(!e)return!1;if(Ep.has(e.commandID))return ye("commandApplied",{commandID:e.commandID}),!0;if(!c0(e,{documentID:nt,documentGeneration:Ve,revision:Mn.revision}))return ye("commandRejected",{commandID:e.commandID,reason:"document or revision mismatch"}),!1;let n=!1;try{switch(e.type){case"loadDocument":{let r=kt(e,"markdown"),i=kt(e,"initialRevision");if(typeof r!="string"||i!==void 0&&!Number.isInteger(i))break;N1(e.documentID,e.documentGeneration),V0(r,Number(i??0)),n=!0;break}case"requestSnapshot":{let r=v1();Zr=r,ye("snapshotReady",{requestID:e.requestID,markdown:r}),n=!0;break}case"setTheme":Xp(kt(e,"theme")),n=!0;break;case"setLanguage":Yp(kt(e,"language")),n=!0;break;case"setEditable":R1(kt(e,"editable")),n=!0;break;case"focus":n=Qp();break;case"scrollToHeading":n=Gp(kt(e,"index"));break;case"applyMarkdownFragment":{let r=kt(e,"markdown");if(typeof r!="string")break;A1(r),n=!0;break}case"replaceSelection":{let r=kt(e,"markdown");if(typeof r!="string")break;Rs(r),n=!0;break}case"executeSelectionCommand":n=S1(kt(e,"action"),kt(e,"value"));break;case"insertStructuredBlock":{let r=kt(e,"markdown");if(typeof r!="string")break;Up(r),n=!0;break}case"restoreCheckpoint":{let r=kt(e,"markdown"),i=kt(e,"revision");if(typeof r!="string"||i!==void 0&&(!Number.isInteger(i)||Number(i)<0))break;V0(r,i===void 0?Mn.revision:Number(i),!0),n=!0;break}}}catch(r){return ye("commandRejected",{commandID:e.commandID,reason:String(r?.message||r)}),!1}return n?(Ep.add(e.commandID),ye("commandApplied",{commandID:e.commandID}),!0):(ye("commandRejected",{commandID:e.commandID,reason:"command could not be applied"}),!1)};window.WeiBeiEditor={dispatchCommand:zL,resolveAttachment:(t,e,n)=>{let r=Gn.get(t);r&&(Gn.delete(t),r.resolve({src:e,alt:n}))},rejectAttachment:(t,e)=>{let n=Gn.get(t);n&&(Gn.delete(t),n.reject(new Error(e||"Attachment save failed")))},resolveImagePicker:(t,e,n)=>{let r=_t.get(t);if(!r||(_t.delete(t),r.documentID!==nt||r.documentGeneration!==Ve))return!1;if(r.mode==="replace"){let i=r.getPos(),o=typeof i=="number"?r.view.state.doc.nodeAt(i):null;if(o?.type.name!=="image")return!1;let s=Fl(o.attrs.alt||"").size,a=`${String(n||"image")}${s?`|${s.width}${s.height?`x${s.height}`:""}`:""}`;return r.view.dispatch(r.view.state.tr.setNodeMarkup(i,void 0,{...o.attrs,src:e,alt:a}).scrollIntoView()),r.view.focus(),!0}return s1(r.view,r.context,$p("image",r.view.state.schema,{src:e,alt:n}))},cancelImagePicker:t=>{let e=_t.get(t);return e?(_t.delete(t),e.mode==="replace"&&e.view.focus(),e.documentID===nt&&e.documentGeneration===Ve):!1},discardImagePicker:t=>_t.delete(t),rejectImagePicker:(t,e)=>{let n=_t.get(t);return!n||(_t.delete(t),n.documentID!==nt||n.documentGeneration!==Ve)?!1:n.mode==="replace"?(n.view.focus(),!0):(I.dismissedContext="",I.error=e||ue("slashImageFailed"),I.view=n.view,I.provider?.show(),Is(),!0)},setTheme:Xp,setInterfaceLanguage:Yp,setReduceMotion:n1,setTextScale:r1,focus:Qp,scrollToHeading:Gp,setSelectionAskMarks:M1,setSelectionRemarkMarks:E1,setMarkdownBaseURL:t=>{J0=t||"",h1()}};window.weiBeiEditorCheckMode&&(Object.assign(window.WeiBeiEditor,{getMarkdown:v1,setMarkdown:Kp,updateStreamingMarkdown:T1,appendStreamingMarkdown:AL,finishStreamingMarkdown:(t,e)=>(DL(t,e),!0),replaceSelection:Rs,executeSelectionCommand:S1,applyAgentPatch:A1,insertMarkdownImage:Rs,insertMarkdown:Up,setEditable:R1,setDocumentID:t=>N1(String(t||""),Ve+1),setTheme:Xp,setInterfaceLanguage:Yp,setReduceMotion:n1,setTextScale:r1,focus:Qp,scrollToHeading:Gp}),window.WeiBeiEditor.getCheckMetrics=()=>({...at,fullBridgeMessages:vp}),window.WeiBeiEditor.resetCheckMetrics=()=>{o0(at),vp=0},window.WeiBeiEditor.getBridgeSessionForCheck=()=>({protocolVersion:2,documentID:nt,documentGeneration:Ve,revision:Mn.revision,dirty:Mn.dirty}),window.WeiBeiEditor.selectFirstTextForCheck=PL,window.WeiBeiEditor.selectedTextForCheck=m1,window.WeiBeiEditor.typeTextForCheck=BL,window.WeiBeiEditor.pressKeyForCheck=FL,window.WeiBeiEditor.compositionStateForCheck=()=>({start:zl,last:Zr,composing:V.action(t=>t.get(U).composing)}),window.WeiBeiEditor.openSlashMenuForCheck=()=>{let t=I.view;return!t||!ro(t)?!1:(I.dismissedContext="",I.provider?.show(),Is(),G.dataset.show==="true")},window.WeiBeiEditor.slashStateForCheck=()=>({show:G.dataset.show==="true",commands:Array.from(G.querySelectorAll(".weibei-slash-command-button")).map(t=>t.textContent),groups:Array.from(G.querySelectorAll(".weibei-slash-group")).map(t=>t.textContent),rows:I.tableRows,columns:I.tableColumns,tableOpen:I.tableOpen,tableSide:As?.dataset.side||"",activeDescendant:I.view?.dom.getAttribute("aria-activedescendant")||"",announcement:Gr.textContent,error:I.error}),window.WeiBeiEditor.renderSlashMenuForCheck=Is,window.WeiBeiEditor.executeSlashCommandForCheck=t=>Xr(t),window.WeiBeiEditor.pendingImagePickerIDsForCheck=()=>Array.from(_t.keys()),window.WeiBeiEditor.undoForCheck=()=>V.action(t=>fs(t.get(U).state,t.get(U).dispatch)),window.WeiBeiEditor.redoForCheck=()=>V.action(t=>ds(t.get(U).state,t.get(U).dispatch)),window.WeiBeiEditor.selectFirstCodeBlockEndForCheck=()=>V.action(t=>{let e=t.get(U),n=null;return e.state.doc.descendants((r,i)=>n!==null||r.type.name!=="code_block"?!0:(n=i+r.content.size+1,!1)),n===null?!1:(e.dispatch(e.state.tr.setSelection(B.create(e.state.doc,n))),e.focus(),!0)}),window.WeiBeiEditor.selectDocumentEndForCheck=()=>V.action(t=>{let e=t.get(U);return e.dispatch(e.state.tr.setSelection($.atEnd(e.state.doc))),e.focus(),!0}),window.WeiBeiEditor.selectionForCheck=()=>V.action(t=>{let e=t.get(U).state.selection;return{from:e.from,to:e.to,parent:e.$from.parent.type.name,parentOffset:e.$from.parentOffset}}));var Os=Ms(window.initialMarkdown||"");Os.body=Jn(Os.body,"userDocument");oo=Os.frontmatter;Zr=Ds(Os.body);Ls();var Qr=Nk.make().config(t=>{t.set(Go,document.querySelector("#editor")),t.set(Ko,Os.body),t.set(Or,{editable:()=>re,nodeViews:{code_block:eL,image:DD,math_inline:P0,math_block:P0,wiki_link:wp,embed:wp,inline_footnote:wp,callout:tL}}),t.set(qn.key,{throttleMs:0,scrollFollow:!1,diffReviewOnEnd:!1,ignoreAttrs:{heading:["id"]}})});Qr=Qr.config(t=>{t.set(Kr.key,{uploader:aL,enableHtmlFileUploader:!0,uploadWidgetFactory:(e,n)=>{let r=document.createElement("span");return r.className="weibei-uploading",r.textContent=ue("uploadingImage"),le.widget(e,r,n)}}),t.set(G0.key,{view(e){let n=l=>l.preventDefault(),r=()=>{let l=i1(e);l&&(e.dispatch(e.state.tr.insertText("/",l.pos).scrollIntoView()),e.focus(),I.dismissedContext="")};st.addEventListener("mousedown",n),st.addEventListener("click",r),document.body.append(Gr,st);let i=new $w({content:G,debounce:0,offset:6,root:document.body,shouldShow:l=>{let c=ro(l);return!!(c&&I.dismissedContext!==c.key)}});I.provider=i,I.view=e;let o=i.show.bind(i),s=i.hide.bind(i),a=l=>{Pe.generation===l&&(Pe.state="closed",G.dataset.state="closed",s())};return i.show=()=>{if(Pe.generation+=1,window.clearTimeout(Pe.timer),window.weiBeiEditorCheckMode||Rp()){Pe.state="open",G.dataset.state="open",o();return}o(),Pe.state="opening",G.dataset.state="opening";let l=Pe.generation;Pe.frame=window.requestAnimationFrame(()=>{Pe.generation===l&&(Pe.state="open",G.dataset.state="open")})},i.hide=()=>{if(Pe.generation+=1,window.clearTimeout(Pe.timer),window.cancelAnimationFrame(Pe.frame),G.dataset.show!=="true"||window.weiBeiEditorCheckMode||Rp()){a(Pe.generation);return}Pe.state="closing",G.dataset.state="closing",G.setAttribute("aria-hidden","true");let l=Pe.generation,c=()=>{Pe.generation===l&&(G.removeAttribute("aria-hidden"),a(l))};G.addEventListener("transitionend",function u(f){f.target!==G||f.propertyName!=="opacity"||(G.removeEventListener("transitionend",u),c())}),Pe.timer=window.setTimeout(c,200)},i.onShow=()=>{I.view=e,Is()},i.onHide=()=>{I.context=null,I.tableOpen=!1,a1(),Hp()},i.update(e),T0(e),{update(l,c){I.view=l;let u=ro(l);I.dismissedContext&&u?.key!==I.dismissedContext&&(I.dismissedContext=""),i.update(l,c),T0(l)},destroy(){i.destroy(),st.removeEventListener("mousedown",n),st.removeEventListener("click",r),G.remove(),Gr.remove(),st.remove(),As?.remove(),I.provider=null,I.view=null}}}})});Qr=Qr.use(ML).use(lb).use(Ix).use(x0).use(lD).use(cw).use(pe(()=>fw(()=>we!==null)));Qr=Qr.use(G0).use(Jx).use(Zd).use(Ww);Qr.use(Vd).config(t=>{t.get(gl).selectionUpdated(()=>{requestAnimationFrame(to)})}).create().then(t=>{V=t,jp(),fL(),document.querySelector("#editor-status")?.remove(),document.addEventListener("mouseup",to),document.addEventListener("pointerdown",()=>{window.weiBeiSuppressSelectionReport||(Zt=null,Qi.text="",Qi.rectKey="",ye("selectionChanged",{text:"",rect:null}))},!0),document.addEventListener("click",e=>{re&&e.target instanceof Element&&e.target.closest(".weibei-structured-node")||!y1(e.target)&&!g1(e.target)&&!Bp(e.target)&&!Fp(e.target)&&!k1(e.target)||(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keydown",e=>{e.key!=="Enter"&&e.key!==" "||Bp(e.target)&&(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keyup",e=>{to()}),document.addEventListener("scroll",io,!0),ye("editorReady",{}),window.setTimeout(()=>{U0=!0,TD(),V.action(e=>Jp(e.get(U).state.doc)),io()})}).catch(no);})(); /*! Bundled license information: lodash-es/lodash.js: diff --git a/Sources/WeiBei/Resources/Editor/editor-resources.json b/Sources/WeiBei/Resources/Editor/editor-resources.json index e13fde2c0..eb74d29d3 100644 --- a/Sources/WeiBei/Resources/Editor/editor-resources.json +++ b/Sources/WeiBei/Resources/Editor/editor-resources.json @@ -3,8 +3,8 @@ "assets": [ { "name": "editor-entry.js", - "bytes": 598840, - "sha256": "6c58c364c03bee4f6f5c5ef16032518586f1a8d00bf4beb42b9106e7840522f0" + "bytes": 599344, + "sha256": "a0f75325f94fc64abb13050b63976c317de7f3a4b9709956506be892539734df" }, { "name": "editor.css", @@ -333,8 +333,8 @@ }, { "name": "viewer-entry.js", - "bytes": 518708, - "sha256": "bacddcf53fea5d5b39c4a85bd73f4c558a0975692a1ae4f5b4c4a8c563f51705" + "bytes": 518730, + "sha256": "b501938b2bdd81b78f2434fb84310f4acedf34838233016b45d65d388ab609ed" } ] } diff --git a/Sources/WeiBei/Resources/Editor/viewer-entry.js b/Sources/WeiBei/Resources/Editor/viewer-entry.js index e29da372c..d149b55b3 100644 --- a/Sources/WeiBei/Resources/Editor/viewer-entry.js +++ b/Sources/WeiBei/Resources/Editor/viewer-entry.js @@ -1,4 +1,4 @@ -"use strict";(()=>{var yx=Object.create;var Ma=Object.defineProperty;var kx=Object.getOwnPropertyDescriptor;var bx=Object.getOwnPropertyNames;var xx=Object.getPrototypeOf,wx=Object.prototype.hasOwnProperty;var Sx=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Cx=(t,e)=>{for(var n in e)Ma(t,n,{get:e[n],enumerable:!0})},Mx=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bx(e))!wx.call(t,i)&&i!==n&&Ma(t,i,{get:()=>e[i],enumerable:!(r=kx(e,i))||r.enumerable});return t};var Ex=(t,e,n)=>(n=t!=null?yx(xx(t)):{},Mx(e||!t||!t.__esModule?Ma(n,"default",{value:t,enumerable:!0}):n,t));var Tp=Sx((TP,Ep)=>{"use strict";var Yo=Object.prototype.hasOwnProperty,Mp=Object.prototype.toString,kp=Object.defineProperty,bp=Object.getOwnPropertyDescriptor,xp=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Mp.call(e)==="[object Array]"},wp=function(e){if(!e||Mp.call(e)!=="[object Object]")return!1;var n=Yo.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Yo.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var i;for(i in e);return typeof i>"u"||Yo.call(e,i)},Sp=function(e,n){kp&&n.name==="__proto__"?kp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Cp=function(e,n){if(n==="__proto__")if(Yo.call(e,n)){if(bp)return bp(e,n).value}else return;return e[n]};Ep.exports=function t(){var e,n,r,i,o,s,a=arguments[0],l=1,c=arguments.length,u=!1;for(typeof a=="boolean"&&(u=a,a=arguments[1]||{},l=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});l<c;++l)if(e=arguments[l],e!=null)for(n in e)r=Cp(a,n),i=Cp(e,n),a!==i&&(u&&i&&(wp(i)||(o=xp(i)))?(o?(o=!1,s=r&&xp(r)?r:[]):s=r&&wp(r)?r:{},Sp(a,{name:n,newValue:t(u,s,i)})):typeof i<"u"&&Sp(a,{name:n,newValue:i}));return a}});var nt=(function(t){return t.docTypeError="docTypeError",t.contextNotFound="contextNotFound",t.timerNotFound="timerNotFound",t.ctxCallOutOfScope="ctxCallOutOfScope",t.createNodeInParserFail="createNodeInParserFail",t.stackOverFlow="stackOverFlow",t.parserMatchError="parserMatchError",t.serializerMatchError="serializerMatchError",t.getAtomFromSchemaFail="getAtomFromSchemaFail",t.expectDomTypeError="expectDomTypeError",t.callCommandBeforeEditorView="callCommandBeforeEditorView",t.missingRootElement="missingRootElement",t.missingNodeInSchema="missingNodeInSchema",t.missingMarkInSchema="missingMarkInSchema",t.ctxNotBind="ctxNotBind",t.missingYjsDoc="missingYjsDoc",t.aiProviderError="aiProviderError",t.aiBuildContextError="aiBuildContextError",t})({}),rt=class extends Error{constructor(t,e,n){super(e,n),this.name="MilkdownError",this.code=t,n?.cause!==void 0&&(this.cause=n.cause)}},Tx=(t,e)=>typeof e=="function"?"[Function]":e,Ro=t=>JSON.stringify(t,Tx);function rd(t){return new rt(nt.docTypeError,`Doc type error, unsupported type: ${Ro(t)}`)}function id(t){return new rt(nt.contextNotFound,`Context "${t}" not found, do you forget to inject it?`)}function od(t){return new rt(nt.timerNotFound,`Timer "${t}" not found, do you forget to record it?`)}function mr(){return new rt(nt.ctxCallOutOfScope,"Should not call a context out of the plugin.")}function sd(t,e,n){let r=`Cannot create node for ${"name"in t?t.name:t}`,i=s=>{if(s==null)return"null";if(Array.isArray(s))return`[${s.map(i).join(", ")}]`;if(typeof s=="object")return"toJSON"in s&&typeof s.toJSON=="function"?JSON.stringify(s.toJSON()):"spec"in s?JSON.stringify(s.spec):JSON.stringify(s);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return JSON.stringify(s);if(typeof s=="function")return`[Function: ${s.name||"anonymous"}]`;try{return String(s)}catch{return"[Unserializable]"}},o=[["[Description]",r],["[Attributes]",e],["[Content]",(n??[]).map(s=>s?typeof s=="object"&&"type"in s?`${s}`:i(s):"null")]].reduce((s,[a,l])=>{let c=`${a}: ${i(l)}.`;return s.concat(c)},[]);return new rt(nt.createNodeInParserFail,o.join(` +"use strict";(()=>{var yx=Object.create;var Ma=Object.defineProperty;var kx=Object.getOwnPropertyDescriptor;var bx=Object.getOwnPropertyNames;var xx=Object.getPrototypeOf,wx=Object.prototype.hasOwnProperty;var Sx=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Cx=(t,e)=>{for(var n in e)Ma(t,n,{get:e[n],enumerable:!0})},Mx=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bx(e))!wx.call(t,i)&&i!==n&&Ma(t,i,{get:()=>e[i],enumerable:!(r=kx(e,i))||r.enumerable});return t};var Ex=(t,e,n)=>(n=t!=null?yx(xx(t)):{},Mx(e||!t||!t.__esModule?Ma(n,"default",{value:t,enumerable:!0}):n,t));var Tp=Sx((IP,Ep)=>{"use strict";var Yo=Object.prototype.hasOwnProperty,Mp=Object.prototype.toString,kp=Object.defineProperty,bp=Object.getOwnPropertyDescriptor,xp=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Mp.call(e)==="[object Array]"},wp=function(e){if(!e||Mp.call(e)!=="[object Object]")return!1;var n=Yo.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Yo.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var i;for(i in e);return typeof i>"u"||Yo.call(e,i)},Sp=function(e,n){kp&&n.name==="__proto__"?kp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Cp=function(e,n){if(n==="__proto__")if(Yo.call(e,n)){if(bp)return bp(e,n).value}else return;return e[n]};Ep.exports=function t(){var e,n,r,i,o,s,a=arguments[0],l=1,c=arguments.length,u=!1;for(typeof a=="boolean"&&(u=a,a=arguments[1]||{},l=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});l<c;++l)if(e=arguments[l],e!=null)for(n in e)r=Cp(a,n),i=Cp(e,n),a!==i&&(u&&i&&(wp(i)||(o=xp(i)))?(o?(o=!1,s=r&&xp(r)?r:[]):s=r&&wp(r)?r:{},Sp(a,{name:n,newValue:t(u,s,i)})):typeof i<"u"&&Sp(a,{name:n,newValue:i}));return a}});var nt=(function(t){return t.docTypeError="docTypeError",t.contextNotFound="contextNotFound",t.timerNotFound="timerNotFound",t.ctxCallOutOfScope="ctxCallOutOfScope",t.createNodeInParserFail="createNodeInParserFail",t.stackOverFlow="stackOverFlow",t.parserMatchError="parserMatchError",t.serializerMatchError="serializerMatchError",t.getAtomFromSchemaFail="getAtomFromSchemaFail",t.expectDomTypeError="expectDomTypeError",t.callCommandBeforeEditorView="callCommandBeforeEditorView",t.missingRootElement="missingRootElement",t.missingNodeInSchema="missingNodeInSchema",t.missingMarkInSchema="missingMarkInSchema",t.ctxNotBind="ctxNotBind",t.missingYjsDoc="missingYjsDoc",t.aiProviderError="aiProviderError",t.aiBuildContextError="aiBuildContextError",t})({}),rt=class extends Error{constructor(t,e,n){super(e,n),this.name="MilkdownError",this.code=t,n?.cause!==void 0&&(this.cause=n.cause)}},Tx=(t,e)=>typeof e=="function"?"[Function]":e,Ro=t=>JSON.stringify(t,Tx);function rd(t){return new rt(nt.docTypeError,`Doc type error, unsupported type: ${Ro(t)}`)}function id(t){return new rt(nt.contextNotFound,`Context "${t}" not found, do you forget to inject it?`)}function od(t){return new rt(nt.timerNotFound,`Timer "${t}" not found, do you forget to record it?`)}function mr(){return new rt(nt.ctxCallOutOfScope,"Should not call a context out of the plugin.")}function sd(t,e,n){let r=`Cannot create node for ${"name"in t?t.name:t}`,i=s=>{if(s==null)return"null";if(Array.isArray(s))return`[${s.map(i).join(", ")}]`;if(typeof s=="object")return"toJSON"in s&&typeof s.toJSON=="function"?JSON.stringify(s.toJSON()):"spec"in s?JSON.stringify(s.spec):JSON.stringify(s);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return JSON.stringify(s);if(typeof s=="function")return`[Function: ${s.name||"anonymous"}]`;try{return String(s)}catch{return"[Unserializable]"}},o=[["[Description]",r],["[Attributes]",e],["[Content]",(n??[]).map(s=>s?typeof s=="object"&&"type"in s?`${s}`:i(s):"null")]].reduce((s,[a,l])=>{let c=`${a}: ${i(l)}.`;return s.concat(c)},[]);return new rt(nt.createNodeInParserFail,o.join(` `))}function Ea(){return new rt(nt.stackOverFlow,"Stack over flow, cannot pop on an empty stack.")}function ad(t){return new rt(nt.parserMatchError,`Cannot match target parser for node: ${Ro(t)}.`)}function ld(t){return new rt(nt.serializerMatchError,`Cannot match target serializer for node: ${Ro(t)}.`)}function it(t){return new rt(nt.expectDomTypeError,`Expect to be a dom, but get: ${Ro(t)}.`)}function Do(){return new rt(nt.callCommandBeforeEditorView,"You're trying to call a command before editor view initialized, make sure to get commandManager from ctx after editor view has been initialized")}function cd(t){return new rt(nt.missingNodeInSchema,`Missing node in schema, milkdown cannot find "${t}" in schema.`)}function ud(t){return new rt(nt.missingMarkInSchema,`Missing mark in schema, milkdown cannot find "${t}" in schema.`)}var Ta=class{constructor(){this.sliceMap=new Map,this.get=t=>{let e=typeof t=="string"?[...this.sliceMap.values()].find(n=>n.type.name===t):this.sliceMap.get(t.id);if(!e)throw id(typeof t=="string"?t:t.name);return e},this.remove=t=>{let e=typeof t=="string"?[...this.sliceMap.values()].find(n=>n.type.name===t):this.sliceMap.get(t.id);e&&this.sliceMap.delete(e.type.id)},this.has=t=>typeof t=="string"?[...this.sliceMap.values()].some(e=>e.type.name===t):this.sliceMap.has(t.id)}},Ix=class{#t;#e;#r;constructor(t,e,n){this.#t=[],this.#r=()=>{this.#t.forEach(r=>r(this.#e))},this.set=r=>{this.#e=r,this.#r()},this.get=()=>this.#e,this.update=r=>{this.#e=r(this.#e),this.#r()},this.type=n,this.#e=e,t.set(n.id,this)}on(t){return this.#t.push(t),()=>{this.#t=this.#t.filter(e=>e!==t)}}once(t){let e=this.on(n=>{t(n),e()});return e}off(t){this.#t=this.#t.filter(e=>e!==t)}offAll(){this.#t=[]}},vx=class{constructor(t,e){this.id=Symbol(`Context-${e}`),this.name=e,this._defaultValue=t,this._typeInfo=()=>{throw mr()}}create(t,e=this._defaultValue){return new Ix(t,e,this)}},K=(t,e)=>new vx(t,e),Ax=class{#t;#e;#r;#n;#s;#o;#i;constructor(t,e,n){this.#n=new Set,this.#s=new Set,this.#o=new Map,this.#i=new Map,this.read=()=>({metadata:this.#t,injectedSlices:[...this.#n].map(r=>({name:typeof r=="string"?r:r.name,value:this.#a(r)})),consumedSlices:[...this.#s].map(r=>({name:typeof r=="string"?r:r.name,value:this.#a(r)})),recordedTimers:[...this.#o].map(([r,{duration:i}])=>({name:r.name,duration:i,status:this.#l(r)})),waitTimers:[...this.#i].map(([r,{duration:i}])=>({name:r.name,duration:i,status:this.#l(r)}))}),this.onRecord=r=>{this.#o.set(r,{start:Date.now(),duration:0})},this.onClear=r=>{this.#o.delete(r)},this.onDone=r=>{let i=this.#o.get(r);i&&(i.duration=Date.now()-i.start)},this.onWait=(r,i)=>{let o=Date.now();i.finally(()=>{this.#i.set(r,{duration:Date.now()-o})}).catch(console.error)},this.onInject=r=>{this.#n.add(r)},this.onRemove=r=>{this.#n.delete(r)},this.onUse=r=>{this.#s.add(r)},this.#a=r=>this.#e.get(r).get(),this.#l=r=>this.#r.get(r).status,this.#e=t,this.#r=e,this.#t=n}#a;#l},fd=class dd{#t;#e;#r;#n;constructor(e,n,r){this.produce=i=>i&&Object.keys(i).length?new dd(this.#t,this.#e,{...i}):this,this.inject=(i,o)=>{let s=i.create(this.#t.sliceMap);return o!=null&&s.set(o),this.#n?.onInject(i),this},this.remove=i=>(this.#t.remove(i),this.#n?.onRemove(i),this),this.record=i=>(i.create(this.#e.store),this.#n?.onRecord(i),this),this.clearTimer=i=>(this.#e.remove(i),this.#n?.onClear(i),this),this.isInjected=i=>this.#t.has(i),this.isRecorded=i=>this.#e.has(i),this.use=i=>(this.#n?.onUse(i),this.#t.get(i)),this.get=i=>this.use(i).get(),this.set=(i,o)=>this.use(i).set(o),this.update=(i,o)=>this.use(i).update(o),this.timer=i=>this.#e.get(i),this.done=i=>{this.timer(i).done(),this.#n?.onDone(i)},this.wait=i=>{let o=this.timer(i).start();return this.#n?.onWait(i,o),o},this.waitTimers=async i=>{await Promise.all(this.get(i).map(o=>this.wait(o)))},this.#t=e,this.#e=n,this.#r=r,r&&(this.#n=new Ax(e,n,r))}get meta(){return this.#r}get inspector(){return this.#n}},pd=class{constructor(){this.store=new Map,this.get=t=>{let e=this.store.get(t.id);if(!e)throw od(t.name);return e},this.remove=t=>{this.store.delete(t.id)},this.has=t=>this.store.has(t.id)}},Nx=class{#t;#e;#r;#n;constructor(t,e){this.#t=null,this.#e=null,this.#n="pending",this.start=()=>(this.#t??=new Promise((n,r)=>{this.#e=i=>{i instanceof CustomEvent&&i.detail.id===this.#r&&(this.#n="resolved",this.#s(),i.stopImmediatePropagation(),n())},this.#o(()=>{this.#n==="pending"&&(this.#n="rejected"),this.#s(),r(new Error(`Timing ${this.type.name} timeout.`))}),this.#n="pending",addEventListener(this.type.name,this.#e)}),this.#t),this.done=()=>{let n=new CustomEvent(this.type.name,{detail:{id:this.#r}});dispatchEvent(n)},this.#s=()=>{this.#e&&removeEventListener(this.type.name,this.#e)},this.#o=n=>{setTimeout(()=>{n()},this.type.timeout)},this.#r=Symbol(e.name),this.type=e,t.set(e.id,this)}get status(){return this.#n}#s;#o},Rx=class{constructor(t,e=3e3){this.create=n=>new Nx(n,this),this.id=Symbol(`Timer-${t}`),this.name=t,this.timeout=e}},ot=(t,e=3e3)=>new Rx(t,e);var Dx={};function En(t,e){let n=e||Dx,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return md(t,r,i)}function md(t,e,n){if(Ox(t)){if("value"in t)return t.type==="html"&&!n?"":t.value;if(e&&"alt"in t&&t.alt)return t.alt;if("children"in t)return hd(t.children,e,n)}return Array.isArray(t)?hd(t,e,n):""}function hd(t,e,n){let r=[],i=-1;for(;++i<t.length;)r[i]=md(t[i],e,n);return r.join("")}function Ox(t){return!!(t&&typeof t=="object")}var gd=document.createElement("i");function gr(t){let e="&"+t+";";gd.innerHTML=e;let n=gd.textContent;return n.charCodeAt(n.length-1)===59&&t!=="semi"||n===e?!1:n}function ue(t,e,n,r){let i=t.length,o=0,s;if(e<0?e=-e>i?0:i+e:e=e>i?i:e,n=n>0?n:0,r.length<1e4)s=Array.from(r),s.unshift(e,n),t.splice(...s);else for(n&&t.splice(e,n);o<r.length;)s=r.slice(o,o+1e4),s.unshift(e,0),t.splice(...s),o+=1e4,e+=1e4}function Be(t,e){return t.length>0?(ue(t,t.length,0,e),t):e}var yd={}.hasOwnProperty;function Oo(t){let e={},n=-1;for(;++n<t.length;)Lx(e,t[n]);return e}function Lx(t,e){let n;for(n in e){let i=(yd.call(t,n)?t[n]:void 0)||(t[n]={}),o=e[n],s;if(o)for(s in o){yd.call(i,s)||(i[s]=[]);let a=o[s];Bx(i[s],Array.isArray(a)?a:a?[a]:[])}}}function Bx(t,e){let n=-1,r=[];for(;++n<e.length;)(e[n].add==="after"?t:r).push(e[n]);ue(t,0,0,r)}function Lo(t,e){let n=Number.parseInt(t,e);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"\uFFFD":String.fromCodePoint(n)}function Ne(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var ye=tn(/[A-Za-z]/),ke=tn(/[\dA-Za-z]/),kd=tn(/[#-'*+\--9=?A-Z^-~]/);function Tn(t){return t!==null&&(t<32||t===127)}var ki=tn(/\d/),bd=tn(/[\dA-Fa-f]/),xd=tn(/[!-/:-@[-`{-~]/);function R(t){return t!==null&&t<-2}function U(t){return t!==null&&(t<0||t===32)}function $(t){return t===-2||t===-1||t===32}var In=tn(/\p{P}|\p{S}/u),Tt=tn(/\s/);function tn(t){return e;function e(n){return n!==null&&n>-1&&t.test(String.fromCharCode(n))}}function F(t,e,n,r){let i=r?r-1:Number.POSITIVE_INFINITY,o=0;return s;function s(l){return $(l)?(t.enter(n),a(l)):e(l)}function a(l){return $(l)&&o++<i?(t.consume(l),a):(t.exit(n),e(l))}}var wd={tokenize:Px};function Px(t){let e=t.attempt(this.parser.constructs.contentInitial,r,i),n;return e;function r(a){if(a===null){t.consume(a);return}return t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),F(t,e,"linePrefix")}function i(a){return t.enter("paragraph"),o(a)}function o(a){let l=t.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,s(a)}function s(a){if(a===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(a);return}return R(a)?(t.consume(a),t.exit("chunkText"),o):(t.consume(a),s)}}var Cd={tokenize:Fx},Sd={tokenize:zx};function Fx(t){let e=this,n=[],r=0,i,o,s;return a;function a(C){if(r<n.length){let I=n[r];return e.containerState=I[1],t.attempt(I[0].continuation,l,c)(C)}return c(C)}function l(C){if(r++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,i&&x();let I=e.events.length,v=I,w;for(;v--;)if(e.events[v][0]==="exit"&&e.events[v][1].type==="chunkFlow"){w=e.events[v][1].end;break}y(r);let N=I;for(;N<e.events.length;)e.events[N][1].end={...w},N++;return ue(e.events,v+1,0,e.events.slice(I)),e.events.length=N,c(C)}return a(C)}function c(C){if(r===n.length){if(!i)return d(C);if(i.currentConstruct&&i.currentConstruct.concrete)return h(C);e.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return e.containerState={},t.check(Sd,u,f)(C)}function u(C){return i&&x(),y(r),d(C)}function f(C){return e.parser.lazy[e.now().line]=r!==n.length,s=e.now().offset,h(C)}function d(C){return e.containerState={},t.attempt(Sd,p,h)(C)}function p(C){return r++,n.push([e.currentConstruct,e.containerState]),d(C)}function h(C){if(C===null){i&&x(),y(0),t.consume(C);return}return i=i||e.parser.flow(e.now()),t.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:o}),m(C)}function m(C){if(C===null){g(t.exit("chunkFlow"),!0),y(0),t.consume(C);return}return R(C)?(t.consume(C),g(t.exit("chunkFlow")),r=0,e.interrupt=void 0,a):(t.consume(C),m)}function g(C,I){let v=e.sliceStream(C);if(I&&v.push(null),C.previous=o,o&&(o.next=C),o=C,i.defineSkip(C.start),i.write(v),e.parser.lazy[C.start.line]){let w=i.events.length;for(;w--;)if(i.events[w][1].start.offset<s&&(!i.events[w][1].end||i.events[w][1].end.offset>s))return;let N=e.events.length,O=N,L,S;for(;O--;)if(e.events[O][0]==="exit"&&e.events[O][1].type==="chunkFlow"){if(L){S=e.events[O][1].end;break}L=!0}for(y(r),w=N;w<e.events.length;)e.events[w][1].end={...S},w++;ue(e.events,O+1,0,e.events.slice(N)),e.events.length=w}}function y(C){let I=n.length;for(;I-- >C;){let v=n[I];e.containerState=v[1],v[0].exit.call(e,t)}n.length=C}function x(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function zx(t,e,n){return F(t,t.attempt(this.parser.constructs.document,e,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function _t(t){if(t===null||U(t)||Tt(t))return 1;if(In(t))return 2}function nn(t,e,n){let r=[],i=-1;for(;++i<t.length;){let o=t[i].resolveAll;o&&!r.includes(o)&&(e=o(e,n),r.push(o))}return e}var bi={name:"attention",resolveAll:_x,tokenize:$x};function _x(t,e){let n=-1,r,i,o,s,a,l,c,u;for(;++n<t.length;)if(t[n][0]==="enter"&&t[n][1].type==="attentionSequence"&&t[n][1]._close){for(r=n;r--;)if(t[r][0]==="exit"&&t[r][1].type==="attentionSequence"&&t[r][1]._open&&e.sliceSerialize(t[r][1]).charCodeAt(0)===e.sliceSerialize(t[n][1]).charCodeAt(0)){if((t[r][1]._close||t[n][1]._open)&&(t[n][1].end.offset-t[n][1].start.offset)%3&&!((t[r][1].end.offset-t[r][1].start.offset+t[n][1].end.offset-t[n][1].start.offset)%3))continue;l=t[r][1].end.offset-t[r][1].start.offset>1&&t[n][1].end.offset-t[n][1].start.offset>1?2:1;let f={...t[r][1].end},d={...t[n][1].start};Md(f,-l),Md(d,l),s={type:l>1?"strongSequence":"emphasisSequence",start:f,end:{...t[r][1].end}},a={type:l>1?"strongSequence":"emphasisSequence",start:{...t[n][1].start},end:d},o={type:l>1?"strongText":"emphasisText",start:{...t[r][1].end},end:{...t[n][1].start}},i={type:l>1?"strong":"emphasis",start:{...s.start},end:{...a.end}},t[r][1].end={...s.start},t[n][1].start={...a.end},c=[],t[r][1].end.offset-t[r][1].start.offset&&(c=Be(c,[["enter",t[r][1],e],["exit",t[r][1],e]])),c=Be(c,[["enter",i,e],["enter",s,e],["exit",s,e],["enter",o,e]]),c=Be(c,nn(e.parser.constructs.insideSpan.null,t.slice(r+1,n),e)),c=Be(c,[["exit",o,e],["enter",a,e],["exit",a,e],["exit",i,e]]),t[n][1].end.offset-t[n][1].start.offset?(u=2,c=Be(c,[["enter",t[n][1],e],["exit",t[n][1],e]])):u=0,ue(t,r-1,n-r+3,c),n=r+c.length-u-2;break}}for(n=-1;++n<t.length;)t[n][1].type==="attentionSequence"&&(t[n][1].type="data");return t}function $x(t,e){let n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=_t(r),o;return s;function s(l){return o=l,t.enter("attentionSequence"),a(l)}function a(l){if(l===o)return t.consume(l),a;let c=t.exit("attentionSequence"),u=_t(l),f=!u||u===2&&i||n.includes(l),d=!i||i===2&&u||n.includes(r);return c._open=!!(o===42?f:f&&(i||!d)),c._close=!!(o===42?d:d&&(u||!f)),e(l)}}function Md(t,e){t.column+=e,t.offset+=e,t._bufferIndex+=e}var Ia={name:"autolink",tokenize:Hx};function Hx(t,e,n){let r=0;return i;function i(p){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),o}function o(p){return ye(p)?(t.consume(p),s):p===64?n(p):c(p)}function s(p){return p===43||p===45||p===46||ke(p)?(r=1,a(p)):c(p)}function a(p){return p===58?(t.consume(p),r=0,l):(p===43||p===45||p===46||ke(p))&&r++<32?(t.consume(p),a):(r=0,c(p))}function l(p){return p===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),e):p===null||p===32||p===60||Tn(p)?n(p):(t.consume(p),l)}function c(p){return p===64?(t.consume(p),u):kd(p)?(t.consume(p),c):n(p)}function u(p){return ke(p)?f(p):n(p)}function f(p){return p===46?(t.consume(p),r=0,u):p===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),e):d(p)}function d(p){if((p===45||ke(p))&&r++<63){let h=p===45?d:f;return t.consume(p),h}return n(p)}}var It={partial:!0,tokenize:Vx};function Vx(t,e,n){return r;function r(o){return $(o)?F(t,i,"linePrefix")(o):i(o)}function i(o){return o===null||R(o)?e(o):n(o)}}var Bo={continuation:{tokenize:jx},exit:qx,name:"blockQuote",tokenize:Wx};function Wx(t,e,n){let r=this;return i;function i(s){if(s===62){let a=r.containerState;return a.open||(t.enter("blockQuote",{_container:!0}),a.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(s),t.exit("blockQuoteMarker"),o}return n(s)}function o(s){return $(s)?(t.enter("blockQuotePrefixWhitespace"),t.consume(s),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),e):(t.exit("blockQuotePrefix"),e(s))}}function jx(t,e,n){let r=this;return i;function i(s){return $(s)?F(t,o,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):o(s)}function o(s){return t.attempt(Bo,e,n)(s)}}function qx(t){t.exit("blockQuote")}var Po={name:"characterEscape",tokenize:Kx};function Kx(t,e,n){return r;function r(o){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(o),t.exit("escapeMarker"),i}function i(o){return xd(o)?(t.enter("characterEscapeValue"),t.consume(o),t.exit("characterEscapeValue"),t.exit("characterEscape"),e):n(o)}}var Fo={name:"characterReference",tokenize:Ux};function Ux(t,e,n){let r=this,i=0,o,s;return a;function a(f){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(f),t.exit("characterReferenceMarker"),l}function l(f){return f===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(f),t.exit("characterReferenceMarkerNumeric"),c):(t.enter("characterReferenceValue"),o=31,s=ke,u(f))}function c(f){return f===88||f===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(f),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),o=6,s=bd,u):(t.enter("characterReferenceValue"),o=7,s=ki,u(f))}function u(f){if(f===59&&i){let d=t.exit("characterReferenceValue");return s===ke&&!gr(r.sliceSerialize(d))?n(f):(t.enter("characterReferenceMarker"),t.consume(f),t.exit("characterReferenceMarker"),t.exit("characterReference"),e)}return s(f)&&i++<o?(t.consume(f),u):n(f)}}var Ed={partial:!0,tokenize:Gx},zo={concrete:!0,name:"codeFenced",tokenize:Jx};function Jx(t,e,n){let r=this,i={partial:!0,tokenize:v},o=0,s=0,a;return l;function l(w){return c(w)}function c(w){let N=r.events[r.events.length-1];return o=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[1],!0).length:0,a=w,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),u(w)}function u(w){return w===a?(s++,t.consume(w),u):s<3?n(w):(t.exit("codeFencedFenceSequence"),$(w)?F(t,f,"whitespace")(w):f(w))}function f(w){return w===null||R(w)?(t.exit("codeFencedFence"),r.interrupt?e(w):t.check(Ed,m,I)(w)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),d(w))}function d(w){return w===null||R(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),f(w)):$(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),F(t,p,"whitespace")(w)):w===96&&w===a?n(w):(t.consume(w),d)}function p(w){return w===null||R(w)?f(w):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),h(w))}function h(w){return w===null||R(w)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),f(w)):w===96&&w===a?n(w):(t.consume(w),h)}function m(w){return t.attempt(i,I,g)(w)}function g(w){return t.enter("lineEnding"),t.consume(w),t.exit("lineEnding"),y}function y(w){return o>0&&$(w)?F(t,x,"linePrefix",o+1)(w):x(w)}function x(w){return w===null||R(w)?t.check(Ed,m,I)(w):(t.enter("codeFlowValue"),C(w))}function C(w){return w===null||R(w)?(t.exit("codeFlowValue"),x(w)):(t.consume(w),C)}function I(w){return t.exit("codeFenced"),e(w)}function v(w,N,O){let L=0;return S;function S(j){return w.enter("lineEnding"),w.consume(j),w.exit("lineEnding"),ce}function ce(j){return w.enter("codeFencedFence"),$(j)?F(w,X,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):X(j)}function X(j){return j===a?(w.enter("codeFencedFenceSequence"),B(j)):O(j)}function B(j){return j===a?(L++,w.consume(j),B):L>=s?(w.exit("codeFencedFenceSequence"),$(j)?F(w,W,"whitespace")(j):W(j)):O(j)}function W(j){return j===null||R(j)?(w.exit("codeFencedFence"),N(j)):O(j)}}}function Gx(t,e,n){let r=this;return i;function i(s){return s===null?n(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}var xi={name:"codeIndented",tokenize:Xx},Qx={partial:!0,tokenize:Yx};function Xx(t,e,n){let r=this;return i;function i(c){return t.enter("codeIndented"),F(t,o,"linePrefix",5)(c)}function o(c){let u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?s(c):n(c)}function s(c){return c===null?l(c):R(c)?t.attempt(Qx,s,l)(c):(t.enter("codeFlowValue"),a(c))}function a(c){return c===null||R(c)?(t.exit("codeFlowValue"),s(c)):(t.consume(c),a)}function l(c){return t.exit("codeIndented"),e(c)}}function Yx(t,e,n){let r=this;return i;function i(s){return r.parser.lazy[r.now().line]?n(s):R(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),i):F(t,o,"linePrefix",5)(s)}function o(s){let a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):R(s)?i(s):n(s)}}var va={name:"codeText",previous:ew,resolve:Zx,tokenize:tw};function Zx(t){let e=t.length-4,n=3,r,i;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(r=n;++r<e;)if(t[r][1].type==="codeTextData"){t[n][1].type="codeTextPadding",t[e][1].type="codeTextPadding",n+=2,e-=2;break}}for(r=n-1,e++;++r<=e;)i===void 0?r!==e&&t[r][1].type!=="lineEnding"&&(i=r):(r===e||t[r][1].type==="lineEnding")&&(t[i][1].type="codeTextData",r!==i+2&&(t[i][1].end=t[r-1][1].end,t.splice(i+2,r-i-2),e-=r-i-2,r=i+2),i=void 0);return t}function ew(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function tw(t,e,n){let r=this,i=0,o,s;return a;function a(d){return t.enter("codeText"),t.enter("codeTextSequence"),l(d)}function l(d){return d===96?(t.consume(d),i++,l):(t.exit("codeTextSequence"),c(d))}function c(d){return d===null?n(d):d===32?(t.enter("space"),t.consume(d),t.exit("space"),c):d===96?(s=t.enter("codeTextSequence"),o=0,f(d)):R(d)?(t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),c):(t.enter("codeTextData"),u(d))}function u(d){return d===null||d===32||d===96||R(d)?(t.exit("codeTextData"),c(d)):(t.consume(d),u)}function f(d){return d===96?(t.consume(d),o++,f):o===i?(t.exit("codeTextSequence"),t.exit("codeText"),e(d)):(s.type="codeTextData",u(d))}}var _o=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,n){let r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(e,r):e>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(e,n,r){let i=n||0;this.setCursor(Math.trunc(e));let o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&wi(this.left,r),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),wi(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),wi(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){let n=this.left.splice(e,Number.POSITIVE_INFINITY);wi(this.right,n.reverse())}else{let n=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);wi(this.left,n.reverse())}}};function wi(t,e){let n=0;if(e.length<1e4)t.push(...e);else for(;n<e.length;)t.push(...e.slice(n,n+1e4)),n+=1e4}function $o(t){let e={},n=-1,r,i,o,s,a,l,c,u=new _o(t);for(;++n<u.length;){for(;n in e;)n=e[n];if(r=u.get(n),n&&r[1].type==="chunkFlow"&&u.get(n-1)[1].type==="listItemPrefix"&&(l=r[1]._tokenizer.events,o=0,o<l.length&&l[o][1].type==="lineEndingBlank"&&(o+=2),o<l.length&&l[o][1].type==="content"))for(;++o<l.length&&l[o][1].type!=="content";)l[o][1].type==="chunkText"&&(l[o][1]._isInFirstContentOfListItem=!0,o++);if(r[0]==="enter")r[1].contentType&&(Object.assign(e,nw(u,n)),n=e[n],c=!0);else if(r[1]._container){for(o=n,i=void 0;o--;)if(s=u.get(o),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(i&&(u.get(i)[1].type="lineEndingBlank"),s[1].type="lineEnding",i=o);else if(!(s[1].type==="linePrefix"||s[1].type==="listItemIndent"))break;i&&(r[1].end={...u.get(i)[1].start},a=u.slice(i,n),a.unshift(r),u.splice(i,n-i+1,a))}}return ue(t,0,Number.POSITIVE_INFINITY,u.slice(0)),!c}function nw(t,e){let n=t.get(e)[1],r=t.get(e)[2],i=e-1,o=[],s=n._tokenizer;s||(s=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(s._contentTypeTextTrailing=!0));let a=s.events,l=[],c={},u,f,d=-1,p=n,h=0,m=0,g=[m];for(;p;){for(;t.get(++i)[1]!==p;);o.push(i),p._tokenizer||(u=r.sliceStream(p),p.next||u.push(null),f&&s.defineSkip(p.start),p._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(u),p._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),f=p,p=p.next}for(p=n;++d<a.length;)a[d][0]==="exit"&&a[d-1][0]==="enter"&&a[d][1].type===a[d-1][1].type&&a[d][1].start.line!==a[d][1].end.line&&(m=d+1,g.push(m),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(s.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),d=g.length;d--;){let y=a.slice(g[d],g[d+1]),x=o.pop();l.push([x,x+y.length-1]),t.splice(x,2,y)}for(l.reverse(),d=-1;++d<l.length;)c[h+l[d][0]]=h+l[d][1],h+=l[d][1]-l[d][0]-1;return c}var Aa={resolve:iw,tokenize:ow},rw={partial:!0,tokenize:sw};function iw(t){return $o(t),t}function ow(t,e){let n;return r;function r(a){return t.enter("content"),n=t.enter("chunkContent",{contentType:"content"}),i(a)}function i(a){return a===null?o(a):R(a)?t.check(rw,s,o)(a):(t.consume(a),i)}function o(a){return t.exit("chunkContent"),t.exit("content"),e(a)}function s(a){return t.consume(a),t.exit("chunkContent"),n.next=t.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,i}}function sw(t,e,n){let r=this;return i;function i(s){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),F(t,o,"linePrefix")}function o(s){if(s===null||R(s))return n(s);let a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):t.interrupt(r.parser.constructs.flow,n,e)(s)}}function Ho(t,e,n,r,i,o,s,a,l){let c=l||Number.POSITIVE_INFINITY,u=0;return f;function f(y){return y===60?(t.enter(r),t.enter(i),t.enter(o),t.consume(y),t.exit(o),d):y===null||y===32||y===41||Tn(y)?n(y):(t.enter(r),t.enter(s),t.enter(a),t.enter("chunkString",{contentType:"string"}),m(y))}function d(y){return y===62?(t.enter(o),t.consume(y),t.exit(o),t.exit(i),t.exit(r),e):(t.enter(a),t.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(t.exit("chunkString"),t.exit(a),d(y)):y===null||y===60||R(y)?n(y):(t.consume(y),y===92?h:p)}function h(y){return y===60||y===62||y===92?(t.consume(y),p):p(y)}function m(y){return!u&&(y===null||y===41||U(y))?(t.exit("chunkString"),t.exit(a),t.exit(s),t.exit(r),e(y)):u<c&&y===40?(t.consume(y),u++,m):y===41?(t.consume(y),u--,m):y===null||y===32||y===40||Tn(y)?n(y):(t.consume(y),y===92?g:m)}function g(y){return y===40||y===41||y===92?(t.consume(y),m):m(y)}}function Vo(t,e,n,r,i,o){let s=this,a=0,l;return c;function c(p){return t.enter(r),t.enter(i),t.consume(p),t.exit(i),t.enter(o),u}function u(p){return a>999||p===null||p===91||p===93&&!l||p===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?n(p):p===93?(t.exit(o),t.enter(i),t.consume(p),t.exit(i),t.exit(r),e):R(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),f(p))}function f(p){return p===null||p===91||p===93||R(p)||a++>999?(t.exit("chunkString"),u(p)):(t.consume(p),l||(l=!$(p)),p===92?d:f)}function d(p){return p===91||p===92||p===93?(t.consume(p),a++,f):f(p)}}function Wo(t,e,n,r,i,o){let s;return a;function a(d){return d===34||d===39||d===40?(t.enter(r),t.enter(i),t.consume(d),t.exit(i),s=d===40?41:d,l):n(d)}function l(d){return d===s?(t.enter(i),t.consume(d),t.exit(i),t.exit(r),e):(t.enter(o),c(d))}function c(d){return d===s?(t.exit(o),l(s)):d===null?n(d):R(d)?(t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),F(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(d))}function u(d){return d===s||d===null||R(d)?(t.exit("chunkString"),c(d)):(t.consume(d),d===92?f:u)}function f(d){return d===s||d===92?(t.consume(d),u):u(d)}}function vn(t,e){let n;return r;function r(i){return R(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),n=!0,r):$(i)?F(t,r,n?"linePrefix":"lineSuffix")(i):e(i)}}var Na={name:"definition",tokenize:lw},aw={partial:!0,tokenize:cw};function lw(t,e,n){let r=this,i;return o;function o(p){return t.enter("definition"),s(p)}function s(p){return Vo.call(r,t,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return i=Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(t.enter("definitionMarker"),t.consume(p),t.exit("definitionMarker"),l):n(p)}function l(p){return U(p)?vn(t,c)(p):c(p)}function c(p){return Ho(t,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return t.attempt(aw,f,f)(p)}function f(p){return $(p)?F(t,d,"whitespace")(p):d(p)}function d(p){return p===null||R(p)?(t.exit("definition"),r.parser.defined.push(i),e(p)):n(p)}}function cw(t,e,n){return r;function r(a){return U(a)?vn(t,i)(a):n(a)}function i(a){return Wo(t,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return $(a)?F(t,s,"whitespace")(a):s(a)}function s(a){return a===null||R(a)?e(a):n(a)}}var Ra={name:"hardBreakEscape",tokenize:uw};function uw(t,e,n){return r;function r(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return R(o)?(t.exit("hardBreakEscape"),e(o)):n(o)}}var Da={name:"headingAtx",resolve:fw,tokenize:dw};function fw(t,e){let n=t.length-2,r=3,i,o;return t[r][1].type==="whitespace"&&(r+=2),n-2>r&&t[n][1].type==="whitespace"&&(n-=2),t[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&t[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:t[r][1].start,end:t[n][1].end},o={type:"chunkText",start:t[r][1].start,end:t[n][1].end,contentType:"text"},ue(t,r,n-r+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function dw(t,e,n){let r=0;return i;function i(u){return t.enter("atxHeading"),o(u)}function o(u){return t.enter("atxHeadingSequence"),s(u)}function s(u){return u===35&&r++<6?(t.consume(u),s):u===null||U(u)?(t.exit("atxHeadingSequence"),a(u)):n(u)}function a(u){return u===35?(t.enter("atxHeadingSequence"),l(u)):u===null||R(u)?(t.exit("atxHeading"),e(u)):$(u)?F(t,a,"whitespace")(u):(t.enter("atxHeadingText"),c(u))}function l(u){return u===35?(t.consume(u),l):(t.exit("atxHeadingSequence"),a(u))}function c(u){return u===null||u===35||U(u)?(t.exit("atxHeadingText"),a(u)):(t.consume(u),c)}}var Td=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Oa=["pre","script","style","textarea"];var La={concrete:!0,name:"htmlFlow",resolveTo:mw,tokenize:gw},pw={partial:!0,tokenize:kw},hw={partial:!0,tokenize:yw};function mw(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function gw(t,e,n){let r=this,i,o,s,a,l;return c;function c(b){return u(b)}function u(b){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(b),f}function f(b){return b===33?(t.consume(b),d):b===47?(t.consume(b),o=!0,m):b===63?(t.consume(b),i=3,r.interrupt?e:k):ye(b)?(t.consume(b),s=String.fromCharCode(b),g):n(b)}function d(b){return b===45?(t.consume(b),i=2,p):b===91?(t.consume(b),i=5,a=0,h):ye(b)?(t.consume(b),i=4,r.interrupt?e:k):n(b)}function p(b){return b===45?(t.consume(b),r.interrupt?e:k):n(b)}function h(b){let qe="CDATA[";return b===qe.charCodeAt(a++)?(t.consume(b),a===qe.length?r.interrupt?e:X:h):n(b)}function m(b){return ye(b)?(t.consume(b),s=String.fromCharCode(b),g):n(b)}function g(b){if(b===null||b===47||b===62||U(b)){let qe=b===47,Sn=s.toLowerCase();return!qe&&!o&&Oa.includes(Sn)?(i=1,r.interrupt?e(b):X(b)):Td.includes(s.toLowerCase())?(i=6,qe?(t.consume(b),y):r.interrupt?e(b):X(b)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(b):o?x(b):C(b))}return b===45||ke(b)?(t.consume(b),s+=String.fromCharCode(b),g):n(b)}function y(b){return b===62?(t.consume(b),r.interrupt?e:X):n(b)}function x(b){return $(b)?(t.consume(b),x):S(b)}function C(b){return b===47?(t.consume(b),S):b===58||b===95||ye(b)?(t.consume(b),I):$(b)?(t.consume(b),C):S(b)}function I(b){return b===45||b===46||b===58||b===95||ke(b)?(t.consume(b),I):v(b)}function v(b){return b===61?(t.consume(b),w):$(b)?(t.consume(b),v):C(b)}function w(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(t.consume(b),l=b,N):$(b)?(t.consume(b),w):O(b)}function N(b){return b===l?(t.consume(b),l=null,L):b===null||R(b)?n(b):(t.consume(b),N)}function O(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||U(b)?v(b):(t.consume(b),O)}function L(b){return b===47||b===62||$(b)?C(b):n(b)}function S(b){return b===62?(t.consume(b),ce):n(b)}function ce(b){return b===null||R(b)?X(b):$(b)?(t.consume(b),ce):n(b)}function X(b){return b===45&&i===2?(t.consume(b),le):b===60&&i===1?(t.consume(b),ge):b===62&&i===4?(t.consume(b),tt):b===63&&i===3?(t.consume(b),k):b===93&&i===5?(t.consume(b),Et):R(b)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(pw,Bt,B)(b)):b===null||R(b)?(t.exit("htmlFlowData"),B(b)):(t.consume(b),X)}function B(b){return t.check(hw,W,Bt)(b)}function W(b){return t.enter("lineEnding"),t.consume(b),t.exit("lineEnding"),j}function j(b){return b===null||R(b)?B(b):(t.enter("htmlFlowData"),X(b))}function le(b){return b===45?(t.consume(b),k):X(b)}function ge(b){return b===47?(t.consume(b),s="",ft):X(b)}function ft(b){if(b===62){let qe=s.toLowerCase();return Oa.includes(qe)?(t.consume(b),tt):X(b)}return ye(b)&&s.length<8?(t.consume(b),s+=String.fromCharCode(b),ft):X(b)}function Et(b){return b===93?(t.consume(b),k):X(b)}function k(b){return b===62?(t.consume(b),tt):b===45&&i===2?(t.consume(b),k):X(b)}function tt(b){return b===null||R(b)?(t.exit("htmlFlowData"),Bt(b)):(t.consume(b),tt)}function Bt(b){return t.exit("htmlFlow"),e(b)}}function yw(t,e,n){let r=this;return i;function i(s){return R(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o):n(s)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}function kw(t,e,n){return r;function r(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(It,e,n)}}var Ba={name:"htmlText",tokenize:bw};function bw(t,e,n){let r=this,i,o,s;return a;function a(k){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(k),l}function l(k){return k===33?(t.consume(k),c):k===47?(t.consume(k),v):k===63?(t.consume(k),C):ye(k)?(t.consume(k),O):n(k)}function c(k){return k===45?(t.consume(k),u):k===91?(t.consume(k),o=0,h):ye(k)?(t.consume(k),x):n(k)}function u(k){return k===45?(t.consume(k),p):n(k)}function f(k){return k===null?n(k):k===45?(t.consume(k),d):R(k)?(s=f,ge(k)):(t.consume(k),f)}function d(k){return k===45?(t.consume(k),p):f(k)}function p(k){return k===62?le(k):k===45?d(k):f(k)}function h(k){let tt="CDATA[";return k===tt.charCodeAt(o++)?(t.consume(k),o===tt.length?m:h):n(k)}function m(k){return k===null?n(k):k===93?(t.consume(k),g):R(k)?(s=m,ge(k)):(t.consume(k),m)}function g(k){return k===93?(t.consume(k),y):m(k)}function y(k){return k===62?le(k):k===93?(t.consume(k),y):m(k)}function x(k){return k===null||k===62?le(k):R(k)?(s=x,ge(k)):(t.consume(k),x)}function C(k){return k===null?n(k):k===63?(t.consume(k),I):R(k)?(s=C,ge(k)):(t.consume(k),C)}function I(k){return k===62?le(k):C(k)}function v(k){return ye(k)?(t.consume(k),w):n(k)}function w(k){return k===45||ke(k)?(t.consume(k),w):N(k)}function N(k){return R(k)?(s=N,ge(k)):$(k)?(t.consume(k),N):le(k)}function O(k){return k===45||ke(k)?(t.consume(k),O):k===47||k===62||U(k)?L(k):n(k)}function L(k){return k===47?(t.consume(k),le):k===58||k===95||ye(k)?(t.consume(k),S):R(k)?(s=L,ge(k)):$(k)?(t.consume(k),L):le(k)}function S(k){return k===45||k===46||k===58||k===95||ke(k)?(t.consume(k),S):ce(k)}function ce(k){return k===61?(t.consume(k),X):R(k)?(s=ce,ge(k)):$(k)?(t.consume(k),ce):L(k)}function X(k){return k===null||k===60||k===61||k===62||k===96?n(k):k===34||k===39?(t.consume(k),i=k,B):R(k)?(s=X,ge(k)):$(k)?(t.consume(k),X):(t.consume(k),W)}function B(k){return k===i?(t.consume(k),i=void 0,j):k===null?n(k):R(k)?(s=B,ge(k)):(t.consume(k),B)}function W(k){return k===null||k===34||k===39||k===60||k===61||k===96?n(k):k===47||k===62||U(k)?L(k):(t.consume(k),W)}function j(k){return k===47||k===62||U(k)?L(k):n(k)}function le(k){return k===62?(t.consume(k),t.exit("htmlTextData"),t.exit("htmlText"),e):n(k)}function ge(k){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(k),t.exit("lineEnding"),ft}function ft(k){return $(k)?F(t,Et,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):Et(k)}function Et(k){return t.enter("htmlTextData"),s(k)}}var An={name:"labelEnd",resolveAll:Cw,resolveTo:Mw,tokenize:Ew},xw={tokenize:Tw},ww={tokenize:Iw},Sw={tokenize:vw};function Cw(t){let e=-1,n=[];for(;++e<t.length;){let r=t[e][1];if(n.push(t[e]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){let i=r.type==="labelImage"?4:2;r.type="data",e+=i}}return t.length!==n.length&&ue(t,0,t.length,n),t}function Mw(t,e){let n=t.length,r=0,i,o,s,a;for(;n--;)if(i=t[n][1],o){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;t[n][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(s){if(t[n][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(o=n,i.type!=="labelLink")){r=2;break}}else i.type==="labelEnd"&&(s=n);let l={type:t[o][1].type==="labelLink"?"link":"image",start:{...t[o][1].start},end:{...t[t.length-1][1].end}},c={type:"label",start:{...t[o][1].start},end:{...t[s][1].end}},u={type:"labelText",start:{...t[o+r+2][1].end},end:{...t[s-2][1].start}};return a=[["enter",l,e],["enter",c,e]],a=Be(a,t.slice(o+1,o+r+3)),a=Be(a,[["enter",u,e]]),a=Be(a,nn(e.parser.constructs.insideSpan.null,t.slice(o+r+4,s-3),e)),a=Be(a,[["exit",u,e],t[s-2],t[s-1],["exit",c,e]]),a=Be(a,t.slice(s+1)),a=Be(a,[["exit",l,e]]),ue(t,o,t.length,a),t}function Ew(t,e,n){let r=this,i=r.events.length,o,s;for(;i--;)if((r.events[i][1].type==="labelImage"||r.events[i][1].type==="labelLink")&&!r.events[i][1]._balanced){o=r.events[i][1];break}return a;function a(d){return o?o._inactive?f(d):(s=r.parser.defined.includes(Ne(r.sliceSerialize({start:o.end,end:r.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(d),t.exit("labelMarker"),t.exit("labelEnd"),l):n(d)}function l(d){return d===40?t.attempt(xw,u,s?u:f)(d):d===91?t.attempt(ww,u,s?c:f)(d):s?u(d):f(d)}function c(d){return t.attempt(Sw,u,f)(d)}function u(d){return e(d)}function f(d){return o._balanced=!0,n(d)}}function Tw(t,e,n){return r;function r(f){return t.enter("resource"),t.enter("resourceMarker"),t.consume(f),t.exit("resourceMarker"),i}function i(f){return U(f)?vn(t,o)(f):o(f)}function o(f){return f===41?u(f):Ho(t,s,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(f)}function s(f){return U(f)?vn(t,l)(f):u(f)}function a(f){return n(f)}function l(f){return f===34||f===39||f===40?Wo(t,c,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(f):u(f)}function c(f){return U(f)?vn(t,u)(f):u(f)}function u(f){return f===41?(t.enter("resourceMarker"),t.consume(f),t.exit("resourceMarker"),t.exit("resource"),e):n(f)}}function Iw(t,e,n){let r=this;return i;function i(a){return Vo.call(r,t,o,s,"reference","referenceMarker","referenceString")(a)}function o(a){return r.parser.defined.includes(Ne(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?e(a):n(a)}function s(a){return n(a)}}function vw(t,e,n){return r;function r(o){return t.enter("reference"),t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),i}function i(o){return o===93?(t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),t.exit("reference"),e):n(o)}}var Pa={name:"labelStartImage",resolveAll:An.resolveAll,tokenize:Aw};function Aw(t,e,n){let r=this;return i;function i(a){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(a),t.exit("labelImageMarker"),o}function o(a){return a===91?(t.enter("labelMarker"),t.consume(a),t.exit("labelMarker"),t.exit("labelImage"),s):n(a)}function s(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):e(a)}}var Fa={name:"labelStartLink",resolveAll:An.resolveAll,tokenize:Nw};function Nw(t,e,n){let r=this;return i;function i(s){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(s),t.exit("labelMarker"),t.exit("labelLink"),o}function o(s){return s===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(s):e(s)}}var Si={name:"lineEnding",tokenize:Rw};function Rw(t,e){return n;function n(r){return t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),F(t,e,"linePrefix")}}var Nn={name:"thematicBreak",tokenize:Dw};function Dw(t,e,n){let r=0,i;return o;function o(c){return t.enter("thematicBreak"),s(c)}function s(c){return i=c,a(c)}function a(c){return c===i?(t.enter("thematicBreakSequence"),l(c)):r>=3&&(c===null||R(c))?(t.exit("thematicBreak"),e(c)):n(c)}function l(c){return c===i?(t.consume(c),r++,l):(t.exit("thematicBreakSequence"),$(c)?F(t,a,"whitespace")(c):a(c))}}var Re={continuation:{tokenize:Pw},exit:zw,name:"list",tokenize:Bw},Ow={partial:!0,tokenize:_w},Lw={partial:!0,tokenize:Fw};function Bw(t,e,n){let r=this,i=r.events[r.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(p){let h=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(h==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:ki(p)){if(r.containerState.type||(r.containerState.type=h,t.enter(h,{_container:!0})),h==="listUnordered")return t.enter("listItemPrefix"),p===42||p===45?t.check(Nn,n,c)(p):c(p);if(!r.interrupt||p===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),l(p)}return n(p)}function l(p){return ki(p)&&++s<10?(t.consume(p),l):(!r.interrupt||s<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(t.exit("listItemValue"),c(p)):n(p)}function c(p){return t.enter("listItemMarker"),t.consume(p),t.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,t.check(It,r.interrupt?n:u,t.attempt(Ow,d,f))}function u(p){return r.containerState.initialBlankLine=!0,o++,d(p)}function f(p){return $(p)?(t.enter("listItemPrefixWhitespace"),t.consume(p),t.exit("listItemPrefixWhitespace"),d):n(p)}function d(p){return r.containerState.size=o+r.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(p)}}function Pw(t,e,n){let r=this;return r.containerState._closeFlow=void 0,t.check(It,i,o);function i(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,F(t,e,"listItemIndent",r.containerState.size+1)(a)}function o(a){return r.containerState.furtherBlankLines||!$(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,t.attempt(Lw,e,s)(a))}function s(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,F(t,t.attempt(Re,e,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function Fw(t,e,n){let r=this;return F(t,i,"listItemIndent",r.containerState.size+1);function i(o){let s=r.events[r.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===r.containerState.size?e(o):n(o)}}function zw(t){t.exit(this.containerState.type)}function _w(t,e,n){let r=this;return F(t,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){let s=r.events[r.events.length-1];return!$(o)&&s&&s[1].type==="listItemPrefixWhitespace"?e(o):n(o)}}var jo={name:"setextUnderline",resolveTo:$w,tokenize:Hw};function $w(t,e){let n=t.length,r,i,o;for(;n--;)if(t[n][0]==="enter"){if(t[n][1].type==="content"){r=n;break}t[n][1].type==="paragraph"&&(i=n)}else t[n][1].type==="content"&&t.splice(n,1),!o&&t[n][1].type==="definition"&&(o=n);let s={type:"setextHeading",start:{...t[r][1].start},end:{...t[t.length-1][1].end}};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",s,e]),t.splice(o+1,0,["exit",t[r][1],e]),t[r][1].end={...t[o][1].end}):t[r][1]=s,t.push(["exit",s,e]),t}function Hw(t,e,n){let r=this,i;return o;function o(c){let u=r.events.length,f;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){f=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||f)?(t.enter("setextHeadingLine"),i=c,s(c)):n(c)}function s(c){return t.enter("setextHeadingLineSequence"),a(c)}function a(c){return c===i?(t.consume(c),a):(t.exit("setextHeadingLineSequence"),$(c)?F(t,l,"lineSuffix")(c):l(c))}function l(c){return c===null||R(c)?(t.exit("setextHeadingLine"),e(c)):n(c)}}var Id={tokenize:Vw};function Vw(t){let e=this,n=t.attempt(It,r,t.attempt(this.parser.constructs.flowInitial,i,F(t,t.attempt(this.parser.constructs.flow,i,t.attempt(Aa,i)),"linePrefix")));return n;function r(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,n}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,n}}var vd={resolveAll:Dd()},Ad=Rd("string"),Nd=Rd("text");function Rd(t){return{resolveAll:Dd(t==="text"?Ww:void 0),tokenize:e};function e(n){let r=this,i=this.parser.constructs[t],o=n.attempt(i,s,a);return s;function s(u){return c(u)?o(u):a(u)}function a(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),l}function l(u){return c(u)?(n.exit("data"),o(u)):(n.consume(u),l)}function c(u){if(u===null)return!0;let f=i[u],d=-1;if(f)for(;++d<f.length;){let p=f[d];if(!p.previous||p.previous.call(r,r.previous))return!0}return!1}}}function Dd(t){return e;function e(n,r){let i=-1,o;for(;++i<=n.length;)o===void 0?n[i]&&n[i][1].type==="data"&&(o=i,i++):(!n[i]||n[i][1].type!=="data")&&(i!==o+2&&(n[o][1].end=n[i-1][1].end,n.splice(o+2,i-o-2),i=o+2),o=void 0);return t?t(n,r):n}}function Ww(t,e){let n=0;for(;++n<=t.length;)if((n===t.length||t[n][1].type==="lineEnding")&&t[n-1][1].type==="data"){let r=t[n-1][1],i=e.sliceStream(r),o=i.length,s=-1,a=0,l;for(;o--;){let c=i[o];if(typeof c=="string"){for(s=c.length;c.charCodeAt(s-1)===32;)a++,s--;if(s)break;s=-1}else if(c===-2)l=!0,a++;else if(c!==-1){o++;break}}if(e._contentTypeTextTrailing&&n===t.length&&(a=0),a){let c={type:n===t.length||l||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?s:r.start._bufferIndex+s,_index:r.start._index+o,line:r.end.line,column:r.end.column-a,offset:r.end.offset-a},end:{...r.end}};r.end={...c.start},r.start.offset===r.end.offset?Object.assign(r,c):(t.splice(n,0,["enter",c,e],["exit",c,e]),n+=2)}n++}return t}var za={};Cx(za,{attentionMarkers:()=>Xw,contentInitial:()=>qw,disable:()=>Yw,document:()=>jw,flow:()=>Uw,flowInitial:()=>Kw,insideSpan:()=>Qw,string:()=>Jw,text:()=>Gw});var jw={42:Re,43:Re,45:Re,48:Re,49:Re,50:Re,51:Re,52:Re,53:Re,54:Re,55:Re,56:Re,57:Re,62:Bo},qw={91:Na},Kw={[-2]:xi,[-1]:xi,32:xi},Uw={35:Da,42:Nn,45:[jo,Nn],60:La,61:jo,95:Nn,96:zo,126:zo},Jw={38:Fo,92:Po},Gw={[-5]:Si,[-4]:Si,[-3]:Si,33:Pa,38:Fo,42:bi,60:[Ia,Ba],91:Fa,92:[Ra,Po],93:An,95:bi,96:va},Qw={null:[bi,vd]},Xw={null:[42,95]},Yw={null:[]};function Od(t,e,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},o=[],s=[],a=[],l=!0,c={attempt:L(N),check:L(O),consume:I,enter:v,exit:w,interrupt:L(O,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:g,parser:t,previous:null,sliceSerialize:h,sliceStream:m,write:p},f=e.tokenize.call(u,c),d;return e.resolveAll&&o.push(e),u;function p(B){return s=Be(s,B),x(),s[s.length-1]!==null?[]:(S(e,0),u.events=nn(o,u.events,u),u.events)}function h(B,W){return e1(m(B),W)}function m(B){return Zw(s,B)}function g(){let{_bufferIndex:B,_index:W,line:j,column:le,offset:ge}=r;return{_bufferIndex:B,_index:W,line:j,column:le,offset:ge}}function y(B){i[B.line]=B.column,X()}function x(){let B;for(;r._index<s.length;){let W=s[r._index];if(typeof W=="string")for(B=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===B&&r._bufferIndex<W.length;)C(W.charCodeAt(r._bufferIndex));else C(W)}}function C(B){l=void 0,d=B,f=f(B)}function I(B){R(B)?(r.line++,r.column=1,r.offset+=B===-3?2:1,X()):B!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===s[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=B,l=!0}function v(B,W){let j=W||{};return j.type=B,j.start=g(),u.events.push(["enter",j,u]),a.push(j),j}function w(B){let W=a.pop();return W.end=g(),u.events.push(["exit",W,u]),W}function N(B,W){S(B,W.from)}function O(B,W){W.restore()}function L(B,W){return j;function j(le,ge,ft){let Et,k,tt,Bt;return Array.isArray(le)?qe(le):"tokenize"in le?qe([le]):b(le);function b(Ee){return mi;function mi(Pt){let Cn=Pt!==null&&Ee[Pt],pr=Pt!==null&&Ee.null,Ca=[...Array.isArray(Cn)?Cn:Cn?[Cn]:[],...Array.isArray(pr)?pr:pr?[pr]:[]];return qe(Ca)(Pt)}}function qe(Ee){return Et=Ee,k=0,Ee.length===0?ft:Sn(Ee[k])}function Sn(Ee){return mi;function mi(Pt){return Bt=ce(),tt=Ee,Ee.partial||(u.currentConstruct=Ee),Ee.name&&u.parser.constructs.disable.null.includes(Ee.name)?No(Pt):Ee.tokenize.call(W?Object.assign(Object.create(u),W):u,c,Sa,No)(Pt)}}function Sa(Ee){return l=!0,B(tt,Bt),ge}function No(Ee){return l=!0,Bt.restore(),++k<Et.length?Sn(Et[k]):ft}}}function S(B,W){B.resolveAll&&!o.includes(B)&&o.push(B),B.resolve&&ue(u.events,W,u.events.length-W,B.resolve(u.events.slice(W),u)),B.resolveTo&&(u.events=B.resolveTo(u.events,u))}function ce(){let B=g(),W=u.previous,j=u.currentConstruct,le=u.events.length,ge=Array.from(a);return{from:le,restore:ft};function ft(){r=B,u.previous=W,u.currentConstruct=j,u.events.length=le,a=ge,X()}}function X(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function Zw(t,e){let n=e.start._index,r=e.start._bufferIndex,i=e.end._index,o=e.end._bufferIndex,s;if(n===i)s=[t[n].slice(r,o)];else{if(s=t.slice(n,i),r>-1){let a=s[0];typeof a=="string"?s[0]=a.slice(r):s.shift()}o>0&&s.push(t[i].slice(0,o))}return s}function e1(t,e){let n=-1,r=[],i;for(;++n<t.length;){let o=t[n],s;if(typeof o=="string")s=o;else switch(o){case-5:{s="\r";break}case-4:{s=` `;break}case-3:{s=`\r `;break}case-2:{s=e?" ":" ";break}case-1:{if(!e&&i)continue;s=" ";break}default:s=String.fromCharCode(o)}i=o===-2,r.push(s)}return r.join("")}function _a(t){let r={constructs:Oo([za,...(t||{}).extensions||[]]),content:i(wd),defined:[],document:i(Cd),flow:i(Id),lazy:{},string:i(Ad),text:i(Nd)};return r;function i(o){return s;function s(a){return Od(r,o,a)}}}function $a(t){for(;!$o(t););return t}var Ld=/[\0\t\n\r]/g;function Ha(){let t=1,e="",n=!0,r;return i;function i(o,s,a){let l=[],c,u,f,d,p;for(o=e+(typeof o=="string"?o.toString():new TextDecoder(s||void 0).decode(o)),f=0,e="",n&&(o.charCodeAt(0)===65279&&f++,n=void 0);f<o.length;){if(Ld.lastIndex=f,c=Ld.exec(o),d=c&&c.index!==void 0?c.index:o.length,p=o.charCodeAt(d),!c){e=o.slice(f);break}if(p===10&&f===d&&r)l.push(-3),r=void 0;else switch(r&&(l.push(-5),r=void 0),f<d&&(l.push(o.slice(f,d)),t+=d-f),p){case 0:{l.push(65533),t++;break}case 9:{for(u=Math.ceil(t/4)*4,l.push(-2);t++<u;)l.push(-1);break}case 10:{l.push(-4),t=1;break}default:r=!0,t=1}f=d+1}return a&&(r&&l.push(-5),e&&l.push(e),l.push(null)),l}}var t1=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function qo(t){return t.replace(t1,n1)}function n1(t,e,n){if(e)return e;if(n.charCodeAt(0)===35){let i=n.charCodeAt(1),o=i===120||i===88;return Lo(n.slice(o?2:1),o?16:10)}return gr(n)||t}function rn(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?Bd(t.position):"start"in t||"end"in t?Bd(t):"line"in t||"column"in t?Va(t):""}function Va(t){return Pd(t&&t.line)+":"+Pd(t&&t.column)}function Bd(t){return Va(t&&t.start)+"-"+Va(t&&t.end)}function Pd(t){return t&&typeof t=="number"?t:1}var zd={}.hasOwnProperty;function Wa(t,e,n){return e&&typeof e=="object"&&(n=e,e=void 0),r1(n)($a(_a(n).document().write(Ha()(t,e,!0))))}function r1(t){let e={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(td),autolinkProtocol:L,autolinkEmail:L,atxHeading:o(Yf),blockQuote:o(Pt),characterEscape:L,characterReference:L,codeFenced:o(Cn),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:o(Cn,s),codeText:o(pr,s),codeTextData:L,data:L,codeFlowValue:L,definition:o(Ca),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:o(ux),hardBreakEscape:o(Zf),hardBreakTrailing:o(Zf),htmlFlow:o(ed,s),htmlFlowData:L,htmlText:o(ed,s),htmlTextData:L,image:o(fx),label:s,link:o(td),listItem:o(dx),listItemValue:d,listOrdered:o(nd,f),listUnordered:o(nd),paragraph:o(px),reference:b,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:o(Yf),strong:o(hx),thematicBreak:o(gx)},exit:{atxHeading:l(),atxHeadingSequence:v,autolink:l(),autolinkEmail:mi,autolinkProtocol:Ee,blockQuote:l(),characterEscapeValue:S,characterReferenceMarkerHexadecimal:Sn,characterReferenceMarkerNumeric:Sn,characterReferenceValue:Sa,characterReference:No,codeFenced:l(g),codeFencedFence:m,codeFencedFenceInfo:p,codeFencedFenceMeta:h,codeFlowValue:S,codeIndented:l(y),codeText:l(j),codeTextData:S,data:S,definition:l(),definitionDestinationString:I,definitionLabelString:x,definitionTitleString:C,emphasis:l(),hardBreakEscape:l(X),hardBreakTrailing:l(X),htmlFlow:l(B),htmlFlowData:S,htmlText:l(W),htmlTextData:S,image:l(ge),label:Et,labelText:ft,lineEnding:ce,link:l(le),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:qe,resourceDestinationString:k,resourceTitleString:tt,resource:Bt,setextHeading:l(O),setextHeadingLineSequence:N,setextHeadingText:w,strong:l(),thematicBreak:l()}};_d(e,(t||{}).mdastExtensions||[]);let n={};return r;function r(T){let D={type:"root",children:[]},q={stack:[D],tokenStack:[],config:e,enter:a,exit:c,buffer:s,resume:u,data:n},Q=[],oe=-1;for(;++oe<T.length;)if(T[oe][1].type==="listOrdered"||T[oe][1].type==="listUnordered")if(T[oe][0]==="enter")Q.push(oe);else{let dt=Q.pop();oe=i(T,dt,oe)}for(oe=-1;++oe<T.length;){let dt=e[T[oe][0]];zd.call(dt,T[oe][1].type)&&dt[T[oe][1].type].call(Object.assign({sliceSerialize:T[oe][2].sliceSerialize},q),T[oe][1])}if(q.tokenStack.length>0){let dt=q.tokenStack[q.tokenStack.length-1];(dt[1]||Fd).call(q,void 0,dt[0])}for(D.position={start:on(T.length>0?T[0][1].start:{line:1,column:1,offset:0}),end:on(T.length>0?T[T.length-2][1].end:{line:1,column:1,offset:0})},oe=-1;++oe<e.transforms.length;)D=e.transforms[oe](D)||D;return D}function i(T,D,q){let Q=D-1,oe=-1,dt=!1,Mn,Ft,gi,yi;for(;++Q<=q;){let Ke=T[Q];switch(Ke[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ke[0]==="enter"?oe++:oe--,yi=void 0;break}case"lineEndingBlank":{Ke[0]==="enter"&&(Mn&&!yi&&!oe&&!gi&&(gi=Q),yi=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:yi=void 0}if(!oe&&Ke[0]==="enter"&&Ke[1].type==="listItemPrefix"||oe===-1&&Ke[0]==="exit"&&(Ke[1].type==="listUnordered"||Ke[1].type==="listOrdered")){if(Mn){let hr=Q;for(Ft=void 0;hr--;){let zt=T[hr];if(zt[1].type==="lineEnding"||zt[1].type==="lineEndingBlank"){if(zt[0]==="exit")continue;Ft&&(T[Ft][1].type="lineEndingBlank",dt=!0),zt[1].type="lineEnding",Ft=hr}else if(!(zt[1].type==="linePrefix"||zt[1].type==="blockQuotePrefix"||zt[1].type==="blockQuotePrefixWhitespace"||zt[1].type==="blockQuoteMarker"||zt[1].type==="listItemIndent"))break}gi&&(!Ft||gi<Ft)&&(Mn._spread=!0),Mn.end=Object.assign({},Ft?T[Ft][1].start:Ke[1].end),T.splice(Ft||Q,0,["exit",Mn,Ke[2]]),Q++,q++}if(Ke[1].type==="listItemPrefix"){let hr={type:"listItem",_spread:!1,start:Object.assign({},Ke[1].start),end:void 0};Mn=hr,T.splice(Q,0,["enter",hr,Ke[2]]),Q++,q++,gi=void 0,yi=!0}}}return T[D][1]._spread=dt,q}function o(T,D){return q;function q(Q){a.call(this,T(Q),Q),D&&D.call(this,Q)}}function s(){this.stack.push({type:"fragment",children:[]})}function a(T,D,q){this.stack[this.stack.length-1].children.push(T),this.stack.push(T),this.tokenStack.push([D,q||void 0]),T.position={start:on(D.start),end:void 0}}function l(T){return D;function D(q){T&&T.call(this,q),c.call(this,q)}}function c(T,D){let q=this.stack.pop(),Q=this.tokenStack.pop();if(Q)Q[0].type!==T.type&&(D?D.call(this,T,Q[0]):(Q[1]||Fd).call(this,T,Q[0]));else throw new Error("Cannot close `"+T.type+"` ("+rn({start:T.start,end:T.end})+"): it\u2019s not open");q.position.end=on(T.end)}function u(){return En(this.stack.pop())}function f(){this.data.expectingFirstListItemValue=!0}function d(T){if(this.data.expectingFirstListItemValue){let D=this.stack[this.stack.length-2];D.start=Number.parseInt(this.sliceSerialize(T),10),this.data.expectingFirstListItemValue=void 0}}function p(){let T=this.resume(),D=this.stack[this.stack.length-1];D.lang=T}function h(){let T=this.resume(),D=this.stack[this.stack.length-1];D.meta=T}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function g(){let T=this.resume(),D=this.stack[this.stack.length-1];D.value=T.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function y(){let T=this.resume(),D=this.stack[this.stack.length-1];D.value=T.replace(/(\r?\n|\r)$/g,"")}function x(T){let D=this.resume(),q=this.stack[this.stack.length-1];q.label=D,q.identifier=Ne(this.sliceSerialize(T)).toLowerCase()}function C(){let T=this.resume(),D=this.stack[this.stack.length-1];D.title=T}function I(){let T=this.resume(),D=this.stack[this.stack.length-1];D.url=T}function v(T){let D=this.stack[this.stack.length-1];if(!D.depth){let q=this.sliceSerialize(T).length;D.depth=q}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function N(T){let D=this.stack[this.stack.length-1];D.depth=this.sliceSerialize(T).codePointAt(0)===61?1:2}function O(){this.data.setextHeadingSlurpLineEnding=void 0}function L(T){let q=this.stack[this.stack.length-1].children,Q=q[q.length-1];(!Q||Q.type!=="text")&&(Q=mx(),Q.position={start:on(T.start),end:void 0},q.push(Q)),this.stack.push(Q)}function S(T){let D=this.stack.pop();D.value+=this.sliceSerialize(T),D.position.end=on(T.end)}function ce(T){let D=this.stack[this.stack.length-1];if(this.data.atHardBreak){let q=D.children[D.children.length-1];q.position.end=on(T.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&e.canContainEols.includes(D.type)&&(L.call(this,T),S.call(this,T))}function X(){this.data.atHardBreak=!0}function B(){let T=this.resume(),D=this.stack[this.stack.length-1];D.value=T}function W(){let T=this.resume(),D=this.stack[this.stack.length-1];D.value=T}function j(){let T=this.resume(),D=this.stack[this.stack.length-1];D.value=T}function le(){let T=this.stack[this.stack.length-1];if(this.data.inReference){let D=this.data.referenceType||"shortcut";T.type+="Reference",T.referenceType=D,delete T.url,delete T.title}else delete T.identifier,delete T.label;this.data.referenceType=void 0}function ge(){let T=this.stack[this.stack.length-1];if(this.data.inReference){let D=this.data.referenceType||"shortcut";T.type+="Reference",T.referenceType=D,delete T.url,delete T.title}else delete T.identifier,delete T.label;this.data.referenceType=void 0}function ft(T){let D=this.sliceSerialize(T),q=this.stack[this.stack.length-2];q.label=qo(D),q.identifier=Ne(D).toLowerCase()}function Et(){let T=this.stack[this.stack.length-1],D=this.resume(),q=this.stack[this.stack.length-1];if(this.data.inReference=!0,q.type==="link"){let Q=T.children;q.children=Q}else q.alt=D}function k(){let T=this.resume(),D=this.stack[this.stack.length-1];D.url=T}function tt(){let T=this.resume(),D=this.stack[this.stack.length-1];D.title=T}function Bt(){this.data.inReference=void 0}function b(){this.data.referenceType="collapsed"}function qe(T){let D=this.resume(),q=this.stack[this.stack.length-1];q.label=D,q.identifier=Ne(this.sliceSerialize(T)).toLowerCase(),this.data.referenceType="full"}function Sn(T){this.data.characterReferenceType=T.type}function Sa(T){let D=this.sliceSerialize(T),q=this.data.characterReferenceType,Q;q?(Q=Lo(D,q==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Q=gr(D);let oe=this.stack[this.stack.length-1];oe.value+=Q}function No(T){let D=this.stack.pop();D.position.end=on(T.end)}function Ee(T){S.call(this,T);let D=this.stack[this.stack.length-1];D.url=this.sliceSerialize(T)}function mi(T){S.call(this,T);let D=this.stack[this.stack.length-1];D.url="mailto:"+this.sliceSerialize(T)}function Pt(){return{type:"blockquote",children:[]}}function Cn(){return{type:"code",lang:null,meta:null,value:""}}function pr(){return{type:"inlineCode",value:""}}function Ca(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ux(){return{type:"emphasis",children:[]}}function Yf(){return{type:"heading",depth:0,children:[]}}function Zf(){return{type:"break"}}function ed(){return{type:"html",value:""}}function fx(){return{type:"image",title:null,url:"",alt:null}}function td(){return{type:"link",title:null,url:"",children:[]}}function nd(T){return{type:"list",ordered:T.type==="listOrdered",start:null,spread:T._spread,children:[]}}function dx(T){return{type:"listItem",spread:T._spread,checked:null,children:[]}}function px(){return{type:"paragraph",children:[]}}function hx(){return{type:"strong",children:[]}}function mx(){return{type:"text",value:""}}function gx(){return{type:"thematicBreak"}}}function on(t){return{line:t.line,column:t.column,offset:t.offset}}function _d(t,e){let n=-1;for(;++n<e.length;){let r=e[n];Array.isArray(r)?_d(t,r):i1(t,r)}}function i1(t,e){let n;for(n in e)if(zd.call(e,n))switch(n){case"canContainEols":{let r=e[n];r&&t[n].push(...r);break}case"transforms":{let r=e[n];r&&t[n].push(...r);break}case"enter":case"exit":{let r=e[n];r&&Object.assign(t[n],r);break}}}function Fd(t,e){throw t?new Error("Cannot close `"+t.type+"` ("+rn({start:t.start,end:t.end})+"): a different token (`"+e.type+"`, "+rn({start:e.start,end:e.end})+") is open"):new Error("Cannot close document, a token (`"+e.type+"`, "+rn({start:e.start,end:e.end})+") is still open")}function yr(t){let e=this;e.parser=n;function n(r){return Wa(r,{...e.data("settings"),...t,extensions:e.data("micromarkExtensions")||[],mdastExtensions:e.data("fromMarkdownExtensions")||[]})}}var $d={}.hasOwnProperty;function Hd(t,e){let n=e||{};function r(i,...o){let s=r.invalid,a=r.handlers;if(i&&$d.call(i,t)){let l=String(i[t]);s=$d.call(a,l)?a[l]:r.unknown}if(s)return s.call(this,i,...o)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var o1={}.hasOwnProperty;function ja(t,e){let n=-1,r;if(e.extensions)for(;++n<e.extensions.length;)ja(t,e.extensions[n]);for(r in e)if(o1.call(e,r))switch(r){case"extensions":break;case"unsafe":{Vd(t[r],e[r]);break}case"join":{Vd(t[r],e[r]);break}case"handlers":{s1(t[r],e[r]);break}default:t.options[r]=e[r]}return t}function Vd(t,e){e&&t.push(...e)}function s1(t,e){e&&Object.assign(t,e)}function Wd(t,e,n,r){let i=n.enter("blockquote"),o=n.createTracker(r);o.move("> "),o.shift(2);let s=n.indentLines(n.containerFlow(t,o.current()),a1);return i(),s}function a1(t,e,n){return">"+(n?"":" ")+t}function Ko(t,e){return jd(t,e.inConstruct,!0)&&!jd(t,e.notInConstruct,!1)}function jd(t,e,n){if(typeof e=="string"&&(e=[e]),!e||e.length===0)return n;let r=-1;for(;++r<e.length;)if(t.includes(e[r]))return!0;return!1}function qa(t,e,n,r){let i=-1;for(;++i<n.unsafe.length;)if(n.unsafe[i].character===` @@ -36,14 +36,14 @@ `);else if(s.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(s.linebreakReplacement.create())){let a=r.split(/\r?\n|\r/);for(let l=0;l<a.length;l++)l&&this.insertNode(s.linebreakReplacement.create(),n,!0),a[l]&&this.insertNode(s.text(a[l]),n,!/\S/.test(a[l]));r=""}else r=r.replace(/\r?\n|\r/g," ");else if(r=r.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(r)&&this.open==this.nodes.length-1){let a=i.content[i.content.length-1],l=e.previousSibling;(!a||l&&l.nodeName=="BR"||a.isText&&/[ \t\r\n\u000c]$/.test(a.text))&&(r=r.slice(1))}r&&this.insertNode(s.text(r),n,!/\S/.test(r)),this.findInText(e)}else this.findInside(e)}addElement(e,n,r){let i=this.localPreserveWS,o=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let s=e.nodeName.toLowerCase(),a;sh.hasOwnProperty(s)&&this.parser.normalizeLists&&lS(e);let l=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,r));e:if(l?l.ignore:aS.hasOwnProperty(s))this.findInside(e),this.ignoreFallback(e,n);else if(!l||l.skip||l.closeParent){l&&l.closeParent?this.open=Math.max(0,this.open-1):l&&l.skip.nodeType&&(e=l.skip);let c,u=this.needsBlock;if(oh.hasOwnProperty(s))o.content.length&&o.content[0].isInline&&this.open&&(this.open--,o=this.top),c=!0,o.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,n);break e}let f=l&&l.skip?n:this.readStyles(e,n);f&&this.addAll(e,f),c&&this.sync(o),this.needsBlock=u}else{let c=this.readStyles(e,n);c&&this.addElementByRule(e,l,c,l.consuming===!1?a:void 0)}this.localPreserveWS=i}leafFallback(e,n){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(` `),n)}ignoreFallback(e,n){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),n,!0)}readStyles(e,n){let r=e.style;if(r&&r.length)for(let i=0;i<this.parser.matchedStyles.length;i++){let o=this.parser.matchedStyles[i],s=r.getPropertyValue(o);if(s)for(let a=void 0;;){let l=this.parser.matchStyle(o,s,this,a);if(!l)break;if(l.ignore)return null;if(l.clearMark?n=n.filter(c=>!l.clearMark(c)):n=n.concat(this.parser.schema.marks[l.mark].create(l.attrs)),l.consuming===!1)a=l;else break}}return n}addElementByRule(e,n,r,i){let o,s;if(n.node)if(s=this.parser.schema.nodes[n.node],s.isLeaf)this.insertNode(s.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let l=this.enter(s,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 a=this.top;if(s&&s.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(l=>this.insertNode(l,r,!1));else{let l=e;typeof n.contentElement=="string"?l=e.querySelector(n.contentElement):typeof n.contentElement=="function"?l=n.contentElement(e):n.contentElement&&(l=n.contentElement),this.findAround(e,l,!0),this.addAll(l,r),this.findAround(e,l,!1)}o&&this.sync(a)&&this.open--}addAll(e,n,r,i){let o=r||0;for(let s=r?e.childNodes[r]:e.firstChild,a=i==null?null:e.childNodes[i];s!=a;s=s.nextSibling,++o)this.findAtPoint(e,o),this.addDOM(s,n);this.findAtPoint(e,o)}findPlace(e,n,r){let i,o;for(let s=this.open,a=0;s>=0;s--){let l=this.nodes[s],c=l.findWrapping(e);if(c&&(!i||i.length>c.length+a)&&(i=c,o=l,!c.length))break;if(l.solid){if(r)break;a+=2}}if(!i)return null;this.sync(o);for(let s=0;s<i.length;s++)n=this.enterInner(i[s],null,n,!1);return n}insertNode(e,n,r){if(e.isInline&&this.needsBlock&&!this.top.type){let o=this.textblockFromContext();o&&(n=this.enterInner(o,null,n))}let i=this.findPlace(e,n,r);if(i){this.closeExtra();let o=this.top;o.match&&(o.match=o.match.matchType(e.type));let s=J.none;for(let a of i.concat(e.marks))(o.type?o.type.allowsMarkType(a.type):$p(a.type,e.type))&&(s=a.addToSet(s));return o.content.push(e.mark(s)),!0}return!1}enter(e,n,r,i){let o=this.findPlace(e.create(n),r,!1);return o&&(o=this.enterInner(e,n,r,!0,i)),o}enterInner(e,n,r,i=!1,o){this.closeExtra();let s=this.top;s.match=s.match&&s.match.matchType(e);let a=zp(e,o,s.options);s.options&Ai&&s.content.length==0&&(a|=Ai);let l=J.none;return r=r.filter(c=>(s.type?s.type.allowsMarkType(c.type):$p(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new Cr(e,n,l,i,null,a)),this.open++,r}closeExtra(e=!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(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Oi)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==e&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&e.nodeType==1&&e.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(e,n,r){if(e!=n&&this.find)for(let i=0;i<this.find.length;i++)this.find[i].pos==null&&e.nodeType==1&&e.contains(this.find[i].node)&&n.compareDocumentPosition(this.find[i].node)&(r?2:4)&&(this.find[i].pos=this.currentPos)}findInText(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&(this.find[n].pos=this.currentPos-(e.nodeValue.length-this.find[n].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(i?0:1),s=(a,l)=>{for(;a>=0;a--){let c=n[a];if(c==""){if(a==n.length-1||a==0)continue;for(;l>=o;l--)if(s(a-1,l))return!0;return!1}else{let u=l>0||l==0&&i?this.nodes[l].type:r&&l>=o?r.node(l-o).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;l--}}return!0};return s(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.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 lS(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&sh.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function cS(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function _p(t){let e={};for(let n in t)e[n]=t[n];return e}function $p(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let o=[],s=a=>{o.push(a);for(let l=0;l<a.edgeCount;l++){let{type:c,next:u}=a.edge(l);if(c==e||o.indexOf(u)<0&&s(u))return!0}};if(s(i.contentMatch))return!0}}var cn=class t{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=ns(n).createDocumentFragment());let i=r,o=[];return e.forEach(s=>{if(o.length||s.marks.length){let a=0,l=0;for(;a<o.length&&l<s.marks.length;){let c=s.marks[l];if(!this.marks[c.type.name]){l++;continue}if(!c.eq(o[a][0])||c.type.spec.spanning===!1)break;a++,l++}for(;a<o.length;)i=o.pop()[1];for(;l<s.marks.length;){let c=s.marks[l++],u=this.serializeMark(c,s.isInline,n);u&&(o.push([c,i]),i.appendChild(u.dom),i=u.contentDOM||u.dom)}}i.appendChild(this.serializeNodeInner(s,n))}),r}serializeNodeInner(e,n){if(e.isText)return ns(n).createTextNode(e.text);let{dom:r,contentDOM:i}=rs(ns(n),this.nodes[e.type.name](e),null,e.attrs);if(i){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,n,i)}return r}serializeNode(e,n={}){let r=this.serializeNodeInner(e,n);for(let i=e.marks.length-1;i>=0;i--){let o=this.serializeMark(e.marks[i],e.isInline,n);o&&((o.contentDOM||o.dom).appendChild(r),r=o.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&rs(ns(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return typeof n=="string"?{dom:e.createTextNode(n)}:rs(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new t(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=Hp(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return Hp(e.marks)}};function Hp(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function ns(t){return t.document||window.document}var Vp=new WeakMap;function uS(t){let e=Vp.get(t);return e===void 0&&Vp.set(t,e=fS(t)),e}function fS(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i<r.length;i++)n(r[i]);else for(let i in r)n(r[i])}return n(t),e}function rs(t,e,n,r){if(e.nodeType==1)return{dom:e};if(e.dom&&e.dom.nodeType==1)return e;let i=e[0],o;if(typeof i!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(o=uS(r))&&o.indexOf(e)>-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let s=i.indexOf(" ");s>0&&(n=i.slice(0,s),i=i.slice(s+1));let a,l=n?t.createElementNS(n,i):t.createElement(i),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let f in c)if(c[f]!=null){let d=f.indexOf(" ");d>0?l.setAttributeNS(f.slice(0,d),f.slice(d+1),c[f]):f=="style"&&l.style?l.style.cssText=c[f]:l.setAttribute(f,c[f])}}for(let f=u;f<e.length;f++){let d=e[f];if(d===0){if(f<e.length-1||f>u)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(t.createTextNode(d));else{let{dom:p,contentDOM:h}=rs(t,d,n,r);if(l.appendChild(p),h){if(a)throw new RangeError("Multiple content holes");a=h}}}return{dom:l,contentDOM:a}}var ch=65535,uh=Math.pow(2,16);function dS(t,e){return t+e*uh}function ah(t){return t&ch}function pS(t){return(t-(t&ch))/uh}var fh=1,dh=2,us=4,ph=8,Pi=class{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&ph)>0}get deletedBefore(){return(this.delInfo&(fh|us))>0}get deletedAfter(){return(this.delInfo&(dh|us))>0}get deletedAcross(){return(this.delInfo&us)>0}},$t=class t{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&t.empty)return t.empty}recover(e){let n=0,r=ah(e);if(!this.inverted)for(let i=0;i<r;i++)n+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[r*3]+n+pS(e)}mapResult(e,n=1){return this._map(e,n,!1)}map(e,n=1){return this._map(e,n,!0)}_map(e,n,r){let i=0,o=this.inverted?2:1,s=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?i:0);if(l>e)break;let c=this.ranges[a+o],u=this.ranges[a+s],f=l+c;if(e<=f){let d=c?e==l?-1:e==f?1:n:n,p=l+i+(d<0?0:u);if(r)return p;let h=e==(n<0?l:f)?null:dS(a/3,e-l),m=e==l?dh:e==f?fh:us;return(n<0?e!=l:e!=f)&&(m|=ph),new Pi(p,m,h)}i+=u-c}return r?e+i:new Pi(e+i,0,null)}touches(e,n){let r=0,i=ah(n),o=this.inverted?2:1,s=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?r:0);if(l>e)break;let c=this.ranges[a+o],u=l+c;if(e<=u&&a==i*3)return!0;r+=this.ranges[a+s]-c}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,o=0;i<this.ranges.length;i+=3){let s=this.ranges[i],a=s-(this.inverted?o:0),l=s+(this.inverted?0:o),c=this.ranges[i+n],u=this.ranges[i+r];e(a,a+c,l,l+u),o+=u-c}}invert(){return new t(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?t.empty:new t(e<0?[0,-e,0]:[0,0,e])}};$t.empty=new $t([]);var Cl=class t{constructor(e,n,r=0,i=e?e.length:0){this.mirror=n,this.from=r,this.to=i,this._maps=e||[],this.ownData=!(e||n)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new t(this._maps,this.mirror,e,n)}appendMap(e,n){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),n!=null&&this.setMirror(this._maps.length-1,n)}appendMapping(e){for(let n=0,r=this._maps.length;n<e._maps.length;n++){let i=e.getMirror(n);this.appendMap(e._maps[n],i!=null&&i<n?r+i:void 0)}}getMirror(e){if(this.mirror){for(let n=0;n<this.mirror.length;n++)if(this.mirror[n]==e)return this.mirror[n+(n%2?-1:1)]}}setMirror(e,n){this.mirror||(this.mirror=[]),this.mirror.push(e,n)}appendMappingInverted(e){for(let n=e.maps.length-1,r=this._maps.length+e._maps.length;n>=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new t;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;r<this.to;r++)e=this._maps[r].map(e,n);return e}mapResult(e,n=1){return this._map(e,n,!1)}_map(e,n,r){let i=0;for(let o=this.from;o<this.to;o++){let s=this._maps[o],a=s.mapResult(e,n);if(a.recover!=null){let l=this.getMirror(o);if(l!=null&&l>o&&l<this.to){o=l,e=this._maps[l].recover(a.recover);continue}}i|=a.delInfo,e=a.pos}return r?e:new Pi(e,i,null)}},xl=Object.create(null),we=class{getMap(){return $t.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=xl[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in xl)throw new RangeError("Duplicate use of step JSON ID "+e);return xl[e]=n,n.prototype.jsonID=e,n}},Te=class t{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new t(e,null)}static fail(e){return new t(null,e)}static fromReplace(e,n,r,i){try{return t.ok(e.replace(n,r,i))}catch(o){if(o instanceof an)return t.fail(o.message);throw o}}};function Tl(t,e,n){let r=[];for(let i=0;i<t.childCount;i++){let o=t.child(i);o.content.size&&(o=o.copy(Tl(o.content,e,o))),o.isInline&&(o=e(o,n,i)),r.push(o)}return E.fromArray(r)}var _n=class t extends we{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=e.resolve(this.from),i=r.node(r.sharedDepth(this.to)),o=new A(Tl(n.content,(s,a)=>!s.isAtom||!a.type.allowsMarkType(this.mark.type)?s:s.mark(this.mark.addToSet(s.marks)),i),n.openStart,n.openEnd);return Te.fromReplace(e,this.from,this.to,o)}invert(){return new $n(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};we.jsonID("addMark",_n);var $n=class t extends we{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new A(Tl(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return Te.fromReplace(e,this.from,this.to,r)}invert(){return new _n(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};we.jsonID("removeMark",$n);var Fi=class t extends we{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Te.fromReplace(e,this.pos,this.pos+1,new A(E.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let i=0;i<n.marks.length;i++)if(!n.marks[i].isInSet(r))return new t(this.pos,n.marks[i]);return new t(this.pos,this.mark)}}return new Mr(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};we.jsonID("addNodeMark",Fi);var Mr=class t extends we{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Te.fromReplace(e,this.pos,this.pos+1,new A(E.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new Fi(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};we.jsonID("removeNodeMark",Mr);var pe=class t extends we{constructor(e,n,r,i=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=i}apply(e){return this.structure&&Ml(e,this.from,this.to)?Te.fail("Structure replace would overwrite content"):Te.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new $t([this.from,this.to-this.from,this.slice.size])}invert(e){return new t(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.to,-1),r=this.from==this.to&&t.MAP_BIAS<0?n:e.mapResult(this.from,1);return r.deletedAcross&&n.deletedAcross?null:new t(r.pos,Math.max(r.pos,n.pos),this.slice,this.structure)}merge(e){if(!(e instanceof t)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let n=this.slice.size+e.slice.size==0?A.empty:new A(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new t(this.from,this.to+(e.to-e.from),n,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let n=this.slice.size+e.slice.size==0?A.empty:new A(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new t(e.from,this.to,n,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new t(n.from,n.to,A.fromJSON(e,n.slice),!!n.structure)}};pe.MAP_BIAS=1;we.jsonID("replace",pe);var Ie=class t extends we{constructor(e,n,r,i,o,s,a=!1){super(),this.from=e,this.to=n,this.gapFrom=r,this.gapTo=i,this.slice=o,this.insert=s,this.structure=a}apply(e){if(this.structure&&(Ml(e,this.from,this.gapFrom)||Ml(e,this.gapTo,this.to)))return Te.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Te.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?Te.fromReplace(e,this.from,this.to,r):Te.fail("Content does not fit in gap")}getMap(){return new $t([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let n=this.gapTo-this.gapFrom;return new t(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),i=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),o=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||i<n.pos||o>r.pos?null:new t(n.pos,r.pos,i,o,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,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 t(n.from,n.to,n.gapFrom,n.gapTo,A.fromJSON(e,n.slice),n.insert,!!n.structure)}};we.jsonID("replaceAround",Ie);function Ml(t,e,n){let r=t.resolve(e),i=n-e,o=r.depth;for(;i>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,i--;if(i>0){let s=r.node(o).maybeChild(r.indexAfter(o));for(;i>0;){if(!s||s.isLeaf)return!0;s=s.firstChild,i--}}return!1}function hS(t,e,n,r){let i=[],o=[],s,a;t.doc.nodesBetween(e,n,(l,c,u)=>{if(!l.isInline)return;let f=l.marks;if(!r.isInSet(f)&&u.type.allowsMarkType(r.type)){let d=Math.max(c,e),p=Math.min(c+l.nodeSize,n),h=r.addToSet(f);for(let m=0;m<f.length;m++)f[m].isInSet(h)||(s&&s.to==d&&s.mark.eq(f[m])?s.to=p:i.push(s=new $n(d,p,f[m])));a&&a.to==d?a.to=p:o.push(a=new _n(d,p,r))}}),i.forEach(l=>t.step(l)),o.forEach(l=>t.step(l))}function mS(t,e,n,r){let i=[],o=0;t.doc.nodesBetween(e,n,(s,a)=>{if(!s.isInline)return;o++;let l=null;if(r instanceof Di){let c=s.marks,u;for(;u=r.isInSet(c);)(l||(l=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(s.marks)&&(l=[r]):l=s.marks;if(l&&l.length){let c=Math.min(a+s.nodeSize,n);for(let u=0;u<l.length;u++){let f=l[u],d;for(let p=0;p<i.length;p++){let h=i[p];h.step==o-1&&f.eq(i[p].style)&&(d=h)}d?(d.to=c,d.step=o):i.push({style:f,from:Math.max(a,e),to:c,step:o})}}}),i.forEach(s=>t.step(new $n(s.from,s.to,s.style)))}function Il(t,e,n,r=n.contentMatch,i=!0){let o=t.doc.nodeAt(e),s=[],a=e+1;for(let l=0;l<o.childCount;l++){let c=o.child(l),u=a+c.nodeSize,f=r.matchType(c.type);if(!f)s.push(new pe(a,u,A.empty));else{r=f;for(let d=0;d<c.marks.length;d++)n.allowsMarkType(c.marks[d].type)||t.step(new $n(a,u,c.marks[d]));if(i&&c.isText&&n.whitespace!="pre"){let d,p=/\r?\n|\r/g,h;for(;d=p.exec(c.text);)h||(h=new A(E.from(n.schema.text(" ",n.allowedMarks(c.marks))),0,0)),s.push(new pe(a+d.index,a+d.index+d[0].length,h))}}a=u}if(!r.validEnd){let l=r.fillBefore(E.empty,!0);t.replace(a,a,new A(l,0,0))}for(let l=s.length-1;l>=0;l--)t.step(s[l])}function gS(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ir(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,o=0;;--r){let s=t.$from.node(r),a=t.$from.index(r)+i,l=t.$to.indexAfter(r)-o;if(r<t.depth&&s.canReplace(a,l,n))return r;if(r==0||s.type.spec.isolating||!gS(s,a,l))break;a&&(i=1),l<s.childCount&&(o=1)}return null}function yS(t,e,n){let{$from:r,$to:i,depth:o}=e,s=r.before(o+1),a=i.after(o+1),l=s,c=a,u=E.empty,f=0;for(let h=o,m=!1;h>n;h--)m||r.index(h)>0?(m=!0,u=E.from(r.node(h).copy(u)),f++):l--;let d=E.empty,p=0;for(let h=o,m=!1;h>n;h--)m||i.after(h+1)<i.end(h)?(m=!0,d=E.from(i.node(h).copy(d)),p++):c++;t.step(new Ie(l,c,s,a,new A(u.append(d),f,p),u.size-f,!0))}function Hn(t,e,n=null,r=t){let i=kS(t,e),o=i&&bS(r,e);return o?i.map(lh).concat({type:e,attrs:n}).concat(o.map(lh)):null}function lh(t){return{type:t,attrs:null}}function kS(t,e){let{parent:n,startIndex:r,endIndex:i}=t,o=n.contentMatchAt(r).findWrapping(e);if(!o)return null;let s=o.length?o[0]:e;return n.canReplaceWith(r,i,s)?o:null}function bS(t,e){let{parent:n,startIndex:r,endIndex:i}=t,o=n.child(r),s=e.contentMatch.findWrapping(o.type);if(!s)return null;let l=(s.length?s[s.length-1]:e).contentMatch;for(let c=r;l&&c<i;c++)l=l.matchType(n.child(c).type);return!l||!l.validEnd?null:s}function xS(t,e,n){let r=E.empty;for(let s=n.length-1;s>=0;s--){if(r.size){let a=n[s].type.contentMatch.matchFragment(r);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=E.from(n[s].type.create(n[s].attrs,r))}let i=e.start,o=e.end;t.step(new Ie(i,o,i,o,new A(r,0,0),n.length,!0))}function wS(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=t.steps.length;t.doc.nodesBetween(e,n,(s,a)=>{let l=typeof i=="function"?i(s):i;if(s.isTextblock&&!s.hasMarkup(r,l)&&SS(t.doc,t.mapping.slice(o).map(a),r)){let c=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",h=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!h?c=!1:!p&&h&&(c=!0)}c===!1&&mh(t,s,a,o),Il(t,t.mapping.slice(o).map(a,1),r,void 0,c===null);let u=t.mapping.slice(o),f=u.map(a,1),d=u.map(a+s.nodeSize,1);return t.step(new Ie(f,d,f+1,d-1,new A(E.from(r.create(l,null,s.marks)),0,0),1,!0)),c===!0&&hh(t,s,a,o),!1}})}function hh(t,e,n,r){e.forEach((i,o)=>{if(i.isText){let s,a=/\r?\n|\r/g;for(;s=a.exec(i.text);){let l=t.mapping.slice(r).map(n+1+o+s.index);t.replaceWith(l,l+1,e.type.schema.linebreakReplacement.create())}}})}function mh(t,e,n,r){e.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let s=t.mapping.slice(r).map(n+1+o);t.replaceWith(s,s+1,e.type.schema.text(` `))}})}function SS(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function CS(t,e,n,r,i){let o=t.doc.nodeAt(e);if(!o)throw new RangeError("No node at given position");n||(n=o.type);let s=n.create(r,null,i||o.marks);if(o.isLeaf)return t.replaceWith(e,e+o.nodeSize,s);if(!n.validContent(o.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new Ie(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new A(E.from(s),0,0),1,!0))}function Vn(t,e,n=1,r){let i=t.resolve(e),o=i.depth-n,s=r&&r[r.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!s.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,u=n-2;c>o;c--,u--){let f=i.node(c),d=i.index(c);if(f.type.spec.isolating)return!1;let p=f.content.cutByIndex(d,f.childCount),h=r&&r[u+1];h&&(p=p.replaceChild(0,h.type.create(h.attrs)));let m=r&&r[u]||f;if(!f.canReplace(d+1,f.childCount)||!m.type.validContent(p))return!1}let a=i.indexAfter(o),l=r&&r[0];return i.node(o).canReplaceWith(a,a,l?l.type:i.node(o+1).type)}function MS(t,e,n=1,r){let i=t.doc.resolve(e),o=E.empty,s=E.empty;for(let a=i.depth,l=i.depth-n,c=n-1;a>l;a--,c--){o=E.from(i.node(a).copy(o));let u=r&&r[c];s=E.from(u?u.type.create(u.attrs,s):i.node(a).copy(s))}t.step(new pe(e,e,new A(o.append(s),n,n),!0))}function Wn(t,e){let n=t.resolve(e),r=n.index();return TS(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function ES(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;i<e.childCount;i++){let o=e.child(i),s=o.type==r?t.type.schema.nodes.text:o.type;if(n=n.matchType(s),!n||!t.type.allowsMarks(o.marks))return!1}return n.validEnd}function TS(t,e){return!!(t&&e&&!t.isLeaf&&ES(t,e))}function IS(t,e,n){let r=null,{linebreakReplacement:i}=t.doc.type.schema,o=t.doc.resolve(e-n),s=o.node().type;if(i&&s.inlineContent){let u=s.whitespace=="pre",f=!!s.contentMatch.matchType(i);u&&!f?r=!1:!u&&f&&(r=!0)}let a=t.steps.length;if(r===!1){let u=t.doc.resolve(e+n);mh(t,u.node(),u.before(),a)}s.inlineContent&&Il(t,e+n-1,s,o.node().contentMatchAt(o.index()),r==null);let l=t.mapping.slice(a),c=l.map(e-n);if(t.step(new pe(c,l.map(e+n,-1),A.empty,!0)),r===!0){let u=t.doc.resolve(c);hh(t,u.node(),u.before(),t.steps.length)}return t}function vS(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let o=r.index(i);if(r.node(i).canReplaceWith(o,o,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<r.node(i).childCount)return null}return null}function gh(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let i=n.content;for(let o=0;o<n.openStart;o++)i=i.firstChild.content;for(let o=1;o<=(n.openStart==0&&n.size?2:1);o++)for(let s=r.depth;s>=0;s--){let a=s==r.depth?0:r.pos<=(r.start(s+1)+r.end(s+1))/2?-1:1,l=r.index(s)+(a>0?1:0),c=r.node(s),u=!1;if(o==1)u=c.canReplace(l,l,i);else{let f=c.contentMatchAt(l).findWrapping(i.firstChild.type);u=f&&c.canReplaceWith(l,l,f[0])}if(u)return a==0?r.pos:a<0?r.before(s+1):r.after(s+1)}return null}function zi(t,e,n=e,r=A.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),o=t.resolve(n);return yh(i,o,r)?new pe(e,n,r):new El(i,o,r).fit()}function yh(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}var El=class{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=E.empty;for(let i=0;i<=e.depth;i++){let o=e.node(i);this.frontier.push({type:o.type,match:o.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=E.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let o=this.placed,s=r.depth,a=i.depth;for(;s&&a&&o.childCount==1;)o=o.firstChild.content,s--,a--;let l=new A(o,s,a);return e>-1?new Ie(r.pos,e,this.$to.pos,this.$to.end(),l,n):l.size||r.pos!=this.$to.pos?new pe(r.pos,i.pos,l):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r<e;r++){let o=n.firstChild;if(n.childCount>1&&(i=0),o.type.spec.isolating&&i<=r){e=r;break}n=o.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let i,o=null;r?(o=wl(this.unplaced.content,r-1).firstChild,i=o.content):i=this.unplaced.content;let s=i.firstChild;for(let a=this.depth;a>=0;a--){let{type:l,match:c}=this.frontier[a],u,f=null;if(n==1&&(s?c.matchType(s.type)||(f=c.fillBefore(E.from(s),!1)):o&&l.compatibleContent(o.type)))return{sliceDepth:r,frontierDepth:a,parent:o,inject:f};if(n==2&&s&&(u=c.findWrapping(s.type)))return{sliceDepth:r,frontierDepth:a,parent:o,wrap:u};if(o&&c.matchType(o.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=wl(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new A(e,n+1,Math.max(r,i.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=wl(e,n);if(i.childCount<=1&&n>0){let o=e.size-n<=n+i.size;this.unplaced=new A(Li(e,n-1,1),n-1,o?n-1:r)}else this.unplaced=new A(Li(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:i,wrap:o}){for(;this.depth>n;)this.closeFrontierNode();if(o)for(let m=0;m<o.length;m++)this.openFrontierNode(o[m]);let s=this.unplaced,a=r?r.content:s.content,l=s.openStart-e,c=0,u=[],{match:f,type:d}=this.frontier[n];if(i){for(let m=0;m<i.childCount;m++)u.push(i.child(m));f=f.matchFragment(i)}let p=a.size+e-(s.content.size-s.openEnd);for(;c<a.childCount;){let m=a.child(c),g=f.matchType(m.type);if(!g)break;c++,(c>1||l==0||m.content.size)&&(f=g,u.push(kh(m.mark(d.allowedMarks(m.marks)),c==1?l:0,c==a.childCount?p:-1)))}let h=c==a.childCount;h||(p=-1),this.placed=Bi(this.placed,n,E.from(u)),this.frontier[n].match=f,h&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=a;m<p;m++){let y=g.lastChild;this.frontier.push({type:y.type,match:y.contentMatchAt(y.childCount)}),g=y.content}this.unplaced=h?e==0?A.empty:new A(Li(s.content,e-1,1),e-1,p<0?s.openEnd:e-1):new A(Li(s.content,e,c),s.openStart,s.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],n;if(!e.type.isTextblock||!Sl(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(n=this.findCloseLevel(this.$to))&&n.depth==this.depth)return-1;let{depth:r}=this.$to,i=this.$to.after(r);for(;r>1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],o=n<e.depth&&e.end(n+1)==e.pos+(e.depth-(n+1)),s=Sl(e,n,i,r,o);if(s){for(let a=n-1;a>=0;a--){let{match:l,type:c}=this.frontier[a],u=Sl(e,a,c,l,!0);if(!u||u.childCount)continue e}return{depth:n,fit:s,move:o?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Bi(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),o=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,o)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=Bi(this.placed,this.depth,E.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(E.empty,!0);n.childCount&&(this.placed=Bi(this.placed,this.frontier.length,n))}};function Li(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Li(t.firstChild.content,e-1,n)))}function Bi(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Bi(t.lastChild.content,e-1,n)))}function wl(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function kh(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,kh(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(E.empty,!0)))),t.copy(r)}function Sl(t,e,n,r,i){let o=t.node(e),s=i?t.indexAfter(e):t.index(e);if(s==o.childCount&&!n.compatibleContent(o.type))return null;let a=r.fillBefore(o.content,!0,s);return a&&!AS(n,o.content,s)?a:null}function AS(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function NS(t){return t.spec.defining||t.spec.definingForContent}function RS(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let i=t.doc.resolve(e),o=t.doc.resolve(n);if(yh(i,o,r))return t.step(new pe(e,n,r));let s=xh(i,o);s[s.length-1]==0&&s.pop();let a=-(i.depth+1);s.unshift(a);for(let d=i.depth,p=i.pos-1;d>0;d--,p--){let h=i.node(d).type.spec;if(h.defining||h.definingAsContext||h.isolating)break;s.indexOf(d)>-1?a=d:i.before(d)==p&&s.splice(1,0,-d)}let l=s.indexOf(a),c=[],u=r.openStart;for(let d=r.content,p=0;;p++){let h=d.firstChild;if(c.push(h),p==r.openStart)break;d=h.content}for(let d=u-1;d>=0;d--){let p=c[d],h=NS(p.type);if(h&&!p.sameMarkup(i.node(Math.abs(a)-1)))u=d;else if(h||!p.type.isTextblock)break}for(let d=r.openStart;d>=0;d--){let p=(d+u+1)%(r.openStart+1),h=c[p];if(h)for(let m=0;m<s.length;m++){let g=s[(m+l)%s.length],y=!0;g<0&&(y=!1,g=-g);let x=i.node(g-1),C=i.index(g-1);if(x.canReplaceWith(C,C,h.type,h.marks))return t.replace(i.before(g),y?o.after(g):n,new A(bh(r.content,0,r.openStart,p),p,r.openEnd))}}let f=t.steps.length;for(let d=s.length-1;d>=0&&(t.replace(e,n,r),!(t.steps.length>f));d--){let p=s[d];p<0||(e=i.before(p),n=o.after(p))}}function bh(t,e,n,r,i){if(e<n){let o=t.firstChild;t=t.replaceChild(0,o.copy(bh(o.content,e+1,n,r,o)))}if(e>r){let o=i.contentMatchAt(0),s=o.fillBefore(t).append(t);t=s.append(o.matchFragment(s).fillBefore(E.empty,!0))}return t}function DS(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=vS(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new A(E.from(r),0,0))}function OS(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let s=r.sharedDepth(n),a=!1;for(let l=r.depth;l>s;l--)r.node(l).type.spec.isolating&&(a=!0);for(let l=i.depth;l>s;l--)i.node(l).type.spec.isolating&&(a=!0);if(!a){for(let l=r.depth;l>0&&e==r.start(l);l--)e=r.before(l);for(let l=i.depth;l>0&&n==i.start(l);l--)n=i.before(l);r=t.doc.resolve(e),i=t.doc.resolve(n)}}let o=xh(r,i);for(let s=0;s<o.length;s++){let a=o[s],l=s==o.length-1;if(l&&a==0||r.node(a).type.contentMatch.validEnd)return t.delete(r.start(a),i.end(a));if(a>0&&(l||r.node(a-1).canReplace(r.index(a-1),i.indexAfter(a-1))))return t.delete(r.before(a),i.after(a))}for(let s=1;s<=r.depth&&s<=i.depth;s++)if(e-r.start(s)==r.depth-s&&n>r.end(s)&&i.end(s)-n!=i.depth-s&&r.start(s-1)==i.start(s-1)&&r.node(s-1).canReplace(r.index(s-1),i.index(s-1)))return t.delete(r.before(s),n);t.delete(e,n)}function xh(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let o=t.start(i);if(o<t.pos-(t.depth-i)||e.end(i)>e.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(o==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==o-1)&&n.push(i)}return n}var fs=class t extends we{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return Te.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 Te.fromReplace(e,this.pos,this.pos+1,new A(E.from(i),0,n.isLeaf?0:1))}getMap(){return $t.empty}invert(e){return new t(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new t(n.pos,n.attr,n.value)}};we.jsonID("attr",fs);var ds=class t extends we{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return Te.ok(r)}getMap(){return $t.empty}invert(e){return new t(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new t(n.attr,n.value)}};we.jsonID("docAttr",ds);var Er=class extends Error{};Er=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};Er.prototype=Object.create(Error.prototype);Er.prototype.constructor=Er;Er.prototype.name="TransformError";var Tr=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Cl}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Er(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r<this.mapping.maps.length;r++){let i=this.mapping.maps[r];r&&(e=i.map(e,1),n=i.map(n,-1)),i.forEach((o,s,a,l)=>{e=Math.min(e,a),n=Math.max(n,l)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=A.empty){let i=zi(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new A(E.from(r),0,0))}delete(e,n){return this.replace(e,n,A.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return RS(this,e,n,r),this}replaceRangeWith(e,n,r){return DS(this,e,n,r),this}deleteRange(e,n){return OS(this,e,n),this}lift(e,n){return yS(this,e,n),this}join(e,n=1){return IS(this,e,n),this}wrap(e,n){return xS(this,e,n),this}setBlockType(e,n=e,r,i=null){return wS(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return CS(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new fs(e,n,r)),this}setDocAttribute(e,n){return this.step(new ds(e,n)),this}addNodeMark(e,n){return this.step(new Fi(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof J)n.isInSet(r.marks)&&this.step(new Mr(e,n));else{let i=r.marks,o,s=[];for(;o=n.isInSet(i);)s.push(new Mr(e,o)),i=o.removeFromSet(i);for(let a=s.length-1;a>=0;a--)this.step(s[a])}return this}split(e,n=1,r){return MS(this,e,n,r),this}addMark(e,n,r){return hS(this,e,n,r),this}removeMark(e,n,r){return mS(this,e,n,r),this}clearIncompatible(e,n,r){return Il(this,e,n,r),this}};var vl=Object.create(null),_=class{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new un(e.min(n),e.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 e=this.ranges;for(let n=0;n<e.length;n++)if(e[n].$from.pos!=e[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,n=A.empty){let r=n.content.lastChild,i=null;for(let a=0;a<n.openEnd;a++)i=r,r=r.lastChild;let o=e.steps.length,s=this.ranges;for(let a=0;a<s.length;a++){let{$from:l,$to:c}=s[a],u=e.mapping.slice(o);e.replaceRange(u.map(l.pos),u.map(c.pos),a?A.empty:n),a==0&&Ch(e,o,(r?r.isInline:i&&i.isTextblock)?-1:1)}}replaceWith(e,n){let r=e.steps.length,i=this.ranges;for(let o=0;o<i.length;o++){let{$from:s,$to:a}=i[o],l=e.mapping.slice(r),c=l.map(s.pos),u=l.map(a.pos);o?e.deleteRange(c,u):(e.replaceRangeWith(c,u,n),Ch(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let i=e.parent.inlineContent?new z(e):vr(e.node(0),e.parent,e.pos,e.index(),n,r);if(i)return i;for(let o=e.depth-1;o>=0;o--){let s=n<0?vr(e.node(0),e.node(o),e.before(o+1),e.index(o),n,r):vr(e.node(0),e.node(o),e.after(o+1),e.index(o)+1,n,r);if(s)return s}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new Je(e.node(0))}static atStart(e){return vr(e,e,0,0,1)||new Je(e)}static atEnd(e){return vr(e,e,e.content.size,e.childCount,-1)||new Je(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=vl[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in vl)throw new RangeError("Duplicate use of selection JSON ID "+e);return vl[e]=n,n.prototype.jsonID=e,n}getBookmark(){return z.between(this.$anchor,this.$head).getBookmark()}};_.prototype.visible=!0;var un=class{constructor(e,n){this.$from=e,this.$to=n}},wh=!1;function Sh(t){!wh&&!t.parent.inlineContent&&(wh=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var z=class t extends _{constructor(e,n=e){Sh(e),Sh(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return _.near(r);let i=e.resolve(n.map(this.anchor));return new t(i.parent.inlineContent?i:r,r)}replace(e,n=A.empty){if(super.replace(e,n),n==A.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof t&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new hs(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new t(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let o=_.findFrom(n,r,!0)||_.findFrom(n,-r,!0);if(o)n=o.$head;else return _.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=(_.findFrom(e,-r,!0)||_.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=i<0&&(e=n))),new t(e,n)}};_.jsonID("text",z);var hs=class t{constructor(e,n){this.anchor=e,this.head=n}map(e){return new t(e.map(this.anchor),e.map(this.head))}resolve(e){return z.between(e.resolve(this.anchor),e.resolve(this.head))}},H=class t extends _{constructor(e){let n=e.nodeAfter,r=e.node(0).resolve(e.pos+n.nodeSize);super(e,r),this.node=n}map(e,n){let{deleted:r,pos:i}=n.mapResult(this.anchor),o=e.resolve(i);return r?_.near(o):new t(o)}content(){return new A(E.from(this.node),0,0)}eq(e){return e instanceof t&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Nl(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new t(e.resolve(n.anchor))}static create(e,n){return new t(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};H.prototype.visible=!1;_.jsonID("node",H);var Nl=class t{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new hs(r,r):new t(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&H.isSelectable(r)?new H(n):_.near(n)}},Je=class t extends _{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=A.empty){if(n==A.empty){e.delete(0,e.doc.content.size);let r=_.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new t(e)}map(e){return new t(e)}eq(e){return e instanceof t}getBookmark(){return LS}};_.jsonID("all",Je);var LS={map(){return this},resolve(t){return new Je(t)}};function vr(t,e,n,r,i,o=!1){if(e.inlineContent)return z.create(t,n);for(let s=r-(i>0?0:1);i>0?s<e.childCount:s>=0;s+=i){let a=e.child(s);if(a.isAtom){if(!o&&H.isSelectable(a))return H.create(t,n-(i<0?a.nodeSize:0))}else{let l=vr(t,a,n+i,i<0?a.childCount:0,i,o);if(l)return l}n+=a.nodeSize*i}return null}function Ch(t,e,n){let r=t.steps.length-1;if(r<e)return;let i=t.steps[r];if(!(i instanceof pe||i instanceof Ie))return;let o=t.mapping.maps[r],s;o.forEach((a,l,c,u)=>{s==null&&(s=u)}),t.setSelection(_.near(t.doc.resolve(s),n))}var Mh=1,ps=2,Eh=4,Rl=class extends Tr{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(e){if(e.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=e,this.curSelectionFor=this.steps.length,this.updated=(this.updated|Mh)&~ps,this.storedMarks=null,this}get selectionSet(){return(this.updated&Mh)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=ps,this}ensureMarks(e){return J.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&ps)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~ps,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||J.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let o=this.storedMarks;if(!o){let s=this.doc.resolve(n);o=r==n?s.marks():s.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(e,o)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(_.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Eh,this}get scrolledIntoView(){return(this.updated&Eh)>0}};function Th(t,e){return!e||!t?t:t.bind(e)}var jn=class{constructor(e,n,r){this.name=e,this.init=Th(n.init,r),this.apply=Th(n.apply,r)}},BS=[new jn("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new jn("selection",{init(t,e){return t.selection||_.atStart(e.doc)},apply(t){return t.selection}}),new jn("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new jn("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})],_i=class{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=BS.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 jn(r.key,r.spec.state,r))})}},Ar=class t{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;r<this.config.plugins.length;r++)if(r!=n){let i=this.config.plugins[r];if(i.spec.filterTransaction&&!i.spec.filterTransaction.call(i,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let n=[e],r=this.applyInner(e),i=null;for(;;){let o=!1;for(let s=0;s<this.config.plugins.length;s++){let a=this.config.plugins[s];if(a.spec.appendTransaction){let l=i?i[s].n:0,c=i?i[s].state:this,u=l<n.length&&a.spec.appendTransaction.call(a,l?n.slice(l):n,c,r);if(u&&r.filterTransaction(u,s)){if(u.setMeta("appendedTransaction",e),!i){i=[];for(let f=0;f<this.config.plugins.length;f++)i.push(f<s?{state:r,n:n.length}:{state:this,n:0})}n.push(u),r=r.applyInner(u),o=!0}i&&(i[s]={state:r,n:n.length})}}if(!o)return{state:r,transactions:n}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let n=new t(this.config),r=this.config.fields;for(let i=0;i<r.length;i++){let o=r[i];n[o.name]=o.apply(e,this[o.name],this,n)}return n}get tr(){return new Rl(this)}static create(e){let n=new _i(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new t(n);for(let i=0;i<n.fields.length;i++)r[n.fields[i].name]=n.fields[i].init(e,r);return r}reconfigure(e){let n=new _i(this.schema,e.plugins),r=n.fields,i=new t(n);for(let o=0;o<r.length;o++){let s=r[o].name;i[s]=this.hasOwnProperty(s)?this[s]:r[o].init(e,i)}return i}toJSON(e){let n={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(n.storedMarks=this.storedMarks.map(r=>r.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],o=i.spec.state;o&&o.toJSON&&(n[r]=o.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new _i(e.schema,e.plugins),o=new t(i);return i.fields.forEach(s=>{if(s.name=="doc")o.doc=Ve.fromJSON(e.schema,n.doc);else if(s.name=="selection")o.selection=_.fromJSON(o.doc,n.selection);else if(s.name=="storedMarks")n.storedMarks&&(o.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let a in r){let l=r[a],c=l.spec.state;if(l.key==s.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(n,a)){o[s.name]=c.fromJSON.call(l,e,n[a],o);return}}o[s.name]=s.init(e,o)}}),o}};function Ih(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Ih(i,e,{})),n[r]=i}return n}var Y=class{constructor(e){this.spec=e,this.props={},e.props&&Ih(e.props,this,this.props),this.key=e.key?e.key.key:vh("plugin")}getState(e){return e[this.key]}},Al=Object.create(null);function vh(t){return t in Al?t+"$"+ ++Al[t]:(Al[t]=0,t+"$")}var te=class{constructor(e="key"){this.key=vh(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var ms=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Nh(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}var Ol=(t,e,n)=>{let r=Nh(t,n);if(!r)return!1;let i=Bl(r);if(!i){let s=r.blockRange(),a=s&&Ir(s);return a==null?!1:(e&&e(t.tr.lift(s,a).scrollIntoView()),!0)}let o=i.nodeBefore;if(Oh(t,i,e,-1))return!0;if(r.parent.content.size==0&&(Nr(o,"end")||H.isSelectable(o)))for(let s=r.depth;;s--){let a=zi(t.doc,r.before(s),r.after(s),A.empty);if(a&&a.slice.size<a.to-a.from){if(e){let l=t.tr.step(a);l.setSelection(Nr(o,"end")?_.findFrom(l.doc.resolve(l.mapping.map(i.pos,-1)),-1):H.create(l.doc,i.pos-o.nodeSize)),e(l.scrollIntoView())}return!0}if(s==1||r.node(s-1).childCount>1)break}return o.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView()),!0):!1},Rh=(t,e,n)=>{let r=Nh(t,n);if(!r)return!1;let i=Bl(r);return i?PS(t,i,e):!1};function PS(t,e,n){let r=e.nodeBefore,i=r,o=e.pos-1;for(;!i.isTextblock;o--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let s=e.nodeAfter,a=s,l=e.pos+1;for(;!a.isTextblock;l++){if(a.type.spec.isolating)return!1;let u=a.firstChild;if(!u)return!1;a=u}let c=zi(t.doc,o,l,A.empty);if(!c||c.from!=o||c instanceof pe&&c.slice.size>=l-o)return!1;if(n){let u=t.tr.step(c);u.setSelection(z.create(u.doc,o)),n(u.scrollIntoView())}return!0}function Nr(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}var Ll=(t,e,n)=>{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;o=Bl(r)}let s=o&&o.nodeBefore;return!s||!H.isSelectable(s)?!1:(e&&e(t.tr.setSelection(H.create(t.doc,o.pos-s.nodeSize)).scrollIntoView()),!0)};function Bl(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function FS(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}var zS=(t,e,n)=>{let r=FS(t,n);if(!r)return!1;let i=Dh(r);if(!i)return!1;let o=i.nodeAfter;if(Oh(t,i,e,1))return!0;if(r.parent.content.size==0&&(Nr(o,"start")||H.isSelectable(o))){let s=zi(t.doc,r.before(),r.after(),A.empty);if(s&&s.slice.size<s.to-s.from){if(e){let a=t.tr.step(s);a.setSelection(Nr(o,"start")?_.findFrom(a.doc.resolve(a.mapping.map(i.pos)),1):H.create(a.doc,a.mapping.map(i.pos))),e(a.scrollIntoView())}return!0}}return o.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos,i.pos+o.nodeSize).scrollIntoView()),!0):!1},_S=(t,e,n)=>{let{$head:r,empty:i}=t.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset<r.parent.content.size)return!1;o=Dh(r)}let s=o&&o.nodeAfter;return!s||!H.isSelectable(s)?!1:(e&&e(t.tr.setSelection(H.create(t.doc,o.pos)).scrollIntoView()),!0)};function Dh(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){let n=t.node(e);if(t.index(e)+1<n.childCount)return t.doc.resolve(t.after(e+1));if(n.type.spec.isolating)break}return null}var $S=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(` -`).scrollIntoView()),!0)};function Pl(t){for(let e=0;e<t.edgeCount;e++){let{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var HS=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),o=n.indexAfter(-1),s=Pl(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let a=n.after(),l=t.tr.replaceWith(a,a,s.createAndFill());l.setSelection(_.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},VS=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof Je||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=Pl(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,a=t.tr.insert(s,o.createAndFill());a.setSelection(z.create(a.doc,s+1)),e(a.scrollIntoView())}return!0},WS=(t,e)=>{let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let o=n.before();if(Vn(t.doc,o))return e&&e(t.tr.split(o).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Ir(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function jS(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof H&&e.selection.node.isBlock)return!r.parentOffset||!Vn(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],s,a,l=!1,c=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){l=r.end(p)==r.pos+(r.depth-p),c=r.start(p)==r.pos-(r.depth-p),a=Pl(r.node(p-1).contentMatchAt(r.indexAfter(p-1)));let m=t&&t(i.parent,l,r);o.unshift(m||(l&&a?{type:a}:null)),s=p;break}else{if(p==1)return!1;o.unshift(null)}let u=e.tr;(e.selection instanceof z||e.selection instanceof Je)&&u.deleteSelection();let f=u.mapping.map(r.pos),d=Vn(u.doc,f,o.length,o);if(d||(o[0]=a?{type:a}:null,d=Vn(u.doc,f,o.length,o)),!d)return!1;if(u.split(f,o.length,o),!l&&c&&r.node(s).type!=a){let p=u.mapping.map(r.before(s)),h=u.doc.resolve(p);a&&r.node(s-1).canReplaceWith(h.index(),h.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(s)),a)}return n&&n(u.scrollIntoView()),!0}}var qS=jS();var KS=(t,e)=>(e&&e(t.tr.setSelection(new Je(t.doc))),!0);function US(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,o=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||Wn(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Oh(t,e,n,r){let i=e.nodeBefore,o=e.nodeAfter,s,a,l=i.type.spec.isolating||o.type.spec.isolating;if(!l&&US(t,e,n))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(s=(a=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&a.matchType(s[0]||o.type).validEnd){if(n){let p=e.pos+o.nodeSize,h=E.empty;for(let y=s.length-1;y>=0;y--)h=E.from(s[y].create(null,h));h=E.from(i.copy(h));let m=t.tr.step(new Ie(e.pos-1,p,e.pos,p,new A(h,1,0),s.length,!0)),g=m.doc.resolve(p+2*s.length);g.nodeAfter&&g.nodeAfter.type==i.type&&Wn(m.doc,g.pos)&&m.join(g.pos),n(m.scrollIntoView())}return!0}let u=o.type.spec.isolating||r>0&&l?null:_.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),d=f&&Ir(f);if(d!=null&&d>=e.depth)return n&&n(t.tr.lift(f,d).scrollIntoView()),!0;if(c&&Nr(o,"start",!0)&&Nr(i,"end")){let p=i,h=[];for(;h.push(p),!p.isTextblock;)p=p.lastChild;let m=o,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,m.content)){if(n){let y=E.empty;for(let C=h.length-1;C>=0;C--)y=E.from(h[C].copy(y));let x=t.tr.step(new Ie(e.pos-h.length,e.pos+o.nodeSize,e.pos+g,e.pos+o.nodeSize-g,new A(y,h.length,0),0,!0));n(x.scrollIntoView())}return!0}}return!1}function Lh(t){return function(e,n){let r=e.selection,i=t<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(e.tr.setSelection(z.create(e.doc,t<0?i.start(o):i.end(o)))),!0):!1}}var JS=Lh(-1),GS=Lh(1);function gs(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o),a=s&&Hn(s,t,e);return a?(r&&r(n.tr.wrap(s,a).scrollIntoView()),!0):!1}}function Rr(t,e=null){return function(n,r){let i=!1;for(let o=0;o<n.selection.ranges.length&&!i;o++){let{$from:{pos:s},$to:{pos:a}}=n.selection.ranges[o];n.doc.nodesBetween(s,a,(l,c)=>{if(i)return!1;if(!(!l.isTextblock||l.hasMarkup(t,e)))if(l.type==t)i=!0;else{let u=n.doc.resolve(c),f=u.index();i=u.parent.canReplaceWith(f,f+1,t)}})}if(!i)return!1;if(r){let o=n.tr;for(let s=0;s<n.selection.ranges.length;s++){let{$from:{pos:a},$to:{pos:l}}=n.selection.ranges[s];o.setBlockType(a,l,t,e)}r(o.scrollIntoView())}return!0}}function QS(t,e,n,r){for(let i=0;i<e.length;i++){let{$from:o,$to:s}=e[i],a=o.depth==0?t.inlineContent&&t.type.allowsMarkType(n):!1;if(t.nodesBetween(o.pos,s.pos,(l,c)=>{if(a||!r&&l.isAtom&&l.isInline&&c>=o.pos&&c+l.nodeSize<=s.pos)return!1;a=l.inlineContent&&l.type.allowsMarkType(n)}),a)return!0}return!1}function XS(t){let e=[];for(let n=0;n<t.length;n++){let{$from:r,$to:i}=t[n];r.doc.nodesBetween(r.pos,i.pos,(o,s)=>{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos)return s+1>r.pos&&e.push(new un(r,r.doc.resolve(s+1))),r=r.doc.resolve(s+1+o.content.size),!1}),r.pos<i.pos&&e.push(new un(r,i))}return e}function Dr(t,e=null,n){let r=(n&&n.removeWhenPresent)!==!1,i=(n&&n.enterInlineAtoms)!==!1,o=!(n&&n.includeWhitespace);return function(s,a){let{empty:l,$cursor:c,ranges:u}=s.selection;if(l&&!c||!QS(s.doc,u,t,i))return!1;if(a)if(c)t.isInSet(s.storedMarks||c.marks())?a(s.tr.removeStoredMark(t)):a(s.tr.addStoredMark(t.create(e)));else{let f,d=s.tr;i||(u=XS(u)),r?f=!u.some(p=>s.doc.rangeHasMark(p.$from.pos,p.$to.pos,t)):f=!u.every(p=>{let h=!1;return d.doc.nodesBetween(p.$from.pos,p.$to.pos,(m,g,y)=>{if(h)return!1;h=!t.isInSet(m.marks)&&!!y&&y.type.allowsMarkType(t)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,p.$from.pos-g),Math.min(m.nodeSize,p.$to.pos-g))))}),!h});for(let p=0;p<u.length;p++){let{$from:h,$to:m}=u[p];if(!f)d.removeMark(h.pos,m.pos,t);else{let g=h.pos,y=m.pos,x=h.nodeAfter,C=m.nodeBefore,I=o&&x&&x.isText?/^\s*/.exec(x.text)[0].length:0,v=o&&C&&C.isText?/\s*$/.exec(C.text)[0].length:0;g+I<y&&(g+=I,y-=v),d.addMark(g,y,t.create(e))}}a(d.scrollIntoView())}return!0}}function qn(...t){return function(e,n,r){for(let i=0;i<t.length;i++)if(t[i](e,n,r))return!0;return!1}}var Dl=qn(ms,Ol,Ll),Ah=qn(ms,zS,_S),Ht={Enter:qn($S,VS,WS,qS),"Mod-Enter":HS,Backspace:Dl,"Mod-Backspace":Dl,"Shift-Backspace":Dl,Delete:Ah,"Mod-Delete":Ah,"Mod-a":KS},Bh={"Ctrl-h":Ht.Backspace,"Alt-Backspace":Ht["Mod-Backspace"],"Ctrl-d":Ht.Delete,"Ctrl-Alt-Backspace":Ht["Mod-Delete"],"Alt-Delete":Ht["Mod-Delete"],"Alt-d":Ht["Mod-Delete"],"Ctrl-a":JS,"Ctrl-e":GS};for(let t in Ht)Bh[t]=Ht[t];var YS=typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform?os.platform()=="darwin":!1,Ph=YS?Bh:Ht;var be=class{constructor(e,n,r={}){this.match=e,this.match=e,this.handler=typeof n=="string"?ZS(n):n,this.undoable=r.undoable!==!1,this.inCode=r.inCode||!1,this.inCodeMark=r.inCodeMark!==!1}};function ZS(t){return function(e,n,r,i){let o=t;if(n[1]){let s=n[0].lastIndexOf(n[1]);o+=n[0].slice(s+n[1].length),r+=s;let a=r-i;a>0&&(o=n[0].slice(s-a,s)+o,r=i)}return e.tr.insertText(o,r,i)}}var Fh=(t,e)=>{let n=t.plugins;for(let r=0;r<n.length;r++){let i=n[r],o;if(i.spec.isInputRules&&(o=i.getState(t))){if(e){let s=t.tr,a=o.transform;for(let l=a.steps.length-1;l>=0;l--)s.step(a.steps[l].invert(a.docs[l]));if(o.text){let l=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,t.schema.text(o.text,l))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},kF=new be(/--$/,"\u2014",{inCodeMark:!1}),bF=new be(/\.\.\.$/,"\u2026",{inCodeMark:!1}),xF=new be(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"\u201C",{inCodeMark:!1}),wF=new be(/"$/,"\u201D",{inCodeMark:!1}),SF=new be(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"\u2018",{inCodeMark:!1}),CF=new be(/'$/,"\u2019",{inCodeMark:!1});function ys(t,e,n=null,r){return new be(t,(i,o,s,a)=>{let l=n instanceof Function?n(o):n,c=i.tr.delete(s,a),u=c.doc.resolve(s),f=u.blockRange(),d=f&&Hn(f,e,l);if(!d)return null;c.wrap(f,d);let p=c.doc.resolve(s-1).nodeBefore;return p&&p.type==e&&Wn(c.doc,s-1)&&(!r||r(o,p))&&c.join(s-1),c})}function Fl(t,e,n=null){return new be(t,(r,i,o,s)=>{let a=r.doc.resolve(o),l=n instanceof Function?n(i):n;return a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),e)?r.tr.delete(o,s).setBlockType(o,o,e,l):null})}var fn=typeof navigator<"u"?navigator:null,zh=typeof document<"u"?document:null,dn=fn&&fn.userAgent||"",_l=/Edge\/(\d+)/.exec(dn),_h=/MSIE \d/.exec(dn),$l=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(dn),Vl=!!(_h||$l||_l),IF=_h?document.documentMode:$l?+$l[1]:_l?+_l[1]:0,e0=!Vl&&/gecko\/(\d+)/i.test(dn),vF=e0&&+(/Firefox\/(\d+)/.exec(dn)||[0,0])[1],Hl=!Vl&&/Chrome\/(\d+)/.exec(dn),t0=!!Hl,AF=Hl?+Hl[1]:0,n0=!Vl&&!!fn&&/Apple Computer/.test(fn.vendor),r0=n0&&(/Mobile\/\w+/.test(dn)||!!fn&&fn.maxTouchPoints>2),NF=r0||(fn?/Mac/.test(fn.platform):!1),i0=/Android \d/.test(dn),o0=!!zh&&"webkitFontSmoothing"in zh.documentElement.style,RF=o0?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function zl(t,e,n,r,i,o){if(t.composing)return!1;let s=t.state,a=s.doc.resolve(e);if(a.parent.type.spec.code)return!1;let l=a.parent.textBetween(Math.max(0,a.parentOffset-500),a.parentOffset,void 0,"\uFFFC")+r;for(let c of i){let u=c,f=u.match.exec(l),d=f&&f[0]&&u.handler(s,f,e-(f[0].length-r.length),n);if(d)return u.undoable!==!1&&d.setMeta(o,{transform:d,from:e,to:n,text:r}),t.dispatch(d),!0}return!1}var s0=new te("MILKDOWN_CUSTOM_INPUTRULES");function $h({rules:t}){let e=new Y({key:s0,isInputRules:!0,state:{init(){return null},apply(n,r){let i=n.getMeta(this);return i||(n.selectionSet||n.docChanged?null:r)}},props:{handleTextInput(n,r,i,o){return zl(n,r,i,o,t,e)},handleDOMEvents:{compositionend:n=>(setTimeout(()=>{let{$cursor:r}=n.state.selection;r&&zl(n,r.pos,r.pos,"",t,e)}),!1),keydown:(n,r)=>!(i0&&t0&&r.key==="Enter")||n.composing?!1:n.someProp("handleKeyDown",i=>i(n,r))?(r.preventDefault(),!0):!1},handleKeyDown(n,r){if(r.key!=="Enter")return!1;let{$cursor:i}=n.state.selection;return i?zl(n,i.pos,i.pos,` +`).scrollIntoView()),!0)};function Pl(t){for(let e=0;e<t.edgeCount;e++){let{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var HS=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),o=n.indexAfter(-1),s=Pl(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let a=n.after(),l=t.tr.replaceWith(a,a,s.createAndFill());l.setSelection(_.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},VS=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof Je||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=Pl(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,a=t.tr.insert(s,o.createAndFill());a.setSelection(z.create(a.doc,s+1)),e(a.scrollIntoView())}return!0},WS=(t,e)=>{let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let o=n.before();if(Vn(t.doc,o))return e&&e(t.tr.split(o).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Ir(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function jS(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof H&&e.selection.node.isBlock)return!r.parentOffset||!Vn(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],s,a,l=!1,c=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){l=r.end(p)==r.pos+(r.depth-p),c=r.start(p)==r.pos-(r.depth-p),a=Pl(r.node(p-1).contentMatchAt(r.indexAfter(p-1)));let m=t&&t(i.parent,l,r);o.unshift(m||(l&&a?{type:a}:null)),s=p;break}else{if(p==1)return!1;o.unshift(null)}let u=e.tr;(e.selection instanceof z||e.selection instanceof Je)&&u.deleteSelection();let f=u.mapping.map(r.pos),d=Vn(u.doc,f,o.length,o);if(d||(o[0]=a?{type:a}:null,d=Vn(u.doc,f,o.length,o)),!d)return!1;if(u.split(f,o.length,o),!l&&c&&r.node(s).type!=a){let p=u.mapping.map(r.before(s)),h=u.doc.resolve(p);a&&r.node(s-1).canReplaceWith(h.index(),h.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(s)),a)}return n&&n(u.scrollIntoView()),!0}}var qS=jS();var KS=(t,e)=>(e&&e(t.tr.setSelection(new Je(t.doc))),!0);function US(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,o=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||Wn(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Oh(t,e,n,r){let i=e.nodeBefore,o=e.nodeAfter,s,a,l=i.type.spec.isolating||o.type.spec.isolating;if(!l&&US(t,e,n))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(s=(a=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&a.matchType(s[0]||o.type).validEnd){if(n){let p=e.pos+o.nodeSize,h=E.empty;for(let y=s.length-1;y>=0;y--)h=E.from(s[y].create(null,h));h=E.from(i.copy(h));let m=t.tr.step(new Ie(e.pos-1,p,e.pos,p,new A(h,1,0),s.length,!0)),g=m.doc.resolve(p+2*s.length);g.nodeAfter&&g.nodeAfter.type==i.type&&Wn(m.doc,g.pos)&&m.join(g.pos),n(m.scrollIntoView())}return!0}let u=o.type.spec.isolating||r>0&&l?null:_.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),d=f&&Ir(f);if(d!=null&&d>=e.depth)return n&&n(t.tr.lift(f,d).scrollIntoView()),!0;if(c&&Nr(o,"start",!0)&&Nr(i,"end")){let p=i,h=[];for(;h.push(p),!p.isTextblock;)p=p.lastChild;let m=o,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,m.content)){if(n){let y=E.empty;for(let C=h.length-1;C>=0;C--)y=E.from(h[C].copy(y));let x=t.tr.step(new Ie(e.pos-h.length,e.pos+o.nodeSize,e.pos+g,e.pos+o.nodeSize-g,new A(y,h.length,0),0,!0));n(x.scrollIntoView())}return!0}}return!1}function Lh(t){return function(e,n){let r=e.selection,i=t<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(e.tr.setSelection(z.create(e.doc,t<0?i.start(o):i.end(o)))),!0):!1}}var JS=Lh(-1),GS=Lh(1);function gs(t,e=null){return function(n,r){let{$from:i,$to:o}=n.selection,s=i.blockRange(o),a=s&&Hn(s,t,e);return a?(r&&r(n.tr.wrap(s,a).scrollIntoView()),!0):!1}}function Rr(t,e=null){return function(n,r){let i=!1;for(let o=0;o<n.selection.ranges.length&&!i;o++){let{$from:{pos:s},$to:{pos:a}}=n.selection.ranges[o];n.doc.nodesBetween(s,a,(l,c)=>{if(i)return!1;if(!(!l.isTextblock||l.hasMarkup(t,e)))if(l.type==t)i=!0;else{let u=n.doc.resolve(c),f=u.index();i=u.parent.canReplaceWith(f,f+1,t)}})}if(!i)return!1;if(r){let o=n.tr;for(let s=0;s<n.selection.ranges.length;s++){let{$from:{pos:a},$to:{pos:l}}=n.selection.ranges[s];o.setBlockType(a,l,t,e)}r(o.scrollIntoView())}return!0}}function QS(t,e,n,r){for(let i=0;i<e.length;i++){let{$from:o,$to:s}=e[i],a=o.depth==0?t.inlineContent&&t.type.allowsMarkType(n):!1;if(t.nodesBetween(o.pos,s.pos,(l,c)=>{if(a||!r&&l.isAtom&&l.isInline&&c>=o.pos&&c+l.nodeSize<=s.pos)return!1;a=l.inlineContent&&l.type.allowsMarkType(n)}),a)return!0}return!1}function XS(t){let e=[];for(let n=0;n<t.length;n++){let{$from:r,$to:i}=t[n];r.doc.nodesBetween(r.pos,i.pos,(o,s)=>{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos)return s+1>r.pos&&e.push(new un(r,r.doc.resolve(s+1))),r=r.doc.resolve(s+1+o.content.size),!1}),r.pos<i.pos&&e.push(new un(r,i))}return e}function Dr(t,e=null,n){let r=(n&&n.removeWhenPresent)!==!1,i=(n&&n.enterInlineAtoms)!==!1,o=!(n&&n.includeWhitespace);return function(s,a){let{empty:l,$cursor:c,ranges:u}=s.selection;if(l&&!c||!QS(s.doc,u,t,i))return!1;if(a)if(c)t.isInSet(s.storedMarks||c.marks())?a(s.tr.removeStoredMark(t)):a(s.tr.addStoredMark(t.create(e)));else{let f,d=s.tr;i||(u=XS(u)),r?f=!u.some(p=>s.doc.rangeHasMark(p.$from.pos,p.$to.pos,t)):f=!u.every(p=>{let h=!1;return d.doc.nodesBetween(p.$from.pos,p.$to.pos,(m,g,y)=>{if(h)return!1;h=!t.isInSet(m.marks)&&!!y&&y.type.allowsMarkType(t)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,p.$from.pos-g),Math.min(m.nodeSize,p.$to.pos-g))))}),!h});for(let p=0;p<u.length;p++){let{$from:h,$to:m}=u[p];if(!f)d.removeMark(h.pos,m.pos,t);else{let g=h.pos,y=m.pos,x=h.nodeAfter,C=m.nodeBefore,I=o&&x&&x.isText?/^\s*/.exec(x.text)[0].length:0,v=o&&C&&C.isText?/\s*$/.exec(C.text)[0].length:0;g+I<y&&(g+=I,y-=v),d.addMark(g,y,t.create(e))}}a(d.scrollIntoView())}return!0}}function qn(...t){return function(e,n,r){for(let i=0;i<t.length;i++)if(t[i](e,n,r))return!0;return!1}}var Dl=qn(ms,Ol,Ll),Ah=qn(ms,zS,_S),Ht={Enter:qn($S,VS,WS,qS),"Mod-Enter":HS,Backspace:Dl,"Mod-Backspace":Dl,"Shift-Backspace":Dl,Delete:Ah,"Mod-Delete":Ah,"Mod-a":KS},Bh={"Ctrl-h":Ht.Backspace,"Alt-Backspace":Ht["Mod-Backspace"],"Ctrl-d":Ht.Delete,"Ctrl-Alt-Backspace":Ht["Mod-Delete"],"Alt-Delete":Ht["Mod-Delete"],"Alt-d":Ht["Mod-Delete"],"Ctrl-a":JS,"Ctrl-e":GS};for(let t in Ht)Bh[t]=Ht[t];var YS=typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform?os.platform()=="darwin":!1,Ph=YS?Bh:Ht;var be=class{constructor(e,n,r={}){this.match=e,this.match=e,this.handler=typeof n=="string"?ZS(n):n,this.undoable=r.undoable!==!1,this.inCode=r.inCode||!1,this.inCodeMark=r.inCodeMark!==!1}};function ZS(t){return function(e,n,r,i){let o=t;if(n[1]){let s=n[0].lastIndexOf(n[1]);o+=n[0].slice(s+n[1].length),r+=s;let a=r-i;a>0&&(o=n[0].slice(s-a,s)+o,r=i)}return e.tr.insertText(o,r,i)}}var Fh=(t,e)=>{let n=t.plugins;for(let r=0;r<n.length;r++){let i=n[r],o;if(i.spec.isInputRules&&(o=i.getState(t))){if(e){let s=t.tr,a=o.transform;for(let l=a.steps.length-1;l>=0;l--)s.step(a.steps[l].invert(a.docs[l]));if(o.text){let l=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,t.schema.text(o.text,l))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},bF=new be(/--$/,"\u2014",{inCodeMark:!1}),xF=new be(/\.\.\.$/,"\u2026",{inCodeMark:!1}),wF=new be(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"\u201C",{inCodeMark:!1}),SF=new be(/"$/,"\u201D",{inCodeMark:!1}),CF=new be(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"\u2018",{inCodeMark:!1}),MF=new be(/'$/,"\u2019",{inCodeMark:!1});function ys(t,e,n=null,r){return new be(t,(i,o,s,a)=>{let l=n instanceof Function?n(o):n,c=i.tr.delete(s,a),u=c.doc.resolve(s),f=u.blockRange(),d=f&&Hn(f,e,l);if(!d)return null;c.wrap(f,d);let p=c.doc.resolve(s-1).nodeBefore;return p&&p.type==e&&Wn(c.doc,s-1)&&(!r||r(o,p))&&c.join(s-1),c})}function Fl(t,e,n=null){return new be(t,(r,i,o,s)=>{let a=r.doc.resolve(o),l=n instanceof Function?n(i):n;return a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),e)?r.tr.delete(o,s).setBlockType(o,o,e,l):null})}var fn=typeof navigator<"u"?navigator:null,zh=typeof document<"u"?document:null,dn=fn&&fn.userAgent||"",_l=/Edge\/(\d+)/.exec(dn),_h=/MSIE \d/.exec(dn),$l=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(dn),Vl=!!(_h||$l||_l),vF=_h?document.documentMode:$l?+$l[1]:_l?+_l[1]:0,e0=!Vl&&/gecko\/(\d+)/i.test(dn),AF=e0&&+(/Firefox\/(\d+)/.exec(dn)||[0,0])[1],Hl=!Vl&&/Chrome\/(\d+)/.exec(dn),t0=!!Hl,NF=Hl?+Hl[1]:0,n0=!Vl&&!!fn&&/Apple Computer/.test(fn.vendor),r0=n0&&(/Mobile\/\w+/.test(dn)||!!fn&&fn.maxTouchPoints>2),RF=r0||(fn?/Mac/.test(fn.platform):!1),i0=/Android \d/.test(dn),o0=!!zh&&"webkitFontSmoothing"in zh.documentElement.style,DF=o0?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function zl(t,e,n,r,i,o){if(t.composing)return!1;let s=t.state,a=s.doc.resolve(e);if(a.parent.type.spec.code)return!1;let l=a.parent.textBetween(Math.max(0,a.parentOffset-500),a.parentOffset,void 0,"\uFFFC")+r;for(let c of i){let u=c,f=u.match.exec(l),d=f&&f[0]&&u.handler(s,f,e-(f[0].length-r.length),n);if(d)return u.undoable!==!1&&d.setMeta(o,{transform:d,from:e,to:n,text:r}),t.dispatch(d),!0}return!1}var s0=new te("MILKDOWN_CUSTOM_INPUTRULES");function $h({rules:t}){let e=new Y({key:s0,isInputRules:!0,state:{init(){return null},apply(n,r){let i=n.getMeta(this);return i||(n.selectionSet||n.docChanged?null:r)}},props:{handleTextInput(n,r,i,o){return zl(n,r,i,o,t,e)},handleDOMEvents:{compositionend:n=>(setTimeout(()=>{let{$cursor:r}=n.state.selection;r&&zl(n,r.pos,r.pos,"",t,e)}),!1),keydown:(n,r)=>!(i0&&t0&&r.key==="Enter")||n.composing?!1:n.someProp("handleKeyDown",i=>i(n,r))?(r.preventDefault(),!0):!1},handleKeyDown(n,r){if(r.key!=="Enter")return!1;let{$cursor:i}=n.state.selection;return i?zl(n,i.pos,i.pos,` `,t,e):!1}}});return e}function Vt(t,e,n={}){return new be(t,(r,i,o,s)=>{var a,l,c,u;let{tr:f}=r,d=i.length,p=i[d-1],h=i[0],m=[],g,y={group:p,fullMatch:h,start:o,end:s},x=(a=n.updateCaptured)==null?void 0:a.call(n,y);if(Object.assign(y,x),{group:p,fullMatch:h,start:o,end:s}=y,h===null||p?.trim()==="")return null;if(p){let C=h.search(/\S/),I=o+h.indexOf(p),v=I+p.length;m=(l=f.storedMarks)!=null?l:[],v<s&&f.delete(v,s),I>o&&f.delete(o+C,I),g=o+C+p.length;let w=(c=n.getAttr)==null?void 0:c.call(n,i);f.addMark(o,g,e.create(w)),f.setStoredMarks(m),(u=n.beforeDispatch)==null||u.call(n,{match:i,start:o,end:s,tr:f})}return f})}function ks(t,e,n={}){return new be(t,(r,i,o,s)=>{var a,l,c;let{tr:u}=r,f=i[1],d=i[0],p={group:f,fullMatch:d,start:o,end:s},h=(a=n.updateCaptured)==null?void 0:a.call(n,p);if(Object.assign(p,h),{group:f,fullMatch:d,start:o,end:s}=p,d===null||!f||f.trim()==="")return null;let m=(l=n.getAttr)==null?void 0:l.call(n,i),g=e.createAndFill(m);return g&&(u.replaceRangeWith(e.isBlock?u.doc.resolve(o).before():o,s,g),(c=n.beforeDispatch)==null||c.call(n,{match:[d,f],start:o,end:s,tr:u})),u})}function Wl(t){return Object.assign(Object.create(t),t).setTime(Date.now())}function a0(t,e){return Array.isArray(t)&&t.includes(e.type)||e.type===t}function l0(t){return e=>{for(let n=e.depth;n>0;n-=1){let r=e.node(n);if(t(r)){let i=e.before(n),o=e.after(n);return{from:i,to:o,node:r}}}}}function Hh(t,e){return l0(n=>n.type===e)(t)}function Vh(t){return e=>{for(let n=e.depth;n>0;n--){let r=e.node(n);if(t(r))return{pos:e.before(n),start:e.start(n),depth:n,node:r}}}}function Wh(t,e){if(!(t instanceof H))return;let{node:n,$from:r}=t;if(a0(e,n))return{node:n,pos:r.pos,start:r.start(r.depth),depth:r.depth}}var jh=(t,e)=>{let{selection:n,doc:r}=t;if(n instanceof H)return{hasNode:n.node.type===e,pos:n.from,target:n.node};let{from:i,to:o}=n,s=!1,a=-1,l=null;return r.nodesBetween(i,o,(c,u)=>l?!1:c.type===e?(s=!0,a=u,l=c,!1):!0),{hasNode:s,pos:a,target:l}};var Wt={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:"'"},xs={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},c0=typeof navigator<"u"&&/Mac/.test(navigator.platform),u0=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(he=0;he<10;he++)Wt[48+he]=Wt[96+he]=String(he);var he;for(he=1;he<=24;he++)Wt[he+111]="F"+he;var he;for(he=65;he<=90;he++)Wt[he]=String.fromCharCode(he+32),xs[he]=String.fromCharCode(he);var he;for(bs in Wt)xs.hasOwnProperty(bs)||(xs[bs]=Wt[bs]);var bs;function qh(t){var e=c0&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||u0&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?xs:Wt)[t.keyCode]||t.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}var f0=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),d0=typeof navigator<"u"&&/Win/.test(navigator.platform);function p0(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,i,o,s;for(let a=0;a<e.length-1;a++){let l=e[a];if(/^(cmd|meta|m)$/i.test(l))s=!0;else if(/^a(lt)?$/i.test(l))r=!0;else if(/^(c|ctrl|control)$/i.test(l))i=!0;else if(/^s(hift)?$/i.test(l))o=!0;else if(/^mod$/i.test(l))f0?s=!0:i=!0;else throw new Error("Unrecognized modifier name: "+l)}return r&&(n="Alt-"+n),i&&(n="Ctrl-"+n),s&&(n="Meta-"+n),o&&(n="Shift-"+n),n}function h0(t){let e=Object.create(null);for(let n in t)e[p0(n)]=t[n];return e}function jl(t,e,n=!0){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),n&&e.shiftKey&&(t="Shift-"+t),t}function Kh(t){return new Y({props:{handleKeyDown:ql(t)}})}function ql(t){let e=h0(t);return function(n,r){let i=qh(r),o,s=e[jl(i,r)];if(s&&s(n.state,n.dispatch,n))return!0;if(i.length==1&&i!=" "){if(r.shiftKey){let a=e[jl(i,r,!1)];if(a&&a(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(d0&&r.ctrlKey&&r.altKey)&&(o=Wt[r.keyCode])&&o!=i){let a=e[jl(o,r)];if(a&&a(n.state,n.dispatch,n))return!0}}return!1}}var Jh=class{},Gh=class{constructor(){this.elements=[],this.size=()=>this.elements.length,this.top=()=>this.elements.at(-1),this.push=t=>{this.top()?.push(t)},this.open=t=>{this.elements.push(t)},this.close=()=>{let t=this.elements.pop();if(!t)throw Ea();return t}}},m0=class Qh extends Jh{constructor(e,n,r){super(),this.type=e,this.content=n,this.attrs=r}push(e,...n){this.content.push(e,...n)}pop(){return this.content.pop()}static create(e,n,r){return new Qh(e,n,r)}},Xh=class extends Gh{#t;static{this.create=(t,e)=>{let n=new this(t);return r=>(n.run(e,r),n.toDoc())}}constructor(t){super(),this.#t=J.none,this.#e=e=>e.isText,this.#r=(e,n)=>{if(this.#e(e)&&this.#e(n)&&J.sameSet(e.marks,n.marks))return this.schema.text(e.text+n.text,e.marks)},this.#n=e=>{let n=Object.values({...this.schema.nodes,...this.schema.marks}).find(r=>r.spec.parseMarkdown.match(e));if(!n)throw ad(e);return n},this.#s=e=>{let n=this.#n(e);n.spec.parseMarkdown.runner(this,e,n)},this.injectRoot=(e,n,r)=>(this.openNode(n,r),this.next(e.children),this),this.openNode=(e,n)=>(this.open(m0.create(e,[],n)),this),this.#o=()=>{this.#t=J.none;let e=this.close();return this.#i(e.type,e.attrs,e.content)},this.closeNode=()=>{try{this.#o()}catch(e){console.error(e)}return this},this.#i=(e,n,r)=>{let i=e.createAndFill(n,r,this.#t);if(!i)throw sd(e,n,r);return this.push(i),i},this.addNode=(e,n,r)=>{try{this.#i(e,n,r)}catch(i){console.error(i)}return this},this.openMark=(e,n)=>{let r=e.create(n);return this.#t=r.addToSet(this.#t),this},this.closeMark=e=>(this.#t=e.removeFromSet(this.#t),this),this.addText=e=>{try{let n=this.top();if(!n)throw Ea();let r=n.pop(),i=this.schema.text(e,this.#t);if(!r)return n.push(i),this;let o=this.#r(r,i);return o?(n.push(o),this):(n.push(r,i),this)}catch(n){return console.error(n),this}},this.build=()=>{let e;do e=this.#o();while(this.size());return e},this.next=(e=[])=>([e].flat().forEach(n=>this.#s(n)),this),this.toDoc=()=>this.build(),this.run=(e,n)=>{let r=e.runSync(e.parse(n),n);return this.next(r),this},this.schema=t}#e;#r;#n;#s;#o;#i},Uh=class Yh extends Jh{constructor(e,n,r,i={}){super(),this.type=e,this.children=n,this.value=r,this.props=i,this.push=(o,...s)=>{this.children||(this.children=[]),this.children.push(o,...s)},this.pop=()=>this.children?.pop()}static{this.create=(e,n,r,i={})=>new Yh(e,n,r,i)}},g0=t=>Object.prototype.hasOwnProperty.call(t,"size"),Zh=class extends Gh{#t;static{this.create=(t,e)=>{let n=new this(t);return r=>(n.run(r),n.toString(e))}}constructor(t){super(),this.#t=[],this.#e=e=>{let n=Object.values({...this.schema.nodes,...this.schema.marks}).find(r=>r.spec.toMarkdown.match(e));if(!n)throw ld(e.type);return n},this.#r=e=>this.#e(e).spec.toMarkdown.runner(this,e),this.#n=(e,n)=>this.#e(e).spec.toMarkdown.runner(this,e,n),this.#s=e=>{let n=o=>o.type.spec.priority??50,r=[...e].sort((o,s)=>n(o)-n(s)),i=[];return this.#t.forEach(({mark:o})=>{let s=r.findIndex(a=>a.eq(o));s>=0&&i.push(...r.splice(s,1))}),i.concat(r)},this.#o=e=>{let n=e?.marks,r=0;for(;r<this.#t.length;){let{mark:i,spanning:o}=this.#t[r];if(o&&n?.some(s=>s.eq(i)))r++;else break}for(let i=this.#t.length-1;i>=r;i--)this.#f(this.#t[i].mark)},this.#i=(e,n)=>{this.#s(e.marks).every(r=>!this.#n(r,e))&&this.#r(e),this.#o(n)},this.#a=e=>{let{children:n}=e;return n&&(e.children=n.reduce((r,i,o)=>{if(o===0)return[i];let s=r.at(-1);if(s&&s.isMark&&i.isMark){let{children:a,...l}=i,{children:c,...u}=s;if(i.type===s.type&&a&&c&&JSON.stringify(l)===JSON.stringify(u)){let f={...u,children:[...c,...a]};return r.slice(0,-1).concat(this.#a(f))}}return r.concat(i)},[])),e},this.#l=e=>{let n={...e.props,type:e.type};return e.children&&(n.children=e.children),e.value&&(n.value=e.value),n},this.openNode=(e,n,r)=>(this.open(Uh.create(e,void 0,n,r)),this),this.#d=(e,n)=>{let r="",i="",o=e.children;if(o){let a=o[0],l=o.at(-1);if(l&&l.type==="text"&&l.value.endsWith(" ")){let c=l.value,u=c.trimEnd();i=c.slice(u.length),l.value=u}if(a&&a.type==="text"&&a.value.startsWith(" ")){let c=a.value,u=c.trimStart();r=c.slice(0,c.length-u.length),a.value=u}}r.length&&this.#u("text",void 0,r);let s=n();return i.length&&this.#u("text",void 0,i),s},this.#c=(e=!1)=>{let n=this.close(),r=()=>this.#u(n.type,n.children,n.value,n.props);return e?this.#d(n,r):r()},this.closeNode=()=>(this.#c(),this),this.#u=(e,n,r,i)=>{let o=Uh.create(e,n,r,i),s=this.#a(this.#l(o));return this.push(s),s},this.addNode=(e,n,r,i)=>(this.#u(e,n,r,i),this),this.#p=(e,n,r,i)=>this.#t.some(o=>o.mark.eq(e))?this:(this.#t.push({mark:e,spanning:r==null}),this.openNode(n,r,{...i,isMark:!0})),this.#f=e=>{let n=-1;for(let r=this.#t.length-1;r>=0;r--)if(this.#t[r].mark.eq(e)){n=r;break}n<0||(this.#t.splice(n,1),this.#c(!0))},this.withMark=(e,n,r,i)=>(this.#p(e,n,r,i),this),this.closeMark=e=>(this.#f(e),this),this.build=()=>{let e=null;do e=this.#c();while(this.size());return e},this.next=e=>g0(e)?(e.forEach((n,r,i)=>{this.#i(n,e.maybeChild(i+1)??void 0)}),this):(this.#i(e),this),this.toString=e=>e.stringify(this.build()),this.run=e=>(this.#t=[],this.next(e),this),this.schema=t}#e;#r;#n;#s;#o;#i;#a;#l;#d;#c;#u;#p;#f};var ve=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Pr=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e},Xl=null,qt=function(t,e,n){let r=Xl||(Xl=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},y0=function(){Xl=null},Zn=function(t,e,n,r){return n&&(em(t,e,n,r,-1)||em(t,e,n,r,1))},k0=/^(img|br|input|textarea|hr)$/i;function em(t,e,n,r,i){for(var o;;){if(t==n&&e==r)return!0;if(e==(i<0?0:at(t))){let s=t.parentNode;if(!s||s.nodeType!=1||Ui(t)||k0.test(t.nodeName)||t.contentEditable=="false")return!1;e=ve(t)+(i<0?0:1),t=s}else if(t.nodeType==1){let s=t.childNodes[e+(i<0?-1:0)];if(s.nodeType==1&&s.contentEditable=="false")if(!((o=s.pmViewDesc)===null||o===void 0)&&o.ignoreForSelection)e+=i;else return!1;else t=s,e=i<0?at(t):0}else return!1}}function at(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function b0(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=at(t)}else if(t.parentNode&&!Ui(t))e=ve(t),t=t.parentNode;else return null}}function x0(t,e){for(;;){if(t.nodeType==3&&e<t.nodeValue.length)return t;if(t.nodeType==1&&e<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[e],e=0}else if(t.parentNode&&!Ui(t))e=ve(t)+1,t=t.parentNode;else return null}}function w0(t,e,n){for(let r=e==0,i=e==at(t);r||i;){if(t==n)return!0;let o=ve(t);if(t=t.parentNode,!t)return!1;r=r&&o==0,i=i&&o==at(t)}}function Ui(t){let e;for(let n=t;n&&!(e=n.pmViewDesc);n=n.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==t||e.contentDOM==t)}var Ds=function(t){return t.focusNode&&Zn(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function Kn(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function S0(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function C0(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(at(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(at(r.startContainer),r.startOffset)}}}var vt=typeof navigator<"u"?navigator:null,tm=typeof document<"u"?document:null,yn=vt&&vt.userAgent||"",Yl=/Edge\/(\d+)/.exec(yn),Nm=/MSIE \d/.exec(yn),Zl=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(yn),We=!!(Nm||Zl||Yl),mn=Nm?document.documentMode:Zl?+Zl[1]:Yl?+Yl[1]:0,lt=!We&&/gecko\/(\d+)/i.test(yn);lt&&+(/Firefox\/(\d+)/.exec(yn)||[0,0])[1];var ec=!We&&/Chrome\/(\d+)/.exec(yn),Se=!!ec,Rm=ec?+ec[1]:0,Le=!We&&!!vt&&/Apple Computer/.test(vt.vendor),Fr=Le&&(/Mobile\/\w+/.test(yn)||!!vt&&vt.maxTouchPoints>2),st=Fr||(vt?/Mac/.test(vt.platform):!1),Dm=vt?/Win/.test(vt.platform):!1,Kt=/Android \d/.test(yn),Ji=!!tm&&"webkitFontSmoothing"in tm.documentElement.style,M0=Ji?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function E0(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function jt(t,e){return typeof t=="number"?t:t[e]}function T0(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function nm(t,e,n){if(!tc(e)&&e.left==0)return;let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,o=t.dom.ownerDocument;for(let s=n||t.dom;s;){if(s.nodeType!=1){s=Pr(s);continue}let a=s,l=a==o.body,c=l?E0(o):T0(a),u=0,f=0;if(e.top<c.top+jt(r,"top")?f=-(c.top-e.top+jt(i,"top")):e.bottom>c.bottom-jt(r,"bottom")&&(f=e.bottom-e.top>c.bottom-c.top?e.top+jt(i,"top")-c.top:e.bottom-c.bottom+jt(i,"bottom")),e.left<c.left+jt(r,"left")?u=-(c.left-e.left+jt(i,"left")):e.right>c.right-jt(r,"right")&&(u=e.right-c.right+jt(i,"right")),u||f)if(l)o.defaultView.scrollBy(u,f);else{let p=a.scrollLeft,h=a.scrollTop;f&&(a.scrollTop+=f),u&&(a.scrollLeft+=u);let m=a.scrollLeft-p,g=a.scrollTop-h;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let d=l?"fixed":getComputedStyle(s).position;if(/^(fixed|sticky)$/.test(d))break;s=d=="absolute"?s.offsetParent:Pr(s)}}function I0(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let o=(e.left+e.right)/2,s=n+1;s<Math.min(innerHeight,e.bottom);s+=5){let a=t.root.elementFromPoint(o,s);if(!a||a==t.dom||!t.dom.contains(a))continue;let l=a.getBoundingClientRect();if(l.top>=n-20){r=a,i=l.top;break}}return{refDOM:r,refTop:i,stack:Om(t.dom)}}function Om(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Pr(r));return e}function v0({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Lm(n,r==0?0:r-e)}function Lm(t,e){for(let n=0;n<t.length;n++){let{dom:r,top:i,left:o}=t[n];r.scrollTop!=i+e&&(r.scrollTop=i+e),r.scrollLeft!=o&&(r.scrollLeft=o)}}var Or=null;function A0(t){if(t.setActive)return t.setActive();if(Or)return t.focus(Or);let e=Om(t);t.focus(Or==null?{get preventScroll(){return Or={preventScroll:!0},!0}}:void 0),Or||(Or=!1,Lm(e,0))}function Bm(t,e){let n,r=2e8,i,o=0,s=e.top,a=e.top,l,c;for(let u=t.firstChild,f=0;u;u=u.nextSibling,f++){let d;if(u.nodeType==1)d=u.getClientRects();else if(u.nodeType==3)d=qt(u).getClientRects();else continue;for(let p=0;p<d.length;p++){let h=d[p];if(h.top<=s&&h.bottom>=a){s=Math.max(h.bottom,s),a=Math.min(h.top,a);let m=h.left>e.left?h.left-e.left:h.right<e.left?e.left-h.right:0;if(m<r){n=u,r=m,i=m&&n.nodeType==3?{left:h.right<e.left?h.right:h.left,top:e.top}:e,u.nodeType==1&&m&&(o=f+(e.left>=(h.left+h.right)/2?1:0));continue}}else h.top>e.top&&!l&&h.left<=e.left&&h.right>=e.left&&(l=u,c={left:Math.max(h.left,Math.min(h.right,e.left)),top:h.top});!n&&(e.left>=h.right&&e.top>=h.top||e.left>=h.left&&e.top>=h.bottom)&&(o=f+1)}}return!n&&l&&(n=l,i=c,r=0),n&&n.nodeType==3?N0(n,i):!n||r&&n.nodeType==1?{node:t,offset:o}:Bm(n,i)}function N0(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let o=0;o<n;o++){r.setEnd(t,o+1),r.setStart(t,o);let s=pn(r,1);if(s.top!=s.bottom&&yc(e,s)){i={node:t,offset:o+(e.left>=(s.left+s.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function yc(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function R0(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function D0(t,e,n){let{node:r,offset:i}=Bm(e,n),o=-1;if(r.nodeType==1&&!r.firstChild){let s=r.getBoundingClientRect();o=s.left!=s.right&&n.left>(s.left+s.right)/2?1:-1}return t.docView.posFromDOM(r,i,o)}function O0(t,e,n,r){let i=-1;for(let o=e,s=!1;o!=t.dom;){let a=t.docView.nearestDesc(o,!0),l;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((l=a.dom.getBoundingClientRect()).width||l.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!s&&l.left>r.left||l.top>r.top?i=a.posBefore:(!s&&l.right<r.left||l.bottom<r.top)&&(i=a.posAfter),s=!0),!a.contentDOM&&i<0&&!a.node.isText))return(a.node.isBlock?r.top<(l.top+l.bottom)/2:r.left<(l.left+l.right)/2)?a.posBefore:a.posAfter;o=a.dom.parentNode}return i>-1?i:t.docView.posFromDOM(e,n,-1)}function Pm(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let i=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),o=i;;){let s=t.childNodes[o];if(s.nodeType==1){let a=s.getClientRects();for(let l=0;l<a.length;l++){let c=a[l];if(yc(e,c))return Pm(s,e,c)}}if((o=(o+1)%r)==i)break}return t}function L0(t,e){let n=t.dom.ownerDocument,r,i=0,o=C0(n,e.left,e.top);o&&({node:r,offset:i}=o);let s=(t.root.elementFromPoint?t.root:n).elementFromPoint(e.left,e.top),a;if(!s||!t.dom.contains(s.nodeType!=1?s.parentNode:s)){let c=t.dom.getBoundingClientRect();if(!yc(e,c)||(s=Pm(t.dom,e,c),!s))return null}if(Le)for(let c=s;r&&c;c=Pr(c))c.draggable&&(r=void 0);if(s=R0(s,e),r){if(lt&&r.nodeType==1&&(i=Math.min(i,r.childNodes.length),i<r.childNodes.length)){let u=r.childNodes[i],f;u.nodeName=="IMG"&&(f=u.getBoundingClientRect()).right<=e.left&&f.bottom>e.top&&i++}let c;Ji&&i&&r.nodeType==1&&(c=r.childNodes[i-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?a=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(a=O0(t,r,i,e))}a==null&&(a=D0(t,s,e));let l=t.docView.nearestDesc(s,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function tc(t){return t.top<t.bottom||t.left<t.right}function pn(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(tc(r))return r}return Array.prototype.find.call(n,tc)||t.getBoundingClientRect()}var B0=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function Fm(t,e,n){let{node:r,offset:i,atom:o}=t.docView.domFromPos(e,n<0?-1:1),s=Ji||lt;if(r.nodeType==3)if(s&&(B0.test(r.nodeValue)||(n<0?!i:i==r.nodeValue.length))){let l=pn(qt(r,i,i),n);if(lt&&i&&/\s/.test(r.nodeValue[i-1])&&i<r.nodeValue.length){let c=pn(qt(r,i-1,i-1),-1);if(c.top==l.top){let u=pn(qt(r,i,i+1),-1);if(u.top!=l.top)return $i(u,u.left<c.left)}}return l}else{let l=i,c=i,u=n<0?1:-1;return n<0&&!i?(c++,u=-1):n>=0&&i==r.nodeValue.length?(l--,u=1):n<0?l--:c++,$i(pn(qt(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&i&&(n<0||i==at(r))){let l=r.childNodes[i-1];if(l.nodeType==1)return Kl(l.getBoundingClientRect(),!1)}if(o==null&&i<at(r)){let l=r.childNodes[i];if(l.nodeType==1)return Kl(l.getBoundingClientRect(),!0)}return Kl(r.getBoundingClientRect(),n>=0)}if(o==null&&i&&(n<0||i==at(r))){let l=r.childNodes[i-1],c=l.nodeType==3?qt(l,at(l)-(s?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return $i(pn(c,1),!1)}if(o==null&&i<at(r)){let l=r.childNodes[i];for(;l.pmViewDesc&&l.pmViewDesc.ignoreForCoords;)l=l.nextSibling;let c=l?l.nodeType==3?qt(l,0,s?0:1):l.nodeType==1?l:null:null;if(c)return $i(pn(c,-1),!0)}return $i(pn(r.nodeType==3?qt(r):r,-n),n>=0)}function $i(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function Kl(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function zm(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function P0(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return zm(t,e,()=>{let{node:o}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let a=t.docView.nearestDesc(o,!0);if(!a)break;if(a.node.isBlock){o=a.contentDOM||a.dom;break}o=a.dom.parentNode}let s=Fm(t,i.pos,1);for(let a=o.firstChild;a;a=a.nextSibling){let l;if(a.nodeType==1)l=a.getClientRects();else if(a.nodeType==3)l=qt(a,0,a.nodeValue.length).getClientRects();else continue;for(let c=0;c<l.length;c++){let u=l[c];if(u.bottom>u.top+1&&(n=="up"?s.top-u.top>(u.bottom-s.top)*2:u.bottom-s.bottom>(s.bottom-u.top)*2))return!1}}return!0})}var F0=/[\u0590-\u08ac]/;function z0(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,o=!i,s=i==r.parent.content.size,a=t.domSelection();return a?!F0.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?o:s:zm(t,e,()=>{let{focusNode:l,focusOffset:c,anchorNode:u,anchorOffset:f}=t.domSelectionRange(),d=a.caretBidiLevel;a.modify("move",n,"character");let p=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:h,focusOffset:m}=t.domSelectionRange(),g=h&&!p.contains(h.nodeType==1?h:h.parentNode)||l==h&&c==m;try{a.collapse(u,f),l&&(l!=u||c!=f)&&a.extend&&a.extend(l,c)}catch{}return d!=null&&(a.caretBidiLevel=d),g}):r.pos==r.start()||r.pos==r.end()}var rm=null,im=null,om=!1;function _0(t,e,n){return rm==e&&im==n?om:(rm=e,im=n,om=n=="up"||n=="down"?P0(t,e,n):z0(t,e,n))}var ct=0,sm=1,Un=2,mt=3,er=class{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=ct,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n<this.children.length;n++)e+=this.children[n].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let n=0,r=this.posAtStart;;n++){let i=this.children[n];if(i==e)return r;r+=i.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(e,n,r){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(r<0){let o,s;if(e==this.contentDOM)o=e.childNodes[n-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;o=e.previousSibling}for(;o&&!((s=o.pmViewDesc)&&s.parent==this);)o=o.previousSibling;return o?this.posBeforeChild(s)+s.size:this.posAtStart}else{let o,s;if(e==this.contentDOM)o=e.childNodes[n];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;o=e.nextSibling}for(;o&&!((s=o.pmViewDesc)&&s.parent==this);)o=o.nextSibling;return o?this.posBeforeChild(s):this.posAtEnd}let i;if(e==this.dom&&this.contentDOM)i=n>ve(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!1;break}if(o.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!0;break}if(o.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let o=this.getDesc(i),s;if(o&&(!n||o.node))if(r&&(s=o.nodeDOM)&&!(s.nodeType==1?s.contains(e.nodeType==1?e:e.parentNode):s==e))r=!1;else return o}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let i=e;i;i=i.parentNode){let o=this.getDesc(i);if(o)return o.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;n<this.children.length;n++){let i=this.children[n],o=r+i.size;if(r==e&&o!=r){for(;!i.border&&i.children.length;)for(let s=0;s<i.children.length;s++){let a=i.children[s];if(a.size){i=a;break}}return i}if(e<o)return i.descAt(e-r-i.border);r=o}}domFromPos(e,n){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let r=0,i=0;for(let o=0;r<this.children.length;r++){let s=this.children[r],a=o+s.size;if(a>e||s instanceof Cs){i=e-o;break}o=a}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 ws&&o.side>=0;r--);if(n<=0){let o,s=!0;for(;o=r?this.children[r-1]:null,!(!o||o.dom.parentNode==this.contentDOM);r--,s=!1);return o&&n&&s&&!o.border&&!o.domAtom?o.domFromPos(o.size,n):{node:this.contentDOM,offset:o?ve(o.dom)+1:0}}else{let o,s=!0;for(;o=r<this.children.length?this.children[r]:null,!(!o||o.dom.parentNode==this.contentDOM);r++,s=!1);return o&&s&&!o.border&&!o.domAtom?o.domFromPos(0,n):{node:this.contentDOM,offset:o?ve(o.dom):this.contentDOM.childNodes.length}}}parseRange(e,n,r=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:n,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let i=-1,o=-1;for(let s=r,a=0;;a++){let l=this.children[a],c=s+l.size;if(i==-1&&e<=c){let u=s+l.border;if(e>=u&&n<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(e,n,u);e=s;for(let f=a;f>0;f--){let d=this.children[f-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=ve(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(c>n||a==this.children.length-1)){n=c;for(let u=a+1;u<this.children.length;u++){let f=this.children[u];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(-1)){o=ve(f.dom);break}n+=f.size}o==-1&&(o=this.contentDOM.childNodes.length);break}s=c}return{node:this.contentDOM,from:e,to:n,fromOffset:i,toOffset:o}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let n=this.children[e<0?0:this.children.length-1];return n.size==0||n.emptyChildAt(e)}domAfterPos(e){let{node:n,offset:r}=this.domFromPos(e,0);if(n.nodeType!=1||r==n.childNodes.length)throw new RangeError("No node after pos "+e);return n.childNodes[r]}setSelection(e,n,r,i=!1){let o=Math.min(e,n),s=Math.max(e,n);for(let p=0,h=0;p<this.children.length;p++){let m=this.children[p],g=h+m.size;if(o>h&&s<g)return m.setSelection(e-h-m.border,n-h-m.border,r,i);h=g}let a=this.domFromPos(e,e?-1:1),l=n==e?a:this.domFromPos(n,n?-1:1),c=r.root.getSelection(),u=r.domSelectionRange(),f=!1;if((lt||Le)&&e==n){let{node:p,offset:h}=a;if(p.nodeType==3){if(f=!!(h&&p.nodeValue[h-1]==` `),f&&h==p.nodeValue.length)for(let m=p,g;m;m=m.parentNode){if(g=m.nextSibling){g.nodeName=="BR"&&(a=l={node:g.parentNode,offset:ve(g)+1});break}let y=m.pmViewDesc;if(y&&y.node&&y.node.isBlock)break}}else{let m=p.childNodes[h-1];f=m&&(m.nodeName=="BR"||m.contentEditable=="false")}}if(lt&&u.focusNode&&u.focusNode!=l.node&&u.focusNode.nodeType==1){let p=u.focusNode.childNodes[u.focusOffset];p&&p.contentEditable=="false"&&(i=!0)}if(!(i||f&&Le)&&Zn(a.node,a.offset,u.anchorNode,u.anchorOffset)&&Zn(l.node,l.offset,u.focusNode,u.focusOffset))return;let d=!1;if((c.extend||e==n)&&!(f&<)){c.collapse(a.node,a.offset);try{e!=n&&c.extend(l.node,l.offset),d=!0}catch{}}if(!d){if(e>n){let h=a;a=l,l=h}let p=document.createRange();p.setEnd(l.node,l.offset),p.setStart(a.node,a.offset),c.removeAllRanges(),c.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,i=0;i<this.children.length;i++){let o=this.children[i],s=r+o.size;if(r==s?e<=s&&n>=r:e<s&&n>r){let a=r+o.border,l=s-o.border;if(e>=a&&n<=l){this.dirty=e==r||n==s?Un:sm,e==a&&n==l&&(o.contentLost||o.dom.parentNode!=this.contentDOM)?o.dirty=mt:o.markDirty(e-a,n-a);return}else o.dirty=o.dom==o.contentDOM&&o.dom.parentNode==this.contentDOM&&!o.children.length?Un:mt}r=s}this.dirty=Un}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Un:sm;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}},ws=class extends er{constructor(e,n,r,i){let o,s=n.type.toDOM;if(typeof s=="function"&&(s=s(r,()=>{if(!o)return i;if(o.parent)return o.parent.posBeforeChild(o)})),!n.type.spec.raw){if(s.nodeType!=1){let a=document.createElement("span");a.appendChild(s),s=a}s.contentEditable="false",s.classList.add("ProseMirror-widget")}super(e,[],s,null),this.widget=n,this.widget=n,o=this}matchesWidget(e){return this.dirty==ct&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},nc=class extends er{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}},Gn=class t extends er{constructor(e,n,r,i,o){super(e,[],r,i),this.mark=n,this.spec=o}static create(e,n,r,i){let o=i.nodeViews[n.type.name],s=o&&o(n,i,r);return(!s||!s.dom)&&(s=cn.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new t(e,n,s.dom,s.contentDOM||s.dom,s)}parseRule(){return this.dirty&mt||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=mt&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=ct){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=ct}}slice(e,n,r){let i=t.create(this.parent,this.mark,!0,r),o=this.children,s=this.size;n<s&&(o=sc(o,n,s,r)),e>0&&(o=sc(o,0,e,r));for(let a=0;a<o.length;a++)o[a].parent=i;return i.children=o,i}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}},gn=class t extends er{constructor(e,n,r,i,o,s,a){super(e,[],o,s),this.node=n,this.outerDeco=r,this.innerDeco=i,this.nodeDOM=a}static create(e,n,r,i,o,s){let a=o.nodeViews[n.type.name],l,c=a&&a(n,o,()=>{if(!l)return s;if(l.parent)return l.parent.posBeforeChild(l)},r,i),u=c&&c.dom,f=c&&c.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:f}=cn.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!f&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let d=u;return u=Hm(u,r,n),c?l=new rc(e,n,r,i,u,f||null,d,c):n.isText?new Ss(e,n,r,i,u,d):new t(e,n,r,i,u,f||null,d)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>E.empty)}return e}matchesNode(e,n,r){return this.dirty==ct&&e.eq(this.node)&&Ms(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,i=n,o=e.composing?this.localCompositionInfo(e,n):null,s=o&&o.pos>-1?o:null,a=o&&o.pos<0,l=new oc(this,s&&s.node,e);W0(this.node,this.innerDeco,(c,u,f)=>{c.spec.marks?l.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!f&&l.syncToMarks(u==this.node.childCount?J.none:this.node.child(u).marks,r,e,u),l.placeWidget(c,e,i)},(c,u,f,d)=>{l.syncToMarks(c.marks,r,e,d);let p;l.findNodeMatch(c,u,f,d)||a&&e.state.selection.from>i&&e.state.selection.to<i+c.nodeSize&&(p=l.findIndexWithChild(o.node))>-1&&l.updateNodeAt(c,u,f,p,e)||l.updateNextNode(c,u,f,e,d,i)||l.addNode(c,u,f,e,i),i+=c.nodeSize}),l.syncToMarks([],r,e,0),this.node.isTextblock&&l.addTextblockHacks(),l.destroyRest(),(l.changed||this.dirty==Un)&&(s&&this.protectLocalComposition(e,s),_m(this.contentDOM,this.children,e),Fr&&j0(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof z)||r<n||i>n+this.node.content.size)return null;let o=e.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let s=o.nodeValue,a=q0(this.node.content,s,r-n,i-n);return a<0?null:{node:o,pos:a,text:s}}else return{node:o,pos:-1,text:""}}protectLocalComposition(e,{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 s=new nc(this,o,n,i);e.input.compositionNodes.push(s),this.children=sc(this.children,r,r+i.length,e,s)}update(e,n,r,i){return this.dirty==mt||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=ct}updateOuterDeco(e){if(Ms(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=$m(this.dom,this.nodeDOM,ic(this.outerDeco,this.node,n),ic(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}};function am(t,e,n,r,i){Hm(r,e,t);let o=new gn(void 0,t,e,n,r,r,r);return o.contentDOM&&o.updateChildren(i,0),o}var Ss=class t extends gn{constructor(e,n,r,i,o,s){super(e,n,r,i,o,null,s)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,i){return this.dirty==mt||this.dirty!=ct&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=ct||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=ct,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let i=this.node.cut(e,n),o=document.createTextNode(i.text);return new t(this.parent,i,this.outerDeco,this.innerDeco,o,o)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=mt)}get domAtom(){return!1}isText(e){return this.node.text==e}},Cs=class extends er{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==ct&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}},rc=class extends gn{constructor(e,n,r,i,o,s,a,l){super(e,n,r,i,o,s,a),this.spec=l}update(e,n,r,i){if(this.dirty==mt)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let o=this.spec.update(e,n,r);return o&&this.updateInner(e,n,r,i),o}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}};function _m(t,e,n){let r=t.firstChild,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=s.dom;if(a.parentNode==t){for(;a!=r;)r=lm(r),i=!0;r=r.nextSibling}else i=!0,t.insertBefore(a,r);if(s instanceof Gn){let l=r?r.previousSibling:t.lastChild;_m(s.contentDOM,s.children,n),r=l?l.nextSibling:t.firstChild}}for(;r;)r=lm(r),i=!0;i&&n.trackWrites==t&&(n.trackWrites=null)}var Hi=function(t){t&&(this.nodeName=t)};Hi.prototype=Object.create(null);var Jn=[new Hi];function ic(t,e,n){if(t.length==0)return Jn;let r=n?Jn[0]:new Hi,i=[r];for(let o=0;o<t.length;o++){let s=t[o].type.attrs;if(s){s.nodeName&&i.push(r=new Hi(s.nodeName));for(let a in s){let l=s[a];l!=null&&(n&&i.length==1&&i.push(r=new Hi(e.isInline?"span":"div")),a=="class"?r.class=(r.class?r.class+" ":"")+l:a=="style"?r.style=(r.style?r.style+";":"")+l:a!="nodeName"&&(r[a]=l))}}}return i}function $m(t,e,n,r){if(n==Jn&&r==Jn)return e;let i=e;for(let o=0;o<r.length;o++){let s=r[o],a=n[o];if(o){let l;a&&a.nodeName==s.nodeName&&i!=t&&(l=i.parentNode)&&l.nodeName.toLowerCase()==s.nodeName||(l=document.createElement(s.nodeName),l.pmIsDeco=!0,l.appendChild(i),a=Jn[0]),i=l}$0(i,a||Jn[0],s)}return i}function $0(t,e,n){for(let r in e)r!="class"&&r!="style"&&r!="nodeName"&&!(r in n)&&t.removeAttribute(r);for(let r in n)r!="class"&&r!="style"&&r!="nodeName"&&n[r]!=e[r]&&t.setAttribute(r,n[r]);if(e.class!=n.class){let r=e.class?e.class.split(" ").filter(Boolean):[],i=n.class?n.class.split(" ").filter(Boolean):[];for(let o=0;o<r.length;o++)i.indexOf(r[o])==-1&&t.classList.remove(r[o]);for(let o=0;o<i.length;o++)r.indexOf(i[o])==-1&&t.classList.add(i[o]);t.classList.length==0&&t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,i;for(;i=r.exec(e.style);)t.style.removeProperty(i[1])}n.style&&(t.style.cssText+=n.style)}}function Hm(t,e,n){return $m(t,t,Jn,ic(e,n,t.nodeType!=1))}function Ms(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].type.eq(e[n].type))return!1;return!0}function lm(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}var oc=class{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=H0(e.node.content,e)}destroyBetween(e,n){if(e!=n){for(let r=e;r<n;r++)this.top.children[r].destroy();this.top.children.splice(e,n-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,n,r,i){let o=0,s=this.stack.length>>1,a=Math.min(s,e.length);for(;o<a&&(o==s-1?this.top:this.stack[o+1<<1]).matchesMark(e[o])&&e[o].type.spec.spanning!==!1;)o++;for(;o<s;)this.destroyRest(),this.top.dirty=ct,this.index=this.stack.pop(),this.top=this.stack.pop(),s--;for(;s<e.length;){this.stack.push(this.top,this.index+1);let l=-1,c=this.top.children.length;i<this.preMatch.index&&(c=Math.min(this.index+3,c));for(let u=this.index;u<c;u++){let f=this.top.children[u];if(f.matchesMark(e[s])&&!this.isLocked(f.dom)){l=u;break}}if(l<0&&this.index<this.top.children.length){let u=this.top.children[this.index];u instanceof Gn&&u.dirty!=mt&&u.mark.type==e[s].type&&u.spec.update&&!this.isLocked(u.dom)&&u.spec.update(e[s])&&(u.mark=e[s],l=this.index,this.changed=!0)}if(l>-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let u=Gn.create(this.top,e[s],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,s++}}findNodeMatch(e,n,r,i){let o=-1,s;if(i>=this.preMatch.index&&(s=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&s.matchesNode(e,n,r))o=this.top.children.indexOf(s,this.index);else for(let a=this.index,l=Math.min(this.top.children.length,a+5);a<l;a++){let c=this.top.children[a];if(c.matchesNode(e,n,r)&&!this.preMatch.matched.has(c)){o=a;break}}return o<0?!1:(this.destroyBetween(this.index,o),this.index++,!0)}updateNodeAt(e,n,r,i,o){let s=this.top.children[i];return s.dirty==mt&&s.dom==s.contentDOM&&(s.dirty=Un),s.update(e,n,r,o)?(this.destroyBetween(this.index,i),this.index++,!0):!1}findIndexWithChild(e){for(;;){let n=e.parentNode;if(!n)return-1;if(n==this.top.contentDOM){let r=e.pmViewDesc;if(r){for(let i=this.index;i<this.top.children.length;i++)if(this.top.children[i]==r)return i}return-1}e=n}}updateNextNode(e,n,r,i,o,s){for(let a=this.index;a<this.top.children.length;a++){let l=this.top.children[a];if(l instanceof gn){let c=this.preMatch.matched.get(l);if(c!=null&&c!=o)return!1;let u=l.dom,f,d=this.isLocked(u)&&!(e.isText&&l.node&&l.node.isText&&l.nodeDOM.nodeValue==e.text&&l.dirty!=mt&&Ms(n,l.outerDeco));if(!d&&l.update(e,n,r,i))return this.destroyBetween(this.index,a),l.dom!=u&&(this.changed=!0),this.index++,!0;if(!d&&(f=this.recreateWrapper(l,e,n,r,i,s)))return this.destroyBetween(this.index,a),this.top.children[this.index]=f,f.contentDOM&&(f.dirty=Un,f.updateChildren(i,s+1),f.dirty=ct),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,n,r,i,o,s){if(e.dirty||n.isAtom||!e.children.length||!e.node.content.eq(n.content)||!Ms(r,e.outerDeco)||!i.eq(e.innerDeco))return null;let a=gn.create(this.top,n,r,i,o,s);if(a.contentDOM){a.children=e.children,e.children=[];for(let l of a.children)l.parent=a}return e.destroy(),a}addNode(e,n,r,i,o){let s=gn.create(this.top,e,n,r,i,o);s.contentDOM&&s.updateChildren(i,o+1),this.top.children.splice(this.index++,0,s),this.changed=!0}placeWidget(e,n,r){let i=this.index<this.top.children.length?this.top.children[this.index]:null;if(i&&i.matchesWidget(e)&&(e==i.widget||!i.widget.type.toDOM.parentNode))this.index++;else{let o=new ws(this.top,e,n,r);this.top.children.splice(this.index++,0,o),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],n=this.top;for(;e instanceof Gn;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof Ss)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Le||Se)&&e&&e.dom.contentEditable=="false"&&this.addHackNode("IMG",n),this.addHackNode("BR",this.top))}addHackNode(e,n){if(n==this.top&&this.index<n.children.length&&n.children[this.index].matchesHack(e))this.index++;else{let r=document.createElement(e);e=="IMG"&&(r.className="ProseMirror-separator",r.alt=""),e=="BR"&&(r.className="ProseMirror-trailingBreak");let i=new Cs(this.top,[],r,null);n!=this.top?n.children.push(i):n.children.splice(this.index++,0,i),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}};function H0(t,e){let n=e,r=n.children.length,i=t.childCount,o=new Map,s=[];e:for(;i>0;){let a;for(;;)if(r){let c=n.children[r-1];if(c instanceof Gn)n=c,r=c.children.length;else{a=c,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let l=a.node;if(l){if(l!=t.child(i-1))break;--i,o.set(a,i),s.push(a)}}return{index:i,matched:o,matches:s.reverse()}}function V0(t,e){return t.type.side-e.type.side}function W0(t,e,n,r){let i=e.locals(t),o=0;if(i.length==0){for(let c=0;c<t.childCount;c++){let u=t.child(c);r(u,i,e.forChild(o,u),c),o+=u.nodeSize}return}let s=0,a=[],l=null;for(let c=0;;){let u,f;for(;s<i.length&&i[s].to==o;){let g=i[s++];g.widget&&(u?(f||(f=[u])).push(g):u=g)}if(u)if(f){f.sort(V0);for(let g=0;g<f.length;g++)n(f[g],c,!!l)}else n(u,c,!!l);let d,p;if(l)p=-1,d=l,l=null;else if(c<t.childCount)p=c,d=t.child(c++);else break;for(let g=0;g<a.length;g++)a[g].to<=o&&a.splice(g--,1);for(;s<i.length&&i[s].from<=o&&i[s].to>o;)a.push(i[s++]);let h=o+d.nodeSize;if(d.isText){let g=h;s<i.length&&i[s].from<g&&(g=i[s].from);for(let y=0;y<a.length;y++)a[y].to<g&&(g=a[y].to);g<h&&(l=d.cut(g-o),d=d.cut(0,g-o),h=g,p=-1)}else for(;s<i.length&&i[s].to<h;)s++;let m=d.isInline&&!d.isLeaf?a.filter(g=>!g.inline):a.slice();r(d,m,e.forChild(o,d),p),o=h}}function j0(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function q0(t,e,n,r){for(let i=0,o=0;i<t.childCount&&o<=r;){let s=t.child(i++),a=o;if(o+=s.nodeSize,!s.isText)continue;let l=s.text;for(;i<t.childCount;){let c=t.child(i++);if(o+=c.nodeSize,!c.isText)break;l+=c.text}if(o>=n){if(o>=r&&l.slice(r-e.length-a,r-a)==e)return r-e.length;let c=a<r?l.lastIndexOf(e,r-a-1):-1;if(c>=0&&c+e.length+a>=n)return a+c;if(n==r&&l.length>=r+e.length-a&&l.slice(r-a,r-a+e.length)==e)return r}}return-1}function sc(t,e,n,r,i){let o=[];for(let s=0,a=0;s<t.length;s++){let l=t[s],c=a,u=a+=l.size;c>=n||u<=e?o.push(l):(c<e&&o.push(l.slice(0,e-c,r)),i&&(o.push(i),i=void 0),u>n&&o.push(l.slice(n-c,l.size,r)))}return o}function kc(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),o=i&&i.size==0,s=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(s<0)return null;let a=r.resolve(s),l,c;if(Ds(n)){for(l=s;i&&!i.node;)i=i.parent;let f=i.node;if(i&&f.isAtom&&H.isSelectable(f)&&i.parent&&!(f.isInline&&w0(n.focusNode,n.focusOffset,i.dom))){let d=i.posBefore;c=new H(s==d?a:r.resolve(d))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let f=s,d=s;for(let p=0;p<n.rangeCount;p++){let h=n.getRangeAt(p);f=Math.min(f,t.docView.posFromDOM(h.startContainer,h.startOffset,1)),d=Math.max(d,t.docView.posFromDOM(h.endContainer,h.endOffset,-1))}if(f<0)return null;[l,s]=d==t.state.selection.anchor?[d,f]:[f,d],a=r.resolve(s)}else l=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(l<0)return null}let u=r.resolve(l);if(!c){let f=e=="pointer"||t.state.selection.head<a.pos&&!o?1:-1;c=bc(t,u,a,f)}return c}function Vm(t){return t.editable?t.hasFocus():jm(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function Jt(t,e=!1){let n=t.state.selection;if(Wm(t,n),!Vm(t))return;let r=t.input.mouseDown;if(!e&&Se&&r){let i=t.domSelectionRange(),o=t.domObserver.currentSelection;if(i.anchorNode&&o.anchorNode&&Zn(i.anchorNode,i.anchorOffset,o.anchorNode,o.anchorOffset)&&r.delaySelUpdate()){t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)U0(t);else{let{anchor:i,head:o}=n,s,a;cm&&!(n instanceof z)&&(n.$from.parent.inlineContent||(s=um(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(a=um(t,n.to))),t.docView.setSelection(i,o,t,e),cm&&(s&&fm(s),a&&fm(a)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&K0(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}var cm=Le||Se&&Rm<63;function um(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),i=r<n.childNodes.length?n.childNodes[r]:null,o=r?n.childNodes[r-1]:null;if(Le&&i&&i.contentEditable=="false")return Ul(i);if((!i||i.contentEditable=="false")&&(!o||o.contentEditable=="false")){if(i)return Ul(i);if(o)return Ul(o)}}function Ul(t){return t.contentEditable="true",Le&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function fm(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function K0(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),r=n.anchorNode,i=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Vm(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function U0(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,ve(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&We&&mn<=11&&(n.disabled=!0,n.disabled=!1)}function Wm(t,e){if(e instanceof H){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(dm(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else dm(t)}function dm(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function bc(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||z.between(e,n,r)}function pm(t){return t.editable&&!t.hasFocus()?!1:jm(t)}function jm(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function J0(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Zn(e.node,e.offset,n.anchorNode,n.anchorOffset)}function ac(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),o=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return o&&_.findFrom(o,e)}function hn(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function hm(t,e,n){let r=t.state.selection;if(r instanceof z)if(n.indexOf("s")>-1){let{$head:i}=r,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let s=t.state.doc.resolve(i.pos+o.nodeSize*(e<0?-1:1));return hn(t,new z(r.$anchor,s))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=ac(t.state,e);return i&&i instanceof H?hn(t,i):!1}else if(!(st&&n.indexOf("m")>-1)){let i=r.$head,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,s;if(!o||o.isText)return!1;let a=e<0?i.pos-o.nodeSize:i.pos;return o.isAtom||(s=t.docView.descAt(a))&&!s.contentDOM?H.isSelectable(o)?hn(t,new H(e<0?t.state.doc.resolve(i.pos-o.nodeSize):i)):Ji?hn(t,new z(t.state.doc.resolve(e<0?a:a+o.nodeSize))):!1:!1}}else return!1;else{if(r instanceof H&&r.node.isInline)return hn(t,new z(e>0?r.$to:r.$from));{let i=ac(t.state,e);return i?hn(t,i):!1}}}function Es(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function Vi(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Lr(t,e){return e<0?G0(t):Q0(t)}function G0(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,o,s=!1;for(lt&&n.nodeType==1&&r<Es(n)&&Vi(n.childNodes[r],-1)&&(s=!0);;)if(r>0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(Vi(a,-1))i=n,o=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if(qm(n))break;{let a=n.previousSibling;for(;a&&Vi(a,-1);)i=n.parentNode,o=ve(a),a=a.previousSibling;if(a)n=a,r=Es(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}s?lc(t,n,r):i&&lc(t,i,o)}function Q0(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=Es(n),o,s;for(;;)if(r<i){if(n.nodeType!=1)break;let a=n.childNodes[r];if(Vi(a,1))o=n,s=++r;else break}else{if(qm(n))break;{let a=n.nextSibling;for(;a&&Vi(a,1);)o=a.parentNode,s=ve(a)+1,a=a.nextSibling;if(a)n=a,r=0,i=Es(n);else{if(n=n.parentNode,n==t.dom)break;r=i=0}}}o&&lc(t,o,s)}function qm(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function X0(t,e){for(;t&&e==t.childNodes.length&&!Ui(t);)e=ve(t)+1,t=t.parentNode;for(;t&&e<t.childNodes.length;){let n=t.childNodes[e];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=0}}function Y0(t,e){for(;t&&!e&&!Ui(t);)e=ve(t),t=t.parentNode;for(;t&&e;){let n=t.childNodes[e-1];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=t.childNodes.length}}function lc(t,e,n){if(e.nodeType!=3){let o,s;(s=X0(e,n))?(e=s,n=0):(o=Y0(e,n))&&(e=o,n=o.nodeValue.length)}let r=t.domSelection();if(!r)return;if(Ds(r)){let o=document.createRange();o.setEnd(e,n),o.setStart(e,n),r.removeAllRanges(),r.addRange(o)}else r.extend&&r.extend(e,n);t.domObserver.setCurSelection();let{state:i}=t;setTimeout(()=>{t.state==i&&Jt(t)},50)}function mm(t,e){let n=t.state.doc.resolve(e);if(!(Se||Dm)&&n.parent.inlineContent){let i=t.coordsAtPos(e);if(e>n.start()){let o=t.coordsAtPos(e-1),s=(o.top+o.bottom)/2;if(s>i.top&&s<i.bottom&&Math.abs(o.left-i.left)>1)return o.left<i.left?"ltr":"rtl"}if(e<n.end()){let o=t.coordsAtPos(e+1),s=(o.top+o.bottom)/2;if(s>i.top&&s<i.bottom&&Math.abs(o.left-i.left)>1)return o.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function gm(t,e,n){let r=t.state.selection;if(r instanceof z&&!r.empty||n.indexOf("s")>-1||st&&n.indexOf("m")>-1)return!1;let{$from:i,$to:o}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let s=ac(t.state,e);if(s&&s instanceof H)return hn(t,s)}if(!i.parent.inlineContent){let s=e<0?i:o,a=r instanceof Je?_.near(s,e):_.findFrom(s,e);return a?hn(t,a):!1}return!1}function ym(t,e){if(!(t.state.selection instanceof z))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(o&&!o.isText){let s=t.state.tr;return e<0?s.delete(n.pos-o.nodeSize,n.pos):s.delete(n.pos,n.pos+o.nodeSize),t.dispatch(s),!0}return!1}function km(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function Z0(t){if(!Le||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;km(t,r,"true"),setTimeout(()=>km(t,r,"false"),20)}return!1}function eC(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function tC(t,e){let n=e.keyCode,r=eC(e);if(n==8||st&&n==72&&r=="c")return ym(t,-1)||Lr(t,-1);if(n==46&&!e.shiftKey||st&&n==68&&r=="c")return ym(t,1)||Lr(t,1);if(n==13||n==27)return!0;if(n==37||st&&n==66&&r=="c"){let i=n==37?mm(t,t.state.selection.from)=="ltr"?-1:1:-1;return hm(t,i,r)||Lr(t,i)}else if(n==39||st&&n==70&&r=="c"){let i=n==39?mm(t,t.state.selection.from)=="ltr"?1:-1:1;return hm(t,i,r)||Lr(t,i)}else{if(n==38||st&&n==80&&r=="c")return gm(t,-1,r)||Lr(t,-1);if(n==40||st&&n==78&&r=="c")return Z0(t)||gm(t,1,r)||Lr(t,1);if(r==(st?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function xc(t,e){t.someProp("transformCopied",p=>{e=p(e,t)});let n=[],{content:r,openStart:i,openEnd:o}=e;for(;i>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,o--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let s=t.someProp("clipboardSerializer")||cn.fromSchema(t.state.schema),a=Xm(),l=a.createElement("div");l.appendChild(s.serializeFragment(r,{document:a}));let c=l.firstChild,u,f=0;for(;c&&c.nodeType==1&&(u=Qm[c.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let h=a.createElement(u[p]);for(;l.firstChild;)h.appendChild(l.firstChild);l.appendChild(h),f++}c=l.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${i} ${o}${f?` -${f}`:""} ${JSON.stringify(n)}`);let d=t.someProp("clipboardTextSerializer",p=>p(e,t))||e.content.textBetween(0,e.content.size,` `);return{dom:l,text:d,slice:e}}function Km(t,e,n,r,i){let o=i.parent.type.spec.code,s,a;if(!n&&!e)return null;let l=!!e&&(r||o||!n);if(l){if(t.someProp("transformPastedText",d=>{e=d(e,o||r,t)}),o)return a=new A(E.from(t.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),t.someProp("transformPasted",d=>{a=d(a,t,!0)}),a;let f=t.someProp("clipboardTextParser",d=>d(e,i,r,t));if(f)a=f;else{let d=i.marks(),{schema:p}=t.state,h=cn.fromSchema(p);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=s.appendChild(document.createElement("p"));m&&g.appendChild(h.serializeNode(p.text(m,d)))})}}else t.someProp("transformPastedHTML",f=>{n=f(n,t)}),s=oC(n),Ji&&sC(s);let c=s&&s.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let f=+u[3];f>0;f--){let d=s.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;s=d}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||ln.fromSchema(t.state.schema)).parseSlice(s,{preserveWhitespace:!!(l||u),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!nC.test(d.parentNode.nodeName)?{ignore:!0}:null}})),u)a=aC(bm(a,+u[1],+u[2]),u[4]);else if(a=A.maxOpen(rC(a.content,i),!0),a.openStart||a.openEnd){let f=0,d=0;for(let p=a.content.firstChild;f<a.openStart&&!p.type.spec.isolating;f++,p=p.firstChild);for(let p=a.content.lastChild;d<a.openEnd&&!p.type.spec.isolating;d++,p=p.lastChild);a=bm(a,f,d)}return t.someProp("transformPasted",f=>{a=f(a,t,l)}),a}var nC=/^(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 rC(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),o,s=[];if(t.forEach(a=>{if(!s)return;let l=i.findWrapping(a.type),c;if(!l)return s=null;if(c=s.length&&o.length&&Jm(l,o,a,s[s.length-1],0))s[s.length-1]=c;else{s.length&&(s[s.length-1]=Gm(s[s.length-1],o.length));let u=Um(a,l);s.push(u),i=i.matchType(u.type),o=l}}),s)return E.from(s)}return t}function Um(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,E.from(t));return t}function Jm(t,e,n,r,i){if(i<t.length&&i<e.length&&t[i]==e[i]){let o=Jm(t,e,n,r.lastChild,i+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(i==t.length-1?n.type:t[i+1]))return r.copy(r.content.append(E.from(Um(n,t,i+1))))}}function Gm(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Gm(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(E.empty,!0);return t.copy(n.append(r))}function cc(t,e,n,r,i,o){let s=e<0?t.firstChild:t.lastChild,a=s.content;return t.childCount>1&&(o=0),i<r-1&&(a=cc(a,e,n,r,i+1,o)),i>=n&&(a=e<0?s.contentMatchAt(0).fillBefore(a,o<=i).append(a):a.append(s.contentMatchAt(s.childCount).fillBefore(E.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,s.copy(a))}function bm(t,e,n){return e<t.openStart&&(t=new A(cc(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new A(cc(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}var Qm={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};function Xm(){return document.implementation.createHTMLDocument("title")}var Jl=null;function iC(t){let e=window.trustedTypes;return e?(Jl||(Jl=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),Jl.createHTML(t)):t}function oC(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Xm(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(t),o;if((o=i&&Qm[i[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),r.innerHTML=iC(t),o)for(let s=0;s<o.length;s++)r=r.querySelector(o[s])||r;for(let s=0;s<n.styleSheets.length;s++){let a=n.styleSheets[s];for(let l=0;l<a.rules.length;l++){let c=a.rules[l];if(c instanceof CSSStyleRule){let u=r.querySelectorAll(c.selectorText);for(let f=0;f<u.length;f++)u[f].style.cssText+=c.style.cssText}}}return r}function sC(t){let e=t.querySelectorAll(Se?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];r.childNodes.length==1&&r.textContent=="\xA0"&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function aC(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return t}let{content:i,openStart:o,openEnd:s}=t;for(let a=r.length-2;a>=0;a-=2){let l=n.nodes[r[a]];if(!l||l.hasRequiredAttrs())break;i=E.from(l.create(r[a+1],i)),o++,s++}return new A(i,o,s)}var Pe={},Fe={},lC={touchstart:!0,touchmove:!0},uc=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function cC(t){for(let e in Pe){let n=Pe[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{fC(t,r)&&!wc(t,r)&&(t.editable||!(r.type in Fe))&&n(t,r)},lC[e]?{passive:!0}:void 0)}Le&&t.dom.addEventListener("input",()=>null),fc(t)}function Ut(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function uC(t){t.input.mouseDown&&t.input.mouseDown.done(),t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function fc(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>wc(t,r))})}function wc(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function fC(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function dC(t,e){!wc(t,e)&&Pe[e.type]&&(t.editable||!(e.type in Fe))&&Pe[e.type](t,e)}Fe.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!eg(t)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Kt&&Se&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Fr&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",i=>i(t,Kn(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||tC(t,n)?n.preventDefault():Ut(t,"key")};Fe.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Fe.keypress=(t,e)=>{let n=e;if(eg(t)||!n.charCode||n.ctrlKey&&!n.altKey||st&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof z)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),o=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",s=>s(t,r.$from.pos,r.$to.pos,i,o))&&t.dispatch(o()),n.preventDefault()}};function Gi(t){return{left:t.clientX,top:t.clientY}}function pC(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function Sc(t,e,n,r,i){if(r==-1)return!1;let o=t.state.doc.resolve(r);for(let s=o.depth+1;s>0;s--)if(t.someProp(e,a=>s>o.depth?a(t,n,o.nodeAfter,o.before(s),i,!0):a(t,n,o.node(s),o.before(s),i,!1)))return!0;return!1}function Qi(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);n=="pointer"&&r.setMeta("pointer",!0),t.dispatch(r)}function hC(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&H.isSelectable(r)?(Qi(t,new H(n),"pointer"),!0):!1}function mC(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof H&&(r=n.node);let o=t.state.doc.resolve(e);for(let s=o.depth+1;s>0;s--){let a=s>o.depth?o.nodeAfter:o.node(s);if(H.isSelectable(a)){r&&n.$from.depth>0&&s>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos?i=o.before(n.$from.depth):i=o.before(s);break}}return i!=null?(Qi(t,H.create(t.state.doc,i),"pointer"),!0):!1}function gC(t,e,n,r,i){return Sc(t,"handleClickOn",e,n,r)||t.someProp("handleClick",o=>o(t,e,r))||(i?mC(t,n):hC(t,n))}function yC(t,e,n,r){return Sc(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function kC(t,e,n,r){return Sc(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||bC(t,n,r)}function bC(t,e,n){if(n.button!=0)return!1;let r=Ym(t,e,!0),i=t.state.doc;return r?(Qi(t,r,"pointer"),r instanceof z&&i.eq(t.state.doc)&&(t.input.mouseDown=new pc(t,r)),!0):!1}function Ym(t,e,n){let r=t.state.doc;if(e==-1)return r.inlineContent?z.create(r,0,r.content.size):null;let i=r.resolve(e);for(let o=i.depth+1;o>0;o--){let s=o>i.depth?i.nodeAfter:i.node(o),a=i.before(o);if(s.inlineContent)return z.create(r,a+1,a+1+s.content.size);if(n&&H.isSelectable(s))return H.create(r,a)}return null}function Cc(t){return Is(t)}var Zm=st?"metaKey":"ctrlKey";Pe.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Cc(t),i=Date.now(),o="singleClick";i-t.input.lastClick.time<500&&pC(n,t.input.lastClick)&&!n[Zm]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?o="doubleClick":t.input.lastClick.type=="doubleClick"&&(o="tripleClick")),t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:o,button:n.button},t.input.mouseDown&&t.input.mouseDown.done();let s=t.posAtCoords(Gi(n));s&&(o=="singleClick"?t.input.mouseDown=new dc(t,s,n,!!r):(o=="doubleClick"?yC:kC)(t,s.pos,s.inside,n)?n.preventDefault():Ut(t,"pointer"))};var Ts=class{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.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}},dc=class extends Ts{constructor(e,n,r,i){super(e),this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Zm],this.allowDefault=r.shiftKey;let o,s;if(n.inside>-1)o=e.state.doc.nodeAt(n.inside),s=n.inside;else{let u=e.state.doc.resolve(n.pos);o=u.parent,s=u.depth?u.before():0}let a=i?null:r.target,l=a?e.docView.nearestDesc(a,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(o.type.spec.draggable&&o.type.spec.selectable!==!1||c instanceof H&&c.from<=s&&c.to>s)&&(this.mightDrag={node:o,pos:s,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&<&&!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()),Ut(e,"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||Jt(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Gi(e))),this.updateAllowDefault(e),this.allowDefault||!n?Ut(this.view,"pointer"):gC(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Le&&this.mightDrag&&!this.mightDrag.node.isAtom||Se&&!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)?(Qi(this.view,_.near(this.view.state.doc.resolve(n.pos)),"pointer"),e.preventDefault()):Ut(this.view,"pointer")}move(e){this.updateAllowDefault(e),Ut(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}},pc=class extends Ts{constructor(e,n){super(e),this.startSelection=n,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),Ut(this.view,"pointer");let n=this.view.posAtCoords(Gi(e)),r=n&&Ym(this.view,n.inside,!1);if(!r)return;let{doc:i}=this.view.state,o=this.startSelection,[s,a]=r.from<o.from?[o.to,r.from]:[o.from,r.to];Qi(this.view,z.create(i,s,a),"pointer")}};Pe.touchstart=t=>{t.input.lastTouch=Date.now(),Cc(t),Ut(t,"pointer")};Pe.touchmove=t=>{t.input.lastTouch=Date.now(),Ut(t,"pointer")};Pe.contextmenu=t=>Cc(t);function eg(t,e){return t.composing?!0:Le&&Math.abs(Date.now()-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}var xC=Kt?5e3:-1;Fe.compositionstart=Fe.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof z&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Se&&Dm&&wC(t)))t.markCursor=t.state.storedMarks||n.marks(),Is(t,!0),t.markCursor=null;else if(Is(t,!e.selection.empty),lt&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,o=r.focusOffset;i&&i.nodeType==1&&o!=0;){let s=o<0?i.lastChild:i.childNodes[o-1];if(!s)break;if(s.nodeType==3){let a=t.domSelection();a&&a.collapse(s,s.nodeValue.length);break}else i=s,o=-1}}t.input.composing=!0}tg(t,xC)};function wC(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Fe.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,tg(t,20))};function tg(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Is(t),e))}function ng(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function SC(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=b0(e.focusNode,e.focusOffset),r=x0(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let s=n.pmViewDesc;if(!(!s||!s.isText(n.nodeValue)))return r}}return n||r}function Is(t,e=!1){if(!(Kt&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),ng(t),e||t.docView&&t.docView.dirty){let n=kc(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function CC(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}var Wi=We&&mn<15||Fr&&M0<604;Pe.copy=Fe.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let o=Wi?null:n.clipboardData,s=r.content(),{dom:a,text:l}=xc(t,s);o?(n.preventDefault(),o.clearData(),o.setData("text/html",a.innerHTML),o.setData("text/plain",l)):CC(t,a),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function MC(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function EC(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.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=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?ji(t,r.value,null,i,e):ji(t,r.textContent,r.innerHTML,i,e)},50)}function ji(t,e,n,r,i){let o=Km(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,i,o||A.empty)))return!0;if(!o)return!1;let s=MC(o),a=s?t.state.tr.replaceSelectionWith(s,r):t.state.tr.replaceSelection(o);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function rg(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Fe.paste=(t,e)=>{let n=e;if(t.composing&&!Kt)return;let r=Wi?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&ji(t,rg(r),r.getData("text/html"),i,n)?n.preventDefault():EC(t,n)};var vs=class{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}},TC=st?"altKey":"ctrlKey";function ig(t,e){let n;return t.someProp("dragCopies",r=>{n=n||r(e)}),n!=null?!n:!e[TC]}Pe.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,o=i.empty?null:t.posAtCoords(Gi(n)),s;if(!(o&&o.pos>=i.from&&o.pos<=(i instanceof H?i.to-1:i.to))){if(r&&r.mightDrag)s=H.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let f=t.docView.nearestDesc(n.target,!0);f&&f.node.type.spec.draggable&&f!=t.docView&&(s=H.create(t.state.doc,f.posBefore))}}let a=(s||t.state.selection).content(),{dom:l,text:c,slice:u}=xc(t,a);(!n.dataTransfer.files.length||!Se||Rm>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Wi?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Wi||n.dataTransfer.setData("text/plain",c),t.dragging=new vs(u,ig(t,n),s)};Pe.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Fe.dragover=Fe.dragenter=(t,e)=>e.preventDefault();Fe.drop=(t,e)=>{try{IC(t,e,t.dragging)}finally{t.dragging=null}};function IC(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Gi(e));if(!r)return;let i=t.state.doc.resolve(r.pos),o=n&&n.slice;o?t.someProp("transformPasted",p=>{o=p(o,t,!1)}):o=Km(t,rg(e.dataTransfer),Wi?null:e.dataTransfer.getData("text/html"),!1,i);let s=!!(n&&ig(t,e));if(t.someProp("handleDrop",p=>p(t,e,o||A.empty,s))){e.preventDefault();return}if(!o)return;e.preventDefault();let a=o?gh(t.state.doc,i.pos,o):i.pos;a==null&&(a=i.pos);let l=t.state.tr;if(s){let{node:p}=n;p?p.replace(l):l.deleteSelection()}let c=l.mapping.map(a),u=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,f=l.doc;if(u?l.replaceRangeWith(c,c,o.content.firstChild):l.replaceRange(c,c,o),l.doc.eq(f))return;let d=l.doc.resolve(c);if(u&&H.isSelectable(o.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(o.content.firstChild))l.setSelection(new H(d));else{let p=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((h,m,g,y)=>p=y),l.setSelection(bc(t,d,l.doc.resolve(p)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}Pe.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Jt(t)},20))};Pe.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};Pe.beforeinput=(t,e)=>{if(Se&&Kt&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",o=>o(t,Kn(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Fe)Pe[t]=Fe[t];function qi(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}var As=class t{constructor(e,n){this.toDOM=e,this.spec=n||Xn,this.side=this.spec.side||0}map(e,n,r,i){let{pos:o,deleted:s}=e.mapResult(n.from+i,this.side<0?-1:1);return s?null:new se(o-r,o-r,this)}valid(){return!0}eq(e){return this==e||e instanceof t&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&qi(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},Qn=class t{constructor(e,n){this.attrs=e,this.spec=n||Xn}map(e,n,r,i){let o=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,s=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return o>=s?null:new se(o,s,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof t&&qi(this.attrs,e.attrs)&&qi(this.spec,e.spec)}static is(e){return e.type instanceof t}destroy(){}},hc=class t{constructor(e,n){this.attrs=e,this.spec=n||Xn}map(e,n,r,i){let o=e.mapResult(n.from+i,1);if(o.deleted)return null;let s=e.mapResult(n.to+i,-1);return s.deleted||s.pos<=o.pos?null:new se(o.pos-r,s.pos-r,this)}valid(e,n){let{index:r,offset:i}=e.content.findIndex(n.from),o;return i==n.from&&!(o=e.child(r)).isText&&i+o.nodeSize==n.to}eq(e){return this==e||e instanceof t&&qi(this.attrs,e.attrs)&&qi(this.spec,e.spec)}destroy(){}},se=class t{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new t(e,n,this.type)}eq(e,n=0){return this.type.eq(e.type)&&this.from+n==e.from&&this.to+n==e.to}map(e,n,r){return this.type.map(e,this,n,r)}static widget(e,n,r){return new t(e,e,new As(n,r))}static inline(e,n,r,i){return new t(e,n,new Qn(r,i))}static node(e,n,r,i){return new t(e,n,new hc(r,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof Qn}get widget(){return this.type instanceof As}},Br=[],Xn={},re=class t{constructor(e,n){this.local=e.length?e:Br,this.children=n.length?n:Br}static create(e,n){return n.length?Rs(n,e,0,Xn):Oe}find(e,n,r){let i=[];return this.findInner(e??0,n??1e9,i,0,r),i}findInner(e,n,r,i,o){for(let s=0;s<this.local.length;s++){let a=this.local[s];a.from<=n&&a.to>=e&&(!o||o(a.spec))&&r.push(a.copy(a.from+i,a.to+i))}for(let s=0;s<this.children.length;s+=3)if(this.children[s]<n&&this.children[s+1]>e){let a=this.children[s]+1;this.children[s+2].findInner(e-a,n-a,r,i+a,o)}}map(e,n,r){return this==Oe||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Xn)}mapInner(e,n,r,i,o){let s;for(let a=0;a<this.local.length;a++){let l=this.local[a].map(e,r,i);l&&l.type.valid(n,l)?(s||(s=[])).push(l):o.onRemove&&o.onRemove(this.local[a].spec)}return this.children.length?vC(this.children,s||[],e,n,r,i,o):s?new t(s.sort(Yn),Br):Oe}add(e,n){return n.length?this==Oe?t.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let i,o=0;e.forEach((a,l)=>{let c=l+r,u;if(u=sg(n,a,c)){for(i||(i=this.children.slice());o<i.length&&i[o]<l;)o+=3;i[o]==l?i[o+2]=i[o+2].addInner(a,u,c+1):i.splice(o,0,l,l+a.nodeSize,Rs(u,a,c+1,Xn)),o+=3}});let s=og(o?ag(n):n,-r);for(let a=0;a<s.length;a++)s[a].type.valid(e,s[a])||s.splice(a--,1);return new t(s.length?this.local.concat(s).sort(Yn):this.local,i||this.children)}remove(e){return e.length==0||this==Oe?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,i=this.local;for(let o=0;o<r.length;o+=3){let s,a=r[o]+n,l=r[o+1]+n;for(let u=0,f;u<e.length;u++)(f=e[u])&&f.from>a&&f.to<l&&(e[u]=null,(s||(s=[])).push(f));if(!s)continue;r==this.children&&(r=this.children.slice());let c=r[o+2].removeInner(s,a+1);c!=Oe?r[o+2]=c:(r.splice(o,3),o-=3)}if(i.length){for(let o=0,s;o<e.length;o++)if(s=e[o])for(let a=0;a<i.length;a++)i[a].eq(s,n)&&(i==this.local&&(i=this.local.slice()),i.splice(a--,1))}return r==this.children&&i==this.local?this:i.length||r.length?new t(i,r):Oe}forChild(e,n){if(this==Oe)return this;if(n.isLeaf)return t.empty;let r,i;for(let a=0;a<this.children.length;a+=3)if(this.children[a]>=e){this.children[a]==e&&(r=this.children[a+2]);break}let o=e+1,s=o+n.content.size;for(let a=0;a<this.local.length;a++){let l=this.local[a];if(l.from<s&&l.to>o&&l.type instanceof Qn){let c=Math.max(o,l.from)-o,u=Math.min(s,l.to)-o;c<u&&(i||(i=[])).push(l.copy(c,u))}}if(i){let a=new t(i.sort(Yn),Br);return r?new Ns([a,r]):a}return r||Oe}eq(e){if(this==e)return!0;if(!(e instanceof t)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let n=0;n<this.local.length;n++)if(!this.local[n].eq(e.local[n]))return!1;for(let n=0;n<this.children.length;n+=3)if(this.children[n]!=e.children[n]||this.children[n+1]!=e.children[n+1]||!this.children[n+2].eq(e.children[n+2]))return!1;return!0}locals(e){return Mc(this.localsInner(e))}localsInner(e){if(this==Oe)return Br;if(e.inlineContent||!this.local.some(Qn.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof Qn||n.push(this.local[r]);return n}forEachSet(e){e(this)}};re.empty=new re([],[]);re.removeOverlap=Mc;var Oe=re.empty,Ns=class t{constructor(e){this.members=e}map(e,n){let r=this.members.map(i=>i.map(e,n,Xn));return t.from(r)}forChild(e,n){if(n.isLeaf)return re.empty;let r=[];for(let i=0;i<this.members.length;i++){let o=this.members[i].forChild(e,n);o!=Oe&&(o instanceof t?r=r.concat(o.members):r.push(o))}return t.from(r)}eq(e){if(!(e instanceof t)||e.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(e.members[n]))return!1;return!0}locals(e){let n,r=!0;for(let i=0;i<this.members.length;i++){let o=this.members[i].localsInner(e);if(o.length)if(!n)n=o;else{r&&(n=n.slice(),r=!1);for(let s=0;s<o.length;s++)n.push(o[s])}}return n?Mc(r?n:n.sort(Yn)):Br}static from(e){switch(e.length){case 0:return Oe;case 1:return e[0];default:return new t(e.every(n=>n instanceof re)?e:e.reduce((n,r)=>n.concat(r instanceof re?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}};function vC(t,e,n,r,i,o,s){let a=t.slice();for(let c=0,u=o;c<n.maps.length;c++){let f=0;n.maps[c].forEach((d,p,h,m)=>{let g=m-h-(p-d);for(let y=0;y<a.length;y+=3){let x=a[y+1];if(x<0||d>x+u-f)continue;let C=a[y]+u-f;p>=C?a[y+1]=d<=C?-2:-1:d>=u&&g&&(a[y]+=g,a[y+1]+=g)}f+=g}),u=n.maps[c].map(u,-1)}let l=!1;for(let c=0;c<a.length;c+=3)if(a[c+1]<0){if(a[c+1]==-2){l=!0,a[c+1]=-1;continue}let u=n.map(t[c]+o),f=u-i;if(f<0||f>=r.content.size){l=!0;continue}let d=n.map(t[c+1]+o,-1),p=d-i,{index:h,offset:m}=r.content.findIndex(f),g=r.maybeChild(h);if(g&&m==f&&m+g.nodeSize==p){let y=a[c+2].mapInner(n,g,u+1,t[c]+o+1,s);y!=Oe?(a[c]=f,a[c+1]=p,a[c+2]=y):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=AC(a,t,e,n,i,o,s),u=Rs(c,r,0,s);e=u.local;for(let f=0;f<a.length;f+=3)a[f+1]<0&&(a.splice(f,3),f-=3);for(let f=0,d=0;f<u.children.length;f+=3){let p=u.children[f];for(;d<a.length&&a[d]<p;)d+=3;a.splice(d,0,u.children[f],u.children[f+1],u.children[f+2])}}return new re(e.sort(Yn),a)}function og(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let i=t[r];n.push(new se(i.from+e,i.to+e,i.type))}return n}function AC(t,e,n,r,i,o,s){function a(l,c){for(let u=0;u<l.local.length;u++){let f=l.local[u].map(r,i,c);f?n.push(f):s.onRemove&&s.onRemove(l.local[u].spec)}for(let u=0;u<l.children.length;u+=3)a(l.children[u+2],l.children[u]+c+1)}for(let l=0;l<t.length;l+=3)t[l+1]==-1&&a(t[l+2],e[l]+o+1);return n}function sg(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,i=null;for(let o=0,s;o<t.length;o++)(s=t[o])&&s.from>n&&s.to<r&&((i||(i=[])).push(s),t[o]=null);return i}function ag(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Rs(t,e,n,r){let i=[],o=!1;e.forEach((a,l)=>{let c=sg(t,a,l+n);if(c){o=!0;let u=Rs(c,a,n+l+1,r);u!=Oe&&i.push(l,l+a.nodeSize,u)}});let s=og(o?ag(t):t,-n).sort(Yn);for(let a=0;a<s.length;a++)s[a].type.valid(e,s[a])||(r.onRemove&&r.onRemove(s[a].spec),s.splice(a--,1));return s.length||i.length?new re(s,i):Oe}function Yn(t,e){return t.from-e.from||t.to-e.to}function Mc(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let i=n+1;i<e.length;i++){let o=e[i];if(o.from==r.from){o.to!=r.to&&(e==t&&(e=t.slice()),e[i]=o.copy(o.from,r.to),xm(e,i+1,o.copy(r.to,o.to)));continue}else{o.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,o.from),xm(e,i,r.copy(o.from,r.to)));break}}}return e}function xm(t,e,n){for(;e<t.length&&Yn(n,t[e])>0;)e++;t.splice(e,0,n)}function Gl(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Oe&&e.push(r)}),t.cursorWrapper&&e.push(re.create(t.state.doc,[t.cursorWrapper.deco])),Ns.from(e)}var NC={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},RC=We&&mn<=11,mc=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},gc=class{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new mc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;i<r.length;i++)this.queue.push(r[i]);We&&mn<=11&&r.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():Le&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),RC&&(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,NC)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let n=0;n<e.length;n++)this.queue.push(e[n]);window.setTimeout(()=>this.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(pm(this.view)){if(this.suppressingSelectionUpdates)return Jt(this.view);if(We&&mn<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Zn(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let o=e.focusNode;o;o=Pr(o))n.add(o);for(let o=e.anchorNode;o;o=Pr(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 e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&pm(e)&&!this.ignoreSelectionChange(r),o=-1,s=-1,a=!1,l=[];if(e.editable)for(let u=0;u<n.length;u++){let f=this.registerMutation(n[u],l);f&&(o=o<0?f.from:Math.min(f.from,o),s=s<0?f.to:Math.max(f.to,s),f.typeOver&&(a=!0))}if(l.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||Se&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&n.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of l)if(u.nodeName=="BR"&&u.parentNode){let f=u.nextSibling;for(;f&&f.nodeType==1;){if(f.contentEditable=="false"){u.parentNode.removeChild(u);break}f=f.firstChild}}}else if(lt&&l.length){let u=l.filter(f=>f.nodeName=="BR");if(u.length==2){let[f,d]=u;f.parentNode&&f.parentNode.parentNode==d.parentNode?d.remove():f.remove()}else{let{focusNode:f}=this.currentSelection;for(let d of u){let p=d.parentNode;p&&p.nodeName=="LI"&&(!f||LC(e,f)!=p)&&d.remove()}}}let c=null;o<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&Ds(r)&&(c=kc(e))&&c.eq(_.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Jt(e),this.currentSelection.set(r),e.scrollToSelection()):(o>-1||i)&&(o>-1&&(e.docView.markDirty(o,s),DC(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,BC(e,l)),this.handleDOMChange(o,s,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Jt(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let f=e.addedNodes[u];n.push(f),f.nodeType==3&&(this.lastChangedTextNode=f)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let i=e.previousSibling,o=e.nextSibling;if(We&&mn<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:f,nextSibling:d}=e.addedNodes[u];(!f||Array.prototype.indexOf.call(e.addedNodes,f)<0)&&(i=f),(!d||Array.prototype.indexOf.call(e.addedNodes,d)<0)&&(o=d)}let s=i&&i.parentNode==e.target?ve(i)+1:0,a=r.localPosFromDOM(e.target,s,-1),l=o&&o.parentNode==e.target?ve(o):e.target.childNodes.length,c=r.localPosFromDOM(e.target,l,1);return{from:a,to:c}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}},wm=new WeakMap,Sm=!1;function DC(t){if(!wm.has(t)&&(wm.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=lt,Sm)return;console.warn("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."),Sm=!0}}function Cm(t,e){let n=e.startContainer,r=e.startOffset,i=e.endContainer,o=e.endOffset,s=t.domAtPos(t.state.selection.anchor);return Zn(s.node,s.offset,i,o)&&([n,r,i,o]=[i,o,n,r]),{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:o}}function OC(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return Cm(t,i)}let n;function r(i){i.preventDefault(),i.stopImmediatePropagation(),n=i.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?Cm(t,n):null}function LC(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function BC(t,e){var n;let{focusNode:r,focusOffset:i}=t.domSelectionRange();for(let o of e)if(((n=o.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let s=o.nextSibling;for(;s&&s.nodeName!="TD"&&s.nodeName!="TH";)s=s.nextSibling;if(s){let a=s;for(;;){let l=a.firstChild;if(!l||l.nodeType!=1||l.contentEditable=="false"||/^(BR|IMG)$/.test(l.nodeName))break;a=l}a.insertBefore(o,a.firstChild),r==o&&t.domSelection().collapse(o,i)}else o.parentNode.removeChild(o)}}function PC(t,e,n){let{node:r,fromOffset:i,toOffset:o,from:s,to:a}=t.docView.parseRange(e,n),l=t.domSelectionRange(),c,u=l.anchorNode;if(u&&t.dom.contains(u.nodeType==1?u:u.parentNode)&&(c=[{node:u,offset:l.anchorOffset}],Ds(l)||c.push({node:l.focusNode,offset:l.focusOffset})),Se&&t.input.lastKeyCode===8)for(let g=o;g>i;g--){let y=r.childNodes[g-1],x=y.pmViewDesc;if(y.nodeName=="BR"&&!x){o=g;break}if(!x||x.size)break}let f=t.state.doc,d=t.someProp("domParser")||ln.fromSchema(t.state.schema),p=f.resolve(s),h=null,m=d.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:i,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:FC,context:p});if(c&&c[0].pos!=null){let g=c[0].pos,y=c[1]&&c[1].pos;y==null&&(y=g),h={anchor:g+s,head:y+s}}return{doc:m,sel:h,from:s,to:a}}function FC(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Le&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||Le&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}var zC=/^(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 _C(t,e,n,r,i){let o=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let N=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,O=kc(t,N);if(O&&!t.state.selection.eq(O)){if(Se&&Kt&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",S=>S(t,Kn(13,"Enter"))))return;let L=t.state.tr.setSelection(O);N=="pointer"?L.setMeta("pointer",!0):N=="key"&&L.scrollIntoView(),o&&L.setMeta("composition",o),t.dispatch(L)}return}let s=t.state.doc.resolve(e),a=s.sharedDepth(n);e=s.before(a+1),n=t.state.doc.resolve(n).after(a+1);let l=t.state.selection,c=PC(t,e,n),u=t.state.doc,f=u.slice(c.from,c.to),d,p;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(d=t.state.selection.to,p="end"):(d=t.state.selection.from,p="start"),t.input.lastKeyCode=null;let h=VC(f.content,c.doc.content,c.from,d,p);if(h&&t.input.domChangeCount++,(Fr&&t.input.lastIOSEnter>Date.now()-225||Kt)&&i.some(N=>N.nodeType==1&&!zC.test(N.nodeName))&&(!h||h.endA>=h.endB)&&t.someProp("handleKeyDown",N=>N(t,Kn(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!h)if(r&&l instanceof z&&!l.empty&&l.$head.sameParent(l.$anchor)&&!t.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))h={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let N=Mm(t,t.state.doc,c.sel);if(N&&!N.eq(t.state.selection)){let O=t.state.tr.setSelection(N);o&&O.setMeta("composition",o),t.dispatch(O)}}return}t.state.selection.from<t.state.selection.to&&h.start==h.endB&&t.state.selection instanceof z&&(h.start>t.state.selection.from&&h.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?h.start=t.state.selection.from:h.endA<t.state.selection.to&&h.endA>=t.state.selection.to-2&&t.state.selection.to<=c.to&&(h.endB+=t.state.selection.to-h.endA,h.endA=t.state.selection.to)),We&&mn<=11&&h.endB==h.start+1&&h.endA==h.start&&h.start>c.from&&c.doc.textBetween(h.start-c.from-1,h.start-c.from+1)==" \xA0"&&(h.start--,h.endA--,h.endB--);let m=c.doc.resolveNoCache(h.start-c.from),g=c.doc.resolveNoCache(h.endB-c.from),y=u.resolve(h.start),x=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=h.endA;if((Fr&&t.input.lastIOSEnter>Date.now()-225&&(!x||i.some(N=>N.nodeName=="DIV"||N.nodeName=="P"))||!x&&m.pos<c.doc.content.size&&(!m.sameParent(g)||!m.parent.inlineContent)&&m.pos<g.pos&&!/\S/.test(c.doc.textBetween(m.pos,g.pos,"","")))&&t.someProp("handleKeyDown",N=>N(t,Kn(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>h.start&&HC(u,h.start,h.endA,m,g)&&t.someProp("handleKeyDown",N=>N(t,Kn(8,"Backspace")))){Kt&&Se&&t.domObserver.suppressSelectionUpdates();return}Se&&h.endB==h.start&&(t.input.lastChromeDelete=Date.now()),Kt&&!x&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==h.endA&&(h.endB-=2,g=c.doc.resolveNoCache(h.endB-c.from),setTimeout(()=>{t.someProp("handleKeyDown",function(N){return N(t,Kn(13,"Enter"))})},20));let C=h.start,I=h.endA,v=N=>{let O=N||t.state.tr.replace(C,I,c.doc.slice(h.start-c.from,h.endB-c.from));if(c.sel){let L=Mm(t,O.doc,c.sel);L&&!(Se&&t.composing&&L.empty&&(h.start!=h.endB||t.input.lastChromeDelete<Date.now()-100)&&(L.head==C||L.head==O.mapping.map(I)-1)||We&&L.empty&&L.head==C)&&O.setSelection(L)}return o&&O.setMeta("composition",o),O.scrollIntoView()},w;if(x)if(m.pos==g.pos){We&&mn<=11&&m.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>Jt(t),20));let N=v(t.state.tr.delete(C,I)),O=u.resolve(h.start).marksAcross(u.resolve(h.endA));O&&N.ensureMarks(O),t.dispatch(N)}else if(h.endA==h.endB&&(w=$C(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,h.endA-y.start())))){let N=v(t.state.tr);w.type=="add"?N.addMark(C,I,w.mark):N.removeMark(C,I,w.mark),t.dispatch(N)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let N=m.parent.textBetween(m.parentOffset,g.parentOffset),O=()=>v(t.state.tr.insertText(N,C,I));t.someProp("handleTextInput",L=>L(t,C,I,N,O))||t.dispatch(O())}else t.dispatch(v());else t.dispatch(v())}function Mm(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:bc(t,e.resolve(n.anchor),e.resolve(n.head))}function $C(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,o=r,s,a,l;for(let u=0;u<r.length;u++)i=r[u].removeFromSet(i);for(let u=0;u<n.length;u++)o=n[u].removeFromSet(o);if(i.length==1&&o.length==0)a=i[0],s="add",l=u=>u.mark(a.addToSet(u.marks));else if(i.length==0&&o.length==1)a=o[0],s="remove",l=u=>u.mark(a.removeFromSet(u.marks));else return null;let c=[];for(let u=0;u<e.childCount;u++)c.push(l(e.child(u)));if(E.from(c).eq(t))return{mark:a,type:s}}function HC(t,e,n,r,i){if(n-e<=i.pos-r.pos||Ql(r,!0,!1)<i.pos)return!1;let o=t.resolve(e);if(!r.parent.isTextblock){let a=o.nodeAfter;return a!=null&&n==e+a.nodeSize}if(o.parentOffset<o.parent.content.size||!o.parent.isTextblock)return!1;let s=t.resolve(Ql(o,!0,!0));return!s.parent.isTextblock||s.pos>n||Ql(s,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(s.parent.content)}function Ql(t,e,n){let r=t.depth,i=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let o=t.node(r).maybeChild(t.indexAfter(r));for(;o&&!o.isLeaf;)o=o.firstChild,i++}return i}function VC(t,e,n,r,i){let o=t.findDiffStart(e,n),s=n+t.size,a=n+e.size;if(o==null)return null;let{a:l,b:c}=t.findDiffEnd(e,s,a);if(i=="end"){let u=Math.max(0,o-Math.min(l,c));r-=l+u-o}if(l<o&&s<a){let u=r<=o&&r>=l?o-r:0;o-=u,c=o+(c-l),l=o}else if(c<o){let u=r<=o&&r>=c?o-r:0;o-=u,l=o+(l-c),c=o}return{start:o,endA:l,endB:c}}var Ki=class{constructor(e,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 uc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Am),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=Im(this),Tm(this),this.nodeViews=vm(this),this.docView=am(this.state.doc,Em(this),Gl(this),this.dom,this),this.domObserver=new gc(this,(r,i,o,s)=>_C(this,r,i,o,s)),this.domObserver.start(),cC(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&fc(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Am),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let i=this.state,o=!1,s=!1;e.storedMarks&&this.composing&&(ng(this),s=!0),this.state=e;let a=i.plugins!=e.plugins||this._props.plugins!=n.plugins;if(a||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=vm(this);jC(p,this.nodeViews)&&(this.nodeViews=p,o=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&fc(this),this.editable=Im(this),Tm(this);let l=Gl(this),c=Em(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",f=o||!this.docView.matchesNode(e.doc,c,l);(f||!e.selection.eq(i.selection))&&(s=!0);let d=u=="preserve"&&s&&this.dom.style.overflowAnchor==null&&I0(this);if(s){this.domObserver.stop();let p=f&&(We||Se)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&WC(i.selection,e.selection);if(f){let m=Se?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=SC(this)),(o||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=am(e.doc,c,l,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}let h=this.input.mouseDown;p||!(h&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&J0(this)&&h.delaySelUpdate())?Jt(this,p):(Wm(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():d&&v0(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof H){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&nm(this,n.getBoundingClientRect(),e)}else nm(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let r=this.state.plugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let r=this.pluginViews[n];r.update&&r.update(this,e)}}updateDraggedNode(e,n){let r=e.node,i=-1;if(r.from<this.state.doc.content.size&&this.state.doc.nodeAt(r.from)==r.node)i=r.from;else{let o=r.from+(this.state.doc.content.size-n.doc.content.size);(o>0&&o<this.state.doc.content.size&&this.state.doc.nodeAt(o))==r.node&&(i=o)}this.dragging=new vs(e.slice,e.move,i<0?void 0:H.create(this.state.doc,i))}someProp(e,n){let r=this._props&&this._props[e],i;if(r!=null&&(i=n?n(r):r))return i;for(let s=0;s<this.directPlugins.length;s++){let a=this.directPlugins[s].props[e];if(a!=null&&(i=n?n(a):a))return i}let o=this.state.plugins;if(o)for(let s=0;s<o.length;s++){let a=o[s].props[e];if(a!=null&&(i=n?n(a):a))return i}}hasFocus(){if(We){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&A0(this.dom),Jt(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let n=this.dom.parentNode;n;n=n.parentNode)if(n.nodeType==9||n.nodeType==11&&n.host)return n.getSelection||(Object.getPrototypeOf(n).getSelection=()=>n.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return L0(this,e)}coordsAtPos(e,n=1){return Fm(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return _0(this,n||this.state,e)}pasteHTML(e,n){return ji(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return ji(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return xc(this,e)}destroy(){this.docView&&(uC(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Gl(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,y0())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return dC(this,e)}domSelectionRange(){let e=this.domSelection();return e?Le&&this.root.nodeType===11&&S0(this.dom.ownerDocument)==this.dom&&OC(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};Ki.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function Em(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[se.node(0,t.state.doc.content.size,e)]}function Tm(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:se.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Im(t){return!t.someProp("editable",e=>e(t.state)===!1)}function WC(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function vm(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function jC(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function Am(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}function Qt(t,e){return t.meta={package:"@milkdown/core",group:"System",...e},t}var ug={text:(t,e,n,r)=>{let i=t.value;return/^[^*_\\]*\s+$/.test(i)?i:n.safe(i,{...r,encode:[]})},strong:(t,e,n,r)=>{let i=t.marker||n.options.strong||"*",o=n.enter("strong"),s=n.createTracker(r),a=s.move(i+i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i+i),o(),a},emphasis:(t,e,n,r)=>{let i=t.marker||n.options.emphasis||"*",o=n.enter("emphasis"),s=n.createTracker(r),a=s.move(i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i),o(),a}},ie=K({},"editorView"),Xi=K({},"editorState"),Ec=K([],"initTimer"),lg=K({},"editor"),jr=K([],"inputRules"),yt=K([],"prosePlugins"),qr=K([],"remarkPlugins"),Vs=K([],"nodeView"),Ws=K([],"markView"),tr=K(Ii().use(yr).use(wr),"remark"),zr=K({handlers:ug,encode:[]},"remarkStringifyOptions"),Os=ot("ConfigReady");function qC(t){let e=n=>(n.record(Os),async()=>(await t(n),n.done(Os),()=>{n.clearTimer(Os)}));return Qt(e,{displayName:"Config"}),e}var Gt=ot("InitReady");function KC(t){let e=n=>(n.inject(lg,t).inject(yt,[]).inject(qr,[]).inject(jr,[]).inject(Vs,[]).inject(Ws,[]).inject(zr,{handlers:ug,encode:[]}).inject(tr,Ii().use(yr).use(wr)).inject(Ec,[Os]).record(Gt),async()=>{await n.waitTimers(Ec);let r=n.get(zr);return n.set(tr,Ii().use(yr).use(wr,r)),n.done(Gt),()=>{n.remove(lg).remove(yt).remove(qr).remove(jr).remove(Vs).remove(Ws).remove(zr).remove(tr).remove(Ec).clearTimer(Gt)}});return Qt(e,{displayName:"Init"}),e}var ze=ot("SchemaReady"),Ls=K([],"schemaTimer"),gt=K({},"schema"),_r=K([],"nodes"),$r=K([],"marks");function cg(t){return{...t,parseDOM:t.parseDOM?.map(e=>({priority:t.priority,...e}))}}var fg=t=>(t.inject(gt,{}).inject(_r,[]).inject($r,[]).inject(Ls,[Gt]).record(ze),async()=>{await t.waitTimers(Ls);let e=t.get(tr),n=t.get(qr).reduce((i,o)=>i.use(o.plugin,o.options),e);t.set(tr,n);let r=new ls({nodes:Object.fromEntries(t.get(_r).map(([i,o])=>[i,cg(o)])),marks:Object.fromEntries(t.get($r).map(([i,o])=>[i,cg(o)]))});return t.set(gt,r),t.done(ze),()=>{t.remove(gt).remove(_r).remove($r).remove(Ls).clearTimer(ze)}});Qt(fg,{displayName:"Schema"});var dg=class{constructor(){this.#t=new Ta,this.#e=null,this.setCtx=t=>{this.#e=t},this.chain=()=>{if(this.#e==null)throw Do();let t=this.#e,e=[],n=this.get.bind(this),r={run:()=>{let o=qn(...e),s=t.get(ie);return o(s.state,s.dispatch,s)},inline:o=>(e.push(o),r),pipe:i.bind(this)};function i(o,s){let a=n(o);return e.push(a(s)),r}return r}}#t;#e;get ctx(){return this.#e}create(t,e){let n=t.create(this.#t.sliceMap);return n.set(e),n}get(t){return this.#t.get(t).get()}remove(t){return this.#t.remove(t)}call(t,e){if(this.#e==null)throw Do();let n=this.get(t)(e),r=this.#e.get(ie);return n(r.state,r.dispatch,r)}inline(t){if(this.#e==null)throw Do();let e=this.#e.get(ie);return t(e.state,e.dispatch,e)}};function pg(t="cmdKey"){return K((()=>()=>!1),t)}var G=K(new dg,"commands"),Bs=K([ze],"commandsTimer"),Hr=ot("CommandsReady"),hg=t=>{let e=new dg;return e.setCtx(t),t.inject(G,e).inject(Bs,[ze]).record(Hr),async()=>(await t.waitTimers(Bs),t.done(Hr),()=>{t.remove(G).remove(Bs).clearTimer(Hr)})};Qt(hg,{displayName:"Commands"});function UC(t){return t.Backspace=qn(Fh,ms,Rh,Ll),t}var mg=class{constructor(){this.#t=null,this.#e=[],this.setCtx=t=>{this.#t=t},this.add=t=>(this.#e.push(t),()=>{this.#e=this.#e.filter(e=>e!==t)}),this.addObjectKeymap=t=>{let e=[];return Object.entries(t).forEach(([n,r])=>{if(typeof r=="function"){let i={key:n,onRun:()=>r};this.#e.push(i),e.push(()=>{this.#e=this.#e.filter(o=>o!==i)})}else this.#e.push(r),e.push(()=>{this.#e=this.#e.filter(i=>i!==r)})}),()=>{e.forEach(n=>n())}},this.addBaseKeymap=()=>{let t=UC(Ph);return this.addObjectKeymap(t)},this.build=()=>{let t={};return this.#e.forEach(e=>{t[e.key]=[...t[e.key]||[],e]}),Object.fromEntries(Object.entries(t).map(([e,n])=>{let r=n.sort((o,s)=>(s.priority??50)-(o.priority??50));return[e,(o,s,a)=>{let l=this.#t;if(l==null)throw mr();return qn(...r.map(c=>c.onRun(l)))(o,s,a)}]}))}}#t;#e;get ctx(){return this.#t}},ro=K(new mg,"keymap"),Tc=K([ze],"keymapTimer"),Vr=ot("KeymapReady"),JC=t=>{let e=new mg;return e.setCtx(t),t.inject(ro,e).inject(Tc,[ze]).record(Vr),async()=>(await t.waitTimers(Tc),t.done(Vr),()=>{t.remove(ro).remove(Tc).clearTimer(Vr)})},Ps=ot("ParserReady"),gg=(()=>{throw mr()}),Ge=K(gg,"parser"),Ic=K([],"parserTimer"),yg=t=>(t.inject(Ge,gg).inject(Ic,[ze]).record(Ps),async()=>{await t.waitTimers(Ic);let e=t.get(tr),n=t.get(gt);return t.set(Ge,Xh.create(n,e)),t.done(Ps),()=>{t.remove(Ge).remove(Ic).clearTimer(Ps)}});Qt(yg,{displayName:"Parser"});var Wr=ot("SerializerReady"),vc=K([],"serializerTimer"),kg=(()=>{throw mr()}),nr=K(kg,"serializer"),bg=t=>(t.inject(nr,kg).inject(vc,[ze]).record(Wr),async()=>{await t.waitTimers(vc);let e=t.get(tr),n=t.get(gt);return t.set(nr,Zh.create(n,e)),t.done(Wr),()=>{t.remove(nr).remove(vc).clearTimer(Wr)}});Qt(bg,{displayName:"Serializer"});var Yi=K("","defaultValue"),Zi=K(t=>t,"stateOptions"),Fs=K([],"editorStateTimer"),zs=ot("EditorStateReady");function GC(t,e,n){if(typeof t=="string")return e(t);if(t.type==="html")return ln.fromSchema(n).parse(t.dom);if(t.type==="json")return Ve.fromJSON(n,t.value);throw rd(t)}var QC=new te("MILKDOWN_STATE_TRACKER"),xg=t=>(t.inject(Yi,"").inject(Xi,{}).inject(Zi,e=>e).inject(Fs,[Ps,Wr,Hr,Vr]).record(zs),async()=>{await t.waitTimers(Fs);let e=t.get(gt),n=t.get(Ge),r=t.get(jr),i=t.get(Zi),o=t.get(yt),s=GC(t.get(Yi),n,e),a=t.get(ro),l=a.addBaseKeymap(),c=[...o,new Y({key:QC,state:{init:()=>{},apply:(d,p,h,m)=>{t.set(Xi,m)}}}),$h({rules:r}),Kh(a.build())];t.set(yt,c);let u=i({schema:e,doc:s,plugins:c}),f=Ar.create(u);return t.set(Xi,f),t.done(zs),()=>{l(),t.remove(Yi).remove(Xi).remove(Zi).remove(Fs).clearTimer(zs)}});Qt(xg,{displayName:"EditorState"});var Kr=K([],"pasteRule"),_s=K([ze],"pasteRuleTimer"),$s=ot("PasteRuleReady"),wg=t=>(t.inject(Kr,[]).inject(_s,[ze]).record($s),async()=>(await t.waitTimers(_s),t.done($s),()=>{t.remove(Kr).remove(_s).clearTimer($s)}));Qt(wg,{displayName:"PasteRule"});var eo=ot("EditorViewReady"),Hs=K([],"editorViewTimer"),to=K({},"editorViewOptions"),no=K(null,"root"),Ac=K(null,"rootDOM"),Nc=K({},"rootAttrs");function XC(t,e){let n=document.createElement("div");n.className="milkdown",t.appendChild(n),e.set(Ac,n);let r=e.get(Nc);return Object.entries(r).forEach(([i,o])=>n.setAttribute(i,o)),n}function YC(t){t.classList.add("editor"),t.setAttribute("role","textbox")}var ZC=new te("MILKDOWN_VIEW_CLEAR"),Sg=t=>(t.inject(no,document.body).inject(ie,{}).inject(to,{}).inject(Ac,null).inject(Nc,{}).inject(Hs,[zs,$s]).record(eo),async()=>{await t.wait(Gt);let e=t.get(no)||document.body,n=typeof e=="string"?document.querySelector(e):e;t.update(yt,s=>[new Y({key:ZC,view:a=>{let l=n?XC(n,t):void 0;return(()=>{if(l&&n){let u=a.dom;n.replaceChild(l,u),l.appendChild(u)}})(),{destroy:()=>{l?.parentNode&&l?.parentNode.replaceChild(a.dom,l),l?.remove()}}}}),...s]),await t.waitTimers(Hs);let r=t.get(Xi),i=t.get(to),o=new Ki(n,{state:r,nodeViews:Object.fromEntries(t.get(Vs)),markViews:Object.fromEntries(t.get(Ws)),transformPasted:(s,a,l)=>(t.get(Kr).sort((c,u)=>(u.priority??50)-(c.priority??50)).map(c=>c.run).forEach(c=>{s=c(s,a,l)}),s),...i});return YC(o.dom),t.set(ie,o),t.done(eo),()=>{o?.destroy(),t.remove(no).remove(ie).remove(to).remove(Ac).remove(Nc).remove(Hs).clearTimer(eo)}});Qt(Sg,{displayName:"EditorView"});var Cg=class Mg{constructor(){this.#t=!1,this.#e="Idle",this.#r=[],this.#n=()=>{},this.#s=new Ta,this.#o=new pd,this.#i=new Map,this.#a=new Map,this.#l=new fd(this.#s,this.#o),this.#d=()=>{let e=qC(async r=>{await Promise.all(this.#r.map(i=>Promise.resolve(i(r))))}),n=[fg,yg,bg,hg,JC,wg,xg,Sg,KC(this),e];this.#c(n,this.#a)},this.#c=(e,n)=>{e.forEach(r=>{let i=this.#l.produce(this.#t?r.meta:void 0),o=r(i);n.set(r,{ctx:i,handler:o,cleanup:void 0})})},this.#u=(e,n=!1)=>Promise.all([e].flat().map(async r=>{let i=this.#i.get(r)?.cleanup;return n?this.#i.delete(r):this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0}),typeof i=="function"?i():i})),this.#p=async()=>{await Promise.all([...this.#a.entries()].map(async([e,{cleanup:n}])=>typeof n=="function"?n():n)),this.#a.clear()},this.#f=e=>{this.#e=e,this.#n(e)},this.#h=e=>[...e.entries()].map(async([n,r])=>{let{ctx:i,handler:o}=r;if(!o)return;let s=await o();e.set(n,{ctx:i,handler:o,cleanup:s})}),this.enableInspector=(e=!0)=>(this.#t=e,this),this.onStatusChange=e=>(this.#n=e,this),this.config=e=>(this.#r.push(e),this),this.removeConfig=e=>(this.#r=this.#r.filter(n=>n!==e),this),this.use=e=>{let n=[e].flat();return n.flat().forEach(r=>{this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0})}),this.#e==="Created"&&this.#c(n,this.#i),this},this.remove=async e=>this.#e==="OnCreate"?(console.warn("[Milkdown]: You are trying to remove plugins when the editor is creating, this is not recommended, please check your code."),new Promise(n=>{setTimeout(()=>{n(this.remove(e))},50)})):(await this.#u([e].flat(),!0),this),this.create=async()=>this.#e==="OnCreate"?this:(this.#e==="Created"&&await this.destroy(),this.#f("OnCreate"),this.#d(),this.#c([...this.#i.keys()],this.#i),await Promise.all([this.#h(this.#a),this.#h(this.#i)].flat()),this.#f("Created"),this),this.destroy=async(e=!1)=>this.#e==="Destroyed"||this.#e==="OnDestroy"?this:this.#e==="OnCreate"?new Promise(n=>{setTimeout(()=>{n(this.destroy(e))},50)}):(e&&(this.#r=[]),this.#f("OnDestroy"),await this.#u([...this.#i.keys()],e),await this.#p(),this.#f("Destroyed"),this),this.action=e=>e(this.#l),this.inspect=()=>this.#t?[...this.#a.values(),...this.#i.values()].map(({ctx:e})=>e?.inspector?.read()).filter(e=>!!e):(console.warn("[Milkdown]: You are trying to collect inspection when inspector is disabled, please enable inspector by `editor.enableInspector()` first."),[])}static make(){return new Mg}#t;#e;#r;#n;#s;#o;#i;#a;#l;#d;#c;#u;#p;#f;#h;get ctx(){return this.#l}get status(){return this.#e}};var eM=t=>crypto.getRandomValues(new Uint8Array(t)),tM=(t,e,n)=>{let r=256-256%t.length;if(r===256){let o=t.length-1;return(s=e)=>{if(!s)return"";let a="";for(;;){let l=n(s),c=s;for(;c--;)if(a+=t[l[c]&o],a.length>=s)return a}}}let i=Math.ceil(1.6*256*e/r);return(o=e)=>{if(!o)return"";let s="";for(;;){let a=n(i),l=i;for(;l--;)if(a[l]<r&&(s+=t[a[l]%t.length],s.length>=o))return s}}},Eg=(t,e=21)=>tM(t,e|0,eM);var yz=Eg("abcedfghicklmn",10);function P(t,e){let n=pg(t),r=i=>async()=>{r.key=n,await i.wait(Hr);let o=e(i);return i.get(G).create(n,o),r.run=s=>i.get(G).call(t,s),()=>{i.get(G).remove(n)}};return r}function fe(t){let e=n=>async()=>{await n.wait(ze);let r=t(n);return n.update(jr,i=>[...i,r]),e.inputRule=r,()=>{n.update(jr,i=>i.filter(o=>o!==r))}};return e}function Tg(t){let e=n=>async()=>{await n.wait(ze);let r=t(n);return n.update(Kr,i=>[...i,r]),e.pasteRule=r,()=>{n.update(Kr,i=>i.filter(o=>o!==r))}};return e}function nM(t,e){let n=r=>async()=>{let i=e(r);return r.update($r,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update($r,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get(gt).marks[t];if(!i)throw ud(t);return i},n}function js(t,e){let n=r=>async()=>{let i=e(r);return r.update(_r,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update(_r,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get(gt).nodes[t];if(!i)throw cd(t);return i},n}function Ce(t){let e,n=r=>async()=>(await r.wait(ze),e=t(r),r.update(yt,i=>[...i,e]),()=>{r.update(yt,i=>i.filter(o=>o!==e))});return n.plugin=()=>e,n.key=()=>e.spec.key,n}function rM(t){let e=n=>async()=>{await n.wait(Vr);let r=n.get(ro),i=t(n),o=r.addObjectKeymap(i);return e.keymap=i,()=>{o()}};return e}function Qe(t,e){let n=K(t,e),r=i=>(i.inject(n),()=>()=>{i.remove(n)});return r.key=n,r}function ne(t,e){let n=Qe(e,t),r=js(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.node=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>ne(t,o(e)),i}function kt(t,e){let n=Qe(e,t),r=nM(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.mark=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>kt(t,o(e)),i}function _e(t,e){let n=Qe(Object.fromEntries(Object.entries(e).map(([o,{shortcuts:s,priority:a}])=>[o,{shortcuts:s,priority:a}])),`${t}Keymap`),r=rM(o=>{let s=o.get(n.key),a=Object.entries(e).flatMap(([l,{command:c}])=>{let u=s[l],f=[u.shortcuts].flat(),d=u.priority;return f.map(p=>[p,{key:p,onRun:c,priority:d}])});return Object.fromEntries(a)}),i=[n,r];return i.ctx=n,i.shortcuts=r,i.key=n.key,i.keymap=r.keymap,i}var ut=(t,e=()=>({}))=>Qe(e,`${t}Attr`),rr=(t,e=()=>({}))=>Qe(e,`${t}Attr`);function Xe(t,e,n){let r=Qe(n??{},t),i=s=>async()=>{await s.wait(Gt);let a={plugin:e(s),options:s.get(r.key)};return s.update(qr,l=>[...l,a]),()=>{s.update(qr,l=>l.filter(c=>c!==a))}},o=[r,i];return o.id=t,o.plugin=i,o.options=r,o}function Ig(t){return e=>{let n=e.get(ie),r=e.get(gt),i=e.get(nr);if(!t)return i(n.state.doc);let o=n.state.doc.slice(t.from,t.to,!0),s=r.topNodeType.createAndFill(null,o.content);return s?i(s):(console.error("No document found"),"")}}function vg(t,e=!1){return n=>{let r=n.get(ie),i=n.get(Ge)(t);if(!i)return;if(!e){let{state:l}=r;return r.dispatch(l.tr.replace(0,l.doc.content.size,new A(i.content,0,0)))}let o=n.get(gt),s=n.get(Zi)({schema:o,doc:i,plugins:n.get(yt)}),a=Ar.create(s);r.updateState(a)}}function Ag(t,e){return function(n,r){let{$from:i,$to:o,node:s}=n.selection;if(s&&s.isBlock||i.depth<2||!i.sameParent(o))return!1;let a=i.node(-1);if(a.type!=t)return!1;if(i.parent.content.size==0&&i.node(-1).childCount==i.indexAfter(-1)){if(i.depth==3||i.node(-3).type!=t||i.index(-2)!=i.node(-2).childCount-1)return!1;if(r){let f=E.empty,d=i.index(-1)?1:i.index(-2)?2:3;for(let y=i.depth-d;y>=i.depth-3;y--)f=E.from(i.node(y).copy(f));let p=i.indexAfter(-1)<i.node(-2).childCount?1:i.indexAfter(-2)<i.node(-3).childCount?2:3;f=f.append(E.from(t.createAndFill()));let h=i.before(i.depth-(d-1)),m=n.tr.replace(h,i.after(-p),new A(f,4-d,0)),g=-1;m.doc.nodesBetween(h,m.doc.content.size,(y,x)=>{if(g>-1)return!1;y.isTextblock&&y.content.size==0&&(g=x+1)}),g>-1&&m.setSelection(_.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let l=o.pos==i.end()?a.contentMatchAt(0).defaultType:null,c=n.tr.delete(i.pos,o.pos),u=l?[e?{type:t,attrs:e}:null,{type:l}]:void 0;return Vn(c.doc,i.pos,2,u)?(r&&r(c.split(i.pos,2,u).scrollIntoView()),!0):!1}}function Ng(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,s=>s.childCount>0&&s.firstChild.type==t);return o?n?r.node(o.depth-1).type==t?iM(e,n,t,o):oM(e,n,o):!0:!1}}function iM(t,e,n,r){let i=t.tr,o=r.end,s=r.$to.end(r.depth);o<s&&(i.step(new Ie(o-1,s,o,s,new A(E.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new Ni(i.doc.resolve(r.$from.pos),i.doc.resolve(s),r.depth));let a=Ir(r);if(a==null)return!1;i.lift(r,a);let l=i.doc.resolve(i.mapping.map(o,-1)-1);return Wn(i.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&i.join(l.pos),e(i.scrollIntoView()),!0}function oM(t,e,n){let r=t.tr,i=n.parent;for(let p=n.end,h=n.endIndex-1,m=n.startIndex;h>m;h--)p-=i.child(h).nodeSize,r.delete(p-1,p+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let a=n.startIndex==0,l=n.endIndex==i.childCount,c=o.node(-1),u=o.index(-1);if(!c.canReplace(u+(a?0:1),u+1,s.content.append(l?E.empty:E.from(i))))return!1;let f=o.pos,d=f+s.nodeSize;return r.step(new Ie(f-(a?1:0),d+(l?1:0),f+1,d-1,new A((a?E.empty:E.from(i.copy(E.empty))).append(l?E.empty:E.from(i.copy(E.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function Rg(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==t);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let a=o.parent,l=a.child(s-1);if(l.type!=t)return!1;if(n){let c=l.lastChild&&l.lastChild.type==a.type,u=E.from(c?t.create():null),f=new A(E.from(t.create(null,E.from(a.type.create(null,u)))),c?3:1,0),d=o.start,p=o.end;n(e.tr.step(new Ie(d-(c?3:1),p,d,p,f,1,!0)).scrollIntoView())}return!0}}function Rc(t){let e=new Map;if(!t||!t.type)throw new Error("mdast-util-definitions expected node");return pt(t,"definition",function(r){let i=Dg(r.identifier);i&&!e.get(i)&&e.set(i,r)}),n;function n(r){let i=Dg(r);return e.get(i)}}function Dg(t){return String(t||"").toUpperCase()}function qs(){return function(t){let e=Rc(t);pt(t,function(n,r,i){if(n.type==="definition"&&i!==void 0&&typeof r=="number")return i.children.splice(r,1),[Dn,r];if(n.type==="imageReference"||n.type==="linkReference"){let o=e(n.identifier);if(o&&i&&typeof r=="number")return i.children[r]=n.type==="imageReference"?{type:"image",url:o.url,title:o.title,alt:n.alt}:{type:"link",url:o.url,title:o.title,children:n.children},[Dn,r]}})}}function Og(t,e){if(!(e.childCount>=1&&e.lastChild?.type.name==="hardbreak")){t.next(e.content);return}let n=[];e.content.forEach((r,i,o)=>{o!==e.childCount-1&&n.push(r)}),t.next(E.fromArray(n))}function M(t,e){return Object.assign(t,{meta:{package:"@milkdown/preset-commonmark",...e}}),t}var Dc=rr("emphasis");M(Dc,{displayName:"Attr<emphasis>",group:"Emphasis"});var Jr=kt("emphasis",t=>({attrs:{marker:{default:t.get(zr).emphasis||"*",validate:"string"}},parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style",getAttrs:e=>e==="italic"}],toDOM:e=>["em",t.get(Dc.key)(e)],parseMarkdown:{match:e=>e.type==="emphasis",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="emphasis",runner:(e,n)=>{e.withMark(n,"emphasis",void 0,{marker:n.attrs.marker})}}}));M(Jr.mark,{displayName:"MarkSchema<emphasis>",group:"Emphasis"});M(Jr.ctx,{displayName:"MarkSchemaCtx<emphasis>",group:"Emphasis"});var Oc=P("ToggleEmphasis",t=>()=>Dr(Jr.type(t)));M(Oc,{displayName:"Command<toggleEmphasisCommand>",group:"Emphasis"});var Lg=fe(t=>Vt(/(?:^|[^*])\*([^*]+)\*$/,Jr.type(t),{getAttr:()=>({marker:"*"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("*")?{}:{fullMatch:e.slice(1),start:n+1}}));M(Lg,{displayName:"InputRule<emphasis>|Star",group:"Emphasis"});var Bg=fe(t=>Vt(/\b_(?![_\s])(.*?[^_\s])_\b/,Jr.type(t),{getAttr:()=>({marker:"_"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("_")?{}:{fullMatch:e.slice(1),start:n+1}}));M(Bg,{displayName:"InputRule<emphasis>|Underscore",group:"Emphasis"});var Lc=_e("emphasisKeymap",{ToggleEmphasis:{shortcuts:"Mod-i",command:t=>{let e=t.get(G);return()=>e.call(Oc.key)}}});M(Lc.ctx,{displayName:"KeymapCtx<emphasis>",group:"Emphasis"});M(Lc.shortcuts,{displayName:"Keymap<emphasis>",group:"Emphasis"});var Bc=rr("strong");M(Bc,{displayName:"Attr<strong>",group:"Strong"});var io=kt("strong",t=>({attrs:{marker:{default:t.get(zr).strong||"*",validate:"string"}},parseDOM:[{tag:"b",getAttrs:e=>e.style.fontWeight!="normal"&&null},{tag:"strong"},{style:"font-style",getAttrs:e=>e==="bold"},{style:"font-weight=400",clearMark:e=>e.type.name=="strong"},{style:"font-weight",getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}],toDOM:e=>["strong",t.get(Bc.key)(e)],parseMarkdown:{match:e=>e.type==="strong",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="strong",runner:(e,n)=>{e.withMark(n,"strong",void 0,{marker:n.attrs.marker})}}}));M(io.mark,{displayName:"MarkSchema<strong>",group:"Strong"});M(io.ctx,{displayName:"MarkSchemaCtx<strong>",group:"Strong"});var Pc=P("ToggleStrong",t=>()=>Dr(io.type(t)));M(Pc,{displayName:"Command<toggleStrongCommand>",group:"Strong"});var Pg=fe(t=>Vt(/(?<![\w:/])(?:\*\*|__)([^*_]+?)(?:\*\*|__)(?![\w/])$/,io.type(t),{getAttr:e=>({marker:e[0].startsWith("*")?"*":"_"})}));M(Pg,{displayName:"InputRule<strong>",group:"Strong"});var Fc=_e("strongKeymap",{ToggleBold:{shortcuts:["Mod-b"],command:t=>{let e=t.get(G);return()=>e.call(Pc.key)}}});M(Fc.ctx,{displayName:"KeymapCtx<strong>",group:"Strong"});M(Fc.shortcuts,{displayName:"Keymap<strong>",group:"Strong"});var zc=rr("inlineCode");M(zc,{displayName:"Attr<inlineCode>",group:"InlineCode"});var bn=kt("inlineCode",t=>({priority:100,code:!0,parseDOM:[{tag:"code"}],toDOM:e=>["code",t.get(zc.key)(e)],parseMarkdown:{match:e=>e.type==="inlineCode",runner:(e,n,r)=>{e.openMark(r),e.addText(n.value),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="inlineCode",runner:(e,n,r)=>(e.withMark(n,"inlineCode",r.text||""),!0)}}));M(bn.mark,{displayName:"MarkSchema<inlineCode>",group:"InlineCode"});M(bn.ctx,{displayName:"MarkSchemaCtx<inlineCode>",group:"InlineCode"});var _c=P("ToggleInlineCode",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(r.empty)return!1;let{from:o,to:s}=r;return e.doc.rangeHasMark(o,s,bn.type(t))?(n?.(i.removeMark(o,s,bn.type(t))),!0):(Object.keys(e.schema.marks).filter(a=>a!==bn.type.name).map(a=>e.schema.marks[a]).forEach(a=>{i.removeMark(o,s,a)}),n?.(i.addMark(o,s,bn.type(t).create())),!0)});M(_c,{displayName:"Command<toggleInlineCodeCommand>",group:"InlineCode"});var Fg=fe(t=>Vt(/(?:`)([^`]+)(?:`)$/,bn.type(t)));M(Fg,{displayName:"InputRule<inlineCodeInputRule>",group:"InlineCode"});var $c=_e("inlineCodeKeymap",{ToggleInlineCode:{shortcuts:"Mod-e",command:t=>{let e=t.get(G);return()=>e.call(_c.key)}}});M($c.ctx,{displayName:"KeymapCtx<inlineCode>",group:"InlineCode"});M($c.shortcuts,{displayName:"Keymap<inlineCode>",group:"InlineCode"});var sM=new Set(["http:","https:","mailto:","tel:","ftp:"]);function aM(t){return t<=32||t>=127&&t<=160||t>=8203&&t<=8205||t===8232||t===8233||t===65279}function lM(t){let e="";for(let n of t)aM(n.codePointAt(0)??0)||(e+=n);return e}function cM(t){if(typeof t!="string")return"";let e=t.trim();if(!e)return"";let n=lM(e),r=/^([a-z][a-z0-9+.-]*):/i.exec(n)?.[1];return!r||sM.has(`${r.toLowerCase()}:`)?e:""}var Hc=rr("link");M(Hc,{displayName:"Attr<link>",group:"Link"});var Ur=kt("link",t=>({attrs:{href:{validate:"string"},title:{default:null,validate:"string|null"}},parseDOM:[{tag:"a[href]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{href:e.getAttribute("href"),title:e.getAttribute("title")}}}],toDOM:e=>["a",{...t.get(Hc.key)(e),...e.attrs,href:cM(e.attrs.href)}],parseMarkdown:{match:e=>e.type==="link",runner:(e,n,r)=>{let i=n.url,o=n.title;e.openMark(r,{href:i,title:o}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="link",runner:(e,n)=>{e.withMark(n,"link",void 0,{title:n.attrs.title,url:n.attrs.href})}}}));M(Ur.mark,{displayName:"MarkSchema<link>",group:"Link"});var zg=P("ToggleLink",t=>(e={})=>Dr(Ur.type(t),e));M(zg,{displayName:"Command<toggleLinkCommand>",group:"Link"});var _g=P("UpdateLink",t=>(e={})=>(n,r)=>{if(!r)return!1;let i,o=-1,{selection:s}=n,{from:a,to:l}=s;if(n.doc.nodesBetween(a,a===l?l+1:l,(h,m)=>{if(Ur.type(t).isInSet(h.marks))return i=h,o=m,!1}),!i)return!1;let c=i.marks.find(({type:h})=>h===Ur.type(t));if(!c)return!1;let u=o,f=o+i.nodeSize,{tr:d}=n,p=Ur.type(t).create({...c.attrs,...e});return p?(r(d.removeMark(u,f,c).addMark(u,f,p).setSelection(new z(d.selection.$anchor)).scrollIntoView()),!0):!1});M(_g,{displayName:"Command<updateLinkCommand>",group:"Link"});var $g=js("doc",()=>({content:"block+",parseMarkdown:{match:({type:t})=>t==="root",runner:(t,e,n)=>{t.injectRoot(e,n)}},toMarkdown:{match:t=>t.type.name==="doc",runner:(t,e)=>{t.openNode("root"),t.next(e.content)}}}));M($g,{displayName:"NodeSchema<doc>",group:"Doc"});function uM(t){return On(t,e=>e.type==="html"&&["<br />","<br>","<br >","<br/>"].includes(e.value?.trim()),(e,n)=>{if(!n.length)return;let r=n[n.length-1];if(!r)return;let i=r.children.indexOf(e);i!==-1&&r.children.splice(i,1)},!0)}var Us=Xe("remark-preserve-empty-line",()=>()=>uM);M(Us.plugin,{displayName:"Remark<remarkPreserveEmptyLine>",group:"Remark"});M(Us.options,{displayName:"RemarkConfig<remarkPreserveEmptyLine>",group:"Remark"});var Vc=ut("paragraph");M(Vc,{displayName:"Attr<paragraph>",group:"Paragraph"});var bt=ne("paragraph",t=>({content:"inline*",group:"block",parseDOM:[{tag:"p"}],toDOM:e=>["p",t.get(Vc.key)(e),0],parseMarkdown:{match:e=>e.type==="paragraph",runner:(e,n,r)=>{e.openNode(r),n.children?e.next(n.children):e.addText(n.value||""),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="paragraph",runner:(e,n)=>{let r=t.get(ie).state?.doc.lastChild;e.openNode("paragraph"),(!n.content||n.content.size===0)&&n!==r&&fM(t)?e.addNode("html",void 0,"<br />"):Og(e,n),e.closeNode()}}}));function fM(t){let e=!1;try{t.get(Us.id),e=!0}catch{e=!1}return e}M(bt.node,{displayName:"NodeSchema<paragraph>",group:"Paragraph"});M(bt.ctx,{displayName:"NodeSchemaCtx<paragraph>",group:"Paragraph"});var Wc=P("TurnIntoText",t=>()=>Rr(bt.type(t)));M(Wc,{displayName:"Command<turnIntoTextCommand>",group:"Paragraph"});var jc=_e("paragraphKeymap",{TurnIntoText:{shortcuts:"Mod-Alt-0",command:t=>{let e=t.get(G);return()=>e.call(Wc.key)}}});M(jc.ctx,{displayName:"KeymapCtx<paragraph>",group:"Paragraph"});M(jc.shortcuts,{displayName:"Keymap<paragraph>",group:"Paragraph"});var dM=Array(6).fill(0).map((t,e)=>e+1);function pM(t){return t.textContent.toLowerCase().trim().replace(/\s+/g,"-")}var Js=Qe(pM,"headingIdGenerator");M(Js,{displayName:"Ctx<HeadingIdGenerator>",group:"Heading"});var qc=ut("heading");M(qc,{displayName:"Attr<heading>",group:"Heading"});var or=ne("heading",t=>{let e=t.get(Js.key);return{content:"inline*",group:"block",defining:!0,attrs:{id:{default:"",validate:"string"},level:{default:1,validate:"number"}},parseDOM:dM.map(n=>({tag:`h${n}`,getAttrs:r=>{if(!(r instanceof HTMLElement))throw it(r);return{level:n,id:r.id}}})),toDOM:n=>[`h${n.attrs.level}`,{...t.get(qc.key)(n),id:n.attrs.id||e(n)},0],parseMarkdown:{match:({type:n})=>n==="heading",runner:(n,r,i)=>{let o=r.depth;n.openNode(i,{level:o}),n.next(r.children),n.closeNode()}},toMarkdown:{match:n=>n.type.name==="heading",runner:(n,r)=>{n.openNode("heading",void 0,{depth:r.attrs.level}),Og(n,r),n.closeNode()}}}});M(or.node,{displayName:"NodeSchema<heading>",group:"Heading"});M(or.ctx,{displayName:"NodeSchemaCtx<heading>",group:"Heading"});var Hg=fe(t=>Fl(/^(?<hashes>#+)\s$/,or.type(t),e=>{let n=e.groups?.hashes?.length||0,{$from:r}=t.get(ie).state.selection,i=r.node();if(i.type.name==="heading"){let o=Number(i.attrs.level)+Number(n);return o>6&&(o=6),{level:o}}return{level:n}}));M(Hg,{displayName:"InputRule<wrapInHeadingInputRule>",group:"Heading"});var kn=P("WrapInHeading",t=>e=>(e??=1,e<1?Rr(bt.type(t)):Rr(or.type(t),{level:e})));M(kn,{displayName:"Command<wrapInHeadingCommand>",group:"Heading"});var Kc=P("DowngradeHeading",t=>()=>(e,n,r)=>{let{$from:i}=e.selection,o=i.node();if(o.type!==or.type(t)||!e.selection.empty||i.parentOffset!==0)return!1;let s=o.attrs.level-1;return s?(n?.(e.tr.setNodeMarkup(e.selection.$from.before(),void 0,{...o.attrs,level:s})),!0):Rr(bt.type(t))(e,n,r)});M(Kc,{displayName:"Command<downgradeHeadingCommand>",group:"Heading"});var Uc=_e("headingKeymap",{TurnIntoH1:{shortcuts:"Mod-Alt-1",command:t=>{let e=t.get(G);return()=>e.call(kn.key,1)}},TurnIntoH2:{shortcuts:"Mod-Alt-2",command:t=>{let e=t.get(G);return()=>e.call(kn.key,2)}},TurnIntoH3:{shortcuts:"Mod-Alt-3",command:t=>{let e=t.get(G);return()=>e.call(kn.key,3)}},TurnIntoH4:{shortcuts:"Mod-Alt-4",command:t=>{let e=t.get(G);return()=>e.call(kn.key,4)}},TurnIntoH5:{shortcuts:"Mod-Alt-5",command:t=>{let e=t.get(G);return()=>e.call(kn.key,5)}},TurnIntoH6:{shortcuts:"Mod-Alt-6",command:t=>{let e=t.get(G);return()=>e.call(kn.key,6)}},DowngradeHeading:{shortcuts:["Delete","Backspace"],command:t=>{let e=t.get(G);return()=>e.call(Kc.key)}}});M(Uc.ctx,{displayName:"KeymapCtx<heading>",group:"Heading"});M(Uc.shortcuts,{displayName:"Keymap<heading>",group:"Heading"});var Jc=ut("blockquote");M(Jc,{displayName:"Attr<blockquote>",group:"Blockquote"});var oo=ne("blockquote",t=>({content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM:e=>["blockquote",t.get(Jc.key)(e),0],parseMarkdown:{match:({type:e})=>e==="blockquote",runner:(e,n,r)=>{e.openNode(r).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="blockquote",runner:(e,n)=>{e.openNode("blockquote").next(n.content).closeNode()}}}));M(oo.node,{displayName:"NodeSchema<blockquote>",group:"Blockquote"});M(oo.ctx,{displayName:"NodeSchemaCtx<blockquote>",group:"Blockquote"});var Vg=fe(t=>ys(/^\s*>\s$/,oo.type(t)));M(Vg,{displayName:"InputRule<wrapInBlockquoteInputRule>",group:"Blockquote"});var Gc=P("WrapInBlockquote",t=>()=>gs(oo.type(t)));M(Gc,{displayName:"Command<wrapInBlockquoteCommand>",group:"Blockquote"});var Qc=_e("blockquoteKeymap",{WrapInBlockquote:{shortcuts:"Mod-Shift-b",command:t=>{let e=t.get(G);return()=>e.call(Gc.key)}}});M(Qc.ctx,{displayName:"KeymapCtx<blockquote>",group:"Blockquote"});M(Qc.shortcuts,{displayName:"Keymap<blockquote>",group:"Blockquote"});var Xc=ut("codeBlock",()=>({pre:{},code:{}}));M(Xc,{displayName:"Attr<codeBlock>",group:"CodeBlock"});var so=ne("code_block",t=>({content:"text*",group:"block",marks:"",defining:!0,code:!0,attrs:{language:{default:"",validate:"string"}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{language:e.dataset.language}}}],toDOM:e=>{let n=t.get(Xc.key)(e),r=e.attrs.language,i=r&&r.length>0?{"data-language":r}:void 0;return["pre",{...n.pre,...i},["code",n.code,0]]},parseMarkdown:{match:({type:e})=>e==="code",runner:(e,n,r)=>{let i=n.lang??"",o=n.value;e.openNode(r,{language:i}),o&&e.addText(o),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="code_block",runner:(e,n)=>{e.addNode("code",void 0,n.content.firstChild?.text||"",{lang:n.attrs.language})}}}));M(so.node,{displayName:"NodeSchema<codeBlock>",group:"CodeBlock"});M(so.ctx,{displayName:"NodeSchemaCtx<codeBlock>",group:"CodeBlock"});var Wg=fe(t=>Fl(/^```(?<language>[a-z]*)?[\s\n]$/,so.type(t),e=>({language:e.groups?.language??""})));M(Wg,{displayName:"InputRule<createCodeBlockInputRule>",group:"CodeBlock"});var Yc=P("CreateCodeBlock",t=>(e="")=>Rr(so.type(t),{language:e}));M(Yc,{displayName:"Command<createCodeBlockCommand>",group:"CodeBlock"});var hM=P("UpdateCodeBlockLanguage",()=>({pos:t,language:e}={pos:-1,language:""})=>(n,r)=>t>=0?(r?.(n.tr.setNodeAttribute(t,"language",e)),!0):!1);M(hM,{displayName:"Command<updateCodeBlockLanguageCommand>",group:"CodeBlock"});var Zc=_e("codeBlockKeymap",{CreateCodeBlock:{shortcuts:"Mod-Alt-c",command:t=>{let e=t.get(G);return()=>e.call(Yc.key)}}});M(Zc.ctx,{displayName:"KeymapCtx<codeBlock>",group:"CodeBlock"});M(Zc.shortcuts,{displayName:"Keymap<codeBlock>",group:"CodeBlock"});var eu=ut("image");M(eu,{displayName:"Attr<image>",group:"Image"});var Gr=ne("image",t=>({inline:!0,group:"inline",selectable:!0,draggable:!0,marks:"",atom:!0,defining:!0,isolating:!0,attrs:{src:{default:"",validate:"string"},alt:{default:"",validate:"string"},title:{default:"",validate:"string"}},parseDOM:[{tag:"img[src]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{src:e.getAttribute("src")||"",alt:e.getAttribute("alt")||"",title:e.getAttribute("title")||e.getAttribute("alt")||""}}}],toDOM:e=>["img",{...t.get(eu.key)(e),...e.attrs}],parseMarkdown:{match:({type:e})=>e==="image",runner:(e,n,r)=>{let i=n.url,o=n.alt,s=n.title;e.addNode(r,{src:i,alt:o,title:s})}},toMarkdown:{match:e=>e.type.name==="image",runner:(e,n)=>{e.addNode("image",void 0,void 0,{title:n.attrs.title,url:n.attrs.src,alt:n.attrs.alt})}}}));M(Gr.node,{displayName:"NodeSchema<image>",group:"Image"});M(Gr.ctx,{displayName:"NodeSchemaCtx<image>",group:"Image"});var jg=P("InsertImage",t=>(e={})=>(n,r)=>{if(!r)return!0;let{src:i="",alt:o="",title:s=""}=e,a=Gr.type(t).create({src:i,alt:o,title:s});return a&&r(n.tr.replaceSelectionWith(a).scrollIntoView()),!0});M(jg,{displayName:"Command<insertImageCommand>",group:"Image"});var qg=P("UpdateImage",t=>(e={})=>(n,r)=>{let i=Wh(n.selection,Gr.type(t));if(!i)return!1;let{node:o,pos:s}=i,a={...o.attrs},{src:l,alt:c,title:u}=e;return l!==void 0&&(a.src=l),c!==void 0&&(a.alt=c),u!==void 0&&(a.title=u),r?.(n.tr.setNodeMarkup(s,void 0,a).scrollIntoView()),!0});M(qg,{displayName:"Command<updateImageCommand>",group:"Image"});var mM=fe(t=>new be(/!\[(?<alt>.*?)]\((?<filename>.*?)\s*(?="|\))"?(?<title>[^"]+)?"?\)/,(e,n,r,i)=>{let[o,s,a="",l]=n;return o?e.tr.replaceWith(r,i,Gr.type(t).create({src:a,alt:s,title:l})):null}));M(mM,{displayName:"InputRule<insertImageInputRule>",group:"Image"});var Ks=ut("hardbreak",t=>({"data-type":"hardbreak","data-is-inline":t.attrs.isInline}));M(Ks,{displayName:"Attr<hardbreak>",group:"Hardbreak"});var ir=ne("hardbreak",t=>({inline:!0,group:"inline",attrs:{isInline:{default:!1,validate:"boolean"}},selectable:!1,parseDOM:[{tag:"br"},{tag:'span[data-type="hardbreak"]',getAttrs:()=>({isInline:!0})}],toDOM:e=>e.attrs.isInline?["span",t.get(Ks.key)(e)," "]:["br",t.get(Ks.key)(e)],parseMarkdown:{match:({type:e})=>e==="break",runner:(e,n,r)=>{e.addNode(r,{isInline:!!n.data?.isInline})}},leafText:()=>` +`))),0,0),t.someProp("transformPasted",d=>{a=d(a,t,!0)}),a;let f=t.someProp("clipboardTextParser",d=>d(e,i,r,t));if(f)a=f;else{let d=i.marks(),{schema:p}=t.state,h=cn.fromSchema(p);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=s.appendChild(document.createElement("p"));m&&g.appendChild(h.serializeNode(p.text(m,d)))})}}else t.someProp("transformPastedHTML",f=>{n=f(n,t)}),s=oC(n),Ji&&sC(s);let c=s&&s.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let f=+u[3];f>0;f--){let d=s.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;s=d}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||ln.fromSchema(t.state.schema)).parseSlice(s,{preserveWhitespace:!!(l||u),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!nC.test(d.parentNode.nodeName)?{ignore:!0}:null}})),u)a=aC(bm(a,+u[1],+u[2]),u[4]);else if(a=A.maxOpen(rC(a.content,i),!0),a.openStart||a.openEnd){let f=0,d=0;for(let p=a.content.firstChild;f<a.openStart&&!p.type.spec.isolating;f++,p=p.firstChild);for(let p=a.content.lastChild;d<a.openEnd&&!p.type.spec.isolating;d++,p=p.lastChild);a=bm(a,f,d)}return t.someProp("transformPasted",f=>{a=f(a,t,l)}),a}var nC=/^(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 rC(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),o,s=[];if(t.forEach(a=>{if(!s)return;let l=i.findWrapping(a.type),c;if(!l)return s=null;if(c=s.length&&o.length&&Jm(l,o,a,s[s.length-1],0))s[s.length-1]=c;else{s.length&&(s[s.length-1]=Gm(s[s.length-1],o.length));let u=Um(a,l);s.push(u),i=i.matchType(u.type),o=l}}),s)return E.from(s)}return t}function Um(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,E.from(t));return t}function Jm(t,e,n,r,i){if(i<t.length&&i<e.length&&t[i]==e[i]){let o=Jm(t,e,n,r.lastChild,i+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(i==t.length-1?n.type:t[i+1]))return r.copy(r.content.append(E.from(Um(n,t,i+1))))}}function Gm(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Gm(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(E.empty,!0);return t.copy(n.append(r))}function cc(t,e,n,r,i,o){let s=e<0?t.firstChild:t.lastChild,a=s.content;return t.childCount>1&&(o=0),i<r-1&&(a=cc(a,e,n,r,i+1,o)),i>=n&&(a=e<0?s.contentMatchAt(0).fillBefore(a,o<=i).append(a):a.append(s.contentMatchAt(s.childCount).fillBefore(E.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,s.copy(a))}function bm(t,e,n){return e<t.openStart&&(t=new A(cc(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new A(cc(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}var Qm={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};function Xm(){return document.implementation.createHTMLDocument("title")}var Jl=null;function iC(t){let e=window.trustedTypes;return e?(Jl||(Jl=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),Jl.createHTML(t)):t}function oC(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Xm(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(t),o;if((o=i&&Qm[i[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),r.innerHTML=iC(t),o)for(let s=0;s<o.length;s++)r=r.querySelector(o[s])||r;for(let s=0;s<n.styleSheets.length;s++){let a=n.styleSheets[s];for(let l=0;l<a.rules.length;l++){let c=a.rules[l];if(c instanceof CSSStyleRule){let u=r.querySelectorAll(c.selectorText);for(let f=0;f<u.length;f++)u[f].style.cssText+=c.style.cssText}}}return r}function sC(t){let e=t.querySelectorAll(Se?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];r.childNodes.length==1&&r.textContent=="\xA0"&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function aC(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return t}let{content:i,openStart:o,openEnd:s}=t;for(let a=r.length-2;a>=0;a-=2){let l=n.nodes[r[a]];if(!l||l.hasRequiredAttrs())break;i=E.from(l.create(r[a+1],i)),o++,s++}return new A(i,o,s)}var Pe={},Fe={},lC={touchstart:!0,touchmove:!0},uc=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function cC(t){for(let e in Pe){let n=Pe[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{fC(t,r)&&!wc(t,r)&&(t.editable||!(r.type in Fe))&&n(t,r)},lC[e]?{passive:!0}:void 0)}Le&&t.dom.addEventListener("input",()=>null),fc(t)}function Ut(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function uC(t){t.input.mouseDown&&t.input.mouseDown.done(),t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function fc(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>wc(t,r))})}function wc(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function fC(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function dC(t,e){!wc(t,e)&&Pe[e.type]&&(t.editable||!(e.type in Fe))&&Pe[e.type](t,e)}Fe.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!eg(t)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Kt&&Se&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Fr&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",i=>i(t,Kn(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||tC(t,n)?n.preventDefault():Ut(t,"key")};Fe.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Fe.keypress=(t,e)=>{let n=e;if(eg(t)||!n.charCode||n.ctrlKey&&!n.altKey||st&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof z)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),o=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",s=>s(t,r.$from.pos,r.$to.pos,i,o))&&t.dispatch(o()),n.preventDefault()}};function Gi(t){return{left:t.clientX,top:t.clientY}}function pC(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function Sc(t,e,n,r,i){if(r==-1)return!1;let o=t.state.doc.resolve(r);for(let s=o.depth+1;s>0;s--)if(t.someProp(e,a=>s>o.depth?a(t,n,o.nodeAfter,o.before(s),i,!0):a(t,n,o.node(s),o.before(s),i,!1)))return!0;return!1}function Qi(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);n=="pointer"&&r.setMeta("pointer",!0),t.dispatch(r)}function hC(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&H.isSelectable(r)?(Qi(t,new H(n),"pointer"),!0):!1}function mC(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof H&&(r=n.node);let o=t.state.doc.resolve(e);for(let s=o.depth+1;s>0;s--){let a=s>o.depth?o.nodeAfter:o.node(s);if(H.isSelectable(a)){r&&n.$from.depth>0&&s>=n.$from.depth&&o.before(n.$from.depth+1)==n.$from.pos?i=o.before(n.$from.depth):i=o.before(s);break}}return i!=null?(Qi(t,H.create(t.state.doc,i),"pointer"),!0):!1}function gC(t,e,n,r,i){return Sc(t,"handleClickOn",e,n,r)||t.someProp("handleClick",o=>o(t,e,r))||(i?mC(t,n):hC(t,n))}function yC(t,e,n,r){return Sc(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function kC(t,e,n,r){return Sc(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||bC(t,n,r)}function bC(t,e,n){if(n.button!=0)return!1;let r=Ym(t,e,!0),i=t.state.doc;return r?(Qi(t,r,"pointer"),r instanceof z&&i.eq(t.state.doc)&&(t.input.mouseDown=new pc(t,r)),!0):!1}function Ym(t,e,n){let r=t.state.doc;if(e==-1)return r.inlineContent?z.create(r,0,r.content.size):null;let i=r.resolve(e);for(let o=i.depth+1;o>0;o--){let s=o>i.depth?i.nodeAfter:i.node(o),a=i.before(o);if(s.inlineContent)return z.create(r,a+1,a+1+s.content.size);if(n&&H.isSelectable(s))return H.create(r,a)}return null}function Cc(t){return Is(t)}var Zm=st?"metaKey":"ctrlKey";Pe.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Cc(t),i=Date.now(),o="singleClick";i-t.input.lastClick.time<500&&pC(n,t.input.lastClick)&&!n[Zm]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?o="doubleClick":t.input.lastClick.type=="doubleClick"&&(o="tripleClick")),t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:o,button:n.button},t.input.mouseDown&&t.input.mouseDown.done();let s=t.posAtCoords(Gi(n));s&&(o=="singleClick"?t.input.mouseDown=new dc(t,s,n,!!r):(o=="doubleClick"?yC:kC)(t,s.pos,s.inside,n)?n.preventDefault():Ut(t,"pointer"))};var Ts=class{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.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}},dc=class extends Ts{constructor(e,n,r,i){super(e),this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Zm],this.allowDefault=r.shiftKey;let o,s;if(n.inside>-1)o=e.state.doc.nodeAt(n.inside),s=n.inside;else{let u=e.state.doc.resolve(n.pos);o=u.parent,s=u.depth?u.before():0}let a=i?null:r.target,l=a?e.docView.nearestDesc(a,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(o.type.spec.draggable&&o.type.spec.selectable!==!1||c instanceof H&&c.from<=s&&c.to>s)&&(this.mightDrag={node:o,pos:s,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&<&&!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()),Ut(e,"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||Jt(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Gi(e))),this.updateAllowDefault(e),this.allowDefault||!n?Ut(this.view,"pointer"):gC(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Le&&this.mightDrag&&!this.mightDrag.node.isAtom||Se&&!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)?(Qi(this.view,_.near(this.view.state.doc.resolve(n.pos)),"pointer"),e.preventDefault()):Ut(this.view,"pointer")}move(e){this.updateAllowDefault(e),Ut(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}},pc=class extends Ts{constructor(e,n){super(e),this.startSelection=n,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),Ut(this.view,"pointer");let n=this.view.posAtCoords(Gi(e)),r=n&&Ym(this.view,n.inside,!1);if(!r)return;let{doc:i}=this.view.state,o=this.startSelection,[s,a]=r.from<o.from?[o.to,r.from]:[o.from,r.to];Qi(this.view,z.create(i,s,a),"pointer")}};Pe.touchstart=t=>{t.input.lastTouch=Date.now(),Cc(t),Ut(t,"pointer")};Pe.touchmove=t=>{t.input.lastTouch=Date.now(),Ut(t,"pointer")};Pe.contextmenu=t=>Cc(t);function eg(t,e){return t.composing?!0:Le&&Math.abs(Date.now()-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}var xC=Kt?5e3:-1;Fe.compositionstart=Fe.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof z&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Se&&Dm&&wC(t)))t.markCursor=t.state.storedMarks||n.marks(),Is(t,!0),t.markCursor=null;else if(Is(t,!e.selection.empty),lt&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,o=r.focusOffset;i&&i.nodeType==1&&o!=0;){let s=o<0?i.lastChild:i.childNodes[o-1];if(!s)break;if(s.nodeType==3){let a=t.domSelection();a&&a.collapse(s,s.nodeValue.length);break}else i=s,o=-1}}t.input.composing=!0}tg(t,xC)};function wC(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Fe.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,tg(t,20))};function tg(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Is(t),e))}function ng(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function SC(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=b0(e.focusNode,e.focusOffset),r=x0(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!i||!i.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let s=n.pmViewDesc;if(!(!s||!s.isText(n.nodeValue)))return r}}return n||r}function Is(t,e=!1){if(!(Kt&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),ng(t),e||t.docView&&t.docView.dirty){let n=kc(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function CC(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}var Wi=We&&mn<15||Fr&&M0<604;Pe.copy=Fe.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let o=Wi?null:n.clipboardData,s=r.content(),{dom:a,text:l}=xc(t,s);o?(n.preventDefault(),o.clearData(),o.setData("text/html",a.innerHTML),o.setData("text/plain",l)):CC(t,a),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function MC(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function EC(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.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=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?ji(t,r.value,null,i,e):ji(t,r.textContent,r.innerHTML,i,e)},50)}function ji(t,e,n,r,i){let o=Km(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,i,o||A.empty)))return!0;if(!o)return!1;let s=MC(o),a=s?t.state.tr.replaceSelectionWith(s,r):t.state.tr.replaceSelection(o);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function rg(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Fe.paste=(t,e)=>{let n=e;if(t.composing&&!Kt)return;let r=Wi?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&ji(t,rg(r),r.getData("text/html"),i,n)?n.preventDefault():EC(t,n)};var vs=class{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}},TC=st?"altKey":"ctrlKey";function ig(t,e){let n;return t.someProp("dragCopies",r=>{n=n||r(e)}),n!=null?!n:!e[TC]}Pe.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,o=i.empty?null:t.posAtCoords(Gi(n)),s;if(!(o&&o.pos>=i.from&&o.pos<=(i instanceof H?i.to-1:i.to))){if(r&&r.mightDrag)s=H.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let f=t.docView.nearestDesc(n.target,!0);f&&f.node.type.spec.draggable&&f!=t.docView&&(s=H.create(t.state.doc,f.posBefore))}}let a=(s||t.state.selection).content(),{dom:l,text:c,slice:u}=xc(t,a);(!n.dataTransfer.files.length||!Se||Rm>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Wi?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Wi||n.dataTransfer.setData("text/plain",c),t.dragging=new vs(u,ig(t,n),s)};Pe.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Fe.dragover=Fe.dragenter=(t,e)=>e.preventDefault();Fe.drop=(t,e)=>{try{IC(t,e,t.dragging)}finally{t.dragging=null}};function IC(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Gi(e));if(!r)return;let i=t.state.doc.resolve(r.pos),o=n&&n.slice;o?t.someProp("transformPasted",p=>{o=p(o,t,!1)}):o=Km(t,rg(e.dataTransfer),Wi?null:e.dataTransfer.getData("text/html"),!1,i);let s=!!(n&&ig(t,e));if(t.someProp("handleDrop",p=>p(t,e,o||A.empty,s))){e.preventDefault();return}if(!o)return;e.preventDefault();let a=o?gh(t.state.doc,i.pos,o):i.pos;a==null&&(a=i.pos);let l=t.state.tr;if(s){let{node:p}=n;p?p.replace(l):l.deleteSelection()}let c=l.mapping.map(a),u=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,f=l.doc;if(u?l.replaceRangeWith(c,c,o.content.firstChild):l.replaceRange(c,c,o),l.doc.eq(f))return;let d=l.doc.resolve(c);if(u&&H.isSelectable(o.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(o.content.firstChild))l.setSelection(new H(d));else{let p=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((h,m,g,y)=>p=y),l.setSelection(bc(t,d,l.doc.resolve(p)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}Pe.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Jt(t)},20))};Pe.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};Pe.beforeinput=(t,e)=>{if(Se&&Kt&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",o=>o(t,Kn(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in Fe)Pe[t]=Fe[t];function qi(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}var As=class t{constructor(e,n){this.toDOM=e,this.spec=n||Xn,this.side=this.spec.side||0}map(e,n,r,i){let{pos:o,deleted:s}=e.mapResult(n.from+i,this.side<0?-1:1);return s?null:new se(o-r,o-r,this)}valid(){return!0}eq(e){return this==e||e instanceof t&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&qi(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},Qn=class t{constructor(e,n){this.attrs=e,this.spec=n||Xn}map(e,n,r,i){let o=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,s=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return o>=s?null:new se(o,s,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof t&&qi(this.attrs,e.attrs)&&qi(this.spec,e.spec)}static is(e){return e.type instanceof t}destroy(){}},hc=class t{constructor(e,n){this.attrs=e,this.spec=n||Xn}map(e,n,r,i){let o=e.mapResult(n.from+i,1);if(o.deleted)return null;let s=e.mapResult(n.to+i,-1);return s.deleted||s.pos<=o.pos?null:new se(o.pos-r,s.pos-r,this)}valid(e,n){let{index:r,offset:i}=e.content.findIndex(n.from),o;return i==n.from&&!(o=e.child(r)).isText&&i+o.nodeSize==n.to}eq(e){return this==e||e instanceof t&&qi(this.attrs,e.attrs)&&qi(this.spec,e.spec)}destroy(){}},se=class t{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new t(e,n,this.type)}eq(e,n=0){return this.type.eq(e.type)&&this.from+n==e.from&&this.to+n==e.to}map(e,n,r){return this.type.map(e,this,n,r)}static widget(e,n,r){return new t(e,e,new As(n,r))}static inline(e,n,r,i){return new t(e,n,new Qn(r,i))}static node(e,n,r,i){return new t(e,n,new hc(r,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof Qn}get widget(){return this.type instanceof As}},Br=[],Xn={},re=class t{constructor(e,n){this.local=e.length?e:Br,this.children=n.length?n:Br}static create(e,n){return n.length?Rs(n,e,0,Xn):Oe}find(e,n,r){let i=[];return this.findInner(e??0,n??1e9,i,0,r),i}findInner(e,n,r,i,o){for(let s=0;s<this.local.length;s++){let a=this.local[s];a.from<=n&&a.to>=e&&(!o||o(a.spec))&&r.push(a.copy(a.from+i,a.to+i))}for(let s=0;s<this.children.length;s+=3)if(this.children[s]<n&&this.children[s+1]>e){let a=this.children[s]+1;this.children[s+2].findInner(e-a,n-a,r,i+a,o)}}map(e,n,r){return this==Oe||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Xn)}mapInner(e,n,r,i,o){let s;for(let a=0;a<this.local.length;a++){let l=this.local[a].map(e,r,i);l&&l.type.valid(n,l)?(s||(s=[])).push(l):o.onRemove&&o.onRemove(this.local[a].spec)}return this.children.length?vC(this.children,s||[],e,n,r,i,o):s?new t(s.sort(Yn),Br):Oe}add(e,n){return n.length?this==Oe?t.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let i,o=0;e.forEach((a,l)=>{let c=l+r,u;if(u=sg(n,a,c)){for(i||(i=this.children.slice());o<i.length&&i[o]<l;)o+=3;i[o]==l?i[o+2]=i[o+2].addInner(a,u,c+1):i.splice(o,0,l,l+a.nodeSize,Rs(u,a,c+1,Xn)),o+=3}});let s=og(o?ag(n):n,-r);for(let a=0;a<s.length;a++)s[a].type.valid(e,s[a])||s.splice(a--,1);return new t(s.length?this.local.concat(s).sort(Yn):this.local,i||this.children)}remove(e){return e.length==0||this==Oe?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,i=this.local;for(let o=0;o<r.length;o+=3){let s,a=r[o]+n,l=r[o+1]+n;for(let u=0,f;u<e.length;u++)(f=e[u])&&f.from>a&&f.to<l&&(e[u]=null,(s||(s=[])).push(f));if(!s)continue;r==this.children&&(r=this.children.slice());let c=r[o+2].removeInner(s,a+1);c!=Oe?r[o+2]=c:(r.splice(o,3),o-=3)}if(i.length){for(let o=0,s;o<e.length;o++)if(s=e[o])for(let a=0;a<i.length;a++)i[a].eq(s,n)&&(i==this.local&&(i=this.local.slice()),i.splice(a--,1))}return r==this.children&&i==this.local?this:i.length||r.length?new t(i,r):Oe}forChild(e,n){if(this==Oe)return this;if(n.isLeaf)return t.empty;let r,i;for(let a=0;a<this.children.length;a+=3)if(this.children[a]>=e){this.children[a]==e&&(r=this.children[a+2]);break}let o=e+1,s=o+n.content.size;for(let a=0;a<this.local.length;a++){let l=this.local[a];if(l.from<s&&l.to>o&&l.type instanceof Qn){let c=Math.max(o,l.from)-o,u=Math.min(s,l.to)-o;c<u&&(i||(i=[])).push(l.copy(c,u))}}if(i){let a=new t(i.sort(Yn),Br);return r?new Ns([a,r]):a}return r||Oe}eq(e){if(this==e)return!0;if(!(e instanceof t)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let n=0;n<this.local.length;n++)if(!this.local[n].eq(e.local[n]))return!1;for(let n=0;n<this.children.length;n+=3)if(this.children[n]!=e.children[n]||this.children[n+1]!=e.children[n+1]||!this.children[n+2].eq(e.children[n+2]))return!1;return!0}locals(e){return Mc(this.localsInner(e))}localsInner(e){if(this==Oe)return Br;if(e.inlineContent||!this.local.some(Qn.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof Qn||n.push(this.local[r]);return n}forEachSet(e){e(this)}};re.empty=new re([],[]);re.removeOverlap=Mc;var Oe=re.empty,Ns=class t{constructor(e){this.members=e}map(e,n){let r=this.members.map(i=>i.map(e,n,Xn));return t.from(r)}forChild(e,n){if(n.isLeaf)return re.empty;let r=[];for(let i=0;i<this.members.length;i++){let o=this.members[i].forChild(e,n);o!=Oe&&(o instanceof t?r=r.concat(o.members):r.push(o))}return t.from(r)}eq(e){if(!(e instanceof t)||e.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(e.members[n]))return!1;return!0}locals(e){let n,r=!0;for(let i=0;i<this.members.length;i++){let o=this.members[i].localsInner(e);if(o.length)if(!n)n=o;else{r&&(n=n.slice(),r=!1);for(let s=0;s<o.length;s++)n.push(o[s])}}return n?Mc(r?n:n.sort(Yn)):Br}static from(e){switch(e.length){case 0:return Oe;case 1:return e[0];default:return new t(e.every(n=>n instanceof re)?e:e.reduce((n,r)=>n.concat(r instanceof re?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}};function vC(t,e,n,r,i,o,s){let a=t.slice();for(let c=0,u=o;c<n.maps.length;c++){let f=0;n.maps[c].forEach((d,p,h,m)=>{let g=m-h-(p-d);for(let y=0;y<a.length;y+=3){let x=a[y+1];if(x<0||d>x+u-f)continue;let C=a[y]+u-f;p>=C?a[y+1]=d<=C?-2:-1:d>=u&&g&&(a[y]+=g,a[y+1]+=g)}f+=g}),u=n.maps[c].map(u,-1)}let l=!1;for(let c=0;c<a.length;c+=3)if(a[c+1]<0){if(a[c+1]==-2){l=!0,a[c+1]=-1;continue}let u=n.map(t[c]+o),f=u-i;if(f<0||f>=r.content.size){l=!0;continue}let d=n.map(t[c+1]+o,-1),p=d-i,{index:h,offset:m}=r.content.findIndex(f),g=r.maybeChild(h);if(g&&m==f&&m+g.nodeSize==p){let y=a[c+2].mapInner(n,g,u+1,t[c]+o+1,s);y!=Oe?(a[c]=f,a[c+1]=p,a[c+2]=y):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=AC(a,t,e,n,i,o,s),u=Rs(c,r,0,s);e=u.local;for(let f=0;f<a.length;f+=3)a[f+1]<0&&(a.splice(f,3),f-=3);for(let f=0,d=0;f<u.children.length;f+=3){let p=u.children[f];for(;d<a.length&&a[d]<p;)d+=3;a.splice(d,0,u.children[f],u.children[f+1],u.children[f+2])}}return new re(e.sort(Yn),a)}function og(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let i=t[r];n.push(new se(i.from+e,i.to+e,i.type))}return n}function AC(t,e,n,r,i,o,s){function a(l,c){for(let u=0;u<l.local.length;u++){let f=l.local[u].map(r,i,c);f?n.push(f):s.onRemove&&s.onRemove(l.local[u].spec)}for(let u=0;u<l.children.length;u+=3)a(l.children[u+2],l.children[u]+c+1)}for(let l=0;l<t.length;l+=3)t[l+1]==-1&&a(t[l+2],e[l]+o+1);return n}function sg(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,i=null;for(let o=0,s;o<t.length;o++)(s=t[o])&&s.from>n&&s.to<r&&((i||(i=[])).push(s),t[o]=null);return i}function ag(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Rs(t,e,n,r){let i=[],o=!1;e.forEach((a,l)=>{let c=sg(t,a,l+n);if(c){o=!0;let u=Rs(c,a,n+l+1,r);u!=Oe&&i.push(l,l+a.nodeSize,u)}});let s=og(o?ag(t):t,-n).sort(Yn);for(let a=0;a<s.length;a++)s[a].type.valid(e,s[a])||(r.onRemove&&r.onRemove(s[a].spec),s.splice(a--,1));return s.length||i.length?new re(s,i):Oe}function Yn(t,e){return t.from-e.from||t.to-e.to}function Mc(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let i=n+1;i<e.length;i++){let o=e[i];if(o.from==r.from){o.to!=r.to&&(e==t&&(e=t.slice()),e[i]=o.copy(o.from,r.to),xm(e,i+1,o.copy(r.to,o.to)));continue}else{o.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,o.from),xm(e,i,r.copy(o.from,r.to)));break}}}return e}function xm(t,e,n){for(;e<t.length&&Yn(n,t[e])>0;)e++;t.splice(e,0,n)}function Gl(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Oe&&e.push(r)}),t.cursorWrapper&&e.push(re.create(t.state.doc,[t.cursorWrapper.deco])),Ns.from(e)}var NC={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},RC=We&&mn<=11,mc=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},gc=class{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new mc,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;i<r.length;i++)this.queue.push(r[i]);We&&mn<=11&&r.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():Le&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),RC&&(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,NC)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let n=0;n<e.length;n++)this.queue.push(e[n]);window.setTimeout(()=>this.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(pm(this.view)){if(this.suppressingSelectionUpdates)return Jt(this.view);if(We&&mn<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Zn(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let o=e.focusNode;o;o=Pr(o))n.add(o);for(let o=e.anchorNode;o;o=Pr(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 e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&pm(e)&&!this.ignoreSelectionChange(r),o=-1,s=-1,a=!1,l=[];if(e.editable)for(let u=0;u<n.length;u++){let f=this.registerMutation(n[u],l);f&&(o=o<0?f.from:Math.min(f.from,o),s=s<0?f.to:Math.max(f.to,s),f.typeOver&&(a=!0))}if(l.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||Se&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&n.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of l)if(u.nodeName=="BR"&&u.parentNode){let f=u.nextSibling;for(;f&&f.nodeType==1;){if(f.contentEditable=="false"){u.parentNode.removeChild(u);break}f=f.firstChild}}}else if(lt&&l.length){let u=l.filter(f=>f.nodeName=="BR");if(u.length==2){let[f,d]=u;f.parentNode&&f.parentNode.parentNode==d.parentNode?d.remove():f.remove()}else{let{focusNode:f}=this.currentSelection;for(let d of u){let p=d.parentNode;p&&p.nodeName=="LI"&&(!f||LC(e,f)!=p)&&d.remove()}}}let c=null;o<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&Ds(r)&&(c=kc(e))&&c.eq(_.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Jt(e),this.currentSelection.set(r),e.scrollToSelection()):(o>-1||i)&&(o>-1&&(e.docView.markDirty(o,s),DC(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,BC(e,l)),this.handleDOMChange(o,s,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Jt(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let f=e.addedNodes[u];n.push(f),f.nodeType==3&&(this.lastChangedTextNode=f)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let i=e.previousSibling,o=e.nextSibling;if(We&&mn<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:f,nextSibling:d}=e.addedNodes[u];(!f||Array.prototype.indexOf.call(e.addedNodes,f)<0)&&(i=f),(!d||Array.prototype.indexOf.call(e.addedNodes,d)<0)&&(o=d)}let s=i&&i.parentNode==e.target?ve(i)+1:0,a=r.localPosFromDOM(e.target,s,-1),l=o&&o.parentNode==e.target?ve(o):e.target.childNodes.length,c=r.localPosFromDOM(e.target,l,1);return{from:a,to:c}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}},wm=new WeakMap,Sm=!1;function DC(t){if(!wm.has(t)&&(wm.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=lt,Sm)return;console.warn("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."),Sm=!0}}function Cm(t,e){let n=e.startContainer,r=e.startOffset,i=e.endContainer,o=e.endOffset,s=t.domAtPos(t.state.selection.anchor);return Zn(s.node,s.offset,i,o)&&([n,r,i,o]=[i,o,n,r]),{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:o}}function OC(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return Cm(t,i)}let n;function r(i){i.preventDefault(),i.stopImmediatePropagation(),n=i.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?Cm(t,n):null}function LC(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function BC(t,e){var n;let{focusNode:r,focusOffset:i}=t.domSelectionRange();for(let o of e)if(((n=o.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let s=o.nextSibling;for(;s&&s.nodeName!="TD"&&s.nodeName!="TH";)s=s.nextSibling;if(s){let a=s;for(;;){let l=a.firstChild;if(!l||l.nodeType!=1||l.contentEditable=="false"||/^(BR|IMG)$/.test(l.nodeName))break;a=l}a.insertBefore(o,a.firstChild),r==o&&t.domSelection().collapse(o,i)}else o.parentNode.removeChild(o)}}function PC(t,e,n){let{node:r,fromOffset:i,toOffset:o,from:s,to:a}=t.docView.parseRange(e,n),l=t.domSelectionRange(),c,u=l.anchorNode;if(u&&t.dom.contains(u.nodeType==1?u:u.parentNode)&&(c=[{node:u,offset:l.anchorOffset}],Ds(l)||c.push({node:l.focusNode,offset:l.focusOffset})),Se&&t.input.lastKeyCode===8)for(let g=o;g>i;g--){let y=r.childNodes[g-1],x=y.pmViewDesc;if(y.nodeName=="BR"&&!x){o=g;break}if(!x||x.size)break}let f=t.state.doc,d=t.someProp("domParser")||ln.fromSchema(t.state.schema),p=f.resolve(s),h=null,m=d.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:i,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:FC,context:p});if(c&&c[0].pos!=null){let g=c[0].pos,y=c[1]&&c[1].pos;y==null&&(y=g),h={anchor:g+s,head:y+s}}return{doc:m,sel:h,from:s,to:a}}function FC(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Le&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||Le&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}var zC=/^(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 _C(t,e,n,r,i){let o=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let N=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,O=kc(t,N);if(O&&!t.state.selection.eq(O)){if(Se&&Kt&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",S=>S(t,Kn(13,"Enter"))))return;let L=t.state.tr.setSelection(O);N=="pointer"?L.setMeta("pointer",!0):N=="key"&&L.scrollIntoView(),o&&L.setMeta("composition",o),t.dispatch(L)}return}let s=t.state.doc.resolve(e),a=s.sharedDepth(n);e=s.before(a+1),n=t.state.doc.resolve(n).after(a+1);let l=t.state.selection,c=PC(t,e,n),u=t.state.doc,f=u.slice(c.from,c.to),d,p;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(d=t.state.selection.to,p="end"):(d=t.state.selection.from,p="start"),t.input.lastKeyCode=null;let h=VC(f.content,c.doc.content,c.from,d,p);if(h&&t.input.domChangeCount++,(Fr&&t.input.lastIOSEnter>Date.now()-225||Kt)&&i.some(N=>N.nodeType==1&&!zC.test(N.nodeName))&&(!h||h.endA>=h.endB)&&t.someProp("handleKeyDown",N=>N(t,Kn(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!h)if(r&&l instanceof z&&!l.empty&&l.$head.sameParent(l.$anchor)&&!t.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))h={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let N=Mm(t,t.state.doc,c.sel);if(N&&!N.eq(t.state.selection)){let O=t.state.tr.setSelection(N);o&&O.setMeta("composition",o),t.dispatch(O)}}return}t.state.selection.from<t.state.selection.to&&h.start==h.endB&&t.state.selection instanceof z&&(h.start>t.state.selection.from&&h.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?h.start=t.state.selection.from:h.endA<t.state.selection.to&&h.endA>=t.state.selection.to-2&&t.state.selection.to<=c.to&&(h.endB+=t.state.selection.to-h.endA,h.endA=t.state.selection.to)),We&&mn<=11&&h.endB==h.start+1&&h.endA==h.start&&h.start>c.from&&c.doc.textBetween(h.start-c.from-1,h.start-c.from+1)==" \xA0"&&(h.start--,h.endA--,h.endB--);let m=c.doc.resolveNoCache(h.start-c.from),g=c.doc.resolveNoCache(h.endB-c.from),y=u.resolve(h.start),x=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=h.endA;if((Fr&&t.input.lastIOSEnter>Date.now()-225&&(!x||i.some(N=>N.nodeName=="DIV"||N.nodeName=="P"))||!x&&m.pos<c.doc.content.size&&(!m.sameParent(g)||!m.parent.inlineContent)&&m.pos<g.pos&&!/\S/.test(c.doc.textBetween(m.pos,g.pos,"","")))&&t.someProp("handleKeyDown",N=>N(t,Kn(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>h.start&&HC(u,h.start,h.endA,m,g)&&t.someProp("handleKeyDown",N=>N(t,Kn(8,"Backspace")))){Kt&&Se&&t.domObserver.suppressSelectionUpdates();return}Se&&h.endB==h.start&&(t.input.lastChromeDelete=Date.now()),Kt&&!x&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==h.endA&&(h.endB-=2,g=c.doc.resolveNoCache(h.endB-c.from),setTimeout(()=>{t.someProp("handleKeyDown",function(N){return N(t,Kn(13,"Enter"))})},20));let C=h.start,I=h.endA,v=N=>{let O=N||t.state.tr.replace(C,I,c.doc.slice(h.start-c.from,h.endB-c.from));if(c.sel){let L=Mm(t,O.doc,c.sel);L&&!(Se&&t.composing&&L.empty&&(h.start!=h.endB||t.input.lastChromeDelete<Date.now()-100)&&(L.head==C||L.head==O.mapping.map(I)-1)||We&&L.empty&&L.head==C)&&O.setSelection(L)}return o&&O.setMeta("composition",o),O.scrollIntoView()},w;if(x)if(m.pos==g.pos){We&&mn<=11&&m.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>Jt(t),20));let N=v(t.state.tr.delete(C,I)),O=u.resolve(h.start).marksAcross(u.resolve(h.endA));O&&N.ensureMarks(O),t.dispatch(N)}else if(h.endA==h.endB&&(w=$C(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,h.endA-y.start())))){let N=v(t.state.tr);w.type=="add"?N.addMark(C,I,w.mark):N.removeMark(C,I,w.mark),t.dispatch(N)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let N=m.parent.textBetween(m.parentOffset,g.parentOffset),O=()=>v(t.state.tr.insertText(N,C,I));t.someProp("handleTextInput",L=>L(t,C,I,N,O))||t.dispatch(O())}else t.dispatch(v());else t.dispatch(v())}function Mm(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:bc(t,e.resolve(n.anchor),e.resolve(n.head))}function $C(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,o=r,s,a,l;for(let u=0;u<r.length;u++)i=r[u].removeFromSet(i);for(let u=0;u<n.length;u++)o=n[u].removeFromSet(o);if(i.length==1&&o.length==0)a=i[0],s="add",l=u=>u.mark(a.addToSet(u.marks));else if(i.length==0&&o.length==1)a=o[0],s="remove",l=u=>u.mark(a.removeFromSet(u.marks));else return null;let c=[];for(let u=0;u<e.childCount;u++)c.push(l(e.child(u)));if(E.from(c).eq(t))return{mark:a,type:s}}function HC(t,e,n,r,i){if(n-e<=i.pos-r.pos||Ql(r,!0,!1)<i.pos)return!1;let o=t.resolve(e);if(!r.parent.isTextblock){let a=o.nodeAfter;return a!=null&&n==e+a.nodeSize}if(o.parentOffset<o.parent.content.size||!o.parent.isTextblock)return!1;let s=t.resolve(Ql(o,!0,!0));return!s.parent.isTextblock||s.pos>n||Ql(s,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(s.parent.content)}function Ql(t,e,n){let r=t.depth,i=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let o=t.node(r).maybeChild(t.indexAfter(r));for(;o&&!o.isLeaf;)o=o.firstChild,i++}return i}function VC(t,e,n,r,i){let o=t.findDiffStart(e,n),s=n+t.size,a=n+e.size;if(o==null)return null;let{a:l,b:c}=t.findDiffEnd(e,s,a);if(i=="end"){let u=Math.max(0,o-Math.min(l,c));r-=l+u-o}if(l<o&&s<a){let u=r<=o&&r>=l?o-r:0;o-=u,c=o+(c-l),l=o}else if(c<o){let u=r<=o&&r>=c?o-r:0;o-=u,l=o+(l-c),c=o}return{start:o,endA:l,endB:c}}var Ki=class{constructor(e,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 uc,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Am),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=Im(this),Tm(this),this.nodeViews=vm(this),this.docView=am(this.state.doc,Em(this),Gl(this),this.dom,this),this.domObserver=new gc(this,(r,i,o,s)=>_C(this,r,i,o,s)),this.domObserver.start(),cC(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&fc(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Am),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let i=this.state,o=!1,s=!1;e.storedMarks&&this.composing&&(ng(this),s=!0),this.state=e;let a=i.plugins!=e.plugins||this._props.plugins!=n.plugins;if(a||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=vm(this);jC(p,this.nodeViews)&&(this.nodeViews=p,o=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&fc(this),this.editable=Im(this),Tm(this);let l=Gl(this),c=Em(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",f=o||!this.docView.matchesNode(e.doc,c,l);(f||!e.selection.eq(i.selection))&&(s=!0);let d=u=="preserve"&&s&&this.dom.style.overflowAnchor==null&&I0(this);if(s){this.domObserver.stop();let p=f&&(We||Se)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&WC(i.selection,e.selection);if(f){let m=Se?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=SC(this)),(o||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=am(e.doc,c,l,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}let h=this.input.mouseDown;p||!(h&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&J0(this)&&h.delaySelUpdate())?Jt(this,p):(Wm(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():d&&v0(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof H){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&nm(this,n.getBoundingClientRect(),e)}else nm(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let r=this.state.plugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let r=this.pluginViews[n];r.update&&r.update(this,e)}}updateDraggedNode(e,n){let r=e.node,i=-1;if(r.from<this.state.doc.content.size&&this.state.doc.nodeAt(r.from)==r.node)i=r.from;else{let o=r.from+(this.state.doc.content.size-n.doc.content.size);(o>0&&o<this.state.doc.content.size&&this.state.doc.nodeAt(o))==r.node&&(i=o)}this.dragging=new vs(e.slice,e.move,i<0?void 0:H.create(this.state.doc,i))}someProp(e,n){let r=this._props&&this._props[e],i;if(r!=null&&(i=n?n(r):r))return i;for(let s=0;s<this.directPlugins.length;s++){let a=this.directPlugins[s].props[e];if(a!=null&&(i=n?n(a):a))return i}let o=this.state.plugins;if(o)for(let s=0;s<o.length;s++){let a=o[s].props[e];if(a!=null&&(i=n?n(a):a))return i}}hasFocus(){if(We){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&A0(this.dom),Jt(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let n=this.dom.parentNode;n;n=n.parentNode)if(n.nodeType==9||n.nodeType==11&&n.host)return n.getSelection||(Object.getPrototypeOf(n).getSelection=()=>n.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return L0(this,e)}coordsAtPos(e,n=1){return Fm(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return _0(this,n||this.state,e)}pasteHTML(e,n){return ji(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return ji(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return xc(this,e)}destroy(){this.docView&&(uC(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Gl(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,y0())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return dC(this,e)}domSelectionRange(){let e=this.domSelection();return e?Le&&this.root.nodeType===11&&S0(this.dom.ownerDocument)==this.dom&&OC(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};Ki.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function Em(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[se.node(0,t.state.doc.content.size,e)]}function Tm(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:se.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Im(t){return!t.someProp("editable",e=>e(t.state)===!1)}function WC(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function vm(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function jC(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function Am(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}function Qt(t,e){return t.meta={package:"@milkdown/core",group:"System",...e},t}var ug={text:(t,e,n,r)=>{let i=t.value;return/^[^*_\\]*\s+$/.test(i)?i:n.safe(i,{...r,encode:[]})},strong:(t,e,n,r)=>{let i=t.marker||n.options.strong||"*",o=n.enter("strong"),s=n.createTracker(r),a=s.move(i+i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i+i),o(),a},emphasis:(t,e,n,r)=>{let i=t.marker||n.options.emphasis||"*",o=n.enter("emphasis"),s=n.createTracker(r),a=s.move(i);return a+=s.move(n.containerPhrasing(t,{before:a,after:i,...s.current()})),a+=s.move(i),o(),a}},ie=K({},"editorView"),Xi=K({},"editorState"),Ec=K([],"initTimer"),lg=K({},"editor"),jr=K([],"inputRules"),yt=K([],"prosePlugins"),qr=K([],"remarkPlugins"),Vs=K([],"nodeView"),Ws=K([],"markView"),tr=K(Ii().use(yr).use(wr),"remark"),zr=K({handlers:ug,encode:[]},"remarkStringifyOptions"),Os=ot("ConfigReady");function qC(t){let e=n=>(n.record(Os),async()=>(await t(n),n.done(Os),()=>{n.clearTimer(Os)}));return Qt(e,{displayName:"Config"}),e}var Gt=ot("InitReady");function KC(t){let e=n=>(n.inject(lg,t).inject(yt,[]).inject(qr,[]).inject(jr,[]).inject(Vs,[]).inject(Ws,[]).inject(zr,{handlers:ug,encode:[]}).inject(tr,Ii().use(yr).use(wr)).inject(Ec,[Os]).record(Gt),async()=>{await n.waitTimers(Ec);let r=n.get(zr);return n.set(tr,Ii().use(yr).use(wr,r)),n.done(Gt),()=>{n.remove(lg).remove(yt).remove(qr).remove(jr).remove(Vs).remove(Ws).remove(zr).remove(tr).remove(Ec).clearTimer(Gt)}});return Qt(e,{displayName:"Init"}),e}var ze=ot("SchemaReady"),Ls=K([],"schemaTimer"),gt=K({},"schema"),_r=K([],"nodes"),$r=K([],"marks");function cg(t){return{...t,parseDOM:t.parseDOM?.map(e=>({priority:t.priority,...e}))}}var fg=t=>(t.inject(gt,{}).inject(_r,[]).inject($r,[]).inject(Ls,[Gt]).record(ze),async()=>{await t.waitTimers(Ls);let e=t.get(tr),n=t.get(qr).reduce((i,o)=>i.use(o.plugin,o.options),e);t.set(tr,n);let r=new ls({nodes:Object.fromEntries(t.get(_r).map(([i,o])=>[i,cg(o)])),marks:Object.fromEntries(t.get($r).map(([i,o])=>[i,cg(o)]))});return t.set(gt,r),t.done(ze),()=>{t.remove(gt).remove(_r).remove($r).remove(Ls).clearTimer(ze)}});Qt(fg,{displayName:"Schema"});var dg=class{constructor(){this.#t=new Ta,this.#e=null,this.setCtx=t=>{this.#e=t},this.chain=()=>{if(this.#e==null)throw Do();let t=this.#e,e=[],n=this.get.bind(this),r={run:()=>{let o=qn(...e),s=t.get(ie);return o(s.state,s.dispatch,s)},inline:o=>(e.push(o),r),pipe:i.bind(this)};function i(o,s){let a=n(o);return e.push(a(s)),r}return r}}#t;#e;get ctx(){return this.#e}create(t,e){let n=t.create(this.#t.sliceMap);return n.set(e),n}get(t){return this.#t.get(t).get()}remove(t){return this.#t.remove(t)}call(t,e){if(this.#e==null)throw Do();let n=this.get(t)(e),r=this.#e.get(ie);return n(r.state,r.dispatch,r)}inline(t){if(this.#e==null)throw Do();let e=this.#e.get(ie);return t(e.state,e.dispatch,e)}};function pg(t="cmdKey"){return K((()=>()=>!1),t)}var G=K(new dg,"commands"),Bs=K([ze],"commandsTimer"),Hr=ot("CommandsReady"),hg=t=>{let e=new dg;return e.setCtx(t),t.inject(G,e).inject(Bs,[ze]).record(Hr),async()=>(await t.waitTimers(Bs),t.done(Hr),()=>{t.remove(G).remove(Bs).clearTimer(Hr)})};Qt(hg,{displayName:"Commands"});function UC(t){return t.Backspace=qn(Fh,ms,Rh,Ll),t}var mg=class{constructor(){this.#t=null,this.#e=[],this.setCtx=t=>{this.#t=t},this.add=t=>(this.#e.push(t),()=>{this.#e=this.#e.filter(e=>e!==t)}),this.addObjectKeymap=t=>{let e=[];return Object.entries(t).forEach(([n,r])=>{if(typeof r=="function"){let i={key:n,onRun:()=>r};this.#e.push(i),e.push(()=>{this.#e=this.#e.filter(o=>o!==i)})}else this.#e.push(r),e.push(()=>{this.#e=this.#e.filter(i=>i!==r)})}),()=>{e.forEach(n=>n())}},this.addBaseKeymap=()=>{let t=UC(Ph);return this.addObjectKeymap(t)},this.build=()=>{let t={};return this.#e.forEach(e=>{t[e.key]=[...t[e.key]||[],e]}),Object.fromEntries(Object.entries(t).map(([e,n])=>{let r=n.sort((o,s)=>(s.priority??50)-(o.priority??50));return[e,(o,s,a)=>{let l=this.#t;if(l==null)throw mr();return qn(...r.map(c=>c.onRun(l)))(o,s,a)}]}))}}#t;#e;get ctx(){return this.#t}},ro=K(new mg,"keymap"),Tc=K([ze],"keymapTimer"),Vr=ot("KeymapReady"),JC=t=>{let e=new mg;return e.setCtx(t),t.inject(ro,e).inject(Tc,[ze]).record(Vr),async()=>(await t.waitTimers(Tc),t.done(Vr),()=>{t.remove(ro).remove(Tc).clearTimer(Vr)})},Ps=ot("ParserReady"),gg=(()=>{throw mr()}),Ge=K(gg,"parser"),Ic=K([],"parserTimer"),yg=t=>(t.inject(Ge,gg).inject(Ic,[ze]).record(Ps),async()=>{await t.waitTimers(Ic);let e=t.get(tr),n=t.get(gt);return t.set(Ge,Xh.create(n,e)),t.done(Ps),()=>{t.remove(Ge).remove(Ic).clearTimer(Ps)}});Qt(yg,{displayName:"Parser"});var Wr=ot("SerializerReady"),vc=K([],"serializerTimer"),kg=(()=>{throw mr()}),nr=K(kg,"serializer"),bg=t=>(t.inject(nr,kg).inject(vc,[ze]).record(Wr),async()=>{await t.waitTimers(vc);let e=t.get(tr),n=t.get(gt);return t.set(nr,Zh.create(n,e)),t.done(Wr),()=>{t.remove(nr).remove(vc).clearTimer(Wr)}});Qt(bg,{displayName:"Serializer"});var Yi=K("","defaultValue"),Zi=K(t=>t,"stateOptions"),Fs=K([],"editorStateTimer"),zs=ot("EditorStateReady");function GC(t,e,n){if(typeof t=="string")return e(t);if(t.type==="html")return ln.fromSchema(n).parse(t.dom);if(t.type==="json")return Ve.fromJSON(n,t.value);throw rd(t)}var QC=new te("MILKDOWN_STATE_TRACKER"),xg=t=>(t.inject(Yi,"").inject(Xi,{}).inject(Zi,e=>e).inject(Fs,[Ps,Wr,Hr,Vr]).record(zs),async()=>{await t.waitTimers(Fs);let e=t.get(gt),n=t.get(Ge),r=t.get(jr),i=t.get(Zi),o=t.get(yt),s=GC(t.get(Yi),n,e),a=t.get(ro),l=a.addBaseKeymap(),c=[...o,new Y({key:QC,state:{init:()=>{},apply:(d,p,h,m)=>{t.set(Xi,m)}}}),$h({rules:r}),Kh(a.build())];t.set(yt,c);let u=i({schema:e,doc:s,plugins:c}),f=Ar.create(u);return t.set(Xi,f),t.done(zs),()=>{l(),t.remove(Yi).remove(Xi).remove(Zi).remove(Fs).clearTimer(zs)}});Qt(xg,{displayName:"EditorState"});var Kr=K([],"pasteRule"),_s=K([ze],"pasteRuleTimer"),$s=ot("PasteRuleReady"),wg=t=>(t.inject(Kr,[]).inject(_s,[ze]).record($s),async()=>(await t.waitTimers(_s),t.done($s),()=>{t.remove(Kr).remove(_s).clearTimer($s)}));Qt(wg,{displayName:"PasteRule"});var eo=ot("EditorViewReady"),Hs=K([],"editorViewTimer"),to=K({},"editorViewOptions"),no=K(null,"root"),Ac=K(null,"rootDOM"),Nc=K({},"rootAttrs");function XC(t,e){let n=document.createElement("div");n.className="milkdown",t.appendChild(n),e.set(Ac,n);let r=e.get(Nc);return Object.entries(r).forEach(([i,o])=>n.setAttribute(i,o)),n}function YC(t){t.classList.add("editor"),t.setAttribute("role","textbox")}var ZC=new te("MILKDOWN_VIEW_CLEAR"),Sg=t=>(t.inject(no,document.body).inject(ie,{}).inject(to,{}).inject(Ac,null).inject(Nc,{}).inject(Hs,[zs,$s]).record(eo),async()=>{await t.wait(Gt);let e=t.get(no)||document.body,n=typeof e=="string"?document.querySelector(e):e;t.update(yt,s=>[new Y({key:ZC,view:a=>{let l=n?XC(n,t):void 0;return(()=>{if(l&&n){let u=a.dom;n.replaceChild(l,u),l.appendChild(u)}})(),{destroy:()=>{l?.parentNode&&l?.parentNode.replaceChild(a.dom,l),l?.remove()}}}}),...s]),await t.waitTimers(Hs);let r=t.get(Xi),i=t.get(to),o=new Ki(n,{state:r,nodeViews:Object.fromEntries(t.get(Vs)),markViews:Object.fromEntries(t.get(Ws)),transformPasted:(s,a,l)=>(t.get(Kr).sort((c,u)=>(u.priority??50)-(c.priority??50)).map(c=>c.run).forEach(c=>{s=c(s,a,l)}),s),...i});return YC(o.dom),t.set(ie,o),t.done(eo),()=>{o?.destroy(),t.remove(no).remove(ie).remove(to).remove(Ac).remove(Nc).remove(Hs).clearTimer(eo)}});Qt(Sg,{displayName:"EditorView"});var Cg=class Mg{constructor(){this.#t=!1,this.#e="Idle",this.#r=[],this.#n=()=>{},this.#s=new Ta,this.#o=new pd,this.#i=new Map,this.#a=new Map,this.#l=new fd(this.#s,this.#o),this.#d=()=>{let e=qC(async r=>{await Promise.all(this.#r.map(i=>Promise.resolve(i(r))))}),n=[fg,yg,bg,hg,JC,wg,xg,Sg,KC(this),e];this.#c(n,this.#a)},this.#c=(e,n)=>{e.forEach(r=>{let i=this.#l.produce(this.#t?r.meta:void 0),o=r(i);n.set(r,{ctx:i,handler:o,cleanup:void 0})})},this.#u=(e,n=!1)=>Promise.all([e].flat().map(async r=>{let i=this.#i.get(r)?.cleanup;return n?this.#i.delete(r):this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0}),typeof i=="function"?i():i})),this.#p=async()=>{await Promise.all([...this.#a.entries()].map(async([e,{cleanup:n}])=>typeof n=="function"?n():n)),this.#a.clear()},this.#f=e=>{this.#e=e,this.#n(e)},this.#h=e=>[...e.entries()].map(async([n,r])=>{let{ctx:i,handler:o}=r;if(!o)return;let s=await o();e.set(n,{ctx:i,handler:o,cleanup:s})}),this.enableInspector=(e=!0)=>(this.#t=e,this),this.onStatusChange=e=>(this.#n=e,this),this.config=e=>(this.#r.push(e),this),this.removeConfig=e=>(this.#r=this.#r.filter(n=>n!==e),this),this.use=e=>{let n=[e].flat();return n.flat().forEach(r=>{this.#i.set(r,{ctx:void 0,handler:void 0,cleanup:void 0})}),this.#e==="Created"&&this.#c(n,this.#i),this},this.remove=async e=>this.#e==="OnCreate"?(console.warn("[Milkdown]: You are trying to remove plugins when the editor is creating, this is not recommended, please check your code."),new Promise(n=>{setTimeout(()=>{n(this.remove(e))},50)})):(await this.#u([e].flat(),!0),this),this.create=async()=>this.#e==="OnCreate"?this:(this.#e==="Created"&&await this.destroy(),this.#f("OnCreate"),this.#d(),this.#c([...this.#i.keys()],this.#i),await Promise.all([this.#h(this.#a),this.#h(this.#i)].flat()),this.#f("Created"),this),this.destroy=async(e=!1)=>this.#e==="Destroyed"||this.#e==="OnDestroy"?this:this.#e==="OnCreate"?new Promise(n=>{setTimeout(()=>{n(this.destroy(e))},50)}):(e&&(this.#r=[]),this.#f("OnDestroy"),await this.#u([...this.#i.keys()],e),await this.#p(),this.#f("Destroyed"),this),this.action=e=>e(this.#l),this.inspect=()=>this.#t?[...this.#a.values(),...this.#i.values()].map(({ctx:e})=>e?.inspector?.read()).filter(e=>!!e):(console.warn("[Milkdown]: You are trying to collect inspection when inspector is disabled, please enable inspector by `editor.enableInspector()` first."),[])}static make(){return new Mg}#t;#e;#r;#n;#s;#o;#i;#a;#l;#d;#c;#u;#p;#f;#h;get ctx(){return this.#l}get status(){return this.#e}};var eM=t=>crypto.getRandomValues(new Uint8Array(t)),tM=(t,e,n)=>{let r=256-256%t.length;if(r===256){let o=t.length-1;return(s=e)=>{if(!s)return"";let a="";for(;;){let l=n(s),c=s;for(;c--;)if(a+=t[l[c]&o],a.length>=s)return a}}}let i=Math.ceil(1.6*256*e/r);return(o=e)=>{if(!o)return"";let s="";for(;;){let a=n(i),l=i;for(;l--;)if(a[l]<r&&(s+=t[a[l]%t.length],s.length>=o))return s}}},Eg=(t,e=21)=>tM(t,e|0,eM);var kz=Eg("abcedfghicklmn",10);function P(t,e){let n=pg(t),r=i=>async()=>{r.key=n,await i.wait(Hr);let o=e(i);return i.get(G).create(n,o),r.run=s=>i.get(G).call(t,s),()=>{i.get(G).remove(n)}};return r}function fe(t){let e=n=>async()=>{await n.wait(ze);let r=t(n);return n.update(jr,i=>[...i,r]),e.inputRule=r,()=>{n.update(jr,i=>i.filter(o=>o!==r))}};return e}function Tg(t){let e=n=>async()=>{await n.wait(ze);let r=t(n);return n.update(Kr,i=>[...i,r]),e.pasteRule=r,()=>{n.update(Kr,i=>i.filter(o=>o!==r))}};return e}function nM(t,e){let n=r=>async()=>{let i=e(r);return r.update($r,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update($r,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get(gt).marks[t];if(!i)throw ud(t);return i},n}function js(t,e){let n=r=>async()=>{let i=e(r);return r.update(_r,o=>[...o.filter(s=>s[0]!==t),[t,i]]),n.id=t,n.schema=i,()=>{r.update(_r,o=>o.filter(([s])=>s!==t))}};return n.type=r=>{let i=r.get(gt).nodes[t];if(!i)throw cd(t);return i},n}function Ce(t){let e,n=r=>async()=>(await r.wait(ze),e=t(r),r.update(yt,i=>[...i,e]),()=>{r.update(yt,i=>i.filter(o=>o!==e))});return n.plugin=()=>e,n.key=()=>e.spec.key,n}function rM(t){let e=n=>async()=>{await n.wait(Vr);let r=n.get(ro),i=t(n),o=r.addObjectKeymap(i);return e.keymap=i,()=>{o()}};return e}function Qe(t,e){let n=K(t,e),r=i=>(i.inject(n),()=>()=>{i.remove(n)});return r.key=n,r}function ne(t,e){let n=Qe(e,t),r=js(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.node=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>ne(t,o(e)),i}function kt(t,e){let n=Qe(e,t),r=nM(t,o=>o.get(n.key)(o)),i=[n,r];return i.id=r.id,i.mark=r,i.type=o=>r.type(o),i.ctx=n,i.key=n.key,i.extendSchema=o=>kt(t,o(e)),i}function _e(t,e){let n=Qe(Object.fromEntries(Object.entries(e).map(([o,{shortcuts:s,priority:a}])=>[o,{shortcuts:s,priority:a}])),`${t}Keymap`),r=rM(o=>{let s=o.get(n.key),a=Object.entries(e).flatMap(([l,{command:c}])=>{let u=s[l],f=[u.shortcuts].flat(),d=u.priority;return f.map(p=>[p,{key:p,onRun:c,priority:d}])});return Object.fromEntries(a)}),i=[n,r];return i.ctx=n,i.shortcuts=r,i.key=n.key,i.keymap=r.keymap,i}var ut=(t,e=()=>({}))=>Qe(e,`${t}Attr`),rr=(t,e=()=>({}))=>Qe(e,`${t}Attr`);function Xe(t,e,n){let r=Qe(n??{},t),i=s=>async()=>{await s.wait(Gt);let a={plugin:e(s),options:s.get(r.key)};return s.update(qr,l=>[...l,a]),()=>{s.update(qr,l=>l.filter(c=>c!==a))}},o=[r,i];return o.id=t,o.plugin=i,o.options=r,o}function Ig(t){return e=>{let n=e.get(ie),r=e.get(gt),i=e.get(nr);if(!t)return i(n.state.doc);let o=n.state.doc.slice(t.from,t.to,!0),s=r.topNodeType.createAndFill(null,o.content);return s?i(s):(console.error("No document found"),"")}}function vg(t,e=!1){return n=>{let r=n.get(ie),i=n.get(Ge)(t);if(!i)return;if(!e){let{state:l}=r;return r.dispatch(l.tr.replace(0,l.doc.content.size,new A(i.content,0,0)))}let o=n.get(gt),s=n.get(Zi)({schema:o,doc:i,plugins:n.get(yt)}),a=Ar.create(s);r.updateState(a)}}function Ag(t,e){return function(n,r){let{$from:i,$to:o,node:s}=n.selection;if(s&&s.isBlock||i.depth<2||!i.sameParent(o))return!1;let a=i.node(-1);if(a.type!=t)return!1;if(i.parent.content.size==0&&i.node(-1).childCount==i.indexAfter(-1)){if(i.depth==3||i.node(-3).type!=t||i.index(-2)!=i.node(-2).childCount-1)return!1;if(r){let f=E.empty,d=i.index(-1)?1:i.index(-2)?2:3;for(let y=i.depth-d;y>=i.depth-3;y--)f=E.from(i.node(y).copy(f));let p=i.indexAfter(-1)<i.node(-2).childCount?1:i.indexAfter(-2)<i.node(-3).childCount?2:3;f=f.append(E.from(t.createAndFill()));let h=i.before(i.depth-(d-1)),m=n.tr.replace(h,i.after(-p),new A(f,4-d,0)),g=-1;m.doc.nodesBetween(h,m.doc.content.size,(y,x)=>{if(g>-1)return!1;y.isTextblock&&y.content.size==0&&(g=x+1)}),g>-1&&m.setSelection(_.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let l=o.pos==i.end()?a.contentMatchAt(0).defaultType:null,c=n.tr.delete(i.pos,o.pos),u=l?[e?{type:t,attrs:e}:null,{type:l}]:void 0;return Vn(c.doc,i.pos,2,u)?(r&&r(c.split(i.pos,2,u).scrollIntoView()),!0):!1}}function Ng(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,s=>s.childCount>0&&s.firstChild.type==t);return o?n?r.node(o.depth-1).type==t?iM(e,n,t,o):oM(e,n,o):!0:!1}}function iM(t,e,n,r){let i=t.tr,o=r.end,s=r.$to.end(r.depth);o<s&&(i.step(new Ie(o-1,s,o,s,new A(E.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new Ni(i.doc.resolve(r.$from.pos),i.doc.resolve(s),r.depth));let a=Ir(r);if(a==null)return!1;i.lift(r,a);let l=i.doc.resolve(i.mapping.map(o,-1)-1);return Wn(i.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&i.join(l.pos),e(i.scrollIntoView()),!0}function oM(t,e,n){let r=t.tr,i=n.parent;for(let p=n.end,h=n.endIndex-1,m=n.startIndex;h>m;h--)p-=i.child(h).nodeSize,r.delete(p-1,p+1);let o=r.doc.resolve(n.start),s=o.nodeAfter;if(r.mapping.map(n.end)!=n.start+o.nodeAfter.nodeSize)return!1;let a=n.startIndex==0,l=n.endIndex==i.childCount,c=o.node(-1),u=o.index(-1);if(!c.canReplace(u+(a?0:1),u+1,s.content.append(l?E.empty:E.from(i))))return!1;let f=o.pos,d=f+s.nodeSize;return r.step(new Ie(f-(a?1:0),d+(l?1:0),f+1,d-1,new A((a?E.empty:E.from(i.copy(E.empty))).append(l?E.empty:E.from(i.copy(E.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function Rg(t){return function(e,n){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==t);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let a=o.parent,l=a.child(s-1);if(l.type!=t)return!1;if(n){let c=l.lastChild&&l.lastChild.type==a.type,u=E.from(c?t.create():null),f=new A(E.from(t.create(null,E.from(a.type.create(null,u)))),c?3:1,0),d=o.start,p=o.end;n(e.tr.step(new Ie(d-(c?3:1),p,d,p,f,1,!0)).scrollIntoView())}return!0}}function Rc(t){let e=new Map;if(!t||!t.type)throw new Error("mdast-util-definitions expected node");return pt(t,"definition",function(r){let i=Dg(r.identifier);i&&!e.get(i)&&e.set(i,r)}),n;function n(r){let i=Dg(r);return e.get(i)}}function Dg(t){return String(t||"").toUpperCase()}function qs(){return function(t){let e=Rc(t);pt(t,function(n,r,i){if(n.type==="definition"&&i!==void 0&&typeof r=="number")return i.children.splice(r,1),[Dn,r];if(n.type==="imageReference"||n.type==="linkReference"){let o=e(n.identifier);if(o&&i&&typeof r=="number")return i.children[r]=n.type==="imageReference"?{type:"image",url:o.url,title:o.title,alt:n.alt}:{type:"link",url:o.url,title:o.title,children:n.children},[Dn,r]}})}}function Og(t,e){if(!(e.childCount>=1&&e.lastChild?.type.name==="hardbreak")){t.next(e.content);return}let n=[];e.content.forEach((r,i,o)=>{o!==e.childCount-1&&n.push(r)}),t.next(E.fromArray(n))}function M(t,e){return Object.assign(t,{meta:{package:"@milkdown/preset-commonmark",...e}}),t}var Dc=rr("emphasis");M(Dc,{displayName:"Attr<emphasis>",group:"Emphasis"});var Jr=kt("emphasis",t=>({attrs:{marker:{default:t.get(zr).emphasis||"*",validate:"string"}},parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style",getAttrs:e=>e==="italic"}],toDOM:e=>["em",t.get(Dc.key)(e)],parseMarkdown:{match:e=>e.type==="emphasis",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="emphasis",runner:(e,n)=>{e.withMark(n,"emphasis",void 0,{marker:n.attrs.marker})}}}));M(Jr.mark,{displayName:"MarkSchema<emphasis>",group:"Emphasis"});M(Jr.ctx,{displayName:"MarkSchemaCtx<emphasis>",group:"Emphasis"});var Oc=P("ToggleEmphasis",t=>()=>Dr(Jr.type(t)));M(Oc,{displayName:"Command<toggleEmphasisCommand>",group:"Emphasis"});var Lg=fe(t=>Vt(/(?:^|[^*])\*([^*]+)\*$/,Jr.type(t),{getAttr:()=>({marker:"*"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("*")?{}:{fullMatch:e.slice(1),start:n+1}}));M(Lg,{displayName:"InputRule<emphasis>|Star",group:"Emphasis"});var Bg=fe(t=>Vt(/\b_(?![_\s])(.*?[^_\s])_\b/,Jr.type(t),{getAttr:()=>({marker:"_"}),updateCaptured:({fullMatch:e,start:n})=>e.startsWith("_")?{}:{fullMatch:e.slice(1),start:n+1}}));M(Bg,{displayName:"InputRule<emphasis>|Underscore",group:"Emphasis"});var Lc=_e("emphasisKeymap",{ToggleEmphasis:{shortcuts:"Mod-i",command:t=>{let e=t.get(G);return()=>e.call(Oc.key)}}});M(Lc.ctx,{displayName:"KeymapCtx<emphasis>",group:"Emphasis"});M(Lc.shortcuts,{displayName:"Keymap<emphasis>",group:"Emphasis"});var Bc=rr("strong");M(Bc,{displayName:"Attr<strong>",group:"Strong"});var io=kt("strong",t=>({attrs:{marker:{default:t.get(zr).strong||"*",validate:"string"}},parseDOM:[{tag:"b",getAttrs:e=>e.style.fontWeight!="normal"&&null},{tag:"strong"},{style:"font-style",getAttrs:e=>e==="bold"},{style:"font-weight=400",clearMark:e=>e.type.name=="strong"},{style:"font-weight",getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}],toDOM:e=>["strong",t.get(Bc.key)(e)],parseMarkdown:{match:e=>e.type==="strong",runner:(e,n,r)=>{e.openMark(r,{marker:n.marker}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="strong",runner:(e,n)=>{e.withMark(n,"strong",void 0,{marker:n.attrs.marker})}}}));M(io.mark,{displayName:"MarkSchema<strong>",group:"Strong"});M(io.ctx,{displayName:"MarkSchemaCtx<strong>",group:"Strong"});var Pc=P("ToggleStrong",t=>()=>Dr(io.type(t)));M(Pc,{displayName:"Command<toggleStrongCommand>",group:"Strong"});var Pg=fe(t=>Vt(/(?<![\w:/])(?:\*\*|__)([^*_]+?)(?:\*\*|__)(?![\w/])$/,io.type(t),{getAttr:e=>({marker:e[0].startsWith("*")?"*":"_"})}));M(Pg,{displayName:"InputRule<strong>",group:"Strong"});var Fc=_e("strongKeymap",{ToggleBold:{shortcuts:["Mod-b"],command:t=>{let e=t.get(G);return()=>e.call(Pc.key)}}});M(Fc.ctx,{displayName:"KeymapCtx<strong>",group:"Strong"});M(Fc.shortcuts,{displayName:"Keymap<strong>",group:"Strong"});var zc=rr("inlineCode");M(zc,{displayName:"Attr<inlineCode>",group:"InlineCode"});var bn=kt("inlineCode",t=>({priority:100,code:!0,parseDOM:[{tag:"code"}],toDOM:e=>["code",t.get(zc.key)(e)],parseMarkdown:{match:e=>e.type==="inlineCode",runner:(e,n,r)=>{e.openMark(r),e.addText(n.value),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="inlineCode",runner:(e,n,r)=>(e.withMark(n,"inlineCode",r.text||""),!0)}}));M(bn.mark,{displayName:"MarkSchema<inlineCode>",group:"InlineCode"});M(bn.ctx,{displayName:"MarkSchemaCtx<inlineCode>",group:"InlineCode"});var _c=P("ToggleInlineCode",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(r.empty)return!1;let{from:o,to:s}=r;return e.doc.rangeHasMark(o,s,bn.type(t))?(n?.(i.removeMark(o,s,bn.type(t))),!0):(Object.keys(e.schema.marks).filter(a=>a!==bn.type.name).map(a=>e.schema.marks[a]).forEach(a=>{i.removeMark(o,s,a)}),n?.(i.addMark(o,s,bn.type(t).create())),!0)});M(_c,{displayName:"Command<toggleInlineCodeCommand>",group:"InlineCode"});var Fg=fe(t=>Vt(/(?:`)([^`]+)(?:`)$/,bn.type(t)));M(Fg,{displayName:"InputRule<inlineCodeInputRule>",group:"InlineCode"});var $c=_e("inlineCodeKeymap",{ToggleInlineCode:{shortcuts:"Mod-e",command:t=>{let e=t.get(G);return()=>e.call(_c.key)}}});M($c.ctx,{displayName:"KeymapCtx<inlineCode>",group:"InlineCode"});M($c.shortcuts,{displayName:"Keymap<inlineCode>",group:"InlineCode"});var sM=new Set(["http:","https:","mailto:","tel:","ftp:"]);function aM(t){return t<=32||t>=127&&t<=160||t>=8203&&t<=8205||t===8232||t===8233||t===65279}function lM(t){let e="";for(let n of t)aM(n.codePointAt(0)??0)||(e+=n);return e}function cM(t){if(typeof t!="string")return"";let e=t.trim();if(!e)return"";let n=lM(e),r=/^([a-z][a-z0-9+.-]*):/i.exec(n)?.[1];return!r||sM.has(`${r.toLowerCase()}:`)?e:""}var Hc=rr("link");M(Hc,{displayName:"Attr<link>",group:"Link"});var Ur=kt("link",t=>({attrs:{href:{validate:"string"},title:{default:null,validate:"string|null"}},parseDOM:[{tag:"a[href]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{href:e.getAttribute("href"),title:e.getAttribute("title")}}}],toDOM:e=>["a",{...t.get(Hc.key)(e),...e.attrs,href:cM(e.attrs.href)}],parseMarkdown:{match:e=>e.type==="link",runner:(e,n,r)=>{let i=n.url,o=n.title;e.openMark(r,{href:i,title:o}),e.next(n.children),e.closeMark(r)}},toMarkdown:{match:e=>e.type.name==="link",runner:(e,n)=>{e.withMark(n,"link",void 0,{title:n.attrs.title,url:n.attrs.href})}}}));M(Ur.mark,{displayName:"MarkSchema<link>",group:"Link"});var zg=P("ToggleLink",t=>(e={})=>Dr(Ur.type(t),e));M(zg,{displayName:"Command<toggleLinkCommand>",group:"Link"});var _g=P("UpdateLink",t=>(e={})=>(n,r)=>{if(!r)return!1;let i,o=-1,{selection:s}=n,{from:a,to:l}=s;if(n.doc.nodesBetween(a,a===l?l+1:l,(h,m)=>{if(Ur.type(t).isInSet(h.marks))return i=h,o=m,!1}),!i)return!1;let c=i.marks.find(({type:h})=>h===Ur.type(t));if(!c)return!1;let u=o,f=o+i.nodeSize,{tr:d}=n,p=Ur.type(t).create({...c.attrs,...e});return p?(r(d.removeMark(u,f,c).addMark(u,f,p).setSelection(new z(d.selection.$anchor)).scrollIntoView()),!0):!1});M(_g,{displayName:"Command<updateLinkCommand>",group:"Link"});var $g=js("doc",()=>({content:"block+",parseMarkdown:{match:({type:t})=>t==="root",runner:(t,e,n)=>{t.injectRoot(e,n)}},toMarkdown:{match:t=>t.type.name==="doc",runner:(t,e)=>{t.openNode("root"),t.next(e.content)}}}));M($g,{displayName:"NodeSchema<doc>",group:"Doc"});function uM(t){return On(t,e=>e.type==="html"&&["<br />","<br>","<br >","<br/>"].includes(e.value?.trim()),(e,n)=>{if(!n.length)return;let r=n[n.length-1];if(!r)return;let i=r.children.indexOf(e);i!==-1&&r.children.splice(i,1)},!0)}var Us=Xe("remark-preserve-empty-line",()=>()=>uM);M(Us.plugin,{displayName:"Remark<remarkPreserveEmptyLine>",group:"Remark"});M(Us.options,{displayName:"RemarkConfig<remarkPreserveEmptyLine>",group:"Remark"});var Vc=ut("paragraph");M(Vc,{displayName:"Attr<paragraph>",group:"Paragraph"});var bt=ne("paragraph",t=>({content:"inline*",group:"block",parseDOM:[{tag:"p"}],toDOM:e=>["p",t.get(Vc.key)(e),0],parseMarkdown:{match:e=>e.type==="paragraph",runner:(e,n,r)=>{e.openNode(r),n.children?e.next(n.children):e.addText(n.value||""),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="paragraph",runner:(e,n)=>{let r=t.get(ie).state?.doc.lastChild;e.openNode("paragraph"),(!n.content||n.content.size===0)&&n!==r&&fM(t)?e.addNode("html",void 0,"<br />"):Og(e,n),e.closeNode()}}}));function fM(t){let e=!1;try{t.get(Us.id),e=!0}catch{e=!1}return e}M(bt.node,{displayName:"NodeSchema<paragraph>",group:"Paragraph"});M(bt.ctx,{displayName:"NodeSchemaCtx<paragraph>",group:"Paragraph"});var Wc=P("TurnIntoText",t=>()=>Rr(bt.type(t)));M(Wc,{displayName:"Command<turnIntoTextCommand>",group:"Paragraph"});var jc=_e("paragraphKeymap",{TurnIntoText:{shortcuts:"Mod-Alt-0",command:t=>{let e=t.get(G);return()=>e.call(Wc.key)}}});M(jc.ctx,{displayName:"KeymapCtx<paragraph>",group:"Paragraph"});M(jc.shortcuts,{displayName:"Keymap<paragraph>",group:"Paragraph"});var dM=Array(6).fill(0).map((t,e)=>e+1);function pM(t){return t.textContent.toLowerCase().trim().replace(/\s+/g,"-")}var Js=Qe(pM,"headingIdGenerator");M(Js,{displayName:"Ctx<HeadingIdGenerator>",group:"Heading"});var qc=ut("heading");M(qc,{displayName:"Attr<heading>",group:"Heading"});var or=ne("heading",t=>{let e=t.get(Js.key);return{content:"inline*",group:"block",defining:!0,attrs:{id:{default:"",validate:"string"},level:{default:1,validate:"number"}},parseDOM:dM.map(n=>({tag:`h${n}`,getAttrs:r=>{if(!(r instanceof HTMLElement))throw it(r);return{level:n,id:r.id}}})),toDOM:n=>[`h${n.attrs.level}`,{...t.get(qc.key)(n),id:n.attrs.id||e(n)},0],parseMarkdown:{match:({type:n})=>n==="heading",runner:(n,r,i)=>{let o=r.depth;n.openNode(i,{level:o}),n.next(r.children),n.closeNode()}},toMarkdown:{match:n=>n.type.name==="heading",runner:(n,r)=>{n.openNode("heading",void 0,{depth:r.attrs.level}),Og(n,r),n.closeNode()}}}});M(or.node,{displayName:"NodeSchema<heading>",group:"Heading"});M(or.ctx,{displayName:"NodeSchemaCtx<heading>",group:"Heading"});var Hg=fe(t=>Fl(/^(?<hashes>#+)\s$/,or.type(t),e=>{let n=e.groups?.hashes?.length||0,{$from:r}=t.get(ie).state.selection,i=r.node();if(i.type.name==="heading"){let o=Number(i.attrs.level)+Number(n);return o>6&&(o=6),{level:o}}return{level:n}}));M(Hg,{displayName:"InputRule<wrapInHeadingInputRule>",group:"Heading"});var kn=P("WrapInHeading",t=>e=>(e??=1,e<1?Rr(bt.type(t)):Rr(or.type(t),{level:e})));M(kn,{displayName:"Command<wrapInHeadingCommand>",group:"Heading"});var Kc=P("DowngradeHeading",t=>()=>(e,n,r)=>{let{$from:i}=e.selection,o=i.node();if(o.type!==or.type(t)||!e.selection.empty||i.parentOffset!==0)return!1;let s=o.attrs.level-1;return s?(n?.(e.tr.setNodeMarkup(e.selection.$from.before(),void 0,{...o.attrs,level:s})),!0):Rr(bt.type(t))(e,n,r)});M(Kc,{displayName:"Command<downgradeHeadingCommand>",group:"Heading"});var Uc=_e("headingKeymap",{TurnIntoH1:{shortcuts:"Mod-Alt-1",command:t=>{let e=t.get(G);return()=>e.call(kn.key,1)}},TurnIntoH2:{shortcuts:"Mod-Alt-2",command:t=>{let e=t.get(G);return()=>e.call(kn.key,2)}},TurnIntoH3:{shortcuts:"Mod-Alt-3",command:t=>{let e=t.get(G);return()=>e.call(kn.key,3)}},TurnIntoH4:{shortcuts:"Mod-Alt-4",command:t=>{let e=t.get(G);return()=>e.call(kn.key,4)}},TurnIntoH5:{shortcuts:"Mod-Alt-5",command:t=>{let e=t.get(G);return()=>e.call(kn.key,5)}},TurnIntoH6:{shortcuts:"Mod-Alt-6",command:t=>{let e=t.get(G);return()=>e.call(kn.key,6)}},DowngradeHeading:{shortcuts:["Delete","Backspace"],command:t=>{let e=t.get(G);return()=>e.call(Kc.key)}}});M(Uc.ctx,{displayName:"KeymapCtx<heading>",group:"Heading"});M(Uc.shortcuts,{displayName:"Keymap<heading>",group:"Heading"});var Jc=ut("blockquote");M(Jc,{displayName:"Attr<blockquote>",group:"Blockquote"});var oo=ne("blockquote",t=>({content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM:e=>["blockquote",t.get(Jc.key)(e),0],parseMarkdown:{match:({type:e})=>e==="blockquote",runner:(e,n,r)=>{e.openNode(r).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="blockquote",runner:(e,n)=>{e.openNode("blockquote").next(n.content).closeNode()}}}));M(oo.node,{displayName:"NodeSchema<blockquote>",group:"Blockquote"});M(oo.ctx,{displayName:"NodeSchemaCtx<blockquote>",group:"Blockquote"});var Vg=fe(t=>ys(/^\s*>\s$/,oo.type(t)));M(Vg,{displayName:"InputRule<wrapInBlockquoteInputRule>",group:"Blockquote"});var Gc=P("WrapInBlockquote",t=>()=>gs(oo.type(t)));M(Gc,{displayName:"Command<wrapInBlockquoteCommand>",group:"Blockquote"});var Qc=_e("blockquoteKeymap",{WrapInBlockquote:{shortcuts:"Mod-Shift-b",command:t=>{let e=t.get(G);return()=>e.call(Gc.key)}}});M(Qc.ctx,{displayName:"KeymapCtx<blockquote>",group:"Blockquote"});M(Qc.shortcuts,{displayName:"Keymap<blockquote>",group:"Blockquote"});var Xc=ut("codeBlock",()=>({pre:{},code:{}}));M(Xc,{displayName:"Attr<codeBlock>",group:"CodeBlock"});var so=ne("code_block",t=>({content:"text*",group:"block",marks:"",defining:!0,code:!0,attrs:{language:{default:"",validate:"string"}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{language:e.dataset.language}}}],toDOM:e=>{let n=t.get(Xc.key)(e),r=e.attrs.language,i=r&&r.length>0?{"data-language":r}:void 0;return["pre",{...n.pre,...i},["code",n.code,0]]},parseMarkdown:{match:({type:e})=>e==="code",runner:(e,n,r)=>{let i=n.lang??"",o=n.value;e.openNode(r,{language:i}),o&&e.addText(o),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="code_block",runner:(e,n)=>{e.addNode("code",void 0,n.content.firstChild?.text||"",{lang:n.attrs.language})}}}));M(so.node,{displayName:"NodeSchema<codeBlock>",group:"CodeBlock"});M(so.ctx,{displayName:"NodeSchemaCtx<codeBlock>",group:"CodeBlock"});var Wg=fe(t=>Fl(/^```(?<language>[a-z]*)?[\s\n]$/,so.type(t),e=>({language:e.groups?.language??""})));M(Wg,{displayName:"InputRule<createCodeBlockInputRule>",group:"CodeBlock"});var Yc=P("CreateCodeBlock",t=>(e="")=>Rr(so.type(t),{language:e}));M(Yc,{displayName:"Command<createCodeBlockCommand>",group:"CodeBlock"});var hM=P("UpdateCodeBlockLanguage",()=>({pos:t,language:e}={pos:-1,language:""})=>(n,r)=>t>=0?(r?.(n.tr.setNodeAttribute(t,"language",e)),!0):!1);M(hM,{displayName:"Command<updateCodeBlockLanguageCommand>",group:"CodeBlock"});var Zc=_e("codeBlockKeymap",{CreateCodeBlock:{shortcuts:"Mod-Alt-c",command:t=>{let e=t.get(G);return()=>e.call(Yc.key)}}});M(Zc.ctx,{displayName:"KeymapCtx<codeBlock>",group:"CodeBlock"});M(Zc.shortcuts,{displayName:"Keymap<codeBlock>",group:"CodeBlock"});var eu=ut("image");M(eu,{displayName:"Attr<image>",group:"Image"});var Gr=ne("image",t=>({inline:!0,group:"inline",selectable:!0,draggable:!0,marks:"",atom:!0,defining:!0,isolating:!0,attrs:{src:{default:"",validate:"string"},alt:{default:"",validate:"string"},title:{default:"",validate:"string"}},parseDOM:[{tag:"img[src]",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{src:e.getAttribute("src")||"",alt:e.getAttribute("alt")||"",title:e.getAttribute("title")||e.getAttribute("alt")||""}}}],toDOM:e=>["img",{...t.get(eu.key)(e),...e.attrs}],parseMarkdown:{match:({type:e})=>e==="image",runner:(e,n,r)=>{let i=n.url,o=n.alt,s=n.title;e.addNode(r,{src:i,alt:o,title:s})}},toMarkdown:{match:e=>e.type.name==="image",runner:(e,n)=>{e.addNode("image",void 0,void 0,{title:n.attrs.title,url:n.attrs.src,alt:n.attrs.alt})}}}));M(Gr.node,{displayName:"NodeSchema<image>",group:"Image"});M(Gr.ctx,{displayName:"NodeSchemaCtx<image>",group:"Image"});var jg=P("InsertImage",t=>(e={})=>(n,r)=>{if(!r)return!0;let{src:i="",alt:o="",title:s=""}=e,a=Gr.type(t).create({src:i,alt:o,title:s});return a&&r(n.tr.replaceSelectionWith(a).scrollIntoView()),!0});M(jg,{displayName:"Command<insertImageCommand>",group:"Image"});var qg=P("UpdateImage",t=>(e={})=>(n,r)=>{let i=Wh(n.selection,Gr.type(t));if(!i)return!1;let{node:o,pos:s}=i,a={...o.attrs},{src:l,alt:c,title:u}=e;return l!==void 0&&(a.src=l),c!==void 0&&(a.alt=c),u!==void 0&&(a.title=u),r?.(n.tr.setNodeMarkup(s,void 0,a).scrollIntoView()),!0});M(qg,{displayName:"Command<updateImageCommand>",group:"Image"});var mM=fe(t=>new be(/!\[(?<alt>.*?)]\((?<filename>.*?)\s*(?="|\))"?(?<title>[^"]+)?"?\)/,(e,n,r,i)=>{let[o,s,a="",l]=n;return o?e.tr.replaceWith(r,i,Gr.type(t).create({src:a,alt:s,title:l})):null}));M(mM,{displayName:"InputRule<insertImageInputRule>",group:"Image"});var Ks=ut("hardbreak",t=>({"data-type":"hardbreak","data-is-inline":t.attrs.isInline}));M(Ks,{displayName:"Attr<hardbreak>",group:"Hardbreak"});var ir=ne("hardbreak",t=>({inline:!0,group:"inline",attrs:{isInline:{default:!1,validate:"boolean"}},selectable:!1,parseDOM:[{tag:"br"},{tag:'span[data-type="hardbreak"]',getAttrs:()=>({isInline:!0})}],toDOM:e=>e.attrs.isInline?["span",t.get(Ks.key)(e)," "]:["br",t.get(Ks.key)(e)],parseMarkdown:{match:({type:e})=>e==="break",runner:(e,n,r)=>{e.addNode(r,{isInline:!!n.data?.isInline})}},leafText:()=>` `,toMarkdown:{match:e=>e.type.name==="hardbreak",runner:(e,n)=>{n.attrs.isInline?e.addNode("text",void 0,` -`):e.addNode("break")}}}));M(ir.node,{displayName:"NodeSchema<hardbreak>",group:"Hardbreak"});M(ir.ctx,{displayName:"NodeSchemaCtx<hardbreak>",group:"Hardbreak"});var tu=P("InsertHardbreak",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(!(r instanceof z))return!1;if(r.empty){let o=r.$from.node();if(o.childCount>0&&o.lastChild?.type.name==="hardbreak")return n?.(i.replaceRangeWith(r.to-1,r.to,e.schema.node("paragraph")).setSelection(_.near(i.doc.resolve(r.to))).scrollIntoView()),!0}return n?.(i.setMeta("hardbreak",!0).replaceSelectionWith(ir.type(t).create()).scrollIntoView()),!0});M(tu,{displayName:"Command<insertHardbreakCommand>",group:"Hardbreak"});var nu=_e("hardbreakKeymap",{InsertHardbreak:{shortcuts:"Shift-Enter",command:t=>{let e=t.get(G);return()=>e.call(tu.key)}}});M(nu.ctx,{displayName:"KeymapCtx<hardbreak>",group:"Hardbreak"});M(nu.shortcuts,{displayName:"Keymap<hardbreak>",group:"Hardbreak"});var ru=ut("hr");M(ru,{displayName:"Attr<hr>",group:"Hr"});var ao=ne("hr",t=>({group:"block",parseDOM:[{tag:"hr"}],toDOM:e=>["hr",t.get(ru.key)(e)],parseMarkdown:{match:({type:e})=>e==="thematicBreak",runner:(e,n,r)=>{e.addNode(r)}},toMarkdown:{match:e=>e.type.name==="hr",runner:e=>{e.addNode("thematicBreak")}}}));M(ao.node,{displayName:"NodeSchema<hr>",group:"Hr"});M(ao.ctx,{displayName:"NodeSchemaCtx<hr>",group:"Hr"});var Kg=fe(t=>new be(/^(?:---|___\s|\*\*\*\s)$/,(e,n,r,i)=>{let{tr:o}=e;return n[0]&&o.replaceWith(r-1,i,ao.type(t).create()),o}));M(Kg,{displayName:"InputRule<insertHrInputRule>",group:"Hr"});var Ug=P("InsertHr",t=>()=>(e,n)=>{if(!n)return!0;let r=bt.node.type(t).create(),{tr:i,selection:o}=e,{from:s}=o,a=ao.type(t).create();if(!a)return!0;let l=i.replaceSelectionWith(a).insert(s,r),c=_.findFrom(l.doc.resolve(s),1,!0);return c&&n(l.setSelection(c).scrollIntoView()),!0});M(Ug,{displayName:"Command<insertHrCommand>",group:"Hr"});var iu=ut("bulletList");M(iu,{displayName:"Attr<bulletList>",group:"BulletList"});var Qr=ne("bullet_list",t=>({content:"listItem+",group:"block",attrs:{spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ul",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{spread:e.dataset.spread==="true"}}}],toDOM:e=>["ul",{...t.get(iu.key)(e),"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"false";e.openNode(r,{spread:i}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="bullet_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!1,spread:n.attrs.spread}).next(n.content).closeNode()}}}));M(Qr.node,{displayName:"NodeSchema<bulletList>",group:"BulletList"});M(Qr.ctx,{displayName:"NodeSchemaCtx<bulletList>",group:"BulletList"});var Jg=fe(t=>ys(/^\s*([-+*])\s$/,Qr.type(t)));M(Jg,{displayName:"InputRule<wrapInBulletListInputRule>",group:"BulletList"});var ou=P("WrapInBulletList",t=>()=>gs(Qr.type(t)));M(ou,{displayName:"Command<wrapInBulletListCommand>",group:"BulletList"});var su=_e("bulletListKeymap",{WrapInBulletList:{shortcuts:"Mod-Alt-8",command:t=>{let e=t.get(G);return()=>e.call(ou.key)}}});M(su.ctx,{displayName:"KeymapCtx<bulletListKeymap>",group:"BulletList"});M(su.shortcuts,{displayName:"Keymap<bulletListKeymap>",group:"BulletList"});var au=ut("orderedList");M(au,{displayName:"Attr<orderedList>",group:"OrderedList"});var Xr=ne("ordered_list",t=>({content:"listItem+",group:"block",attrs:{order:{default:1,validate:"number"},spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ol",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{spread:e.dataset.spread,order:e.hasAttribute("start")?Number(e.getAttribute("start")):1}}}],toDOM:e=>["ol",{...t.get(au.key)(e),...e.attrs.order===1?{}:{start:e.attrs.order},"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{spread:i,order:n.start??1}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="ordered_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!0,start:n.attrs.order??1,spread:n.attrs.spread==="true"}),e.next(n.content),e.closeNode()}}}));M(Xr.node,{displayName:"NodeSchema<orderedList>",group:"OrderedList"});M(Xr.ctx,{displayName:"NodeSchemaCtx<orderedList>",group:"OrderedList"});var Gg=fe(t=>ys(/^\s*(\d+)\.\s$/,Xr.type(t),e=>({order:Number(e[1])}),(e,n)=>n.childCount+n.attrs.order===Number(e[1])));M(Gg,{displayName:"InputRule<wrapInOrderedListInputRule>",group:"OrderedList"});var lu=P("WrapInOrderedList",t=>()=>gs(Xr.type(t)));M(lu,{displayName:"Command<wrapInOrderedListCommand>",group:"OrderedList"});var cu=_e("orderedListKeymap",{WrapInOrderedList:{shortcuts:"Mod-Alt-7",command:t=>{let e=t.get(G);return()=>e.call(lu.key)}}});M(cu.ctx,{displayName:"KeymapCtx<orderedList>",group:"OrderedList"});M(cu.shortcuts,{displayName:"Keymap<orderedList>",group:"OrderedList"});var uu=ut("listItem");M(uu,{displayName:"Attr<listItem>",group:"ListItem"});var At=ne("list_item",t=>({group:"listItem",content:"paragraph block*",attrs:{label:{default:"\u2022",validate:"string"},listType:{default:"bullet",validate:"string"},spread:{default:!0,validate:"boolean"}},defining:!0,parseDOM:[{tag:"li",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{label:e.dataset.label,listType:e.dataset.listType,spread:e.dataset.spread==="true"}}}],toDOM:e=>["li",{...t.get(uu.key)(e),"data-label":e.attrs.label,"data-list-type":e.attrs.listType,"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e})=>e==="listItem",runner:(e,n,r)=>{let i=n.label!=null?`${n.label}.`:"\u2022",o=n.label!=null?"ordered":"bullet",s=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{label:i,listType:o,spread:s}),e.next(n.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="list_item",runner:(e,n)=>{e.openNode("listItem",void 0,{spread:n.attrs.spread}),e.next(n.content),e.closeNode()}}}));M(At.node,{displayName:"NodeSchema<listItem>",group:"ListItem"});M(At.ctx,{displayName:"NodeSchemaCtx<listItem>",group:"ListItem"});var fu=P("SinkListItem",t=>()=>Rg(At.type(t)));M(fu,{displayName:"Command<sinkListItemCommand>",group:"ListItem"});var du=P("LiftListItem",t=>()=>Ng(At.type(t)));M(du,{displayName:"Command<liftListItemCommand>",group:"ListItem"});var pu=P("SplitListItem",t=>()=>Ag(At.type(t)));M(pu,{displayName:"Command<splitListItemCommand>",group:"ListItem"});function gM(t){return(e,n,r)=>{let{selection:i}=e;if(!(i instanceof z))return!1;let{empty:o,$from:s}=i;return!o||s.parentOffset!==0||s.node(-1).type!==At.type(t)?!1:Ol(e,n,r)}}var hu=P("LiftFirstListItem",t=>()=>gM(t));M(hu,{displayName:"Command<liftFirstListItemCommand>",group:"ListItem"});var mu=_e("listItemKeymap",{NextListItem:{shortcuts:"Enter",command:t=>{let e=t.get(G);return()=>e.call(pu.key)}},SinkListItem:{shortcuts:["Tab","Mod-]"],command:t=>{let e=t.get(G);return()=>e.call(fu.key)}},LiftListItem:{shortcuts:["Shift-Tab","Mod-["],command:t=>{let e=t.get(G);return()=>e.call(du.key)}},LiftFirstListItem:{shortcuts:["Backspace","Delete"],command:t=>{let e=t.get(G);return()=>e.call(hu.key)}}});M(mu.ctx,{displayName:"KeymapCtx<listItem>",group:"ListItem"});M(mu.shortcuts,{displayName:"Keymap<listItem>",group:"ListItem"});var Qg=js("text",()=>({group:"inline",parseMarkdown:{match:({type:t})=>t==="text",runner:(t,e)=>{t.addText(e.value)}},toMarkdown:{match:t=>t.type.name==="text",runner:(t,e)=>{t.addNode("text",void 0,e.text)}}}));M(Qg,{displayName:"NodeSchema<text>",group:"Text"});var gu=ut("html");M(gu,{displayName:"Attr<html>",group:"Html"});var yu=ne("html",t=>({atom:!0,group:"inline",inline:!0,attrs:{value:{default:"",validate:"string"}},toDOM:e=>{let n=document.createElement("span"),r={...t.get(gu.key)(e),"data-value":e.attrs.value,"data-type":"html"};return n.textContent=e.attrs.value,["span",r,e.attrs.value]},parseDOM:[{tag:'span[data-type="html"]',getAttrs:e=>({value:e.dataset.value??""})}],parseMarkdown:{match:({type:e})=>e==="html",runner:(e,n,r)=>{e.addNode(r,{value:n.value})}},toMarkdown:{match:e=>e.type.name==="html",runner:(e,n)=>{e.addNode("html",void 0,n.attrs.value)}}}));M(yu.node,{displayName:"NodeSchema<html>",group:"Html"});M(yu.ctx,{displayName:"NodeSchemaCtx<html>",group:"Html"});var yM=[$g,Vc,bt,Js,qc,or,Ks,ir,Jc,oo,Xc,so,ru,ao,eu,Gr,iu,Qr,au,Xr,uu,At,Dc,Jr,Bc,io,zc,bn,Hc,Ur,gu,yu,Qg].flat(),kM=[Vg,Jg,Gg,Wg,Kg,Hg].flat(),bM=[Lg,Bg,Fg,Pg],xM=P("IsMarkSelected",()=>t=>e=>{if(!t)return!1;let{doc:n,selection:r}=e;return n.rangeHasMark(r.from,r.to,t)}),wM=P("IsNoteSelected",()=>t=>e=>t?jh(e,t).hasNode:!1),SM=P("ClearTextInCurrentBlock",()=>()=>(t,e)=>{let n=t.tr,{$from:r,$to:i}=n.selection,{pos:o}=r,{pos:s}=i,a=o-r.node().content.size;return a<0?!1:(n=n.deleteRange(a,s),e?.(n),!0)}),CM=P("SetBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr,{from:s,to:a}=o.selection;try{o.setBlockType(s,a,r,i)}catch{return!1}return n?.(o),!0}),MM=P("WrapInBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let{$from:s,$to:a}=o.selection,l=s.blockRange(a),c=l&&Hn(l,r,i);if(!c)return!1;o=o.wrap(l,c)}catch{return!1}return n?.(o),!0}),EM=P("AddBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let s=r instanceof Ve?r:r.createAndFill(i);if(!s)return!1;o.replaceSelectionWith(s)}catch{return!1}return n?.(o),!0}),TM=P("SelectTextNearPos",()=>t=>(e,n)=>{let{pos:r}=t??{};if(r==null)return!1;let i=(s,a,l)=>Math.min(Math.max(s,a),l),o=e.tr;try{let s=e.doc.resolve(i(r,0,e.doc.content.size));o.setSelection(z.near(s))}catch{return!1}return n?.(o.scrollIntoView()),!0}),IM=[Wc,Gc,kn,Kc,Yc,tu,Ug,jg,qg,lu,ou,fu,pu,du,hu,Oc,_c,Pc,zg,_g,xM,wM,SM,CM,MM,EM,TM],vM=[Qc,Zc,nu,Uc,mu,cu,su,jc,Lc,$c,Fc].flat(),ku=Xe("remarkAddOrderInList",()=>()=>t=>{pt(t,"list",e=>{if(e.ordered){let n=e.start??1;e.children.forEach((r,i)=>{r.label=i+n})}})});M(ku.plugin,{displayName:"Remark<remarkAddOrderInListPlugin>",group:"Remark"});M(ku.options,{displayName:"RemarkConfig<remarkAddOrderInListPlugin>",group:"Remark"});var bu=Xe("remarkLineBreak",()=>()=>t=>{let e=/[\t ]*(?:\r?\n|\r)/g;pt(t,"text",(n,r,i)=>{if(!n.value||typeof n.value!="string")return;let o=[],s=0;e.lastIndex=0;let a=e.exec(n.value);for(;a;){let l=a.index;s!==l&&o.push({type:"text",value:n.value.slice(s,l)}),o.push({type:"break",data:{isInline:!0}}),s=l+a[0].length,a=e.exec(n.value)}if(o.length>0&&i&&typeof r=="number")return s<n.value.length&&o.push({type:"text",value:n.value.slice(s)}),i.children.splice(r,1,...o),r+o.length})});M(bu.plugin,{displayName:"Remark<remarkLineBreak>",group:"Remark"});M(bu.options,{displayName:"RemarkConfig<remarkLineBreak>",group:"Remark"});var xu=Xe("remarkInlineLink",()=>qs);M(xu.plugin,{displayName:"Remark<remarkInlineLinkPlugin>",group:"Remark"});M(xu.options,{displayName:"RemarkConfig<remarkInlineLinkPlugin>",group:"Remark"});var AM=t=>!!t.children,NM=t=>t.type==="html";function RM(t,e){return n(t,0,null)[0];function n(r,i,o){if(AM(r)){let s=[];for(let a=0,l=r.children.length;a<l;a++){let c=r.children[a];if(c){let u=n(c,a,r);if(u)for(let f=0,d=u.length;f<d;f++){let p=u[f];p&&s.push(p)}}}r.children=s}return e(r,i,o)}}var DM=["root","blockquote","listItem"],wu=Xe("remarkHTMLTransformer",()=>()=>t=>{RM(t,(e,n,r)=>NM(e)?(r&&DM.includes(r.type)&&(e.children=[{...e}],delete e.value,e.type="paragraph"),[e]):[e])});M(wu.plugin,{displayName:"Remark<remarkHtmlTransformer>",group:"Remark"});M(wu.options,{displayName:"RemarkConfig<remarkHtmlTransformer>",group:"Remark"});var Su=Xe("remarkMarker",()=>()=>(t,e)=>{let n=r=>e.value.charAt(r.position.start.offset);pt(t,r=>["strong","emphasis"].includes(r.type),r=>{r.marker=n(r)})});M(Su.plugin,{displayName:"Remark<remarkMarker>",group:"Remark"});M(Su.options,{displayName:"RemarkConfig<remarkMarker>",group:"Remark"});var Xg=Ce(()=>{let t=!1,e=new Y({key:new te("MILKDOWN_INLINE_NODES_CURSOR"),state:{init(){return!1},apply(n){if(!n.selection.empty)return!1;let r=n.selection.$from,i=r.nodeBefore,o=r.nodeAfter;return!!(i&&o&&i.isInline&&!i.isText&&o.isInline&&!o.isText)}},props:{handleDOMEvents:{compositionend:(n,r)=>t?(t=!1,requestAnimationFrame(()=>{if(e.getState(n.state)){let i=n.state.selection.from;r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i))}}),!0):!1,compositionstart:n=>(e.getState(n.state)&&(t=!0),!1),beforeinput:(n,r)=>{if(e.getState(n.state)&&r instanceof InputEvent&&r.data&&!t){let i=n.state.selection.from;return r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i)),!0}return!1}},decorations(n){if(e.getState(n)){let r=n.selection.$from.pos,i=document.createElement("span"),o=se.widget(r,i,{side:-1}),s=document.createElement("span"),a=se.widget(r,s);return setTimeout(()=>{i.contentEditable="true",s.contentEditable="true"}),re.create(n.doc,[o,a])}return re.empty}}});return e});M(Xg,{displayName:"Prose<inlineNodesCursorPlugin>",group:"Prose"});var Yg=Ce(t=>new Y({key:new te("MILKDOWN_HARDBREAK_MARKS"),appendTransaction:(e,n,r)=>{if(!e.length)return;let[i]=e;if(!i)return;let[o]=i.steps;if(i.getMeta("hardbreak")){if(!(o instanceof pe))return;let{from:s}=o;return r.tr.setNodeMarkup(s,ir.type(t),void 0,[])}if(o instanceof _n){let s=r.tr,{from:a,to:l}=o;return r.doc.nodesBetween(a,l,(c,u)=>{c.type===ir.type(t)&&(s=s.setNodeMarkup(u,ir.type(t),void 0,[]))}),s}}}));M(Yg,{displayName:"Prose<hardbreakClearMarkPlugin>",group:"Prose"});var Cu=Qe(["table","code_block"],"hardbreakFilterNodes");M(Cu,{displayName:"Ctx<hardbreakFilterNodes>",group:"Prose"});var Zg=Ce(t=>{let e=t.get(Cu.key);return new Y({key:new te("MILKDOWN_HARDBREAK_FILTER"),filterTransaction:(n,r)=>{let i=n.getMeta("hardbreak"),[o]=n.steps;if(i&&o){let{from:s}=o,a=r.doc.resolve(s),l=a.depth,c=!0;for(;l>0;)e.includes(a.node(l).type.name)&&(c=!1),l--;return c}return!0}})});M(Zg,{displayName:"Prose<hardbreakFilterPlugin>",group:"Prose"});var ey=Ce(t=>{let e=new te("MILKDOWN_HEADING_ID"),n=r=>{if(r.composing)return;let i=t.get(Js.key),o=r.state.tr.setMeta("addToHistory",!1),s=!1,a={};r.state.doc.descendants((l,c)=>{if(l.type===or.type(t)){if(l.textContent.trim().length===0)return;let u=l.attrs,f=i(l);a[f]?(a[f]+=1,f+=`-#${a[f]}`):a[f]=1,u.id!==f&&(s=!0,o.setMeta(e,!0).setNodeMarkup(c,void 0,{...u,id:f}))}}),s&&r.dispatch(o)};return new Y({key:e,view:r=>(n(r),{update:(i,o)=>{i.state.doc.eq(o.doc)||n(i)}})})});M(ey,{displayName:"Prose<syncHeadingIdPlugin>",group:"Prose"});var ty=Ce(t=>{let e=(n,r,i)=>{if(!i.selection||n.some(f=>f.getMeta("addToHistory")===!1||!f.isGeneric))return null;let o=Xr.type(t),s=Qr.type(t),a=At.type(t),l=(f,d,p=1)=>{let h=!1,m=`${d+p}.`;return f.label!==m&&(f.label=m,h=!0),h},c=i.tr,u=!1;return i.doc.descendants((f,d,p,h)=>{if(f.type===s){let m=f.maybeChild(0);m?.type===a&&m.attrs.listType==="ordered"&&(u=!0,c.setNodeMarkup(d,o,{spread:"true"}),f.descendants((g,y,x,C)=>{if(g.type===a){let I={...g.attrs};l(I,C)&&(c=c.setNodeMarkup(y,void 0,I))}return!1}))}else if(f.type===a&&p?.type===o){let m={...f.attrs},g=!1;m.listType!=="ordered"&&(m.listType="ordered",g=!0),p?.maybeChild(0)&&(g=l(m,h,p?.attrs.order??1)),g&&(c=c.setNodeMarkup(d,void 0,m),u=!0)}}),u?c.setMeta("addToHistory",!1):null};return new Y({key:new te("MILKDOWN_KEEP_LIST_ORDER"),appendTransaction:e})});M(ty,{displayName:"Prose<syncListOrderPlugin>",group:"Prose"});var OM=[Yg,Cu,Zg,Xg,ku,xu,bu,wu,Su,Us,ey,ty].flat(),ny=[yM,kM,bM,IM,vM,OM].flat();var Eu,Tu;if(typeof WeakMap<"u"){let t=new WeakMap;Eu=e=>t.get(e),Tu=(e,n)=>(t.set(e,n),n)}else{let t=[],n=0;Eu=r=>{for(let i=0;i<t.length;i+=2)if(t[i]==r)return t[i+1]},Tu=(r,i)=>(n==10&&(n=0),t[n++]=r,t[n++]=i)}var Z=class{constructor(t,e,n,r){this.width=t,this.height=e,this.map=n,this.problems=r}findCell(t){for(let e=0;e<this.map.length;e++){let n=this.map[e];if(n!=t)continue;let r=e%this.width,i=e/this.width|0,o=r+1,s=i+1;for(let a=1;o<this.width&&this.map[e+a]==n;a++)o++;for(let a=1;s<this.height&&this.map[e+this.width*a]==n;a++)s++;return{left:r,top:i,right:o,bottom:s}}throw new RangeError(`No cell with offset ${t} found`)}colCount(t){for(let e=0;e<this.map.length;e++)if(this.map[e]==t)return e%this.width;throw new RangeError(`No cell with offset ${t} found`)}nextCell(t,e,n){let{left:r,right:i,top:o,bottom:s}=this.findCell(t);return e=="horiz"?(n<0?r==0:i==this.width)?null:this.map[o*this.width+(n<0?r-1:i)]:(n<0?o==0:s==this.height)?null:this.map[r+this.width*(n<0?o-1:s)]}rectBetween(t,e){let{left:n,right:r,top:i,bottom:o}=this.findCell(t),{left:s,right:a,top:l,bottom:c}=this.findCell(e);return{left:Math.min(n,s),top:Math.min(i,l),right:Math.max(r,a),bottom:Math.max(o,c)}}cellsInRect(t){let e=[],n={};for(let r=t.top;r<t.bottom;r++)for(let i=t.left;i<t.right;i++){let o=r*this.width+i,s=this.map[o];n[s]||(n[s]=!0,!(i==t.left&&i&&this.map[o-1]==s||r==t.top&&r&&this.map[o-this.width]==s)&&e.push(s))}return e}positionAt(t,e,n){for(let r=0,i=0;;r++){let o=i+n.child(r).nodeSize;if(r==t){let s=e+t*this.width,a=(t+1)*this.width;for(;s<a&&this.map[s]<i;)s++;return s==a?o-1:this.map[s]}i=o}}static get(t){return Eu(t)||Tu(t,LM(t))}};function LM(t){if(t.type.spec.tableRole!="table")throw new RangeError("Not a table node: "+t.type.name);let e=BM(t),n=t.childCount,r=[],i=0,o=null,s=[];for(let c=0,u=e*n;c<u;c++)r[c]=0;for(let c=0,u=0;c<n;c++){let f=t.child(c);u++;for(let h=0;;h++){for(;i<r.length&&r[i]!=0;)i++;if(h==f.childCount)break;let m=f.child(h),{colspan:g,rowspan:y,colwidth:x}=m.attrs;for(let C=0;C<y;C++){if(C+c>=n){(o||(o=[])).push({type:"overlong_rowspan",pos:u,n:y-C});break}let I=i+C*e;for(let v=0;v<g;v++){r[I+v]==0?r[I+v]=u:(o||(o=[])).push({type:"collision",row:c,pos:u,n:g-v});let w=x&&x[v];if(w){let N=(I+v)%e*2,O=s[N];O==null||O!=w&&s[N+1]==1?(s[N]=w,s[N+1]=1):O==w&&s[N+1]++}}}i+=g,u+=m.nodeSize}let d=(c+1)*e,p=0;for(;i<d;)r[i++]==0&&p++;p&&(o||(o=[])).push({type:"missing",row:c,n:p}),u++}(e===0||n===0)&&(o||(o=[])).push({type:"zero_sized"});let a=new Z(e,n,r,o),l=!1;for(let c=0;!l&&c<s.length;c+=2)s[c]!=null&&s[c+1]<n&&(l=!0);return l&&PM(a,s,t),a}function BM(t){let e=-1,n=!1;for(let r=0;r<t.childCount;r++){let i=t.child(r),o=0;if(n)for(let s=0;s<r;s++){let a=t.child(s);for(let l=0;l<a.childCount;l++){let c=a.child(l);s+c.attrs.rowspan>r&&(o+=c.attrs.colspan)}}for(let s=0;s<i.childCount;s++){let a=i.child(s);o+=a.attrs.colspan,a.attrs.rowspan>1&&(n=!0)}e==-1?e=o:e!=o&&(e=Math.max(e,o))}return e}function PM(t,e,n){t.problems||(t.problems=[]);let r={};for(let i=0;i<t.map.length;i++){let o=t.map[i];if(r[o])continue;r[o]=!0;let s=n.nodeAt(o);if(!s)throw new RangeError(`No cell with offset ${o} found`);let a=null,l=s.attrs;for(let c=0;c<l.colspan;c++){let u=e[(i+c)%t.width*2];u!=null&&(!l.colwidth||l.colwidth[c]!=u)&&((a||(a=FM(l)))[c]=u)}a&&t.problems.unshift({type:"colwidth mismatch",pos:o,colwidth:a})}}function FM(t){if(t.colwidth)return t.colwidth.slice();let e=[];for(let n=0;n<t.colspan;n++)e.push(0);return e}function ry(t,e){if(typeof t=="string")return{};let n=t.getAttribute("data-colwidth"),r=n&&/^\d+(,\d+)*$/.test(n)?n.split(",").map(s=>Number(s)):null,i=Number(t.getAttribute("colspan")||1),o={colspan:i,rowspan:Number(t.getAttribute("rowspan")||1),colwidth:r&&r.length==i?r:null};for(let s in e){let a=e[s].getFromDOM,l=a&&a(t);l!=null&&(o[s]=l)}return o}function iy(t,e){let n={};t.attrs.colspan!=1&&(n.colspan=t.attrs.colspan),t.attrs.rowspan!=1&&(n.rowspan=t.attrs.rowspan),t.attrs.colwidth&&(n["data-colwidth"]=t.attrs.colwidth.join(","));for(let r in e){let i=e[r].setDOMAttr;i&&i(t.attrs[r],n)}return n}function zM(t){if(t!==null){if(!Array.isArray(t))throw new TypeError("colwidth must be null or an array");for(let e of t)if(typeof e!="number")throw new TypeError("colwidth must be null or an array of numbers")}}function gy(t){let e=t.cellAttributes||{},n={colspan:{default:1,validate:"number"},rowspan:{default:1,validate:"number"},colwidth:{default:null,validate:zM}};for(let r in e)n[r]={default:e[r].default,validate:e[r].validate};return{table:{content:"table_row+",tableRole:"table",isolating:!0,group:t.tableGroup,parseDOM:[{tag:"table"}],toDOM(){return["table",["tbody",0]]}},table_row:{content:"(table_cell | table_header)*",tableRole:"row",parseDOM:[{tag:"tr"}],toDOM(){return["tr",0]}},table_cell:{content:t.cellContent,attrs:n,tableRole:"cell",isolating:!0,parseDOM:[{tag:"td",getAttrs:r=>ry(r,e)}],toDOM(r){return["td",iy(r,e),0]}},table_header:{content:t.cellContent,attrs:n,tableRole:"header_cell",isolating:!0,parseDOM:[{tag:"th",getAttrs:r=>ry(r,e)}],toDOM(r){return["th",iy(r,e),0]}}}}function $e(t){let e=t.cached.tableNodeTypes;if(!e){e=t.cached.tableNodeTypes={};for(let n in t.nodes){let r=t.nodes[n],i=r.spec.tableRole;i&&(e[i]=r)}}return e}var xn=new te("selectingCells");function ei(t){for(let e=t.depth-1;e>0;e--)if(t.node(e).type.spec.tableRole=="row")return t.node(0).resolve(t.before(e+1));return null}function Ae(t){let e=t.selection.$head;for(let n=e.depth;n>0;n--)if(e.node(n).type.spec.tableRole=="row")return!0;return!1}function ea(t){let e=t.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;let n=ei(e.$head)||_M(e.$head);if(n)return n;throw new RangeError(`No cell found around position ${e.head}`)}function _M(t){for(let e=t.nodeAfter,n=t.pos;e;e=e.firstChild,n++){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n)}for(let e=t.nodeBefore,n=t.pos;e;e=e.lastChild,n--){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n-e.nodeSize)}}function Iu(t){return t.parent.type.spec.tableRole=="row"&&!!t.nodeAfter}function $M(t){return t.node(0).resolve(t.pos+t.nodeAfter.nodeSize)}function Nu(t,e){return t.depth==e.depth&&t.pos>=e.start(-1)&&t.pos<=e.end(-1)}function yy(t,e,n){let r=t.node(-1),i=Z.get(r),o=t.start(-1),s=i.nextCell(t.pos-o,e,n);return s==null?null:t.node(0).resolve(o+s)}function sr(t,e,n=1){let r={...t,colspan:t.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,n),r.colwidth.some(i=>i>0)||(r.colwidth=null)),r}function HM(t,e,n=1){let r={...t,colspan:t.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let i=0;i<n;i++)r.colwidth.splice(e,0,0)}return r}function VM(t,e,n){let r=$e(e.type.schema).header_cell;for(let i=0;i<t.height;i++)if(e.nodeAt(t.map[n+i*t.width]).type!=r)return!1;return!0}var ae=class Xt extends _{constructor(e,n=e){let r=e.node(-1),i=Z.get(r),o=e.start(-1),s=i.rectBetween(e.pos-o,n.pos-o),a=e.node(0),l=i.cellsInRect(s).filter(u=>u!=n.pos-o);l.unshift(n.pos-o);let c=l.map(u=>{let f=r.nodeAt(u);if(!f)throw new RangeError(`No cell with offset ${u} found`);let d=o+u+1;return new un(a.resolve(d),a.resolve(d+f.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=n}map(e,n){let r=e.resolve(n.map(this.$anchorCell.pos)),i=e.resolve(n.map(this.$headCell.pos));if(Iu(r)&&Iu(i)&&Nu(r,i)){let o=this.$anchorCell.node(-1)!=r.node(-1);return o&&this.isRowSelection()?Xt.rowSelection(r,i):o&&this.isColSelection()?Xt.colSelection(r,i):new Xt(r,i)}return z.between(r,i)}content(){let e=this.$anchorCell.node(-1),n=Z.get(e),r=this.$anchorCell.start(-1),i=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),o={},s=[];for(let l=i.top;l<i.bottom;l++){let c=[];for(let u=l*n.width+i.left,f=i.left;f<i.right;f++,u++){let d=n.map[u];if(o[d])continue;o[d]=!0;let p=n.findCell(d),h=e.nodeAt(d);if(!h)throw new RangeError(`No cell with offset ${d} found`);let m=i.left-p.left,g=p.right-i.right;if(m>0||g>0){let y=h.attrs;if(m>0&&(y=sr(y,0,m)),g>0&&(y=sr(y,y.colspan-g,g)),p.left<i.left){if(h=h.type.createAndFill(y),!h)throw new RangeError(`Could not create cell with attrs ${JSON.stringify(y)}`)}else h=h.type.create(y,h.content)}if(p.top<i.top||p.bottom>i.bottom){let y={...h.attrs,rowspan:Math.min(p.bottom,i.bottom)-Math.max(p.top,i.top)};p.top<i.top?h=h.type.createAndFill(y):h=h.type.create(y,h.content)}c.push(h)}s.push(e.child(l).copy(E.from(c)))}let a=this.isColSelection()&&this.isRowSelection()?e:s;return new A(E.from(a),1,1)}replace(e,n=A.empty){let r=e.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:a,$to:l}=i[s],c=e.mapping.slice(r);e.replace(c.map(a.pos),c.map(l.pos),s?A.empty:n)}let o=_.findFrom(e.doc.resolve(e.mapping.slice(r).map(this.to)),-1);o&&e.setSelection(o)}replaceWith(e,n){this.replace(e,new A(E.from(n),0,0))}forEachCell(e){let n=this.$anchorCell.node(-1),r=Z.get(n),i=this.$anchorCell.start(-1),o=r.cellsInRect(r.rectBetween(this.$anchorCell.pos-i,this.$headCell.pos-i));for(let s=0;s<o.length;s++)e(n.nodeAt(o[s]),i+o[s])}isColSelection(){let e=this.$anchorCell.index(-1),n=this.$headCell.index(-1);if(Math.min(e,n)>0)return!1;let r=e+this.$anchorCell.nodeAfter.attrs.rowspan,i=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,i)==this.$headCell.node(-1).childCount}static colSelection(e,n=e){let r=e.node(-1),i=Z.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.top<=a.top?(s.top>0&&(e=l.resolve(o+i.map[s.left])),a.bottom<i.height&&(n=l.resolve(o+i.map[i.width*(i.height-1)+a.right-1]))):(a.top>0&&(n=l.resolve(o+i.map[a.left])),s.bottom<i.height&&(e=l.resolve(o+i.map[i.width*(i.height-1)+s.right-1]))),new Xt(e,n)}isRowSelection(){let e=this.$anchorCell.node(-1),n=Z.get(e),r=this.$anchorCell.start(-1),i=n.colCount(this.$anchorCell.pos-r),o=n.colCount(this.$headCell.pos-r);if(Math.min(i,o)>0)return!1;let s=i+this.$anchorCell.nodeAfter.attrs.colspan,a=o+this.$headCell.nodeAfter.attrs.colspan;return Math.max(s,a)==n.width}eq(e){return e instanceof Xt&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,n=e){let r=e.node(-1),i=Z.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.left<=a.left?(s.left>0&&(e=l.resolve(o+i.map[s.top*i.width])),a.right<i.width&&(n=l.resolve(o+i.map[i.width*(a.top+1)-1]))):(a.left>0&&(n=l.resolve(o+i.map[a.top*i.width])),s.right<i.width&&(e=l.resolve(o+i.map[i.width*(s.top+1)-1]))),new Xt(e,n)}toJSON(){return{type:"cell",anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(e,n){return new Xt(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){return new Xt(e.resolve(n),e.resolve(r))}getBookmark(){return new WM(this.$anchorCell.pos,this.$headCell.pos)}};ae.prototype.visible=!1;_.jsonID("cell",ae);var WM=class ky{constructor(e,n){this.anchor=e,this.head=n}map(e){return new ky(e.map(this.anchor),e.map(this.head))}resolve(e){let n=e.resolve(this.anchor),r=e.resolve(this.head);return n.parent.type.spec.tableRole=="row"&&r.parent.type.spec.tableRole=="row"&&n.index()<n.parent.childCount&&r.index()<r.parent.childCount&&Nu(n,r)?new ae(n,r):_.near(r,1)}};function jM(t){if(!(t.selection instanceof ae))return null;let e=[];return t.selection.forEachCell((n,r)=>{e.push(se.node(r,r+n.nodeSize,{class:"selectedCell"}))}),re.create(t.doc,e)}function qM({$from:t,$to:e}){if(t.pos==e.pos||t.pos<e.pos-6)return!1;let n=t.pos,r=e.pos,i=t.depth;for(;i>=0&&!(t.after(i+1)<t.end(i));i--,n++);for(let o=e.depth;o>=0&&!(e.before(o+1)>e.start(o));o--,r--);return n==r&&/row|table/.test(t.node(i).type.spec.tableRole)}function KM({$from:t,$to:e}){let n,r;for(let i=t.depth;i>0;i--){let o=t.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){n=o;break}}for(let i=e.depth;i>0;i--){let o=e.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){r=o;break}}return n!==r&&e.parentOffset===0}function UM(t,e,n){let r=(e||t).selection,i=(e||t).doc,o,s;if(r instanceof H&&(s=r.node.type.spec.tableRole)){if(s=="cell"||s=="header_cell")o=ae.create(i,r.from);else if(s=="row"){let a=i.resolve(r.from+1);o=ae.rowSelection(a,a)}else if(!n){let a=Z.get(r.node),l=r.from+1,c=l+a.map[a.width*a.height-1];o=ae.create(i,l+1,c)}}else r instanceof z&&qM(r)?o=z.create(i,r.from):r instanceof z&&KM(r)&&(o=z.create(i,r.$from.start(),r.$from.end()));return o&&(e||(e=t.tr)).setSelection(o),e}var JM=new te("fix-tables");function by(t,e,n,r){let i=t.childCount,o=e.childCount;e:for(let s=0,a=0;s<o;s++){let l=e.child(s);for(let c=a,u=Math.min(i,s+3);c<u;c++)if(t.child(c)==l){a=c+1,n+=l.nodeSize;continue e}r(l,n),a<i&&t.child(a).sameMarkup(l)?by(t.child(a),l,n+1,r):l.nodesBetween(0,l.content.size,r,n+1),n+=l.nodeSize}}function GM(t,e){let n,r=(i,o)=>{i.type.spec.tableRole=="table"&&(n=QM(t,i,o,n))};return e?e.doc!=t.doc&&by(e.doc,t.doc,0,r):t.doc.descendants(r),n}function QM(t,e,n,r){let i=Z.get(e);if(!i.problems)return r;r||(r=t.tr);let o=[];for(let l=0;l<i.height;l++)o.push(0);for(let l=0;l<i.problems.length;l++){let c=i.problems[l];if(c.type=="collision"){let u=e.nodeAt(c.pos);if(!u)continue;let f=u.attrs;for(let d=0;d<f.rowspan;d++)o[c.row+d]+=c.n;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,sr(f,f.colspan-c.n,c.n))}else if(c.type=="missing")o[c.row]+=c.n;else if(c.type=="overlong_rowspan"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,rowspan:u.attrs.rowspan-c.n})}else if(c.type=="colwidth mismatch"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,colwidth:c.colwidth})}else if(c.type=="zero_sized"){let u=r.mapping.map(n);r.delete(u,u+e.nodeSize)}}let s,a;for(let l=0;l<o.length;l++)o[l]&&(s==null&&(s=l),a=l);for(let l=0,c=n+1;l<i.height;l++){let u=e.child(l),f=c+u.nodeSize,d=o[l];if(d>0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);let h=[];for(let g=0;g<d;g++){let y=$e(t.schema)[p].createAndFill();y&&h.push(y)}let m=(l==0||s==l-1)&&a==l?c+1:f-1;r.insert(r.mapping.map(m),h)}c=f}return r.setMeta(JM,{fixTables:!0})}function xy(t){let e=Z.get(t),n=[],r=e.height,i=e.width;for(let o=0;o<r;o++){let s=[];for(let a=0;a<i;a++){let l=o*i+a,c=e.map[l];if(o>0){let u=l-i;if(c===e.map[u]){s.push(null);continue}}if(a>0){let u=l-1;if(c===e.map[u]){s.push(null);continue}}s.push(t.nodeAt(c))}n.push(s)}return n}function wy(t,e){let n=[],r=Z.get(t),i=r.height,o=r.width;for(let s=0;s<i;s++){let a=t.child(s),l=[];for(let u=0;u<o;u++){let f=e[s][u];if(!f)continue;let d=r.map[s*r.width+u],p=t.nodeAt(d);if(!p)continue;let h=p.type.createChecked(f.attrs,f.content,f.marks);l.push(h)}let c=a.type.createChecked(a.attrs,l,a.marks);n.push(c)}return t.type.createChecked(t.attrs,n,t.marks)}function Sy(t,e,n,r){let i=e[0]>n[0]?-1:1,o=t.splice(e[0],e.length),s=o.length%2===0?1:0,a;return r===-1&&i===1?a=n[0]-1:r===1&&i===-1?a=n[n.length-1]-s+1:a=i===-1?n[0]:n[n.length-1]-s,t.splice(a,0,...o),t}function ti(t){return XM(e=>e.type.spec.tableRole==="table",t)}function XM(t,e){for(let n=e.depth;n>=0;n-=1){let r=e.node(n);if(t(r))return{node:r,pos:n===0?0:e.before(n),start:e.start(n),depth:n}}return null}function Yr(t,e){let n=ti(e.$from);if(!n)return;let r=Z.get(n.node);if(!(t<0||t>r.width-1))return r.cellsInRect({left:t,right:t+1,top:0,bottom:r.height}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function Zr(t,e){let n=ti(e.$from);if(!n)return;let r=Z.get(n.node);if(!(t<0||t>r.height-1))return r.cellsInRect({left:0,right:r.width,top:t,bottom:t+1}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function oy(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=Yr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=Yr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;d.node.attrs.colspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=Yr(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=Yr(r,t.selection),a=Zr(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=Yr(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function sy(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=Zr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=Zr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;d.node.attrs.rowspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=Zr(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=Zr(r,t.selection),a=Yr(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=Zr(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function ay(t){return t[0].map((e,n)=>t.map(r=>r[n]))}function YM(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=ti(r.doc.resolve(a));if(!l)return!1;let c=(e=oy(r,i))===null||e===void 0?void 0:e.indexes,u=(n=oy(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=ZM(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=Z.get(f),p=l.start,h=o,m=d.positionAt(d.height-1,h,f),g=r.doc.resolve(p+m),y=d.positionAt(0,h,f),x=r.doc.resolve(p+y);return r.setSelection(ae.colSelection(g,x)),!0}function ZM(t,e,n,r){let i=ay(xy(t));return i=Sy(i,e,n,r),i=ay(i),wy(t,i)}function eE(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=ti(r.doc.resolve(a));if(!l)return!1;let c=(e=sy(r,i))===null||e===void 0?void 0:e.indexes,u=(n=sy(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=tE(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=Z.get(f),p=l.start,h=o,m=d.positionAt(h,d.width-1,f),g=r.doc.resolve(p+m),y=d.positionAt(h,0,f),x=r.doc.resolve(p+y);return r.setSelection(ae.rowSelection(g,x)),!0}function tE(t,e,n,r){let i=xy(t);return i=Sy(i,e,n,r),wy(t,i)}function xt(t){let e=t.selection,n=ea(t),r=n.node(-1),i=n.start(-1),o=Z.get(r);return{...e instanceof ae?o.rectBetween(e.$anchorCell.pos-i,e.$headCell.pos-i):o.findCell(n.pos-i),tableStart:i,map:o,table:r}}function Cy(t,{map:e,tableStart:n,table:r},i){let o=i>0?-1:0;VM(e,r,i+o)&&(o=i==0||i==e.width?null:0);for(let s=0;s<e.height;s++){let a=s*e.width+i;if(i>0&&i<e.width&&e.map[a-1]==e.map[a]){let l=e.map[a],c=r.nodeAt(l);t.setNodeMarkup(t.mapping.map(n+l),null,HM(c.attrs,i-e.colCount(l))),s+=c.attrs.rowspan-1}else{let l=o==null?$e(r.type.schema).cell:r.nodeAt(e.map[a+o]).type,c=e.positionAt(s,i,r);t.insert(t.mapping.map(n+c),l.createAndFill())}}return t}function My(t,e){if(!Ae(t))return!1;if(e){let n=xt(t);e(Cy(t.tr,n,n.left))}return!0}function ta(t,e){if(!Ae(t))return!1;if(e){let n=xt(t);e(Cy(t.tr,n,n.right))}return!0}function nE(t,{map:e,table:n,tableStart:r},i){let o=t.mapping.maps.length;for(let s=0;s<e.height;){let a=s*e.width+i,l=e.map[a],c=n.nodeAt(l),u=c.attrs;if(i>0&&e.map[a-1]==l||i<e.width-1&&e.map[a+1]==l)t.setNodeMarkup(t.mapping.slice(o).map(r+l),null,sr(u,i-e.colCount(l)));else{let f=t.mapping.slice(o).map(r+l);t.delete(f,f+c.nodeSize)}s+=u.rowspan}}function na(t,e){if(!Ae(t))return!1;if(e){let n=xt(t),r=t.tr;if(n.left==0&&n.right==n.map.width)return!1;for(let i=n.right-1;nE(r,n,i),i!=n.left;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=Z.get(o)}e(r)}return!0}function rE(t,e,n){var r;let i=$e(e.type.schema).header_cell;for(let o=0;o<t.width;o++)if(((r=e.nodeAt(t.map[o+n*t.width]))===null||r===void 0?void 0:r.type)!=i)return!1;return!0}function iE(t,{map:e,tableStart:n,table:r},i){let o=n;for(let c=0;c<i;c++)o+=r.child(c).nodeSize;let s=[],a=i>0?-1:0;rE(e,r,i+a)&&(a=i==0||i==e.height?null:0);for(let c=0,u=e.width*i;c<e.width;c++,u++)if(i>0&&i<e.height&&e.map[u]==e.map[u-e.width]){let f=e.map[u],d=r.nodeAt(f).attrs;t.setNodeMarkup(n+f,null,{...d,rowspan:d.rowspan+1}),c+=d.colspan-1}else{var l;let f=a==null?$e(r.type.schema).cell:(l=r.nodeAt(e.map[u+a*e.width]))===null||l===void 0?void 0:l.type,d=f?.createAndFill();d&&s.push(d)}return t.insert(o,$e(r.type.schema).row.create(null,s)),t}function Ey(t,e){if(!Ae(t))return!1;if(e){let n=xt(t);e(iE(t.tr,n,n.bottom))}return!0}function oE(t,{map:e,table:n,tableStart:r},i){let o=0;for(let c=0;c<i;c++)o+=n.child(c).nodeSize;let s=o+n.child(i).nodeSize,a=t.mapping.maps.length;t.delete(o+r,s+r);let l=new Set;for(let c=0,u=i*e.width;c<e.width;c++,u++){let f=e.map[u];if(!l.has(f)){if(l.add(f),i>0&&f==e.map[u-e.width]){let d=n.nodeAt(f).attrs;t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d,rowspan:d.rowspan-1}),c+=d.colspan-1}else if(i<e.height&&f==e.map[u+e.width]){let d=n.nodeAt(f),p=d.attrs,h=d.type.create({...p,rowspan:d.attrs.rowspan-1},d.content),m=e.positionAt(i+1,c,n);t.insert(t.mapping.slice(a).map(r+m),h),c+=p.colspan-1}}}}function ra(t,e){if(!Ae(t))return!1;if(e){let n=xt(t),r=t.tr;if(n.top==0&&n.bottom==n.map.height)return!1;for(let i=n.bottom-1;oE(r,n,i),i!=n.top;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=Z.get(n.table)}e(r)}return!0}function Ty(t,e){return function(n,r){if(!Ae(n))return!1;let i=ea(n);if(i.nodeAfter.attrs[t]===e)return!1;if(r){let o=n.tr;n.selection instanceof ae?n.selection.forEachCell((s,a)=>{s.attrs[t]!==e&&o.setNodeMarkup(a,null,{...s.attrs,[t]:e})}):o.setNodeMarkup(i.pos,null,{...i.nodeAfter.attrs,[t]:e}),r(o)}return!0}}function sE(t){return function(e,n){if(!Ae(e))return!1;if(n){let r=$e(e.schema),i=xt(e),o=e.tr,s=i.map.cellsInRect(t=="column"?{left:i.left,top:0,right:i.right,bottom:i.map.height}:t=="row"?{left:0,top:i.top,right:i.map.width,bottom:i.bottom}:i),a=s.map(l=>i.table.nodeAt(l));for(let l=0;l<s.length;l++)a[l].type==r.header_cell&&o.setNodeMarkup(i.tableStart+s[l],r.cell,a[l].attrs);if(o.steps.length===0)for(let l=0;l<s.length;l++)o.setNodeMarkup(i.tableStart+s[l],r.header_cell,a[l].attrs);n(o)}return!0}}function ly(t,e,n){let r=e.map.cellsInRect({left:0,top:0,right:t=="row"?e.map.width:1,bottom:t=="column"?e.map.height:1});for(let i=0;i<r.length;i++){let o=e.table.nodeAt(r[i]);if(o&&o.type!==n.header_cell)return!1}return!0}function Ru(t,e){return e=e||{useDeprecatedLogic:!1},e.useDeprecatedLogic?sE(t):function(n,r){if(!Ae(n))return!1;if(r){let i=$e(n.schema),o=xt(n),s=n.tr,a=ly("row",o,i),l=ly("column",o,i),c=(t==="column"?a:t==="row"&&l)?1:0,u=t=="column"?{left:0,top:c,right:1,bottom:o.map.height}:t=="row"?{left:c,top:0,right:o.map.width,bottom:1}:o,f=t=="column"?l?i.cell:i.header_cell:t=="row"?a?i.cell:i.header_cell:i.cell;o.map.cellsInRect(u).forEach(d=>{let p=d+o.tableStart,h=s.doc.nodeAt(p);h&&s.setNodeMarkup(p,f,h.attrs)}),r(s)}return!0}}var Yz=Ru("row",{useDeprecatedLogic:!0}),Zz=Ru("column",{useDeprecatedLogic:!0}),e_=Ru("cell",{useDeprecatedLogic:!0});function aE(t,e){if(e<0){let n=t.nodeBefore;if(n)return t.pos-n.nodeSize;for(let r=t.index(-1)-1,i=t.before();r>=0;r--){let o=t.node(-1).child(r),s=o.lastChild;if(s)return i-1-s.nodeSize;i-=o.nodeSize}}else{if(t.index()<t.parent.childCount-1)return t.pos+t.nodeAfter.nodeSize;let n=t.node(-1);for(let r=t.indexAfter(-1),i=t.after();r<n.childCount;r++){let o=n.child(r);if(o.childCount)return i+1;i+=o.nodeSize}}return null}function ia(t){return function(e,n){if(!Ae(e))return!1;let r=aE(ea(e),t);if(r==null)return!1;if(n){let i=e.doc.resolve(r);n(e.tr.setSelection(z.between(i,$M(i))).scrollIntoView())}return!0}}function Iy(t,e){let n=t.selection.$anchor;for(let r=n.depth;r>0;r--)if(n.node(r).type.spec.tableRole=="table")return e&&e(t.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function Gs(t,e){let n=t.selection;if(!(n instanceof ae))return!1;if(e){let r=t.tr,i=$e(t.schema).cell.createAndFill().content;n.forEachCell((o,s)=>{o.content.eq(i)||r.replace(r.mapping.map(s+1),r.mapping.map(s+o.nodeSize-1),new A(i,0,0))}),r.docChanged&&e(r)}return!0}function vy(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return eE({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function Ay(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return YM({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function lE(t){if(t.size===0)return null;let{content:e,openStart:n,openEnd:r}=t;for(;e.childCount==1&&(n>0&&r>0||e.child(0).type.spec.tableRole=="table");)n--,r--,e=e.child(0).content;let i=e.child(0),o=i.type.spec.tableRole,s=i.type.schema,a=[];if(o=="row")for(let l=0;l<e.childCount;l++){let c=e.child(l).content,u=l?0:Math.max(0,n-1),f=l<e.childCount-1?0:Math.max(0,r-1);(u||f)&&(c=vu($e(s).row,new A(c,u,f)).content),a.push(c)}else if(o=="cell"||o=="header_cell")a.push(n||r?vu($e(s).row,new A(e,n,r)).content:e);else return null;return cE(s,a)}function cE(t,e){let n=[];for(let i=0;i<e.length;i++){let o=e[i];for(let s=o.childCount-1;s>=0;s--){let{rowspan:a,colspan:l}=o.child(s).attrs;for(let c=i;c<i+a;c++)n[c]=(n[c]||0)+l}}let r=0;for(let i=0;i<n.length;i++)r=Math.max(r,n[i]);for(let i=0;i<n.length;i++)if(i>=e.length&&e.push(E.empty),n[i]<r){let o=$e(t).cell.createAndFill(),s=[];for(let a=n[i];a<r;a++)s.push(o);e[i]=e[i].append(E.from(s))}return{height:e.length,width:r,rows:e}}function vu(t,e){let n=t.createAndFill();return new Tr(n).replace(0,n.content.size,e).doc}function uE({width:t,height:e,rows:n},r,i){if(t!=r){let o=[],s=[];for(let a=0;a<n.length;a++){let l=n[a],c=[];for(let u=o[a]||0,f=0;u<r;f++){let d=l.child(f%l.childCount);u+d.attrs.colspan>r&&(d=d.type.createChecked(sr(d.attrs,d.attrs.colspan,u+d.attrs.colspan-r),d.content)),c.push(d),u+=d.attrs.colspan;for(let p=1;p<d.attrs.rowspan;p++)o[a+p]=(o[a+p]||0)+d.attrs.colspan}s.push(E.from(c))}n=s,t=r}if(e!=i){let o=[];for(let s=0,a=0;s<i;s++,a++){let l=[],c=n[a%e];for(let u=0;u<c.childCount;u++){let f=c.child(u);s+f.attrs.rowspan>i&&(f=f.type.create({...f.attrs,rowspan:Math.max(1,i-f.attrs.rowspan)},f.content)),l.push(f)}o.push(E.from(l))}n=o,e=i}return{width:t,height:e,rows:n}}function fE(t,e,n,r,i,o,s){let a=t.doc.type.schema,l=$e(a),c,u;if(i>e.width)for(let f=0,d=0;f<e.height;f++){let p=n.child(f);d+=p.nodeSize;let h=[],m;p.lastChild==null||p.lastChild.type==l.cell?m=c||(c=l.cell.createAndFill()):m=u||(u=l.header_cell.createAndFill());for(let g=e.width;g<i;g++)h.push(m);t.insert(t.mapping.slice(s).map(d-1+r),h)}if(o>e.height){let f=[];for(let h=0,m=(e.height-1)*e.width;h<Math.max(e.width,i);h++){let g=h>=e.width?!1:n.nodeAt(e.map[m+h]).type==l.header_cell;f.push(g?u||(u=l.header_cell.createAndFill()):c||(c=l.cell.createAndFill()))}let d=l.row.create(null,E.from(f)),p=[];for(let h=e.height;h<o;h++)p.push(d);t.insert(t.mapping.slice(s).map(r+n.nodeSize-2),p)}return!!(c||u)}function cy(t,e,n,r,i,o,s,a){if(s==0||s==e.height)return!1;let l=!1;for(let c=i;c<o;c++){let u=s*e.width+c,f=e.map[u];if(e.map[u-e.width]==f){l=!0;let d=n.nodeAt(f),{top:p,left:h}=e.findCell(f);t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d.attrs,rowspan:s-p}),t.insert(t.mapping.slice(a).map(e.positionAt(s,h,n)),d.type.createAndFill({...d.attrs,rowspan:p+d.attrs.rowspan-s})),c+=d.attrs.colspan-1}}return l}function uy(t,e,n,r,i,o,s,a){if(s==0||s==e.width)return!1;let l=!1;for(let c=i;c<o;c++){let u=c*e.width+s,f=e.map[u];if(e.map[u-1]==f){l=!0;let d=n.nodeAt(f),p=e.colCount(f),h=t.mapping.slice(a).map(f+r);t.setNodeMarkup(h,null,sr(d.attrs,s-p,d.attrs.colspan-(s-p))),t.insert(h+d.nodeSize,d.type.createAndFill(sr(d.attrs,0,s-p))),c+=d.attrs.rowspan-1}}return l}function fy(t,e,n,r,i){let o=n?t.doc.nodeAt(n-1):t.doc;if(!o)throw new Error("No table found");let s=Z.get(o),{top:a,left:l}=r,c=l+i.width,u=a+i.height,f=t.tr,d=0;function p(){if(o=n?f.doc.nodeAt(n-1):f.doc,!o)throw new Error("No table found");s=Z.get(o),d=f.mapping.maps.length}fE(f,s,o,n,c,u,d)&&p(),cy(f,s,o,n,l,c,a,d)&&p(),cy(f,s,o,n,l,c,u,d)&&p(),uy(f,s,o,n,a,u,l,d)&&p(),uy(f,s,o,n,a,u,c,d)&&p();for(let h=a;h<u;h++){let m=s.positionAt(h,l,o),g=s.positionAt(h,c,o);f.replace(f.mapping.slice(d).map(m+n),f.mapping.slice(d).map(g+n),new A(i.rows[h-a],0,0))}p(),f.setSelection(new ae(f.doc.resolve(n+s.positionAt(a,l,o)),f.doc.resolve(n+s.positionAt(u-1,c-1,o)))),e(f)}var dE=ql({ArrowLeft:Qs("horiz",-1),ArrowRight:Qs("horiz",1),ArrowUp:Qs("vert",-1),ArrowDown:Qs("vert",1),"Shift-ArrowLeft":Xs("horiz",-1),"Shift-ArrowRight":Xs("horiz",1),"Shift-ArrowUp":Xs("vert",-1),"Shift-ArrowDown":Xs("vert",1),Backspace:Gs,"Mod-Backspace":Gs,Delete:Gs,"Mod-Delete":Gs});function Ys(t,e,n){return n.eq(t.selection)?!1:(e&&e(t.tr.setSelection(n).scrollIntoView()),!0)}function Qs(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection;if(o instanceof ae)return Ys(n,r,_.near(o.$headCell,e));if(t!="horiz"&&!o.empty)return!1;let s=Ny(i,t,e);if(s==null)return!1;if(t=="horiz")return Ys(n,r,_.near(n.doc.resolve(o.head+e),e));{let a=n.doc.resolve(s),l=yy(a,t,e),c;return l?c=_.near(l,1):e<0?c=_.near(n.doc.resolve(a.before(-1)),-1):c=_.near(n.doc.resolve(a.after(-1)),1),Ys(n,r,c)}}}function Xs(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection,s;if(o instanceof ae)s=o;else{let l=Ny(i,t,e);if(l==null)return!1;s=new ae(n.doc.resolve(l))}let a=yy(s.$headCell,t,e);return a?Ys(n,r,new ae(s.$anchorCell,a)):!1}}function pE(t,e){let n=t.state.doc,r=ei(n.resolve(e));return r?(t.dispatch(t.state.tr.setSelection(new ae(r))),!0):!1}function hE(t,e,n){if(!Ae(t.state))return!1;let r=lE(n),i=t.state.selection;if(i instanceof ae){r||(r={width:1,height:1,rows:[E.from(vu($e(t.state.schema).cell,n))]});let o=i.$anchorCell.node(-1),s=i.$anchorCell.start(-1),a=Z.get(o).rectBetween(i.$anchorCell.pos-s,i.$headCell.pos-s);return r=uE(r,a.right-a.left,a.bottom-a.top),fy(t.state,t.dispatch,s,a,r),!0}else if(r){let o=ea(t.state),s=o.start(-1);return fy(t.state,t.dispatch,s,Z.get(o.node(-1)).findCell(o.pos-s),r),!0}else return!1}function mE(t,e){var n;if(e.button!=0||e.ctrlKey||e.metaKey)return;let r=dy(t,e.target),i;if(e.shiftKey&&t.state.selection instanceof ae)o(t.state.selection.$anchorCell,e),e.preventDefault();else if(e.shiftKey&&r&&(i=ei(t.state.selection.$anchor))!=null&&((n=Mu(t,e))===null||n===void 0?void 0:n.pos)!=i.pos)o(i,e),e.preventDefault();else if(!r)return;function o(l,c){let u=Mu(t,c),f=xn.getState(t.state)==null;if(!u||!Nu(l,u))if(f)u=l;else return;let d=new ae(l,u);if(f||!t.state.selection.eq(d)){let p=t.state.tr.setSelection(d);f&&p.setMeta(xn,l.pos),t.dispatch(p)}}function s(){t.root.removeEventListener("mouseup",s),t.root.removeEventListener("dragstart",s),t.root.removeEventListener("mousemove",a),xn.getState(t.state)!=null&&t.dispatch(t.state.tr.setMeta(xn,-1))}function a(l){let c=l,u=xn.getState(t.state),f;if(u!=null)f=t.state.doc.resolve(u);else if(dy(t,c.target)!=r&&(f=Mu(t,e),!f))return s();f&&o(f,c)}t.root.addEventListener("mouseup",s),t.root.addEventListener("dragstart",s),t.root.addEventListener("mousemove",a)}function Ny(t,e,n){if(!(t.state.selection instanceof z))return null;let{$head:r}=t.state.selection;for(let i=r.depth-1;i>=0;i--){let o=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:o.childCount))return null;if(o.type.spec.tableRole=="cell"||o.type.spec.tableRole=="header_cell"){let s=r.before(i),a=e=="vert"?n>0?"down":"up":n>0?"right":"left";return t.endOfTextblock(a)?s:null}}return null}function dy(t,e){for(;e&&e!=t.dom;e=e.parentNode)if(e.nodeName=="TD"||e.nodeName=="TH")return e;return null}function Mu(t,e){let n=t.posAtCoords({left:e.clientX,top:e.clientY});if(!n)return null;let{inside:r,pos:i}=n;return r>=0&&ei(t.state.doc.resolve(r))||ei(t.state.doc.resolve(i))}var gE=class{constructor(t,e){this.node=t,this.defaultCellMinWidth=e,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${e}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),Au(t,this.colgroup,this.table,e),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,Au(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function Au(t,e,n,r,i,o){let s=0,a=!0,l=e.firstChild,c=t.firstChild;if(c){for(let f=0,d=0;f<c.childCount;f++){let{colspan:p,colwidth:h}=c.child(f).attrs;for(let m=0;m<p;m++,d++){let g=i==d?o:h&&h[m],y=g?g+"px":"";if(s+=g||r,g||(a=!1),l)l.style.width!=y&&(l.style.width=y),l=l.nextSibling;else{let x=document.createElement("col");x.style.width=y,e.appendChild(x)}}}for(;l;){var u;let f=l.nextSibling;(u=l.parentNode)===null||u===void 0||u.removeChild(l),l=f}a?(n.style.width=s+"px",n.style.minWidth=""):(n.style.width="",n.style.minWidth=s+"px")}}var Ye=new te("tableColumnResizing");function Ry({handleWidth:t=5,cellMinWidth:e=25,defaultCellMinWidth:n=100,View:r=gE,lastColumnResizable:i=!0}={}){let o=new Y({key:Ye,state:{init(s,a){var l;let c=(l=o.spec)===null||l===void 0||(l=l.props)===null||l===void 0?void 0:l.nodeViews,u=$e(a.schema).table.name;return r&&c&&(c[u]=(f,d)=>new r(f,n,d)),new yE(-1,!1)},apply(s,a){return a.apply(s)}},props:{attributes:s=>{let a=Ye.getState(s);return a&&a.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(s,a)=>{kE(s,a,t,i)},mouseleave:s=>{bE(s)},mousedown:(s,a)=>{xE(s,a,e,n)}},decorations:s=>{let a=Ye.getState(s);if(a&&a.activeHandle>-1)return EE(s,a.activeHandle)},nodeViews:{}}});return o}var yE=class Zs{constructor(e,n){this.activeHandle=e,this.dragging=n}apply(e){let n=this,r=e.getMeta(Ye);if(r&&r.setHandle!=null)return new Zs(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new Zs(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&e.docChanged){let i=e.mapping.map(n.activeHandle,-1);return Iu(e.doc.resolve(i))||(i=-1),new Zs(i,n.dragging)}return n}};function kE(t,e,n,r){if(!t.editable)return;let i=Ye.getState(t.state);if(i&&!i.dragging){let o=SE(e.target),s=-1;if(o){let{left:a,right:l}=o.getBoundingClientRect();e.clientX-a<=n?s=py(t,e,"left",n):l-e.clientX<=n&&(s=py(t,e,"right",n))}if(s!=i.activeHandle){if(!r&&s!==-1){let a=t.state.doc.resolve(s),l=a.node(-1),c=Z.get(l),u=a.start(-1);if(c.colCount(a.pos-u)+a.nodeAfter.attrs.colspan-1==c.width-1)return}Dy(t,s)}}}function bE(t){if(!t.editable)return;let e=Ye.getState(t.state);e&&e.activeHandle>-1&&!e.dragging&&Dy(t,-1)}function xE(t,e,n,r){var i;if(!t.editable)return!1;let o=(i=t.dom.ownerDocument.defaultView)!==null&&i!==void 0?i:window,s=Ye.getState(t.state);if(!s||s.activeHandle==-1||s.dragging)return!1;let a=t.state.doc.nodeAt(s.activeHandle),l=wE(t,s.activeHandle,a.attrs);t.dispatch(t.state.tr.setMeta(Ye,{setDragging:{startX:e.clientX,startWidth:l}}));function c(f){o.removeEventListener("mouseup",c),o.removeEventListener("mousemove",u);let d=Ye.getState(t.state);d?.dragging&&(CE(t,d.activeHandle,hy(d.dragging,f,n)),t.dispatch(t.state.tr.setMeta(Ye,{setDragging:null})))}function u(f){if(!f.which)return c(f);let d=Ye.getState(t.state);if(d&&d.dragging){let p=hy(d.dragging,f,n);my(t,d.activeHandle,p,r)}}return my(t,s.activeHandle,l,r),o.addEventListener("mouseup",c),o.addEventListener("mousemove",u),e.preventDefault(),!0}function wE(t,e,{colspan:n,colwidth:r}){let i=r&&r[r.length-1];if(i)return i;let o=t.domAtPos(e),s=o.node.childNodes[o.offset].offsetWidth,a=n;if(r)for(let l=0;l<n;l++)r[l]&&(s-=r[l],a--);return s/a}function SE(t){for(;t&&t.nodeName!="TD"&&t.nodeName!="TH";)t=t.classList&&t.classList.contains("ProseMirror")?null:t.parentNode;return t}function py(t,e,n,r){let i=n=="right"?-r:r,o=t.posAtCoords({left:e.clientX+i,top:e.clientY});if(!o)return-1;let{pos:s}=o,a=ei(t.state.doc.resolve(s));if(!a)return-1;if(n=="right")return a.pos;let l=Z.get(a.node(-1)),c=a.start(-1),u=l.map.indexOf(a.pos-c);return u%l.width==0?-1:c+l.map[u-1]}function hy(t,e,n){let r=e.clientX-t.startX;return Math.max(n,t.startWidth+r)}function Dy(t,e){t.dispatch(t.state.tr.setMeta(Ye,{setHandle:e}))}function CE(t,e,n){let r=t.state.doc.resolve(e),i=r.node(-1),o=Z.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1,l=t.state.tr;for(let c=0;c<o.height;c++){let u=c*o.width+a;if(c&&o.map[u]==o.map[u-o.width])continue;let f=o.map[u],d=i.nodeAt(f).attrs,p=d.colspan==1?0:a-o.colCount(f);if(d.colwidth&&d.colwidth[p]==n)continue;let h=d.colwidth?d.colwidth.slice():ME(d.colspan);h[p]=n,l.setNodeMarkup(s+f,null,{...d,colwidth:h})}l.docChanged&&t.dispatch(l)}function my(t,e,n,r){let i=t.state.doc.resolve(e),o=i.node(-1),s=i.start(-1),a=Z.get(o).colCount(i.pos-s)+i.nodeAfter.attrs.colspan-1,l=t.domAtPos(i.start(-1)).node;for(;l&&l.nodeName!="TABLE";)l=l.parentNode;l&&Au(o,l.firstChild,l,r,a,n)}function ME(t){return Array(t).fill(0)}function EE(t,e){let n=[],r=t.doc.resolve(e),i=r.node(-1);if(!i)return re.empty;let o=Z.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1;for(let c=0;c<o.height;c++){let u=a+c*o.width;if((a==o.width-1||o.map[u]!=o.map[u+1])&&(c==0||o.map[u]!=o.map[u-o.width])){var l;let f=o.map[u],d=s+f+i.nodeAt(f).nodeSize-1,p=document.createElement("div");p.className="column-resize-handle",!((l=Ye.getState(t))===null||l===void 0)&&l.dragging&&n.push(se.node(s+f,s+f+i.nodeAt(f).nodeSize,{class:"column-resize-dragging"})),n.push(se.widget(d,p))}}return re.create(t.doc,n)}function Oy({allowTableNodeSelection:t=!1}={}){return new Y({key:xn,state:{init(){return null},apply(e,n){let r=e.getMeta(xn);if(r!=null)return r==-1?null:r;if(n==null||!e.docChanged)return n;let{deleted:i,pos:o}=e.mapping.mapResult(n);return i?null:o}},props:{decorations:jM,handleDOMEvents:{mousedown:mE},createSelectionBetween(e){return xn.getState(e.state)!=null?e.state.selection:null},handleTripleClick:pE,handleKeyDown:dE,handlePaste:hE},appendTransaction(e,n,r){return UM(r,GM(r,n),t)}})}var oa=typeof navigator<"u"?navigator:null,Ou=oa&&oa.userAgent||"",TE=/Edge\/(\d+)/.exec(Ou),IE=/MSIE \d/.exec(Ou),vE=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Ou),AE=!!(IE||vE||TE),NE=!AE&&!!oa&&/Apple Computer/.test(oa.vendor),Ly=new te("safari-ime-span"),Du=!1,RE={key:Ly,props:{decorations:DE,handleDOMEvents:{compositionstart:()=>{Du=!0},compositionend:()=>{Du=!1}}}};function DE(t){let{$from:e,$to:n,to:r}=t.selection;if(Du&&e.sameParent(n)){let i=se.widget(r,OE,{ignoreSelection:!0,key:"safari-ime-span"});return re.create(t.doc,[i])}}function OE(t){let e=t.dom.ownerDocument.createElement("span");return e.className="ProseMirror-safari-ime-span",e}var By=new Y(NE?RE:{key:Ly});function Lu(t,e){let n=String(t);if(typeof e!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(e);for(;i!==-1;)r++,i=n.indexOf(e,i+e.length);return r}function Bu(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Pu(t,e,n){let i=sn((n||{}).ignore||[]),o=LE(e),s=-1;for(;++s<o.length;)On(t,"text",a);function a(c,u){let f=-1,d;for(;++f<u.length;){let p=u[f],h=d?d.children:void 0;if(i(p,h?h.indexOf(p):void 0,d))return;d=p}if(d)return l(c,u)}function l(c,u){let f=u[u.length-1],d=o[s][0],p=o[s][1],h=0,g=f.children.indexOf(c),y=!1,x=[];d.lastIndex=0;let C=d.exec(c.value);for(;C;){let I=C.index,v={index:C.index,input:C.input,stack:[...u,c]},w=p(...C,v);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?d.lastIndex=I+1:(h!==I&&x.push({type:"text",value:c.value.slice(h,I)}),Array.isArray(w)?x.push(...w):w&&x.push(w),h=I+C[0].length,y=!0),!d.global)break;C=d.exec(c.value)}return y?(h<c.value.length&&x.push({type:"text",value:c.value.slice(h)}),f.children.splice(g,1,...x)):x=[c],g+x.length}}function LE(t){let e=[];if(!Array.isArray(t))throw new TypeError("Expected find and replace tuple or list of tuples");let n=!t[0]||Array.isArray(t[0])?t:[t],r=-1;for(;++r<n.length;){let i=n[r];e.push([BE(i[0]),PE(i[1])])}return e}function BE(t){return typeof t=="string"?new RegExp(Bu(t),"g"):t}function PE(t){return typeof t=="function"?t:function(){return t}}var Fu="phrasing",zu=["autolink","link","image","label"];function $u(){return{transforms:[VE],enter:{literalAutolink:FE,literalAutolinkEmail:_u,literalAutolinkHttp:_u,literalAutolinkWww:_u},exit:{literalAutolink:HE,literalAutolinkEmail:$E,literalAutolinkHttp:zE,literalAutolinkWww:_E}}}function Hu(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Fu,notInConstruct:zu},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Fu,notInConstruct:zu},{character:":",before:"[ps]",after:"\\/",inConstruct:Fu,notInConstruct:zu}]}}function FE(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function _u(t){this.config.enter.autolinkProtocol.call(this,t)}function zE(t){this.config.exit.autolinkProtocol.call(this,t)}function _E(t){this.config.exit.data.call(this,t);let e=this.stack[this.stack.length-1];e.type,e.url="http://"+this.sliceSerialize(t)}function $E(t){this.config.exit.autolinkEmail.call(this,t)}function HE(t){this.exit(t)}function VE(t){Pu(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,WE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,jE]],{ignore:["link","linkReference"]})}function WE(t,e,n,r,i){let o="";if(!Py(i)||(/^w/i.test(e)&&(n=e+n,e="",o="http://"),!qE(n)))return!1;let s=KE(n+r);if(!s[0])return!1;let a={type:"link",title:null,url:o+e+s[0],children:[{type:"text",value:e+s[0]}]};return s[1]?[a,{type:"text",value:s[1]}]:a}function jE(t,e,n,r){return!Py(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+e+"@"+n,children:[{type:"text",value:e+"@"+n}]}}function qE(t){let e=t.split(".");return!(e.length<2||e[e.length-1]&&(/_/.test(e[e.length-1])||!/[a-zA-Z\d]/.test(e[e.length-1]))||e[e.length-2]&&(/_/.test(e[e.length-2])||!/[a-zA-Z\d]/.test(e[e.length-2])))}function KE(t){let e=/[!"&'),.:;<>?\]}]+$/.exec(t);if(!e)return[t,void 0];t=t.slice(0,e.index);let n=e[0],r=n.indexOf(")"),i=Lu(t,"("),o=Lu(t,")");for(;r!==-1&&i>o;)t+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),o++;return[t,n]}function Py(t,e){let n=t.input.charCodeAt(t.index-1);return(t.index===0||Tt(n)||In(n))&&(!e||n!==47)}Fy.peek=tT;function UE(){this.buffer()}function JE(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function GE(){this.buffer()}function QE(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function XE(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(t)).toLowerCase(),n.label=e}function YE(t){this.exit(t)}function ZE(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(t)).toLowerCase(),n.label=e}function eT(t){this.exit(t)}function tT(){return"["}function Fy(t,e,n,r){let i=n.createTracker(r),o=i.move("[^"),s=n.enter("footnoteReference"),a=n.enter("reference");return o+=i.move(n.safe(n.associationId(t),{after:"]",before:o})),a(),s(),o+=i.move("]"),o}function Vu(){return{enter:{gfmFootnoteCallString:UE,gfmFootnoteCall:JE,gfmFootnoteDefinitionLabelString:GE,gfmFootnoteDefinition:QE},exit:{gfmFootnoteCallString:XE,gfmFootnoteCall:YE,gfmFootnoteDefinitionLabelString:ZE,gfmFootnoteDefinition:eT}}}function Wu(t){let e=!1;return t&&t.firstLineBlank&&(e=!0),{handlers:{footnoteDefinition:n,footnoteReference:Fy},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,o,s){let a=o.createTracker(s),l=a.move("[^"),c=o.enter("footnoteDefinition"),u=o.enter("label");return l+=a.move(o.safe(o.associationId(r),{before:l,after:"]"})),u(),l+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),l+=a.move((e?` +`):e.addNode("break")}}}));M(ir.node,{displayName:"NodeSchema<hardbreak>",group:"Hardbreak"});M(ir.ctx,{displayName:"NodeSchemaCtx<hardbreak>",group:"Hardbreak"});var tu=P("InsertHardbreak",t=>()=>(e,n)=>{let{selection:r,tr:i}=e;if(!(r instanceof z))return!1;if(r.empty){let o=r.$from.node();if(o.childCount>0&&o.lastChild?.type.name==="hardbreak")return n?.(i.replaceRangeWith(r.to-1,r.to,e.schema.node("paragraph")).setSelection(_.near(i.doc.resolve(r.to))).scrollIntoView()),!0}return n?.(i.setMeta("hardbreak",!0).replaceSelectionWith(ir.type(t).create()).scrollIntoView()),!0});M(tu,{displayName:"Command<insertHardbreakCommand>",group:"Hardbreak"});var nu=_e("hardbreakKeymap",{InsertHardbreak:{shortcuts:"Shift-Enter",command:t=>{let e=t.get(G);return()=>e.call(tu.key)}}});M(nu.ctx,{displayName:"KeymapCtx<hardbreak>",group:"Hardbreak"});M(nu.shortcuts,{displayName:"Keymap<hardbreak>",group:"Hardbreak"});var ru=ut("hr");M(ru,{displayName:"Attr<hr>",group:"Hr"});var ao=ne("hr",t=>({group:"block",parseDOM:[{tag:"hr"}],toDOM:e=>["hr",t.get(ru.key)(e)],parseMarkdown:{match:({type:e})=>e==="thematicBreak",runner:(e,n,r)=>{e.addNode(r)}},toMarkdown:{match:e=>e.type.name==="hr",runner:e=>{e.addNode("thematicBreak")}}}));M(ao.node,{displayName:"NodeSchema<hr>",group:"Hr"});M(ao.ctx,{displayName:"NodeSchemaCtx<hr>",group:"Hr"});var Kg=fe(t=>new be(/^(?:---|___\s|\*\*\*\s)$/,(e,n,r,i)=>{let{tr:o}=e;return n[0]&&o.replaceWith(r-1,i,ao.type(t).create()),o}));M(Kg,{displayName:"InputRule<insertHrInputRule>",group:"Hr"});var Ug=P("InsertHr",t=>()=>(e,n)=>{if(!n)return!0;let r=bt.node.type(t).create(),{tr:i,selection:o}=e,{from:s}=o,a=ao.type(t).create();if(!a)return!0;let l=i.replaceSelectionWith(a).insert(s,r),c=_.findFrom(l.doc.resolve(s),1,!0);return c&&n(l.setSelection(c).scrollIntoView()),!0});M(Ug,{displayName:"Command<insertHrCommand>",group:"Hr"});var iu=ut("bulletList");M(iu,{displayName:"Attr<bulletList>",group:"BulletList"});var Qr=ne("bullet_list",t=>({content:"listItem+",group:"block",attrs:{spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ul",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{spread:e.dataset.spread==="true"}}}],toDOM:e=>["ul",{...t.get(iu.key)(e),"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"false";e.openNode(r,{spread:i}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="bullet_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!1,spread:n.attrs.spread}).next(n.content).closeNode()}}}));M(Qr.node,{displayName:"NodeSchema<bulletList>",group:"BulletList"});M(Qr.ctx,{displayName:"NodeSchemaCtx<bulletList>",group:"BulletList"});var Jg=fe(t=>ys(/^\s*([-+*])\s$/,Qr.type(t)));M(Jg,{displayName:"InputRule<wrapInBulletListInputRule>",group:"BulletList"});var ou=P("WrapInBulletList",t=>()=>gs(Qr.type(t)));M(ou,{displayName:"Command<wrapInBulletListCommand>",group:"BulletList"});var su=_e("bulletListKeymap",{WrapInBulletList:{shortcuts:"Mod-Alt-8",command:t=>{let e=t.get(G);return()=>e.call(ou.key)}}});M(su.ctx,{displayName:"KeymapCtx<bulletListKeymap>",group:"BulletList"});M(su.shortcuts,{displayName:"Keymap<bulletListKeymap>",group:"BulletList"});var au=ut("orderedList");M(au,{displayName:"Attr<orderedList>",group:"OrderedList"});var Xr=ne("ordered_list",t=>({content:"listItem+",group:"block",attrs:{order:{default:1,validate:"number"},spread:{default:!1,validate:"boolean"}},parseDOM:[{tag:"ol",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{spread:e.dataset.spread,order:e.hasAttribute("start")?Number(e.getAttribute("start")):1}}}],toDOM:e=>["ol",{...t.get(au.key)(e),...e.attrs.order===1?{}:{start:e.attrs.order},"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e,ordered:n})=>e==="list"&&!!n,runner:(e,n,r)=>{let i=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{spread:i,order:n.start??1}).next(n.children).closeNode()}},toMarkdown:{match:e=>e.type.name==="ordered_list",runner:(e,n)=>{e.openNode("list",void 0,{ordered:!0,start:n.attrs.order??1,spread:n.attrs.spread==="true"}),e.next(n.content),e.closeNode()}}}));M(Xr.node,{displayName:"NodeSchema<orderedList>",group:"OrderedList"});M(Xr.ctx,{displayName:"NodeSchemaCtx<orderedList>",group:"OrderedList"});var Gg=fe(t=>ys(/^\s*(\d+)\.\s$/,Xr.type(t),e=>({order:Number(e[1])}),(e,n)=>n.childCount+n.attrs.order===Number(e[1])));M(Gg,{displayName:"InputRule<wrapInOrderedListInputRule>",group:"OrderedList"});var lu=P("WrapInOrderedList",t=>()=>gs(Xr.type(t)));M(lu,{displayName:"Command<wrapInOrderedListCommand>",group:"OrderedList"});var cu=_e("orderedListKeymap",{WrapInOrderedList:{shortcuts:"Mod-Alt-7",command:t=>{let e=t.get(G);return()=>e.call(lu.key)}}});M(cu.ctx,{displayName:"KeymapCtx<orderedList>",group:"OrderedList"});M(cu.shortcuts,{displayName:"Keymap<orderedList>",group:"OrderedList"});var uu=ut("listItem");M(uu,{displayName:"Attr<listItem>",group:"ListItem"});var At=ne("list_item",t=>({group:"listItem",content:"paragraph block*",attrs:{label:{default:"\u2022",validate:"string"},listType:{default:"bullet",validate:"string"},spread:{default:!0,validate:"boolean"}},defining:!0,parseDOM:[{tag:"li",getAttrs:e=>{if(!(e instanceof HTMLElement))throw it(e);return{label:e.dataset.label,listType:e.dataset.listType,spread:e.dataset.spread==="true"}}}],toDOM:e=>["li",{...t.get(uu.key)(e),"data-label":e.attrs.label,"data-list-type":e.attrs.listType,"data-spread":e.attrs.spread},0],parseMarkdown:{match:({type:e})=>e==="listItem",runner:(e,n,r)=>{let i=n.label!=null?`${n.label}.`:"\u2022",o=n.label!=null?"ordered":"bullet",s=n.spread!=null?`${n.spread}`:"true";e.openNode(r,{label:i,listType:o,spread:s}),e.next(n.children),e.closeNode()}},toMarkdown:{match:e=>e.type.name==="list_item",runner:(e,n)=>{e.openNode("listItem",void 0,{spread:n.attrs.spread}),e.next(n.content),e.closeNode()}}}));M(At.node,{displayName:"NodeSchema<listItem>",group:"ListItem"});M(At.ctx,{displayName:"NodeSchemaCtx<listItem>",group:"ListItem"});var fu=P("SinkListItem",t=>()=>Rg(At.type(t)));M(fu,{displayName:"Command<sinkListItemCommand>",group:"ListItem"});var du=P("LiftListItem",t=>()=>Ng(At.type(t)));M(du,{displayName:"Command<liftListItemCommand>",group:"ListItem"});var pu=P("SplitListItem",t=>()=>Ag(At.type(t)));M(pu,{displayName:"Command<splitListItemCommand>",group:"ListItem"});function gM(t){return(e,n,r)=>{let{selection:i}=e;if(!(i instanceof z))return!1;let{empty:o,$from:s}=i;return!o||s.parentOffset!==0||s.node(-1).type!==At.type(t)?!1:Ol(e,n,r)}}var hu=P("LiftFirstListItem",t=>()=>gM(t));M(hu,{displayName:"Command<liftFirstListItemCommand>",group:"ListItem"});var mu=_e("listItemKeymap",{NextListItem:{shortcuts:"Enter",command:t=>{let e=t.get(G);return()=>e.call(pu.key)}},SinkListItem:{shortcuts:["Tab","Mod-]"],command:t=>{let e=t.get(G);return()=>e.call(fu.key)}},LiftListItem:{shortcuts:["Shift-Tab","Mod-["],command:t=>{let e=t.get(G);return()=>e.call(du.key)}},LiftFirstListItem:{shortcuts:["Backspace","Delete"],command:t=>{let e=t.get(G);return()=>e.call(hu.key)}}});M(mu.ctx,{displayName:"KeymapCtx<listItem>",group:"ListItem"});M(mu.shortcuts,{displayName:"Keymap<listItem>",group:"ListItem"});var Qg=js("text",()=>({group:"inline",parseMarkdown:{match:({type:t})=>t==="text",runner:(t,e)=>{t.addText(e.value)}},toMarkdown:{match:t=>t.type.name==="text",runner:(t,e)=>{t.addNode("text",void 0,e.text)}}}));M(Qg,{displayName:"NodeSchema<text>",group:"Text"});var gu=ut("html");M(gu,{displayName:"Attr<html>",group:"Html"});var yu=ne("html",t=>({atom:!0,group:"inline",inline:!0,attrs:{value:{default:"",validate:"string"}},toDOM:e=>{let n=document.createElement("span"),r={...t.get(gu.key)(e),"data-value":e.attrs.value,"data-type":"html"};return n.textContent=e.attrs.value,["span",r,e.attrs.value]},parseDOM:[{tag:'span[data-type="html"]',getAttrs:e=>({value:e.dataset.value??""})}],parseMarkdown:{match:({type:e})=>e==="html",runner:(e,n,r)=>{e.addNode(r,{value:n.value})}},toMarkdown:{match:e=>e.type.name==="html",runner:(e,n)=>{e.addNode("html",void 0,n.attrs.value)}}}));M(yu.node,{displayName:"NodeSchema<html>",group:"Html"});M(yu.ctx,{displayName:"NodeSchemaCtx<html>",group:"Html"});var yM=[$g,Vc,bt,Js,qc,or,Ks,ir,Jc,oo,Xc,so,ru,ao,eu,Gr,iu,Qr,au,Xr,uu,At,Dc,Jr,Bc,io,zc,bn,Hc,Ur,gu,yu,Qg].flat(),kM=[Vg,Jg,Gg,Wg,Kg,Hg].flat(),bM=[Lg,Bg,Fg,Pg],xM=P("IsMarkSelected",()=>t=>e=>{if(!t)return!1;let{doc:n,selection:r}=e;return n.rangeHasMark(r.from,r.to,t)}),wM=P("IsNoteSelected",()=>t=>e=>t?jh(e,t).hasNode:!1),SM=P("ClearTextInCurrentBlock",()=>()=>(t,e)=>{let n=t.tr,{$from:r,$to:i}=n.selection,{pos:o}=r,{pos:s}=i,a=o-r.node().content.size;return a<0?!1:(n=n.deleteRange(a,s),e?.(n),!0)}),CM=P("SetBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr,{from:s,to:a}=o.selection;try{o.setBlockType(s,a,r,i)}catch{return!1}return n?.(o),!0}),MM=P("WrapInBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let{$from:s,$to:a}=o.selection,l=s.blockRange(a),c=l&&Hn(l,r,i);if(!c)return!1;o=o.wrap(l,c)}catch{return!1}return n?.(o),!0}),EM=P("AddBlockType",()=>t=>(e,n)=>{let{nodeType:r,attrs:i=null}=t??{};if(!r)return!1;let o=e.tr;try{let s=r instanceof Ve?r:r.createAndFill(i);if(!s)return!1;o.replaceSelectionWith(s)}catch{return!1}return n?.(o),!0}),TM=P("SelectTextNearPos",()=>t=>(e,n)=>{let{pos:r}=t??{};if(r==null)return!1;let i=(s,a,l)=>Math.min(Math.max(s,a),l),o=e.tr;try{let s=e.doc.resolve(i(r,0,e.doc.content.size));o.setSelection(z.near(s))}catch{return!1}return n?.(o.scrollIntoView()),!0}),IM=[Wc,Gc,kn,Kc,Yc,tu,Ug,jg,qg,lu,ou,fu,pu,du,hu,Oc,_c,Pc,zg,_g,xM,wM,SM,CM,MM,EM,TM],vM=[Qc,Zc,nu,Uc,mu,cu,su,jc,Lc,$c,Fc].flat(),ku=Xe("remarkAddOrderInList",()=>()=>t=>{pt(t,"list",e=>{if(e.ordered){let n=e.start??1;e.children.forEach((r,i)=>{r.label=i+n})}})});M(ku.plugin,{displayName:"Remark<remarkAddOrderInListPlugin>",group:"Remark"});M(ku.options,{displayName:"RemarkConfig<remarkAddOrderInListPlugin>",group:"Remark"});var bu=Xe("remarkLineBreak",()=>()=>t=>{let e=/[\t ]*(?:\r?\n|\r)/g;pt(t,"text",(n,r,i)=>{if(!n.value||typeof n.value!="string")return;let o=[],s=0;e.lastIndex=0;let a=e.exec(n.value);for(;a;){let l=a.index;s!==l&&o.push({type:"text",value:n.value.slice(s,l)}),o.push({type:"break",data:{isInline:!0}}),s=l+a[0].length,a=e.exec(n.value)}if(o.length>0&&i&&typeof r=="number")return s<n.value.length&&o.push({type:"text",value:n.value.slice(s)}),i.children.splice(r,1,...o),r+o.length})});M(bu.plugin,{displayName:"Remark<remarkLineBreak>",group:"Remark"});M(bu.options,{displayName:"RemarkConfig<remarkLineBreak>",group:"Remark"});var xu=Xe("remarkInlineLink",()=>qs);M(xu.plugin,{displayName:"Remark<remarkInlineLinkPlugin>",group:"Remark"});M(xu.options,{displayName:"RemarkConfig<remarkInlineLinkPlugin>",group:"Remark"});var AM=t=>!!t.children,NM=t=>t.type==="html";function RM(t,e){return n(t,0,null)[0];function n(r,i,o){if(AM(r)){let s=[];for(let a=0,l=r.children.length;a<l;a++){let c=r.children[a];if(c){let u=n(c,a,r);if(u)for(let f=0,d=u.length;f<d;f++){let p=u[f];p&&s.push(p)}}}r.children=s}return e(r,i,o)}}var DM=["root","blockquote","listItem"],wu=Xe("remarkHTMLTransformer",()=>()=>t=>{RM(t,(e,n,r)=>NM(e)?(r&&DM.includes(r.type)&&(e.children=[{...e}],delete e.value,e.type="paragraph"),[e]):[e])});M(wu.plugin,{displayName:"Remark<remarkHtmlTransformer>",group:"Remark"});M(wu.options,{displayName:"RemarkConfig<remarkHtmlTransformer>",group:"Remark"});var Su=Xe("remarkMarker",()=>()=>(t,e)=>{let n=r=>e.value.charAt(r.position.start.offset);pt(t,r=>["strong","emphasis"].includes(r.type),r=>{r.marker=n(r)})});M(Su.plugin,{displayName:"Remark<remarkMarker>",group:"Remark"});M(Su.options,{displayName:"RemarkConfig<remarkMarker>",group:"Remark"});var Xg=Ce(()=>{let t=!1,e=new Y({key:new te("MILKDOWN_INLINE_NODES_CURSOR"),state:{init(){return!1},apply(n){if(!n.selection.empty)return!1;let r=n.selection.$from,i=r.nodeBefore,o=r.nodeAfter;return!!(i&&o&&i.isInline&&!i.isText&&o.isInline&&!o.isText)}},props:{handleDOMEvents:{compositionend:(n,r)=>t?(t=!1,requestAnimationFrame(()=>{if(e.getState(n.state)){let i=n.state.selection.from;r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i))}}),!0):!1,compositionstart:n=>(e.getState(n.state)&&(t=!0),!1),beforeinput:(n,r)=>{if(e.getState(n.state)&&r instanceof InputEvent&&r.data&&!t){let i=n.state.selection.from;return r.preventDefault(),n.dispatch(n.state.tr.insertText(r.data||"",i)),!0}return!1}},decorations(n){if(e.getState(n)){let r=n.selection.$from.pos,i=document.createElement("span"),o=se.widget(r,i,{side:-1}),s=document.createElement("span"),a=se.widget(r,s);return setTimeout(()=>{i.contentEditable="true",s.contentEditable="true"}),re.create(n.doc,[o,a])}return re.empty}}});return e});M(Xg,{displayName:"Prose<inlineNodesCursorPlugin>",group:"Prose"});var Yg=Ce(t=>new Y({key:new te("MILKDOWN_HARDBREAK_MARKS"),appendTransaction:(e,n,r)=>{if(!e.length)return;let[i]=e;if(!i)return;let[o]=i.steps;if(i.getMeta("hardbreak")){if(!(o instanceof pe))return;let{from:s}=o;return r.tr.setNodeMarkup(s,ir.type(t),void 0,[])}if(o instanceof _n){let s=r.tr,{from:a,to:l}=o;return r.doc.nodesBetween(a,l,(c,u)=>{c.type===ir.type(t)&&(s=s.setNodeMarkup(u,ir.type(t),void 0,[]))}),s}}}));M(Yg,{displayName:"Prose<hardbreakClearMarkPlugin>",group:"Prose"});var Cu=Qe(["table","code_block"],"hardbreakFilterNodes");M(Cu,{displayName:"Ctx<hardbreakFilterNodes>",group:"Prose"});var Zg=Ce(t=>{let e=t.get(Cu.key);return new Y({key:new te("MILKDOWN_HARDBREAK_FILTER"),filterTransaction:(n,r)=>{let i=n.getMeta("hardbreak"),[o]=n.steps;if(i&&o){let{from:s}=o,a=r.doc.resolve(s),l=a.depth,c=!0;for(;l>0;)e.includes(a.node(l).type.name)&&(c=!1),l--;return c}return!0}})});M(Zg,{displayName:"Prose<hardbreakFilterPlugin>",group:"Prose"});var ey=Ce(t=>{let e=new te("MILKDOWN_HEADING_ID"),n=r=>{if(r.composing)return;let i=t.get(Js.key),o=r.state.tr.setMeta("addToHistory",!1),s=!1,a={};r.state.doc.descendants((l,c)=>{if(l.type===or.type(t)){if(l.textContent.trim().length===0)return;let u=l.attrs,f=i(l);a[f]?(a[f]+=1,f+=`-#${a[f]}`):a[f]=1,u.id!==f&&(s=!0,o.setMeta(e,!0).setNodeMarkup(c,void 0,{...u,id:f}))}}),s&&r.dispatch(o)};return new Y({key:e,view:r=>(n(r),{update:(i,o)=>{i.state.doc.eq(o.doc)||n(i)}})})});M(ey,{displayName:"Prose<syncHeadingIdPlugin>",group:"Prose"});var ty=Ce(t=>{let e=(n,r,i)=>{if(!i.selection||n.some(f=>f.getMeta("addToHistory")===!1||!f.isGeneric))return null;let o=Xr.type(t),s=Qr.type(t),a=At.type(t),l=(f,d,p=1)=>{let h=!1,m=`${d+p}.`;return f.label!==m&&(f.label=m,h=!0),h},c=i.tr,u=!1;return i.doc.descendants((f,d,p,h)=>{if(f.type===s){let m=f.maybeChild(0);m?.type===a&&m.attrs.listType==="ordered"&&(u=!0,c.setNodeMarkup(d,o,{spread:"true"}),f.descendants((g,y,x,C)=>{if(g.type===a){let I={...g.attrs};l(I,C)&&(c=c.setNodeMarkup(y,void 0,I))}return!1}))}else if(f.type===a&&p?.type===o){let m={...f.attrs},g=!1;m.listType!=="ordered"&&(m.listType="ordered",g=!0),p?.maybeChild(0)&&(g=l(m,h,p?.attrs.order??1)),g&&(c=c.setNodeMarkup(d,void 0,m),u=!0)}}),u?c.setMeta("addToHistory",!1):null};return new Y({key:new te("MILKDOWN_KEEP_LIST_ORDER"),appendTransaction:e})});M(ty,{displayName:"Prose<syncListOrderPlugin>",group:"Prose"});var OM=[Yg,Cu,Zg,Xg,ku,xu,bu,wu,Su,Us,ey,ty].flat(),ny=[yM,kM,bM,IM,vM,OM].flat();var Eu,Tu;if(typeof WeakMap<"u"){let t=new WeakMap;Eu=e=>t.get(e),Tu=(e,n)=>(t.set(e,n),n)}else{let t=[],n=0;Eu=r=>{for(let i=0;i<t.length;i+=2)if(t[i]==r)return t[i+1]},Tu=(r,i)=>(n==10&&(n=0),t[n++]=r,t[n++]=i)}var Z=class{constructor(t,e,n,r){this.width=t,this.height=e,this.map=n,this.problems=r}findCell(t){for(let e=0;e<this.map.length;e++){let n=this.map[e];if(n!=t)continue;let r=e%this.width,i=e/this.width|0,o=r+1,s=i+1;for(let a=1;o<this.width&&this.map[e+a]==n;a++)o++;for(let a=1;s<this.height&&this.map[e+this.width*a]==n;a++)s++;return{left:r,top:i,right:o,bottom:s}}throw new RangeError(`No cell with offset ${t} found`)}colCount(t){for(let e=0;e<this.map.length;e++)if(this.map[e]==t)return e%this.width;throw new RangeError(`No cell with offset ${t} found`)}nextCell(t,e,n){let{left:r,right:i,top:o,bottom:s}=this.findCell(t);return e=="horiz"?(n<0?r==0:i==this.width)?null:this.map[o*this.width+(n<0?r-1:i)]:(n<0?o==0:s==this.height)?null:this.map[r+this.width*(n<0?o-1:s)]}rectBetween(t,e){let{left:n,right:r,top:i,bottom:o}=this.findCell(t),{left:s,right:a,top:l,bottom:c}=this.findCell(e);return{left:Math.min(n,s),top:Math.min(i,l),right:Math.max(r,a),bottom:Math.max(o,c)}}cellsInRect(t){let e=[],n={};for(let r=t.top;r<t.bottom;r++)for(let i=t.left;i<t.right;i++){let o=r*this.width+i,s=this.map[o];n[s]||(n[s]=!0,!(i==t.left&&i&&this.map[o-1]==s||r==t.top&&r&&this.map[o-this.width]==s)&&e.push(s))}return e}positionAt(t,e,n){for(let r=0,i=0;;r++){let o=i+n.child(r).nodeSize;if(r==t){let s=e+t*this.width,a=(t+1)*this.width;for(;s<a&&this.map[s]<i;)s++;return s==a?o-1:this.map[s]}i=o}}static get(t){return Eu(t)||Tu(t,LM(t))}};function LM(t){if(t.type.spec.tableRole!="table")throw new RangeError("Not a table node: "+t.type.name);let e=BM(t),n=t.childCount,r=[],i=0,o=null,s=[];for(let c=0,u=e*n;c<u;c++)r[c]=0;for(let c=0,u=0;c<n;c++){let f=t.child(c);u++;for(let h=0;;h++){for(;i<r.length&&r[i]!=0;)i++;if(h==f.childCount)break;let m=f.child(h),{colspan:g,rowspan:y,colwidth:x}=m.attrs;for(let C=0;C<y;C++){if(C+c>=n){(o||(o=[])).push({type:"overlong_rowspan",pos:u,n:y-C});break}let I=i+C*e;for(let v=0;v<g;v++){r[I+v]==0?r[I+v]=u:(o||(o=[])).push({type:"collision",row:c,pos:u,n:g-v});let w=x&&x[v];if(w){let N=(I+v)%e*2,O=s[N];O==null||O!=w&&s[N+1]==1?(s[N]=w,s[N+1]=1):O==w&&s[N+1]++}}}i+=g,u+=m.nodeSize}let d=(c+1)*e,p=0;for(;i<d;)r[i++]==0&&p++;p&&(o||(o=[])).push({type:"missing",row:c,n:p}),u++}(e===0||n===0)&&(o||(o=[])).push({type:"zero_sized"});let a=new Z(e,n,r,o),l=!1;for(let c=0;!l&&c<s.length;c+=2)s[c]!=null&&s[c+1]<n&&(l=!0);return l&&PM(a,s,t),a}function BM(t){let e=-1,n=!1;for(let r=0;r<t.childCount;r++){let i=t.child(r),o=0;if(n)for(let s=0;s<r;s++){let a=t.child(s);for(let l=0;l<a.childCount;l++){let c=a.child(l);s+c.attrs.rowspan>r&&(o+=c.attrs.colspan)}}for(let s=0;s<i.childCount;s++){let a=i.child(s);o+=a.attrs.colspan,a.attrs.rowspan>1&&(n=!0)}e==-1?e=o:e!=o&&(e=Math.max(e,o))}return e}function PM(t,e,n){t.problems||(t.problems=[]);let r={};for(let i=0;i<t.map.length;i++){let o=t.map[i];if(r[o])continue;r[o]=!0;let s=n.nodeAt(o);if(!s)throw new RangeError(`No cell with offset ${o} found`);let a=null,l=s.attrs;for(let c=0;c<l.colspan;c++){let u=e[(i+c)%t.width*2];u!=null&&(!l.colwidth||l.colwidth[c]!=u)&&((a||(a=FM(l)))[c]=u)}a&&t.problems.unshift({type:"colwidth mismatch",pos:o,colwidth:a})}}function FM(t){if(t.colwidth)return t.colwidth.slice();let e=[];for(let n=0;n<t.colspan;n++)e.push(0);return e}function ry(t,e){if(typeof t=="string")return{};let n=t.getAttribute("data-colwidth"),r=n&&/^\d+(,\d+)*$/.test(n)?n.split(",").map(s=>Number(s)):null,i=Number(t.getAttribute("colspan")||1),o={colspan:i,rowspan:Number(t.getAttribute("rowspan")||1),colwidth:r&&r.length==i?r:null};for(let s in e){let a=e[s].getFromDOM,l=a&&a(t);l!=null&&(o[s]=l)}return o}function iy(t,e){let n={};t.attrs.colspan!=1&&(n.colspan=t.attrs.colspan),t.attrs.rowspan!=1&&(n.rowspan=t.attrs.rowspan),t.attrs.colwidth&&(n["data-colwidth"]=t.attrs.colwidth.join(","));for(let r in e){let i=e[r].setDOMAttr;i&&i(t.attrs[r],n)}return n}function zM(t){if(t!==null){if(!Array.isArray(t))throw new TypeError("colwidth must be null or an array");for(let e of t)if(typeof e!="number")throw new TypeError("colwidth must be null or an array of numbers")}}function gy(t){let e=t.cellAttributes||{},n={colspan:{default:1,validate:"number"},rowspan:{default:1,validate:"number"},colwidth:{default:null,validate:zM}};for(let r in e)n[r]={default:e[r].default,validate:e[r].validate};return{table:{content:"table_row+",tableRole:"table",isolating:!0,group:t.tableGroup,parseDOM:[{tag:"table"}],toDOM(){return["table",["tbody",0]]}},table_row:{content:"(table_cell | table_header)*",tableRole:"row",parseDOM:[{tag:"tr"}],toDOM(){return["tr",0]}},table_cell:{content:t.cellContent,attrs:n,tableRole:"cell",isolating:!0,parseDOM:[{tag:"td",getAttrs:r=>ry(r,e)}],toDOM(r){return["td",iy(r,e),0]}},table_header:{content:t.cellContent,attrs:n,tableRole:"header_cell",isolating:!0,parseDOM:[{tag:"th",getAttrs:r=>ry(r,e)}],toDOM(r){return["th",iy(r,e),0]}}}}function $e(t){let e=t.cached.tableNodeTypes;if(!e){e=t.cached.tableNodeTypes={};for(let n in t.nodes){let r=t.nodes[n],i=r.spec.tableRole;i&&(e[i]=r)}}return e}var xn=new te("selectingCells");function ei(t){for(let e=t.depth-1;e>0;e--)if(t.node(e).type.spec.tableRole=="row")return t.node(0).resolve(t.before(e+1));return null}function Ae(t){let e=t.selection.$head;for(let n=e.depth;n>0;n--)if(e.node(n).type.spec.tableRole=="row")return!0;return!1}function ea(t){let e=t.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;let n=ei(e.$head)||_M(e.$head);if(n)return n;throw new RangeError(`No cell found around position ${e.head}`)}function _M(t){for(let e=t.nodeAfter,n=t.pos;e;e=e.firstChild,n++){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n)}for(let e=t.nodeBefore,n=t.pos;e;e=e.lastChild,n--){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return t.doc.resolve(n-e.nodeSize)}}function Iu(t){return t.parent.type.spec.tableRole=="row"&&!!t.nodeAfter}function $M(t){return t.node(0).resolve(t.pos+t.nodeAfter.nodeSize)}function Nu(t,e){return t.depth==e.depth&&t.pos>=e.start(-1)&&t.pos<=e.end(-1)}function yy(t,e,n){let r=t.node(-1),i=Z.get(r),o=t.start(-1),s=i.nextCell(t.pos-o,e,n);return s==null?null:t.node(0).resolve(o+s)}function sr(t,e,n=1){let r={...t,colspan:t.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,n),r.colwidth.some(i=>i>0)||(r.colwidth=null)),r}function HM(t,e,n=1){let r={...t,colspan:t.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let i=0;i<n;i++)r.colwidth.splice(e,0,0)}return r}function VM(t,e,n){let r=$e(e.type.schema).header_cell;for(let i=0;i<t.height;i++)if(e.nodeAt(t.map[n+i*t.width]).type!=r)return!1;return!0}var ae=class Xt extends _{constructor(e,n=e){let r=e.node(-1),i=Z.get(r),o=e.start(-1),s=i.rectBetween(e.pos-o,n.pos-o),a=e.node(0),l=i.cellsInRect(s).filter(u=>u!=n.pos-o);l.unshift(n.pos-o);let c=l.map(u=>{let f=r.nodeAt(u);if(!f)throw new RangeError(`No cell with offset ${u} found`);let d=o+u+1;return new un(a.resolve(d),a.resolve(d+f.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=n}map(e,n){let r=e.resolve(n.map(this.$anchorCell.pos)),i=e.resolve(n.map(this.$headCell.pos));if(Iu(r)&&Iu(i)&&Nu(r,i)){let o=this.$anchorCell.node(-1)!=r.node(-1);return o&&this.isRowSelection()?Xt.rowSelection(r,i):o&&this.isColSelection()?Xt.colSelection(r,i):new Xt(r,i)}return z.between(r,i)}content(){let e=this.$anchorCell.node(-1),n=Z.get(e),r=this.$anchorCell.start(-1),i=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),o={},s=[];for(let l=i.top;l<i.bottom;l++){let c=[];for(let u=l*n.width+i.left,f=i.left;f<i.right;f++,u++){let d=n.map[u];if(o[d])continue;o[d]=!0;let p=n.findCell(d),h=e.nodeAt(d);if(!h)throw new RangeError(`No cell with offset ${d} found`);let m=i.left-p.left,g=p.right-i.right;if(m>0||g>0){let y=h.attrs;if(m>0&&(y=sr(y,0,m)),g>0&&(y=sr(y,y.colspan-g,g)),p.left<i.left){if(h=h.type.createAndFill(y),!h)throw new RangeError(`Could not create cell with attrs ${JSON.stringify(y)}`)}else h=h.type.create(y,h.content)}if(p.top<i.top||p.bottom>i.bottom){let y={...h.attrs,rowspan:Math.min(p.bottom,i.bottom)-Math.max(p.top,i.top)};p.top<i.top?h=h.type.createAndFill(y):h=h.type.create(y,h.content)}c.push(h)}s.push(e.child(l).copy(E.from(c)))}let a=this.isColSelection()&&this.isRowSelection()?e:s;return new A(E.from(a),1,1)}replace(e,n=A.empty){let r=e.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:a,$to:l}=i[s],c=e.mapping.slice(r);e.replace(c.map(a.pos),c.map(l.pos),s?A.empty:n)}let o=_.findFrom(e.doc.resolve(e.mapping.slice(r).map(this.to)),-1);o&&e.setSelection(o)}replaceWith(e,n){this.replace(e,new A(E.from(n),0,0))}forEachCell(e){let n=this.$anchorCell.node(-1),r=Z.get(n),i=this.$anchorCell.start(-1),o=r.cellsInRect(r.rectBetween(this.$anchorCell.pos-i,this.$headCell.pos-i));for(let s=0;s<o.length;s++)e(n.nodeAt(o[s]),i+o[s])}isColSelection(){let e=this.$anchorCell.index(-1),n=this.$headCell.index(-1);if(Math.min(e,n)>0)return!1;let r=e+this.$anchorCell.nodeAfter.attrs.rowspan,i=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,i)==this.$headCell.node(-1).childCount}static colSelection(e,n=e){let r=e.node(-1),i=Z.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.top<=a.top?(s.top>0&&(e=l.resolve(o+i.map[s.left])),a.bottom<i.height&&(n=l.resolve(o+i.map[i.width*(i.height-1)+a.right-1]))):(a.top>0&&(n=l.resolve(o+i.map[a.left])),s.bottom<i.height&&(e=l.resolve(o+i.map[i.width*(i.height-1)+s.right-1]))),new Xt(e,n)}isRowSelection(){let e=this.$anchorCell.node(-1),n=Z.get(e),r=this.$anchorCell.start(-1),i=n.colCount(this.$anchorCell.pos-r),o=n.colCount(this.$headCell.pos-r);if(Math.min(i,o)>0)return!1;let s=i+this.$anchorCell.nodeAfter.attrs.colspan,a=o+this.$headCell.nodeAfter.attrs.colspan;return Math.max(s,a)==n.width}eq(e){return e instanceof Xt&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,n=e){let r=e.node(-1),i=Z.get(r),o=e.start(-1),s=i.findCell(e.pos-o),a=i.findCell(n.pos-o),l=e.node(0);return s.left<=a.left?(s.left>0&&(e=l.resolve(o+i.map[s.top*i.width])),a.right<i.width&&(n=l.resolve(o+i.map[i.width*(a.top+1)-1]))):(a.left>0&&(n=l.resolve(o+i.map[a.top*i.width])),s.right<i.width&&(e=l.resolve(o+i.map[i.width*(s.top+1)-1]))),new Xt(e,n)}toJSON(){return{type:"cell",anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(e,n){return new Xt(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){return new Xt(e.resolve(n),e.resolve(r))}getBookmark(){return new WM(this.$anchorCell.pos,this.$headCell.pos)}};ae.prototype.visible=!1;_.jsonID("cell",ae);var WM=class ky{constructor(e,n){this.anchor=e,this.head=n}map(e){return new ky(e.map(this.anchor),e.map(this.head))}resolve(e){let n=e.resolve(this.anchor),r=e.resolve(this.head);return n.parent.type.spec.tableRole=="row"&&r.parent.type.spec.tableRole=="row"&&n.index()<n.parent.childCount&&r.index()<r.parent.childCount&&Nu(n,r)?new ae(n,r):_.near(r,1)}};function jM(t){if(!(t.selection instanceof ae))return null;let e=[];return t.selection.forEachCell((n,r)=>{e.push(se.node(r,r+n.nodeSize,{class:"selectedCell"}))}),re.create(t.doc,e)}function qM({$from:t,$to:e}){if(t.pos==e.pos||t.pos<e.pos-6)return!1;let n=t.pos,r=e.pos,i=t.depth;for(;i>=0&&!(t.after(i+1)<t.end(i));i--,n++);for(let o=e.depth;o>=0&&!(e.before(o+1)>e.start(o));o--,r--);return n==r&&/row|table/.test(t.node(i).type.spec.tableRole)}function KM({$from:t,$to:e}){let n,r;for(let i=t.depth;i>0;i--){let o=t.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){n=o;break}}for(let i=e.depth;i>0;i--){let o=e.node(i);if(o.type.spec.tableRole==="cell"||o.type.spec.tableRole==="header_cell"){r=o;break}}return n!==r&&e.parentOffset===0}function UM(t,e,n){let r=(e||t).selection,i=(e||t).doc,o,s;if(r instanceof H&&(s=r.node.type.spec.tableRole)){if(s=="cell"||s=="header_cell")o=ae.create(i,r.from);else if(s=="row"){let a=i.resolve(r.from+1);o=ae.rowSelection(a,a)}else if(!n){let a=Z.get(r.node),l=r.from+1,c=l+a.map[a.width*a.height-1];o=ae.create(i,l+1,c)}}else r instanceof z&&qM(r)?o=z.create(i,r.from):r instanceof z&&KM(r)&&(o=z.create(i,r.$from.start(),r.$from.end()));return o&&(e||(e=t.tr)).setSelection(o),e}var JM=new te("fix-tables");function by(t,e,n,r){let i=t.childCount,o=e.childCount;e:for(let s=0,a=0;s<o;s++){let l=e.child(s);for(let c=a,u=Math.min(i,s+3);c<u;c++)if(t.child(c)==l){a=c+1,n+=l.nodeSize;continue e}r(l,n),a<i&&t.child(a).sameMarkup(l)?by(t.child(a),l,n+1,r):l.nodesBetween(0,l.content.size,r,n+1),n+=l.nodeSize}}function GM(t,e){let n,r=(i,o)=>{i.type.spec.tableRole=="table"&&(n=QM(t,i,o,n))};return e?e.doc!=t.doc&&by(e.doc,t.doc,0,r):t.doc.descendants(r),n}function QM(t,e,n,r){let i=Z.get(e);if(!i.problems)return r;r||(r=t.tr);let o=[];for(let l=0;l<i.height;l++)o.push(0);for(let l=0;l<i.problems.length;l++){let c=i.problems[l];if(c.type=="collision"){let u=e.nodeAt(c.pos);if(!u)continue;let f=u.attrs;for(let d=0;d<f.rowspan;d++)o[c.row+d]+=c.n;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,sr(f,f.colspan-c.n,c.n))}else if(c.type=="missing")o[c.row]+=c.n;else if(c.type=="overlong_rowspan"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,rowspan:u.attrs.rowspan-c.n})}else if(c.type=="colwidth mismatch"){let u=e.nodeAt(c.pos);if(!u)continue;r.setNodeMarkup(r.mapping.map(n+1+c.pos),null,{...u.attrs,colwidth:c.colwidth})}else if(c.type=="zero_sized"){let u=r.mapping.map(n);r.delete(u,u+e.nodeSize)}}let s,a;for(let l=0;l<o.length;l++)o[l]&&(s==null&&(s=l),a=l);for(let l=0,c=n+1;l<i.height;l++){let u=e.child(l),f=c+u.nodeSize,d=o[l];if(d>0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);let h=[];for(let g=0;g<d;g++){let y=$e(t.schema)[p].createAndFill();y&&h.push(y)}let m=(l==0||s==l-1)&&a==l?c+1:f-1;r.insert(r.mapping.map(m),h)}c=f}return r.setMeta(JM,{fixTables:!0})}function xy(t){let e=Z.get(t),n=[],r=e.height,i=e.width;for(let o=0;o<r;o++){let s=[];for(let a=0;a<i;a++){let l=o*i+a,c=e.map[l];if(o>0){let u=l-i;if(c===e.map[u]){s.push(null);continue}}if(a>0){let u=l-1;if(c===e.map[u]){s.push(null);continue}}s.push(t.nodeAt(c))}n.push(s)}return n}function wy(t,e){let n=[],r=Z.get(t),i=r.height,o=r.width;for(let s=0;s<i;s++){let a=t.child(s),l=[];for(let u=0;u<o;u++){let f=e[s][u];if(!f)continue;let d=r.map[s*r.width+u],p=t.nodeAt(d);if(!p)continue;let h=p.type.createChecked(f.attrs,f.content,f.marks);l.push(h)}let c=a.type.createChecked(a.attrs,l,a.marks);n.push(c)}return t.type.createChecked(t.attrs,n,t.marks)}function Sy(t,e,n,r){let i=e[0]>n[0]?-1:1,o=t.splice(e[0],e.length),s=o.length%2===0?1:0,a;return r===-1&&i===1?a=n[0]-1:r===1&&i===-1?a=n[n.length-1]-s+1:a=i===-1?n[0]:n[n.length-1]-s,t.splice(a,0,...o),t}function ti(t){return XM(e=>e.type.spec.tableRole==="table",t)}function XM(t,e){for(let n=e.depth;n>=0;n-=1){let r=e.node(n);if(t(r))return{node:r,pos:n===0?0:e.before(n),start:e.start(n),depth:n}}return null}function Yr(t,e){let n=ti(e.$from);if(!n)return;let r=Z.get(n.node);if(!(t<0||t>r.width-1))return r.cellsInRect({left:t,right:t+1,top:0,bottom:r.height}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function Zr(t,e){let n=ti(e.$from);if(!n)return;let r=Z.get(n.node);if(!(t<0||t>r.height-1))return r.cellsInRect({left:0,right:r.width,top:t,bottom:t+1}).map(i=>{let o=n.node.nodeAt(i),s=i+n.start;return{pos:s,start:s+1,node:o,depth:n.depth+2}})}function oy(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=Yr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=Yr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.colspan+u-1;d.node.attrs.colspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=Yr(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=Yr(r,t.selection),a=Zr(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=Yr(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function sy(t,e,n=e){let r=e,i=n;for(let u=e;u>=0;u--){let f=Zr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;p>=r&&(r=u),p>i&&(i=p)})}for(let u=e;u<=i;u++){let f=Zr(u,t.selection);f&&f.forEach(d=>{let p=d.node.attrs.rowspan+u-1;d.node.attrs.rowspan>1&&p>i&&(i=p)})}let o=[];for(let u=r;u<=i;u++){let f=Zr(u,t.selection);f&&f.length>0&&o.push(u)}r=o[0],i=o[o.length-1];let s=Zr(r,t.selection),a=Yr(0,t.selection);if(!s||!a)return;let l=t.doc.resolve(s[s.length-1].pos),c;for(let u=i;u>=r;u--){let f=Zr(u,t.selection);if(f&&f.length>0){for(let d=a.length-1;d>=0;d--)if(a[d].pos===f[0].pos){c=f[0];break}if(c)break}}if(c)return{$anchor:l,$head:t.doc.resolve(c.pos),indexes:o}}function ay(t){return t[0].map((e,n)=>t.map(r=>r[n]))}function YM(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=ti(r.doc.resolve(a));if(!l)return!1;let c=(e=oy(r,i))===null||e===void 0?void 0:e.indexes,u=(n=oy(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=ZM(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=Z.get(f),p=l.start,h=o,m=d.positionAt(d.height-1,h,f),g=r.doc.resolve(p+m),y=d.positionAt(0,h,f),x=r.doc.resolve(p+y);return r.setSelection(ae.colSelection(g,x)),!0}function ZM(t,e,n,r){let i=ay(xy(t));return i=Sy(i,e,n,r),i=ay(i),wy(t,i)}function eE(t){var e,n;let{tr:r,originIndex:i,targetIndex:o,select:s,pos:a}=t,l=ti(r.doc.resolve(a));if(!l)return!1;let c=(e=sy(r,i))===null||e===void 0?void 0:e.indexes,u=(n=sy(r,o))===null||n===void 0?void 0:n.indexes;if(!c||!u||c.includes(o))return!1;let f=tE(l.node,c,u,0);if(r.replaceWith(l.pos,l.pos+l.node.nodeSize,f),!s)return!0;let d=Z.get(f),p=l.start,h=o,m=d.positionAt(h,d.width-1,f),g=r.doc.resolve(p+m),y=d.positionAt(h,0,f),x=r.doc.resolve(p+y);return r.setSelection(ae.rowSelection(g,x)),!0}function tE(t,e,n,r){let i=xy(t);return i=Sy(i,e,n,r),wy(t,i)}function xt(t){let e=t.selection,n=ea(t),r=n.node(-1),i=n.start(-1),o=Z.get(r);return{...e instanceof ae?o.rectBetween(e.$anchorCell.pos-i,e.$headCell.pos-i):o.findCell(n.pos-i),tableStart:i,map:o,table:r}}function Cy(t,{map:e,tableStart:n,table:r},i){let o=i>0?-1:0;VM(e,r,i+o)&&(o=i==0||i==e.width?null:0);for(let s=0;s<e.height;s++){let a=s*e.width+i;if(i>0&&i<e.width&&e.map[a-1]==e.map[a]){let l=e.map[a],c=r.nodeAt(l);t.setNodeMarkup(t.mapping.map(n+l),null,HM(c.attrs,i-e.colCount(l))),s+=c.attrs.rowspan-1}else{let l=o==null?$e(r.type.schema).cell:r.nodeAt(e.map[a+o]).type,c=e.positionAt(s,i,r);t.insert(t.mapping.map(n+c),l.createAndFill())}}return t}function My(t,e){if(!Ae(t))return!1;if(e){let n=xt(t);e(Cy(t.tr,n,n.left))}return!0}function ta(t,e){if(!Ae(t))return!1;if(e){let n=xt(t);e(Cy(t.tr,n,n.right))}return!0}function nE(t,{map:e,table:n,tableStart:r},i){let o=t.mapping.maps.length;for(let s=0;s<e.height;){let a=s*e.width+i,l=e.map[a],c=n.nodeAt(l),u=c.attrs;if(i>0&&e.map[a-1]==l||i<e.width-1&&e.map[a+1]==l)t.setNodeMarkup(t.mapping.slice(o).map(r+l),null,sr(u,i-e.colCount(l)));else{let f=t.mapping.slice(o).map(r+l);t.delete(f,f+c.nodeSize)}s+=u.rowspan}}function na(t,e){if(!Ae(t))return!1;if(e){let n=xt(t),r=t.tr;if(n.left==0&&n.right==n.map.width)return!1;for(let i=n.right-1;nE(r,n,i),i!=n.left;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=Z.get(o)}e(r)}return!0}function rE(t,e,n){var r;let i=$e(e.type.schema).header_cell;for(let o=0;o<t.width;o++)if(((r=e.nodeAt(t.map[o+n*t.width]))===null||r===void 0?void 0:r.type)!=i)return!1;return!0}function iE(t,{map:e,tableStart:n,table:r},i){let o=n;for(let c=0;c<i;c++)o+=r.child(c).nodeSize;let s=[],a=i>0?-1:0;rE(e,r,i+a)&&(a=i==0||i==e.height?null:0);for(let c=0,u=e.width*i;c<e.width;c++,u++)if(i>0&&i<e.height&&e.map[u]==e.map[u-e.width]){let f=e.map[u],d=r.nodeAt(f).attrs;t.setNodeMarkup(n+f,null,{...d,rowspan:d.rowspan+1}),c+=d.colspan-1}else{var l;let f=a==null?$e(r.type.schema).cell:(l=r.nodeAt(e.map[u+a*e.width]))===null||l===void 0?void 0:l.type,d=f?.createAndFill();d&&s.push(d)}return t.insert(o,$e(r.type.schema).row.create(null,s)),t}function Ey(t,e){if(!Ae(t))return!1;if(e){let n=xt(t);e(iE(t.tr,n,n.bottom))}return!0}function oE(t,{map:e,table:n,tableStart:r},i){let o=0;for(let c=0;c<i;c++)o+=n.child(c).nodeSize;let s=o+n.child(i).nodeSize,a=t.mapping.maps.length;t.delete(o+r,s+r);let l=new Set;for(let c=0,u=i*e.width;c<e.width;c++,u++){let f=e.map[u];if(!l.has(f)){if(l.add(f),i>0&&f==e.map[u-e.width]){let d=n.nodeAt(f).attrs;t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d,rowspan:d.rowspan-1}),c+=d.colspan-1}else if(i<e.height&&f==e.map[u+e.width]){let d=n.nodeAt(f),p=d.attrs,h=d.type.create({...p,rowspan:d.attrs.rowspan-1},d.content),m=e.positionAt(i+1,c,n);t.insert(t.mapping.slice(a).map(r+m),h),c+=p.colspan-1}}}}function ra(t,e){if(!Ae(t))return!1;if(e){let n=xt(t),r=t.tr;if(n.top==0&&n.bottom==n.map.height)return!1;for(let i=n.bottom-1;oE(r,n,i),i!=n.top;i--){let o=n.tableStart?r.doc.nodeAt(n.tableStart-1):r.doc;if(!o)throw new RangeError("No table found");n.table=o,n.map=Z.get(n.table)}e(r)}return!0}function Ty(t,e){return function(n,r){if(!Ae(n))return!1;let i=ea(n);if(i.nodeAfter.attrs[t]===e)return!1;if(r){let o=n.tr;n.selection instanceof ae?n.selection.forEachCell((s,a)=>{s.attrs[t]!==e&&o.setNodeMarkup(a,null,{...s.attrs,[t]:e})}):o.setNodeMarkup(i.pos,null,{...i.nodeAfter.attrs,[t]:e}),r(o)}return!0}}function sE(t){return function(e,n){if(!Ae(e))return!1;if(n){let r=$e(e.schema),i=xt(e),o=e.tr,s=i.map.cellsInRect(t=="column"?{left:i.left,top:0,right:i.right,bottom:i.map.height}:t=="row"?{left:0,top:i.top,right:i.map.width,bottom:i.bottom}:i),a=s.map(l=>i.table.nodeAt(l));for(let l=0;l<s.length;l++)a[l].type==r.header_cell&&o.setNodeMarkup(i.tableStart+s[l],r.cell,a[l].attrs);if(o.steps.length===0)for(let l=0;l<s.length;l++)o.setNodeMarkup(i.tableStart+s[l],r.header_cell,a[l].attrs);n(o)}return!0}}function ly(t,e,n){let r=e.map.cellsInRect({left:0,top:0,right:t=="row"?e.map.width:1,bottom:t=="column"?e.map.height:1});for(let i=0;i<r.length;i++){let o=e.table.nodeAt(r[i]);if(o&&o.type!==n.header_cell)return!1}return!0}function Ru(t,e){return e=e||{useDeprecatedLogic:!1},e.useDeprecatedLogic?sE(t):function(n,r){if(!Ae(n))return!1;if(r){let i=$e(n.schema),o=xt(n),s=n.tr,a=ly("row",o,i),l=ly("column",o,i),c=(t==="column"?a:t==="row"&&l)?1:0,u=t=="column"?{left:0,top:c,right:1,bottom:o.map.height}:t=="row"?{left:c,top:0,right:o.map.width,bottom:1}:o,f=t=="column"?l?i.cell:i.header_cell:t=="row"?a?i.cell:i.header_cell:i.cell;o.map.cellsInRect(u).forEach(d=>{let p=d+o.tableStart,h=s.doc.nodeAt(p);h&&s.setNodeMarkup(p,f,h.attrs)}),r(s)}return!0}}var Zz=Ru("row",{useDeprecatedLogic:!0}),e_=Ru("column",{useDeprecatedLogic:!0}),t_=Ru("cell",{useDeprecatedLogic:!0});function aE(t,e){if(e<0){let n=t.nodeBefore;if(n)return t.pos-n.nodeSize;for(let r=t.index(-1)-1,i=t.before();r>=0;r--){let o=t.node(-1).child(r),s=o.lastChild;if(s)return i-1-s.nodeSize;i-=o.nodeSize}}else{if(t.index()<t.parent.childCount-1)return t.pos+t.nodeAfter.nodeSize;let n=t.node(-1);for(let r=t.indexAfter(-1),i=t.after();r<n.childCount;r++){let o=n.child(r);if(o.childCount)return i+1;i+=o.nodeSize}}return null}function ia(t){return function(e,n){if(!Ae(e))return!1;let r=aE(ea(e),t);if(r==null)return!1;if(n){let i=e.doc.resolve(r);n(e.tr.setSelection(z.between(i,$M(i))).scrollIntoView())}return!0}}function Iy(t,e){let n=t.selection.$anchor;for(let r=n.depth;r>0;r--)if(n.node(r).type.spec.tableRole=="table")return e&&e(t.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function Gs(t,e){let n=t.selection;if(!(n instanceof ae))return!1;if(e){let r=t.tr,i=$e(t.schema).cell.createAndFill().content;n.forEachCell((o,s)=>{o.content.eq(i)||r.replace(r.mapping.map(s+1),r.mapping.map(s+o.nodeSize-1),new A(i,0,0))}),r.docChanged&&e(r)}return!0}function vy(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return eE({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function Ay(t){return(e,n)=>{let{from:r,to:i,select:o=!0,pos:s=e.selection.from}=t,a=e.tr;return YM({tr:a,originIndex:r,targetIndex:i,select:o,pos:s})?(n?.(a),!0):!1}}function lE(t){if(t.size===0)return null;let{content:e,openStart:n,openEnd:r}=t;for(;e.childCount==1&&(n>0&&r>0||e.child(0).type.spec.tableRole=="table");)n--,r--,e=e.child(0).content;let i=e.child(0),o=i.type.spec.tableRole,s=i.type.schema,a=[];if(o=="row")for(let l=0;l<e.childCount;l++){let c=e.child(l).content,u=l?0:Math.max(0,n-1),f=l<e.childCount-1?0:Math.max(0,r-1);(u||f)&&(c=vu($e(s).row,new A(c,u,f)).content),a.push(c)}else if(o=="cell"||o=="header_cell")a.push(n||r?vu($e(s).row,new A(e,n,r)).content:e);else return null;return cE(s,a)}function cE(t,e){let n=[];for(let i=0;i<e.length;i++){let o=e[i];for(let s=o.childCount-1;s>=0;s--){let{rowspan:a,colspan:l}=o.child(s).attrs;for(let c=i;c<i+a;c++)n[c]=(n[c]||0)+l}}let r=0;for(let i=0;i<n.length;i++)r=Math.max(r,n[i]);for(let i=0;i<n.length;i++)if(i>=e.length&&e.push(E.empty),n[i]<r){let o=$e(t).cell.createAndFill(),s=[];for(let a=n[i];a<r;a++)s.push(o);e[i]=e[i].append(E.from(s))}return{height:e.length,width:r,rows:e}}function vu(t,e){let n=t.createAndFill();return new Tr(n).replace(0,n.content.size,e).doc}function uE({width:t,height:e,rows:n},r,i){if(t!=r){let o=[],s=[];for(let a=0;a<n.length;a++){let l=n[a],c=[];for(let u=o[a]||0,f=0;u<r;f++){let d=l.child(f%l.childCount);u+d.attrs.colspan>r&&(d=d.type.createChecked(sr(d.attrs,d.attrs.colspan,u+d.attrs.colspan-r),d.content)),c.push(d),u+=d.attrs.colspan;for(let p=1;p<d.attrs.rowspan;p++)o[a+p]=(o[a+p]||0)+d.attrs.colspan}s.push(E.from(c))}n=s,t=r}if(e!=i){let o=[];for(let s=0,a=0;s<i;s++,a++){let l=[],c=n[a%e];for(let u=0;u<c.childCount;u++){let f=c.child(u);s+f.attrs.rowspan>i&&(f=f.type.create({...f.attrs,rowspan:Math.max(1,i-f.attrs.rowspan)},f.content)),l.push(f)}o.push(E.from(l))}n=o,e=i}return{width:t,height:e,rows:n}}function fE(t,e,n,r,i,o,s){let a=t.doc.type.schema,l=$e(a),c,u;if(i>e.width)for(let f=0,d=0;f<e.height;f++){let p=n.child(f);d+=p.nodeSize;let h=[],m;p.lastChild==null||p.lastChild.type==l.cell?m=c||(c=l.cell.createAndFill()):m=u||(u=l.header_cell.createAndFill());for(let g=e.width;g<i;g++)h.push(m);t.insert(t.mapping.slice(s).map(d-1+r),h)}if(o>e.height){let f=[];for(let h=0,m=(e.height-1)*e.width;h<Math.max(e.width,i);h++){let g=h>=e.width?!1:n.nodeAt(e.map[m+h]).type==l.header_cell;f.push(g?u||(u=l.header_cell.createAndFill()):c||(c=l.cell.createAndFill()))}let d=l.row.create(null,E.from(f)),p=[];for(let h=e.height;h<o;h++)p.push(d);t.insert(t.mapping.slice(s).map(r+n.nodeSize-2),p)}return!!(c||u)}function cy(t,e,n,r,i,o,s,a){if(s==0||s==e.height)return!1;let l=!1;for(let c=i;c<o;c++){let u=s*e.width+c,f=e.map[u];if(e.map[u-e.width]==f){l=!0;let d=n.nodeAt(f),{top:p,left:h}=e.findCell(f);t.setNodeMarkup(t.mapping.slice(a).map(f+r),null,{...d.attrs,rowspan:s-p}),t.insert(t.mapping.slice(a).map(e.positionAt(s,h,n)),d.type.createAndFill({...d.attrs,rowspan:p+d.attrs.rowspan-s})),c+=d.attrs.colspan-1}}return l}function uy(t,e,n,r,i,o,s,a){if(s==0||s==e.width)return!1;let l=!1;for(let c=i;c<o;c++){let u=c*e.width+s,f=e.map[u];if(e.map[u-1]==f){l=!0;let d=n.nodeAt(f),p=e.colCount(f),h=t.mapping.slice(a).map(f+r);t.setNodeMarkup(h,null,sr(d.attrs,s-p,d.attrs.colspan-(s-p))),t.insert(h+d.nodeSize,d.type.createAndFill(sr(d.attrs,0,s-p))),c+=d.attrs.rowspan-1}}return l}function fy(t,e,n,r,i){let o=n?t.doc.nodeAt(n-1):t.doc;if(!o)throw new Error("No table found");let s=Z.get(o),{top:a,left:l}=r,c=l+i.width,u=a+i.height,f=t.tr,d=0;function p(){if(o=n?f.doc.nodeAt(n-1):f.doc,!o)throw new Error("No table found");s=Z.get(o),d=f.mapping.maps.length}fE(f,s,o,n,c,u,d)&&p(),cy(f,s,o,n,l,c,a,d)&&p(),cy(f,s,o,n,l,c,u,d)&&p(),uy(f,s,o,n,a,u,l,d)&&p(),uy(f,s,o,n,a,u,c,d)&&p();for(let h=a;h<u;h++){let m=s.positionAt(h,l,o),g=s.positionAt(h,c,o);f.replace(f.mapping.slice(d).map(m+n),f.mapping.slice(d).map(g+n),new A(i.rows[h-a],0,0))}p(),f.setSelection(new ae(f.doc.resolve(n+s.positionAt(a,l,o)),f.doc.resolve(n+s.positionAt(u-1,c-1,o)))),e(f)}var dE=ql({ArrowLeft:Qs("horiz",-1),ArrowRight:Qs("horiz",1),ArrowUp:Qs("vert",-1),ArrowDown:Qs("vert",1),"Shift-ArrowLeft":Xs("horiz",-1),"Shift-ArrowRight":Xs("horiz",1),"Shift-ArrowUp":Xs("vert",-1),"Shift-ArrowDown":Xs("vert",1),Backspace:Gs,"Mod-Backspace":Gs,Delete:Gs,"Mod-Delete":Gs});function Ys(t,e,n){return n.eq(t.selection)?!1:(e&&e(t.tr.setSelection(n).scrollIntoView()),!0)}function Qs(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection;if(o instanceof ae)return Ys(n,r,_.near(o.$headCell,e));if(t!="horiz"&&!o.empty)return!1;let s=Ny(i,t,e);if(s==null)return!1;if(t=="horiz")return Ys(n,r,_.near(n.doc.resolve(o.head+e),e));{let a=n.doc.resolve(s),l=yy(a,t,e),c;return l?c=_.near(l,1):e<0?c=_.near(n.doc.resolve(a.before(-1)),-1):c=_.near(n.doc.resolve(a.after(-1)),1),Ys(n,r,c)}}}function Xs(t,e){return(n,r,i)=>{if(!i)return!1;let o=n.selection,s;if(o instanceof ae)s=o;else{let l=Ny(i,t,e);if(l==null)return!1;s=new ae(n.doc.resolve(l))}let a=yy(s.$headCell,t,e);return a?Ys(n,r,new ae(s.$anchorCell,a)):!1}}function pE(t,e){let n=t.state.doc,r=ei(n.resolve(e));return r?(t.dispatch(t.state.tr.setSelection(new ae(r))),!0):!1}function hE(t,e,n){if(!Ae(t.state))return!1;let r=lE(n),i=t.state.selection;if(i instanceof ae){r||(r={width:1,height:1,rows:[E.from(vu($e(t.state.schema).cell,n))]});let o=i.$anchorCell.node(-1),s=i.$anchorCell.start(-1),a=Z.get(o).rectBetween(i.$anchorCell.pos-s,i.$headCell.pos-s);return r=uE(r,a.right-a.left,a.bottom-a.top),fy(t.state,t.dispatch,s,a,r),!0}else if(r){let o=ea(t.state),s=o.start(-1);return fy(t.state,t.dispatch,s,Z.get(o.node(-1)).findCell(o.pos-s),r),!0}else return!1}function mE(t,e){var n;if(e.button!=0||e.ctrlKey||e.metaKey)return;let r=dy(t,e.target),i;if(e.shiftKey&&t.state.selection instanceof ae)o(t.state.selection.$anchorCell,e),e.preventDefault();else if(e.shiftKey&&r&&(i=ei(t.state.selection.$anchor))!=null&&((n=Mu(t,e))===null||n===void 0?void 0:n.pos)!=i.pos)o(i,e),e.preventDefault();else if(!r)return;function o(l,c){let u=Mu(t,c),f=xn.getState(t.state)==null;if(!u||!Nu(l,u))if(f)u=l;else return;let d=new ae(l,u);if(f||!t.state.selection.eq(d)){let p=t.state.tr.setSelection(d);f&&p.setMeta(xn,l.pos),t.dispatch(p)}}function s(){t.root.removeEventListener("mouseup",s),t.root.removeEventListener("dragstart",s),t.root.removeEventListener("mousemove",a),xn.getState(t.state)!=null&&t.dispatch(t.state.tr.setMeta(xn,-1))}function a(l){let c=l,u=xn.getState(t.state),f;if(u!=null)f=t.state.doc.resolve(u);else if(dy(t,c.target)!=r&&(f=Mu(t,e),!f))return s();f&&o(f,c)}t.root.addEventListener("mouseup",s),t.root.addEventListener("dragstart",s),t.root.addEventListener("mousemove",a)}function Ny(t,e,n){if(!(t.state.selection instanceof z))return null;let{$head:r}=t.state.selection;for(let i=r.depth-1;i>=0;i--){let o=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:o.childCount))return null;if(o.type.spec.tableRole=="cell"||o.type.spec.tableRole=="header_cell"){let s=r.before(i),a=e=="vert"?n>0?"down":"up":n>0?"right":"left";return t.endOfTextblock(a)?s:null}}return null}function dy(t,e){for(;e&&e!=t.dom;e=e.parentNode)if(e.nodeName=="TD"||e.nodeName=="TH")return e;return null}function Mu(t,e){let n=t.posAtCoords({left:e.clientX,top:e.clientY});if(!n)return null;let{inside:r,pos:i}=n;return r>=0&&ei(t.state.doc.resolve(r))||ei(t.state.doc.resolve(i))}var gE=class{constructor(t,e){this.node=t,this.defaultCellMinWidth=e,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${e}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),Au(t,this.colgroup,this.table,e),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,Au(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function Au(t,e,n,r,i,o){let s=0,a=!0,l=e.firstChild,c=t.firstChild;if(c){for(let f=0,d=0;f<c.childCount;f++){let{colspan:p,colwidth:h}=c.child(f).attrs;for(let m=0;m<p;m++,d++){let g=i==d?o:h&&h[m],y=g?g+"px":"";if(s+=g||r,g||(a=!1),l)l.style.width!=y&&(l.style.width=y),l=l.nextSibling;else{let x=document.createElement("col");x.style.width=y,e.appendChild(x)}}}for(;l;){var u;let f=l.nextSibling;(u=l.parentNode)===null||u===void 0||u.removeChild(l),l=f}a?(n.style.width=s+"px",n.style.minWidth=""):(n.style.width="",n.style.minWidth=s+"px")}}var Ye=new te("tableColumnResizing");function Ry({handleWidth:t=5,cellMinWidth:e=25,defaultCellMinWidth:n=100,View:r=gE,lastColumnResizable:i=!0}={}){let o=new Y({key:Ye,state:{init(s,a){var l;let c=(l=o.spec)===null||l===void 0||(l=l.props)===null||l===void 0?void 0:l.nodeViews,u=$e(a.schema).table.name;return r&&c&&(c[u]=(f,d)=>new r(f,n,d)),new yE(-1,!1)},apply(s,a){return a.apply(s)}},props:{attributes:s=>{let a=Ye.getState(s);return a&&a.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(s,a)=>{kE(s,a,t,i)},mouseleave:s=>{bE(s)},mousedown:(s,a)=>{xE(s,a,e,n)}},decorations:s=>{let a=Ye.getState(s);if(a&&a.activeHandle>-1)return EE(s,a.activeHandle)},nodeViews:{}}});return o}var yE=class Zs{constructor(e,n){this.activeHandle=e,this.dragging=n}apply(e){let n=this,r=e.getMeta(Ye);if(r&&r.setHandle!=null)return new Zs(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new Zs(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&e.docChanged){let i=e.mapping.map(n.activeHandle,-1);return Iu(e.doc.resolve(i))||(i=-1),new Zs(i,n.dragging)}return n}};function kE(t,e,n,r){if(!t.editable)return;let i=Ye.getState(t.state);if(i&&!i.dragging){let o=SE(e.target),s=-1;if(o){let{left:a,right:l}=o.getBoundingClientRect();e.clientX-a<=n?s=py(t,e,"left",n):l-e.clientX<=n&&(s=py(t,e,"right",n))}if(s!=i.activeHandle){if(!r&&s!==-1){let a=t.state.doc.resolve(s),l=a.node(-1),c=Z.get(l),u=a.start(-1);if(c.colCount(a.pos-u)+a.nodeAfter.attrs.colspan-1==c.width-1)return}Dy(t,s)}}}function bE(t){if(!t.editable)return;let e=Ye.getState(t.state);e&&e.activeHandle>-1&&!e.dragging&&Dy(t,-1)}function xE(t,e,n,r){var i;if(!t.editable)return!1;let o=(i=t.dom.ownerDocument.defaultView)!==null&&i!==void 0?i:window,s=Ye.getState(t.state);if(!s||s.activeHandle==-1||s.dragging)return!1;let a=t.state.doc.nodeAt(s.activeHandle),l=wE(t,s.activeHandle,a.attrs);t.dispatch(t.state.tr.setMeta(Ye,{setDragging:{startX:e.clientX,startWidth:l}}));function c(f){o.removeEventListener("mouseup",c),o.removeEventListener("mousemove",u);let d=Ye.getState(t.state);d?.dragging&&(CE(t,d.activeHandle,hy(d.dragging,f,n)),t.dispatch(t.state.tr.setMeta(Ye,{setDragging:null})))}function u(f){if(!f.which)return c(f);let d=Ye.getState(t.state);if(d&&d.dragging){let p=hy(d.dragging,f,n);my(t,d.activeHandle,p,r)}}return my(t,s.activeHandle,l,r),o.addEventListener("mouseup",c),o.addEventListener("mousemove",u),e.preventDefault(),!0}function wE(t,e,{colspan:n,colwidth:r}){let i=r&&r[r.length-1];if(i)return i;let o=t.domAtPos(e),s=o.node.childNodes[o.offset].offsetWidth,a=n;if(r)for(let l=0;l<n;l++)r[l]&&(s-=r[l],a--);return s/a}function SE(t){for(;t&&t.nodeName!="TD"&&t.nodeName!="TH";)t=t.classList&&t.classList.contains("ProseMirror")?null:t.parentNode;return t}function py(t,e,n,r){let i=n=="right"?-r:r,o=t.posAtCoords({left:e.clientX+i,top:e.clientY});if(!o)return-1;let{pos:s}=o,a=ei(t.state.doc.resolve(s));if(!a)return-1;if(n=="right")return a.pos;let l=Z.get(a.node(-1)),c=a.start(-1),u=l.map.indexOf(a.pos-c);return u%l.width==0?-1:c+l.map[u-1]}function hy(t,e,n){let r=e.clientX-t.startX;return Math.max(n,t.startWidth+r)}function Dy(t,e){t.dispatch(t.state.tr.setMeta(Ye,{setHandle:e}))}function CE(t,e,n){let r=t.state.doc.resolve(e),i=r.node(-1),o=Z.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1,l=t.state.tr;for(let c=0;c<o.height;c++){let u=c*o.width+a;if(c&&o.map[u]==o.map[u-o.width])continue;let f=o.map[u],d=i.nodeAt(f).attrs,p=d.colspan==1?0:a-o.colCount(f);if(d.colwidth&&d.colwidth[p]==n)continue;let h=d.colwidth?d.colwidth.slice():ME(d.colspan);h[p]=n,l.setNodeMarkup(s+f,null,{...d,colwidth:h})}l.docChanged&&t.dispatch(l)}function my(t,e,n,r){let i=t.state.doc.resolve(e),o=i.node(-1),s=i.start(-1),a=Z.get(o).colCount(i.pos-s)+i.nodeAfter.attrs.colspan-1,l=t.domAtPos(i.start(-1)).node;for(;l&&l.nodeName!="TABLE";)l=l.parentNode;l&&Au(o,l.firstChild,l,r,a,n)}function ME(t){return Array(t).fill(0)}function EE(t,e){let n=[],r=t.doc.resolve(e),i=r.node(-1);if(!i)return re.empty;let o=Z.get(i),s=r.start(-1),a=o.colCount(r.pos-s)+r.nodeAfter.attrs.colspan-1;for(let c=0;c<o.height;c++){let u=a+c*o.width;if((a==o.width-1||o.map[u]!=o.map[u+1])&&(c==0||o.map[u]!=o.map[u-o.width])){var l;let f=o.map[u],d=s+f+i.nodeAt(f).nodeSize-1,p=document.createElement("div");p.className="column-resize-handle",!((l=Ye.getState(t))===null||l===void 0)&&l.dragging&&n.push(se.node(s+f,s+f+i.nodeAt(f).nodeSize,{class:"column-resize-dragging"})),n.push(se.widget(d,p))}}return re.create(t.doc,n)}function Oy({allowTableNodeSelection:t=!1}={}){return new Y({key:xn,state:{init(){return null},apply(e,n){let r=e.getMeta(xn);if(r!=null)return r==-1?null:r;if(n==null||!e.docChanged)return n;let{deleted:i,pos:o}=e.mapping.mapResult(n);return i?null:o}},props:{decorations:jM,handleDOMEvents:{mousedown:mE},createSelectionBetween(e){return xn.getState(e.state)!=null?e.state.selection:null},handleTripleClick:pE,handleKeyDown:dE,handlePaste:hE},appendTransaction(e,n,r){return UM(r,GM(r,n),t)}})}var oa=typeof navigator<"u"?navigator:null,Ou=oa&&oa.userAgent||"",TE=/Edge\/(\d+)/.exec(Ou),IE=/MSIE \d/.exec(Ou),vE=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Ou),AE=!!(IE||vE||TE),NE=!AE&&!!oa&&/Apple Computer/.test(oa.vendor),Ly=new te("safari-ime-span"),Du=!1,RE={key:Ly,props:{decorations:DE,handleDOMEvents:{compositionstart:()=>{Du=!0},compositionend:()=>{Du=!1}}}};function DE(t){let{$from:e,$to:n,to:r}=t.selection;if(Du&&e.sameParent(n)){let i=se.widget(r,OE,{ignoreSelection:!0,key:"safari-ime-span"});return re.create(t.doc,[i])}}function OE(t){let e=t.dom.ownerDocument.createElement("span");return e.className="ProseMirror-safari-ime-span",e}var By=new Y(NE?RE:{key:Ly});function Lu(t,e){let n=String(t);if(typeof e!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(e);for(;i!==-1;)r++,i=n.indexOf(e,i+e.length);return r}function Bu(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Pu(t,e,n){let i=sn((n||{}).ignore||[]),o=LE(e),s=-1;for(;++s<o.length;)On(t,"text",a);function a(c,u){let f=-1,d;for(;++f<u.length;){let p=u[f],h=d?d.children:void 0;if(i(p,h?h.indexOf(p):void 0,d))return;d=p}if(d)return l(c,u)}function l(c,u){let f=u[u.length-1],d=o[s][0],p=o[s][1],h=0,g=f.children.indexOf(c),y=!1,x=[];d.lastIndex=0;let C=d.exec(c.value);for(;C;){let I=C.index,v={index:C.index,input:C.input,stack:[...u,c]},w=p(...C,v);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?d.lastIndex=I+1:(h!==I&&x.push({type:"text",value:c.value.slice(h,I)}),Array.isArray(w)?x.push(...w):w&&x.push(w),h=I+C[0].length,y=!0),!d.global)break;C=d.exec(c.value)}return y?(h<c.value.length&&x.push({type:"text",value:c.value.slice(h)}),f.children.splice(g,1,...x)):x=[c],g+x.length}}function LE(t){let e=[];if(!Array.isArray(t))throw new TypeError("Expected find and replace tuple or list of tuples");let n=!t[0]||Array.isArray(t[0])?t:[t],r=-1;for(;++r<n.length;){let i=n[r];e.push([BE(i[0]),PE(i[1])])}return e}function BE(t){return typeof t=="string"?new RegExp(Bu(t),"g"):t}function PE(t){return typeof t=="function"?t:function(){return t}}var Fu="phrasing",zu=["autolink","link","image","label"];function $u(){return{transforms:[VE],enter:{literalAutolink:FE,literalAutolinkEmail:_u,literalAutolinkHttp:_u,literalAutolinkWww:_u},exit:{literalAutolink:HE,literalAutolinkEmail:$E,literalAutolinkHttp:zE,literalAutolinkWww:_E}}}function Hu(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Fu,notInConstruct:zu},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Fu,notInConstruct:zu},{character:":",before:"[ps]",after:"\\/",inConstruct:Fu,notInConstruct:zu}]}}function FE(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function _u(t){this.config.enter.autolinkProtocol.call(this,t)}function zE(t){this.config.exit.autolinkProtocol.call(this,t)}function _E(t){this.config.exit.data.call(this,t);let e=this.stack[this.stack.length-1];e.type,e.url="http://"+this.sliceSerialize(t)}function $E(t){this.config.exit.autolinkEmail.call(this,t)}function HE(t){this.exit(t)}function VE(t){Pu(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,WE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,jE]],{ignore:["link","linkReference"]})}function WE(t,e,n,r,i){let o="";if(!Py(i)||(/^w/i.test(e)&&(n=e+n,e="",o="http://"),!qE(n)))return!1;let s=KE(n+r);if(!s[0])return!1;let a={type:"link",title:null,url:o+e+s[0],children:[{type:"text",value:e+s[0]}]};return s[1]?[a,{type:"text",value:s[1]}]:a}function jE(t,e,n,r){return!Py(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+e+"@"+n,children:[{type:"text",value:e+"@"+n}]}}function qE(t){let e=t.split(".");return!(e.length<2||e[e.length-1]&&(/_/.test(e[e.length-1])||!/[a-zA-Z\d]/.test(e[e.length-1]))||e[e.length-2]&&(/_/.test(e[e.length-2])||!/[a-zA-Z\d]/.test(e[e.length-2])))}function KE(t){let e=/[!"&'),.:;<>?\]}]+$/.exec(t);if(!e)return[t,void 0];t=t.slice(0,e.index);let n=e[0],r=n.indexOf(")"),i=Lu(t,"("),o=Lu(t,")");for(;r!==-1&&i>o;)t+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),o++;return[t,n]}function Py(t,e){let n=t.input.charCodeAt(t.index-1);return(t.index===0||Tt(n)||In(n))&&(!e||n!==47)}Fy.peek=tT;function UE(){this.buffer()}function JE(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function GE(){this.buffer()}function QE(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function XE(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(t)).toLowerCase(),n.label=e}function YE(t){this.exit(t)}function ZE(t){let e=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ne(this.sliceSerialize(t)).toLowerCase(),n.label=e}function eT(t){this.exit(t)}function tT(){return"["}function Fy(t,e,n,r){let i=n.createTracker(r),o=i.move("[^"),s=n.enter("footnoteReference"),a=n.enter("reference");return o+=i.move(n.safe(n.associationId(t),{after:"]",before:o})),a(),s(),o+=i.move("]"),o}function Vu(){return{enter:{gfmFootnoteCallString:UE,gfmFootnoteCall:JE,gfmFootnoteDefinitionLabelString:GE,gfmFootnoteDefinition:QE},exit:{gfmFootnoteCallString:XE,gfmFootnoteCall:YE,gfmFootnoteDefinitionLabelString:ZE,gfmFootnoteDefinition:eT}}}function Wu(t){let e=!1;return t&&t.firstLineBlank&&(e=!0),{handlers:{footnoteDefinition:n,footnoteReference:Fy},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,o,s){let a=o.createTracker(s),l=a.move("[^"),c=o.enter("footnoteDefinition"),u=o.enter("label");return l+=a.move(o.safe(o.associationId(r),{before:l,after:"]"})),u(),l+=a.move("]:"),r.children&&r.children.length>0&&(a.shift(4),l+=a.move((e?` `:" ")+o.indentLines(o.containerFlow(r,a.current()),e?zy:nT))),c(),l}}function nT(t,e,n){return e===0?t:zy(t,e,n)}function zy(t,e,n){return(n?"":" ")+t}var rT=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];_y.peek=sT;function ju(){return{canContainEols:["delete"],enter:{strikethrough:iT},exit:{strikethrough:oT}}}function qu(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:rT}],handlers:{delete:_y}}}function iT(t){this.enter({type:"delete",children:[]},t)}function oT(t){this.exit(t)}function _y(t,e,n,r){let i=n.createTracker(r),o=n.enter("strikethrough"),s=i.move("~~");return s+=n.containerPhrasing(t,{...i.current(),before:s,after:"~"}),s+=i.move("~~"),o(),s}function sT(){return"~"}function aT(t){return t.length}function Hy(t,e){let n=e||{},r=(n.align||[]).concat(),i=n.stringLength||aT,o=[],s=[],a=[],l=[],c=0,u=-1;for(;++u<t.length;){let m=[],g=[],y=-1;for(t[u].length>c&&(c=t[u].length);++y<t[u].length;){let x=lT(t[u][y]);if(n.alignDelimiters!==!1){let C=i(x);g[y]=C,(l[y]===void 0||C>l[y])&&(l[y]=C)}m.push(x)}s[u]=m,a[u]=g}let f=-1;if(typeof r=="object"&&"length"in r)for(;++f<c;)o[f]=$y(r[f]);else{let m=$y(r);for(;++f<c;)o[f]=m}f=-1;let d=[],p=[];for(;++f<c;){let m=o[f],g="",y="";m===99?(g=":",y=":"):m===108?g=":":m===114&&(y=":");let x=n.alignDelimiters===!1?1:Math.max(1,l[f]-g.length-y.length),C=g+"-".repeat(x)+y;n.alignDelimiters!==!1&&(x=g.length+x+y.length,x>l[f]&&(l[f]=x),p[f]=x),d[f]=C}s.splice(1,0,d),a.splice(1,0,p),u=-1;let h=[];for(;++u<s.length;){let m=s[u],g=a[u];f=-1;let y=[];for(;++f<c;){let x=m[f]||"",C="",I="";if(n.alignDelimiters!==!1){let v=l[f]-(g[f]||0),w=o[f];w===114?C=" ".repeat(v):w===99?v%2?(C=" ".repeat(v/2+.5),I=" ".repeat(v/2-.5)):(C=" ".repeat(v/2),I=C):I=" ".repeat(v)}n.delimiterStart!==!1&&!f&&y.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&x==="")&&(n.delimiterStart!==!1||f)&&y.push(" "),n.alignDelimiters!==!1&&y.push(C),y.push(x),n.alignDelimiters!==!1&&y.push(I),n.padding!==!1&&y.push(" "),(n.delimiterEnd!==!1||f!==c-1)&&y.push("|")}h.push(n.delimiterEnd===!1?y.join("").replace(/ +$/,""):y.join(""))}return h.join(` `)}function lT(t){return t==null?"":String(t)}function $y(t){let e=typeof t=="string"?t.codePointAt(0):0;return e===67||e===99?99:e===76||e===108?108:e===82||e===114?114:0}function Uu(){return{enter:{table:cT,tableData:Vy,tableHeader:Vy,tableRow:fT},exit:{codeText:dT,table:uT,tableData:Ku,tableHeader:Ku,tableRow:Ku}}}function cT(t){let e=t._align;this.enter({type:"table",align:e.map(function(n){return n==="none"?null:n}),children:[]},t),this.data.inTable=!0}function uT(t){this.exit(t),this.data.inTable=void 0}function fT(t){this.enter({type:"tableRow",children:[]},t)}function Ku(t){this.exit(t)}function Vy(t){this.enter({type:"tableCell",children:[]},t)}function dT(t){let e=this.resume();this.data.inTable&&(e=e.replace(/\\([\\|])/g,pT));let n=this.stack[this.stack.length-1];n.type,n.value=e,this.exit(t)}function pT(t,e){return e==="|"?e:t}function Ju(t){let e=t||{},n=e.tableCellPadding,r=e.tablePipeAlign,i=e.stringLength,o=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:d,table:s,tableCell:l,tableRow:a}};function s(p,h,m,g){return c(u(p,m,g),p.align)}function a(p,h,m,g){let y=f(p,m,g),x=c([y]);return x.slice(0,x.indexOf(` @@ -63,19 +63,19 @@ $$`).replace(/^[ \t]*\$\$([^$\n]+)\$\$[ \t]*$/gm,(n,r)=>`$$ ${String(r).trim()} $$`).replace(/\\hat\s+(\\[A-Za-z]+|[A-Za-z])/g,"\\hat{$1}").replace(/\\hat(?!\{)(\\[A-Za-z]+|[A-Za-z])/g,"\\hat{$1}")),bo=(t,e)=>{let n=Rv(t);return(e==="userPaste"||e==="agentGenerated")&&(n=Lv(n)),e==="agentGenerated"&&(n=Bv(n)),Ov(n)};var xo=t=>{let e=t||"",n=e.match(/^(---\n[\s\S]*?\n---)(?:\n+|$)/);return n?{frontmatter:n[1],body:e.slice(n[0].length)}:{frontmatter:"",body:e}},fb=(t,e)=>{let n=Av(e),r=t?n.replace(/^\n+/,""):n;return t?`${t} -${r}`:r};var Pv=["transactions","fullSerializations","bridgeMessages","bridgeBytes","decorationNodes","decorationCacheHits","katexRenders","mermaidRenders","imageScans","imageNodeUpdates","codeTokenizations","outlineReports"],db=()=>Object.fromEntries(Pv.map(t=>[t,0])),wt=(t,e,n=1)=>{t&&(t[e]+=n)};var pb=t=>JSON.stringify(t.map(({level:e,title:n})=>[e,n]));var hb=(t,e)=>({...e,protocolVersion:2,documentID:t.documentID,documentGeneration:t.documentGeneration,revision:t.revision});var Fv=(t,e)=>{let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r-=1)n+=1;return n%2===1},mb=t=>{let e=[],n=/!\[\[([^\]\n]+)\]\]|\[\[([^\]\n]+)\]\]|==([^=\n]+)==|\^\[([^\]\n]+)\]/g,r=0;for(let i of t.matchAll(n)){let o=i.index||0;if(Fv(t,o))continue;o>r&&e.push({type:"text",value:t.slice(r,o)});let s=i[1]??i[2];if(s!==void 0){let a=s.indexOf("|"),l=(a<0?s:s.slice(0,a)).trim(),c=(a<0?"":s.slice(a+1)).trim();e.push({type:i[1]===void 0?"wikiLink":"embed",raw:s,target:l,label:c})}else i[3]!==void 0?e.push({type:"highlight",value:i[3]}):e.push({type:"inlineFootnote",value:i[4]});r=o+i[0].length}return r<t.length&&e.push({type:"text",value:t.slice(r)}),e.length?e:[{type:"text",value:t}]};var gb=t=>{let e=t.match(/^\[!([A-Za-z][A-Za-z0-9_-]*)\]([+-]?)(?:[ \t]+(.+))?$/);return e?{calloutType:e[1].toLowerCase(),fold:e[2]||"",title:(e[3]||"").trim()}:null},yb=t=>`[!${t.calloutType}]${t.fold}${t.title?` ${t.title}`:""}`;var Of=new Set(["system","serif","literary"]),zv=t=>{let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],i=r.type==="html"?String(r.value||"").match(/^<span data-weibei-font="(system|serif|literary)">$/):null;if(!i){e.push(r);continue}let o=t.findIndex((s,a)=>a>n&&s.type==="html"&&String(s.value||"")==="</span>");if(o<0){e.push(r);continue}e.push({type:"writingFont",font:i[1],children:t.slice(n+1,o)}),n=o}return e},_v=t=>t.type==="text"?{type:"text",value:t.value}:t.type==="highlight"?{type:"highlight",children:[{type:"text",value:t.value}]}:t.type==="inlineFootnote"?{type:"inlineFootnote",value:t.value}:{type:t.type,raw:t.raw,target:t.target,label:t.label},kb=t=>{if(!t.children||["code","inlineCode","html"].includes(t.type))return;if(t.type==="blockquote"){let n=t.children[0],r=n?.type==="paragraph"&&n.children?.length===1&&n.children[0].type==="text"?String(n.children[0].value||""):"",i=gb(r);if(i){t.type="callout",t.calloutType=i.calloutType,t.fold=i.fold,t.title=i.title,t.children=t.children.slice(1),t.children.length===0&&t.children.push({type:"paragraph",children:[]});let o=t.children[0]?.type==="paragraph"?t.children[0].children?.[0]:null;o?.type==="text"&&(o.value=String(o.value||"").replace(/^\[![A-Za-z][A-Za-z0-9_-]*\][+-]?[ \t]*/,""))}}let e=t.children.flatMap(n=>n.type!=="text"?(kb(n),[n]):mb(String(n.value||"")).map(_v));t.children=zv(e)},$v=Xe("weiBeiStructuredMarkdown",()=>(function(){let e=this.data();return(e.toMarkdownExtensions||(e.toMarkdownExtensions=[])).push({handlers:{wikiLink:(r,i,o,s)=>`[[${o.safe(r.raw,{...s,before:"[[",after:"]]"})}]]`,embed:(r,i,o,s)=>`![[${o.safe(r.raw,{...s,before:"![[",after:"]]"})}]]`,inlineFootnote:(r,i,o,s)=>`^[${o.safe(r.value,{...s,before:"^[",after:"]"})}]`,highlight:(r,i,o,s)=>`==${o.containerPhrasing(r,{...s,before:"==",after:"=="})}==`,writingFont:(r,i,o,s)=>{let a=Of.has(r.font)?r.font:"serif",l=o.containerPhrasing(r,{...s,before:">",after:"<"});return`<span data-weibei-font="${a}">${l}</span>`},callout:(r,i,o,s)=>{let l={type:"blockquote",children:[{type:"paragraph",children:[{type:"text",value:yb({calloutType:r.calloutType,fold:r.fold||"",title:r.title||""})}]},...r.children||[]]},c=o.enter("blockquote"),u=o.createTracker(s);u.move("> "),u.shift(2);let f=o.indentLines(o.containerFlow(l,u.current()),(d,p,h)=>`>${h?"":" "}${d}`);return c(),f}}}),r=>kb(r)})),bb=ne("wiki_link",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="wiki_link"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"wiki_link","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-wikilink weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="wikiLink",runner:(t,e,n)=>{t.addNode(n,{raw:e.raw,target:e.target,label:e.label})}},toMarkdown:{match:t=>t.type.name==="wiki_link",runner:(t,e)=>t.addNode("wikiLink",void 0,void 0,e.attrs)}})),xb=ne("embed",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="embed"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"embed","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-embed-note weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="embed",runner:(t,e,n)=>t.addNode(n,{raw:e.raw,target:e.target,label:e.label})},toMarkdown:{match:t=>t.type.name==="embed",runner:(t,e)=>t.addNode("embed",void 0,void 0,e.attrs)}})),wb=ne("inline_footnote",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{value:{default:""}},parseDOM:[{tag:'span[data-type="inline_footnote"]',getAttrs:t=>t instanceof HTMLElement?{value:t.dataset.value||""}:!1}],toDOM:t=>["span",{"data-type":"inline_footnote","data-value":t.attrs.value,class:"weibei-inline-footnote weibei-structured-node"},t.attrs.value],parseMarkdown:{match:t=>t.type==="inlineFootnote",runner:(t,e,n)=>t.addNode(n,{value:e.value})},toMarkdown:{match:t=>t.type.name==="inline_footnote",runner:(t,e)=>t.addNode("inlineFootnote",void 0,void 0,{value:e.attrs.value})}})),Hv=fe(t=>ks(/!\[\[([^\]\n]+)\]\]$/,xb.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),Vv=fe(t=>ks(/(?<!!)\[\[([^\]\n]+)\]\]$/,bb.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),Wv=fe(t=>ks(/\^\[([^\]\n]+)\]$/,wb.type(t),{getAttr:e=>({value:e[1]||""})})),Sb=kt("highlight",()=>({parseDOM:[{tag:"mark.weibei-highlight"}],toDOM:()=>["mark",{class:"weibei-highlight"},0],parseMarkdown:{match:t=>t.type==="highlight",runner:(t,e,n)=>t.openMark(n).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="highlight",runner:(t,e)=>{t.withMark(e,"highlight")}}})),jv=kt("writing_font",()=>({attrs:{font:{default:"serif"}},excludes:"writing_font",priority:10,parseDOM:[{tag:"span[data-weibei-font]",getAttrs:t=>{let e=t instanceof HTMLElement?t.dataset.weibeiFont:"";return e&&Of.has(e)?{font:e}:!1}}],toDOM:t=>["span",{"data-weibei-font":Of.has(t.attrs.font)?t.attrs.font:"serif"},0],parseMarkdown:{match:t=>t.type==="writingFont",runner:(t,e,n)=>t.openMark(n,{font:e.font}).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="writing_font",runner:(t,e)=>{t.withMark(e,"writingFont",void 0,{font:e.attrs.font})}}})),qv=fe(t=>Vt(/(?:^|[^\\=])==([^=\n]+)==$/,Sb.type(t))),Kv=ne("callout",()=>({content:"block+",group:"block",defining:!0,selectable:!0,attrs:{calloutType:{default:"note"},title:{default:""},fold:{default:""}},parseDOM:[{tag:'blockquote[data-type="callout"]',getAttrs:t=>t instanceof HTMLElement?{calloutType:t.dataset.callout||"note",title:t.dataset.calloutTitle||"",fold:t.dataset.calloutFold||""}:!1}],toDOM:t=>["blockquote",{"data-type":"callout","data-callout":t.attrs.calloutType,"data-callout-title":t.attrs.title,"data-callout-fold":t.attrs.fold,class:`weibei-callout weibei-callout-${t.attrs.calloutType}`},0],parseMarkdown:{match:t=>t.type==="callout",runner:(t,e,n)=>t.openNode(n,{calloutType:e.calloutType,title:e.title,fold:e.fold}).next(e.children).closeNode()},toMarkdown:{match:t=>t.type.name==="callout",runner:(t,e)=>{t.openNode("callout",void 0,e.attrs).next(e.content).closeNode()}}})),Cb=[$v,bb,xb,wb,jv,Sb,qv,Kv,Hv,Vv,Wv].flat();var Uv=window.webkit?.messageHandlers,Mt=window.weiBeiEditorCheckMode?db():null,ee,To="",Jf=null,So=null,ka=!1,zf=null,ci={text:null,rectKey:null,detailKey:null},pi="",Ze=!1,xa=window.weiBeiMarkdownCompactPreview===!0,ba=window.weiBeiDocumentID||"",fr=window.weiBeiDocumentGeneration||0,Jv={revision:0,dirty:!1};var Hb=!1,Gv=0,Vb=window.weiBeiMarkdownBaseURL||"",Qv=window.weiBeiLocalImageScheme||"weibeiimage";var Xv=0,Mb=0,ui=0,Yv=new Map,Zv=new Map;var eA=[nb,rb,ib].flat(),Mo=0,de=null,Ot=null,hi=null,_f=[],$f=[],dr=0;var Wb=t=>t==="en"?"en":"zh-Hans",ga=Wb(window.weiBeiInterfaceLanguage);var Eb={"zh-Hans":{properties:"\u5C5E\u6027",bootFailed:"Milkdown \u521D\u59CB\u5316\u5931\u8D25",imageMissing:"\u56FE\u7247\u672A\u627E\u5230",inlineFootnote:"\u884C\u5185\u811A\u6CE8\uFF1A{value}",openOrCreateNote:"\u6253\u5F00\u6216\u521B\u5EFA\u7B14\u8BB0\uFF1A{value}",openSource:"\u6253\u5F00\u6765\u6E90\uFF1A{value}",embed:"\u5D4C\u5165\uFF1A{value}",mermaidRendering:"\u6B63\u5728\u6E32\u67D3 Mermaid \u56FE\u8868...",mermaidFailed:`Mermaid \u56FE\u8868\u672A\u89E3\u6790 +${r}`:r};var Pv=["transactions","fullSerializations","bridgeMessages","bridgeBytes","decorationNodes","decorationCacheHits","katexRenders","mermaidRenders","imageScans","imageNodeUpdates","codeTokenizations","outlineReports"],db=()=>Object.fromEntries(Pv.map(t=>[t,0])),wt=(t,e,n=1)=>{t&&(t[e]+=n)};var pb=t=>JSON.stringify(t.map(({level:e,title:n})=>[e,n]));var hb=(t,e)=>({...e,protocolVersion:2,documentID:t.documentID,documentGeneration:t.documentGeneration,revision:t.revision});var Fv=(t,e)=>{let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r-=1)n+=1;return n%2===1},mb=t=>{let e=[],n=/!\[\[([^\]\n]+)\]\]|\[\[([^\]\n]+)\]\]|==([^=\n]+)==|\^\[([^\]\n]+)\]/g,r=0;for(let i of t.matchAll(n)){let o=i.index||0;if(Fv(t,o))continue;o>r&&e.push({type:"text",value:t.slice(r,o)});let s=i[1]??i[2];if(s!==void 0){let a=s.indexOf("|"),l=(a<0?s:s.slice(0,a)).trim(),c=(a<0?"":s.slice(a+1)).trim();e.push({type:i[1]===void 0?"wikiLink":"embed",raw:s,target:l,label:c})}else i[3]!==void 0?e.push({type:"highlight",value:i[3]}):e.push({type:"inlineFootnote",value:i[4]});r=o+i[0].length}return r<t.length&&e.push({type:"text",value:t.slice(r)}),e.length?e:[{type:"text",value:t}]};var gb=t=>{let e=t.match(/^\[!([A-Za-z][A-Za-z0-9_-]*)\]([+-]?)(?:[ \t]+(.+))?$/);return e?{calloutType:e[1].toLowerCase(),fold:e[2]||"",title:(e[3]||"").trim()}:null},yb=t=>`[!${t.calloutType}]${t.fold}${t.title?` ${t.title}`:""}`;var Of=new Set(["system","serif","literary"]),zv=t=>{let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],i=r.type==="html"?String(r.value||"").match(/^<span data-weibei-font="(system|serif|literary)">$/):null;if(!i){e.push(r);continue}let o=t.findIndex((s,a)=>a>n&&s.type==="html"&&String(s.value||"")==="</span>");if(o<0){e.push(r);continue}e.push({type:"writingFont",font:i[1],children:t.slice(n+1,o)}),n=o}return e},_v=t=>t.type==="text"?{type:"text",value:t.value}:t.type==="highlight"?{type:"highlight",children:[{type:"text",value:t.value}]}:t.type==="inlineFootnote"?{type:"inlineFootnote",value:t.value}:{type:t.type,raw:t.raw,target:t.target,label:t.label},kb=t=>{if(!t.children||["code","inlineCode","html"].includes(t.type))return;if(t.type==="blockquote"){let n=t.children[0],r=n?.type==="paragraph"&&n.children?.length===1&&n.children[0].type==="text"?String(n.children[0].value||""):"",i=gb(r);if(i){t.type="callout",t.calloutType=i.calloutType,t.fold=i.fold,t.title=i.title,t.children=t.children.slice(1),t.children.length===0&&t.children.push({type:"paragraph",children:[]});let o=t.children[0]?.type==="paragraph"?t.children[0].children?.[0]:null;o?.type==="text"&&(o.value=String(o.value||"").replace(/^\[![A-Za-z][A-Za-z0-9_-]*\][+-]?[ \t]*/,""))}}let e=t.children.flatMap(n=>n.type!=="text"?(kb(n),[n]):mb(String(n.value||"")).map(_v));t.children=zv(e)},$v=Xe("weiBeiStructuredMarkdown",()=>(function(){let e=this.data();return(e.toMarkdownExtensions||(e.toMarkdownExtensions=[])).push({handlers:{wikiLink:(r,i,o,s)=>`[[${o.safe(r.raw,{...s,before:"[[",after:"]]"})}]]`,embed:(r,i,o,s)=>`![[${o.safe(r.raw,{...s,before:"![[",after:"]]"})}]]`,inlineFootnote:(r,i,o,s)=>`^[${o.safe(r.value,{...s,before:"^[",after:"]"})}]`,highlight:(r,i,o,s)=>`==${o.containerPhrasing(r,{...s,before:"==",after:"=="})}==`,writingFont:(r,i,o,s)=>{let a=Of.has(r.font)?r.font:"serif",l=o.containerPhrasing(r,{...s,before:">",after:"<"});return`<span data-weibei-font="${a}">${l}</span>`},callout:(r,i,o,s)=>{let l={type:"blockquote",children:[{type:"paragraph",children:[{type:"text",value:yb({calloutType:r.calloutType,fold:r.fold||"",title:r.title||""})}]},...r.children||[]]},c=o.enter("blockquote"),u=o.createTracker(s);u.move("> "),u.shift(2);let f=o.indentLines(o.containerFlow(l,u.current()),(d,p,h)=>`>${h?"":" "}${d}`);return c(),f}}}),r=>kb(r)})),bb=ne("wiki_link",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="wiki_link"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"wiki_link","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-wikilink weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="wikiLink",runner:(t,e,n)=>{t.addNode(n,{raw:e.raw,target:e.target,label:e.label})}},toMarkdown:{match:t=>t.type.name==="wiki_link",runner:(t,e)=>t.addNode("wikiLink",void 0,void 0,e.attrs)}})),xb=ne("embed",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{raw:{default:""},target:{default:""},label:{default:""}},parseDOM:[{tag:'span[data-type="embed"]',getAttrs:t=>t instanceof HTMLElement?{raw:t.dataset.raw||"",target:t.dataset.target||"",label:t.dataset.label||""}:!1}],toDOM:t=>["span",{"data-type":"embed","data-raw":t.attrs.raw,"data-target":t.attrs.target,"data-label":t.attrs.label,class:"weibei-embed-note weibei-structured-node"},t.attrs.label||t.attrs.target],parseMarkdown:{match:t=>t.type==="embed",runner:(t,e,n)=>t.addNode(n,{raw:e.raw,target:e.target,label:e.label})},toMarkdown:{match:t=>t.type.name==="embed",runner:(t,e)=>t.addNode("embed",void 0,void 0,e.attrs)}})),wb=ne("inline_footnote",()=>({group:"inline",inline:!0,atom:!0,selectable:!0,attrs:{value:{default:""}},parseDOM:[{tag:'span[data-type="inline_footnote"]',getAttrs:t=>t instanceof HTMLElement?{value:t.dataset.value||""}:!1}],toDOM:t=>["span",{"data-type":"inline_footnote","data-value":t.attrs.value,class:"weibei-inline-footnote weibei-structured-node"},t.attrs.value],parseMarkdown:{match:t=>t.type==="inlineFootnote",runner:(t,e,n)=>t.addNode(n,{value:e.value})},toMarkdown:{match:t=>t.type.name==="inline_footnote",runner:(t,e)=>t.addNode("inlineFootnote",void 0,void 0,{value:e.attrs.value})}})),Hv=fe(t=>ks(/!\[\[([^\]\n]+)\]\]$/,xb.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),Vv=fe(t=>ks(/(?<!!)\[\[([^\]\n]+)\]\]$/,bb.type(t),{getAttr:e=>{let n=e[1]||"",[r="",...i]=n.split("|");return{raw:n,target:r.trim(),label:i.join("|").trim()}}})),Wv=fe(t=>ks(/\^\[([^\]\n]+)\]$/,wb.type(t),{getAttr:e=>({value:e[1]||""})})),Sb=kt("highlight",()=>({parseDOM:[{tag:"mark.weibei-highlight"}],toDOM:()=>["mark",{class:"weibei-highlight"},0],parseMarkdown:{match:t=>t.type==="highlight",runner:(t,e,n)=>t.openMark(n).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="highlight",runner:(t,e)=>{t.withMark(e,"highlight")}}})),jv=kt("writing_font",()=>({attrs:{font:{default:"serif"}},excludes:"writing_font",priority:10,parseDOM:[{tag:"span[data-weibei-font]",getAttrs:t=>{let e=t instanceof HTMLElement?t.dataset.weibeiFont:"";return e&&Of.has(e)?{font:e}:!1}}],toDOM:t=>["span",{"data-weibei-font":Of.has(t.attrs.font)?t.attrs.font:"serif"},0],parseMarkdown:{match:t=>t.type==="writingFont",runner:(t,e,n)=>t.openMark(n,{font:e.font}).next(e.children).closeMark(n)},toMarkdown:{match:t=>t.type.name==="writing_font",runner:(t,e)=>{t.withMark(e,"writingFont",void 0,{font:e.attrs.font})}}})),qv=fe(t=>Vt(/(?:^|[^\\=])==([^=\n]+)==$/,Sb.type(t))),Kv=ne("callout",()=>({content:"block+",group:"block",defining:!0,selectable:!0,attrs:{calloutType:{default:"note"},title:{default:""},fold:{default:""}},parseDOM:[{tag:'blockquote[data-type="callout"]',getAttrs:t=>t instanceof HTMLElement?{calloutType:t.dataset.callout||"note",title:t.dataset.calloutTitle||"",fold:t.dataset.calloutFold||""}:!1}],toDOM:t=>["blockquote",{"data-type":"callout","data-callout":t.attrs.calloutType,"data-callout-title":t.attrs.title,"data-callout-fold":t.attrs.fold,class:`weibei-callout weibei-callout-${t.attrs.calloutType}`},0],parseMarkdown:{match:t=>t.type==="callout",runner:(t,e,n)=>t.openNode(n,{calloutType:e.calloutType,title:e.title,fold:e.fold}).next(e.children).closeNode()},toMarkdown:{match:t=>t.type.name==="callout",runner:(t,e)=>{t.openNode("callout",void 0,e.attrs).next(e.content).closeNode()}}})),Cb=[$v,bb,xb,wb,jv,Sb,qv,Kv,Hv,Vv,Wv].flat();var Uv=window.webkit?.messageHandlers,Mt=window.weiBeiEditorCheckMode?db():null,ee,To="",Jf=null,So=null,ka=!1,zf=null,ci={text:null,rectKey:null,detailKey:null},pi="",Ze=!1,xa=window.weiBeiMarkdownCompactPreview===!0,ba=window.weiBeiDocumentID||"",fr=window.weiBeiDocumentGeneration||0,Jv={revision:0,dirty:!1},Gv=new Set;var Hb=!1,Qv=0,Vb=window.weiBeiMarkdownBaseURL||"",Xv=window.weiBeiLocalImageScheme||"weibeiimage";var Yv=0,Mb=0,ui=0,Zv=new Map,eA=new Map;var tA=[nb,rb,ib].flat(),Mo=0,de=null,Ot=null,hi=null,_f=[],$f=[],dr=0;var Wb=t=>t==="en"?"en":"zh-Hans",ga=Wb(window.weiBeiInterfaceLanguage);var Eb={"zh-Hans":{properties:"\u5C5E\u6027",bootFailed:"Milkdown \u521D\u59CB\u5316\u5931\u8D25",imageMissing:"\u56FE\u7247\u672A\u627E\u5230",inlineFootnote:"\u884C\u5185\u811A\u6CE8\uFF1A{value}",openOrCreateNote:"\u6253\u5F00\u6216\u521B\u5EFA\u7B14\u8BB0\uFF1A{value}",openSource:"\u6253\u5F00\u6765\u6E90\uFF1A{value}",embed:"\u5D4C\u5165\uFF1A{value}",mermaidRendering:"\u6B63\u5728\u6E32\u67D3 Mermaid \u56FE\u8868...",mermaidFailed:`Mermaid \u56FE\u8868\u672A\u89E3\u6790 {value}`,uploadingImage:"\u6B63\u5728\u6536\u7EB3\u56FE\u7247...",emptyNotePlaceholder:"\u4ECE\u8FD9\u91CC\u5F00\u59CB\u5199\u4E0B\u7B2C\u4E00\u53E5\u2026",slashNoResults:"\u6CA1\u6709\u5339\u914D\u547D\u4EE4",slashStructure:"\u7ED3\u6784",slashLists:"\u5217\u8868",slashContent:"\u5185\u5BB9",slashRichContent:"\u4E30\u5BCC\u5185\u5BB9",slashFonts:"\u5B57\u4F53",slashHeading1:"\u4E00\u7EA7\u6807\u9898",slashHeading2:"\u4E8C\u7EA7\u6807\u9898",slashHeading3:"\u4E09\u7EA7\u6807\u9898",slashHeading4:"\u56DB\u7EA7\u6807\u9898",slashHeading5:"\u4E94\u7EA7\u6807\u9898",slashHeading6:"\u516D\u7EA7\u6807\u9898",slashBulletList:"\u65E0\u5E8F\u5217\u8868",slashOrderedList:"\u6709\u5E8F\u5217\u8868",slashTaskList:"\u5F85\u529E\u5217\u8868",slashQuote:"\u5F15\u7528",slashCallout:"\u63D0\u793A\u5757",slashCode:"\u4EE3\u7801\u5757",slashDivider:"\u5206\u9694\u7EBF",slashTable:"\u8868\u683C",slashImage:"\u56FE\u7247",slashMermaid:"Mermaid \u56FE\u8868",slashLink:"\u94FE\u63A5",slashWikiLink:"\u7B14\u8BB0\u94FE\u63A5",slashFootnote:"\u811A\u6CE8",slashInlineMath:"\u884C\u5185\u516C\u5F0F",slashBlockMath:"\u5757\u7EA7\u516C\u5F0F",slashFontSystem:"\u5B57\u4F53\uFF1ASF Pro / PingFang SC",slashFontSerif:"\u5B57\u4F53\uFF1ASongti SC",slashFontLiterary:"\u5B57\u4F53\uFF1AWeiBeiStele",slashRows:"\u884C",slashColumns:"\u5217",slashInsertTable:"\u63D2\u5165\u8868\u683C",slashImageFailed:"\u56FE\u7247\u8BFB\u53D6\u6216\u4FDD\u5B58\u5931\u8D25",tableAddRow:"\uFF0B\u884C",tableDeleteRow:"\u2212\u884C",tableAddColumn:"\uFF0B\u5217",tableDeleteColumn:"\u2212\u5217",tableHeader:"\u8868\u5934",linkPlaceholder:"\u94FE\u63A5\u6587\u5B57",wikiLinkPlaceholder:"\u7B14\u8BB0\u6807\u9898",footnotePlaceholder:"\u811A\u6CE8\u5185\u5BB9",codeLanguage:"\u4EE3\u7801\u8BED\u8A00",codeLanguagePlaceholder:"text"},en:{properties:"Properties",bootFailed:"Milkdown failed to initialize",imageMissing:"Image not found",inlineFootnote:"Inline footnote: {value}",openOrCreateNote:"Open or create note: {value}",openSource:"Open source: {value}",embed:"Embed: {value}",mermaidRendering:"Rendering Mermaid diagram...",mermaidFailed:`Mermaid diagram did not parse -{value}`,uploadingImage:"Saving image...",emptyNotePlaceholder:"Start writing here\u2026",slashNoResults:"No matching commands",slashStructure:"Structure",slashLists:"Lists",slashContent:"Content",slashRichContent:"Rich content",slashFonts:"Fonts",slashHeading1:"Heading 1",slashHeading2:"Heading 2",slashHeading3:"Heading 3",slashHeading4:"Heading 4",slashHeading5:"Heading 5",slashHeading6:"Heading 6",slashBulletList:"Bulleted list",slashOrderedList:"Numbered list",slashTaskList:"To-do list",slashQuote:"Quote",slashCallout:"Callout",slashCode:"Code block",slashDivider:"Divider",slashTable:"Table",slashImage:"Image",slashMermaid:"Mermaid diagram",slashLink:"Link",slashWikiLink:"Note link",slashFootnote:"Footnote",slashInlineMath:"Inline formula",slashBlockMath:"Block formula",slashFontSystem:"Font: SF Pro / PingFang SC",slashFontSerif:"Font: Songti SC",slashFontLiterary:"Font: WeiBeiStele",slashRows:"Rows",slashColumns:"Columns",slashInsertTable:"Insert table",slashImageFailed:"Image could not be read or saved",tableAddRow:"+ Row",tableDeleteRow:"\u2212 Row",tableAddColumn:"+ Column",tableDeleteColumn:"\u2212 Column",tableHeader:"Header",linkPlaceholder:"Link text",wikiLinkPlaceholder:"Note title",footnotePlaceholder:"Footnote",codeLanguage:"Code language",codeLanguagePlaceholder:"text"}},Lt=(t,e={})=>{let n=Eb[ga]?.[t]||Eb["zh-Hans"][t]||t;for(let[r,i]of Object.entries(e))n=n.split(`{${r}}`).join(String(i));return n},tA=()=>Lt("properties"),nA=new RegExp(`(^|\\n)\\s*(?:>\\s*)*\\\\?\\[!(?:${Df})\\][+-]?[ \\t]*`,"gi"),rA=/<br\s*\/?>/gi,jb=t=>String(t||"").replace(rA,` -`).replace(/%%[\s\S]*?%%\n?/g,"").replace(/!\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=yA(n);return r.label||r.target}).replace(/\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=Xb(n);return r.display||r.target}).replace(/!\[([^\]\n]*)\]\([^\)\n]+\)/g,(e,n)=>Gb(n).alt||"").replace(/\[([^\]\n]+)\]\([^\)\n]+\)/g,"$1").replace(/==([^=\n]+)==/g,"$1").replace(/~~([^~\n]+)~~/g,"$1").replace(/`([^`\n]+)`/g,"$1").replace(/\^\[([^\]\n]+)\]/g,"$1").replace(nA,"$1").replace(/(^|\n)\s*>\s?/g,"$1").replace(/(^|\n)\s*[-*+]\s+\[[ xX]\]\s*/g,"$1").replace(/[ \t]+\n/g,` +{value}`,uploadingImage:"Saving image...",emptyNotePlaceholder:"Start writing here\u2026",slashNoResults:"No matching commands",slashStructure:"Structure",slashLists:"Lists",slashContent:"Content",slashRichContent:"Rich content",slashFonts:"Fonts",slashHeading1:"Heading 1",slashHeading2:"Heading 2",slashHeading3:"Heading 3",slashHeading4:"Heading 4",slashHeading5:"Heading 5",slashHeading6:"Heading 6",slashBulletList:"Bulleted list",slashOrderedList:"Numbered list",slashTaskList:"To-do list",slashQuote:"Quote",slashCallout:"Callout",slashCode:"Code block",slashDivider:"Divider",slashTable:"Table",slashImage:"Image",slashMermaid:"Mermaid diagram",slashLink:"Link",slashWikiLink:"Note link",slashFootnote:"Footnote",slashInlineMath:"Inline formula",slashBlockMath:"Block formula",slashFontSystem:"Font: SF Pro / PingFang SC",slashFontSerif:"Font: Songti SC",slashFontLiterary:"Font: WeiBeiStele",slashRows:"Rows",slashColumns:"Columns",slashInsertTable:"Insert table",slashImageFailed:"Image could not be read or saved",tableAddRow:"+ Row",tableDeleteRow:"\u2212 Row",tableAddColumn:"+ Column",tableDeleteColumn:"\u2212 Column",tableHeader:"Header",linkPlaceholder:"Link text",wikiLinkPlaceholder:"Note title",footnotePlaceholder:"Footnote",codeLanguage:"Code language",codeLanguagePlaceholder:"text"}},Lt=(t,e={})=>{let n=Eb[ga]?.[t]||Eb["zh-Hans"][t]||t;for(let[r,i]of Object.entries(e))n=n.split(`{${r}}`).join(String(i));return n},nA=()=>Lt("properties"),rA=new RegExp(`(^|\\n)\\s*(?:>\\s*)*\\\\?\\[!(?:${Df})\\][+-]?[ \\t]*`,"gi"),iA=/<br\s*\/?>/gi,jb=t=>String(t||"").replace(iA,` +`).replace(/%%[\s\S]*?%%\n?/g,"").replace(/!\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=kA(n);return r.label||r.target}).replace(/\[\[([^\]\n]+)\]\]/g,(e,n)=>{let r=Xb(n);return r.display||r.target}).replace(/!\[([^\]\n]*)\]\([^\)\n]+\)/g,(e,n)=>Gb(n).alt||"").replace(/\[([^\]\n]+)\]\([^\)\n]+\)/g,"$1").replace(/==([^=\n]+)==/g,"$1").replace(/~~([^~\n]+)~~/g,"$1").replace(/`([^`\n]+)`/g,"$1").replace(/\^\[([^\]\n]+)\]/g,"$1").replace(rA,"$1").replace(/(^|\n)\s*>\s?/g,"$1").replace(/(^|\n)\s*[-*+]\s+\[[ xX]\]\s*/g,"$1").replace(/[ \t]+\n/g,` `).replace(/\n{2,}/g,` -`).trim(),qb=t=>t==="glassLight"||t==="glassMist"?"xuan":t==="glassDark"||t==="glassSlate"?"stele":t==="xuan"||t==="inkstone"||t==="stele"||t==="paper"?t:"paper",iA=t=>["glassLight","glassDark","glassMist","glassSlate"].includes(t)?t:"",fi=qb(window.weiBeiTheme),oA=()=>{switch(fi){case"inkstone":return{background:"#151515",primaryColor:"#1c1c1c",primaryTextColor:"#d7cbb0",primaryBorderColor:"#3a3328",lineColor:"#8b5e3c",secondaryColor:"#222222",tertiaryColor:"#171717",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"stele":return{background:"#1e2228",primaryColor:"#252a32",primaryTextColor:"#d2d6dc",primaryBorderColor:"#3a414c",lineColor:"#8a7a5c",secondaryColor:"#2a3038",tertiaryColor:"#1a1e24",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"xuan":return{background:"#f7f4ef",primaryColor:"#fcfbf8",primaryTextColor:"#25231f",primaryBorderColor:"#d8d2c6",lineColor:"#6e634f",secondaryColor:"#ebe6dc",tertiaryColor:"#f7f4ef",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};default:return{background:"#fbf5e8",primaryColor:"#f6eddc",primaryTextColor:"#2e261f",primaryBorderColor:"#cbb79b",lineColor:"#7a6250",secondaryColor:"#efe4d2",tertiaryColor:"#f8f0e1",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'}}},sA=t=>{t.initialize({startOnLoad:!1,securityLevel:"strict",theme:"base",themeVariables:oA()})},Kb=t=>{fi=qb(t);let e=iA(t);document.documentElement.dataset.weibeiTheme=fi,document.body&&(document.body.dataset.weibeiTheme=fi),e?(document.documentElement.dataset.weibeiGlass=e,document.body&&(document.body.dataset.weibeiGlass=e)):(delete document.documentElement.dataset.weibeiGlass,document.body&&delete document.body.dataset.weibeiGlass),ui+=1};Kb(window.weiBeiTheme);var ur=t=>{if(window.WeiBeiEditorBootFailed){window.WeiBeiEditorBootFailed(t);return}let e=document.querySelector("#editor");e&&(e.innerHTML=`<pre style="white-space:pre-wrap;color:#9f3427;padding:24px;font:13px/1.5 SFMono-Regular,Menlo,monospace;">${Lt("bootFailed")} -${String(t?.stack||t)}</pre>`)};window.addEventListener("error",t=>ur(t.error||t.message));window.addEventListener("unhandledrejection",t=>ur(t.reason));var et=(t,e={})=>{let n=Uv?.[t];if(!n)return;let r=hb({documentID:ba,documentGeneration:fr,revision:Jv.revision},e);typeof r.markdown=="string"&&(Gv+=1),wt(Mt,"bridgeMessages"),Mt&&wt(Mt,"bridgeBytes",new TextEncoder().encode(JSON.stringify(r)).byteLength),n.postMessage(r)};var en=null;var aA=()=>document.documentElement.dataset.weibeiReduceMotion==="true",lA=t=>{document.documentElement.dataset.weibeiReduceMotion=t===!0||t==="true"?"true":"false"},cA=t=>{let e=Number(t),n=Number.isFinite(e)&&e>0?e:1;document.documentElement.style.setProperty("--weibei-text-scale",String(n))};document.documentElement.dataset.weibeiCompactPreview=xa?"true":"false";window.weiBeiEditorCheckMode&&(document.documentElement.dataset.weibeiCheckMode="true");var Tb=0,Lf=0,Ib=0,vb=0,Ub=()=>[document.querySelector("#editor"),document.querySelector(".milkdown"),document.querySelector(".ProseMirror")].filter(Boolean),uA=t=>{let e=t.getBoundingClientRect?.();return Math.max(0,t.scrollHeight||0,t.offsetHeight||0,t.clientHeight||0,e?.height||0)},Hf=()=>{let t=Ub(),e=Math.ceil(Math.max(1,...t.map(uA))),n=Math.ceil(Math.max(1,...t.map(r=>r.getBoundingClientRect?.().width||r.clientWidth||0)));window.WeiBeiCompactPreviewHeight=e,window.WeiBeiCompactPreviewMeasuredAt=Date.now(),!(Math.abs(e-Ib)<1&&Math.abs(n-vb)<1)&&(Ib=e,vb=n,et("contentHeightChanged",{height:e}))},fA=()=>{!xa||!Hb||(Hf(),window.cancelAnimationFrame(Tb),Tb=window.requestAnimationFrame(Hf))},je=()=>{if(!xa||Lf)return;let t=de!==null?100:40;Lf=window.setTimeout(()=>{Lf=0,fA()},t)},dA=()=>{if(xa){if(window.ResizeObserver){let t=new ResizeObserver(je);Ub().forEach(e=>t.observe(e))}je(),document.fonts?.ready?.then(je).catch(()=>{})}},pA=()=>{let t=window.getSelection();if(!t||t.rangeCount===0)return null;let e=t.getRangeAt(0).getBoundingClientRect();return!e||e.width+e.height===0?null:{x:e.left+e.width/2,y:e.bottom,width:e.width,height:e.height}},Io=t=>fb(pi,t),hA=t=>String(t||"").split(/\r?\n/).slice(1,-1).map(e=>{let n=e.match(/^\s*([^:#][^:]*):\s*(.*)$/);return n?{key:n[1].trim(),value:n[2].trim()||" "}:null}).filter(Boolean),vo=()=>{let t=document.querySelector("#frontmatter-panel");if(!t)return;let e=hA(pi);t.dataset.visible=e.length>0?"true":"false",t.innerHTML=e.length>0?`<div class="frontmatter-title">${tA()}</div>${e.map(n=>`<div class="frontmatter-row"><span class="frontmatter-key">${Vf(n.key)}</span><span>${Vf(n.value)}</span></div>`).join("")}`:""},Vf=t=>String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Ab=t=>`${Qv}://image?src=${encodeURIComponent(t)}`;var Jb=t=>{let n=(t||"").trim().match(/^(\d{1,4})(?:x(\d{1,4}))?$/i);return n?{width:Math.max(1,Number(n[1])),height:n[2]?Math.max(1,Number(n[2])):null}:null},mA=(t,e)=>{t.style.width=e?`${e.width}px`:"",t.style.maxWidth=e?"100%":"",t.style.height=e?.height?`${e.height}px`:""},Gb=t=>{let e=String(t||"").split("|"),n=e.length>1?Jb(e.at(-1)):null;return{alt:n?e.slice(0,-1).join("|").trim():String(t||""),size:n}},gA=(t,e,n)=>{let r=e,i=n;for(;r<i&&/\s/.test(t[r]);)r+=1;for(;i>r&&/\s/.test(t[i-1]);)i-=1;return{start:r,end:i}},Qb=t=>{let e=String(t||""),n=[],r=0,i="";for(let o=0;o<e.length;o+=1){let s=e[o],a=e[o+1];if(s==="\\"&&a==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+2,i="",o+=1;continue}if(s==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+1,i="";continue}i+=s}return n.push({raw:e.slice(r),value:i,start:r,end:e.length}),n},Xb=t=>{let e=String(t||"").trim(),n=Qb(e),i=(n.shift()||{value:"",start:0,end:0}).value.trim(),o=n,s=o.map(u=>u.value).join("|").trim(),a=o.length>0?gA(e,o[0].start,o.at(-1).end):null,l=i.indexOf("#"),c=l>=0?i.slice(0,l).trim():i;return{source:e,target:i,noteTitle:c,display:s||i,alias:s,aliasRange:a}},yA=t=>{let e=Qb(String(t||"").trim()),n=(e.shift()?.value||"").trim(),r=e.at(-1),i=r?Jb(r.value):null,o=i?e.slice(0,-1):e;return{target:n,size:i,label:o.map(s=>s.value).join("|").trim()}},Nb=()=>{let t=fi==="inkstone"?{background:"#151515",accent:"#a6362b",text:"#d7cbb0"}:{background:"#efe6d8",accent:"#9f3b2f",text:"#6b5148"},e=`<svg xmlns="http://www.w3.org/2000/svg" width="156" height="34" viewBox="0 0 156 34"> +`).trim(),qb=t=>t==="glassLight"||t==="glassMist"?"xuan":t==="glassDark"||t==="glassSlate"?"stele":t==="xuan"||t==="inkstone"||t==="stele"||t==="paper"?t:"paper",oA=t=>["glassLight","glassDark","glassMist","glassSlate"].includes(t)?t:"",fi=qb(window.weiBeiTheme),sA=()=>{switch(fi){case"inkstone":return{background:"#151515",primaryColor:"#1c1c1c",primaryTextColor:"#d7cbb0",primaryBorderColor:"#3a3328",lineColor:"#8b5e3c",secondaryColor:"#222222",tertiaryColor:"#171717",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"stele":return{background:"#1e2228",primaryColor:"#252a32",primaryTextColor:"#d2d6dc",primaryBorderColor:"#3a414c",lineColor:"#8a7a5c",secondaryColor:"#2a3038",tertiaryColor:"#1a1e24",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};case"xuan":return{background:"#f7f4ef",primaryColor:"#fcfbf8",primaryTextColor:"#25231f",primaryBorderColor:"#d8d2c6",lineColor:"#6e634f",secondaryColor:"#ebe6dc",tertiaryColor:"#f7f4ef",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'};default:return{background:"#fbf5e8",primaryColor:"#f6eddc",primaryTextColor:"#2e261f",primaryBorderColor:"#cbb79b",lineColor:"#7a6250",secondaryColor:"#efe4d2",tertiaryColor:"#f8f0e1",fontFamily:'-apple-system, BlinkMacSystemFont, "Songti SC", serif'}}},aA=t=>{t.initialize({startOnLoad:!1,securityLevel:"strict",theme:"base",themeVariables:sA()})},Kb=t=>{fi=qb(t);let e=oA(t);document.documentElement.dataset.weibeiTheme=fi,document.body&&(document.body.dataset.weibeiTheme=fi),e?(document.documentElement.dataset.weibeiGlass=e,document.body&&(document.body.dataset.weibeiGlass=e)):(delete document.documentElement.dataset.weibeiGlass,document.body&&delete document.body.dataset.weibeiGlass),ui+=1};Kb(window.weiBeiTheme);var ur=t=>{if(window.WeiBeiEditorBootFailed){window.WeiBeiEditorBootFailed(t);return}let e=document.querySelector("#editor");e&&(e.innerHTML=`<pre style="white-space:pre-wrap;color:#9f3427;padding:24px;font:13px/1.5 SFMono-Regular,Menlo,monospace;">${Lt("bootFailed")} +${String(t?.stack||t)}</pre>`)};window.addEventListener("error",t=>ur(t.error||t.message));window.addEventListener("unhandledrejection",t=>ur(t.reason));var et=(t,e={})=>{let n=Uv?.[t];if(!n)return;let r=hb({documentID:ba,documentGeneration:fr,revision:Jv.revision},e);typeof r.markdown=="string"&&(Qv+=1),wt(Mt,"bridgeMessages"),Mt&&wt(Mt,"bridgeBytes",new TextEncoder().encode(JSON.stringify(r)).byteLength),n.postMessage(r)};var en=null;var lA=()=>document.documentElement.dataset.weibeiReduceMotion==="true",cA=t=>{document.documentElement.dataset.weibeiReduceMotion=t===!0||t==="true"?"true":"false"},uA=t=>{let e=Number(t),n=Number.isFinite(e)&&e>0?e:1;document.documentElement.style.setProperty("--weibei-text-scale",String(n))};document.documentElement.dataset.weibeiCompactPreview=xa?"true":"false";window.weiBeiEditorCheckMode&&(document.documentElement.dataset.weibeiCheckMode="true");var Tb=0,Lf=0,Ib=0,vb=0,Ub=()=>[document.querySelector("#editor"),document.querySelector(".milkdown"),document.querySelector(".ProseMirror")].filter(Boolean),fA=t=>{let e=t.getBoundingClientRect?.();return Math.max(0,t.scrollHeight||0,t.offsetHeight||0,t.clientHeight||0,e?.height||0)},Hf=()=>{let t=Ub(),e=Math.ceil(Math.max(1,...t.map(fA))),n=Math.ceil(Math.max(1,...t.map(r=>r.getBoundingClientRect?.().width||r.clientWidth||0)));window.WeiBeiCompactPreviewHeight=e,window.WeiBeiCompactPreviewMeasuredAt=Date.now(),!(Math.abs(e-Ib)<1&&Math.abs(n-vb)<1)&&(Ib=e,vb=n,et("contentHeightChanged",{height:e}))},dA=()=>{!xa||!Hb||(Hf(),window.cancelAnimationFrame(Tb),Tb=window.requestAnimationFrame(Hf))},je=()=>{if(!xa||Lf)return;let t=de!==null?100:40;Lf=window.setTimeout(()=>{Lf=0,dA()},t)},pA=()=>{if(xa){if(window.ResizeObserver){let t=new ResizeObserver(je);Ub().forEach(e=>t.observe(e))}je(),document.fonts?.ready?.then(je).catch(()=>{})}},hA=()=>{let t=window.getSelection();if(!t||t.rangeCount===0)return null;let e=t.getRangeAt(0).getBoundingClientRect();return!e||e.width+e.height===0?null:{x:e.left+e.width/2,y:e.bottom,width:e.width,height:e.height}},Io=t=>fb(pi,t),mA=t=>String(t||"").split(/\r?\n/).slice(1,-1).map(e=>{let n=e.match(/^\s*([^:#][^:]*):\s*(.*)$/);return n?{key:n[1].trim(),value:n[2].trim()||" "}:null}).filter(Boolean),vo=()=>{let t=document.querySelector("#frontmatter-panel");if(!t)return;let e=mA(pi);t.dataset.visible=e.length>0?"true":"false",t.innerHTML=e.length>0?`<div class="frontmatter-title">${nA()}</div>${e.map(n=>`<div class="frontmatter-row"><span class="frontmatter-key">${Vf(n.key)}</span><span>${Vf(n.value)}</span></div>`).join("")}`:""},Vf=t=>String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Ab=t=>`${Xv}://image?src=${encodeURIComponent(t)}`;var Jb=t=>{let n=(t||"").trim().match(/^(\d{1,4})(?:x(\d{1,4}))?$/i);return n?{width:Math.max(1,Number(n[1])),height:n[2]?Math.max(1,Number(n[2])):null}:null},gA=(t,e)=>{t.style.width=e?`${e.width}px`:"",t.style.maxWidth=e?"100%":"",t.style.height=e?.height?`${e.height}px`:""},Gb=t=>{let e=String(t||"").split("|"),n=e.length>1?Jb(e.at(-1)):null;return{alt:n?e.slice(0,-1).join("|").trim():String(t||""),size:n}},yA=(t,e,n)=>{let r=e,i=n;for(;r<i&&/\s/.test(t[r]);)r+=1;for(;i>r&&/\s/.test(t[i-1]);)i-=1;return{start:r,end:i}},Qb=t=>{let e=String(t||""),n=[],r=0,i="";for(let o=0;o<e.length;o+=1){let s=e[o],a=e[o+1];if(s==="\\"&&a==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+2,i="",o+=1;continue}if(s==="|"){n.push({raw:e.slice(r,o),value:i,start:r,end:o}),r=o+1,i="";continue}i+=s}return n.push({raw:e.slice(r),value:i,start:r,end:e.length}),n},Xb=t=>{let e=String(t||"").trim(),n=Qb(e),i=(n.shift()||{value:"",start:0,end:0}).value.trim(),o=n,s=o.map(u=>u.value).join("|").trim(),a=o.length>0?yA(e,o[0].start,o.at(-1).end):null,l=i.indexOf("#"),c=l>=0?i.slice(0,l).trim():i;return{source:e,target:i,noteTitle:c,display:s||i,alias:s,aliasRange:a}},kA=t=>{let e=Qb(String(t||"").trim()),n=(e.shift()?.value||"").trim(),r=e.at(-1),i=r?Jb(r.value):null,o=i?e.slice(0,-1):e;return{target:n,size:i,label:o.map(s=>s.value).join("|").trim()}},Nb=()=>{let t=fi==="inkstone"?{background:"#151515",accent:"#a6362b",text:"#d7cbb0"}:{background:"#efe6d8",accent:"#9f3b2f",text:"#6b5148"},e=`<svg xmlns="http://www.w3.org/2000/svg" width="156" height="34" viewBox="0 0 156 34"> <rect width="156" height="34" rx="3" fill="${t.background}"/> <path d="M18 22l5-6 4 4 3-3 6 5" fill="none" stroke="${t.accent}" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/> <rect x="17" y="11" width="20" height="14" rx="2" fill="none" stroke="${t.accent}" stroke-width="1.2"/> <text x="48" y="22" fill="${t.text}" font-family="-apple-system, BlinkMacSystemFont, 'Songti SC', serif" font-size="13">${Vf(Lt("imageMissing"))}</text> -</svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`},kA=t=>{if(!t||/^(?:data:|blob:|weibeiimage:)/i.test(t))return t;if(/^https:/i.test(t))return Ab(t);if(/^http:/i.test(t))return"";try{let e=new URL(t,Vb||window.location.href).href;return/^(?:file:|https:)/i.test(e)?Ab(e):/^(?:data:|blob:|weibeiimage:)/i.test(e)?e:""}catch{return""}},Yb=()=>{document.body.dataset.editable=Ze?"true":"false",document.querySelectorAll(".weibei-code-language-input").forEach(t=>{t instanceof HTMLInputElement&&(t.readOnly=!Ze,t.tabIndex=Ze?0:-1,t.setAttribute("aria-readonly",t.readOnly?"true":"false"),t.setAttribute("aria-label",Lt("codeLanguage")),t.placeholder=Lt("codeLanguagePlaceholder"))})},Wf=new Set,bA=new Set,xA=t=>{let e=t,n=document.createElement("img");n.className="weibei-image";let r=()=>{let i=Gb(e.attrs.alt||""),o=kA(String(e.attrs.src||""));n.alt=i.alt,n.title=String(e.attrs.title||""),mA(n,i.size),n.src=o||Nb()};return n.addEventListener("load",je),n.addEventListener("error",()=>{n.src=Nb()}),Wf.add(r),r(),{dom:n,update(i){return i.type!==e.type?!1:(e=i,r(),!0)},destroy(){Wf.delete(r)}}};var Zb=()=>Wf.forEach(t=>t()),wA=()=>{if(!ee)return null;let t=ee.action(e=>e.get(ie).state.selection);return!t||t.empty?null:{from:t.from,to:t.to}},SA=()=>ee?ee.action(t=>{let{selection:e}=t.get(ie).state;if(!e||e.empty)return"";let n=e.content().content;return jb(n.textBetween(0,n.size,` -`))}):"",CA=()=>jb(window.getSelection()?.toString()||SA()),Ct=(t,e,n,r,i={})=>{n<=e||t.push(se.inline(e,n,{...i,class:r}))},MA=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=4),EA=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=2),TA=(t,e,n,r)=>{Ze||$f.length===0||$f.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ct(t,n+a,n+a+i.text.length,"weibei-remark-mark",{"data-record-id":i.id,title:"\u56DE\u8BBF\u8FD9\u53E5\u7684\u672D\u8BB0"}),s+=1,o=a+i.text.length}r.set(i.id,s)})},IA=(t,e,n,r)=>{Ze||_f.length===0||_f.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ct(t,n+a,n+a+i.text.length,"weibei-selection-ask-mark",{"data-thread-id":i.id,title:"\u6253\u5F00\u5F53\u65F6\u7684\u9009\u533A\u95EE\u7B54"}),s+=1,o=a+i.text.length}r.set(i.id,s)})};var vA=(t,e,n)=>{for(let r of e.matchAll(/(?:^|[\s`])((?:来源:|Source:)[^`\n]+)/g)){let i=r[0].startsWith(r[1])?0:1,o=r[1].startsWith("\u6765\u6E90\uFF1A")?"\u6765\u6E90\uFF1A":"Source:",s=n+(r.index||0)+i,a=s+r[1].length;Ct(t,s,a,"weibei-source-reference",{role:"link",tabindex:"0",title:Lt("openSource",{value:r[1].slice(o.length).trim()}),"data-source-reference":r[1]})}},AA=(t,e,n,r)=>{let i=0;for(;i<e.length;){if(r.open){let a=e.indexOf("%%",i);if(a<0){Ct(t,n+i,n+e.length,"weibei-comment");return}Ct(t,n+i,n+a+2,"weibei-comment"),r.open=!1,i=a+2;continue}let o=e.indexOf("%%",i);if(o<0)return;let s=e.indexOf("%%",o+2);if(s<0){Ct(t,n+o,n+e.length,"weibei-comment"),r.open=!0;return}Ct(t,n+o,n+s+2,"weibei-comment"),i=s+2}},NA=(t,e,n)=>{for(let r of e.matchAll(/(^|\s)(#[\p{L}\p{N}_/-]+)\b/gu)){let i=n+(r.index||0)+r[1].length;Ct(t,i,i+r[2].length,"weibei-tag")}for(let r of e.matchAll(/(^|\s)(\^[A-Za-z0-9-]+)\s*$/g)){let i=n+(r.index||0)+r[1].length;Ct(t,i,i+r[2].length,"weibei-block-id")}},RA=(t,e,n)=>{for(let r of e.matchAll(/<br\s*\/?>/gi)){let i=n+(r.index||0),o=i+r[0].length;Ct(t,i,o,"weibei-html-break-source"),t.push(se.widget(o,()=>{let s=document.createElement("br");return s.className="weibei-html-break-preview",s},{side:1}))}},Rb=t=>{let e=document.createElement("div");e.className="weibei-mermaid-render",e.textContent=Lt("mermaidRendering");let n="\0",r=0,i=0,o=(s,a=!1)=>{let l=String(s||"");if(l===n)return;n=l;let c=i+=1;window.clearTimeout(r),r=window.setTimeout(async()=>{if(!(!e.isConnected||c!==i)){e.classList.remove("weibei-mermaid-error");try{let u=await lb();sA(u);let f=`weibei-mermaid-${Xv+=1}`;wt(Mt,"mermaidRenders");let{svg:d,bindFunctions:p}=await u.render(f,l,e);if(!e.isConnected||c!==i)return;e.innerHTML=d,p?.(e),e.dataset.rendered="true"}catch(u){if(!e.isConnected||c!==i)return;e.classList.add("weibei-mermaid-error"),e.textContent=Lt("mermaidFailed",{value:String(u?.message||u)})}je()}},a?300:0)};return o(t),{element:e,updateSource:o}},ya=new WeakMap,St=null,wo=!1,DA=t=>{if(!wo||!(t.selection instanceof z))return null;let{$from:e}=t.selection;for(let n=e.depth;n>0;n-=1){let r=e.node(n);if(r.type.name==="code_block")return Gf(r.attrs.language||"")!=="mermaid"?null:{node:r,pos:e.before(n)}}return null},OA=t=>{St&&(St.documentGeneration!==fr||St.contentGeneration!==Mo||St.generation!==ui||t?.pos!==St.pos)&&(St=null)},LA=(t,e,n)=>{let r=n?.pos===e;if(r&&!St){let s=ya.get(t);St=s?.generation===ui?{...s,pos:e,documentGeneration:fr,contentGeneration:Mo}:{...Rb(t.textContent),generation:ui,key:`mermaid-preview-${Mb+=1}`,pos:e,documentGeneration:fr,contentGeneration:Mo}}if(r)return St.updateSource(t.textContent,!0),St;let i=ya.get(t);if(i?.generation===ui)return i.updateSource(t.textContent),i;let o={...Rb(t.textContent),generation:ui,key:`mermaid-preview-${Mb+=1}`};return ya.set(t,o),o},BA=(t,e,n,r)=>{if(Gf(e.attrs.language||"")!=="mermaid")return!1;t.push(se.node(n,n+e.nodeSize,{class:"weibei-code-block weibei-mermaid-block","data-language":"mermaid"}));let i=LA(e,n,r);return t.push(se.widget(n+e.nodeSize,()=>i.element,{side:-1,key:i.key})),!0},PA=t=>{let e=Xb(t);return e.target||e.noteTitle},FA=t=>{let e=t instanceof Element?t.closest(".weibei-wikilink, .weibei-embed-note[data-wikilink-title]"):null;return e?.getAttribute("data-wikilink-title")||e?.textContent?.trim()||""},jf=t=>{let e=FA(t);return e?(et("wikiLinkActivated",{title:e}),!0):!1},zA=t=>(t instanceof Element?t.closest(".weibei-source-reference[data-source-reference]"):null)?.getAttribute("data-source-reference")||"",qf=t=>{let e=zA(t);return e?(et("sourceReferenceActivated",{reference:e}),!0):!1},ex=t=>{let e=t instanceof Element?t.closest(".weibei-selection-ask-mark[data-thread-id]"):null,n=e?.getAttribute("data-thread-id")||"";return n?(et("selectionAskMark",{threadId:n,text:e.textContent||""}),!0):!1},tx=t=>{let e=t instanceof Element?t.closest(".weibei-remark-mark[data-record-id]"):null,n=e?.getAttribute("data-record-id")||"";return n?(et("remarkMark",{recordId:n,text:e.textContent||""}),!0):!1},nx=t=>{if(Ze||!(t instanceof Element))return!1;let e=t.closest('blockquote.weibei-callout[data-callout-fold="-"]');return e?(e.classList.toggle("weibei-callout-open"),!0):!1},Gf=t=>{let e=(t||"").trim().toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",sh:"bash",shell:"bash",zsh:"bash",md:"markdown",yml:"yaml"}[e]||e},rx=t=>typeof t=="string"?t.length:Array.isArray(t.content)?t.content.reduce((e,n)=>e+rx(n),0):String(t.content||"").length,_A=t=>{let e=Array.isArray(t.alias)?t.alias:t.alias?[t.alias]:[];return["weibei-prism-token","token",t.type,...e].filter(Boolean).join(" ")},Db=new WeakMap,$A=new Set(["bash","css","do","java","javascript","json","jsx","markdown","python","r","ruby","rust","sql","stata","swift","tsx","typescript","yaml"]),Co=null,Ob=!1,HA=()=>{Co||Ob||(Ob=!0,cb().then(t=>{Co=t,dr+=1,ee?.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiPrismReady",!0))})}).catch(ur))},ix=(t,e,n)=>{let r=n;for(let i of e){let o=rx(i);typeof i!="string"&&o>0&&(t.push({from:r,to:r+o,className:_A(i)}),Array.isArray(i.content)&&ix(t,i.content,r)),r+=o}},VA=(t,e,n)=>{let r=Gf(e.attrs.language||"");if(!$A.has(r))return;if(!Co){HA();return}let i=Db.get(e);try{i||(wt(Mt,"codeTokenizations"),i=[],ix(i,Co.tokenize(e.textContent,Co.languages[r]),0),Db.set(e,i)),i.forEach(o=>Ct(t,n+1+o.from,n+1+o.to,o.className))}catch{}},Lb=t=>{let e=t,n=e.type.name==="math_block",r=document.createElement(n?"div":"span");r.className=`weibei-math-node ${n?"weibei-math-block":"weibei-math-inline"}`,r.dataset.type=e.type.name;let i=0,o=()=>n?String(e.attrs.value||""):e.textContent,s=async()=>{let a=i+=1,l=o();r.dataset.value=l,r.textContent=l||"\u516C\u5F0F";let c=(u,f=!1)=>{a!==i||f&&!r.isConnected||(wt(Mt,"katexRenders"),u.render(l,r,{throwOnError:!0,strict:!1,trust:!1,displayMode:n}))};try{let u=ab();u?c(u):c(await sb(),!0)}catch{a===i&&(r.textContent=l||"\u516C\u5F0F")}je()};return s(),{dom:r,update(a){return a.type!==e.type?!1:(e=a,s(),!0)},ignoreMutation(){return!0}}};var WA=()=>ee?ee.action(t=>{let e=t.get(ie),n=e.state.selection.from,r="";return e.state.doc.descendants((i,o)=>{if(!i.isText||r)return!0;let s=i.text||"",a=o,l=o+s.length;if(n<a||n>l)return!0;for(let c of s.matchAll(/\[\[([^\]\n]+)\]\]/g)){let u=a+(c.index||0),f=u+c[0].length;if(n>=u&&n<=f)return r=PA(c[1]),!1}return!0}),r}):"";var jA="#editor, .ProseMirror pre, .weibei-math-block",Bf=new WeakMap,qA=t=>{if(!(t instanceof Element))return;t.classList.add("weibei-scroll-active");let e=Bf.get(t);e&&window.clearTimeout(e),Bf.set(t,window.setTimeout(()=>{t.classList.remove("weibei-scroll-active"),Bf.delete(t)},850))},KA=()=>{document.addEventListener("scroll",t=>{let e=t.target instanceof Element?t.target.closest(jA):null;e&&qA(e)},!0)};var UA=(t,e)=>{if(!Ze||e.key!=="Tab"||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof z)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(" "));return t.dispatch(r.setSelection(z.create(r.doc,n.from+1)).scrollIntoView()),!0},JA=new Set(["-","'",'"']),GA=(t,e)=>{if(!Ze||!JA.has(e.key)||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof z)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(e.key));return t.dispatch(r.setSelection(z.create(r.doc,n.from+e.key.length)).scrollIntoView()),!0},QA=(t,e)=>{if(!Ze||e.inputType!=="insertReplacementText"||e.isComposing||!e.cancelable)return!1;let{selection:n}=t.state;return!(n instanceof z)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0?!1:(e.preventDefault(),e.stopImmediatePropagation(),!0)};var XA=(t,e)=>{if(!Ze||!Ae(t.state))return!1;if(e==="addRow")return Ey(t.state,t.dispatch);if(e==="deleteRow")return ra(t.state,t.dispatch);if(e==="addColumn")return ta(t.state,t.dispatch);if(e==="deleteColumn")return na(t.state,t.dispatch);if(e==="header"){let{$from:n}=t.state.selection;for(let r=n.depth;r>0;r-=1){if(n.node(r).type.name!=="table")continue;let i=Math.min(n.before(r)+4,t.state.doc.content.size);return t.dispatch(t.state.tr.setSelection(_.near(t.state.doc.resolve(i),1)).scrollIntoView()),!0}}return!1},Pf=t=>{t?(en.dataset.state="open",en.setAttribute("aria-hidden","false")):en.dataset.state!=="closed"&&(en.dataset.state="closed",en.setAttribute("aria-hidden","true"))},YA=t=>{if(en.querySelectorAll("button").forEach(i=>{let o=Lt(i.dataset.label);i.textContent=o,i.setAttribute("aria-label",o)}),!Ze||!Ae(t.state)){Pf(!1);return}let e=t.domAtPos(t.state.selection.from).node,n=(e instanceof Element?e:e.parentElement)?.closest("td, th");if(!(n instanceof HTMLElement)){Pf(!1);return}let r=n.getBoundingClientRect();en.style.left=`${Math.max(8,Math.min(window.innerWidth-en.offsetWidth-8,r.left))}px`,en.style.top=`${Math.max(8,r.top-32)}px`,Pf(!0)},Bb={doc:null,focusedMermaidPos:null,generation:-1,decorations:re.empty},Pb=(t,e,n)=>{let r=!1,i=Math.max(0,Math.min(t.content.size,e-1)),o=Math.max(i,Math.min(t.content.size,Math.max(n,e+1)+1));return t.nodesBetween(i,o,s=>(s.type.name==="heading"&&(r=!0),!r)),r},ZA=t=>t.steps.some((e,n)=>{let r=t.docs[n],i=t.docs[n+1]||t.doc,o=!1;return e.getMap().forEach((s,a,l,c)=>{(Pb(r,s,a)||Pb(i,l,c))&&(o=!0)}),o}),eN=Ce(()=>new Y({state:{init:()=>null,apply:(t,e,n,r)=>(wt(Mt,"transactions"),t.docChanged&&ZA(t)&&Xf(r.doc),e)},view(t){let e={autocapitalize:"none",autocorrect:"off",spellcheck:"false"},n=new Map(Object.keys(e).map(h=>[h,t.dom.getAttribute(h)])),r=h=>{if(h.state.selection.$from.parent.type.spec.code===!0){for(let[m,g]of Object.entries(e))h.dom.setAttribute(m,g);return}for(let[m,g]of n)g===null?h.dom.removeAttribute(m):h.dom.setAttribute(m,g)},i=h=>{let m=h.state.doc;h.dom.classList.toggle("weibei-empty-document",m.childCount===1&&m.firstChild?.type.name==="paragraph"&&m.firstChild.content.size===0),h.dom.dataset.emptyPlaceholder=Lt("emptyNotePlaceholder")},o=h=>{wo!==h&&(wo=h,t.dispatch(t.state.tr.setMeta("weibeiMermaidFocusChanged",h)))},s=h=>o(h.target===t.dom),a=h=>{h.target===t.dom&&o(!1)},l=()=>{Jf=To,ka=!1;let{$from:h}=t.state.selection;So=h.parent.isTextblock&&h.parent.content.size===0?h.before(h.depth):null},c=()=>{ka=!0,setTimeout(nN)},u=h=>{h.target!==t.dom||!t.hasFocus()||!UA(t,h)&&!GA(t,h)||(h.preventDefault(),h.stopImmediatePropagation())},f=h=>{h.target===t.dom&&QA(t,h)},d=h=>h.preventDefault(),p=h=>{let m=h.target instanceof Element?h.target.closest("button[data-action]"):null;m instanceof HTMLElement&&(XA(t,m.dataset.action||""),t.focus(),window.requestAnimationFrame(()=>YA(t)))};return t.dom.addEventListener("focus",s,!0),t.dom.addEventListener("blur",a,!0),wo=t.hasFocus(),{update(h,m){h.state.doc.eq(m.doc)||(je(),di())},destroy(){t.dom.removeEventListener("focus",s,!0),t.dom.removeEventListener("blur",a,!0),wo=!1,St=null,ya=new WeakMap}}},props:{handlePaste:()=>!1,handleDrop:()=>!1,handleTextInput:()=>!1,handleClick(t,e,n){return tx(n.target)||ex(n.target)||jf(n.target)||qf(n.target)||nx(n.target)},handleKeyDown(t,e){if(e.key!=="Enter"&&e.key!==" ")return!1;if(qf(e.target))return e.preventDefault(),!0;if(!e.metaKey&&!e.ctrlKey)return!1;let n=WA();return n?(et("wikiLinkActivated",{title:n}),e.preventDefault(),!0):!1},decorations(t){let e=DA(t);OA(e);let n=e?.pos??null,r=Bb;if(r.doc===t.doc&&r.focusedMermaidPos===n&&r.generation===dr)return wt(Mt,"decorationCacheHits"),r.decorations;let i=[],o={open:!1},s=new Map,a=new Map;t.doc.descendants((c,u,f)=>{if(wt(Mt,"decorationNodes"),c.type.name==="code_block")return BA(i,c,u,e)||(i.push(se.node(u,u+c.nodeSize,{class:"weibei-code-block","data-language":c.attrs.language||""})),VA(i,c,u)),!1;if(c.isText){let p=u,h=c.text||"";if((c.marks||[]).some(g=>g.type.name.toLowerCase().includes("code"))||de!==null)return!0;RA(i,h,p),AA(i,h,p,o),vA(i,h,p),NA(i,h,p),IA(i,h,p,s),TA(i,h,p,a)}return!0});let l=re.create(t.doc,i);return Bb={doc:t.doc,focusedMermaidPos:n,generation:dr,decorations:l},l}}})),Ff=()=>{if(window.weiBeiSuppressSelectionReport)return;let t=CA(),e=t?pA():null,n=t&&ee?ee.action(o=>{let{state:s}=o.get(ie),{selection:a}=s,c=["strong","emphasis","highlight","link","inlineCode"].filter(y=>s.schema.marks[y]&&s.doc.rangeHasMark(a.from,a.to,s.schema.marks[y])),u=s.schema.marks.writing_font,f,d=!1;u&&s.doc.nodesBetween(a.from,a.to,y=>{if(!y.isText)return!0;let x=u.isInSet(y.marks||[])?.attrs.font||"serif";return f===void 0?f=x:f!==x&&(d=!0),!0}),f&&!d&&c.push(`font:${f}`);let p=a instanceof H&&a.node.type.name==="math_inline";p&&c.push("inlineMath");let h=a.$from.parent.type.name;for(let y=a.$from.depth;y>0;y-=1){let x=a.$from.node(y).type.name;if(x==="blockquote"||x==="block_quote"){h="blockquote";break}}h==="heading"&&(h=`heading${a.$from.parent.attrs.level||""}`);let m="",g=s.schema.marks.link;return g&&s.doc.nodesBetween(a.from,a.to,y=>{let x=g.isInSet(y.marks||[]);return x&&!m&&(m=String(x.attrs.href||"")),!m}),{activeMarks:c,blockType:h,canConvertToMath:p||a instanceof z&&!a.empty&&a.$from.parent===a.$to.parent&&a.$from.parent.isTextblock,linkTarget:m}}):{activeMarks:[],blockType:"",canConvertToMath:!1,linkTarget:""},r=e?`${Math.round(e.x)}:${Math.round(e.y)}:${Math.round(e.width)}:${Math.round(e.height)}`:"",i=JSON.stringify(n);if(!(t===ci.text&&r===ci.rectKey&&i===ci.detailKey)){if(ci={text:t,rectKey:r,detailKey:i},!t){zf=null,et("selectionChanged",{text:"",rect:null,...n});return}zf=wA(),et("selectionChanged",{text:t,rect:e,...n})}};var Qf=()=>{if(!ee)throw new Error("WeiBei editor is not ready")},ox=t=>{_f=MA(t),dr+=1,ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},sx=t=>{$f=EA(t),dr+=1,ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},tN=()=>{if(!ee||So===null)return;let t=So;So=null,ee.action(e=>{let n=e.get(ie);n.domObserver?.flush();let r=n.state.doc.nodeAt(t);if(!r?.isTextblock||!r.textContent)return;let i=n.state.schema.nodes.hardbreak||n.state.schema.nodes.hard_break,o=[];for(let a=0;a<r.childCount;a+=1){let l=r.child(a);l.type!==i&&o.push(l)}if(o.length!==r.childCount){let a=r.type.create(r.attrs,E.fromArray(o),r.marks),l=n.state.tr.replaceWith(t,t+r.nodeSize,a).scrollIntoView();l.setSelection(z.create(l.doc,Math.min(t+1+a.content.size,l.doc.content.size))),n.dispatch(l)}let s=n.nodeDOM(t);s instanceof HTMLElement&&(s.querySelectorAll("br").forEach(a=>a.remove()),n.domObserver?.flush())})},nN=()=>{ee&&(tN(),ka=!1,Jf=null,je(),di())},Ao=()=>ee.action(t=>t.get(G)),rN=(t=!0)=>{wa(),de!==null&&(Ao().call(yo.key,{keep:t}),de=null,Ot=null,hi=null)},ax=t=>{Qf(),wa();let e=String(t||"");hi=e;let n=xo(e);pi=n.frontmatter,vo();let r=n.body,i=Ot!==null&&de===Ot&&r.startsWith(Ot)?r.slice(Ot.length):null,o;i!==null&&!/[$<>\\`\r]/.test(i)?(o=r,Ot=r):(o=bo(r,"agentGenerated"),Ot=o===r?r:null,To=Io(o));let s=Ao();de===null?(s.call(lr.key),de=""):o.startsWith(de)||(s.call(li.key,{diffReview:!1}),s.call(lr.key),de="");let a=o.slice(de.length);a&&s.call(go.key,a),de=o,je()},iN=t=>{let e=String(t||"");if(!e)return;let n=hi;ax(n===null?e:n+e)},cr=null,oN=24,sN=12,Fb=33,aN=3e3,lN=240,wa=()=>{cr!=null&&(window.clearTimeout(cr),cr=null)},zb=t=>{let e=Ao();de===null?(e.call(lr.key),de=""):t.startsWith(de)||(e.call(li.key,{diffReview:!1}),e.call(lr.key),de="");let n=t.slice(de.length);n&&e.call(go.key,n),de=t,je()},_b=()=>{Ao().call(li.key,{diffReview:!1}),Ot=null,de=null,hi=null,wa();try{ee?.action(t=>{t.get(ie).updateState(t.get(ie).state)})}catch{}Hf(),je()},cN=(t,e)=>{wa(),Ot=null;let n=String(t||""),r=xo(n);pi=r.frontmatter,vo();let i=bo(r.body,"agentGenerated");To=Io(i),hi=n;let o=de,s=e?.paced===!0&&o!==null&&i.startsWith(o)&&i.length-o.length>oN;if(o!==null&&s){let a=o.length,l=0,c=Date.now(),u=()=>{cr=null;let f=Date.now();l+=1,a=Math.min(i.length,a+sN);let d=a>=i.length||f-c>=aN||l>=lN;try{if(zb(d?i:i.slice(0,a)),!d){cr=window.setTimeout(u,Fb);return}_b()}catch{cr=null,de=null,Ot=null;try{Ao().call(yo.key,{keep:!1})}catch{}try{lx(n)}catch{}je()}};cr=window.setTimeout(u,Fb),je();return}zb(i),_b()},lx=t=>{Qf(),rN(),hi=null,Jf=null,So=null,ka=!1,Mo+=1;let e=xo(t||""),n=bo(e.body,"userDocument");pi=e.frontmatter,vo(),ee.action(vg(n)),To=Io(n),ee.action(r=>Xf(r.get(ie).state.doc)),je()};var uN=()=>(Qf(),wt(Mt,"fullSerializations"),Io(ee.action(Ig())));var cx=()=>Array.from(document.querySelectorAll(".ProseMirror h1, .ProseMirror h2, .ProseMirror h3, .ProseMirror h4, .ProseMirror h5, .ProseMirror h6")),$b=0,ma=-2,Kf=null,Xf=t=>{let e=[],n=Math.max(1,t.content.size);t.descendants((i,o)=>{if(i.type.name!=="heading")return!0;let s=i.textContent.trim();if(!s)return!1;let a=e.length;return e.push({id:`note-heading-${a}`,index:a,level:Number(i.attrs.level||1),title:s,position:Math.max(0,Math.min(1,o/n))}),!1});let r=pb(e);r!==Kf&&(Kf=r,wt(Mt,"outlineReports"),et("outlineChanged",{items:e}))},di=()=>{window.cancelAnimationFrame($b),$b=window.requestAnimationFrame(()=>{let t=cx();if(t.length===0){ma!==-1&&(ma=-1,et("activeHeadingChanged",{index:null}));return}let e=Math.max(0,window.innerHeight*.32),n=0;t.forEach((r,i)=>{r.getBoundingClientRect().top<=e&&(n=i)}),n!==ma&&(ma=n,et("activeHeadingChanged",{index:n}))})},fN=t=>{let e=Number(t),n=cx(),r=Number.isFinite(e)?n[Math.max(0,Math.floor(e))]:null;if(!r)return!1;let i=aA();return r.scrollIntoView({block:"start",behavior:i?"auto":"smooth"}),i?di():window.setTimeout(di,180),!0},dN=(t,e)=>{let n=t!==ba||e!==fr;ba=t,fr=e,n&&(Kf=null,Mo+=1,Zv.clear(),Yv.clear(),ox([]),sx([]))};var pN=t=>{Kb(t),dr+=1,Zb(),ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiThemeChanged",fi))})},hN=t=>{ga=Wb(t),dr+=1,document.documentElement.dataset.weibeiLanguage=ga,vo(),Yb(),bA.forEach(e=>e()),ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiLanguageChanged",ga))})},mN=()=>ee?(ee.action(t=>t.get(ie).focus()),!0):!1;window.WeiBeiEditor={getMarkdown:uN,setMarkdown:t=>lx(String(t||"")),updateStreamingMarkdown:t=>{try{ax(t)}catch(e){ur(e)}},appendStreamingMarkdown:t=>{try{iN(t)}catch(e){ur(e)}},finishStreamingMarkdown:(t,e)=>{try{return cN(t,e),!0}catch(n){return ur(n),!1}},setDocumentID:t=>{let e=t||"";e!==ba&&dN(e,fr+1)},setTheme:pN,setInterfaceLanguage:hN,setReduceMotion:lA,setTextScale:cA,focus:mN,scrollToHeading:fN,setSelectionAskMarks:ox,setSelectionRemarkMarks:sx,setMarkdownBaseURL:t=>{Vb=t||"",Zb()}};var Eo=xo(window.initialMarkdown||"");Eo.body=bo(Eo.body,"userDocument");pi=Eo.frontmatter;To=Io(Eo.body);vo();var Uf=Cg.make().config(t=>{t.set(no,document.querySelector("#editor")),t.set(Yi,Eo.body),t.set(to,{editable:()=>Ze,nodeViews:{image:xA,math_inline:Lb,math_block:Lb}}),t.set(wn.key,{throttleMs:0,scrollFollow:!1,diffReviewOnEnd:!1,ignoreAttrs:{heading:["id"]}})});Uf=Uf.use(eN).use(ny).use(Mk).use(Cb).use(eA).use(Qk).use(Ce(()=>Yk(()=>de!==null)));Uf.use(Sf).config(t=>{t.get(fa).selectionUpdated(()=>{requestAnimationFrame(Ff)})}).create().then(t=>{ee=t,Yb(),KA(),document.querySelector("#editor-status")?.remove(),document.addEventListener("mouseup",Ff),document.addEventListener("pointerdown",()=>{window.weiBeiSuppressSelectionReport||(zf=null,ci.text="",ci.rectKey="",et("selectionChanged",{text:"",rect:null}))},!0),document.addEventListener("click",e=>{Ze&&e.target instanceof Element&&e.target.closest(".weibei-structured-node")||!tx(e.target)&&!ex(e.target)&&!jf(e.target)&&!qf(e.target)&&!nx(e.target)||(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keydown",e=>{e.key!=="Enter"&&e.key!==" "||jf(e.target)&&(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keyup",e=>{Ff()}),document.addEventListener("scroll",di,!0),et("editorReady",{}),window.setTimeout(()=>{Hb=!0,dA(),ee.action(e=>Xf(e.get(ie).state.doc)),di()})}).catch(ur);})(); +</svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`},bA=t=>{if(!t||/^(?:data:|blob:|weibeiimage:)/i.test(t))return t;if(/^https:/i.test(t))return Ab(t);if(/^http:/i.test(t))return"";try{let e=new URL(t,Vb||window.location.href).href;return/^(?:file:|https:)/i.test(e)?Ab(e):/^(?:data:|blob:|weibeiimage:)/i.test(e)?e:""}catch{return""}},Yb=()=>{document.body.dataset.editable=Ze?"true":"false",document.querySelectorAll(".weibei-code-language-input").forEach(t=>{t instanceof HTMLInputElement&&(t.readOnly=!Ze,t.tabIndex=Ze?0:-1,t.setAttribute("aria-readonly",t.readOnly?"true":"false"),t.setAttribute("aria-label",Lt("codeLanguage")),t.placeholder=Lt("codeLanguagePlaceholder"))})},Wf=new Set,xA=new Set,wA=t=>{let e=t,n=document.createElement("img");n.className="weibei-image";let r=()=>{let i=Gb(e.attrs.alt||""),o=bA(String(e.attrs.src||""));n.alt=i.alt,n.title=String(e.attrs.title||""),gA(n,i.size),n.src=o||Nb()};return n.addEventListener("load",je),n.addEventListener("error",()=>{n.src=Nb()}),Wf.add(r),r(),{dom:n,update(i){return i.type!==e.type?!1:(e=i,r(),!0)},destroy(){Wf.delete(r)}}};var Zb=()=>Wf.forEach(t=>t()),SA=()=>{if(!ee)return null;let t=ee.action(e=>e.get(ie).state.selection);return!t||t.empty?null:{from:t.from,to:t.to}},CA=()=>ee?ee.action(t=>{let{selection:e}=t.get(ie).state;if(!e||e.empty)return"";let n=e.content().content;return jb(n.textBetween(0,n.size,` +`))}):"",MA=()=>jb(window.getSelection()?.toString()||CA()),Ct=(t,e,n,r,i={})=>{n<=e||t.push(se.inline(e,n,{...i,class:r}))},EA=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=4),TA=t=>(Array.isArray(t)?t:[]).map(e=>({id:String(e?.id||""),text:String(e?.text||"").trim()})).filter(e=>e.id&&e.text.length>=2),IA=(t,e,n,r)=>{Ze||$f.length===0||$f.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ct(t,n+a,n+a+i.text.length,"weibei-remark-mark",{"data-record-id":i.id,title:"\u56DE\u8BBF\u8FD9\u53E5\u7684\u672D\u8BB0"}),s+=1,o=a+i.text.length}r.set(i.id,s)})},vA=(t,e,n,r)=>{Ze||_f.length===0||_f.forEach(i=>{let o=0,s=r.get(i.id)||0;for(;s<3;){let a=e.indexOf(i.text,o);if(a<0)break;Ct(t,n+a,n+a+i.text.length,"weibei-selection-ask-mark",{"data-thread-id":i.id,title:"\u6253\u5F00\u5F53\u65F6\u7684\u9009\u533A\u95EE\u7B54"}),s+=1,o=a+i.text.length}r.set(i.id,s)})};var AA=(t,e,n)=>{for(let r of e.matchAll(/(?:^|[\s`])((?:来源:|Source:)[^`\n]+)/g)){let i=r[0].startsWith(r[1])?0:1,o=r[1].startsWith("\u6765\u6E90\uFF1A")?"\u6765\u6E90\uFF1A":"Source:",s=n+(r.index||0)+i,a=s+r[1].length;Ct(t,s,a,"weibei-source-reference",{role:"link",tabindex:"0",title:Lt("openSource",{value:r[1].slice(o.length).trim()}),"data-source-reference":r[1]})}},NA=(t,e,n,r)=>{let i=0;for(;i<e.length;){if(r.open){let a=e.indexOf("%%",i);if(a<0){Ct(t,n+i,n+e.length,"weibei-comment");return}Ct(t,n+i,n+a+2,"weibei-comment"),r.open=!1,i=a+2;continue}let o=e.indexOf("%%",i);if(o<0)return;let s=e.indexOf("%%",o+2);if(s<0){Ct(t,n+o,n+e.length,"weibei-comment"),r.open=!0;return}Ct(t,n+o,n+s+2,"weibei-comment"),i=s+2}},RA=(t,e,n)=>{for(let r of e.matchAll(/(^|\s)(#[\p{L}\p{N}_/-]+)\b/gu)){let i=n+(r.index||0)+r[1].length;Ct(t,i,i+r[2].length,"weibei-tag")}for(let r of e.matchAll(/(^|\s)(\^[A-Za-z0-9-]+)\s*$/g)){let i=n+(r.index||0)+r[1].length;Ct(t,i,i+r[2].length,"weibei-block-id")}},DA=(t,e,n)=>{for(let r of e.matchAll(/<br\s*\/?>/gi)){let i=n+(r.index||0),o=i+r[0].length;Ct(t,i,o,"weibei-html-break-source"),t.push(se.widget(o,()=>{let s=document.createElement("br");return s.className="weibei-html-break-preview",s},{side:1}))}},Rb=t=>{let e=document.createElement("div");e.className="weibei-mermaid-render",e.textContent=Lt("mermaidRendering");let n="\0",r=0,i=0,o=(s,a=!1)=>{let l=String(s||"");if(l===n)return;n=l;let c=i+=1;window.clearTimeout(r),r=window.setTimeout(async()=>{if(!(!e.isConnected||c!==i)){e.classList.remove("weibei-mermaid-error");try{let u=await lb();aA(u);let f=`weibei-mermaid-${Yv+=1}`;wt(Mt,"mermaidRenders");let{svg:d,bindFunctions:p}=await u.render(f,l,e);if(!e.isConnected||c!==i)return;e.innerHTML=d,p?.(e),e.dataset.rendered="true"}catch(u){if(!e.isConnected||c!==i)return;e.classList.add("weibei-mermaid-error"),e.textContent=Lt("mermaidFailed",{value:String(u?.message||u)})}je()}},a?300:0)};return o(t),{element:e,updateSource:o}},ya=new WeakMap,St=null,wo=!1,OA=t=>{if(!wo||!(t.selection instanceof z))return null;let{$from:e}=t.selection;for(let n=e.depth;n>0;n-=1){let r=e.node(n);if(r.type.name==="code_block")return Gf(r.attrs.language||"")!=="mermaid"?null:{node:r,pos:e.before(n)}}return null},LA=t=>{St&&(St.documentGeneration!==fr||St.contentGeneration!==Mo||St.generation!==ui||t?.pos!==St.pos)&&(St=null)},BA=(t,e,n)=>{let r=n?.pos===e;if(r&&!St){let s=ya.get(t);St=s?.generation===ui?{...s,pos:e,documentGeneration:fr,contentGeneration:Mo}:{...Rb(t.textContent),generation:ui,key:`mermaid-preview-${Mb+=1}`,pos:e,documentGeneration:fr,contentGeneration:Mo}}if(r)return St.updateSource(t.textContent,!0),St;let i=ya.get(t);if(i?.generation===ui)return i.updateSource(t.textContent),i;let o={...Rb(t.textContent),generation:ui,key:`mermaid-preview-${Mb+=1}`};return ya.set(t,o),o},PA=(t,e,n,r)=>{if(Gf(e.attrs.language||"")!=="mermaid")return!1;t.push(se.node(n,n+e.nodeSize,{class:"weibei-code-block weibei-mermaid-block","data-language":"mermaid"}));let i=BA(e,n,r);return t.push(se.widget(n+e.nodeSize,()=>i.element,{side:-1,key:i.key})),!0},FA=t=>{let e=Xb(t);return e.target||e.noteTitle},zA=t=>{let e=t instanceof Element?t.closest(".weibei-wikilink, .weibei-embed-note[data-wikilink-title]"):null;return e?.getAttribute("data-wikilink-title")||e?.textContent?.trim()||""},jf=t=>{let e=zA(t);return e?(et("wikiLinkActivated",{title:e}),!0):!1},_A=t=>(t instanceof Element?t.closest(".weibei-source-reference[data-source-reference]"):null)?.getAttribute("data-source-reference")||"",qf=t=>{let e=_A(t);return e?(et("sourceReferenceActivated",{reference:e}),!0):!1},ex=t=>{let e=t instanceof Element?t.closest(".weibei-selection-ask-mark[data-thread-id]"):null,n=e?.getAttribute("data-thread-id")||"";return n?(et("selectionAskMark",{threadId:n,text:e.textContent||""}),!0):!1},tx=t=>{let e=t instanceof Element?t.closest(".weibei-remark-mark[data-record-id]"):null,n=e?.getAttribute("data-record-id")||"";return n?(et("remarkMark",{recordId:n,text:e.textContent||""}),!0):!1},nx=t=>{if(Ze||!(t instanceof Element))return!1;let e=t.closest('blockquote.weibei-callout[data-callout-fold="-"]');return e?(e.classList.toggle("weibei-callout-open"),!0):!1},Gf=t=>{let e=(t||"").trim().toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",sh:"bash",shell:"bash",zsh:"bash",md:"markdown",yml:"yaml"}[e]||e},rx=t=>typeof t=="string"?t.length:Array.isArray(t.content)?t.content.reduce((e,n)=>e+rx(n),0):String(t.content||"").length,$A=t=>{let e=Array.isArray(t.alias)?t.alias:t.alias?[t.alias]:[];return["weibei-prism-token","token",t.type,...e].filter(Boolean).join(" ")},Db=new WeakMap,HA=new Set(["bash","css","do","java","javascript","json","jsx","markdown","python","r","ruby","rust","sql","stata","swift","tsx","typescript","yaml"]),Co=null,Ob=!1,VA=()=>{Co||Ob||(Ob=!0,cb().then(t=>{Co=t,dr+=1,ee?.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiPrismReady",!0))})}).catch(ur))},ix=(t,e,n)=>{let r=n;for(let i of e){let o=rx(i);typeof i!="string"&&o>0&&(t.push({from:r,to:r+o,className:$A(i)}),Array.isArray(i.content)&&ix(t,i.content,r)),r+=o}},WA=(t,e,n)=>{let r=Gf(e.attrs.language||"");if(!HA.has(r))return;if(!Co){VA();return}let i=Db.get(e);try{i||(wt(Mt,"codeTokenizations"),i=[],ix(i,Co.tokenize(e.textContent,Co.languages[r]),0),Db.set(e,i)),i.forEach(o=>Ct(t,n+1+o.from,n+1+o.to,o.className))}catch{}},Lb=t=>{let e=t,n=e.type.name==="math_block",r=document.createElement(n?"div":"span");r.className=`weibei-math-node ${n?"weibei-math-block":"weibei-math-inline"}`,r.dataset.type=e.type.name;let i=0,o=()=>n?String(e.attrs.value||""):e.textContent,s=async()=>{let a=i+=1,l=o();r.dataset.value=l,r.textContent=l||"\u516C\u5F0F";let c=(u,f=!1)=>{a!==i||f&&!r.isConnected||(wt(Mt,"katexRenders"),u.render(l,r,{throwOnError:!0,strict:!1,trust:!1,displayMode:n}))};try{let u=ab();u?c(u):c(await sb(),!0)}catch{a===i&&(r.textContent=l||"\u516C\u5F0F")}je()};return s(),{dom:r,update(a){return a.type!==e.type?!1:(e=a,s(),!0)},ignoreMutation(){return!0}}};var jA=()=>ee?ee.action(t=>{let e=t.get(ie),n=e.state.selection.from,r="";return e.state.doc.descendants((i,o)=>{if(!i.isText||r)return!0;let s=i.text||"",a=o,l=o+s.length;if(n<a||n>l)return!0;for(let c of s.matchAll(/\[\[([^\]\n]+)\]\]/g)){let u=a+(c.index||0),f=u+c[0].length;if(n>=u&&n<=f)return r=FA(c[1]),!1}return!0}),r}):"";var qA="#editor, .ProseMirror pre, .weibei-math-block",Bf=new WeakMap,KA=t=>{if(!(t instanceof Element))return;t.classList.add("weibei-scroll-active");let e=Bf.get(t);e&&window.clearTimeout(e),Bf.set(t,window.setTimeout(()=>{t.classList.remove("weibei-scroll-active"),Bf.delete(t)},850))},UA=()=>{document.addEventListener("scroll",t=>{let e=t.target instanceof Element?t.target.closest(qA):null;e&&KA(e)},!0)};var JA=(t,e)=>{if(!Ze||e.key!=="Tab"||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof z)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(" "));return t.dispatch(r.setSelection(z.create(r.doc,n.from+1)).scrollIntoView()),!0},GA=new Set(["-","'",'"']),QA=(t,e)=>{if(!Ze||!GA.has(e.key)||e.altKey||e.metaKey||e.ctrlKey||e.isComposing||e.keyCode===229)return!1;let{selection:n}=t.state;if(!(n instanceof z)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0)return!1;let r=t.state.tr.replaceWith(n.from,n.to,t.state.schema.text(e.key));return t.dispatch(r.setSelection(z.create(r.doc,n.from+e.key.length)).scrollIntoView()),!0},XA=(t,e)=>{if(!Ze||e.inputType!=="insertReplacementText"||e.isComposing||!e.cancelable)return!1;let{selection:n}=t.state;return!(n instanceof z)||n.$from.parent!==n.$to.parent||n.$from.parent.type.spec.code!==!0?!1:(e.preventDefault(),e.stopImmediatePropagation(),!0)};var YA=(t,e)=>{if(!Ze||!Ae(t.state))return!1;if(e==="addRow")return Ey(t.state,t.dispatch);if(e==="deleteRow")return ra(t.state,t.dispatch);if(e==="addColumn")return ta(t.state,t.dispatch);if(e==="deleteColumn")return na(t.state,t.dispatch);if(e==="header"){let{$from:n}=t.state.selection;for(let r=n.depth;r>0;r-=1){if(n.node(r).type.name!=="table")continue;let i=Math.min(n.before(r)+4,t.state.doc.content.size);return t.dispatch(t.state.tr.setSelection(_.near(t.state.doc.resolve(i),1)).scrollIntoView()),!0}}return!1},Pf=t=>{t?(en.dataset.state="open",en.setAttribute("aria-hidden","false")):en.dataset.state!=="closed"&&(en.dataset.state="closed",en.setAttribute("aria-hidden","true"))},ZA=t=>{if(en.querySelectorAll("button").forEach(i=>{let o=Lt(i.dataset.label);i.textContent=o,i.setAttribute("aria-label",o)}),!Ze||!Ae(t.state)){Pf(!1);return}let e=t.domAtPos(t.state.selection.from).node,n=(e instanceof Element?e:e.parentElement)?.closest("td, th");if(!(n instanceof HTMLElement)){Pf(!1);return}let r=n.getBoundingClientRect();en.style.left=`${Math.max(8,Math.min(window.innerWidth-en.offsetWidth-8,r.left))}px`,en.style.top=`${Math.max(8,r.top-32)}px`,Pf(!0)},Bb={doc:null,focusedMermaidPos:null,generation:-1,decorations:re.empty},Pb=(t,e,n)=>{let r=!1,i=Math.max(0,Math.min(t.content.size,e-1)),o=Math.max(i,Math.min(t.content.size,Math.max(n,e+1)+1));return t.nodesBetween(i,o,s=>(s.type.name==="heading"&&(r=!0),!r)),r},eN=t=>t.steps.some((e,n)=>{let r=t.docs[n],i=t.docs[n+1]||t.doc,o=!1;return e.getMap().forEach((s,a,l,c)=>{(Pb(r,s,a)||Pb(i,l,c))&&(o=!0)}),o}),tN=Ce(()=>new Y({state:{init:()=>null,apply:(t,e,n,r)=>(wt(Mt,"transactions"),t.docChanged&&eN(t)&&Xf(r.doc),e)},view(t){let e={autocapitalize:"none",autocorrect:"off",spellcheck:"false"},n=new Map(Object.keys(e).map(h=>[h,t.dom.getAttribute(h)])),r=h=>{if(h.state.selection.$from.parent.type.spec.code===!0){for(let[m,g]of Object.entries(e))h.dom.setAttribute(m,g);return}for(let[m,g]of n)g===null?h.dom.removeAttribute(m):h.dom.setAttribute(m,g)},i=h=>{let m=h.state.doc;h.dom.classList.toggle("weibei-empty-document",m.childCount===1&&m.firstChild?.type.name==="paragraph"&&m.firstChild.content.size===0),h.dom.dataset.emptyPlaceholder=Lt("emptyNotePlaceholder")},o=h=>{wo!==h&&(wo=h,t.dispatch(t.state.tr.setMeta("weibeiMermaidFocusChanged",h)))},s=h=>o(h.target===t.dom),a=h=>{h.target===t.dom&&o(!1)},l=()=>{Jf=To,ka=!1;let{$from:h}=t.state.selection;So=h.parent.isTextblock&&h.parent.content.size===0?h.before(h.depth):null},c=()=>{ka=!0,setTimeout(rN)},u=h=>{h.target!==t.dom||!t.hasFocus()||!JA(t,h)&&!QA(t,h)||(h.preventDefault(),h.stopImmediatePropagation())},f=h=>{h.target===t.dom&&XA(t,h)},d=h=>h.preventDefault(),p=h=>{let m=h.target instanceof Element?h.target.closest("button[data-action]"):null;m instanceof HTMLElement&&(YA(t,m.dataset.action||""),t.focus(),window.requestAnimationFrame(()=>ZA(t)))};return t.dom.addEventListener("focus",s,!0),t.dom.addEventListener("blur",a,!0),wo=t.hasFocus(),{update(h,m){h.state.doc.eq(m.doc)||(je(),di())},destroy(){t.dom.removeEventListener("focus",s,!0),t.dom.removeEventListener("blur",a,!0),wo=!1,St=null,ya=new WeakMap}}},props:{handlePaste:()=>!1,handleDrop:()=>!1,handleTextInput:()=>!1,handleClick(t,e,n){return tx(n.target)||ex(n.target)||jf(n.target)||qf(n.target)||nx(n.target)},handleKeyDown(t,e){if(e.key!=="Enter"&&e.key!==" ")return!1;if(qf(e.target))return e.preventDefault(),!0;if(!e.metaKey&&!e.ctrlKey)return!1;let n=jA();return n?(et("wikiLinkActivated",{title:n}),e.preventDefault(),!0):!1},decorations(t){let e=OA(t);LA(e);let n=e?.pos??null,r=Bb;if(r.doc===t.doc&&r.focusedMermaidPos===n&&r.generation===dr)return wt(Mt,"decorationCacheHits"),r.decorations;let i=[],o={open:!1},s=new Map,a=new Map;t.doc.descendants((c,u,f)=>{if(wt(Mt,"decorationNodes"),c.type.name==="code_block")return PA(i,c,u,e)||(i.push(se.node(u,u+c.nodeSize,{class:"weibei-code-block","data-language":c.attrs.language||""})),WA(i,c,u)),!1;if(c.isText){let p=u,h=c.text||"";if((c.marks||[]).some(g=>g.type.name.toLowerCase().includes("code"))||de!==null)return!0;DA(i,h,p),NA(i,h,p,o),AA(i,h,p),RA(i,h,p),vA(i,h,p,s),IA(i,h,p,a)}return!0});let l=re.create(t.doc,i);return Bb={doc:t.doc,focusedMermaidPos:n,generation:dr,decorations:l},l}}})),Ff=()=>{if(window.weiBeiSuppressSelectionReport)return;let t=MA(),e=t?hA():null,n=t&&ee?ee.action(o=>{let{state:s}=o.get(ie),{selection:a}=s,c=["strong","emphasis","highlight","link","inlineCode"].filter(y=>s.schema.marks[y]&&s.doc.rangeHasMark(a.from,a.to,s.schema.marks[y])),u=s.schema.marks.writing_font,f,d=!1;u&&s.doc.nodesBetween(a.from,a.to,y=>{if(!y.isText)return!0;let x=u.isInSet(y.marks||[])?.attrs.font||"serif";return f===void 0?f=x:f!==x&&(d=!0),!0}),f&&!d&&c.push(`font:${f}`);let p=a instanceof H&&a.node.type.name==="math_inline";p&&c.push("inlineMath");let h=a.$from.parent.type.name;for(let y=a.$from.depth;y>0;y-=1){let x=a.$from.node(y).type.name;if(x==="blockquote"||x==="block_quote"){h="blockquote";break}}h==="heading"&&(h=`heading${a.$from.parent.attrs.level||""}`);let m="",g=s.schema.marks.link;return g&&s.doc.nodesBetween(a.from,a.to,y=>{let x=g.isInSet(y.marks||[]);return x&&!m&&(m=String(x.attrs.href||"")),!m}),{activeMarks:c,blockType:h,canConvertToMath:p||a instanceof z&&!a.empty&&a.$from.parent===a.$to.parent&&a.$from.parent.isTextblock,linkTarget:m}}):{activeMarks:[],blockType:"",canConvertToMath:!1,linkTarget:""},r=e?`${Math.round(e.x)}:${Math.round(e.y)}:${Math.round(e.width)}:${Math.round(e.height)}`:"",i=JSON.stringify(n);if(!(t===ci.text&&r===ci.rectKey&&i===ci.detailKey)){if(ci={text:t,rectKey:r,detailKey:i},!t){zf=null,et("selectionChanged",{text:"",rect:null,...n});return}zf=SA(),et("selectionChanged",{text:t,rect:e,...n})}};var Qf=()=>{if(!ee)throw new Error("WeiBei editor is not ready")},ox=t=>{_f=EA(t),dr+=1,ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},sx=t=>{$f=TA(t),dr+=1,ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiSelectionAskMarksChanged",!0))})},nN=()=>{if(!ee||So===null)return;let t=So;So=null,ee.action(e=>{let n=e.get(ie);n.domObserver?.flush();let r=n.state.doc.nodeAt(t);if(!r?.isTextblock||!r.textContent)return;let i=n.state.schema.nodes.hardbreak||n.state.schema.nodes.hard_break,o=[];for(let a=0;a<r.childCount;a+=1){let l=r.child(a);l.type!==i&&o.push(l)}if(o.length!==r.childCount){let a=r.type.create(r.attrs,E.fromArray(o),r.marks),l=n.state.tr.replaceWith(t,t+r.nodeSize,a).scrollIntoView();l.setSelection(z.create(l.doc,Math.min(t+1+a.content.size,l.doc.content.size))),n.dispatch(l)}let s=n.nodeDOM(t);s instanceof HTMLElement&&(s.querySelectorAll("br").forEach(a=>a.remove()),n.domObserver?.flush())})},rN=()=>{ee&&(nN(),ka=!1,Jf=null,je(),di())},Ao=()=>ee.action(t=>t.get(G)),iN=(t=!0)=>{wa(),de!==null&&(Ao().call(yo.key,{keep:t}),de=null,Ot=null,hi=null)},ax=t=>{Qf(),wa();let e=String(t||"");hi=e;let n=xo(e);pi=n.frontmatter,vo();let r=n.body,i=Ot!==null&&de===Ot&&r.startsWith(Ot)?r.slice(Ot.length):null,o;i!==null&&!/[$<>\\`\r]/.test(i)?(o=r,Ot=r):(o=bo(r,"agentGenerated"),Ot=o===r?r:null,To=Io(o));let s=Ao();de===null?(s.call(lr.key),de=""):o.startsWith(de)||(s.call(li.key,{diffReview:!1}),s.call(lr.key),de="");let a=o.slice(de.length);a&&s.call(go.key,a),de=o,je()},oN=t=>{let e=String(t||"");if(!e)return;let n=hi;ax(n===null?e:n+e)},cr=null,sN=24,aN=12,Fb=33,lN=3e3,cN=240,wa=()=>{cr!=null&&(window.clearTimeout(cr),cr=null)},zb=t=>{let e=Ao();de===null?(e.call(lr.key),de=""):t.startsWith(de)||(e.call(li.key,{diffReview:!1}),e.call(lr.key),de="");let n=t.slice(de.length);n&&e.call(go.key,n),de=t,je()},_b=()=>{Ao().call(li.key,{diffReview:!1}),Ot=null,de=null,hi=null,wa();try{ee?.action(t=>{t.get(ie).updateState(t.get(ie).state)})}catch{}Hf(),je()},uN=(t,e)=>{wa(),Ot=null;let n=String(t||""),r=xo(n);pi=r.frontmatter,vo();let i=bo(r.body,"agentGenerated");To=Io(i),hi=n;let o=de,s=e?.paced===!0&&o!==null&&i.startsWith(o)&&i.length-o.length>sN;if(o!==null&&s){let a=o.length,l=0,c=Date.now(),u=()=>{cr=null;let f=Date.now();l+=1,a=Math.min(i.length,a+aN);let d=a>=i.length||f-c>=lN||l>=cN;try{if(zb(d?i:i.slice(0,a)),!d){cr=window.setTimeout(u,Fb);return}_b()}catch{cr=null,de=null,Ot=null;try{Ao().call(yo.key,{keep:!1})}catch{}try{lx(n)}catch{}je()}};cr=window.setTimeout(u,Fb),je();return}zb(i),_b()},lx=t=>{Qf(),iN(),hi=null,Jf=null,So=null,ka=!1,Mo+=1;let e=xo(t||""),n=bo(e.body,"userDocument");pi=e.frontmatter,vo(),ee.action(vg(n)),To=Io(n),ee.action(r=>Xf(r.get(ie).state.doc)),je()};var fN=()=>(Qf(),wt(Mt,"fullSerializations"),Io(ee.action(Ig())));var cx=()=>Array.from(document.querySelectorAll(".ProseMirror h1, .ProseMirror h2, .ProseMirror h3, .ProseMirror h4, .ProseMirror h5, .ProseMirror h6")),$b=0,ma=-2,Kf=null,Xf=t=>{let e=[],n=Math.max(1,t.content.size);t.descendants((i,o)=>{if(i.type.name!=="heading")return!0;let s=i.textContent.trim();if(!s)return!1;let a=e.length;return e.push({id:`note-heading-${a}`,index:a,level:Number(i.attrs.level||1),title:s,position:Math.max(0,Math.min(1,o/n))}),!1});let r=pb(e);r!==Kf&&(Kf=r,wt(Mt,"outlineReports"),et("outlineChanged",{items:e}))},di=()=>{window.cancelAnimationFrame($b),$b=window.requestAnimationFrame(()=>{let t=cx();if(t.length===0){ma!==-1&&(ma=-1,et("activeHeadingChanged",{index:null}));return}let e=Math.max(0,window.innerHeight*.32),n=0;t.forEach((r,i)=>{r.getBoundingClientRect().top<=e&&(n=i)}),n!==ma&&(ma=n,et("activeHeadingChanged",{index:n}))})},dN=t=>{let e=Number(t),n=cx(),r=Number.isFinite(e)?n[Math.max(0,Math.floor(e))]:null;if(!r)return!1;let i=lA();return r.scrollIntoView({block:"start",behavior:i?"auto":"smooth"}),i?di():window.setTimeout(di,180),!0},pN=(t,e)=>{let n=t!==ba||e!==fr;ba=t,fr=e,n&&(Gv.clear(),Kf=null,Mo+=1,eA.clear(),Zv.clear(),ox([]),sx([]))};var hN=t=>{Kb(t),dr+=1,Zb(),ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiThemeChanged",fi))})},mN=t=>{ga=Wb(t),dr+=1,document.documentElement.dataset.weibeiLanguage=ga,vo(),Yb(),xA.forEach(e=>e()),ee&&ee.action(e=>{let n=e.get(ie);n.dispatch(n.state.tr.setMeta("weibeiLanguageChanged",ga))})},gN=()=>ee?(ee.action(t=>t.get(ie).focus()),!0):!1;window.WeiBeiEditor={getMarkdown:fN,setMarkdown:t=>lx(String(t||"")),updateStreamingMarkdown:t=>{try{ax(t)}catch(e){ur(e)}},appendStreamingMarkdown:t=>{try{oN(t)}catch(e){ur(e)}},finishStreamingMarkdown:(t,e)=>{try{return uN(t,e),!0}catch(n){return ur(n),!1}},setDocumentID:t=>{let e=t||"";e!==ba&&pN(e,fr+1)},setTheme:hN,setInterfaceLanguage:mN,setReduceMotion:cA,setTextScale:uA,focus:gN,scrollToHeading:dN,setSelectionAskMarks:ox,setSelectionRemarkMarks:sx,setMarkdownBaseURL:t=>{Vb=t||"",Zb()}};var Eo=xo(window.initialMarkdown||"");Eo.body=bo(Eo.body,"userDocument");pi=Eo.frontmatter;To=Io(Eo.body);vo();var Uf=Cg.make().config(t=>{t.set(no,document.querySelector("#editor")),t.set(Yi,Eo.body),t.set(to,{editable:()=>Ze,nodeViews:{image:wA,math_inline:Lb,math_block:Lb}}),t.set(wn.key,{throttleMs:0,scrollFollow:!1,diffReviewOnEnd:!1,ignoreAttrs:{heading:["id"]}})});Uf=Uf.use(tN).use(ny).use(Mk).use(Cb).use(tA).use(Qk).use(Ce(()=>Yk(()=>de!==null)));Uf.use(Sf).config(t=>{t.get(fa).selectionUpdated(()=>{requestAnimationFrame(Ff)})}).create().then(t=>{ee=t,Yb(),UA(),document.querySelector("#editor-status")?.remove(),document.addEventListener("mouseup",Ff),document.addEventListener("pointerdown",()=>{window.weiBeiSuppressSelectionReport||(zf=null,ci.text="",ci.rectKey="",et("selectionChanged",{text:"",rect:null}))},!0),document.addEventListener("click",e=>{Ze&&e.target instanceof Element&&e.target.closest(".weibei-structured-node")||!tx(e.target)&&!ex(e.target)&&!jf(e.target)&&!qf(e.target)&&!nx(e.target)||(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keydown",e=>{e.key!=="Enter"&&e.key!==" "||jf(e.target)&&(e.preventDefault(),e.stopPropagation())},!0),document.addEventListener("keyup",e=>{Ff()}),document.addEventListener("scroll",di,!0),et("editorReady",{}),window.setTimeout(()=>{Hb=!0,pA(),ee.action(e=>Xf(e.get(ie).state.doc)),di()})}).catch(ur);})(); /*! Bundled license information: lodash-es/lodash.js: diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 3866564b7..a3b6bf277 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -582,6 +582,7 @@ final class WorkspaceStore: ObservableObject { } } @Published var noteEditorCommand: NoteEditorCommand? + @Published private var rejectedNoteEditorCommands: [RejectedNoteEditorCommand] = [] /// Success / info banner for note create/switch — separate from errors so it auto-dismisses cleanly. @Published var transientNoteStatus: String? @Published private var noteSelectionTransitionState = NoteSelectionTransitionState.idle @@ -796,6 +797,11 @@ final class WorkspaceStore: ObservableObject { let apply: () -> Void } + private struct RejectedNoteEditorCommand { + let documentID: String + let command: NoteEditorCommand + } + private enum NotebookNoteSeed { case blank case currentMaterial(StudyItem) @@ -10213,6 +10219,39 @@ final class WorkspaceStore: ObservableObject { } } + var noteEditorCommandFailureMessage: String? { + guard let rejected = rejectedNoteEditorCommands.first else { return nil } + if rejected.documentID != activeNoteEditorDocumentID { + return ui( + "未应用的内容已保留。返回原笔记后可重试。", + "The unapplied content is preserved. Return to its original note to retry." + ) + } + return ui( + "编辑器未完成这次操作;涉及的内容已保留。请重试。", + "The editor did not complete this operation. Its content is preserved; please retry." + ) + } + + var canRetryRejectedNoteEditorCommand: Bool { + rejectedNoteEditorCommands.first?.documentID == activeNoteEditorDocumentID + && noteEditorCommand == nil + } + + func noteEditorCommandRejected(_ command: NoteEditorCommand) { + guard !rejectedNoteEditorCommands.contains(where: { $0.command.id == command.id }) else { return } + rejectedNoteEditorCommands.append(RejectedNoteEditorCommand( + documentID: activeNoteEditorDocumentID, + command: command + )) + } + + func retryRejectedNoteEditorCommand() { + guard noteEditorCommand == nil, + rejectedNoteEditorCommands.first?.documentID == activeNoteEditorDocumentID else { return } + noteEditorCommand = rejectedNoteEditorCommands.removeFirst().command + } + var canRetryPendingNoteSelection: Bool { if case .failed = noteSelectionTransitionState { return pendingNoteSelection != nil diff --git a/Sources/WeiBei/Views/ContentView.swift b/Sources/WeiBei/Views/ContentView.swift index c28dfca29..18021d013 100644 --- a/Sources/WeiBei/Views/ContentView.swift +++ b/Sources/WeiBei/Views/ContentView.swift @@ -87,6 +87,7 @@ struct ContentView: View { // user is; the old notes-pane-local copy is gone. if store.importantOperationError != nil || store.workspaceSaveError != nil + || store.noteEditorCommandFailureMessage != nil || store.noteSelectionStatusMessage != nil || store.transientNoteStatus != nil { WorkspaceStatusBanner() @@ -107,6 +108,7 @@ struct ContentView: View { } .animation(WeiBeiMotion.panel, value: store.importantOperationError) .animation(WeiBeiMotion.panel, value: store.workspaceSaveError) + .animation(WeiBeiMotion.panel, value: store.noteEditorCommandFailureMessage) .animation(WeiBeiMotion.panel, value: store.noteSelectionStatusMessage) .animation(WeiBeiMotion.panel, value: store.transientNoteStatus) .background { @@ -391,16 +393,22 @@ private struct WorkspaceStatusBanner: View { } private var isNoteSelectionFailure: Bool { - !isImportant && !isSaveFailure && store.canRetryPendingNoteSelection + !isImportant && !isSaveFailure && !isEditorCommandFailure + && store.canRetryPendingNoteSelection + } + + private var isEditorCommandFailure: Bool { + !isImportant && !isSaveFailure && store.noteEditorCommandFailureMessage != nil } private var isAlert: Bool { - isImportant || isSaveFailure || isNoteSelectionFailure + isImportant || isSaveFailure || isEditorCommandFailure || isNoteSelectionFailure } private var message: String { store.importantOperationError ?? store.workspaceSaveError + ?? store.noteEditorCommandFailureMessage ?? store.noteSelectionStatusMessage ?? store.transientNoteStatus ?? "" @@ -428,6 +436,17 @@ private struct WorkspaceStatusBanner: View { } .buttonStyle(.plain) .accessibilityLabel(Text(store.ui("重试保存", "Retry save"))) + } else if isEditorCommandFailure && store.canRetryRejectedNoteEditorCommand { + Button { + store.retryRejectedNoteEditorCommand() + } label: { + Text(store.ui("重试", "Retry")) + .weiBeiText(12, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(Text(store.ui("重试应用编辑内容", "Retry applying editor content"))) } else if isNoteSelectionFailure { Button { store.retryPendingNoteSelection() diff --git a/Sources/WeiBei/Views/NotesAgentView.swift b/Sources/WeiBei/Views/NotesAgentView.swift index b0f29976d..be716cf86 100644 --- a/Sources/WeiBei/Views/NotesAgentView.swift +++ b/Sources/WeiBei/Views/NotesAgentView.swift @@ -748,6 +748,8 @@ struct NotePaneView: View { if editorRecoveryState.renderFailed() { editorRecoveryGeneration &+= 1 } + }, onCommandRejected: { command in + store.noteEditorCommandRejected(command) }) .id("\(store.activeNoteEditorDocumentID):\(editorRecoveryGeneration)") .background(WeiBeiTheme.paper) diff --git a/Sources/WeiBei/Views/RichMarkdownEditorView.swift b/Sources/WeiBei/Views/RichMarkdownEditorView.swift index 17b2681c2..e63893bf5 100644 --- a/Sources/WeiBei/Views/RichMarkdownEditorView.swift +++ b/Sources/WeiBei/Views/RichMarkdownEditorView.swift @@ -630,6 +630,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { var onRenderReady: () -> Void = {} var onFinalizedRenderReady: (CGFloat) -> Void = { _ in } var onRenderFailure: () -> Void = {} + var onCommandRejected: (NoteEditorCommand) -> Void = { _ in } var onSearchResult: (String, Bool) -> Void = { _, _ in } /// JSON array of `{id,text}` for selection-ask underline marks (read-only surfaces). var selectionAskMarks: String = "[]" @@ -668,6 +669,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { onRenderReady: onRenderReady, onFinalizedRenderReady: onFinalizedRenderReady, onRenderFailure: onRenderFailure, + onCommandRejected: onCommandRejected, onSearchResult: onSearchResult, onSelectionAskMark: onSelectionAskMark, onSelectionRemarkMark: onSelectionRemarkMark @@ -889,6 +891,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { context.coordinator.onRenderReady = onRenderReady context.coordinator.onFinalizedRenderReady = onFinalizedRenderReady context.coordinator.onRenderFailure = onRenderFailure + context.coordinator.onCommandRejected = onCommandRejected context.coordinator.onSearchResult = onSearchResult let nextBaseURL = markdownBaseURL?.absoluteString ?? "" if context.coordinator.markdownBaseURLString != nextBaseURL { @@ -956,6 +959,8 @@ struct RichMarkdownEditorView: NSViewRepresentable { "editorReady", "dirtyChanged", "snapshotReady", + "commandApplied", + "commandRejected", "outlineChanged", "selectionChanged", "askAgentWithSelection", @@ -1072,6 +1077,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { var onRenderReady: () -> Void var onFinalizedRenderReady: (CGFloat) -> Void var onRenderFailure: () -> Void + var onCommandRejected: (NoteEditorCommand) -> Void var onSearchResult: (String, Bool) -> Void var onSelectionAskMark: (String) -> Void var selectionAskMarks: String @@ -1095,7 +1101,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { var pendingStreamingCompletion = false var lastCommandID: UUID? private var queuedCommands: [NoteEditorCommand] = [] - private let queuedCommandLimit = 16 + private var inFlightCommandID: UUID? private var editingSessionBindingToken: UUID? private var pendingV2DocumentID: String? let performanceInstanceID = UUID() @@ -1135,6 +1141,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { onRenderReady: @escaping () -> Void, onFinalizedRenderReady: @escaping (CGFloat) -> Void, onRenderFailure: @escaping () -> Void, + onCommandRejected: @escaping (NoteEditorCommand) -> Void, onSearchResult: @escaping (String, Bool) -> Void, onSelectionAskMark: @escaping (String) -> Void, onSelectionRemarkMark: @escaping (String) -> Void @@ -1166,6 +1173,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { self.onRenderReady = onRenderReady self.onFinalizedRenderReady = onFinalizedRenderReady self.onRenderFailure = onRenderFailure + self.onCommandRejected = onCommandRejected self.onSearchResult = onSearchResult self.onSelectionAskMark = onSelectionAskMark self.onSelectionRemarkMark = onSelectionRemarkMark @@ -1384,6 +1392,12 @@ struct RichMarkdownEditorView: NSViewRepresentable { if editingSession?.receive(event) == true { webMarkdown = event.markdown } + case "commandApplied": + guard let event = decodeV2Event(NoteEditorCommandResultEvent.self, from: message.body) else { return } + finishCommand(event.commandID, rejectionReason: nil) + case "commandRejected": + guard let event = decodeV2Event(NoteEditorCommandResultEvent.self, from: message.body) else { return } + finishCommand(event.commandID, rejectionReason: event.reason ?? "rejected") case "outlineChanged": guard let event = decodeV2Event( NoteEditorOutlineChangedEvent.self, @@ -1618,25 +1632,27 @@ struct RichMarkdownEditorView: NSViewRepresentable { """) } - func run(_ command: NoteEditorCommand) { + private func run(_ command: NoteEditorCommand) { guard let editingSession else { return } let type: NoteEditorCommandType switch command.kind { case .replaceSelection: type = .replaceSelection case .selectionCommand: - dispatchV2(NoteEditorCommandEnvelope( + dispatchQueued(NoteEditorCommandEnvelope( + commandID: command.id.uuidString, documentID: editingSession.documentID, documentGeneration: editingSession.documentGeneration, minimumRevision: editingSession.currentRevision, type: .executeSelectionCommand, payload: NoteEditorSelectionCommandPayload(action: command.markdown, value: command.value) - )) + ), source: command) return case .applyAgentPatch: type = .applyMarkdownFragment case .insertMarkdown: type = .insertStructuredBlock case .reloadDocument: webMarkdown = command.markdown - dispatchV2(NoteEditorCommandEnvelope( + dispatchQueued(NoteEditorCommandEnvelope( + commandID: command.id.uuidString, documentID: editingSession.documentID, documentGeneration: editingSession.documentGeneration, type: .loadDocument, @@ -1644,53 +1660,55 @@ struct RichMarkdownEditorView: NSViewRepresentable { markdown: command.markdown, initialRevision: editingSession.currentRevision ) - )) + ), source: command) return case .scrollToHeading: - guard let index = Int(command.markdown) else { return } - dispatchV2(NoteEditorCommandEnvelope( + guard let index = Int(command.markdown) else { + rejectCommand(command, reason: "invalid heading index") + return + } + dispatchQueued(NoteEditorCommandEnvelope( + commandID: command.id.uuidString, documentID: editingSession.documentID, documentGeneration: editingSession.documentGeneration, minimumRevision: editingSession.currentRevision, type: .scrollToHeading, payload: NoteEditorScrollPayload(index: index) - )) + ), source: command) return } - dispatchV2(NoteEditorCommandEnvelope( + dispatchQueued(NoteEditorCommandEnvelope( + commandID: command.id.uuidString, documentID: editingSession.documentID, documentGeneration: editingSession.documentGeneration, minimumRevision: editingSession.currentRevision, type: type, payload: NoteEditorMarkdownPayload(markdown: command.markdown) - )) + ), source: command) } func runPendingCommandIfReady() { ingestCommandBinding() guard isReady, pendingV2DocumentID == nil, + inFlightCommandID == nil, let next = queuedCommands.first else { return } - queuedCommands.removeFirst() - lastCommandID = next.id + inFlightCommandID = next.id run(next) } - /// 编辑器就绪前连发的命令不再只留最后一条:入队保序, - /// 同类可互相覆盖的命令(替换选区/整档重载)只留最新,其余保序排队。 + /// 内容命令保序且不设数量上限;只有最终状态可替代前态的命令合并。 private func ingestCommandBinding() { guard let pending = command.wrappedValue, pending.id != lastCommandID, !queuedCommands.contains(where: { $0.id == pending.id }) else { return } if let tail = queuedCommands.last, + tail.id != inFlightCommandID, tail.kind == pending.kind, - pending.kind == .replaceSelection || pending.kind == .reloadDocument { + pending.kind == .reloadDocument || pending.kind == .scrollToHeading { queuedCommands[queuedCommands.count - 1] = pending } else { queuedCommands.append(pending) - if queuedCommands.count > queuedCommandLimit { - queuedCommands.removeFirst(queuedCommands.count - queuedCommandLimit) - } } let ingestedID = pending.id DispatchQueue.main.async { @@ -1700,6 +1718,50 @@ struct RichMarkdownEditorView: NSViewRepresentable { } } + private func dispatchQueued<Payload>( + _ envelope: NoteEditorCommandEnvelope<Payload>, + source: NoteEditorCommand + ) { + guard let data = try? JSONEncoder().encode(envelope), + let json = String(data: data, encoding: .utf8), + let webView else { + rejectCommand(source, reason: "bridge unavailable") + return + } + webView.evaluateJavaScript("window.WeiBeiEditor?.dispatchCommand(\(json))") { [weak self] _, error in + guard let self, self.inFlightCommandID == source.id, let error else { return } + Self.bridgeLogger.error( + "editor command evaluation failed: \(error.localizedDescription, privacy: .private)" + ) + self.rejectCommand(source, reason: "javascript evaluation failed") + } + } + + private func finishCommand(_ commandID: String, rejectionReason: String?) { + guard let id = UUID(uuidString: commandID), + id == inFlightCommandID, + queuedCommands.first?.id == id else { return } + let source = queuedCommands.removeFirst() + inFlightCommandID = nil + if let rejectionReason { + Self.bridgeLogger.error( + "editor command rejected: \(rejectionReason, privacy: .private)" + ) + if command.wrappedValue?.id == source.id { + command.wrappedValue = nil + } + onCommandRejected(source) + } else { + lastCommandID = source.id + } + runPendingCommandIfReady() + } + + private func rejectCommand(_ source: NoteEditorCommand, reason: String) { + guard inFlightCommandID == source.id else { return } + finishCommand(source.id.uuidString, rejectionReason: reason) + } + private static let bridgeLogger = Logger( subsystem: "app.weibei.Weibei", category: "NoteEditorBridge" diff --git a/Sources/WeiBei/WebEditor/src/editor.ts b/Sources/WeiBei/WebEditor/src/editor.ts index e9ac47228..fdcd64a92 100644 --- a/Sources/WeiBei/WebEditor/src/editor.ts +++ b/Sources/WeiBei/WebEditor/src/editor.ts @@ -95,6 +95,7 @@ const isCompactPreview = window.weiBeiMarkdownCompactPreview === true; let currentDocumentID = window.weiBeiDocumentID || ''; let currentDocumentGeneration = window.weiBeiDocumentGeneration || 0; let revisionState = { revision: 0, dirty: false }; +const appliedCommandIDs = new Set<string>(); let suppressDirtyTransactions = false; let editorReadyPosted = false; let fullMarkdownBridgeMessages = 0; @@ -3359,6 +3360,7 @@ const setDocumentIdentityInternal = (documentID: string, documentGeneration: num currentDocumentID = documentID; currentDocumentGeneration = documentGeneration; if (!changed) return; + appliedCommandIDs.clear(); lastOutlineChangeKey = null; currentContentGeneration += 1; pendingImagePickers.clear(); @@ -3413,69 +3415,102 @@ const commandPayloadValue = (command: EditorCommand, name: string) => command.pa const dispatchEditorCommand = (value: unknown) => { const command = parseEditorCommand(value); - if (!command || !acceptsEditorCommand(command, { + if (!command) return false; + if (appliedCommandIDs.has(command.commandID)) { + post('commandApplied', { commandID: command.commandID }); + return true; + } + if (!acceptsEditorCommand(command, { documentID: currentDocumentID, documentGeneration: currentDocumentGeneration, revision: revisionState.revision, - })) return false; + })) { + post('commandRejected', { commandID: command.commandID, reason: 'document or revision mismatch' }); + return false; + } - switch (command.type) { + let applied = false; + try { + switch (command.type) { case 'loadDocument': { const markdown = commandPayloadValue(command, 'markdown'); const initialRevision = commandPayloadValue(command, 'initialRevision'); if (typeof markdown !== 'string' - || (initialRevision !== undefined && !Number.isInteger(initialRevision))) return false; + || (initialRevision !== undefined && !Number.isInteger(initialRevision))) break; setDocumentIdentityInternal(command.documentID, command.documentGeneration); loadMarkdownInternal(markdown, Number(initialRevision ?? 0)); - return true; + applied = true; + break; } case 'requestSnapshot': { const markdown = getMarkdownInternal(); lastMarkdown = markdown; post('snapshotReady', { requestID: command.requestID!, markdown }); - return true; + applied = true; + break; } case 'setTheme': setThemeInternal(commandPayloadValue(command, 'theme')); - return true; + applied = true; + break; case 'setLanguage': setLanguageInternal(commandPayloadValue(command, 'language')); - return true; + applied = true; + break; case 'setEditable': setEditableInternal(commandPayloadValue(command, 'editable')); - return true; + applied = true; + break; case 'focus': - return focusInternal(); + applied = focusInternal(); + break; case 'scrollToHeading': - return scrollToHeadingInternal(commandPayloadValue(command, 'index')); + applied = scrollToHeadingInternal(commandPayloadValue(command, 'index')); + break; case 'applyMarkdownFragment': { const markdown = commandPayloadValue(command, 'markdown'); - if (typeof markdown !== 'string') return false; + if (typeof markdown !== 'string') break; appendMarkdownInternal(markdown); - return true; + applied = true; + break; } case 'replaceSelection': { const markdown = commandPayloadValue(command, 'markdown'); - if (typeof markdown !== 'string') return false; + if (typeof markdown !== 'string') break; replaceSelectionInternal(markdown); - return true; + applied = true; + break; } case 'executeSelectionCommand': - return executeSelectionCommandInternal(commandPayloadValue(command, 'action'), commandPayloadValue(command, 'value')); + applied = executeSelectionCommandInternal(commandPayloadValue(command, 'action'), commandPayloadValue(command, 'value')); + break; case 'insertStructuredBlock': { const markdown = commandPayloadValue(command, 'markdown'); - if (typeof markdown !== 'string') return false; + if (typeof markdown !== 'string') break; insertMarkdownInternal(markdown); - return true; + applied = true; + break; } case 'restoreCheckpoint': { const markdown = commandPayloadValue(command, 'markdown'); const revision = commandPayloadValue(command, 'revision'); - if (typeof markdown !== 'string' || (revision !== undefined && (!Number.isInteger(revision) || Number(revision) < 0))) return false; + if (typeof markdown !== 'string' || (revision !== undefined && (!Number.isInteger(revision) || Number(revision) < 0))) break; loadMarkdownInternal(markdown, revision === undefined ? revisionState.revision : Number(revision), true); - return true; + applied = true; + break; + } } + } catch (error) { + post('commandRejected', { commandID: command.commandID, reason: String((error as any)?.message || error) }); + return false; + } + if (!applied) { + post('commandRejected', { commandID: command.commandID, reason: 'command could not be applied' }); + return false; } + appliedCommandIDs.add(command.commandID); + post('commandApplied', { commandID: command.commandID }); + return true; }; window.WeiBeiEditor = { diff --git a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift index be99a1eed..4845ec2b0 100644 --- a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift +++ b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift @@ -6,6 +6,123 @@ import XCTest import WeiBeiCore final class RichMarkdownEditorBridgeTests: XCTestCase { + @MainActor + func testContentCommandsBeyondOldLimitAwaitAcknowledgementAndRejectedContentRetries() async throws { + var command: NoteEditorCommand? = nil + var rejectedCommand: NoteEditorCommand? = nil + let rejected = expectation(description: "rejected content remained recoverable") + let editor = RichMarkdownEditorView( + documentID: "note-a", + markdown: "", + command: Binding(get: { command }, set: { command = $0 }), + editingSession: NoteEditingSession(documentID: "note-a"), + onSelectionChange: { _, _ in }, + onAskAgentWithSelection: { _, _ in }, + onCommandRejected: { failed in + rejectedCommand = failed + rejected.fulfill() + } + ) + let coordinator = editor.makeCoordinator() + let allApplied = expectation(description: "all content commands applied") + let retried = expectation(description: "rejected content applied after retry") + let completionProbe = EditorCommandQueueProbe { name in + if name == "allApplied" { + allApplied.fulfill() + } else if name == "retried" { + retried.fulfill() + } + } + let controller = WKUserContentController() + controller.add(coordinator, name: "commandApplied") + controller.add(coordinator, name: "commandRejected") + controller.add(completionProbe, name: "queueProbe") + let configuration = WKWebViewConfiguration() + configuration.userContentController = controller + let loaded = expectation(description: "command bridge loaded") + let navigationProbe = FinalizedMarkdownNavigationProbe { loaded.fulfill() } + let webView = WKWebView(frame: .zero, configuration: configuration) + webView.navigationDelegate = navigationProbe + webView.loadHTMLString(""" + <!doctype html> + <body></body> + <script> + const appliedIDs = new Set(); + const appliedMarkdown = []; + let rejectedMarkdown = "保留我"; + const reply = (name, command, reason) => { + window.webkit.messageHandlers[name].postMessage({ + protocolVersion: 2, + commandID: command.commandID, + documentID: "note-a", + documentGeneration: 1, + revision: 0, + ...(reason ? { reason } : {}) + }); + }; + window.WeiBeiEditor = { + dispatchCommand(command) { + const markdown = command.payload.markdown; + if (markdown === rejectedMarkdown) { + reply("commandRejected", command, "fixture rejection"); + return false; + } + if (!appliedIDs.has(command.commandID)) { + appliedIDs.add(command.commandID); + appliedMarkdown.push(markdown); + } + reply("commandApplied", command); + if (appliedMarkdown.length === 18) { + window.webkit.messageHandlers.queueProbe.postMessage("allApplied"); + } else if (markdown === "保留我") { + window.webkit.messageHandlers.queueProbe.postMessage("retried"); + } + return true; + }, + allowRejectedContent() { rejectedMarkdown = null; }, + appliedMarkdown() { return appliedMarkdown; } + }; + </script> + """, baseURL: nil) + await fulfillment(of: [loaded], timeout: 3) + + coordinator.webView = webView + for index in 0..<18 { + command = NoteEditorCommand(kind: .insertMarkdown, markdown: "内容\(index)") + coordinator.runPendingCommandIfReady() + } + coordinator.isReady = true + coordinator.runPendingCommandIfReady() + await fulfillment(of: [allApplied], timeout: 3) + let appliedValue = try await webView.evaluateJavaScript( + "window.WeiBeiEditor.appliedMarkdown()" + ) + let applied = try XCTUnwrap(appliedValue as? [String]) + XCTAssertEqual(applied, (0..<18).map { "内容\($0)" }) + + command = NoteEditorCommand(kind: .replaceSelection, markdown: "保留我") + coordinator.runPendingCommandIfReady() + await fulfillment(of: [rejected], timeout: 3) + let recoverable = try XCTUnwrap(rejectedCommand) + XCTAssertEqual(recoverable.markdown, "保留我") + + _ = try await webView.evaluateJavaScript(""" + (() => { + window.WeiBeiEditor.allowRejectedContent(); + return true; + })() + """) + command = recoverable + coordinator.runPendingCommandIfReady() + await fulfillment(of: [retried], timeout: 3) + let afterRetryValue = try await webView.evaluateJavaScript( + "window.WeiBeiEditor.appliedMarkdown()" + ) + let afterRetry = try XCTUnwrap(afterRetryValue as? [String]) + XCTAssertEqual(afterRetry.filter { $0 == "保留我" }.count, 1) + withExtendedLifetime((navigationProbe, completionProbe)) {} + } + @MainActor func testExecutedCommandDoesNotClearNewerCommand() async { var command: NoteEditorCommand? = NoteEditorCommand(kind: .selectionCommand, markdown: "bold") @@ -172,6 +289,23 @@ final class RichMarkdownEditorBridgeTests: XCTestCase { } } +private final class EditorCommandQueueProbe: NSObject, WKScriptMessageHandler { + private let receive: (String) -> Void + + init(receive: @escaping (String) -> Void) { + self.receive = receive + } + + func userContentController( + _ userContentController: WKUserContentController, + didReceive message: WKScriptMessage + ) { + if let name = message.body as? String { + receive(name) + } + } +} + private final class FinalizedMarkdownNavigationProbe: NSObject, WKNavigationDelegate { private let onFinish: () -> Void From b348724f11a4856a1dc0cd4619b1ad8dc86d3452 Mon Sep 17 00:00:00 2001 From: taekchef <taekchef@users.noreply.github.com> Date: Mon, 24 Aug 2026 06:54:37 +0800 Subject: [PATCH 5/8] =?UTF-8?q?fix:=20=E5=88=87=E6=8D=A2=E5=89=8D=E7=AD=89?= =?UTF-8?q?=E5=BE=85=E7=BC=96=E8=BE=91=E5=91=BD=E4=BB=A4=E7=A1=AE=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 46 +++++- Sources/WeiBei/Views/NotesAgentView.swift | 8 +- .../WeiBei/Views/RichMarkdownEditorView.swift | 149 ++++++++++++------ .../ImportedIdentitySelfCheck.swift | 30 ++-- .../RichMarkdownEditorBridgeTests.swift | 6 +- 5 files changed, 174 insertions(+), 65 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index a3b6bf277..631551b1a 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -583,6 +583,7 @@ final class WorkspaceStore: ObservableObject { } @Published var noteEditorCommand: NoteEditorCommand? @Published private var rejectedNoteEditorCommands: [RejectedNoteEditorCommand] = [] + private var unresolvedContentCommandDocumentIDs: [UUID: String] = [:] /// Success / info banner for note create/switch — separate from errors so it auto-dismisses cleanly. @Published var transientNoteStatus: String? @Published private var noteSelectionTransitionState = NoteSelectionTransitionState.idle @@ -10238,10 +10239,25 @@ final class WorkspaceStore: ObservableObject { && noteEditorCommand == nil } - func noteEditorCommandRejected(_ command: NoteEditorCommand) { + func noteEditorContentCommandPending(_ command: NoteEditorCommand, documentID: String) { + unresolvedContentCommandDocumentIDs[command.id] = documentID + if pendingNoteSelection != nil, + noteEditingSession.documentID == documentID { + noteSelectionTransitionState = .saving + } + } + + func noteEditorContentCommandApplied(_ command: NoteEditorCommand, documentID: String) { + guard unresolvedContentCommandDocumentIDs[command.id] == documentID else { return } + unresolvedContentCommandDocumentIDs.removeValue(forKey: command.id) + rejectedNoteEditorCommands.removeAll { $0.command.id == command.id } + resumePendingNoteSelection(afterResolvingCommandFor: documentID) + } + + func noteEditorCommandRejected(_ command: NoteEditorCommand, documentID: String) { guard !rejectedNoteEditorCommands.contains(where: { $0.command.id == command.id }) else { return } rejectedNoteEditorCommands.append(RejectedNoteEditorCommand( - documentID: activeNoteEditorDocumentID, + documentID: documentID, command: command )) } @@ -10250,6 +10266,9 @@ final class WorkspaceStore: ObservableObject { guard noteEditorCommand == nil, rejectedNoteEditorCommands.first?.documentID == activeNoteEditorDocumentID else { return } noteEditorCommand = rejectedNoteEditorCommands.removeFirst().command + if pendingNoteSelection != nil { + noteSelectionTransitionState = .saving + } } var canRetryPendingNoteSelection: Bool { @@ -10268,8 +10287,9 @@ final class WorkspaceStore: ObservableObject { to documentID: String?, apply: @escaping () -> Void ) { - guard noteEditingSession.dirty, - noteEditingSession.documentID != documentID else { + let sourceDocumentID = noteEditingSession.documentID + guard sourceDocumentID != documentID, + noteEditingSession.dirty || hasUnresolvedContentCommand(for: sourceDocumentID) else { pendingNoteSelection = nil noteSelectionTransitionState = .idle apply() @@ -10277,10 +10297,28 @@ final class WorkspaceStore: ObservableObject { } pendingNoteSelection = PendingNoteSelection(apply: apply) + if hasUnresolvedContentCommand(for: sourceDocumentID) { + noteSelectionTransitionState = .saving + return + } guard noteSelectionTransitionState != .saving else { return } requestPendingNoteSelectionSnapshot() } + private func hasUnresolvedContentCommand(for documentID: String) -> Bool { + unresolvedContentCommandDocumentIDs.values.contains(documentID) + } + + private func resumePendingNoteSelection(afterResolvingCommandFor documentID: String) { + guard pendingNoteSelection != nil, + noteEditingSession.documentID == documentID else { return } + guard !hasUnresolvedContentCommand(for: documentID) else { + noteSelectionTransitionState = .saving + return + } + requestPendingNoteSelectionSnapshot() + } + private func requestPendingNoteSelectionSnapshot() { guard pendingNoteSelection != nil else { return } noteSelectionTransitionState = .saving diff --git a/Sources/WeiBei/Views/NotesAgentView.swift b/Sources/WeiBei/Views/NotesAgentView.swift index be716cf86..ef5a98812 100644 --- a/Sources/WeiBei/Views/NotesAgentView.swift +++ b/Sources/WeiBei/Views/NotesAgentView.swift @@ -748,8 +748,12 @@ struct NotePaneView: View { if editorRecoveryState.renderFailed() { editorRecoveryGeneration &+= 1 } - }, onCommandRejected: { command in - store.noteEditorCommandRejected(command) + }, onContentCommandPending: { documentID, command in + store.noteEditorContentCommandPending(command, documentID: documentID) + }, onContentCommandApplied: { documentID, command in + store.noteEditorContentCommandApplied(command, documentID: documentID) + }, onCommandRejected: { documentID, command in + store.noteEditorCommandRejected(command, documentID: documentID) }) .id("\(store.activeNoteEditorDocumentID):\(editorRecoveryGeneration)") .background(WeiBeiTheme.paper) diff --git a/Sources/WeiBei/Views/RichMarkdownEditorView.swift b/Sources/WeiBei/Views/RichMarkdownEditorView.swift index e63893bf5..eb7c47b6c 100644 --- a/Sources/WeiBei/Views/RichMarkdownEditorView.swift +++ b/Sources/WeiBei/Views/RichMarkdownEditorView.swift @@ -630,7 +630,9 @@ struct RichMarkdownEditorView: NSViewRepresentable { var onRenderReady: () -> Void = {} var onFinalizedRenderReady: (CGFloat) -> Void = { _ in } var onRenderFailure: () -> Void = {} - var onCommandRejected: (NoteEditorCommand) -> Void = { _ in } + var onContentCommandPending: (String, NoteEditorCommand) -> Void = { _, _ in } + var onContentCommandApplied: (String, NoteEditorCommand) -> Void = { _, _ in } + var onCommandRejected: (String, NoteEditorCommand) -> Void = { _, _ in } var onSearchResult: (String, Bool) -> Void = { _, _ in } /// JSON array of `{id,text}` for selection-ask underline marks (read-only surfaces). var selectionAskMarks: String = "[]" @@ -669,6 +671,8 @@ struct RichMarkdownEditorView: NSViewRepresentable { onRenderReady: onRenderReady, onFinalizedRenderReady: onFinalizedRenderReady, onRenderFailure: onRenderFailure, + onContentCommandPending: onContentCommandPending, + onContentCommandApplied: onContentCommandApplied, onCommandRejected: onCommandRejected, onSearchResult: onSearchResult, onSelectionAskMark: onSelectionAskMark, @@ -891,6 +895,8 @@ struct RichMarkdownEditorView: NSViewRepresentable { context.coordinator.onRenderReady = onRenderReady context.coordinator.onFinalizedRenderReady = onFinalizedRenderReady context.coordinator.onRenderFailure = onRenderFailure + context.coordinator.onContentCommandPending = onContentCommandPending + context.coordinator.onContentCommandApplied = onContentCommandApplied context.coordinator.onCommandRejected = onCommandRejected context.coordinator.onSearchResult = onSearchResult let nextBaseURL = markdownBaseURL?.absoluteString ?? "" @@ -1077,7 +1083,9 @@ struct RichMarkdownEditorView: NSViewRepresentable { var onRenderReady: () -> Void var onFinalizedRenderReady: (CGFloat) -> Void var onRenderFailure: () -> Void - var onCommandRejected: (NoteEditorCommand) -> Void + var onContentCommandPending: (String, NoteEditorCommand) -> Void + var onContentCommandApplied: (String, NoteEditorCommand) -> Void + var onCommandRejected: (String, NoteEditorCommand) -> Void var onSearchResult: (String, Bool) -> Void var onSelectionAskMark: (String) -> Void var selectionAskMarks: String @@ -1101,7 +1109,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { var pendingStreamingCompletion = false var lastCommandID: UUID? private var queuedCommands: [NoteEditorCommand] = [] - private var inFlightCommandID: UUID? + private var inFlightCommand: InFlightCommand? private var editingSessionBindingToken: UUID? private var pendingV2DocumentID: String? let performanceInstanceID = UUID() @@ -1113,6 +1121,13 @@ struct RichMarkdownEditorView: NSViewRepresentable { private var finalizedRenderGeneration = 0 private var hasReportedRenderFailure = false + private struct InFlightCommand { + let command: NoteEditorCommand + let documentID: String + let documentGeneration: UInt64 + let minimumRevision: UInt64 + } + init( documentID: String, markdown: String, @@ -1141,7 +1156,9 @@ struct RichMarkdownEditorView: NSViewRepresentable { onRenderReady: @escaping () -> Void, onFinalizedRenderReady: @escaping (CGFloat) -> Void, onRenderFailure: @escaping () -> Void, - onCommandRejected: @escaping (NoteEditorCommand) -> Void, + onContentCommandPending: @escaping (String, NoteEditorCommand) -> Void, + onContentCommandApplied: @escaping (String, NoteEditorCommand) -> Void, + onCommandRejected: @escaping (String, NoteEditorCommand) -> Void, onSearchResult: @escaping (String, Bool) -> Void, onSelectionAskMark: @escaping (String) -> Void, onSelectionRemarkMark: @escaping (String) -> Void @@ -1173,6 +1190,8 @@ struct RichMarkdownEditorView: NSViewRepresentable { self.onRenderReady = onRenderReady self.onFinalizedRenderReady = onFinalizedRenderReady self.onRenderFailure = onRenderFailure + self.onContentCommandPending = onContentCommandPending + self.onContentCommandApplied = onContentCommandApplied self.onCommandRejected = onCommandRejected self.onSearchResult = onSearchResult self.onSelectionAskMark = onSelectionAskMark @@ -1394,10 +1413,20 @@ struct RichMarkdownEditorView: NSViewRepresentable { } case "commandApplied": guard let event = decodeV2Event(NoteEditorCommandResultEvent.self, from: message.body) else { return } - finishCommand(event.commandID, rejectionReason: nil) + finishCommand( + event.commandID, + documentID: event.documentID, + documentGeneration: event.documentGeneration, + rejectionReason: nil + ) case "commandRejected": guard let event = decodeV2Event(NoteEditorCommandResultEvent.self, from: message.body) else { return } - finishCommand(event.commandID, rejectionReason: event.reason ?? "rejected") + finishCommand( + event.commandID, + documentID: event.documentID, + documentGeneration: event.documentGeneration, + rejectionReason: event.reason ?? "rejected" + ) case "outlineChanged": guard let event = decodeV2Event( NoteEditorOutlineChangedEvent.self, @@ -1632,20 +1661,20 @@ struct RichMarkdownEditorView: NSViewRepresentable { """) } - private func run(_ command: NoteEditorCommand) { - guard let editingSession else { return } + private func run(_ inFlight: InFlightCommand) { + let command = inFlight.command let type: NoteEditorCommandType switch command.kind { case .replaceSelection: type = .replaceSelection case .selectionCommand: dispatchQueued(NoteEditorCommandEnvelope( commandID: command.id.uuidString, - documentID: editingSession.documentID, - documentGeneration: editingSession.documentGeneration, - minimumRevision: editingSession.currentRevision, + documentID: inFlight.documentID, + documentGeneration: inFlight.documentGeneration, + minimumRevision: inFlight.minimumRevision, type: .executeSelectionCommand, payload: NoteEditorSelectionCommandPayload(action: command.markdown, value: command.value) - ), source: command) + ), source: inFlight) return case .applyAgentPatch: type = .applyMarkdownFragment case .insertMarkdown: type = .insertStructuredBlock @@ -1653,48 +1682,58 @@ struct RichMarkdownEditorView: NSViewRepresentable { webMarkdown = command.markdown dispatchQueued(NoteEditorCommandEnvelope( commandID: command.id.uuidString, - documentID: editingSession.documentID, - documentGeneration: editingSession.documentGeneration, + documentID: inFlight.documentID, + documentGeneration: inFlight.documentGeneration, type: .loadDocument, payload: NoteEditorLoadDocumentPayload( markdown: command.markdown, - initialRevision: editingSession.currentRevision + initialRevision: inFlight.minimumRevision ) - ), source: command) + ), source: inFlight) return case .scrollToHeading: guard let index = Int(command.markdown) else { - rejectCommand(command, reason: "invalid heading index") + rejectCommand(inFlight, reason: "invalid heading index") return } dispatchQueued(NoteEditorCommandEnvelope( commandID: command.id.uuidString, - documentID: editingSession.documentID, - documentGeneration: editingSession.documentGeneration, - minimumRevision: editingSession.currentRevision, + documentID: inFlight.documentID, + documentGeneration: inFlight.documentGeneration, + minimumRevision: inFlight.minimumRevision, type: .scrollToHeading, payload: NoteEditorScrollPayload(index: index) - ), source: command) + ), source: inFlight) return } dispatchQueued(NoteEditorCommandEnvelope( commandID: command.id.uuidString, - documentID: editingSession.documentID, - documentGeneration: editingSession.documentGeneration, - minimumRevision: editingSession.currentRevision, + documentID: inFlight.documentID, + documentGeneration: inFlight.documentGeneration, + minimumRevision: inFlight.minimumRevision, type: type, payload: NoteEditorMarkdownPayload(markdown: command.markdown) - ), source: command) + ), source: inFlight) } func runPendingCommandIfReady() { ingestCommandBinding() guard isReady, pendingV2DocumentID == nil, - inFlightCommandID == nil, - let next = queuedCommands.first else { return } - inFlightCommandID = next.id - run(next) + inFlightCommand == nil, + let next = queuedCommands.first, + let editingSession else { return } + let inFlight = InFlightCommand( + command: next, + documentID: editingSession.documentID, + documentGeneration: editingSession.documentGeneration, + minimumRevision: editingSession.currentRevision + ) + inFlightCommand = inFlight + if next.kind != .scrollToHeading { + onContentCommandPending(inFlight.documentID, next) + } + run(inFlight) } /// 内容命令保序且不设数量上限;只有最终状态可替代前态的命令合并。 @@ -1703,7 +1742,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { pending.id != lastCommandID, !queuedCommands.contains(where: { $0.id == pending.id }) else { return } if let tail = queuedCommands.last, - tail.id != inFlightCommandID, + tail.id != inFlightCommand?.command.id, tail.kind == pending.kind, pending.kind == .reloadDocument || pending.kind == .scrollToHeading { queuedCommands[queuedCommands.count - 1] = pending @@ -1720,7 +1759,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { private func dispatchQueued<Payload>( _ envelope: NoteEditorCommandEnvelope<Payload>, - source: NoteEditorCommand + source: InFlightCommand ) { guard let data = try? JSONEncoder().encode(envelope), let json = String(data: data, encoding: .utf8), @@ -1728,21 +1767,35 @@ struct RichMarkdownEditorView: NSViewRepresentable { rejectCommand(source, reason: "bridge unavailable") return } - webView.evaluateJavaScript("window.WeiBeiEditor?.dispatchCommand(\(json))") { [weak self] _, error in - guard let self, self.inFlightCommandID == source.id, let error else { return } - Self.bridgeLogger.error( - "editor command evaluation failed: \(error.localizedDescription, privacy: .private)" - ) - self.rejectCommand(source, reason: "javascript evaluation failed") + webView.evaluateJavaScript("window.WeiBeiEditor?.dispatchCommand(\(json))") { [weak self] result, error in + guard let self, + self.inFlightCommand?.command.id == source.command.id else { return } + if let error { + Self.bridgeLogger.error( + "editor command evaluation failed: \(error.localizedDescription, privacy: .private)" + ) + self.rejectCommand(source, reason: "javascript evaluation failed") + } else if result as? Bool != true { + Self.bridgeLogger.error("editor command was not accepted by the web bridge") + self.rejectCommand(source, reason: "command was not accepted") + } } } - private func finishCommand(_ commandID: String, rejectionReason: String?) { + private func finishCommand( + _ commandID: String, + documentID: String, + documentGeneration: UInt64, + rejectionReason: String? + ) { guard let id = UUID(uuidString: commandID), - id == inFlightCommandID, + let inFlight = inFlightCommand, + id == inFlight.command.id, + documentID == inFlight.documentID, + documentGeneration == inFlight.documentGeneration, queuedCommands.first?.id == id else { return } let source = queuedCommands.removeFirst() - inFlightCommandID = nil + inFlightCommand = nil if let rejectionReason { Self.bridgeLogger.error( "editor command rejected: \(rejectionReason, privacy: .private)" @@ -1750,16 +1803,24 @@ struct RichMarkdownEditorView: NSViewRepresentable { if command.wrappedValue?.id == source.id { command.wrappedValue = nil } - onCommandRejected(source) + onCommandRejected(inFlight.documentID, source) } else { lastCommandID = source.id + if source.kind != .scrollToHeading { + onContentCommandApplied(inFlight.documentID, source) + } } runPendingCommandIfReady() } - private func rejectCommand(_ source: NoteEditorCommand, reason: String) { - guard inFlightCommandID == source.id else { return } - finishCommand(source.id.uuidString, rejectionReason: reason) + private func rejectCommand(_ source: InFlightCommand, reason: String) { + guard inFlightCommand?.command.id == source.command.id else { return } + finishCommand( + source.command.id.uuidString, + documentID: source.documentID, + documentGeneration: source.documentGeneration, + rejectionReason: reason + ) } private static let bridgeLogger = Logger( diff --git a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift index 60f16eb4e..293b106a1 100644 --- a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift @@ -8,7 +8,7 @@ enum ImportedIdentitySelfCheck { @MainActor static func run() throws { try launchAndPrimaryEntriesStartBlank() - try dirtyEditorSelectionWaitsForAcceptedSnapshot() + try editorSelectionWaitsForCommandAndAcceptedSnapshot() try paneAndInteractionStateDoNotInvalidateWorkspaceStore() try agentFailureMessagesExposeOnlyUserFacingDetails() try storageModelsDecodeLegacySnapshotsAndRoundTrip() @@ -24,7 +24,7 @@ enum ImportedIdentitySelfCheck { } @MainActor - private static func dirtyEditorSelectionWaitsForAcceptedSnapshot() throws { + private static func editorSelectionWaitsForCommandAndAcceptedSnapshot() throws { let fixture = try WorkspaceFixture(name: "dirty-editor-selection") defer { fixture.remove() } @@ -64,24 +64,28 @@ enum ImportedIdentitySelfCheck { var bridgeToken = store.noteEditingSession.bindSnapshotRequestHandler { requests.append($0) } - try check( - store.noteEditingSession.receive(NoteEditorDirtyChangedEvent( - documentID: noteA.id, - documentGeneration: store.noteEditingSession.documentGeneration, - revision: 1, - dirty: true - )), - "脏编辑器切换场景没有接收正文变化" - ) + let pendingCommand = NoteEditorCommand(kind: .insertMarkdown, markdown: "最后一段编辑") + store.noteEditorContentCommandPending(pendingCommand, documentID: noteA.id) store.select(itemID: noteC.id) store.select(itemID: noteB.id) try check( store.activeNoteItemID == noteA.id && store.noteSelectionStatusMessage?.contains("正在保存") == true - && requests.count == 1, - "脏编辑器切换没有保持 A,或没有合并为一次真实快照" + && requests.isEmpty, + "内容命令回执前切换没有保持 A,或提前销毁了来源编辑器" ) + store.noteEditorCommandRejected(pendingCommand, documentID: noteA.id) + try check( + store.activeNoteItemID == noteA.id + && store.canRetryRejectedNoteEditorCommand, + "内容命令被拒绝后没有留在来源笔记并允许重试" + ) + store.retryRejectedNoteEditorCommand() + try check(store.noteEditorCommand?.id == pendingCommand.id, "重试没有保留原命令编号和内容") + store.noteEditorCommand = nil + store.noteEditorContentCommandApplied(pendingCommand, documentID: noteA.id) + try check(requests.count == 1, "内容命令应用后没有进入现有真实快照保存链") store.noteEditingSession.unbindSnapshotRequestHandler(bridgeToken) try check( diff --git a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift index 4845ec2b0..861bfc38e 100644 --- a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift +++ b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift @@ -10,6 +10,7 @@ final class RichMarkdownEditorBridgeTests: XCTestCase { func testContentCommandsBeyondOldLimitAwaitAcknowledgementAndRejectedContentRetries() async throws { var command: NoteEditorCommand? = nil var rejectedCommand: NoteEditorCommand? = nil + var rejectedDocumentID: String? = nil let rejected = expectation(description: "rejected content remained recoverable") let editor = RichMarkdownEditorView( documentID: "note-a", @@ -18,7 +19,8 @@ final class RichMarkdownEditorBridgeTests: XCTestCase { editingSession: NoteEditingSession(documentID: "note-a"), onSelectionChange: { _, _ in }, onAskAgentWithSelection: { _, _ in }, - onCommandRejected: { failed in + onCommandRejected: { documentID, failed in + rejectedDocumentID = documentID rejectedCommand = failed rejected.fulfill() } @@ -64,7 +66,6 @@ final class RichMarkdownEditorBridgeTests: XCTestCase { dispatchCommand(command) { const markdown = command.payload.markdown; if (markdown === rejectedMarkdown) { - reply("commandRejected", command, "fixture rejection"); return false; } if (!appliedIDs.has(command.commandID)) { @@ -104,6 +105,7 @@ final class RichMarkdownEditorBridgeTests: XCTestCase { coordinator.runPendingCommandIfReady() await fulfillment(of: [rejected], timeout: 3) let recoverable = try XCTUnwrap(rejectedCommand) + XCTAssertEqual(rejectedDocumentID, "note-a") XCTAssertEqual(recoverable.markdown, "保留我") _ = try await webView.evaluateJavaScript(""" From d0cb4cc650b591a79d9469e53bc81832d001f298 Mon Sep 17 00:00:00 2001 From: taekchef <taekchef@users.noreply.github.com> Date: Mon, 24 Aug 2026 07:04:27 +0800 Subject: [PATCH 6/8] =?UTF-8?q?fix:=20=E5=8F=91=E5=B8=83=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E6=97=B6=E9=94=81=E5=AE=9A=E6=9D=A5=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 10 +- .../ImportedIdentitySelfCheck.swift | 3 +- .../RichMarkdownEditorBridgeTests.swift | 255 +++++++++++------- 3 files changed, 164 insertions(+), 104 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 631551b1a..262f2a197 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -581,7 +581,13 @@ final class WorkspaceStore: ObservableObject { } } } - @Published var noteEditorCommand: NoteEditorCommand? + @Published var noteEditorCommand: NoteEditorCommand? { + willSet { + guard let command = newValue, + command.kind != .scrollToHeading else { return } + unresolvedContentCommandDocumentIDs[command.id] = noteEditingSession.documentID + } + } @Published private var rejectedNoteEditorCommands: [RejectedNoteEditorCommand] = [] private var unresolvedContentCommandDocumentIDs: [UUID: String] = [:] /// Success / info banner for note create/switch — separate from errors so it auto-dismisses cleanly. @@ -10240,7 +10246,7 @@ final class WorkspaceStore: ObservableObject { } func noteEditorContentCommandPending(_ command: NoteEditorCommand, documentID: String) { - unresolvedContentCommandDocumentIDs[command.id] = documentID + guard unresolvedContentCommandDocumentIDs[command.id] == documentID else { return } if pendingNoteSelection != nil, noteEditingSession.documentID == documentID { noteSelectionTransitionState = .saving diff --git a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift index 293b106a1..5ceeb2127 100644 --- a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift @@ -65,7 +65,7 @@ enum ImportedIdentitySelfCheck { requests.append($0) } let pendingCommand = NoteEditorCommand(kind: .insertMarkdown, markdown: "最后一段编辑") - store.noteEditorContentCommandPending(pendingCommand, documentID: noteA.id) + store.noteEditorCommand = pendingCommand store.select(itemID: noteC.id) store.select(itemID: noteB.id) @@ -75,6 +75,7 @@ enum ImportedIdentitySelfCheck { && requests.isEmpty, "内容命令回执前切换没有保持 A,或提前销毁了来源编辑器" ) + store.noteEditorCommand = nil store.noteEditorCommandRejected(pendingCommand, documentID: noteA.id) try check( store.activeNoteItemID == noteA.id diff --git a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift index 861bfc38e..0e9666270 100644 --- a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift +++ b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift @@ -7,122 +7,62 @@ import WeiBeiCore final class RichMarkdownEditorBridgeTests: XCTestCase { @MainActor - func testContentCommandsBeyondOldLimitAwaitAcknowledgementAndRejectedContentRetries() async throws { - var command: NoteEditorCommand? = nil - var rejectedCommand: NoteEditorCommand? = nil - var rejectedDocumentID: String? = nil - let rejected = expectation(description: "rejected content remained recoverable") - let editor = RichMarkdownEditorView( - documentID: "note-a", - markdown: "", - command: Binding(get: { command }, set: { command = $0 }), - editingSession: NoteEditingSession(documentID: "note-a"), - onSelectionChange: { _, _ in }, - onAskAgentWithSelection: { _, _ in }, - onCommandRejected: { documentID, failed in - rejectedDocumentID = documentID - rejectedCommand = failed - rejected.fulfill() - } - ) - let coordinator = editor.makeCoordinator() + func testContentCommandsBeyondOldLimitAwaitAcknowledgement() async throws { let allApplied = expectation(description: "all content commands applied") - let retried = expectation(description: "rejected content applied after retry") - let completionProbe = EditorCommandQueueProbe { name in - if name == "allApplied" { - allApplied.fulfill() - } else if name == "retried" { - retried.fulfill() - } + let fixture = await makeCommandBridge { name in + if name == "allApplied" { allApplied.fulfill() } } - let controller = WKUserContentController() - controller.add(coordinator, name: "commandApplied") - controller.add(coordinator, name: "commandRejected") - controller.add(completionProbe, name: "queueProbe") - let configuration = WKWebViewConfiguration() - configuration.userContentController = controller - let loaded = expectation(description: "command bridge loaded") - let navigationProbe = FinalizedMarkdownNavigationProbe { loaded.fulfill() } - let webView = WKWebView(frame: .zero, configuration: configuration) - webView.navigationDelegate = navigationProbe - webView.loadHTMLString(""" - <!doctype html> - <body></body> - <script> - const appliedIDs = new Set(); - const appliedMarkdown = []; - let rejectedMarkdown = "保留我"; - const reply = (name, command, reason) => { - window.webkit.messageHandlers[name].postMessage({ - protocolVersion: 2, - commandID: command.commandID, - documentID: "note-a", - documentGeneration: 1, - revision: 0, - ...(reason ? { reason } : {}) - }); - }; - window.WeiBeiEditor = { - dispatchCommand(command) { - const markdown = command.payload.markdown; - if (markdown === rejectedMarkdown) { - return false; - } - if (!appliedIDs.has(command.commandID)) { - appliedIDs.add(command.commandID); - appliedMarkdown.push(markdown); - } - reply("commandApplied", command); - if (appliedMarkdown.length === 18) { - window.webkit.messageHandlers.queueProbe.postMessage("allApplied"); - } else if (markdown === "保留我") { - window.webkit.messageHandlers.queueProbe.postMessage("retried"); - } - return true; - }, - allowRejectedContent() { rejectedMarkdown = null; }, - appliedMarkdown() { return appliedMarkdown; } - }; - </script> - """, baseURL: nil) - await fulfillment(of: [loaded], timeout: 3) - coordinator.webView = webView for index in 0..<18 { - command = NoteEditorCommand(kind: .insertMarkdown, markdown: "内容\(index)") - coordinator.runPendingCommandIfReady() + fixture.enqueue(NoteEditorCommand(kind: .insertMarkdown, markdown: "内容\(index)")) } - coordinator.isReady = true - coordinator.runPendingCommandIfReady() + fixture.start() await fulfillment(of: [allApplied], timeout: 3) - let appliedValue = try await webView.evaluateJavaScript( - "window.WeiBeiEditor.appliedMarkdown()" - ) - let applied = try XCTUnwrap(appliedValue as? [String]) + let applied = try await fixture.appliedMarkdown() XCTAssertEqual(applied, (0..<18).map { "内容\($0)" }) + } - command = NoteEditorCommand(kind: .replaceSelection, markdown: "保留我") - coordinator.runPendingCommandIfReady() + @MainActor + func testRejectedContentKeepsDispatchDocumentAndRetries() async throws { + var rejectedCommand: NoteEditorCommand? + var rejectedDocumentID: String? + let rejected = expectation(description: "rejected content remained recoverable") + let retried = expectation(description: "rejected content applied after retry") + let fixture = await makeCommandBridge(onRejected: { documentID, command in + rejectedDocumentID = documentID + rejectedCommand = command + rejected.fulfill() + }, onProbe: { name in + if name == "retried" { retried.fulfill() } + }) + + fixture.enqueue(NoteEditorCommand(kind: .replaceSelection, markdown: "保留我")) + fixture.start() await fulfillment(of: [rejected], timeout: 3) let recoverable = try XCTUnwrap(rejectedCommand) XCTAssertEqual(rejectedDocumentID, "note-a") XCTAssertEqual(recoverable.markdown, "保留我") - _ = try await webView.evaluateJavaScript(""" - (() => { - window.WeiBeiEditor.allowRejectedContent(); - return true; - })() - """) - command = recoverable - coordinator.runPendingCommandIfReady() + try await fixture.allowRejectedContent() + fixture.enqueue(recoverable) await fulfillment(of: [retried], timeout: 3) - let afterRetryValue = try await webView.evaluateJavaScript( - "window.WeiBeiEditor.appliedMarkdown()" - ) - let afterRetry = try XCTUnwrap(afterRetryValue as? [String]) + let afterRetry = try await fixture.appliedMarkdown() XCTAssertEqual(afterRetry.filter { $0 == "保留我" }.count, 1) - withExtendedLifetime((navigationProbe, completionProbe)) {} + } + + @MainActor + private func makeCommandBridge( + onRejected: @escaping (String, NoteEditorCommand) -> Void = { _, _ in }, + onProbe: @escaping (String) -> Void + ) async -> EditorCommandBridgeFixture { + let loaded = expectation(description: "command bridge loaded") + let fixture = EditorCommandBridgeFixture( + onLoaded: { loaded.fulfill() }, + onRejected: onRejected, + onProbe: onProbe + ) + await fulfillment(of: [loaded], timeout: 3) + return fixture } @MainActor @@ -291,6 +231,119 @@ final class RichMarkdownEditorBridgeTests: XCTestCase { } } +@MainActor +private final class EditorCommandBridgeFixture { + private final class CommandBox { + var value: NoteEditorCommand? + } + + private let commandBox: CommandBox + private let completionProbe: EditorCommandQueueProbe + private let navigationProbe: FinalizedMarkdownNavigationProbe + private let coordinator: RichMarkdownEditorView.Coordinator + private let webView: WKWebView + + init( + onLoaded: @escaping () -> Void, + onRejected: @escaping (String, NoteEditorCommand) -> Void, + onProbe: @escaping (String) -> Void + ) { + let commandBox = CommandBox() + self.commandBox = commandBox + let editor = RichMarkdownEditorView( + documentID: "note-a", + markdown: "", + command: Binding( + get: { commandBox.value }, + set: { commandBox.value = $0 } + ), + editingSession: NoteEditingSession(documentID: "note-a"), + onSelectionChange: { _, _ in }, + onAskAgentWithSelection: { _, _ in }, + onCommandRejected: onRejected + ) + let coordinator = editor.makeCoordinator() + self.coordinator = coordinator + let completionProbe = EditorCommandQueueProbe(receive: onProbe) + self.completionProbe = completionProbe + let navigationProbe = FinalizedMarkdownNavigationProbe(onFinish: onLoaded) + self.navigationProbe = navigationProbe + + let controller = WKUserContentController() + controller.add(coordinator, name: "commandApplied") + controller.add(coordinator, name: "commandRejected") + controller.add(completionProbe, name: "queueProbe") + let configuration = WKWebViewConfiguration() + configuration.userContentController = controller + let webView = WKWebView(frame: .zero, configuration: configuration) + self.webView = webView + webView.navigationDelegate = navigationProbe + webView.loadHTMLString(Self.page, baseURL: nil) + coordinator.webView = webView + } + + func enqueue(_ command: NoteEditorCommand) { + commandBox.value = command + coordinator.runPendingCommandIfReady() + } + + func start() { + coordinator.isReady = true + coordinator.runPendingCommandIfReady() + } + + func allowRejectedContent() async throws { + _ = try await webView.evaluateJavaScript( + "window.WeiBeiEditor.allowRejectedContent()" + ) + } + + func appliedMarkdown() async throws -> [String] { + let value = try await webView.evaluateJavaScript( + "window.WeiBeiEditor.appliedMarkdown()" + ) + return try XCTUnwrap(value as? [String]) + } + + private static let page = """ + <!doctype html> + <body></body> + <script> + const appliedIDs = new Set(); + const appliedMarkdown = []; + let rejectedMarkdown = "保留我"; + const replyApplied = command => { + window.webkit.messageHandlers.commandApplied.postMessage({ + protocolVersion: 2, + commandID: command.commandID, + documentID: "note-a", + documentGeneration: 1, + revision: 0 + }); + }; + window.WeiBeiEditor = { + dispatchCommand(command) { + const markdown = command.payload.markdown; + if (markdown === rejectedMarkdown) return false; + if (!appliedIDs.has(command.commandID)) { + appliedIDs.add(command.commandID); + appliedMarkdown.push(markdown); + } + replyApplied(command); + if (appliedMarkdown.length === 18) { + window.webkit.messageHandlers.queueProbe.postMessage("allApplied"); + } else if (markdown === "保留我") { + window.webkit.messageHandlers.queueProbe.postMessage("retried"); + } + return true; + }, + allowRejectedContent() { rejectedMarkdown = null; return true; }, + appliedMarkdown() { return appliedMarkdown; } + }; + </script> + """ +} + private final class EditorCommandQueueProbe: NSObject, WKScriptMessageHandler { private let receive: (String) -> Void From 16db82bd4d270077bce6049be0fac82fdf77e60b Mon Sep 17 00:00:00 2001 From: taekchef <taekchef@users.noreply.github.com> Date: Mon, 24 Aug 2026 07:23:00 +0800 Subject: [PATCH 7/8] =?UTF-8?q?fix:=20=E7=A1=AE=E8=AE=A4=E7=AC=94=E8=AE=B0?= =?UTF-8?q?=E6=8C=81=E4=B9=85=E5=8C=96=E5=90=8E=E5=86=8D=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 93 +++++++++++++-- .../ImportedIdentitySelfCheck.swift | 108 ++++++++++++------ 2 files changed, 158 insertions(+), 43 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 262f2a197..8b26ea6a5 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -798,6 +798,7 @@ final class WorkspaceStore: ObservableObject { case idle case saving case failed(NoteEditingSessionError) + case persistenceFailed } private struct PendingNoteSelection { @@ -10223,6 +10224,11 @@ final class WorkspaceStore: ObservableObject { "保存过程中当前笔记发生了变化,魏碑没有切换。请重试。", "The current note changed while saving, so WeiBei did not switch. Please retry." ) + case .persistenceFailed: + ui( + "当前笔记尚未安全保存,魏碑没有切换。请重试。", + "The current note was not safely saved, so WeiBei did not switch. Please retry." + ) } } @@ -10278,10 +10284,12 @@ final class WorkspaceStore: ObservableObject { } var canRetryPendingNoteSelection: Bool { - if case .failed = noteSelectionTransitionState { + switch noteSelectionTransitionState { + case .failed, .persistenceFailed: return pendingNoteSelection != nil + case .idle, .saving: + return false } - return false } func retryPendingNoteSelection() { @@ -10364,16 +10372,80 @@ final class WorkspaceStore: ObservableObject { failPendingNoteSelection(.documentChanged) return } - let apply = pendingNoteSelection?.apply - pendingNoteSelection = nil - noteSelectionTransitionState = .idle - persistCurrentNote() - apply?() + if noteEditorSnapshotIsDurable(snapshot, digest: digest) { + applyPendingNoteSelection() + return + } + guard item(withID: snapshot.documentID)? + .editsBackingMarkdownFile == false else { + failPendingNoteSelectionPersistence() + return + } + Task { @MainActor [weak self] in + await self?.persistPendingNoteSelectionSnapshot( + snapshot, + digest: digest + ) + } case .failure(let error): failPendingNoteSelection(error) } } + private func persistPendingNoteSelectionSnapshot( + _ snapshot: NoteEditorSnapshotReadyEvent, + digest: String + ) async { + let persisted = await persistWorkspaceNow() + guard pendingNoteSelection != nil else { + noteSelectionTransitionState = .idle + return + } + guard noteEditingSession.documentID == snapshot.documentID else { + failPendingNoteSelection(.documentChanged) + return + } + guard !hasUnresolvedContentCommand(for: snapshot.documentID) else { + noteSelectionTransitionState = .saving + return + } + guard noteEditingSession.currentRevision == snapshot.revision, + let accepted = latestNoteEditorSnapshot, + accepted.documentID == snapshot.documentID, + accepted.revision == snapshot.revision, + accepted.digest == digest else { + requestPendingNoteSelectionSnapshot() + return + } + guard persisted, + noteEditorSnapshotIsDurable(snapshot, digest: digest) else { + failPendingNoteSelectionPersistence() + return + } + applyPendingNoteSelection() + } + + private func noteEditorSnapshotIsDurable( + _ snapshot: NoteEditorSnapshotReadyEvent, + digest: String + ) -> Bool { + guard noteEditingSession.documentID == snapshot.documentID, + noteEditingSession.currentRevision == snapshot.revision, + !noteEditingSession.dirty, + let accepted = latestNoteEditorSnapshot else { return false } + return accepted.documentID == snapshot.documentID + && accepted.revision == snapshot.revision + && accepted.digest == digest + && accepted.baseDigest == digest + } + + private func applyPendingNoteSelection() { + let apply = pendingNoteSelection?.apply + pendingNoteSelection = nil + noteSelectionTransitionState = .idle + apply?() + } + private func failPendingNoteSelection(_ error: NoteEditingSessionError) { WeiBeiLog.noteRepair.error( "note selection snapshot failed: \(String(describing: error), privacy: .private)" @@ -10381,6 +10453,13 @@ final class WorkspaceStore: ObservableObject { noteSelectionTransitionState = .failed(error) } + private func failPendingNoteSelectionPersistence() { + WeiBeiLog.noteRepair.error( + "note selection stopped because the accepted snapshot was not durably persisted" + ) + noteSelectionTransitionState = .persistenceFailed + } + func selectMeasured(itemID: String?, opensNotebook: Bool?) { invalidateAgentContext() persistCurrentNote() diff --git a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift index 5ceeb2127..6767a8061 100644 --- a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift @@ -25,43 +25,51 @@ enum ImportedIdentitySelfCheck { @MainActor private static func editorSelectionWaitsForCommandAndAcceptedSnapshot() throws { - let fixture = try WorkspaceFixture(name: "dirty-editor-selection") + let fixture = try WorkspaceFixture(name: "durable-editor-selection") defer { fixture.remove() } - let noteAURL = fixture.importsDirectory.appendingPathComponent("A笔记.md") - let noteBURL = fixture.importsDirectory.appendingPathComponent("B笔记.md") - let noteCURL = fixture.importsDirectory.appendingPathComponent("C笔记.md") - try Data("# A笔记\n\n旧正文".utf8).write(to: noteAURL) - try Data("# B笔记\n\n正文".utf8).write(to: noteBURL) - try Data("# C笔记\n\n正文".utf8).write(to: noteCURL) + let notes = ["A", "B", "C"].map { name in + StudyItem( + id: "internal-note-\(name.lowercased())", + title: "\(name) 笔记", + subtitle: "\(name) 笔记", + kind: .text, + urlPath: nil, + isSample: false, + isNotebookNote: true, + storage: .common(relativePath: "") + ) + } + let noteA = notes[0] + let noteB = notes[1] + let noteC = notes[2] + try fixture.write(PersistedWorkspace( + importedItems: notes, + notesByItemID: [ + noteA.id: "# A笔记\n\n旧正文", + noteB.id: "# B笔记\n\n正文", + noteC.id: "# C笔记\n\n正文", + ], + activeNotebookItemID: noteA.id, + noteSourceLinksMigrationVersion: 1 + )) + var rejectsWorkspaceWrite = false let store = WorkspaceStore( workspaceDirectory: fixture.workspaceDirectory, + workspaceSnapshotWriter: { data, url in + if rejectsWorkspaceWrite { + throw CocoaError(.fileWriteUnknown) + } + try data.write(to: url, options: [.atomic]) + }, selectionAskThreadDefaults: fixture.selectionAskThreadDefaults ) - _ = importFilesAndWait( - store, - [noteAURL, noteBURL, noteCURL], - selectsFirstImportedItem: false, - markdownNotePaths: [noteAURL.path, noteBURL.path, noteCURL.path] - ) - let noteA = try require( - store.courseNotebookItems.first { $0.urlPath == noteAURL.path }, - "脏编辑器切换场景找不到 A 笔记" - ) - let noteB = try require( - store.courseNotebookItems.first { $0.urlPath == noteBURL.path }, - "脏编辑器切换场景找不到 B 笔记" - ) - let noteC = try require( - store.courseNotebookItems.first { $0.urlPath == noteCURL.path }, - "脏编辑器切换场景找不到 C 笔记" - ) store.select(itemID: noteA.id) store.noteEditingSession.replaceDocument(with: noteA.id) var requests = [NoteEditorSnapshotRequest]() - var bridgeToken = store.noteEditingSession.bindSnapshotRequestHandler { + let bridgeToken = store.noteEditingSession.bindSnapshotRequestHandler { requests.append($0) } let pendingCommand = NoteEditorCommand(kind: .insertMarkdown, markdown: "最后一段编辑") @@ -88,22 +96,41 @@ enum ImportedIdentitySelfCheck { store.noteEditorContentCommandApplied(pendingCommand, documentID: noteA.id) try check(requests.count == 1, "内容命令应用后没有进入现有真实快照保存链") - store.noteEditingSession.unbindSnapshotRequestHandler(bridgeToken) + rejectsWorkspaceWrite = true + let request = try require(requests.first, "内容命令应用后没有请求真实快照") + let latestA = "# A笔记\n\n最后一段编辑" + try check( + store.noteEditingSession.receive(NoteEditorSnapshotReadyEvent( + requestID: request.requestID ?? "", + documentID: request.documentID, + documentGeneration: request.documentGeneration, + revision: 1, + markdown: latestA + )), + "真实快照没有被编辑会话接收" + ) + let failureDeadline = Date().addingTimeInterval(5) + while !store.canRetryPendingNoteSelection, + Date() < failureDeadline { + RunLoop.main.run( + mode: .default, + before: Date(timeIntervalSinceNow: 0.01) + ) + } + let snapshotAfterFailure = try fixture.readSnapshot() try check( store.activeNoteItemID == noteA.id && store.canRetryPendingNoteSelection - && store.noteSelectionStatusMessage?.contains("持久恢复点") == true, - "快照失败后离开了 A,或没有提供带恢复来源说明的重试" + && store.noteSelectionStatusMessage?.contains("尚未安全保存") == true + && snapshotAfterFailure.notesByItemID[noteA.id] != latestA, + "工作区写入失败后离开了 A,或把内存快照误当成安全保存" ) + rejectsWorkspaceWrite = false requests.removeAll() - bridgeToken = store.noteEditingSession.bindSnapshotRequestHandler { - requests.append($0) - } store.retryPendingNoteSelection() let retry = try require(requests.first, "重试没有重新请求真实快照") try check(store.activeNoteItemID == noteA.id, "重试快照送达前离开了 A") - let latestA = "# A笔记\n\n最后一段编辑" try check( store.noteEditingSession.receive(NoteEditorSnapshotReadyEvent( requestID: retry.requestID ?? "", @@ -114,15 +141,24 @@ enum ImportedIdentitySelfCheck { )), "重试快照没有被编辑会话接收" ) + let successDeadline = Date().addingTimeInterval(5) + while store.activeNoteItemID != noteB.id, + Date() < successDeadline { + RunLoop.main.run( + mode: .default, + before: Date(timeIntervalSinceNow: 0.01) + ) + } try check( store.activeNoteItemID == noteB.id, - "快照接收后没有只切到最后点击的 B" + "工作区恢复写入后没有只切到最后点击的 B" ) store.select(itemID: noteA.id) - let reopenedDiskA = try String(contentsOf: noteAURL, encoding: .utf8) + let snapshotAfterRetry = try fixture.readSnapshot() try check( - store.noteText == latestA && reopenedDiskA == latestA, + store.noteText == latestA + && snapshotAfterRetry.notesByItemID[noteA.id] == latestA, "重开 A 后最新正文不完整" ) store.noteEditingSession.unbindSnapshotRequestHandler(bridgeToken) From d7aad9a0fbfe9b713f3a865a51900b97c33cff59 Mon Sep 17 00:00:00 2001 From: taekchef <taekchef@users.noreply.github.com> Date: Mon, 24 Aug 2026 07:40:32 +0800 Subject: [PATCH 8/8] =?UTF-8?q?fix:=20=E7=BC=96=E8=BE=91=E5=99=A8=E9=87=8D?= =?UTF-8?q?=E5=BB=BA=E6=97=B6=E4=BF=9D=E7=95=99=E6=9C=AA=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 52 ++++++-- .../WeiBei/Views/RichMarkdownEditorView.swift | 74 +++++++---- Sources/WeiBeiCore/WorkspaceModels.swift | 4 + .../ImportedIdentitySelfCheck.swift | 115 +++++++----------- .../RichMarkdownEditorBridgeTests.swift | 65 +++++----- 5 files changed, 174 insertions(+), 136 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 8b26ea6a5..f3c794113 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -583,13 +583,27 @@ final class WorkspaceStore: ObservableObject { } @Published var noteEditorCommand: NoteEditorCommand? { willSet { + if let current = noteEditorCommand, + current.id != newValue?.id, + current.kind.isContentCommand, + let tracked = unresolvedContentCommands[current.id], + !tracked.isCoordinatorOwned { + noteEditorCommandRejected( + current, + documentID: noteEditingSession.documentID + ) + } guard let command = newValue, - command.kind != .scrollToHeading else { return } - unresolvedContentCommandDocumentIDs[command.id] = noteEditingSession.documentID + command.kind.isContentCommand, + unresolvedContentCommands[command.id] == nil else { return } + unresolvedContentCommands[command.id] = TrackedNoteEditorCommand( + documentID: noteEditingSession.documentID, + command: command + ) } } @Published private var rejectedNoteEditorCommands: [RejectedNoteEditorCommand] = [] - private var unresolvedContentCommandDocumentIDs: [UUID: String] = [:] + private var unresolvedContentCommands: [UUID: TrackedNoteEditorCommand] = [:] /// Success / info banner for note create/switch — separate from errors so it auto-dismisses cleanly. @Published var transientNoteStatus: String? @Published private var noteSelectionTransitionState = NoteSelectionTransitionState.idle @@ -805,11 +819,14 @@ final class WorkspaceStore: ObservableObject { let apply: () -> Void } - private struct RejectedNoteEditorCommand { + private struct TrackedNoteEditorCommand { let documentID: String let command: NoteEditorCommand + var isCoordinatorOwned = false } + private typealias RejectedNoteEditorCommand = TrackedNoteEditorCommand + private enum NotebookNoteSeed { case blank case currentMaterial(StudyItem) @@ -10252,7 +10269,10 @@ final class WorkspaceStore: ObservableObject { } func noteEditorContentCommandPending(_ command: NoteEditorCommand, documentID: String) { - guard unresolvedContentCommandDocumentIDs[command.id] == documentID else { return } + guard var tracked = unresolvedContentCommands[command.id], + tracked.documentID == documentID else { return } + tracked.isCoordinatorOwned = true + unresolvedContentCommands[command.id] = tracked if pendingNoteSelection != nil, noteEditingSession.documentID == documentID { noteSelectionTransitionState = .saving @@ -10260,18 +10280,22 @@ final class WorkspaceStore: ObservableObject { } func noteEditorContentCommandApplied(_ command: NoteEditorCommand, documentID: String) { - guard unresolvedContentCommandDocumentIDs[command.id] == documentID else { return } - unresolvedContentCommandDocumentIDs.removeValue(forKey: command.id) + guard unresolvedContentCommands[command.id]?.documentID == documentID else { return } + unresolvedContentCommands.removeValue(forKey: command.id) rejectedNoteEditorCommands.removeAll { $0.command.id == command.id } resumePendingNoteSelection(afterResolvingCommandFor: documentID) } func noteEditorCommandRejected(_ command: NoteEditorCommand, documentID: String) { - guard !rejectedNoteEditorCommands.contains(where: { $0.command.id == command.id }) else { return } - rejectedNoteEditorCommands.append(RejectedNoteEditorCommand( - documentID: documentID, - command: command - )) + guard command.kind.isContentCommand else { return } + var tracked = unresolvedContentCommands[command.id] + ?? TrackedNoteEditorCommand(documentID: documentID, command: command) + tracked.isCoordinatorOwned = false + unresolvedContentCommands[command.id] = tracked + guard !rejectedNoteEditorCommands.contains(where: { + $0.command.id == command.id + }) else { return } + rejectedNoteEditorCommands.append(tracked) } func retryRejectedNoteEditorCommand() { @@ -10320,7 +10344,9 @@ final class WorkspaceStore: ObservableObject { } private func hasUnresolvedContentCommand(for documentID: String) -> Bool { - unresolvedContentCommandDocumentIDs.values.contains(documentID) + unresolvedContentCommands.values.contains { + $0.documentID == documentID + } } private func resumePendingNoteSelection(afterResolvingCommandFor documentID: String) { diff --git a/Sources/WeiBei/Views/RichMarkdownEditorView.swift b/Sources/WeiBei/Views/RichMarkdownEditorView.swift index eb7c47b6c..957b4bc71 100644 --- a/Sources/WeiBei/Views/RichMarkdownEditorView.swift +++ b/Sources/WeiBei/Views/RichMarkdownEditorView.swift @@ -948,6 +948,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { } static func dismantleNSView(_ view: WKWebView, coordinator: Coordinator) { + coordinator.rejectUnconfirmedContentCommands() coordinator.unbindEditingSession() coordinator.imageSchemeHandler.invalidate() WeiBeiPerf.event( @@ -1108,7 +1109,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { var webMarkdown = "" var pendingStreamingCompletion = false var lastCommandID: UUID? - private var queuedCommands: [NoteEditorCommand] = [] + private var queuedCommands: [InFlightCommand] = [] private var inFlightCommand: InFlightCommand? private var editingSessionBindingToken: UUID? private var pendingV2DocumentID: String? @@ -1339,6 +1340,7 @@ struct RichMarkdownEditorView: NSViewRepresentable { // WebView cannot become ready again. finalizedRenderGeneration &+= 1 isReady = false + rejectUnconfirmedContentCommands() onRenderFailure() } @@ -1721,33 +1723,35 @@ struct RichMarkdownEditorView: NSViewRepresentable { guard isReady, pendingV2DocumentID == nil, inFlightCommand == nil, - let next = queuedCommands.first, - let editingSession else { return } - let inFlight = InFlightCommand( - command: next, - documentID: editingSession.documentID, - documentGeneration: editingSession.documentGeneration, - minimumRevision: editingSession.currentRevision - ) - inFlightCommand = inFlight - if next.kind != .scrollToHeading { - onContentCommandPending(inFlight.documentID, next) - } - run(inFlight) + let next = queuedCommands.first else { return } + inFlightCommand = next + run(next) } /// 内容命令保序且不设数量上限;只有最终状态可替代前态的命令合并。 private func ingestCommandBinding() { guard let pending = command.wrappedValue, pending.id != lastCommandID, - !queuedCommands.contains(where: { $0.id == pending.id }) else { return } + !queuedCommands.contains(where: { + $0.command.id == pending.id + }), + let editingSession else { return } + let source = InFlightCommand( + command: pending, + documentID: editingSession.documentID, + documentGeneration: editingSession.documentGeneration, + minimumRevision: editingSession.currentRevision + ) if let tail = queuedCommands.last, - tail.id != inFlightCommand?.command.id, - tail.kind == pending.kind, + tail.command.id != inFlightCommand?.command.id, + tail.command.kind == pending.kind, pending.kind == .reloadDocument || pending.kind == .scrollToHeading { - queuedCommands[queuedCommands.count - 1] = pending + queuedCommands[queuedCommands.count - 1] = source } else { - queuedCommands.append(pending) + queuedCommands.append(source) + } + if pending.kind.isContentCommand { + onContentCommandPending(source.documentID, pending) } let ingestedID = pending.id DispatchQueue.main.async { @@ -1793,26 +1797,46 @@ struct RichMarkdownEditorView: NSViewRepresentable { id == inFlight.command.id, documentID == inFlight.documentID, documentGeneration == inFlight.documentGeneration, - queuedCommands.first?.id == id else { return } + queuedCommands.first?.command.id == id else { return } let source = queuedCommands.removeFirst() inFlightCommand = nil if let rejectionReason { Self.bridgeLogger.error( "editor command rejected: \(rejectionReason, privacy: .private)" ) - if command.wrappedValue?.id == source.id { + if command.wrappedValue?.id == source.command.id { command.wrappedValue = nil } - onCommandRejected(inFlight.documentID, source) + onCommandRejected(source.documentID, source.command) } else { - lastCommandID = source.id - if source.kind != .scrollToHeading { - onContentCommandApplied(inFlight.documentID, source) + lastCommandID = source.command.id + if source.command.kind.isContentCommand { + onContentCommandApplied( + source.documentID, + source.command + ) } } runPendingCommandIfReady() } + func rejectUnconfirmedContentCommands() { + ingestCommandBinding() + let abandoned = queuedCommands + queuedCommands.removeAll() + inFlightCommand = nil + if let bound = command.wrappedValue, + bound.id == lastCommandID || abandoned.contains(where: { + $0.command.id == bound.id + }) { + command.wrappedValue = nil + } + for source in abandoned + where source.command.kind.isContentCommand { + onCommandRejected(source.documentID, source.command) + } + } + private func rejectCommand(_ source: InFlightCommand, reason: String) { guard inFlightCommand?.command.id == source.command.id else { return } finishCommand( diff --git a/Sources/WeiBeiCore/WorkspaceModels.swift b/Sources/WeiBeiCore/WorkspaceModels.swift index cdd0de618..5c5435603 100644 --- a/Sources/WeiBeiCore/WorkspaceModels.swift +++ b/Sources/WeiBeiCore/WorkspaceModels.swift @@ -746,6 +746,10 @@ public struct NoteEditorCommand: Identifiable, Hashable { case insertMarkdown case scrollToHeading case reloadDocument + + public var isContentCommand: Bool { + self != .scrollToHeading && self != .reloadDocument + } } public var id: UUID diff --git a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift index 6767a8061..66755edd7 100644 --- a/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/ImportedIdentitySelfCheck.swift @@ -28,7 +28,7 @@ enum ImportedIdentitySelfCheck { let fixture = try WorkspaceFixture(name: "durable-editor-selection") defer { fixture.remove() } - let notes = ["A", "B", "C"].map { name in + let notes = ["A", "B"].map { name in StudyItem( id: "internal-note-\(name.lowercased())", title: "\(name) 笔记", @@ -42,13 +42,11 @@ enum ImportedIdentitySelfCheck { } let noteA = notes[0] let noteB = notes[1] - let noteC = notes[2] try fixture.write(PersistedWorkspace( importedItems: notes, notesByItemID: [ noteA.id: "# A笔记\n\n旧正文", noteB.id: "# B笔记\n\n正文", - noteC.id: "# C笔记\n\n正文", ], activeNotebookItemID: noteA.id, noteSourceLinksMigrationVersion: 1 @@ -66,62 +64,28 @@ enum ImportedIdentitySelfCheck { selectionAskThreadDefaults: fixture.selectionAskThreadDefaults ) - store.select(itemID: noteA.id) store.noteEditingSession.replaceDocument(with: noteA.id) var requests = [NoteEditorSnapshotRequest]() let bridgeToken = store.noteEditingSession.bindSnapshotRequestHandler { requests.append($0) } - let pendingCommand = NoteEditorCommand(kind: .insertMarkdown, markdown: "最后一段编辑") - store.noteEditorCommand = pendingCommand - - store.select(itemID: noteC.id) - store.select(itemID: noteB.id) - try check( - store.activeNoteItemID == noteA.id - && store.noteSelectionStatusMessage?.contains("正在保存") == true - && requests.isEmpty, - "内容命令回执前切换没有保持 A,或提前销毁了来源编辑器" - ) - store.noteEditorCommand = nil - store.noteEditorCommandRejected(pendingCommand, documentID: noteA.id) - try check( - store.activeNoteItemID == noteA.id - && store.canRetryRejectedNoteEditorCommand, - "内容命令被拒绝后没有留在来源笔记并允许重试" - ) - store.retryRejectedNoteEditorCommand() - try check(store.noteEditorCommand?.id == pendingCommand.id, "重试没有保留原命令编号和内容") - store.noteEditorCommand = nil - store.noteEditorContentCommandApplied(pendingCommand, documentID: noteA.id) - try check(requests.count == 1, "内容命令应用后没有进入现有真实快照保存链") - + try check(store.noteEditingSession.receive(NoteEditorDirtyChangedEvent( + documentID: noteA.id, + documentGeneration: store.noteEditingSession.documentGeneration, + revision: 1, + dirty: true + )), "A 的脏正文事件没有被编辑会话接收") rejectsWorkspaceWrite = true - let request = try require(requests.first, "内容命令应用后没有请求真实快照") + store.select(itemID: noteB.id) + let request = try require(requests.first, "脏正文切换没有请求真实快照") let latestA = "# A笔记\n\n最后一段编辑" - try check( - store.noteEditingSession.receive(NoteEditorSnapshotReadyEvent( - requestID: request.requestID ?? "", - documentID: request.documentID, - documentGeneration: request.documentGeneration, - revision: 1, - markdown: latestA - )), - "真实快照没有被编辑会话接收" - ) - let failureDeadline = Date().addingTimeInterval(5) - while !store.canRetryPendingNoteSelection, - Date() < failureDeadline { - RunLoop.main.run( - mode: .default, - before: Date(timeIntervalSinceNow: 0.01) - ) + try deliverSnapshot(request, markdown: latestA, to: store.noteEditingSession) + try waitForCondition("等待写入失败状态超时") { + store.canRetryPendingNoteSelection } let snapshotAfterFailure = try fixture.readSnapshot() try check( store.activeNoteItemID == noteA.id - && store.canRetryPendingNoteSelection - && store.noteSelectionStatusMessage?.contains("尚未安全保存") == true && snapshotAfterFailure.notesByItemID[noteA.id] != latestA, "工作区写入失败后离开了 A,或把内存快照误当成安全保存" ) @@ -130,29 +94,10 @@ enum ImportedIdentitySelfCheck { requests.removeAll() store.retryPendingNoteSelection() let retry = try require(requests.first, "重试没有重新请求真实快照") - try check(store.activeNoteItemID == noteA.id, "重试快照送达前离开了 A") - try check( - store.noteEditingSession.receive(NoteEditorSnapshotReadyEvent( - requestID: retry.requestID ?? "", - documentID: retry.documentID, - documentGeneration: retry.documentGeneration, - revision: 1, - markdown: latestA - )), - "重试快照没有被编辑会话接收" - ) - let successDeadline = Date().addingTimeInterval(5) - while store.activeNoteItemID != noteB.id, - Date() < successDeadline { - RunLoop.main.run( - mode: .default, - before: Date(timeIntervalSinceNow: 0.01) - ) + try deliverSnapshot(retry, markdown: latestA, to: store.noteEditingSession) + try waitForCondition("等待恢复写入超时") { + store.activeNoteItemID == noteB.id } - try check( - store.activeNoteItemID == noteB.id, - "工作区恢复写入后没有只切到最后点击的 B" - ) store.select(itemID: noteA.id) let snapshotAfterRetry = try fixture.readSnapshot() @@ -3427,6 +3372,36 @@ enum ImportedIdentitySelfCheck { return value } + @MainActor + private static func deliverSnapshot( + _ request: NoteEditorSnapshotRequest, + markdown: String, + to session: NoteEditingSession + ) throws { + try check(session.receive(NoteEditorSnapshotReadyEvent( + requestID: request.requestID ?? "", + documentID: request.documentID, + documentGeneration: request.documentGeneration, + revision: 1, + markdown: markdown + )), "真实快照没有被编辑会话接收") + } + + @MainActor + private static func waitForCondition( + _ timeoutMessage: String, + condition: () -> Bool + ) throws { + let deadline = Date().addingTimeInterval(5) + while !condition(), Date() < deadline { + RunLoop.main.run( + mode: .default, + before: Date(timeIntervalSinceNow: 0.01) + ) + } + try check(condition(), timeoutMessage) + } + private static func check(_ condition: @autoclosure () -> Bool, _ message: String) throws { guard condition() else { throw CheckError.failed(message) } } diff --git a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift index 0e9666270..377902e3a 100644 --- a/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift +++ b/Tests/WeiBeiSafetyTests/RichMarkdownEditorBridgeTests.swift @@ -23,31 +23,43 @@ final class RichMarkdownEditorBridgeTests: XCTestCase { } @MainActor - func testRejectedContentKeepsDispatchDocumentAndRetries() async throws { - var rejectedCommand: NoteEditorCommand? - var rejectedDocumentID: String? - let rejected = expectation(description: "rejected content remained recoverable") - let retried = expectation(description: "rejected content applied after retry") + func testDestroyedCoordinatorReturnsContentToExistingRetryQueue() async { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("WeiBeiEditorCommand-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: root) } + let store = WorkspaceStore( + workspaceDirectory: root, + startsAtBlankEntries: true + ) + store.importedItems = [StudyItem( + id: "note-a", + title: "A", + subtitle: "A", + kind: .text, + urlPath: nil, + isSample: false, + isNotebookNote: true + )] + store.activeNotebookItemID = "note-a" + store.noteEditingSession.replaceDocument(with: "note-a") + let rejected = expectation(description: "unconfirmed content returned") let fixture = await makeCommandBridge(onRejected: { documentID, command in - rejectedDocumentID = documentID - rejectedCommand = command + store.noteEditorCommandRejected(command, documentID: documentID) rejected.fulfill() - }, onProbe: { name in - if name == "retried" { retried.fulfill() } - }) + }, onProbe: { _ in }) - fixture.enqueue(NoteEditorCommand(kind: .replaceSelection, markdown: "保留我")) + let command = NoteEditorCommand( + kind: .replaceSelection, + markdown: "销毁后保留" + ) + fixture.enqueue(command) fixture.start() + fixture.destroy() await fulfillment(of: [rejected], timeout: 3) - let recoverable = try XCTUnwrap(rejectedCommand) - XCTAssertEqual(rejectedDocumentID, "note-a") - XCTAssertEqual(recoverable.markdown, "保留我") - - try await fixture.allowRejectedContent() - fixture.enqueue(recoverable) - await fulfillment(of: [retried], timeout: 3) - let afterRetry = try await fixture.appliedMarkdown() - XCTAssertEqual(afterRetry.filter { $0 == "保留我" }.count, 1) + XCTAssertTrue(store.canRetryRejectedNoteEditorCommand) + store.retryRejectedNoteEditorCommand() + XCTAssertEqual(store.noteEditorCommand?.id, command.id) + XCTAssertEqual(store.noteEditorCommand?.markdown, command.markdown) } @MainActor @@ -292,9 +304,10 @@ private final class EditorCommandBridgeFixture { coordinator.runPendingCommandIfReady() } - func allowRejectedContent() async throws { - _ = try await webView.evaluateJavaScript( - "window.WeiBeiEditor.allowRejectedContent()" + func destroy() { + RichMarkdownEditorView.dismantleNSView( + webView, + coordinator: coordinator ) } @@ -311,7 +324,6 @@ private final class EditorCommandBridgeFixture { <script> const appliedIDs = new Set(); const appliedMarkdown = []; - let rejectedMarkdown = "保留我"; const replyApplied = command => { window.webkit.messageHandlers.commandApplied.postMessage({ protocolVersion: 2, @@ -324,7 +336,7 @@ private final class EditorCommandBridgeFixture { window.WeiBeiEditor = { dispatchCommand(command) { const markdown = command.payload.markdown; - if (markdown === rejectedMarkdown) return false; + if (markdown === "销毁后保留") return true; if (!appliedIDs.has(command.commandID)) { appliedIDs.add(command.commandID); appliedMarkdown.push(markdown); @@ -332,12 +344,9 @@ private final class EditorCommandBridgeFixture { replyApplied(command); if (appliedMarkdown.length === 18) { window.webkit.messageHandlers.queueProbe.postMessage("allApplied"); - } else if (markdown === "保留我") { - window.webkit.messageHandlers.queueProbe.postMessage("retried"); } return true; }, - allowRejectedContent() { rejectedMarkdown = null; return true; }, appliedMarkdown() { return appliedMarkdown; } }; </script>