const root = document.getElementById("bds-shell-app"); const bootstrapNode = document.getElementById("bds-shell-bootstrap"); if (!root || !bootstrapNode) { throw new Error("Missing shell bootstrap payload"); } const SIDEBAR_STORAGE_KEY = "bds-panel-sidebar"; const ASSISTANT_STORAGE_KEY = "bds-panel-assistant-sidebar"; const TASK_STATUS_POLL_MS = 1500; const bootstrap = JSON.parse(bootstrapNode.textContent); const isMac = typeof navigator !== "undefined" && navigator.platform.toLowerCase().includes("mac"); const state = { session: hydrateSession(clone(bootstrap.session)), status: clone(bootstrap.status), projects: normalizeProjects(bootstrap.projects), projectMenuOpen: false, taskStatus: normalizeTaskStatus(bootstrap.task_status), outputEntries: [], gitLogEntries: [], uiLanguage: readStoredUiLanguage(bootstrap.i18n?.ui_language || bootstrap.status.right.ui_language), supportedUiLanguages: bootstrap.i18n?.supported_ui_languages || [], tabMeta: {}, }; bindNativeMenuBridge(); bindGlobalHotkeys(); scheduleTaskPolling(); void fetchProjects(); render(); function render() { root.style.setProperty("--sidebar-width", state.session.sidebar_visible ? `${state.session.sidebar_width}px` : "0px"); root.style.setProperty("--assistant-width", state.session.assistant_sidebar_visible ? `${state.session.assistant_sidebar_width}px` : "0px"); renderTitlebar(); renderActivityBar(); renderSidebar(); renderTabs(); renderEditor(); renderPanel(); renderAssistant(); renderStatusBar(); applyVisibility(); bindEvents(); } function renderTitlebar() { const menuBarClass = isMac ? "window-titlebar-menu-bar is-hidden" : "window-titlebar-menu-bar"; root.querySelector(".window-titlebar").innerHTML = `
${bootstrap.menu_groups .map((group) => ``) .join("")}
${escapeHtml(bootstrap.title)}
${renderTitlebarAction("toggle-sidebar", "toggle-sidebar", "Toggle sidebar", ` `)} ${renderTitlebarAction("toggle-panel", "toggle-panel", "Toggle panel", ` `)} ${renderTitlebarAction("toggle-assistant-sidebar", "toggle-assistant", "Toggle assistant", ` `)}
`; } function renderTitlebarAction(command, testId, label, iconMarkup) { return ` `; } function renderActivityBar() { const top = sidebarViews().filter((view) => view.activity_group === "top"); const bottom = sidebarViews().filter((view) => view.activity_group === "bottom"); root.querySelector(".activity-bar").innerHTML = `
${top.map(renderActivityButton).join("")}
${bottom.map(renderActivityButton).join("")}
`; } function renderActivityButton(view) { const active = state.session.sidebar_visible && state.session.active_view === view.id; return ` `; } function renderSidebar() { const view = currentSidebarView(); const data = currentSidebarData(); root.querySelector(".sidebar").innerHTML = ` `; } function renderSidebarItem(item, view) { const tabRef = currentTabRef(); const itemRoute = item.route || view.editor_route; const tabId = tabIdForItem(item, itemRoute); const active = tabRef && tabRef.type === itemRoute && tabRef.id === tabId; return ` `; } function renderTabs() { const tabs = state.session.tabs; const node = root.querySelector(".tab-bar"); if (tabs.length === 0) { node.innerHTML = `
Dashboard
`; return; } node.innerHTML = `
${tabs.map(renderTab).join("")}
`; } function renderTab(tab) { const active = sameTab(tab, currentTabRef()); const meta = tabMetadata(tab); return ` `; } function renderEditor() { const route = currentRoute(); const meta = currentEditorMeta(); const node = root.querySelector(".editor-shell"); node.innerHTML = `
${escapeHtml(routeLabel(route))}

${escapeHtml(editorTitle())}

${escapeHtml(editorSubtitle(route))}

${renderEditorBody(route)}
`; } function renderEditorBody(route) { const meta = currentTabMeta(); if (route === "dashboard") { const dashboard = bootstrap.content.dashboard; return `

Workbench Notes

`; } if (meta?.payload) { return renderCommandPayload(route, meta.payload); } const active = activeItem(); return `

${escapeHtml(active?.title || routeLabel(route))}

${escapeHtml(active?.meta || "Desktop workbench content routed through the Elixir shell.")}

`; } function renderPanel() { const tabs = panelTabs(); root.querySelector(".panel-shell").innerHTML = `
${tabs.map((tab) => renderPanelTab(tab)).join("")}
${renderPanelBody()}
`; } function renderPanelBody() { if (state.session.panel.active_tab === "tasks") { return renderTaskPanelEntries(); } if (state.session.panel.active_tab === "output") { return renderOutputEntries(); } if (state.session.panel.active_tab === "git_log") { return renderGitLogEntries(); } return `
${escapeHtml(routeLabel(state.session.panel.active_tab))} The shared lower panel is available for tasks, output, git details, and editor-specific diagnostics.
`; } function renderTaskPanelEntries() { if (!state.taskStatus.tasks.length) { return `
Tasks No background tasks running
`; } return `
${state.taskStatus.tasks.map((task) => renderTaskEntry(task)).join("")}
`; } function renderTaskEntry(task) { const progress = typeof task.progress === "number" ? `${Math.round(task.progress * 100)}%` : null; const statusDetail = [task.group_name, progress].filter(Boolean).join(" • "); const message = task.message || statusLabel(task.status); return `
${escapeHtml(task.name)} ${escapeHtml(statusLabel(task.status))}
${statusDetail ? `${escapeHtml(statusDetail)}` : ""} ${escapeHtml(message)}
`; } function renderOutputEntries() { if (!state.outputEntries.length) { return `
Output No shell output yet
`; } return `
${state.outputEntries .map( (entry) => `
${escapeHtml(entry.title)} ${escapeHtml(entry.message)} ${entry.details ? `
${escapeHtml(entry.details)}
` : ""}
` ) .join("")}
`; } function renderGitLogEntries() { return `
Git Log Working tree integration is not wired yet in the shell, but the tab is selectable and ready for command output.
`; } function renderAssistant() { root.querySelector(".assistant-sidebar").innerHTML = `
Assistant
${bootstrap.content.assistant_cards .map( (card) => `
${escapeHtml(card.label)} ${escapeHtml(card.text)}
` ) .join("")}
`; } function renderStatusBar() { const status = state.status; const taskOverflow = state.taskStatus.running_task_overflow; const taskMessage = state.taskStatus.running_task_message || "Idle"; root.querySelector(".status-bar").innerHTML = `
${renderProjectSelector()}
${escapeHtml(status.right.post_count)} ${escapeHtml(status.right.media_count)} ${escapeHtml(status.right.theme_badge)} ${escapeHtml(status.right.brand)}
`; } function applyVisibility() { root.querySelector(".sidebar-shell").classList.toggle("is-hidden", !state.session.sidebar_visible); root.querySelector(".assistant-sidebar-shell").classList.toggle("is-hidden", !state.session.assistant_sidebar_visible); root.querySelector(".panel-shell").classList.toggle("is-hidden", !state.session.panel.visible); } function bindEvents() { root.querySelectorAll("button[data-command]").forEach((button) => { button.onclick = () => { const command = button.dataset.command; if (command === "create-project") { void createProject(); return; } if (command === "open-tasks-panel") { openTasksPanel(); render(); return; } if (command === "toggle-offline-mode") { executeShellCommand("toggle_offline_mode"); return; } executeShellCommand(command.replace(/-/g, "_")); }; }); root.querySelectorAll("[data-project-menu-trigger]").forEach((button) => { button.onclick = (event) => { event.stopPropagation(); toggleProjectMenu(); }; }); root.querySelectorAll("[data-project-id]").forEach((button) => { button.onclick = () => { void selectProject(button.dataset.projectId); }; }); root.querySelectorAll("[data-project-create]").forEach((button) => { button.onclick = () => { void createProject(); }; }); root.querySelectorAll("[data-command='set-ui-language']").forEach((select) => { select.onchange = (event) => { setUiLanguage(event.target.value); render(); }; }); root.querySelectorAll("[data-activity]").forEach((button) => { button.onclick = () => { const next = button.dataset.activity; if (state.session.active_view === next && state.session.sidebar_visible) { state.session.sidebar_visible = false; } else { state.session.active_view = next; state.session.sidebar_visible = true; } render(); }; }); root.querySelectorAll("[data-open-tab]").forEach((button) => { button.onclick = () => { openTab(button.dataset.openRoute, button.dataset.openTab, button.dataset.openTitle, true); }; button.ondblclick = () => { openTab(button.dataset.openRoute, button.dataset.openTab, button.dataset.openTitle, false); }; }); root.querySelectorAll("[data-tab-id]").forEach((button) => { button.onclick = () => { state.session.active_tab = { type: button.dataset.tabType, id: button.dataset.tabId }; render(); }; }); root.querySelectorAll("[data-close-tab]").forEach((button) => { button.onclick = (event) => { event.stopPropagation(); const [type, id] = button.dataset.closeTab.split(":"); closeSpecificTab(type, id); render(); }; }); root.querySelectorAll("[data-panel-tab]").forEach((button) => { button.onclick = () => { state.session.panel.active_tab = button.dataset.panelTab; state.session.panel.visible = true; render(); }; }); bindResizeHandle("sidebar", { key: SIDEBAR_STORAGE_KEY, min: 200, max: 500, get: () => state.session.sidebar_width, set: (value) => { state.session.sidebar_width = value; state.session.sidebar_visible = true; }, }); bindResizeHandle("assistant", { key: ASSISTANT_STORAGE_KEY, min: 280, max: 640, get: () => state.session.assistant_sidebar_width, set: (value) => { state.session.assistant_sidebar_width = value; state.session.assistant_sidebar_visible = true; }, invert: true, }); bindProjectMenuDismiss(); } function bindNativeMenuBridge() { if (window.__BDS_NATIVE_MENU_BRIDGE__) { return; } window.__BDS_NATIVE_MENU_BRIDGE__ = true; window.addEventListener("bds:native-menu-action", (event) => { handleNativeMenuAction(event.detail?.action); }); } function bindGlobalHotkeys() { if (window.__BDS_KEYBOARD_BOUND__) { return; } window.__BDS_KEYBOARD_BOUND__ = true; window.addEventListener("keydown", (event) => { if (!(event.metaKey || event.ctrlKey) || event.altKey) { return; } if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLSelectElement) { return; } const key = event.key.toLowerCase(); let command = null; switch (key) { case "b": command = "toggle_sidebar"; break; case "j": command = "toggle_panel"; break; case "1": command = "view_posts"; break; case "2": command = "view_media"; break; case "\\": command = "toggle_assistant_sidebar"; break; case "w": command = "close_tab"; break; default: command = null; } if (!command) { return; } event.preventDefault(); executeShellCommand(command); }); } function scheduleTaskPolling() { window.setInterval(fetchTaskStatus, TASK_STATUS_POLL_MS); void fetchTaskStatus(); } async function fetchTaskStatus() { try { const response = await fetch("/api/tasks", { headers: { Accept: "application/json" }, cache: "no-store", }); if (!response.ok) { return; } const next = normalizeTaskStatus(await response.json()); if (JSON.stringify(next) === JSON.stringify(state.taskStatus)) { return; } state.taskStatus = next; state.status.left.running_task_message = next.running_task_message; state.status.left.running_task_overflow = next.running_task_overflow; render(); } catch (_error) { // Keep the shell usable if task polling is temporarily unavailable. } } async function fetchProjects() { try { const response = await fetch("/api/projects", { headers: { Accept: "application/json" }, cache: "no-store", }); if (!response.ok) { return; } state.projects = normalizeProjects(await response.json()); if (!state.projects.active_project_id && state.projects.projects.length) { state.projects.active_project_id = state.projects.projects[0].id; } render(); } catch (_error) { // Keep the shell usable if project loading is temporarily unavailable. } } async function createProject() { const name = window.prompt("New project name", "New Project"); if (!name || !name.trim()) { return; } closeProjectMenu(); try { const response = await fetch("/api/projects", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ name: name.trim() }), }); const payload = await response.json(); if (!response.ok || payload.status !== "ok") { appendOutputEntry("Create Project", payload.error?.message || `Command failed with HTTP ${response.status}`); setPanelTab("output"); render(); return; } await fetchProjects(); appendOutputEntry("Create Project", `Activated ${payload.project.name}`); render(); } catch (error) { appendOutputEntry("Create Project", error?.message || String(error)); setPanelTab("output"); render(); } } async function selectProject(projectId) { if (!projectId || projectId === state.projects.active_project_id) { closeProjectMenu(); return; } closeProjectMenu(); try { const response = await fetch("/api/projects", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ project_id: projectId }), }); const payload = await response.json(); if (!response.ok || payload.status !== "ok") { appendOutputEntry("Select Project", payload.error?.message || `Command failed with HTTP ${response.status}`); setPanelTab("output"); render(); return; } await fetchProjects(); appendOutputEntry("Select Project", `Activated ${payload.project.name}`); render(); } catch (error) { appendOutputEntry("Select Project", error?.message || String(error)); setPanelTab("output"); render(); } } function openTasksPanel() { state.session.panel.visible = true; state.session.panel.active_tab = "tasks"; } function handleNativeMenuAction(action) { executeShellCommand(action); } function executeShellCommand(action) { if (!action) { return; } if (executeLocalShellCommand(action)) { render(); return; } void executeBackendShellCommand(action); } function executeLocalShellCommand(action) { switch (action) { case "toggle_sidebar": state.session.sidebar_visible = !state.session.sidebar_visible; persistSessionWidths(); return true; case "toggle_panel": state.session.panel.visible = !state.session.panel.visible; if (state.session.panel.visible && !state.session.panel.active_tab) { state.session.panel.active_tab = "tasks"; } return true; case "toggle_assistant_sidebar": state.session.assistant_sidebar_visible = !state.session.assistant_sidebar_visible; persistSessionWidths(); return true; case "view_posts": state.session.active_view = "posts"; state.session.sidebar_visible = true; return true; case "view_media": state.session.active_view = "media"; state.session.sidebar_visible = true; return true; case "close_tab": closeActiveTab(); return true; case "edit_preferences": openSingletonTab("settings"); return true; case "edit_menu": openSingletonTab("menu_editor"); return true; case "documentation": openSingletonTab("documentation"); return true; case "api_documentation": openSingletonTab("api_documentation"); return true; case "regenerate_calendar": appendOutputEntry("Regenerate Calendar", "Calendar regeneration is not wired yet, but the base shell now surfaces the command and keeps the Output tab selectable."); setPanelTab("output"); return true; case "fill_missing_translations": appendOutputEntry("Fill Missing Translations", "Translation fill is not wired yet, but the command is now routed into Output instead of being ignored."); setPanelTab("output"); return true; case "toggle_offline_mode": state.status.right.offline_mode = !state.status.right.offline_mode; return true; default: return false; } } async function executeBackendShellCommand(action) { try { const response = await fetch("/api/commands", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ action }), }); if (!response.ok) { appendOutputEntry(routeLabel(action), `Command failed with HTTP ${response.status}`); setPanelTab("output"); render(); return; } const payload = await response.json(); if (payload.status !== "ok") { applyShellCommandError(action, payload.error || { message: "Unknown shell command error" }); return; } applyShellCommandResult(payload.result); } catch (error) { applyShellCommandError(action, { message: error?.message || String(error) }); } } function applyShellCommandResult(result) { if (!result) { return; } switch (result.kind) { case "task_queued": appendOutputEntry(result.title, result.message); setPanelTab(result.panel_tab || "tasks"); void fetchTaskStatus(); break; case "open_url": appendOutputEntry(result.title, result.url || result.message || "Opened URL"); setPanelTab("output"); if (result.url) { window.open(result.url, "_blank", "noopener"); } break; case "open_editor": openSingletonTab(result.route, { title: result.title, subtitle: result.subtitle, editorMeta: result.editorMeta, payload: result.payload, }); return; case "output": appendOutputEntry(result.title, result.message, result.details); setPanelTab(result.panel_tab || "output"); break; default: appendOutputEntry(routeLabel(result.action || "output"), result.message || "Command completed"); setPanelTab("output"); break; } render(); } function applyShellCommandError(action, error) { appendOutputEntry(routeLabel(action), error?.message || "Command failed"); setPanelTab("output"); render(); } function setPanelTab(tab) { state.session.panel.visible = true; state.session.panel.active_tab = tab; } function appendOutputEntry(title, message, details = "") { state.outputEntries = [{ title, message, details }, ...state.outputEntries].slice(0, 20); } function openSingletonTab(type, meta = {}) { openTab(type, type, meta.title || routeLabel(type), false, meta); } function closeActiveTab() { const active = currentTabRef(); if (!active) { return; } const index = state.session.tabs.findIndex((tab) => tab.type === active.type && tab.id === active.id); if (index < 0) { return; } state.session.tabs.splice(index, 1); if (state.session.tabs.length === 0) { state.session.active_tab = null; return; } if (index < state.session.tabs.length) { const next = state.session.tabs[index]; state.session.active_tab = { type: next.type, id: next.id }; } else { const next = state.session.tabs[state.session.tabs.length - 1]; state.session.active_tab = { type: next.type, id: next.id }; } } function closeSpecificTab(type, id) { const index = state.session.tabs.findIndex((tab) => tab.type === type && tab.id === id); if (index < 0) { return; } const wasActive = state.session.active_tab?.type === type && state.session.active_tab?.id === id; state.session.tabs.splice(index, 1); delete state.tabMeta[`${type}:${id}`]; if (!state.session.tabs.length) { state.session.active_tab = null; return; } if (!wasActive) { return; } const next = state.session.tabs[Math.min(index, state.session.tabs.length - 1)]; state.session.active_tab = { type: next.type, id: next.id }; } function openTab(type, id, title, transient, meta = {}) { const existingIndex = state.session.tabs.findIndex((tab) => tab.type === type && tab.id === id); if (existingIndex >= 0) { state.session.tabs[existingIndex].is_transient = transient ? state.session.tabs[existingIndex].is_transient : false; } else if (transient) { const transientIndex = state.session.tabs.findIndex((tab) => tab.type === type && tab.is_transient); const nextTab = { type, id, is_transient: true }; if (transientIndex >= 0) { state.session.tabs.splice(transientIndex, 1, nextTab); } else { state.session.tabs.push(nextTab); } } else { state.session.tabs.push({ type, id, is_transient: false }); } state.tabMeta[`${type}:${id}`] = { title, ...meta }; state.session.active_tab = { type, id }; render(); } function currentTabMeta() { const tab = currentTabRef(); return tab ? state.tabMeta[`${tab.type}:${tab.id}`] : null; } function activeItem() { const tab = currentTabRef(); if (!tab) { return null; } const sections = Object.values(bootstrap.content.sidebar).flatMap((view) => view.sections); return sections.flatMap((section) => section.items).find((item) => tabIdForItem(item, item.route) === tab.id) || null; } function tabMetadata(tab) { const lookup = state.tabMeta[`${tab.type}:${tab.id}`]; if (lookup) { return lookup; } const item = activeItem(); if (item && tab.id === tabIdForItem(item, item.route)) { return { title: item.title }; } return { title: routeLabel(tab.type) }; } function currentSidebarView() { return sidebarViews().find((view) => view.id === state.session.active_view) || sidebarViews()[0]; } function currentSidebarData() { return bootstrap.content.sidebar[state.session.active_view] || bootstrap.content.sidebar[bootstrap.registry.default_sidebar_view]; } function currentTabRef() { return state.session.active_tab; } function currentRoute() { return currentTabRef()?.type || "dashboard"; } function currentEditorMeta() { const meta = currentTabMeta(); return meta?.editorMeta || bootstrap.content.editor_meta[currentRoute()] || bootstrap.content.editor_meta.dashboard; } function editorTitle() { const meta = currentTabMeta(); if (meta?.title) { return meta.title; } const item = activeItem(); return item?.title || bootstrap.content.dashboard.title; } function editorSubtitle(route) { const meta = currentTabMeta(); if (meta?.subtitle) { return meta.subtitle; } if (route === "dashboard") { return bootstrap.content.dashboard.subtitle; } const item = activeItem(); return item?.meta || `${routeLabel(route)} content loaded through the desktop shell.`; } function routeLabel(route) { if (!route) { return "Dashboard"; } if (route === "output") { return "Output"; } if (route === "git_log") { return "Git Log"; } if (route === "open_in_browser") { return "Open in Browser"; } if (route === "open_data_folder") { return "Open Data Folder"; } if (route === "upload_site") { return "Upload Site"; } return ( bootstrap.registry.editor_routes.find((item) => item.id === route)?.title || sidebarViews().find((item) => item.id === route)?.label || titleCase(route) ); } function renderCommandPayload(route, payload) { switch (route) { case "metadata_diff": return `

Diff Reports

${renderKeyedEntries(payload.diff_reports, ["entity_type", "entity_id", "differences"])}

Orphan Reports

${renderKeyedEntries(payload.orphan_reports, ["entity_type", "path"])}
`; case "site_validation": return `

Missing Pages

${renderStringList(payload.missing_pages, "No missing pages")}

Extra Pages

${renderStringList(payload.extra_pages, "No extra pages")}

Stale Pages

${renderStringList(payload.stale_pages, "No stale pages")}
`; case "translation_validation": return `

Missing Translations

${renderKeyedEntries(payload.missing, ["post_id", "language"])}

Orphan Files

${renderStringList(payload.orphan_files, "No orphan translation files")}
`; case "find_duplicates": return `

Duplicate Candidates

${renderKeyedEntries(payload.pairs, ["title_a", "title_b", "score"])}
`; default: return `
${escapeHtml(JSON.stringify(payload, null, 2))}
`; } } function renderStringList(items, emptyMessage) { if (!items || !items.length) { return `

${escapeHtml(emptyMessage)}

`; } return ``; } function renderKeyedEntries(items, keys) { if (!items || !items.length) { return `

No items

`; } return `
${items .map((item) => `
${keys .filter((key) => item[key] !== undefined) .map((key) => `${escapeHtml(titleCase(key))}: ${escapeHtml(formatPayloadValue(item[key]))}`) .join("")}
`) .join("")}
`; } function formatPayloadValue(value) { if (Array.isArray(value)) { return value.map((entry) => formatPayloadValue(entry)).join(", "); } if (value && typeof value === "object") { return JSON.stringify(value); } return String(value); } function tabIdForItem(item, route) { if (route === "settings" || route === "tags") { return route; } return item.id; } function sidebarViews() { return bootstrap.registry.sidebar_views; } function sameTab(tab, ref) { return Boolean(ref) && tab.type === ref.type && tab.id === ref.id; } function uniqueValue(value, index, array) { return Boolean(value) && array.indexOf(value) === index; } function titleCase(value) { return value .split("_") .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) .join(" "); } function clone(value) { return JSON.parse(JSON.stringify(value)); } function hydrateSession(session) { const next = session; next.sidebar_width = readStoredSize(SIDEBAR_STORAGE_KEY, next.sidebar_width, 200, 500); next.assistant_sidebar_width = readStoredSize(ASSISTANT_STORAGE_KEY, next.assistant_sidebar_width, 280, 640); return next; } function bindResizeHandle(name, options) { const handle = root.querySelector(`[data-resize='${name}']`); if (!handle) { return; } handle.onmousedown = (event) => { event.preventDefault(); const startX = event.clientX; const startWidth = options.get(); const onMouseMove = (moveEvent) => { const delta = options.invert ? startX - moveEvent.clientX : moveEvent.clientX - startX; const width = clamp(startWidth + delta, options.min, options.max); options.set(width); persistSessionWidths(); render(); }; const onMouseUp = () => { window.removeEventListener("mousemove", onMouseMove); window.removeEventListener("mouseup", onMouseUp); }; window.addEventListener("mousemove", onMouseMove); window.addEventListener("mouseup", onMouseUp); }; } function persistSessionWidths() { localStorage.setItem(SIDEBAR_STORAGE_KEY, String(state.session.sidebar_width)); localStorage.setItem(ASSISTANT_STORAGE_KEY, String(state.session.assistant_sidebar_width)); } function readStoredSize(key, fallback, min, max) { const raw = localStorage.getItem(key); if (!raw) { return fallback; } const parsed = Number.parseInt(raw, 10); if (Number.isNaN(parsed)) { return fallback; } return clamp(parsed, min, max); } function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } function activityIcon(id) { const icons = { posts: '', pages: '', media: '', scripts: '', templates: '', tags: '', chat: '', import: '', git: '', settings: '', }; return icons[id] || icons.posts; } function tabIcon(type) { return activityIcon(type === "post" ? "posts" : type); } function normalizeTaskStatus(taskStatus) { return { active_count: taskStatus?.active_count || 0, running_count: taskStatus?.running_count || 0, pending_count: taskStatus?.pending_count || 0, running_task_message: taskStatus?.running_task_message || null, running_task_overflow: taskStatus?.running_task_overflow || 0, tasks: Array.isArray(taskStatus?.tasks) ? taskStatus.tasks : [], }; } function normalizeProjects(projectsPayload) { return { active_project_id: projectsPayload?.active_project_id || null, projects: Array.isArray(projectsPayload?.projects) ? projectsPayload.projects : [], }; } function panelTabs() { return ["tasks", state.session.panel.active_tab, "output", "git_log"].filter(uniqueValue); } function renderPanelTab(tab) { if (tab === "tasks") { return ``; } if (tab === "output") { return ``; } if (tab === "git_log") { return ``; } return ``; } function renderLanguageOptions() { return state.supportedUiLanguages .map((language) => { const selected = language.code === state.uiLanguage ? " selected" : ""; return ``; }) .join(""); } function renderProjectSelector() { const activeProject = currentProject(); return `
${state.projectMenuOpen ? renderProjectDropdown() : ""}
`; } function renderProjectDropdown() { return `
Projects
${state.projects.projects.map((project) => renderProjectItem(project)).join("")}
`; } function renderProjectItem(project) { const active = project.id === state.projects.active_project_id; return ` `; } function currentProject() { return state.projects.projects.find((project) => project.id === state.projects.active_project_id) || state.projects.projects[0] || null; } function toggleProjectMenu() { state.projectMenuOpen = !state.projectMenuOpen; render(); } function closeProjectMenu() { if (!state.projectMenuOpen) { return; } state.projectMenuOpen = false; render(); } function bindProjectMenuDismiss() { if (window.__BDS_PROJECT_MENU_DISMISS_BOUND__) { return; } window.__BDS_PROJECT_MENU_DISMISS_BOUND__ = true; document.addEventListener("mousedown", (event) => { if (!state.projectMenuOpen) { return; } const selector = root.querySelector(".project-selector"); if (selector && !selector.contains(event.target)) { closeProjectMenu(); } }); } function setUiLanguage(nextLanguage) { state.uiLanguage = nextLanguage; state.status.right.ui_language = nextLanguage; localStorage.setItem("bds-ui-language", nextLanguage); } function readStoredUiLanguage(fallback) { const stored = localStorage.getItem("bds-ui-language"); return stored || fallback || "en"; } function statusLabel(status) { switch (status) { case "running": return "Running"; case "pending": return "Queued"; default: return titleCase(status || "task"); } } function escapeHtml(value) { return String(value) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); } function escapeHtmlAttribute(value) { return escapeHtml(value).replaceAll("`", "`"); }