fix(tree): stabilize filetree mindmap switching

Open filetree mindmap assets inside the primary document pane so the sidebar root is not rebuilt during rapid mindmap/page switching.

Keep filetree active rows on doc:<documentId> and asset:<mindmapId>, shorten generated mindmap filenames, and preserve legacy index rows only as compatibility input.

Add task438-task445 browser smokes and close the 4-27/4-38/4-39/4-40 tree-domain bug records.
This commit is contained in:
lix-2026
2026-05-16 07:11:06 +08:00
parent 01fdd2a8c3
commit 274779c0d8
15 changed files with 2128 additions and 155 deletions
+206 -14
View File
@@ -131,9 +131,15 @@ pub async fn document_page_shell(
load_sidebar_tree_html(state.config(), &context, &workspace_id, Some(&document_id))
.await
.unwrap_or_default(),
load_file_tree_html(state.config(), &context, &workspace_id, Some(&document_id))
.await
.unwrap_or_default(),
load_file_tree_html(
state.config(),
&context,
&workspace_id,
Some(&document_id),
None,
)
.await
.unwrap_or_default(),
)
};
let workspace_sidebar_html = render_workspace_shell_sidebar_html(
@@ -268,9 +274,8 @@ fn render_hermes_settings_config_script() -> String {
]
.into_iter()
.find_map(env_or_dotenv)
.map(|value| value.trim().trim_end_matches('/').to_string())
.filter(|value| !value.is_empty())
else {
.map(|value| value.trim().trim_end_matches('/').to_string())
.filter(|value| !value.is_empty()) else {
return String::new();
};
let settings_url = format!("{base_url}/hermes/settings");
@@ -438,6 +443,11 @@ pub(crate) fn render_document_title_controller_script() -> &'static str {
});
};
const fileTreePageTitle = (value) => {
const normalized = String(value || '无标题').trim() || '无标题';
return normalized.toLowerCase().endsWith('.md') ? normalized : `${normalized}.md`;
};
const updateVisibleTitle = (input, title, documentId) => {
const pane = input.closest('[data-document-pane="true"]');
const isPrimaryDocument = documentId && document.body?.dataset.documentId === documentId;
@@ -476,7 +486,7 @@ pub(crate) fn render_document_title_controller_script() -> &'static str {
const escapedId = cssEscape(documentId);
const escapedDocRowId = cssEscape(`doc:${documentId}`);
setText(`.tree-row[data-shell-mode="page"][data-node-id="${escapedId}"] > .tree-link > .tree-link-title`, title);
setText(`.tree-row[data-shell-mode="filetree"][data-row-id="${escapedDocRowId}"] > .tree-link > .tree-link-title`, title);
setText(`.tree-row[data-shell-mode="filetree"][data-row-id="${escapedDocRowId}"] > .tree-link > .tree-link-title`, fileTreePageTitle(title));
setText(`.wolai-page-row[data-node-id="${escapedId}"] > .wolai-row-title`, title);
setText(`a[href="/documents/${escapedId}"] > .wolai-row-title`, title);
setText(`a[href^="/documents/${escapedId}?"] > .wolai-row-title`, title);
@@ -1204,11 +1214,32 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
const documentSessionRegistry = new Map();
const localFolderEventRegistry = new Map();
const paneViewRegistry = new Map();
const mindmapPaneViewRegistry = new Map();
let nextViewId = 1;
const externalConflictMessage = '本地 Markdown 文件已在外部更新,请刷新或保存前先处理冲突';
const treeExternalConflictMessage = '当前页面已在其它窗口更新,请刷新或保存前先处理冲突';
const SESSION_RELEASE_DELAY_MS = 1200;
const unmountMindmapPane = (paneRole) => {
const view = mindmapPaneViewRegistry.get(paneRole);
if (!view) return;
mindmapPaneViewRegistry.delete(paneRole);
if (view.mountId != null && view.runtime && typeof view.runtime.unmount === 'function') {
try {
view.runtime.unmount(view.mountId);
} catch (error) {
console.warn('mnote mindmap pane unmount failed', error);
}
}
if (view.root instanceof HTMLElement) {
view.root.removeAttribute('data-runtime-mount-id');
view.root.removeAttribute('data-mnote-object-editor');
view.root.removeAttribute('data-mnote-object-identity');
view.root.removeAttribute('data-mnote-mindmap-id');
view.root.replaceChildren();
}
};
const parseLocalFolderEventPayload = (event) => {
try {
return JSON.parse(String(event?.data || '{}'));
@@ -1565,7 +1596,12 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
cache: 'no-store',
headers: { accept: 'application/json' },
});
if (!response.ok) return;
if (!response.ok) {
if (session.sourceKind === 'local_folder') {
markSessionExternalConflict(session, externalConflictMessage);
}
return;
}
const payload = await response.json();
const nextAggregate = payload?.result;
const nextBody = nextAggregate?.body || {};
@@ -1627,10 +1663,13 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
if (!payload) return;
Array.from(channel.sessions.values()).forEach((targetSession) => {
const documentId = typeof payload.documentId === 'string' ? payload.documentId.trim() : '';
if (documentId && documentId !== targetSession.documentId) return;
const eventKind = String(payload.eventKind || '');
const mayAffectMissingDocument = eventKind.includes('Remove') || eventKind.includes('Name');
const targetsCurrentDocument = Boolean(documentId && documentId === targetSession.documentId);
if (documentId && !targetsCurrentDocument && !mayAffectMissingDocument) return;
targetSession.lastExternalChangeSignalAt = Date.now();
targetSession.externalChangePending = true;
if (targetSession.hasExternalConflict || sessionHasRecentLocalInput(targetSession) || targetSession.dirty || targetSession.saveTimer || targetSession.saving) {
if (targetsCurrentDocument && (targetSession.hasExternalConflict || sessionHasRecentLocalInput(targetSession) || targetSession.dirty || targetSession.saveTimer || targetSession.saving)) {
markSessionExternalConflict(targetSession, externalConflictMessage);
return;
}
@@ -1897,6 +1936,8 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
});
if (runtimeDescriptor.paneRole === 'primary') {
document.body.dataset.documentId = documentId;
document.body.dataset.mnoteShell = 'document';
delete document.body.dataset.mindmapId;
document.title = title;
const topbarCurrent = document.querySelector('.wolai-breadcrumb-current [data-page-title-current]');
if (topbarCurrent instanceof HTMLElement) topbarCurrent.textContent = title;
@@ -1910,12 +1951,15 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
document.querySelectorAll(`.tree-row[data-node-id="${escapedId}"], .tree-row[data-document-id="${escapedId}"], .tree-row[data-doc-id="${escapedId}"]`).forEach((row) => {
if (!(row instanceof HTMLElement)) return;
if (row.getAttribute('data-shell-mode') === 'filetree') {
row.setAttribute('data-selected', String(row.getAttribute('data-row-id') === `index:${documentId}`));
row.setAttribute('data-selected', String(row.getAttribute('data-row-id') === `doc:${documentId}`));
} else {
row.setAttribute('data-active', 'true');
}
});
}
runtimeDescriptor.root.removeAttribute('data-mnote-object-editor');
runtimeDescriptor.root.removeAttribute('data-mnote-object-identity');
runtimeDescriptor.root.removeAttribute('data-mnote-mindmap-id');
};
const fetchPageAggregateForPane = async (descriptor) => {
@@ -1930,6 +1974,7 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
};
const replacePaneDocument = async (paneRole, descriptor, options = {}) => {
unmountMindmapPane(paneRole);
const runtime = await loadRuntime();
const root = document.querySelector(`${ROOT_SELECTOR}[data-pane-role="${paneRole}"]`);
const observability = document.querySelector(`[data-editor-host-observability][data-pane-role="${paneRole}"]`);
@@ -2028,6 +2073,123 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
replaceUrlState(url);
};
const parseJsonScriptFromDocument = (doc, id) => {
const node = doc?.getElementById?.(id);
if (!node) return null;
try {
return JSON.parse(node.textContent || 'null');
} catch (error) {
console.warn(`mnote mindmap shell JSON 解析失败: ${id}`, error);
return null;
}
};
const fetchMindmapShellBootstrap = async (url) => {
const response = await fetch(url.toString(), {
cache: 'no-store',
credentials: 'include',
headers: { accept: 'text/html' },
});
if (!response.ok) throw new Error(`mindmap_shell_failed_${response.status}`);
const html = await response.text();
const parsed = new DOMParser().parseFromString(html, 'text/html');
const bootstrap = parseJsonScriptFromDocument(parsed, '__MNOTE_MINDMAP_EDITOR_BOOTSTRAP__');
if (!bootstrap || typeof bootstrap !== 'object') throw new Error('mindmap_shell_missing_bootstrap');
const contract = parseJsonScriptFromDocument(parsed, '__MNOTE_MINDMAP_SHELL__') || {};
const title = String(bootstrap.title || parsed.querySelector('title')?.textContent || '思维导图').trim() || '思维导图';
return { bootstrap, contract, title };
};
const setPrimaryMindmapSelection = (documentId, mindmapId) => {
const cssEscape = window.CSS && typeof window.CSS.escape === 'function' ? window.CSS.escape : (value) => String(value).replace(/["\\]/g, '\\$&');
const escapedDocId = cssEscape(documentId);
const escapedMindmapId = cssEscape(mindmapId);
document.querySelectorAll('.tree-row[data-active="true"], .tree-row[data-selected="true"]').forEach((row) => {
if (!(row instanceof HTMLElement)) return;
row.setAttribute('data-active', 'false');
row.setAttribute('data-selected', 'false');
});
document.querySelectorAll(`.tree-row[data-shell-mode="page"][data-node-id="${escapedDocId}"]`).forEach((row) => {
if (row instanceof HTMLElement) row.setAttribute('data-active', 'true');
});
document.querySelectorAll(`.tree-row[data-shell-mode="filetree"][data-asset-id="${escapedMindmapId}"]`).forEach((row) => {
if (row instanceof HTMLElement) row.setAttribute('data-selected', 'true');
});
};
const updatePrimaryMindmapChrome = ({ documentId, mindmapId, workspaceId, title, root }) => {
const pane = root.closest('[data-document-pane="true"]');
if (pane instanceof HTMLElement) {
pane.setAttribute('data-pane-document-id', `__mindmap_object__:${documentId}:${mindmapId}`);
pane.setAttribute('data-pane-workspace-id', workspaceId || '');
pane.setAttribute('data-pane-visible', 'true');
pane.hidden = false;
}
const shell = root.closest('.document-shell');
if (shell instanceof HTMLElement) {
shell.setAttribute('data-editor-host', 'mindmap_object');
shell.setAttribute('data-document-id', documentId);
shell.setAttribute('data-workspace-id', workspaceId || '');
shell.setAttribute('data-mindmap-id', mindmapId);
}
document.body.dataset.documentId = documentId;
document.body.dataset.mindmapId = mindmapId;
document.body.dataset.mnoteShell = 'mindmap';
document.title = title;
document.querySelectorAll('[data-page-title-input="true"][data-pane-role="primary"]').forEach((node) => {
if (!(node instanceof HTMLTextAreaElement)) return;
node.value = title;
node.setAttribute('data-document-id', documentId);
node.setAttribute('data-workspace-id', workspaceId || '');
node.setAttribute('data-title-last-saved', title);
node.setAttribute('data-title-save-status', 'saved');
node.style.height = 'auto';
node.style.height = `${Math.max(48, node.scrollHeight)}px`;
});
document.querySelectorAll('[data-page-title-current="true"]').forEach((node) => {
if (node instanceof HTMLElement) node.textContent = title;
});
const topbarCurrent = document.querySelector('.wolai-breadcrumb-current [data-page-title-current]');
if (topbarCurrent instanceof HTMLElement) topbarCurrent.textContent = title;
root.setAttribute('data-mnote-object-editor', 'mindmap');
root.setAttribute('data-mnote-object-identity', `resource:mindmap:${documentId}:${mindmapId}`);
root.setAttribute('data-mnote-mindmap-id', mindmapId);
setPrimaryMindmapSelection(documentId, mindmapId);
};
const replacePrimaryPaneMindmap = async ({ documentId, mindmapId, workspaceId, url }) => {
const targetUrl = url instanceof URL
? url
: new URL(`/mindmap/${encodeURIComponent(documentId)}/${encodeURIComponent(mindmapId)}`, window.location.origin);
const root = document.querySelector(`${ROOT_SELECTOR}[data-pane-role="primary"]`);
const observability = document.querySelector('[data-editor-host-observability][data-pane-role="primary"]');
if (!(root instanceof HTMLElement)) throw new Error('primary_pane_root_missing');
const runtime = await loadRuntime();
const { bootstrap, title } = await fetchMindmapShellBootstrap(targetUrl);
const previousView = paneViewRegistry.get('primary');
if (previousView) {
unmountEditorViewBinding(previousView);
paneViewRegistry.delete('primary');
}
unmountMindmapPane('primary');
if (observability instanceof HTMLElement) {
observability.setAttribute('data-editor-host-active', 'mindmap_object');
observability.setAttribute('data-editor-host-status', 'mounting');
}
root.replaceChildren();
root.setAttribute('data-runtime-editor-status', 'booting');
updatePrimaryMindmapChrome({ documentId, mindmapId, workspaceId, title, root });
const mountId = runtime.mount(root, bootstrap);
root.setAttribute('data-runtime-mount-id', String(mountId));
root.setAttribute('data-editor-host-kind', 'mindmap_object');
if (observability instanceof HTMLElement) {
observability.setAttribute('data-editor-host-status', 'mounted');
}
mindmapPaneViewRegistry.set('primary', { paneRole: 'primary', root, runtime, mountId });
pushUrlState(targetUrl);
return true;
};
const handleSessionChange = (session, view, event) => {
const payload = normalizeEnvelopePayload(event);
if (!payload) return;
@@ -2221,6 +2383,18 @@ pub(crate) fn render_editor_island_adapter_script() -> &'static str {
updatePrimaryUrl(descriptor, url instanceof URL ? url : null);
return true;
},
openPrimaryMindmap: async ({ documentId, mindmapId, workspaceId, url } = {}) => {
const docId = typeof documentId === 'string' ? documentId.trim() : '';
const mapId = typeof mindmapId === 'string' ? mindmapId.trim() : '';
if (!docId || !mapId) return false;
await replacePrimaryPaneMindmap({
documentId: docId,
mindmapId: mapId,
workspaceId: typeof workspaceId === 'string' ? workspaceId.trim() : '',
url,
});
return true;
},
openSecondaryDocument: async ({ documentId, workspaceId, sourceKind, rootUri, url } = {}) => {
const id = typeof documentId === 'string' ? documentId.trim() : '';
if (!id) return false;
@@ -2610,6 +2784,7 @@ pub(crate) async fn load_file_tree_html(
context: &RequestContext,
workspace_id: &str,
active_document_id: Option<&str>,
active_row_id: Option<&str>,
) -> Option<String> {
let spec = ProjectionSnapshotSpec {
workspace_id,
@@ -2654,7 +2829,7 @@ pub(crate) async fn load_file_tree_html(
Err(_) => None,
};
result.map(|(projection, dev_fixture)| {
let rows = collect_filetree_render_rows(&projection, active_document_id);
let rows = collect_filetree_render_rows(&projection, active_document_id, active_row_id);
let html = render_initial_filetree_html(&FileTreeInitialRenderInput { rows });
mark_dev_fixture_html(html, dev_fixture, "file-tree")
})
@@ -2687,7 +2862,7 @@ pub(crate) fn render_local_file_tree_html(
active_document_id: Option<&str>,
) -> Result<String, WebError> {
let snapshot = load_local_folder_file_tree_snapshot(root_uri)?;
let rows = collect_filetree_render_rows(&snapshot.projection, active_document_id);
let rows = collect_filetree_render_rows(&snapshot.projection, active_document_id, None);
Ok(render_initial_filetree_html(&FileTreeInitialRenderInput {
rows,
}))
@@ -2806,6 +2981,15 @@ mod tests {
assert!(html.contains(
r#".tree-row[data-shell-mode="page"][data-node-id="' + escaped + '"] > .tree-link > .tree-link-title"#
));
assert!(html.contains("const fileTreePageTitle = (value) => {"));
assert!(html.contains(
"return normalized.toLowerCase().endsWith('.md') ? normalized : `${normalized}.md`;"
));
assert!(html.contains(
r#".tree-row[data-shell-mode="filetree"][data-row-id="${escapedDocRowId}"] > .tree-link > .tree-link-title`, fileTreePageTitle(title)"#
));
assert!(html.contains("row.getAttribute('data-row-id') === `doc:${documentId}`"));
assert!(!html.contains("row.getAttribute('data-row-id') === `index:${documentId}`"));
assert!(!html.contains("[data-node-id=\"${escapedId}\"] .tree-link-title"));
assert!(html.contains("data-testid=\"wolai-page-settings-trigger\""));
assert!(html.contains("data-mnote-action=\"open-page-settings\""));
@@ -2815,6 +2999,10 @@ mod tests {
assert!(html.contains("data-document-pane=\"true\""));
assert!(html.contains("data-pane-role=\"primary\""));
assert!(html.contains("data-document-pane-resizer=\"true\""));
assert!(html.contains("openPrimaryMindmap"));
assert!(html.contains("replacePrimaryPaneMindmap"));
assert!(html.contains("__MNOTE_MINDMAP_EDITOR_BOOTSTRAP__"));
assert!(html.contains("data-mnote-object-identity"));
assert!(html.contains("__MNOTE_DOCUMENT_PANES_BOOTSTRAP__"));
assert!(html.contains("__MNOTE_TREE_LIVE_BOOTSTRAP__"));
assert!(html.contains("mnote.tree_live_bootstrap.v1"));
@@ -2972,6 +3160,10 @@ mod tests {
assert!(html.contains("/api/local-folder/events"));
assert!(html.contains("new EventSource(url.toString())"));
assert!(html.contains("localFolderEventRegistry"));
assert!(html
.contains("if (!response.ok) {\n if (session.sourceKind === 'local_folder')"));
assert!(html.contains("mayAffectMissingDocument"));
assert!(html.contains("eventKind.includes('Remove') || eventKind.includes('Name')"));
assert!(html.contains("command: 'replaceContent'"));
assert!(html.contains("external-change-conflict"));
assert!(!html.contains(
@@ -3012,7 +3204,7 @@ mod tests {
let sidebar_html =
super::load_sidebar_tree_html(&config, &context, "ws_demo", Some("doc_1")).await;
let filetree_html =
super::load_file_tree_html(&config, &context, "ws_demo", Some("doc_1")).await;
super::load_file_tree_html(&config, &context, "ws_demo", Some("doc_1"), None).await;
let workspace_projection = super::load_workspace_shell_projection(
&config,
&context,