From 3bc99258a2ca4f7116b93a49556a4e0d9a48c4e9 Mon Sep 17 00:00:00 2001 From: Dark98 Date: Thu, 14 May 2026 02:46:29 +0100 Subject: [PATCH] Rip Some Duplicate Code Into Functions --- .gitignore | 3 +- web/static/common.js | 28 +++ web/static/dashboard.html | 12 +- web/static/dashboard.js | 211 ---------------------- web/static/printer-agent.html | 12 +- web/static/printer-agent.js | 108 ----------- web/static/printer-page-common.js | 86 +++++++++ web/static/printer-settings.html | 12 +- web/static/printer-settings.js | 55 ------ web/static/printer-shared.js | 183 +++++++++++++++++++ web/static/printer.html | 13 +- web/static/printer.js | 289 ------------------------------ 12 files changed, 328 insertions(+), 684 deletions(-) create mode 100644 web/static/common.js create mode 100644 web/static/printer-page-common.js create mode 100644 web/static/printer-shared.js diff --git a/.gitignore b/.gitignore index 9acb106..1641179 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ -dist/ +dist*/ bin/ +.tmp/ .env *.exe *.log diff --git a/web/static/common.js b/web/static/common.js new file mode 100644 index 0000000..a4f9588 --- /dev/null +++ b/web/static/common.js @@ -0,0 +1,28 @@ +function relativeTime(unixSeconds) { + const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds); + if (seconds < 5) { + return "just now"; + } + if (seconds < 60) { + return `${seconds}s ago`; + } + const minutes = Math.floor(seconds / 60); + if (minutes < 60) { + return `${minutes}m ago`; + } + const hours = Math.floor(minutes / 60); + return `${hours}h ago`; +} + +function escapeHTML(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +function fact(label, value) { + return `
${escapeHTML(label)}
${escapeHTML(value)}
`; +} diff --git a/web/static/dashboard.html b/web/static/dashboard.html index d260164..936873c 100644 --- a/web/static/dashboard.html +++ b/web/static/dashboard.html @@ -50,8 +50,10 @@ - - - - - + + + + + + + diff --git a/web/static/dashboard.js b/web/static/dashboard.js index 631c699..b5f8996 100644 --- a/web/static/dashboard.js +++ b/web/static/dashboard.js @@ -90,217 +90,6 @@ function renderPrinter(printer) { `; } -function relativeTime(unixSeconds) { - const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds); - if (seconds < 5) { - return "just now"; - } - if (seconds < 60) { - return `${seconds}s ago`; - } - const minutes = Math.floor(seconds / 60); - if (minutes < 60) { - return `${minutes}m ago`; - } - const hours = Math.floor(minutes / 60); - return `${hours}h ago`; -} - -function escapeHTML(value) { - return String(value) - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """) - .replaceAll("'", "'"); -} - -function formatMmuMaterialsHtml(printStatus) { - if (!printStatus || typeof printStatus !== "object") { - return ""; - } - const state = collectMmuMaterialState(printStatus); - if (!state.visible) { - return ""; - } - if (state.disabled) { - return `${escapeHTML(state.label)}: disabled`; - } - if (state.rows.length === 0) { - return `${escapeHTML(state.label)}: enabled`; - } - return [ - ...state.rows.map((row) => mmuMaterialRowHtml(row)), - ].join(""); -} - -function collectMmuMaterialState(printStatus) { - const mmu = printStatus.moonraker_status && printStatus.moonraker_status.mmu; - if (!mmu || typeof mmu !== "object" || !Object.prototype.hasOwnProperty.call(mmu, "enabled")) { - return { visible: false, disabled: false, label: "MMU", rows: [] }; - } - const machine = printStatus.moonraker_status && printStatus.moonraker_status.mmu_machine; - const enabled = isTruthyMetadataValue(mmu.enabled); - const label = machine?.unit_0?.name || "MMU"; - if (!enabled) { - return { visible: true, disabled: true, label, rows: [] }; - } - const names = normalizeMetadataList(mmu.gate_filament_name); - const materials = normalizeMetadataList(mmu.gate_material); - const colors = normalizeMetadataList(mmu.gate_color); - const count = Math.max(names.length, materials.length, colors.length, Number(mmu.num_gates || 0)); - if (count === 0) { - return { visible: true, disabled: false, label, rows: [{ label, value: "Enabled", color: "" }] }; - } - return { - visible: true, - disabled: false, - label, - rows: Array.from({ length: count }, (_, index) => { - const parts = []; - let color = ""; - if (names[index] && names[index] !== "Unknown") { - parts.push(String(names[index])); - } - if (materials[index] && materials[index] !== names[index]) { - parts.push(`(${String(materials[index])})`); - } - if (colors[index]) { - color = String(colors[index]).replace(/[^0-9a-fA-F]/g, ""); - } - return { - label: `Gate ${index + 1}`, - value: parts.join(" ") || "Unknown material", - color, - }; - }), - }; -} - -function normalizeMetadataList(value) { - if (Array.isArray(value)) { - return value.filter((item) => item !== null && item !== undefined && item !== ""); - } - if (value === null || value === undefined || value === "") { - return []; - } - return [value]; -} - -function isTruthyMetadataValue(value) { - if (Array.isArray(value)) { - return value.length > 0; - } - if (typeof value === "string") { - const normalized = value.trim().toLowerCase(); - return normalized === "1" || normalized === "true" || normalized === "yes"; - } - return Boolean(value); -} - -function mmuMaterialRowHtml(row) { - const label = escapeHTML(row.label); - const value = row.value ? escapeHTML(row.value) : ""; - const color = row.color ? mmuNormalizeHexColor(row.color) : ""; - const swatchStyle = color ? ` style="--mmu-swatch:${escapeHTML(color)}"` : ""; - return `${label}${value ? ` ${value}` : ""}`; -} - -function mmuNormalizeHexColor(value) { - const raw = String(value || "").trim().replace(/[^0-9a-fA-F]/g, ""); - if (raw.length === 8) { - return `#${raw.slice(0, 6)}`; - } - if (raw.length === 6) { - return `#${raw}`; - } - if (raw.length === 3) { - return `#${raw.split("").map((ch) => ch + ch).join("")}`; - } - return ""; -} - -function formatTemperatureSummary(printStatus) { - const state = collectTemperatureState(printStatus); - if (!state.visible) { - return ""; - } - return state.rows.map((row) => `${row.label} ${row.value}`).join(" · "); -} - -function collectTemperatureState(printStatus) { - const status = printStatus && printStatus.moonraker_status; - if (!status || typeof status !== "object") { - return { visible: false, rows: [] }; - } - const rows = []; - const seen = new Set(); - const add = (key, label) => { - if (!Object.prototype.hasOwnProperty.call(status, key)) { - return; - } - const sensor = status[key]; - if (!sensor || typeof sensor !== "object") { - return; - } - const reading = formatTemperatureReading(sensor); - if (!reading) { - return; - } - rows.push({ label, value: reading }); - seen.add(key); - }; - add("extruder", "Hotend"); - add("heater_bed", "Bed"); - add("temperature_sensor chamber", "Chamber"); - Object.keys(status).sort().forEach((key) => { - if (seen.has(key) || !isTemperatureSensorKey(key)) { - return; - } - const sensor = status[key]; - if (!sensor || typeof sensor !== "object") { - return; - } - const reading = formatTemperatureReading(sensor); - if (!reading) { - return; - } - rows.push({ label: prettifyTemperatureLabel(key), value: reading }); - }); - return { visible: rows.length > 0, rows }; -} - -function isTemperatureSensorKey(key) { - return typeof key === "string" && ( - key.startsWith("temperature_sensor ") || - key.startsWith("temperature_fan ") || - key.startsWith("temperature_probe ") - ); -} - -function prettifyTemperatureLabel(key) { - const raw = String(key || "") - .replace(/^temperature_(sensor|fan|probe)\s+/i, "") - .replace(/_/g, " ") - .trim(); - if (!raw) { - return "Sensor"; - } - return raw.replace(/\b\w/g, (ch) => ch.toUpperCase()); -} - -function formatTemperatureReading(sensor) { - const current = Number(sensor.temperature); - if (!Number.isFinite(current)) { - return ""; - } - const target = Number(sensor.target); - if (Number.isFinite(target) && target > 0) { - return `${current.toFixed(1)} / ${target.toFixed(1)}°C`; - } - return `${current.toFixed(1)}°C`; -} - refresh.addEventListener("click", loadPrinters); const sessionReady = window.__KA_SESSION_PROMISE__ || Promise.resolve(); sessionReady.finally(() => { diff --git a/web/static/printer-agent.html b/web/static/printer-agent.html index 633f490..623743d 100644 --- a/web/static/printer-agent.html +++ b/web/static/printer-agent.html @@ -181,8 +181,10 @@ - - - - - + + + + + + + diff --git a/web/static/printer-agent.js b/web/static/printer-agent.js index ea03053..a97275b 100644 --- a/web/static/printer-agent.js +++ b/web/static/printer-agent.js @@ -647,40 +647,6 @@ function updateUILink(health) { uiLink.textContent = "UI unavailable"; } -function computeSettingsSync(settings, health) { - const updatedAt = parseTimestamp(settings.updated_at); - const lastSyncedAt = parseTimestamp(settings.last_synced_at); - const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly"; - const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown"; - const uiURL = String(settings.ui_url || "").trim(); - const agentUIURL = String(health.ui_url || "").trim(); - const autoDetect = Boolean(settings.ui_auto_detect); - const agentAutoDetect = Boolean(health.ui_auto_detect); - const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt); - if (synced) { - return { - synced: true, - state: "Synced", - detail: "Agent acknowledged the latest saved settings.", - }; - } - const detailBits = []; - if (controlMode !== appliedMode && appliedMode !== "unknown") { - detailBits.push(`control mode ${controlMode} -> ${appliedMode}`); - } - if (uiURL && uiURL !== agentUIURL) { - detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`); - } - if (autoDetect !== agentAutoDetect) { - detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`); - } - return { - synced: false, - state: "Pending", - detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.", - }; -} - function computeVersionState(health) { const current = String(health && health.agent_version ? health.agent_version : "Unknown"); const available = String(window.__KA_SESSION__ && window.__KA_SESSION__.server_version ? window.__KA_SESSION__.server_version : "dev"); @@ -703,80 +669,6 @@ function setStatus(label, ok) { status.classList.toggle("warn", !ok); } -function fact(label, value) { - return `
${escapeHTML(label)}
${escapeHTML(value)}
`; -} - -function parseTimestamp(value) { - if (!value) { - return 0; - } - const parsed = Date.parse(value); - return Number.isFinite(parsed) ? parsed : 0; -} - -function relativeTime(unixSeconds) { - const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds); - if (seconds < 5) { - return "just now"; - } - if (seconds < 60) { - return `${seconds}s ago`; - } - const minutes = Math.floor(seconds / 60); - if (minutes < 60) { - return `${minutes}m ago`; - } - const hours = Math.floor(minutes / 60); - return `${hours}h ago`; -} - -function formatProgress(value) { - const progress = Number(value); - if (!Number.isFinite(progress) || progress <= 0) { - return "0%"; - } - if (progress <= 1) { - return `${Math.round(progress * 100)}%`; - } - return `${Math.round(progress)}%`; -} - -function formatDuration(value) { - const seconds = Number(value); - if (!Number.isFinite(seconds) || seconds < 0) { - return "Unknown"; - } - const whole = Math.floor(seconds); - const hours = Math.floor(whole / 3600); - const minutes = Math.floor((whole % 3600) / 60); - const secs = whole % 60; - if (hours > 0) { - return `${hours}h ${minutes}m ${secs}s`; - } - if (minutes > 0) { - return `${minutes}m ${secs}s`; - } - return `${secs}s`; -} - -function formatFilament(value) { - const number = Number(value); - if (!Number.isFinite(number) || number <= 0) { - return "Unknown"; - } - return `${number.toFixed(1)} mm`; -} - -function escapeHTML(value) { - return String(value) - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """) - .replaceAll("'", "'"); -} - refresh.addEventListener("click", loadPrinter); if (updateCheck) { updateCheck.addEventListener("click", handleUpdateCheckClick); diff --git a/web/static/printer-page-common.js b/web/static/printer-page-common.js new file mode 100644 index 0000000..4c113f3 --- /dev/null +++ b/web/static/printer-page-common.js @@ -0,0 +1,86 @@ +function computeSettingsSync(settings, health) { + const updatedAt = parseTimestamp(settings.updated_at); + const lastSyncedAt = parseTimestamp(settings.last_synced_at); + const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly"; + const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown"; + const uiURL = String(settings.ui_url || "").trim(); + const agentUIURL = String(health.ui_url || "").trim(); + const autoDetect = Boolean(settings.ui_auto_detect); + const agentAutoDetect = Boolean(health.ui_auto_detect); + const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt); + if (synced) { + return { + synced: true, + state: "Synced", + detail: "Agent acknowledged the latest saved settings.", + }; + } + const detailBits = []; + if (controlMode !== appliedMode && appliedMode !== "unknown") { + detailBits.push(`control mode ${controlMode} -> ${appliedMode}`); + } + if (uiURL && uiURL !== agentUIURL) { + detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`); + } + if (autoDetect !== agentAutoDetect) { + detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`); + } + return { + synced: false, + state: "Pending", + detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.", + }; +} + +function parseTimestamp(value) { + if (!value) { + return 0; + } + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : 0; +} + +function formatProgress(value) { + const progress = Number(value); + if (!Number.isFinite(progress) || progress <= 0) { + return "0%"; + } + if (progress <= 1) { + return `${Math.round(progress * 100)}%`; + } + return `${Math.round(progress)}%`; +} + +function formatDuration(value) { + const seconds = Number(value); + if (!Number.isFinite(seconds) || seconds < 0) { + return "Unknown"; + } + const whole = Math.floor(seconds); + const hours = Math.floor(whole / 3600); + const minutes = Math.floor((whole % 3600) / 60); + const secs = whole % 60; + if (hours > 0) { + return `${hours}h ${minutes}m ${secs}s`; + } + if (minutes > 0) { + return `${minutes}m ${secs}s`; + } + return `${secs}s`; +} + +function formatFilament(value) { + const number = Number(value); + if (!Number.isFinite(number) || number <= 0) { + return "Unknown"; + } + return `${number.toFixed(1)} mm`; +} + +function formatHistoryTime(value) { + const unix = Number(value); + if (!Number.isFinite(unix) || unix <= 0) { + return "Unknown"; + } + return new Date(unix * 1000).toLocaleString(); +} diff --git a/web/static/printer-settings.html b/web/static/printer-settings.html index 589baa8..0273a8f 100644 --- a/web/static/printer-settings.html +++ b/web/static/printer-settings.html @@ -158,8 +158,10 @@ - - - - - + + + + + + + diff --git a/web/static/printer-settings.js b/web/static/printer-settings.js index a429cc6..6f23a56 100644 --- a/web/static/printer-settings.js +++ b/web/static/printer-settings.js @@ -236,40 +236,6 @@ function installURL(install) { return `/install?${params.toString()}`; } -function computeSettingsSync(settings, health) { - const updatedAt = parseTimestamp(settings.updated_at); - const lastSyncedAt = parseTimestamp(settings.last_synced_at); - const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly"; - const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown"; - const uiURL = String(settings.ui_url || "").trim(); - const agentUIURL = String(health.ui_url || "").trim(); - const autoDetect = Boolean(settings.ui_auto_detect); - const agentAutoDetect = Boolean(health.ui_auto_detect); - const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt); - if (synced) { - return { - synced: true, - state: "Synced", - detail: "Agent acknowledged the latest synced settings.", - }; - } - const detailBits = []; - if (controlMode !== appliedMode && appliedMode !== "unknown") { - detailBits.push(`control mode ${controlMode} -> ${appliedMode}`); - } - if (uiURL && uiURL !== agentUIURL) { - detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`); - } - if (autoDetect !== agentAutoDetect) { - detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`); - } - return { - synced: false, - state: "Pending", - detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.", - }; -} - function setStatus(label, ok) { status.textContent = label; status.classList.toggle("ok", ok); @@ -386,27 +352,6 @@ function renderSnapshotCameraOptions(cameras, selectedCamera) { settingsNotificationSnapshotCamera.disabled = snapshotCameras.length === 0 && selected === ""; } -function fact(label, value) { - return `
${escapeHTML(label)}
${escapeHTML(value)}
`; -} - -function parseTimestamp(value) { - if (!value) { - return 0; - } - const parsed = Date.parse(value); - return Number.isFinite(parsed) ? parsed : 0; -} - -function escapeHTML(value) { - return String(value) - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """) - .replaceAll("'", "'"); -} - refresh.addEventListener("click", loadPrinter); if (settingsForm) { settingsForm.addEventListener("submit", saveSettings); diff --git a/web/static/printer-shared.js b/web/static/printer-shared.js new file mode 100644 index 0000000..65cd240 --- /dev/null +++ b/web/static/printer-shared.js @@ -0,0 +1,183 @@ +function formatMmuMaterialsHtml(printStatus) { + if (!printStatus || typeof printStatus !== "object") { + return ""; + } + const state = collectMmuMaterialState(printStatus); + if (!state.visible) { + return ""; + } + if (state.disabled) { + return `${escapeHTML(state.label)}: disabled`; + } + if (state.rows.length === 0) { + return `${escapeHTML(state.label)}: enabled`; + } + return state.rows.map((row) => mmuMaterialRowHtml(row)).join(""); +} + +function collectMmuMaterialState(printStatus) { + const mmu = printStatus.moonraker_status && printStatus.moonraker_status.mmu; + if (!mmu || typeof mmu !== "object" || !Object.prototype.hasOwnProperty.call(mmu, "enabled")) { + return { visible: false, disabled: false, label: "MMU", rows: [] }; + } + const machine = printStatus.moonraker_status && printStatus.moonraker_status.mmu_machine; + const enabled = isTruthyMetadataValue(mmu.enabled); + const label = machine?.unit_0?.name || "MMU"; + if (!enabled) { + return { visible: true, disabled: true, label, rows: [] }; + } + const names = normalizeMetadataList(mmu.gate_filament_name); + const materials = normalizeMetadataList(mmu.gate_material); + const colors = normalizeMetadataList(mmu.gate_color); + const count = Math.max(names.length, materials.length, colors.length, Number(mmu.num_gates || 0)); + if (count === 0) { + return { visible: true, disabled: false, label, rows: [{ label, value: "Enabled", color: "" }] }; + } + return { + visible: true, + disabled: false, + label, + rows: Array.from({ length: count }, (_, index) => { + const parts = []; + let color = ""; + if (names[index] && names[index] !== "Unknown") { + parts.push(String(names[index])); + } + if (materials[index] && materials[index] !== names[index]) { + parts.push(`(${String(materials[index])})`); + } + if (colors[index]) { + color = String(colors[index]).replace(/[^0-9a-fA-F]/g, ""); + } + return { + label: `Gate ${index + 1}`, + value: parts.join(" ") || "Unknown material", + color, + }; + }), + }; +} + +function normalizeMetadataList(value) { + if (Array.isArray(value)) { + return value.filter((item) => item !== null && item !== undefined && item !== ""); + } + if (value === null || value === undefined || value === "") { + return []; + } + return [value]; +} + +function isTruthyMetadataValue(value) { + if (Array.isArray(value)) { + return value.length > 0; + } + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + return normalized === "1" || normalized === "true" || normalized === "yes"; + } + return Boolean(value); +} + +function mmuMaterialRowHtml(row) { + const label = escapeHTML(row.label); + const value = row.value ? escapeHTML(row.value) : ""; + const color = row.color ? mmuNormalizeHexColor(row.color) : ""; + const swatchStyle = color ? ` style="--mmu-swatch:${escapeHTML(color)}"` : ""; + return `${label}${value ? ` ${value}` : ""}`; +} + +function mmuNormalizeHexColor(value) { + const raw = String(value || "").trim().replace(/[^0-9a-fA-F]/g, ""); + if (raw.length === 8) { + return `#${raw.slice(0, 6)}`; + } + if (raw.length === 6) { + return `#${raw}`; + } + if (raw.length === 3) { + return `#${raw.split("").map((ch) => ch + ch).join("")}`; + } + return ""; +} + +function formatTemperatureSummary(printStatus) { + const state = collectTemperatureState(printStatus); + if (!state.visible) { + return ""; + } + return state.rows.map((row) => `${row.label} ${row.value}`).join(" · "); +} + +function collectTemperatureState(printStatus) { + const status = printStatus && printStatus.moonraker_status; + if (!status || typeof status !== "object") { + return { visible: false, rows: [] }; + } + const rows = []; + const seen = new Set(); + const add = (key, label) => { + if (!Object.prototype.hasOwnProperty.call(status, key)) { + return; + } + const sensor = status[key]; + if (!sensor || typeof sensor !== "object") { + return; + } + const reading = formatTemperatureReading(sensor); + if (!reading) { + return; + } + rows.push({ label, value: reading }); + seen.add(key); + }; + add("extruder", "Hotend"); + add("heater_bed", "Bed"); + add("temperature_sensor chamber", "Chamber"); + Object.keys(status).sort().forEach((key) => { + if (seen.has(key) || !isTemperatureSensorKey(key)) { + return; + } + const sensor = status[key]; + if (!sensor || typeof sensor !== "object") { + return; + } + const reading = formatTemperatureReading(sensor); + if (!reading) { + return; + } + rows.push({ label: prettifyTemperatureLabel(key), value: reading }); + }); + return { visible: rows.length > 0, rows }; +} + +function isTemperatureSensorKey(key) { + return typeof key === "string" && ( + key.startsWith("temperature_sensor ") || + key.startsWith("temperature_fan ") || + key.startsWith("temperature_probe ") + ); +} + +function prettifyTemperatureLabel(key) { + const raw = String(key || "") + .replace(/^temperature_(sensor|fan|probe)\s+/i, "") + .replace(/_/g, " ") + .trim(); + if (!raw) { + return "Sensor"; + } + return raw.replace(/\b\w/g, (ch) => ch.toUpperCase()); +} + +function formatTemperatureReading(sensor) { + const current = Number(sensor.temperature); + if (!Number.isFinite(current)) { + return ""; + } + const target = Number(sensor.target); + if (Number.isFinite(target) && target > 0) { + return `${current.toFixed(1)} / ${target.toFixed(1)}°C`; + } + return `${current.toFixed(1)}°C`; +} diff --git a/web/static/printer.html b/web/static/printer.html index 2872912..31707a8 100644 --- a/web/static/printer.html +++ b/web/static/printer.html @@ -144,8 +144,11 @@ - - - - - + + + + + + + + diff --git a/web/static/printer.js b/web/static/printer.js index f58acf8..eae3e24 100644 --- a/web/static/printer.js +++ b/web/static/printer.js @@ -319,179 +319,6 @@ function renderPrintStatus(status, error, controlMode) { renderPrintActionRow(state, controlMode); } -function collectMmuMaterialState(printStatus) { - if (!printStatus || typeof printStatus !== "object") { - return { visible: false, disabled: false, label: "MMU", rows: [] }; - } - const mmu = printStatus.moonraker_status && printStatus.moonraker_status.mmu; - if (!mmu || typeof mmu !== "object" || !Object.prototype.hasOwnProperty.call(mmu, "enabled")) { - return { visible: false, disabled: false, label: "MMU", rows: [] }; - } - const machine = printStatus.moonraker_status && printStatus.moonraker_status.mmu_machine; - const label = machine?.unit_0?.name || "MMU"; - if (!isTruthyMetadataValue(mmu.enabled)) { - return { visible: true, disabled: true, label, rows: [] }; - } - const names = normalizeMetadataList(mmu.gate_filament_name); - const materials = normalizeMetadataList(mmu.gate_material); - const colors = normalizeMetadataList(mmu.gate_color); - const count = Math.max(names.length, materials.length, colors.length, Number(mmu.num_gates || 0)); - if (count === 0) { - return { visible: true, disabled: false, label, rows: [{ label, value: "Enabled" }] }; - } - return { - visible: true, - disabled: false, - label, - rows: Array.from({ length: count }, (_, index) => { - const parts = []; - let color = ""; - if (names[index] && names[index] !== "Unknown") { - parts.push(String(names[index])); - } - if (materials[index] && materials[index] !== names[index]) { - parts.push(`(${String(materials[index])})`); - } - if (colors[index]) { - color = String(colors[index]).replace(/[^0-9a-fA-F]/g, ""); - } - return { - label: `Gate ${index + 1}`, - value: parts.join(" ") || "Unknown material", - color, - }; - }), - }; -} - -function normalizeMetadataList(value) { - if (Array.isArray(value)) { - return value.filter((item) => item !== null && item !== undefined && item !== ""); - } - if (value === null || value === undefined || value === "") { - return []; - } - return [value]; -} - -function isTruthyMetadataValue(value) { - if (Array.isArray(value)) { - return value.length > 0; - } - if (typeof value === "string") { - const normalized = value.trim().toLowerCase(); - return normalized === "1" || normalized === "true" || normalized === "yes"; - } - return Boolean(value); -} - -function mmuMaterialChipHtml(row, disabled) { - const label = escapeHTML(row && row.label ? row.label : ""); - const value = row && row.value ? escapeHTML(row.value) : ""; - const color = row && row.color ? mmuNormalizeHexColor(row.color) : ""; - const style = color ? ` style="--mmu-swatch:${escapeHTML(color)}"` : ""; - const classes = ["mmu-material-chip"]; - if (disabled) { - classes.push("mmu-disabled"); - } - return `${label}${value ? ` ${value}` : ""}`; -} - -function mmuNormalizeHexColor(value) { - const raw = String(value || "").trim().replace(/[^0-9a-fA-F]/g, ""); - if (raw.length === 8) { - return `#${raw.slice(0, 6)}`; - } - if (raw.length === 6) { - return `#${raw}`; - } - if (raw.length === 3) { - return `#${raw.split("").map((ch) => ch + ch).join("")}`; - } - return ""; -} - -function formatTemperatureSummary(printStatus) { - const state = collectTemperatureState(printStatus); - if (!state.visible) { - return ""; - } - return state.rows.map((row) => `${row.label} ${row.value}`).join(" · "); -} - -function collectTemperatureState(printStatus) { - const status = printStatus && printStatus.moonraker_status; - if (!status || typeof status !== "object") { - return { visible: false, rows: [] }; - } - const rows = []; - const seen = new Set(); - const add = (key, label) => { - if (!Object.prototype.hasOwnProperty.call(status, key)) { - return; - } - const sensor = status[key]; - if (!sensor || typeof sensor !== "object") { - return; - } - const value = formatTemperatureReading(sensor); - if (!value) { - return; - } - rows.push({ label, value }); - seen.add(key); - }; - add("extruder", "Hotend"); - add("heater_bed", "Bed"); - add("temperature_sensor chamber", "Chamber"); - Object.keys(status).sort().forEach((key) => { - if (seen.has(key) || !isTemperatureSensorKey(key)) { - return; - } - const sensor = status[key]; - if (!sensor || typeof sensor !== "object") { - return; - } - const value = formatTemperatureReading(sensor); - if (!value) { - return; - } - rows.push({ label: prettifyTemperatureLabel(key), value }); - }); - return { visible: rows.length > 0, rows }; -} - -function isTemperatureSensorKey(key) { - return typeof key === "string" && ( - key.startsWith("temperature_sensor ") || - key.startsWith("temperature_fan ") || - key.startsWith("temperature_probe ") - ); -} - -function prettifyTemperatureLabel(key) { - const raw = String(key || "") - .replace(/^temperature_(sensor|fan|probe)\s+/i, "") - .replace(/_/g, " ") - .trim(); - if (!raw) { - return "Sensor"; - } - return raw.replace(/\b\w/g, (ch) => ch.toUpperCase()); -} - -function formatTemperatureReading(sensor) { - const current = Number(sensor.temperature); - if (!Number.isFinite(current)) { - return ""; - } - const target = Number(sensor.target); - if (Number.isFinite(target) && target > 0) { - return `${current.toFixed(1)} / ${target.toFixed(1)}\u00b0C`; - } - return `${current.toFixed(1)}\u00b0C`; -} - function renderPrintActionRow(state, controlMode) { if (!printActionRow) { return; @@ -1011,128 +838,12 @@ function cameraMeta(camera) { return parts.join(" / ") || "Configured camera"; } -function relativeTime(unixSeconds) { - const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds); - if (seconds < 5) { - return "just now"; - } - if (seconds < 60) { - return `${seconds}s ago`; - } - const minutes = Math.floor(seconds / 60); - if (minutes < 60) { - return `${minutes}m ago`; - } - const hours = Math.floor(minutes / 60); - return `${hours}h ago`; -} - function setStatus(label, ok) { status.textContent = label; status.classList.toggle("ok", ok); status.classList.toggle("warn", !ok); } -function fact(label, value) { - return `
${escapeHTML(label)}
${escapeHTML(value)}
`; -} - -function computeSettingsSync(settings, health) { - const updatedAt = parseTimestamp(settings.updated_at); - const lastSyncedAt = parseTimestamp(settings.last_synced_at); - const controlMode = String(settings.control_mode || "").toLowerCase() || "readonly"; - const appliedMode = String(health.control_mode || "").toLowerCase() || "unknown"; - const uiURL = String(settings.ui_url || "").trim(); - const agentUIURL = String(health.ui_url || "").trim(); - const autoDetect = Boolean(settings.ui_auto_detect); - const agentAutoDetect = Boolean(health.ui_auto_detect); - const synced = Boolean(updatedAt && lastSyncedAt && lastSyncedAt >= updatedAt); - if (synced) { - return { - synced: true, - state: "Synced", - detail: "Agent acknowledged the latest saved settings.", - }; - } - const detailBits = []; - if (controlMode !== appliedMode && appliedMode !== "unknown") { - detailBits.push(`control mode ${controlMode} -> ${appliedMode}`); - } - if (uiURL && uiURL !== agentUIURL) { - detailBits.push(`UI URL ${uiURL} -> ${agentUIURL || "unset"}`); - } - if (autoDetect !== agentAutoDetect) { - detailBits.push(`auto-detect ${autoDetect} -> ${agentAutoDetect}`); - } - return { - synced: false, - state: "Pending", - detail: detailBits.length > 0 ? `Waiting for agent confirmation; ${detailBits.join("; ")}` : "Waiting for the agent to confirm the latest settings.", - }; -} - -function parseTimestamp(value) { - if (!value) { - return 0; - } - const parsed = Date.parse(value); - return Number.isFinite(parsed) ? parsed : 0; -} - -function formatProgress(value) { - const progress = Number(value); - if (!Number.isFinite(progress) || progress <= 0) { - return "0%"; - } - if (progress <= 1) { - return `${Math.round(progress * 100)}%`; - } - return `${Math.round(progress)}%`; -} - -function formatDuration(value) { - const seconds = Number(value); - if (!Number.isFinite(seconds) || seconds < 0) { - return "Unknown"; - } - const whole = Math.floor(seconds); - const hours = Math.floor(whole / 3600); - const minutes = Math.floor((whole % 3600) / 60); - const secs = whole % 60; - if (hours > 0) { - return `${hours}h ${minutes}m ${secs}s`; - } - if (minutes > 0) { - return `${minutes}m ${secs}s`; - } - return `${secs}s`; -} - -function formatFilament(value) { - const number = Number(value); - if (!Number.isFinite(number) || number <= 0) { - return "Unknown"; - } - return `${number.toFixed(1)} mm`; -} - -function formatHistoryTime(value) { - const unix = Number(value); - if (!Number.isFinite(unix) || unix <= 0) { - return "Unknown"; - } - return new Date(unix * 1000).toLocaleString(); -} - -function escapeHTML(value) { - return String(value) - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """) - .replaceAll("'", "'"); -} - refresh.addEventListener("click", loadPrinter); loadSession().then(loadPrinter); setInterval(loadPrinter, 15000);