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), sidebarContent: clone(bootstrap.content.sidebar), sidebarFilters: hydrateSidebarFilters(bootstrap.content.sidebar), projectMenuOpen: false, taskStatus: normalizeTaskStatus(bootstrap.task_status), handledTaskResults: {}, outputEntries: [], gitLogEntries: [], uiLanguage: readStoredUiLanguage(bootstrap.i18n?.ui_language || bootstrap.status.right.ui_language), supportedUiLanguages: bootstrap.i18n?.supported_ui_languages || [], tabMeta: {}, }; function translationsForLanguage(language) { return bootstrap.i18n?.catalogs?.[language] || bootstrap.i18n?.catalogs?.en || {}; } function t(key, bindings = {}) { const catalog = translationsForLanguage(state.uiLanguage); let text = catalog[key] || key; Object.entries(bindings).forEach(([binding, value]) => { text = text.replaceAll(`%{${binding}}`, String(value)); }); return text; } function tText(value, bindings = {}) { return t(String(value), bindings); } 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", t("Toggle sidebar"), ` `)} ${renderTitlebarAction("toggle-panel", "toggle-panel", t("Toggle panel"), ` `)} ${renderTitlebarAction("toggle-assistant-sidebar", "toggle-assistant", t("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(); const filterState = currentSidebarFilterState(view.id); root.querySelector(".sidebar").innerHTML = ` ${renderSidebarSearchBox(data, view, filterState)} ${renderSidebarFilterPanel(data, view, filterState)} ${renderSidebarFilterStatus(data, view, filterState)} ${renderSidebarLoadMore(data, view)} `; } function renderSidebarSearchBox(data, view, filterState) { if (!data.filters?.enabled) { return ""; } return ` `; } function renderSidebarFilterPanel(data, view, filterState) { if (!data.filters?.enabled || !filterState.showFilters) { return ""; } return ` ${renderSidebarArchiveFilter(data, view, filterState)} ${renderSidebarFilterChips(data, view, filterState)} `; } function renderSidebarArchiveFilter(data, view, filterState) { const entries = Array.isArray(data.filters?.year_month_counts) ? data.filters.year_month_counts : []; const years = groupSidebarYearMonths(entries); return `
${(filterState.year || filterState.month) ? `` : ""} ${filterState.archiveCollapsed ? "" : `
${years .map( (yearEntry) => `
${filterState.expandedYear === yearEntry.year ? `
${yearEntry.months .map( (monthEntry) => ` ` ) .join("")}
` : ""}
` ) .join("")}
`}
`; } function renderSidebarFilterChips(data, view, filterState) { const tags = Array.isArray(data.filters?.available_tags) ? data.filters.available_tags : []; const categories = Array.isArray(data.filters?.available_categories) ? data.filters.available_categories : []; return `
${tags.length ? `
${filterState.tagsCollapsed ? "" : `
${tags .map( (tag) => ` ` ) .join("")}
`}
` : ""} ${categories.length ? `
${filterState.categoriesCollapsed ? "" : `
${categories .map( (category) => ` ` ) .join("")}
`}
` : ""}
`; } function renderSidebarFilterStatus(data, view, filterState) { if (!data.filters?.enabled || !data.filters.has_active_filters) { return ""; } const count = Number(data.filters.total_count) || 0; const label = filterState.search ? t(data.filters.results_for_label, { count, query: filterState.search }) : t(data.filters.results_label, { count }); return `
${escapeHtml(label)}
`; } function renderSidebarLoadMore(data, view) { if (!data.filters?.enabled || !data.filters.has_more) { return ""; } return ` `; } function renderSidebarBody(data, view) { switch (data.layout) { case "post_list": return renderSidebarPostList(data, view); case "media_grid": return renderSidebarMediaGrid(data, view); case "entity_list": return renderSidebarEntityList(data, view); case "nav_list": return renderSidebarNavList(data, view); default: return (data.sections || []) .map( (section) => ` ` ) .join(""); } } function renderSidebarPostList(data, view) { const sections = Array.isArray(data.sections) ? data.sections : []; const hasItems = sections.some((section) => (section.items || []).length > 0); return ` ${sections .map( (section) => ` ` ) .join("")} ${hasItems ? "" : renderSidebarEmpty(data.empty_message || "No items")} `; } function renderSidebarPostItem(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; const postType = getSidebarPostType(item.categories || []); const languageBadge = Number(item.language_count) > 1 ? `${escapeHtml(String(item.language_count))}` : ""; return ` `; } function renderSidebarMediaGrid(data, view) { const items = Array.isArray(data.items) ? data.items : []; if (!items.length) { return renderSidebarEmpty(data.empty_message || "No items"); } return ` `; } function renderSidebarMediaItem(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 renderSidebarEntityList(data, view) { const items = Array.isArray(data.items) ? data.items : []; if (!items.length) { return renderSidebarEmpty(data.empty_message || "No items"); } return items.map((item) => renderSidebarEntityItem(item, view)).join(""); } function renderSidebarEntityItem(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; const meta = item.updated_at ? formatSidebarRelativeDateMs(item.updated_at) : tText(item.meta || ""); return ` `; } function renderSidebarNavList(data, view) { const items = Array.isArray(data.items) ? data.items : []; return `
${items.map((item) => renderSidebarNavItem(item, view)).join("")}
`; } function renderSidebarNavItem(item, view) { const itemRoute = item.route || view.editor_route; const tabId = tabIdForItem(item, itemRoute); const tabTitle = routeLabel(itemRoute); return ` `; } function renderSidebarEmpty(message) { return ` `; } function groupSidebarYearMonths(entries) { const years = new Map(); entries.forEach((entry) => { const year = Number(entry.year); const month = Number(entry.month); const count = Number(entry.count) || 0; if (!years.has(year)) { years.set(year, { year, count: 0, months: [] }); } const yearEntry = years.get(year); yearEntry.count += count; yearEntry.months.push({ month, count }); }); return Array.from(years.values()) .map((yearEntry) => ({ ...yearEntry, months: yearEntry.months.sort((left, right) => right.month - left.month), })) .sort((left, right) => right.year - left.year); } function hydrateSidebarFilters(sidebarContent) { return Object.fromEntries( Object.entries(sidebarContent || {}).map(([viewId, data]) => [viewId, defaultSidebarFilterState(viewId, data)]) ); } function defaultSidebarFilterState(viewId, data) { const selected = data?.filters?.selected || {}; return { search: selected.search || "", year: selected.year || null, month: selected.month || null, tags: Array.isArray(selected.tags) ? [...selected.tags] : [], categories: Array.isArray(selected.categories) ? [...selected.categories] : [], showFilters: false, archiveCollapsed: true, tagsCollapsed: true, categoriesCollapsed: true, expandedYear: selected.year || null, displayLimit: data?.filters?.display_limit || data?.filters?.max_items || 500, }; } function currentSidebarFilterState(viewId) { if (!state.sidebarFilters[viewId]) { state.sidebarFilters[viewId] = defaultSidebarFilterState(viewId, state.sidebarContent[viewId]); } return state.sidebarFilters[viewId]; } function applySidebarPostFilters(viewId) { void refreshSidebarView(viewId); } function applySidebarMediaFilters(viewId) { void refreshSidebarView(viewId); } async function refreshSidebarView(viewId) { try { const filterState = currentSidebarFilterState(viewId); const response = await fetch("/api/sidebar", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ view: viewId, filters: { search: filterState.search, year: filterState.year, month: filterState.month, tags: filterState.tags, categories: filterState.categories, display_limit: filterState.displayLimit, }, }), }); if (!response.ok) { return; } const payload = await response.json(); if (payload.status !== "ok") { return; } state.sidebarContent[viewId] = payload.data; state.sidebarFilters[viewId] = { ...filterState, displayLimit: payload.data?.filters?.display_limit || filterState.displayLimit, }; render(); } catch (_error) { // Keep the shell usable if sidebar filtering is temporarily unavailable. } } function renderTabs() { const tabs = state.session.tabs; const node = root.querySelector(".tab-bar"); if (tabs.length === 0) { node.innerHTML = `
${escapeHtml(t("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 node = root.querySelector(".editor-shell"); if (route === "dashboard") { node.innerHTML = renderDashboard(); return; } const meta = currentEditorMeta(); node.innerHTML = `
${escapeHtml(routeLabel(route))}

${escapeHtml(editorTitle())}

${escapeHtml(editorSubtitle(route))}

${renderEditorBody(route)}
`; } function renderDashboard() { const dashboard = bootstrap.content.dashboard || {}; const postStats = dashboard.post_stats || {}; const mediaStats = dashboard.media_stats || {}; const timelineEntries = Array.isArray(dashboard.timeline_entries) ? dashboard.timeline_entries : []; const tagCloudItems = buildDashboardTagCloudItems(dashboard.tag_cloud_items || []); const categoryCounts = Array.isArray(dashboard.category_counts) ? dashboard.category_counts : []; const recentPosts = Array.isArray(dashboard.recent_posts) ? dashboard.recent_posts : []; const meta = currentEditorMeta(); const maxCount = Math.max(1, ...timelineEntries.map((entry) => Number(entry.count) || 0)); return `

${escapeHtml(t("dashboard.title"))}

${escapeHtml(t("dashboard.subtitle"))}

${escapeHtml(String(postStats.total_posts || 0))}
${escapeHtml(t("dashboard.stats.totalPosts"))}
${escapeHtml(t("dashboard.stats.published", { count: postStats.published_count || 0 }))} ${escapeHtml(t("dashboard.stats.drafts", { count: postStats.draft_count || 0 }))} ${(postStats.archived_count || 0) > 0 ? `${escapeHtml(t("dashboard.stats.archived", { count: postStats.archived_count || 0 }))}` : ""}
${escapeHtml(String(mediaStats.media_count || 0))}
${escapeHtml(t("dashboard.stats.mediaFiles"))}
${escapeHtml(t("dashboard.stats.images", { count: mediaStats.image_count || 0 }))} ${escapeHtml(formatBytes(mediaStats.total_bytes || 0))}
${escapeHtml(String((dashboard.tag_cloud_items || []).length))}
${escapeHtml(t("dashboard.stats.tags"))}
${escapeHtml(t("dashboard.stats.categories", { count: categoryCounts.length }))}
${timelineEntries.length ? `

${escapeHtml(t("dashboard.section.postsOverTime"))}

${timelineEntries .map( (entry) => `
${escapeHtml(String(entry.count || 0))}
${escapeHtml(formatDashboardMonth(entry.year, entry.month))} ${escapeHtml(String(entry.year || ""))}
` ) .join("")}
` : ""} ${tagCloudItems.length ? `

${escapeHtml(t("dashboard.section.tags"))}

${tagCloudItems .map((item) => `${escapeHtml(item.tag)}`) .join("")} ${(dashboard.tag_cloud_items || []).length > 40 ? `${escapeHtml(t("dashboard.tagCloud.more", { count: (dashboard.tag_cloud_items || []).length - 40 }))}` : ""}
` : ""} ${categoryCounts.length ? `

${escapeHtml(t("dashboard.section.categories"))}

${categoryCounts .map( (category) => ` ${escapeHtml(category.category || "")} ${escapeHtml(String(category.count || 0))} ` ) .join("")}
` : ""} ${recentPosts.length ? `

${escapeHtml(t("dashboard.section.recentlyUpdated"))}

${recentPosts .map( (post) => `
` : ""}
`; } function renderEditorBody(route) { const meta = currentTabMeta(); if (meta?.payload) { return renderCommandPayload(route, meta.payload); } const active = activeItem(); return `

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

${escapeHtml(tText(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))} ${escapeHtml(t("The shared lower panel is available for tasks, output, git details, and editor-specific diagnostics."))}
`; } function renderTaskPanelEntries() { if (!state.taskStatus.tasks.length) { return `
${escapeHtml(t("Tasks"))} ${escapeHtml(t("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 `
${escapeHtml(t("Output"))} ${escapeHtml(t("No shell output yet"))}
`; } return `
${state.outputEntries .map( (entry) => `
${escapeHtml(entry.title)} ${escapeHtml(entry.message)} ${entry.details ? `
${escapeHtml(entry.details)}
` : ""}
` ) .join("")}
`; } function renderGitLogEntries() { return `
${escapeHtml(t("Git Log"))} ${escapeHtml(t("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 = `
${escapeHtml(t("Assistant"))}
${bootstrap.content.assistant_cards .map( (card) => `
${escapeHtml(tText(card.label))} ${escapeHtml(tText(card.text))}
` ) .join("")}
`; } function renderStatusBar() { const status = state.status; const taskOverflow = state.taskStatus.running_task_overflow; const taskMessage = state.taskStatus.running_task_message || t("Idle"); const postCount = status.right.post_count_value ?? status.right.post_count; const mediaCount = status.right.media_count_value ?? status.right.media_count; root.querySelector(".status-bar").innerHTML = `
${renderProjectSelector()}
${escapeHtml(typeof postCount === "number" ? t("%{count} posts", { count: postCount }) : tText(postCount))} ${escapeHtml(typeof mediaCount === "number" ? t("%{count} media", { count: mediaCount }) : tText(mediaCount))} ${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-project-import]").forEach((button) => { button.onclick = () => { void importExistingProject(); }; }); 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-sidebar-toggle-filters]").forEach((button) => { button.onclick = () => { const viewId = button.dataset.sidebarToggleFilters; const filterState = currentSidebarFilterState(viewId); filterState.showFilters = !filterState.showFilters; render(); }; }); root.querySelectorAll("form[data-sidebar-search]").forEach((form) => { form.onsubmit = (event) => { event.preventDefault(); const viewId = form.dataset.sidebarSearch; const input = form.querySelector("input[data-sidebar-search-input]"); const filterState = currentSidebarFilterState(viewId); filterState.search = input?.value?.trim() || ""; filterState.displayLimit = state.sidebarContent[viewId]?.filters?.max_items || filterState.displayLimit; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); root.querySelectorAll("[data-sidebar-clear-search]").forEach((button) => { button.onclick = () => { const viewId = button.dataset.sidebarClearSearch; const filterState = currentSidebarFilterState(viewId); filterState.search = ""; filterState.displayLimit = state.sidebarContent[viewId]?.filters?.max_items || filterState.displayLimit; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); root.querySelectorAll("[data-sidebar-toggle-collapse]").forEach((button) => { button.onclick = () => { const [viewId, section] = button.dataset.sidebarToggleCollapse.split(":"); const filterState = currentSidebarFilterState(viewId); if (section === "archive") { filterState.archiveCollapsed = !filterState.archiveCollapsed; } if (section === "tags") { filterState.tagsCollapsed = !filterState.tagsCollapsed; } if (section === "categories") { filterState.categoriesCollapsed = !filterState.categoriesCollapsed; } render(); }; }); root.querySelectorAll("[data-sidebar-year]").forEach((button) => { button.onclick = () => { const [viewId, year] = button.dataset.sidebarYear.split(":"); const filterState = currentSidebarFilterState(viewId); const nextYear = Number.parseInt(year, 10); filterState.expandedYear = filterState.expandedYear === nextYear ? null : nextYear; filterState.year = nextYear; filterState.month = null; filterState.displayLimit = state.sidebarContent[viewId]?.filters?.max_items || filterState.displayLimit; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); root.querySelectorAll("[data-sidebar-month]").forEach((button) => { button.onclick = () => { const [viewId, year, month] = button.dataset.sidebarMonth.split(":"); const filterState = currentSidebarFilterState(viewId); filterState.year = Number.parseInt(year, 10); filterState.month = Number.parseInt(month, 10); filterState.expandedYear = filterState.year; filterState.displayLimit = state.sidebarContent[viewId]?.filters?.max_items || filterState.displayLimit; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); root.querySelectorAll("[data-sidebar-clear-date]").forEach((button) => { button.onclick = () => { const viewId = button.dataset.sidebarClearDate; const filterState = currentSidebarFilterState(viewId); filterState.year = null; filterState.month = null; filterState.expandedYear = null; filterState.displayLimit = state.sidebarContent[viewId]?.filters?.max_items || filterState.displayLimit; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); root.querySelectorAll("[data-sidebar-tag]").forEach((button) => { button.onclick = () => { const [viewId, tag] = button.dataset.sidebarTag.split(":"); const filterState = currentSidebarFilterState(viewId); filterState.tags = toggleSidebarFilterValue(filterState.tags, tag); filterState.displayLimit = state.sidebarContent[viewId]?.filters?.max_items || filterState.displayLimit; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); root.querySelectorAll("[data-sidebar-category]").forEach((button) => { button.onclick = () => { const [viewId, category] = button.dataset.sidebarCategory.split(":"); const filterState = currentSidebarFilterState(viewId); filterState.categories = toggleSidebarFilterValue(filterState.categories, category); filterState.displayLimit = state.sidebarContent[viewId]?.filters?.max_items || filterState.displayLimit; applySidebarPostFilters(viewId); }; }); root.querySelectorAll("[data-sidebar-clear-filters]").forEach((button) => { button.onclick = () => { const viewId = button.dataset.sidebarClearFilters; const existing = currentSidebarFilterState(viewId); state.sidebarFilters[viewId] = { ...defaultSidebarFilterState(viewId, state.sidebarContent[viewId]), showFilters: existing.showFilters, archiveCollapsed: existing.archiveCollapsed, tagsCollapsed: existing.tagsCollapsed, categoriesCollapsed: existing.categoriesCollapsed, }; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); root.querySelectorAll("[data-sidebar-load-more]").forEach((button) => { button.onclick = () => { const viewId = button.dataset.sidebarLoadMore; const filterState = currentSidebarFilterState(viewId); filterState.displayLimit += state.sidebarContent[viewId]?.filters?.max_items || 500; if (viewId === "media") { applySidebarMediaFilters(viewId); } else { applySidebarPostFilters(viewId); } }; }); 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; applyCompletedTaskResults(next.tasks); render(); } catch (_error) { // Keep the shell usable if task polling is temporarily unavailable. } } function applyCompletedTaskResults(tasks) { pruneHandledTaskResults(tasks); tasks.forEach((task) => { if (task.status !== "completed" || state.handledTaskResults[task.id]) { return; } if (!task.result || typeof task.result !== "object" || typeof task.result.kind !== "string") { return; } state.handledTaskResults[task.id] = true; applyShellCommandResult(task.result); }); } function pruneHandledTaskResults(tasks) { const visibleTaskIds = new Set(tasks.map((task) => task.id)); Object.keys(state.handledTaskResults).forEach((taskId) => { if (!visibleTaskIds.has(taskId)) { delete state.handledTaskResults[taskId]; } }); } 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 chooseProjectFolder() { try { const response = await fetch("/api/project-folder", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ prompt: t("Select existing blog folder") }), }); const payload = await response.json(); if (!response.ok || payload.status === "error") { appendOutputEntry(t("Open Existing Blog"), payload.error?.message || t("Command failed with HTTP %{status}", { status: response.status })); setPanelTab("output"); render(); return null; } if (payload.status === "cancel") { return null; } return payload; } catch (error) { appendOutputEntry(t("Open Existing Blog"), error?.message || String(error)); setPanelTab("output"); render(); return null; } } async function createProject(options = {}) { const suggestedName = options.name ? String(options.name).trim() : ""; const name = suggestedName || window.prompt(t("New project name"), t("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(), description: options.description, data_path: options.dataPath, }), }); const payload = await response.json(); if (!response.ok || payload.status !== "ok") { appendOutputEntry(t("Create Project"), payload.error?.message || t("Command failed with HTTP %{status}", { status: response.status })); setPanelTab("output"); render(); return; } await fetchProjects(); appendOutputEntry(t("Create Project"), t("Activated %{name}", { name: payload.project.name })); render(); } catch (error) { appendOutputEntry(t("Create Project"), error?.message || String(error)); setPanelTab("output"); render(); } } async function importExistingProject() { closeProjectMenu(); const selection = await chooseProjectFolder(); if (!selection) { return; } if (selection.existing_project_id) { await selectProject(selection.existing_project_id); return; } await createProject({ name: selection.name, description: selection.description, dataPath: selection.path, }); } 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(t("Select Project"), payload.error?.message || t("Command failed with HTTP %{status}", { status: response.status })); setPanelTab("output"); render(); return; } await fetchProjects(); appendOutputEntry(t("Select Project"), t("Activated %{name}", { name: payload.project.name })); render(); } catch (error) { appendOutputEntry(t("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(t("Regenerate Calendar"), t("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(t("Fill Missing Translations"), t("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), t("Command failed with HTTP %{status}", { status: 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(tText(result.title), tText(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(tText(result.title), tText(result.message), result.details); setPanelTab(result.panel_tab || "output"); break; default: appendOutputEntry(routeLabel(result.action || "output"), tText(result.message || "Command completed")); setPanelTab("output"); break; } render(); } function applyShellCommandError(action, error) { appendOutputEntry(routeLabel(action), error?.message || t("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 items = Object.values(state.sidebarContent).flatMap(flattenSidebarItems); return items.find((item) => item.route === tab.type && tabIdForItem(item, item.route) === tab.id) || null; } function flattenSidebarItems(view) { if (Array.isArray(view.sections)) { return view.sections.flatMap((section) => section.items || []); } return Array.isArray(view.items) ? view.items : []; } 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: tText(item.title) }; } return { title: routeLabel(tab.type) }; } function currentSidebarView() { return sidebarViews().find((view) => view.id === state.session.active_view) || sidebarViews()[0]; } function currentSidebarData() { return state.sidebarContent[state.session.active_view] || state.sidebarContent[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 tText(meta.title); } const item = activeItem(); return tText(item?.title || bootstrap.content.dashboard.title); } function editorSubtitle(route) { const meta = currentTabMeta(); if (meta?.subtitle) { return tText(meta.subtitle); } if (route === "dashboard") { return tText(bootstrap.content.dashboard.subtitle); } const item = activeItem(); return tText(item?.meta || "Desktop workbench content routed through the Elixir shell."); } function routeLabel(route) { if (!route) { return t("Dashboard"); } if (route === "output") { return t("Output"); } if (route === "git_log") { return t("Git Log"); } if (route === "open_in_browser") { return t("Open in Browser"); } if (route === "open_data_folder") { return t("Open Data Folder"); } if (route === "upload_site") { return t("Upload Site"); } return tText( 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 `

${escapeHtml(t("Diff Reports"))}

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

${escapeHtml(t("Orphan Reports"))}

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

${escapeHtml(t("Missing Pages"))}

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

${escapeHtml(t("Extra Pages"))}

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

${escapeHtml(t("Stale Pages"))}

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

${escapeHtml(t("Missing Translations"))}

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

${escapeHtml(t("Orphan Files"))}

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

${escapeHtml(t("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 `

${escapeHtml(t("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" || route === "style") { return route; } return item.id; } function toggleSidebarFilterValue(values, value) { return values.includes(value) ? values.filter((entry) => entry !== value) : [...values, value]; } 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", "output", "git_log", state.session.panel.active_tab].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 `
${escapeHtml(t("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 t("Running"); case "pending": return t("Queued"); default: return tText(titleCase(status || "task")); } } function getSidebarPostType(categories) { const lowerCategories = (categories || []).map((category) => String(category).toLowerCase()); if (lowerCategories.includes("picture") || lowerCategories.includes("photo") || lowerCategories.includes("image")) { return { icon: "🖼️", type: "picture" }; } if (lowerCategories.includes("aside") || lowerCategories.includes("note") || lowerCategories.includes("quick")) { return { icon: "📝", type: "aside" }; } if (lowerCategories.includes("link") || lowerCategories.includes("bookmark")) { return { icon: "🔗", type: "link" }; } if (lowerCategories.includes("video")) { return { icon: "🎬", type: "video" }; } if (lowerCategories.includes("quote")) { return { icon: "💬", type: "quote" }; } return { icon: "📄", type: "article" }; } function formatSidebarAbsoluteDate(timestamp) { if (!timestamp) { return ""; } return new Intl.DateTimeFormat(formatLocaleFor(state.uiLanguage), { month: "short", day: "numeric", year: "numeric", }).format(new Date(timestamp)); } function formatSidebarRelativeDateMs(timestamp) { if (!timestamp) { return ""; } const date = new Date(timestamp); const now = new Date(); const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)); if (diffDays === 0) { return date.toLocaleTimeString(formatLocaleFor(state.uiLanguage), { hour: "numeric", minute: "2-digit" }); } if (diffDays === 1) { return t("sidebar.chat.yesterday"); } if (diffDays < 7) { return date.toLocaleDateString(formatLocaleFor(state.uiLanguage), { weekday: "short" }); } return date.toLocaleDateString(formatLocaleFor(state.uiLanguage), { month: "short", day: "numeric" }); } function mediaThumbnailGlyph(mimeType) { if (String(mimeType || "").startsWith("image/")) { return "🖼️"; } return "📄"; } function buildDashboardTagCloudItems(items) { if (!Array.isArray(items) || !items.length) { return []; } const topItems = items .slice() .sort((left, right) => (Number(right.count) || 0) - (Number(left.count) || 0)) .slice(0, 40); const counts = topItems.map((item) => Number(item.count) || 0); const maxCount = Math.max(1, ...counts); const minCount = Math.min(...counts); const range = Math.max(1, maxCount - minCount); return topItems .map((item) => ({ ...item, color: normalizeDashboardTagColor(item.color), fontSize: 11 + (((Number(item.count) || 0) - minCount) / range) * 11, })) .sort((left, right) => String(left.tag || "").localeCompare(String(right.tag || ""))); } function dashboardPostCountLabel(count) { const normalizedCount = Number(count) || 0; return t(normalizedCount === 1 ? "dashboard.postCount.one" : "dashboard.postCount.other", { count: normalizedCount }); } function dashboardStatusLabel(status) { const keys = { draft: "dashboard.status.draft", published: "dashboard.status.published", archived: "dashboard.status.archived", }; return keys[status] ? t(keys[status]) : tText(titleCase(status || "draft")); } function formatDashboardMonth(year, month) { return new Intl.DateTimeFormat(formatLocaleFor(state.uiLanguage), { month: "short" }).format(new Date(year, (month || 1) - 1, 1)); } function formatDashboardDate(timestamp) { if (!timestamp) { return ""; } return new Intl.DateTimeFormat(formatLocaleFor(state.uiLanguage)).format(new Date(timestamp)); } function formatLocaleFor(language) { const locales = { de: "de-DE", en: "en-US", es: "es-ES", fr: "fr-FR", it: "it-IT", }; return locales[language] || locales.en; } function formatBytes(bytes) { const normalizedBytes = Number(bytes) || 0; if (normalizedBytes === 0) { return "0 B"; } const units = ["B", "KB", "MB", "GB"]; const unitIndex = Math.min(Math.floor(Math.log(normalizedBytes) / Math.log(1024)), units.length - 1); const value = normalizedBytes / Math.pow(1024, unitIndex); return `${value.toFixed(value >= 10 || unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`; } function renderDashboardTagStyle(item) { const declarations = [`font-size: ${(item.fontSize || 11).toFixed(1)}px;`]; if (item.color) { declarations.push(`background-color: ${item.color};`); declarations.push(`color: ${dashboardContrastColor(item.color)};`); } return declarations.join(" "); } function normalizeDashboardTagColor(color) { if (typeof color !== "string") { return null; } const trimmed = color.trim(); return /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(trimmed) ? trimmed : null; } function dashboardContrastColor(hexColor) { const normalized = hexColor.length === 4 ? `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}` : hexColor; const red = Number.parseInt(normalized.slice(1, 3), 16); const green = Number.parseInt(normalized.slice(3, 5), 16); const blue = Number.parseInt(normalized.slice(5, 7), 16); const luminance = (red * 299 + green * 587 + blue * 114) / 1000; return luminance >= 140 ? "#111111" : "#f5f5f5"; } function escapeHtml(value) { return String(value) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); } function escapeHtmlAttribute(value) { return escapeHtml(value).replaceAll("`", "`"); }