diff --git a/.gitignore b/.gitignore index 2256f1518..33b9596ab 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ repomix-output.xml generate-context.ps1 .env languages/backup/ +build_analysis/* +test/out/ diff --git a/config/Caddyfile b/config/Caddyfile new file mode 100644 index 000000000..a6f233890 --- /dev/null +++ b/config/Caddyfile @@ -0,0 +1,31 @@ +# HTTPS front for the dev/mock servers (test https / wss / br behaviour) +# Started by `npm run dev-xxx secure` (see config/dev.js), or by hand: +# caddy run --config config/Caddyfile +# - https://localhost:8443 -> webpack dev server 8088 (dev bundle) +# - https://localhost -> same, on default port 443 (http://localhost redirects) +# - https://localhost:8445 -> mock HTTP server 8080 (Flash/index.html.br or .gz) +# - wss://localhost:8444 -> mock WebSocket server 8089 +# (the mock reports WebSocketPort 8444 when WS_PUBLIC_PORT=8444) +# Caddy uses its local CA and installs it in the Windows trust store on first +# run (confirm the Windows dialog), so no certificate warning in Chrome/Edge. +{ + local_certs +} + +https://localhost:8443 { + reverse_proxy localhost:8088 +} + +# Default port (443), like a real HTTPS reverse proxy without port in the URL. +# Caddy also listens on 80 and redirects http://localhost to https://localhost. +https://localhost { + reverse_proxy localhost:8088 +} + +https://localhost:8444 { + reverse_proxy localhost:8089 +} + +https://localhost:8445 { + reverse_proxy localhost:8080 +} diff --git a/config/build-icons.js b/config/build-icons.js new file mode 100644 index 000000000..7ca9c9579 --- /dev/null +++ b/config/build-icons.js @@ -0,0 +1,111 @@ +/** + * Regenerates src/components/Icons/index.js: scans src/ for imports from + * "preact-feather" (aliased to the local registry at build time) and + * embeds only the SVG children data of the icons actually used. + * Run: node config/build-icons.js (after adding/removing an icon import) + */ +const fs = require("fs") +const path = require("path") + +const SRC = path.join(__dirname, "..", "src") +const FEATHER = path.join( + __dirname, + "..", + "node_modules", + "preact-feather", + "dist", + "icons" +) +const OUT = path.join(SRC, "components", "Icons", "index.js") + +const walk = (dir, out = []) => { + for (const f of fs.readdirSync(dir)) { + const p = path.join(dir, f) + if (fs.statSync(p).isDirectory()) walk(p, out) + else if (/\.[jt]sx?$/.test(f)) out.push(p) + } + return out +} + +const used = new Set() +const importRe = /import\s*\{([^}]*)\}\s*from\s*["']preact-feather["']/g +for (const f of walk(SRC)) { + const txt = fs.readFileSync(f, "utf8") + let m + while ((m = importRe.exec(txt))) { + m[1].split(",") + .map((s) => s.trim()) + .filter(Boolean) + .forEach((n) => used.add(n.split(" as ")[0].trim())) + } +} + +const byNorm = {} +for (const f of fs.readdirSync(FEATHER).filter((f) => f.endsWith(".js"))) + byNorm[f.replace(/\.js$/, "").replace(/-/g, "")] = f + +const entries = [] +for (const name of [...used].sort()) { + const file = byNorm[name.toLowerCase()] + if (!file) throw new Error("Icon not found in preact-feather: " + name) + const src = fs.readFileSync(path.join(FEATHER, file), "utf8") + const children = [...src.matchAll(/h\("(\w+)", (\{[^{}]*\})\)/g)].map( + (mm) => [mm[1], mm[2]] + ) + if (!children.length) + throw new Error("No SVG children parsed for " + name) + entries.push({ name, children }) +} + +const header = `/* + index.js - ESP3D local icon set (drop-in replacement for preact-feather) + + Icon path data derived from Feather Icons (https://feathericons.com, MIT License). + A single shared SVG wrapper + per-icon child table, instead of one full + Preact component per icon, to reduce bundle size. + + GENERATED FILE - regenerate with: node config/build-icons.js +*/ +import { h } from "preact" + +const makeIcon = (children) => { + const Icon = (props) => { + const { color, size, ...rest } = props || {} + return h( + "svg", + { + xmlns: "http://www.w3.org/2000/svg", + width: size || 24, + height: size || 24, + viewBox: "0 0 24 24", + fill: "none", + stroke: color || "currentColor", + "stroke-width": "2", + "stroke-linecap": "round", + "stroke-linejoin": "round", + ...rest, + }, + children.map(([tag, attrs]) => h(tag, attrs)) + ) + } + return Icon +} + +` + +let out = header +for (const e of entries) { + const kids = e.children + .map( + ([t, a]) => + "[" + + JSON.stringify(t) + + ", " + + a.replace(/\s+/g, " ").replace(/\{ /g, "{").replace(/ \}/g, "}") + + "]" + ) + .join(",") + out += "export const " + e.name + " = /*#__PURE__*/ makeIcon([" + kids + "])\n" +} +fs.writeFileSync(OUT, out) +console.log("Generated", OUT, "-", entries.length, "icons") diff --git a/config/buildlangpack.js b/config/buildlangpack.js index 5c526fc1d..2fa662f89 100644 --- a/config/buildlangpack.js +++ b/config/buildlangpack.js @@ -4,16 +4,15 @@ Copyright (c) 2021 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + General Public License for more details. + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const path = require("path") diff --git a/config/buildtemplate.js b/config/buildtemplate.js index 47938cf84..ef9635e52 100644 --- a/config/buildtemplate.js +++ b/config/buildtemplate.js @@ -4,16 +4,15 @@ Copyright (c) 2021 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + General Public License for more details. + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const path = require("path") diff --git a/config/checkpack.js b/config/checkpack.js index 9f293de7e..c7f63ab61 100644 --- a/config/checkpack.js +++ b/config/checkpack.js @@ -4,16 +4,15 @@ Copyright (c) 2021 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + General Public License for more details. + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const path = require("path") diff --git a/config/dev.js b/config/dev.js new file mode 100644 index 000000000..a20a8c445 --- /dev/null +++ b/config/dev.js @@ -0,0 +1,107 @@ +/* + * Dev launcher: mock server + webpack dev server (+ Caddy HTTPS front) + * + * node config/dev.js [secure] [auth] [root=] + * npm run dev-cnc-grblhal -> http://localhost:8088 + * npm run dev-cnc-grblhal secure -> https://localhost:8443 + * npm run dev-cnc-grblhal auth -> mock with authentication (admin/admin) + * npm run dev-cnc-grblhal root=www -> override the target webRoot + * (HostPath simulation, fixtures must + * exist under server///Flash/www) + * + * secure mode needs Caddy (https://caddyserver.com, `winget install CaddyServer.Caddy`): + * https://localhost:8443 -> webpack dev server 8088 (dev bundle) + * https://localhost:8445 -> mock server 8080 (packaged Flash/index.html.br|.gz) + * wss://localhost:8444 -> mock WebSocket 8089 + * The mock then reports WebSocketPort 8444, so the plain http:// URLs do not + * get a working WebSocket in this mode. + */ +const { spawn, spawnSync } = require("child_process") +const path = require("path") +const fs = require("fs") + +const args = process.argv.slice(2) +const secure = args.includes("secure") +const auth = args.includes("auth") +const rootArg = args.find((a) => a.startsWith("root=")) +const [target = "Printer3D", subtarget = "Marlin"] = args.filter( + (a) => a !== "secure" && a !== "auth" && !a.startsWith("root=") +) + +const env = { + ...process.env, + TARGET_ENV: target, + SUBTARGET_ENV: subtarget, +} +if (auth) env.AUTH = "1" +//root= overrides the target webRoot AND the HostPath reported by +//ESP800 - normalized here so targets can use it as-is +if (rootArg) { + let w = rootArg.substring("root=".length) + if (!w.startsWith("/")) w = "/" + w + env.WEBROOT = w.replace(/\/+$/, "") || "/" +} + +const commands = ['"npm run server"', '"npm run front"'] +const names = ["server", "front"] + +// Caddy location: CADDY env var, PATH, or the winget install folder (the +// PATH updated by winget is not seen by terminals of an already running VS Code) +function findCaddy() { + const candidates = [process.env.CADDY, "caddy"] + const wingetDir = path.join( + process.env.LOCALAPPDATA || "", + "Microsoft/WinGet/Packages" + ) + if (process.env.LOCALAPPDATA && fs.existsSync(wingetDir)) { + fs.readdirSync(wingetDir) + .filter((d) => d.startsWith("CaddyServer.Caddy")) + .forEach((d) => candidates.push(path.join(wingetDir, d, "caddy.exe"))) + } + return candidates.find( + (c) => + c && + spawnSync(`"${c}"`, ["version"], { shell: true }).status === 0 + ) +} + +if (secure) { + const caddy = findCaddy() + if (!caddy) { + console.error( + "secure mode needs Caddy: winget install CaddyServer.Caddy (or set CADDY=)" + ) + process.exit(1) + } + env.SECURE = "1" + env.WS_PUBLIC_PORT = "8444" + if (caddy !== "caddy") { + // make the found caddy reachable as "caddy" for the child processes + const key = + Object.keys(env).find((k) => k.toUpperCase() === "PATH") || "PATH" + env[key] = path.dirname(caddy) + path.delimiter + (env[key] || "") + } + commands.push('"caddy run --config config/Caddyfile --adapter caddyfile"') + names.push("caddy") + console.log( + "Secure mode: https://localhost or https://localhost:8443 (dev) / https://localhost:8445 (packaged) / wss://localhost:8444" + ) +} + +const options = [ + secure ? "secure" : null, + rootArg ? `webRoot=${env.WEBROOT}` : null, + auth ? "auth (admin/admin)" : null, +].filter(Boolean) +if (options.length) console.log("Options: " + options.join(", ")) + +const concurrently = path.join( + __dirname, + "../node_modules/.bin/concurrently" +) +const child = spawn( + `"${concurrently}"`, + ["--kill-others-on-fail", "--names", names.join(","), ...commands], + { stdio: "inherit", shell: true, env, cwd: path.join(__dirname, "..") } +) +child.on("exit", (code) => process.exit(code ?? 0)) diff --git a/config/pack.js b/config/pack.js index 201a64a84..6076d8f1f 100644 --- a/config/pack.js +++ b/config/pack.js @@ -4,16 +4,15 @@ Copyright (c) 2021 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + General Public License for more details. + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const path = require("path") diff --git a/config/server.js b/config/server.js index fb5708e1b..0e18f310f 100644 --- a/config/server.js +++ b/config/server.js @@ -3,7 +3,7 @@ const expressStaticGzip = require("express-static-gzip") const chalk = require("chalk") let path = require("path") const fs = require("fs") -const port = 8080 +const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 8080 /* * Web Server for development * Web Socket server for development @@ -13,6 +13,8 @@ const expresscolor = chalk.green const commandcolor = chalk.white const WebSocket = require("ws") let currentID = 0 +//firmware session timeout when authentication is enabled (PING keep-alive) +const sessionTime = 60000 const app = express() const fileUpload = require("express-fileupload") let sensorInterval = -1 @@ -34,32 +36,81 @@ if (!fs.existsSync(serverpath + "SD")) { fs.mkdirSync(serverpath + "SD", { recursive: true }) } +//normalize the WEBROOT override (dev launcher root= arg) before targets +//read it for their ESP800 HostPath; reject Git Bash-mangled Windows paths +if (process.env.WEBROOT) { + if (/^[A-Za-z]:[\\/]/.test(process.env.WEBROOT)) { + console.log( + `[server] Invalid WEBROOT "${process.env.WEBROOT}" - in Git Bash use //www instead of /www, or use PowerShell` + ) + process.exit(1) + } + let w = process.env.WEBROOT + if (!w.startsWith("/")) w = "/" + w + process.env.WEBROOT = w.replace(/\/+$/, "") || "/" +} + const { commandsQuery, configURI, getLastconnection, hasEnabledAuthentication, + loginURI, + startAutoReport, + webRoot: targetWebRoot = "", } = require( path.normalize( __dirname + "/targets/" + target + "/" + subtarget + "/index.js" ) ) +//optional: the firmware roots its /files query API and default document +//at a web subdir (e.g. grblHAL HostPath "/www"), while static URLs and +//uploads use absolute FS paths - see docs/hostpath_files_api.md. +//Exported by the target config, overridable via WEBROOT (normalized above) +const webRoot = process.env.WEBROOT || targetWebRoot +//a root= override on a target without prepared fixtures should still work: +//create the web root directory (empty listing) instead of crashing +const filesRootDir = path.join(serverpath + "Flash", "." + webRoot) +if (!fs.existsSync(filesRootDir)) fs.mkdirSync(filesRootDir, { recursive: true }) + const WebSocketServer = require("ws").Server, wss = new WebSocketServer({ port: 8089 }) -// Prefer .gz: if client asks for toto.html (or /), serve toto.html.gz with Content-Encoding: gzip when present +// Like the firmware: if client asks for toto.html (or /), serve toto.html.br +// (only when the browser advertises br, i.e. over HTTPS) or toto.html.gz app.use("/", (req, res, next) => { - if (req.method !== "GET" || req.path.endsWith(".gz")) return next() + if (req.method !== "GET" || /\.(gz|br)$/.test(req.path)) return next() const relPath = !req.path || req.path === "/" ? "index.html" : req.path const base = path.join(serverpath, "Flash", relPath) - const gzPath = base + ".gz" - if (!fs.existsSync(gzPath) || !fs.statSync(gzPath).isFile()) return next() - const ext = path.extname(req.path) + const isFile = (p) => fs.existsSync(p) && fs.statSync(p).isFile() + const acceptsBr = /\bbr\b/.test(req.headers["accept-encoding"] || "") + let file, encoding + if (acceptsBr && isFile(base + ".br")) { + file = base + ".br" + encoding = "br" + } else if (isFile(base + ".gz")) { + file = base + ".gz" + encoding = "gzip" + } else if (webRoot && !relPath.startsWith(webRoot + "/")) { + //grblHAL-style targets: the default document lives under the web + //root (e.g. / -> /www/index.html), like the real firmware + const baseWeb = path.join(serverpath, "Flash", webRoot, relPath) + if (acceptsBr && isFile(baseWeb + ".br")) { + file = baseWeb + ".br" + encoding = "br" + } else if (isFile(baseWeb + ".gz")) { + file = baseWeb + ".gz" + encoding = "gzip" + } else return next() + } else return next() + const ext = path.extname(relPath) const types = { ".html": "text/html", ".css": "text/css", ".js": "application/javascript", ".json": "application/json" } if (types[ext]) res.setHeader("Content-Type", types[ext]) - res.setHeader("Content-Encoding", "gzip") - res.sendFile(path.resolve(gzPath)) + res.setHeader("Content-Encoding", encoding) + res.setHeader("Vary", "Accept-Encoding") + console.log(expresscolor(`[server] ${relPath} -> ${path.basename(file)} (Accept-Encoding: ${req.headers["accept-encoding"] || "none"})`)) + res.sendFile(path.resolve(file)) }) app.use("/", express.static(serverpath + "Flash")) @@ -67,9 +118,21 @@ app.use("/sd", express.static(serverpath + "sd")) app.use("/", expressStaticGzip(serverpath + "Flash")) app.use(fileUpload({ preserveExtension: true, debug: false })) -app.listen(port, () => console.log("Env:", subtarget, ":", target)) +app.listen(port, () => + console.log( + "Env:", + subtarget, + ":", + target, + webRoot ? "webRoot:" + webRoot : "", + process.env.AUTH === "1" ? "auth:admin/admin" : "" + ) +) app.timeout = 2000 +//some targets (e.g. grblHAL) push periodic status reports like the real firmware +if (typeof startAutoReport === "function") startAutoReport(SendWS) + //app.use(express.urlencoded({ extended: false })); function SendWS(text, isbinary = true, isNotification = true) { @@ -95,12 +158,17 @@ function SendWS(text, isbinary = true, isNotification = true) { } } +//server-level mirror of the target login state: loginURI answers 200 on +//success, 401 on failure/logout - track it so non-target endpoints +//(/files, /sdfiles, /updatefw) can enforce authentication too +let mockLoggedIn = false app.post("/login", function (req, res) { loginURI(req, res) + mockLoggedIn = res.statusCode == 200 }) function checkAuthentication(req, res) { - if (hasEnabledAuthentication() && !getLastconnection()) { + if (hasEnabledAuthentication() && !mockLoggedIn) { res.status(401).send("Authentication required") return false } @@ -123,6 +191,9 @@ app.get("/command", function (req, res) { if (MOCK_VERBOSE) console.log(commandcolor(`[server]/command ${url}`)) commandsQuery(req, res, SendWS, mockContext) if (!res.headersSent) { + //a handler that set a non-200 status without a body still ends + //with that status - never mask it as "unknown command" + if (res.statusCode !== 200) return res.end() if (MOCK_VERBOSE) console.log(commandcolor(`[server]/command unknown: ${url}`)) res.status(200).send("error:unknown command\n") } @@ -159,8 +230,12 @@ function getFileListArray(mypath, destination) { }) } -function filesList(mypath, destination) { - const currentPath = path.normalize(serverpath + destination + mypath) +function filesList(mypath, destination, useWebRoot) { + const baseDir = path.join( + serverpath + destination, + useWebRoot ? "." + webRoot : "." + ) + const currentPath = path.normalize(baseDir + mypath) console.log("[path]" + currentPath) const totalUsed = getTotalSize(serverpath + destination) const total = (destination == "SD" ? 4096 : 1.31) * 1024 * 1024 @@ -225,19 +300,27 @@ function deleteFolderRecursive(path) { } app.all("/updatefw", function (req, res) { + if (!checkAuthentication(req, res)) return res.send("ok") }) app.all("/files", function (req, res) { + if (!checkAuthentication(req, res)) return let mypath = req.query.path let url = req.originalUrl + //Two path conventions, like the real firmware (docs/hostpath_files_api.md): + //- query-driven actions (list/delete/createdir) use paths relative to + // the web root (HostPath, e.g. "/www" on grblHAL): "/files?path=/" + // lists the CONTENT of /www - the user never sees "/www", the panel + // root IS the host path content + //- uploads and direct downloads use absolute FS paths ("/www/themes/...") + const filesBase = path.join(serverpath + "Flash", "." + webRoot) let filepath = path.normalize( - serverpath + "Flash" + mypath + "/" + req.query.filename + filesBase + (mypath || "/") + "/" + req.query.filename ) if (url.indexOf("action=deletedir") != -1) { console.log("[server]delete directory " + filepath) deleteFolderRecursive(filepath) - fs.readdirSync(mypath) } else if (url.indexOf("action=delete") != -1) { console.log("[server]delete file " + filepath) fs.unlinkSync(filepath) @@ -255,35 +338,47 @@ app.all("/files", function (req, res) { } } console.log("[server]path is " + mypath) + //uploads report their directory as an absolute FS path ("/www/themes/") - + //bring it back to a web-root-relative path for the listing response + const listPath = + webRoot && mypath.startsWith(webRoot + "/") + ? mypath.substring(webRoot.length) + : mypath if (!req.files || Object.keys(req.files).length === 0) { - return res.send(filesList(mypath, "Flash")) + return res.send(filesList(listPath, "Flash", true)) } let myFile = req.files.myfiles + //the WebUI sends the multipart filename as the absolute FS path + //(upload path + file name, e.g. "/www/themes/pack.gz") - use it as-is + //when absolute, fall back to the (web-root-relative) upload directory + //otherwise + const toAbsolute = (name) => + name && name.startsWith("/") + ? path.normalize(serverpath + "Flash" + name) + : path.normalize(filesBase + listPath + name) if (typeof myFile.length == "undefined") { - let fullpath = path.normalize( - serverpath + "Flash" + mypath + myFile.name - ) + let fullpath = toAbsolute(myFile.name) console.log("[server]one file:" + fullpath) myFile.mv(fullpath, function (err) { if (err) return res.status(500).send(err) - res.send(filesList(mypath, "Flash")) + res.send(filesList(listPath, "Flash", true)) }) return } else { console.log(myFile.length + " files") for (let i = 0; i < myFile.length; i++) { - let fullpath = path.normalize( - serverpath + "Flash" + mypath + myFile[i].name - ) + let fullpath = toAbsolute(myFile[i].name) console.log(fullpath) myFile[i].mv(fullpath).then(() => { - if (i == myFile.length - 1) res.send(filesList(mypath, "Flash")) + if (i == myFile.length - 1) + res.send(filesList(listPath, "Flash", true)) }) } } }) app.all("/sdfiles", function (req, res) { + if (!checkAuthentication(req, res)) return let mypath = req.query.path let url = req.originalUrl let filepath = path.normalize( @@ -359,12 +454,9 @@ wss.on("connection", (socket, request) => { if (hasEnabledAuthentication() && message.startsWith("PING:")) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { - let t = hasEnableAuthentication() - ? sessiontTime - (Date.now() - getLastconnection()) - : 60000 - let remainingtime = t < 0 ? 0 : t - console.log("remain:", remainingtime, "millisec") - client.send(`PING:${remainingtime}:60000`) + //PING IS the session keep-alive: it refreshes the + //session, so the reply reports the full window + client.send(`PING:${sessionTime}:${sessionTime}`) } }) } diff --git a/config/targets/CNC/GRBL/index.js b/config/targets/CNC/GRBL/index.js index 3fb3c971b..ac529d7f4 100644 --- a/config/targets/CNC/GRBL/index.js +++ b/config/targets/CNC/GRBL/index.js @@ -4,25 +4,24 @@ Copyright (c) 2020 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const wscolor = chalk.cyan const expresscolor = chalk.green const commandcolor = chalk.white -const enableAuthentication = false +const enableAuthentication = process.env.AUTH === "1" let lastconnection = Date.now() let logindone = false const sessiontTime = 60000 @@ -80,7 +79,7 @@ const commandsQuery = (req, res, SendWS) => { } if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -164,12 +163,12 @@ const commandsQuery = (req, res, SendWS) => { Authentication: "Disabled", WebCommunication: "Synchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "esp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/", + HostPath: process.env.WEBROOT || "/", Time: "none", CameraID: "4", CameraName: "ESP32 Cam", @@ -673,7 +672,10 @@ const loginURI = (req, res) => { if (req.body.DISCONNECT == "YES") { res.status(401) logindone = false - } else if (req.body.USER == "admin" && req.body.PASSWORD == "admin") { + } else if ( + !enableAuthentication || + (req.body.USER == "admin" && req.body.PASSWORD == "admin") + ) { logindone = true lastconnection = Date.now() } else { @@ -685,7 +687,7 @@ const loginURI = (req, res) => { const configURI = (req, res) => { if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() diff --git a/config/targets/CNC/grblHAL/index.js b/config/targets/CNC/grblHAL/index.js index ecf76ebcd..13d8c5e64 100644 --- a/config/targets/CNC/grblHAL/index.js +++ b/config/targets/CNC/grblHAL/index.js @@ -4,25 +4,24 @@ Copyright (c) 2020 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const wscolor = chalk.cyan const expresscolor = chalk.green const commandcolor = chalk.white -const enableAuthentication = false +const enableAuthentication = process.env.AUTH === "1" let lastconnection = Date.now() let logindone = false const sessiontTime = 60000 @@ -30,9 +29,26 @@ let countStatus = 0 let change = false const emulationESP400 = false -const state = { position: { X: 0, Y: 0, Z: 0 } } +const state = { + position: { X: 0, Y: 0, Z: 0 }, + units: "G21", //modal G20/G21 + reportInches: "0", //$13 + activeTool: 0, + pendingTool: 0, + toolChanging: false, + alarm: false, +} +//force next $TPW outcome: "ok" (default) or "fail", set via SIM:TPW=OK / SIM:TPW=FAIL +let tpwOutcome = "ok" +//tool probe in progress: status reports Run during the motion window +let tpwProbing = false +let tpwTimer = null +//writable grbl settings reflected in $$ output ($341 default: manual touch off) +const grblSettings = { "341": "1" } let jog = null const JOGCANCEL_BYTE = 0x85 +const CYCLESTART_BYTE = 0x81 +const TOOLCHANGE_BYTE = 0xa3 function parseAxis(url, axis) { const m = url.match(new RegExp(axis + "([+-]?[0-9.]+)", "i")) @@ -59,6 +75,32 @@ function getLastconnection() { return lastconnection } +function formatPos(v) { + return (state.reportInches === "1" ? v / 25.4 : v).toFixed(3) +} + +function currentStateName() { + if (state.alarm) return "Alarm" + if (tpwProbing) return "Run" + if (state.toolChanging) return "Tool" + if (jog) return "Jog" + return "Idle" +} + +function buildStatusReport() { + applyJogPosition() + const { X, Y, Z } = state.position + const wpos = `${formatPos(X)},${formatPos(Y)},${formatPos(Z)},1.000,1.000` + return `<${currentStateName()}|WPos:${wpos}|FS:0,0|WCO:0.000,0.000,0.000,1.000,1.000>\n` +} + +//mimic ESP3D firmware auto report: push status to all ws clients +let autoReportTimer = null +function startAutoReport(SendWS) { + if (autoReportTimer) clearInterval(autoReportTimer) + autoReportTimer = setInterval(() => SendWS(buildStatusReport()), 1000) +} + function hasEnabledAuthentication() { return enableAuthentication } @@ -77,7 +119,7 @@ const commandsQuery = (req, res, SendWS) => { } if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -121,11 +163,87 @@ const commandsQuery = (req, res, SendWS) => { return } + //modal units G20 (inches) / G21 (mm) + if (/\bG20\b/.test(url) || /\bG21\b/.test(url)) { + state.units = /\bG20\b/.test(url) ? "G20" : "G21" + SendWS("ok\n") + res.send("") + return + } + + //set current tool number, no movement + const m61 = url.match(/\bM61\s*Q(\d+)/i) + if (m61) { + state.activeTool = parseInt(m61[1]) + SendWS("ok\n") + res.send("") + return + } + + //manual tool change protocol: T M6 -> Tool state + const tMatch = url.match(/\bT(\d+)/) + if (tMatch) { + state.pendingTool = parseInt(tMatch[1]) + if (/\bM6\b/.test(url)) state.toolChanging = true + SendWS("ok\n") + res.send("") + return + } + + //tool change ack (real-time 0xA3) + if ( + url.indexOf(String.fromCharCode(TOOLCHANGE_BYTE)) !== -1 || + url.includes("%A3") + ) { + SendWS("ok\n") + res.send("") + return + } + + //cycle start (real-time 0x81): completes a pending tool change + if ( + url.indexOf(String.fromCharCode(CYCLESTART_BYTE)) !== -1 || + url.includes("%81") + ) { + if (state.toolChanging) { + state.activeTool = state.pendingTool + state.toolChanging = false + } + SendWS("ok\n") + res.send("") + return + } + + //tool probe workflow: probing motion ~2s (status reports Run), + //then [PRB:..]+ok on success or ALARM:5 on failure + if (url.indexOf("$TPW") != -1) { + const fail = tpwOutcome == "fail" + tpwProbing = true + tpwTimer = setTimeout(() => { + tpwTimer = null + tpwProbing = false + if (fail) { + //probe failed to contact within travel -> grbl alarm 5 + state.alarm = true + SendWS("ALARM:5\n") + } else { + const { X, Y, Z } = state.position + SendWS( + `[PRB:${formatPos(X)},${formatPos(Y)},${formatPos( + Z - 2 + )}:1]\n` + "ok\n" + ) + } + }, 2000) + res.send("") + return + } + if (req.query.cmd && req.query.cmd == "?") { applyJogPosition() countStatus++ const { X, Y, Z } = state.position - const wpos = `${Number(X).toFixed(3)},${Number(Y).toFixed(3)},${Number(Z).toFixed(3)},1.000,1.000` + const wpos = `${formatPos(X)},${formatPos(Y)},${formatPos(Z)},1.000,1.000` if (countStatus == 1) SendWS(`\n`) else if (countStatus == 2) @@ -140,6 +258,14 @@ const commandsQuery = (req, res, SendWS) => { return } + //force next $TPW outcome for testing: SIM:TPW=FAIL / SIM:TPW=OK + if (url.indexOf("SIM:TPW=") != -1) { + tpwOutcome = url.indexOf("SIM:TPW=FAIL") != -1 ? "fail" : "ok" + SendWS("ok\n") + res.send("") + return + } + if (url.indexOf("SIM:") != -1) { const response = url.substring(url.indexOf("SIM:") + 4) SendWS(response + "\n" + "ok\n") @@ -161,12 +287,12 @@ const commandsQuery = (req, res, SendWS) => { Authentication: "Disabled", WebCommunication: "Synchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "esp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/www", + HostPath: process.env.WEBROOT || "/www", Time: "none", Axisletters: "XYZUV", }, @@ -267,13 +393,14 @@ const commandsQuery = (req, res, SendWS) => { if (url.indexOf("$G") != -1) { change = !change - //SendWS("[GC:G0 G54 G17 G21 G90 G94 M5 M9 T0 F0.0 S0]\n") if (change) { SendWS( - "[GC:G0 G54 G17 G21 G90 G92 G94 G49 G98 G51:5 M5 M6 M9 T0 F0 S0.]\n" + `[GC:G0 G54 G17 ${state.units} G90 G92 G94 G49 G98 G51:5 M5 M6 M9 T${state.activeTool} F0 S0.]\n` ) } else { - SendWS("[GC:G0 G54 G17 G21 G90 G94 G49 G98 M56 M5 M9 T0 F0 S0.]\n") + SendWS( + `[GC:G0 G54 G17 ${state.units} G90 G94 G49 G98 M56 M5 M9 T${state.activeTool} F0 S0.]\n` + ) } res.send("") @@ -286,8 +413,32 @@ const commandsQuery = (req, res, SendWS) => { return } + //kill alarm lock + if (url.indexOf("$X") != -1) { + state.alarm = false + SendWS("[MSG:Caution: Unlocked]\n" + "ok\n") + res.send("") + return + } + if (url.indexOf("\x18") != -1) { - SendWS("Grbl 1.1f ['$' for help]\n") + //soft reset aborts any pending tool change / jog / tool probe + //hypothesis (bench test #4): reset during motion raises an alarm + const inMotion = jog != null || tpwProbing + if (tpwTimer) { + clearTimeout(tpwTimer) + tpwTimer = null + } + tpwProbing = false + state.toolChanging = false + jog = null + if (inMotion) { + state.alarm = true + SendWS("ALARM:1\n") + } else { + state.alarm = false + SendWS("Grbl 1.1f ['$' for help]\n") + } res.send("") return } @@ -322,7 +473,7 @@ const commandsQuery = (req, res, SendWS) => { "$10=1\n" + "$11=0.010\n" + "$12=0.002\n" + - "$13=0\n" + + `$13=${state.reportInches}\n` + "$20=0\n" + "$21=0\n" + "$22=0\n" + @@ -359,12 +510,29 @@ const commandsQuery = (req, res, SendWS) => { "$134=300.000\n" + "$135=300.000\n" + "$337=\n" + + `$341=${grblSettings["341"]}\n` + "ok\n" ) res.send("") return } + //settings write e.g. $13=1 (report in inches) + if (/\$\d+=/.test(url)) { + const m = url.match(/\$(\d+)=([^\s&]*)/) + if (m) { + grblSettings[m[1]] = m[2] + if (m[1] === "13") { + state.reportInches = m[2] === "1" ? "1" : "0" + //echo so the UI updates reportUnit immediately + SendWS(`$13=${state.reportInches}\n`) + } + } + SendWS("ok\n") + res.send("") + return + } + if (url.indexOf("ESP600") != -1) { const text = url.substring(8) SendWS(text, false) @@ -3001,7 +3169,10 @@ const loginURI = (req, res) => { if (req.body.DISCONNECT == "YES") { res.status(401) logindone = false - } else if (req.body.USER == "admin" && req.body.PASSWORD == "admin") { + } else if ( + !enableAuthentication || + (req.body.USER == "admin" && req.body.PASSWORD == "admin") + ) { logindone = true lastconnection = Date.now() } else { @@ -3013,7 +3184,7 @@ const loginURI = (req, res) => { const configURI = (req, res) => { if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -3060,4 +3231,8 @@ module.exports = { loginURI, getLastconnection, hasEnabledAuthentication, + startAutoReport, + //the firmware roots its /files API and default document at /www + //(HostPath), while static URLs and uploads use the real FS path + webRoot: "/www", } diff --git a/config/targets/Printer3D/Marlin-embedded/index.js b/config/targets/Printer3D/Marlin-embedded/index.js index 421df1532..02d3a3682 100644 --- a/config/targets/Printer3D/Marlin-embedded/index.js +++ b/config/targets/Printer3D/Marlin-embedded/index.js @@ -4,25 +4,24 @@ Copyright (c) 2020 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const wscolor = chalk.cyan const expresscolor = chalk.green const commandcolor = chalk.white -const enableAuthentication = false +const enableAuthentication = process.env.AUTH === "1" const SERIAL_PROTOCOL = "RAW" let lastconnection = Date.now() let logindone = false @@ -213,7 +212,7 @@ const commandsQuery = (req, res, SendWS) => { } if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -506,12 +505,12 @@ const commandsQuery = (req, res, SendWS) => { Authentication: "Disabled", WebCommunication: "Synchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "esp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/", + HostPath: process.env.WEBROOT || "/", Time: "none", }, }) @@ -896,7 +895,10 @@ const loginURI = (req, res) => { if (req.body.DISCONNECT == "YES") { res.status(401) logindone = false - } else if (req.body.USER == "admin" && req.body.PASSWORD == "admin") { + } else if ( + !enableAuthentication || + (req.body.USER == "admin" && req.body.PASSWORD == "admin") + ) { logindone = true lastconnection = Date.now() } else { @@ -908,7 +910,7 @@ const loginURI = (req, res) => { const configURI = (req, res) => { if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() diff --git a/config/targets/Printer3D/Marlin/index.js b/config/targets/Printer3D/Marlin/index.js index a86a3a97e..e64e495f4 100644 --- a/config/targets/Printer3D/Marlin/index.js +++ b/config/targets/Printer3D/Marlin/index.js @@ -4,25 +4,24 @@ Copyright (c) 2020 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const wscolor = chalk.cyan const expresscolor = chalk.green const commandcolor = chalk.white -const enableAuthentication = false +const enableAuthentication = process.env.AUTH === "1" const SERIAL_PROTOCOL = "RAW" const SDCONNECTION = "none" let lastconnection = Date.now() @@ -216,7 +215,7 @@ const commandsQuery = (req, res, SendWS, context) => { } if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -638,12 +637,12 @@ const commandsQuery = (req, res, SendWS, context) => { Authentication: "Disabled", WebCommunication: "Asynchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "esp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/", + HostPath: process.env.WEBROOT || "/", Time: "none", }, }) @@ -661,12 +660,12 @@ const commandsQuery = (req, res, SendWS, context) => { Authentication: "Disabled", WebCommunication: "Synchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "esp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/", + HostPath: process.env.WEBROOT || "/", Time: "none", CameraID: "4", CameraName: "ESP32 Cam", @@ -1073,7 +1072,10 @@ const loginURI = (req, res) => { if (req.body.DISCONNECT == "YES") { res.status(401) logindone = false - } else if (req.body.USER == "admin" && req.body.PASSWORD == "admin") { + } else if ( + !enableAuthentication || + (req.body.USER == "admin" && req.body.PASSWORD == "admin") + ) { logindone = true lastconnection = Date.now() } else { @@ -1085,7 +1087,7 @@ const loginURI = (req, res) => { const configURI = (req, res) => { if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() diff --git a/config/targets/Printer3D/Repetier/index.js b/config/targets/Printer3D/Repetier/index.js index 35f0ab9f3..9e46da5c1 100644 --- a/config/targets/Printer3D/Repetier/index.js +++ b/config/targets/Printer3D/Repetier/index.js @@ -4,25 +4,24 @@ Copyright (c) 2020 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const wscolor = chalk.cyan const expresscolor = chalk.green const commandcolor = chalk.white -const enableAuthentication = false +const enableAuthentication = process.env.AUTH === "1" let lastconnection = Date.now() let logindone = false const sessiontTime = 60000 @@ -204,7 +203,7 @@ const commandsQuery = (req, res, SendWS) => { } if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -537,12 +536,12 @@ const commandsQuery = (req, res, SendWS) => { Authentication: enableAuthentication ? "Enabled" : "Disabled", WebCommunication: "Synchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "esp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/", + HostPath: process.env.WEBROOT || "/", Time: "none", CameraID: "4", CameraName: "ESP32 Cam", @@ -929,7 +928,10 @@ const loginURI = (req, res) => { if (req.body.DISCONNECT == "YES") { res.status(401) logindone = false - } else if (req.body.USER == "admin" && req.body.PASSWORD == "admin") { + } else if ( + !enableAuthentication || + (req.body.USER == "admin" && req.body.PASSWORD == "admin") + ) { logindone = true lastconnection = Date.now() } else { @@ -941,7 +943,7 @@ const loginURI = (req, res) => { const configURI = (req, res) => { if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() diff --git a/config/targets/Printer3D/Smoothieware/index.js b/config/targets/Printer3D/Smoothieware/index.js index 55920a1cf..ccfadbc13 100644 --- a/config/targets/Printer3D/Smoothieware/index.js +++ b/config/targets/Printer3D/Smoothieware/index.js @@ -4,25 +4,24 @@ Copyright (c) 2020 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const wscolor = chalk.cyan const expresscolor = chalk.green const commandcolor = chalk.white -const enableAuthentication = false +const enableAuthentication = process.env.AUTH === "1" let lastconnection = Date.now() let logindone = false const sessiontTime = 60000 @@ -200,7 +199,7 @@ const commandsQuery = (req, res, SendWS) => { } if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -797,12 +796,12 @@ const commandsQuery = (req, res, SendWS) => { Authentication: enableAuthentication ? "Enabled" : "Disabled", WebCommunication: "Synchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "smoothesp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/", + HostPath: process.env.WEBROOT || "/", Time: "none", CameraID: "4", CameraName: "ESP32 Cam", @@ -1189,7 +1188,10 @@ const loginURI = (req, res) => { if (req.body.DISCONNECT == "YES") { res.status(401) logindone = false - } else if (req.body.USER == "admin" && req.body.PASSWORD == "admin") { + } else if ( + !enableAuthentication || + (req.body.USER == "admin" && req.body.PASSWORD == "admin") + ) { logindone = true lastconnection = Date.now() } else { @@ -1201,7 +1203,7 @@ const loginURI = (req, res) => { const configURI = (req, res) => { if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() diff --git a/config/targets/SandTable/GRBL/index.js b/config/targets/SandTable/GRBL/index.js index 2a4182ca1..4856ee1f0 100644 --- a/config/targets/SandTable/GRBL/index.js +++ b/config/targets/SandTable/GRBL/index.js @@ -4,25 +4,24 @@ Copyright (c) 2020 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public + modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + version 3 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. + General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + You should have received a copy of the GNU General Public + License along with This code; if not, see . */ const chalk = require("chalk") const wscolor = chalk.cyan const expresscolor = chalk.green const commandcolor = chalk.white -const enableAuthentication = false +const enableAuthentication = process.env.AUTH === "1" let lastconnection = Date.now() let logindone = false const sessiontTime = 60000 @@ -75,7 +74,7 @@ const commandsQuery = (req, res, SendWS) => { } if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() @@ -149,12 +148,12 @@ const commandsQuery = (req, res, SendWS) => { Authentication: "Disabled", WebCommunication: "Synchronous", WebSocketIP: "localhost", - WebSocketPort: "81", + WebSocketPort: process.env.WS_PUBLIC_PORT || "8089", Hostname: "esp3d", WiFiMode: "STA", WebUpdate: "Enabled", FlashFileSystem: "LittleFS", - HostPath: "/", + HostPath: process.env.WEBROOT || "/", Time: "none", CameraID: "4", CameraName: "ESP32 Cam", @@ -593,7 +592,10 @@ const loginURI = (req, res) => { if (req.body.DISCONNECT == "YES") { res.status(401) logindone = false - } else if (req.body.USER == "admin" && req.body.PASSWORD == "admin") { + } else if ( + !enableAuthentication || + (req.body.USER == "admin" && req.body.PASSWORD == "admin") + ) { logindone = true lastconnection = Date.now() } else { @@ -605,7 +607,7 @@ const loginURI = (req, res) => { const configURI = (req, res) => { if (!logindone && enableAuthentication) { - res.status(401) + res.sendStatus(401) return } lastconnection = Date.now() diff --git a/config/webpack.dev.js b/config/webpack.dev.js index ec5874b81..c444fa174 100644 --- a/config/webpack.dev.js +++ b/config/webpack.dev.js @@ -11,6 +11,12 @@ console.log("Target:", target, " Subtarget:", subtarget) module.exports = { resolve: { alias: { + // Local icon registry replaces preact-feather (same named exports, + // much smaller footprint: shared SVG wrapper + path data only) + "preact-feather": path.resolve( + __dirname, + "../src/components/Icons/index.js" + ), TargetDir: path.resolve(__dirname, "../src/targets", target), SubTargetDir: path.resolve( __dirname, @@ -28,7 +34,15 @@ module.exports = { }, devServer: { historyApiFallback: true, // to make our SPA works after a full reload, so that it serves 'index.html' when 404 response - open: true, + // secure mode (npm run dev-xxx secure): page served by Caddy over https + open: process.env.SECURE ? "https://localhost:8443/" : true, + // HMR websocket must go through the Caddy front in secure mode: + // the default URL is derived from the page (https) but keeps this + // server's plain-http port, which fails with ERR_SSL_PROTOCOL_ERROR + // and retries forever. Caddy proxies the ws upgrade to 8088. + client: process.env.SECURE + ? { webSocketURL: "wss://localhost:8443/ws" } + : undefined, static: { directory: path.resolve(__dirname, "server", "public"), }, diff --git a/config/webpack.prod.js b/config/webpack.prod.js index 169fd226b..b9e4cef72 100644 --- a/config/webpack.prod.js +++ b/config/webpack.prod.js @@ -14,11 +14,18 @@ const { purgeContent, purgeSafelist } = require("./purgecss.config") let target = process.env.TARGET_ENV ? process.env.TARGET_ENV : "Printer3D" let subtarget = process.env.SUBTARGET_ENV ? process.env.SUBTARGET_ENV : "Marlin" -const runAnalyzer = process.env.ANALYZE === "1" || process.env.ANALYZE === "true" +const runAnalyzer = + process.env.ANALYZE === "1" || process.env.ANALYZE === "true" module.exports = { resolve: { alias: { + // Local icon registry replaces preact-feather (same named exports, + // much smaller footprint: shared SVG wrapper + path data only) + "preact-feather": path.resolve( + __dirname, + "../src/components/Icons/index.js" + ), TargetDir: path.resolve(__dirname, "../src/targets", target), SubTargetDir: path.resolve( __dirname, @@ -110,25 +117,33 @@ module.exports = { "/" + subtarget + "/[base].gz", - algorithm: "gzip", + // Zopfli: ~4% smaller than zlib gzip, output remains + // standard gzip readable by any browser / ESP3D. + // (provided by gzipper dependency: @gfx/zopfli) + algorithm: (input, options, callback) => + require("@gfx/zopfli").gzip( + input, + { numiterations: 15 }, + callback + ), exclude: /.map$/, deleteOriginalAssets: false, }), new Compression({ - test: /\.(html)$/, - filename: - "[path]../dist/" + - target + - "/" + - subtarget + - "/[base].br", - algorithm: "brotliCompress", - compressionOptions: { - level: 11, // max compression - }, - exclude: /.map$/, - deleteOriginalAssets: false, - }), + test: /\.(html)$/, + filename: + "[path]../dist/" + + target + + "/" + + subtarget + + "/[base].br", + algorithm: "brotliCompress", + compressionOptions: { + level: 11, // max compression + }, + exclude: /.map$/, + deleteOriginalAssets: false, + }), ]), ...(runAnalyzer ? [ @@ -164,7 +179,9 @@ module.exports = { }), ], }, - devtool: "source-map", // supposedly the ideal type without bloating bundle size + // No source maps in prod: they are excluded from the final gz anyway, + // and disabling them speeds up the build. + devtool: false, performance: { // All JS/CSS is intentionally inlined into a single HTML file for embedded targets. // The resulting index.html will always exceed webpack's default 244 KiB hint. diff --git a/dist/BUNDLE_SIZES.md b/dist/BUNDLE_SIZES.md index 1e5933ebb..43b785d3e 100644 --- a/dist/BUNDLE_SIZES.md +++ b/dist/BUNDLE_SIZES.md @@ -4,13 +4,13 @@ Generated by `tools/release_bundle_sizes.py`. Use this table in RELEASE_*.md or | Target | Subtarget | Gzip Path | Gzip Size | Brotli Path | Brotli Size | |--------|-----------|-----------|-----------|-------------|-------------| -| CNC | GRBL | CNC\GRBL\index.html.gz | 92.1 KB | CNC\GRBL\index.html.br | 76.4 KB | -| CNC | grblHAL | CNC\grblHAL\index.html.gz | 96.9 KB | CNC\grblHAL\index.html.br | 79.7 KB | -| Printer3D | Marlin | Printer3D\Marlin\index.html.gz | 98.2 KB | Printer3D\Marlin\index.html.br | 81.0 KB | -| Printer3D | Marlin-embedded | Printer3D\Marlin-embedded\index.html.gz | 97.6 KB | Printer3D\Marlin-embedded\index.html.br | 80.5 KB | -| Printer3D | Repetier | Printer3D\Repetier\index.html.gz | 96.9 KB | Printer3D\Repetier\index.html.br | 79.9 KB | -| Printer3D | Smoothieware | Printer3D\Smoothieware\index.html.gz | 96.6 KB | Printer3D\Smoothieware\index.html.br | 79.6 KB | -| SandTable | GRBL | SandTable\GRBL\index.html.gz | 84.4 KB | SandTable\GRBL\index.html.br | 69.9 KB | +| CNC | GRBL | CNC\GRBL\index.html.gz | 87.3 KB | CNC\GRBL\index.html.br | 76.7 KB | +| CNC | grblHAL | CNC\grblHAL\index.html.gz | 92.4 KB | CNC\grblHAL\index.html.br | 81.0 KB | +| Printer3D | Marlin | Printer3D\Marlin\index.html.gz | 92.3 KB | Printer3D\Marlin\index.html.br | 80.9 KB | +| Printer3D | Marlin-embedded | Printer3D\Marlin-embedded\index.html.gz | 91.6 KB | Printer3D\Marlin-embedded\index.html.br | 80.3 KB | +| Printer3D | Repetier | Printer3D\Repetier\index.html.gz | 90.8 KB | Printer3D\Repetier\index.html.br | 79.7 KB | +| Printer3D | Smoothieware | Printer3D\Smoothieware\index.html.gz | 90.7 KB | Printer3D\Smoothieware\index.html.br | 79.5 KB | +| SandTable | GRBL | SandTable\GRBL\index.html.gz | 79.7 KB | SandTable\GRBL\index.html.br | 70.0 KB | -**Total Gzip size:** 662.7 KB (678616 bytes). -**Total Brotli size:** 547.1 KB (560234 bytes). +**Total Gzip size:** 624.8 KB (639762 bytes). +**Total Brotli size:** 548.1 KB (561268 bytes). diff --git a/dist/CNC/GRBL/index.html.br b/dist/CNC/GRBL/index.html.br index 817f804d4..5822ec05f 100644 Binary files a/dist/CNC/GRBL/index.html.br and b/dist/CNC/GRBL/index.html.br differ diff --git a/dist/CNC/GRBL/index.html.gz b/dist/CNC/GRBL/index.html.gz index 369dee19e..dbae6eefd 100644 Binary files a/dist/CNC/GRBL/index.html.gz and b/dist/CNC/GRBL/index.html.gz differ diff --git a/dist/CNC/GRBLHal/index.html.br b/dist/CNC/GRBLHal/index.html.br index b85281363..1fe53da2e 100644 Binary files a/dist/CNC/GRBLHal/index.html.br and b/dist/CNC/GRBLHal/index.html.br differ diff --git a/dist/CNC/GRBLHal/index.html.gz b/dist/CNC/GRBLHal/index.html.gz index 6805b7548..12851e2a6 100644 Binary files a/dist/CNC/GRBLHal/index.html.gz and b/dist/CNC/GRBLHal/index.html.gz differ diff --git a/dist/CNC/grblHAL/index.html.br b/dist/CNC/grblHAL/index.html.br index b85281363..1fe53da2e 100644 Binary files a/dist/CNC/grblHAL/index.html.br and b/dist/CNC/grblHAL/index.html.br differ diff --git a/dist/CNC/grblHAL/index.html.gz b/dist/CNC/grblHAL/index.html.gz index 6805b7548..12851e2a6 100644 Binary files a/dist/CNC/grblHAL/index.html.gz and b/dist/CNC/grblHAL/index.html.gz differ diff --git a/dist/Printer3D/Marlin-embedded/index.html.br b/dist/Printer3D/Marlin-embedded/index.html.br index d6c300257..f629f9590 100644 Binary files a/dist/Printer3D/Marlin-embedded/index.html.br and b/dist/Printer3D/Marlin-embedded/index.html.br differ diff --git a/dist/Printer3D/Marlin-embedded/index.html.gz b/dist/Printer3D/Marlin-embedded/index.html.gz index 027302787..3ab32ca9a 100644 Binary files a/dist/Printer3D/Marlin-embedded/index.html.gz and b/dist/Printer3D/Marlin-embedded/index.html.gz differ diff --git a/dist/Printer3D/Marlin/index.html.br b/dist/Printer3D/Marlin/index.html.br index 4e7401540..35f18e9b9 100644 Binary files a/dist/Printer3D/Marlin/index.html.br and b/dist/Printer3D/Marlin/index.html.br differ diff --git a/dist/Printer3D/Marlin/index.html.gz b/dist/Printer3D/Marlin/index.html.gz index fcb4587a4..af3a94a72 100644 Binary files a/dist/Printer3D/Marlin/index.html.gz and b/dist/Printer3D/Marlin/index.html.gz differ diff --git a/dist/Printer3D/Repetier/index.html.br b/dist/Printer3D/Repetier/index.html.br index 0ba978771..7f3a56cd9 100644 Binary files a/dist/Printer3D/Repetier/index.html.br and b/dist/Printer3D/Repetier/index.html.br differ diff --git a/dist/Printer3D/Repetier/index.html.gz b/dist/Printer3D/Repetier/index.html.gz index 1600d397b..0896168a1 100644 Binary files a/dist/Printer3D/Repetier/index.html.gz and b/dist/Printer3D/Repetier/index.html.gz differ diff --git a/dist/Printer3D/Smoothieware/index.html.br b/dist/Printer3D/Smoothieware/index.html.br index 47ea47cf3..3b3b5c3ca 100644 Binary files a/dist/Printer3D/Smoothieware/index.html.br and b/dist/Printer3D/Smoothieware/index.html.br differ diff --git a/dist/Printer3D/Smoothieware/index.html.gz b/dist/Printer3D/Smoothieware/index.html.gz index 48856d660..8284d8bd9 100644 Binary files a/dist/Printer3D/Smoothieware/index.html.gz and b/dist/Printer3D/Smoothieware/index.html.gz differ diff --git a/dist/SandTable/GRBL/index.html.br b/dist/SandTable/GRBL/index.html.br index ea061a2c4..092d6b82f 100644 Binary files a/dist/SandTable/GRBL/index.html.br and b/dist/SandTable/GRBL/index.html.br differ diff --git a/dist/SandTable/GRBL/index.html.gz b/dist/SandTable/GRBL/index.html.gz index de5c961c2..bea16a512 100644 Binary files a/dist/SandTable/GRBL/index.html.gz and b/dist/SandTable/GRBL/index.html.gz differ diff --git a/docs/Devin-luc-github-ESP3D-WEBUI.md b/docs/Devin-luc-github-ESP3D-WEBUI.md new file mode 100644 index 000000000..1d9053e4d --- /dev/null +++ b/docs/Devin-luc-github-ESP3D-WEBUI.md @@ -0,0 +1,14676 @@ +# Repo-Note + +## Purpose + +ESP3D-WEBUI provides a client-side graphical user interface for communicating with embedded machine firmware. It is used by operators to control 3D printers, CNC systems, and kinetic sand tables via web browsers. + +## Key Technologies + +Preact, Spectre.css, JavaScript, Node.js, HTML5, WebSockets, Gzip, Brotli + +## Top-Level Structure + +- `src/`: Frontend application source code +- `dist/`: Compiled production distribution bundles +- `README.md`: Setup instructions and metadata +- `package.json`: Node dependencies and build scripts +- `package-lock.json`: Deterministic dependency lock file +- `info.json`: Version metadata and build targets +- `.all-contributorsrc`: Contributor tracking configuration + +## Key Concepts + +- ESP3D-WEBUI: Preact-based client web interface layer +- GRBL / GRBL-HAL: CNC milling controller firmware +- Marlin: 3D printer motion control firmware +- Smoothieware: 32-bit ARM printer and CNC firmware +- Repetier: 3D printer host and server ecosystem +- Sand Table: Kinetic art plotter mechanism +- ExtraContentItem: Dynamic content and extension container +- G-code: Numerical control machine programming language +- DRO: Digital Readout for real-time axis coordinates +- Compressed Assets: Gzip and Brotli distribution bundles + +--- + +# 1-Overview + +# Overview +Relevant source files + +- [.all-contributorsrc](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.all-contributorsrc) +- [.github/ci/final-check.sh](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh) +- [.github/workflows/build-ci.yml](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml) +- [LICENSE](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/LICENSE) +- [README.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1) +- [dist/Printer3D/Repetier/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Repetier/index.html.gz) +- [dist/Printer3D/Smoothieware/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Smoothieware/index.html.gz) +- [dist/SandTable/GRBL/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/SandTable/GRBL/index.html.gz) +- [info.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json) +- [src/components/App/version.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js) +- [src/components/ExtraContent/extraContentItem.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js) + +## Purpose and Scope + +ESP3D-WEBUI is a universal web interface for controlling and monitoring 3D printers, CNC machines, and sand tables. This documentation covers the complete system architecture, build process, and development workflow for ESP3D-WEBUI version 3.0. + +**Related Documentation:** + +- For detailed feature descriptions, see [Features and Capabilities](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/1.1?branch=%223.0%22) +- For firmware-specific details, see [Supported Targets and Firmware](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/1.2?branch=%223.0%22) +- For installation procedures, see [Installation and Deployment](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/1.3?branch=%223.0%22) +- For development setup, see [Development Guide](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/11?branch=%223.0%22) + +**Sources:**[README.md#1-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L1-L78)[src/components/App/version.js#20](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L20-L20)[info.json#1-4](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L1-L4) + +## What is ESP3D-WEBUI? + +ESP3D-WEBUI is a single-page web application (SPA) built with Preact that provides a unified control interface for 3D printers, CNC machines, and sand tables. The application targets resource-constrained ESP32/ESP8266 devices by compiling into a single compressed `index.html.gz` file (typically 300-400KB) served from the device's flash storage. + +**Core Architecture:** + +[Flowchart Diagram] + +**Key Technical Characteristics:** + +- **Multi-Target Build System**: Target-specific configurations in `src/targets/` generate firmware-optimized builds. +- **Context-Based State Management**: `UiContext`, `SettingsContext`, and `TargetContext` manage application state. +- **HTTP Queue System**: `useHttpQueue` hook manages command queuing with retry logic. +- **WebSocket Streaming**: Real-time data parsed by target-specific `processData` functions. +- **Compressed Single-File Deployment**: Webpack bundles all assets into `index.html.gz`. + +**Sources:**[README.md#1-9](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L1-L9)[src/components/App/version.js#1-26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L1-L26)[src/areas/index.js#20-26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L20-L26) + +## Technology Stack and Build Pipeline + +ESP3D-WEBUI uses a carefully selected technology stack optimized for minimal bundle size: + +| | | | +| --- | --- | --- | +| **Preact** | UI Framework (3KB) | [src/areas/index.js#20](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L20-L20) imports `h`, `Fragment`, `render` | +| **Spectre.css** | Lightweight CSS Framework | Replaces Bootstrap 4.x for smaller footprint | +| **Webpack** | Module Bundler | Configured in build scripts | +| **Babel** | ES6+ Transpiler | Transforms JSX and modern JavaScript | +| **Sass** | CSS Preprocessor | `.scss` files compiled to CSS | +| **Express + express-ws** | Dev Server | WebSocket support via `express-ws`, static files via `express-static-gzip` | + +**Build Pipeline Architecture:** + +[Flowchart Diagram] + +**Build Commands:** + +- Development: `npm run dev--` (launches Express server on port 8088) [README.md#38-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L38-L52) +- Production: `npm run -` (outputs to `dist/`) [README.md#64-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L64-L75) +- Build all: `npm run buildall` (generates all target variants) [README.md#54-62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L62) + +**Sources:**[README.md#6-7](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L6-L7)[README.md#38-69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L38-L69)[src/areas/index.js#20](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L20-L20) + +## Compatible Backend Systems + +ESP3D-WEBUI 3.0 is compatible with the following backend systems: + +[Flowchart Diagram] + +**Version Information:** + +- **WebUI Version**: `3.0.2` (defined in [src/components/App/version.js#20](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L20-L20)) +- **Backend Compatibility**: ESP3D 3.0, ESP3DLib 3.0, grblHAL, ESP3D_TFT 1.0 [README.md#9](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L9-L9) + +**Sources:**[README.md#6](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L6-L6)[src/components/App/version.js#20-24](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L20-L24)[info.json#2](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L2-L2) + +## Supported Firmware Types + +ESP3D-WEBUI supports six primary firmware types across three machine categories: + +| | | | | +| --- | --- | --- | --- | +| **3D Printer** | Marlin | `npm run printer-marlin` | `dist/Printer3D/Marlin/` | +| | Marlin-embedded (ESP3DLib) | `npm run printer-marlin-embedded` | `dist/Printer3D/Marlin-embedded/` | +| | Repetier | `npm run printer-repetier` | `dist/Printer3D/Repetier/` | +| | Smoothieware | `npm run printer-smoothieware` | `dist/Printer3D/Smoothieware/` | +| **CNC** | GRBL | `npm run cnc-grbl` | `dist/CNC/GRBL/` | +| | grblHAL | `npm run cnc-grblhal` | `dist/CNC/grblHAL/` | +| **Sand Table** | GRBL | `npm run sand-grbl` | `dist/SandTable/GRBL/` | + +Each build produces a firmware-specific `index.html.gz` file optimized for that target's capabilities and UI requirements. + +**Build All Targets:** + +``` +npm run buildall +``` + +**Sources:**[README.md#37-69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L37-L69)[dist/Printer3D/Smoothieware/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Smoothieware/index.html.gz)[dist/Printer3D/Repetier/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Repetier/index.html.gz)[dist/SandTable/GRBL/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/SandTable/GRBL/index.html.gz) + +## High-Level System Architecture + +The following diagram shows the complete lifecycle from development to production deployment: + +**System Architecture Overview** + +[Flowchart Diagram] + +**Sources:**[README.md#15-69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L15-L69)[src/areas/index.js#1-40](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L1-L40) + +## Application Component Architecture + +The application follows a hierarchical component structure with Preact Context API for state management. + +**Component Hierarchy and Context Flow:** + +[Flowchart Diagram] + +**Context API Usage:** + +Each context provides both state and update functions accessible via hooks: + +| | | | | | +| --- | --- | --- | --- | --- | +| **UiContext** | `useUiContext()` | `connection`, `dialogs`, `toasts`, `modals`, `panels` | `setConnectionState()`, `showToast()`, `showModal()`, `panels.setVisibility()` | [src/contexts/UiContext](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext) | +| **SettingsContext** | `useSettingsContext()` | `interfaceSettings`, `connectionSettings`, `featuresSettings` | `updateSettings()`, `loadSettings()`, `saveSettings()` | [src/contexts/SettingsContext](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/SettingsContext) | +| **TargetContext** | `useTargetContext()` | `temperatures`, `positions`, `printState`, `gcodeParams` | `processData()`, `updateTargetState()` | [src/contexts/TargetContext](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/TargetContext) | + +**View Routing Logic:** + +`ViewContainer` implements conditional rendering based on authentication and connection state [src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73) + +**Sources:**[src/areas/index.js#20-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L20-L73)[src/areas/index.js#75-240](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L75-L240) + +## Development vs. Production Flow + +**Development Mode:** + +``` +npm run dev-- +# Example: npm run dev-printer-marlin +# Opens http://localhost:8088 +``` + +In development mode, an Express server with WebSocket support simulates the ESP3D backend, enabling rapid iteration without hardware [README.md#38-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L38-L52) + +**Production Build:** + +``` +npm run - +# Example: npm run printer-marlin +# Outputs: dist/Printer3D/Marlin/index.html.gz +``` + +Production builds create a single compressed HTML file containing all JavaScript, CSS, and resources, which is uploaded to the ESP3D device's filesystem [README.md#64-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L64-L75) + +**Sources:**[README.md#33-69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L33-L69) + +## Communication Architecture + +ESP3D-WEBUI employs a multi-layered communication architecture for interacting with the ESP3D device. + +**HTTP and WebSocket Communication Layers:** + +[Flowchart Diagram] + +**HTTP Request Patterns:** + +| | | | | +| --- | --- | --- | --- | +| **Queued Requests** | `useHttpQueue()` | Commands requiring order/retry | G-code commands, file operations | +| **Single Requests** | `useHttpFn` | One-off queries | Configuration fetch, status check | + +**Extension IFrame Communication:** + +Extensions (loaded via `ExtraContentItem`) communicate with the main UI via `postMessage`[src/components/ExtraContent/extraContentItem.js#34-65](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L34-L65) + +[Flowchart Diagram] + +**Sources:**[src/areas/index.js#84-206](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L84-L206)[src/components/ExtraContent/extraContentItem.js#34-170](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L34-L170)[src/components/Helpers](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers) + +## Key Architectural Patterns + +**1. Target Configuration System** +Each firmware type has a target-specific configuration in `src/targets/` defining capabilities and response filters. + +**2. Context-Based State Management** +Transient UI state, persistent settings, and runtime machine data are isolated into separate Preact contexts. + +**3. Capability-Driven UI** +UI elements are conditionally rendered based on the machine's reported capabilities and current connection state. + +**4. Real-Time Data Pipeline** + +[Flowchart Diagram] + +**5. Single-File Deployment** +The build process ensures that the entire application, including styles and translations, is bundled into a single compressed file for easy flashing to ESP devices. + +**Sources:**[src/areas/index.js#75-240](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L75-L240)[README.md#1-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L1-L78)[src/targets/](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/) + +## Version and Compatibility + +**Current Version:**`3.0.2`[src/components/App/version.js#20](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L20-L20) + +Version information is defined across multiple files: + +- **WebUI Version**: `webUIversion = "3.0.2"` in [src/components/App/version.js#20](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L20-L20) +- **Development Version**: `devt: "3.1.0 beta 1"` in [info.json#3](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L3-L3) +- **Build Number**: `webUIbuild` imported from target-specific configuration [src/components/App/version.js#19](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L19-L19) + +**Sources:**[README.md#9](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L9-L9)[src/components/App/version.js#1-26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L1-L26)[info.json#1-4](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L1-L4) + +## License + +ESP3D-WEBUI is licensed under the GNU General Public License v3.0 [LICENSE#1-674](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/LICENSE#L1-L674) The software is provided "as is" without warranty [README.md#15-18](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L15-L18) + +## Additional Resources + +- **Project Website**: [https://esp3d.io](https://esp3d.io) +- **Discord Community**: [https://discord.gg/Z4ujTwE](https://discord.gg/Z4ujTwE) +- **GitHub Repository**: [https://github.com/luc-github/ESP3D-WEBUI](https://github.com/luc-github/ESP3D-WEBUI) + +**Sources:**[README.md#71-83](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L71-L83) + +--- + +# 1.1-Features-and-Capabilities + +# Features and Capabilities +Relevant source files + +- [.all-contributorsrc](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.all-contributorsrc) +- [.github/ci/final-check.sh](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh) +- [.github/workflows/build-ci.yml](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml) +- [LICENSE](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/LICENSE) +- [README.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1) +- [dist/CNC/GRBL/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBL/index.html.gz) +- [dist/CNC/GRBLHal/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBLHal/index.html.gz) +- [dist/Printer3D/Marlin-embedded/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin-embedded/index.html.gz) +- [dist/Printer3D/Marlin/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin/index.html.gz) +- [dist/Printer3D/Repetier/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Repetier/index.html.gz) +- [dist/Printer3D/Smoothieware/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Smoothieware/index.html.gz) +- [dist/SandTable/GRBL/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/SandTable/GRBL/index.html.gz) +- [info.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json) +- [src/components/App/version.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js) +- [src/components/ExtraContent/extraContentItem.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js) + +ESP3D-WEBUI is a high-performance, responsive web interface designed to control 3D printers, CNC machines, and sand tables running [ESP3D](https://github.com/luc-github/ESP3D/tree/3.0) or [ESP3DLib](https://github.com/luc-github/ESP3DLib/tree/3.0) firmware. Built with **Preact** and **Spectre.css**, it provides a lightweight alternative to traditional heavy web interfaces, optimized for the resource-constrained environments of ESP32 and ESP8266 microcontrollers. [README.md#1-13](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L1-L13) + +## Multi-Firmware and Multi-Target Support + +The core strength of ESP3D-WEBUI is its ability to adapt to different machine types and firmware protocols using a single codebase. This is achieved through a "Target" abstraction layer. + +### Supported Build Targets + +The build system generates specialized `index.html.gz` files for specific combinations of machine types and firmware. [README.md#43-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L43-L50) + +| | | | | +| --- | --- | --- | --- | +| **CNC** | GRBL | `npm run cnc-grbl` | `dist/CNC/GRBL/index.html.gz` | +| **CNC** | grblHAL | `npm run cnc-grblhal` | `dist/CNC/GRBLHal/index.html.gz` | +| **Printer** | Marlin | `npm run printer-marlin` | `dist/Printer3D/Marlin/index.html.gz` | +| **Printer** | Marlin-Embedded | `npm run printer-marlin-embedded` | `dist/Printer3D/Marlin-embedded/index.html.gz` | +| **Printer** | Repetier | `npm run printer-repetier` | `dist/Printer3D/Repetier/index.html.gz` | +| **Printer** | Smoothieware | `npm run printer-smoothieware` | `dist/Printer3D/Smoothieware/index.html.gz` | +| **Sand Table** | GRBL | `npm run sand-grbl` | `dist/SandTable/GRBL/index.html.gz` | + +### Target Abstraction Architecture + +Each target defines its own parsing logic, UI preferences, and command sets. The `webUIbuild` variable is used to distinguish these builds at runtime. [src/components/App/version.js#19-23](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L19-L23) + +**Target Logic Association** + +[Flowchart Diagram] + +Sources: [src/targets/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/index.js)[src/components/App/version.js#19](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L19-L19) + +## Real-Time Monitoring and Control + +The UI provides live updates of machine state, temperatures, and positions by processing serial streams from the firmware. + +### Data Processing Pipeline + +Data flows from the machine via WebSockets or HTTP, where it is buffered and parsed by target-specific filters. + +1. **Ingress**: Raw data enters through `processData` in the communication layer. +2. **Filtering**: Target-specific `filters.js` identify patterns (e.g., temperature reports `T:210.0 /220.0`). +3. **State Update**: Parsed values are dispatched to the `TargetContext` to trigger UI re-renders. + +**Firmware Data Flow** + +```mermaid +sequenceDiagram + participant FW as Firmware (Marlin/GRBL) + participant COMM as processData() + participant FILT as filters.js (isTemperatures) + participant CTX as TargetContext + participant UI as TemperaturesPanel + FW->>COMM: "T:200.0 /200.0 B:60.0 /60.0" + COMM->>FILT: Extract Line + FILT-->>COMM: Match Found + COMM->>CTX: updateState({hotend: 200}) + CTX->>UI: Trigger Re-render +``` + +Sources: [src/targets/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/index.js)[dist/Printer3D/Marlin/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin/index.html.gz) (simulated logic based on build targets). + +## File Management System + +ESP3D-WEBUI features a unified file management interface that abstracts operations across various storage backends. + +### Supported Storage Backends + +The system can interact with multiple sources simultaneously: + +- **FLASH**: Internal ESP module storage. +- **SD**: Standard SD card attached to the controller. +- **DIRECTSD**: Direct SPI access to SD cards (supported by grblHAL). +- **TFT SD/USB**: Storage attached to a connected TFT screen. + +### Capabilities and Commands + +The file system is controlled via the `files` object in each target, which defines: + +- `capability(source, cap)`: Checks if a source supports `upload`, `delete`, or `download`. +- `command(source, op, params)`: Executes operations like `list`, `play`, or `upload`. + +Sources: [dist/CNC/GRBLHal/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBLHal/index.html.gz)[dist/Printer3D/Marlin-embedded/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin-embedded/index.html.gz) (Capability sets vary by target). + +## Extensibility and Custom Content + +The UI can be extended without modifying the core codebase through "Extra Content" and "Extensions". + +### ExtraContentItem Component + +The `ExtraContentItem` component allows embedding external resources such as camera feeds or custom web pages. [src/components/ExtraContent/extraContentItem.js#34-42](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L34-L42) + +- **Camera/Image**: Supports MJPEG streams or static images with auto-refresh via `refreshtime`. [src/components/ExtraContent/extraContentItem.js#69-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L69-L73) +- **Extensions**: Loads HTML content into a sandboxed iframe. [src/components/ExtraContent/extraContentItem.js#74-76](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L74-L76) +- **Lifecycle Management**: Tracks visibility state (`visibilityState`) to pause background refreshes when the panel is hidden, saving bandwidth and ESP resources. [src/components/ExtraContent/extraContentItem.js#102-105](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L102-L105) + +### Extension Communication + +Extensions can communicate with the main UI using `postMessage`. + +- **Parent to Extension**: Notifies the extension about visibility changes. [src/components/ExtraContent/extraContentItem.js#53-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L53-L61) +- **Extension to Parent**: Can trigger commands or request machine state through `dispatchToExtensions`. [src/components/ExtraContent/extraContentItem.js#22](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L22-L22) + +**Extension Integration Map** + +[Flowchart Diagram] + +Sources: [src/components/ExtraContent/extraContentItem.js#21-28](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L21-L28)[src/components/ExtraContent/extraContentItem.js#154-166](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L154-L166) + +## Build System and Deployment + +The project uses a Webpack-based pipeline to minimize the final footprint. + +- **Compression**: All production assets are Gzipped. The ESP32 serves the `.gz` file directly, and the browser handles decompression. [dist/CNC/GRBL/index.html.gz#1](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBL/index.html.gz#L1-L1) +- **Versioning**: The UI version (e.g., `3.0.2`) and target-specific build IDs are embedded in the UI. [src/components/App/version.js#20-23](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L20-L23) +- **Development Server**: Developers can run `npm run dev--` to start a local server at `localhost:8088` with hot-module replacement. [README.md#38-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L38-L52) + +Sources: [README.md#54-62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L62)[src/components/App/version.js#18-25](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L18-L25) + +--- + +# 1.2-Supported-Targets-and-Firmware + +# Supported Targets and Firmware +Relevant source files + +- [.all-contributorsrc](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.all-contributorsrc) +- [.github/ci/final-check.sh](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh) +- [.github/workflows/build-ci.yml](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml) +- [LICENSE](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/LICENSE) +- [README.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1) +- [dist/CNC/GRBL/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBL/index.html.gz) +- [dist/CNC/GRBLHal/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBLHal/index.html.gz) +- [dist/Printer3D/Marlin-embedded/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin-embedded/index.html.gz) +- [dist/Printer3D/Marlin/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin/index.html.gz) +- [info.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json) +- [src/targets/Printer3D/Marlin-embedded/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/preferences.json) +- [src/targets/Printer3D/Marlin/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json) +- [src/targets/Printer3D/Repetier/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json) +- [src/targets/Printer3D/Smoothieware/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/preferences.json) +- [src/targets/Printer3D/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json) +- [src/targets/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json) + +## Purpose and Scope + +This document catalogs all supported machine types and firmware variants in ESP3D-WEBUI, detailing the specific configurations available for each target platform. ESP3D-WEBUI employs a **multi-target build architecture** that generates firmware-specific web interface builds from a single codebase. Each target represents a combination of machine type (3D Printer, CNC, SandTable) and firmware implementation (Marlin, GRBL, Repetier, etc.). + +For information about how the target system is implemented and how to extend it, see [Target Configuration System](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/Target Configuration System) For deployment procedures, see [Installation and Deployment](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/Installation and Deployment) + +--- + +## Target Overview + +ESP3D-WEBUI supports three primary machine categories, each with multiple firmware variants. The selection is determined at build time via `npm` scripts which map to specific directory structures in `src/targets/`. + +**System Mapping to Code Entities** + +[Flowchart Diagram] + +**Sources:**[README.md#46-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L46-L50)[README.md#70-74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L70-L74)[src/targets/Printer3D/preferences.json#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L1-L10)[src/targets/CNC/preferences.json#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json#L1-L10) + +--- + +## 3D Printer Targets + +### Marlin + +**Build Output:**`dist/Printer3D/Marlin/index.html.gz` + +Standard Marlin firmware implementation for FDM 3D printers. It is optimized for the full Marlin G-code command set and provides comprehensive hardware monitoring. + +**Key Features:** + +- **Temperature Control:** Support for multiple extruders, heated bed, and chamber. +- **File Systems:** Unified access to `SD`, `DIRECTSD`, `FLASH`, `SDEXT`, `TFTSD`, and `TFTUSB`[src/targets/Printer3D/Marlin/preferences.json#184-200](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L184-L200) +- **Emergency Stop:** Hardcoded to `M112`[src/targets/Printer3D/Marlin/preferences.json#8](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L8-L8) +- **Polling:** Default status polling uses `M105` every 3000ms [src/targets/Printer3D/Marlin/preferences.json#62-63](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L62-L63) + +**Sources:**[src/targets/Printer3D/Marlin/preferences.json#1-152](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L1-L152)[dist/Printer3D/Marlin/index.html.gz#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin/index.html.gz#L1-L10) + +--- + +### Marlin-embedded + +**Build Output:**`dist/Printer3D/Marlin-embedded/index.html.gz` + +Specialized variant for **embedded mode** where the ESP3D device (running `ESP3DLib`) shares the serial connection with a host computer or a TFT screen. + +**Key Differences:** + +- **Shared Connection:** Optimized for `SDConnection` modes where the serial line is not exclusive to the WebUI. +- **Simplified UI:** Reduced polling frequency and simplified file management to minimize serial traffic interference. +- **Compatibility:** Specifically targets `ESP3DLib 3.0`[README.md#9](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L9-L9) + +**Sources:**[dist/Printer3D/Marlin-embedded/index.html.gz#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin-embedded/index.html.gz#L1-L10)[src/targets/Printer3D/Marlin-embedded/preferences.json#1-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/preferences.json#L1-L50) + +--- + +### Repetier + +**Build Output:**`dist/Printer3D/Repetier/index.html.gz` + +Supports Repetier firmware's unique response formats and command structures. + +**Key Features:** + +- **File Management:** Uses `M20` for listing but allows configuration of `sdlistcmd`, `sdplaycmd`, and `sddeletecmd`[src/targets/Printer3D/Repetier/preferences.json#97-135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json#L97-L135) +- **Default Storage:** Defaults to `FLASH` but supports `SD`, `TFTSD`, and `TFTUSB` backends [src/targets/Printer3D/Repetier/preferences.json#161-196](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json#L161-L196) + +**Sources:**[src/targets/Printer3D/Repetier/preferences.json#1-200](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json#L1-L200) + +--- + +### Smoothieware + +**Build Output:**`dist/Printer3D/Smoothieware/index.html.gz` + +Supports the Smoothieware firmware which utilizes Unix-like commands (e.g., `ls`, `cd`) rather than standard G-code for file operations. + +**Sources:**[README.md#49](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L49-L49)[src/targets/Printer3D/Smoothieware/preferences.json#1-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/preferences.json#L1-L50) + +--- + +## CNC Targets + +### GRBL + +**Build Output:**`dist/CNC/GRBL/index.html.gz` + +Standard GRBL firmware for 3-axis CNC machines, lasers, and spindles. + +**Key Features:** + +- **Real-time Interaction:** Uses `?` for status reports and character-based overrides (feed/spindle). +- **Settings Management:** Full support for `$`-prefixed configuration parameters (e.g., `$0` to `$132`). +- **Jogging:** Optimized for `$J=` jogging commands. + +**Sources:**[src/targets/CNC/GRBL/preferences.json#1-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/preferences.json#L1-L50)[dist/CNC/GRBL/index.html.gz#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBL/index.html.gz#L1-L10) + +--- + +### GrblHAL + +**Build Output:**`dist/CNC/GRBLHal/index.html.gz` + +The next-generation GRBL (Hardware Abstraction Layer) target, supporting up to 6 axes and advanced hardware features. + +**Key Features:** + +- **Extended Axes:** Support for X, Y, Z, A, B, and C axes. +- **DIRECTSD:** Implements a high-performance direct SD card access protocol [dist/CNC/GRBLHal/index.html.gz#20-25](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBLHal/index.html.gz#L20-L25) +- **Compatibility:** Compatible with `grblHAL` core [README.md#9](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L9-L9) + +**Sources:**[src/targets/CNC/grblHAL/preferences.json#1-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L1-L50)[dist/CNC/GRBLHal/index.html.gz#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBLHal/index.html.gz#L1-L10) + +--- + +## Target Configuration Hierarchy + +Each target build is composed of a three-tier configuration hierarchy. The build system merges these `preferences.json` files to create the final application state. + +**Configuration Merge Flow** + +[Flowchart Diagram] + +**Sources:**[src/targets/preferences.json#3-120](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L3-L120)[src/targets/Printer3D/preferences.json#1-166](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L1-L166)[src/targets/Printer3D/Marlin/preferences.json#1-176](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L1-L176) + +--- + +## Feature Matrix by Target + +| | | | | | +| --- | --- | --- | --- | --- | +| **Emergency Stop** | `M112` | `M112` | `Ctrl+X` | `Ctrl+X` | +| **Status Polling** | `M105`/`M114` | `M105` | `?` | `?` | +| **Max Axes** | 4 (XYZ+E) | 4 (XYZ+E) | 3 (XYZ) | 6 (XYZABC) | +| **Laser Panel** | No | No | Yes | Yes | +| **Storage: FLASH** | Yes | Yes | Yes | Yes | +| **Storage: SD** | Yes | Yes | No | Yes | +| **Storage: DIRECTSD** | Yes | No | No | Yes | + +**Sources:**[src/targets/Printer3D/Marlin/preferences.json#8-184](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L8-L184)[src/targets/Printer3D/Repetier/preferences.json#8-189](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json#L8-L189)[src/targets/CNC/GRBL/preferences.json#1-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/preferences.json#L1-L50)[src/targets/CNC/grblHAL/preferences.json#1-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L1-L50) + +--- + +## Build Artifacts + +The project generates a compressed single-file application for each target. These are located in the `dist/` directory following the hierarchy of the `src/targets/` folder. + +**Artifact Structure:** + +- `dist/Printer3D/Marlin/index.html.gz`[dist/Printer3D/Marlin/index.html.gz#1](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin/index.html.gz#L1-L1) +- `dist/Printer3D/Marlin-embedded/index.html.gz`[dist/Printer3D/Marlin-embedded/index.html.gz#1](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin-embedded/index.html.gz#L1-L1) +- `dist/CNC/GRBL/index.html.gz`[dist/CNC/GRBL/index.html.gz#1](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBL/index.html.gz#L1-L1) +- `dist/CNC/GRBLHal/index.html.gz`[dist/CNC/GRBLHal/index.html.gz#1](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBLHal/index.html.gz#L1-L1) + +**Sources:**[README.md#54-62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L62)[dist/Printer3D/Marlin/index.html.gz#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Marlin/index.html.gz#L1-L10)[dist/CNC/GRBL/index.html.gz#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/CNC/GRBL/index.html.gz#L1-L10) + +--- + +# 1.3-Installation-and-Deployment + +# Installation and Deployment +Relevant source files + +- [.all-contributorsrc](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.all-contributorsrc) +- [.github/ci/final-check.sh](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh) +- [.github/workflows/build-ci.yml](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml) +- [LICENSE](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/LICENSE) +- [README.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1) +- [info.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json) +- [package-lock.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package-lock.json) +- [package.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json) + +## Purpose and Scope + +This document covers the complete lifecycle of setting up, building, and deploying ESP3D-WEBUI from source code to a running ESP3D device. It includes development environment configuration, build pipeline execution, and deployment procedures for all supported firmware targets. This version of the WebUI (3.0) is built using Preact and Spectre.css for a lightweight footprint suitable for embedded controllers. + +--- + +## Prerequisites + +### Node.js and npm + +ESP3D-WEBUI requires Node.js LTS version 20.8.0 or compatible for the build toolchain: + +``` +node -v +# Expected output: v20.8.0 + +npm -v +# Expected output: 10.2.0 +``` + +### Target Hardware Compatibility + +Deployment requires one of the following compatible firmware versions: + +- **ESP3D 3.0** (ESP8266/ESP32) +- **ESP3DLib 3.0** (For Marlin-embedded targets) +- **grblHAL** (CNC controllers) +- **ESP3D_TFT 1.0** (TFT-based configurations) + +**Sources:**[README.md#9-30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L9-L30)[package.json#3-4](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L3-L4) + +--- + +## Development Environment Setup + +### 1. Clone Repository + +``` +git clone https://github.com/luc-github/ESP3D-WEBUI.git +cd ESP3D-WEBUI +``` + +### 2. Install Dependencies + +From the repository root directory, install the required node modules: + +``` +npm install +``` + +This populates the `node_modules/` directory with the following core dependencies: + +- **UI Framework:**`preact`[package.json#72](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L72-L72) +- **Icons:**`preact-feather`[package.json#73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L73-L73) +- **Charts:**`smoothie`[package.json#74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L74-L74) +- **CSS Framework:**`spectre.css`[package.json#75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L75-L75) +- **Build Tools:**`webpack`, `babel-loader`, `sass-loader`[package.json#38-70](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L38-L70) + +[Flowchart Diagram] + +**Sources:**[README.md#32-36](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L32-L36)[package.json#37-76](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L37-L76) + +--- + +## Development Workflow + +### Starting the Development Server + +The development environment utilizes `concurrently` to run a local Express server and the Webpack development server simultaneously. This allows for real-time UI updates while simulating device communication. + +``` +npm run dev-- +``` + +### Available Target Combinations + +The build system uses `TARGET_ENV` and `SUBTARGET_ENV` environment variables to inject the correct target context during compilation. + +| | | | +| --- | --- | --- | +| `Printer3D` | `Marlin` | `npm run dev-printer-marlin` | +| `Printer3D` | `Marlin-embedded` | `npm run dev-printer-marlin-embedded` | +| `Printer3D` | `Repetier` | `npm run dev-printer-repetier` | +| `Printer3D` | `Smoothieware` | `npm run dev-printer-smoothieware` | +| `CNC` | `GRBL` | `npm run dev-cnc-grbl` | +| `CNC` | `grblHAL` | `npm run dev-cnc-grblhal` | +| `SandTable` | `GRBL` | `npm run dev-sand-grbl` | + +Example for CNC with grblHAL: + +``` +npm run dev-cnc-grblhal +``` + +This command triggers `cross-env TARGET_ENV=CNC SUBTARGET_ENV=grblHAL concurrently "npm run server" "npm run front"`[package.json#11](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L11-L11) + +Loading diagram… + +**Sources:**[README.md#38-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L38-L52)[package.json#10-17](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L10-L17) + +--- + +## Building for Production + +### Target-Specific Builds + +To build a production-ready `index.html.gz` for a specific machine: + +``` +npm run - +``` + +These scripts invoke Webpack with `config/webpack.prod.js`[package.json#18-24](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L18-L24) + +### Full Distribution Build + +To generate artifacts for all supported targets at once: + +``` +npm run buildall +``` + +This executes `buildsand`, `buildprinter`, and `buildcnc` sequentially [package.json#29](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L29-L29) + +### Build Artifacts Structure + +Generated files are placed in the `dist/` directory, organized by target type and firmware: + +- `dist/Printer3D/Marlin/index.html.gz` +- `dist/Printer3D/Repetier/index.html.gz` +- `dist/CNC/GRBL/index.html.gz` +- ...and others for each target combination. + +**Sources:**[README.md#54-74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L74)[package.json#18-29](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L18-L29) + +--- + +## Deployment to ESP3D Devices + +### Deployment Procedure + +1. **Locate Artifact:** Navigate to the `dist/` folder and select the `index.html.gz` file that matches your machine's firmware (e.g., `dist/CNC/grblHAL/index.html.gz`). +2. **Access Web Interface:** Connect to your ESP3D device's current IP address in a browser. +3. **Upload File:** Use the device's built-in file manager or system update tool to upload the new `index.html.gz`. + +- Note: The file must be named exactly `index.html.gz` on the device's filesystem for the web server to serve it as the default page. +4. **Restart/Refresh:** Once the upload is complete, refresh the page. The device will serve the compressed file, which the browser will automatically decompress and render. + +### Continuous Integration (CI) + +The project uses GitHub Actions to automate builds on every push to major branches (`2.1`, `3.0`, `3.1`). The CI workflow performs the following: + +1. Installs libraries via `npm install`[.github/workflows/build-ci.yml#26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml#L26-L26) +2. Executes `npm run buildall` to verify all targets compile successfully [.github/workflows/build-ci.yml#30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml#L30-L30) +3. Runs a final check script [.github/ci/final-check.sh](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh) which notifies Discord via webhook if configured [.github/workflows/build-ci.yml#37-42](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml#L37-L42) + +Loading diagram… + +**Sources:**[.github/workflows/build-ci.yml#1-43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml#L1-L43)[.github/ci/final-check.sh#17-35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh#L17-L35) + +--- + +## Versioning and Information + +The current version of the WebUI is tracked in `info.json`: + +- **Stable Version:**`3.0.1`[info.json#2](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L2-L2) +- **Development Version:**`3.1.0 beta 1`[info.json#3](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L3-L3) + +This information is used by the build system to tag generated artifacts and is displayed in the UI's about/information sections. + +**Sources:**[info.json#1-4](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L1-L4)[package.json#3](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/package.json#L3-L3) + +--- + +# 2-Architecture-Overview + +# Architecture Overview +Relevant source files + +- [.all-contributorsrc](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.all-contributorsrc) +- [.github/ci/final-check.sh](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh) +- [.github/workflows/build-ci.yml](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml) +- [LICENSE](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/LICENSE) +- [README.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1) +- [dist/Printer3D/Repetier/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Repetier/index.html.gz) +- [dist/Printer3D/Smoothieware/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Smoothieware/index.html.gz) +- [dist/SandTable/GRBL/index.html.gz](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/SandTable/GRBL/index.html.gz) +- [info.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json) +- [src/areas/elementsCache.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js) +- [src/components/App/version.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js) +- [src/components/ExtraContent/extraContentItem.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js) +- [src/contexts/UiContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js) +- [src/hooks/eventBus.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js) + +## Purpose and Scope + +This document provides a high-level overview of the ESP3D-WEBUI system architecture. It describes the build pipeline, the runtime environment based on Preact, and the core abstraction layers that allow the interface to support a wide variety of 3D printers and CNC firmwares. + +For deep dives into specific subsystems, refer to the following child pages: + +- [Multi-Target Build Architecture](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.1?branch=%223.0%22) — The cascading configuration system. +- [Client-Server Communication](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.2?branch=%223.0%22) — HTTP and WebSocket protocols. +- [Context and State Management](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.3?branch=%223.0%22) — Preact contexts (`UiContext`, `SettingsContext`, `TargetContext`). +- [File System Abstraction Layer](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.4?branch=%223.0%22) — Unified API for FLASH, SD, and TFT storage. +- [Component Hierarchy](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.5?branch=%223.0%22) — The UI tree from `ViewContainer` to fields. + +--- + +## System Architecture Overview + +ESP3D-WEBUI is a single-page application (SPA) built with Preact and Spectre.css. It operates as a thin client that communicates with ESP3D firmware running on ESP32 or ESP8266 hardware. + +### High-Level Component Interaction + +[Flowchart Diagram] + +**Sources:**[src/contexts/UiContext.js#33-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L33-L57)[src/components/App/version.js#18-25](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L18-L25) + +--- + +## Multi-Target Build Architecture + +The codebase uses a cascading build system to generate optimized firmware-specific bundles. A single command like `npm run buildall` triggers Webpack to produce tailored versions for Marlin, GRBL, Smoothieware, and others. + +| | | | +| --- | --- | --- | +| **Printer3D** | Marlin, Repetier, Smoothieware | `dist/Printer3D/` | +| **CNC** | GRBL, grblHAL | `dist/CNC/` | +| **SandTable** | GRBL | `dist/SandTable/` | + +Each build results in a highly compressed `index.html.gz` file (typically ~45-50KB) designed to fit within the limited flash space of ESP devices. + +**Sources:**[README.md#42-74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L42-L74)[dist/Printer3D/Smoothieware/index.html.gz#1-2](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/Printer3D/Smoothieware/index.html.gz#L1-L2)[dist/SandTable/GRBL/index.html.gz#1-2](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/dist/SandTable/GRBL/index.html.gz#L1-L2) + +--- + +## State and Context Management + +The application state is partitioned into three primary Preact contexts to ensure efficient updates and clear separation of concerns. + +1. **`UiContext`**: Manages the "Application Shell" state, including the connection status (`connectionState`), active modals, toasts, and panel visibility. +2. **`SettingsContext`**: Stores persistent user preferences and hardware configuration (e.g., `interfaceSettings`). +3. **`TargetContext`**: A firmware-specific context provided by the active target. it holds real-time machine data like positions, temperatures, and buffer status. + +**Sources:**[src/contexts/UiContext.js#33-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L33-L61)[src/areas/elementsCache.js#28-29](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L28-L29) + +--- + +## Real-time Data Pipeline + +Data flows from the machine firmware to the UI through a pattern-matching filter system. Raw strings from the WebSocket or HTTP responses are passed through `filters.js` to update the application state. + +[Flowchart Diagram] + +**Sources:**[src/areas/elementsCache.js#32-38](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L32-L38)[src/components/ExtraContent/extraContentItem.js#67-86](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L67-L86) + +--- + +## Extension and Extra Content System + +ESP3D-WEBUI features an extensible architecture that allows embedding external tools (like G-Code viewers or camera feeds) via the `ExtraContentItem` component. + +- **`ElementsCache`**: A hidden DOM area (`#elementsCache`) where extra content is pre-rendered to maintain state even when panels are closed. +- **`ExtraContentItem`**: Handles the lifecycle of iframes or images, including refresh intervals and visibility notifications via `postMessage`. +- **`eventBus`**: A lightweight mechanism used to share data between components and extensions without the overhead of a full Preact context. + +**Sources:**[src/areas/elementsCache.js#66-72](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L66-L72)[src/components/ExtraContent/extraContentItem.js#34-65](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js#L34-L65)[src/hooks/eventBus.js#25-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js#L25-L52) + +--- + +## Versioning + +The WebUI maintains its own versioning independent of the ESP3D backend. + +- **WebUI Version**: `3.0.2` (defined in `src/components/App/version.js`) +- **Build Version**: Appended during the build process based on the target configuration. + +**Sources:**[src/components/App/version.js#20-25](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L20-L25)[info.json#2-3](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json#L2-L3) + +--- + +# 2.1-Multi-Target-Build-Architecture + +# Multi-Target Build Architecture +Relevant source files + +- [.all-contributorsrc](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.all-contributorsrc) +- [.github/ci/final-check.sh](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/ci/final-check.sh) +- [.github/workflows/build-ci.yml](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/.github/workflows/build-ci.yml) +- [LICENSE](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/LICENSE) +- [Memo/Commands.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/Memo/Commands.md?plain=1) +- [Memo/ESP3D [ESP400] format.md](Memo/ESP3D [ESP400] format.md) +- [README.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1) +- [config/targets/CNC/GRBL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/CNC/GRBL/index.js) +- [config/targets/Printer3D/Marlin-embedded/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin-embedded/index.js) +- [config/targets/Printer3D/Marlin/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js) +- [config/targets/Printer3D/Repetier/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Repetier/index.js) +- [config/targets/Printer3D/Smoothieware/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Smoothieware/index.js) +- [config/targets/SandTable/GRBL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/SandTable/GRBL/index.js) +- [info.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/info.json) +- [src/targets/Printer3D/Marlin/DIRECTSD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/DIRECTSD-source.js) +- [src/targets/Printer3D/Marlin/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/FLASH-source.js) +- [src/targets/Printer3D/Marlin/files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/files.js) + +## Purpose and Scope + +This document explains how ESP3D-WEBUI's build system produces firmware-specific, optimized web bundles from a single codebase. The multi-target build architecture enables one source tree to generate specialized builds for different machine types (`cnc`, `printer`, `sand`) and firmware variants (`marlin`, `grbl`, `grblhal`, `smoothieware`, etc.), each with appropriate UI components, settings, and command protocols [README.md#43-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L43-L50) + +--- + +## Overview + +ESP3D-WEBUI implements a **single-codebase, multi-target build strategy** where: + +- **One source tree** contains all UI code using Preact [README.md#6-7](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L6-L7) +- **Target-specific configurations** define firmware behaviors and simulated server responses [config/targets/Printer3D/Marlin/index.js#1-30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js#L1-L30) +- **Build scripts** generate optimized, compressed `.html.gz` bundles for each target [README.md#54-62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L62) +- **Output structure** organizes builds by machine type and firmware [README.md#67-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L67-L75) + +This architecture eliminates code duplication while allowing each target to have tailored functionality, settings schemas, and command protocols. + +**Sources:**[README.md#1-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L1-L75)[config/targets/Printer3D/Marlin/index.js#1-30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js#L1-L30) + +--- + +## Build System Components + +The build system is orchestrated through npm scripts to transform modern JavaScript and SCSS into a single, compressed HTML file optimized for embedded deployment on [ESP3D 3.0](https://github.com/luc-github/ESP3D/tree/3.0) and [grblHAL](https://github.com/grblHAL) devices [README.md#9-35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L9-L35) + +| | | +| --- | --- | +| **Node.js** | Runtime environment (v20.8.0 recommended) [README.md#22-26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L22-L26) | +| **npm** | Package manager (v10.2.0 recommended) [README.md#28-30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L28-L30) | +| **Webpack** | Module bundler used to generate production versions [README.md#62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L62-L62) | +| **Dev Server** | Local test server for rapid iteration [README.md#52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L52-L52) | +| **Gzip** | Compression for the final `index.html.gz`[README.md#54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L54) | + +**Sources:**[README.md#9-62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L9-L62) + +--- + +## Target Matrix + +ESP3D-WEBUI supports a variety of system and firmware combinations. + +[Flowchart Diagram] + +**Sources:**[README.md#43-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L43-L50)[README.md#67-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L67-L75) + +--- + +## Build Commands and Script Architecture + +### Production Build Scripts + +The build system generates production-ready files in the `/dist` folder [README.md#54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L54) + +**Build all targets sequentially:** + +``` +npm run buildall +``` + +**Build specific targets:** +The syntax is `npm run -`[README.md#67](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L67-L67) + +- `npm run printer-marlin` +- `npm run cnc-grblhal` +- `npm run sand-grbl` + +### Development Server Scripts + +Development builds use a local test server available at `http://localhost:8088`[README.md#52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L52-L52) + +``` +npm run dev-- +``` + +The development environment includes a mock backend (e.g., `config/targets/Printer3D/Marlin/index.js`) that simulates firmware responses like temperatures, file lists, and position updates [config/targets/Printer3D/Marlin/index.js#137-215](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js#L137-L215) + +**Sources:**[README.md#38-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L38-L75)[config/targets/Printer3D/Marlin/index.js#137-215](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js#L137-L215) + +--- + +## Target-Specific Code Resolution + +**Code Entity Mapping: Target Configuration** + +[Flowchart Diagram] + +### File System Abstraction Layer + +The build system includes target-specific file system implementations. For example, the Marlin target includes specific logic for `FLASH`, `SD`, and `DIRECTSD`[src/targets/Printer3D/Marlin/files.js#21-26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/files.js#L21-L26) + +- **Capabilities**: Defines what the file system can do (e.g., `Upload`, `DeleteFile`, `CreateDir`) [src/targets/Printer3D/Marlin/FLASH-source.js#24-54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/FLASH-source.js#L24-L54) +- **Commands**: Maps UI actions to firmware-specific URLs or G-Code commands [src/targets/Printer3D/Marlin/DIRECTSD-source.js#60-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/DIRECTSD-source.js#L60-L156) +- **Dynamic Selection**: File systems are shown in the UI based on dependencies like `SDConnection` settings [src/targets/Printer3D/Marlin/files.js#30-85](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/files.js#L30-L85) + +**Sources:**[src/targets/Printer3D/Marlin/files.js#21-85](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/files.js#L21-L85)[src/targets/Printer3D/Marlin/FLASH-source.js#24-54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/FLASH-source.js#L24-L54)[src/targets/Printer3D/Marlin/DIRECTSD-source.js#60-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/DIRECTSD-source.js#L60-L156) + +--- + +## Mock Backend Implementation + +For development purposes, each target provides a Node.js-based mock of the firmware's behavior. This allows testing the UI without a physical ESP32. + +**Marlin Mock Example (`config/targets/Printer3D/Marlin/index.js`):** + +- **Temperature Simulation**: Simulates heating and cooling logic with random variations [config/targets/Printer3D/Marlin/index.js#77-127](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js#L77-L127) +- **Command Handling**: Responds to G-Codes like `M114` (Position) and `M20` (File List) [config/targets/Printer3D/Marlin/index.js#192-215](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js#L192-L215) +- **ESP-Specific Commands**: Handles `ESP800` (System Info) and `ESP420` (Status) queries [config/targets/CNC/GRBL/index.js#85-168](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/CNC/GRBL/index.js#L85-L168) + +**Sources:**[config/targets/Printer3D/Marlin/index.js#77-215](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js#L77-L215)[config/targets/CNC/GRBL/index.js#85-168](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/CNC/GRBL/index.js#L85-L168) + +--- + +## Build Pipeline Flow + +**Build Process Visualization** + +[Flowchart Diagram] + +**Sources:**[README.md#54-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/README.md?plain=1#L54-L75)[src/targets/Printer3D/Marlin/files.js#1-130](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/files.js#L1-L130) + +--- + +## Continuous Integration (CI) + +The project uses GitHub Actions to ensure build integrity across all targets. The `build-ci` workflow automatically runs `npm install` and `npm run buildall` on every push to the `3.0` and `3.1` branches [`.github/workflows/build-ci.yml:1-30`](). + +- **Automated Validation**: Verifies that all target combinations compile successfully [`.github/workflows/build-ci.yml:28-31`](). +- **Notification**: Sends build status updates (Success/Failure) to a Discord webhook [`.github/ci/final-check.sh:17-35`](). + +**Sources:**[`.github/workflows/build-ci.yml:1-31`](), [`.github/ci/final-check.sh:17-35`]() + +--- + +# 2.2-Client-Server-Communication + +# Client-Server Communication +Relevant source files + +- [server/CNC/GRBL/Flash/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/server/CNC/GRBL/Flash/preferences.json) +- [src/components/Helpers/http.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js) +- [src/contexts/WsContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js) +- [src/tabs/interface/importHelper.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/importHelper.js) +- [src/targets/Printer3D/Marlin-embedded/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/SD-source.js) +- [src/targets/Printer3D/Marlin/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js) +- [src/targets/Printer3D/Marlin/SDEXT-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SDEXT-source.js) + +This page describes the HTTP and WebSocket communication protocols used by ESP3D-WEBUI to exchange data between the browser client and the ESP3D device. It covers URL construction, authentication mechanisms, request queue management, and the backend server architecture that translates web requests into firmware-specific serial commands. + +For information about how target-specific data is processed after receiving responses, see [Data Processing Pipeline](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.3?branch=%223.0%22). For details on connection state management and authentication flows, see [Connection Management](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.2?branch=%223.0%22). + +--- + +## Overview + +ESP3D-WEBUI uses a **three-layer communication architecture**: + +[Flowchart Diagram] + +**Sources**: [src/contexts/WsContext.js#41-53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L41-L53)[src/components/Helpers/http.js#37-49](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L37-L49) + +--- + +## HTTP Communication + +### URL Construction + +The `espHttpURL` helper function constructs properly-formatted URLs for communicating with the ESP3D device: + +[Flowchart Diagram] + +The function handles both relative and absolute URLs: + +| | | | +| --- | --- | --- | +| Relative path | `"command"` | Appends to `window.location.host`[src/components/Helpers/http.js#42](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L42-L42) | +| Absolute URL | `"http://192.168.1.100/command"` | Uses as-is [src/components/Helpers/http.js#40](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L40-L40) | +| Empty base | `""` | Returns current host [src/components/Helpers/http.js#42](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L42-L42) | + +**Key behavior**: Query parameters are automatically URL-encoded and appended using `URLSearchParams`[src/components/Helpers/http.js#45-48](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L45-L48) + +**Sources**: [src/components/Helpers/http.js#37-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L37-L50) + +### Authentication + +ESP3D-WEBUI uses **cookie-based session authentication**: + +```mermaid +sequenceDiagram + participant Client as WsContext.js + participant Server as ESP3D Server + participant Firmware as Serial Firmware + Client->>Server: GET /command?cmd=[ESP800] + Server-->>Client: 401 Unauthorized + Client->>Client: showLogin() + Client->>Server: POST /login {user, password} + Server->>Server: Validate credentials + Server-->>Client: Set-Cookie: ESPSESSIONID=... + Client->>Server: GET /command?cmd=M105 Cookie: ESPSESSIONID=... + Server->>Firmware: M105 (serial) + Firmware-->>Server: ok T:25.0 + Server-->>Client: 200 OK {temperature data} +``` + +**Cookie handling**: + +- `getCookie(cname)` retrieves session cookies from `document.cookie`[src/components/Helpers/http.js#19-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L19-L33) +- In `WsContext.js`, the session cookie is retrieved and sent as a `PING` message to maintain the connection [src/contexts/WsContext.js#66-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L66-L68) + +**Sources**: [src/components/Helpers/http.js#19-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L19-L33)[src/contexts/WsContext.js#66-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L66-L68) + +--- + +## WebSocket Communication + +### Connection Management + +The `WsContext.js` file manages the WebSocket lifecycle. It includes a heartbeat mechanism (`ping`) and reconnection logic [src/contexts/WsContext.js#38-40](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L38-L40) + +| | | +| --- | --- | +| **Ping Delay** | 5000ms [src/contexts/WsContext.js#38](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L38-L38) | +| **Max Retries** | 4 attempts [src/contexts/WsContext.js#39](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L39-L39) | +| **Binary Support** | Handles `ArrayBuffer` for stream data [src/contexts/WsContext.js#77-80](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L77-L80) | +| **Session Check** | Pings include `ESPSESSIONID`[src/contexts/WsContext.js#66-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L66-L68) | + +**Sources**: [src/contexts/WsContext.js#36-71](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L36-L71) + +### Real-time Data Streaming + +Incoming WebSocket messages are parsed based on their prefix [src/contexts/WsContext.js#84-140](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L84-L140) + +| | | | +| --- | --- | --- | +| `CURRENTID` | Updates local WebSocket ID | [src/contexts/WsContext.js#85-87](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L85-L87) | +| `PING` | Monitors session timeout/expiry | [src/contexts/WsContext.js#93-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L93-L101) | +| `NOTIFICATION` | Triggers a UI Toast notification | [src/contexts/WsContext.js#102-122](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L102-L122) | +| `ERROR` | Aborts current HTTP request and alerts user | [src/contexts/WsContext.js#123-135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L123-L135) | +| Default | Passes data to `processData("core", ...)` | [src/contexts/WsContext.js#137-138](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L137-L138) | + +**Sources**: [src/contexts/WsContext.js#73-142](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L73-L142) + +--- + +## File System Communication Protocols + +File operations vary significantly between storage backends (FLASH vs. SD vs. SDEXT). + +### SD Card Protocol (Marlin) + +The `SD-source.js` defines how the client interacts with the printer's SD card via serial commands [src/targets/Printer3D/Marlin/SD-source.js#178-180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L178-L180) + +| | | | +| --- | --- | --- | +| **List Files** | Serial Command | Sends `sdlistcmd` (usually `M20`) [src/targets/Printer3D/Marlin/SD-source.js#88](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L88-L88) | +| **Play/Print** | Serial Command | Replaces `#` in `sdplaycmd` with path [src/targets/Printer3D/Marlin/SD-source.js#136](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L136-L136) | +| **Delete** | Serial Command | Replaces `#` in `sddeletecmd` with path [src/targets/Printer3D/Marlin/SD-source.js#148](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L148-L148) | +| **Upload** | HTTP URL | Uses `/upload` endpoint if `SerialProtocol` is "MKS" [src/targets/Printer3D/Marlin/SD-source.js#92-97](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L92-L97) | + +### Response Parsing (Marlin SD) + +The `responseSteps` object defines how to identify the start and end of a serial file list [src/targets/Printer3D/Marlin/SD-source.js#155-176](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L155-L176) + +- **Start**: "Begin file list" [src/targets/Printer3D/Marlin/SD-source.js#159](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L159-L159) +- **End**: "End file list" [src/targets/Printer3D/Marlin/SD-source.js#160](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L160-L160) +- **Errors**: Includes "No SD card", "No media", or "Unknown command: M20" [src/targets/Printer3D/Marlin/SD-source.js#161-168](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L161-L168) + +**Sources**: [src/targets/Printer3D/Marlin/SD-source.js#84-176](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L84-L176)[src/targets/Printer3D/Marlin/SDEXT-source.js#84-178](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SDEXT-source.js#L84-L178) + +--- + +## Client-Side Request Management + +### useHttpQueue Hook + +The `useHttpQueue` hook provides **request queue management** for operations that must be sequential. + +[Flowchart Diagram] + +In `WsContext.js`, the `removeAllRequests()` function is called upon disconnection to clear the queue and prevent stale commands from executing [src/contexts/WsContext.js#160](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L160-L160) + +**Sources**: [src/contexts/WsContext.js#43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L43-L43)[src/contexts/WsContext.js#159-160](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L159-L160) + +### Polling Mechanism + +For CNC/GRBL targets, real-time status is often achieved through polling rather than pure push-based WebSockets. The `preferences.json` defines polling commands [server/CNC/GRBL/Flash/preferences.json#64-72](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/server/CNC/GRBL/Flash/preferences.json#L64-L72) + +- **Example**: Sending `?;[ESP701]json` every 3000ms [server/CNC/GRBL/Flash/preferences.json#69-70](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/server/CNC/GRBL/Flash/preferences.json#L69-L70) +- **Management**: Controlled by the `activity` object in `WsContext.js`[src/contexts/WsContext.js#158](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L158-L158) + +**Sources**: [server/CNC/GRBL/Flash/preferences.json#64-72](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/server/CNC/GRBL/Flash/preferences.json#L64-L72)[src/contexts/WsContext.js#158](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L158-L158) + +--- + +## Summary Table: Communication Endpoints + +| | | | | +| --- | --- | --- | --- | +| `/command` | GET | Send G-code/M-codes | `espHttpURL` in `http.js` | +| `/config` | GET | Get device config | `useHttpFn` | +| `/files` | GET | List/download files | `SD-source.js` / `SDEXT-source.js` | +| `/upload` | POST | Upload file | `SD-source.js` (MKS Protocol) | +| `/login` | POST | Authenticate user | `getCookie` in `http.js` | +| WebSocket | WS | Real-time streaming | `WsContext.js` | + +**Sources**: [src/components/Helpers/http.js#37-49](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js#L37-L49)[src/contexts/WsContext.js#41-53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L41-L53)[src/targets/Printer3D/Marlin/SD-source.js#92-97](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L92-L97) + +--- + +# 2.3-Context-and-State-Management + +# Context and State Management +Relevant source files + +- [src/areas/elementsCache.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js) +- [src/components/Helpers/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/filters.js) +- [src/components/Helpers/storedState.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js) +- [src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) +- [src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js) +- [src/contexts/UiContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js) +- [src/hooks/eventBus.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js) +- [src/hooks/useSettings.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js) +- [src/targets/CNC/Controls/QuickStopButton.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js) +- [src/targets/CNC/GRBL/Controls/BackgroundContainer.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js) + +## Purpose and Scope + +This document describes the primary Preact contexts that manage application state in ESP3D-WEBUI: `UiContext`, `SettingsContext`, `TargetContext`, and `DatasContext`. These contexts provide a centralized state management architecture that enables loose coupling between UI components, persistent user preferences, and firmware-specific logic. + +For component lifecycle and data flow, see [Application Lifecycle](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.1?branch=%223.0%22). For target-specific configuration, see [Target Configuration System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4?branch=%223.0%22). + +--- + +## Context Architecture Overview + +ESP3D-WEBUI employs a multi-tier context architecture where each context manages a distinct category of application state. + +| | | | +| --- | --- | --- | +| `UiContext` | [src/contexts/UiContext.js#33-35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L33-L35) | Manages transient UI state (modals, toasts, connection status). | +| `SettingsContext` | [src/contexts/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/index.js) | Manages persistent user configuration and preferences. | +| `TargetContext` | [src/targets/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/index.js) | Manages firmware-specific runtime data (temperatures, positions). | +| `DatasContext` | [src/contexts/DatasContext.js#27-30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L27-L30) | Manages high-volume data like terminal buffers and history. | + +### Context Dependency Graph + +[Flowchart Diagram] + +**Sources:**[src/contexts/UiContext.js#33-35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L33-L35)[src/contexts/DatasContext.js#27-105](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L27-L105)[src/hooks/useSettings.js#58-62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L58-L62) + +--- + +## UiContext: Transient UI State + +### Purpose + +`UiContext` manages ephemeral UI state that does not persist between sessions. This includes the real-time connection status, the active modal stack, and the notification system. + +### Key State and Logic + +The context provides state for managing the visibility of various UI elements: + +- **Panels Management**: Tracks `panelsList`[src/contexts/UiContext.js#36](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L36-L36) and `visiblePanelsListRef`[src/contexts/UiContext.js#38](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L38-L38) It uses `addToVisibles`[src/contexts/UiContext.js#70](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L70-L70) and `removeFromVisibles`[src/contexts/UiContext.js#63](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L63-L63) to control which panels are rendered. +- **Modals and Toasts**: Maintains a stack of `modals`[src/contexts/UiContext.js#44](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L44-L44) and a queue of `toasts`[src/contexts/UiContext.js#45](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L45-L45) +- **Connection State**: A central object `connectionState`[src/contexts/UiContext.js#52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L52-L52) tracks if the UI is `connected`, if it requires `authenticate`, and the current `page` (e.g., "connecting"). + +### Component Integration (Natural Language to Code) + +[Flowchart Diagram] + +**Sources:**[src/contexts/UiContext.js#35-146](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L35-L146)[src/components/Modal/logginModal.js#34-85](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L34-L85) + +--- + +## SettingsContext: Persistent Configuration + +### Purpose + +`SettingsContext` manages user preferences stored in `localStorage`. It utilizes the `useStoredState` hook [src/components/Helpers/storedState.js#21-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js#L21-L33) to ensure values persist across browser refreshes. + +### Implementation Detail + +The `useSettings` hook [src/hooks/useSettings.js#56](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L56-L56) acts as the primary orchestrator for initializing the application based on these settings: + +- **Polling**: `initPolling()`[src/hooks/useSettings.js#92](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L92-L92) reads `enablepolling` and `pollingcmds` from the interface settings and schedules commands via `activity.startPolling`[src/hooks/useSettings.js#135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L135-L135) +- **Initialization**: `getConnectionSettings()`[src/hooks/useSettings.js#173](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L173-L173) fetches firmware configuration (via `[ESP800]`) to sync the web UI with the physical device state. + +**Sources:**[src/hooks/useSettings.js#56-173](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L56-L173)[src/components/Helpers/storedState.js#21-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js#L21-L33) + +--- + +## TargetContext: Firmware Runtime Data + +### Purpose + +`TargetContext` provides firmware-specific runtime state. Unlike `UiContext`, its structure varies depending on the selected machine type (3D Printer vs. CNC). + +### Data Flow and Processing + +The `processData` function [src/hooks/useSettings.js#59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L59-L59) is the entry point for all firmware responses. It routes raw strings through target-specific filters (e.g., `isTemperatures`, `isPositions`) to update the context state. + +| | | | +| --- | --- | --- | +| `variablesList` | Maps generic variables to firmware commands. | [src/targets/CNC/Controls/QuickStopButton.js#35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L35-L35) | +| `replaceVariables` | Utility to inject runtime values into commands. | [src/targets/CNC/Controls/QuickStopButton.js#35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L35-L35) | +| `BackgroundContainer` | Monitors context state (like `alarmCode`) to trigger UI side-effects. | [src/targets/CNC/GRBL/Controls/BackgroundContainer.js#26-43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js#L26-L43) | + +**Sources:**[src/targets/CNC/GRBL/Controls/BackgroundContainer.js#26-43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js#L26-L43)[src/targets/CNC/Controls/QuickStopButton.js#28-69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L28-L69) + +--- + +## DatasContext: Terminal and Buffers + +### Purpose + +`DatasContext`[src/contexts/DatasContext.js#30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L30-L30) handles the "heavy" data stream coming from the machine's serial console. It manages the terminal history and auto-scroll logic. + +### Buffer Management + +To prevent memory leaks and UI lag, `DatasContext` uses `limitArr`[src/contexts/DatasContext.js#21](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L21-L21) to cap the number of lines stored in the terminal. + +- **`terminalBuffer`**: Stores all lines for verbose mode [src/contexts/DatasContext.js#34](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L34-L34) +- **`terminalBufferQuiet`**: Filters out non-essential status updates [src/contexts/DatasContext.js#35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L35-L35) +- **`terminalInputHistory`**: Persists previous commands sent by the user in `localStorage`[src/contexts/DatasContext.js#37](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L37-L37) + +**Sources:**[src/contexts/DatasContext.js#30-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L30-L103) + +--- + +## EventBus: Decoupled Communication + +In addition to Contexts, the system uses an `EventBus`[src/hooks/eventBus.js#25](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js#L25-L25) for non-reactive communication between components that shouldn't trigger a full Preact render cycle. + +### EventBus Mechanism + +```mermaid +sequenceDiagram + participant C as Component + participant EB as EventBus + participant L as Listener + Note over C,L: Decoupled Messaging + L->>EB: on(event | callback) + C->>EB: emit(event | data) + EB->>L: callback(data) +``` + +**Sources:**[src/hooks/eventBus.js#25-80](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js#L25-L80)[src/areas/elementsCache.js#25](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L25-L25) + +--- + +## Context Consumption Summary + +Components access these states through specialized hooks: + +1. **`useUiContext()`**: Access `toasts`, `modals`, and `connection`[src/targets/CNC/Controls/QuickStopButton.js#29](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L29-L29) +2. **`useTargetContext()`**: Access runtime variables like `alarmCode` or `status`[src/targets/CNC/GRBL/Controls/BackgroundContainer.js#27](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js#L27-L27) +3. **`useDatasContext()`**: Access terminal `content` and `add` functions [src/contexts/DatasContext.js#28](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L28-L28) +4. **`useUiContextFn`**: A static object providing helper functions (like `haptic()`) without causing re-renders [src/components/Modal/logginModal.js#53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L53-L53) + +**Sources:**[src/contexts/UiContext.js#34](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L34-L34)[src/contexts/DatasContext.js#28](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L28-L28)[src/hooks/useSettings.js#58-62](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L58-L62) + +--- + +# 2.4-File-System-Abstraction-Layer + +# File System Abstraction Layer +Relevant source files + +- [src/components/Helpers/http.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js) +- [src/tabs/interface/importHelper.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/importHelper.js) +- [src/targets/CNC/GRBL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js) +- [src/targets/CNC/grblHAL/DIRECTSD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js) +- [src/targets/CNC/grblHAL/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js) +- [src/targets/CNC/grblHAL/files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js) +- [src/targets/CNC/grblHAL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js) +- [src/targets/CNC/grblHAL/realCommandsTable.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js) +- [src/targets/CNC/grblHAL/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json) +- [src/targets/CNC/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json) +- [src/targets/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/FLASH-source.js) +- [src/targets/Printer3D/Marlin-embedded/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/SD-source.js) +- [src/targets/Printer3D/Marlin/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js) +- [src/targets/Printer3D/Marlin/SDEXT-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SDEXT-source.js) +- [src/targets/Printer3D/Smoothieware/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/SD-source.js) +- [src/targets/Printer3D/Smoothieware/SDEXT-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/SDEXT-source.js) + +## Purpose and Scope + +The File System Abstraction Layer provides a unified API for interacting with diverse storage backends across different firmware and hardware configurations. This layer enables the ESP3D-WEBUI to perform file operations (list, upload, download, delete, play) without UI components needing knowledge of the underlying storage protocol or hardware implementation. + +This document covers the architecture, storage backend implementations, capability system, and command routing. For information about how these file operations are used in the UI, see [File Manager Panel](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/5.4?branch=%223.0%22). For target-specific configuration that determines which storage types are available, see [Target Configuration System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4?branch=%223.0%22). + +--- + +## Unified Files API + +The file system abstraction is exposed through a `files` object that exports three primary members: + +**API Surface** + +``` +files.command(filesystem, cmd, ...args) // Execute a command +files.capability(filesystem, cap, ...args) // Query capabilities +files.supported // Array of available filesystems +``` + +The `files` object is exported from target-specific modules and provides a consistent interface regardless of firmware type. The API routes requests to the appropriate storage backend based on the `filesystem` parameter. + +**Files API Architecture** + +Loading diagram… + +**Sources:**[src/targets/CNC/grblHAL/files.js#1-84](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L1-L84)[src/targets/CNC/grblHAL/index.js#22](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L22-L22)[src/targets/CNC/grblHAL/index.js#87](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L87-L87) + +--- + +## Storage Backend Implementations + +Each storage type is implemented in a dedicated source file that exports a structured object containing `capabilities`, `commands`, and optionally `responseSteps`. + +### Backend Structure + +Loading diagram… + +**Storage Types by Target** + +| | | | | +| --- | --- | --- | --- | +| **FLASH** | ✓ | ✓ | ESP internal memory (LittleFS/SPIFFS) | +| **SD** | ✓ | ✗ | SD card via serial G-code (M20/M23/M30) | +| **DIRECTSD** | ✓ | ✓ | Hardware direct SD card access | +| **SDEXT** | ✓ | ✗ | External SD card reader | +| **TFTSD** | ✓ | ✗ | TFT display controller SD slot | +| **TFTUSB** | ✓ | ✗ | TFT display controller USB port | + +**Sources:**[src/targets/CNC/grblHAL/files.js#26-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L26-L47)[src/targets/Printer3D/Marlin/SD-source.js#178-180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L178-L180)[src/targets/Printer3D/Marlin/SDEXT-source.js#180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SDEXT-source.js#L180-L180) + +### FLASH Storage + +FLASH storage represents the ESP device's internal memory. It provides full file system capabilities and is accessed via HTTP endpoints. + +**Implementation Details:** + +- **File**: `FLASH-source.js` +- **Protocol**: HTTP JSON API (`/files` endpoint) [src/targets/CNC/grblHAL/FLASH-source.js#57-59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L57-L59) +- **Hierarchical**: Supports directories and nested paths [src/targets/CNC/grblHAL/FLASH-source.js#29](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L29-L29) +- **Features**: Full CRUD operations including directory creation [src/targets/CNC/grblHAL/FLASH-source.js#48-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L48-L50) + +**Key Characteristics:** + +``` +capabilities = { + Process: (path, filename) => canProcessFile(filename), [src/targets/CNC/grblHAL/FLASH-source.js:25-27] + UseFilters: () => true, [src/targets/CNC/grblHAL/FLASH-source.js:28-28] + IsFlatFS: () => false, [src/targets/CNC/grblHAL/FLASH-source.js:29-29] + Upload: () => true, [src/targets/CNC/grblHAL/FLASH-source.js:30-32] + UploadMultiple: () => true, [src/targets/CNC/grblHAL/FLASH-source.js:36-38] + Download: () => true, [src/targets/CNC/grblHAL/FLASH-source.js:39-41] + DeleteFile: () => true, [src/targets/CNC/grblHAL/FLASH-source.js:42-44] + DeleteDir: () => true, [src/targets/CNC/grblHAL/FLASH-source.js:45-47] + CreateDir: () => true [src/targets/CNC/grblHAL/FLASH-source.js:48-50] +} +``` + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#1-134](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L1-L134) + +### SD Storage + +SD storage accesses SD cards through firmware serial protocol commands. The firmware acts as an intermediary, translating HTTP/serial commands to SD operations. + +**Implementation Details:** + +- **File**: `SD-source.js` +- **Protocol**: Serial G-code commands (e.g., `M20`) [src/targets/Printer3D/Marlin/SD-source.js#88](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L88-L88) +- **Flat**: Files listed without directory structure [src/targets/Printer3D/Marlin/SD-source.js#60](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L60-L60) +- **Response Parsing**: Multi-line serial responses parsed using `responseSteps`[src/targets/Printer3D/Marlin/SD-source.js#157-176](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L157-L176) + +**Response Parsing Pattern:** + +``` +responseSteps = { + list: { + start: (data) => data.startsWith("Begin file list"), [src/targets/Printer3D/Marlin/SD-source.js:159-159] + end: (data) => data.startsWith("End file list"), [src/targets/Printer3D/Marlin/SD-source.js:160-160] + error: (data) => data.indexOf("echo:No SD card") != -1 [src/targets/Printer3D/Marlin/SD-source.js:161-168] + } +} +``` + +**Sources:**[src/targets/Printer3D/Marlin/SD-source.js#1-181](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L1-L181) + +### DIRECTSD Storage + +DIRECTSD provides hardware-level access to SD cards, bypassing firmware protocol layer. The ESP device reads/writes SD card directly via HTTP. + +**Implementation Details:** + +- **File**: `DIRECTSD-source.js` +- **Protocol**: HTTP JSON API (`/sdfiles` endpoint) [src/targets/CNC/grblHAL/DIRECTSD-source.js#58-59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L58-L59) +- **Hierarchical**: Full directory support [src/targets/CNC/grblHAL/DIRECTSD-source.js#30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L30-L30) + +**Capability Summary (grblHAL):** + +- **Upload**: Supported (including Multiple) [src/targets/CNC/grblHAL/DIRECTSD-source.js#31-39](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L31-L39) +- **Download**: Supported [src/targets/CNC/grblHAL/DIRECTSD-source.js#40-42](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L40-L42) +- **Directories**: Create and Delete supported [src/targets/CNC/grblHAL/DIRECTSD-source.js#46-51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L46-L51) + +**Sources:**[src/targets/CNC/grblHAL/DIRECTSD-source.js#1-125](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L1-L125) + +--- + +## Capabilities System + +The capabilities system enables runtime UI adaptation based on storage backend features. Each capability is a function that returns a boolean or error message. + +### Capability Functions + +Loading diagram… + +**Capability Types** + +| | | | +| --- | --- | --- | +| `Process(path, filename)` | Can file be executed/streamed? | Boolean | +| `UseFilters()` | Should extension filters apply? | Boolean | +| `IsFlatFS()` | Is filesystem flat (no dirs)? | Boolean | +| `Upload(path, filename, eMsg)` | Can upload files? | Boolean / Error String | +| `UploadMultiple()` | Supports multi-file upload? | Boolean | +| `Download()` | Can download files? | Boolean | +| `DeleteFile()` | Can delete files? | Boolean | +| `DeleteDir()` | Can delete directories? | Boolean | +| `CreateDir()` | Can create directories? | Boolean | + +**Sources:**[src/targets/CNC/grblHAL/files.js#59-66](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L59-L66)[src/targets/CNC/grblHAL/FLASH-source.js#24-51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L24-L51)[src/targets/Printer3D/Marlin/SD-source.js#55-82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L55-L82) + +--- + +## Commands System + +Commands define how to perform operations on each storage backend. Each command returns a command descriptor object. + +### Command Descriptor Types + +Loading diagram… + +**Command Functions (grblHAL FLASH Example):** + +``` +// List operation [src/targets/CNC/grblHAL/FLASH-source.js:54-60] +commands.list = (path, filename) => { + return { + type: "url", + url: "files", + args: { path, action: "list" }, + } +} + +// Play operation [src/targets/CNC/grblHAL/FLASH-source.js:115-127] +commands.play = (path, filename) => { + const spath = (path + (path == "/" ? "" : "/") + filename).replaceAll("//", "/") + const cmd = useUiContextFn.getValue("playcmd").replace("#", spath) + return { type: "cmd", cmd } +} +``` + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#53-129](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L53-L129)[src/targets/CNC/grblHAL/DIRECTSD-source.js#54-120](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L54-L120) + +### Result Formatting + +The `formatResult` function parses backend responses into standardized structures. + +**Format Result Flow:** + +Loading diagram… + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#71-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L71-L78)[src/targets/CNC/grblHAL/DIRECTSD-source.js#69-76](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L69-L76) + +--- + +## Supported Filesystems Registry + +The `supportedFileSystems` array defines which storage types are available for a given target based on settings dependencies. + +**Registry Structure (grblHAL):** + +``` +const supportedFileSystems = [ + { + value: "FLASH", + name: "S137", + depend: () => { + return ( + useUiContextFn.getValue("flashfs") && + useSettingsContextFn.getValue("FlashFileSystem") != "none" + ) + }, + }, + { + value: "DIRECTSD", + name: "S190", + depend: () => { + return ( + useUiContextFn.getValue("directsd") && + useSettingsContextFn.getValue("SDConnection") != "none" + ) + }, + } +] +``` + +**Sources:**[src/targets/CNC/grblHAL/files.js#26-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L26-L47) + +--- + +## File Processing and Streaming + +The `Process` capability and `play` command enable file execution. + +**Processing Logic:** + +- **Extension Check**: Uses `canProcessFile(filename)` to match allowed extensions (e.g., .gcode, .nc) [src/targets/CNC/grblHAL/FLASH-source.js#26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L26-L26) +- **Command Replacement**: The `play` command retrieves the `playcmd` from UI settings and replaces the `#` placeholder with the full file path [src/targets/CNC/grblHAL/DIRECTSD-source.js#106-118](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L106-L118) + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#115-127](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L115-L127)[src/targets/CNC/grblHAL/DIRECTSD-source.js#106-118](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L106-L118)[src/targets/Printer3D/Marlin/SD-source.js#131-141](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L131-L141) + +--- + +## File Upload Handling + +Upload operations are routed either via specific HTTP endpoints or G-code protocols. + +**grblHAL FLASH Upload:** + +- Uses the `/files` URL [src/targets/CNC/grblHAL/FLASH-source.js#67](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L67-L67) +- Prepends `HostUploadPath` setting to the destination path [src/targets/CNC/grblHAL/FLASH-source.js#63-64](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L63-L64) + +**Marlin SD Upload:** + +- Only supported if `SerialProtocol` is set to "MKS" [src/targets/Printer3D/Marlin/SD-source.js#65](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L65-L65) +- Returns a `refresh` type command post-upload to update the UI after a 3000ms timeout [src/targets/Printer3D/Marlin/SD-source.js#104-111](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L104-L111) + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#61-70](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L61-L70)[src/targets/Printer3D/Marlin/SD-source.js#91-113](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L91-L113) + +--- + +## Sorting and Filtering + +The abstraction layer handles sorting and filtering to ensure a consistent UI experience. + +**Sorting:** + +- Triggered by UI context values (e.g., `sort_flashfs_files`, `sort_directsd_files`) [src/targets/CNC/grblHAL/FLASH-source.js#73-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L73-L75) +- Uses `sortedFilesList()` helper to organize the file array [src/targets/CNC/grblHAL/DIRECTSD-source.js#72](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L72-L72) + +**Filtering (Flat Filesystems):** + +- Flat filesystems (like standard Marlin SD) use `filterResultFiles(data.files, path)` to simulate directory structures by filtering files based on path prefixes [src/targets/Printer3D/Marlin/SD-source.js#127](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L127-L127) + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#71-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L71-L78)[src/targets/CNC/grblHAL/DIRECTSD-source.js#69-76](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L69-L76)[src/targets/Printer3D/Marlin/SD-source.js#123-130](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L123-L130) + +--- + +# 2.5-Component-Hierarchy + +# Component Hierarchy +Relevant source files + +- [src/areas/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js) +- [src/components/ExtraContent/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js) +- [src/components/Panels/Files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js) +- [src/components/Panels/Jog.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js) +- [src/components/Panels/JogCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js) +- [src/components/Panels/JogPlotter.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js) +- [src/components/Panels/Notifications.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js) +- [src/components/Panels/OverridesCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js) +- [src/pages/dashboard/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js) + +This document explains the hierarchical structure of Preact components in ESP3D-WEBUI, from the root `ViewContainer` down to individual panels and fields. It covers how components are organized, how conditional rendering determines the UI state (authenticated vs. unauthenticated), and how the panel system provides modular functionality. + +--- + +## Overview of Component Structure + +ESP3D-WEBUI uses a hierarchical component architecture where `ContentContainer` serves as the application root. It orchestrates all top-level functionality including context management, extension messaging, and lifecycle handling. The hierarchy branches based on authentication state: authenticated users see the full interface with panels, while unauthenticated users see only the connection/login screen. + +**Component Tree (High-Level)** + +[Flowchart Diagram] + +**Sources:**[src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73)[src/areas/index.js#75-306](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L75-L306) + +--- + +## ContentContainer - Application Root + +The `ContentContainer` component [src/areas/index.js#75-306](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L75-L306) is the top-level orchestrator. It wraps the UI in context providers and handles critical application-level concerns like extension communication. + +### Responsibilities + +| | | +| --- | --- | +| Context provisioning | Wraps children with `SettingsContextProvider`, `TargetContextProvider`, `UiContextProvider`[src/areas/index.js#191-306](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L191-L306) | +| Extension messaging | Handles `postMessage` events from iframe extensions via `processExtensionMessage`[src/areas/index.js#84-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L84-L156) | +| Icon management | Merges `iconsTarget` and `iconsFeather` into `iconsList`[src/areas/index.js#82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L82-L82) | +| Settings persistence | Provides `exportPreferencesSection` and `importPreferencesSection` functions [src/areas/index.js#28-31](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L28-L31) | + +### Extension Message Protocol + +`ContentContainer` implements a router for messages coming from iframes [src/areas/index.js#84-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L84-L156) It supports `cmd` (serial commands), `query` (URL-based API calls), and `upload` (file transfers) by wrapping them in `createNewRequest` from the `useHttpQueue` hook. + +**Sources:**[src/areas/index.js#84-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L84-L156)[src/areas/index.js#191-306](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L191-L306) + +--- + +## ViewContainer - Conditional Rendering + +The `ViewContainer` component [src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73) determines which UI tree to render based on the authentication state stored in `UiContext`. + +### Rendering Logic + +[Flowchart Diagram] + +**Sources:**[src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73) + +--- + +## MainContainer and Dashboard + +`MainContainer`[src/areas/main/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/main/index.js) hosts the functional pages. The primary view is the `Dashboard`[src/pages/dashboard/index.js#113](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L113-L113) which acts as a grid for functional panels. + +### Dashboard Responsibilities + +- **Keyboard Shortcuts**: Manages global keyboard listeners via `AddKeyboardListener`[src/pages/dashboard/index.js#166-172](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L166-L172) and `keyboardEventHandlerDown`[src/pages/dashboard/index.js#43-110](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L43-L110) +- **Panel Layout**: Renders panels based on `uisettings.getValue("fixedpanels")`[src/pages/dashboard/index.js#118](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L118-L118) +- **Quick Buttons**: Renders the `QuickButtonsBar`[src/pages/dashboard/index.js#26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L26-L26) + +**Sources:**[src/pages/dashboard/index.js#43-110](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L43-L110)[src/pages/dashboard/index.js#113-200](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L113-L200) + +--- + +## Panel System + +Each panel is a self-contained Preact component. Panels generally use `useTargetContext` to access real-time machine data and `useUiContext` for UI state (toasts, modals). + +### Panel Types and Implementations + +| | | | +| --- | --- | --- | +| **FilesPanel** | [src/components/Panels/Files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js) | Manages file systems via `files.command()`[src/components/Panels/Files.js#121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L121-L121) Handles uploads [src/components/Panels/Files.js#196](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L196-L196) and directory navigation. | +| **JogPanel (CNC)** | [src/components/Panels/JogCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js) | Handles multi-axis movement (X, Y, Z, A, B, C, U, V, W) [src/components/Panels/JogCNC.js#41-43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js#L41-L43) Supports MPos and WPos display [src/components/Panels/JogCNC.js#50-112](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js#L50-L112) | +| **JogPanel (3D)** | [src/components/Panels/Jog.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js) | Optimized for 3D printer axis control with feedrate selection [src/components/Panels/Jog.js#188-205](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js#L188-L205) | +| **JogPanel (Plotter)** | [src/components/Panels/JogPlotter.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js) | Simplified XY control with Pen up/down status [src/components/Panels/JogPlotter.js#81-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js#L81-L100) | +| **Notifications** | [src/components/Panels/Notifications.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js) | Displays time-stamped logs with auto-scroll logic [src/components/Panels/Notifications.js#52-60](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js#L52-L60) | +| **Overrides** | [src/components/Panels/OverridesCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js) | Real-time spindle, feed, and rapid override controls [src/components/Panels/OverridesCNC.js#34-69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js#L34-L69) | + +### Common Panel Structure + +Panels use `ContainerHelper`[src/components/Controls/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/index.js) to provide a consistent wrapper, and often include `FullScreenButton` and `CloseButton`. + +[Flowchart Diagram] + +**Sources:**[src/components/Panels/Files.js#57-195](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L57-L195)[src/components/Panels/JogCNC.js#114-145](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js#L114-L145) + +--- + +## ExtraContent and Extensions + +The `ExtraContent` component [src/components/ExtraContent/index.js#36](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L36-L36) manages external content like camera streams or custom HTML. It uses `ExtraContentItem`[src/components/ExtraContent/extraContentItem.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/extraContentItem.js) for actual rendering. + +### Dynamic Positioning + +`ExtraContent` calculates its position relative to a target DOM element (e.g., a panel or page area) using `getBoundingClientRect()`[src/components/ExtraContent/index.js#53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L53-L53) It communicates this position to the rendering layer via the `eventBus`[src/components/ExtraContent/index.js#55](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L55-L55) + +### Extension Messaging + +When `target === "panel"`, it renders standard panel controls (Refresh, Fullscreen, Close) [src/components/ExtraContent/index.js#125-145](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L125-L145) + +**Sources:**[src/components/ExtraContent/index.js#45-82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L45-L82)[src/components/ExtraContent/index.js#125-145](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L125-L145) + +--- + +## Field Component Hierarchy + +Configuration interfaces (like the Settings tab) are built using a recursive hierarchy of `Field` and `FieldGroup` components. + +### Field Mapping + +| | | +| --- | --- | +| `boolean` | Checkbox / Toggle | +| `number` | `Input` (type=number) [src/components/Controls/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/index.js) | +| `select` | `Select` dropdown | +| `mask` | `Mask` bitmask selector [src/components/Controls/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/index.js) | +| `group` | `FieldGroup` container [src/components/Controls/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/index.js) | + +**Sources:**[src/areas/index.js#38](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L38-L38)[src/components/Controls/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/index.js) + +--- + +## Summary of Data Flow + +1. **Top-Down**: Contexts (`UiContext`, `SettingsContext`, `TargetContext`) are provided at the root and consumed by leaf components (Panels, Fields). +2. **Bottom-Up**: User interactions (button clicks, input changes) trigger `createNewRequest`[src/hooks/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/index.js) or context update functions. +3. **Cross-Component**: The `eventBus`[src/hooks/eventBus.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js) is used for non-hierarchical communication, such as updating `ExtraContent` positions when panels are scrolled or resized [src/components/ExtraContent/index.js#61-63](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L61-L63) + +**Sources:**[src/areas/index.js#191-306](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L191-L306)[src/components/ExtraContent/index.js#61-82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L61-L82) + +--- + +# 3-Application-Lifecycle + +# Application Lifecycle +Relevant source files + +- [src/areas/elementsCache.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js) +- [src/components/Helpers/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/filters.js) +- [src/components/Helpers/storedState.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js) +- [src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) +- [src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js) +- [src/contexts/UiContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js) +- [src/hooks/eventBus.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js) +- [src/hooks/useSettings.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js) +- [src/targets/CNC/Controls/QuickStopButton.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js) +- [src/targets/CNC/GRBL/Controls/BackgroundContainer.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js) + +## Purpose and Scope + +This page walks through the complete lifecycle of ESP3D-WEBUI from initial page load to steady-state operation. It documents the four major phases: **Loading** (browser fetches/decompressed `index.html.gz`), **Initialization** (context providers mount, settings load), **Connection** (authentication and `ViewContainer` routing), and **Steady-State** (bidirectional data flow via WebSocket and HTTP). + +The lifecycle is orchestrated by several key components: + +- `App` - The entry point component [src/hooks/useSettings.js#21](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L21-L21) +- `ViewContainer` - Conditional renderer that switches between login UI and authenticated UI [src/contexts/UiContext.js#55](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L55-L55) +- `UiContext`, `SettingsContext`, `TargetContext` - Primary providers managing application state [src/hooks/useSettings.js#30-34](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L30-L34) +- `processData()` - The central function for parsing incoming firmware data [src/hooks/useSettings.js#59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L59-L59) + +For implementation details of each phase: + +- **Initialization and Loading**: see [Initialization and Loading](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.1?branch=%223.0%22) +- **Connection Management**: see [Connection Management](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.2?branch=%223.0%22) +- **Data Processing Pipeline**: see [Data Processing Pipeline](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.3?branch=%223.0%22) + +--- + +## Lifecycle Phases Overview + +ESP3D-WEBUI progresses through four phases: + +| | | | | +| --- | --- | --- | --- | +| **Loading** | Browser fetches and decompresses `index.html.gz` | `webUIversion`, gzip decompression | User navigates to device URL | +| **Initialization** | Preact app mounts contexts and loads preferences | `UiContextProvider`, `useSettings`, `useStoredState` | Script execution begins | +| **Connection** | UI renders login or main view based on auth state | `connectionState`, `showLogin`, `showKeepConnected` | Context providers ready | +| **Steady-State** | Bidirectional data flow and UI updates | `processData()`, `eventBus`, `initPolling()` | `connected: true` in `UiContext` | + +### Application Lifecycle State Machine + +Loading diagram… + +**Sources:**[src/hooks/useSettings.js#52-171](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L52-L171)[src/contexts/UiContext.js#50-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L50-L57)[src/components/Helpers/storedState.js#21-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js#L21-L33)[src/hooks/eventBus.js#25-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js#L25-L68) + +--- + +## Phase 1: Application Loading + +The loading phase begins when the browser requests the target-specific bundle. ESP3D-WEBUI is distributed as target-specific compressed single-page applications. + +### Build Artifacts and Deployment + +The build system produces one `.html.gz` file per firmware variant. These files are self-contained, inlining all JS and CSS to minimize requests on resource-constrained ESP devices. + +| | | | +| --- | --- | --- | +| `printer3d-marlin` | `dist/Printer3D/Marlin/index.html.gz` | Marlin | +| `cnc-grbl` | `dist/CNC/GRBL/index.html.gz` | GRBL | +| `cnc-grblhal` | `dist/CNC/GRBLHal/index.html.gz` | grblHAL | + +**Sources:**[src/components/App/version.js#21](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/App/version.js#L21-L21)[src/hooks/useSettings.js#176](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L176-L176) + +--- + +## Phase 2: Initialization + +Once the JS bundle executes, Preact initializes the context providers. + +### Component and Context Provider Tree + +Loading diagram… + +### Initialization Steps + +1. **Preference Retrieval**: `useStoredState` retrieves UI preferences from `localStorage`[src/components/Helpers/storedState.js#21-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js#L21-L33) +2. **Context Setup**: `UiContextProvider` initializes `connectionState` and UI elements like `panelsList`[src/contexts/UiContext.js#35-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L35-L57) +3. **Target Sync**: `useSettings` triggers `getConnectionSettings` which calls `[ESP800]` to sync time, timezone, and version with the hardware [src/hooks/useSettings.js#173-182](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L173-L182) +4. **Cache Preparation**: `ElementsCache` prepares extra content items (like cameras or custom frames) [src/areas/elementsCache.js#40-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L40-L61) + +**Sources:**[src/contexts/UiContext.js#35-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L35-L57)[src/hooks/useSettings.js#173-182](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L173-L182)[src/areas/elementsCache.js#27-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L27-L61) + +--- + +## Phase 3: Connection Management + +Connection state is managed within `UiContext`. The UI adapts based on whether the device requires authentication (`needLogin`) or is currently connected. + +### Authentication Flow + +If the ESP3D backend returns a requirement for authentication, the `showLogin` function is triggered, mounting the `logginModal`. + +Loading diagram… + +**Sources:**[src/components/Modal/logginModal.js#33-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L33-L79)[src/contexts/UiContext.js#50-56](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L50-L56) + +--- + +## Phase 4: Steady-State Operation + +Steady-state is characterized by continuous monitoring and command execution. + +### Data Processing Loop + +1. **Polling**: `initPolling()` sends periodic commands (e.g., status, temperatures) defined in `uisettings`[src/hooks/useSettings.js#92-171](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L92-L171) +2. **Command Execution**: Components use `createNewRequest` to send G-code or ESP commands via `espHttpURL`[src/hooks/useSettings.js#63-90](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L63-L90) +3. **Data Handling**: Incoming responses are passed to `processData`. If the response starts with `{`, it is treated as JSON; otherwise, it is processed as a standard firmware response [src/hooks/useSettings.js#74-81](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L74-L81) +4. **Terminal Logging**: Raw data is appended to the `DatasContext` terminal buffer for display in the Terminal Panel [src/contexts/DatasContext.js#49-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L49-L78) + +### Event Distribution + +The `eventBus` allows components to communicate without direct context dependencies, which is used for high-frequency updates or decoupled interactions [src/hooks/eventBus.js#25-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js#L25-L68) + +Loading diagram… + +**Sources:**[src/hooks/useSettings.js#59-171](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L59-L171)[src/contexts/DatasContext.js#86-98](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L86-L98)[src/hooks/eventBus.js#60-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js#L60-L68) + +--- + +## Lifecycle Summary + +1. **Loading**: Decompression and mounting of the Preact tree. +2. **Initialization**: Loading local state and syncing with hardware via `[ESP800]`. +3. **Connection**: Handling authentication via `logginModal` and establishing WebSocket/HTTP communication. +4. **Steady-State**: Running the `initPolling` loop and updating `TargetContext` via `processData`. + +For implementation details, refer to the sub-pages: + +- [Initialization and Loading](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.1?branch=%223.0%22) +- [Connection Management](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.2?branch=%223.0%22) +- [Data Processing Pipeline](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.3?branch=%223.0%22) + +**Sources:**[src/hooks/useSettings.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js)[src/contexts/UiContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js)[src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js)[src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) + +--- + +# 3.1-Initialization-and-Loading + +# Initialization and Loading +Relevant source files + +- [src/areas/elementsCache.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js) +- [src/components/ExtraContent/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js) +- [src/contexts/UiContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js) +- [src/hooks/eventBus.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js) +- [src/hooks/useSettings.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js) +- [src/pages/dashboard/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js) + +This page describes how the ESP3D-WEBUI application bootstraps from initial page load through context initialization, settings loading, and the first UI render. For information about connection establishment after initial load, see [Connection Management](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/3.2?branch=%223.0%22). For details on the build process that creates the deployable artifacts, see [Build Pipeline Overview](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/9.1?branch=%223.0%22). + +--- + +## Overview + +The initialization process transforms a compressed HTML file served by the ESP3D device into a fully interactive Preact application. The process involves five distinct phases: + +1. **Asset Loading**: The browser requests and decompresses the `index.html.gz` artifact. +2. **Script Execution**: Webpack-bundled JavaScript executes, initializing Preact. +3. **Context Setup**: Three primary context providers (`UiContextProvider`, `SettingsContextProvider`, `TargetContextProvider`) instantiate global state. +4. **Settings Restoration**: User preferences load from browser `localStorage` or defaults via the `useSettings` hook. +5. **Initial Render**: The application renders either the connection screen or the dashboard interface. + +--- + +## Initialization Sequence + +```mermaid +sequenceDiagram + participant Browser + participant ESP3D as ESP3D Device + participant Bundle as Webpack Bundle + participant Preact as Preact Runtime + participant Contexts as Context Providers + participant Settings as useSettings Hook + participant UI as UI Components + Browser->>ESP3D: GET /index.html.gz + ESP3D-->>Browser: Compressed HTML+CSS+JS + Browser->>Browser: Decompress .gz + Browser->>Bundle: Execute inline script + Bundle->>Preact: Initialize Preact runtime + Preact->>Contexts: Mount UiContextProvider + Preact->>Contexts: Mount SettingsContextProvider + Preact->>Contexts: Mount TargetContextProvider + Contexts->>Settings: getConnectionSettings() + Settings->>ESP3D: GET [ESP800] (JSON config) + ESP3D-->>Settings: Return Firmware JSON + Settings-->>Contexts: Update interfaceSettings/connectionSettings + Contexts->>UI: Render Dashboard +``` + +**Sources**: [src/hooks/useSettings.js#173-200](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L173-L200)[src/contexts/UiContext.js#35-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L35-L57) + +--- + +## Application Entry Point + +The application begins execution in the root mounting point where context providers are nested. The `UiContextProvider` is the outermost layer, managing the core application state including connection status and UI visibility. + +### Root Component Structure + +[Flowchart Diagram] + +The initialization orchestrates: + +- **UI State**: `UiContextProvider` initializes `panelsList`, `modals`, and `connectionState`[src/contexts/UiContext.js#36-56](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L36-L56) +- **Keyboard Shortcuts**: The `Dashboard` component checks `enableshortcuts` and attaches global listeners [src/pages/dashboard/index.js#187-193](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L187-L193) +- **Extra Content**: The `ElementsCache` component initializes iframe-based extensions if `showextracontents` is enabled [src/areas/elementsCache.js#41-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L41-L47) + +**Sources**: [src/contexts/UiContext.js#35-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L35-L57)[src/pages/dashboard/index.js#113-200](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L113-L200)[src/areas/elementsCache.js#27-72](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L27-L72) + +--- + +## Context Initialization and Polling + +The `useSettings` hook is a critical part of the bootstrap process. It handles the initial communication with the ESP3D backend to retrieve device-specific parameters. + +### Settings and Polling Flow + +1. **Connection Settings**: The hook calls `getConnectionSettings`, which sends an `[ESP800]` command to the firmware to sync time, timezone, and retrieve version info [src/hooks/useSettings.js#173-180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L173-L180) +2. **Polling Initialization**: Once settings are loaded, `initPolling()` is called. This reads `pollingcmds` from the interface settings and schedules recurring `sendCommand` calls via `activity.startPolling`[src/hooks/useSettings.js#92-135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L92-L135) +3. **Command Formatting**: Commands sent during initialization are passed through `variablesList.formatCommand` to replace placeholders with runtime values [src/hooks/useSettings.js#120-124](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L120-L124) + +**Sources**: [src/hooks/useSettings.js#92-171](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L92-L171)[src/hooks/useSettings.js#173-200](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L173-L200) + +--- + +## UI Component Bootstrapping + +### Dashboard and Keyboard Listeners + +Upon mounting, the `Dashboard` component initializes the keyboard shortcut system. It uses `AddKeyboardListener` to attach `keydown` and `keyup` events to the window [src/pages/dashboard/index.js#166-172](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L166-L172) This allows global G-code triggers (macros/jogging) even when no input is focused. + +### Extra Content (Iframe) Loading + +The `ElementsCache` component serves as a persistent background container for "Extra Content" (like camera feeds or custom web views). + +- It extracts settings from `interfaceSettings.current.settings.extracontents`[src/areas/elementsCache.js#49-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L49-L50) +- It renders `ExtraContentItem` components into a hidden `div` with `id="elementsCache"`[src/areas/elementsCache.js#66](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L66-L66) +- These items communicate with the main UI via the `eventBus` to update their visibility and position [src/hooks/eventBus.js#25-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js#L25-L78)[src/components/ExtraContent/index.js#55](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L55-L55) + +**Sources**: [src/pages/dashboard/index.js#166-185](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L166-L185)[src/areas/elementsCache.js#41-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L41-L68)[src/components/ExtraContent/index.js#36-113](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L36-L113) + +--- + +## Version and Environment Checks + +During loading, the system performs environment checks to adapt the UI: + +- **Limited Environment**: The `isLimitedEnvironment` helper determines if the browser has restricted capabilities [src/hooks/useSettings.js#26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L26-L26) +- **Version Sync**: The `webUIversion` is sent to the ESP3D device during the initial handshake to ensure compatibility [src/hooks/useSettings.js#176](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L176-L176) + +| | | | +| --- | --- | --- | +| `webUIversion` | `../components/App/version` | Identifies the UI version to the firmware [src/hooks/useSettings.js#21](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L21-L21) | +| `connectionState` | `UiContext` | Tracks if the UI is "connecting", "authenticating", or "ready" [src/contexts/UiContext.js#52-56](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L52-L56) | +| `ui.ready` | `UiContext` | Global flag indicating contexts and settings are fully initialized [src/areas/elementsCache.js#41](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L41-L41) | + +**Sources**: [src/hooks/useSettings.js#21-27](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L21-L27)[src/contexts/UiContext.js#52-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js#L52-L57)[src/areas/elementsCache.js#41-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js#L41-L61) + +--- + +## Target-Specific Initialization + +The application loads firmware-specific configuration during the build process. Each target (Marlin, GRBL, Smoothieware, etc.) has its own configuration embedded: + +- **defaultPreferences**: Loaded from `../targets` to provide firmware-specific defaults [src/hooks/useSettings.js#41](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L41-L41) +- **processData**: The `useTargetContextFn` provides the specific data processor for the active firmware (e.g., parsing Marlin vs. GRBL status reports) [src/hooks/useSettings.js#59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L59-L59) +- **variablesList**: Contains firmware-specific command formatters and variable definitions [src/hooks/useSettings.js#43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L43-L43) + +**Sources**: [src/hooks/useSettings.js#40-44](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L40-L44)[src/hooks/useSettings.js#59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L59-L59)[src/hooks/useSettings.js#120-124](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L120-L124) + +--- + +# 3.2-Connection-Management + +# Connection Management +Relevant source files + +- [src/components/Helpers/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/filters.js) +- [src/components/Helpers/storedState.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js) +- [src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) +- [src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js) +- [src/contexts/WsContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js) +- [src/targets/CNC/Controls/QuickStopButton.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js) +- [src/targets/CNC/GRBL/Controls/BackgroundContainer.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js) + +## Purpose and Scope + +Connection Management handles the authentication lifecycle, connection state tracking, and conditional UI rendering in ESP3D-WEBUI. This system determines whether users see the login screen (`ConnectionContainer`) or the authenticated interface (`Menu` + `MainContainer`). It also manages the WebSocket lifecycle, including heartbeat (ping) mechanisms and automatic reconnection logic. + +## Connection State Architecture + +The connection state is centrally managed in `UiContext` and accessed throughout the application to control UI visibility and enable/disable features. The `ViewContainer` component acts as the primary decision point for rendering authenticated vs. unauthenticated views. + +[Flowchart Diagram] + +**Sources:**[src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73)[src/contexts/WsContext.js#144-150](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L144-L150) + +## WebSocket Lifecycle Management + +The `WsContextProvider` manages the persistent communication channel with the firmware. It handles binary streams for terminal data and text-based events for system notifications. + +### Connection State Machine (Code Entity Space) + +The following diagram maps WebSocket events to specific functions and state updates within `WsContext.js`. + +[Flowchart Diagram] + +**Sources:**[src/contexts/WsContext.js#41-166](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L41-L166)[src/contexts/WsContext.js#175-186](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L175-L186) + +## Authentication Flow + +Authentication is handled via the `showLogin` modal, which performs a `POST` request to the `/login` endpoint. + +### Login Sequence + +1. **Trigger**: The `ViewContainer` detects `dialogs.needLogin` and calls `showLogin()`. [src/areas/index.js#51-54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L51-L54) +2. **Input**: User enters credentials in `logginModal.js`. [src/components/Modal/logginModal.js#94-126](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L94-L126) +3. **Submission**: `clickLogin` creates a `POST` request with `USER` and `PASSWORD` fields. [src/components/Modal/logginModal.js#46-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L46-L61) +4. **Success**: On `onSuccess`, the page reloads to initialize the session. [src/components/Modal/logginModal.js#62-65](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L62-L65) +5. **Failure**: The UI displays an error message (T("S201")). [src/components/Modal/logginModal.js#127-131](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L127-L131) + +**Sources:**[src/components/Modal/logginModal.js#33-147](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js#L33-L147) + +## Terminal Data Management + +Connection status directly impacts how terminal data is buffered and displayed. The `DatasContext` manages the history of commands and responses received over the connection. + +| | | | +| --- | --- | --- | +| `addTerminalContent` | Adds lines to buffer | Limits array size based on scroll state (300-600 lines). [src/contexts/DatasContext.js#49-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L49-L78) | +| `clearTerminal` | Flushes buffers | Resets `terminalBuffer` and `terminalContent`. [src/contexts/DatasContext.js#43-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L43-L47) | +| `addInputHistory` | Saves sent commands | Uses `useStoredState` to persist 50 items in `localStorage`. [src/contexts/DatasContext.js#37-40](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L37-L40)[src/contexts/DatasContext.js#80-84](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L80-L84) | + +**Sources:**[src/contexts/DatasContext.js#30-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L30-L103)[src/components/Helpers/storedState.js#21-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js#L21-L33) + +## Connection Resilience and Heartbeats + +To ensure the connection remains active, the UI implements a PING mechanism. + +- **Ping Interval**: 5000ms. [src/contexts/WsContext.js#38](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L38-L38) +- **Payload**: `PING:ESPSESSIONID` (or "none" if no cookie exists). [src/contexts/WsContext.js#66-68](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L66-L68) +- **Timeout Handling**: If the server returns a ping response with a value `< 30000`, the UI triggers `dialogs.setShowKeepConnected(true)`. [src/contexts/WsContext.js#93-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L93-L101) + +**Sources:**[src/contexts/WsContext.js#55-71](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L55-L71)[src/contexts/WsContext.js#93-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/WsContext.js#L93-L101) + +## Emergency and Quick Actions + +Connection management also includes high-priority command handling, such as the `QuickStopButton` (Emergency Stop). + +- **Implementation**: Sends commands defined in the `emergencystop` setting. [src/targets/CNC/Controls/QuickStopButton.js#63-67](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L63-L67) +- **Variable Injection**: Commands are processed through `replaceVariables` before transmission to handle dynamic parameters. [src/targets/CNC/Controls/QuickStopButton.js#35-40](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L35-L40) + +**Sources:**[src/targets/CNC/Controls/QuickStopButton.js#28-71](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L28-L71) + +--- + +# 3.3-Data-Processing-Pipeline + +# Data Processing Pipeline +Relevant source files + +- [src/components/Helpers/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/filters.js) +- [src/components/Helpers/storedState.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js) +- [src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) +- [src/components/Panels/Status.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js) +- [src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js) +- [src/targets/CNC/Controls/QuickStopButton.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js) +- [src/targets/CNC/GRBL/Controls/BackgroundContainer.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js) +- [src/targets/Printer3D/Marlin-embedded/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/TargetContext.js) +- [src/targets/Printer3D/Marlin-embedded/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/filters.js) +- [src/targets/Printer3D/Marlin/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js) +- [src/targets/Printer3D/Marlin/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js) +- [src/targets/Printer3D/Repetier/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/TargetContext.js) +- [src/targets/Printer3D/Repetier/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/filters.js) +- [src/targets/Printer3D/Smoothieware/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js) +- [src/targets/Printer3D/Smoothieware/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js) +- [src/targets/Printer3D/Smoothieware/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/index.js) + +The data processing pipeline is responsible for transforming raw serial/HTTP responses from the firmware into structured state that drives the user interface. This pipeline handles character-level stream buffering, firmware-specific pattern matching, data extraction, and state updates. + +## Pipeline Overview + +The data processing pipeline implements a three-stage transformation that converts raw firmware responses into structured application state. The entry point is `useTargetContextFn.processData(type, data, noecho)` which is called from WebSocket handlers and HTTP response callbacks. + +**Pipeline Entry Point:**`useTargetContextFn.processData(type, data, noecho)`[src/targets/Printer3D/Marlin/TargetContext.js#312-313](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L312-L313) + +**Data Flow Architecture:** + +[Flowchart Diagram] + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#312-414](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L312-L414)[src/targets/Printer3D/Marlin/filters.js#1-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L1-L100) + +## Data Types and Sources + +The pipeline processes five distinct data types defined in `dataBuffer.current`, each originating from different communication channels: + +| | | | | | +| --- | --- | --- | --- | --- | +| `stream` | WebSocket `onmessage` | Firmware serial output (M105, M114, status reports) | Character-by-character | [src/targets/Printer3D/Marlin/TargetContext.js#314-373](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L314-L373) | +| `response` | HTTP `fetch()` responses | Synchronous command replies (ESP800, ESP420) | Line-based | [src/targets/Printer3D/Marlin/TargetContext.js#374-405](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L374-L405) | +| `core` | ESP3D internal messages | System notifications (SENSOR: data) | Line-based | [src/targets/Printer3D/Marlin/TargetContext.js#248-257](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L248-L257) | +| `error` | Error handlers | Exception messages | Line-based | [src/targets/Printer3D/Marlin/TargetContext.js#168](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L168-L168) | +| `echo` | Command echo | User command feedback | Line-based | [src/targets/Printer3D/Marlin/TargetContext.js#169](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L169-L169) | + +**Buffer Structure:** + +``` +const dataBuffer = useRef({ + stream: "", + core: "", + response: "", + error: "", + echo: "", +}) +``` + +[src/targets/Printer3D/Marlin/TargetContext.js#164-170](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L164-L170) + +The `type` parameter in `processData(type, data, noecho)` determines processing logic. Stream data requires character-level buffering (newline detection) to handle fragmented WebSocket packets. + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#164-170](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L164-L170)[src/targets/Printer3D/Marlin/TargetContext.js#312-414](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L312-L414) + +## Stream Buffering Mechanism + +### Character-by-Character Accumulation + +Stream data from the WebSocket connection arrives in potentially fragmented chunks. The buffering system accumulates characters until a complete line is detected: + +[Flowchart Diagram] + +The implementation in `TargetContext.js` shows this buffering logic: + +``` +data.split("").forEach((element, index) => { + if (element == "\n" || element == "\r") { + if (dataBuffer.current[type].length > 0) { + dispatchInternally(type, dataBuffer.current[type]) + // ... terminal processing ... + dataBuffer.current[type] = "" + } + } else { + dataBuffer.current[type] += element + } +}) +``` + +[src/targets/Printer3D/Marlin/TargetContext.js#318-373](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L318-L373) + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#318-373](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L318-L373)[src/targets/Printer3D/Smoothieware/TargetContext.js#221-261](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js#L221-L261) + +## Internal Dispatch and Filter Matching + +### The dispatchInternally Function + +The `dispatchInternally(type, data)` function orchestrates filter matching and state updates. It implements a non-exclusive pattern-matching strategy where multiple filters may process the same data. + +**Dispatch Logic Flow:** + +[Flowchart Diagram] + +**Filter Processing Order (Marlin):** + +1. `processor.handle()`: File operation responses (M20, M30, upload confirmations) [src/targets/Printer3D/Marlin/TargetContext.js#174](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L174-L174) +2. `isOk()`: Simple acknowledgments [src/targets/Printer3D/Marlin/TargetContext.js#178](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L178-L178) +3. `isTemperatures()`: Temperature reports (M105 output) [src/targets/Printer3D/Marlin/TargetContext.js#180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L180-L180) +4. `isPositions()`: Position data (M114 output) [src/targets/Printer3D/Marlin/TargetContext.js#184](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L184-L184) +5. `isPrintStatus()`: Print progress (M27 output) [src/targets/Printer3D/Marlin/TargetContext.js#187](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L187-L187) +6. `isStatus()`: Busy/error states [src/targets/Printer3D/Marlin/TargetContext.js#213](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L213-L213) +7. `isSensor()`: Custom sensor data [src/targets/Printer3D/Marlin/TargetContext.js#235](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L235-L235) + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#172-310](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L172-L310)[src/targets/Printer3D/Marlin/filters.js#1-414](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L1-L414) + +## Filter Implementation Pattern + +### Regex-Based Pattern Matching + +Each filter consists of an `is*` function for detection and a `get*` function for extraction. + +#### Temperature Filter Example (Marlin) + +Marlin temperature responses follow the format `T:25.00 /210.00 B:25.00 /0.00`: + +``` +const isTemperatures = (str) => { + const regex_search = /T:.*\s@:[0-9]*/g + return regex_search.test(str) +} + +const getTemperatures = (str) => { + const response = { + T: [], R: [], B: [], C: [], P: [], M: [], L: [], + } + const regex_search = /(B|T|C|P|R)([\d]*):([+|-]?[0-9]*\.?[0-9]+|inf)? \/([+]?[0-9]*\.?[0-9]+)/g + while ((result = regex_search.exec(str)) !== null) { + response[result[1]][result[2] == "" ? 0 : result[2]] = { + value: result[3], + target: result[4], + } + } + return response +} +``` + +[src/targets/Printer3D/Marlin/filters.js#44-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L44-L78) + +#### Position Filter Example (Smoothieware) + +Smoothieware uses a slightly different regex for position reports: + +``` +const isPositions = (str) => { + const regex_search = /X:\s*[+,-]?[0-9]*\.?[0-9]+?\s*Y:\s*[+,-]?[0-9]*\.?[0-9]+?\s*Z:\s*[+,-]?[0-9]*\.?[0-9]+?\s*E/ + return regex_search.test(str) +} +``` + +[src/targets/Printer3D/Smoothieware/filters.js#87-91](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L87-L91) + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#44-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L44-L100)[src/targets/Printer3D/Smoothieware/filters.js#87-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L87-L101) + +## State Update Flow + +### Preact State Management + +Once data is extracted, it updates Preact state variables exposed through `TargetContext`. + +**Temperature State Update Logic:** + +[Flowchart Diagram] + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#78-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L78-L121)[src/targets/Printer3D/Marlin/TargetContext.js#180-183](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L180-L183) + +### Complex State: Print Status with Time Estimation + +The print status processing calculates derived state like `printLeftTime` by combining progress percentage and elapsed time. + +``` +const estimatedTime = (progress, time) => { + const total = (time.day ? parseInt(time.day) * 86400 : 0) + ...; + const totalSecondsLeft = (total * (100 - progress)) / progress + return { + day: Math.floor(totalSecondsLeft / 86400), + hour: Math.floor((totalSecondsLeft % 86400) / 3600), + min: Math.floor((totalSecondsLeft % 3600) / 60), + sec: Math.floor(totalSecondsLeft % 60), + } +} +``` + +[src/targets/Printer3D/Marlin/TargetContext.js#142-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L142-L156) + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#142-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L142-L156)[src/targets/Printer3D/Marlin/TargetContext.js#187-209](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L187-L209) + +## Terminal and Extension Integration + +### Terminal Output + +Processed data is forwarded to the `DatasContext` terminal buffer for display in the console. + +``` +const addTerminalContent = (element) => { + const newData = {} + newData.verbose = limitArr([...terminalBuffer.current, element], 300) + if (!element.isverboseOnly) { + newData.quiet = limitArr([...terminalBufferQuiet.current, element], 300) + } + setTerminalContent(isVerbose.current ? newData.verbose : newData.quiet) +} +``` + +[src/contexts/DatasContext.js#49-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L49-L78) + +### Extension Forwarding + +Raw and processed data is dispatched to iframe extensions via `dispatchToExtensions(type, data)`. + +``` +dispatchToExtensions(type, data) +``` + +[src/targets/Printer3D/Marlin/TargetContext.js#412](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L412-L412) + +**Sources:**[src/contexts/DatasContext.js#49-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L49-L78)[src/targets/Printer3D/Marlin/TargetContext.js#412](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L412-L412)[src/components/Helpers/index.js#NaN-NaN](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/index.js#LNaN-LNaN) + +## UI Consumption Example + +### Status Panel Integration + +The `StatusPanel` consumes the `status` and `streamStatus` state from `TargetContext` to render real-time progress. + +``` +const StatusControls = () => { + const { streamStatus, status } = useTargetContext() + + return ( + + {streamStatus?.status && ( +
+
{T(streamStatus.status)}
+
{streamStatus.progress}%
+ +
+ )} + {/* ... Machine State and SD Status ... */} +
+ ) +} +``` + +[src/components/Panels/Status.js#72-166](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L72-L166) + +**Sources:**[src/components/Panels/Status.js#29-166](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L29-L166)[src/targets/Printer3D/Marlin/TargetContext.js#418-456](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L418-L456) + +--- + +# 4-Target-Configuration-System + +# Target Configuration System +Relevant source files + +- [src/components/Controls/Fields/Mask.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js) +- [src/targets/CNC/GRBL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js) +- [src/targets/CNC/GRBL/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/preferences.json) +- [src/targets/CNC/grblHAL/DIRECTSD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js) +- [src/targets/CNC/grblHAL/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js) +- [src/targets/CNC/grblHAL/files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js) +- [src/targets/CNC/grblHAL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js) +- [src/targets/CNC/grblHAL/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json) +- [src/targets/CNC/grblHAL/realCommandsTable.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js) +- [src/targets/CNC/grblHAL/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json) +- [src/targets/CNC/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json) +- [src/targets/CNC/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json) +- [src/targets/Printer3D/Marlin-embedded/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/preferences.json) +- [src/targets/Printer3D/Marlin/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json) +- [src/targets/Printer3D/Repetier/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json) +- [src/targets/Printer3D/Smoothieware/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/preferences.json) +- [src/targets/Printer3D/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json) +- [src/targets/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json) +- [src/targets/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/translations/en.json) + +The Target Configuration System is the architectural foundation that enables ESP3D-WEBUI to support multiple firmware types (Marlin, GRBL, grblHAL, Smoothieware, Repetier) and machine types (3D Printers, CNC, SandTables) from a single codebase. This system provides declarative configuration through JSON preferences files, firmware-specific data processing through the `TargetContext` pattern, and dynamic UI adaptation through dependency evaluation. + +For information about the UI components that consume target configurations, see [User Interface Components](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/5?branch=%223.0%22). For build pipeline details, see [Build System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/9?branch=%223.0%22). For file system operations across different targets, see [File System Operations](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/10?branch=%223.0%22). + +--- + +## Target Types and Structure + +Each target in ESP3D-WEBUI represents a specific firmware type and is organized in a hierarchical directory structure. Targets inherit base configurations and override them with firmware-specific behavior. + +### Directory Organization + +[Flowchart Diagram] + +**Sources:**[src/targets/preferences.json#1-251](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L1-L251)[src/targets/Printer3D/preferences.json#1-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L1-L165)[src/targets/CNC/preferences.json#1-216](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json#L1-L216)[src/targets/CNC/grblHAL/preferences.json#1-200](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L1-L200)[src/targets/Printer3D/Marlin/preferences.json#1-175](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L1-L175) + +### Target Index Exports + +Each target's `index.js` file exports a standard set of objects that define the target's behavior: + +[Flowchart Diagram] + +**Example Target Export Structure:**[src/targets/CNC/grblHAL/index.js#81-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L81-L103) + +**Sources:**[src/targets/CNC/grblHAL/index.js#43-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L43-L103)[src/targets/CNC/GRBL/index.js#1-102](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L1-L102) + +--- + +## Preferences System + +The preferences system uses hierarchical JSON files to define UI settings with type information, validation rules, and dependency logic. Preferences cascade from base to machine type to firmware-specific layers. + +### Setting Types + +ESP3D-WEBUI supports several distinct setting types, each mapping to specific UI controls: + +| | | | | +| --- | --- | --- | --- | +| `boolean` | Toggle/Checkbox | `true`/`false` | Enable/disable panels [src/targets/Printer3D/preferences.json#5-9](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L5-L9) | +| `number` | Numeric Input | Integer/Float | Feedrates, temperatures [src/targets/Printer3D/preferences.json#46-51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L46-L51) | +| `text` | Text Input | String | G-code commands [src/targets/Printer3D/preferences.json#61-66](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L61-L66) | +| `select` | Dropdown | String (from options) | Filesystem selection [src/targets/CNC/grblHAL/preferences.json#159-162](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L159-L162) | +| `list` | Ordered List Editor | Array of objects | Polling commands [src/targets/Printer3D/Marlin/preferences.json#48-66](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L48-L66) | +| `group` | Nested Container | Array of settings | Related control groups [src/targets/Printer3D/preferences.json#40-44](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L40-L44) | +| `mask` | Bitmask Toggles | Integer (bit flags) | Axis visibility [src/components/Controls/Fields/Mask.js#43-55](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L43-L55) | +| `pickup` | Dynamic Loader | String (resource id) | Language packs [src/targets/preferences.json#5-9](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L5-L9) | + +**Sources:**[src/targets/Printer3D/preferences.json#1-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L1-L165)[src/components/Controls/Fields/Mask.js#43-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L43-L165)[src/targets/preferences.json#1-96](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L1-L96) + +### Preference Object Structure + +**Example Boolean Setting with Dependencies:**[src/targets/Printer3D/preferences.json#10-16](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L10-L16) + +**Example Group Setting with Nested Values:**[src/targets/Printer3D/preferences.json#115-143](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L115-L143) + +**Sources:**[src/targets/Printer3D/preferences.json#10-143](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L10-L143)[src/targets/CNC/grblHAL/preferences.json#169-180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L169-L180) + +### Dependency Evaluation System + +The dependency system uses the `checkDependencies` function to evaluate complex visibility rules based on current settings and connection state. + +**Example Complex Dependency with OR Groups:**[src/targets/CNC/grblHAL/preferences.json#169-180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L169-L180) + +**Example Connection-Based Dependency:**[src/targets/Printer3D/Marlin/preferences.json#99-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L99-L101) + +**Sources:**[src/components/Controls/Fields/Mask.js#74-83](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L74-L83)[src/targets/Printer3D/Marlin/preferences.json#99-106](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L99-L106) + +--- + +## TargetContext and Data Processing + +The `TargetContext` system provides firmware-specific state management and real-time data processing. Each target exports a `TargetContextProvider` that wraps the application and maintains machine state. + +For details, see [TargetContext and Data Processing](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.3?branch=%223.0%22). + +**Sources:**[src/targets/CNC/grblHAL/index.js#33-36](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L33-L36)[src/targets/CNC/grblHAL/index.js#92-94](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L92-L94) + +--- + +## Filter System + +The filter system provides pattern matching and data extraction for firmware-specific response formats. Filters follow an `is`/`get` naming convention for detection and extraction, typically used within the `processor` module. + +For details, see [Filter System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.4?branch=%223.0%22). + +**Sources:**[src/targets/CNC/grblHAL/index.js#23](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L23-L23)[src/targets/CNC/grblHAL/index.js#89](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L89-L89) + +--- + +## Variables and Events System + +The variables and events system provides dynamic command substitution and extensibility hooks for target-specific behaviors. + +### Variables List + +The `variablesList` object contains a combined table of `realCommandsTable` (firmware-specific non-printable commands) and `variablesTable` (UI-level placeholders). + +[src/targets/CNC/grblHAL/index.js#52-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L61) + +### Events System + +The `eventsList` provides a standard `on`/`off`/`emit` pattern for inter-component communication within a target's context. + +[src/targets/CNC/grblHAL/index.js#62-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L62-L79) + +For details, see [Variables and Events System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.5?branch=%223.0%22). + +**Sources:**[src/targets/CNC/grblHAL/index.js#52-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L79)[src/targets/CNC/grblHAL/realCommandsTable.js#1-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js#L1-L50) + +--- + +## File System Abstraction + +The target system defines storage backend implementations through the `files` export. This includes capabilities (e.g., `Upload`, `CreateDir`) and command generators (e.g., `list`, `play`). + +**Example Files Export Structure:**[src/targets/CNC/grblHAL/files.js#49-83](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L49-L83) + +**Sources:**[src/targets/CNC/grblHAL/files.js#49-83](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L49-L83)[src/targets/CNC/grblHAL/FLASH-source.js#25-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L25-L52)[src/targets/CNC/grblHAL/DIRECTSD-source.js#25-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L25-L52) + +--- + +# 4.1-Target-Types-and-Structure + +# Target Types and Structure +Relevant source files + +- [config/targets/Printer3D/Marlin/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/Printer3D/Marlin/index.js) +- [src/targets/CNC/GRBL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js) +- [src/targets/CNC/grblHAL/DIRECTSD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js) +- [src/targets/CNC/grblHAL/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js) +- [src/targets/CNC/grblHAL/files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js) +- [src/targets/CNC/grblHAL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js) +- [src/targets/CNC/grblHAL/realCommandsTable.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js) +- [src/targets/CNC/grblHAL/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json) +- [src/targets/CNC/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json) +- [src/targets/Printer3D/Marlin-embedded/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/filters.js) +- [src/targets/Printer3D/Marlin/DIRECTSD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/DIRECTSD-source.js) +- [src/targets/Printer3D/Marlin/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/FLASH-source.js) +- [src/targets/Printer3D/Marlin/files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/files.js) +- [src/targets/Printer3D/Repetier/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/filters.js) +- [src/targets/Printer3D/Smoothieware/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js) +- [src/targets/Printer3D/Smoothieware/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/index.js) + +## Purpose and Scope + +This document describes the organization and structure of target directories in ESP3D-WEBUI. A "target" represents a specific firmware type (e.g., Marlin, GRBL, grblHAL) that the WebUI can communicate with. This page covers the directory hierarchy, the key exports from each target's `index.js` file, and how targets inherit and override configurations. + +For information about the preferences system within targets, see [4.2](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/4.2) For details on how targets process firmware data, see [4.3](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/4.3) For file system abstractions provided by targets, see [10.1](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/10.1) + +--- + +## Target Directory Hierarchy + +The target system employs a three-tier hierarchical structure that enables configuration inheritance and specialization: + +**Directory Structure Diagram** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/grblHAL/index.js#43-45](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L43-L45)[src/targets/CNC/GRBL/index.js#43-45](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L43-L45)[src/targets/CNC/translations/en.json#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json#L1-L10) + +### Tier Definitions + +| | | | | +| --- | --- | --- | --- | +| **Base** | `src/targets/` | Common settings for all targets | `translations/en.json` | +| **Machine Type** | `src/targets/CNC/` | Settings shared by machine category | `translations/en.json` | +| **Firmware** | `src/targets/CNC/grblHAL/` | Firmware-specific implementation | `index.js`, `files.js`, `processor.js` | + +--- + +## Target Index Exports + +Each firmware target exports a standardized set of components and configurations from its `index.js` file. These exports define the target's identity, capabilities, and UI customizations. + +**Target Export Structure** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/grblHAL/index.js#81-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L81-L103)[src/targets/CNC/GRBL/index.js#79-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L79-L101) + +### Required Exports + +The following table documents the exports that every target must provide: + +| | | | | +| --- | --- | --- | --- | +| `Target` | string | Unique target identifier | `"grblHAL"`[src/targets/CNC/grblHAL/index.js#43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L43-L43) | +| `Name` | string | Display name | `"grblHAL"`[src/targets/CNC/grblHAL/index.js#45](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L45-L45) | +| `webUIbuild` | string | Build identifier for this target | `"GH5"`[src/targets/CNC/grblHAL/index.js#44](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L44-L44) | +| `fwUrl` | string[] | Links to firmware repositories | `["https://github.com/grblHAL", ...]`[src/targets/CNC/grblHAL/index.js#46-49](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L46-L49) | +| `restartdelay` | number | Seconds to wait after restart | `30`[src/targets/CNC/grblHAL/index.js#51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L51-L51) | +| `files` | object | File system abstraction | `{ command, capability, supported }`[src/targets/CNC/grblHAL/files.js#77-81](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L77-L81) | +| `processor` | function | Processes firmware data streams | `processor`[src/targets/CNC/grblHAL/index.js#89](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L89-L89) | +| `TargetContextProvider` | component | Preact context provider | React component [src/targets/CNC/grblHAL/index.js#92](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L92-L92) | +| `useTargetContext` | hook | Context consumer hook | Preact hook [src/targets/CNC/grblHAL/index.js#93](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L93-L93) | +| `useTargetContextFn` | hook | Function-based context access | Preact hook [src/targets/CNC/grblHAL/index.js#94](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L94-L94) | +| `MachineSettings` | component | Settings UI component | React component [src/targets/CNC/grblHAL/index.js#82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L82-L82) | +| `machineSettings` | object | Settings configuration | Configuration object [src/targets/CNC/grblHAL/index.js#83](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L83-L83) | +| `variablesList` | object | Command variables and modes | See Variables section below | +| `eventsList` | object | Event subscription system | See Events section below | +| `defaultPanelsList` | array | Default panel configuration | `defaultPanelsList`[src/targets/CNC/grblHAL/index.js#91](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L91-L91) | + +Sources: [src/targets/CNC/grblHAL/index.js#81-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L81-L103)[src/targets/CNC/GRBL/index.js#79-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L79-L101) + +--- + +## Variables List System + +The `variablesList` export provides a dynamic command system that allows runtime modification of available commands and variables. + +**variablesList Structure** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/grblHAL/index.js#52-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L61) + +### variablesList Properties + +| | | | +| --- | --- | --- | +| `commands` | array | Combined array of real commands and variable placeholders [src/targets/CNC/grblHAL/index.js#53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L53-L53) | +| `addCommand(variable)` | function | Dynamically add a command/variable at runtime [src/targets/CNC/grblHAL/index.js#54-55](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L54-L55) | +| `removeCommand(name)` | function | Remove a command/variable by name [src/targets/CNC/grblHAL/index.js#56-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L56-L57) | +| `modes` | array | G-code parser mode definitions for syntax highlighting [src/targets/CNC/grblHAL/index.js#58](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L58-L58) | +| `hideFeatures` | boolean | Whether to hide feature-specific commands (grblHAL only) [src/targets/CNC/grblHAL/index.js#59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L59-L59) | + +**Real Commands Example** + +``` +// From src/targets/CNC/grblHAL/realCommandsTable.js:20-50 +const realCommandsTable = [ + { name: "#SOFTRESET#", value: "\x18", notprintable: true }, + { name: "#STATUSREPORT#", value: "\x80", notprintable: true }, + { name: "#CYCLESTART#", value: "\x81", notprintable: true }, + // ... +] +``` + +Sources: [src/targets/CNC/grblHAL/realCommandsTable.js#20-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js#L20-L50)[src/targets/CNC/grblHAL/index.js#52-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L61) + +--- + +## Events List System + +The `eventsList` export provides a pub-sub event system for inter-component communication within a target. + +**eventsList API** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/grblHAL/index.js#62-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L62-L79) + +### Event Methods + +| | | | +| --- | --- | --- | +| `on(event, fn)` | `event`: string, `fn`: function | Register a callback for an event [src/targets/CNC/grblHAL/index.js#64-69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L64-L69) | +| `off(event, fn)` | `event`: string, `fn`: function | Unregister a callback [src/targets/CNC/grblHAL/index.js#70-72](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L70-L72) | +| `emit(event, data)` | `event`: string, `data`: any | Trigger all callbacks for an event [src/targets/CNC/grblHAL/index.js#73-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L73-L78) | + +--- + +## File System Abstraction + +Each target defines which file systems it supports and how to interact with them. The file system abstraction is exported as the `files` object. + +**File System Structure** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/grblHAL/files.js#49-81](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L49-L81) + +### Supported File Systems (grblHAL Example) + +| | | | +| --- | --- | --- | +| `FLASH` | `FLASH-source.js` | `flashfs` enabled AND `FlashFileSystem != "none"`[src/targets/CNC/grblHAL/files.js#30-35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L30-L35) | +| `DIRECTSD` | `DIRECTSD-source.js` | `directsd` enabled AND `SDConnection != "none"`[src/targets/CNC/grblHAL/files.js#40-45](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L40-L45) | + +### File System Capabilities + +Each file system implementation (e.g., `FLASH`, `DIRECTSD`) defines a `capabilities` object: + +| | | | +| --- | --- | --- | +| `Process` | function | Whether file can be executed [src/targets/CNC/grblHAL/DIRECTSD-source.js#26-28](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L26-L28) | +| `UseFilters` | function | Whether to apply file extension filters [src/targets/CNC/grblHAL/DIRECTSD-source.js#29](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L29-L29) | +| `Upload` | function | Whether file upload is supported [src/targets/CNC/grblHAL/DIRECTSD-source.js#31-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L31-L33) | +| `Download` | function | Whether file download is supported [src/targets/CNC/grblHAL/DIRECTSD-source.js#40-42](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L40-L42) | + +### File System Commands + +Commands return objects specifying the action type (URL or CMD): + +| | | | +| --- | --- | --- | +| `list` | (path) | `{ type: "url", url: "sdfiles", args: { path, action: "list" } }`[src/targets/CNC/grblHAL/DIRECTSD-source.js#55-60](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L55-L60) | +| `play` | (path, filename) | `{ type: "cmd", cmd: "M24 ..." }`[src/targets/Printer3D/Marlin/FLASH-source.js#131-138](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/FLASH-source.js#L131-L138) | +| `formatResult` | (resultTxt) | Parsed JSON with formatted status [src/targets/CNC/grblHAL/DIRECTSD-source.js#69-76](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L69-L76) | + +--- + +## Translation Files + +Translation files are organized hierarchically, allowing machine-specific strings to override base strings. + +**Translation Hierarchy** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/translations/en.json#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json#L1-L10)[src/targets/CNC/grblHAL/translations/en.json#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json#L1-L10) + +### Translation Key Prefixes + +| | | | | +| --- | --- | --- | --- | +| `CN` | CNC-specific | `CN36` | "Spindle" [src/targets/CNC/translations/en.json#27](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json#L27-L27) | +| `$` | GRBL settings | `$100` | "X steps/mm" [src/targets/CNC/grblHAL/translations/en.json#96](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json#L96-L96) | +| `ALARM` | Firmware Alarms | `ALARM:1` | "Hard limit has been triggered..." [src/targets/CNC/translations/en.json#140](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json#L140-L140) | + +--- + +## Filter System + +Targets implement filters to parse specific firmware responses (e.g., temperatures, positions) into the application state. + +**Filter Implementation (Smoothieware Example)** + +| | | | +| --- | --- | --- | +| `isTemperatures` | `/T:.*\s@[0-2]/g` | Detects temperature reports [src/targets/Printer3D/Smoothieware/filters.js#48-51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L48-L51) | +| `getTemperatures` | `/(B\|T\|C\|P\|R)([\d]*):.../g` | Parses tool, current, and target temps [src/targets/Printer3D/Smoothieware/filters.js#53-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L53-L79) | +| `isPositions` | `/X:\s*[+,-]?[0-9].../` | Detects coordinate reports [src/targets/Printer3D/Smoothieware/filters.js#87-91](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L87-L91) | +| `getPrintStatus` | `/(Not\scurrently\splaying)/` | Parses SD printing progress [src/targets/Printer3D/Smoothieware/filters.js#120-139](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L120-L139) | + +Sources: [src/targets/Printer3D/Smoothieware/filters.js#1-236](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L1-L236) + +--- + +# 4.2-Preferences-System + +# Preferences System +Relevant source files + +- [Memo/preferences.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/Memo/preferences.md?plain=1) +- [src/components/Controls/FieldGroup.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js) +- [src/components/Controls/Fields/Boolean.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Boolean.js) +- [src/components/Controls/Fields/ItemsList.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js) +- [src/components/Controls/Fields/Mask.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js) +- [src/components/Controls/Fields/Select.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Select.js) +- [src/components/Controls/Fields/Slider.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Slider.js) +- [src/targets/CNC/GRBL/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/preferences.json) +- [src/targets/CNC/grblHAL/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json) +- [src/targets/CNC/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json) +- [src/targets/Printer3D/Marlin-embedded/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/preferences.json) +- [src/targets/Printer3D/Marlin/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json) +- [src/targets/Printer3D/Repetier/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json) +- [src/targets/Printer3D/Smoothieware/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/preferences.json) +- [src/targets/Printer3D/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json) +- [src/targets/preferences.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json) +- [src/targets/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/translations/en.json) + +The Preferences System provides a declarative, JSON-based configuration mechanism that controls the behavior and appearance of the ESP3D-WEBUI interface. Settings are organized hierarchically across target types (base, machine type, firmware), support complex visibility dependencies, and automatically generate validated UI controls. + +For information about how preferences are rendered in the user interface, see [Settings Interface](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/5.5?branch=%223.0%22). For details on how settings are stored and persisted, see [Settings and Configuration](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/7?branch=%223.0%22). + +--- + +## Hierarchical Preferences Architecture + +The preferences system employs a three-tier cascading structure where each level inherits from and extends the previous level: + +[Flowchart Diagram] + +**Sources**: [src/targets/preferences.json#1-251](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L1-L251)[src/targets/Printer3D/preferences.json#1-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L1-L165)[src/targets/CNC/preferences.json#1-235](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json#L1-L235)[src/targets/Printer3D/Marlin/preferences.json#1-175](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L1-L175)[src/targets/CNC/grblHAL/preferences.json#1-215](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L1-L215) + +### Preferences Structure + +All preferences files follow the same JSON structure with a top-level `settings` object containing category arrays: + +``` +{ + "settings": { + "general": [...], + "panels": [...], + "polling": [...], + "terminal": [...], + "files": [...], + "jog": [...] + } +} +``` + +Categories defined at the base level: + +- `general`: Language, theme, audio, shortcuts, mobile view [src/targets/preferences.json#3-97](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L3-L97) +- `panels`: Panel ordering and fixed layout settings [src/targets/preferences.json#98](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L98-L98) +- `polling`: Polling command configuration [src/targets/preferences.json#99-119](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L99-L119) +- `terminal`: Terminal panel settings [src/targets/preferences.json#120-153](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L120-L153) +- `files`: File system visibility and configuration [src/targets/preferences.json#154-168](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L154-L168) +- `jog`: Jog panel visibility [src/targets/preferences.json#169-183](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L169-L183) +- `notification`: Notification panel settings [src/targets/preferences.json#184-205](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L184-L205) +- `macros`: Macro definitions [src/targets/preferences.json#206-227](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L206-L227) +- `extracontents`: Extra content panels [src/targets/preferences.json#228-232](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L228-L232) + +Machine-type-specific categories: + +- **Printer3D**: `status`, `temperatures`, `charts`[src/targets/Printer3D/preferences.json#3-205](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L3-L205) +- **CNC**: `status`, `probe`, `laser`, `spindle`, `overrides`, `jog`[src/targets/CNC/preferences.json#3-219](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json#L3-L219) + +--- + +## Setting Types + +The preferences system supports several distinct setting types, each mapping to a specific UI control: + +| | | | | | +| --- | --- | --- | --- | --- | +| `boolean` | On/off toggle | `true` or `false` | Checkbox | Enable/disable panels [src/targets/preferences.json#18](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L18-L18) | +| `number` | Numeric input | Integer or float | Number input | Feedrate, temperature limits [src/targets/Printer3D/preferences.json#47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L47-L47) | +| `text` | Single-line text | String | Text input | Commands, file extensions [src/targets/Printer3D/preferences.json#54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L54-L54) | +| `select` | Single choice | String | Dropdown | Filesystem selection [src/targets/CNC/grblHAL/preferences.json#160](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L160-L160) | +| `list` | Ordered items | Array of objects | List editor | Macros, polling commands [src/targets/preferences.json#114](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L114-L114) | +| `group` | Nested settings | Array of setting objects | Fieldset | Related settings grouping [src/targets/Printer3D/preferences.json#41](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L41-L41) | +| `mask` | Bit flags | Integer (as bitmask) | Checkbox group | Axis visibility [src/components/Controls/Fields/Mask.js#43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L43-L43) | +| `pickup` | Dynamic selection | String | Picker modal | Language/theme selection [src/targets/preferences.json#6](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L6-L6) | + +**Sources**: [src/targets/preferences.json#5-114](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/preferences.json#L5-L114)[src/targets/Printer3D/preferences.json#41-67](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L41-L67)[src/components/Controls/Fields/Mask.js#43-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L43-L165) + +### Setting Property Reference + +Each setting object contains the following properties: + +**Required Properties**: + +- `id` (string): Unique identifier for the setting [src/targets/Printer3D/preferences.json#5](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L5-L5) +- `type` (string): One of the types listed above [src/targets/Printer3D/preferences.json#6](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L6-L6) +- `label` (string): Translation key (e.g., "S63", "P82") [src/targets/Printer3D/preferences.json#7](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L7-L7) +- `value` (mixed): Default value matching the type [src/targets/Printer3D/preferences.json#8](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L8-L8) + +**Optional Properties**: + +- `depend` (array): Dependency conditions for visibility [src/targets/Printer3D/preferences.json#15](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L15-L15) +- `help` (string): Translation key for help text [src/targets/Printer3D/preferences.json#58](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L58-L58) +- `append` (string): Translation key for suffix text (e.g., units) [src/targets/Printer3D/preferences.json#50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L50-L50) +- `min` (number): Minimum value for number types [src/targets/Printer3D/preferences.json#88](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L88-L88) +- `max` (number): Maximum value for number types [src/targets/CNC/preferences.json#104](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json#L104-L104) +- `step` (number): Increment step for number types [src/targets/CNC/preferences.json#55](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/preferences.json#L55-L55) +- `options` (array): Available choices for select/mask types [src/targets/CNC/grblHAL/preferences.json#181](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L181-L181) + +--- + +## Dependency System + +Settings can conditionally appear or be enabled based on the values of other settings or connection properties. The dependency evaluation system supports complex boolean logic. + +[Flowchart Diagram] + +**Sources**: [src/components/Controls/Fields/Mask.js#30-83](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L30-L83)[src/components/Controls/FieldGroup.js#26-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js#L26-L33) + +### Dependency Conditions + +**Simple Setting Dependency**: + +``` +{ + "id": "openstatusonstart", + "type": "boolean", + "label": "S93", + "value": true, + "depend": [{"id": "showstatuspanel", "value": true}] +} +``` + +This setting only appears when `showstatuspanel` is `true`[src/targets/Printer3D/preferences.json#11-16](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L11-L16) + +**Connection Property Dependency**: + +``` +{ + "id": "sdlistcmd", + "depend": [ + {"id": "sd", "value": true}, + {"connection_id": "SDConnection", "value": "=='none'"} + ] +} +``` + +This setting appears only when `sd` is enabled AND the machine connection property `SDConnection` equals `'none'`[src/targets/Printer3D/Marlin/preferences.json#88-107](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L88-L107) + +**Complex OR Logic**: + +``` +{ + "id": "playcmd", + "depend": [ { + "orGroups": [ + [{"id": "directsd", "value": true}], + [{"id": "flashfs", "value": true}] + ] + }] +} +``` + +This uses `orGroups` to express: `(directsd==true) OR (flashfs==true)`[src/targets/CNC/grblHAL/preferences.json#135-157](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L135-L157) + +### Dependency Operators + +| | | | | +| --- | --- | --- | --- | +| `value` | Setting or Connection | Exact match or comparison | `"value": "=='none'"`[src/targets/Printer3D/Marlin/preferences.json#100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L100-L100) | +| `notvalue` | Setting or Connection | Not equal | `"notvalue": "none"`[src/targets/Printer3D/Repetier/preferences.json#178](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/preferences.json#L178-L178) | +| `contains` | Connection (string) | Substring match | Used for checking axis availability [src/targets/CNC/grblHAL/preferences.json#207-209](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L207-L209) | + +--- + +## Setting Type Details + +### Mask Type Implementation + +The `Mask` component represents a bitmask as a group of checkboxes. It is used extensively for axis visibility configuration in CNC targets. + +- **Data Flow**: It uses `BitsArray.fromInt(value, maskSize)` to convert the integer setting value into an array of bits [src/components/Controls/Fields/Mask.js#91](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L91-L91) +- **UI Generation**: It maps over the `options` array, creating a `Boolean` component for each bit [src/components/Controls/Fields/Mask.js#100-139](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L100-L139) +- **State Update**: When a checkbox is toggled, it uses `mask.setBit()` and then calls `setValue(mask.toInt())` to save the new integer value back to settings [src/components/Controls/Fields/Mask.js#145-153](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L145-L153) + +**Sources**: [src/components/Controls/Fields/Mask.js#43-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Mask.js#L43-L165)[src/targets/CNC/grblHAL/preferences.json#197-201](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L197-L201) + +### Group Type Implementation + +The `FieldGroup` component serves as a container for nested settings. It evaluates its own `depend` array; if conditions are not met, the entire group and its children are not rendered [src/components/Controls/FieldGroup.js#28-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js#L28-L33) + +**Sources**: [src/components/Controls/FieldGroup.js#28-53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js#L28-L53)[src/targets/Printer3D/preferences.json#40-44](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L40-L44) + +--- + +## Target-Specific Preference Examples + +### Marlin File System + +Marlin targets define complex storage dependencies, supporting internal SD, external SD, and TFT-based storage (USB/SD) [src/targets/Printer3D/Marlin/preferences.json#68-210](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L68-L210) Visibility of specific commands like `sdlistcmd` or `sddeletecmd` is strictly tied to whether the `SDConnection` is "direct" or "none" [src/targets/Printer3D/Marlin/preferences.json#88-153](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L88-L153) + +### GrblHAL Axis Control + +GrblHAL uses the `Axisletters` connection property to dynamically show or hide axis controls. If the firmware reports it only supports "XYZ", the "A", "B", and "C" axis toggles are hidden via the dependency system [src/targets/CNC/grblHAL/preferences.json#202-215](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L202-L215) + +### Smoothieware Unix-like Commands + +Smoothieware preferences replace standard G-code commands (like `M20`) with Unix-like commands (like `ls -s /sd/#`) in the `sdlistcmd` and `sdplaycmd` fields [src/targets/Printer3D/Smoothieware/preferences.json#98-126](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/preferences.json#L98-L126) + +--- + +## Translation and Labeling + +The preferences system uses a unified labeling system where strings are replaced by keys referencing `src/targets/translations/en.json`. + +- **S-Prefix**: System strings (e.g., "S63" = "Show" [src/targets/translations/en.json#64](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/translations/en.json#L64-L64)). +- **P-Prefix**: Printer-specific strings (e.g., "P15" = "Emergency stop" [src/targets/Printer3D/Marlin/preferences.json#7](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/preferences.json#L7-L7)). +- **CN-Prefix**: CNC-specific strings (e.g., "CN8" = "Axis" [src/targets/CNC/grblHAL/preferences.json#199](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/preferences.json#L199-L199)). + +**Sources**: [src/targets/translations/en.json#1-235](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/translations/en.json#L1-L235)[src/targets/Printer3D/preferences.json#7](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/preferences.json#L7-L7) + +--- + +# 4.3-TargetContext-and-Data-Processing + +# TargetContext and Data Processing +Relevant source files + +- [src/components/Helpers/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/filters.js) +- [src/components/Helpers/storedState.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js) +- [src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) +- [src/components/Panels/Status.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js) +- [src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js) +- [src/targets/CNC/Controls/QuickStopButton.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js) +- [src/targets/CNC/GRBL/Controls/BackgroundContainer.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js) +- [src/targets/Printer3D/Marlin-embedded/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/TargetContext.js) +- [src/targets/Printer3D/Marlin-embedded/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/filters.js) +- [src/targets/Printer3D/Marlin/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js) +- [src/targets/Printer3D/Marlin/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js) +- [src/targets/Printer3D/Repetier/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/TargetContext.js) +- [src/targets/Printer3D/Repetier/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/filters.js) +- [src/targets/Printer3D/Smoothieware/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js) +- [src/targets/Printer3D/Smoothieware/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js) +- [src/targets/Printer3D/Smoothieware/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/index.js) + +This page documents the TargetContext system, which is responsible for processing firmware-specific data streams received from the ESP3D device, parsing responses using filters, and updating application state. TargetContext acts as the bridge between raw firmware output and the UI components that display machine status. + +For information about the broader target configuration hierarchy, see [Target Types and Structure](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.1?branch=%223.0%22). For details on the command and event management systems that work alongside TargetContext, see [Variables and Events System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.5?branch=%223.0%22). For context provider architecture in general, see [Context and State Management](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.3?branch=%223.0%22). + +## TargetContext Architecture + +Each target implements a `TargetContextProvider` component that wraps the application with firmware-specific state and data processing. The provider exposes state via the `useTargetContext()` hook and processes incoming firmware data through the `processData(type, data, noecho)` function. + +**TargetContext Data Flow** + +[Flowchart Diagram] + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#60-464](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L60-L464)[src/components/Panels/Status.js#169-171](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L169-L171) + +## Core Components + +### TargetContextProvider + +The `TargetContextProvider` component is the root of the data processing system. It maintains all firmware-specific state and provides the `processData` function to the application. + +| | | | +| --- | --- | --- | +| `TargetContextProvider` | Preact Component | Context provider wrapping application | +| `useTargetContext` | Hook | Accesses context state from components | +| `useTargetContextFn` | Utility Object | Provides static utility functions | +| `processData` | Function | Main entry point for all incoming data | + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#60-67](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L60-L67)[src/targets/Printer3D/Marlin/TargetContext.js#70-462](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L70-L462) + +### State Management + +The `TargetContextProvider` maintains firmware-specific state using a combination of `useState` and `useRef` hooks: + +| | | | | +| --- | --- | --- | --- | +| `positions` | `useState` | `setPositions({ x, y, z })` | Current machine coordinates | +| `temperatures` | `useState` | `setTemperatures({ T:[], B:[], C:[], P:[], R:[], M:[] })` | Current temperature readings | +| `temperaturesList` | `useState` | `add2TemperaturesList()` | Historical temperature data (max 400 entries) | +| `status` | `useState` | `setStatus(globalStatus.current)` | Print status, filename, state | +| `streamStatus` | `useState` | `setStreamStatus()` | ESP701 streaming status | +| `fanSpeed` | `useRef` + `useState` | `fansSpeed.current[index] = value` | Fan speed by index | +| `flowRate` | `useRef` + `useState` | `flowsRate.current[index] = value` | Flow rate per extruder | +| `feedRate` | `useRef` + `useState` | `feedsRate.current[index] = value` | Feed rate override | +| `sensorData` | `useState` | `setSensorData({ S: [] })` | Custom sensor readings | + +**Ref-based State Pattern:** + +The `fanSpeed`, `flowRate`, and `feedRate` use a hybrid pattern where data is stored in a `useRef` but exposed via `useState`: + +``` +const fansSpeed = useRef([]) +const [fanSpeed, setFanSpeed] = useState(fansSpeed.current) + +// Update pattern in dispatchInternally: +fansSpeed.current[index] = value +setFanSpeed(fansSpeed.current) +``` + +This pattern allows indexed updates without recreating the entire array, while still triggering re-renders. + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#72-96](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L72-L96)[src/targets/Printer3D/Marlin/TargetContext.js#418-455](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L418-L455) + +## Data Processing Pipeline + +The `processData(type, data, noecho)` function is the entry point for all firmware data. It handles three data types with different processing strategies: + +**Processing by Type** + +```mermaid +sequenceDiagram + participant WS as "WebSocket/Serial" + participant PD as "processData()" + participant Buf as "dataBuffer.current" + participant DI as "dispatchInternally()" + participant F as "filters.js" + participant S as "State Setters" + participant T as "terminal.add()" + WS->>PD: type='stream', data='ok T:25.0...' + PD->>Buf: data.split('').forEach() + Buf->>Buf: Accumulate in buffer + Buf->>DI: dispatchInternally('stream' | line) + DI->>F: isTemperatures(line)? + F->>S: setTemperatures(getTemperatures()) + Buf->>T: terminal.add({type | content | isverboseOnly}) + Buf->>Buf: buffer = '' + PD->>DI: dispatchInternally('response' | data) + DI->>F: Check all filters + F->>S: Update matching state + PD->>T: terminal.add({type | content}) + PD->>DI: dispatchInternally('core' | data) + DI->>F: Limited filter check (sensors only) + F->>S: Update state + PD->>PD: dispatchToExtensions(type | data) +``` + +**Type-Specific Characteristics:** + +| | | | | | +| --- | --- | --- | --- | --- | +| `stream` | Character-by-character until `\r`/`\n` | Yes (with JSON beautify) | Full | Real-time serial data | +| `response` | None | Yes (unless `noecho=true`) | Full | Command response data | +| `core` | None | No | Sensors only | Internal state updates | +| `error` | None | Yes | None | Error messages | +| `echo` | None | Yes | None | User command echo | + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#312-414](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L312-L414) + +### processData Function + +The `processData` function is the main entry point for all incoming firmware data. It handles buffering, parsing, and routing to appropriate handlers. + +**Function Signature:**`processData(type, data, noecho = false)` + +**Parameters:** + +- `type`: One of `"stream"`, `"response"`, `"core"`, `"error"`, or `"echo"` +- `data`: Raw string data from firmware +- `noecho`: Boolean to suppress terminal output (default: false) + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#312-313](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L312-L313) + +### dataBuffer System + +The `dataBuffer` ref maintains separate accumulators for each data type: + +``` +const dataBuffer = useRef({ + stream: "", + core: "", + response: "", + error: "", + echo: "", +}) +``` + +**Stream Buffering Algorithm:** + +``` +// In processData for type == "stream" +data.split("").forEach((element, index) => { + if (element == "\n" || element == "\r") { + if (dataBuffer.current[type].length > 0) { + // Process complete line + dispatchInternally(type, dataBuffer.current[type]) + terminal.add({ type, content: dataBuffer.current[type], ... }) + dataBuffer.current[type] = "" + } + } else { + dataBuffer.current[type] += element + } +}) +``` + +This character-by-character accumulation handles firmware that sends partial lines or uses inconsistent line endings (`\r`, `\n`, or `\r\n`). The `response` and `core` types bypass buffering since they arrive as complete messages. + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#164-170](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L164-L170)[src/targets/Printer3D/Marlin/TargetContext.js#318-373](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L318-L373) + +## Filter System + +Filters are pairs of `is*()` and `get*()` functions in `filters.js` that detect and parse firmware-specific response patterns. The `dispatchInternally()` function checks each filter in sequence. + +**Marlin Filter Functions** + +| | | | | +| --- | --- | --- | --- | +| `isOk()` | `str.startsWith("ok")` | N/A (ignored) | None | +| `isTemperatures()` / `getTemperatures()` | `/T:.*\s@:[0-9]*/g` | `{ T:[], B:[], C:[], P:[], R:[], M:[] }` | `setTemperatures()` | +| `isPositions()` / `getPositions()` | `/X:\s*[+-]?[0-9.]+\s*Y:.*Z:.*E/` | `{ x, y, z }` | `setPositions()` | +| `isPrintStatus()` / `getPrintStatus()` | Multiple patterns | `{ status, printing, progress }` or `{ time }` | `globalStatus.current.printState` | +| `isPrintFileName()` / `getPrintFileName()` | `/Current\sfile:\s(.*)/` | filename string | `globalStatus.current.filename` | +| `isStatus()` / `getStatus()` | `/echo:busy:\s(.*)/ or /Error:(.*)/` | status string | `globalStatus.current.state` | +| `isFlowRate()` / `getFlowRate()` | `/echo:E([0-9])\sFlow:\s(.*)\%/` | `{ index, value }` | `flowsRate.current[index]` | +| `isFanSpeed()` / `getFanSpeed()` | `/M106\sP([0-9]+)\sS([0-9]+)/` | `{ index, value }` | `fansSpeed.current[index]` | +| `isFeedRate()` / `getFeedRate()` | `/FR:(.*)\%/` | `{ index: 0, value }` | `feedsRate.current[0]` | +| `isPrinterCapability()` / `getPrinterCapability()` | `FIRMWARE_NAME:` or `/^Cap:([^:]+):[0-1]$/` | Array of `{ name, value }` | `printerCapabilities` array | +| `isSensor()` / `getSensor()` | `str.startsWith("SENSOR:")` | Array of `{ value, unit }` | `setSensorData()` | +| `isStreamingStatus()` / `getStreamingStatus()` | JSON with `cmd: "701"` | `{ status, name, processed, total, elapsed }` | `setStreamStatus()` | + +**Filter Application in dispatchInternally** + +[Flowchart Diagram] + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#1-414](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L1-L414)[src/targets/Printer3D/Marlin/TargetContext.js#172-310](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L172-L310) + +### Temperature Parsing Example + +**Marlin Temperature Format:**`ok T:25.00 /120.00 B:25.00 /0.00 @:127 B@:0` + +**Filter Implementation:** + +``` +// Detection +const isTemperatures = (str) => { + const regex_search = /T:.*\s@:[0-9]*/g + return regex_search.test(str) +} + +// Extraction +const getTemperatures = (str) => { + const response = { + T: [], // Extruders T0-T8 + B: [], // Heated bed + // ... + } + const regex_search = + /(B|T|C|P|R)([\d]*):([+|-]?[0-9]*\.?[0-9]+|inf)? \/([+]?[0-9]*\.?[0-9]+)/g + + while ((result = regex_search.exec(str)) !== null) { + response[result[1]][result[2] === "" ? 0 : result[2]] = { + value: result[3], + target: result[4] + } + } + return response +} +``` + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#44-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L44-L78) + +## dispatchInternally Function + +The `dispatchInternally(type, data)` function applies filter checks and routes data to state updates. It always calls `processor.handle()` for file operations, then applies type-specific filter chains. + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#172-310](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L172-L310) + +### Historical Lists Management + +Temperature history is maintained for graphing: + +``` +const MAX_TEMPERATURES_LIST_SIZE = 400 + +const add2TemperaturesList = (temperaturesSet) => { + if (temperaturesListRef.current.length >= MAX_TEMPERATURES_LIST_SIZE) { + temperaturesListRef.current.shift() + } + temperaturesListRef.current = + temperaturesListRef.current.concat(temperaturesSet) + setTemperaturesList(temperaturesListRef.current) +} +``` + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#78-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L78-L121) + +## Terminal Integration + +The `processData()` function sends processed lines to `terminal.add()` from the `DatasContext`: + +``` +const { terminal } = useDatasContext() + +// In processData() +terminal.add({ type, content: dataBuffer.current[type], isverboseOnly }) +``` + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#163](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L163-L163)[src/targets/Printer3D/Marlin/TargetContext.js#347](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L347-L347) + +## Extension Dispatch + +All processed data is forwarded to loaded extensions via the `dispatchToExtensions` helper: + +``` +dispatchToExtensions(type, data) +``` + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#412](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L412-L412) + +## Firmware-Specific Implementations + +Each firmware implements its own `TargetContext.js` with specialized filters: + +| | | +| --- | --- | +| Marlin | `src/targets/Printer3D/Marlin/TargetContext.js` | +| Smoothieware | `src/targets/Printer3D/Smoothieware/TargetContext.js` | +| Repetier | `src/targets/Printer3D/Repetier/TargetContext.js` | +| Marlin-embedded | `src/targets/Printer3D/Marlin-embedded/TargetContext.js` | + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#1-18](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L1-L18)[src/targets/Printer3D/Smoothieware/TargetContext.js#1-18](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js#L1-L18)[src/targets/Printer3D/Repetier/TargetContext.js#1-18](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/TargetContext.js#L1-L18)[src/targets/Printer3D/Marlin-embedded/TargetContext.js#1-18](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/TargetContext.js#L1-L18) + +## Context Store Structure + +The `TargetContextProvider` exposes machine state via `useTargetContext()`: + +``` +const store = { + positions, + temperatures, + temperaturesList: { + current: temperaturesList, + clear: clearTemperaturesList + }, + status: status, + streamStatus, + processData +} +``` + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#418-461](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L418-L461) + +--- + +# 4.4-Filter-System + +# Filter System +Relevant source files + +- [src/components/Helpers/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/filters.js) +- [src/components/Helpers/storedState.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js) +- [src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) +- [src/components/Panels/Status.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js) +- [src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js) +- [src/targets/CNC/Controls/QuickStopButton.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js) +- [src/targets/CNC/GRBL/Controls/BackgroundContainer.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js) +- [src/targets/Printer3D/Marlin-embedded/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/TargetContext.js) +- [src/targets/Printer3D/Marlin-embedded/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/filters.js) +- [src/targets/Printer3D/Marlin/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js) +- [src/targets/Printer3D/Marlin/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js) +- [src/targets/Printer3D/Repetier/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/TargetContext.js) +- [src/targets/Printer3D/Repetier/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/filters.js) +- [src/targets/Printer3D/Smoothieware/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js) +- [src/targets/Printer3D/Smoothieware/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js) +- [src/targets/Printer3D/Smoothieware/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/index.js) + +## Purpose and Scope + +The Filter System is the pattern matching and data extraction layer that transforms raw firmware responses into structured state objects. Each target (Marlin, GRBL, Repetier, etc.) implements firmware-specific filters that use regular expressions to identify and parse response formats. The system enables the WebUI to support multiple firmware types through a common abstraction while handling their different communication protocols. + +For information about how filters integrate with the overall target architecture, see [Target Types and Structure](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.1?branch=%223.0%22). For details on how parsed data updates UI state, see [TargetContext and Data Processing](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.3?branch=%223.0%22). + +## Filter Function Pattern + +Filters are implemented as function pairs that follow a consistent naming convention: + +| | | | | +| --- | --- | --- | --- | +| Test function | `is*()` | `boolean` | Tests if a string matches a specific pattern | +| Extractor function | `get*()` | `object` or `null` | Extracts structured data from a matched string | + +### Filter Pattern Diagram + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#26-54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L26-L54) + +## Data Processing Pipeline + +The filter system operates within the `dispatchInternally` function of each target's `TargetContext`. Raw data is tested against multiple filters in sequence until a match is found. + +### Filter Processing Flow + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#172-247](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L172-L247)[src/targets/Printer3D/Smoothieware/TargetContext.js#151-213](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js#L151-L213) + +## Regex Pattern Matching + +Each filter uses regular expressions to match firmware-specific response formats. The patterns capture groups that are then extracted into structured objects. + +### Temperature Filter Example + +The Marlin temperature filter handles multiple extruders, bed, chamber, and other sensors. It specifically accounts for variations like MKS serial protocols [src/targets/Printer3D/Marlin/filters.js#50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L50-L50) + +**Implementation:** + +[src/targets/Printer3D/Marlin/filters.js#44-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L44-L78) defines the temperature filter: + +- Line 45: `isTemperatures()` tests for the pattern using `/T:.*\s@:[0-9]*/g`. +- Line 61-62: `getTemperatures()` uses a global regex to capture tool type, index, current, and target. +- Line 72: Results are mapped to the response object using the tool type as the key and index as the array position. + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#36-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L36-L78) + +## Common Filter Types + +### Position Filters + +Extract machine position data (X, Y, Z coordinates) from standard reporting formats. + +**Test Pattern:**[src/targets/Printer3D/Marlin/filters.js#86-90](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L86-L90) + +``` +/X:\s*[+,-]?[0-9]*\.?[0-9]+?\s*Y:\s*[+,-]?[0-9]*\.?[0-9]+?\s*Z:\s*[+,-]?[0-9]*\.?[0-9]+?\s*E/ +``` + +**Example Input:**`X:0.00 Y:0.00 Z:0.00 E:0.00 Count X:0 Y:0 Z:0`**Example Output:**`{x: "0.00", y: "0.00", z: "0.00"}`[src/targets/Printer3D/Marlin/filters.js#97](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L97-L97) + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#80-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L80-L100) + +### Print Status Filters + +Detect and parse printing progress information, supporting multiple formats including SD byte progress and M73 messages. + +**Test Patterns:**[src/targets/Printer3D/Marlin/filters.js#106-124](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L106-L124) + +- `/(Not\sSD\sprinting|Done\sprinting\sfile)/` +- `/SD\sprinting\sbyte\s([0-9]*)\/([0-9]*)/` +- `/echo:\sM73\sProgress:\s+([0-9.]*)%/` + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#102-180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L102-L180) + +### Status and Error Filters + +Parse printer state and busy messages to update the UI status indicator. + +**Test Patterns:**[src/targets/Printer3D/Marlin/filters.js#207-218](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L207-L218) + +- `/echo:busy:\s(.*)/` +- `/Error:(.*)/` + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#204-231](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L204-L231) + +## Integration with TargetContext + +The filter system is tightly integrated with `TargetContextProvider` through the `dispatchInternally` function, which orchestrates filter execution and state updates. + +### Filter-to-State Mapping + +### State Update Flow + +[src/targets/Printer3D/Marlin/TargetContext.js#178-247](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L178-L247) shows the typical pattern: + +1. **Temperature Logic**: Matches data, extracts tool values, and updates the temperature history list for charts [src/targets/Printer3D/Marlin/TargetContext.js#180-183](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L180-L183) +2. **Print Status Logic**: Handles both progress percentage and print time estimation. If a time object is returned, it updates `globalStatus.current.printTime`[src/targets/Printer3D/Marlin/TargetContext.js#189-190](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L189-L190) +3. **Estimation**: If printing, the system calculates `printLeftTime` using the `estimatedTime` utility [src/targets/Printer3D/Marlin/TargetContext.js#198-202](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L198-L202) + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#172-247](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L172-L247)[src/targets/Printer3D/Smoothieware/TargetContext.js#151-213](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js#L151-L213) + +## Target-Specific Filter Implementations + +Each firmware target implements its own filter set tailored to that firmware's response format. While the function signatures remain consistent, the regex patterns and parsing logic differ significantly. + +| | | | +| --- | --- | --- | +| Marlin | [src/targets/Printer3D/Marlin/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js) | Detailed tool indexing (T0, T1, B, C) and M73 support. | +| Smoothieware | [src/targets/Printer3D/Smoothieware/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js) | Unix-like file paths in progress reports (`file: /sd/...`) [src/targets/Printer3D/Smoothieware/filters.js#110](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L110-L110) | +| Repetier | [src/targets/Printer3D/Repetier/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/filters.js) | Support for Repetier-specific fan and flow rate reporting. | + +**Sources:**[src/targets/Printer3D/Marlin/filters.js#1-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L1-L78)[src/targets/Printer3D/Smoothieware/filters.js#107-161](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/filters.js#L107-L161) + +## Extension of the Filter System + +The filter system is designed for extensibility. To add support for a new firmware feature: + +1. **Define Filter**: Add `isFeature` and `getFeature` to the target's `filters.js`. +2. **Import**: Import the new functions into the target's `TargetContext.js`. +3. **Dispatch**: Add a condition in `dispatchInternally`[src/targets/Printer3D/Marlin/TargetContext.js#172](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L172-L172) +4. **Update State**: Use a `useState` hook to store the parsed data and pass it to the context provider. + +**Sources:**[src/targets/Printer3D/Marlin/TargetContext.js#30-54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L30-L54)[src/targets/Printer3D/Marlin/filters.js#1-19](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L1-L19) + +--- + +# 4.5-Variables-and-Events-System + +# Variables and Events System +Relevant source files + +- [config/targets/CNC/grblHAL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/config/targets/CNC/grblHAL/index.js) +- [src/areas/elementsCache.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/elementsCache.js) +- [src/contexts/UiContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/UiContext.js) +- [src/hooks/eventBus.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/eventBus.js) +- [src/targets/CNC/GRBL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js) +- [src/targets/CNC/grblHAL/DIRECTSD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js) +- [src/targets/CNC/grblHAL/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js) +- [src/targets/CNC/grblHAL/MachineSettings.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/MachineSettings.js) +- [src/targets/CNC/grblHAL/files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js) +- [src/targets/CNC/grblHAL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js) +- [src/targets/CNC/grblHAL/realCommandsTable.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js) +- [src/targets/CNC/grblHAL/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json) +- [src/targets/CNC/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json) + +## Purpose and Scope + +The Variables and Events System provides runtime customization and inter-component communication mechanisms in ESP3D-WEBUI. This system enables: + +- **Dynamic command substitution** through named variables that map to firmware-specific commands. +- **Event-driven communication** between UI components and external extensions. +- **Runtime modification** of command tables without code changes. +- **Extension integration** by allowing external code to inject commands and subscribe to events. + +This page covers the structure and usage of `variablesList` and `eventsList` objects. For information about how these variables are replaced in actual commands, see the `replaceVariables` function usage throughout the codebase. For target-specific data processing, see [TargetContext and Data Processing](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.3?branch=%223.0%22). For file system command integration, see [File System Operations](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/10?branch=%223.0%22). + +--- + +## System Architecture + +The Variables and Events System operates as a runtime registry that bridges UI components, file operations, and firmware-specific commands. + +**Variables and Events Registry Architecture** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/grblHAL/index.js#52-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L79)[src/targets/CNC/GRBL/index.js#52-77](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L52-L77) + +--- + +## variablesList Object + +The `variablesList` object provides a unified registry of all command variables available in a target. It is exported from each target's `index.js` and consumed by components that need to display, validate, or execute commands. + +### Structure + +**variablesList Class Structure** + +[Class Diagram] + +Sources: [src/targets/CNC/grblHAL/index.js#52-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L61) + +### Property Definitions + +| | | | +| --- | --- | --- | +| `commands` | `Array` | Combined array of `realCommandsTable` and `variablesTable` entries. | +| `addCommand` | `Function` | Adds a new command variable at runtime using `addObjectItem` helper. | +| `removeCommand` | `Function` | Removes a command variable by name using `removeObjectItem` helper. | +| `modes` | `Array` | G-code parser mode definitions from `gcode_parser_modes`. | +| `hideFeatures` | `Boolean` | Flag to hide advanced features (grblHAL only). | +| `allowEmptyLine` | `Boolean` | Flag to allow empty lines in command input (grblHAL only). | + +Sources: [src/targets/CNC/grblHAL/index.js#52-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L61)[src/targets/CNC/GRBL/index.js#52-59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L52-L59) + +### Implementation Example + +``` +// From grblHAL target +const variablesList = { + commands: [...realCommandsTable, ...variablesTable], + addCommand: (variable) => + addObjectItem(variablesList.commands, "name", variable), + removeCommand: (name) => + removeObjectItem(variablesList.commands, "name", name), + modes: [...gcode_parser_modes], + hideFeatures: false, + allowEmptyLine: true, +} +``` + +Sources: [src/targets/CNC/grblHAL/index.js#52-61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L52-L61) + +--- + +## realCommandsTable Structure + +The `realCommandsTable` contains firmware-specific real-time commands that are transmitted as raw byte sequences. These commands bypass normal command buffering and execute immediately. + +### Command Entry Format + +Each entry in `realCommandsTable` is an object with three properties: + +**Command Entry Definition** + +[Class Diagram] + +Sources: [src/targets/CNC/grblHAL/realCommandsTable.js#20-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js#L20-L50) + +### Example Entries + +| | | | +| --- | --- | --- | +| `#SOFTRESET#` | `\x18` | Immediately reset the controller. | +| `#STATUSREPORT#` | `\x80` | Request current status report. | +| `#CYCLESTART#` | `\x81` | Resume paused operation. | +| `#FEEDHOLD#` | `\x82` | Pause current operation. | +| `#FO100#` | `\x90` | Set feed override to 100%. | +| `#FO+10#` | `\x91` | Increase feed override by 10%. | +| `#SSO100#` | `\x99` | Set spindle speed override to 100%. | +| `#T-FLOODCOOLANT#` | `\xA0` | Toggle flood coolant. | + +Sources: [src/targets/CNC/grblHAL/realCommandsTable.js#20-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js#L20-L50) + +--- + +## eventsList Object + +The `eventsList` object provides a simple event bus implementation for inter-component communication and extension integration. Components can register event handlers, emit events, and unregister handlers. + +### Event Bus Pattern + +**eventsList Interaction Flow** + +```mermaid +sequenceDiagram + participant Ext as Extension/Component + participant Events as eventsList + participant Handler1 as Handler 1 + participant Handler2 as Handler 2 + Ext->>Events: on("fileSelected" | handler1) + Ext->>Events: on("fileSelected" | handler2) + Note over Events: evts["fileSelected"] = [handler1 | handler2] + Ext->>Events: emit("fileSelected" | {file: "test.gcode"}) + Events->>Handler1: handler1({file: "test.gcode"}) + Events->>Handler2: handler2({file: "test.gcode"}) + Ext->>Events: off("fileSelected" | handler1) + Note over Events: Remove handler1 from evts["fileSelected"] +``` + +Sources: [src/targets/CNC/grblHAL/index.js#62-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L62-L79) + +### API Methods + +| | | | +| --- | --- | --- | +| `on` | `(event: String, fn: Function) => void` | Register an event handler for the specified event name. | +| `off` | `(event: String, fn: Function) => void` | Unregister a specific event handler. | +| `emit` | `(event: String, data: Any) => void` | Trigger all handlers registered for the event, passing data. | + +Sources: [src/targets/CNC/grblHAL/index.js#62-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L62-L79) + +### Implementation Details + +The implementation uses internal arrays to store functions associated with event keys. + +``` +const eventsList = { + evts: [], + on: (event, fn) => { + if (typeof eventsList.evts[event] === "undefined") { + eventsList.evts[event] = [] + } + addObjectItem(eventsList.evts[event], "fn", { fn: fn }) + }, + off: (event, fn) => { + // Note: references variablesList.evts instead of eventsList.evts in some versions + removeObjectItem(eventsList.evts[event], "fn", fn) + }, + emit: (event, data) => { + if (eventsList.evts[event]) + eventsList.evts[event].forEach((element) => { + if (typeof element.fn === "function") element.fn(data) + }) + }, +} +``` + +Sources: [src/targets/CNC/grblHAL/index.js#62-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L62-L79)[src/targets/CNC/GRBL/index.js#60-77](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L60-L77) + +--- + +## Runtime Command Management + +The `addCommand` and `removeCommand` functions enable dynamic modification of the command registry at runtime. This is essential for extensions and plugins that need to inject custom commands. + +**Runtime Command Modification** + +```mermaid +sequenceDiagram + participant Ext as Extension + participant VarList as variablesList + participant Helper as addObjectItem/removeObjectItem + participant Cmds as commands[] + Ext->>VarList: addCommand({name: " + VarList->>Helper: addObjectItem(commands | "name" | variable) + Helper->>Cmds: Update or Append entry + Ext->>VarList: removeCommand(" + VarList->>Helper: removeObjectItem(commands | "name" | " + Helper->>Cmds: Remove entry from array +``` + +Sources: [src/targets/CNC/grblHAL/index.js#54-57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L54-L57) + +--- + +## Integration with File System Operations + +The Variables and Events System integrates deeply with file system operations, particularly for constructing firmware-specific commands for file playback via the `play` command. + +### Variable Replacement in File Commands + +**File Command Variable Substitution** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/grblHAL/DIRECTSD-source.js#106-119](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L106-L119)[src/targets/CNC/grblHAL/FLASH-source.js#115-128](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L115-L128) + +### Example: DIRECTSD Play Command Construction + +``` +play: (path, filename) => { + const spath = (path + (path == "/" ? "" : "/") + filename).replaceAll( + "//", + "/" + ) + const cmd = useUiContextFn + .getValue("playcmd") // Retrieves stored variable from UiContext + .replace("#", spath) // Replaces symbolic # with the actual file path + .replaceAll("//", "/") + return { + type: "cmd", + cmd, + } +} +``` + +Sources: [src/targets/CNC/grblHAL/DIRECTSD-source.js#106-119](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L106-L119) + +--- + +## Translation Integration + +Variables are referenced in translation files to provide localized descriptions and labels. The translation system uses prefixed keys to namespace command-related strings. + +**Translation Space to Code Entity Space** + +[Flowchart Diagram] + +Sources: [src/targets/CNC/translations/en.json#116-158](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json#L116-L158)[src/targets/CNC/grblHAL/translations/en.json#2-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json#L2-L10) + +### Localization Examples + +From the CNC target English translation file: + +- `btnHAll`: "Home All axis" [src/targets/CNC/translations/en.json#116](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json#L116-L116) +- `error:1`: "G-code words consist of a letter and a value. Letter was not found." [src/targets/CNC/translations/en.json#158](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json#L158-L158) +- `$0`: "Step pulse, microseconds" [src/targets/CNC/grblHAL/translations/en.json#2](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json#L2-L2) + +--- + +## Export and Access + +The Variables and Events System is exported from each target's `index.js` and made available to the rest of the application via the Target context. + +``` +export { + // ... + variablesList, + eventsList, + // ... +} +``` + +Sources: [src/targets/CNC/grblHAL/index.js#81-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js#L81-L103)[src/targets/CNC/GRBL/index.js#79-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js#L79-L101) + +--- + +# 5-User-Interface-Components + +# User Interface Components +Relevant source files + +- [Memo/preferences.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/Memo/preferences.md?plain=1) +- [src/components/Controls/FieldGroup.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js) +- [src/components/Controls/Fields/Boolean.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Boolean.js) +- [src/components/Controls/Fields/Input.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js) +- [src/components/Controls/Fields/ItemsList.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js) +- [src/components/Controls/Fields/Select.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Select.js) +- [src/components/Controls/Fields/Slider.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Slider.js) +- [src/components/Helpers/components.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js) +- [src/components/Helpers/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/index.js) +- [src/components/Panels/Files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js) +- [src/components/Panels/Jog.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js) +- [src/components/Panels/JogCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js) +- [src/components/Panels/JogPlotter.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js) +- [src/components/Panels/LaserCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js) +- [src/components/Panels/Notifications.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js) +- [src/components/Panels/OverridesCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js) +- [src/components/Panels/SpindleCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js) +- [src/style/components/_control.scss](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss) + +This page catalogs the major UI components that comprise the ESP3D-WEBUI interface, including panels, tabs, controls, and field components. It explains the component hierarchy, patterns for visibility management, context integration, and styling conventions. + +**Scope**: This page focuses on the structure and behavior of UI components themselves. For state management via contexts, see [Context and State Management](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.3?branch=%223.0%22). For panel-specific features (temperature monitoring, jogging, file management, etc.), see sections [Status and Monitoring Panels](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/5.2?branch=%223.0%22) through [Terminal Panel](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/5.6?branch=%223.0%22). For the settings configuration system that drives the InterfaceTab, see [Preferences System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.2?branch=%223.0%22) and [Settings and Configuration](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/7?branch=%223.0%22). + +--- + +## Component Architecture Overview + +ESP3D-WEBUI follows a **hierarchical component structure** where high-level containers orchestrate multiple specialized components. The architecture employs Preact for rendering, context hooks for state access, and a dependency system for conditional visibility. + +### Component Hierarchy + +[Flowchart Diagram] + +**Sources**: [src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73)[src/components/Panels/SpindleCNC.js#106-111](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L106-L111)[src/components/Panels/LaserCNC.js#80-84](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js#L80-L84)[src/components/Panels/Files.js#57-71](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L57-L71)[src/components/Controls/FieldGroup.js#28-53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js#L28-L53) + +### Component Rendering Flow + +The top-level `ViewContainer` determines which major UI area to render based on connection state: + +[State Diagram] + +The `ViewContainer` component [src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73) implements this logic by checking `dialogs.needLogin` and `connection.connectionState`. + +**Sources**: [src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73) + +--- + +## Core Component Types + +### 1. Panels (Feature Modules) + +Panels are self-contained UI sections. Each panel consumes contexts and checks visibility via `useUiContextFn.getValue()`. + +- **SpindlePanel**: Controls CNC spindle modes (M3, M4, M5) and speeds [src/components/Panels/SpindleCNC.js#106-210](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L106-L210) +- **LaserPanel**: Manages laser power percentages and test durations [src/components/Panels/LaserCNC.js#80-186](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js#L80-L186) +- **FilesPanel**: Integrated file manager supporting multiple filesystems like SD and Flash [src/components/Panels/Files.js#57-196](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L57-L196) + +**Sources**: [src/components/Panels/SpindleCNC.js#106-210](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L106-L210)[src/components/Panels/LaserCNC.js#80-186](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js#L80-L186)[src/components/Panels/Files.js#57-196](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L57-L196) + +### 2. Tabs (Full-Page Views) + +Tabs like the `InterfaceTab`[src/tabs/interface/index.js#229-552](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L229-L552) render user preferences using a schema-driven system. It iterates over setting groups and dynamically generates UI using the `Field` component. + +### 3. Controls (Interactive Elements) + +| | | | +| --- | --- | --- | +| `ButtonImg` | [src/components/Controls/Buttons/ButtonImg.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Buttons/ButtonImg.js) | Icon buttons with tooltips | +| `ContainerHelper` | [src/components/Controls/ContainerHelper.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/ContainerHelper.js) | Wrapper for collapsible sections | + +### 4. Fields (Form Inputs) + +The Field system maps data types to UI controls. + +- **Input**: Handles text, number, and password types with reveal toggles [src/components/Controls/Fields/Input.js#44-206](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L44-L206) +- **Boolean**: Renders as a `form-switch` toggle [src/components/Controls/Fields/Boolean.js#38-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Boolean.js#L38-L100) +- **Select**: Dropdown menus with dependency-aware options [src/components/Controls/Fields/Select.js#52-122](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Select.js#L52-L122) +- **ItemsList**: Complex list editor for macros and panels [src/components/Controls/Fields/ItemsList.js#49-188](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js#L49-L188) +- **Slider**: Combines a range input with a numeric text field [src/components/Controls/Fields/Slider.js#37-123](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Slider.js#L37-L123) + +**Sources**: [src/components/Controls/Fields/Input.js#44-206](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L44-L206)[src/components/Controls/Fields/Boolean.js#38-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Boolean.js#L38-L100)[src/components/Controls/Fields/Select.js#52-122](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Select.js#L52-L122)[src/components/Controls/Fields/ItemsList.js#49-188](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js#L49-L188)[src/components/Controls/Fields/Slider.js#37-123](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Slider.js#L37-L123) + +--- + +## Component Patterns + +### Dependency-Based Visibility + +Visibility is managed via `checkDependencies()`, which evaluates rules against `interfaceSettings` and `connectionSettings`[src/components/Helpers/components.js#149-167](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js#L149-L167) + +[Flowchart Diagram] + +Components use `generateDependIds()` to create a list of IDs to watch for updates [src/components/Helpers/components.js#91-107](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js#L91-L107) + +**Sources**: [src/components/Helpers/components.js#91-167](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js#L91-L167)[src/components/Controls/Fields/Input.js#155-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L155-L165) + +### Validation Pattern + +The `InterfaceTab` uses `generateValidationGlobal()` to validate fields like shortkeys (checking for duplicates) and numeric ranges [src/tabs/interface/index.js#45-229](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L45-L229) + +--- + +## Styling System + +The UI uses SCSS modules and the Spectre.css framework. Key styles are defined in `_control.scss`[src/style/components/_control.scss#1-356](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L1-L356) + +| | | | +| --- | --- | --- | +| `.emergency-btn` | High-visibility stop button | [src/style/components/_control.scss#68-82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L68-L82) | +| `.terminal` | Scrollable command output | [src/style/components/_control.scss#206-233](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L206-L233) | +| `.field-group` | Grouped field labels | [src/style/components/_control.scss#162-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L162-L165) | +| `.itemEditor` | Layout for list item editing | [src/style/components/_control.scss#84-91](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L84-L91) | + +**Sources**: [src/style/components/_control.scss#1-356](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L1-L356) + +--- + +# 5.1-Panel-System + +# Panel System +Relevant source files + +- [src/areas/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js) +- [src/components/ExtraContent/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js) +- [src/components/Panels/Files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js) +- [src/components/Panels/Jog.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js) +- [src/components/Panels/JogCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js) +- [src/components/Panels/JogPlotter.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js) +- [src/components/Panels/Notifications.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js) +- [src/components/Panels/OverridesCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js) +- [src/pages/dashboard/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js) + +## Purpose and Scope + +The Panel System is the modular UI organization architecture that structures the ESP3D-WEBUI interface into independently controllable, collapsible sections. This document explains how panels are defined, configured, ordered, and managed throughout the application lifecycle. The system allows for target-specific UI adaptation, where different machine types (3D Printers, CNC, Sandtables) display different sets of controls based on firmware capabilities. + +--- + +## Panel Architecture Overview + +The panel system provides a flexible container-based UI where each functional area (files, terminal, jog controls, etc.) is encapsulated as an independently controllable panel. Panels are primarily rendered within the `MainContainer` and managed via the `UiContext`. + +### Panel Hierarchy in Component Tree + +[Flowchart Diagram] + +**Sources:**[src/areas/index.js#49-73](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L49-L73)[src/pages/dashboard/index.js#113-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L113-L121) + +--- + +## Panel Types and Components + +### Core Panel Categories + +The UI dynamically loads panels based on the `uisettings` and the machine target. Common panels include: + +| | | | +| --- | --- | --- | +| `StatusPanel` | `statusPanel` | Real-time machine status monitoring. | +| `JogPanel` | `jogPanel` | Manual axis movement (variants for [CNC](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/CNC)[Plotter](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/Plotter) and [3D Printer](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/3D Printer)). | +| `FilesPanel` | `filesPanel` | File system abstraction for SD, Flash, and TFT storage. | +| `NotificationsPanel` | `notificationsPanel` | Historical log of system messages and errors. | +| `OverridesPanel` | `OverridesPanel` | CNC-specific feed and spindle overrides. | +| `ExtraContent` | `extra_content_ID` | Iframe extensions, camera streams, or custom HTML. | + +### Component Implementation Pattern + +Standard panels utilize `ContainerHelper` for layout consistency and `FullScreenButton`/`CloseButton` for window management. + +``` +const NotificationsPanel = () => { + const id = "notificationsPanel"; + // ... + return ( +
+ + +
+ {/* Content */} +
+
+ ); +} +``` + +**Sources:**[src/components/Panels/Notifications.js#38-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js#L38-L50)[src/components/Panels/Notifications.js#110-129](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js#L110-L129)[src/components/Panels/Files.js#57-71](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L57-L71) + +--- + +## Panel Visibility and State Management + +### Visibility Logic + +Panel visibility is determined by boolean flags in the interface settings (e.g., `showfilespanel`). The `Dashboard` component filters the `panels` list from `useUiContext()` to decide what to render. + +[Flowchart Diagram] + +### Dependency Resolution + +Panels often depend on other settings. For example, the `OverridesPanel` only renders if `showoverridespanel` is true. + +``` +const OverridesControls = () => { + const { overrides } = useTargetContext() + if (!useUiContextFn.getValue("showoverridespanel")) return null + // ... +} +``` + +**Sources:**[src/components/Panels/OverridesCNC.js#34-36](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js#L34-L36)[src/pages/dashboard/index.js#113-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L113-L121) + +--- + +## Panel Ordering System + +### Fixed vs. Dynamic Layout + +The system supports two ordering modes controlled by the `fixedpanels` setting: + +1. **Dynamic**: Panels appear in the order defined by the target's default list. +2. **Fixed**: Panels follow the user-defined order stored in `panelsorder`. + +The `Dashboard` component tracks this via `uisettings.getValue("fixedpanels")`. When enabled, users can reorder panels, and the new sequence is persisted to the device's `preferences.json`. + +**Sources:**[src/pages/dashboard/index.js#118-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L118-L121)[src/targets/index.js#26](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/index.js#L26-L26) (defaultPanelsList) + +--- + +## Extra Content and Extensions + +The `ExtraContent` system allows for dynamic UI injection. These items are not hardcoded but defined in settings. + +### ExtraContent Architecture + +[Flowchart Diagram] + +### Key Functions + +- `updateContentPosition()`: Calculates the bounding rectangle of the target container to position the absolute-layered extra content (like iframes or video). +- `handleRefresh()`: Triggers a reload of the content via the `eventBus`. +- `dispatchToExtensions()`: Facilitates communication between the WebUI and iframe-based extensions. + +**Sources:**[src/components/ExtraContent/index.js#36-59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L36-L59)[src/components/ExtraContent/index.js#116-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/ExtraContent/index.js#L116-L121)[src/areas/index.js#84-120](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/areas/index.js#L84-L120) + +--- + +## Interaction and Control Flow + +Panels interact with the machine firmware through the `useHttpFn` and `useTargetContext` hooks. + +### Command Execution Flow (Files Example) + +1. User clicks "Play" on a file in `FilesPanel`. +2. `FilesPanel` calls `files.command(currentFS, "play", file)`. +3. The command is sent via `createNewRequest` to `espHttpURL("command", { cmd: ... })`. +4. Success/Failure is reported via `toasts.addToast`. + +``` +const sendURLCmd = (cmd) => { + createNewRequest( + espHttpURL(cmd.url, cmd.args), + { method: "GET" }, + { + onSuccess: (result) => { /* Refresh list */ }, + onFail: (error) => { toasts.addToast({ content: error, type: "error" }) } + } + ) +} +``` + +**Sources:**[src/components/Panels/Files.js#115-136](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L115-L136)[src/components/Panels/Jog.js#85-97](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js#L85-L97) + +--- + +## Keyboard Shortcuts Integration + +The Panel System integrates with a global keyboard listener managed in the `Dashboard`. + +- **Key Mapping**: Keys are mapped to panel buttons via `keymap` and `macros` preferences. +- **Bail Condition**: Shortcuts are disabled if the user is focused on an `INPUT` element to prevent accidental machine movement while typing G-code. +- **Auto-repeat**: Supports continuous movement for jogging if `enableautorepeat` is set. + +**Sources:**[src/pages/dashboard/index.js#43-52](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L43-L52)[src/pages/dashboard/index.js#91-110](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/pages/dashboard/index.js#L91-L110) + +--- + +# 5.2-Status-and-Monitoring-Panels + +# Status and Monitoring Panels +Relevant source files + +- [src/components/Panels/Charts.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Charts.js) +- [src/components/Panels/Extruders.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Extruders.js) +- [src/components/Panels/Status.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js) +- [src/components/Panels/Temperatures.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js) +- [src/targets/Printer3D/Marlin-embedded/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/TargetContext.js) +- [src/targets/Printer3D/Marlin/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js) +- [src/targets/Printer3D/Marlin/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js) +- [src/targets/Printer3D/Repetier/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Repetier/TargetContext.js) +- [src/targets/Printer3D/Smoothieware/TargetContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Smoothieware/TargetContext.js) + +## Purpose and Scope + +This page documents the **status and monitoring panels** in ESP3D-WEBUI, which provide real-time visibility into printer and machine operations. These panels display print progress, temperatures, positions, and machine state by consuming data from the firmware through the `TargetContext` system. + +The primary monitoring panels are: + +- **StatusPanel**: Real-time print job progress, filename, and machine state controls. [src/components/Panels/Status.js#168-378](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L168-L378) +- **TemperaturesPanel**: Current and target temperatures for extruders, beds, chambers, and other sensors. [src/components/Panels/Temperatures.js#106-259](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L106-L259) +- **ChartsPanel**: Historical temperature and sensor data visualized via the Smoothie charting library. [src/components/Panels/Charts.js#55-296](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Charts.js#L55-L296) + +--- + +## Monitoring Panel Architecture + +Monitoring panels consume real-time data from `TargetContext`, respond to user preferences from `SettingsContext`, and display firmware-specific information parsed by the filter system. + +### Data Flow Diagram + +This diagram bridges the gap between the firmware's raw output and the UI components. + +[Flowchart Diagram] + +**Sources**: [src/components/Panels/Status.js#23-27](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L23-L27)[src/targets/Printer3D/Marlin/TargetContext.js#172-230](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L172-L230)[src/targets/Printer3D/Marlin/filters.js#26-180](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L26-L180) + +--- + +## StatusPanel Component + +The `StatusPanel` tracks active print jobs. It differentiates between files printed from the firmware's local storage (SD/TFT) and files streamed from the WebUI via the ESP701 protocol. [src/components/Panels/Status.js#72-166](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L72-L166) + +### Status Data Structures + +The panel consumes two distinct status objects from `TargetContext`: + +| | | | +| --- | --- | --- | +| `status` | `printState` (status, printing, progress), `filename`, `printTime`, `printLeftTime` | Firmware reports (e.g., M27) [src/targets/Printer3D/Marlin/TargetContext.js#80-84](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L80-L84) | +| `streamStatus` | `status` (processing/pause), `name`, `progress`, `printTime`, `printLeftTime` | ESP701 WebUI Stream [src/targets/Printer3D/Marlin/TargetContext.js#77](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L77-L77) | + +### Control Buttons and Device Logic + +The panel renders a `deviceList` that maps physical storage to UI controls. [src/components/Panels/Status.js#175-300](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L175-L300) + +- **SD Card**: Uses `sdpausecmd`, `sdresumecmd`, `sdstopcmd`. [src/components/Panels/Status.js#184-192](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L184-L192) +- **TFT SD/USB**: Uses `tftsd*` and `tftusb*` command variants. [src/components/Panels/Status.js#220-250](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L220-L250) + +**Sources**: [src/components/Panels/Status.js#72-166](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L72-L166)[src/targets/Printer3D/Marlin/TargetContext.js#187-215](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L187-L215) + +--- + +## TemperaturesPanel Component + +The `TemperaturesPanel` provides a unified interface for monitoring and controlling all heating elements. [src/components/Panels/Temperatures.js#106-146](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L106-L146) + +### Heater Control Logic + +The panel uses `target_temperatures` to track user input locally before sending commands. [src/components/Panels/Temperatures.js#42-46](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L42-L46) + +- **Validation**: Inputs are validated against `extrudermax`, `bedmax`, or `chambermax` settings. [src/components/Panels/Temperatures.js#172-202](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L172-L202) +- **Command Generation**: Commands are generated using the `heaterCommand` helper, which replaces placeholders (`#` for index, `$` for value). [src/components/Panels/Temperatures.js#84-96](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L84-L96) + +### Temperature Tool Mapping + +Data is categorized by tool prefix: + +- `T`: Extruders [src/components/Panels/Temperatures.js#43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L43-L43) +- `B`: Heated Bed [src/components/Panels/Temperatures.js#44](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L44-L44) +- `C`: Chamber [src/components/Panels/Temperatures.js#45](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L45-L45) +- `R`: Redundant sensors [src/components/Panels/Temperatures.js#99](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L99-L99) +- `M`: Motherboard [src/components/Panels/Temperatures.js#99](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L99-L99) + +**Sources**: [src/components/Panels/Temperatures.js#42-104](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L42-L104)[src/components/Panels/Temperatures.js#148-163](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Temperatures.js#L148-L163) + +--- + +## ChartsPanel Component + +The `ChartsPanel` uses the `SmoothieChart` library to provide real-time graphical monitoring of temperatures and sensors. [src/components/Panels/Charts.js#235-260](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Charts.js#L235-L260) + +### Chart Organization + +Data is distributed across three distinct chart instances to maintain readability: [src/components/Panels/Charts.js#55-97](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Charts.js#L55-L97) + +1. **Chart 0**: Extruders (`T`) and Redundant sensors (`R`). +2. **Chart 1**: Bed (`B`), Chamber (`C`), Probe (`P`), and Motherboard (`M`). +3. **Chart 2**: Custom Sensors (`S`). + +### Data Buffering + +`TargetContext` maintains a `temperaturesList` and `sensorDataList` with a maximum size of `MAX_TEMPERATURES_LIST_SIZE` (400 entries). [src/targets/Printer3D/Marlin/TargetContext.js#78-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L78-L121) + +- **add2TemperaturesList**: Appends new data and shifts the array if it exceeds the limit. [src/targets/Printer3D/Marlin/TargetContext.js#114-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L114-L121) + +**Sources**: [src/components/Panels/Charts.js#55-136](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Charts.js#L55-L136)[src/targets/Printer3D/Marlin/TargetContext.js#108-121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L108-L121) + +--- + +## Implementation Details: Marlin Filter System + +The monitoring panels rely on the `filters.js` file in each target directory to parse raw firmware strings. + +### Code Entity Association + +This diagram maps firmware strings to the internal functions that update the UI state. + +[Flowchart Diagram] + +### Regex Implementation Examples + +- **Temperatures**: Matches Marlin format `T:.*\s@:[0-9]*`. [src/targets/Printer3D/Marlin/filters.js#44-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L44-L47) +- **Positions**: Matches coordinate strings `X:\s*[+,-]?[0-9]*\.?[0-9]+?\s*Y:...`. [src/targets/Printer3D/Marlin/filters.js#86-90](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L86-L90) +- **Print Progress**: Parses SD byte counts `SD\sprinting\sbyte\s([0-9]*)\/([0-9]*)`. [src/targets/Printer3D/Marlin/filters.js#109](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L109-L109) + +**Sources**: [src/targets/Printer3D/Marlin/filters.js#44-117](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/filters.js#L44-L117)[src/targets/Printer3D/Marlin/TargetContext.js#177-210](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L177-L210) + +--- + +## Time Estimation Logic + +The `TargetContext` includes an `estimatedTime` function used by the `StatusPanel` to calculate the "Time Left" display. [src/targets/Printer3D/Marlin/TargetContext.js#142-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L142-L156) + +``` +const estimatedTime = (progress, time) => { + // 1. Convert elapsed time object to total seconds + const total = (time.day * 86400) + (time.hour * 3600) + (time.min * 60) + time.sec; + // 2. Extrapolate total time based on progress percentage + const totalSecondsLeft = (total * (100 - progress)) / progress; + // 3. Return formatted time object + return { day, hour, min, sec }; +} +``` + +**Sources**: [src/targets/Printer3D/Marlin/TargetContext.js#142-156](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/TargetContext.js#L142-L156)[src/components/Panels/Status.js#29-65](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Status.js#L29-L65) + +--- + +# 5.3-Control-Panels + +# Control Panels +Relevant source files + +- [src/components/Controls/Fields/Input.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js) +- [src/components/Helpers/components.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js) +- [src/components/Helpers/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/index.js) +- [src/components/Panels/Files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js) +- [src/components/Panels/Jog.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js) +- [src/components/Panels/JogCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js) +- [src/components/Panels/JogPlotter.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js) +- [src/components/Panels/LaserCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js) +- [src/components/Panels/Notifications.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js) +- [src/components/Panels/OverridesCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js) +- [src/components/Panels/ProbeCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js) +- [src/components/Panels/SpindleCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js) +- [src/style/components/_control.scss](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss) +- [src/tabs/interface/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js) + +## Purpose and Scope + +This document describes the **Control Panels** subsystem in ESP3D-WEBUI. Control Panels are interactive UI components that allow users to directly control machine hardware functions such as jogging axes, operating spindles, lasers, probes, and extruders. This page covers: + +- The architecture and structure of control panels. +- The mapping between UI controls and firmware commands. +- The implementation of specific panels: `JogPanel`, `SpindlePanel`, `LaserPanel`, and `ProbePanel`. +- The data flow between user inputs, validation logic, and HTTP command dispatch. + +--- + +## Overview of Control Panels + +Control Panels are specialized UI panels that provide direct, real-time control over machine hardware. They are primarily located in `src/components/Panels/`. + +**Diagram: Control Panel Types and Code Entities** + +[Flowchart Diagram] + +Sources: [src/components/Panels/JogCNC.js#28-35](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js#L28-L35)[src/components/Panels/SpindleCNC.js#28-31](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L28-L31)[src/components/Panels/LaserCNC.js#24-27](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js#L24-L27)[src/components/Panels/ProbeCNC.js#28-31](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L28-L31) + +--- + +## Control Panel Architecture + +Control panels follow a consistent pattern for handling user interaction and machine feedback: + +1. **State Management**: Panels use `useTargetContext` to access machine positions, states (Idle, Run, Hold), and pins [src/components/Panels/JogCNC.js#118-119](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js#L118-L119) +2. **Input Validation**: Local state or refs (e.g., `spindleSpeedValue`) store user inputs. Validation is often handled via the `Field` component or local `hasError` functions [src/components/Panels/ProbeCNC.js#109-111](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L109-L111) +3. **Command Dispatch**: Commands are sent via `createNewRequest` using the `espHttpURL("command", {cmd: ...})` helper [src/components/Panels/SpindleCNC.js#110-114](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L110-L114) +4. **Variable Substitution**: Commands often contain placeholders (e.g., `M3 S#`). These are processed by `replaceVariables` using `variablesList.commands` before being sent [src/components/Panels/LaserCNC.js#106-113](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js#L106-L113) + +### Common UI Components + +- **`ButtonImg`**: Used for icon-based controls like directional arrows [src/components/Controls/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/index.js) +- **`Field`**: Wraps inputs (Number, Slider, Select) with labels and tooltips [src/components/Controls/Fields/Input.js#83-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L83-L101) +- **`PositionsControls`**: A sub-component used across jog panels to display real-time coordinates (MPos/WPos) without re-rendering the entire panel [src/components/Panels/JogCNC.js#50-112](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js#L50-L112) + +--- + +## Jog Panels + +The Jog system is split into multiple implementations based on machine type: + +- **`JogCNC.js`**: Supports standard CNC axes (X, Y, Z) and extended axes (A, B, C, U, V, W) [src/components/Panels/JogCNC.js#41-43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js#L41-L43) +- **`JogPlotter.js`**: Tailored for sand tables and plotters, including Pen Up/Down controls [src/components/Panels/JogPlotter.js#81-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js#L81-L100) +- **`Jog.js`**: Standard 3D printer jogging [src/components/Panels/Jog.js#69](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js#L69-L69) + +### Jog Logic Flow + +When a user clicks a jog button: + +1. The `clickBtn` or `sendJogCommand` function is triggered [src/components/Panels/Jog.js#122](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js#L122-L122) +2. Distance and Feedrate are retrieved from UI state (`jogDistance`, `currentFeedRate`) [src/components/Panels/Jog.js#126-129](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js#L126-L129) +3. A G-code string is constructed (e.g., `G91\nG1 X10 F3000\nG90`) and dispatched [src/components/Panels/Jog.js#130-135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js#L130-L135) + +--- + +## Spindle and Laser Panels (CNC) + +These panels manage secondary machine heads. + +### Spindle Panel (`SpindleCNC.js`) + +Controls rotation and cooling. + +- **Commands**: `M3` (CW), `M4` (CCW), `M5` (Stop), `M7`/`M8` (Coolant) [src/components/Panels/SpindleCNC.js#121-179](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L121-L179) +- **Dynamic Updates**: Uses `eventsList.on("reset", ...)` to handle firmware resets [src/components/Panels/SpindleCNC.js#53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L53-L53) +- **State Display**: Shows current `spindle_speed`, `feed_rate`, and `spindle_mode`[src/components/Panels/SpindleCNC.js#55-64](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js#L55-L64) + +### Laser Panel (`LaserCNC.js`) + +Controls laser power and testing. + +- **Test Fire**: Allows firing the laser for a specific duration (`lasertestduration`) at a set power percentage (`laserPercentage`) [src/components/Panels/LaserCNC.js#88-92](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js#L88-L92) +- **Power Scaling**: Calculates actual PWM values by multiplying `laserMaxPower` by `laserPercentage`[src/components/Panels/LaserCNC.js#192-196](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js#L192-L196) + +--- + +## Probe Panel (`ProbeCNC.js`) + +The Probe Panel facilitates tool length offsets and work surface detection. + +- **Axis Selection**: Users can select which axis to probe (X, Y, Z, A, B, C) based on visibility settings [src/components/Panels/ProbeCNC.js#140-185](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L140-L185) +- **Pin Monitoring**: Displays the real-time state of the Probe pin (`P`) [src/components/Panels/ProbeCNC.js#60-78](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L60-L78) +- **G-Code Types**: Supports multiple probing commands like `G38.2` (Probe toward workpiece, stop on contact) [src/components/Panels/ProbeCNC.js#102-104](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L102-L104) + +**Diagram: Probing Data Flow** + +[Flowchart Diagram] + +Sources: [src/components/Panels/ProbeCNC.js#113-130](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L113-L130)[src/components/Panels/ProbeCNC.js#55-59](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L55-L59)[src/components/Helpers/strings.js#39](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/strings.js#L39-L39) + +--- + +## UI Styling and Components + +The visual representation of these panels relies on the `_control.scss` stylesheet and specialized field components. + +### CSS Patterns + +- **Layout**: `.buttons-bar` and `.image-button-bar` use flexbox for aligning control buttons [src/style/components/_control.scss#1-7](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L1-L7) +- **Special Buttons**: `.emergency-btn` provides high-visibility red styling for stop commands [src/style/components/_control.scss#68-82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L68-L82) +- **Input Groups**: `.field-group` and `.field-group-content` manage the spacing of labels and inputs [src/style/components/_control.scss#162-199](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss#L162-L199) + +### Input Component (`Input.js`) + +The `Input` component is the workhorse for control panels. It handles: + +- **Dependency Tracking**: Automatically hides/shows inputs based on other settings using `checkDependencies`[src/components/Controls/Fields/Input.js#156-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L156-L165) +- **Type Handling**: Supports `text`, `number`, `password` (with reveal toggle), and `slider`[src/components/Controls/Fields/Input.js#190-206](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L190-L206) +- **Shortkeys**: Allows capturing key combinations for jog movements [src/components/Controls/Fields/Input.js#112-135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L112-L135) + +Sources: [src/components/Controls/Fields/Input.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js)[src/style/components/_control.scss](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss)[src/components/Helpers/components.js#149-167](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js#L149-L167) + +--- + +## Key Points for Developers + +1. **Haptic Feedback**: Most button interactions trigger `useUiContextFn.haptic()` for touch device support [src/components/Controls/Fields/Input.js#47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L47-L47) +2. **Context Dependencies**: Panels must be wrapped in `TargetContextProvider` to receive the real-time data needed for `PositionsControls`[src/targets/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/index.js) +3. **Command Echoing**: When sending commands, an `echo` parameter is often passed to `createNewRequest` so the Terminal panel can display the sent command [src/components/Panels/JogPlotter.js#121](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js#L121-L121) +4. **Conditional Visibility**: Panels use `checkDependencies` to ensure controls for hardware not present (e.g., a 4th axis `A`) are hidden [src/components/Panels/ProbeCNC.js#182-185](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L182-L185) + +Sources: [src/components/Panels/JogPlotter.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js)[src/components/Panels/SpindleCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js)[src/components/Helpers/components.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js) + +--- + +# 5.4-File-Manager-Panel + +# File Manager Panel +Relevant source files + +- [src/components/Helpers/http.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js) +- [src/components/Panels/Files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js) +- [src/components/Panels/Jog.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Jog.js) +- [src/components/Panels/JogCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogCNC.js) +- [src/components/Panels/JogPlotter.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/JogPlotter.js) +- [src/components/Panels/Notifications.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Notifications.js) +- [src/components/Panels/OverridesCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/OverridesCNC.js) +- [src/tabs/interface/importHelper.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/importHelper.js) +- [src/targets/CNC/GRBL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/index.js) +- [src/targets/CNC/grblHAL/DIRECTSD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js) +- [src/targets/CNC/grblHAL/FLASH-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js) +- [src/targets/CNC/grblHAL/files.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js) +- [src/targets/CNC/grblHAL/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/index.js) +- [src/targets/CNC/grblHAL/realCommandsTable.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/realCommandsTable.js) +- [src/targets/CNC/grblHAL/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/translations/en.json) +- [src/targets/CNC/translations/en.json](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/translations/en.json) +- [src/targets/Printer3D/Marlin-embedded/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/SD-source.js) +- [src/targets/Printer3D/Marlin/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js) +- [src/targets/Printer3D/Marlin/SDEXT-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SDEXT-source.js) + +## Purpose and Scope + +The File Manager Panel (`FilesPanel`) provides a unified interface for browsing, uploading, downloading, and managing files across multiple storage backends. These backends include internal flash memory (FLASH), SD cards accessed via serial protocol (SD, SDEXT), SD cards accessed via HTTP (DIRECTSD), and TFT display storage (TFTSD, TFTUSB). + +This document focuses on the **FilesPanel** component implementation and the **file system abstraction layer** it integrates with, explaining how file operations are abstracted, routed to appropriate storage backends, and executed. + +For information about the panel system architecture and visibility management, see [Panel System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/5.1?branch=%223.0%22). For details on the HTTP communication layer, see [Client-Server Communication](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/2.2?branch=%223.0%22). + +--- + +## FilesPanel Component Overview + +The `FilesPanel` component is a functional Preact component that manages the state of the file browser, including the current path, file list cache, and loading status. It adapts its interface based on the supported file systems of the active target. + +**Key Features:** + +- **Filesystem Selector**: Populated by `files.supported` after checking dependencies like `flashfs` or `directsd`[src/targets/CNC/grblHAL/files.js#26-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L26-L47) +- **State Management**: Tracks `filePath`, `fileSystem`, and `filesList` using Preact hooks [src/components/Panels/Files.js#72-76](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L72-L76) +- **Cache System**: Uses `filesListCache` to store directory contents, minimizing redundant network requests [src/components/Panels/Files.js#50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L50-L50) +- **Context Integration**: Consumes `useUiContext` for modals/toasts and `useTargetContextFn` for data processing [src/components/Panels/Files.js#78-79](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L78-L79) + +**Sources:**[src/components/Panels/Files.js#57-84](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L57-L84)[src/targets/CNC/grblHAL/files.js#26-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L26-L47) + +--- + +## Architecture Overview + +The File Manager Panel operates through a three-tier architecture: + +1. **UI Layer**: The `FilesPanel` component handles user interactions and displays file listings. +2. **Abstraction Layer**: The target-specific `files` object provides `capability()` and `command()` functions. +3. **Backend Layer**: Storage backend implementations (e.g., `FLASH-source.js`, `SD-source.js`) handle protocol-specific operations. + +**FilesPanel Integration Architecture** + +[Flowchart Diagram] + +**Sources:**[src/components/Panels/Files.js#115-136](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L115-L136)[src/targets/CNC/grblHAL/files.js#49-74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L49-L74)[src/targets/CNC/grblHAL/FLASH-source.js#53-60](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L53-L60)[src/targets/Printer3D/Marlin/SD-source.js#84-89](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L84-L89) + +--- + +## File System Abstraction Layer + +### The `files` Object + +Each target (e.g., `grblHAL`, `Marlin`) exports a `files` object. This object is the primary interface for the `FilesPanel`. + +| | | | +| --- | --- | --- | +| `supported` | Array of available filesystems | Filters based on `depend()` functions [src/targets/CNC/grblHAL/files.js#26-47](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L26-L47) | +| `capability()` | Checks feature support | Proxies to backend `capabilities` object [src/targets/CNC/grblHAL/files.js#59-66](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L59-L66) | +| `command()` | Generates action objects | Returns `{ type, url, cmd, args }`[src/targets/CNC/grblHAL/files.js#68-74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L68-L74) | + +**Sources:**[src/targets/CNC/grblHAL/files.js#77-82](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L77-L82)[src/targets/Printer3D/Marlin/files.js#123-127](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/files.js#L123-L127) + +### The `capability()` Function + +The `FilesPanel` calls `capability()` to determine which UI elements to display (e.g., Upload button, New Folder button). + +**Panel Logic Example:** +The panel checks if the current filesystem supports `IsFlatFS` to decide whether to render hierarchical navigation or a simple list [src/components/Panels/Files.js#156-167](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L156-L167) + +**Backend Implementation (grblHAL FLASH):** + +``` +const capabilities = { + Upload: () => true, + Download: () => true, + DeleteFile: () => true, + CreateDir: () => true, + IsFlatFS: () => false +} +``` + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#24-51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L24-L51)[src/targets/CNC/grblHAL/files.js#59-66](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L59-L66) + +### The `command()` Function + +The `command()` function generates execution instructions. The `FilesPanel` processes the returned object based on its `type`. + +**Execution Flow in FilesPanel:** + +1. **type: "url"**: Calls `sendURLCmd(cmd)` which uses `createNewRequest` to perform an HTTP fetch [src/components/Panels/Files.js#115-136](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L115-L136) +2. **type: "cmd"**: Calls `sendSerialCmd(command)` which sends G-code/System commands to the firmware [src/components/Panels/Files.js#94-113](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L94-L113) + +**Sources:**[src/components/Panels/Files.js#94-136](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L94-L136)[src/targets/CNC/grblHAL/files.js#68-74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L68-L74) + +--- + +## Data Flow: Listing Files + +The following diagram traces the data flow from a user clicking "Refresh" to the UI updating with new file entries. + +```mermaid +sequenceDiagram + participant UI as "FilesPanel.js" + participant API as "files.js" + participant BE as "DIRECTSD-source.js" + participant Srv as "ESP32 Backend" + UI->>API: command(fs | "list" | path) + API->>BE: commands.list(path) + BE-->>UI: { type: "url", url: "sdfiles", args: {action: "list"} } + UI->>Srv: GET /sdfiles?path=/&action=list + Srv-->>UI: JSON String (FileList) + UI->>API: command(fs | "formatResult" | response) + API->>BE: commands.formatResult(response) + BE->>BE: JSON.parse() + BE->>BE: sortedFilesList() if enabled + BE-->>UI: { files: [...], status: "ok" } + UI->>UI: setFilesList(data) +``` + +**Sources:**[src/components/Panels/Files.js#115-136](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Files.js#L115-L136)[src/targets/CNC/grblHAL/DIRECTSD-source.js#54-76](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L54-L76)[src/targets/Printer3D/Marlin/SD-source.js#114-122](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L114-L122) + +--- + +## Storage Backend Comparison + +### FLASH (Internal) + +- **Protocol**: HTTP [src/targets/CNC/grblHAL/FLASH-source.js#57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L57-L57) +- **Capabilities**: Full support for directories, multiple uploads, and downloads [src/targets/CNC/grblHAL/FLASH-source.js#24-51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L24-L51) +- **Pathing**: Uses `HostUploadPath` setting to prefix paths [src/targets/CNC/grblHAL/FLASH-source.js#63](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L63-L63) + +### SD / SDEXT (Serial) + +- **Protocol**: Serial (G-code) [src/targets/Printer3D/Marlin/SD-source.js#87](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L87-L87) +- **Capabilities**: Usually flat filesystem; upload/delete depends on `SerialProtocol` (e.g., "MKS" support) [src/targets/Printer3D/Marlin/SD-source.js#61-75](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L61-L75) +- **Parsing**: Requires `formatFileSerialLine` to parse raw serial strings like `Begin file list...End file list`[src/targets/Printer3D/Marlin/SD-source.js#31-53](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L31-L53) + +### DIRECTSD (HTTP-to-SD) + +- **Protocol**: HTTP [src/targets/CNC/grblHAL/DIRECTSD-source.js#58](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L58-L58) +- **Capabilities**: Supports hierarchical directories and native downloads [src/targets/CNC/grblHAL/DIRECTSD-source.js#30-51](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L30-L51) +- **Integration**: Specific to targets like grblHAL or Marlin with specific SD connection modes [src/targets/CNC/grblHAL/files.js#38-46](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/files.js#L38-L46) + +--- + +## Response Processing and Parsing + +For serial backends, the system must detect the start and end of a file list in the stream. This is defined in `responseSteps`. + +**Example: Marlin SD Response Detection** + +``` +const responseSteps = { + list: { + start: (data) => data.startsWith("Begin file list"), + end: (data) => data.startsWith("End file list"), + error: (data) => data.indexOf("error") != -1 || data.indexOf("No SD card") != -1 + } +} +``` + +The `FilesPanel` uses these via the `processor` to "catch" the serial response and aggregate it into a content array before calling `formatResult`[src/targets/Printer3D/Marlin/SD-source.js#155-170](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L155-L170) + +**Sources:**[src/targets/Printer3D/Marlin/SD-source.js#155-176](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js#L155-L176)[src/targets/Printer3D/Marlin/SDEXT-source.js#157-178](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SDEXT-source.js#L157-L178) + +--- + +## Summary Table of File Commands + +| | | | +| --- | --- | --- | +| **List** | `url` | `GET /files?path=/&action=list`[src/targets/CNC/grblHAL/FLASH-source.js#57](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L57-L57) | +| **Upload** | `url` | `POST /files?path=/`[src/targets/CNC/grblHAL/FLASH-source.js#61](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L61-L61) | +| **Delete** | `url` | `GET /files?path=/&action=delete&filename=f.nc`[src/targets/CNC/grblHAL/FLASH-source.js#87](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L87-L87) | +| **Play** | `cmd` | `replace("#", path)` in `playcmd` setting [src/targets/CNC/grblHAL/FLASH-source.js#115](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L115-L115) | +| **Create Dir** | `url` | `GET /files?path=/&action=createdir&filename=new`[src/targets/CNC/grblHAL/FLASH-source.js#92](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L92-L92) | + +**Sources:**[src/targets/CNC/grblHAL/FLASH-source.js#53-129](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/FLASH-source.js#L53-L129)[src/targets/CNC/grblHAL/DIRECTSD-source.js#54-120](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/grblHAL/DIRECTSD-source.js#L54-L120) + +--- + +# 5.5-Settings-Interface + +# Settings Interface +Relevant source files + +- [src/components/Helpers/http.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/http.js) +- [src/components/Panels/ProbeCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js) +- [src/hooks/useSettings.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js) +- [src/tabs/interface/importHelper.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/importHelper.js) +- [src/tabs/interface/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js) +- [src/targets/Printer3D/Marlin-embedded/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin-embedded/SD-source.js) +- [src/targets/Printer3D/Marlin/SD-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SD-source.js) +- [src/targets/Printer3D/Marlin/SDEXT-source.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/Printer3D/Marlin/SDEXT-source.js) + +The Settings Interface is the UI component that provides users with a comprehensive form-based editor for viewing, modifying, validating, and persisting application preferences. It renders all configurable settings organized by category, performs real-time validation, manages dependency-based field visibility, and handles import/export/save operations. + +For information about the underlying preferences data structure and hierarchical inheritance system, see [Preferences System](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/4.2?branch=%223.0%22). For details on individual field component implementations, see [Field Components](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/5.7?branch=%223.0%22). For information about settings validation rules and dependency logic, see [Settings Validation and Dependencies](/org/luc-github/wiki/luc-github/ESP3D-WEBUI/page/7.4?branch=%223.0%22). + +## Component Architecture + +The `InterfaceTab` component serves as the main orchestrator for the settings interface, coordinating between the settings context, field rendering, validation logic, and persistence operations. + +[Flowchart Diagram] + +**Sources:**[src/tabs/interface/index.js#20-102](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L20-L102)[src/tabs/interface/index.js#336-416](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L336-L416) + +## Settings Data Structure + +The settings interface operates on a nested data structure where each setting field contains metadata for rendering, validation, and state tracking. + +[Flowchart Diagram] + +**Field Object Structure:** + +| | | | +| --- | --- | --- | +| `id` | string | Unique identifier for the field | +| `type` | string | Field type: text, number, select, boolean, icon, list, group | +| `label` | string | Translation key for field label | +| `value` | any | Current field value | +| `initial` | any | Original/default value for change detection | +| `hasmodified` | boolean | Whether value differs from initial | +| `haserror` | boolean | Whether validation has failed | +| `depend` | array | Dependency conditions for visibility/validity | +| `min`, `max` | number | Range constraints for numbers/text length | +| `step` | number | Increment step for number inputs | +| `regexpattern` | string | Validation regex for text inputs | +| `options` | array | Available options for select fields | +| `hide` | boolean | Whether to hide the field | +| `shortkey` | boolean | Whether this is a keyboard shortcut field | + +**Sources:**[src/tabs/interface/index.js#45-299](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L45-L299)[src/tabs/interface/importHelper.js#30-167](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/importHelper.js#L30-L167) + +## Validation System + +The validation system provides comprehensive real-time validation for all field types via `generateValidationGlobal`. + +[Flowchart Diagram] + +**Validation Rules by Field Type:** + +| | | +| --- | --- | +| `shortkey` | Must not end with "+"; must be unique across jog keymap and macros [src/tabs/interface/index.js#60-102](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L60-L102) | +| `number` | Must satisfy min/max range; handles `minSecondary` for dual-range validation [src/tabs/interface/index.js#166-189](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L166-L189) | +| `text` | Must match `regexpattern` if provided; must satisfy min/max length constraints [src/tabs/interface/index.js#136-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L136-L165) | +| `select` | Selected option must be valid; option dependencies must be satisfied [src/tabs/interface/index.js#191-203](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L191-L203) | +| `list` | Stringified check for `newItem` or `hasmodified` flags; check for `haserror` in nested items [src/tabs/interface/index.js#119-135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L119-L135) | +| `all types` | Step validation using modulo arithmetic with float precision handling [src/tabs/interface/index.js#104-118](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L104-L118) | + +**Sources:**[src/tabs/interface/index.js#45-299](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L45-L299) + +## Dependency System + +The dependency system controls field visibility and validity based on other settings values or connection capabilities using `checkDependencies`. + +[Flowchart Diagram] + +**Sources:**[src/tabs/interface/index.js#40-43](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L40-L43)[src/components/Panels/ProbeCNC.js#148-165](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L148-L165)[src/tabs/interface/importHelper.js#79-128](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/importHelper.js#L79-L128) + +## Action Buttons and Save Workflow + +The interface provides actions for refreshing, importing, exporting, and saving settings. + +### Save Implementation + +The save operation uploads modified settings to the device as a `preferences.json` file. + +1. **File Creation**: [src/tabs/interface/index.js#384-400](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L384-L400) +- Uses `exportPreferences()` with `false` flag to exclude unmodified values. +- Creates a `Blob` and wraps it in a `File` object. +2. **FormData Structure**: + +- `path`: Host upload path. +- `creatPath`: Set to "true". +- `myfiles`: The generated JSON file. +3. **HTTP Request**: [src/tabs/interface/index.js#402-415](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L402-L415) +- Method: POST via `createNewRequest`. +- Reloads the page on success to apply changes. + +### Import/Export + +- **Export**: Generates a JSON blob containing settings, custom content, and extensions [src/tabs/interface/index.js#636-655](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L636-L655) +- **Import**: Uses `FileReader` to read local JSON and `importPreferencesSection` to merge data [src/tabs/interface/index.js#342-380](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L342-L380) + +**Sources:**[src/tabs/interface/index.js#336-416](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/index.js#L336-L416)[src/tabs/interface/exportHelper.js#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/exportHelper.js#L1-L10)[src/tabs/interface/importHelper.js#1-10](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/tabs/interface/importHelper.js#L1-L10) + +## Practical Usage in Panels + +Panels like `ProbePanel` leverage the settings validation logic to ensure machine commands are safe. + +**Field Rendering with Validation:**[src/components/Panels/ProbeCNC.js#583-637](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L583-L637) + +``` + { + if (!update) element.value.current = val + const validationObj = generateValidation(element) + setvalidation(validationObj) + // ... update variablesList if valid + }} + validation={validation} +/> +``` + +**Sources:**[src/components/Panels/ProbeCNC.js#449-638](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/ProbeCNC.js#L449-L638)[src/hooks/useSettings.js#56-90](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/hooks/useSettings.js#L56-L90) + +--- + +# 5.6-Terminal-Panel + +# Terminal Panel +Relevant source files + +- [src/components/Helpers/filters.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/filters.js) +- [src/components/Helpers/storedState.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js) +- [src/components/Modal/logginModal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Modal/logginModal.js) +- [src/components/Panels/Terminal.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js) +- [src/contexts/DatasContext.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js) +- [src/targets/CNC/Controls/QuickStopButton.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js) +- [src/targets/CNC/GRBL/Controls/BackgroundContainer.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/GRBL/Controls/BackgroundContainer.js) + +## Purpose and Scope + +The Terminal Panel provides a direct G-code and command console for interacting with machine firmware. It serves as the primary interface for manual command entry, real-time output monitoring, and debugging. The panel supports features such as command history, auto-scroll management, verbose filtering, and variable replacement. + +This document details the `TerminalPanel` component implementation, the underlying `DatasContext` state management, and the data flow between the UI and the firmware. + +--- + +## Architecture and Data Flow + +The Terminal Panel operates as a consumer of both the `DatasContext` (for message storage) and the `TargetContext` (for command processing). + +### System Component Interaction + +[Flowchart Diagram] + +**Sources:**[src/components/Panels/Terminal.js#42-152](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L42-L152)[src/contexts/DatasContext.js#30-98](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L30-L98)[src/components/Helpers/storedState.js#21-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js#L21-L33) + +--- + +## State Management: DatasContext + +The terminal's state is centralized in the `DatasContext` to ensure persistence across panel re-renders and to allow background data collection. + +### Terminal State Structure + +| | | | | +| --- | --- | --- | --- | +| `input` | `useRef` | [src/contexts/DatasContext.js#41](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L41-L41) | Holds the current unsent input string. | +| `content` | `useState` | [src/contexts/DatasContext.js#36](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L36-L36) | The array of messages currently rendered in the UI. | +| `inputHistory` | `useStoredState` | [src/contexts/DatasContext.js#37](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L37-L37) | Command history persisted in `localStorage`. | +| `isVerbose` | `useRef` | [src/contexts/DatasContext.js#33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L33-L33) | Controls whether all messages or only "quiet" messages are shown. | +| `isAutoScroll` | `useRef` | [src/contexts/DatasContext.js#31](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L31-L31) | Global toggle for automatic scrolling to bottom. | + +### Content Buffering Logic + +The context maintains two internal buffers: `terminalBuffer` (all data) and `terminalBufferQuiet` (filtered data). When `addTerminalContent` is called, it limits the array size based on the scroll state (typically 300-600 lines) using `limitArr` to prevent browser memory exhaustion [src/contexts/DatasContext.js#58-74](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L58-L74) + +**Sources:**[src/contexts/DatasContext.js#43-98](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/contexts/DatasContext.js#L43-L98)[src/components/Helpers/storedState.js#21-33](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/storedState.js#L21-L33) + +--- + +## Component Implementation + +### Command Entry and History + +The `TerminalPanel` implements a standard terminal UX with keyboard navigation for command history. + +- **Keyboard Hooks (`onKeyUp`)**: + +- `Enter` (13): Triggers `onSend`[src/components/Panels/Terminal.js#95-97](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L95-L97) +- `ArrowUp` (38): Navigates to the previous command in `terminal.inputHistory`[src/components/Panels/Terminal.js#98-100](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L98-L100) +- `ArrowDown` (40): Navigates to the next command or clears the input if at the end of history [src/components/Panels/Terminal.js#101-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L101-L103) + +### Command Processing Pipeline + +When a command is sent via `onSend`[src/components/Panels/Terminal.js#108-149](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L108-L149): + +1. **Haptic Feedback**: Triggers a vibration if supported [src/components/Panels/Terminal.js#109](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L109-L109) +2. **Variable Replacement**: The command is passed through `replaceVariables` using the `variablesList.commands` pattern [src/components/Panels/Terminal.js#128](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L128-L128) +3. **Local Echo**: `processData("echo", ...)` is called to immediately display the sent command in the terminal [src/components/Panels/Terminal.js#126-129](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L126-L129) +4. **Network Request**: An HTTP GET request is created via `createNewRequest` to the `/command` endpoint [src/components/Panels/Terminal.js#130-134](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L130-L134) +5. **Response Handling**: On success, the result is passed to `processData("response", result)` for parsing and display [src/components/Panels/Terminal.js#136-138](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L136-L138) + +**Sources:**[src/components/Panels/Terminal.js#71-149](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L71-L149)[src/targets/CNC/Controls/QuickStopButton.js#32-49](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L32-L49) + +--- + +## User Interface Features + +### Terminal Menu + +The panel includes a specialized menu (accessible via the `PanelMenu` component) to control display behavior: + +| | | | +| --- | --- | --- | +| **Verbose Mode** | `S76` | Toggles between full stream and filtered output [src/components/Panels/Terminal.js#184-195](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L184-L195) | +| **Auto-scroll** | `S77` | Toggles automatic scrolling. If paused by user interaction, it can be resumed here [src/components/Panels/Terminal.js#197-207](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L197-L207) | +| **Clear** | `S78` | Calls `terminal.clear()` to empty the display and buffers [src/components/Panels/Terminal.js#215-220](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L215-L220) | + +### Auto-Scroll Behavior + +The component uses a `useRef` for the terminal output container (`terminalOutput`) and a `scrollToBottom` function. + +- **Automatic Trigger**: Whenever `terminal.content` updates, an `useEffect` hook triggers `scrollToBottom`[src/components/Panels/Terminal.js#153-155](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L153-L155) +- **Pause Logic**: Scrolling is suppressed if `terminal.isAutoScrollPaused.current` is true, allowing users to inspect previous logs without the view jumping [src/components/Panels/Terminal.js#63-70](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L63-L70) + +**Sources:**[src/components/Panels/Terminal.js#58-70](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L58-L70)[src/components/Panels/Terminal.js#182-221](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L182-L221) + +--- + +## Technical Details: Variables and Replacement + +The terminal supports dynamic variable replacement before commands are dispatched to the firmware. This is handled by `replaceVariables` [src/components/Helpers/index.js] and informed by `variablesList` from the target configuration. + +[Flowchart Diagram] + +**Sources:**[src/components/Panels/Terminal.js#128-132](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/Terminal.js#L128-L132)[src/targets/CNC/Controls/QuickStopButton.js#35-39](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/targets/CNC/Controls/QuickStopButton.js#L35-L39) + +--- + +# 5.7-Field-Components + +# Field Components +Relevant source files + +- [Memo/preferences.md](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/Memo/preferences.md?plain=1) +- [src/components/Controls/Button.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Button.js) +- [src/components/Controls/FieldGroup.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js) +- [src/components/Controls/Fields/Boolean.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Boolean.js) +- [src/components/Controls/Fields/IconSelect.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/IconSelect.js) +- [src/components/Controls/Fields/Input.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js) +- [src/components/Controls/Fields/ItemsList.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js) +- [src/components/Controls/Fields/Select.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Select.js) +- [src/components/Controls/Fields/Slider.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Slider.js) +- [src/components/Helpers/components.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js) +- [src/components/Helpers/index.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/index.js) +- [src/components/Panels/LaserCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/LaserCNC.js) +- [src/components/Panels/SpindleCNC.js](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Panels/SpindleCNC.js) +- [src/style/components/_control.scss](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/style/components/_control.scss) + +This page documents the reusable field components used throughout the ESP3D-WEBUI for user input and data entry. These components provide standardized input controls with built-in validation, dependency checking, and various specialized input modes. + +## Overview + +The field component system provides a consistent interface for user input across all panels and settings dialogs. The primary components are: + +- **`Input`**: Core text/number input with multiple specialized modes [src/components/Controls/Fields/Input.js#83-360](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L83-L360) +- **`Field`**: Higher-level wrapper that adds labels and validation display [src/components/Controls/Fields/ItemsList.js#30](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js#L30-L30) +- **`Select`**: Dropdown selection component [src/components/Controls/Fields/Select.js#52-123](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Select.js#L52-L123) +- **`Boolean`**: Toggle switch for true/false values [src/components/Controls/Fields/Boolean.js#38-102](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Boolean.js#L38-L102) +- **`FieldGroup`**: Container for grouping related fields with a legend [src/components/Controls/FieldGroup.js#28-54](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js#L28-L54) +- **`ItemsList`**: Complex component for managing lists of editable items (e.g., Macros, Custom Panels) [src/components/Controls/Fields/ItemsList.js#207-336](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js#L207-L336) +- **`IconSelect`**: Modal-based icon picker [src/components/Controls/Fields/IconSelect.js#34-112](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/IconSelect.js#L34-L112) + +All field components integrate with the `SettingsContext` and `UiContext` for state management and support conditional visibility through the dependency system [src/components/Controls/Fields/Input.js#102-106](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L102-L106) + +**Sources:**[src/components/Controls/Fields/Input.js#1-361](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L1-L361)[src/components/Controls/FieldGroup.js#1-56](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/FieldGroup.js#L1-L56)[src/components/Controls/Fields/Boolean.js#1-103](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Boolean.js#L1-L103) + +## Component Architecture + +[Flowchart Diagram] + +**Sources:**[src/components/Controls/Fields/Input.js#83-360](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L83-L360)[src/components/Helpers/components.js#91-167](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Helpers/components.js#L91-L167)[src/components/Controls/Fields/ItemsList.js#49-205](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/ItemsList.js#L49-L205) + +## Core Field Components + +### Input Component + +The `Input` component is the most versatile field, handling standard text, numeric entries, and specialized data capture [src/components/Controls/Fields/Input.js#83-101](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L83-L101) + +| | | | +| --- | --- | --- | +| `type` | string | HTML type (`text`, `password`, `number`, `slider`) [src/components/Controls/Fields/Input.js#190-206](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L190-L206) | +| `extra` | string | Specialized modes: `dropList` (predefined options) or `scan` (WiFi AP list) [src/components/Controls/Fields/Input.js#207-324](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L207-L324) | +| `shortkey` | boolean | Captures key combinations (e.g., "Control+Alt+P") [src/components/Controls/Fields/Input.js#112-135](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L112-L135) | +| `append` | string | Unit or label appended to the input (e.g., "mm", "%") [src/components/Controls/Fields/Input.js#224-231](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L224-L231) | +| `prec` | number | Decimal precision hint shown in a tooltip [src/components/Controls/Fields/Input.js#109-110](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Input.js#L109-L110) | + +### Select Component + +A standard dropdown component that supports conditional visibility for individual options [src/components/Controls/Fields/Select.js#29-50](https://github.com/luc-github/ESP3D-WEBUI/blob/97c01e85/src/components/Controls/Fields/Select.js#L29-L50) + +- **Option Dependencies**: Individual `