Files
alkane-os/third-party/flare-ui/dash-editor/editor/dashboard-doc.js
T
x ad31cfbafa Vendor flare-ui v0.2.9 and prove the schema-driven UI in an image
Spike, not the final UI: it answers whether flare-ui can drive Alkane OS's
on-box pages, and what it costs.

What works:

- schema/alkane-bb.json authors the sidebar as data (3 sections, 14 tabs);
- src/bin/ui-spike.rs renders it through flare_ui::nav + flare_ui::shell, so
  the unified sidebar, ordering and surface filtering come from the schema
  rather than from hand-written HTML;
- the render uses the shared bf- design tokens, the same ones the rest of the
  suite uses.

Size, measured rather than assumed (armv7, release, stripped):

  ui-baseline   323 KiB   (maud + serde_json, no flare-ui)
  ui-spike      771 KiB   (flare-ui + wschema + sha2)
  marginal      448 KiB

Vendoring: third-party/flare-ui is the full v0.2.9 tree pinned in
flare-ui/flare-ui.lock (a partial archive does not compile, since the crate
include_str!s assets from dash-editor/). vendor/ is re-generated as a cargo
directory source with the new registry dependencies (maud, sha2, typenum,
digest, generic-array, block-buffer, crypto-common, cfg-if, etc.) so the build
still works offline. third-party/README.md records how to re-pin.
2026-11-04 14:06:25 -06:00

616 lines
26 KiB
JavaScript

// The dashboard document, with nothing on screen in it.
//
// A version 3 document is a tree of blocks, so almost everything the editor
// does is a walk rather than an array index. This file is that walk, the caps
// the server enforces, and the rules for what a block of each kind carries.
// It touches no element and reads no page: it is loaded before
// dashboard-editor.js and again, later, by the source picker and the list
// view, which need the same tree without a second copy of it.
//
// It is a plain global rather than a module because every other script here is
// one, the page has no build step, and a module would be the only deferred
// script on the page whose load order differs from the rest.
(function () {
"use strict";
// --- the server's numbers ------------------------------------------------
//
// All four are the server's to decide and all four are copied here because
// the canvas has to act on them before a save rather than after.
// `the_editor_repeats_the_servers_constants` pins each line to
// dashboard.rs, so a copy cannot drift the way the version check once did.
// Drawable blocks. Containers are structure rather than content, so tidying
// a layout into rows never costs an operator a block.
var BLOCK_CAP = 32;
// Every node, containers included. The server's other cap, and the one a
// deeply nested document reaches first.
var NODE_CAP = 64;
// How deep groups may nest, counting root children as zero.
var DEPTH_CAP = 3;
// How many blocks one row holds.
var ROW_CAP = 6;
// How many columns and rows one table holds. The panel stops at these
// rather than writing a table the save refuses.
var TABLE_COLUMN_CAP = 8;
var TABLE_ROW_CAP = 32;
// The document version this canvas draws. A document of any other version
// is preserved rather than drawn.
var VERSION = 3;
// Every kind the server knows, in its order. `legacy_grid` is in the list
// because the canvas has to draw one without dumping the document into the
// raw pane; it is deliberately not in the palette, because it is something
// the upgrade produces rather than something anyone inserts.
var KINDS = ["metric", "status", "text", "heading", "separator", "card", "gauge", "chart", "status_grid", "table", "group", "legacy_grid"];
// The kinds that carry a unit. A kind outside this list is left alone: its
// attributes are a newer build's.
var UNIT_KINDS = ["metric", "status", "card", "gauge", "chart"];
// The kinds that carry no value at all. A separator draws a rule, so a
// value on one is a key the server does not know that kind to carry.
var VALUELESS_KINDS = ["separator", "status_grid", "table"];
// The kinds that divide a dashboard rather than sit on it. They span the
// row by default and the live page draws them without the block's label.
var STRUCTURAL_KINDS = ["heading", "separator"];
// What a newly inserted block of each kind says, so an operator sees the
// shape rather than an empty box. A kind absent here starts at "No data".
var DEFAULT_VALUE = {
text: "Add context here.",
heading: "Section",
card: "No data",
gauge: "No data",
chart: "No data"
};
// A gauge is a reading against a range, so a new one has to arrive with a
// range: the server refuses a pair that is not two different numbers, and
// an operator should see a working bar before they have typed anything.
// 0 to 100 reads as a percentage, which is the commonest of these.
var GAUGE_MIN = 0;
var GAUGE_MAX = 100;
// A chart's window, matching dashboard.rs's CHART_HOURS_*. A new chart
// arrives with one because the server requires one, the same way a new
// gauge arrives with a range.
var CHART_HOURS = 6;
// The class suffix each space_before value carries, as dashboard.rs writes
// it. Kept as a map rather than a slice of the name, because the wire values
// and the class names are two vocabularies that happen to line up today.
var SPACE_CLASS = { small: "sm", medium: "md", large: "lg" };
// The frame ranges validate() enforces, which are also the ranges the
// stylesheets have classes for.
var WIDTH_MIN = 1;
var WIDTH_MAX = 12;
var MIN_ROWS_MIN = 1;
var MIN_ROWS_MAX = 8;
// --- the tree ------------------------------------------------------------
function kindOf(block) {
return block && block.body ? block.body.kind : "";
}
/// A group's children, or null for anything that is not a container.
function childrenOf(block) {
return block && block.body && block.body.kind === "group" && Array.isArray(block.body.children)
? block.body.children
: null;
}
/// Every block in document order, with where it sits.
///
/// An entry is `{block, parent, siblings, index, depth}`: the block itself,
/// the container holding it or null at the root, the list it is in, its
/// place in that list, and how deep it sits. Everything the editor does to
/// a block is expressed against one of these rather than against an index
/// into the root list, which is what the grid model could get away with.
function walk(blocks, parent, depth, out) {
(blocks || []).forEach(function (block, index) {
out.push({ block: block, parent: parent, siblings: blocks, index: index, depth: depth });
var kids = childrenOf(block);
if (kids) walk(kids, block, depth + 1, out);
});
return out;
}
/// Every entry of a document, depth first, which is the order it draws in.
function flat(documentValue) {
return walk(documentValue ? documentValue.blocks : [], null, 0, []);
}
function findEntry(documentValue, id) {
return flat(documentValue).find(function (entry) {
return entry.block.id === id;
}) || null;
}
function countLeaves(documentValue) {
return flat(documentValue).filter(function (entry) {
return !childrenOf(entry.block);
}).length;
}
function countNodes(documentValue) {
return flat(documentValue).length;
}
/// True when this entry is a child of a row, which is the only place a
/// width means anything.
function inRow(entry) {
return !!(entry && entry.parent && entry.parent.body.flow === "row");
}
/// Drop a block into a sibling list at a position, clamped to that list.
function attach(siblings, index, block) {
siblings.splice(Math.max(0, Math.min(index, siblings.length)), 0, block);
}
/// Every id in a document, in document order.
function ids(blocks) {
var found = [];
(function down(list) {
(list || []).forEach(function (block) {
found.push(block.id);
if (block.body && block.body.kind === "group") down(block.body.children);
});
})(blocks);
return found;
}
// --- what this build can draw --------------------------------------------
// `blocks` is optional on the wire: the field carries serde's default, so
// {"version":3} is a document the server accepts and the live page draws as
// an empty dashboard. Reading a missing key as [] here is what stops the
// editor from declaring a document broken that nothing else refuses.
function normalized(documentValue) {
if (documentValue && typeof documentValue === "object" &&
documentValue.blocks === undefined) {
documentValue.blocks = [];
}
return documentValue;
}
function isDrawable(documentValue) {
function drawableList(blocks) {
return Array.isArray(blocks) && blocks.every(function (block) {
if (!block || typeof block !== "object") return false;
if (typeof block.id !== "string" || typeof block.title !== "string") return false;
if (!block.body || typeof block.body !== "object") return false;
if (typeof block.body.kind !== "string") return false;
// A container is drawable only if everything under it is. The frame
// no longer carries coordinates, so there is nothing else to check:
// width, min_rows and space_before are all optional.
if (block.body.kind === "group") return drawableList(block.body.children || []);
return true;
});
}
return documentValue && documentValue.version === VERSION && drawableList(documentValue.blocks);
}
// The one rule validate() enforces that a canvas cannot express. Every
// control addresses a block by its id, so two blocks sharing one are drawn
// as two rectangles and moved, retitled and removed as one: Remove deleted
// both. A document like that is refused instead, which is what the server
// does with it too, and the text stays in the pane for repair.
//
// Across the whole tree, as the server checks it. A nested block sharing an
// id with a root one is the same defect.
function duplicateId(blocks) {
var found = ids(blocks);
return found.some(function (id, at) { return found.indexOf(id) !== at; });
}
// The frame values this build draws, which are the ranges the server takes.
//
// A share or a height outside them is not a newer build's attribute to be
// preserved: it is a v3 field with a v3 range, the server refuses it, and
// there is no class for it. Drawing it anyway put a block on screen at a
// size the live page would not give it and left the refusal to Save.
function outOfRange(blocks) {
var bad = null;
(function down(list) {
(list || []).forEach(function (block) {
if (bad) return;
if (block.width !== undefined &&
(!Number.isInteger(block.width) || block.width < WIDTH_MIN || block.width > WIDTH_MAX)) {
bad = { id: block.id, field: "share of the row", low: WIDTH_MIN, high: WIDTH_MAX };
} else if (block.min_rows !== undefined &&
(!Number.isInteger(block.min_rows) ||
block.min_rows < MIN_ROWS_MIN || block.min_rows > MIN_ROWS_MAX)) {
bad = { id: block.id, field: "minimum height", low: MIN_ROWS_MIN, high: MIN_ROWS_MAX };
}
if (block.body && block.body.kind === "group") down(block.body.children);
});
})(blocks);
return bad;
}
// --- building a block ----------------------------------------------------
/// A free id built from a kind name, unique across `taken`.
///
/// `taken` is every id in the document, not just the root list: ids are
/// unique document wide, so a stem counted against the root alone hands the
/// same id to a new block and one already sitting inside a group.
function nextId(kind, taken) {
// The id charset validate() enforces, because this id is built from a kind
// name and a kind can arrive from the pane rather than from the palette.
var stem = String(kind).replace(/[^A-Za-z0-9_-]/g, "") || "block";
var suffix = 1;
while (taken.indexOf(stem + "-" + suffix) >= 0) suffix += 1;
return stem + "-" + suffix;
}
// One threshold field onto the block's threshold object.
//
// The object is created on first touch and then kept, rather than dropped
// again when both limits are cleared: the direction is a setting of its own,
// and a panel that forgot it the moment a limit was emptied would snap the
// select back to rising under the operator's hands.
//
// An empty field is null, not zero. Number("") is 0, and a caution of zero
// on a rising card puts every reading in caution.
function applyThreshold(block, name, raw) {
var thresholds = block.body.thresholds;
if (!thresholds) {
thresholds = { caution: null, critical: null, rising: true };
block.body.thresholds = thresholds;
}
if (name === "rising") {
thresholds.rising = raw !== "0";
return;
}
thresholds[name] = raw === "" ? null : Number(raw);
}
// One `label = source` per line into the cell list the server expects.
//
// A line with no `=` becomes a cell showing its own text, so a half-typed
// line is a cell that draws rather than a document the server refuses. An
// empty list would be refused, so an empty box keeps one placeholder cell:
// the alternative is a block that cannot be saved while it is being written.
function parseCells(text) {
var cells = String(text).split("\n").map(function (line) {
var at = line.indexOf("=");
var label = (at < 0 ? line : line.slice(0, at)).trim();
var source = at < 0 ? "" : line.slice(at + 1).trim();
if (label === "") return null;
return { label: label, value: source === "" ? { literal: label } : { source: source } };
}).filter(Boolean);
return cells.length ? cells : [{ label: "Cell", value: { literal: "No data" } }];
}
// A table as two lists of lines, which is the panel's row editor: one
// column per line, `Label | unit`, and one row per line,
// `Label | cell | cell`, a cell being a source or a "quoted" literal.
//
// Neither parse can produce a table the server refuses: an empty list keeps
// one placeholder, the caps cut the tail off, and every row is padded or cut
// to the column count, because a short row draws each reading after the gap
// under the wrong heading. A column keeps the thresholds of the column it
// replaces at the same position; those are set in the raw pane.
function splitLine(line) {
return line.split("|").map(function (part) { return part.trim(); });
}
function parseColumns(text, old) {
var columns = String(text).split("\n").map(splitLine).filter(function (parts) {
return parts[0] !== "";
}).slice(0, TABLE_COLUMN_CAP).map(function (parts, at) {
var column = { label: parts[0], unit: parts[1] || "" };
var was = (old || [])[at];
if (was && was.thresholds) column.thresholds = was.thresholds;
return column;
});
return columns.length ? columns : [{ label: "Reading", unit: "" }];
}
function cellOf(text) {
var quoted = /^"(.*)"$/.exec(text);
if (quoted) return { literal: quoted[1] };
return text === "" ? { literal: "" } : { source: text };
}
function fitCells(cells, count) {
cells = cells.slice(0, count);
while (cells.length < count) cells.push({ literal: "" });
return cells;
}
function parseRows(text, count) {
var rows = String(text).split("\n").map(splitLine).filter(function (parts) {
return parts[0] !== "";
}).slice(0, TABLE_ROW_CAP).map(function (parts) {
return { label: parts[0], cells: fitCells(parts.slice(1).map(cellOf), count) };
});
return rows.length ? rows : [{ label: "Row 1", cells: fitCells([], count) }];
}
// A new column list, and every row refitted to it.
function applyColumns(body, text) {
body.columns = parseColumns(text, body.columns);
body.rows = (body.rows || []).map(function (row) {
return { label: row.label, cells: fitCells(row.cells || [], body.columns.length) };
});
}
function cellText(value) {
value = value || {};
return value.source !== undefined ? value.source
: value.literal ? "\"" + value.literal + "\"" : "";
}
// One block of a kind, with only the attributes that kind has. A unit on a
// text block is a key the server does not know that kind to carry, and it
// refuses one.
function blockOf(kind, taken) {
var body = { kind: kind };
if (kind === "group" || kind === "row" || kind === "section") {
// Row and section are one kind with two flows, which is how WordPress
// models it too: a Row is a variation of a Group, not a block type of
// its own. Group, ungroup and "make this a row" stay one operation on
// one type instead of a conversion between two.
body = { kind: "group", flow: kind === "row" ? "row" : "stack", children: [] };
} else {
if (VALUELESS_KINDS.indexOf(kind) < 0) body.value = { literal: DEFAULT_VALUE[kind] || "No data" };
if (UNIT_KINDS.indexOf(kind) >= 0) body.unit = "";
if (kind === "card") body.caption = "";
if (kind === "gauge") {
body.min = GAUGE_MIN;
body.max = GAUGE_MAX;
}
if (kind === "chart") body.hours = CHART_HOURS;
if (kind === "heading") body.level = 2;
if (kind === "status_grid") body.cells = parseCells("");
if (kind === "table") {
body.columns = parseColumns("");
body.rows = parseRows("", 1);
}
}
var label = kind === "row" ? "Row" : kind === "section" ? "Section"
: kind.charAt(0).toUpperCase() + kind.slice(1).replace("_", " ");
return { id: nextId(kind, taken), title: label, body: body };
}
// --- patterns ------------------------------------------------------------
//
// A prebuilt arrangement, inserted as a unit. For a SCADA product this is
// worth more than any layout control, because most dashboards are the same
// few shapes: an engine, a tank, a site header. Building one of those from
// the palette is a dozen operations that are the same dozen every time.
//
// A pattern inserts a copy and keeps no link to anything. It is not a
// reusable block: a synced instance would need a second table, an override
// mechanism and a fan-out invalidation story, and inserting a copy is what
// the cases here actually want.
//
// Every pattern is structure, titles and units only. No pattern carries a
// source, because a source names a measurement a particular Warden happens
// to publish and this file ships to every deployment; the picker fills them
// in against the site being edited.
var PATTERNS = [
{
id: "engine",
label: "Engine panel",
hint: "A heading and three readings",
spec: {
kind: "section", title: "Engine", heading: 2, children: [
{
kind: "row", title: "Engine readings", children: [
{ kind: "card", title: "Oil pressure", unit: "bar", width: 4 },
{ kind: "card", title: "Coolant temperature", unit: "C", width: 4 },
{ kind: "metric", title: "Runtime", unit: "h", width: 4 }
]
}
]
}
},
{
id: "tank",
label: "Tank panel",
hint: "A level, a pressure and a note",
spec: {
kind: "section", title: "Tank", heading: 2, children: [
{
kind: "row", title: "Tank readings", children: [
{ kind: "card", title: "Level", unit: "%", width: 6 },
{ kind: "card", title: "Pressure", unit: "bar", width: 6 }
]
},
{ kind: "text", title: "Notes" }
]
}
},
{
id: "site-header",
label: "Site header",
hint: "A title and the site's counts",
spec: {
kind: "section", title: "Overview", heading: 2, children: [
{
kind: "row", title: "Counts", children: [
{ kind: "metric", title: "Devices", width: 6 },
{ kind: "status", title: "Warden", width: 6 }
]
},
{ kind: "separator", title: "Divider" }
]
}
}
];
/// How many nodes and how many leaves a pattern's spec builds.
///
/// Counted from the spec rather than from the built blocks, so the caps can
/// be checked before anything is built and the refusal can name the number
/// rather than half-inserting a pattern.
function patternSize(spec) {
var total = 1;
var leaves = spec.children ? 0 : 1;
(spec.children || []).forEach(function (child) {
var inner = patternSize(child);
total += inner.total;
leaves += inner.leaves;
});
return { total: total, leaves: leaves };
}
/// Build one pattern's blocks, with ids free in `taken`.
///
/// `taken` is appended to as it goes, because every block in the pattern
/// needs an id free of the others in the same pattern as well as of the
/// document's.
function buildPattern(spec, taken) {
var block = blockOf(spec.kind, taken);
taken.push(block.id);
block.title = spec.title;
if (spec.unit !== undefined) block.body.unit = spec.unit;
if (spec.width !== undefined) block.width = spec.width;
if (spec.heading !== undefined) block.body.heading = spec.heading;
(spec.children || []).forEach(function (child) {
block.body.children.push(buildPattern(child, taken));
});
return block;
}
// --- what the panel offers -----------------------------------------------
// The frame fields are the block's own; the rest are its body's.
function fieldValue(block, name) {
var body = block.body || {};
var value = body.value || {};
if (name === "title") return block.title;
if (name === "width") return block.width || 1;
if (name === "min_rows") return block.min_rows === undefined ? "" : block.min_rows;
if (name === "space_before") return block.space_before || "none";
if (name === "flow") return body.flow || "stack";
if (name === "group_heading") return body.heading === undefined ? "" : body.heading;
if (name === "stack_narrow") return body.stack_narrow === false ? "0" : "1";
if (name === "source") return value.source === undefined ? "" : value.source;
if (name === "value") return value.literal === undefined ? "" : value.literal;
if (name === "caption") return body.caption === undefined ? "" : body.caption;
if (name === "level") return body.level === undefined ? 2 : body.level;
// The ends of a gauge's range. A gauge always carries both, so a missing
// one is a document written by hand rather than a field left blank, and
// the default is what a freshly added gauge would have had.
if (name === "trend") return body.trend === true ? "1" : "0";
if (name === "hours") return body.hours === undefined ? CHART_HOURS : body.hours;
if (name === "min") return body.min === undefined ? GAUGE_MIN : body.min;
if (name === "max") return body.max === undefined ? GAUGE_MAX : body.max;
// A threshold left empty is absent rather than zero, so an empty field is
// what "nothing said" looks like on the way out as well as in.
if (name === "caution" || name === "critical") {
var limit = (body.thresholds || {})[name];
return limit === undefined || limit === null ? "" : limit;
}
if (name === "rising") return (body.thresholds || {}).rising === false ? "0" : "1";
// The cell list as text, one `label = source` per line. A cell reading a
// literal shows the literal, which is what the parser round-trips it to.
if (name === "cells") {
return (body.cells || []).map(function (cell) {
var v = cell.value || {};
return v.source === undefined ? cell.label : cell.label + " = " + v.source;
}).join("\n");
}
if (name === "columns") {
return (body.columns || []).map(function (column) {
return column.unit ? column.label + " | " + column.unit : column.label;
}).join("\n");
}
if (name === "rows") {
return (body.rows || []).map(function (row) {
return [row.label].concat((row.cells || []).map(cellText)).join(" | ");
}).join("\n");
}
return body.unit === undefined ? "" : body.unit;
}
// The body fields each kind offers. The panel shows the frame to every
// block and these only to the kinds that carry them, so a field an operator
// fills in is always one the server will accept on that kind.
function fieldApplies(name, kind, entry) {
var isGroup = kind === "group";
// A width is a share of a row, so it is offered only to a row's children.
// Anywhere else the server refuses it, and a control that writes a value
// the save rejects is worse than no control.
if (name === "width") return !!(entry && inRow(entry));
if (name === "flow" || name === "group_heading") return isGroup;
if (name === "stack_narrow") return isGroup && entry && entry.block.body.flow === "row";
// Only while the row is still empty. Once it holds blocks, filling it is
// not what the operator wants and the shares are the per-block control
// above; a picker that appended six more blocks to a full row would be a
// button whose only outcome is a refusal.
if (name === "row_variation") {
return isGroup && !!entry && entry.block.body.flow === "row" &&
(childrenOf(entry.block) || []).length === 0;
}
if (name === "min_rows" || name === "space_before") return true;
if (isGroup) return false;
if (name === "unit") return UNIT_KINDS.indexOf(kind) >= 0;
if (name === "caption") return kind === "card";
if (name === "level") return kind === "heading";
if (name === "caution" || name === "critical" || name === "rising") {
return kind === "card" || kind === "status_grid" || kind === "gauge" ||
kind === "chart";
}
// How far back the line reaches. Only a chart has one and it always has
// one: the server refuses a window outside its bounds, so this is not
// optional the way a threshold is.
if (name === "hours") return kind === "chart";
// The two ends of the range. Only a gauge has them, and it always has
// them: the server refuses a gauge whose ends are not two different
// numbers, so these are not optional the way a threshold is.
if (name === "min" || name === "max") return kind === "gauge";
// Only while the block reads a source. A literal has no history, the
// server refuses that pairing outright, and a control whose only outcome
// is a refused save is worse than no control.
if (name === "trend") {
return (kind === "metric" || kind === "card") && !!entry &&
(entry.block.body.value || {}).source !== undefined;
}
if (name === "cells") return kind === "status_grid";
if (name === "columns" || name === "rows") return kind === "table";
if (name === "value" || name === "source") return VALUELESS_KINDS.indexOf(kind) < 0;
return true;
}
window.FlareDashboardDoc = {
BLOCK_CAP: BLOCK_CAP,
NODE_CAP: NODE_CAP,
DEPTH_CAP: DEPTH_CAP,
ROW_CAP: ROW_CAP,
TABLE_COLUMN_CAP: TABLE_COLUMN_CAP,
TABLE_ROW_CAP: TABLE_ROW_CAP,
VERSION: VERSION,
KINDS: KINDS,
UNIT_KINDS: UNIT_KINDS,
VALUELESS_KINDS: VALUELESS_KINDS,
STRUCTURAL_KINDS: STRUCTURAL_KINDS,
DEFAULT_VALUE: DEFAULT_VALUE,
SPACE_CLASS: SPACE_CLASS,
kindOf: kindOf,
childrenOf: childrenOf,
walk: walk,
flat: flat,
findEntry: findEntry,
countLeaves: countLeaves,
countNodes: countNodes,
inRow: inRow,
attach: attach,
ids: ids,
normalized: normalized,
isDrawable: isDrawable,
duplicateId: duplicateId,
outOfRange: outOfRange,
nextId: nextId,
blockOf: blockOf,
PATTERNS: PATTERNS,
patternSize: patternSize,
buildPattern: buildPattern,
parseCells: parseCells,
parseRows: parseRows,
applyColumns: applyColumns,
applyThreshold: applyThreshold,
fieldValue: fieldValue,
fieldApplies: fieldApplies
};
}());