@mccaskie-labs/workbench-site 0.9.0 → 0.11.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,21 @@
1
1
  # @mccaskie-labs/workbench-site
2
2
 
3
+ ## 0.11.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Default pages step 2 (`docs/default-pages.md` decision 4): Admin home (recipe version 2) is the admins' dashboard. It shows what needs them now, then the admin menu. A recipe can have a `needsYou` count: a function in one of its files that the dashboard calls with (env, ctx). The generated `src/pages/needs.ts` (rewritten on each add) reads every count at once, and one that fails shows as "can't be counted" while the others still show.
8
+ - Enquiries (recipe version 2) is the first count: `src/pages/enquiry-count.ts` counts the enquiries not yet deleted, as the signed-in admin. It is written for any site with the Enquiries page, including one built before it existed.
9
+ - The `needsYou` section (`wb-site-needs-*` classes, with a sample for the style guide). The generated pages test checks that a new enquiry shows as a count on `/admin`.
10
+
11
+ ## 0.10.0
12
+
13
+ ### Minor Changes
14
+
15
+ - Default pages step 1 (`docs/default-pages.md`): three new recipes, Questions and answers (`faq`, `/faq`), Accessibility (`accessibility`, `/accessibility`) and Something went wrong (`error`, no address, status 500).
16
+ - Every recipe has a `tier`: `always` (built without asking), `ticked` (suggested) or `offered` (shown unticked). Only About, Questions and answers and Accessibility are not always. `npx workbench-site add` with no pages named builds the always set (`alwaysSet()`), members pages left out; `list` shows each page's tier.
17
+ - `src/pages/index.ts` exports `errorPage(request, env)`, which draws Something went wrong in the site's look with status 500, never cached. The template's `src/index.ts` calls it when answering throws, and its starter `src/pages/index.ts` has it too: a project on an older template keeps its plain error until it takes the template update. The generated pages test checks a page that throws shows it.
18
+
3
19
  ## 0.9.0
4
20
 
5
21
  ### Minor Changes
package/README.md CHANGED
@@ -3,12 +3,17 @@
3
3
  A Workbench project's standard pages (`docs/site-planner.md`). Workbench builds the pages; the project's Claude goes over them with the owner and changes what they want.
4
4
 
5
5
  ```sh
6
- npx workbench-site list # the pages it can build
7
- npx workbench-site add home about contact # build them into this project
6
+ npx workbench-site list # the pages it can build, and which are asked about
7
+ npx workbench-site add # build the pages every project has, without asking
8
+ npx workbench-site add about faq # and the ones the owner kept
8
9
  npx workbench-site check # site.json matches the pages, every word is there
9
10
  npx workbench-site check --live # and no [fill-in] is left, before going live
10
11
  ```
11
12
 
13
+ Every page has a tier (`docs/default-pages.md` §3). Always pages are built without asking: Home, Contact, Not found, Something went wrong (the site's own error page, shown when a page breaks), Admin home, Enquiries, Style guide, Looks and Design mode. The owner is asked about three: About and Questions and answers (ticked) and Accessibility (not ticked).
14
+
15
+ Admin home is the admins' dashboard: what needs them now (each page with a "needs you" count, Enquiries first, from `src/pages/needs.ts`), then every admin page.
16
+
12
17
  `add` writes, in a project made from Workbench's template:
13
18
 
14
19
  | File | What it is |
package/dist/builder.d.ts CHANGED
@@ -25,7 +25,7 @@ export interface BuildOptions {
25
25
  read: (path: string) => string | undefined;
26
26
  /** Lists a project folder's file names; undefined or empty when it doesn't exist. */
27
27
  list?: (dir: string) => readonly string[] | undefined;
28
- /** The recipe ids to add. */
28
+ /** The recipe ids to add. Empty builds the always set (alwaysSet). */
29
29
  add: readonly string[];
30
30
  /** This package's version, written into the page files and the project's dependency. */
31
31
  version: string;
@@ -49,7 +49,13 @@ export interface BuildResult {
49
49
  /** True when a form's answers file was written, so `npm run forms` must run. */
50
50
  forms: boolean;
51
51
  }
52
- /** Builds the chosen recipes into the project. */
52
+ /**
53
+ * The pages every project gets without being asked (docs/default-pages.md §3):
54
+ * the always tier, members pages left out (they come when the project has
55
+ * members, default pages step 4).
56
+ */
57
+ export declare function alwaysSet(catalogue?: readonly Recipe[]): string[];
58
+ /** Builds the chosen recipes into the project; with none chosen, the always set. */
53
59
  export declare function buildSite(o: BuildOptions): BuildResult;
54
60
  /** One problem with the site's record, its page files or their words. */
55
61
  export interface SiteCheckInput {
package/dist/builder.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // It reads the project's files through `read` and returns what to write; the
8
8
  // CLI (cli.ts) does the disk. A page already in workbench/site.json is never
9
9
  // written again: once built, it is the project's.
10
- import { recipeKeys, recipeProblems, SECTION_FUNCTIONS, STORE_SECTIONS, UI_SECTIONS } from "./recipe.js";
10
+ import { recipeKeys, recipeProblems, SECTION_FUNCTIONS, STORE_SECTIONS, UI_SECTIONS, UNADDRESSED } from "./recipe.js";
11
11
  import { RECIPES } from "./recipes/index.js";
12
12
  export const SITE_FILE = "workbench/site.json";
13
13
  const PACKAGE = "@mccaskie-labs/workbench-site";
@@ -20,7 +20,15 @@ function readJson(read, path) {
20
20
  return undefined;
21
21
  return JSON.parse(text);
22
22
  }
23
- /** Builds the chosen recipes into the project. */
23
+ /**
24
+ * The pages every project gets without being asked (docs/default-pages.md §3):
25
+ * the always tier, members pages left out (they come when the project has
26
+ * members, default pages step 4).
27
+ */
28
+ export function alwaysSet(catalogue = RECIPES) {
29
+ return catalogue.filter((r) => r.tier === "always" && r.area !== "members" && r.area !== "legal").map((r) => r.id);
30
+ }
31
+ /** Builds the chosen recipes into the project; with none chosen, the always set. */
24
32
  export function buildSite(o) {
25
33
  const catalogue = o.catalogue ?? RECIPES;
26
34
  const base = o.base ?? "en-AU";
@@ -71,8 +79,8 @@ export function buildSite(o) {
71
79
  }
72
80
  added.push(id);
73
81
  };
74
- for (const id of o.add)
75
- visit(id, true);
82
+ for (const id of o.add.length ? o.add : alwaysSet(catalogue))
83
+ visit(id, o.add.length > 0);
76
84
  if (problems.length)
77
85
  return fail();
78
86
  const pages = [...site.pages];
@@ -82,8 +90,9 @@ export function buildSite(o) {
82
90
  problems.push(`${id} would be at ${r.path}, where ${pages.find((p) => p.path === r.path).recipe} already is.`);
83
91
  continue;
84
92
  }
85
- if (r.path === null && pages.some((p) => p.path === null)) {
86
- problems.push(`${id} would be the page shown when no other answers, which ${pages.find((p) => p.path === null).recipe} already is.`);
93
+ const same = r.path === null ? pages.find((p) => p.path === null && (byId.get(p.recipe)?.status ?? 404) === r.status) : undefined;
94
+ if (same) {
95
+ problems.push(`${id} would be the ${UNADDRESSED[r.status]} page, which ${same.recipe} already is.`);
87
96
  continue;
88
97
  }
89
98
  if (o.read(fileOf(id)) !== undefined) {
@@ -102,13 +111,22 @@ export function buildSite(o) {
102
111
  const helper = o.read("src/pages/site.ts");
103
112
  if (helper === undefined || (helper !== SITE_HELPER && PAST_HELPERS.has(fnv(helper))))
104
113
  writes["src/pages/site.ts"] = SITE_HELPER;
105
- writes["src/pages/index.ts"] = indexFile(pages);
114
+ writes["src/pages/index.ts"] = indexFile(pages, byId);
106
115
  writes["src/pages/nav.ts"] = navFile(pages, byId);
107
- writes["test/pages.test.ts"] = testFile(base, pages);
116
+ const dashboard = pages.some((p) => byId.get(p.recipe)?.sections.some((x) => x.kind === "needs-you"));
117
+ if (dashboard)
118
+ writes["src/pages/needs.ts"] = needsFile(pages, byId);
119
+ writes["test/pages.test.ts"] = testFile(base, pages, byId);
108
120
  // What the pages need besides their files: each written once, then the project's.
109
121
  let forms = false;
110
122
  const migrations = [];
111
123
  const stamp = (o.now ?? new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
124
+ // A count file comes with any page on the site that has one, even one built before it existed.
125
+ for (const p of pages) {
126
+ const n = byId.get(p.recipe)?.needsYou;
127
+ if (n && o.read(n.file) === undefined && !(n.file in writes))
128
+ writes[n.file] = byId.get(p.recipe).files[n.file];
129
+ }
112
130
  for (const id of added) {
113
131
  const r = byId.get(id);
114
132
  for (const [path, text] of Object.entries(r.files ?? {})) {
@@ -223,6 +241,12 @@ function sectionCode(s, pathOf, self) {
223
241
  add("signedIn", `w(${JSON.stringify(s.signedIn)}, { email: ctx.user?.email ?? "" })`);
224
242
  add("signOut", w(s.signOut));
225
243
  break;
244
+ case "needs-you":
245
+ add("heading", s.heading && w(s.heading));
246
+ add("items", "needs.map((n) => ({ ...n, label: w(n.label) }))");
247
+ add("none", w(s.none));
248
+ add("unavailable", w(s.unavailable));
249
+ break;
226
250
  case "admin-menu":
227
251
  add("heading", s.heading && w(s.heading));
228
252
  add("items", `ADMIN_MENU.filter(([, href]) => href !== ${JSON.stringify(self)}).map(([label, href, about]) => ({ title: w(label), href, body: w(about) }))`);
@@ -280,7 +304,8 @@ function pageFile(r, version, base, pathOf) {
280
304
  const usesMenu = sections.some(([s]) => s.kind === "admin-menu");
281
305
  const looks = sections.some(([s]) => s.kind === "look-preview");
282
306
  const design = sections.some(([s]) => s.kind === "design-switch");
283
- const block = list || guide;
307
+ const needs = sections.some(([s]) => s.kind === "needs-you");
308
+ const block = list || guide || needs;
284
309
  const area = r.area === "members" || r.area === "admin" ? `, area: ${JSON.stringify(r.area)}` : "";
285
310
  const prefix = `page.${r.id.replace(/-/g, "_")}.`;
286
311
  const frame = r.frames[0];
@@ -302,6 +327,7 @@ function pageFile(r, version, base, pathOf) {
302
327
  ...(looks || design ? [`import { appConfig } from "../config.ts";`] : []),
303
328
  ...(looks ? [`import { BRAND } from "../lib/brand.ts";`] : []),
304
329
  ...(usesMenu || looks ? [`import { ${[...(usesMenu ? ["ADMIN_MENU"] : []), ...(looks ? ["MENU"] : [])].join(", ")} } from "./nav.ts";`] : []),
330
+ ...(needs ? [`import { readNeeds } from "./needs.ts";`] : []),
305
331
  `import { sitePage, type SitePage } from "./site.ts";`,
306
332
  "",
307
333
  `export const ${camel(r.id)}: SitePage = {`,
@@ -310,9 +336,11 @@ function pageFile(r, version, base, pathOf) {
310
336
  ` access: ${JSON.stringify(r.area === "legal" ? "public" : r.area)},`,
311
337
  ...(list
312
338
  ? [" render: async (request, env, ctx) => {", " const enquiries = await listEnquiries(env, ctx);"]
313
- : guide
314
- ? [" render: (request, env) => {", " // ?view=light, dark or admin: the switch at the top of the guide.", " const view = guideView(request.url);"]
315
- : [` render: (request, env${usesCtx ? ", ctx" : ""}) =>`]),
339
+ : needs
340
+ ? [" render: async (request, env, ctx) => {", " // Each tool's count, read at once (src/pages/needs.ts).", " const needs = await readNeeds(env, ctx);"]
341
+ : guide
342
+ ? [" render: (request, env) => {", " // ?view=light, dark or admin: the switch at the top of the guide.", " const view = guideView(request.url);"]
343
+ : [` render: (request, env${usesCtx ? ", ctx" : ""}) =>`]),
316
344
  ` ${block ? "return " : ""}sitePage(request, env, { frame: ${JSON.stringify(frame)}, title: ${JSON.stringify(r.pageTitle)}${r.status && r.status !== 200 ? `, status: ${r.status}` : ""}${area}${guide ? `, view, stylesheets: [${JSON.stringify(GUIDE_SHEET)}]` : ""} }, (w) => [`,
317
345
  ...sections.map(([, code]) => ` ${code},`),
318
346
  block ? " ]);\n }," : " ]),",
@@ -324,15 +352,19 @@ function pageFile(r, version, base, pathOf) {
324
352
  ];
325
353
  return lines.join("\n");
326
354
  }
327
- function indexFile(pages) {
355
+ /** The page with no address that answers with this status (Not found's 404, Something went wrong's 500). */
356
+ const unaddressed = (pages, byId, status) => pages.find((p) => p.path === null && (byId.get(p.recipe)?.status ?? 404) === status);
357
+ function indexFile(pages, byId) {
358
+ const notFound = unaddressed(pages, byId, 404);
359
+ const broken = unaddressed(pages, byId, 500);
328
360
  const sorted = [...pages].sort((a, b) => (a.recipe < b.recipe ? -1 : a.recipe > b.recipe ? 1 : 0));
329
361
  const members = pages.some((p) => p.access !== "public");
330
362
  const admin = pages.some((p) => p.access === "admin");
331
363
  return [
332
364
  `// Generated by ${PACKAGE} from workbench/site.json: \`npx workbench-site add <page>\``,
333
365
  "// rewrites it. Each page's own file is the project's. src/index.ts hands",
334
- "// every request the app's own routes didn't answer to sitePages, and one no",
335
- "// page answers to notFoundPage. A page's access is checked here, before it",
366
+ "// every request the app's own routes didn't answer to sitePages, one no",
367
+ "// page answers to notFoundPage, and one that threw to errorPage. A page's access is checked here, before it",
336
368
  "// is drawn: members pages need the app's sign-in, admin pages one of the",
337
369
  "// app's admins (the same check as Brand settings).",
338
370
  "",
@@ -354,10 +386,29 @@ function indexFile(pages) {
354
386
  "}",
355
387
  "",
356
388
  "/** The page shown when no other answers (its status is 404); null when the site has none. */",
357
- "export async function notFoundPage(request: Request, env: Env, _url: URL): Promise<Response | null> {",
358
- " const page = PAGES.find((p) => p.path === null);",
359
- ' if (!page || (request.method !== "GET" && request.method !== "HEAD")) return null;',
360
- " return serve(page, request, env);",
389
+ `export async function notFoundPage(${notFound ? "request" : "_request"}: Request, ${notFound ? "env" : "_env"}: Env, _url: URL): Promise<Response | null> {`,
390
+ ...(notFound
391
+ ? [' if (request.method !== "GET" && request.method !== "HEAD") return null;', ` return serve(${camel(notFound.recipe)}, request, env);`]
392
+ : [" return null;"]),
393
+ "}",
394
+ "",
395
+ "/**",
396
+ " * The page shown when answering threw (its status is 500), for any method; null",
397
+ " * when the site has none, or it can't be drawn either. Never kept by a cache.",
398
+ " */",
399
+ `export async function errorPage(${broken ? "request" : "_request"}: Request, ${broken ? "env" : "_env"}: Env): Promise<Response | null> {`,
400
+ ...(broken
401
+ ? [
402
+ " try {",
403
+ ` const res = await ${camel(broken.recipe)}.render(new Request(request.url, { headers: request.headers }), env, { user: null });`,
404
+ " const headers = new Headers(res.headers);",
405
+ ' headers.set("cache-control", "private, no-store");',
406
+ " return new Response(res.body, { status: 500, headers });",
407
+ " } catch {",
408
+ " return null;",
409
+ " }",
410
+ ]
411
+ : [" return null;"]),
361
412
  "}",
362
413
  "",
363
414
  "/** Checks who may open the page, then draws it, or takes its form's POST. */",
@@ -391,6 +442,41 @@ function indexFile(pages) {
391
442
  "",
392
443
  ].join("\n");
393
444
  }
445
+ /** src/pages/needs.ts: the admin dashboard's counts, one per page on the site that has one, in the admin menu's order. */
446
+ function needsFile(pages, byId) {
447
+ const counts = pages
448
+ .flatMap((p) => {
449
+ const r = byId.get(p.recipe);
450
+ return r?.needsYou && p.path !== null ? [{ order: r.menu?.admin ?? 1000, label: r.needsYou.label, href: p.path, file: r.needsYou.file, fn: r.needsYou.fn }] : [];
451
+ })
452
+ .sort((a, b) => a.order - b.order);
453
+ const imports = [...new Map(counts.map((c) => [`${c.fn}|${c.file}`, c])).values()].map((c) => `import { ${c.fn} } from "./${c.file.replace(/^src\/pages\//, "")}";`);
454
+ return [
455
+ `// Generated by ${PACKAGE} from workbench/site.json and its recipes: \`npx workbench-site add <page>\``,
456
+ "// rewrites it. What needs the site's admins, for Admin home's \"needs you\"",
457
+ "// (docs/default-pages.md decision 4): each page with a count, and where it's",
458
+ "// dealt with.",
459
+ "",
460
+ ...imports,
461
+ `import type { PageContext } from "./site.ts";`,
462
+ "",
463
+ "/** One count: its word's key, its page, and how many wait (null when they can't be counted). */",
464
+ "export interface Need {",
465
+ " label: string;",
466
+ " href: string;",
467
+ " count: number | null;",
468
+ "}",
469
+ "",
470
+ "const NEEDS: readonly { label: string; href: string; count: (env: Env, ctx: PageContext) => Promise<number | null> }[] = " +
471
+ (counts.length ? `[\n${counts.map((c) => ` { label: ${JSON.stringify(c.label)}, href: ${JSON.stringify(c.href)}, count: ${c.fn} },`).join("\n")}\n];` : "[];"),
472
+ "",
473
+ "/** Every count, read at once; one that fails is null, and the others still show. */",
474
+ "export async function readNeeds(env: Env, ctx: PageContext): Promise<Need[]> {",
475
+ " return Promise.all(NEEDS.map(async (n) => ({ label: n.label, href: n.href, count: await n.count(env, ctx).catch(() => null) })));",
476
+ "}",
477
+ "",
478
+ ].join("\n");
479
+ }
394
480
  function navFile(pages, byId) {
395
481
  const entries = (place) => pages
396
482
  .map((p) => ({ p, menu: byId.get(p.recipe)?.menu }))
@@ -422,8 +508,12 @@ function navFile(pages, byId) {
422
508
  "",
423
509
  ].join("\n");
424
510
  }
425
- function testFile(base, pages) {
511
+ function testFile(base, pages, byId) {
512
+ const status = Object.fromEntries(pages.filter((p) => p.path === null).map((p) => [p.recipe, byId.get(p.recipe)?.status ?? 404]));
513
+ const broken = unaddressed(pages, byId, 500);
514
+ const sample = pages.find((p) => p.access === "public" && p.path !== null);
426
515
  const enquiries = pages.some((p) => p.recipe === "enquiries");
516
+ const dashboard = pages.find((p) => p.path !== null && byId.get(p.recipe)?.sections.some((x) => x.kind === "needs-you"));
427
517
  const form = pages.find((p) => p.access === "public" && p.path !== null && p.recipe === "contact");
428
518
  const guide = pages.find((p) => p.recipe === "style-guide" && p.path !== null);
429
519
  return `// Generated by ${PACKAGE}: every page in workbench/site.json answers, in
@@ -432,9 +522,9 @@ function testFile(base, pages) {
432
522
  // workbench/site.json matches the page files (check:site).
433
523
 
434
524
  import { siteProblems } from "${PACKAGE}";
435
- import { ${enquiries ? "beforeEach, " : ""}describe, expect, it${enquiries ? ", vi" : ""} } from "vitest";
525
+ import { ${enquiries ? "beforeEach, " : ""}describe, expect, it${enquiries || (broken && sample) ? ", vi" : ""} } from "vitest";
436
526
  import worker from "../src/index.ts";
437
- ${enquiries ? 'import { enquiryStore } from "../src/pages/enquiry-store.ts";\n' : ""}import { PAGES } from "../src/pages/index.ts";
527
+ ${enquiries ? 'import { enquiryCount } from "../src/pages/enquiry-count.ts";\nimport { enquiryStore } from "../src/pages/enquiry-store.ts";\n' : ""}import { PAGES } from "../src/pages/index.ts";
438
528
  import { SITE_LAYOUT as LAYOUT } from "../src/site-layout.generated.ts";
439
529
  import site from "../workbench/site.json";
440
530
  import strings from "../strings/strings.${base}.json";
@@ -447,20 +537,23 @@ const SESSION_SECRET = "s".repeat(43);
447
537
  const production = () => testEnv({ WORKBENCH_ENV: "production", WORKBENCH_GATEWAY_KEY: FAKE.prdKey, ACCESS_AUD: AUD, SESSION_SECRET });
448
538
  const staging = () => testEnv({ WORKBENCH_ENV: "staging", WORKBENCH_GATEWAY_KEY: FAKE.stgKey, ACCESS_AUD: AUD, SESSION_SECRET });
449
539
  const MISSING = "/no-page-is-here-" + "x".repeat(8);
540
+ /** What each page answers with: 200, but 404 for Not found and 500 for Something went wrong. */
541
+ const STATUS: Readonly<Record<string, number>> = ${JSON.stringify(status)};
450
542
  const files = import.meta.glob<string>("../src/pages/*.ts", { query: "?raw", import: "default", eager: true });
451
543
 
452
544
  describe("site pages", () => {
453
- ${enquiries ? " // The enquiries table isn't reached: each test says what it holds.\n beforeEach(() => void vi.spyOn(enquiryStore, \"list\").mockResolvedValue([]));\n\n" : ""} it("workbench/site.json matches the page files and the strings catalogue (check:site)", () => {
545
+ ${enquiries ? " // The enquiries table isn't reached: each test says what it holds.\n beforeEach(() => {\n vi.spyOn(enquiryStore, \"list\").mockResolvedValue([]);\n vi.spyOn(enquiryCount, \"count\").mockResolvedValue(0);\n });\n\n" : ""} it("workbench/site.json matches the page files and the strings catalogue (check:site)", () => {
454
546
  const byPath = Object.fromEntries(Object.entries(files).map(([path, text]) => [path.replace(/^\\.\\.\\//, ""), text]));
455
547
  expect(siteProblems({ site, strings, files: byPath })).toEqual([]);
456
548
  });
457
549
 
458
550
  for (const page of PAGES) {
459
551
  const path = page.path ?? MISSING;
552
+ const status = STATUS[page.recipe] ?? 200;
460
553
  it(\`\${page.recipe} draws in the project's look\`, async () => {
461
554
  const user = page.access === "public" ? null : { id: "user-1", email: "sam@example.com" };
462
555
  const res = await page.render(new Request(\`https://example.com\${path}\`), production(), user ? { user, accessToken: "token" } : { user });
463
- expect(res.status).toBe(page.path === null ? 404 : 200);
556
+ expect(res.status).toBe(status);
464
557
  expect(res.headers.get("content-type")).toContain("text/html");
465
558
  const html = await res.text();
466
559
  expect(html).toMatch(/<html [^>]*class="wb-site[ "]/);
@@ -476,9 +569,12 @@ ${enquiries ? " // The enquiries table isn't reached: each test says what it ho
476
569
  expect(html.includes("wb-ui-admin")).toBe(page.access === "admin" && page.recipe !== "style-guide");
477
570
  });
478
571
 
572
+ // No address opens Something went wrong: its own test is below.
573
+ if (status === 500) continue;
574
+
479
575
  it(\`\${page.recipe} answers at \${path} to whoever may open it\`, async () => {
480
576
  const res = await get(path, production());
481
- if (page.access === "public") expect(res.status).toBe(page.path === null ? 404 : 200);
577
+ if (page.access === "public") expect(res.status).toBe(status);
482
578
  else {
483
579
  // Signed out: sent to sign in, and back here afterwards.
484
580
  expect(res.status).toBe(303);
@@ -490,12 +586,52 @@ ${enquiries ? " // The enquiries table isn't reached: each test says what it ho
490
586
  useTestTeam();
491
587
  expect((await get(path, staging())).status).toBe(403);
492
588
  const res = await get(path, staging(), { "Cf-Access-Jwt-Assertion": await accessToken() });
493
- expect(res.status).toBe(page.access !== "public" ? 303 : page.path === null ? 404 : 200);
589
+ expect(res.status).toBe(page.access !== "public" ? 303 : status);
494
590
  expect(res.headers.get("cache-control")).toBe("private, no-store");
495
591
  });
496
592
  }
497
593
  });
498
- ${enquiries && form ? enquiryTests(form.path) : ""}${guide ? guideTests(guide.path) : ""}`;
594
+ ${enquiries && form ? enquiryTests(form.path) : ""}${guide ? guideTests(guide.path) : ""}${broken && sample ? errorTests(sample.recipe, sample.path) : ""}${enquiries && dashboard ? dashboardTests(dashboard.recipe, dashboard.path) : ""}`;
595
+ }
596
+ /** The admin dashboard's own tests, when the site has it and Enquiries. */
597
+ function dashboardTests(recipe, path) {
598
+ return `
599
+ describe("admin dashboard", () => {
600
+ const page = PAGES.find((p) => p.recipe === ${JSON.stringify(recipe)})!;
601
+ const draw = async () => (await page.render(new Request(\`https://example.com${path}\`), production(), { user: { id: "user-1", email: "a@example.com" }, accessToken: "token" })).text();
602
+
603
+ it("shows a new enquiry as a count, linking to the Enquiries page", async () => {
604
+ const count = vi.spyOn(enquiryCount, "count").mockResolvedValue(3);
605
+ const html = await draw().finally(() => count.mockRestore());
606
+ expect(html).toMatch(/<a class="wb-site-needs-link" href="\\/admin\\/enquiries"><span class="wb-site-needs-count">3<\\/span>/);
607
+ });
608
+
609
+ it("says when nothing needs the admin, and when a count can't be read", async () => {
610
+ const none = vi.spyOn(enquiryCount, "count").mockResolvedValue(0);
611
+ expect(await draw().finally(() => none.mockRestore())).not.toContain("wb-site-needs-items");
612
+ const down = vi.spyOn(enquiryCount, "count").mockResolvedValue(null);
613
+ expect(await draw().finally(() => down.mockRestore())).toContain("wb-site-needs-unknown");
614
+ });
615
+ });
616
+ `;
617
+ }
618
+ /** Something went wrong's own test, when the site has it and a public page to break. */
619
+ function errorTests(recipe, path) {
620
+ return `
621
+ describe("something went wrong", () => {
622
+ it("a page that throws shows the site's own error page, never the error", async () => {
623
+ const page = PAGES.find((p) => p.recipe === ${JSON.stringify(recipe)})!;
624
+ const render = vi.spyOn(page, "render").mockRejectedValue(new Error("a secret detail"));
625
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
626
+ const res = await get(${JSON.stringify(path)}, production()).finally(() => (render.mockRestore(), log.mockRestore()));
627
+ expect(res.status).toBe(500);
628
+ expect(res.headers.get("cache-control")).toBe("private, no-store");
629
+ const html = await res.text();
630
+ expect(html).toMatch(/<html [^>]*class="wb-site[ "]/);
631
+ expect(html).not.toContain("a secret detail");
632
+ });
633
+ });
634
+ `;
499
635
  }
500
636
  /** The style guide's own tests, when the site has it. */
501
637
  function guideTests(path) {
@@ -743,7 +879,7 @@ export function siteProblems(i) {
743
879
  out.push(`${where}: its file ${p.file} is missing`);
744
880
  if (!["built", "checked", "changed"].includes(p.state))
745
881
  out.push(`${where}: state ${String(p.state)} isn't built, checked or changed`);
746
- const key = p.path ?? "(not found)";
882
+ const key = p.path ?? `(${UNADDRESSED[byId.get(p.recipe)?.status ?? 404] ?? "no address"})`;
747
883
  if (seen.has(key))
748
884
  out.push(`${where}: ${key} is also ${seen.get(key)}'s address`);
749
885
  seen.set(key, p.recipe);
package/dist/cli.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // `npx workbench-site list`
3
3
  // The page recipes this version can build, by group.
4
- // `npx workbench-site add <page>... [--dir <project>] [--no-install]`
5
- // Builds the pages into the project (the current folder by default): one
4
+ // `npx workbench-site add [<page>...] [--dir <project>] [--no-install]`
5
+ // With no pages named, builds the pages every project has without being
6
+ // asked (the always tier, docs/default-pages.md §3). Builds the pages into the project (the current folder by default): one
6
7
  // thin file per page in src/pages/, their words in the strings catalogue,
7
8
  // the routes, the menu, a test per page and workbench/site.json. Then it
8
9
  // installs this package into the project and regenerates
@@ -19,7 +20,8 @@ import { fileURLToPath } from "node:url";
19
20
  import { buildSite, SITE_FILE, siteProblems } from "./builder.js";
20
21
  import { GROUPS } from "./recipe.js";
21
22
  import { RECIPES } from "./recipes/index.js";
22
- const USAGE = ["Usage: workbench-site list", " workbench-site add <page>... [--dir <project>] [--no-install]", " workbench-site check [--live] [--dir <project>]"].join("\n");
23
+ const USAGE = ["Usage: workbench-site list", " workbench-site add [<page>...] [--dir <project>] [--no-install]", " workbench-site check [--live] [--dir <project>]"].join("\n");
24
+ const TIER_NAMES = { always: "always built", ticked: "ask, ticked", offered: "ask, not ticked" };
23
25
  const GROUP_NAMES = { "every-site": "Every site", members: "Members", admin: "Admin", business: "For your business" };
24
26
  function version() {
25
27
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
@@ -53,7 +55,7 @@ export function main(argv, deps = realDeps) {
53
55
  continue;
54
56
  deps.log(`${GROUP_NAMES[g]}:`);
55
57
  for (const r of rs)
56
- deps.log(` ${r.id.padEnd(12)} ${r.path ?? "(any missing address)"} ${r.does}`);
58
+ deps.log(` ${r.id.padEnd(14)} ${(r.path ?? (r.status === 500 ? "(when a page breaks)" : "(any missing address)")).padEnd(20)} ${TIER_NAMES[r.tier].padEnd(16)} ${r.does}`);
57
59
  }
58
60
  return 0;
59
61
  }
@@ -79,7 +81,7 @@ export function main(argv, deps = realDeps) {
79
81
  deps.log(`✓ ${SITE_FILE} matches the page files and their words${live ? ", and no word waits for the owner" : ""}.`);
80
82
  return problems.length ? 1 : 0;
81
83
  }
82
- if (command !== "add" || !ids.length || ids.some((i) => i.startsWith("-"))) {
84
+ if (command !== "add" || ids.some((i) => i.startsWith("-"))) {
83
85
  deps.error(USAGE);
84
86
  return 2;
85
87
  }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { frame, FOOTERS, FRAMES, HEADERS, type FooterStyle, type FrameLayout, type FrameName, type FrameOptions, type HeaderStyle, type MenuLink } from "./frames.ts";
2
2
  export { escape } from "./html.ts";
3
- export { account, callToAction, DESIGN_COOKIE, designModeOn, designModePost, designSwitch, details, enquiryList, formSection, hero, HERO_ARRANGEMENTS, list, picture, text, type AccountOptions, type Action, type CallToActionOptions, type DesignSwitchOptions, type DetailRow, type DetailsOptions, type Enquiry, type EnquiryListOptions, type FormSectionOptions, type HeroArrangement, type HeroOptions, type ListItem, type ListOptions, type Picture, type PictureOptions, type TextOptions, } from "./sections.ts";
4
- export { recipeKeys, recipeProblems, type ActionSpec, type Area, type Group, type Recipe, type SectionSpec } from "./recipe.ts";
3
+ export { account, callToAction, DESIGN_COOKIE, designModeOn, designModePost, designSwitch, details, enquiryList, needsYou, formSection, hero, HERO_ARRANGEMENTS, list, picture, text, type AccountOptions, type Action, type CallToActionOptions, type DesignSwitchOptions, type DetailRow, type DetailsOptions, type Enquiry, type EnquiryListOptions, type NeedsYouItem, type NeedsYouOptions, type FormSectionOptions, type HeroArrangement, type HeroOptions, type ListItem, type ListOptions, type Picture, type PictureOptions, type TextOptions, } from "./sections.ts";
4
+ export { recipeKeys, recipeProblems, TIERS, type ActionSpec, type Area, type Group, type Recipe, type SectionSpec, type Tier } from "./recipe.ts";
5
5
  export { RECIPES } from "./recipes/index.ts";
6
- export { buildSite, SITE_FILE, siteProblems, type BuildOptions, type BuildResult, type SiteCheckInput, type SitePageRecord, type SiteRecord } from "./builder.ts";
6
+ export { alwaysSet, buildSite, SITE_FILE, siteProblems, type BuildOptions, type BuildResult, type SiteCheckInput, type SitePageRecord, type SiteRecord } from "./builder.ts";
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // project, and the page frames and sections those files call.
4
4
  export { frame, FOOTERS, FRAMES, HEADERS } from "./frames.js";
5
5
  export { escape } from "./html.js";
6
- export { account, callToAction, DESIGN_COOKIE, designModeOn, designModePost, designSwitch, details, enquiryList, formSection, hero, HERO_ARRANGEMENTS, list, picture, text, } from "./sections.js";
7
- export { recipeKeys, recipeProblems } from "./recipe.js";
6
+ export { account, callToAction, DESIGN_COOKIE, designModeOn, designModePost, designSwitch, details, enquiryList, needsYou, formSection, hero, HERO_ARRANGEMENTS, list, picture, text, } from "./sections.js";
7
+ export { recipeKeys, recipeProblems, TIERS } from "./recipe.js";
8
8
  export { RECIPES } from "./recipes/index.js";
9
- export { buildSite, SITE_FILE, siteProblems } from "./builder.js";
9
+ export { alwaysSet, buildSite, SITE_FILE, siteProblems } from "./builder.js";
package/dist/recipe.d.ts CHANGED
@@ -54,6 +54,13 @@ export type SectionSpec = {
54
54
  kind: "admin-menu";
55
55
  heading?: WordKey;
56
56
  }
57
+ /** What needs the admin now: each page's "needs you" count (Recipe.needsYou), linking to it. Admin pages only. */
58
+ | {
59
+ kind: "needs-you";
60
+ heading?: WordKey;
61
+ none: WordKey;
62
+ unavailable: WordKey;
63
+ }
57
64
  /** The enquiry form (workbench/forms/enquiry.json), or its thank-you once sent: public pages, with the Enquiries page on the site. `send` is the button's key. */
58
65
  | {
59
66
  kind: "enquiry-form";
@@ -122,6 +129,7 @@ export declare const SECTION_FUNCTIONS: {
122
129
  readonly details: "details";
123
130
  readonly account: "account";
124
131
  readonly "admin-menu": "list";
132
+ readonly "needs-you": "needsYou";
125
133
  readonly "enquiry-form": "enquirySection";
126
134
  readonly enquiries: "enquiriesSection";
127
135
  readonly "style-guide": "styleGuide";
@@ -136,6 +144,16 @@ declare const AREAS: readonly ["public", "members", "admin", "legal"];
136
144
  export type Area = (typeof AREAS)[number];
137
145
  export declare const GROUPS: readonly ["every-site", "members", "admin", "business"];
138
146
  export type Group = (typeof GROUPS)[number];
147
+ /**
148
+ * Whether the owner is asked (docs/default-pages.md §3): always pages are built
149
+ * without asking (`npx workbench-site add` with no pages named builds them),
150
+ * ticked pages are suggested and may be unticked, offered pages are shown
151
+ * unticked.
152
+ */
153
+ export declare const TIERS: readonly ["always", "ticked", "offered"];
154
+ export type Tier = (typeof TIERS)[number];
155
+ /** The statuses a page with no address can answer with: Not found's, and Something went wrong's. */
156
+ export declare const UNADDRESSED: Readonly<Record<number, string>>;
139
157
  export interface Recipe {
140
158
  /** Its name in the catalogue and on the command line: lower case and hyphens. */
141
159
  id: string;
@@ -145,11 +163,13 @@ export interface Recipe {
145
163
  title: string;
146
164
  does: string;
147
165
  group: Group;
166
+ /** Whether the owner is asked about it: always, ticked or offered. */
167
+ tier: Tier;
148
168
  /** Sets the access rule the builder writes: public, members (signed in) or admin (signed in and one of the app's admins). Legal pages come with step 4. */
149
169
  area: Area;
150
- /** Its default address. Null for the page shown when no other answers (Not found). */
170
+ /** Its default address. Null for a page no address opens: Not found (status 404) and Something went wrong (status 500). */
151
171
  path: string | null;
152
- /** The answer's status: 404 for Not found. Defaults to 200. */
172
+ /** The answer's status: 404 for Not found, 500 for Something went wrong. Defaults to 200. */
153
173
  status?: number;
154
174
  /** The frames it can use, its default first. */
155
175
  frames: readonly FrameName[];
@@ -180,6 +200,18 @@ export interface Recipe {
180
200
  files?: Readonly<Record<string, string>>;
181
201
  /** Workbench packages its page needs at least this version of (x.y.z): the builder raises the project's to it. */
182
202
  packages?: Readonly<Record<string, string>>;
203
+ /**
204
+ * Its count on the admin dashboard's "needs you" (docs/default-pages.md
205
+ * decision 4): `fn`, exported by `file` (one of its `files`, written whenever
206
+ * the page is on the site), is called with (env, ctx) and gives how many are
207
+ * waiting, or null when they can't be counted. `label` is one of its words.
208
+ * Admin pages only.
209
+ */
210
+ needsYou?: {
211
+ label: WordKey;
212
+ file: string;
213
+ fn: string;
214
+ };
183
215
  /** Its table, as a Workbench tool's own migration: supabase/migrations/<stamp>_<name>.sql and its down file, written once. */
184
216
  migration?: {
185
217
  name: string;
package/dist/recipe.js CHANGED
@@ -6,13 +6,22 @@
6
6
  import { FRAMES } from "./frames.js";
7
7
  import { HERO_ARRANGEMENTS } from "./sections.js";
8
8
  /** The section functions a page file calls, by kind. Those in STORE_SECTIONS come from the project's src/pages/enquiry-store.ts, the rest from this package. */
9
- export const SECTION_FUNCTIONS = { hero: "hero", text: "text", list: "list", call: "callToAction", details: "details", account: "account", "admin-menu": "list", "enquiry-form": "enquirySection", enquiries: "enquiriesSection", "style-guide": "styleGuide", "look-preview": "lookPreview", "design-switch": "designSwitch" };
9
+ export const SECTION_FUNCTIONS = { hero: "hero", text: "text", list: "list", call: "callToAction", details: "details", account: "account", "admin-menu": "list", "needs-you": "needsYou", "enquiry-form": "enquirySection", enquiries: "enquiriesSection", "style-guide": "styleGuide", "look-preview": "lookPreview", "design-switch": "designSwitch" };
10
10
  /** Sections whose function is in the project's own src/pages/enquiry-store.ts, which the Enquiries recipe writes. */
11
11
  export const STORE_SECTIONS = new Set(["enquiry-form", "enquiries"]);
12
12
  /** Sections whose function comes from workbench-ui, not this package. */
13
13
  export const UI_SECTIONS = new Set(["style-guide", "look-preview"]);
14
14
  const AREAS = ["public", "members", "admin", "legal"];
15
15
  export const GROUPS = ["every-site", "members", "admin", "business"];
16
+ /**
17
+ * Whether the owner is asked (docs/default-pages.md §3): always pages are built
18
+ * without asking (`npx workbench-site add` with no pages named builds them),
19
+ * ticked pages are suggested and may be unticked, offered pages are shown
20
+ * unticked.
21
+ */
22
+ export const TIERS = ["always", "ticked", "offered"];
23
+ /** The statuses a page with no address can answer with: Not found's, and Something went wrong's. */
24
+ export const UNADDRESSED = { 404: "Not found", 500: "Something went wrong" };
16
25
  /** Every word key a section names. */
17
26
  function sectionKeys(s) {
18
27
  switch (s.kind) {
@@ -30,6 +39,8 @@ function sectionKeys(s) {
30
39
  return [s.heading, s.signedIn, s.signOut].filter((k) => !!k);
31
40
  case "admin-menu":
32
41
  return [s.heading].filter((k) => !!k);
42
+ case "needs-you":
43
+ return [s.heading, s.none, s.unavailable].filter((k) => !!k);
33
44
  case "enquiry-form":
34
45
  return [s.heading, s.intro, s.send, s.sent, s.unavailable].filter((k) => !!k);
35
46
  case "enquiries":
@@ -46,7 +57,7 @@ function sectionKeys(s) {
46
57
  export function recipeKeys(r) {
47
58
  const menu = r.menu ? [r.menu.label, r.menu.about].filter((k) => !!k) : [];
48
59
  const links = (r.links ?? []).flatMap((l) => [l.label, l.about]);
49
- return [...new Set([r.pageTitle, ...menu, ...links, ...r.sections.flatMap(sectionKeys)])];
60
+ return [...new Set([r.pageTitle, ...menu, ...links, ...(r.needsYou ? [r.needsYou.label] : []), ...r.sections.flatMap(sectionKeys)])];
50
61
  }
51
62
  /** The values a word is given when the page says it. */
52
63
  function valuesFor(r, key) {
@@ -70,8 +81,14 @@ export function recipeProblems(r, catalogue) {
70
81
  p(`area ${r.area} isn't one of ${AREAS.join(", ")}`);
71
82
  if (r.path !== null && !/^\/([a-z0-9-]+(\/[a-z0-9-]+)*)?$/.test(r.path))
72
83
  p(`path ${r.path} must be / or /lower-case-words`);
73
- if (r.path === null && r.status !== 404)
74
- p("a page with no path is the Not found page, so its status is 404");
84
+ if (!TIERS.includes(r.tier))
85
+ p(`tier ${r.tier} isn't one of ${TIERS.join(", ")}`);
86
+ if (r.path === null && !(r.status !== undefined && r.status in UNADDRESSED))
87
+ p("a page with no path is Not found (status 404) or Something went wrong (status 500)");
88
+ if (r.path !== null && r.status !== undefined && r.status !== 200)
89
+ p("a page with an address answers 200");
90
+ if (r.path === null && catalogue.some((c) => c.id !== r.id && c.path === null && c.status === r.status))
91
+ p(`another recipe is already the ${UNADDRESSED[r.status] ?? "unaddressed"} page`);
75
92
  if (!r.frames.length || r.frames.some((f) => !FRAMES.includes(f)))
76
93
  p(`frames must be some of ${FRAMES.join(", ")}`);
77
94
  for (const n of r.needs)
@@ -117,12 +134,14 @@ export function recipeProblems(r, catalogue) {
117
134
  if (r.area === "admin" && (r.path === null || !/^\/admin(\/|$)/.test(r.path)))
118
135
  p("an admin page's address starts /admin");
119
136
  if (r.area !== "public" && r.path === null)
120
- p("the Not found page is public");
137
+ p("a page with no path is public");
121
138
  for (const s of r.sections) {
122
139
  if (s.kind === "account" && r.area !== "members")
123
140
  p("the account section is for members pages");
124
141
  if (s.kind === "admin-menu" && r.area !== "admin")
125
142
  p("the admin menu section is for admin pages");
143
+ if (s.kind === "needs-you" && r.area !== "admin")
144
+ p("the needs-you section is for admin pages");
126
145
  if (s.kind === "enquiries" && r.area !== "admin")
127
146
  p("the enquiries list is for admin pages");
128
147
  if (s.kind === "enquiry-form" && r.area !== "public")
@@ -139,6 +158,14 @@ export function recipeProblems(r, catalogue) {
139
158
  p(`link ${l.href}: only admin pages add admin menu links, to /admin addresses`);
140
159
  if (r.menu && r.path === null)
141
160
  p("a page with no path can't be in the menu");
161
+ if (r.needsYou) {
162
+ if (r.area !== "admin" || r.path === null)
163
+ p("only an admin page has a needs-you count");
164
+ if (!(r.needsYou.file in (r.files ?? {})))
165
+ p(`its needs-you count's file ${r.needsYou.file} isn't one of its files`);
166
+ if (!/^[a-z][A-Za-z0-9]*$/.test(r.needsYou.fn) || !(r.files?.[r.needsYou.file] ?? "").includes(`export async function ${r.needsYou.fn}(`))
167
+ p(`its needs-you file must export async function ${r.needsYou.fn}`);
168
+ }
142
169
  if (r.migration && !/^workbench_site_[a-z0-9_]+$/.test(r.migration.name))
143
170
  p("a migration is named workbench_site_<what>, so Control treats it as a Workbench tool's own");
144
171
  for (const [name, v] of Object.entries(r.packages ?? {}))
@@ -2,13 +2,14 @@
2
2
  // (the client first, then whoever they invite at /admin/brand). Each tool's
3
3
  // own admin list joins the admin menu with its recipe; the template's Brand
4
4
  // settings page is in the menu from the start.
5
- import { ENQUIRY_ANSWERS, ENQUIRY_MIGRATION, ENQUIRY_STORE } from "./enquiries-kit.js";
5
+ import { ENQUIRY_ANSWERS, ENQUIRY_COUNT, ENQUIRY_MIGRATION, ENQUIRY_STORE } from "./enquiries-kit.js";
6
6
  const adminHome = {
7
7
  id: "admin-home",
8
- version: 1,
8
+ version: 2,
9
9
  title: "Admin home",
10
- does: "One page with a link to everything the business's admins look after.",
10
+ does: "The admins' dashboard: what needs them now, such as enquiries to answer, then a link to everything they look after.",
11
11
  group: "admin",
12
+ tier: "always",
12
13
  area: "admin",
13
14
  path: "/admin",
14
15
  frames: ["column"],
@@ -19,14 +20,18 @@ const adminHome = {
19
20
  pageTitle: "page.admin_home.title",
20
21
  sections: [
21
22
  { kind: "hero", heading: "page.admin_home.hero.heading", lead: "page.admin_home.hero.lead" },
23
+ { kind: "needs-you", heading: "page.admin_home.needs.heading", none: "page.admin_home.needs.none", unavailable: "page.admin_home.needs.unavailable" },
22
24
  { kind: "admin-menu", heading: "page.admin_home.pages.heading" },
23
25
  ],
24
26
  words: {
25
27
  "page.admin_home.menu": "Admin",
26
- "page.admin_home.about": "This page: every admin page in one list.",
28
+ "page.admin_home.about": "This page: what needs you, then every admin page in one list.",
27
29
  "page.admin_home.title": "Admin",
28
30
  "page.admin_home.hero.heading": "Admin",
29
31
  "page.admin_home.hero.lead": "Everything you look after on the site. Only the site's admins can see these pages.",
32
+ "page.admin_home.needs.heading": "Needs you",
33
+ "page.admin_home.needs.none": "Nothing needs you right now.",
34
+ "page.admin_home.needs.unavailable": "Can't be counted right now.",
30
35
  "page.admin_home.pages.heading": "Your pages",
31
36
  "page.admin_home.brand.label": "Brand settings",
32
37
  "page.admin_home.brand.about": "Your business's name, colour and logo on emails and PDFs, and who else can manage the site.",
@@ -35,10 +40,11 @@ const adminHome = {
35
40
  };
36
41
  const enquiries = {
37
42
  id: "enquiries",
38
- version: 1,
43
+ version: 2,
39
44
  title: "Enquiries",
40
45
  does: "Every message sent from the Contact page, newest first, with a way to reply.",
41
46
  group: "admin",
47
+ tier: "always",
42
48
  area: "admin",
43
49
  path: "/admin/enquiries",
44
50
  frames: ["column"],
@@ -47,9 +53,11 @@ const enquiries = {
47
53
  menu: { label: "page.enquiries.menu", admin: 10, about: "page.enquiries.about" },
48
54
  files: {
49
55
  "src/pages/enquiry-store.ts": ENQUIRY_STORE,
56
+ "src/pages/enquiry-count.ts": ENQUIRY_COUNT,
50
57
  "workbench/forms/enquiry.json": `${JSON.stringify(ENQUIRY_ANSWERS, null, 2)}\n`,
51
58
  },
52
59
  migration: ENQUIRY_MIGRATION,
60
+ needsYou: { label: "page.enquiries.needs_you", file: "src/pages/enquiry-count.ts", fn: "countEnquiries" },
53
61
  pageTitle: "page.enquiries.title",
54
62
  sections: [
55
63
  { kind: "hero", heading: "page.enquiries.hero.heading", lead: "page.enquiries.hero.lead" },
@@ -58,6 +66,7 @@ const enquiries = {
58
66
  words: {
59
67
  "page.enquiries.menu": "Enquiries",
60
68
  "page.enquiries.about": "Messages people sent from the Contact page.",
69
+ "page.enquiries.needs_you": "Enquiries to answer",
61
70
  "page.enquiries.title": "Enquiries",
62
71
  "page.enquiries.hero.heading": "Enquiries",
63
72
  "page.enquiries.hero.lead": "Messages from the Contact page, newest first. Reply by email or phone, then delete the ones you've dealt with.",
@@ -73,6 +82,7 @@ const styleGuide = {
73
82
  title: "Style guide",
74
83
  does: "Every part of the site on one page, in its look, light and dark, so a change of colours or fonts can be checked at a glance.",
75
84
  group: "admin",
85
+ tier: "always",
76
86
  area: "admin",
77
87
  path: "/admin/style-guide",
78
88
  frames: ["column"],
@@ -115,6 +125,7 @@ const look = {
115
125
  title: "Looks",
116
126
  does: "The site's own pages in every look it may choose, side by side, light or dark, so an owner can see a new look on their real words and pictures before choosing it.",
117
127
  group: "admin",
128
+ tier: "always",
118
129
  area: "admin",
119
130
  path: "/admin/look",
120
131
  frames: ["column"],
@@ -163,6 +174,7 @@ const design = {
163
174
  title: "Design mode",
164
175
  does: "Turns design mode on in this browser, on the test site: a bar on every page to try looks, light or dark and the site layout, and a badge on each tool to try its layouts, on the real pages.",
165
176
  group: "admin",
177
+ tier: "always",
166
178
  area: "admin",
167
179
  path: "/admin/design",
168
180
  frames: ["column"],
@@ -53,3 +53,5 @@ export declare const ENQUIRY_MIGRATION: {
53
53
  };
54
54
  /** src/pages/enquiry-store.ts: written once, then the project's. */
55
55
  export declare const ENQUIRY_STORE = "// The site's enquiries: Contact's form and the Enquiries admin list. Written by\n// @mccaskie-labs/workbench-site once; it's the project's to change.\n//\n// - The form is workbench/forms/enquiry.json (`npm run forms` builds it); its\n// numbers are in the limits register and match site_enquiries' columns.\n// - The table is site_enquiries (supabase/migrations/*_workbench_site_enquiries.sql).\n// Anyone may add a row and only the site's admins read or delete them, as\n// themselves (RLS), so the project needs no secret key.\n// - The page checks the form and Turnstile before it stores an enquiry. The\n// table also takes rows sent straight to the database with the publishable\n// key, which skip both: each is capped in length, and admins delete what\n// they don't want. To close that, add SUPABASE_SECRET_KEY (two-step), send\n// with the service client, and drop the insert policy.\n\nimport { readForm, validate, type Result } from \"@mccaskie-labs/workbench-forms\";\nimport { FORMS_SCRIPT } from \"@mccaskie-labs/workbench-forms/browser\";\nimport { boundsFor } from \"@mccaskie-labs/workbench-forms/limits\";\nimport { formatDateTime } from \"@mccaskie-labs/workbench-country\";\nimport { enquiryList, formSection, type Enquiry } from \"@mccaskie-labs/workbench-site\";\nimport { sameOrigin } from \"@mccaskie-labs/workbench-supabase\";\nimport { escape, FORM_SCRIPT } from \"@mccaskie-labs/workbench-ui\";\nimport { appConfig } from \"../config.ts\";\nimport { FORMS, formContext } from \"../forms/index.ts\";\nimport { formHtml } from \"../forms/page.ts\";\nimport { READERS } from \"../lib/country.ts\";\nimport { dbAs } from \"../lib/db.ts\";\nimport { TURNSTILE_ACTION, TURNSTILE_ORIGIN, turnstileSetup, verifyTurnstile } from \"../lib/turnstile.ts\";\nimport { LIMITS } from \"../limits.ts\";\nimport type { PageContext, SitePage } from \"./site.ts\";\n\n/** The form's state after a submit that didn't go through. */\nexport interface EnquiryState {\n result?: Result;\n input?: Record<string, unknown>;\n /** It couldn't be sent: the check or the database is down. */\n problem?: boolean;\n}\n\nconst SENT = \"sent\";\n/** At most this many shown, newest first. */\nconst SHOWN = 200;\n\nfunction enquiryForm() {\n const form = FORMS.find((f) => f.name === \"enquiry\");\n if (!form) throw new Error(\"There's no enquiry form: run npm run forms (workbench/forms/enquiry.json)\");\n return form;\n}\n\n/** The table, as the Worker reaches it. Tests replace these. */\nexport const enquiryStore = {\n /** Adds one enquiry as anyone (the publishable key). False when the database didn't take it. */\n async send(env: object, values: { name: string; email: string; phone: string | null; message: string }): Promise<boolean> {\n const c = appConfig(env);\n try {\n const res = await fetch(`${c.SUPABASE_URL}/rest/v1/site_enquiries`, {\n method: \"POST\",\n headers: { apikey: c.SUPABASE_PUBLISHABLE_KEY, \"content-type\": \"application/json\", prefer: \"return=minimal\" },\n body: JSON.stringify(values),\n signal: AbortSignal.timeout(10_000),\n });\n if (!res.ok) console.warn(JSON.stringify({ event: \"site_enquiry_failed\", status: res.status }));\n return res.ok;\n } catch {\n console.warn(JSON.stringify({ event: \"site_enquiry_failed\", status: 0 }));\n return false;\n }\n },\n /** The newest enquiries, as the signed-in admin. Null when they can't be read. */\n async list(env: object, accessToken: string): Promise<{ id: string; name: string; email: string; phone: string | null; message: string; received_at: string }[] | null> {\n const { data, error } = await dbAs(env, accessToken).from(\"site_enquiries\").select(\"id, name, email, phone, message, received_at\").order(\"received_at\", { ascending: false }).limit(SHOWN);\n if (error) {\n console.warn(JSON.stringify({ event: \"site_enquiries_read_failed\" }));\n return null;\n }\n return data;\n },\n /** Deletes one, as the signed-in admin. */\n async remove(env: object, accessToken: string, id: string): Promise<boolean> {\n const { error } = await dbAs(env, accessToken).from(\"site_enquiries\").delete().eq(\"id\", id);\n return !error;\n },\n};\n\nexport interface EnquiryWords {\n heading: string;\n intro?: string;\n /** The submit button's key: renderForm looks it up. */\n send: string;\n /** The thank-you. */\n sent: string;\n /** When the check or the database is down. */\n unavailable: string;\n}\n\n/** Contact's enquiry form, or its thank-you once sent. */\nexport function enquirySection(request: Request, env: object, ctx: PageContext, w: EnquiryWords): string {\n if (new URL(request.url).searchParams.get(SENT) === \"1\") return formSection({ id: \"enquiry\", heading: w.heading, done: w.sent });\n const state = (ctx.form ?? {}) as EnquiryState;\n const path = new URL(request.url).pathname;\n let html = formHtml(enquiryForm(), request, env, { action: `${path}#enquiry`, submit: w.send, ...(state.result ? { result: state.result } : {}), ...(state.input ? { input: state.input } : {}) });\n const bot = turnstileSetup(env);\n if (bot.state === \"on\") {\n // Inside the form, so its token is sent with it; shown only when Cloudflare needs the person to click.\n const widget = `<div class=\"cf-turnstile\" data-sitekey=\"${escape(bot.siteKey)}\" data-action=\"${TURNSTILE_ACTION}\" data-appearance=\"interaction-only\" data-theme=\"auto\"></div>`;\n const at = html.lastIndexOf(\"</form>\");\n if (at !== -1) html = html.slice(0, at) + widget + html.slice(at);\n html += `<script src=\"${TURNSTILE_ORIGIN}/turnstile/v0/api.js\" async defer></script>`;\n }\n html += `<script>${FORMS_SCRIPT}</script><script>${FORM_SCRIPT}</script>`;\n return formSection({ id: \"enquiry\", heading: w.heading, ...(w.intro ? { intro: w.intro } : {}), form: html, ...(state.problem ? { problem: w.unavailable } : {}) });\n}\n\n/** Contact's POST: checks the form and Turnstile, stores it, and sends the person back to the thank-you. */\nexport async function takeEnquiry(request: Request, env: Env, ctx: PageContext, page: SitePage): Promise<Response> {\n if (!sameOrigin(request)) return new Response(\"Forbidden\\n\", { status: 403 });\n const again = async (status: number, form: EnquiryState) => {\n const res = await page.render(request, env, { ...ctx, form });\n return new Response(res.body, { status, headers: res.headers });\n };\n let data: FormData;\n try {\n data = await request.formData();\n } catch {\n return again(400, {});\n }\n const form = enquiryForm();\n const input = readForm(form, data);\n const result = validate(form, input, { ...formContext(), bounds: boundsFor(LIMITS, form) });\n if (!result.ok) return again(422, { result, input });\n const bot = turnstileSetup(env);\n if (bot.state === \"missing\") return again(503, { input, problem: true });\n if (bot.state === \"on\" && !(await verifyTurnstile(bot.secret, data.get(\"cf-turnstile-response\"), request, bot.strict)).ok) return again(400, { input, problem: true });\n const v = result.values as Record<string, unknown>;\n const sent = await enquiryStore.send(env, { name: String(v.name), email: String(v.email), phone: typeof v.phone === \"string\" ? v.phone : null, message: String(v.message) });\n if (!sent) return again(503, { input, problem: true });\n const back = new URL(request.url);\n back.search = `?${SENT}=1`;\n back.hash = \"enquiry\";\n return new Response(null, { status: 303, headers: { location: `${back.pathname}${back.search}${back.hash}` } });\n}\n\n/** The enquiries for the admin list, in the readers' time zone. Null when they can't be read. */\nexport async function listEnquiries(env: object, ctx: PageContext): Promise<Enquiry[] | null> {\n if (!ctx.accessToken) return null;\n const rows = await enquiryStore.list(env, ctx.accessToken);\n return rows && rows.map((r) => ({ id: r.id, name: r.name, email: r.email, phone: r.phone, message: r.message, received: formatDateTime(r.received_at, { pack: READERS }) }));\n}\n\nexport interface EnquiryListWords {\n heading?: string;\n empty: string;\n unavailable: string;\n remove: string;\n}\n\n/** The Enquiries admin list. */\nexport function enquiriesSection(request: Request, enquiries: Enquiry[] | null, w: EnquiryListWords): string {\n return enquiryList({ ...w, enquiries, removeAction: new URL(request.url).pathname });\n}\n\n/** The Enquiries page's POST: deletes one, as the admin, and shows the list again. */\nexport async function removeEnquiry(request: Request, env: object, ctx: PageContext): Promise<Response> {\n let id: unknown = null;\n try {\n id = (await request.formData()).get(\"remove\");\n } catch {\n // Nothing to delete: shown the list again.\n }\n if (ctx.accessToken && typeof id === \"string\" && /^[0-9a-f-]{36}$/.test(id)) await enquiryStore.remove(env, ctx.accessToken, id);\n return new Response(null, { status: 303, headers: { location: new URL(request.url).pathname } });\n}\n";
56
+ /** src/pages/enquiry-count.ts: the Enquiries page's count on the admin dashboard. Written once, then the project's. */
57
+ export declare const ENQUIRY_COUNT = "// How many enquiries wait for an answer, for the admin dashboard's \"needs you\"\n// (src/pages/needs.ts). Written by @mccaskie-labs/workbench-site once; it's the\n// project's to change. Every enquiry not yet deleted is waiting: the Enquiries\n// page asks admins to delete the ones they've dealt with.\n\nimport { dbAs } from \"../lib/db.ts\";\nimport type { PageContext } from \"./site.ts\";\n\n/** The table, as the Worker reaches it. Tests replace this. */\nexport const enquiryCount = {\n /** How many, as the signed-in admin (RLS). Null when they can't be counted. */\n async count(env: object, accessToken: string): Promise<number | null> {\n const { count, error } = await dbAs(env, accessToken).from(\"site_enquiries\").select(\"id\", { count: \"exact\", head: true });\n if (error) {\n console.warn(JSON.stringify({ event: \"site_enquiries_count_failed\" }));\n return null;\n }\n return count ?? 0;\n },\n};\n\n/** The count on the admin dashboard. */\nexport async function countEnquiries(env: object, ctx: PageContext): Promise<number | null> {\n return ctx.accessToken ? enquiryCount.count(env, ctx.accessToken) : null;\n}\n";
@@ -233,3 +233,30 @@ export async function removeEnquiry(request: Request, env: object, ctx: PageCont
233
233
  return new Response(null, { status: 303, headers: { location: new URL(request.url).pathname } });
234
234
  }
235
235
  `;
236
+ /** src/pages/enquiry-count.ts: the Enquiries page's count on the admin dashboard. Written once, then the project's. */
237
+ export const ENQUIRY_COUNT = `// How many enquiries wait for an answer, for the admin dashboard's "needs you"
238
+ // (src/pages/needs.ts). Written by @mccaskie-labs/workbench-site once; it's the
239
+ // project's to change. Every enquiry not yet deleted is waiting: the Enquiries
240
+ // page asks admins to delete the ones they've dealt with.
241
+
242
+ import { dbAs } from "../lib/db.ts";
243
+ import type { PageContext } from "./site.ts";
244
+
245
+ /** The table, as the Worker reaches it. Tests replace this. */
246
+ export const enquiryCount = {
247
+ /** How many, as the signed-in admin (RLS). Null when they can't be counted. */
248
+ async count(env: object, accessToken: string): Promise<number | null> {
249
+ const { count, error } = await dbAs(env, accessToken).from("site_enquiries").select("id", { count: "exact", head: true });
250
+ if (error) {
251
+ console.warn(JSON.stringify({ event: "site_enquiries_count_failed" }));
252
+ return null;
253
+ }
254
+ return count ?? 0;
255
+ },
256
+ };
257
+
258
+ /** The count on the admin dashboard. */
259
+ export async function countEnquiries(env: object, ctx: PageContext): Promise<number | null> {
260
+ return ctx.accessToken ? enquiryCount.count(env, ctx.accessToken) : null;
261
+ }
262
+ `;
@@ -1,6 +1,6 @@
1
1
  // The "Every site" recipes (docs/site-planner.md §5): the pages most sites
2
- // have. Privacy and Terms join them with their written clauses per country
3
- // (site planner step 4). Contact's enquiry form needs the Enquiries admin
2
+ // have (docs/default-pages.md §3). Privacy and Terms join them with their
3
+ // written clauses per country (default pages step 3). Contact's enquiry form needs the Enquiries admin
4
4
  // list, so no enquiry is taken before there is somewhere to read it. Words in [square brackets] are the owner's to fill in: Workbench
5
5
  // never makes up a price, an address, an opening hour or a person.
6
6
  const home = {
@@ -9,6 +9,7 @@ const home = {
9
9
  title: "Home",
10
10
  does: "The first page people see: what you do, who for, and how to get in touch.",
11
11
  group: "every-site",
12
+ tier: "always",
12
13
  area: "public",
13
14
  path: "/",
14
15
  frames: ["landing", "column"],
@@ -57,6 +58,7 @@ const about = {
57
58
  title: "About",
58
59
  does: "Your story: who you are, why you started and what you care about.",
59
60
  group: "every-site",
61
+ tier: "ticked",
60
62
  area: "public",
61
63
  path: "/about",
62
64
  frames: ["column", "landing"],
@@ -90,6 +92,7 @@ const contact = {
90
92
  title: "Contact",
91
93
  does: "How to reach you: email, phone, where you are and when you're open, and a form to send you a message.",
92
94
  group: "every-site",
95
+ tier: "always",
93
96
  area: "public",
94
97
  path: "/contact",
95
98
  frames: ["two-columns", "column"],
@@ -140,12 +143,113 @@ const contact = {
140
143
  },
141
144
  suggest: { types: [], signals: ["every site"] },
142
145
  };
146
+ const faq = {
147
+ id: "faq",
148
+ version: 1,
149
+ title: "Questions and answers",
150
+ does: "The questions people ask you most, each with your answer, so they needn't message you to find out.",
151
+ group: "every-site",
152
+ tier: "ticked",
153
+ area: "public",
154
+ path: "/faq",
155
+ frames: ["column"],
156
+ tools: [],
157
+ needs: [],
158
+ menu: { label: "page.faq.menu", footer: 20 },
159
+ pageTitle: "page.faq.title",
160
+ sections: [
161
+ { kind: "hero", heading: "page.faq.hero.heading", lead: "page.faq.hero.lead" },
162
+ {
163
+ kind: "list",
164
+ items: [
165
+ { title: "page.faq.offer.question", body: "page.faq.offer.answer" },
166
+ { title: "page.faq.where.question", body: "page.faq.where.answer" },
167
+ { title: "page.faq.cost.question", body: "page.faq.cost.answer" },
168
+ { title: "page.faq.start.question", body: "page.faq.start.answer" },
169
+ { title: "page.faq.contact.question", body: "page.faq.contact.answer" },
170
+ ],
171
+ },
172
+ { kind: "call", heading: "page.faq.call.heading", body: "page.faq.call.body", action: { label: "page.faq.call.action", to: "contact" } },
173
+ ],
174
+ words: {
175
+ "page.faq.menu": "Questions and answers",
176
+ "page.faq.title": "Questions and answers",
177
+ "page.faq.hero.heading": "Questions and answers",
178
+ "page.faq.hero.lead": "The things people ask us most.",
179
+ "page.faq.offer.question": "What do you offer?",
180
+ "page.faq.offer.answer": "[A sentence or two on what you offer, and who it's for.]",
181
+ "page.faq.where.question": "Where are you, and when are you open?",
182
+ "page.faq.where.answer": "[Where to find you, or the area you cover, and your opening hours.]",
183
+ "page.faq.cost.question": "How much does it cost?",
184
+ "page.faq.cost.answer": "[Your prices, or how you work out a price.]",
185
+ "page.faq.start.question": "How do I get started?",
186
+ "page.faq.start.answer": "[How people book, order or start with you.]",
187
+ "page.faq.contact.question": "How do I get in touch?",
188
+ "page.faq.contact.answer": "Send us a message from the Contact page and we'll reply by email.",
189
+ "page.faq.call.heading": "Still have a question?",
190
+ "page.faq.call.body": "Ask us, and we'll get back to you.",
191
+ "page.faq.call.action": "Ask a question",
192
+ },
193
+ suggest: { types: [], signals: ["every site", "people ask the same questions"] },
194
+ };
195
+ const accessibility = {
196
+ id: "accessibility",
197
+ version: 1,
198
+ title: "Accessibility",
199
+ does: "What you do so everyone can use your site, anything that doesn't work well yet, and how to tell you when something is hard to use.",
200
+ group: "every-site",
201
+ tier: "offered",
202
+ area: "public",
203
+ path: "/accessibility",
204
+ frames: ["column"],
205
+ tools: [],
206
+ needs: [],
207
+ menu: { label: "page.accessibility.menu", footer: 40 },
208
+ pageTitle: "page.accessibility.title",
209
+ sections: [
210
+ { kind: "hero", heading: "page.accessibility.hero.heading", lead: "page.accessibility.hero.lead" },
211
+ { kind: "text", heading: "page.accessibility.aim.heading", body: "page.accessibility.aim.body" },
212
+ {
213
+ kind: "list",
214
+ heading: "page.accessibility.done.heading",
215
+ items: [
216
+ { title: "page.accessibility.done.read.title", body: "page.accessibility.done.read.body" },
217
+ { title: "page.accessibility.done.keys.title", body: "page.accessibility.done.keys.body" },
218
+ { title: "page.accessibility.done.forms.title", body: "page.accessibility.done.forms.body" },
219
+ ],
220
+ },
221
+ { kind: "text", heading: "page.accessibility.known.heading", body: "page.accessibility.known.body" },
222
+ { kind: "call", heading: "page.accessibility.call.heading", body: "page.accessibility.call.body", action: { label: "page.accessibility.call.action", to: "contact" } },
223
+ ],
224
+ words: {
225
+ "page.accessibility.menu": "Accessibility",
226
+ "page.accessibility.title": "Accessibility",
227
+ "page.accessibility.hero.heading": "Accessibility",
228
+ "page.accessibility.hero.lead": "We want everyone to be able to use this site.",
229
+ "page.accessibility.aim.heading": "What we aim for",
230
+ "page.accessibility.aim.body": "We aim to meet the Web Content Accessibility Guidelines (WCAG) 2.2 at level AA.",
231
+ "page.accessibility.done.heading": "What we've done",
232
+ "page.accessibility.done.read.title": "Easy to read",
233
+ "page.accessibility.done.read.body": "Text and buttons have strong contrast in light and dark, and the pages still work when you make the text bigger.",
234
+ "page.accessibility.done.keys.title": "No mouse needed",
235
+ "page.accessibility.done.keys.body": "Every link, button and form works with a keyboard, and with screen readers.",
236
+ "page.accessibility.done.forms.title": "Clear forms",
237
+ "page.accessibility.done.forms.body": "Every field has a label, and a problem with an answer is said in words, not only in colour.",
238
+ "page.accessibility.known.heading": "What doesn't work well yet",
239
+ "page.accessibility.known.body": "[Anything on the site that is hard to use, such as a video without captions or a PDF, and when you'll fix it. If you know of nothing, say so.]",
240
+ "page.accessibility.call.heading": "Something hard to use?",
241
+ "page.accessibility.call.body": "Tell us what you were trying to do, and we'll help you and fix it.",
242
+ "page.accessibility.call.action": "Tell us",
243
+ },
244
+ suggest: { types: [], signals: ["every site", "government or community funding", "older or disabled customers"] },
245
+ };
143
246
  const notFound = {
144
247
  id: "not-found",
145
248
  version: 1,
146
249
  title: "Not found",
147
250
  does: "What people see when an address on your site doesn't exist, with a way back.",
148
251
  group: "every-site",
252
+ tier: "always",
149
253
  area: "public",
150
254
  path: null,
151
255
  status: 404,
@@ -162,5 +266,28 @@ const notFound = {
162
266
  },
163
267
  suggest: { types: [], signals: ["every site"] },
164
268
  };
269
+ const error = {
270
+ id: "error",
271
+ version: 1,
272
+ title: "Something went wrong",
273
+ does: "What people see, in your site's look, when a page breaks, instead of a blank error.",
274
+ group: "every-site",
275
+ tier: "always",
276
+ area: "public",
277
+ path: null,
278
+ status: 500,
279
+ frames: ["column"],
280
+ tools: [],
281
+ needs: [],
282
+ pageTitle: "page.error.title",
283
+ sections: [{ kind: "hero", heading: "page.error.hero.heading", lead: "page.error.hero.lead", action: { label: "page.error.hero.action", to: "/" } }],
284
+ words: {
285
+ "page.error.title": "Something went wrong",
286
+ "page.error.hero.heading": "Something went wrong",
287
+ "page.error.hero.lead": "That's our fault, not yours. Please try again in a minute.",
288
+ "page.error.hero.action": "Go to the home page",
289
+ },
290
+ suggest: { types: [], signals: ["every site"] },
291
+ };
165
292
  /** The "Every site" group, in the order they're offered. */
166
- export const EVERY_SITE = [home, about, contact, notFound];
293
+ export const EVERY_SITE = [home, about, contact, faq, accessibility, notFound, error];
@@ -7,6 +7,7 @@ const account = {
7
7
  title: "Your account",
8
8
  does: "Where a signed-in customer sees who they're signed in as and signs out.",
9
9
  group: "members",
10
+ tier: "always",
10
11
  area: "members",
11
12
  path: "/account",
12
13
  frames: ["column"],
package/dist/samples.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // own frame() and sections; the style guide shows what is inside the page's
5
5
  // body.
6
6
  import { FOOTERS, frame, FRAMES, HEADERS } from "./frames.js";
7
- import { account, callToAction, designSwitch, details, enquiryList, formSection, hero, list, picture, text } from "./sections.js";
7
+ import { account, callToAction, designSwitch, details, enquiryList, formSection, hero, list, needsYou, picture, text } from "./sections.js";
8
8
  import { SITE_STYLES } from "./styles.js";
9
9
  const PHOTO = { src: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 90"><rect width="160" height="90" fill="#6b8f71"/></svg>')}`, alt: "The studio in morning light" };
10
10
  const MENU = [
@@ -65,5 +65,18 @@ export const SITE_SAMPLES = {
65
65
  removeAction: "/admin/enquiries",
66
66
  }),
67
67
  },
68
+ {
69
+ id: "needs-you",
70
+ title: "What needs the admin now",
71
+ html: () => needsYou({
72
+ heading: "Needs you",
73
+ items: [
74
+ { label: "Enquiries to answer", href: "/admin/enquiries", count: 3 },
75
+ { label: "Bookings to confirm", href: "/admin/bookings", count: null },
76
+ ],
77
+ none: "Nothing needs you right now.",
78
+ unavailable: "Can't be counted right now.",
79
+ }),
80
+ },
68
81
  ],
69
82
  };
@@ -113,6 +113,30 @@ export interface EnquiryListOptions {
113
113
  }
114
114
  /** The site's enquiries, newest first, each with a way to reply and a delete button. */
115
115
  export declare function enquiryList(o: EnquiryListOptions): string;
116
+ /** One count on the admin dashboard's "needs you". */
117
+ export interface NeedsYouItem {
118
+ /** What is waiting, such as "Enquiries to answer". */
119
+ label: string;
120
+ /** The admin page where it is dealt with. */
121
+ href: string;
122
+ /** How many are waiting; null when it couldn't be counted. */
123
+ count: number | null;
124
+ }
125
+ export interface NeedsYouOptions {
126
+ heading?: string;
127
+ /** Each tool's count, in the admin menu's order. */
128
+ items: readonly NeedsYouItem[];
129
+ /** Shown when nothing is waiting. */
130
+ none: string;
131
+ /** Shown beside a count that couldn't be read. */
132
+ unavailable: string;
133
+ }
134
+ /**
135
+ * What needs the admin now (docs/default-pages.md decision 4): each count
136
+ * above nought, or that couldn't be read, links to its page; when nothing is
137
+ * waiting, one line says so.
138
+ */
139
+ export declare function needsYou(o: NeedsYouOptions): string;
116
140
  /** The cookie that turns design mode on in this browser (docs/look-studio.md §8): the site helper reads it, the design script clears it. */
117
141
  export declare const DESIGN_COOKIE = "wb-design";
118
142
  /** True when this request comes from a browser with design mode on. */
package/dist/sections.js CHANGED
@@ -85,6 +85,24 @@ export function enquiryList(o) {
85
85
  .join("")}</ul>`;
86
86
  return `<section class="wb-site-section wb-site-enquiry-list">${heading(o.heading)}${body}</section>`;
87
87
  }
88
+ /**
89
+ * What needs the admin now (docs/default-pages.md decision 4): each count
90
+ * above nought, or that couldn't be read, links to its page; when nothing is
91
+ * waiting, one line says so.
92
+ */
93
+ export function needsYou(o) {
94
+ const waiting = o.items.filter((i) => i.count === null || i.count > 0);
95
+ const body = waiting.length
96
+ ? `<ul class="wb-site-needs-items">${waiting
97
+ .map((i) => {
98
+ const count = i.count === null ? "" : `<span class="wb-site-needs-count">${i.count}</span> `;
99
+ const unknown = i.count === null ? ` <span class="wb-site-needs-unknown">${escape(o.unavailable)}</span>` : "";
100
+ return `<li class="wb-site-needs-item"><a class="wb-site-needs-link" href="${escape(safeHref(i.href))}">${count}<span class="wb-site-needs-label">${escape(i.label)}</span></a>${unknown}</li>`;
101
+ })
102
+ .join("")}</ul>`
103
+ : `<p class="wb-site-paragraph">${escape(o.none)}</p>`;
104
+ return `<section class="wb-site-section wb-site-needs">${heading(o.heading)}${body}</section>`;
105
+ }
88
106
  /** The cookie that turns design mode on in this browser (docs/look-studio.md §8): the site helper reads it, the design script clears it. */
89
107
  export const DESIGN_COOKIE = "wb-design";
90
108
  /** True when this request comes from a browser with design mode on. */
package/dist/styles.js CHANGED
@@ -123,6 +123,13 @@ export const SITE_STYLES = {
123
123
  { name: "wb-site-form-section", element: "section", about: "A form on a page, such as Contact's enquiry form", css: `max-width:${v("reading")}` },
124
124
  { name: "wb-site-problem", element: "p", about: "Why a form can't be sent, or a list read, right now", css: `margin:${v("space")} 0;padding:calc(${v("space")} * .75);border-left:4px solid ${v("danger")};background:${v("surface")};color:${v("text")}` },
125
125
  { name: "wb-site-done", element: "p", about: "The thank-you once a form is sent", css: `margin:${v("space")} 0;padding:calc(${v("space")} * .75);border-left:4px solid ${v("success")};background:${v("surface")};color:${v("text")}` },
126
+ { name: "wb-site-needs", element: "section", about: "What needs the admin now, on the admin dashboard", css: `max-width:${v("reading")}` },
127
+ { name: "wb-site-needs-items", element: "ul", about: "Each count that is waiting", css: `list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(auto-fit, minmax(min(100%, 12rem), 1fr));gap:${v("space")}` },
128
+ { name: "wb-site-needs-item", element: "li", about: "One count", css: `padding:${v("space")};border:1px solid ${v("line")};border-radius:${v("radius")};background:${v("background")}` },
129
+ { name: "wb-site-needs-link", element: "a", about: "The count and what it is, linking to its page", css: `display:grid;gap:.25rem;color:${v("text")};text-decoration:none` },
130
+ { name: "wb-site-needs-count", element: "span", about: "How many are waiting", css: `font-size:2rem;font-weight:700;line-height:1;color:${v("accent")}` },
131
+ { name: "wb-site-needs-label", element: "span", about: "What is waiting", css: `font-weight:600;text-decoration:underline` },
132
+ { name: "wb-site-needs-unknown", element: "span", about: "A count that couldn't be read right now", css: `display:block;margin-top:.25rem;font-size:.9rem;color:${v("muted")}` },
126
133
  { name: "wb-site-enquiry-list", element: "section", about: "The Enquiries admin list", css: `max-width:${v("reading")}` },
127
134
  { name: "wb-site-enquiries", element: "ul", about: "The enquiries, newest first", css: `list-style:none;margin:0;padding:0;display:grid;gap:${v("space")}` },
128
135
  { name: "wb-site-enquiry", element: "li", about: "One enquiry", css: `padding:${v("space")};border:1px solid ${v("line")};border-radius:${v("radius")};background:${v("background")}` },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-site",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "A Workbench project's standard pages: page recipes, the builder that turns them into thin page files calling Workbench's tools, and the page frames and sections they are drawn with (wb-site-*, restylable, on the project's theme tokens).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",