Agent Zero AI framework
Polish native Markdown editor experience
Alessandro89901b64f090
diff --git a/plugins/_editor/api/editor_session.py b/plugins/_editor/api/editor_session.pyindex 75419f9ab..2a4ceb7fd 100644--- a/plugins/_editor/api/editor_session.py+++ b/plugins/_editor/api/editor_session.py@@ -97,7 +97,12 @@ class EditorSession(ApiHandler):origin=self._origin(request),)try:- editor = markdown_sessions.get_manager().open(doc, sid="", context_id=context_id)+ editor = markdown_sessions.get_manager().open(+ doc,+ sid="",+ context_id=context_id,+ refresh=input.get("refresh") is True,+ )except ValueError as exc:document_store.close_session(session_id=store_session["session_id"])return {"ok": False, "error": str(exc)}diff --git a/plugins/_editor/api/ws_editor.py b/plugins/_editor/api/ws_editor.pyindex 716812932..7c8e6e446 100644--- a/plugins/_editor/api/ws_editor.py+++ b/plugins/_editor/api/ws_editor.py@@ -60,4 +60,9 @@ class WsEditor(WsHandler):content=str(data.get("content") or ""),context_id=context_id,)- return markdown_sessions.get_manager().open(doc, sid=sid, context_id=context_id)+ return markdown_sessions.get_manager().open(+ doc,+ sid=sid,+ context_id=context_id,+ refresh=data.get("refresh") is True,+ )diff --git a/plugins/_editor/helpers/markdown_sessions.py b/plugins/_editor/helpers/markdown_sessions.pyindex af5862df6..15b352f45 100644--- a/plugins/_editor/helpers/markdown_sessions.py+++ b/plugins/_editor/helpers/markdown_sessions.py@@ -33,19 +33,29 @@ class MarkdownSessionManager:self._sessions: dict[str, MarkdownSession] = {}self._active_by_context: dict[str, str] = {}- def open(self, doc: dict[str, Any], sid: str = "", context_id: str = "") -> dict[str, Any]:+ def open(self, doc: dict[str, Any], sid: str = "", context_id: str = "", refresh: bool = False) -> dict[str, Any]:ext = str(doc["extension"]).lower()if ext != "md":raise ValueError(f"Editor is only available for Markdown. Open .{ext} files in the Desktop.")normalized_context = str(context_id or "")+ if refresh:+ try:+ doc = document_store.register_document(doc["path"], context_id=normalized_context)+ except Exception:+ pass+for session in self._sessions.values():if session.file_id != doc["file_id"] or session.context_id != normalized_context:continueif sid:session.sid = sid+ if refresh and not session.dirty:+ session.text = document_store.read_text_for_editor(doc)+ session.dirty = Falsesession.path = doc["path"]session.title = doc["basename"]+ session.updated_at = time.time()self.activate(session.session_id)return self._payload(session, doc)diff --git a/plugins/_editor/webui/editor-panel.html b/plugins/_editor/webui/editor-panel.htmlindex 33c375cc8..45aea8aa7 100644--- a/plugins/_editor/webui/editor-panel.html+++ b/plugins/_editor/webui/editor-panel.html@@ -8,7 +8,7 @@<div x-data><template x-if="$store.editor"><div class="editor-panel" x-create="$store.editor.onMount($el, xAttrs($el) || {})" x-destroy="$store.editor.cleanup()">- <div class="editor-shell">+ <div class="editor-shell" @keydown="$store.editor.handleEditorKeydown($event)"><div class="editor-tabs" x-show="$store.editor.visibleTabs().length > 0" style="display: none;" role="tablist" aria-label="Open Markdown files"><template x-for="tab in $store.editor.visibleTabs()" :key="tab.tab_id"><div@@ -31,12 +31,23 @@class="editor-tab-close"title="Close file"aria-label="Close file"+ @pointerdown.stop@click.stop="$store.editor.closeTab(tab.tab_id)"><span class="material-symbols-outlined" aria-hidden="true">close</span></button></div></template>+ <button+ type="button"+ class="editor-new-tab"+ title="New Markdown"+ aria-label="New Markdown"+ :disabled="$store.editor.loading || $store.editor.saving"+ @click="$store.editor.runNewMenuAction('markdown')"+ >+ <span class="material-symbols-outlined" aria-hidden="true">add</span>+ </button></div><div class="editor-close-confirm" x-show="$store.editor.hasPendingClose()" style="display: none;" role="status">@@ -66,58 +77,9 @@</div></div>- <div class="editor-document-header" x-show="$store.editor.hasActiveFile()" style="display: none;">- <div class="editor-document-title" :title="$store.editor.tabLabel($store.editor.session)">- <span class="material-symbols-outlined editor-document-icon" aria-hidden="true" x-text="$store.editor.tabIcon($store.editor.session)"></span>- <span class="editor-document-name" x-text="$store.editor.tabTitle($store.editor.session)"></span>- <span class="editor-document-dirty" x-show="$store.editor.dirty" aria-hidden="true">*</span>- </div>-- <button- type="button"- class="editor-icon-button editor-document-save-button"- title="Save"- aria-label="Save"- :class="{ 'is-primary': $store.editor.dirty }"- :disabled="$store.editor.saving"- @click="$store.editor.save()"- >- <span class="material-symbols-outlined" :class="{ spinning: $store.editor.saving }" x-text="$store.editor.saving ? 'progress_activity' : 'save'"></span>- </button>-- <div class="editor-file-actions" x-data="{ open: false }" @click.outside="open = false" @keydown.escape.window="open = false">- <button- type="button"- class="editor-icon-button editor-file-menu-button"- title="File actions"- aria-label="File actions"- aria-haspopup="menu"- :aria-expanded="open.toString()"- :disabled="$store.editor.saving"- @click.stop="open = !open"- >- <span class="material-symbols-outlined">more_vert</span>- </button>- <div class="editor-new-menu editor-file-menu" role="menu" x-show="open" @click.stop>- <button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.saving" @click="open = false; $store.editor.renameActiveFile()">- <span class="material-symbols-outlined" aria-hidden="true">edit</span>- <span>Rename</span>- </button>- <button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.loading" @click="open = false; $store.editor.closeActiveFile()">- <span class="material-symbols-outlined" aria-hidden="true">close</span>- <span>Close File</span>- </button>- <button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.loading || $store.editor.visibleTabs().length === 0" @click="open = false; $store.editor.closeAllFiles()">- <span class="material-symbols-outlined" aria-hidden="true">close</span>- <span>Close All</span>- </button>- </div>- </div>- </div>-- <div class="editor-toolbar" x-show="$store.editor.session && $store.editor.isMarkdown()" style="display: none;">+ <div class="editor-toolbar" x-show="$store.editor.session" style="display: none;"><div class="editor-toolbar-row">- <div class="editor-tool-group editor-source-tools">+ <div class="editor-tool-group editor-source-tools" x-show="$store.editor.isMarkdown() && $store.editor.isSourceMode()" style="display: none;"><button type="button" class="editor-icon-button" title="Undo" aria-label="Undo" :disabled="!$store.editor.canUndo()" @click="$store.editor.undo()"><span class="material-symbols-outlined">undo</span></button>@@ -140,28 +102,145 @@<span class="material-symbols-outlined">table</span></button></div>+ <div class="editor-tool-group editor-preview-tools" x-show="$store.editor.isPreviewMode()" style="display: none;">+ <button type="button" class="editor-icon-button" title="Previous page" aria-label="Previous page" :disabled="$store.editor.previewEditing || $store.editor.activePageIndex <= 0" @click="$store.editor.previousPage()">+ <span class="material-symbols-outlined">chevron_left</span>+ </button>+ <span class="editor-page-count" x-text="$store.editor.pagePositionLabel()"></span>+ <button type="button" class="editor-icon-button" title="Next page" aria-label="Next page" :disabled="$store.editor.previewEditing || $store.editor.activePageIndex >= $store.editor.pages().length - 1" @click="$store.editor.nextPage()">+ <span class="material-symbols-outlined">chevron_right</span>+ </button>+ <button type="button" class="editor-icon-button" title="Edit page" aria-label="Edit page" x-show="!$store.editor.previewEditing" @click="$store.editor.startPreviewEdit()">+ <span class="material-symbols-outlined">edit_note</span>+ </button>+ <button type="button" class="editor-icon-button is-primary" title="Apply page edit" aria-label="Apply page edit" x-show="$store.editor.previewEditing" @click="$store.editor.applyPreviewEdit()">+ <span class="material-symbols-outlined">check</span>+ </button>+ <button type="button" class="editor-icon-button" title="Cancel page edit" aria-label="Cancel page edit" x-show="$store.editor.previewEditing" @click="$store.editor.cancelPreviewEdit()">+ <span class="material-symbols-outlined">close</span>+ </button>+ <button type="button" class="editor-icon-button" title="Search" aria-label="Search" :disabled="$store.editor.previewEditing" @click="$store.editor.openSearch()">+ <span class="material-symbols-outlined">search</span>+ </button>+ </div><span class="editor-toolbar-spacer"></span>++ <button+ type="button"+ class="editor-icon-button editor-mode-toggle"+ :title="$store.editor.viewModeTitle()"+ :aria-label="$store.editor.viewModeTitle()"+ @click="$store.editor.toggleViewMode()"+ >+ <span class="material-symbols-outlined" aria-hidden="true" x-text="$store.editor.viewModeIcon()"></span>+ </button>++ <div class="editor-file-actions" x-data="{ open: false }" @click.outside="open = false" @keydown.escape.window="open = false">+ <button+ type="button"+ class="editor-icon-button editor-file-menu-button"+ title="File actions"+ aria-label="File actions"+ aria-haspopup="menu"+ :aria-expanded="open.toString()"+ :disabled="$store.editor.saving"+ @click.stop="open = !open"+ >+ <span class="material-symbols-outlined">more_vert</span>+ </button>+ <div class="editor-new-menu editor-file-menu" role="menu" x-show="open" @click.stop>+ <button type="button" class="editor-new-menu-item" :class="{ 'is-emphasized': $store.editor.dirty }" role="menuitem" :disabled="$store.editor.saving" @click="open = false; $store.editor.save()">+ <span class="material-symbols-outlined" :class="{ spinning: $store.editor.saving }" x-text="$store.editor.saving ? 'progress_activity' : 'save'"></span>+ <span>Save</span>+ </button>+ <button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.saving" @click="open = false; $store.editor.renameActiveFile()">+ <span class="material-symbols-outlined" aria-hidden="true">edit</span>+ <span>Rename</span>+ </button>+ <button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.loading" @click="open = false; $store.editor.closeActiveFile()">+ <span class="material-symbols-outlined" aria-hidden="true">close</span>+ <span>Close File</span>+ </button>+ <button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.loading || $store.editor.visibleTabs().length === 0" @click="open = false; $store.editor.closeAllFiles()">+ <span class="material-symbols-outlined" aria-hidden="true">close</span>+ <span>Close All</span>+ </button>+ </div>+ </div></div></div>+ <div class="editor-search-bar" x-show="$store.editor.searchOpen" style="display: none;">+ <span class="material-symbols-outlined" aria-hidden="true">search</span>+ <input+ type="search"+ data-editor-search+ aria-label="Search preview"+ x-model="$store.editor.searchQuery"+ @input="$store.editor.runSearch()"+ @keydown.enter.prevent="$event.shiftKey ? $store.editor.previousSearchMatch() : $store.editor.nextSearchMatch()"+ @keydown.escape.prevent="$store.editor.closeSearch()"+ />+ <span class="editor-search-count" x-text="$store.editor.searchCountLabel()"></span>+ <button type="button" class="editor-icon-button" title="Previous match" aria-label="Previous match" :disabled="$store.editor.searchMatches.length === 0" @click="$store.editor.previousSearchMatch()">+ <span class="material-symbols-outlined">keyboard_arrow_up</span>+ </button>+ <button type="button" class="editor-icon-button" title="Next match" aria-label="Next match" :disabled="$store.editor.searchMatches.length === 0" @click="$store.editor.nextSearchMatch()">+ <span class="material-symbols-outlined">keyboard_arrow_down</span>+ </button>+ <button type="button" class="editor-icon-button" title="Close search" aria-label="Close search" @click="$store.editor.closeSearch()">+ <span class="material-symbols-outlined">close</span>+ </button>+ </div>+<div class="editor-state-line" x-show="$store.editor.message || $store.editor.error || $store.editor.loading" style="display: none;"><span class="material-symbols-outlined" :class="{ spinning: $store.editor.loading }" x-text="$store.editor.loading ? 'progress_activity' : ($store.editor.error ? 'error' : 'check_circle')"></span><span x-text="$store.editor.error || $store.editor.message || 'Working'"></span></div><div class="editor-body">- <div class="editor-wrap" x-show="$store.editor.session" style="display: none;">+ <div class="editor-wrap" x-show="$store.editor.session && $store.editor.isSourceMode()" style="display: none;"><div class="editor-scroll" @click.self="$store.editor.focusEditor()">+ <div class="editor-ace" data-editor-ace x-show="!$store.editor.aceUnavailable"></div><textareaclass="editor-source-editor"data-editor-sourcearia-label="Markdown source"+ x-show="$store.editor.aceUnavailable"x-model="$store.editor.editorText"@input="$store.editor.onSourceInput()"@blur="$store.editor.flushInput()"spellcheck="true"+ style="display: none;"+ ></textarea>+ </div>+ </div>++ <div class="editor-preview-shell" x-show="$store.editor.session && $store.editor.isPreviewMode()" style="display: none;">+ <div class="editor-preview-title">+ <h1 x-text="$store.editor.pageTitle()"></h1>+ </div>+ <div class="editor-preview-edit-shell" x-show="$store.editor.previewEditing" style="display: none;">+ <textarea+ class="editor-preview-page-editor"+ data-editor-preview-source+ aria-label="Markdown page source"+ x-model="$store.editor.previewEditText"+ @input="$store.editor.onPreviewEditInput()"+ @keydown.meta.enter.prevent="$store.editor.applyPreviewEdit()"+ @keydown.ctrl.enter.prevent="$store.editor.applyPreviewEdit()"+ @keydown.escape.prevent="$store.editor.cancelPreviewEdit()"+ spellcheck="true"></textarea></div>+ <div+ class="editor-preview-content msg-content"+ data-editor-preview+ x-show="!$store.editor.previewEditing"+ x-html="$store.editor.previewHtml()"+ x-effect="$store.editor.activePageIndex; $store.editor.editorText; $store.editor.searchQuery; $store.editor.searchIndex; $store.editor.schedulePreviewEnhance()"+ @click="$store.editor.handlePreviewClick($event)"+ ></div></div><div class="editor-empty" x-show="!$store.editor.session && !$store.editor.loading" style="display: none;">@@ -185,6 +264,12 @@<style>.editor-panel,.editor-shell {+ --editor-chrome-surface: color-mix(in srgb, var(--color-background) 92%, #000 8%);+ --editor-chrome-border: color-mix(in srgb, var(--color-border) 58%, transparent);+ --editor-tab-hover-border: color-mix(in srgb, var(--color-border) 78%, transparent);+ --editor-tab-height: 36px;+ --editor-tab-close-size: 32px;+ --editor-control-radius: 0.55rem;display: flex;flex: 1 1 auto;flex-direction: column;@@ -242,25 +327,71 @@.editor-tabs {display: flex;- gap: 6px;- min-height: 42px;- padding: 7px 10px;+ align-items: end;+ gap: 4px;+ min-height: 44px;+ padding: 7px 10px 0;overflow-x: auto;overflow-y: hidden;- border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 22%);- background: color-mix(in srgb, var(--color-panel), var(--color-background) 28%);+ border-bottom: 1px solid var(--editor-chrome-border);+ background: var(--editor-chrome-surface);+ scrollbar-width: thin;+ }++ .editor-tabs::-webkit-scrollbar {+ height: 4px;+ }++ .editor-tabs::-webkit-scrollbar-track {+ background: transparent;+ }++ .editor-tabs::-webkit-scrollbar-thumb {+ background: color-mix(in srgb, var(--color-border) 78%, transparent);+ border-radius: 999px;}.editor-tab-shell {+ flex: 0 1 210px;+ position: relative;display: grid;- grid-template-columns: minmax(0, 1fr) 28px;+ grid-template-columns: minmax(0, 1fr) var(--editor-tab-close-size);align-items: center;- min-width: 150px;- max-width: 240px;+ gap: 3px;+ min-width: 128px;+ max-width: 250px;+ height: var(--editor-tab-height);+ padding: 0 7px 0 10px;+ border: 1px solid transparent;+ border-radius: var(--editor-control-radius) var(--editor-control-radius) 0 0;+ background: transparent;+ opacity: 0.72;+ transition: border-color 0.18s cubic-bezier(0.4, 0, 0.2, 1),+ color 0.18s cubic-bezier(0.4, 0, 0.2, 1),+ opacity 0.18s cubic-bezier(0.4, 0, 0.2, 1);+ }++ .editor-new-tab {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex: 0 0 34px;+ width: 34px;+ min-width: 34px;+ height: 34px;+ min-height: 34px;+ padding: 0;+ border: 1px solid transparent;+ border-radius: var(--editor-control-radius);+ background: transparent;+ color: color-mix(in srgb, var(--color-text) 62%, var(--color-primary) 38%);+ cursor: pointer;+ transition: background-color 0.18s cubic-bezier(0.4, 0, 0.2, 1),+ border-color 0.18s cubic-bezier(0.4, 0, 0.2, 1),+ color 0.18s cubic-bezier(0.4, 0, 0.2, 1),+ opacity 0.18s cubic-bezier(0.4, 0, 0.2, 1);}- .editor-tab,- .editor-tab-close,.editor-icon-button {border: 1px solid color-mix(in srgb, var(--color-border), transparent 12%);border-radius: 8px;@@ -273,36 +404,64 @@.editor-tab {display: flex;align-items: center;- gap: 6px;+ gap: 8px;min-width: 0;- height: 28px;- padding: 0 8px;- border-top-right-radius: 0;- border-bottom-right-radius: 0;+ width: 100%;+ height: 100%;+ padding: 0;+ border: 0;+ border-radius: 0;+ background: transparent;+ color: inherit;+ cursor: pointer;+ font: inherit;text-align: left;}.editor-tab-close {- display: grid;- place-items: center;- height: 28px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: var(--editor-tab-close-size);+ min-width: var(--editor-tab-close-size);+ height: var(--editor-tab-close-size);+ min-height: var(--editor-tab-close-size);padding: 0;- border-left: 0;- border-top-left-radius: 0;- border-bottom-left-radius: 0;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: color-mix(in srgb, var(--color-text) 52%, var(--color-primary) 48%);+ cursor: pointer;+ opacity: 0.72;+ transition: background-color 0.18s cubic-bezier(0.4, 0, 0.2, 1),+ color 0.18s cubic-bezier(0.4, 0, 0.2, 1),+ opacity 0.18s cubic-bezier(0.4, 0, 0.2, 1);+ }++ .editor-tab-shell:hover,+ .editor-tab-shell:focus-within {+ border-color: var(--editor-tab-hover-border);+ opacity: 0.94;+ }++ .editor-tab-shell.is-active {+ z-index: 2;+ margin-bottom: -1px;+ border-color: var(--editor-chrome-border);+ background: transparent;+ opacity: 1;+ box-shadow: none;}- .editor-tab-shell.is-active .editor-tab,- .editor-tab-shell.is-active .editor-tab-close,.editor-icon-button.is-primary {border-color: color-mix(in srgb, #2c7be5, var(--color-border) 36%);background: color-mix(in srgb, #2c7be5, var(--color-panel) 88%);}- .editor-tab-shell.is-pending-close .editor-tab,- .editor-tab-shell.is-pending-close .editor-tab-close {+ .editor-tab-shell.is-pending-close {border-color: color-mix(in srgb, #d98b2b, var(--color-border) 30%);background: color-mix(in srgb, #d98b2b, var(--color-panel) 88%);+ opacity: 1;}.editor-tab-shell.is-dirty .editor-tab-title::after {@@ -310,8 +469,7 @@color: #2ca58d;}- .editor-tab-title,- .editor-document-name {+ .editor-tab-title {min-width: 0;overflow: hidden;text-overflow: ellipsis;@@ -319,15 +477,15 @@}.editor-tab-title {- font-size: 12px;- font-weight: 700;+ font-size: 0.88rem;+ font-weight: 600;letter-spacing: 0;}- .editor-document-header,.editor-toolbar,.editor-state-line,- .editor-close-confirm {+ .editor-close-confirm,+ .editor-search-bar {display: flex;align-items: center;gap: 8px;@@ -336,11 +494,6 @@min-width: 0;}- .editor-document-header {- min-height: 38px;- background: color-mix(in srgb, var(--color-panel), var(--color-background) 30%);- }-.editor-close-confirm {min-height: 44px;background: color-mix(in srgb, #d98b2b 9%, var(--color-background));@@ -385,25 +538,12 @@gap: 6px;}- .editor-document-title {- display: flex;- align-items: center;- gap: 7px;- min-width: 0;- flex: 1 1 auto;- font-size: 13px;- font-weight: 750;- letter-spacing: 0;- }-- .editor-document-dirty {- color: #2ca58d;- font-weight: 800;- }-.editor-toolbar {+ min-height: 46px;padding: 6px 10px;- overflow: hidden;+ position: relative;+ z-index: 20;+ overflow: visible;background: color-mix(in srgb, var(--color-background), var(--color-panel) 48%);}@@ -417,8 +557,7 @@.editor-toolbar-row {width: 100%;- overflow-x: auto;- overflow-y: hidden;+ overflow: visible;}.editor-toolbar-spacer {@@ -426,6 +565,35 @@min-width: 8px;}+ .editor-page-count,+ .editor-search-count {+ min-width: 54px;+ color: var(--color-text-secondary);+ font-size: 12px;+ font-weight: 700;+ letter-spacing: 0;+ text-align: center;+ white-space: nowrap;+ }++ .editor-search-bar {+ min-height: 40px;+ background: color-mix(in srgb, var(--color-background), var(--color-panel) 30%);+ }++ .editor-search-bar input {+ flex: 1 1 auto;+ min-width: 90px;+ height: 30px;+ border: 1px solid color-mix(in srgb, var(--color-border), transparent 12%);+ border-radius: 7px;+ background: var(--color-background);+ color: var(--color-text);+ padding: 0 9px;+ font: inherit;+ font-size: 13px;+ }+.editor-icon-button {display: inline-grid;place-items: center;@@ -435,13 +603,55 @@padding: 0;}- .editor-icon-button:hover:not(:disabled),- .editor-tab:hover,- .editor-tab-close:hover {+ .editor-icon-button:hover:not(:disabled) {border-color: color-mix(in srgb, #2c7be5, var(--color-border) 45%);background: color-mix(in srgb, var(--color-panel), #2c7be5 8%);}+ .editor-tab:hover {+ background: transparent;+ }++ .editor-tab:focus-visible,+ .editor-tab-close:focus-visible {+ outline: 1px solid color-mix(in srgb, var(--color-primary) 70%, transparent);+ outline-offset: 1px;+ }++ .editor-tab-icon {+ flex: 0 0 auto;+ color: color-mix(in srgb, var(--color-text) 72%, var(--color-primary) 28%);+ font-size: 1.04rem;+ line-height: 1;+ }++ .editor-tab-close:hover {+ background: color-mix(in srgb, var(--color-background-hover) 70%, transparent);+ color: var(--color-text);+ opacity: 1;+ }++ .editor-new-tab:hover:not(:disabled) {+ background: color-mix(in srgb, var(--color-background-hover) 58%, transparent);+ border-color: color-mix(in srgb, var(--color-primary) 24%, transparent);+ color: var(--color-text);+ }++ .editor-new-tab:disabled {+ cursor: default;+ opacity: 0.42;+ }++ .editor-tab-close .material-symbols-outlined {+ font-size: 1rem;+ line-height: 1;+ }++ .editor-new-tab .material-symbols-outlined {+ font-size: 1.12rem;+ line-height: 1;+ }+.editor-icon-button:disabled {cursor: default;opacity: 0.42;@@ -453,13 +663,14 @@display: inline-flex;align-items: center;flex: 0 0 auto;+ z-index: 30;}.editor-new-menu {position: absolute;top: calc(100% + 6px);right: 0;- z-index: 4000;+ z-index: 10000;min-width: 184px;padding: 5px;border: 1px solid color-mix(in srgb, var(--color-border), transparent 10%);@@ -506,6 +717,11 @@text-align: left;}+ .editor-new-menu-item.is-emphasized {+ color: var(--color-text);+ background: color-mix(in srgb, #2c7be5 10%, transparent);+ }+.editor-text-button {appearance: none;height: 28px;@@ -554,7 +770,8 @@.editor-body,.editor-wrap,- .editor-scroll {+ .editor-scroll,+ .editor-preview-shell {display: flex;flex: 1 1 auto;min-width: 0;@@ -573,6 +790,27 @@height: 100%;}+ .editor-scroll {+ position: relative;+ }++ .editor-ace {+ flex: 1 1 auto;+ width: 100%;+ height: 100%;+ min-width: 0;+ min-height: 0;+ font: 13px/1.55 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;+ }++ .editor-ace .ace_gutter {+ display: none !important;+ }++ .editor-ace .ace_scroller {+ left: 0 !important;+ }+.editor-source-editor {box-sizing: border-box;width: 100%;@@ -589,6 +827,191 @@letter-spacing: 0;}+ .editor-preview-shell {+ flex-direction: column;+ overflow: hidden;+ background: var(--color-background);+ }++ .editor-preview-title {+ flex: 0 0 auto;+ padding: 20px 24px 10px;+ border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 30%);+ }++ .editor-preview-title h1 {+ margin: 0;+ color: var(--color-text);+ font-size: 24px;+ line-height: 1.2;+ letter-spacing: 0;+ }++ .editor-preview-content {+ flex: 1 1 auto;+ min-width: 0;+ min-height: 0;+ overflow: auto;+ padding: 20px 24px 36px;+ color: var(--color-text);+ line-height: 1.58;+ }++ .editor-preview-edit-shell {+ display: flex;+ flex: 1 1 auto;+ min-width: 0;+ min-height: 0;+ padding: 16px 24px 36px;+ background: var(--color-background);+ }++ .editor-preview-page-editor {+ box-sizing: border-box;+ flex: 1 1 auto;+ width: 100%;+ min-width: 0;+ min-height: 0;+ resize: none;+ border: 1px solid color-mix(in srgb, var(--color-border), transparent 12%);+ border-radius: 8px;+ outline: none;+ padding: 14px 16px;+ background: color-mix(in srgb, var(--color-panel), var(--color-background) 28%);+ color: var(--color-text);+ font: 13px/1.55 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;+ letter-spacing: 0;+ }++ .editor-preview-page-editor:focus {+ border-color: color-mix(in srgb, #2c7be5, var(--color-border) 40%);+ box-shadow: 0 0 0 1px color-mix(in srgb, #2c7be5 24%, transparent);+ }++ .editor-preview-content img {+ display: block;+ max-width: 100%;+ height: auto;+ margin: 12px 0;+ }++ .editor-preview-content h1,+ .editor-preview-content h2,+ .editor-preview-content h3,+ .editor-preview-content h4,+ .editor-preview-content h5,+ .editor-preview-content h6 {+ scroll-margin-top: 16px;+ letter-spacing: 0;+ }++ .editor-preview-content blockquote {+ margin: 12px 0;+ padding: 1px 0 1px 14px;+ border-left: 3px solid color-mix(in srgb, var(--color-primary), var(--color-border) 45%);+ color: var(--color-text-secondary);+ }++ .editor-table-wrap {+ max-width: 100%;+ overflow-x: auto;+ margin: 14px 0;+ border: 1px solid color-mix(in srgb, var(--color-border), transparent 12%);+ border-radius: 8px;+ }++ .editor-preview-content table {+ width: 100%;+ border-collapse: collapse;+ min-width: 420px;+ }++ .editor-preview-content th,+ .editor-preview-content td {+ border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 22%);+ padding: 8px 10px;+ text-align: inherit;+ vertical-align: top;+ }++ .editor-preview-content th {+ background: color-mix(in srgb, var(--color-panel), var(--color-background) 24%);+ font-weight: 800;+ }++ .editor-preview-content input[type="checkbox"] {+ margin-right: 6px;+ cursor: pointer;+ }++ .editor-code-block {+ overflow: hidden;+ margin: 14px 0;+ border: 1px solid color-mix(in srgb, var(--color-border), transparent 12%);+ border-radius: 8px;+ background: color-mix(in srgb, var(--color-panel), var(--color-background) 16%);+ }++ .editor-code-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ min-height: 32px;+ padding: 0 8px 0 10px;+ border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 22%);+ color: var(--color-text-secondary);+ font-size: 12px;+ font-weight: 700;+ }++ .editor-code-copy {+ height: 24px;+ border: 1px solid color-mix(in srgb, var(--color-border), transparent 12%);+ border-radius: 6px;+ background: var(--color-background);+ color: var(--color-text);+ cursor: pointer;+ font: inherit;+ font-size: 11px;+ font-weight: 750;+ }++ .editor-code-block pre {+ margin: 0;+ overflow: auto;+ padding: 12px;+ }++ .editor-code-block code {+ font: 12px/1.55 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;+ }++ .editor-math-display {+ margin: 14px 0;+ overflow-x: auto;+ text-align: center;+ }++ .editor-footnotes {+ margin-top: 24px;+ border-top: 1px solid color-mix(in srgb, var(--color-border), transparent 22%);+ color: var(--color-text-secondary);+ font-size: 13px;+ }++ mark.editor-search-mark {+ border-radius: 3px;+ background: color-mix(in srgb, #d9b12b 55%, transparent);+ color: inherit;+ padding: 0 1px;+ }++ mark.editor-search-mark.is-current {+ background: color-mix(in srgb, #2c7be5 55%, transparent);+ outline: 1px solid color-mix(in srgb, #2c7be5, var(--color-border) 24%);+ }+.editor-empty {display: grid;flex: 1 1 auto;diff --git a/plugins/_editor/webui/editor-preview.js b/plugins/_editor/webui/editor-preview.jsnew file mode 100644index 000000000..419bfdcbb--- /dev/null+++ b/plugins/_editor/webui/editor-preview.js@@ -0,0 +1,214 @@+import { renderSafeMarkdown } from "/js/safe-markdown.js";++const PAGE_HEADING_RE = /^(#{1,2})\s+(.+?)\s*#*\s*$/;+const FOOTNOTE_DEF_RE = /^\[\^([^\]]+)\]:\s*(.*)$/;++export function renderEditorPreviewMarkdown(markdown = "", fullMarkdown = markdown) {+ return renderSafeMarkdown(prepareFootnotes(markdown, fullMarkdown), {+ allowDataImages: true,+ allowLatex: true,+ openExternalLinksInNewTab: true,+ });+}++export function buildMarkdownPages(markdown = "", fallbackTitle = "Markdown") {+ const source = String(markdown || "");+ const lines = source.split("\n");+ const pages = [];+ let current = null;+ let intro = [];+ let introStart = 0;+ let fenced = false;+ let offset = 0;++ const startPage = (title, level, line, start) => {+ if (current) {+ current.end = start;+ pages.push(finalizePage(current, pages.length, source));+ }+ current = {+ title: cleanHeadingText(title) || fallbackTitle,+ level,+ lines: [line],+ start,+ end: source.length,+ };+ };++ for (const [index, line] of lines.entries()) {+ const lineStart = offset;+ const lineEnd = lineStart + line.length + (index < lines.length - 1 ? 1 : 0);+ if (/^\s*```/.test(line)) fenced = !fenced;+ const match = !fenced ? line.match(PAGE_HEADING_RE) : null;+ if (match) {+ if (!current && intro.join("\n").trim()) {+ pages.push(finalizePage({+ title: fallbackTitle,+ level: 0,+ lines: intro,+ start: introStart,+ end: lineStart,+ }, pages.length, source));+ intro = [];+ }+ startPage(match[2], match[1].length, line, lineStart);+ offset = lineEnd;+ continue;+ }+ if (current) current.lines.push(line);+ else intro.push(line);+ offset = lineEnd;+ }++ if (current) {+ current.end = source.length;+ pages.push(finalizePage(current, pages.length, source));+ }+ else if (intro.join("\n").trim() || !pages.length) {+ pages.push(finalizePage({+ title: fallbackTitle,+ level: 0,+ lines: intro,+ start: introStart,+ end: source.length,+ }, pages.length, source));+ }++ return pages;+}++export function slugifyHeading(text = "", used = new Map()) {+ const base = String(text || "")+ .toLowerCase()+ .replace(/<[^>]+>/g, "")+ .replace(/[`*_~[\]()]/g, "")+ .replace(/&[a-z0-9#]+;/gi, "")+ .replace(/[^a-z0-9\s-]/g, "")+ .trim()+ .replace(/\s+/g, "-")+ .replace(/-+/g, "-") || "section";+ const count = used.get(base) || 0;+ used.set(base, count + 1);+ return count ? `${base}-${count + 1}` : base;+}++export function resolveDocumentRelativePath(documentPath = "", target = "") {+ const value = String(target || "").trim();+ if (!value) return "";+ if (value.startsWith("/")) return normalizePath(value);+ const base = parentPath(documentPath);+ return normalizePath(`${base}/${value}`);+}++export function splitHref(href = "") {+ const value = String(href || "").trim();+ const hashIndex = value.indexOf("#");+ if (hashIndex < 0) return { path: value, fragment: "" };+ return {+ path: value.slice(0, hashIndex),+ fragment: decodeURIComponent(value.slice(hashIndex + 1) || ""),+ };+}++export function isExternalHref(href = "") {+ const value = String(href || "").trim();+ return /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(value) || value.startsWith("//");+}++export function isMarkdownPath(path = "") {+ return /\.md(?:own)?$/i.test(String(path || "").split(/[?#]/, 1)[0]);+}++function finalizePage(page, index, source = "") {+ const start = Math.max(0, Number(page.start || 0));+ const end = Math.max(start, Number(page.end ?? String(source || "").length));+ const markdown = String(source || "").slice(start, end) || page.lines.join("\n");+ return {+ index,+ title: page.title,+ level: page.level,+ anchor: slugifyHeading(page.title),+ start,+ end,+ markdown,+ };+}++function cleanHeadingText(text = "") {+ return String(text || "")+ .replace(/\\([\\`*_[\]{}()#+.!-])/g, "$1")+ .replace(/[*_`~]/g, "")+ .trim();+}++function prepareFootnotes(markdown = "", fullMarkdown = markdown) {+ const definitions = [];+ const body = [];+ for (const line of String(fullMarkdown || "").split("\n")) {+ const match = line.match(FOOTNOTE_DEF_RE);+ if (match) {+ definitions.push({ id: match[1], text: match[2] });+ }+ }+ for (const line of String(markdown || "").split("\n")) {+ if (line.match(FOOTNOTE_DEF_RE)) {+ continue;+ }+ body.push(line);+ }+ if (!definitions.length) return markdown;++ const counts = new Map();+ let prepared = body.join("\n").replace(/\[\^([^\]]+)\]/g, (_all, id) => {+ const number = definitions.findIndex((item) => item.id === id) + 1;+ if (number <= 0) return `[^${id}]`;+ const count = (counts.get(id) || 0) + 1;+ counts.set(id, count);+ const safeId = footnoteId(id);+ return `<sup class="editor-footnote-ref"><a id="fnref-${safeId}-${count}" href="#fn-${safeId}">${number}</a></sup>`;+ });++ prepared += "\n\n<section class=\"editor-footnotes\" aria-label=\"Footnotes\">\n<ol>\n";+ for (const [index, definition] of definitions.entries()) {+ const safeId = footnoteId(definition.id);+ prepared += `<li id="fn-${safeId}">${escapeHtml(definition.text)} <a class="editor-footnote-backref" href="#fnref-${safeId}-1">Back</a></li>\n`;+ }+ prepared += "</ol>\n</section>";+ return prepared;+}++function footnoteId(id = "") {+ return String(id || "")+ .toLowerCase()+ .replace(/[^a-z0-9_-]+/g, "-")+ .replace(/^-+|-+$/g, "") || "note";+}++function parentPath(path = "") {+ const normalized = String(path || "").split(/[?#]/, 1)[0].replace(/\/+$/, "");+ const index = normalized.lastIndexOf("/");+ if (index <= 0) return "/";+ return normalized.slice(0, index);+}++function normalizePath(path = "") {+ const absolute = String(path || "").startsWith("/");+ const parts = [];+ for (const part of String(path || "").split("/")) {+ if (!part || part === ".") continue;+ if (part === "..") {+ parts.pop();+ continue;+ }+ parts.push(part);+ }+ return `${absolute ? "/" : ""}${parts.join("/")}`;+}++function escapeHtml(value = "") {+ return String(value || "")+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """);+}diff --git a/plugins/_editor/webui/editor-store.js b/plugins/_editor/webui/editor-store.jsindex a18f48de9..6c19439b0 100644--- a/plugins/_editor/webui/editor-store.js+++ b/plugins/_editor/webui/editor-store.js@@ -2,6 +2,15 @@ import { createStore } from "/js/AlpineStore.js";import { callJsonApi } from "/js/api.js";import { getNamespacedClient } from "/js/websocket.js";import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";+import {+ buildMarkdownPages,+ isExternalHref,+ isMarkdownPath,+ renderEditorPreviewMarkdown,+ resolveDocumentRelativePath,+ slugifyHeading,+ splitHref,+} from "/plugins/_editor/webui/editor-preview.js";const editorSocket = getNamespacedClient("/ws");editorSocket.addHandlers(["ws_webui"]);@@ -9,6 +18,8 @@ editorSocket.addHandlers(["ws_webui"]);const SAVE_MESSAGE_MS = 1800;const INPUT_PUSH_DELAY_MS = 650;const MAX_HISTORY = 80;+const SOURCE_MODE = "source";+const PREVIEW_MODE = "preview";function currentContextId() {try {@@ -94,6 +105,48 @@ function documentLabel(document = {}) {return document.title || document.basename || basename(document.path);}+function escapeRegExp(value = "") {+ return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++function textNodesUnder(root, skipSelector = "") {+ const nodes = [];+ if (!root) return nodes;+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {+ acceptNode(node) {+ if (!node.nodeValue) return NodeFilter.FILTER_REJECT;+ if (skipSelector && node.parentElement?.closest(skipSelector)) return NodeFilter.FILTER_REJECT;+ return NodeFilter.FILTER_ACCEPT;+ },+ });+ while (walker.nextNode()) nodes.push(walker.currentNode);+ return nodes;+}++function aceModeForLanguage(language = "") {+ const value = String(language || "").toLowerCase();+ const aliases = {+ bash: "sh",+ shell: "sh",+ zsh: "sh",+ py: "python",+ js: "javascript",+ jsx: "javascript",+ ts: "typescript",+ md: "markdown",+ yml: "yaml",+ };+ return aliases[value] || value || "text";+}++function taskLineIndexes(markdown = "") {+ const indexes = [];+ String(markdown || "").split("\n").forEach((line, index) => {+ if (/^\s*(?:[-*+]|\d+[.)])\s+\[[ xX]\](?:\s+|$)/.test(line)) indexes.push(index);+ });+ return indexes;+}+async function callEditor(action, payload = {}) {return await callJsonApi("/plugins/_editor/editor_session", {action,@@ -142,7 +195,19 @@ const model = {error: "",message: "",pendingClose: null,+ viewMode: SOURCE_MODE,+ searchOpen: false,+ searchQuery: "",+ searchMatches: [],+ searchIndex: -1,+ activePageIndex: 0,+ previewEditing: false,+ previewEditDirty: false,+ previewEditText: "",+ previewEditPageIndex: -1,+ aceUnavailable: false,editorText: "",+ sourceEditor: null,_root: null,_mode: "modal",_initialized: false,@@ -155,6 +220,12 @@ const model = {_focusAttempts: 0,_headerCleanup: null,_surfaceHandoff: false,+ _settingSourceEditorValue: false,+ _sourceEditorChangeHandler: null,+ _previewEnhanceTimer: null,+ _staticHighlightPromise: null,+ _pendingPreviewFragment: "",+ _initialCreatePromise: null,async init() {if (this._initialized) return;@@ -167,6 +238,7 @@ const model = {if (element) this._root = element;this._mode = options?.mode === "canvas" ? "canvas" : "modal";if (this._mode === "modal") this.setupMarkdownModal(element);+ this.scheduleSourceEditorInit();this.queueRender();},@@ -180,7 +252,9 @@ const model = {refresh: payload.refresh === true,source: payload.source || "",});+ return;}+ await this.ensureInitialMarkdownFile();},beforeHostHidden() {@@ -189,6 +263,9 @@ const model = {cleanup() {this.flushInput();+ this.destroySourceEditor();+ if (this._previewEnhanceTimer) globalThis.clearTimeout(this._previewEnhanceTimer);+ this._previewEnhanceTimer = null;this._headerCleanup?.();this._headerCleanup = null;if (this._mode === "modal") this._root = null;@@ -217,10 +294,557 @@ const model = {}},+ isSourceMode() {+ return this.viewMode === SOURCE_MODE;+ },++ isPreviewMode() {+ return this.viewMode === PREVIEW_MODE;+ },++ async setViewMode(mode) {+ const next = mode === PREVIEW_MODE ? PREVIEW_MODE : SOURCE_MODE;+ if (this.viewMode === next) return;+ this.applyPreviewEdit({ silent: true });+ this.syncEditorText();+ this.viewMode = next;+ this.cancelPendingClose();+ if (next === SOURCE_MODE) {+ this.setSourceEditorText(this.editorText);+ this.scheduleSourceEditorInit();+ this.refreshSourceEditorLayout();+ this.queueRender({ focus: Boolean(this.session), end: false });+ return;+ }+ this.clampActivePage();+ this.schedulePreviewEnhance();+ },++ async toggleViewMode() {+ await this.setViewMode(this.isPreviewMode() ? SOURCE_MODE : PREVIEW_MODE);+ },++ viewModeIcon() {+ return this.isPreviewMode() ? "code" : "article";+ },++ viewModeTitle() {+ return this.isPreviewMode() ? "Source edit" : "Preview";+ },++ pages() {+ return buildMarkdownPages(this.editorText, this.tabTitle(this.session || {}));+ },++ currentPage() {+ const pages = this.pages();+ const index = Math.max(0, Math.min(this.activePageIndex, pages.length - 1));+ return pages[index] || pages[0] || { title: this.tabTitle(this.session || {}), markdown: "" };+ },++ pageTitle() {+ return this.currentPage().title || this.tabTitle(this.session || {});+ },++ pagePositionLabel() {+ const pages = this.pages();+ if (!pages.length) return "";+ return `${Math.min(this.activePageIndex + 1, pages.length)} of ${pages.length}`;+ },++ previewHtml() {+ return renderEditorPreviewMarkdown(this.currentPage().markdown || "", this.editorText);+ },++ selectPage(index) {+ if (this.previewEditing) return;+ const pages = this.pages();+ if (!pages.length) return;+ this.activePageIndex = Math.max(0, Math.min(Number(index) || 0, pages.length - 1));+ this.schedulePreviewEnhance();+ },++ nextPage() {+ this.selectPage(this.activePageIndex + 1);+ },++ previousPage() {+ this.selectPage(this.activePageIndex - 1);+ },++ startPreviewEdit() {+ if (!this.session || !this.isMarkdown() || !this.isPreviewMode()) return;+ const page = this.currentPage();+ this.previewEditing = true;+ this.previewEditDirty = false;+ this.previewEditPageIndex = this.activePageIndex;+ this.previewEditText = page.markdown || "";+ this.queueRender({ force: true, focus: false });+ globalThis.requestAnimationFrame?.(() => {+ const editor = this._root?.querySelector?.("[data-editor-preview-source]");+ editor?.focus?.({ preventScroll: true });+ });+ },++ onPreviewEditInput() {+ if (this.previewEditing) this.previewEditDirty = true;+ },++ cancelPreviewEdit() {+ this.previewEditing = false;+ this.previewEditDirty = false;+ this.previewEditText = "";+ this.previewEditPageIndex = -1;+ this.schedulePreviewEnhance();+ },++ applyPreviewEdit(options = {}) {+ if (!this.previewEditing) return false;+ if (!this.previewEditDirty && options.force !== true) {+ this.cancelPreviewEdit();+ return false;+ }+ const pages = this.pages();+ const index = Math.max(0, Math.min(+ this.previewEditPageIndex >= 0 ? this.previewEditPageIndex : this.activePageIndex,+ pages.length - 1,+ ));+ const page = pages[index];+ if (!page) {+ this.cancelPreviewEdit();+ return false;+ }++ let replacement = String(this.previewEditText || "");+ this.previewEditing = false;+ this.previewEditDirty = false;+ this.previewEditText = "";+ this.previewEditPageIndex = -1;++ return this.replacePageMarkdown(page, replacement, {+ message: "Page updated",+ silent: options.silent,+ });+ },++ replacePageMarkdown(page = null, markdown = "", options = {}) {+ if (!page) return false;+ const source = String(this.editorText || "");+ const start = Math.max(0, Number(page.start || 0));+ const end = Math.max(start, Number(page.end ?? source.length));+ const before = source.slice(0, start);+ const after = source.slice(end);+ let replacement = String(markdown || "");+ if (replacement && after && !replacement.endsWith("\n")) replacement += "\n";+ const next = before + replacement + after;+ if (next === source) {+ this.schedulePreviewEnhance();+ return false;+ }++ this.editorText = next;+ this.setSourceEditorText(next);+ if (this.session) {+ this.session.text = next;+ this.session.dirty = true;+ }+ this.dirty = true;+ this.pushHistory(next);+ this.scheduleInputPush();+ this.clampActivePage();+ this.schedulePreviewEnhance();+ if (!options.silent && options.message) this.setMessage(options.message);+ this.queueRender({ force: true, focus: false });+ return true;+ },++ togglePreviewTask(taskIndex, checked) {+ if (!this.session || !this.isMarkdown() || !this.isPreviewMode() || this.previewEditing) return false;+ const page = this.currentPage();+ const lines = String(page.markdown || "").split("\n");+ const indexes = taskLineIndexes(page.markdown || "");+ const lineIndex = indexes[Number(taskIndex)];+ if (lineIndex == null || !lines[lineIndex]) return false;+ const nextLine = lines[lineIndex].replace(+ /^(\s*(?:[-*+]|\d+[.)])\s+\[)[ xX](\](?:\s+|$))/,+ `$1${checked ? "x" : " "}$2`,+ );+ if (nextLine === lines[lineIndex]) return false;+ lines[lineIndex] = nextLine;+ return this.replacePageMarkdown(page, lines.join("\n"));+ },++ clampActivePage() {+ const pages = this.pages();+ this.activePageIndex = Math.max(0, Math.min(this.activePageIndex, Math.max(0, pages.length - 1)));+ },++ schedulePreviewEnhance() {+ if (!this.isPreviewMode()) return;+ if (this._previewEnhanceTimer) globalThis.clearTimeout(this._previewEnhanceTimer);+ this._previewEnhanceTimer = globalThis.setTimeout(() => {+ this._previewEnhanceTimer = null;+ this.enhancePreview();+ }, 0);+ },++ enhancePreview() {+ const root = this._root?.querySelector?.("[data-editor-preview]");+ if (!root) return;+ this.addHeadingIds(root);+ this.enhanceTables(root);+ this.enhanceTaskLists(root);+ this.enhanceImages(root);+ this.enhanceLinks(root);+ this.enhanceCodeBlocks(root);+ this.renderMath(root);+ this.applySearchHighlights(root);+ this.scrollPendingFragment(root);+ },++ addHeadingIds(root) {+ const used = new Map();+ root.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach((heading) => {+ if (!heading.id) heading.id = slugifyHeading(heading.textContent || "", used);+ });+ },++ enhanceTables(root) {+ root.querySelectorAll("table").forEach((table) => {+ if (table.parentElement?.classList.contains("editor-table-wrap")) return;+ const wrapper = document.createElement("div");+ wrapper.className = "editor-table-wrap";+ table.parentNode?.insertBefore(wrapper, table);+ wrapper.appendChild(table);+ });+ },++ enhanceTaskLists(root) {+ root.querySelectorAll('input[type="checkbox"]').forEach((checkbox, index) => {+ if (checkbox.dataset.editorTaskEnhanced === "true") return;+ checkbox.dataset.editorTaskEnhanced = "true";+ checkbox.dataset.editorTaskIndex = String(index);+ checkbox.disabled = false;+ checkbox.removeAttribute("disabled");+ checkbox.addEventListener("change", (event) => {+ const target = event.currentTarget;+ this.togglePreviewTask(Number(target?.dataset?.editorTaskIndex || 0), Boolean(target?.checked));+ });+ });+ },++ enhanceImages(root) {+ const docPath = this.session?.path || this.session?.document?.path || "";+ root.querySelectorAll("img[src]").forEach((image) => {+ const src = image.getAttribute("src") || "";+ if (!src || isExternalHref(src) || src.startsWith("data:") || src.startsWith("/api/image_get")) return;+ const resolved = resolveDocumentRelativePath(docPath, src);+ image.setAttribute("src", `/api/image_get?path=${encodeURIComponent(resolved)}`);+ image.setAttribute("loading", "lazy");+ });+ },++ enhanceLinks(root) {+ const docPath = this.session?.path || this.session?.document?.path || "";+ root.querySelectorAll("a[href]").forEach((anchor) => {+ const href = anchor.getAttribute("href") || "";+ if (!href || isExternalHref(href)) return;+ const { path, fragment } = splitHref(href);+ if (!path && fragment) {+ anchor.dataset.editorFragment = fragment;+ return;+ }+ if (!isMarkdownPath(path)) return;+ anchor.dataset.editorMarkdownPath = resolveDocumentRelativePath(docPath, path);+ anchor.dataset.editorFragment = fragment;+ });+ },++ async enhanceCodeBlocks(root) {+ root.querySelectorAll("pre > code").forEach((code) => {+ const pre = code.parentElement;+ if (!pre || pre.parentElement?.classList.contains("editor-code-block")) return;+ const wrapper = document.createElement("div");+ wrapper.className = "editor-code-block";+ const header = document.createElement("div");+ header.className = "editor-code-header";+ const language = this.codeLanguage(code);+ const label = document.createElement("span");+ label.className = "editor-code-language";+ label.textContent = language || "text";+ const button = document.createElement("button");+ button.type = "button";+ button.className = "editor-code-copy";+ button.textContent = "Copy";+ button.addEventListener("click", async () => {+ await navigator.clipboard?.writeText(code.textContent || "");+ button.textContent = "Copied";+ globalThis.setTimeout(() => { button.textContent = "Copy"; }, 1200);+ });+ header.append(label, button);+ pre.parentNode?.insertBefore(wrapper, pre);+ wrapper.append(header, pre);+ this.highlightCodeBlock(code, language);+ });+ },++ codeLanguage(code) {+ for (const className of code.classList || []) {+ if (className.startsWith("language-")) return className.slice("language-".length);+ if (className.startsWith("lang-")) return className.slice("lang-".length);+ }+ return "";+ },++ async highlightCodeBlock(code, language) {+ if (!language || !globalThis.ace?.require) return;+ const source = code.textContent || "";+ try {+ const highlighter = await this.loadAceStaticHighlighter();+ const darkMode = globalThis.localStorage?.getItem("darkMode");+ const theme = darkMode !== "false" ? "ace/theme/github_dark" : "ace/theme/github";+ const mode = `ace/mode/${aceModeForLanguage(language)}`;+ highlighter.render(source, mode, theme, 1, true, (result) => {+ code.innerHTML = result.html;+ code.classList.add("is-highlighted");+ });+ } catch {+ // Fenced code still renders as preformatted text if highlighting is unavailable.+ }+ },++ loadAceStaticHighlighter() {+ if (this._staticHighlightPromise) return this._staticHighlightPromise;+ this._staticHighlightPromise = new Promise((resolve, reject) => {+ let existing = null;+ try {+ existing = globalThis.ace?.require?.("ace/ext/static_highlight");+ } catch {+ existing = null;+ }+ if (existing?.render) {+ resolve(existing);+ return;+ }+ const script = document.createElement("script");+ script.src = "/vendor/ace-min/ext-static_highlight.js";+ script.onload = () => {+ const loaded = globalThis.ace?.require?.("ace/ext/static_highlight");+ loaded?.render ? resolve(loaded) : reject(new Error("ACE highlighter unavailable"));+ };+ script.onerror = () => reject(new Error("ACE highlighter failed to load"));+ document.head.appendChild(script);+ });+ return this._staticHighlightPromise;+ },++ renderMath(root) {+ if (!globalThis.katex?.render) return;+ for (const node of textNodesUnder(root, "code,pre,.katex,.editor-code-block")) {+ this.replaceMathInTextNode(node);+ }+ },++ replaceMathInTextNode(node) {+ const text = node.nodeValue || "";+ const pattern = /(\$\$[^$]+\$\$|\$[^$\n]+\$)/g;+ if (!pattern.test(text)) return;+ pattern.lastIndex = 0;+ const fragment = document.createDocumentFragment();+ let lastIndex = 0;+ let match;+ while ((match = pattern.exec(text))) {+ if (match.index > lastIndex) fragment.append(document.createTextNode(text.slice(lastIndex, match.index)));+ const raw = match[0];+ const displayMode = raw.startsWith("$$");+ const expression = raw.slice(displayMode ? 2 : 1, displayMode ? -2 : -1);+ const span = document.createElement(displayMode ? "div" : "span");+ span.className = displayMode ? "editor-math-display" : "editor-math-inline";+ try {+ globalThis.katex.render(expression, span, { throwOnError: false, displayMode });+ } catch {+ span.textContent = raw;+ }+ fragment.append(span);+ lastIndex = match.index + raw.length;+ }+ if (lastIndex < text.length) fragment.append(document.createTextNode(text.slice(lastIndex)));+ node.parentNode?.replaceChild(fragment, node);+ },++ openSearch() {+ if (!this.isPreviewMode()) {+ this.setViewMode(PREVIEW_MODE);+ }+ this.searchOpen = true;+ this.runSearch();+ globalThis.requestAnimationFrame?.(() => {+ this._root?.querySelector?.("[data-editor-search]")?.focus?.();+ });+ },++ closeSearch() {+ this.searchOpen = false;+ this.searchQuery = "";+ this.searchMatches = [];+ this.searchIndex = -1;+ this.schedulePreviewEnhance();+ },++ searchCountLabel() {+ if (!this.searchQuery) return "";+ if (!this.searchMatches.length) return "0 of 0";+ return `${this.searchIndex + 1} of ${this.searchMatches.length}`;+ },++ runSearch() {+ const query = String(this.searchQuery || "");+ if (!query) {+ this.searchMatches = [];+ this.searchIndex = -1;+ this.schedulePreviewEnhance();+ return;+ }+ const lower = query.toLowerCase();+ const matches = [];+ for (const page of this.pages()) {+ const text = this.renderedTextForPage(page);+ let index = 0;+ let occurrence = 0;+ while ((index = text.toLowerCase().indexOf(lower, index)) >= 0) {+ matches.push({ pageIndex: page.index, occurrence, offset: index });+ occurrence += 1;+ index += Math.max(1, lower.length);+ }+ }+ this.searchMatches = matches;+ this.searchIndex = matches.length ? 0 : -1;+ this.goToCurrentSearchMatch();+ },++ nextSearchMatch() {+ if (!this.searchMatches.length) return;+ this.searchIndex = (this.searchIndex + 1) % this.searchMatches.length;+ this.goToCurrentSearchMatch();+ },++ previousSearchMatch() {+ if (!this.searchMatches.length) return;+ this.searchIndex = (this.searchIndex - 1 + this.searchMatches.length) % this.searchMatches.length;+ this.goToCurrentSearchMatch();+ },++ goToCurrentSearchMatch() {+ const match = this.searchMatches[this.searchIndex];+ if (!match) {+ this.schedulePreviewEnhance();+ return;+ }+ this.activePageIndex = match.pageIndex;+ this.schedulePreviewEnhance();+ },++ renderedTextForPage(page) {+ const html = renderEditorPreviewMarkdown(page.markdown || "", this.editorText);+ const doc = new DOMParser().parseFromString(html, "text/html");+ return doc.body.textContent || "";+ },++ applySearchHighlights(root) {+ root.querySelectorAll("mark.editor-search-mark").forEach((mark) => {+ mark.replaceWith(document.createTextNode(mark.textContent || ""));+ });+ const query = String(this.searchQuery || "");+ if (!query || !this.searchMatches.length) return;+ const regex = new RegExp(escapeRegExp(query), "gi");+ const current = this.searchMatches[this.searchIndex];+ let occurrence = 0;+ for (const node of textNodesUnder(root, "script,style")) {+ const text = node.nodeValue || "";+ if (!regex.test(text)) continue;+ regex.lastIndex = 0;+ const fragment = document.createDocumentFragment();+ let lastIndex = 0;+ let match;+ while ((match = regex.exec(text))) {+ if (match.index > lastIndex) fragment.append(document.createTextNode(text.slice(lastIndex, match.index)));+ const mark = document.createElement("mark");+ mark.className = "editor-search-mark";+ if (current?.pageIndex === this.activePageIndex && current.occurrence === occurrence) {+ mark.classList.add("is-current");+ }+ mark.textContent = match[0];+ fragment.append(mark);+ occurrence += 1;+ lastIndex = match.index + match[0].length;+ }+ if (lastIndex < text.length) fragment.append(document.createTextNode(text.slice(lastIndex)));+ node.parentNode?.replaceChild(fragment, node);+ }+ root.querySelector("mark.editor-search-mark.is-current")?.scrollIntoView?.({ block: "center" });+ },++ async handlePreviewClick(event) {+ const anchor = event.target?.closest?.("a[href]");+ if (!anchor) return;+ const markdownPath = anchor.dataset.editorMarkdownPath || "";+ const fragment = anchor.dataset.editorFragment || "";+ if (!markdownPath && fragment) {+ event.preventDefault();+ this.navigateToFragment(fragment);+ return;+ }+ if (!markdownPath) return;+ event.preventDefault();+ this._pendingPreviewFragment = fragment;+ const opened = await this.openSession({ path: markdownPath, refresh: true, source: "editor-preview-link" });+ if (!opened) return;+ if (this.isPreviewMode() && fragment) {+ this.navigateToFragment(fragment);+ }+ },++ navigateToFragment(fragment = "") {+ const target = String(fragment || "").replace(/^#/, "");+ if (!target) return;+ const pages = this.pages();+ const normalized = target.toLowerCase();+ for (const page of pages) {+ const doc = new DOMParser().parseFromString(renderEditorPreviewMarkdown(page.markdown || "", this.editorText), "text/html");+ const used = new Map();+ const headings = [...doc.body.querySelectorAll("h1,h2,h3,h4,h5,h6")];+ if (headings.some((heading) => (heading.id || slugifyHeading(heading.textContent || "", used)) === normalized)) {+ this.activePageIndex = page.index;+ this._pendingPreviewFragment = target;+ this.schedulePreviewEnhance();+ return;+ }+ }+ this._pendingPreviewFragment = target;+ this.schedulePreviewEnhance();+ },++ scrollPendingFragment(root) {+ const fragment = this._pendingPreviewFragment;+ if (!fragment) return;+ const target = root.querySelector(`#${CSS.escape(fragment)}`);+ if (target) {+ target.scrollIntoView({ block: "start" });+ this._pendingPreviewFragment = "";+ }+ },++ handleEditorKeydown(event) {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "f") {+ event.preventDefault();+ this.openSearch();+ }+ },+async create(kind = "document", format = "") {const fmt = "md";const title = this.defaultTitle(kind, fmt);- await this.openSession({+ return await this.openSession({action: "create",kind: "document",format: fmt,@@ -228,6 +852,15 @@ const model = {});},+ async ensureInitialMarkdownFile() {+ if (this.session || this.visibleTabs().length > 0 || this.loading) return null;+ if (!this._root || this._initialCreatePromise) return this._initialCreatePromise;+ this._initialCreatePromise = this.create("document", "md").finally(() => {+ this._initialCreatePromise = null;+ });+ return await this._initialCreatePromise;+ },+async openFileBrowser() {let workdirPath = "/a0/usr/workdir";try {@@ -281,8 +914,15 @@ const model = {|| (session.path && tab.path === session.path)));if (existingIndex >= 0) {- this.tabs.splice(existingIndex, 1, { ...this.tabs[existingIndex], ...session, tab_id: this.tabs[existingIndex].tab_id });- this.activeTabId = this.tabs[existingIndex].tab_id;+ const tabId = this.tabs[existingIndex].tab_id;+ const wasActive = this.activeTabId === tabId || this.session?.tab_id === tabId;+ const merged = { ...this.tabs[existingIndex], ...session, tab_id: tabId };+ this.tabs.splice(existingIndex, 1, merged);+ this.activeTabId = tabId;+ if (wasActive) {+ this.hydrateActiveSession(merged, { preservePage: true, focus: false });+ return;+ }} else {this.tabs.push(session);this.activeTabId = session.tab_id;@@ -290,18 +930,40 @@ const model = {this.selectTab(this.activeTabId);},- selectTab(tabId, options = {}) {- this.syncEditorText();- const tab = this.tabs.find((item) => item.tab_id === tabId) || this.tabs[0] || null;- this.session = tab;+ hydrateActiveSession(tab, options = {}) {+ this.session = tab || null;this.activeTabId = tab?.tab_id || "";this.editorText = String(tab?.text || "");this.dirty = Boolean(tab?.dirty);+ if (this.previewEditing) this.cancelPreviewEdit();+ if (!options.preservePage) {+ this.activePageIndex = 0;+ } else {+ this.clampActivePage();+ }+ this.searchMatches = [];+ this.searchIndex = -1;this.resetHistory(this.editorText);+ this.setSourceEditorText(this.editorText);if (tab?.session_id) {requestEditor("editor_activate", { session_id: tab.session_id }, 2500).catch(() => {});}- this.queueRender({ focus: Boolean(tab) && options.focus !== false });+ if (this.searchOpen && this.searchQuery) this.runSearch();+ else if (this.isSourceMode()) this.scheduleSourceEditorInit();+ else this.schedulePreviewEnhance();+ this.refreshSourceEditorLayout();+ this.queueRender({ focus: this.isSourceMode() && Boolean(tab) && options.focus !== false, end: false });+ },++ selectTab(tabId, options = {}) {+ this.applyPreviewEdit({ silent: true });+ this.syncEditorText();+ const tab = this.tabs.find((item) => item.tab_id === tabId) || this.tabs[0] || null;+ this.previewEditing = false;+ this.previewEditDirty = false;+ this.previewEditText = "";+ this.previewEditPageIndex = -1;+ this.hydrateActiveSession(tab, { preservePage: false, focus: options.focus !== false });},ensureActiveTab() {@@ -314,7 +976,7 @@ const model = {},isTabDirty(tab) {- return Boolean(tab?.dirty || (this.isActiveTab(tab) && this.dirty));+ return Boolean(tab?.dirty || (this.isActiveTab(tab) && (this.dirty || this.previewEditDirty)));},hasPendingClose() {@@ -362,7 +1024,7 @@ const model = {totalCount: tabs.length,dirtyCount,};- if (kind === "single" && ids[0]) {+ if (kind === "single" && ids[0] && this.activeTabId !== ids[0]) {this.selectTab(ids[0], { focus: false });}},@@ -400,6 +1062,7 @@ const model = {const saved = await this.saveTab(tab);if (!saved) return false;}+ if (this.activeTabId === tabId && this.previewEditing) this.cancelPreviewEdit();try {if (tab.session_id) {await requestEditor("editor_close", { session_id: tab.session_id }, 2500).catch(() => null);@@ -458,8 +1121,87 @@ const model = {}},+ scheduleSourceEditorInit() {+ if (!this.isSourceMode()) return;+ globalThis.requestAnimationFrame?.(() => {+ globalThis.requestAnimationFrame?.(() => this.initSourceEditor());+ });+ },++ initSourceEditor() {+ if (!this.isSourceMode() || !this._root) return;+ const container = this._root.querySelector?.("[data-editor-ace]");+ if (!container || this.sourceEditor) return;+ if (!globalThis.ace?.edit) {+ this.aceUnavailable = true;+ return;+ }++ const editor = globalThis.ace.edit(container);+ const darkMode = globalThis.localStorage?.getItem("darkMode");+ const theme = darkMode !== "false" ? "ace/theme/github_dark" : "ace/theme/github";+ editor.setTheme(theme);+ editor.session.setMode("ace/mode/markdown");+ editor.session.setUseWrapMode(true);+ editor.setOptions({+ fontSize: "13px",+ showGutter: false,+ showPrintMargin: false,+ useWorker: false,+ });+ editor.renderer.setShowGutter(false);+ editor.renderer.setScrollMargin(14, 14, 0, 0);+ editor.setValue(this.editorText || "", -1);+ this._sourceEditorChangeHandler = () => {+ if (this._settingSourceEditorValue) return;+ this.editorText = editor.getValue();+ this.onSourceInput();+ };+ editor.session.on("change", this._sourceEditorChangeHandler);+ this.sourceEditor = editor;+ this.aceUnavailable = false;+ this.queueRender({ focus: Boolean(this.session), end: false });+ },++ destroySourceEditor() {+ if (this.sourceEditor?.session && this._sourceEditorChangeHandler) {+ this.sourceEditor.session.off?.("change", this._sourceEditorChangeHandler);+ }+ const container = this.sourceEditor?.container;+ this.sourceEditor?.destroy?.();+ if (container) container.textContent = "";+ this.sourceEditor = null;+ this._sourceEditorChangeHandler = null;+ },++ setSourceEditorText(text = "") {+ if (!this.sourceEditor) return;+ const value = String(text || "");+ if (this.sourceEditor.getValue() === value) return;+ this._settingSourceEditorValue = true;+ this.sourceEditor.setValue(value, -1);+ this._settingSourceEditorValue = false;+ this.refreshSourceEditorLayout();+ },++ refreshSourceEditorLayout() {+ const editor = this.sourceEditor;+ if (!editor) return;+ const refresh = () => {+ editor.resize?.(true);+ editor.renderer?.updateFull?.();+ editor.renderer?.updateText?.();+ };+ if (globalThis.requestAnimationFrame) {+ globalThis.requestAnimationFrame(() => globalThis.requestAnimationFrame(refresh));+ } else {+ globalThis.setTimeout(refresh, 0);+ }+ },+async save() {if (!this.session || this.saving || !this.isMarkdown()) return;+ this.applyPreviewEdit({ silent: true });this.syncEditorText();this.saving = true;this.error = "";@@ -496,6 +1238,7 @@ const model = {async saveTab(tab) {if (!tab || this.saving || !this.isMarkdown(tab)) return false;if (this.isActiveTab(tab)) {+ this.applyPreviewEdit({ silent: true });this.syncEditorText();}this.saving = true;@@ -539,6 +1282,7 @@ const model = {async renameActiveFile() {if (!this.session || this.saving) return;+ this.applyPreviewEdit({ silent: true });const session = this.session;const path = session.path || session.document?.path || "";if (!path) {@@ -642,12 +1386,24 @@ const model = {},undo() {+ if (this.sourceEditor && this.isSourceMode()) {+ this.sourceEditor.undo();+ this.editorText = this.sourceEditor.getValue();+ this.syncEditorText();+ return;+ }if (this._historyIndex <= 0) return;this._historyIndex -= 1;this.applyEditorText(this._history[this._historyIndex], true);},redo() {+ if (this.sourceEditor && this.isSourceMode()) {+ this.sourceEditor.redo();+ this.editorText = this.sourceEditor.getValue();+ this.syncEditorText();+ return;+ }if (this._historyIndex >= this._history.length - 1) return;this._historyIndex += 1;this.applyEditorText(this._history[this._historyIndex], true);@@ -663,6 +1419,7 @@ const model = {applyEditorText(text, markDirty = false) {this.editorText = String(text || "");+ this.setSourceEditorText(this.editorText);if (this.session) {this.session.text = this.editorText;this.session.dirty = markDirty || this.session.dirty;@@ -684,6 +1441,10 @@ const model = {syncEditorText() {if (!this.session) return;+ if (this.previewEditing) return;+ if (this.sourceEditor && this.isSourceMode()) {+ this.editorText = this.sourceEditor.getValue();+ }this.session.text = this.editorText;},@@ -698,6 +1459,7 @@ const model = {flushInput() {if (!this.session?.session_id || !this.isMarkdown()) return;+ if (this.previewEditing) return;this.syncEditorText();requestEditor("editor_input", {session_id: this.session.session_id,@@ -707,17 +1469,22 @@ const model = {format(command) {if (!this.session || !this.isMarkdown()) return;+ if (this.sourceEditor && this.isSourceMode()) {+ const selected = this.sourceEditor.getSelectedText();+ const replacement = this.formatReplacement(command, selected);+ if (replacement === selected) return;+ this.sourceEditor.session.replace(this.sourceEditor.getSelectionRange(), replacement);+ this.editorText = this.sourceEditor.getValue();+ this.onSourceInput();+ this.sourceEditor.focus();+ return;+ }const textarea = this._root?.querySelector?.("[data-editor-source]");if (!textarea) return;const start = textarea.selectionStart || 0;const end = textarea.selectionEnd || start;const selected = this.editorText.slice(start, end);- let replacement = selected;- if (command === "bold") replacement = `**${selected || "text"}**`;- if (command === "italic") replacement = `*${selected || "text"}*`;- if (command === "list") replacement = (selected || "item").split("\n").map((line) => `- ${line.replace(/^[-*]\s+/, "")}`).join("\n");- if (command === "numbered") replacement = (selected || "item").split("\n").map((line, index) => `${index + 1}. ${line.replace(/^\d+\.\s+/, "")}`).join("\n");- if (command === "table") replacement = "| Column | Value |\n| --- | --- |\n| | |";+ const replacement = this.formatReplacement(command, selected);if (replacement === selected) return;this.editorText = `${this.editorText.slice(0, start)}${replacement}${this.editorText.slice(end)}`;this.onSourceInput();@@ -728,6 +1495,15 @@ const model = {});},+ formatReplacement(command, selected = "") {+ if (command === "bold") return `**${selected || "text"}**`;+ if (command === "italic") return `*${selected || "text"}*`;+ if (command === "list") return (selected || "item").split("\n").map((line) => `- ${line.replace(/^[-*]\s+/, "")}`).join("\n");+ if (command === "numbered") return (selected || "item").split("\n").map((line, index) => `${index + 1}. ${line.replace(/^\d+\.\s+/, "")}`).join("\n");+ if (command === "table") return "| Column | Value |\n| --- | --- |\n| | |";+ return selected;+ },+queueRender(options = {}) {if (options.focus) {this._pendingFocus = true;@@ -752,6 +1528,16 @@ const model = {focusEditor(options = {}) {if (!this.session || !this.isMarkdown()) return false;+ if (this.sourceEditor && this.isSourceMode()) {+ this.sourceEditor.focus();+ if (options.end !== false) {+ const session = this.sourceEditor.session;+ const row = Math.max(0, session.getLength() - 1);+ const column = session.getLine(row).length;+ this.sourceEditor.moveCursorTo(row, column);+ }+ return true;+ }const source = this._root?.querySelector?.("[data-editor-source]");if (!source) return false;source.focus?.({ preventScroll: true });diff --git a/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.js b/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.jsindex cc233a1a2..030681647 100644--- a/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.js+++ b/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.js@@ -11,12 +11,18 @@ export default async function syncDocumentResultsIntoOpenOfficeModal(context) {for (const { args } of context.results) {const payload = getDocumentPayload(args);- if (getToolName(payload) !== "document_artifact") continue;+ const toolName = getToolName(payload);+ if (toolName === "text_editor") {+ syncTextEditorMarkdownResult(args, payload);+ continue;+ }+ if (toolName !== "document_artifact") continue;if (!shouldSyncOpenOfficeModal(args, payload)) continue;const document = payload.document && typeof payload.document === "object" ? payload.document : {};- const path = payload.path || document.path || "";- const fileId = payload.file_id || document.file_id || "";+ const target = documentTarget(payload, document);+ const path = target.path || "";+ const fileId = target.file_id || "";if (!path && !fileId) continue;const key = [@@ -24,24 +30,47 @@ export default async function syncDocumentResultsIntoOpenOfficeModal(context) {payload.action || "",fileId || "",path || "",- payload.version || document.version || "",+ target.version || "",].join(":");if (syncedDocumentResults.has(key)) continue;syncedDocumentResults.add(key);if (shouldOpenDocumentUiFromResult(payload, document)) {globalThis.setTimeout(() => {- void openDocumentUiFromResult({ path, file_id: fileId }, payload, document);+ void openDocumentUiFromResult(target, payload, document);}, 0);continue;}globalThis.setTimeout(() => {- void syncOpenDocumentSurfaces({ path, file_id: fileId });+ void syncOpenDocumentSurfaces(target);}, 0);}}+function syncTextEditorMarkdownResult(args = {}, payload = {}) {+ const target = textEditorTarget(payload);+ if (!target.path || target.extension !== "md") return;+ if (!shouldSyncTextEditorResult(args, payload)) return;++ globalThis.setTimeout(() => {+ void syncOpenEditorSurface(target);+ }, 0);+}++function documentTarget(payload = {}, document = {}) {+ const extension = documentExtension(payload, document);+ return {+ ...document,+ path: payload.path || document.path || "",+ file_id: payload.file_id || document.file_id || "",+ format: payload.format || document.format || extension,+ extension,+ version: payload.version || document.version || "",+ last_modified: payload.last_modified || document.last_modified || "",+ };+}+function getDocumentPayload(args = {}) {const contentPayload = parseMaybeJson(args.content);const kvpsPayload = args.kvps && typeof args.kvps === "object"@@ -72,6 +101,7 @@ function pickPayloadFields(args = {}) {"path","version","last_modified",+ "method",]) {if (args[key] != null && args[key] !== "") payload[key] = args[key];}@@ -88,6 +118,12 @@ function shouldSyncOpenOfficeModal(args = {}, payload = {}) {return ["create", "open", "edit", "restore_version"].includes(action);}+function shouldSyncTextEditorResult(args = {}, payload = {}) {+ if (!isFresh(args.timestamp, payload.last_modified)) return false;+ const action = String(payload.action || payload.method || "").trim().toLowerCase().replace("-", "_");+ return ["write", "patch"].includes(action);+}+function shouldOpenDocumentUiFromResult(payload = {}, document = {}) {if (!isExplicitDocumentUiRequest(payload)) return false;return Boolean(documentExtension(payload, document));@@ -122,6 +158,25 @@ function documentExtension(payload = {}, document = {}) {).toLowerCase();}+function textEditorTarget(payload = {}) {+ const path = String(payload.path || "").trim();+ return {+ path,+ file_id: "",+ extension: extensionFromPath(path),+ format: extensionFromPath(path),+ version: "",+ last_modified: payload.last_modified || "",+ };+}++function extensionFromPath(path = "") {+ const clean = String(path || "").split("?")[0].split("#")[0];+ const name = clean.split("/").filter(Boolean).pop() || "";+ const index = name.lastIndexOf(".");+ return index > 0 ? name.slice(index + 1).toLowerCase() : "";+}+function surfaceForDocument(payload = {}, document = {}) {return documentExtension(payload, document) === "md" ? "editor" : "desktop";}@@ -219,7 +274,7 @@ function isDirtySameDocument(store, document = {}) {return documentEntries(store).some((entry) => {if (!documentsMatch(entry, document)) return false;const isActive = entry === store?.session || (entry.tab_id && entry.tab_id === store?.activeTabId);- return Boolean(entry.dirty || (isActive && store?.dirty));+ return Boolean(entry.dirty || (isActive && (store?.dirty || store?.previewEditDirty)));});}diff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.pyindex 37e43fe64..2f3b83027 100644--- a/tests/test_office_canvas_setup.py+++ b/tests/test_office_canvas_setup.py@@ -102,6 +102,8 @@ def test_right_canvas_uses_desktop_surface_id_and_migrates_legacy_office_state()editor_main = read("plugins", "_editor", "webui", "main.html")editor_web_panel = read("plugins", "_editor", "webui", "editor-panel.html")editor_store = read("plugins", "_editor", "webui", "editor-store.js")+ editor_preview = read("plugins", "_editor", "webui", "editor-preview.js")+ safe_markdown = read("webui", "js", "safe-markdown.js")assert 'await callJsExtensions("surfaces_register", this);' in canvas_storeassert 'await callJsExtensions("right_canvas_register_surfaces", this);' in canvas_store@@ -123,12 +125,52 @@ def test_right_canvas_uses_desktop_surface_id_and_migrates_legacy_office_state()assert "editor-source-editor" in editor_web_panelassert "data-editor-source" in editor_web_panelassert "editor-tabs" in editor_web_panel+ assert "editor-new-tab" in editor_web_panel+ assert 'aria-label="New Markdown"' in editor_web_panelassert "editor-close-confirm" in editor_web_panelassert "Save & Close" in editor_web_panelassert "Close All" in editor_web_panel+ assert "editor-document-header" not in editor_web_panel+ assert "editor-document-save-button" not in editor_web_panel+ assert "data-editor-ace" in editor_web_panel+ assert "data-editor-preview" in editor_web_panel+ assert "data-editor-preview-source" in editor_web_panel+ assert "editor-mode-toggle" in editor_web_panel+ assert "editor-search-bar" in editor_web_panel+ assert "editor-preview-title" in editor_web_panel+ assert "editor-preview-page-editor" in editor_web_panel+ assert "editor-table-wrap" in editor_web_panelassert "closeAllFiles" in editor_storeassert "confirmPendingClose" in editor_store+ assert "ensureInitialMarkdownFile" in editor_store+ assert "await this.ensureInitialMarkdownFile();" in editor_store+ assert "startPreviewEdit" in editor_store+ assert "applyPreviewEdit" in editor_store+ assert "previewEditDirty" in editor_store+ assert "replacePageMarkdown" in editor_store+ assert "enhanceTaskLists" in editor_store+ assert "togglePreviewTask" in editor_store+ assert 'input[type="checkbox"]' in editor_store+ assert "renderEditorPreviewMarkdown" in editor_store+ assert "buildMarkdownPages" in editor_store+ assert "hydrateActiveSession" in editor_store+ assert "refreshSourceEditorLayout" in editor_store+ assert "editor.resize?.(true)" in editor_store+ assert "openSearch" in editor_store+ assert "handlePreviewClick" in editor_store+ assert "ace.edit" in editor_store+ assert "showGutter: false" in editor_storeassert "globalThis.confirm" not in editor_store+ assert ".editor-toolbar" in editor_web_panel+ assert "overflow: visible;" in editor_web_panel+ assert "z-index: 10000;" in editor_web_panel+ assert "renderSafeMarkdown" in editor_preview+ assert "prepareFootnotes" in editor_preview+ assert "resolveDocumentRelativePath" in editor_preview+ assert "slice(start, end)" in editor_preview+ assert "allowDataImages: true" in editor_preview+ assert "allowLatex: true" in editor_preview+ assert "html = sanitizeHtml(html, options);" in safe_markdownassert "right-canvas-desktop-actions" in desktop_new_menuassert "isSurfaceActive('desktop')" in desktop_new_menuassert "runNewMenuAction('writer')" in desktop_new_menu@@ -296,11 +338,20 @@ def test_document_artifacts_only_open_desktop_from_explicit_document_ui_requestsassert "officeStore" in auto_openassert "desktopStore" in auto_openassert "editorStore" in auto_open+ assert "store?.previewEditDirty" in auto_openassert "syncOpenEditorSurface" in auto_openassert "isEditorSurfaceOpen" in auto_openassert "syncOpenDesktopCanvas" in auto_openassert "syncOpenOfficeModal" in auto_openassert "isDesktopSurfaceOpen" in auto_open+ assert "function documentTarget(payload = {}, document = {})" in auto_open+ assert "syncTextEditorMarkdownResult" in auto_open+ assert "textEditorTarget" in auto_open+ assert 'toolName === "text_editor"' in auto_open+ assert 'return ["write", "patch"].includes(action);' in auto_open+ assert "void syncOpenDocumentSurfaces(target);" in auto_open+ assert "void syncOpenDocumentSurfaces({ path, file_id: fileId });" not in auto_open+ assert "return documentExtension(payload, document) === \"md\" ? \"editor\" : \"desktop\";" in auto_openassert "hasSameDocument" in auto_openassert 'source: "tool-result-sync"' in auto_openassert '".modal .office-panel"' not in auto_opendiff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.pyindex 81066eb20..cd8324f9b 100644--- a/tests/test_office_document_store.py+++ b/tests/test_office_document_store.py@@ -508,6 +508,32 @@ def test_direct_markdown_edits_refresh_open_canvas_session(office_state, monkeypassert manager._sessions[session["session_id"]].text == "# Receiver\n\nSecond"+def test_refresh_open_markdown_session_reloads_external_file_edits(office_state):+ manager = editor_markdown_sessions.MarkdownSessionManager()+ doc = document_store.create_document("document", "External Refresh", "md", "First")+ session = manager.open(doc, context_id="ctx-a")++ Path(doc["path"]).write_text("# External Refresh\n\nSecond\n", encoding="utf-8")+ refreshed = manager.open(doc, context_id="ctx-a", refresh=True)++ assert refreshed["session_id"] == session["session_id"]+ assert refreshed["text"] == "# External Refresh\n\nSecond\n"+ assert manager._sessions[session["session_id"]].dirty is False+++def test_refresh_open_markdown_session_preserves_dirty_editor_text(office_state):+ manager = editor_markdown_sessions.MarkdownSessionManager()+ doc = document_store.create_document("document", "Dirty External Refresh", "md", "First")+ session = manager.open(doc, context_id="ctx-a")+ manager.input(session["session_id"], text="Unsaved editor text")++ Path(doc["path"]).write_text("External disk text\n", encoding="utf-8")+ refreshed = manager.open(doc, context_id="ctx-a", refresh=True)++ assert refreshed["text"] == "Unsaved editor text"+ assert manager._sessions[session["session_id"]].dirty is True++def test_markdown_session_rejects_office_binaries(office_state):manager = editor_markdown_sessions.MarkdownSessionManager()doc = document_store.create_document("document", "Desktop Only", "odt", "Native text")diff --git a/webui/js/safe-markdown.js b/webui/js/safe-markdown.jsindex 6dfb30e87..dd6913373 100644--- a/webui/js/safe-markdown.js+++ b/webui/js/safe-markdown.js@@ -190,7 +190,7 @@ export function renderSafeMarkdown(markdown, options = {}) {html = rebaseGithubReadmeHtml(html, githubUrl, branch);}- html = sanitizeHtml(html);+ html = sanitizeHtml(html, options);if (openExternalLinksInNewTab) {html = addBlankTargetsToLinks(html);