diff --git a/autoware_system_designer_studio/README.md b/autoware_system_designer_studio/README.md index ac23ec4b..a75a6c99 100644 --- a/autoware_system_designer_studio/README.md +++ b/autoware_system_designer_studio/README.md @@ -68,13 +68,13 @@ selector, the mode, which every activity reads, and the launch bar; other select live in the activity that uses them, as store keys mirrored in the URL. The system selector lists the systems of the site by package, each with its icon. -| Activity | Rail items | Side panel | Main area | -| -------- | ------------------------------------------------------------ | ----------------------------------------------- | ------------------------------------------------------------- | -| Explore | Diagrams: Nodes, Logic, Sequence (`?diagram=`) | depth, entity search, image download (PNG, SVG) | diagram canvas; inspector shows the selected element | -| Launch | Launch: Control; Monitor: Logs, Topics, Resources (`?view=`) | none | the view of the mode | -| Replay | Replay | scope tree (`?scope=`) | boundary, bag match, configuration, run (daemon) | -| E/E | E/E | architecture, view, load, environments | wiring or units diagram; inspector shows the selected element | -| Build | Build | target, compute unit, start; job list (daemon) | log of the selected job (`?job=`) | +| Activity | Rail items | Side panel | Main area | +| -------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------- | ------------------------------------------------------------- | +| Explore | Diagrams: Nodes, Logic, Sequence (`?diagram=`) | component list with depth per component, entity search, image download (PNG, SVG) | diagram canvas; inspector shows the selected element | +| Launch | Launch: Control; Monitor: Logs, Topics, Resources (`?view=`) | none | the view of the mode | +| Replay | Replay | scope tree (`?scope=`) | boundary, bag match, configuration, run (daemon) | +| E/E | E/E | architecture, view, load, environments | wiring or units diagram; inspector shows the selected element | +| Build | Build | target, compute unit, start; job list (daemon) | log of the selected job (`?job=`) | The E/E activity draws an E/E architecture the system is declared for (`?architecture=`) from the record in the system's `deployment.json`, laid out from the record alone. Devices hosting an @@ -515,14 +515,11 @@ the foot of the tree gives each mark's shape and colour. ### Live monitoring -The Explore activity overlays the live state of the launched members on its diagrams while a -daemon serves the page. The node diagram marks each launched node in its corner with the monitor's -run-state marks, a module or compute unit with the severest state among the nodes within; the mark -is the only change to the drawing, and its tooltip names the state and the restarts. The sequence -diagram treats the process gates of a member that is down as dead, so the -fold rules carry the outage along the chains: an or gate keeps to its live branches, an and gate -waiting on a dead one is dead itself. States come from the same `member` events as the Launch -monitor, with a composable node following its container; a node never launched carries no mark. +The Explore activity overlays the live state of the launched members on the sequence diagram +while a daemon serves the page. The diagram treats the process gates of a member that is down as +dead, so the fold rules carry the outage along the chains: an or gate keeps to its live branches, +an and gate waiting on a dead one is dead itself. States come from the same `member` events as the +Launch monitor, with a composable node following its container. The daemon polls the record root while an event stream is open (one directory listing per `//latency/`, every 2 s) and publishes `records.changed` once a new record diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/pages/assets.py b/autoware_system_designer_studio/autoware_system_designer_studio/pages/assets.py index 0ff61b86..cb2a8a37 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/pages/assets.py +++ b/autoware_system_designer_studio/autoware_system_designer_studio/pages/assets.py @@ -37,7 +37,8 @@ # Diagrams of the Explore activity, in rail order: the rail label and icon (SVG path data), the # module script loaded when the diagram is first shown, whether the module locates entities # (``focusEntity``), which Explore search needs, and whether it draws the design hierarchy cut at -# a chosen depth (the ``depth`` option). ``kinds`` limits a diagram to those target kinds. +# a depth chosen per component (the ``componentDepth`` option). ``kinds`` limits a diagram to +# those target kinds. DIAGRAMS = { "node_diagram": { "label": "Node Diagram", diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/css/activities/explore.css b/autoware_system_designer_studio/autoware_system_designer_studio/web/css/activities/explore.css index 38d75ee6..a27cd155 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/css/activities/explore.css +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/css/activities/explore.css @@ -18,27 +18,107 @@ position: relative; } -/* Depth switch: one segment per design level, across the side panel */ -.depth-levels .segmented button { - flex: 1; +/* Component list: the top-level entities under their compute unit */ +.component-list { + display: flex; + flex-direction: column; + gap: 8px; + max-height: 45vh; + overflow-y: auto; } -.image-save { +.component-group { display: flex; - gap: 6px; + flex-direction: column; + gap: 3px; + padding: 0 6px 4px; + border: 1px solid var(--border-color); + border-radius: 4px; } -.image-save .panel-button { - flex: 1; +.component-unit { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin: 0 -6px 2px; + padding: 4px 6px; + background: var(--bg-tertiary); + border-bottom: 1px solid var(--border-color); + border-radius: 3px 3px 0 0; +} + +.component-unit-name { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + font-weight: 700; + color: var(--text-primary); } -.live-legend { +.component-unit-toggle { display: flex; - flex-wrap: wrap; - gap: 4px 10px; - margin-top: 6px; + flex: none; + align-items: center; + gap: 4px; font-size: 11px; color: var(--text-muted); + cursor: pointer; +} + +.component-unit-toggle input { + margin: 0; +} + +.component-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.component-row[hidden] { + display: none; +} + +.component-name { + min-width: 0; + padding: 2px 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + text-align: left; + background: none; + border: none; + color: var(--text-primary); + cursor: pointer; +} + +.component-name:hover { + color: var(--border-active); +} + +/* Depth switch: one segment of fixed width per level of the component */ +.depth-levels { + flex: none; +} + +.depth-levels button { + width: 20px; + padding: 2px 0; + font-size: 11px; +} + +.image-save { + display: flex; + gap: 6px; +} + +.image-save .panel-button { + flex: 1; } /* Subsystem interface: one scrolling sheet of the launch-file interface */ diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/css/node_diagram.css b/autoware_system_designer_studio/autoware_system_designer_studio/web/css/node_diagram.css index a90970b0..93eefea2 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/css/node_diagram.css +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/css/node_diagram.css @@ -95,11 +95,6 @@ fill: var(--highlight-bg); } -/* Live state of a launched member: a mark in the box's corner */ -.live-mark { - pointer-events: none; -} - /* Gateway node: talks to a peripheral's hardware; opens the peripheral in E/E. */ .gateway-icon { cursor: pointer; diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/architecture/index.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/architecture/index.js index 9cc37032..b21eadbd 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/architecture/index.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/architecture/index.js @@ -485,9 +485,11 @@ (e) => e.entity_type === "node" && e.path === path, ); if (!entity) return; - store.set("diagram", "node_diagram"); - store.set("entity", SD.NamespaceTree.entityKey(entity)); - store.set("activity", "explore"); + store.navigate({ + diagram: "node_diagram", + entity: SD.NamespaceTree.entityKey(entity), + activity: "explore", + }); } function select(target) { @@ -528,7 +530,9 @@ empty.hidden = !!cards.length; } - const views = segmented(VIEWS, (value) => store.set("wiring", value)); + const views = segmented(VIEWS, (value) => + store.navigate({ wiring: value }), + ); views.element.classList.add("ee-views"); const capacity = document.createElement("input"); capacity.type = "checkbox"; diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/depth_selector.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/depth_selector.js index 7ca6c96e..58a3482b 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/depth_selector.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/depth_selector.js @@ -1,14 +1,29 @@ -// Explore: depth switch for the diagrams that draw the design hierarchy cut -// at a level. Level 1 holds the top-level components, the deepest level of -// the mode's structure the nodes. The switch offers up to five levels; a -// deeper structure ends with N, the deepest. The store's `depth` names the -// level; empty is the deepest, so the full view carries over to modes of -// another depth. +// Explore: the top-level entities of the mode's structure listed per compute +// unit, each component with its own depth switch, for the diagrams that draw +// the design hierarchy cut at a level. Level 1 draws a component as a closed +// box, its deepest level down to the nodes. A system starts with every +// component at level 1, a subsystem with every component at its deepest. The +// store's `depth` holds the levels off that default as `name:level` pairs. +// A click on a level selects the component, and a click on its name also +// opens it to its deepest level; the toggle above the list opens every +// component to its deepest level or closes them all. Direct nodes, the +// top-level entities without an inside, carry no switch; those that no link +// joins show for the compute units the store's `unlinked` names, by the +// toggle on the unit's head. (function () { const SD = window.SD; const { element, section, segmented } = SD.widgets; const explore = (SD.activities.explore ||= {}); + const DEFAULT_LEVEL = 1; + + // Level of a component the store names no level for. + function defaultLevel(config) { + return config?.subsystem ? Infinity : DEFAULT_LEVEL; + } + // Store token of the entities on no compute unit. + const NO_UNIT = "-"; + // Number of levels below `instance`. function structureDepth(instance, depth = 0) { if (!instance?.children?.length) return depth; @@ -17,66 +32,274 @@ ); } - const ALL = ""; - const MAX_OPTIONS = 5; + // Component name -> level, from the store's value. + function parseDepths(value) { + const depths = new Map(); + String(value || "") + .split(",") + .forEach((pair) => { + const at = pair.lastIndexOf(":"); + const level = parseInt(pair.slice(at + 1), 10); + if (at > 0 && level > 0) depths.set(pair.slice(0, at), level); + }); + return depths; + } + + // Store value of `depths`; the default level `fallback` is left out. + function formatDepths(depths, fallback = DEFAULT_LEVEL) { + return [...depths] + .filter(([, level]) => level !== fallback) + .map(([name, level]) => `${name}:${level}`) + .join(","); + } + + // Level `depths` gives `instance`, `fallback` without an entry. + function levelOf(depths, instance, fallback = DEFAULT_LEVEL) { + return depths.get(instance?.name) ?? fallback; + } + + const isDirectNode = (instance) => !instance?.children?.length; - // Switch value for the store's `value`: a level above the deepest, or - // `ALL` for the deepest. - function switchValue(value, levels) { - const chosen = parseInt(value, 10); - return chosen > 0 && chosen < levels ? String(chosen) : ALL; + // Direct nodes of `root` with no port on a link. + function unlinkedNodes(root) { + const linked = new Set(); + (root?.links || []).forEach((link) => { + linked.add(String(link.from_port?.unique_id)); + linked.add(String(link.to_port?.unique_id)); + }); + const isLinked = (node) => + [...(node.in_ports || []), ...(node.out_ports || [])].some((port) => + linked.has(String(port.unique_id)), + ); + return (root?.children || []).filter( + (child) => isDirectNode(child) && !isLinked(child), + ); } - // [value, label] pairs of a structure `levels` deep: the levels above the - // last option, then the deepest as its own number or N when the structure - // is deeper than the switch. - function switchOptions(levels) { - const count = Math.min(levels, MAX_OPTIONS); - const options = Array.from({ length: count - 1 }, (_, i) => { - const level = String(i + 1); - return [level, level]; + // Top-level entities per compute unit as { unit, members }: declared units + // in declaration order, then the other units, then the entities on none. + function componentGroups(root) { + const groups = new Map( + (root?.compute_units || []) + .filter((unit) => unit?.name) + .map((unit) => [unit.name, []]), + ); + const ungrouped = []; + (root?.children || []).forEach((child) => { + const unit = child.compute_unit || ""; + if (!unit) ungrouped.push(child); + else if (groups.has(unit)) groups.get(unit).push(child); + else groups.set(unit, [child]); }); - options.push([ALL, levels > MAX_OPTIONS ? "N" : String(levels)]); - return options; + groups.set("", ungrouped); + return [...groups] + .filter(([, members]) => members.length) + .map(([unit, members]) => ({ unit, members })); + } + + // Compute units whose unlinked direct nodes show, from the store's value. + function parseUnits(value) { + return new Set( + String(value || "") + .split(",") + .filter(Boolean) + .map((token) => (token === NO_UNIT ? "" : token)), + ); + } + + function formatUnits(units) { + return [...units].map((unit) => unit || NO_UNIT).join(","); } - function depthSelector(config, store) { - const control = element("div", "depth-levels"); - const group = section("Depth", control); - let levels = 0; - let switcher = null; + // Unlinked direct nodes of `root` on a compute unit outside `shownUnits`. + function hiddenNodes(root, shownUnits) { + return unlinkedNodes(root).filter( + (node) => !shownUnits.has(node.compute_unit || ""), + ); + } + + // Entities from the top-level one down to the entity with `id`; empty when + // `root` holds none. + function pathTo(root, id) { + const walk = (instance, trail) => { + for (const child of instance?.children || []) { + const next = [...trail, child]; + if (String(child.unique_id) === String(id)) return next; + const found = walk(child, next); + if (found.length) return found; + } + return []; + }; + return walk(root, []); + } + + // Store values { depth, unlinked } under which the entity with `id` is + // drawn: its component opened down to it, or the unlinked direct nodes of + // its compute unit shown. Values that already draw it are returned as given. + function revealed(root, id, depth, unlinked, fallback = DEFAULT_LEVEL) { + const path = pathTo(root, id); + if (!path.length) return { depth, unlinked }; + const [component] = path; + if (path.length === 1) { + const units = parseUnits(unlinked); + if (!hiddenNodes(root, units).includes(component)) + return { depth, unlinked }; + units.add(component.compute_unit || ""); + return { depth, unlinked: formatUnits(units) }; + } + const depths = parseDepths(depth); + if (levelOf(depths, component, fallback) >= path.length) + return { depth, unlinked }; + depths.set(component.name, path.length); + return { depth: formatDepths(depths, fallback), unlinked }; + } + + // `onSelect(component)` runs on a click on a name or a level, ahead of the + // depth change. + function depthSelector(config, store, onSelect) { + const expandAll = element("input"); + expandAll.type = "checkbox"; + const expandRow = element("label", "panel-check"); + expandRow.append(expandAll, "Expand all"); + expandAll.addEventListener("change", () => { + const depths = new Map(); + switches.forEach(({ levels }, component) => + depths.set( + component.name, + expandAll.checked ? Math.max(levels, fallback) : DEFAULT_LEVEL, + ), + ); + store.set("depth", formatDepths(depths, fallback)); + }); + const list = element("div", "component-list"); + const group = section("Components", expandRow, list); + // Component -> its switch; compute unit -> its toggle and the rows of its + // unlinked direct nodes. + let switches = new Map(); + let unitRows = new Map(); + const fallback = defaultLevel(config); + + function setLevel(component, level) { + const depths = parseDepths(store.get("depth")); + depths.set(component.name, level); + store.set("depth", formatDepths(depths, fallback)); + } + + function setShown(unit, shown) { + const units = parseUnits(store.get("unlinked")); + if (shown) units.add(unit); + else units.delete(unit); + store.set("unlinked", formatUnits(units)); + } function mark() { - switcher?.mark(switchValue(store.get("depth"), levels)); + const depths = parseDepths(store.get("depth")); + let expanded = true; + switches.forEach(({ switcher, levels }, component) => { + const level = Math.min(levelOf(depths, component, fallback), levels); + switcher.mark(String(level)); + expanded &&= level === levels; + }); + expandAll.checked = expanded; + expandRow.hidden = !switches.size; + const units = parseUnits(store.get("unlinked")); + unitRows.forEach(({ toggle, rows }, unit) => { + toggle.checked = units.has(unit); + rows.forEach((row) => (row.hidden = !toggle.checked)); + }); } - function render() { - switcher = segmented(switchOptions(levels), (value) => - store.set("depth", value), + function memberRow(member) { + const row = element("div", "component-row"); + const name = element("button", "component-name", member.name); + name.type = "button"; + name.title = member.name; + row.appendChild(name); + if (isDirectNode(member)) { + name.addEventListener("click", () => onSelect(member)); + return row; + } + const levels = structureDepth(member) + 1; + const switcher = segmented( + Array.from({ length: levels }, (_, i) => [ + String(i + 1), + String(i + 1), + ]), + (value) => { + onSelect(member); + setLevel(member, parseInt(value, 10)); + }, ); - control.replaceChildren(switcher.element); - mark(); + switcher.element.classList.add("depth-levels"); + name.addEventListener("click", () => { + onSelect(member); + setLevel(member, levels); + }); + switches.set(member, { switcher, levels }); + row.appendChild(switcher.element); + return row; + } + + // Unit head with the toggle of its unlinked direct nodes, then its members. + function unitGroup(unit, members, unlinked) { + const head = element("div", "component-unit"); + const title = element("span", "component-unit-name", unit || "No unit"); + title.title = unit || "On no compute unit"; + head.appendChild(title); + const rows = []; + const body = members.map((member) => { + const row = memberRow(member); + if (unlinked.has(member)) rows.push(row); + return row; + }); + if (rows.length) { + const toggle = element("input"); + toggle.type = "checkbox"; + toggle.addEventListener("change", () => setShown(unit, toggle.checked)); + const label = element("label", "component-unit-toggle"); + label.title = "Show the direct nodes of this unit that no link joins"; + label.append(toggle, `${rows.length} unlinked`); + head.appendChild(label); + unitRows.set(unit, { toggle, rows }); + } + const box = element("div", "component-group"); + box.append(head, ...body); + return box; } - async function loadMode() { - const data = await SD.NamespaceTree.loadStructure( - config.dataBase, - store.get("mode"), + function render(root) { + switches = new Map(); + unitRows = new Map(); + const unlinked = new Set(unlinkedNodes(root)); + list.replaceChildren( + ...componentGroups(root).map(({ unit, members }) => + unitGroup(unit, members, unlinked), + ), ); - levels = Math.max(1, structureDepth(data)); - render(); + mark(); } const reload = () => - loadMode().catch((error) => console.warn("explore depth:", error)); + SD.NamespaceTree.loadStructure(config.dataBase, store.get("mode")) + .then(render) + .catch((error) => console.warn("explore depth:", error)); store.onChange("mode", reload); store.onChange("depth", mark); + store.onChange("unlinked", mark); reload(); return group; } + depthSelector.parseUnits = parseUnits; + depthSelector.formatUnits = formatUnits; + depthSelector.hiddenNodes = hiddenNodes; + depthSelector.revealed = revealed; depthSelector.structureDepth = structureDepth; - depthSelector.switchValue = switchValue; - depthSelector.switchOptions = switchOptions; + depthSelector.parseDepths = parseDepths; + depthSelector.formatDepths = formatDepths; + depthSelector.levelOf = levelOf; + depthSelector.defaultLevel = defaultLevel; + depthSelector.unlinkedNodes = unlinkedNodes; + depthSelector.componentGroups = componentGroups; explore.depthSelector = depthSelector; })(); diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/diagram_host.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/diagram_host.js index 3960dc9f..d4903875 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/diagram_host.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/diagram_host.js @@ -5,7 +5,8 @@ // selected port's topic under `topic`, and // `focusKey` locates the store's entity on the diagram; `clearSelection` // drops the module's selection and empties the inspector. A module that draws -// the hierarchy cut at a level is handed the store's `depth`. Live member +// the hierarchy cut at a level is handed the level of each component from the +// store's `depth`, and the unlinked direct nodes to leave out. Live member // states set on the host reach the module shown, now and after each load, // where the module draws them; a measurement reload reaches it the same way. // `saveImage` downloads the drawing of a module that exports one, and @@ -91,9 +92,15 @@ inspector.reset(); showLoading(`Loading ${diagram.label.toLowerCase()}...`); try { - gateways = gatewayIndex( - await SD.NamespaceTree.loadStructure(config.dataBase, mode), + const structure = await SD.NamespaceTree.loadStructure( + config.dataBase, + mode, ); + gateways = gatewayIndex(structure); + const { parseDepths, levelOf, defaultLevel, parseUnits, hiddenNodes } = + explore.depthSelector; + const depths = parseDepths(store.get("depth")); + const shownUnits = parseUnits(store.get("unlinked")); await DiagramBase.loadScript(diagram.script); const ModuleClass = SD.diagrams.get(diagram.type); if (!ModuleClass) @@ -106,7 +113,13 @@ dataBase: config.dataBase, latencyModes: config.latencyModes, subsystem: config.subsystem, - depth: parseInt(store.get("depth"), 10) || null, + componentDepth: (component) => + levelOf(depths, component, defaultLevel(config)), + hiddenIds: new Set( + hiddenNodes(structure, shownUnits).map((node) => + String(node.unique_id), + ), + ), onInfoUpdate(data, type, entity) { const peripherals = (entity?.entity_type === "node" && gateways.get(entity.path)) || @@ -196,6 +209,10 @@ if (target === module) target.setLiveStates(liveStates); } + function drawsLiveStates() { + return typeof module?.setLiveStates === "function"; + } + function setLiveStates(states) { liveStates = states; applyLiveStates(module).catch((error) => @@ -217,6 +234,7 @@ focusKey, clearSelection, updateTheme, + drawsLiveStates, setLiveStates, reloadMeasurement, canSaveImage, diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/index.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/index.js index 9405f728..1d131be7 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/index.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/index.js @@ -1,8 +1,9 @@ -// Explore activity: the diagrams as rail items, entity search, depth switch -// and image download beside the diagram canvas, with the inspector showing the -// selected element. Search is offered for diagrams that locate entities, the -// depth switch for diagrams that draw the hierarchy cut at a level. With a daemon, the live state of the -// launched members overlays the canvas. +// Explore activity: the diagrams as rail items, entity search, component +// list and image download beside the diagram canvas, with the inspector +// showing the selected element. Search is offered for diagrams that locate +// entities, the component list with its depth switches for diagrams that draw +// the hierarchy cut at a level. With a daemon, the live state of the launched +// members overlays the canvas. (function () { const SD = window.SD; const { element, section } = SD.widgets; @@ -102,16 +103,19 @@ })), }), mount({ side, main, inspector }, { config, store }) { - store.define("depth", "", (v) => /^[1-9]\d*$/.test(v)); + store.define("depth", ""); + store.define("unlinked", ""); // Shared with the E/E activity: the focused peripheral and the view it opens in. store.define("peripheral", ""); store.define("wiring", ""); store.syncUrl(); function openPeripheral(name) { - store.set("peripheral", name); - store.set("wiring", "units"); - store.set("activity", "architecture"); + store.navigate({ + peripheral: name, + wiring: "units", + activity: "architecture", + }); } const host = diagramHost( main, @@ -120,8 +124,49 @@ store, openPeripheral, ); - const search = entitySearch(config, store, (id) => host.focus(id)); - const depth = depthSelector(config, store); + const layered = () => + config.diagrams.find((d) => d.type === store.get("diagram"))?.layered; + // Selects the entity drawn with `id`, on the diagram shown and on the + // one a reload started within the same task draws. The id tells apart + // entities that share a key. + let selectedId = null; + function select(entity) { + selectedId = String(entity.unique_id); + queueMicrotask(() => (selectedId = null)); + store.set("entity", SD.NamespaceTree.entityKey(entity)); + host.focus(selectedId); + } + // A located entity is drawn first: its component opens down to it, the + // unlinked direct nodes of its unit show. + async function locate(id) { + if (layered()) { + const root = await SD.NamespaceTree.loadStructure( + config.dataBase, + store.get("mode"), + ); + const entity = SD.NamespaceTree.entities(root).find( + (e) => String(e.unique_id) === String(id), + ); + const drawn = depthSelector.revealed( + root, + id, + store.get("depth"), + store.get("unlinked"), + depthSelector.defaultLevel(config), + ); + if (entity) { + select(entity); + store.set("depth", drawn.depth); + store.set("unlinked", drawn.unlinked); + return; + } + } + host.focus(id); + } + const search = entitySearch(config, store, (id) => + locate(id).catch((error) => console.warn("explore:", error)), + ); + const depth = depthSelector(config, store, select); const live = liveOverlay(config, store, host, () => main.hidden); const sideBlocks = SD.widgets.sideSplit(side); sideBlocks.top.append( @@ -155,8 +200,13 @@ host.focusKey(key).catch((error) => console.warn("explore:", error)); } function load() { + const id = selectedId; shownKey = ""; - host.load().then(followEntity); + host.load().then(() => { + if (!id) return followEntity(); + shownKey = store.get("entity"); + return host.focus(id); + }); } // The canvas lays out only while visible; a change made while hidden reloads on the next show. @@ -170,12 +220,11 @@ reload(); }); store.onChange("mode", reload); - store.onChange("depth", () => { - if ( - config.diagrams.find((d) => d.type === store.get("diagram"))?.layered - ) - reload(); - }); + ["depth", "unlinked"].forEach((key) => + store.onChange(key, () => { + if (layered()) reload(); + }), + ); store.onChange("entity", (key) => { if (main.hidden) return; shownKey = key; diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/live_overlay.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/live_overlay.js index ddf60bbc..1268d85e 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/live_overlay.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/explore/live_overlay.js @@ -1,10 +1,10 @@ -// Explore: live state of the launched members over the diagrams. The states -// come from the launch session store (one entry per launched node of this -// system, with its container's state for a composable) and reach the canvas -// through the host, which hands them to the diagram module shown. The side -// panel, shown with a daemon, carries a switch for the overlay and the mark -// legend. The mode's -// latency record reloads after the daemon reported a new one. +// Explore: live state of the launched members over the diagrams that draw +// it. The states come from the launch session store (one entry per launched +// node of this system, with its container's state for a composable) and reach +// the canvas through the host, which hands them to the diagram module shown. +// The side panel, shown with a daemon beside such a diagram, carries a switch +// for the overlay. The mode's latency record reloads after the daemon +// reported a new one. (function () { const SD = window.SD; const { element, section } = SD.widgets; @@ -26,13 +26,11 @@ SD.storage.set(OVERLAY_KEY, String(toggle.checked)); schedule(); }); - toggleRow.append(toggle, element("span", "", "Show on diagrams")); - const panel = section( - "Live state", - toggleRow, - SD.RunState.legend("live-legend"), - ); - panel.hidden = !SD.daemon.health; + toggleRow.append(toggle, element("span", "", "Show on the diagram")); + const panel = section("Live state", toggleRow); + const showPanel = () => + (panel.hidden = !SD.daemon.health || !host.drawsLiveStates()); + showPanel(); // Entities of the shown mode, composables nested under their container. let entities = null; @@ -80,7 +78,8 @@ SD.on("launch.member", schedule); SD.on("launch.sessions", schedule); SD.on("daemon.records.changed", onRecord); - SD.on("daemon.health", () => (panel.hidden = !SD.daemon.health)); + SD.on("daemon.health", showPanel); + host.onLoad(showPanel); store.onChange("mode", schedule); schedule(); function show() { diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/launch/topic_rates.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/launch/topic_rates.js index 6f30619e..ebed79a4 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/launch/topic_rates.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/activities/launch/topic_rates.js @@ -18,7 +18,8 @@ // rates records the runtime leaves in the log directories of its units' runs, // over the whole launch or the span between two samples, brushed over the // launch's event density. A topic row click selects the topic and -// its publishing node as the store's `entity`, a node row click the node; the +// its publishing node as the store's `entity`, a node row click the node, each +// as a step of the browser history; the // topic rows of the interfaces of the topic's publishers (else subscribers), // or of the entity's node, are marked by direction, the selected topic in the // stronger shade of its own. @@ -635,8 +636,7 @@ function selectTopic(topic, origin) { selectedTopic = topic; topicEntity = origin ? keyOfNode(origin) : ""; - store.set("topic", topic); - store.set("entity", topicEntity); + store.navigate({ topic, entity: topicEntity }); followEntity(topicEntity); } @@ -649,7 +649,7 @@ function selectNode(path) { selectedNode = path; nodeEntity = path ? keyOfNode(path) : ""; - store.set("entity", nodeEntity); + store.navigate({ entity: nodeEntity }); } // Opens a topic of the node diagram in the topic list. @@ -1289,8 +1289,9 @@ if (list === "node") { selectNode(row.dataset.node === selectedNode ? null : row.dataset.node); } else if (row.dataset.topic === selectedTopic) { - dropTopic(); - store.set("entity", ""); + selectedTopic = null; + topicEntity = null; + store.navigate({ topic: "", entity: "" }); } else { selectTopic(row.dataset.topic, row.dataset.node); } diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/core/store.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/core/store.js index ea7b4eb1..7b37f815 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/core/store.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/core/store.js @@ -1,10 +1,14 @@ // Workbench selection shared by the top bar, the rail panels and the canvas. // Every key mirrors a URL parameter, so a link reopens the same view. A held -// key stays at its value until released. +// key stays at its value until released. A navigation adds a browser history +// entry, and the browser's back and forward restore the selection of the +// entry they land on. (function () { const SD = window.SD; const state = {}; const urlKeys = new Set(); + // key -> { fallback, accept }, as declared. + const declared = new Map(); const heldKeys = new Set(); function readUrl(key) { @@ -23,11 +27,17 @@ // Declares a key; the URL value wins over the default when it passes `accept`. function define(key, fallback, accept = () => true) { - const fromUrl = readUrl(key); - state[key] = fromUrl !== null && accept(fromUrl) ? fromUrl : fallback; + declared.set(key, { fallback, accept }); + state[key] = urlValue(key); urlKeys.add(key); } + function urlValue(key) { + const { fallback, accept } = declared.get(key); + const fromUrl = readUrl(key); + return fromUrl !== null && accept(fromUrl) ? fromUrl : fallback; + } + function get(key) { return state[key]; } @@ -42,6 +52,24 @@ SD.emit("selection", { key, value, previous }); } + // Sets the keys of `changes` in order as one step of the browser history. + function navigate(changes) { + const from = window.location.href; + Object.entries(changes).forEach(([key, value]) => set(key, value)); + const to = window.location.href; + if (to === from) return; + history.replaceState(null, "", from); + history.pushState(null, "", to); + } + + // Takes the selection of the URL a history step landed on, key by key in + // declaration order; held keys stay. + function restore() { + const landed = [...urlKeys].map((key) => [key, urlValue(key)]); + landed.forEach(([key, value]) => set(key, value)); + writeUrl(); + } + // Sets `key` to `value` and holds it there until `release`. function hold(key, value) { heldKeys.delete(key); @@ -63,10 +91,13 @@ }); } + window.addEventListener?.("popstate", restore); + SD.store = { define, get, set, + navigate, hold, release, held, diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/node_diagram.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/node_diagram.js index 3a42cfad..027e236c 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/node_diagram.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/node_diagram.js @@ -79,14 +79,17 @@ this.portAbsPos = new Map(); this.globalOverlay = null; this.activeGlobalTopic = null; - // The mode's structure, and node path -> live member state drawn over it. + // The mode's structure. this.structureRoot = null; - this.liveStates = null; - // Deepest design level drawn: the root is level 0, and an entity at the - // limit is drawn as a box with its boundary ports, its inside left out. - this.depthLimit = Number.isInteger(options.depth) - ? Math.max(1, options.depth) - : Infinity; + // Deepest design level drawn inside a top-level component: the root is + // level 0, and an entity at the limit is drawn as a box with its + // boundary ports, its inside left out. + this.componentDepth = + typeof options.componentDepth === "function" + ? (component) => Math.max(1, options.componentDepth(component)) + : () => Infinity; + // Top-level entities left out of the drawing. + this.hiddenIds = options.hiddenIds || new Set(); // Entities whose inside the limit leaves out, and parent id of every // entity in the structure, drawn or not. this.collapsedIds = new Set(); @@ -108,7 +111,15 @@ async loadAndRender() { try { - const data = await this.loadModeData(this.options.mode); + const loaded = await this.loadModeData(this.options.mode); + const data = this.hiddenIds.size + ? { + ...loaded, + children: (loaded.children || []).filter( + (child) => !this.hiddenIds.has(String(child.unique_id)), + ), + } + : loaded; this.structureRoot = data; const elkGraph = this.transformDataToElk(data); await this.layoutAndRenderNodeDiagram(elkGraph); @@ -158,8 +169,9 @@ }); }; - const convertNode = (instance, depth = 0) => { + const convertNode = (instance, depth = 0, limit = Infinity) => { if (!instance?.unique_id) return null; + if (depth === 1) limit = this.componentDepth(instance); const nodeId = String(instance.unique_id); const style = this._styleOf(nodeId); @@ -227,12 +239,12 @@ // The inside of an entity at the limit, children and the links joining // their ports, stays out of the graph. - const inside = depth < this.depthLimit; + const inside = depth < limit; if (instance.children?.length > 0) { if (!inside) this.collapsedIds.add(nodeId); else { node.children = instance.children - .map((child) => convertNode(child, depth + 1)) + .map((child) => convertNode(child, depth + 1, limit)) .filter(Boolean); if (node.children.length > 0) { delete node.width; @@ -329,13 +341,16 @@ // within STEP_DROP_LIMIT of the box holding it. _indexSteps(root) { this.steps.clear(); - const drawnChildren = (instance, depth) => - depth < this.depthLimit + const limitOf = (instance, depth, limit) => + depth === 1 ? this.componentDepth(instance) : limit; + const drawnChildren = (instance, depth, limit) => + depth < limit ? (instance.children || []).filter((child) => child?.unique_id) : []; - const rise = (instance, depth) => { + const rise = (instance, depth, limit = Infinity) => { + limit = limitOf(instance, depth, limit); const id = String(instance.unique_id); - const children = drawnChildren(instance, depth); + const children = drawnChildren(instance, depth, limit); if (!children.length) { this.steps.set(id, 0); return 1; @@ -343,7 +358,7 @@ let leaves = 0; let inner = 0; children.forEach((child) => { - leaves += rise(child, depth + 1); + leaves += rise(child, depth + 1, limit); inner = Math.max(inner, this.steps.get(String(child.unique_id))); }); this.steps.set( @@ -355,12 +370,13 @@ ); return leaves; }; - const settle = (instance, depth, floor) => { + const settle = (instance, depth, floor, limit = Infinity) => { + limit = limitOf(instance, depth, limit); const id = String(instance.unique_id); const step = Math.max(this.steps.get(id), floor); this.steps.set(id, step); - drawnChildren(instance, depth).forEach((child) => - settle(child, depth + 1, step - STEP_DROP_LIMIT), + drawnChildren(instance, depth, limit).forEach((child) => + settle(child, depth + 1, step - STEP_DROP_LIMIT, limit), ); }; if (root?.unique_id) { @@ -1106,7 +1122,6 @@ svg.appendChild(this.globalOverlay); this.currentGraph = graph; - this.applyLiveStates(); } renderNode(node, parentGroup, depth = 0, originX = 0, originY = 0) { @@ -1571,67 +1586,6 @@ return path; } - // ── Live state ──────────────────────────────────────────────────────────────── - - // Node path -> live member state (token, label, dead, restarts); drawn now - // and again after every render. - setLiveStates(states) { - this.liveStates = states; - this.applyLiveStates(); - } - - // Live state per drawn element: a node's own, a module's the roll-up of - // the nodes within, a compute unit's the roll-up of its members. An - // element with no launched member within carries no mark. - _liveStateById() { - const { rollup, summarize } = window.SD.RunState; - const byId = rollup(this.structureRoot, this.liveStates || new Map()); - // Clusters are not design instances; their members are their direct child groups. - this.currentSvgRoot?.querySelectorAll("g.node-group").forEach((group) => { - if (this.elementData.get(group.id)?.entity_type !== "compute_unit") - return; - const parts = Array.from( - group.querySelectorAll(":scope > g.node-group"), - (child) => byId.get(child.id), - ).filter(Boolean); - if (parts.length) byId.set(group.id, summarize(parts)); - }); - return byId; - } - - applyLiveStates() { - const svg = this.currentSvgRoot; - if (!svg || !this.structureRoot) return; - const byId = this._liveStateById(); - svg.querySelectorAll("g.node-group").forEach((group) => { - group.querySelector(":scope > .live-mark")?.remove(); - const info = byId.get(group.id); - if (!info) return; - const step = stepAttr(group); - const style = this.getLayerStyle(step); - const size = Math.max(4, Math.round(style.fontSize * 0.9)); - const pad = style.badgePad + size / 2; - const mark = document.createElementNS(SVG_NS, "g"); - mark.classList.add("live-mark"); - const restarts = info.restarts ? info.restarts.restarts : 0; - const title = document.createElementNS(SVG_NS, "title"); - title.textContent = [ - info.dead ? `${info.label} · down` : info.label, - restarts ? `restarted ×${restarts}` : "", - ] - .filter(Boolean) - .join(" · "); - mark.appendChild(title); - mark.appendChild( - window.SD.RunState.svgMark(info.token, pad, pad, size), - ); - group.insertBefore( - mark, - group.querySelector(":scope > .node-rect")?.nextSibling || null, - ); - }); - } - // ── Viewport / navigation ───────────────────────────────────────────────────── // Selects the entity drawn with `id` as a click would and centres it in the diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_diagram.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_diagram.js index 32ecf844..5fc392f9 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_diagram.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_diagram.js @@ -167,7 +167,7 @@ layout.innerStubs.forEach((stub) => { const line = svg( "line", - { x1: stub.x, y1: stub.y1, x2: stub.x, y2: stub.y2 }, + { x1: stub.x1, y1: stub.y, x2: stub.x2, y2: stub.y }, "wiring-wire type-ethernet", ); line.dataset.connection = stub.connection; @@ -176,7 +176,7 @@ layout.rails.forEach((rail) => { const line = svg( "line", - { x1: rail.x1, y1: rail.y, x2: rail.x2, y2: rail.y }, + { x1: rail.x, y1: rail.y1, x2: rail.x, y2: rail.y2 }, "wiring-rail", ); line.dataset.device = rail.id; @@ -184,7 +184,7 @@ layers.runs.appendChild(line); const label = svg( "text", - { x: rail.x1 + 4, y: rail.y - 7 }, + { x: rail.x - 3, y: rail.y1 - 7 }, "wiring-text name", ); label.textContent = rail.label; @@ -198,15 +198,11 @@ .map((e) => (e.interface ? `${e.device}.${e.interface}` : e.device)) .join(" — ")}`; wire.segments.forEach((s) => { - const horizontal = s.y1 === s.y2; + const vertical = s.x1 === s.x2; const attributes = { x1: s.x1, y1: s.y1, x2: s.x2, y2: s.y2 }; - const line = svg( - "line", - attributes, - `${cls}${horizontal && wire.run ? " run" : ""}`, - ); + const line = svg("line", attributes, `${cls}${s.run ? " run" : ""}`); line.dataset.connection = wire.id; - (horizontal ? layers.runs : layers.stubs).appendChild(line); + (vertical ? layers.runs : layers.stubs).appendChild(line); const hit = svg("line", attributes, "wiring-hit"); hit.addEventListener("click", (e) => pick("connection", wire.id, e)); const tip = svg("title"); @@ -235,7 +231,7 @@ layers.halos.appendChild( svg( "line", - { x1: point.x - 5, y1: point.y, x2: point.x + 5, y2: point.y }, + { x1: point.x, y1: point.y - 5, x2: point.x, y2: point.y + 5 }, "wiring-halo", ), ), @@ -298,10 +294,10 @@ }); if (!overlay) return; overlay.arrows.forEach((arrow) => { - const sign = arrow.dir === "down" ? -1 : 1; + const sign = arrow.dir === "down" || arrow.dir === "right" ? -1 : 1; const back = - arrow.dir === "right" - ? `l${-ARROW * 1.8} ${-ARROW} v${ARROW * 2}` + arrow.dir === "left" || arrow.dir === "right" + ? `l${sign * ARROW * 1.8} ${-ARROW} v${ARROW * 2}` : `l${-ARROW} ${sign * ARROW * 1.8} h${ARROW * 2}`; const tip = svg( "path", diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_layout.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_layout.js index 48f01731..12c54613 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_layout.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/diagrams/wiring_layout.js @@ -1,10 +1,10 @@ // Wiring layout: the devices of a wiring model as boxes in canvas coordinates // and its connections as axis-aligned wires. Devices hosting environments form -// the core row. Switches and routers joining several of them are rails above -// it, with the devices reached only through a rail in a row over the rails. -// Buses and links between core devices run in lanes under the core row. Every -// other device hangs below the core device it is wired to, and the devices -// wired through it are stacked under it. +// the core column. Switches and routers joining several of them are rails on +// its left, with the devices reached only through a rail in a column left of +// the rails. Buses and links between core devices run in lanes on the right of +// the core column. Every other device hangs beside the core device it is wired +// to, right of the lanes, and the devices wired through it are stacked under it. (function () { const SD = window.SD; const wiring = (SD.wiring ||= {}); @@ -17,23 +17,24 @@ leafGap: 12, indent: 16, stackGap: 8, - stackLabel: 22, - aboveGap: 16, - slotMin: 26, + aboveGap: 24, + slotH: 26, slotPad: 12, groupGap: 10, + captionH: 14, coreMinW: 150, leafMinW: 88, lineH: 13, headH: 36, - portZone: 30, railLabel: 18, - railStep: 26, + railStep: 36, laneGap: 22, - rowGap: 40, + rowGap: 44, partBar: 10, partBox: 24, + partEdge: 20, portStep: 14, + labelRoom: 44, }; const ROW_CORE = "core"; @@ -166,22 +167,13 @@ .filter((d) => rowOf(d.id) !== ROW_CORE && rowOf(d.id) !== ROW_RAIL) .forEach((d) => boxes.set(d.id, leafBox(d))); - const subtreeW = (id) => { - const own = boxes.get(id).w; - const below = kids(id); - if (!below.length) return own; - return Math.max( - own, - G.indent + Math.max(...below.map(subtreeW)) + G.stackLabel, - ); - }; const subtreeH = (id) => kids(id).reduce( (sum, kid) => sum + G.stackGap + subtreeH(kid), boxes.get(id).h, ); - // -- core boxes: slots of the connections leaving each edge ------------ + // -- core boxes: slots of the connections leaving each side ------------- const slotKey = (c, index) => `${c.id}#${index}`; const slotOf = new Map(); @@ -198,8 +190,8 @@ if (own && part) ifaceToPart.set(own.interface, { part: part.device, conn: c.id }); }); - const top = []; - const bottom = []; + const left = []; + const right = []; const wired = new Set(); // Connections whose hung devices have their slot on this device. const hanging = new Set(); @@ -221,38 +213,35 @@ part, label, sub, - w: Math.max( - G.slotMin, - textW(label) + G.slotPad, - textW(sub) + G.slotPad, - ), + w: Math.max(textW(label), textW(sub)), + h: G.slotH, }; slotOf.set(slotKey(c, index), slot); const others = ownersOf(c).filter((id) => id !== device.id); if (isLink(c) && rowOf(others[0]) === ROW_RAIL) { - slot.side = "top"; - top.push(slot); + slot.side = "left"; + left.push(slot); return; } - slot.side = "bottom"; - bottom.push(slot); + slot.side = "right"; + right.push(slot); const hung = hanging.has(c) ? [] : kids(device.id).filter((kid) => place.get(kid).via === c); hanging.add(c); - // The first device hung by the connection sits under its port, the others in columns beside it. + // The first device hung by the connection sits beside its port, the others in rows under it. hung.forEach((kid, i) => { - const w = subtreeW(kid) + G.leafGap; - if (i) bottom.push({ column: kid, part, w, side: "bottom" }); + const h = subtreeH(kid) + G.leafGap; + if (i) right.push({ column: kid, part, w: 0, h, side: "right" }); else { slot.child = kid; - slot.w = Math.max(slot.w, w); + slot.h = Math.max(slot.h, h); } }); }); }); const groupIndex = (slot) => partIds.indexOf(slot.part); - bottom.sort((a, b) => groupIndex(a) - groupIndex(b)); + right.sort((a, b) => groupIndex(a) - groupIndex(b)); const groups = parts.map((part) => { const uplinks = [...ifaceToPart] @@ -264,136 +253,106 @@ conn: to.conn, label: name, sub, - w: Math.max(textW(name), textW(sub)) + G.slotPad, + w: Math.max(textW(name), textW(sub)), }; }); const caption = [part.name, shortDefinition(part.definition)] .filter(Boolean) .join(" · "); - const slotsW = bottom + const slotsH = right .filter((s) => s.part === part.id) - .reduce((sum, s) => sum + s.w, 0); - const need = Math.max( - 60, - textW(caption) + 10, - uplinks.reduce((sum, u) => sum + u.w, 0), - ); - if (slotsW < need) { - const filler = { part: part.id, w: need - slotsW, side: "bottom" }; - const last = bottom + .reduce((sum, s) => sum + s.h, 0); + const need = G.slotH * Math.max(1, uplinks.length); + if (slotsH < need) { + const filler = { + part: part.id, + w: 0, + h: need - slotsH, + side: "right", + }; + const last = right .map(groupIndex) .lastIndexOf(partIds.indexOf(part.id)); if (last < 0) { - const after = bottom.findIndex( + const after = right.findIndex( (s) => groupIndex(s) > partIds.indexOf(part.id), ); - bottom.splice(after < 0 ? bottom.length : after, 0, filler); - } else bottom.splice(last + 1, 0, filler); + right.splice(after < 0 ? right.length : after, 0, filler); + } else right.splice(last + 1, 0, filler); } + const thickness = wiring.isInfra(part) ? G.partBar : G.partBox; return { part, caption, uplinks, - h: wiring.isInfra(part) ? G.partBar : G.partBox, + thickness, + w: Math.max( + textW(caption) + G.partEdge, + Math.max(0, ...uplinks.map((u) => u.w)) + + 10 + + thickness + + G.partEdge, + ), }; }); - let bottomW = 0; - bottom.forEach((slot, i) => { - if (i && slot.part !== bottom[i - 1].part) bottomW += G.groupGap; - slot.offset = bottomW; - bottomW += slot.w; + let rightH = 0; + right.forEach((slot, i) => { + if (i && slot.part !== right[i - 1].part) rightH += G.groupGap; + // The first slot of a part leaves a line for the part's caption. + if (slot.part && slot.part !== right[i - 1]?.part) rightH += G.captionH; + slot.offset = rightH; + rightH += slot.h; }); - let topW = 0; - top.forEach((slot) => { - slot.offset = topW; - topW += slot.w; + let leftH = 0; + left.forEach((slot) => { + slot.offset = leftH; + leftH += slot.h; }); const sub = [shortDefinition(device.definition), device.hardware] .filter(Boolean) .join(" · ") || device.role; - const topZone = top.length ? G.portZone : 6; - const partH = Math.max(0, ...groups.map((g) => g.h)); - const labelled = bottom.some((s) => !s.part && s.label); - const bottomZone = groups.length - ? G.portZone + partH + 24 - : labelled - ? G.portZone - : 8; + const sideW = (slots) => + slots.length ? Math.max(...slots.map((s) => s.w)) + G.slotPad : 0; return { device, core: true, - top, - bottom, + left, + right, groups, sub, - topW, - bottomW, - topZone, w: Math.max( G.coreMinW, - topW + 20, - bottomW + 20, textW(device.name, true) + 110, textW(sub) + 24, + sideW(left) + + 16 + + Math.max( + sideW(right.filter((s) => !s.part)), + ...groups.map((g) => g.w + G.slotPad), + ), ), - h: topZone + G.headH + bottomZone, + h: G.headH + 4 + Math.max(leftH, rightH) + 8, }; } inRow(ROW_CORE).forEach((d) => boxes.set(d.id, coreBox(d))); // -- positions --------------------------------------------------------- - function placeSubtree(id, x0) { - boxes.get(id).x = x0; - kids(id).forEach((kid) => placeSubtree(kid, x0 + G.indent)); - } - function stackSubtree(id) { + // A hung device with the devices wired through it stacked under it. + function placeSubtree(id, x0, y0) { const box = boxes.get(id); - let y0 = box.y + box.h + G.stackGap; + box.x = x0; + box.y = y0; + let next = y0 + box.h + G.stackGap; kids(id).forEach((kid) => { - boxes.get(kid).y = y0; - stackSubtree(kid); - y0 += subtreeH(kid) + G.stackGap; + placeSubtree(kid, x0 + G.indent, next); + next += subtreeH(kid) + G.stackGap; }); } - let x = G.margin; - inRow(ROW_CORE).forEach((d) => { - const box = boxes.get(d.id); - box.x = x; - const bottomX = x + (box.w - box.bottomW) / 2; - box.bottom.forEach((slot) => { - slot.x0 = bottomX + slot.offset; - slot.cx = slot.x0 + slot.w / 2; - const hung = slot.child || slot.column; - if (!hung) return; - const x0 = slot.x0 + (slot.w - subtreeW(hung)) / 2; - placeSubtree(hung, x0); - slot.cx = x0 + boxes.get(hung).w / 2; - }); - const topX = x + (box.w - box.topW) / 2; - box.top.forEach((slot) => { - slot.x0 = topX + slot.offset; - slot.cx = slot.x0 + slot.w / 2; - }); - x += box.w + G.colGap; - }); - const coreRight = Math.max(G.margin, x - G.colGap); - - const above = inRow(ROW_ABOVE); - const aboveW = - above.reduce((sum, d) => sum + boxes.get(d.id).w, 0) + - G.aboveGap * Math.max(0, above.length - 1); - x = G.margin + Math.max(0, (coreRight - G.margin - aboveW) / 2); - above.forEach((d) => { - boxes.get(d.id).x = x; - x += boxes.get(d.id).w + G.aboveGap; - }); - const aboveRight = above.length ? x - G.aboveGap : G.margin; - - // Lanes of the horizontal runs: buses, and links joining two placed devices. + // Lanes of the vertical runs: buses, and links joining two placed devices. const hangs = (c) => isLink(c) && ownersOf(c).some( @@ -403,56 +362,92 @@ const toRail = (c) => isLink(c) && ownersOf(c).some((id) => rowOf(id) === ROW_RAIL); const laned = external.filter((c) => !toRail(c) && !hangs(c)); - const upperLanes = laned.filter((c) => + const outerLanes = laned.filter((c) => ownersOf(c).every((id) => rowOf(id) === ROW_ABOVE), ); - const lowerLanes = laned.filter((c) => !upperLanes.includes(c)); - const laneY = new Map(); + const innerLanes = laned.filter((c) => !outerLanes.includes(c)); + const laneX = new Map(); + + const railDevices = inRow(ROW_RAIL); + // Each rail starts a label line lower than the rail on its left, whose label passes over it. + const railTop = (i) => G.margin + 12 + i * G.railLabel; + const top = railDevices.length ? railTop(railDevices.length) + 4 : G.margin; - let y = G.margin; + let x = G.margin; + const above = inRow(ROW_ABOVE); if (above.length) { - const aboveH = Math.max(...above.map((d) => boxes.get(d.id).h)); - above.forEach((d) => (boxes.get(d.id).y = y)); - y += aboveH + 10; - upperLanes.forEach((c) => { - y += G.laneGap; - laneY.set(c.id, y); + let y0 = top; + above.forEach((d) => { + const box = boxes.get(d.id); + box.x = x; + box.y = y0; + y0 += box.h + G.aboveGap; + }); + x += Math.max(...above.map((d) => boxes.get(d.id).w)); + outerLanes.forEach((c) => { + x += G.laneGap; + laneX.set(c.id, x); }); - y += 14; + if (!railDevices.length) x += G.rowGap; } - const rails = inRow(ROW_RAIL).map((device) => { - y += G.railLabel; - const rail = { device, y, xs: [] }; - y += G.railStep; - return rail; + const rails = railDevices.map((device, i) => { + x += G.railStep; + return { device, x, top: railTop(i), ys: [] }; }); const railOf = new Map(rails.map((rail) => [rail.device.id, rail])); - if (rails.length) y += 6; + if (rails.length) x += G.railStep; const core = inRow(ROW_CORE); - const coreH = Math.max(0, ...core.map((d) => boxes.get(d.id).h)); + const coreX = x; + const coreW = Math.max(0, ...core.map((d) => boxes.get(d.id).w)); + x += coreW; + if (innerLanes.length) { + x += 6; + innerLanes.forEach((c) => { + x += G.laneGap; + laneX.set(c.id, x); + }); + } + // The gap before the hung devices holds the names of the buses. + const laneName = (c) => + [ + c.name, + c.type === wiring.KIND_NETWORK ? "" : c.type, + wiring.formatBitrate(c.bitrate), + ] + .filter(Boolean) + .join(" · "); + const hungX = + x + + Math.max( + G.rowGap, + ...innerLanes + .filter((c) => !isLink(c)) + .map((c) => textW(laneName(c)) + 14), + ); + + let y = top; core.forEach((d) => { const box = boxes.get(d.id); + box.x = coreX; box.y = y; - box.h = coreH; - }); - y += coreH; - if (lowerLanes.length) { - y += 6; - lowerLanes.forEach((c) => { - y += G.laneGap; - laneY.set(c.id, y); + box.w = coreW; + const slotsY = y + G.headH + 4; + box.left.forEach((slot) => { + slot.y0 = slotsY + slot.offset; + slot.cy = slot.y0 + slot.h / 2; }); - } - const hung = inRow(ROW_BELOW).filter((d) => place.get(d.id).depth === 1); - if (hung.length) { - y += G.rowGap; - hung.forEach((d) => { - boxes.get(d.id).y = y; - stackSubtree(d.id); + box.right.forEach((slot) => { + slot.y0 = slotsY + slot.offset; + slot.cy = slot.y0 + slot.h / 2; + const hung = slot.child || slot.column; + if (!hung) return; + const y0 = slot.y0 + G.leafGap / 2; + placeSubtree(hung, hungX, y0); + slot.cy = y0 + boxes.get(hung).h / 2; }); - y += Math.max(...hung.map((d) => subtreeH(d.id))); - } + y += box.h + G.colGap; + }); // -- box contents -------------------------------------------------------- @@ -469,77 +464,69 @@ box.lines.forEach((line, i) => say(line.text, cx, box.y + 19 + i * G.lineH, line.cls, "middle", id), ); - badgeAnchors.set(id, { - x: cx, - y: box.y + box.h + 12, - anchor: "middle", - }); + badgeAnchors.set( + id, + rowOf(id) === ROW_ABOVE + ? { x: cx, y: box.y + box.h + 12, anchor: "middle" } + : { x: box.x + box.w + 6, y: box.y + 12, anchor: "start" }, + ); return; } - const bottomY = box.y + box.h; - box.top.forEach((slot) => { - slot.fromY = box.y; - say(slot.label, slot.cx, box.y + 13, "port", "middle", id); - say(slot.sub, slot.cx, box.y + 25, "address", "middle", id); - }); - say( - box.device.name, - box.x + 10, - box.y + box.topZone + 18, - "name core", - "start", - id, - ); - say(box.sub, box.x + 10, box.y + box.topZone + 32, "sub", "start", id); - badgeAnchors.set(id, { - x: box.x + box.w - 10, - y: box.y + box.topZone + 18, - anchor: "end", - }); - const partBottom = bottomY - 20; + const rightX = box.x + box.w; + say(box.device.name, box.x + 10, box.y + 18, "name core", "start", id); + say(box.sub, box.x + 10, box.y + 32, "sub", "start", id); + badgeAnchors.set(id, { x: rightX - 10, y: box.y + 18, anchor: "end" }); const partRect = new Map(); box.groups.forEach((group) => { - const slots = box.bottom.filter((s) => s.part === group.part.id); - const x0 = slots[0].x0 + 4; - const x1 = slots[slots.length - 1].x0 + slots[slots.length - 1].w - 4; + const slots = box.right.filter((s) => s.part === group.part.id); + const last = slots[slots.length - 1]; + const y0 = slots[0].y0 + 2; const rect = { id: group.part.id, parent: id, device: group.part, - x: x0, - y: partBottom - group.h, - w: x1 - x0, - h: group.h, - bar: group.h === G.partBar, + x: rightX - G.partEdge - group.thickness, + y: y0, + w: group.thickness, + h: last.y0 + last.h - 2 - y0, + bar: group.thickness === G.partBar, }; partRect.set(group.part.id, rect); partBoxes.push(rect); - say(group.caption, x0, bottomY - 7, "sub", "start", group.part.id); + say( + group.caption, + rect.x + rect.w, + y0 - 5, + "sub", + "end", + group.part.id, + ); group.uplinks.forEach((uplink, i) => { - const cx = x0 + (rect.w * (i + 0.5)) / group.uplinks.length; - say(uplink.label, cx, rect.y - 20, "port", "middle", id); - say(uplink.sub, cx, rect.y - 9, "address", "middle", id); + const cy = y0 + (rect.h * (i + 0.5)) / group.uplinks.length; + say(uplink.label, rect.x - 10, cy - 2, "port", "end", id); + say(uplink.sub, rect.x - 10, cy + 9, "address", "end", id); innerStubs.push({ - x: cx, - y1: rect.y - 6, - y2: rect.y, + y: cy, + x1: rect.x - 6, + x2: rect.x, device: id, connection: uplink.conn, }); }); }); - box.bottom.forEach((slot) => { + box.left.forEach((slot) => { const rect = slot.part ? partRect.get(slot.part) : null; - slot.fromY = rect ? rect.y + rect.h : bottomY; + slot.fromX = rect ? rect.x : box.x; + say(slot.label, box.x + 6, slot.cy - 2, "port", "start", id); + say(slot.sub, box.x + 6, slot.cy + 9, "address", "start", id); + }); + box.right.forEach((slot) => { + const rect = slot.part ? partRect.get(slot.part) : null; + slot.fromX = rect ? rect.x + rect.w : rightX; if (!slot.conn) return; - if (slot.label) - say(slot.label, slot.cx, bottomY - 17, "port", "middle", id); - if (slot.sub) - say(slot.sub, slot.cx, bottomY - 6, "address", "middle", id); + say(slot.label, rightX - 6, slot.cy - 2, "port", "end", id); + say(slot.sub, rightX - 6, slot.cy + 9, "address", "end", id); }); - box.top - .filter((slot) => slot.part && partRect.has(slot.part)) - .forEach((slot) => (slot.fromY = partRect.get(slot.part).y)); }); // -- wires --------------------------------------------------------------- @@ -565,13 +552,13 @@ const index = Math.max(0, order.indexOf(c)); if (row === ROW_ABOVE) { return { - x: box.x + (box.w * (index + 1)) / (order.length + 1), - y: box.y + box.h, - dir: "up", + x: box.x + box.w, + y: box.y + (box.h * (index + 1)) / (order.length + 1), + dir: "left", }; } const step = Math.ceil(index / 2) * G.portStep * (index % 2 ? -1 : 1); - return { x: box.x + box.w / 2 + step, y: box.y, dir: "down" }; + return { x: box.x, y: box.y + box.h / 2 + step, dir: "right" }; } function anchor(c, index) { @@ -583,9 +570,9 @@ if (row === ROW_CORE) { const slot = slotOf.get(slotKey(c, index)); return { - x: slot.cx, - y: slot.fromY, - dir: slot.side === "top" ? "down" : "up", + x: slot.fromX, + y: slot.cy, + dir: slot.side === "left" ? "right" : "left", device: endpoint.device, owner: id, }; @@ -595,10 +582,9 @@ const wires = []; let connectors = 0; - const rightEdge = Math.max( - coreRight, - aboveRight, - ...[...boxes.values()].map((box) => box.x + box.w), + const bottomEdge = Math.max( + top, + ...[...boxes.values()].map((box) => box.y + box.h), ); external.forEach((c) => { const wire = { @@ -608,8 +594,8 @@ ends: [], label: null, }; - const line = (x1, y1, x2, y2) => { - if (x1 !== x2 || y1 !== y2) wire.segments.push({ x1, y1, x2, y2 }); + const line = (x1, y1, x2, y2, run = false) => { + if (x1 !== x2 || y1 !== y2) wire.segments.push({ x1, y1, x2, y2, run }); }; const end = (a, x0 = a.x, y0 = a.y, dir = a.dir) => wire.ends.push({ device: a.device, owner: a.owner, x: x0, y: y0, dir }); @@ -619,33 +605,33 @@ if (toRail(c)) { const [first, second] = anchors; if (first.rail && second.rail) { - const cx = rightEdge + 24 + connectors++ * G.portStep; - line(cx, first.rail.y, cx, second.rail.y); + const cy = bottomEdge + 24 + connectors++ * G.portStep; + line(first.rail.x, cy, second.rail.x, cy); [first, second].forEach((a) => { - a.rail.xs.push(cx); - end(a, cx, a.rail.y, a === first ? "up" : "down"); + a.rail.ys.push(cy); + const other = a === first ? second : first; + end(a, a.rail.x, cy, other.rail.x > a.rail.x ? "left" : "right"); }); wire.label = { - x: cx + 4, - y: (first.rail.y + second.rail.y) / 2 + 4, + x: (first.rail.x + second.rail.x) / 2, + y: cy - 4, text: capacity, + anchor: "middle", }; } else { const railEnd = first.rail ? first : second; const other = first.rail ? second : first; - railEnd.rail.xs.push(other.x); - line(other.x, other.y, other.x, railEnd.rail.y); + const railX = railEnd.rail.x; + const after = other.x > railX; + railEnd.rail.ys.push(other.y); + line(other.x, other.y, railX, other.y); end(other); - end( - railEnd, - other.x, - railEnd.rail.y, - other.y > railEnd.rail.y ? "up" : "down", - ); + end(railEnd, railX, other.y, after ? "left" : "right"); wire.label = { - x: other.x + 4, - y: railEnd.rail.y + (other.y > railEnd.rail.y ? 13 : -6), + x: railX + (after ? 6 : -6), + y: other.y - 4, text: capacity, + anchor: after ? "start" : "end", }; } } else if (hangs(c)) { @@ -658,7 +644,12 @@ line(parent.x, parent.y, child.x, child.y); end(parent); end(child); - wire.label = { x: child.x + 4, y: child.y - 5, text: capacity }; + wire.label = { + x: child.x - 5, + y: child.y - 4, + text: capacity, + anchor: "end", + }; } else { const above = boxes.get(parent.owner); const box = boxes.get(child.owner); @@ -671,81 +662,88 @@ wire.label = { x: box.x + box.w + 4, y: mid + 3, text: capacity }; } } else { - const laneAt = laneY.get(c.id); - const xs = []; + const laneAt = laneX.get(c.id); + const ys = []; anchors.forEach((a) => { if (a.rail) return; - xs.push(a.x); - line(a.x, a.y, a.x, laneAt); + ys.push(a.y); + line(a.x, a.y, laneAt, a.y); end(a); }); - if (xs.length) { - let x1 = Math.min(...xs); - let x2 = Math.max(...xs); - if (x1 === x2) { - x1 -= 24; - x2 += 24; + if (ys.length) { + let y1 = Math.min(...ys); + let y2 = Math.max(...ys); + if (y1 === y2) { + y1 -= 24; + y2 += 24; } - // A rail on the lane joins it by a drop of its own past the other ends. + // A rail on the lane joins it by a run of its own past the other + // ends, under the core device it would pass through. anchors.forEach((a) => { if (!a.rail) return; - x2 += G.portStep; - a.rail.xs.push(x2); - line(x2, a.rail.y, x2, laneAt); - end(a, x2, a.rail.y, laneAt > a.rail.y ? "up" : "down"); + y2 += G.portStep; + const over = core + .map((d) => boxes.get(d.id)) + .find((box) => box.y <= y2 && y2 <= box.y + box.h); + if (over) y2 = over.y + over.h + G.colGap / 2; + a.rail.ys.push(y2); + line(a.rail.x, y2, laneAt, y2); + end(a, a.rail.x, y2, laneAt > a.rail.x ? "left" : "right"); }); - line(x1, laneAt, x2, laneAt); - wire.run = { x1, x2, y: laneAt }; - const named = isLink(c) - ? capacity - : [c.name, c.type === wiring.KIND_NETWORK ? "" : c.type, capacity] - .filter(Boolean) - .join(" · "); + line(laneAt, y1, laneAt, y2, true); + wire.run = { x: laneAt, y1, y2 }; wire.label = isLink(c) - ? { x: (x1 + x2) / 2, y: laneAt - 4, text: named, anchor: "middle" } - : { x: x1 + 4, y: laneAt - 5, text: named, name: true }; + ? { x: laneAt + 4, y: (y1 + y2) / 2 + 3, text: capacity } + : { + x: laneAt + 6, + y: Math.min(...ys) - 4, + text: laneName(c), + name: true, + }; } } wires.push(wire); }); const railBars = rails.map((rail) => { - const xs = rail.xs.length ? rail.xs : [G.margin, G.margin + 120]; - const x1 = Math.min(...xs) - 16; - const x2 = Math.max(...xs) + 16; + const y2 = rail.ys.length ? Math.max(...rail.ys) + 16 : rail.top + 120; const label = [ rail.device.name, shortDefinition(rail.device.definition) || rail.device.hardware, ] .filter(Boolean) .join(" · "); - badgeAnchors.set(rail.device.id, { x: x2, y: rail.y - 7, anchor: "end" }); + badgeAnchors.set(rail.device.id, { + x: rail.x, + y: y2 + 14, + anchor: "middle", + }); return { id: rail.device.id, device: rail.device, - x1, - x2, - y: rail.y, + x: rail.x, + y1: rail.top, + y2, label, }; }); - // Points where a vertical run passes over the horizontal run of another wire or a rail. - const horizontals = [ + // Points where a horizontal run passes over the vertical run of another wire or a rail. + const verticals = [ ...railBars.map((bar) => ({ id: bar.id, - x1: bar.x1, - x2: bar.x2, - y: bar.y, + x: bar.x, + y1: bar.y1, + y2: bar.y2, })), ...wires.flatMap((wire) => wire.segments - .filter((s) => s.y1 === s.y2) + .filter((s) => s.x1 === s.x2) .map((s) => ({ id: wire.id, - x1: Math.min(s.x1, s.x2), - x2: Math.max(s.x1, s.x2), - y: s.y1, + x: s.x1, + y1: Math.min(s.y1, s.y2), + y2: Math.max(s.y1, s.y2), })), ), ]; @@ -753,14 +751,14 @@ wires.forEach((wire) => { const touched = new Set(wire.ends.map((e) => e.owner)); wire.segments - .filter((s) => s.x1 === s.x2) + .filter((s) => s.y1 === s.y2) .forEach((s) => { - const top = Math.min(s.y1, s.y2); - const bottom = Math.max(s.y1, s.y2); - horizontals.forEach((h) => { - if (h.id === wire.id || touched.has(h.id)) return; - if (h.y > top && h.y < bottom && s.x1 > h.x1 && s.x1 < h.x2) - crossings.push({ x: s.x1, y: h.y }); + const from = Math.min(s.x1, s.x2); + const to = Math.max(s.x1, s.x2); + verticals.forEach((v) => { + if (v.id === wire.id || touched.has(v.id)) return; + if (v.x > from && v.x < to && s.y1 > v.y1 && s.y1 < v.y2) + crossings.push({ x: v.x, y: s.y1 }); }); }); }); @@ -776,12 +774,19 @@ })); const width = Math.max( - rightEdge + (connectors ? 24 + connectors * G.portStep : 0), - ...railBars.map((bar) => bar.x2), + coreX + coreW, + x, + ...deviceBoxes.map((box) => box.x + box.w + G.labelRoom), + ...railBars.map((bar) => bar.x + textW(bar.label, true)), + ) + G.margin; + const height = + Math.max( + bottomEdge + (connectors ? 24 + connectors * G.portStep : 0), + ...railBars.map((bar) => bar.y2 + 14), ) + G.margin; return { width, - height: y + G.margin + 14, + height, devices: deviceBoxes, parts: partBoxes, rails: railBars, diff --git a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/shell/shell.js b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/shell/shell.js index 26be58ba..f611232f 100644 --- a/autoware_system_designer_studio/autoware_system_designer_studio/web/js/shell/shell.js +++ b/autoware_system_designer_studio/autoware_system_designer_studio/web/js/shell/shell.js @@ -259,8 +259,10 @@ return; } SD.layout.setSidePanelCollapsed(false); - if (views) SD.store.set(views.key, value); - SD.store.set("activity", def.id); + SD.store.navigate({ + ...(views ? { [views.key]: value } : {}), + activity: def.id, + }); } function showActivity(id) { @@ -505,6 +507,11 @@ }); SD.on("daemon.connection", ({ connected }) => renderConnection(connected)); SD.on("daemon.jobs", SD.statusbar.jobs); + // The page holds the system as exported when it loaded; a build of its + // package reloads it on the new export, the URL keeping the selection. + SD.on("daemon.systems.changed", (change) => { + if (change.package === config.packageName) window.location.reload(); + }); buildRail(); refreshRail(); diff --git a/autoware_system_designer_studio/test/js/explore_depth_selector.test.js b/autoware_system_designer_studio/test/js/explore_depth_selector.test.js index 67cc4a9f..57a1d9fe 100644 --- a/autoware_system_designer_studio/test/js/explore_depth_selector.test.js +++ b/autoware_system_designer_studio/test/js/explore_depth_selector.test.js @@ -1,5 +1,7 @@ -// Unit tests for the Explore depth switch: the levels of a structure and the -// level the store's value names, on a stub window. +// Unit tests for the Explore component list: the levels of a structure, the +// store value of the component levels, the unlinked direct nodes shown per +// compute unit, the grouping per compute unit and the values that draw a +// located entity, on a stub window. const test = require("node:test"); const assert = require("node:assert/strict"); @@ -25,8 +27,19 @@ global.window = { }, }; require(path.join(JS_DIR, "activities", "explore", "depth_selector.js")); -const { structureDepth, switchValue, switchOptions } = - global.window.SD.activities.explore.depthSelector; +const { + structureDepth, + parseDepths, + formatDepths, + levelOf, + defaultLevel, + unlinkedNodes, + componentGroups, + parseUnits, + formatUnits, + hiddenNodes, + revealed, +} = global.window.SD.activities.explore.depthSelector; test("structure depth counts the levels below the root", () => { const root = { @@ -38,33 +51,116 @@ test("structure depth counts the levels below the root", () => { assert.equal(structureDepth(null), 0); }); -test("the switch marks a level above the deepest, otherwise N", () => { - assert.equal(switchValue("2", 3), "2"); - assert.equal(switchValue("3", 3), ""); - assert.equal(switchValue("5", 3), ""); - assert.equal(switchValue("", 3), ""); - assert.equal(switchValue("0", 3), ""); +test("the store value names the component levels above the default", () => { + const depths = parseDepths("perception:3,planning:2"); + assert.deepEqual( + [...depths], + [ + ["perception", 3], + ["planning", 2], + ], + ); + assert.equal(formatDepths(depths), "perception:3,planning:2"); + depths.set("planning", 1); + assert.equal(formatDepths(depths), "perception:3"); }); -test("the switch offers up to five levels, ending with N when deeper", () => { - assert.deepEqual(switchOptions(1), [["", "1"]]); - assert.deepEqual(switchOptions(3), [ - ["1", "1"], - ["2", "2"], - ["", "3"], - ]); - assert.deepEqual(switchOptions(5), [ - ["1", "1"], - ["2", "2"], - ["3", "3"], - ["4", "4"], - ["", "5"], +test("a component without a valid entry sits at level 1", () => { + const depths = parseDepths("2,control:0,map:x,:4,sensing:2"); + assert.deepEqual([...depths], [["sensing", 2]]); + assert.equal(levelOf(depths, { name: "sensing" }), 2); + assert.equal(levelOf(depths, { name: "control" }), 1); + assert.equal(parseDepths("").size, 0); +}); + +test("a direct node is unlinked when no link joins its ports", () => { + const port = (id) => ({ unique_id: id }); + const linked = { name: "a", in_ports: [port(1)], out_ports: [port(2)] }; + const alone = { name: "b", out_ports: [port(3)] }; + const portless = { name: "c" }; + const module = { name: "m", in_ports: [port(4)], children: [{}] }; + const root = { + children: [linked, alone, portless, module], + links: [{ from_port: port(2), to_port: port(9) }], + }; + assert.deepEqual(unlinkedNodes(root), [alone, portless]); + assert.deepEqual(unlinkedNodes({}), []); +}); + +test("top-level entities group per compute unit, declared units first", () => { + const a = { name: "a", compute_unit: "sub" }; + const b = { name: "b", compute_unit: "main" }; + const c = { name: "c" }; + const d = { name: "d", compute_unit: "extra" }; + const root = { + compute_units: [{ name: "main" }, { name: "sub" }, { name: "spare" }], + children: [a, b, c, d], + }; + assert.deepEqual(componentGroups(root), [ + { unit: "main", members: [b] }, + { unit: "sub", members: [a] }, + { unit: "extra", members: [d] }, + { unit: "", members: [c] }, ]); - assert.deepEqual(switchOptions(7), [ - ["1", "1"], - ["2", "2"], - ["3", "3"], - ["4", "4"], - ["", "N"], + assert.deepEqual(componentGroups({ children: [c] }), [ + { unit: "", members: [c] }, ]); }); + +test("unlinked direct nodes hide on the units the store leaves out", () => { + const a = { name: "a", unique_id: 1, compute_unit: "main" }; + const b = { name: "b", unique_id: 2, compute_unit: "sub" }; + const c = { name: "c", unique_id: 3 }; + const root = { children: [a, b, c] }; + assert.deepEqual(hiddenNodes(root, parseUnits("")), [a, b, c]); + assert.deepEqual(hiddenNodes(root, parseUnits("sub,-")), [a]); + assert.equal(formatUnits(parseUnits("sub,-")), "sub,-"); + assert.deepEqual([...parseUnits("-")], [""]); +}); + +test("a located entity opens its component down to it", () => { + const node = { name: "n", unique_id: 3 }; + const inner = { name: "inner", unique_id: 2, children: [node] }; + const component = { name: "comp", unique_id: 1, children: [inner] }; + const alone = { name: "alone", unique_id: 4, compute_unit: "main" }; + const root = { children: [component, alone] }; + assert.deepEqual(revealed(root, 3, "", ""), { + depth: "comp:3", + unlinked: "", + }); + assert.deepEqual(revealed(root, 2, "other:2", ""), { + depth: "other:2,comp:2", + unlinked: "", + }); + assert.deepEqual(revealed(root, 2, "comp:3", ""), { + depth: "comp:3", + unlinked: "", + }); + assert.deepEqual(revealed(root, 1, "", ""), { depth: "", unlinked: "" }); + assert.deepEqual(revealed(root, 4, "", "sub"), { + depth: "", + unlinked: "sub,main", + }); + assert.deepEqual(revealed(root, 9, "comp:2", "sub"), { + depth: "comp:2", + unlinked: "sub", + }); +}); + +test("a subsystem starts with every component at its deepest level", () => { + const fallback = defaultLevel({ subsystem: {} }); + assert.equal(fallback, Infinity); + assert.equal(defaultLevel({ subsystem: null }), 1); + const depths = parseDepths("comp:1"); + assert.equal(levelOf(depths, { name: "comp" }, fallback), 1); + assert.equal(levelOf(depths, { name: "other" }, fallback), Infinity); + assert.equal(formatDepths(depths, fallback), "comp:1"); + const node = { name: "n", unique_id: 2 }; + const root = { + children: [{ name: "other", unique_id: 1, children: [node] }], + }; + assert.deepEqual(revealed(root, 2, "comp:1", "", fallback), { + depth: "comp:1", + unlinked: "", + }); +}); diff --git a/autoware_system_designer_studio/test/js/store.test.js b/autoware_system_designer_studio/test/js/store.test.js index 7f1f3e20..83bece72 100644 --- a/autoware_system_designer_studio/test/js/store.test.js +++ b/autoware_system_designer_studio/test/js/store.test.js @@ -15,23 +15,51 @@ const CORE_DIR = path.join( "core", ); -// Loads sd.js and store.js against a page at `search`; returns SD and the URLs written. +// Loads sd.js and store.js against a page at `search`; returns SD, the URLs +// written, the history entries with the index of the shown one, and `go`, +// which steps through them as the browser's back and forward do. function loadStore(search) { const written = []; + const page = "http://studio.test/systems/pkg/sys/index.html"; + const entries = [`${page}${search}`]; + const shown = { index: 0 }; + let onPopState = () => {}; + const show = (url) => { + const parsed = new URL(url); + global.window.location = { search: parsed.search, href: parsed.href }; + }; global.window = { - location: { - search, - href: `http://studio.test/systems/pkg/sys/index.html${search}`, + addEventListener: (type, handler) => { + if (type === "popstate") onPopState = handler; + }, + }; + show(entries[0]); + global.history = { + replaceState: (_state, _title, url) => { + written.push(url); + entries[shown.index] = url; + show(url); }, + pushState: (_state, _title, url) => { + entries.splice(shown.index + 1, entries.length, url); + shown.index += 1; + show(url); + }, + }; + const go = (delta) => { + shown.index += delta; + show(entries[shown.index]); + onPopState(); }; - global.history = { replaceState: (_state, _title, url) => written.push(url) }; delete require.cache[path.join(CORE_DIR, "sd.js")]; delete require.cache[path.join(CORE_DIR, "store.js")]; require(path.join(CORE_DIR, "sd.js")); require(path.join(CORE_DIR, "store.js")); - return { SD: global.window.SD, written }; + return { SD: global.window.SD, written, entries, shown, go }; } +const params = (url) => Object.fromEntries(new URL(url).searchParams); + test("define takes the URL value when accepted and the fallback otherwise", () => { const { SD } = loadStore("?mode=Planning&diagram=bogus"); SD.store.define("mode", "Runtime", (v) => @@ -86,3 +114,56 @@ test("a held key keeps its value until released", () => { SD.store.set("mode", "Runtime"); assert.deepEqual(changes, ["Planning", "Other", "Runtime"]); }); + +test("a navigation is one history entry that back and forward restore", () => { + const { SD, entries, shown, go } = loadStore("?activity=explore"); + SD.store.define("activity", "explore", (v) => + ["explore", "launch"].includes(v), + ); + SD.store.define("view", "control"); + SD.store.define("entity", ""); + SD.store.syncUrl(); + const changes = []; + SD.on("selection", (change) => changes.push([change.key, change.value])); + + SD.store.set("entity", "/a"); + assert.equal(entries.length, 1); + SD.store.navigate({ view: "topics", activity: "launch" }); + assert.equal(entries.length, 2); + assert.deepEqual(params(entries[0]), { + activity: "explore", + view: "control", + entity: "/a", + }); + SD.store.navigate({ view: "topics", activity: "launch" }); + assert.equal(entries.length, 2); + + changes.length = 0; + go(-1); + assert.equal(SD.store.get("activity"), "explore"); + assert.equal(SD.store.get("view"), "control"); + assert.deepEqual(changes, [ + ["activity", "explore"], + ["view", "control"], + ]); + go(1); + assert.equal(SD.store.get("activity"), "launch"); + assert.equal(SD.store.get("view"), "topics"); + assert.equal(shown.index, 1); + assert.equal(entries.length, 2); +}); + +test("a history step leaves a held key and an unaccepted value aside", () => { + const { SD, entries, go } = loadStore(""); + SD.store.define("mode", "Runtime", (v) => + ["Runtime", "Planning"].includes(v), + ); + SD.store.define("activity", "explore"); + SD.store.syncUrl(); + SD.store.navigate({ mode: "Planning", activity: "launch" }); + SD.store.hold("mode", "Planning"); + go(-1); + assert.equal(SD.store.get("mode"), "Planning"); + assert.equal(SD.store.get("activity"), "explore"); + assert.equal(params(entries[0]).mode, "Planning"); +}); diff --git a/autoware_system_designer_studio/test/js/wiring.test.js b/autoware_system_designer_studio/test/js/wiring.test.js index c6b043b3..4993ca2c 100644 --- a/autoware_system_designer_studio/test/js/wiring.test.js +++ b/autoware_system_designer_studio/test/js/wiring.test.js @@ -92,7 +92,7 @@ test("an empty record lays out to nothing", () => { assert.equal(Number.isFinite(layout.width + layout.height), true); }); -test("hosting devices form the core row, shared switches rails, the rest hangs or sits above", () => { +test("hosting devices form the core column, shared switches rails, the rest hangs beside it or sits before the rails", () => { const layout = wiring.layout(wiring.model(RECORD)); const rows = Object.fromEntries(layout.devices.map((d) => [d.id, d.row])); ["ecu_1", "ecu_2", "ecu_3", "ecu_4", "ecu_5", "ecu_6"].forEach((id) => @@ -103,11 +103,13 @@ test("hosting devices form the core row, shared switches rails, the rest hangs o ["hub_10g", "hub_1g"], ); assert.equal(rows.gnss, "above"); - // A switch wired to one core device hangs below it with the devices behind it. + // A switch wired to one core device hangs beside it with the devices behind it under the switch. assert.equal(rows.radar_gateway, "below"); assert.equal(rows.radar_front_center, "below"); - assert.equal(box(layout, "gnss").y < layout.rails[0].y, true); - assert.equal(layout.rails[1].y < box(layout, "ecu_1").y, true); + assert.equal(box(layout, "gnss").x < layout.rails[0].x, true); + assert.equal(layout.rails[1].x < box(layout, "ecu_1").x, true); + assert.equal(box(layout, "ecu_2").y > box(layout, "ecu_1").y, true); + assert.equal(box(layout, "radar_gateway").x > box(layout, "ecu_1").x, true); assert.equal( box(layout, "radar_front_center").y > box(layout, "radar_gateway").y, true, @@ -153,10 +155,10 @@ test("every connection between devices is a wire of axis-aligned runs ending on ); assert.equal(wire.ends.length, wire.connection.endpoints.length, wire.id); }); - // A device hung by a link sits straight under its port. + // A device hung by a link sits straight beside its port. const hung = layout.wires.find((w) => w.id === "c19"); assert.equal(hung.segments.length, 1); - assert.equal(hung.segments[0].x1, hung.segments[0].x2); + assert.equal(hung.segments[0].y1, hung.segments[0].y2); // The wiring inside a composite device is drawn in its box. assert.deepEqual(layout.innerStubs.map((s) => s.connection).sort(), [ "c0", @@ -178,15 +180,15 @@ test("each wire keeps a capacity label, filled where the bit rate is known", () test("a run passing over a rail or another wire's run is a crossing", () => { const layout = wiring.layout(wiring.model(RECORD)); - const [upper, lower] = layout.rails; + const [outer, inner] = layout.rails; const stub = layout.wires.find((w) => w.id === "c5").segments[0]; - assert.equal(lower.y > upper.y, true); + assert.equal(inner.x > outer.x, true); assert.equal( - layout.crossings.some((c) => c.x === stub.x1 && c.y === lower.y), + layout.crossings.some((c) => c.y === stub.y1 && c.x === inner.x), true, ); assert.equal( - layout.crossings.some((c) => c.x === stub.x1 && c.y === upper.y), + layout.crossings.some((c) => c.y === stub.y1 && c.x === outer.x), false, ); }); @@ -218,7 +220,9 @@ test("a time sync domain lights its paths and points at its members", () => { assert.equal( one.arrows.some( (a) => - a.device === "lidar_front_upper" && a.y === lidar.y && a.dir === "down", + a.device === "lidar_front_upper" && + a.x === lidar.x && + a.dir === "right", ), true, ); @@ -512,8 +516,11 @@ test("a bus with a rail among its ends ends on the rail", () => { assert.deepEqual(wire.ends.map((e) => e.owner).sort(), ["a", "sw"]); const rail = layout.rails.find((r) => r.id === "sw"); const onRail = wire.ends.find((e) => e.owner === "sw"); - assert.equal(onRail.y, rail.y); - assert.ok(rail.x1 <= onRail.x && onRail.x <= rail.x2); + assert.equal(onRail.x, rail.x); + assert.ok(rail.y1 <= onRail.y && onRail.y <= rail.y2); + // The run from the rail to the bus passes under the core device, not through it. + const core = box(layout, "a"); + assert.ok(onRail.y > core.y + core.h); wire.segments.forEach((s) => assert.ok(s.x1 === s.x2 || s.y1 === s.y2)); });