@mccaskie-labs/workbench-ui 0.13.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @mccaskie-labs/workbench-ui
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Design mode's try-it part (docs/look-studio.md §8, step 7b). `npx workbench-ui styles` also writes `public/scripts/design-mode.generated.js` from the installed tools' layouts. On a page that loads it, a bar across the top tries any look, light or dark, a site layout (its header and footer) and a phone's width, and a badge before each tool lists that tool's layouts, for this one or every one on the site. Everything tried is a page attribute the stylesheets already answer, so nothing redraws or redeploys. A trial sits in the browser's session only, and nobody else sees it. Keep saves to the address the page gives the script (`data-keep`), which workbench-settings' design group provides next. A layout a tool draws differently (not by CSS alone) is shown but can't be tried in place. New `wb-ui-design*` classes, each with its default style and a sample. Also exports `designData`, `designBar`, `designBadge`, `designScript` and `DESIGN_FILE`.
8
+
9
+ ## 0.13.3
10
+
11
+ ### Patch Changes
12
+
13
+ - The look previewer (docs/look-studio.md §9.1, step 7a): `lookPreview({ pages, url, current, live, words })` draws the project's own pages framed side by side, as the site is now and in every look it may choose, with a switch for the page and for light or dark (`lookPreviewView` reads them from the address, kept to the site's own paths). On the live site (`live: true`) it shows only the site as it is, with a note that the other looks show on the test site. New `wb-ui-look*` classes, each with its default style and a sample. The preview fonts are now each look's families in full, not only the latin letters, so a look previewed in another language shows its own letters. Additive only.
14
+
3
15
  ## 0.13.2
4
16
 
5
17
  ### Patch Changes
package/dist/cli.js CHANGED
@@ -23,6 +23,7 @@ import { createRequire } from "node:module";
23
23
  import { dirname, join, relative, resolve } from "node:path";
24
24
  import { fileURLToPath, pathToFileURL } from "node:url";
25
25
  import { UI_STYLES } from "./ui-styles.js";
26
+ import { DESIGN_FILE, designModeFile } from "./design-mode.js";
26
27
  import { libraryProblems, PREVIEW_FILE, previewFamilies, renderLooks, renderSchemes, resolveSiteLayout, renderTheme, resolveAdminTheme, resolveTheme, themeFixes, themeInput, themeProblems } from "./theme.js";
27
28
  import { familiesIn, fontGaps, projectFonts } from "./fonts.js";
28
29
  import { findItem, itemProblems, LIBRARY, withProjectItems } from "./library.js";
@@ -259,8 +260,9 @@ export function planStyles(dir, tools, uiVersion) {
259
260
  problems.push(...theme.problems);
260
261
  const fonts = projectFonts(theme.families);
261
262
  const generated = renderStyles(tools, uiVersion, theme.css, fonts.css);
262
- // Every look the project may preview, with the latin letters of each look's fonts (docs/look-studio.md §5.3).
263
- const preview = projectFonts(previewFamilies(theme.library), undefined, ["latin"]);
263
+ // Every look the project may choose, with each look's fonts in full (docs/look-studio.md §5.3): the previewer and
264
+ // design mode switch looks with no redeploy, and a project started in any look already holds its fonts.
265
+ const preview = projectFonts(previewFamilies(theme.library));
264
266
  const fontFiles = [...fonts.files, ...preview.files.filter((p) => !fonts.files.some((f) => f.path === p.path))];
265
267
  for (const f of fontFiles) {
266
268
  const bytes = readFileSync(f.from);
@@ -274,6 +276,7 @@ export function planStyles(dir, tools, uiVersion) {
274
276
  [SAMPLE_FILES.guide]: theme.guide,
275
277
  [PREVIEW_FILE.path]: renderLooks(theme.library, preview.css),
276
278
  [SITE_LAYOUT_FILE]: siteLayoutModule(theme.layout),
279
+ [DESIGN_FILE.path]: designModeFile(tools, theme.library),
277
280
  };
278
281
  for (const [path, text] of Object.entries(derived)) {
279
282
  if (existsSync(join(dir, path)) && read(join(dir, path)) === text)
@@ -351,7 +354,7 @@ async function main(argv) {
351
354
  }
352
355
  // Writing fixes workbench.css; project.css and the project's own pages are fixed by hand.
353
356
  // brand.json's problems are fixed by hand too.
354
- const left = plan.problems.filter((p) => !p.startsWith(STYLE_FILES.generated) && !Object.values(SAMPLE_FILES).some((f) => p.startsWith(f)) && !p.startsWith(PREVIEW_FILE.path) && !p.startsWith(SITE_LAYOUT_FILE) && !p.startsWith("public/fonts/") && !(p.startsWith(STYLE_FILES.project) && plan.files[STYLE_FILES.project]));
357
+ const left = plan.problems.filter((p) => !p.startsWith(STYLE_FILES.generated) && !Object.values(SAMPLE_FILES).some((f) => p.startsWith(f)) && !p.startsWith(PREVIEW_FILE.path) && !p.startsWith(SITE_LAYOUT_FILE) && !p.startsWith(DESIGN_FILE.path) && !p.startsWith("public/fonts/") && !(p.startsWith(STYLE_FILES.project) && plan.files[STYLE_FILES.project]));
355
358
  for (const p of left)
356
359
  console.error(p);
357
360
  return left.length ? 1 : 0;
@@ -0,0 +1,80 @@
1
+ import { type Library } from "./library.ts";
2
+ import type { InstalledStyles } from "./styles.ts";
3
+ /** Where the generated script sits and is served. */
4
+ export declare const DESIGN_FILE: {
5
+ readonly path: "public/scripts/design-mode.generated.js";
6
+ readonly url: "/scripts/design-mode.generated.js";
7
+ };
8
+ /** One tool design mode can lay out: the data-tool its outer element carries, and its layouts. */
9
+ export interface DesignTool {
10
+ tool: string;
11
+ /** Its name in the badge, such as "Form". */
12
+ title: string;
13
+ default: string;
14
+ layouts: {
15
+ id: string;
16
+ title: string;
17
+ bestFor: string;
18
+ needs?: readonly string[];
19
+ render?: boolean;
20
+ }[];
21
+ }
22
+ /** What the script knows: every choice it can offer. */
23
+ export interface DesignData {
24
+ looks: {
25
+ id: string;
26
+ title: string;
27
+ feel: string;
28
+ }[];
29
+ siteLayouts: {
30
+ id: string;
31
+ title: string;
32
+ bestFor: string;
33
+ header: string;
34
+ footer: string;
35
+ }[];
36
+ tools: DesignTool[];
37
+ /** The words, in the site's language. */
38
+ words: DesignWords;
39
+ }
40
+ export interface DesignWords {
41
+ bar: string;
42
+ look: string;
43
+ scheme: string;
44
+ light: string;
45
+ dark: string;
46
+ siteLayout: string;
47
+ asNow: string;
48
+ width: string;
49
+ phone: string;
50
+ desktop: string;
51
+ keep: string;
52
+ keepNone: string;
53
+ putBack: string;
54
+ leave: string;
55
+ layout: string;
56
+ thisOne: string;
57
+ everyOne: string;
58
+ needs: string;
59
+ afterKeep: string;
60
+ tried: string;
61
+ }
62
+ export declare const DESIGN_WORDS: DesignWords;
63
+ /** The choices design mode offers in this project: the library's looks and site layouts, and each installed tool's layouts. */
64
+ export declare function designData(tools: readonly InstalledStyles[], lib?: Library, words?: Partial<DesignWords>): DesignData;
65
+ /** The bar across the top of every page in design mode. The script fills in what is chosen and counts the changes. */
66
+ export declare function designBar(d: DesignData): string;
67
+ /** The page at a phone's width, over the page, while Width is Phone. */
68
+ export declare function designPhone(src: string, w: DesignWords): string;
69
+ /** A tool's badge and the list of its layouts it opens: the script puts one before each tool on the page. */
70
+ export declare function designBadge(d: DesignData, t: DesignTool, current: string): string;
71
+ /**
72
+ * The script itself: the bar, a badge on each tool, and the trial kept in
73
+ * sessionStorage. A tool's layout key is its tool id for the whole site, or
74
+ * tool@/path for this page only, as workbench-settings' design.layouts keys
75
+ * them. `keep` (the site's address for saving) is read from the script tag's
76
+ * data-keep; without one the Keep button stays off.
77
+ */
78
+ export declare function designScript(d: DesignData): string;
79
+ /** The script for a project's installed tools, as `styles` writes it. */
80
+ export declare function designModeFile(tools: readonly InstalledStyles[], lib?: Library): string;
@@ -0,0 +1,209 @@
1
+ // Design mode's trial part (docs/look-studio.md §8): on the test site, a
2
+ // signed-in admin tries a look, light or dark, a site layout and each tool's
3
+ // layouts in place, on the real pages. Every choice here is a page attribute
4
+ // the stylesheets already answer (looks.css's [data-wb-look], the frame's
5
+ // data-header and data-footer, each tool's [data-layout]), so trying needs no
6
+ // redraw and no redeploy. Trials sit in the browser's session only: nothing is
7
+ // saved, and nobody else's view changes. Keeping goes through the settings
8
+ // tool (workbench-settings' "design" group) at the address the site gives.
9
+ //
10
+ // `npx workbench-ui styles` writes public/scripts/design-mode.generated.js from the
11
+ // installed tools' layouts, and the site frame loads it only in design mode.
12
+ import { LIBRARY, usable } from "./library.js";
13
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
14
+ /** Where the generated script sits and is served. */
15
+ export const DESIGN_FILE = { path: "public/scripts/design-mode.generated.js", url: "/scripts/design-mode.generated.js" };
16
+ export const DESIGN_WORDS = {
17
+ bar: "Design mode",
18
+ look: "Look",
19
+ scheme: "Show",
20
+ light: "Light",
21
+ dark: "Dark",
22
+ siteLayout: "Site layout",
23
+ asNow: "As it is now",
24
+ width: "Width",
25
+ phone: "Phone",
26
+ desktop: "Desktop",
27
+ keep: "Keep these {n} changes",
28
+ keepNone: "Nothing tried yet",
29
+ putBack: "Put back",
30
+ leave: "Leave design mode",
31
+ layout: "layout",
32
+ thisOne: "This one",
33
+ everyOne: "Every one on the site",
34
+ needs: "Needs {what}",
35
+ afterKeep: "Shows once kept",
36
+ tried: "Only you see these until you keep them.",
37
+ };
38
+ /** A tool's own name for its badge, from its tool id. */
39
+ const TOOL_TITLES = { forms: "Form", booking: "Booking", orders: "Order list", review: "Reviews", tickets: "Tickets" };
40
+ /** The choices design mode offers in this project: the library's looks and site layouts, and each installed tool's layouts. */
41
+ export function designData(tools, lib = LIBRARY, words = {}) {
42
+ return {
43
+ looks: usable(lib.looks).map((l) => ({ id: l.id, title: l.title, feel: l.feel })),
44
+ siteLayouts: usable(lib.layouts).map((l) => ({ id: l.id, title: l.title, bestFor: l.bestFor, header: l.header, footer: l.footer })),
45
+ tools: tools
46
+ .flatMap(({ styles: s }) => (s.layouts && s.layouts.layouts.length > 1 ? [{ tool: s.tool, layouts: s.layouts }] : []))
47
+ .map(({ tool, layouts }) => ({
48
+ tool,
49
+ title: TOOL_TITLES[tool] ?? tool,
50
+ default: layouts.default,
51
+ layouts: layouts.layouts.map((l) => ({ id: l.id, title: l.title, bestFor: l.bestFor, ...(l.needs?.length ? { needs: l.needs } : {}), ...(l.render ? { render: true } : {}) })),
52
+ }))
53
+ .sort((a, b) => (a.tool < b.tool ? -1 : 1)),
54
+ words: { ...DESIGN_WORDS, ...words },
55
+ };
56
+ }
57
+ const option = (value, label) => `<option class="wb-ui-design-option" value="${esc(value)}">${esc(label)}</option>`;
58
+ /** The bar across the top of every page in design mode. The script fills in what is chosen and counts the changes. */
59
+ export function designBar(d) {
60
+ const w = d.words;
61
+ const select = (name, label, options) => `<label class="wb-ui-design-field"><span class="wb-ui-design-label">${esc(label)}</span><select class="wb-ui-design-select" name="${name}">${options}</select></label>`;
62
+ const pair = (name, label, a, b) => `<fieldset class="wb-ui-design-pair"><legend class="wb-ui-design-label">${esc(label)}</legend>${[a, b].map(([v, t]) => `<label class="wb-ui-design-choice"><input class="wb-ui-design-radio" type="radio" name="${name}" value="${esc(v)}"> ${esc(t)}</label>`).join("")}</fieldset>`;
63
+ return (`<div class="wb-ui-design" role="region" aria-label="${esc(w.bar)}" data-wb-design-bar>` +
64
+ `<strong class="wb-ui-design-name">${esc(w.bar)}</strong>` +
65
+ select("look", w.look, option("", w.asNow) + d.looks.map((l) => option(l.id, l.title)).join("")) +
66
+ pair("scheme", w.scheme, ["light", w.light], ["dark", w.dark]) +
67
+ select("site-layout", w.siteLayout, option("", w.asNow) + d.siteLayouts.map((l) => option(l.id, l.title)).join("")) +
68
+ pair("width", w.width, ["phone", w.phone], ["desktop", w.desktop]) +
69
+ `<span class="wb-ui-design-actions"><button class="wb-ui-design-keep" type="button" data-wb-design="keep" disabled>${esc(w.keepNone)}</button>` +
70
+ `<button class="wb-ui-design-button" type="button" data-wb-design="put-back">${esc(w.putBack)}</button>` +
71
+ `<button class="wb-ui-design-button" type="button" data-wb-design="leave">${esc(w.leave)}</button></span>` +
72
+ `<p class="wb-ui-design-note">${esc(w.tried)}</p>` +
73
+ `</div>`);
74
+ }
75
+ /** The page at a phone's width, over the page, while Width is Phone. */
76
+ export function designPhone(src, w) {
77
+ return `<div class="wb-ui-design-phone" data-wb-design-phone><iframe class="wb-ui-design-frame" src="${esc(src)}" title="${esc(w.phone)}"></iframe></div>`;
78
+ }
79
+ /** A tool's badge and the list of its layouts it opens: the script puts one before each tool on the page. */
80
+ export function designBadge(d, t, current) {
81
+ const w = d.words;
82
+ const now = t.layouts.find((l) => l.id === current) ?? t.layouts.find((l) => l.id === t.default);
83
+ const items = t.layouts
84
+ .map((l) => {
85
+ const why = l.render ? w.afterKeep : l.needs?.length ? w.needs.replace("{what}", l.needs.join(", ")) : "";
86
+ return `<li class="wb-ui-design-item"><button class="wb-ui-design-pick" type="button" data-wb-layout="${esc(l.id)}"${l.id === now.id ? ' aria-pressed="true"' : ""}${l.render ? " disabled" : ""}><span class="wb-ui-design-pick-title">${esc(l.title)}</span><span class="wb-ui-design-pick-about">${esc(l.bestFor)}</span>${why ? `<span class="wb-ui-design-pick-why">${esc(why)}</span>` : ""}</button></li>`;
87
+ })
88
+ .join("");
89
+ return (`<details class="wb-ui-design-badge" data-wb-design-tool="${esc(t.tool)}"><summary class="wb-ui-design-badge-name">${esc(t.title)} ${esc(w.layout)}: ${esc(now.title)}</summary>` +
90
+ `<div class="wb-ui-design-menu"><fieldset class="wb-ui-design-pair"><legend class="wb-ui-design-label">${esc(t.title)}</legend>` +
91
+ `<label class="wb-ui-design-choice"><input class="wb-ui-design-radio" type="radio" name="scope-${esc(t.tool)}" value="page" checked> ${esc(w.thisOne)}</label>` +
92
+ `<label class="wb-ui-design-choice"><input class="wb-ui-design-radio" type="radio" name="scope-${esc(t.tool)}" value="site"> ${esc(w.everyOne)}</label></fieldset>` +
93
+ `<ul class="wb-ui-design-list">${items}</ul></div></details>`);
94
+ }
95
+ /**
96
+ * The script itself: the bar, a badge on each tool, and the trial kept in
97
+ * sessionStorage. A tool's layout key is its tool id for the whole site, or
98
+ * tool@/path for this page only, as workbench-settings' design.layouts keys
99
+ * them. `keep` (the site's address for saving) is read from the script tag's
100
+ * data-keep; without one the Keep button stays off.
101
+ */
102
+ export function designScript(d) {
103
+ const badges = Object.fromEntries(d.tools.flatMap((t) => t.layouts.map((l) => [`${t.tool}:${l.id}`, designBadge(d, t, l.id)])));
104
+ return `// Generated by @mccaskie-labs/workbench-ui (\`npx workbench-ui styles\`): design mode (docs/look-studio.md §8). Do not edit.
105
+ (() => {
106
+ "use strict";
107
+ const DATA = ${JSON.stringify({ looks: d.looks, siteLayouts: d.siteLayouts, tools: d.tools.map((t) => ({ tool: t.tool, layouts: t.layouts.map((l) => ({ id: l.id, render: !!l.render })) })), words: { keep: d.words.keep, keepNone: d.words.keepNone } })};
108
+ const BAR = ${JSON.stringify(designBar(d))};
109
+ const BADGES = ${JSON.stringify(badges)};
110
+ const PHONE = ${JSON.stringify(designPhone("{src}", d.words))};
111
+ const KEY = "wb-design-trial";
112
+ // Inside the phone frame: the page only, in the same trial, without a bar of its own.
113
+ const framed = window.top !== window.self;
114
+ const me = document.currentScript;
115
+ const keepAt = me && me.dataset.keep;
116
+ const html = document.documentElement;
117
+ const path = location.pathname;
118
+ const read = () => { try { return JSON.parse(sessionStorage.getItem(KEY) || "{}") || {}; } catch { return {}; } };
119
+ const write = (t) => { try { sessionStorage.setItem(KEY, JSON.stringify(t)); } catch {} };
120
+ const own = { look: html.getAttribute("data-wb-look"), scheme: html.getAttribute("data-wb-scheme") };
121
+ const header = document.querySelector(".wb-site-header[data-header]");
122
+ const footer = document.querySelector(".wb-site-footer[data-footer]");
123
+ const frame = { header: header && header.getAttribute("data-header"), footer: footer && footer.getAttribute("data-footer") };
124
+ const tools = [...document.querySelectorAll("[data-tool][data-layout]")].filter((el) => DATA.tools.some((t) => t.tool === el.dataset.tool));
125
+ tools.forEach((el) => { el.dataset.wbOwnLayout = el.dataset.layout; });
126
+ const count = (t) => ["look", "scheme", "siteLayout"].filter((k) => t[k]).length + Object.keys(t.layouts || {}).length;
127
+ let apply = function (t) {
128
+ const look = t.look || own.look;
129
+ if (look) html.setAttribute("data-wb-look", look); else html.removeAttribute("data-wb-look");
130
+ const scheme = t.scheme || own.scheme;
131
+ if (scheme) html.setAttribute("data-wb-scheme", scheme); else html.removeAttribute("data-wb-scheme");
132
+ const site = DATA.siteLayouts.find((l) => l.id === t.siteLayout);
133
+ if (header) header.setAttribute("data-header", site ? site.header : frame.header);
134
+ if (footer) footer.setAttribute("data-footer", site ? site.footer : frame.footer);
135
+ // A phone's width: the page itself in a frame that wide, so each tool's own phone rules apply.
136
+ const shown = document.querySelector("[data-wb-design-phone]");
137
+ if (t.width === "phone" && !shown) document.body.insertAdjacentHTML("beforeend", PHONE.replace("{src}", location.href.replace(/"/g, "%22")));
138
+ else if (t.width !== "phone" && shown) shown.remove();
139
+ const layouts = t.layouts || {};
140
+ for (const el of tools) {
141
+ const id = layouts[el.dataset.tool + "@" + path] || layouts[el.dataset.tool] || el.dataset.wbOwnLayout;
142
+ const known = DATA.tools.find((x) => x.tool === el.dataset.tool).layouts.find((l) => l.id === id && !l.render);
143
+ el.dataset.layout = known ? id : el.dataset.wbOwnLayout;
144
+ const badge = el.previousElementSibling && el.previousElementSibling.matches("[data-wb-design-tool]") ? el.previousElementSibling : null;
145
+ const fresh = document.createRange().createContextualFragment(BADGES[el.dataset.tool + ":" + el.dataset.layout] || "");
146
+ if (badge) badge.replaceWith(fresh); else el.before(fresh);
147
+ }
148
+ const keep = bar.querySelector("[data-wb-design=keep]");
149
+ const n = count(t);
150
+ keep.textContent = n ? DATA.words.keep.replace("{n}", String(n)) : DATA.words.keepNone;
151
+ keep.disabled = !n || !keepAt;
152
+ for (const s of bar.querySelectorAll("select")) s.value = (s.name === "site-layout" ? t.siteLayout : t[s.name]) || "";
153
+ for (const r of bar.querySelectorAll("input[type=radio]")) r.checked = r.name === "scheme" ? r.value === (t.scheme || own.scheme || "light") : r.value === (t.width || "desktop");
154
+ const phone = document.querySelector("[data-wb-design-phone] iframe");
155
+ if (phone && phone.contentWindow && phone.contentWindow.wbDesignApply) phone.contentWindow.wbDesignApply();
156
+ };
157
+ window.wbDesignApply = () => apply(read());
158
+ if (framed) {
159
+ apply = ((inner) => (t) => inner({ ...t, width: undefined }))(apply);
160
+ addEventListener("storage", () => apply(read()));
161
+ }
162
+ document.body.insertAdjacentHTML("afterbegin", BAR);
163
+ const bar = document.body.firstElementChild;
164
+ if (framed) bar.hidden = true;
165
+ bar.addEventListener("change", (e) => {
166
+ const t = read();
167
+ const el = e.target;
168
+ if (el.name === "look") t.look = el.value || undefined;
169
+ else if (el.name === "site-layout") t.siteLayout = el.value || undefined;
170
+ else if (el.name === "scheme") t.scheme = el.value === (own.scheme || "light") ? undefined : el.value;
171
+ else if (el.name === "width") t.width = el.value === "phone" ? "phone" : undefined;
172
+ write(t);
173
+ apply(t);
174
+ });
175
+ bar.addEventListener("click", async (e) => {
176
+ const act = e.target.closest("[data-wb-design]");
177
+ if (!act) return;
178
+ const what = act.dataset.wbDesign;
179
+ if (what === "put-back") { write({}); apply({}); }
180
+ else if (what === "leave") { write({}); document.cookie = "wb-design=; Path=/; Max-Age=0; SameSite=Lax; Secure"; location.reload(); }
181
+ else if (what === "keep" && keepAt) {
182
+ const t = read();
183
+ act.disabled = true;
184
+ const res = await fetch(keepAt, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ look: t.look, scheme: t.scheme, layout: t.siteLayout, layouts: t.layouts || {} }), credentials: "same-origin" }).catch(() => null);
185
+ if (res && res.ok) { write({}); location.reload(); } else { act.disabled = false; act.textContent = (res && (await res.text().catch(() => ""))) || act.textContent; }
186
+ }
187
+ });
188
+ document.addEventListener("click", (e) => {
189
+ const pick = e.target.closest("[data-wb-layout]");
190
+ const badge = pick && pick.closest("[data-wb-design-tool]");
191
+ if (!badge) return;
192
+ const tool = badge.dataset.wbDesignTool;
193
+ const site = badge.querySelector("input[value=site]").checked;
194
+ const t = read();
195
+ t.layouts = t.layouts || {};
196
+ delete t.layouts[tool + "@" + path];
197
+ if (site) delete t.layouts[tool];
198
+ t.layouts[site ? tool : tool + "@" + path] = pick.dataset.wbLayout;
199
+ write(t);
200
+ apply(t);
201
+ });
202
+ apply(read());
203
+ })();
204
+ `;
205
+ }
206
+ /** The script for a project's installed tools, as `styles` writes it. */
207
+ export function designModeFile(tools, lib = LIBRARY) {
208
+ return designScript(designData(tools, lib));
209
+ }
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export { FORM_SCRIPT } from "./form-script.ts";
6
6
  export { chooseLayout, LAYOUT_BREAKPOINT, LAYOUT_KIT, layoutProblems, type LayoutRule, type ToolLayout, type ToolLayouts } from "./layouts.ts";
7
7
  export { classesIn, sampleProblems, type ToolSample, type ToolSamples } from "./samples.ts";
8
8
  export { guideView, styleGuide, type GuideView, type StyleGuideOptions } from "./style-guide.ts";
9
+ export { lookPreview, lookPreviewView, type LookPreviewOptions, type PreviewPage } from "./look-preview.ts";
9
10
  export { DEFAULT_THEME_CSS, renderStyles, STYLE_FILES, STYLED_SCOPE, styleNames, styleProblems, STYLESHEETS, starterProjectCss, unknownMarkupNames, unknownNames, type InstalledStyles, type StyleClass, type StyleState, type StyleVariable, type ToolStyles, } from "./styles.ts";
10
11
  export { contrast, DEFAULT_LOOK, LOOKS, fixPalette, libraryProblems, lookById, lookFor, lookOf, looksIn, MIN_PALETTE_DISTANCE, mix, nearestPassing, paletteDistance, PREVIEW_FILE, previewAttributes, previewFamilies, renderLooks, renderSchemes, renderTheme, resolveAdminTheme, resolveSiteLayout, resolveTheme, THEME_TOKENS, themeFixes, themeInput, themeProblems, type Look, type LookId, type Palette, type Scheme, type Shape, type Theme, type ThemeFix, type ThemeInput, type ThemeToken, type TokenName, } from "./theme.ts";
11
12
  export { findItem, itemProblems, LIBRARY, LIBRARY_KINDS, libraryOf, SITE_LAYOUT_CHOICES, usable, withProjectItems, type FontFallback, type ItemStatus, type LayoutItem, type Library, type LibraryItem, type LibraryKind, type LookItem, type PairingFont, type PairingItem, type PaletteItem, type SiteLayoutChoice, } from "./library.ts";
@@ -198,3 +199,4 @@ export interface ShellOptions {
198
199
  }
199
200
  /** A whole page: the shared look, the top bar, the heading, then `body`. */
200
201
  export declare function shell(opts: ShellOptions): string;
202
+ export { DESIGN_FILE, DESIGN_WORDS, designBadge, designBar, designData, designModeFile, designPhone, designScript, type DesignData, type DesignTool, type DesignWords } from "./design-mode.ts";
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ export { FORM_SCRIPT } from "./form-script.js";
11
11
  export { chooseLayout, LAYOUT_BREAKPOINT, LAYOUT_KIT, layoutProblems } from "./layouts.js";
12
12
  export { classesIn, sampleProblems } from "./samples.js";
13
13
  export { guideView, styleGuide } from "./style-guide.js";
14
+ export { lookPreview, lookPreviewView } from "./look-preview.js";
14
15
  export { DEFAULT_THEME_CSS, renderStyles, STYLE_FILES, STYLED_SCOPE, styleNames, styleProblems, STYLESHEETS, starterProjectCss, unknownMarkupNames, unknownNames, } from "./styles.js";
15
16
  export { contrast, DEFAULT_LOOK, LOOKS, fixPalette, libraryProblems, lookById, lookFor, lookOf, looksIn, MIN_PALETTE_DISTANCE, mix, nearestPassing, paletteDistance, PREVIEW_FILE, previewAttributes, previewFamilies, renderLooks, renderSchemes, renderTheme, resolveAdminTheme, resolveSiteLayout, resolveTheme, THEME_TOKENS, themeFixes, themeInput, themeProblems, } from "./theme.js";
16
17
  export { findItem, itemProblems, LIBRARY, LIBRARY_KINDS, libraryOf, SITE_LAYOUT_CHOICES, usable, withProjectItems, } from "./library.js";
@@ -305,3 +306,4 @@ export function shell(opts) {
305
306
  ${opts.top}
306
307
  <main class="wb-ui-main"><h1 class="wb-ui-title">${escape(opts.title)}</h1>${opts.body}</main>${opts.tail ?? ""}</html>`;
307
308
  }
309
+ export { DESIGN_FILE, DESIGN_WORDS, designBadge, designBar, designData, designModeFile, designPhone, designScript } from "./design-mode.js";
@@ -0,0 +1,43 @@
1
+ import { type Library } from "./library.ts";
2
+ import type { Scheme } from "./library.ts";
3
+ /** One of the project's pages the previewer can show. */
4
+ export interface PreviewPage {
5
+ path: string;
6
+ label: string;
7
+ }
8
+ export interface LookPreviewOptions {
9
+ /** The pages to choose between; the first is shown first. Paths only, on the project's own site. */
10
+ pages: readonly PreviewPage[];
11
+ /** The page and scheme asked for (`?page=` and `?scheme=`); see lookPreviewView. */
12
+ page?: string;
13
+ scheme?: Scheme;
14
+ /** The previewer's own address, read for `?page=` and `?scheme=` instead of page and scheme. */
15
+ url?: string | URL;
16
+ /**
17
+ * True on the live site, where a page shows only its own look (the frame
18
+ * reads ?wb-look= only outside production): just the site as it is, with a
19
+ * note that the other looks show on the test site.
20
+ */
21
+ live?: boolean;
22
+ /** The project's own look, marked as the one in use. */
23
+ current?: string;
24
+ library?: Library;
25
+ /** The switch's and captions' words, in the page's language. */
26
+ words?: {
27
+ pages?: string;
28
+ schemes?: string;
29
+ light?: string;
30
+ dark?: string;
31
+ yours?: string;
32
+ inUse?: string;
33
+ open?: string;
34
+ live?: string;
35
+ };
36
+ }
37
+ /** The page and scheme a previewer address asks for, kept to the pages offered. */
38
+ export declare function lookPreviewView(url: string | URL, pages: readonly PreviewPage[]): {
39
+ page: string;
40
+ scheme: Scheme;
41
+ };
42
+ /** The previewer's HTML: a switch for the page and the scheme, then one framed page per look. */
43
+ export declare function lookPreview(o: LookPreviewOptions): string;
@@ -0,0 +1,36 @@
1
+ // The look previewer's body (docs/look-studio.md §9.1): the project's own
2
+ // pages in every look it may choose, side by side, light or dark. Each page
3
+ // is the real one, drawn by the project's Worker with ?wb-look= and
4
+ // ?wb-scheme= (previewAttributes), so its words, pictures and tools are the
5
+ // project's own. The page around it is the workbench-site recipe /admin/look.
6
+ import { LIBRARY, usable } from "./library.js";
7
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
8
+ // A page path the previewer may frame: the site's own, never another site's or a script.
9
+ const SAFE_PATH = /^\/(?!\/)[A-Za-z0-9/_.~-]*$/;
10
+ /** The page and scheme a previewer address asks for, kept to the pages offered. */
11
+ export function lookPreviewView(url, pages) {
12
+ const q = new URL(url, "https://x.invalid").searchParams;
13
+ const own = pages.filter((p) => SAFE_PATH.test(p.path));
14
+ const page = own.find((p) => p.path === q.get("page"))?.path ?? own[0]?.path ?? "/";
15
+ return { page, scheme: q.get("scheme") === "dark" ? "dark" : "light" };
16
+ }
17
+ /** The previewer's HTML: a switch for the page and the scheme, then one framed page per look. */
18
+ export function lookPreview(o) {
19
+ const w = { pages: "Page", schemes: "Show", light: "Light", dark: "Dark", yours: "Your site now", inUse: "In use", open: "Open on its own", live: "The other looks show on your test site.", ...o.words };
20
+ const pages = o.pages.filter((p) => SAFE_PATH.test(p.path));
21
+ const asked = o.url !== undefined ? lookPreviewView(o.url, pages) : o;
22
+ const page = pages.find((p) => p.path === asked.page)?.path ?? pages[0]?.path ?? "/";
23
+ const scheme = asked.scheme === "dark" ? "dark" : "light";
24
+ const query = (p, s) => `?page=${encodeURIComponent(p)}&amp;scheme=${s}`;
25
+ const pageSwitch = pages.length > 1 ? `<nav class="wb-ui-look-switch" aria-label="${esc(w.pages)}">${pages.map((p) => `<a class="wb-ui-look-choice" href="${query(p.path, scheme)}"${p.path === page ? ' aria-current="page"' : ""}>${esc(p.label)}</a>`).join("")}</nav>` : "";
26
+ const schemeSwitch = `<nav class="wb-ui-look-switch" aria-label="${esc(w.schemes)}">${["light", "dark"].map((s) => `<a class="wb-ui-look-choice" href="${query(page, s)}"${s === scheme ? ' aria-current="page"' : ""}>${esc(w[s])}</a>`).join("")}</nav>`;
27
+ const sep = page.includes("?") ? "&amp;" : "?";
28
+ const figure = (title, about, src, inUse) => `<figure class="wb-ui-look"><figcaption class="wb-ui-look-caption"><span class="wb-ui-look-title">${esc(title)}</span>${inUse ? `<span class="wb-ui-look-in-use">${esc(w.inUse)}</span>` : ""}<span class="wb-ui-look-about">${esc(about)}</span></figcaption><iframe class="wb-ui-look-frame" src="${src}" title="${esc(title)}" loading="lazy" sandbox="allow-same-origin"></iframe><a class="wb-ui-look-open" href="${src}" target="_blank" rel="noopener">${esc(w.open)}</a></figure>`;
29
+ const looks = o.live ? [] : usable((o.library ?? LIBRARY).looks);
30
+ const figures = [
31
+ figure(w.yours, "", esc(page), false),
32
+ ...looks.map((l) => figure(l.title, l.feel, `${esc(page)}${sep}wb-look=${esc(l.id)}&amp;wb-scheme=${scheme}`, l.id === o.current)),
33
+ ];
34
+ const live = o.live ? `<p class="wb-ui-look-live">${esc(w.live)}</p>` : "";
35
+ return `<div class="wb-ui-looks">${pageSwitch}${o.live ? "" : schemeSwitch}${live}<div class="wb-ui-look-grid">${figures.join("")}</div></div>`;
36
+ }
@@ -2,6 +2,8 @@
2
2
  // project's pages are built from, drawn by the parts themselves with made-up
3
3
  // words. Exported at ./samples beside ./styles.
4
4
  import { actions, body, button, card, check, chip, code, confirm, facts, field, input, jumpNav, message, more, note, pill, select, small, table, textarea, topBar } from "./index.js";
5
+ import { lookPreview } from "./look-preview.js";
6
+ import { designBadge, designBar, designData, designPhone } from "./design-mode.js";
5
7
  import { styleGuide } from "./style-guide.js";
6
8
  export const UI_SAMPLES = {
7
9
  format: 1,
@@ -67,5 +69,21 @@ export const UI_SAMPLES = {
67
69
  html: () => styleGuide([{ format: 1, package: "@mccaskie-labs/workbench-ui", title: "Page parts", prefix: "wb-ui-", samples: [{ id: "note", title: "A note", layout: "stacked", html: () => note("<p>A note.</p>") }] }]) +
68
70
  styleGuide([], { view: "dark" }),
69
71
  },
72
+ {
73
+ id: "design-mode",
74
+ title: "Design mode: the bar, and a tool's badge opened",
75
+ html: () => {
76
+ const tool = { tool: "forms", title: "Form", default: "stacked", layouts: [{ id: "stacked", title: "Stacked", bestFor: "Most forms" }, { id: "two-columns", title: "Two columns", bestFor: "Long forms on a wide screen" }, { id: "steps", title: "One question at a time", bestFor: "Long forms on a phone", render: true }, { id: "beside-picture", title: "Beside a picture", bestFor: "A short form with a photo", needs: ["pictures"] }] };
77
+ const d = { ...designData([]), tools: [tool] };
78
+ return designBar(d) + designBadge(d, tool, "two-columns").replace("<details", "<details open") + designPhone("about:blank", d.words).replace('class="wb-ui-design-phone"', 'class="wb-ui-design-phone" style="position:static;height:14rem"');
79
+ },
80
+ },
81
+ {
82
+ id: "look-preview",
83
+ title: "The look previewer, with its pages left blank, then as the live site shows it",
84
+ // The real one frames the site's own pages; here the frames are empty, so the style guide doesn't load the site inside itself.
85
+ html: () => lookPreview({ pages: [{ path: "/", label: "Home" }, { path: "/classes", label: "Classes" }], current: "calm" }).replace(/ src="[^"]*"/g, ' src="about:blank"').replace(/ href="\/[^"]*wb-look[^"]*"/g, ' href="#"') +
86
+ lookPreview({ pages: [{ path: "/", label: "Home" }], live: true }).replace(/ src="[^"]*"/g, ' src="about:blank"'),
87
+ },
70
88
  ],
71
89
  };
package/dist/ui-styles.js CHANGED
@@ -333,5 +333,48 @@ export const UI_STYLES = {
333
333
  { name: "wb-ui-guide-layout", element: "span", about: "The tool layout a sample shows", css: "font-weight:600" },
334
334
  { name: "wb-ui-guide-frame", element: "div", about: "The sample itself, drawn on the page's own background; a part fixed to the screen (the ask button) stays inside it", css: "padding:1.25rem;contain:layout;min-height:6rem" },
335
335
  { name: "wb-ui-guide-empty", element: "p", about: "Said when no tool has samples yet", css: `color:${v("muted")}` },
336
+ // The look previewer (docs/look-studio.md §9.1): the project's own pages in every look.
337
+ { name: "wb-ui-looks", element: "div", about: "The look previewer: the site's pages in every look", css: "display:grid;gap:1rem" },
338
+ { name: "wb-ui-look-switch", element: "nav", about: "A switch: which page, or light and dark", css: "display:flex;flex-wrap:wrap;gap:.5rem" },
339
+ {
340
+ name: "wb-ui-look-choice",
341
+ element: "a",
342
+ about: "One choice in a switch",
343
+ css: `padding:.3rem .8rem;border:1px solid ${v("line")};border-radius:999px;color:${v("text")};text-decoration:none`,
344
+ states: [{ selector: "[aria-current=page]", about: "The choice shown now", css: `background:${v("accent")};border-color:${v("accent")};color:${v("accent-text")}` }, { selector: ":focus-visible", about: "Has focus", css: FOCUS }],
345
+ },
346
+ { name: "wb-ui-design", element: "div", about: "Design mode's bar across the top of the page", css: `position:sticky;top:0;z-index:50;display:flex;flex-wrap:wrap;gap:.5rem 1rem;align-items:end;padding:.6rem 1rem;background:${v("surface")};color:${v("text")};border-bottom:2px solid ${v("accent")};font-size:.9rem` },
347
+ { name: "wb-ui-design-name", element: "strong", about: "Design mode's name", css: "align-self:center" },
348
+ { name: "wb-ui-design-field", element: "label", about: "One choice on the bar, with its name", css: "display:grid;gap:.15rem" },
349
+ { name: "wb-ui-design-label", element: "span", about: "A choice's name", css: `font-size:.75rem;color:${v("muted")};padding:0` },
350
+ { name: "wb-ui-design-select", element: "select", about: "A list of choices", css: `font:inherit;padding:.25rem .5rem;border:1px solid ${v("line")};border-radius:6px;background:${v("surface")};color:${v("text")}`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
351
+ { name: "wb-ui-design-pair", element: "fieldset", about: "Two choices side by side, such as light or dark", css: "display:flex;gap:.6rem;align-items:center;margin:0;padding:0;border:0" },
352
+ { name: "wb-ui-design-choice", element: "label", about: "One of a pair", css: "display:inline-flex;gap:.25rem;align-items:center" },
353
+ { name: "wb-ui-design-radio", element: "input", about: "A round choice", css: `margin:0;accent-color:${v("accent")}`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
354
+ { name: "wb-ui-design-option", element: "option", about: "One choice in a list", css: "font:inherit" },
355
+ { name: "wb-ui-design-actions", element: "span", about: "Keep, Put back and Leave", css: "display:flex;flex-wrap:wrap;gap:.5rem;margin-left:auto" },
356
+ { name: "wb-ui-design-keep", element: "button", about: "Keeps what was tried", css: `font:inherit;padding:.35rem .9rem;border:0;border-radius:6px;background:${v("accent")};color:${v("accent-text")};cursor:pointer`, states: [{ selector: ":disabled", about: "Nothing to keep", css: "opacity:.55;cursor:default" }, { selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
357
+ { name: "wb-ui-design-button", element: "button", about: "Put back or Leave design mode", css: `font:inherit;padding:.35rem .9rem;border:1px solid ${v("line")};border-radius:6px;background:${v("surface")};color:${v("text")};cursor:pointer`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
358
+ { name: "wb-ui-design-note", element: "p", about: "Says only the admin sees what they try", css: `flex-basis:100%;margin:0;font-size:.8rem;color:${v("muted")}` },
359
+ { name: "wb-ui-design-badge", element: "details", about: "The badge on a tool: its layout now, and the others to try", css: `position:relative;z-index:40;margin:0 0 .5rem;font-size:.85rem;color:${v("text")}` },
360
+ { name: "wb-ui-design-badge-name", element: "summary", about: "The tool and its layout now", css: `display:inline-block;padding:.2rem .7rem;border:1px dashed ${v("accent")};border-radius:999px;background:${v("surface")};cursor:pointer`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
361
+ { name: "wb-ui-design-menu", element: "div", about: "The tool's layouts and where a choice applies", css: `position:absolute;top:100%;left:0;width:min(22rem,90vw);display:grid;gap:.5rem;margin-top:.3rem;padding:.6rem;background:${v("surface")};border:1px solid ${v("line")};border-radius:8px;box-shadow:0 6px 24px rgb(0 0 0 / .15)` },
362
+ { name: "wb-ui-design-list", element: "ul", about: "The tool's layouts", css: "display:grid;gap:.3rem;margin:0;padding:0;list-style:none" },
363
+ { name: "wb-ui-design-item", element: "li", about: "One layout", css: "margin:0" },
364
+ { name: "wb-ui-design-pick", element: "button", about: "Tries the layout", css: `display:grid;gap:.1rem;width:100%;text-align:left;font:inherit;padding:.4rem .6rem;border:1px solid ${v("line")};border-radius:6px;background:${v("surface")};color:${v("text")};cursor:pointer`, states: [{ selector: "[aria-pressed=true]", about: "The layout shown now", css: `border-color:${v("accent")};box-shadow:inset 3px 0 0 ${v("accent")}` }, { selector: ":disabled", about: "Can't be tried in place", css: "opacity:.6;cursor:default" }, { selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
365
+ { name: "wb-ui-design-pick-title", element: "span", about: "The layout's name", css: "font-weight:700" },
366
+ { name: "wb-ui-design-pick-about", element: "span", about: "What the layout is good for", css: `font-size:.8rem;color:${v("muted")}` },
367
+ { name: "wb-ui-design-pick-why", element: "span", about: "Why it can't be tried here", css: `font-size:.8rem;color:${v("muted")};font-style:italic` },
368
+ { name: "wb-ui-design-phone", element: "div", about: "The page at a phone's width, over the page", css: `position:fixed;inset:4.5rem 0 0;z-index:45;display:grid;justify-items:center;padding:1rem;background:rgb(0 0 0 / .45)` },
369
+ { name: "wb-ui-design-frame", element: "iframe", about: "The page itself, 390 pixels wide", css: "width:390px;max-width:100%;height:100%;border:0;border-radius:12px;background:#fff" },
370
+ { name: "wb-ui-look-live", element: "p", about: "On the live site: where the other looks show", css: `margin:0;color:${v("muted")}` },
371
+ { name: "wb-ui-look-grid", element: "div", about: "The looks side by side, as many as fit", css: "display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,22rem),1fr));gap:1rem" },
372
+ { name: "wb-ui-look", element: "figure", about: "One look: its name and the page drawn in it", css: `margin:0;display:grid;border:1px solid ${v("line")};border-radius:${v("corner")};overflow:hidden` },
373
+ { name: "wb-ui-look-caption", element: "figcaption", about: "The look's name and feel", css: `display:flex;flex-wrap:wrap;gap:.25rem .5rem;align-items:baseline;padding:.5rem .9rem;border-bottom:1px solid ${v("line")}` },
374
+ { name: "wb-ui-look-title", element: "span", about: "The look's name", css: "font-weight:700" },
375
+ { name: "wb-ui-look-in-use", element: "span", about: "Marks the look the site uses now", css: `font-size:.8rem;padding:.05rem .5rem;border-radius:999px;background:${v("accent")};color:${v("accent-text")}` },
376
+ { name: "wb-ui-look-about", element: "span", about: "How the look feels", css: `flex-basis:100%;font-size:.85rem;color:${v("muted")}` },
377
+ { name: "wb-ui-look-frame", element: "iframe", about: "The page itself, in the look", css: "display:block;width:100%;height:26rem;border:0;background:#fff" },
378
+ { name: "wb-ui-look-open", element: "a", about: "Opens the page in the look on its own", css: `padding:.5rem .9rem;font-size:.85rem;color:${v("accent")}`, states: [{ selector: ":focus-visible", about: "Has focus", css: FOCUS }] },
336
379
  ],
337
380
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-ui",
3
- "version": "0.13.2",
3
+ "version": "0.14.0",
4
4
  "description": "Workbench pages: one dark look, a top bar with the environment tag, cards, outcome pills, and one format for times, money and durations.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",