Skip to content

Agent Zero AI framework

Polish Editor and Browser surface cleanup

Alessandro70adbe91a0e6
diff --git a/plugins/_browser/webui/browser-panel.html b/plugins/_browser/webui/browser-panel.html
index ec579836a..c72112064 100644
--- a/plugins/_browser/webui/browser-panel.html
+++ b/plugins/_browser/webui/browser-panel.html
@@ -177,6 +177,7 @@
<span class="material-symbols-outlined browser-address-icon">language</span>
<input class="browser-address" aria-label="Browser address" name="browser_address" x-model="$store.browserPage.address"
@focus="$store.browserPage.onAddressFocus()" @blur="$store.browserPage.onAddressBlur()"
+ @keydown.enter.prevent="$store.browserPage.go()"
:disabled="$store.browserPage.isBusy()"
placeholder="https://example.com" autocomplete="off" />
</form>
diff --git a/plugins/_editor/extensions/webui/right_canvas_register_surfaces/register-editor.js b/plugins/_editor/extensions/webui/right_canvas_register_surfaces/register-editor.js
index 14e31262b..2c4e8d53c 100644
--- a/plugins/_editor/extensions/webui/right_canvas_register_surfaces/register-editor.js
+++ b/plugins/_editor/extensions/webui/right_canvas_register_surfaces/register-editor.js
@@ -29,12 +29,6 @@ export default async function registerEditorSurface(surfaces) {
beginDockHandoff() {
editorStore.beginSurfaceHandoff?.();
},
- finishDockHandoff() {
- editorStore.finishSurfaceHandoff?.();
- },
- cancelDockHandoff() {
- editorStore.cancelSurfaceHandoff?.();
- },
async open(payload = {}) {
const panel = await waitForElement('[data-surface-id="editor"] .editor-panel');
if (!panel) throw new Error("Editor surface panel did not mount.");
diff --git a/plugins/_editor/webui/editor-panel.html b/plugins/_editor/webui/editor-panel.html
index 45aea8aa7..3739bcc64 100644
--- a/plugins/_editor/webui/editor-panel.html
+++ b/plugins/_editor/webui/editor-panel.html
@@ -393,6 +393,12 @@
}
.editor-icon-button {
+ display: inline-grid;
+ place-items: center;
+ width: 32px;
+ height: 32px;
+ min-width: 32px;
+ padding: 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%);
@@ -474,9 +480,6 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
- }
-
- .editor-tab-title {
font-size: 0.88rem;
font-weight: 600;
letter-spacing: 0;
@@ -594,15 +597,6 @@
font-size: 13px;
}
- .editor-icon-button {
- display: inline-grid;
- place-items: center;
- width: 32px;
- height: 32px;
- min-width: 32px;
- padding: 0;
- }
-
.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%);
diff --git a/plugins/_editor/webui/editor-preview.js b/plugins/_editor/webui/editor-preview.js
index 419bfdcbb..47fcc8cfb 100644
--- a/plugins/_editor/webui/editor-preview.js
+++ b/plugins/_editor/webui/editor-preview.js
@@ -169,7 +169,7 @@ function prepareFootnotes(markdown = "", fullMarkdown = markdown) {
});
prepared += "\n\n<section class=\"editor-footnotes\" aria-label=\"Footnotes\">\n<ol>\n";
- for (const [index, definition] of definitions.entries()) {
+ for (const definition of definitions) {
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`;
}
diff --git a/plugins/_editor/webui/editor-store.js b/plugins/_editor/webui/editor-store.js
index 6c19439b0..ab9007670 100644
--- a/plugins/_editor/webui/editor-store.js
+++ b/plugins/_editor/webui/editor-store.js
@@ -219,7 +219,6 @@ const model = {
_pendingFocusEnd: true,
_focusAttempts: 0,
_headerCleanup: null,
- _surfaceHandoff: false,
_settingSourceEditorValue: false,
_sourceEditorChangeHandler: null,
_previewEnhanceTimer: null,
@@ -235,11 +234,18 @@ const model = {
async onMount(element = null, options = {}) {
await this.init();
- if (element) this._root = element;
+ if (element && element !== this._root) {
+ if (this.sourceEditor && !element.contains?.(this.sourceEditor.container)) {
+ this.destroySourceEditor();
+ }
+ this._root = element;
+ }
this._mode = options?.mode === "canvas" ? "canvas" : "modal";
- if (this._mode === "modal") this.setupMarkdownModal(element);
+ if (this._mode === "modal") {
+ this.setupMarkdownModal(element);
+ await this.ensureInitialMarkdownFile();
+ }
this.scheduleSourceEditorInit();
- this.queueRender();
},
async onOpen(payload = {}) {
@@ -272,18 +278,9 @@ const model = {
},
beginSurfaceHandoff() {
- this._surfaceHandoff = true;
this.flushInput();
},
- finishSurfaceHandoff() {
- this._surfaceHandoff = false;
- },
-
- cancelSurfaceHandoff() {
- this._surfaceHandoff = false;
- },
-
async refresh() {
try {
const status = await callEditor("status");
@@ -379,7 +376,6 @@ const model = {
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 });
@@ -454,7 +450,6 @@ const model = {
this.clampActivePage();
this.schedulePreviewEnhance();
if (!options.silent && options.message) this.setMessage(options.message);
- this.queueRender({ force: true, focus: false });
return true;
},
@@ -1131,6 +1126,9 @@ const model = {
initSourceEditor() {
if (!this.isSourceMode() || !this._root) return;
const container = this._root.querySelector?.("[data-editor-ace]");
+ if (this.sourceEditor && !this._root.contains?.(this.sourceEditor.container)) {
+ this.destroySourceEditor();
+ }
if (!container || this.sourceEditor) return;
if (!globalThis.ace?.edit) {
this.aceUnavailable = true;
@@ -1359,7 +1357,6 @@ const model = {
if (wasActive) this.session = next;
const index = this.tabs.findIndex((tab) => tab.tab_id === (previous?.tab_id || next.tab_id));
if (index >= 0) this.tabs.splice(index, 1, next);
- this.queueRender();
},
setMessage(value) {
@@ -1425,7 +1422,7 @@ const model = {
this.session.dirty = markDirty || this.session.dirty;
}
if (markDirty) this.markDirty();
- this.queueRender({ force: true, focus: true });
+ this.queueRender({ focus: true });
},
markDirty() {
diff --git a/plugins/_office/api/ws_office.py b/plugins/_office/api/ws_office.py
index d5aa350f4..8fc225a76 100644
--- a/plugins/_office/api/ws_office.py
+++ b/plugins/_office/api/ws_office.py
@@ -92,5 +92,5 @@ def _public_doc(doc: dict[str, Any]) -> dict[str, Any]:
"size": doc["size"],
"version": document_store.item_version(doc),
"last_modified": doc["last_modified"],
- "exists": Path(doc["path"]).exists(),
+ "exists": Path(doc["path"]).exists(),
}
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.js
index 030681647..c3b084630 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
@@ -6,7 +6,7 @@ import { open as openSurface } from "/js/surfaces.js";
const SYNC_WINDOW_MS = 10 * 60 * 1000;
const syncedDocumentResults = new Set();
-export default async function syncDocumentResultsIntoOpenOfficeModal(context) {
+export default async function syncDocumentResultsIntoOpenSurfaces(context) {
if (!context?.results?.length || context.historyEmpty) return;
for (const { args } of context.results) {
diff --git a/plugins/_office/webui/office-panel.html b/plugins/_office/webui/office-panel.html
index 7dd2afa40..f2c067d32 100644
--- a/plugins/_office/webui/office-panel.html
+++ b/plugins/_office/webui/office-panel.html
@@ -9,58 +9,13 @@
<template x-if="$store.office">
<div class="office-panel" x-create="$store.office.onMount($el, xAttrs($el) || {})" x-destroy="$store.office.cleanup()">
<div class="office-shell">
- <div class="office-document-header" x-show="$store.office.hasActiveFile()" style="display: none;">
- <div class="office-document-title" :title="$store.office.tabLabel($store.office.session)">
- <span class="material-symbols-outlined office-document-icon" aria-hidden="true" x-text="$store.office.tabIcon($store.office.session)"></span>
- <span class="office-document-name" x-text="$store.office.tabTitle($store.office.session)"></span>
- <span class="office-document-dirty" x-show="$store.office.dirty" aria-hidden="true">*</span>
- </div>
-
- <button
- type="button"
- class="office-icon-button office-document-save-button"
- title="Save"
- aria-label="Save"
- :class="{ 'is-primary': $store.office.dirty }"
- :disabled="$store.office.saving"
- @click="$store.office.save()"
- >
- <span class="material-symbols-outlined" :class="{ spinning: $store.office.saving }" x-text="$store.office.saving ? 'progress_activity' : 'save'"></span>
- </button>
-
- <div class="office-file-actions" x-data="{ open: false }" @click.outside="open = false" @keydown.escape.window="open = false">
- <button
- type="button"
- class="office-icon-button office-file-menu-button"
- title="File actions"
- aria-label="File actions"
- aria-haspopup="menu"
- :aria-expanded="open.toString()"
- :disabled="$store.office.saving"
- @click.stop="open = !open"
- >
- <span class="material-symbols-outlined">more_vert</span>
- </button>
- <div class="office-new-menu office-file-menu" role="menu" x-show="open" @click.stop>
- <button type="button" class="office-new-menu-item" role="menuitem" :disabled="$store.office.saving" @click="open = false; $store.office.renameActiveFile()">
- <span class="material-symbols-outlined" aria-hidden="true">edit</span>
- <span>Rename</span>
- </button>
- <button type="button" class="office-new-menu-item" role="menuitem" :disabled="$store.office.loading" @click="open = false; $store.office.closeActiveFile()">
- <span class="material-symbols-outlined" aria-hidden="true">close</span>
- <span>Close File</span>
- </button>
- </div>
- </div>
- </div>
-
<div class="office-state-line" x-show="$store.office.message || $store.office.error || $store.office.loading" style="display: none;">
<span class="material-symbols-outlined" :class="{ spinning: $store.office.loading }" x-text="$store.office.loading ? 'progress_activity' : ($store.office.error ? 'error' : 'check_circle')"></span>
<span x-text="$store.office.error || $store.office.message || 'Working'"></span>
</div>
<div class="office-body">
- <div class="office-empty" x-show="!$store.office.session && !$store.office.loading" style="display: none;">
+ <div class="office-empty" x-show="!$store.office.loading" style="display: none;">
<div class="office-empty-actions">
<button type="button" class="office-icon-button office-command-button" @click="$store.office.runNewMenuAction('open')">
<span class="material-symbols-outlined" aria-hidden="true">folder_open</span>
@@ -128,8 +83,6 @@
grid-template-columns: minmax(0, 1fr) auto auto;
}
- .office-document-header,
- .office-toolbar,
.office-state-line {
display: flex;
align-items: center;
@@ -137,26 +90,8 @@
border-bottom: 1px solid var(--color-border);
padding: 8px 10px;
min-width: 0;
- }
-
- .office-document-title {
- display: flex;
- align-items: center;
- gap: 8px;
- min-width: 0;
- flex: 1 1 auto;
- font-size: 14px;
- font-weight: 600;
- }
-
- .office-document-name {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .office-document-dirty {
- color: var(--color-accent);
+ font-size: 13px;
+ color: var(--color-muted);
}
.office-icon-button {
@@ -182,15 +117,6 @@
opacity: 0.55;
}
- .office-document-save-button.is-primary {
- border-color: var(--color-accent);
- color: var(--color-accent);
- }
-
- .office-file-actions {
- position: relative;
- }
-
.office-new-menu {
position: absolute;
top: calc(100% + 6px);
@@ -230,11 +156,6 @@
gap: 6px;
}
- .office-state-line {
- font-size: 13px;
- color: var(--color-muted);
- }
-
.office-body {
display: flex;
flex: 1 1 auto;
@@ -279,8 +200,6 @@
}
@container (max-width: 560px) {
- .office-document-header,
- .office-toolbar,
.office-state-line {
padding: 7px;
}
diff --git a/plugins/_office/webui/office-store.js b/plugins/_office/webui/office-store.js
index ae6da3826..9eeae3bcf 100644
--- a/plugins/_office/webui/office-store.js
+++ b/plugins/_office/webui/office-store.js
@@ -1,15 +1,9 @@
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 { open as openSurface } from "/js/surfaces.js";
-const officeSocket = getNamespacedClient("/ws");
-officeSocket.addHandlers(["ws_webui"]);
-
const SAVE_MESSAGE_MS = 1800;
-const INPUT_PUSH_DELAY_MS = 650;
-const MAX_HISTORY = 80;
const DESKTOP_DOCUMENT_EXTENSIONS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx"]);
function currentContextId() {
@@ -31,39 +25,6 @@ function extensionOf(path = "") {
return index >= 0 ? name.slice(index + 1) : "";
}
-function parentPath(path = "") {
- const normalized = String(path || "").split("?")[0].split("#")[0].replace(/\/+$/, "");
- const index = normalized.lastIndexOf("/");
- if (index <= 0) return "/";
- return normalized.slice(0, index);
-}
-
-function uniqueTabId(session = {}) {
- return String(session.file_id || session.session_id || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`);
-}
-
-function editorContainsFocus(element) {
- const active = document.activeElement;
- return Boolean(element && active && (element === active || element.contains(active)));
-}
-
-function placeCaretAtEnd(element) {
- if (!element) return;
- if (element.tagName === "TEXTAREA" || element.tagName === "INPUT") {
- const length = element.value?.length || 0;
- element.selectionStart = length;
- element.selectionEnd = length;
- return;
- }
- const selection = globalThis.getSelection?.();
- const range = document.createRange?.();
- if (!selection || !range) return;
- range.selectNodeContents(element);
- range.collapse(false);
- selection.removeAllRanges();
- selection.addRange(range);
-}
-
function normalizeDocument(doc = {}) {
const path = doc.path || "";
const extension = String(doc.extension || extensionOf(path)).toLowerCase();
@@ -76,21 +37,6 @@ function normalizeDocument(doc = {}) {
};
}
-function normalizeSession(payload = {}) {
- const document = normalizeDocument(payload.document || payload);
- return {
- ...payload,
- document,
- extension: String(payload.extension || document.extension || "").toLowerCase(),
- file_id: payload.file_id || document.file_id || "",
- path: document.path || payload.path || "",
- title: payload.title || document.title || document.basename || basename(document.path),
- tab_id: uniqueTabId(payload),
- text: String(payload.text || ""),
- dirty: false,
- };
-}
-
function documentLabel(document = {}) {
return document.title || document.basename || basename(document.path);
}
@@ -103,56 +49,15 @@ async function callOffice(action, payload = {}) {
});
}
-async function requestOffice(eventType, payload = {}, timeoutMs = 5000) {
- const response = await officeSocket.request(eventType, {
- ctxid: currentContextId(),
- ...payload,
- }, { timeoutMs });
- const results = Array.isArray(response?.results) ? response.results : [];
- const first = results.find((item) => item?.ok === true && isOfficeSocketData(item?.data))
- || results.find((item) => item?.ok === true);
- if (!first) {
- const error = results.find((item) => item?.error)?.error;
- throw new Error(error?.error || error?.code || `${eventType} failed`);
- }
- if (first.data?.office_error) {
- const error = first.data.office_error;
- throw new Error(error.error || error.code || `${eventType} failed`);
- }
- return first.data || {};
-}
-
-function isOfficeSocketData(data) {
- if (!data || typeof data !== "object") return false;
- return (
- Object.prototype.hasOwnProperty.call(data, "office_error")
- || Object.prototype.hasOwnProperty.call(data, "ok")
- || Object.prototype.hasOwnProperty.call(data, "session_id")
- || Object.prototype.hasOwnProperty.call(data, "document")
- );
-}
-
const model = {
status: null,
- tabs: [],
- activeTabId: "",
- session: null,
loading: false,
- saving: false,
- dirty: false,
error: "",
message: "",
- editorText: "",
_root: null,
_mode: "modal",
_initialized: false,
_saveMessageTimer: null,
- _inputTimer: null,
- _history: [],
- _historyIndex: -1,
- _pendingFocus: false,
- _pendingFocusEnd: true,
- _focusAttempts: 0,
_headerCleanup: null,
async init() {
@@ -166,7 +71,6 @@ const model = {
if (element) this._root = element;
this._mode = options?.mode === "canvas" ? "canvas" : "modal";
if (this._mode === "modal") this.setupDocumentModal(element);
- this.queueRender();
},
async onOpen(payload = {}) {
@@ -182,12 +86,7 @@ const model = {
}
},
- beforeHostHidden() {
- this.flushInput();
- },
-
cleanup() {
- this.flushInput();
this._headerCleanup?.();
this._headerCleanup = null;
if (this._mode === "modal") this._root = null;
@@ -261,10 +160,8 @@ const model = {
await this.refresh();
return response;
}
- const session = normalizeSession(response);
- this.installSession(session);
await this.refresh();
- return session;
+ return response;
} catch (error) {
this.error = error instanceof Error ? error.message : String(error);
return null;
@@ -273,190 +170,6 @@ const model = {
}
},
- installSession(session) {
- const existingIndex = this.tabs.findIndex((tab) => (
- (session.file_id && tab.file_id === session.file_id)
- || (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;
- } else {
- this.tabs.push(session);
- this.activeTabId = session.tab_id;
- }
- this.selectTab(this.activeTabId);
- },
-
- selectTab(tabId, options = {}) {
- const tab = this.tabs.find((item) => item.tab_id === tabId) || this.tabs[0] || null;
- this.session = tab;
- this.activeTabId = tab?.tab_id || "";
- this.editorText = String(tab?.text || "");
- this.dirty = Boolean(tab?.dirty);
- this.resetHistory(this.editorText);
- this.queueRender({ focus: Boolean(tab) && options.focus !== false });
- },
-
- ensureActiveTab() {
- if (this.session && this.tabs.some((tab) => tab.tab_id === this.session.tab_id)) return;
- if (this.tabs.length) this.selectTab(this.tabs[0].tab_id, { focus: false });
- },
-
- isActiveTab(tab) {
- return Boolean(tab && tab.tab_id === this.activeTabId);
- },
-
- async closeTab(tabId) {
- const tab = this.tabs.find((item) => item.tab_id === tabId);
- if (!tab) return;
- if (tab.dirty || (this.isActiveTab(tab) && this.dirty)) {
- const shouldSave = globalThis.confirm?.("Save changes?") ?? true;
- if (shouldSave) await this.save();
- }
- try {
- if (tab.session_id) {
- await requestOffice("office_close", { session_id: tab.session_id }, 2500).catch(() => null);
- }
- await callOffice("close", {
- session_id: tab.store_session_id || "",
- file_id: tab.file_id || "",
- });
- } catch (error) {
- console.warn("Document close skipped", error);
- }
- this.tabs = this.tabs.filter((item) => item.tab_id !== tabId);
- if (this.activeTabId === tabId) {
- this.session = null;
- this.activeTabId = "";
- this.editorText = "";
- this.dirty = false;
- this.ensureActiveTab();
- }
- this.ensureActiveTab();
- await this.refresh();
- },
-
- async closeActiveFile() {
- if (!this.session || this.loading) return;
- await this.closeTab(this.session.tab_id);
- },
-
- async save() {
- if (!this.session || this.saving || !this.isMarkdown()) return;
- this.syncEditorText();
- this.saving = true;
- this.error = "";
- try {
- let response;
- const payload = { session_id: this.session.session_id, text: this.editorText };
- try {
- response = await requestOffice("office_save", payload, 10000);
- } catch (_socketError) {
- response = await callOffice("save", payload);
- }
- if (response?.ok === false) throw new Error(response.error || "Save failed.");
- const document = normalizeDocument(response.document || this.session.document || {});
- const updated = {
- ...this.session,
- text: this.editorText,
- dirty: false,
- document,
- path: document.path || this.session.path,
- file_id: document.file_id || this.session.file_id,
- version: document.version || response.version || this.session.version,
- };
- this.replaceActiveSession(updated);
- this.dirty = false;
- this.setMessage("Saved");
- await this.refresh();
- } catch (error) {
- this.error = error instanceof Error ? error.message : String(error);
- } finally {
- this.saving = false;
- }
- },
-
- async renameActiveFile() {
- if (!this.session || this.saving) return;
- const session = this.session;
- const path = session.path || session.document?.path || "";
- if (!path) {
- this.error = "This document does not have a file path to rename.";
- return;
- }
- const name = basename(path || session.title || "");
- const extension = extensionOf(name);
- await fileBrowserStore.openRenameModal(
- {
- name,
- path,
- is_dir: false,
- size: session.document?.size || 0,
- modified: session.document?.last_modified || "",
- type: "document",
- },
- {
- currentPath: parentPath(path),
- validateName: (newName) => {
- if (!extension) return true;
- return extensionOf(newName) === extension || `Keep the .${extension} extension for this open document.`;
- },
- performRename: async ({ path: renamedPath }) => {
- const payload = {
- file_id: session.file_id || "",
- path: renamedPath,
- };
- if (this.isMarkdown(session)) {
- this.syncEditorText();
- payload.text = this.session?.tab_id === session.tab_id ? this.editorText : session.text || "";
- }
- return await callOffice("renamed", payload);
- },
- onRenamed: async ({ path: renamedPath, response }) => {
- await this.handleActiveFileRenamed(session, renamedPath, response);
- },
- },
- );
- },
-
- async handleActiveFileRenamed(session, renamedPath, renameResponse = null) {
- const response = renameResponse || await callOffice("renamed", {
- file_id: session.file_id || "",
- path: renamedPath,
- });
- if (response?.ok === false) throw new Error(response.error || "Rename failed.");
-
- const document = normalizeDocument(response.document || session.document || {});
- const updated = {
- ...session,
- document,
- title: document.title || document.basename || basename(document.path),
- path: document.path || renamedPath,
- extension: document.extension || session.extension,
- file_id: document.file_id || session.file_id,
- version: document.version || response.version || session.version,
- text: this.session?.tab_id === session.tab_id ? this.editorText : session.text,
- dirty: false,
- };
- this.replaceSession(session, updated);
- this.dirty = false;
- this.setMessage("Renamed");
- await this.refresh();
- },
-
- replaceActiveSession(next) {
- if (!this.session) return;
- this.replaceSession(this.session, next);
- },
-
- replaceSession(previous, next) {
- this.session = next;
- const index = this.tabs.findIndex((tab) => tab.tab_id === (previous?.tab_id || next.tab_id));
- if (index >= 0) this.tabs.splice(index, 1, next);
- this.queueRender();
- },
-
setMessage(value) {
this.message = value;
if (this._saveMessageTimer) globalThis.clearTimeout(this._saveMessageTimer);
@@ -466,157 +179,11 @@ const model = {
}, SAVE_MESSAGE_MS);
},
- resetHistory(text) {
- this._history = [String(text || "")];
- this._historyIndex = 0;
- },
-
- pushHistory(text) {
- const value = String(text || "");
- if (this._history[this._historyIndex] === value) return;
- this._history = this._history.slice(0, this._historyIndex + 1);
- this._history.push(value);
- if (this._history.length > MAX_HISTORY) this._history.shift();
- this._historyIndex = this._history.length - 1;
- },
-
- undo() {
- if (this._historyIndex <= 0) return;
- this._historyIndex -= 1;
- this.applyEditorText(this._history[this._historyIndex], true);
- },
-
- redo() {
- if (this._historyIndex >= this._history.length - 1) return;
- this._historyIndex += 1;
- this.applyEditorText(this._history[this._historyIndex], true);
- },
-
- canUndo() {
- return this._historyIndex > 0;
- },
-
- canRedo() {
- return this._historyIndex < this._history.length - 1;
- },
-
- applyEditorText(text, markDirty = false) {
- this.editorText = String(text || "");
- if (this.session) {
- this.session.text = this.editorText;
- this.session.dirty = markDirty || this.session.dirty;
- }
- if (markDirty) this.markDirty();
- this.queueRender({ force: true, focus: true });
- },
-
- markDirty() {
- this.dirty = true;
- if (this.session) this.session.dirty = true;
- },
-
- onSourceInput() {
- this.markDirty();
- this.pushHistory(this.editorText);
- this.scheduleInputPush();
- },
-
- syncEditorText() {
- if (!this.session) return;
- this.session.text = this.editorText;
- },
-
- scheduleInputPush() {
- if (!this.session?.session_id || !this.isMarkdown()) return;
- if (this._inputTimer) globalThis.clearTimeout(this._inputTimer);
- this._inputTimer = globalThis.setTimeout(() => {
- this._inputTimer = null;
- this.flushInput();
- }, INPUT_PUSH_DELAY_MS);
- },
-
- flushInput() {
- if (!this.session?.session_id || !this.isMarkdown()) return;
- this.syncEditorText();
- requestOffice("office_input", {
- session_id: this.session.session_id,
- text: this.editorText,
- }, 3000).catch(() => {});
- },
-
- format(command) {
- if (!this.session || !this.isMarkdown()) return;
- const textarea = this._root?.querySelector?.("[data-office-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| | |";
- if (replacement === selected) return;
- this.editorText = `${this.editorText.slice(0, start)}${replacement}${this.editorText.slice(end)}`;
- this.onSourceInput();
- globalThis.requestAnimationFrame?.(() => {
- textarea.focus();
- textarea.selectionStart = start;
- textarea.selectionEnd = start + replacement.length;
- });
- },
-
- queueRender(options = {}) {
- if (options.focus) {
- this._pendingFocus = true;
- this._pendingFocusEnd = options.end !== false;
- this._focusAttempts = 0;
- }
- const render = () => {
- if (this._pendingFocus && this.focusEditor({ end: this._pendingFocusEnd })) {
- this._pendingFocus = false;
- this._focusAttempts = 0;
- } else if (this._pendingFocus && this._focusAttempts < 6) {
- this._focusAttempts += 1;
- globalThis.setTimeout(render, 45);
- }
- };
- if (globalThis.requestAnimationFrame) {
- globalThis.requestAnimationFrame(render);
- } else {
- globalThis.setTimeout(render, 0);
- }
- },
-
- focusEditor(options = {}) {
- if (!this.session || !this.isMarkdown()) return false;
- const source = this._root?.querySelector?.("[data-office-source]");
- if (!source) return false;
- source.focus?.({ preventScroll: true });
- if (!editorContainsFocus(source)) return false;
- if (options.end !== false) placeCaretAtEnd(source);
- return true;
- },
-
- isMarkdown(tab = this.session) {
- const ext = String(tab?.extension || tab?.document?.extension || "").toLowerCase();
- return ext === "md";
- },
-
- isDesktopDocument(tab = this.session) {
+ isDesktopDocument(tab = {}) {
const ext = String(tab?.extension || tab?.document?.extension || "").toLowerCase();
return DESKTOP_DOCUMENT_EXTENSIONS.has(ext);
},
- hasActiveFile(tab = this.session) {
- return Boolean(tab && this.isMarkdown(tab));
- },
-
- visibleTabs() {
- return this.tabs.filter((tab) => this.hasActiveFile(tab));
- },
-
defaultTitle(kind, fmt) {
const date = new Date().toISOString().slice(0, 10);
if (fmt === "md") return `Document ${date}`;
@@ -627,44 +194,9 @@ const model = {
return `Document ${date}`;
},
- tabTitle(tab = {}) {
- tab = tab || {};
- return tab.title || tab.document?.basename || basename(tab.path);
- },
-
- tabLabel(tab = {}) {
- tab = tab || {};
- const title = this.tabTitle(tab);
- return tab.dirty ? `${title} unsaved` : title;
- },
-
- tabIcon(tab = {}) {
- tab = tab || {};
- const ext = String(tab.extension || tab.document?.extension || "").toLowerCase();
- if (ext === "md") return "article";
- if (ext === "odt" || ext === "docx") return "description";
- if (ext === "ods" || ext === "xlsx") return "table_chart";
- if (ext === "odp" || ext === "pptx") return "co_present";
- return "draft";
- },
-
- async openActiveInDesktop() {
- const target = this.session?.document || this.session;
- if (!target?.path && !target?.file_id) return;
- await openSurface("desktop", {
- path: target.path || "",
- file_id: target.file_id || "",
- refresh: true,
- source: "office-explicit-action",
- });
- },
-
async runNewMenuAction(action = "") {
const normalized = String(action || "").trim().toLowerCase();
if (normalized === "open") return await this.openFileBrowser();
- if (normalized === "markdown") {
- return await openSurface("editor", { source: "office-editor-handoff" });
- }
if (normalized === "writer") return await this.create("document", "odt");
if (normalized === "spreadsheet") return await this.create("spreadsheet", "ods");
if (normalized === "presentation") return await this.create("presentation", "odp");
diff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.py
index 2f3b83027..3e7f1bf6d 100644
--- a/tests/test_office_canvas_setup.py
+++ b/tests/test_office_canvas_setup.py
@@ -222,13 +222,16 @@ def test_office_frontend_is_document_only_and_does_not_import_browser_or_desktop
assert "office-source-editor" not in office_panel
assert "data-office-source" not in office_panel
+ assert "office-document-header" not in office_panel
assert "runNewMenuAction('markdown')" not in office_panel
assert 'data-office-new-action="markdown"' not in office_store
- assert "openRenameModal" in office_store
- assert "office_save" in office_store
- assert 'callOffice("renamed"' in office_store
+ assert "openRenameModal" not in office_store
+ assert "office_save" not in office_store
+ assert 'callOffice("renamed"' not in office_store
+ assert "data-office-source" not in office_store
+ assert "office_input" not in office_store
assert "requires_desktop" in office_store
- assert "openSurface(\"desktop\"" in office_store
+ assert "openSurface(\"desktop\"" not in office_store
def test_desktop_plugin_owns_routes_runtime_surface_and_state_paths():
@@ -333,7 +336,7 @@ def test_document_artifacts_only_open_desktop_from_explicit_document_ui_requests
assert 'surfaces.open("desktop"' not in auto_open
assert "rightCanvas.open" not in auto_open
assert "globalThis.Alpine" not in auto_open
- assert "syncDocumentResultsIntoOpenOfficeModal" in auto_open
+ assert "syncDocumentResultsIntoOpenSurfaces" in auto_open
assert "isOfficeCanvas" not in auto_open
assert "officeStore" in auto_open
assert "desktopStore" in auto_open