ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/lenses/kit/kit/templates/canvas.js

kit/kit/templates/canvas.js

256 líneas, 18.4 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. /* The "canvas" template: regions with cards on a grid and arrows by link fields.
  2. *
  3. * layout: {columns: "1fr 1fr ...", areas: ["a b c", "a d c"]} - the CSS grid of the regions (areas may be omitted)
  4. * regions: [{id, title, hint, color, from, type, where, not, sort, group, columns, card, area}]
  5. * columns: auto (or units: auto with card.size) - the columns are counted by the "no long rows" rule, Lens.gridCols.
  6. * from is the folder of records, type is the type, where/not filter by fields, group is the field for subgroups,
  7. * name/notName is a mask of the record file name ("integrations-*"),
  8. * card is {sub, chips, compact, mono, full, art} for the cards of the region; art is a field with the path to the card picture; ratio is the aspect ratio of the card ("3/2"); size is the card sizes s/m/l ("auto" - by the text length),
  9. * then the region has units, its width in grid cells (s is 2 cells, m is 3, l is 4; a cell is 103 pixels); full is the whole card text, without cutting; mono is a monospace line from linked records:
  10. * {back: usedBy, where: {status: taken}} - for example, the libraries of a component. A record goes to the first suitable region.
  11. * linked: true - take only records linked to those already placed (the regions go in order).
  12. * regions + layout - a frame: inside it a grid of its own with regions of its own (server → platform, agent...), any nesting.
  13. * the layout of a frame understands columns, areas and stacks. plain: true - a frame without an outline and a title, only the layout.
  14. * surface: "paper" - the regions are white (the color stays in the top strip and the title), the cards have a barely visible tint of the region
  15. * and are raised by a shadow; works with the atlas look.
  16. * layout.groups: {name: [region, [region, region]]} - a stack of regions under one name in areas: the regions go one under another
  17. * without gaps, a nested list stands in a row.
  18. * tree: on a region - the name of the field "belongs to": the region is drawn as a tree from left to right. The roots are the records of the region without a parent,
  19. * to the right of each are the records that refer to it by this field, to any depth; the order is by sort
  20. * (sort: title - by title). Roots that nobody belongs to lie in a grid under the tree.
  21. * flow: down - a tree from top to bottom: the root on top, its children in a row under it; spread: N is how many levels spread in a row
  22. * (1 by default), deeper the children stand in a column with an indent; a record field kids: stack puts its branch in a column earlier. A record field color paints its branch.
  23. * fold: N - branches deeper than N levels are folded (0 - only the roots are visible), they unfold by a button with the number of those inside.
  24. * modes: [{id, label, card, columns, areas, units}] - card views with a switch in the side panel ("Cards"):
  25. * card is appended to the card of each region, columns and areas replace the layout, units: {region: cells} - the width of a region.
  26. * mode is the id of the default view; the reader's choice is remembered for this lens.
  27. * look: "map" - the map look: light regions with frames, dashed for the proposed (status: proposed / candidate).
  28. * "spec" - a blueprint: nodes in a thin frame without icons, groups with an uppercase caption, right-angle arrows.
  29. * "atlas" - a colored blueprint: regions with a pastel fill, a colored strip on top and an icon (the icon of the region),
  30. * white cards with the record icon, compact cards as plates in a row, right-angle arrows.
  31. * route: "ortho" - right-angle arrows (the default for spec).
  32. * edges: [{field, label, color, dash, from, to, reverse, id}]
  33. * An arrow is drawn if a record field from the region `from` (or any) refers to a record
  34. * on the canvas (in the region `to`, if set). reverse turns the arrow around.
  35. * show: "all" | "hover" - links are visible always or only on hover.
  36. * counters: [[caption, number], ...] - counters in the "Overview" section of the side panel (instead of "Cards / Links").
  37. * list: {title, hint, groups: [{title, color, ids}], card} - the record cards under the canvas, in groups;
  38. * card is as in a region (sub, chips, mono). Without groups all records of the canvas form one group.
  39. * fit: "width" - if the canvas is wider than the window, shrink it to the window width on opening (not below 67%).
  40. * areaMax: the ceiling of the width of a region and a card, pixels or a CSS length (720px in the kit): raise it when the regions
  41. * go across the whole width of a wide canvas.
  42. * hug: true on a region - the region is as wide as its content and stands in the middle of its grid cell,
  43. * and does not stretch over it (for example, a row of cards over wider frames).
  44. * A guide with an example: patterns/map.md.
  45. */
  46. (function () {
  47. const { h } = Lens;
  48. Lens.templates.canvas = function (cfg) {
  49. const ui = Lens.page(cfg);
  50. look = cfg.look || null;
  51. const grid = h("div", { class: "lx-canvas" + (cfg.look ? " lx-look-" + cfg.look : "") + (cfg.surface ? " lx-surface-" + cfg.surface : "") });
  52. // areaMax is the ceiling of the width of a region and a card on this canvas (--block-max in the kit, 720px)
  53. if (cfg.areaMax != null) grid.style.setProperty("--block-max", typeof cfg.areaMax === "number" ? cfg.areaMax + "px" : String(cfg.areaMax));
  54. // card views: a switch in the side panel; a view appends the card options of the regions and may give a layout of its own
  55. const modes = Array.isArray(cfg.modes) ? cfg.modes : [];
  56. const modeKey = Lens.prefs.lens("mode");
  57. const mode = modes.find((m) => m.id === Lens.store.get(modeKey, cfg.mode || null)) || modes.find((m) => m.id === cfg.mode) || modes[0] || null;
  58. let layout = cfg.layout || {};
  59. let regions = cfg.regions || [];
  60. if (mode) {
  61. if (mode.columns) layout = { ...layout, columns: mode.columns };
  62. if (mode.areas) layout = { ...layout, areas: mode.areas };
  63. // the view reaches the regions inside frames too
  64. const apply = (r) => ({ ...r, card: { ...(r.card || {}), ...(mode.card || {}) }, ...(mode.units && mode.units[r.id] != null ? { units: mode.units[r.id] } : {}),
  65. ...(r.regions ? { regions: r.regions.map(apply) } : {}) });
  66. regions = regions.map(apply);
  67. }
  68. if (modes.length > 1) ui.section("Cards", Lens.segmented(modes.map((m) => [m.id, m.label || m.id]), mode.id, (v) => {
  69. Lens.store.set(modeKey, v);
  70. try { localStorage.removeItem(Lens.prefs.lens("view")); } catch (e) { /* storage is closed: the view just will not reset */ }
  71. location.reload();
  72. }));
  73. // counters are in the side panel ("Overview"), fixed: the canvas under them moves and scales
  74. if (cfg.counters) ui.showBar().append(...Lens.stats(cfg.counters));
  75. ui.main.append(grid);
  76. const placed = new Map(); // record id → region id
  77. fill(grid, regions, layout, placed);
  78. Lens.stack(grid, layout);
  79. // layout.groups are named stacks inside the areas layout: {name: [region, [region, region], ...]}.
  80. // The name is put into areas; the regions of the stack go one under another without gaps, a nested list goes in a row.
  81. if (layout.groups && !layout.stacks) for (const [name, items] of Object.entries(layout.groups)) {
  82. const take = (id) => { const el = grid.querySelector(`:scope > [data-region="${id}"]`); if (el) el.style.gridArea = ""; return el; };
  83. const col = h("div", { class: "lx-stack lx-group", style: { gridArea: name } });
  84. for (const item of items) {
  85. if (!Array.isArray(item)) { const el = take(item); if (el) col.append(el); continue; }
  86. const row = h("div", { class: "lx-stackrow" }, item.map(take).filter(Boolean));
  87. if (row.children.length) col.append(row);
  88. }
  89. if (col.children.length) grid.append(col);
  90. }
  91. if (cfg.look === "spec" || cfg.look === "atlas") ui.section("Nodes", h("div", { class: "lx-legend-spec" },
  92. h("div", {}, h("i"), "planned"), h("div", {}, h("i", { class: "p" }), "proposed"), h("div", {}, h("i", { class: "d" }), "already done, exists or taken")));
  93. if (cfg.look === "map") ui.section("Frames", h("div", { class: "lx-hint" },
  94. "A solid frame is planned, dashed is proposed, green is already done. Big dashed frames show where it lives (the server, the outside world)."));
  95. const { edges, kinds, counts } = Lens.fieldEdges(placed, cfg.edges);
  96. // summary arrows between regions: in the atlas look they are always there, except show: hover - then the canvas has only the arrows of the card under the cursor
  97. const areas = (cfg.look === "atlas" || cfg.show === "areas") && cfg.show !== "hover";
  98. if (areas) grid.querySelectorAll("[data-region]").forEach((el) => { el.dataset.node = "@" + el.dataset.region; });
  99. const api = Lens.edges(grid, areas ? edges.concat(Lens.areaEdges(edges, placed)) : edges, { kinds, route: cfg.route || (cfg.look === "spec" || cfg.look === "atlas" ? "ortho" : null) });
  100. if (!cfg.counters) ui.showBar().append(...Lens.stats([["Cards", placed.size], ["Links", edges.length]]));
  101. Lens.edgesPanel(ui, grid, kinds, api, counts, cfg.show || (areas ? "areas" : "all"), areas);
  102. ui.main.classList.add("is-canvas");
  103. Lens.backgroundPanel(ui, ui.main);
  104. const zoom = Lens.zoom(ui.main, grid, { pan: true });
  105. if (cfg.list) ui.main.append(listBelow(cfg.list, placed));
  106. if (cfg.fit === "width") {
  107. const fitWidth = () => {
  108. const room = ui.main.clientWidth, need = grid.scrollWidth;
  109. if (!zoom.restored && zoom.get() === 1 && need > room + 1) { zoom.set(Math.max(0.67, Math.floor((room / need) * 100) / 100)); zoom.home(); }
  110. };
  111. requestAnimationFrame(fitWidth);
  112. }
  113. Lens.emit("ready", { grid, placed, edges, api });
  114. };
  115. // the cards under the canvas: groups with a title and a counter, the cards in a grid by the window width
  116. function listBelow(list, placed) {
  117. const groups = list.groups || [{ ids: [...placed.keys()] }];
  118. const card = { node: false, ...(list.card || {}) };
  119. return h("section", { class: "lx-list" },
  120. list.title ? h("h2", {}, list.title) : null,
  121. list.hint ? h("p", { class: "lx-list-hint" }, list.hint) : null,
  122. groups.filter((g) => g.ids && g.ids.length).map((g) => {
  123. const t = Lens.tone(g.color);
  124. return h("div", { class: "lx-list-group", ...t },
  125. g.title ? h("div", { class: "lx-list-gh" }, h("i", {}), h("span", { class: "t" }, g.title), h("span", { class: "n" }, String(g.ids.length))) : null,
  126. h("div", { class: "lx-cards lx-list-cards" }, g.ids.filter((id) => Lens.rec(id)).map((id) => Lens.card(id, card))));
  127. }));
  128. }
  129. // lays the regions out into a container; a region with regions is a frame with a grid of its own inside (the layout of the frame)
  130. function fill(container, regions, layout, placed) {
  131. container.style.gridTemplateColumns = layout.columns || `repeat(${regions.length}, minmax(220px, 1fr))`;
  132. if (layout.areas) container.style.gridTemplateAreas = layout.areas.map((a) => `"${a}"`).join(" ");
  133. for (const reg of regions) {
  134. const area = layout.areas ? reg.area || reg.id : null;
  135. const own = !reg.regions || reg.from || reg.type || reg.ids;
  136. let recs = own ? Lens.query(reg).filter((r) => !placed.has(r.id)) : [];
  137. if (reg.linked) recs = recs.filter((r) => isLinked(r.id, placed));
  138. // only records without a parent stand in the roots of a tree: whoever has a parent comes with it, in whatever region it stands
  139. if (reg.tree) recs = withKids(recs.filter((r) => !Lens.targets(r.id, reg.tree).some((t) => t !== r.id && Lens.rec(t))), reg.tree, placed);
  140. recs.forEach((r) => placed.set(r.id, reg.id));
  141. if (!reg.regions) {
  142. container.append(Lens.region({ ...reg, class: (reg.hug ? "lx-hug " : "") + (reg.class || ""), area, count: recs.length, body: regionBody(reg, recs) }));
  143. continue;
  144. }
  145. const inner = h("div", { class: "lx-subgrid" });
  146. const before = placed.size;
  147. fill(inner, reg.regions, reg.layout || {}, placed);
  148. Lens.stack(inner, reg.layout);
  149. const body = recs.length ? [regionBody(reg, recs), inner] : [inner];
  150. container.append(Lens.region({ ...reg, class: "lx-frame " + (reg.plain ? "lx-plain " : "") + (reg.hug ? "lx-hug " : "") + (reg.class || ""), area, count: reg.count === false ? null : placed.size - before + recs.length, body }));
  151. }
  152. }
  153. // a tree region: to the records of the region we add all that refer to them by the field tree ("belongs to"), to any depth
  154. function withKids(roots, field, placed) {
  155. const out = [], seen = new Set();
  156. const walk = (r) => {
  157. if (!r || seen.has(r.id) || placed.has(r.id)) return;
  158. seen.add(r.id); out.push(r);
  159. Lens.back(r.id).filter((b) => b.field === field).forEach((b) => walk(Lens.rec(b.id)));
  160. };
  161. roots.forEach(walk);
  162. return out;
  163. }
  164. // a tree from left to right: a card, to the right of it a column of those who belong to it; the lines are drawn by CSS
  165. function treeBody(reg, recs, card, cards) {
  166. const ids = new Set(recs.map((r) => r.id)), kids = new Map(), roots = [];
  167. const ord = (r) => +Lens.prop(r, reg.sort || "order") || 0;
  168. const by = reg.sort === "title" ? (a, b) => String(a.title).localeCompare(String(b.title), "ru") : (a, b) => ord(a) - ord(b);
  169. // fold: N - branches deeper than N levels are folded (0 - only the roots are visible); a folded branch has a button with the number of all inside
  170. const fold = reg.fold == null ? null : +reg.fold;
  171. const inside = (id) => (kids.get(id) || []).reduce((n, k) => n + 1 + inside(k.id), 0);
  172. for (const r of recs) {
  173. const p = Lens.targets(r.id, reg.tree).find((t) => t !== r.id && ids.has(t));
  174. if (!p) { roots.push(r); continue; }
  175. if (!kids.has(p)) kids.set(p, []);
  176. kids.get(p).push(r);
  177. }
  178. // flow: down - a tree from top to bottom: the top spread levels spread in a row, deeper the children stand in a column under the parent.
  179. // A record may have a field color: its branch is painted in this color.
  180. const down = reg.flow === "down", spread = reg.spread == null ? 1 : +reg.spread;
  181. // a record with the field kids: stack puts its branch in a column before the level spread
  182. const node = (r, depth, forced) => {
  183. const k = (kids.get(r.id) || []).sort(by);
  184. const stacked = down && (forced || depth >= spread || (r.props && r.props.kids === "stack"));
  185. const tone = down && r.props && typeof r.props.color === "string" ? Lens.tone(r.props.color) : {};
  186. const head = down ? h("div", { class: "lx-thead" }, Lens.card(r.id, card)) : Lens.card(r.id, card);
  187. const el = h("div", { class: "lx-tnode" + (stacked ? " lx-tstack" : ""), ...tone }, head);
  188. if (!k.length) return el;
  189. if (fold != null) {
  190. const n = inside(r.id);
  191. const btn = h("button", { class: "lx-tfold", type: "button", title: "Unfold or fold the branch" });
  192. const set = (f) => { el.classList.toggle("folded", f); btn.textContent = f ? "+" + n : "−"; };
  193. btn.addEventListener("click", (e) => { e.stopPropagation(); set(!el.classList.contains("folded")); });
  194. set(depth >= fold);
  195. (down ? head : el).append(btn);
  196. }
  197. el.append(h("div", { class: "lx-tkids" + (stacked ? " lx-stackkids" : "") }, k.map((c) => node(c, depth + 1, stacked))));
  198. return el;
  199. };
  200. // roots that nobody belongs to do not drag a branch behind them: they lie in an ordinary grid under the tree, not in a long column
  201. roots.sort(by);
  202. const grown = roots.filter((r) => kids.has(r.id)), alone = roots.filter((r) => !kids.has(r.id));
  203. if (!grown.length) return cards(alone);
  204. return h("div", { class: "lx-treewrap" }, h("div", { class: "lx-tree" + (down ? " lx-down" : "") }, grown.map((r) => node(r, 0))), alone.length ? cards(alone) : null);
  205. }
  206. // whether a record is linked to something that already lies on the canvas (in either direction)
  207. function isLinked(id, placed) {
  208. if (Lens.links(id).some((l) => placed.has(l.id))) return true;
  209. return Lens.back(id).some((b) => b.field !== "body" && placed.has(b.id));
  210. }
  211. let look = null;
  212. function regionBody(reg, recs) {
  213. const card = { ...(look === "atlas" ? { icon: "own" } : {}), ...(reg.card || {}) };
  214. // card.size - cards of three sizes on a grid of small cells: s takes 2×2 cells, m 3×3, l 4×4; units is the width of a region in cells
  215. // columns: auto and units: auto - the "no long rows" rule (Lens.gridCols): a grid close to a square, a row no longer than four cards
  216. const cells = { s: 2, m: 3, l: 4 }[card.size] || 3;
  217. const cols = (list) => (reg.columns === "auto" || reg.units === "auto" ? Lens.gridCols(list.length) : reg.columns || 1);
  218. const cards = (list) => h("div", { class: "lx-cards" + (card.size ? " lx-sized" : ""), "--cols": cols(list), "--units": card.size ? (reg.units === "auto" ? cols(list) * cells : reg.units || cols(list) * 3) : null },
  219. list.map((r) => Lens.card(r.id, card)));
  220. if (!recs.length) return h("div", { class: "lx-empty" }, "Empty so far");
  221. if (reg.tree) return treeBody(reg, recs, card, cards);
  222. if (!reg.group) return cards(recs);
  223. if (reg.groupLayout === "row") {
  224. // the groups stand side by side in columns, in each of them short rows by reg.rows in a column
  225. const rows = reg.rows || 10, groups = new Map();
  226. for (const r of recs) { const v = Lens.prop(r, reg.group); const k = Array.isArray(v) ? v[0] : v; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(r); }
  227. return h("div", { class: "lx-grprow" }, [...groups].map(([k, list]) => {
  228. const o = Lens.option(list[0].type, reg.group, k);
  229. return h("div", { class: "lx-grpcol" },
  230. h("div", { class: "grp" }, h("span", {}, o ? o.text : k || "no value"), h("span", { class: "n" }, String(list.length))),
  231. h("div", { class: "lx-cards", "--cols": Math.ceil(list.length / rows) }, list.map((r) => Lens.card(r.id, card))));
  232. }));
  233. }
  234. const groups = new Map();
  235. for (const r of recs) {
  236. const v = Lens.prop(r, reg.group);
  237. const key = Array.isArray(v) ? v[0] : v;
  238. if (!groups.has(key)) groups.set(key, []);
  239. groups.get(key).push(r);
  240. }
  241. const out = [];
  242. for (const [k, list] of groups) {
  243. const o = Lens.option(list[0].type, reg.group, k);
  244. const title = o ? o.text : k && Lens.rec(k) ? Lens.rec(k).title : k || "no value";
  245. out.push(h("div", { class: "grp" }, `${title} · ${list.length}`), cards(list));
  246. }
  247. return out;
  248. }
  249. })();