@mccaskie-labs/workbench-site 0.10.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,13 @@
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
+
3
11
  ## 0.10.0
4
12
 
5
13
  ### Minor Changes
package/README.md CHANGED
@@ -12,6 +12,8 @@ npx workbench-site check --live # and no [fill-in] is left, before
12
12
 
13
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
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
+
15
17
  `add` writes, in a project made from Workbench's template:
16
18
 
17
19
  | File | What it is |
package/dist/builder.js CHANGED
@@ -113,11 +113,20 @@ export function buildSite(o) {
113
113
  writes["src/pages/site.ts"] = SITE_HELPER;
114
114
  writes["src/pages/index.ts"] = indexFile(pages, byId);
115
115
  writes["src/pages/nav.ts"] = navFile(pages, byId);
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);
116
119
  writes["test/pages.test.ts"] = testFile(base, pages, byId);
117
120
  // What the pages need besides their files: each written once, then the project's.
118
121
  let forms = false;
119
122
  const migrations = [];
120
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
+ }
121
130
  for (const id of added) {
122
131
  const r = byId.get(id);
123
132
  for (const [path, text] of Object.entries(r.files ?? {})) {
@@ -232,6 +241,12 @@ function sectionCode(s, pathOf, self) {
232
241
  add("signedIn", `w(${JSON.stringify(s.signedIn)}, { email: ctx.user?.email ?? "" })`);
233
242
  add("signOut", w(s.signOut));
234
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;
235
250
  case "admin-menu":
236
251
  add("heading", s.heading && w(s.heading));
237
252
  add("items", `ADMIN_MENU.filter(([, href]) => href !== ${JSON.stringify(self)}).map(([label, href, about]) => ({ title: w(label), href, body: w(about) }))`);
@@ -289,7 +304,8 @@ function pageFile(r, version, base, pathOf) {
289
304
  const usesMenu = sections.some(([s]) => s.kind === "admin-menu");
290
305
  const looks = sections.some(([s]) => s.kind === "look-preview");
291
306
  const design = sections.some(([s]) => s.kind === "design-switch");
292
- const block = list || guide;
307
+ const needs = sections.some(([s]) => s.kind === "needs-you");
308
+ const block = list || guide || needs;
293
309
  const area = r.area === "members" || r.area === "admin" ? `, area: ${JSON.stringify(r.area)}` : "";
294
310
  const prefix = `page.${r.id.replace(/-/g, "_")}.`;
295
311
  const frame = r.frames[0];
@@ -311,6 +327,7 @@ function pageFile(r, version, base, pathOf) {
311
327
  ...(looks || design ? [`import { appConfig } from "../config.ts";`] : []),
312
328
  ...(looks ? [`import { BRAND } from "../lib/brand.ts";`] : []),
313
329
  ...(usesMenu || looks ? [`import { ${[...(usesMenu ? ["ADMIN_MENU"] : []), ...(looks ? ["MENU"] : [])].join(", ")} } from "./nav.ts";`] : []),
330
+ ...(needs ? [`import { readNeeds } from "./needs.ts";`] : []),
314
331
  `import { sitePage, type SitePage } from "./site.ts";`,
315
332
  "",
316
333
  `export const ${camel(r.id)}: SitePage = {`,
@@ -319,9 +336,11 @@ function pageFile(r, version, base, pathOf) {
319
336
  ` access: ${JSON.stringify(r.area === "legal" ? "public" : r.area)},`,
320
337
  ...(list
321
338
  ? [" render: async (request, env, ctx) => {", " const enquiries = await listEnquiries(env, ctx);"]
322
- : guide
323
- ? [" render: (request, env) => {", " // ?view=light, dark or admin: the switch at the top of the guide.", " const view = guideView(request.url);"]
324
- : [` 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" : ""}) =>`]),
325
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) => [`,
326
345
  ...sections.map(([, code]) => ` ${code},`),
327
346
  block ? " ]);\n }," : " ]),",
@@ -423,6 +442,41 @@ function indexFile(pages, byId) {
423
442
  "",
424
443
  ].join("\n");
425
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
+ }
426
480
  function navFile(pages, byId) {
427
481
  const entries = (place) => pages
428
482
  .map((p) => ({ p, menu: byId.get(p.recipe)?.menu }))
@@ -459,6 +513,7 @@ function testFile(base, pages, byId) {
459
513
  const broken = unaddressed(pages, byId, 500);
460
514
  const sample = pages.find((p) => p.access === "public" && p.path !== null);
461
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"));
462
517
  const form = pages.find((p) => p.access === "public" && p.path !== null && p.recipe === "contact");
463
518
  const guide = pages.find((p) => p.recipe === "style-guide" && p.path !== null);
464
519
  return `// Generated by ${PACKAGE}: every page in workbench/site.json answers, in
@@ -469,7 +524,7 @@ function testFile(base, pages, byId) {
469
524
  import { siteProblems } from "${PACKAGE}";
470
525
  import { ${enquiries ? "beforeEach, " : ""}describe, expect, it${enquiries || (broken && sample) ? ", vi" : ""} } from "vitest";
471
526
  import worker from "../src/index.ts";
472
- ${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";
473
528
  import { SITE_LAYOUT as LAYOUT } from "../src/site-layout.generated.ts";
474
529
  import site from "../workbench/site.json";
475
530
  import strings from "../strings/strings.${base}.json";
@@ -487,7 +542,7 @@ const STATUS: Readonly<Record<string, number>> = ${JSON.stringify(status)};
487
542
  const files = import.meta.glob<string>("../src/pages/*.ts", { query: "?raw", import: "default", eager: true });
488
543
 
489
544
  describe("site pages", () => {
490
- ${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)", () => {
491
546
  const byPath = Object.fromEntries(Object.entries(files).map(([path, text]) => [path.replace(/^\\.\\.\\//, ""), text]));
492
547
  expect(siteProblems({ site, strings, files: byPath })).toEqual([]);
493
548
  });
@@ -536,7 +591,29 @@ ${enquiries ? " // The enquiries table isn't reached: each test says what it ho
536
591
  });
537
592
  }
538
593
  });
539
- ${enquiries && form ? enquiryTests(form.path) : ""}${guide ? guideTests(guide.path) : ""}${broken && sample ? errorTests(sample.recipe, sample.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
+ `;
540
617
  }
541
618
  /** Something went wrong's own test, when the site has it and a public page to break. */
542
619
  function errorTests(recipe, path) {
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";
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
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
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";
6
+ export { account, callToAction, DESIGN_COOKIE, designModeOn, designModePost, designSwitch, details, enquiryList, needsYou, formSection, hero, HERO_ARRANGEMENTS, list, picture, text, } from "./sections.js";
7
7
  export { recipeKeys, recipeProblems, TIERS } from "./recipe.js";
8
8
  export { RECIPES } from "./recipes/index.js";
9
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";
@@ -192,6 +200,18 @@ export interface Recipe {
192
200
  files?: Readonly<Record<string, string>>;
193
201
  /** Workbench packages its page needs at least this version of (x.y.z): the builder raises the project's to it. */
194
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
+ };
195
215
  /** Its table, as a Workbench tool's own migration: supabase/migrations/<stamp>_<name>.sql and its down file, written once. */
196
216
  migration?: {
197
217
  name: string;
package/dist/recipe.js CHANGED
@@ -6,7 +6,7 @@
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. */
@@ -39,6 +39,8 @@ function sectionKeys(s) {
39
39
  return [s.heading, s.signedIn, s.signOut].filter((k) => !!k);
40
40
  case "admin-menu":
41
41
  return [s.heading].filter((k) => !!k);
42
+ case "needs-you":
43
+ return [s.heading, s.none, s.unavailable].filter((k) => !!k);
42
44
  case "enquiry-form":
43
45
  return [s.heading, s.intro, s.send, s.sent, s.unavailable].filter((k) => !!k);
44
46
  case "enquiries":
@@ -55,7 +57,7 @@ function sectionKeys(s) {
55
57
  export function recipeKeys(r) {
56
58
  const menu = r.menu ? [r.menu.label, r.menu.about].filter((k) => !!k) : [];
57
59
  const links = (r.links ?? []).flatMap((l) => [l.label, l.about]);
58
- 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)])];
59
61
  }
60
62
  /** The values a word is given when the page says it. */
61
63
  function valuesFor(r, key) {
@@ -138,6 +140,8 @@ export function recipeProblems(r, catalogue) {
138
140
  p("the account section is for members pages");
139
141
  if (s.kind === "admin-menu" && r.area !== "admin")
140
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");
141
145
  if (s.kind === "enquiries" && r.area !== "admin")
142
146
  p("the enquiries list is for admin pages");
143
147
  if (s.kind === "enquiry-form" && r.area !== "public")
@@ -154,6 +158,14 @@ export function recipeProblems(r, catalogue) {
154
158
  p(`link ${l.href}: only admin pages add admin menu links, to /admin addresses`);
155
159
  if (r.menu && r.path === null)
156
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
+ }
157
169
  if (r.migration && !/^workbench_site_[a-z0-9_]+$/.test(r.migration.name))
158
170
  p("a migration is named workbench_site_<what>, so Control treats it as a Workbench tool's own");
159
171
  for (const [name, v] of Object.entries(r.packages ?? {}))
@@ -2,12 +2,12 @@
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
12
  tier: "always",
13
13
  area: "admin",
@@ -20,14 +20,18 @@ const adminHome = {
20
20
  pageTitle: "page.admin_home.title",
21
21
  sections: [
22
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" },
23
24
  { kind: "admin-menu", heading: "page.admin_home.pages.heading" },
24
25
  ],
25
26
  words: {
26
27
  "page.admin_home.menu": "Admin",
27
- "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.",
28
29
  "page.admin_home.title": "Admin",
29
30
  "page.admin_home.hero.heading": "Admin",
30
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.",
31
35
  "page.admin_home.pages.heading": "Your pages",
32
36
  "page.admin_home.brand.label": "Brand settings",
33
37
  "page.admin_home.brand.about": "Your business's name, colour and logo on emails and PDFs, and who else can manage the site.",
@@ -36,7 +40,7 @@ const adminHome = {
36
40
  };
37
41
  const enquiries = {
38
42
  id: "enquiries",
39
- version: 1,
43
+ version: 2,
40
44
  title: "Enquiries",
41
45
  does: "Every message sent from the Contact page, newest first, with a way to reply.",
42
46
  group: "admin",
@@ -49,9 +53,11 @@ const enquiries = {
49
53
  menu: { label: "page.enquiries.menu", admin: 10, about: "page.enquiries.about" },
50
54
  files: {
51
55
  "src/pages/enquiry-store.ts": ENQUIRY_STORE,
56
+ "src/pages/enquiry-count.ts": ENQUIRY_COUNT,
52
57
  "workbench/forms/enquiry.json": `${JSON.stringify(ENQUIRY_ANSWERS, null, 2)}\n`,
53
58
  },
54
59
  migration: ENQUIRY_MIGRATION,
60
+ needsYou: { label: "page.enquiries.needs_you", file: "src/pages/enquiry-count.ts", fn: "countEnquiries" },
55
61
  pageTitle: "page.enquiries.title",
56
62
  sections: [
57
63
  { kind: "hero", heading: "page.enquiries.hero.heading", lead: "page.enquiries.hero.lead" },
@@ -60,6 +66,7 @@ const enquiries = {
60
66
  words: {
61
67
  "page.enquiries.menu": "Enquiries",
62
68
  "page.enquiries.about": "Messages people sent from the Contact page.",
69
+ "page.enquiries.needs_you": "Enquiries to answer",
63
70
  "page.enquiries.title": "Enquiries",
64
71
  "page.enquiries.hero.heading": "Enquiries",
65
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.",
@@ -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
+ `;
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.10.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",