@mccaskie-labs/workbench-site 0.10.0 → 0.12.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 +16 -0
- package/README.md +6 -0
- package/dist/builder.d.ts +2 -0
- package/dist/builder.js +114 -16
- package/dist/cli.d.ts +11 -1
- package/dist/cli.js +59 -8
- package/dist/gather.d.ts +20 -0
- package/dist/gather.js +50 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/recipe.d.ts +49 -0
- package/dist/recipe.js +18 -2
- package/dist/recipes/admin.js +12 -5
- package/dist/recipes/enquiries-kit.d.ts +2 -0
- package/dist/recipes/enquiries-kit.js +27 -0
- package/dist/samples.js +14 -1
- package/dist/sections.d.ts +24 -0
- package/dist/sections.js +18 -0
- package/dist/styles.js +7 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @mccaskie-labs/workbench-site
|
|
2
2
|
|
|
3
|
+
## 0.12.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Recipes from other tools (`docs/builder-ready.md` B5, `docs/site-planner.md` §5): a tool's own pages are recipes in its own package, exported as `RECIPES` from `"<package>/recipes"`. The CLI finds every Workbench package the project depends on that has the export and gathers its recipes beside the site's own (`recipeSources`, `gatherRecipes`), for `list`, `add` and `check`. A package whose export isn't recipes, that repeats an id, or that has a recipe that can't be built is left out whole and named, so the site's own pages and the other tools' still build. `list` names the package each tool page comes from.
|
|
8
|
+
- A tool can draw a section itself: `{ kind: "tool", from, fn, words }`. The page file imports `fn` from the tool's package (a `ToolSectionFunction`), calls it with (request, env, ctx) before drawing the page, and draws what it gives back with the page's words.
|
|
9
|
+
- `buildSite` takes `from` (recipe id to package), and the generated pages test imports those packages' recipes for `siteProblems`. `main` is now async.
|
|
10
|
+
|
|
11
|
+
## 0.11.0
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- 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.
|
|
16
|
+
- 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.
|
|
17
|
+
- 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`.
|
|
18
|
+
|
|
3
19
|
## 0.10.0
|
|
4
20
|
|
|
5
21
|
### 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 |
|
|
@@ -38,3 +40,7 @@ import { account, callToAction, details, enquiryList, formSection, frame, hero,
|
|
|
38
40
|
```
|
|
39
41
|
|
|
40
42
|
Each section takes plain words (escaped) and returns HTML with `wb-site-*` classes; `frame` wraps them in a whole page (`landing`, `column` or `two-columns`). Restyle them in the project's `public/styles/project.css`: every class and `--wb-site-*` variable is listed in the generated `public/styles/workbench.css`, and the colour, font, corner and space variables follow the project's theme tokens (`--wb-accent` and the rest).
|
|
43
|
+
|
|
44
|
+
## A tool's own pages
|
|
45
|
+
|
|
46
|
+
A tool's pages are recipes in its own package (`docs/site-planner.md` §5). Export them as `RECIPES` (a `readonly Recipe[]`, the type from this package) from a `./recipes` subpath in the package's `exports`. `npx workbench-site` gathers them from every Workbench package the project has installed, beside this package's own. Each recipe follows the same rules: ids unique across every package, words under `page.<id>.`, files only in `src/pages/` and `workbench/forms/`, and a `needsYou` count when its admin page has something waiting. A section only the tool can draw (a slot picker) is `{ kind: "tool", from: "<package>", fn: "<export>", words: [<its word keys>] }`: the export is a `ToolSectionFunction`, called with (request, env, ctx) before the page is drawn, which gives back a function that draws the section's HTML with the page's words, in the tool's own `wb-<tool>-*` classes.
|
package/dist/builder.d.ts
CHANGED
|
@@ -32,6 +32,8 @@ export interface BuildOptions {
|
|
|
32
32
|
/** The project's base locale: its words go into strings/strings.<base>.json. Defaults to en-AU. */
|
|
33
33
|
base?: string;
|
|
34
34
|
catalogue?: readonly Recipe[];
|
|
35
|
+
/** Which tool package each recipe in `catalogue` came from, by id (gatherRecipes' `from`): the generated test imports their recipes. */
|
|
36
|
+
from?: Readonly<Record<string, string>>;
|
|
35
37
|
/** Stamps a new migration's file name. Defaults to now. */
|
|
36
38
|
now?: Date;
|
|
37
39
|
}
|
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
|
-
|
|
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, o.from ?? {});
|
|
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) }))`);
|
|
@@ -253,6 +268,9 @@ function sectionCode(s, pathOf, self) {
|
|
|
253
268
|
for (const k of ["views", "light", "dark", "admin", "empty", "layout"])
|
|
254
269
|
add(k, w(s[k]));
|
|
255
270
|
return `styleGuide(SAMPLES, { view, words: { ${fields.join(", ")} } })`;
|
|
271
|
+
case "tool":
|
|
272
|
+
// Drawn from what its function gave back (pageFile).
|
|
273
|
+
return null;
|
|
256
274
|
case "design-switch":
|
|
257
275
|
for (const k of ["on", "off", "turnOn", "turnOff", "live"])
|
|
258
276
|
add(k, w(s[k]));
|
|
@@ -279,8 +297,19 @@ function older(have, least) {
|
|
|
279
297
|
/** The style guide's own sheet, which workbench-ui's styles command writes (both schemes of the project's look). */
|
|
280
298
|
const GUIDE_SHEET = "/styles/style-guide.css";
|
|
281
299
|
function pageFile(r, version, base, pathOf) {
|
|
282
|
-
|
|
283
|
-
|
|
300
|
+
// A tool's section is drawn by a function from its own package, called before the page (it may read the database).
|
|
301
|
+
let n = 0;
|
|
302
|
+
const tools = [];
|
|
303
|
+
const sections = r.sections
|
|
304
|
+
.map((s) => {
|
|
305
|
+
if (s.kind !== "tool")
|
|
306
|
+
return [s, sectionCode(s, pathOf, r.path)];
|
|
307
|
+
n += 1;
|
|
308
|
+
tools.push({ name: `tool${n}`, from: s.from, fn: s.fn });
|
|
309
|
+
return [s, `tool${n}(w)`];
|
|
310
|
+
})
|
|
311
|
+
.filter((x) => x[1] !== null);
|
|
312
|
+
const used = [...new Set([...sections.filter(([s]) => !STORE_SECTIONS.has(s.kind) && !UI_SECTIONS.has(s.kind) && s.kind !== "tool").map(([s]) => SECTION_FUNCTIONS[s.kind]), ...(sections.some(([s]) => s.kind === "design-switch") ? ["designModeOn", "designModePost"] : [])])].sort();
|
|
284
313
|
const guide = sections.some(([s]) => s.kind === "style-guide");
|
|
285
314
|
const form = sections.some(([s]) => s.kind === "enquiry-form");
|
|
286
315
|
const list = sections.some(([s]) => s.kind === "enquiries");
|
|
@@ -289,7 +318,16 @@ function pageFile(r, version, base, pathOf) {
|
|
|
289
318
|
const usesMenu = sections.some(([s]) => s.kind === "admin-menu");
|
|
290
319
|
const looks = sections.some(([s]) => s.kind === "look-preview");
|
|
291
320
|
const design = sections.some(([s]) => s.kind === "design-switch");
|
|
292
|
-
const
|
|
321
|
+
const needs = sections.some(([s]) => s.kind === "needs-you");
|
|
322
|
+
const pre = [
|
|
323
|
+
...(list ? [" const enquiries = await listEnquiries(env, ctx);"] : []),
|
|
324
|
+
...(needs ? [" // Each tool's count, read at once (src/pages/needs.ts).", " const needs = await readNeeds(env, ctx);"] : []),
|
|
325
|
+
...(guide ? [" // ?view=light, dark or admin: the switch at the top of the guide.", " const view = guideView(request.url);"] : []),
|
|
326
|
+
...tools.map((t) => ` const ${t.name} = await ${t.fn}(request, env, ctx);`),
|
|
327
|
+
];
|
|
328
|
+
const block = pre.length > 0;
|
|
329
|
+
const waits = list || needs || tools.length > 0;
|
|
330
|
+
const toolImports = [...new Set(tools.map((t) => t.from))].sort().map((from) => `import { ${[...new Set(tools.filter((t) => t.from === from).map((t) => t.fn))].sort().join(", ")} } from "${from}";`);
|
|
293
331
|
const area = r.area === "members" || r.area === "admin" ? `, area: ${JSON.stringify(r.area)}` : "";
|
|
294
332
|
const prefix = `page.${r.id.replace(/-/g, "_")}.`;
|
|
295
333
|
const frame = r.frames[0];
|
|
@@ -304,24 +342,22 @@ function pageFile(r, version, base, pathOf) {
|
|
|
304
342
|
"// fill in. Once you change this file, set its state in workbench/site.json to",
|
|
305
343
|
'// "changed", and Workbench never writes over it.',
|
|
306
344
|
"",
|
|
307
|
-
`import { ${used.join(", ")} } from "${PACKAGE}"
|
|
345
|
+
...(used.length ? [`import { ${used.join(", ")} } from "${PACKAGE}";`] : []),
|
|
346
|
+
...toolImports,
|
|
308
347
|
...(store.length ? [`import { ${store.join(", ")} } from "./enquiry-store.ts";`] : []),
|
|
309
348
|
...(guide ? [`import { guideView, styleGuide } from "@mccaskie-labs/workbench-ui";`, `import { SAMPLES } from "../samples.generated.ts";`] : []),
|
|
310
349
|
...(looks ? [`import { lookPreview } from "@mccaskie-labs/workbench-ui";`] : []),
|
|
311
350
|
...(looks || design ? [`import { appConfig } from "../config.ts";`] : []),
|
|
312
351
|
...(looks ? [`import { BRAND } from "../lib/brand.ts";`] : []),
|
|
313
352
|
...(usesMenu || looks ? [`import { ${[...(usesMenu ? ["ADMIN_MENU"] : []), ...(looks ? ["MENU"] : [])].join(", ")} } from "./nav.ts";`] : []),
|
|
353
|
+
...(needs ? [`import { readNeeds } from "./needs.ts";`] : []),
|
|
314
354
|
`import { sitePage, type SitePage } from "./site.ts";`,
|
|
315
355
|
"",
|
|
316
356
|
`export const ${camel(r.id)}: SitePage = {`,
|
|
317
357
|
` recipe: ${JSON.stringify(r.id)},`,
|
|
318
358
|
` path: ${JSON.stringify(r.path)},`,
|
|
319
359
|
` access: ${JSON.stringify(r.area === "legal" ? "public" : r.area)},`,
|
|
320
|
-
...(
|
|
321
|
-
? [" 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" : ""}) =>`]),
|
|
360
|
+
...(block ? [` render: ${waits ? "async " : ""}(request, env${usesCtx || waits ? ", ctx" : ""}) => {`, ...pre] : [` render: (request, env${usesCtx ? ", ctx" : ""}) =>`]),
|
|
325
361
|
` ${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
362
|
...sections.map(([, code]) => ` ${code},`),
|
|
327
363
|
block ? " ]);\n }," : " ]),",
|
|
@@ -423,6 +459,41 @@ function indexFile(pages, byId) {
|
|
|
423
459
|
"",
|
|
424
460
|
].join("\n");
|
|
425
461
|
}
|
|
462
|
+
/** src/pages/needs.ts: the admin dashboard's counts, one per page on the site that has one, in the admin menu's order. */
|
|
463
|
+
function needsFile(pages, byId) {
|
|
464
|
+
const counts = pages
|
|
465
|
+
.flatMap((p) => {
|
|
466
|
+
const r = byId.get(p.recipe);
|
|
467
|
+
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 }] : [];
|
|
468
|
+
})
|
|
469
|
+
.sort((a, b) => a.order - b.order);
|
|
470
|
+
const imports = [...new Map(counts.map((c) => [`${c.fn}|${c.file}`, c])).values()].map((c) => `import { ${c.fn} } from "./${c.file.replace(/^src\/pages\//, "")}";`);
|
|
471
|
+
return [
|
|
472
|
+
`// Generated by ${PACKAGE} from workbench/site.json and its recipes: \`npx workbench-site add <page>\``,
|
|
473
|
+
"// rewrites it. What needs the site's admins, for Admin home's \"needs you\"",
|
|
474
|
+
"// (docs/default-pages.md decision 4): each page with a count, and where it's",
|
|
475
|
+
"// dealt with.",
|
|
476
|
+
"",
|
|
477
|
+
...imports,
|
|
478
|
+
`import type { PageContext } from "./site.ts";`,
|
|
479
|
+
"",
|
|
480
|
+
"/** One count: its word's key, its page, and how many wait (null when they can't be counted). */",
|
|
481
|
+
"export interface Need {",
|
|
482
|
+
" label: string;",
|
|
483
|
+
" href: string;",
|
|
484
|
+
" count: number | null;",
|
|
485
|
+
"}",
|
|
486
|
+
"",
|
|
487
|
+
"const NEEDS: readonly { label: string; href: string; count: (env: Env, ctx: PageContext) => Promise<number | null> }[] = " +
|
|
488
|
+
(counts.length ? `[\n${counts.map((c) => ` { label: ${JSON.stringify(c.label)}, href: ${JSON.stringify(c.href)}, count: ${c.fn} },`).join("\n")}\n];` : "[];"),
|
|
489
|
+
"",
|
|
490
|
+
"/** Every count, read at once; one that fails is null, and the others still show. */",
|
|
491
|
+
"export async function readNeeds(env: Env, ctx: PageContext): Promise<Need[]> {",
|
|
492
|
+
" return Promise.all(NEEDS.map(async (n) => ({ label: n.label, href: n.href, count: await n.count(env, ctx).catch(() => null) })));",
|
|
493
|
+
"}",
|
|
494
|
+
"",
|
|
495
|
+
].join("\n");
|
|
496
|
+
}
|
|
426
497
|
function navFile(pages, byId) {
|
|
427
498
|
const entries = (place) => pages
|
|
428
499
|
.map((p) => ({ p, menu: byId.get(p.recipe)?.menu }))
|
|
@@ -454,11 +525,16 @@ function navFile(pages, byId) {
|
|
|
454
525
|
"",
|
|
455
526
|
].join("\n");
|
|
456
527
|
}
|
|
457
|
-
|
|
528
|
+
/** A package's name as an identifier for its recipes: @mccaskie-labs/workbench-bookings gives bookingsRecipes. */
|
|
529
|
+
const recipesName = (pkg) => `${pkg.replace(/^@[^/]+\//, "").replace(/^workbench-/, "").replace(/[^a-z0-9]+([a-z0-9])/gi, (_, c) => c.toUpperCase())}Recipes`;
|
|
530
|
+
function testFile(base, pages, byId, from) {
|
|
531
|
+
// The tool packages whose pages are on the site: siteProblems needs their recipes too.
|
|
532
|
+
const tools = [...new Set(pages.map((p) => from[p.recipe]).filter((x) => !!x))].sort();
|
|
458
533
|
const status = Object.fromEntries(pages.filter((p) => p.path === null).map((p) => [p.recipe, byId.get(p.recipe)?.status ?? 404]));
|
|
459
534
|
const broken = unaddressed(pages, byId, 500);
|
|
460
535
|
const sample = pages.find((p) => p.access === "public" && p.path !== null);
|
|
461
536
|
const enquiries = pages.some((p) => p.recipe === "enquiries");
|
|
537
|
+
const dashboard = pages.find((p) => p.path !== null && byId.get(p.recipe)?.sections.some((x) => x.kind === "needs-you"));
|
|
462
538
|
const form = pages.find((p) => p.access === "public" && p.path !== null && p.recipe === "contact");
|
|
463
539
|
const guide = pages.find((p) => p.recipe === "style-guide" && p.path !== null);
|
|
464
540
|
return `// Generated by ${PACKAGE}: every page in workbench/site.json answers, in
|
|
@@ -466,10 +542,10 @@ function testFile(base, pages, byId) {
|
|
|
466
542
|
// in the project's look, with each of its words from the catalogue; and
|
|
467
543
|
// workbench/site.json matches the page files (check:site).
|
|
468
544
|
|
|
469
|
-
import { siteProblems } from "${PACKAGE}"
|
|
545
|
+
import { ${tools.length ? "RECIPES, " : ""}siteProblems } from "${PACKAGE}";${tools.map((t) => `\nimport { RECIPES as ${recipesName(t)} } from "${t}/recipes";`).join("")}
|
|
470
546
|
import { ${enquiries ? "beforeEach, " : ""}describe, expect, it${enquiries || (broken && sample) ? ", vi" : ""} } from "vitest";
|
|
471
547
|
import worker from "../src/index.ts";
|
|
472
|
-
${enquiries ? 'import { enquiryStore } from "../src/pages/enquiry-store.ts";\n' : ""}import { PAGES } from "../src/pages/index.ts";
|
|
548
|
+
${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
549
|
import { SITE_LAYOUT as LAYOUT } from "../src/site-layout.generated.ts";
|
|
474
550
|
import site from "../workbench/site.json";
|
|
475
551
|
import strings from "../strings/strings.${base}.json";
|
|
@@ -487,9 +563,9 @@ const STATUS: Readonly<Record<string, number>> = ${JSON.stringify(status)};
|
|
|
487
563
|
const files = import.meta.glob<string>("../src/pages/*.ts", { query: "?raw", import: "default", eager: true });
|
|
488
564
|
|
|
489
565
|
describe("site pages", () => {
|
|
490
|
-
${enquiries ? " // The enquiries table isn't reached: each test says what it holds.\n beforeEach(() =>
|
|
566
|
+
${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
567
|
const byPath = Object.fromEntries(Object.entries(files).map(([path, text]) => [path.replace(/^\\.\\.\\//, ""), text]));
|
|
492
|
-
expect(siteProblems({ site, strings, files: byPath })).toEqual([]);
|
|
568
|
+
expect(siteProblems({ site, strings, files: byPath${tools.length ? `, catalogue: [...RECIPES, ${tools.map((t) => `...${recipesName(t)}`).join(", ")}]` : ""} })).toEqual([]);
|
|
493
569
|
});
|
|
494
570
|
|
|
495
571
|
for (const page of PAGES) {
|
|
@@ -536,7 +612,29 @@ ${enquiries ? " // The enquiries table isn't reached: each test says what it ho
|
|
|
536
612
|
});
|
|
537
613
|
}
|
|
538
614
|
});
|
|
539
|
-
${enquiries && form ? enquiryTests(form.path) : ""}${guide ? guideTests(guide.path) : ""}${broken && sample ? errorTests(sample.recipe, sample.path) : ""}`;
|
|
615
|
+
${enquiries && form ? enquiryTests(form.path) : ""}${guide ? guideTests(guide.path) : ""}${broken && sample ? errorTests(sample.recipe, sample.path) : ""}${enquiries && dashboard ? dashboardTests(dashboard.recipe, dashboard.path) : ""}`;
|
|
616
|
+
}
|
|
617
|
+
/** The admin dashboard's own tests, when the site has it and Enquiries. */
|
|
618
|
+
function dashboardTests(recipe, path) {
|
|
619
|
+
return `
|
|
620
|
+
describe("admin dashboard", () => {
|
|
621
|
+
const page = PAGES.find((p) => p.recipe === ${JSON.stringify(recipe)})!;
|
|
622
|
+
const draw = async () => (await page.render(new Request(\`https://example.com${path}\`), production(), { user: { id: "user-1", email: "a@example.com" }, accessToken: "token" })).text();
|
|
623
|
+
|
|
624
|
+
it("shows a new enquiry as a count, linking to the Enquiries page", async () => {
|
|
625
|
+
const count = vi.spyOn(enquiryCount, "count").mockResolvedValue(3);
|
|
626
|
+
const html = await draw().finally(() => count.mockRestore());
|
|
627
|
+
expect(html).toMatch(/<a class="wb-site-needs-link" href="\\/admin\\/enquiries"><span class="wb-site-needs-count">3<\\/span>/);
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
it("says when nothing needs the admin, and when a count can't be read", async () => {
|
|
631
|
+
const none = vi.spyOn(enquiryCount, "count").mockResolvedValue(0);
|
|
632
|
+
expect(await draw().finally(() => none.mockRestore())).not.toContain("wb-site-needs-items");
|
|
633
|
+
const down = vi.spyOn(enquiryCount, "count").mockResolvedValue(null);
|
|
634
|
+
expect(await draw().finally(() => down.mockRestore())).toContain("wb-site-needs-unknown");
|
|
635
|
+
});
|
|
636
|
+
});
|
|
637
|
+
`;
|
|
540
638
|
}
|
|
541
639
|
/** Something went wrong's own test, when the site has it and a public page to break. */
|
|
542
640
|
function errorTests(recipe, path) {
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { type RecipeSource } from "./gather.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The recipes of every Workbench package the project depends on that exports
|
|
5
|
+
* them (RECIPES from "<package>/recipes"), read from its node_modules. A
|
|
6
|
+
* package without the export has no pages; one that can't be loaded is named.
|
|
7
|
+
*/
|
|
8
|
+
export declare function recipeSources(dir: string): Promise<{
|
|
9
|
+
sources: RecipeSource[];
|
|
10
|
+
problems: string[];
|
|
11
|
+
}>;
|
|
2
12
|
export interface CliDeps {
|
|
3
13
|
log: (line: string) => void;
|
|
4
14
|
error: (line: string) => void;
|
|
5
15
|
/** Runs a command in the project; returns its exit code. */
|
|
6
16
|
run: (cmd: string, args: readonly string[], cwd: string) => number;
|
|
7
17
|
}
|
|
8
|
-
export declare function main(argv: readonly string[], deps?: CliDeps): number
|
|
18
|
+
export declare function main(argv: readonly string[], deps?: CliDeps): Promise<number>;
|
package/dist/cli.js
CHANGED
|
@@ -13,13 +13,21 @@
|
|
|
13
13
|
// workbench/site.json against the page files and the strings catalogue
|
|
14
14
|
// (siteProblems). With --live, before go-live, a built page's word still in
|
|
15
15
|
// [square brackets] fails too.
|
|
16
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
17
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
18
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
19
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
return path;
|
|
23
|
+
};
|
|
16
24
|
import { spawnSync } from "node:child_process";
|
|
17
25
|
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
18
26
|
import { dirname, join, resolve } from "node:path";
|
|
19
|
-
import { fileURLToPath } from "node:url";
|
|
27
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
20
28
|
import { buildSite, SITE_FILE, siteProblems } from "./builder.js";
|
|
29
|
+
import { gatherRecipes, RECIPES_EXPORT } from "./gather.js";
|
|
21
30
|
import { GROUPS } from "./recipe.js";
|
|
22
|
-
import { RECIPES } from "./recipes/index.js";
|
|
23
31
|
const USAGE = ["Usage: workbench-site list", " workbench-site add [<page>...] [--dir <project>] [--no-install]", " workbench-site check [--live] [--dir <project>]"].join("\n");
|
|
24
32
|
const TIER_NAMES = { always: "always built", ticked: "ask, ticked", offered: "ask, not ticked" };
|
|
25
33
|
const GROUP_NAMES = { "every-site": "Every site", members: "Members", admin: "Admin", business: "For your business" };
|
|
@@ -27,12 +35,49 @@ function version() {
|
|
|
27
35
|
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
28
36
|
return pkg.version;
|
|
29
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* The recipes of every Workbench package the project depends on that exports
|
|
40
|
+
* them (RECIPES from "<package>/recipes"), read from its node_modules. A
|
|
41
|
+
* package without the export has no pages; one that can't be loaded is named.
|
|
42
|
+
*/
|
|
43
|
+
export async function recipeSources(dir) {
|
|
44
|
+
const sources = [];
|
|
45
|
+
const problems = [];
|
|
46
|
+
let deps = {};
|
|
47
|
+
try {
|
|
48
|
+
deps = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).dependencies ?? {};
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return { sources, problems };
|
|
52
|
+
}
|
|
53
|
+
for (const name of Object.keys(deps).filter((d) => /^@mccaskie-labs\/workbench-[a-z]+$/.test(d) && d !== "@mccaskie-labs/workbench-site").sort()) {
|
|
54
|
+
const root = join(dir, "node_modules", ...name.split("/"));
|
|
55
|
+
let target;
|
|
56
|
+
try {
|
|
57
|
+
target = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).exports?.[RECIPES_EXPORT];
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
continue; // Not installed yet: npm install brings it, and its pages with it.
|
|
61
|
+
}
|
|
62
|
+
const file = typeof target === "string" ? target : target && typeof target === "object" ? (target.import ?? target.default) : undefined;
|
|
63
|
+
if (typeof file !== "string")
|
|
64
|
+
continue;
|
|
65
|
+
try {
|
|
66
|
+
const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(resolve(root, file)).href)));
|
|
67
|
+
sources.push({ package: name, recipes: mod.RECIPES });
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
problems.push(`${name}: its recipes couldn't be loaded (${e.message}), so its pages are left out.`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return { sources, problems };
|
|
74
|
+
}
|
|
30
75
|
const realDeps = {
|
|
31
76
|
log: (l) => console.log(l),
|
|
32
77
|
error: (l) => console.error(l),
|
|
33
78
|
run: (cmd, args, cwd) => spawnSync(cmd, [...args], { cwd, stdio: "inherit", shell: process.platform === "win32" }).status ?? 1,
|
|
34
79
|
};
|
|
35
|
-
export function main(argv, deps = realDeps) {
|
|
80
|
+
export async function main(argv, deps = realDeps) {
|
|
36
81
|
const args = [...argv];
|
|
37
82
|
const take = (name) => {
|
|
38
83
|
const at = args.indexOf(name);
|
|
@@ -48,14 +93,20 @@ export function main(argv, deps = realDeps) {
|
|
|
48
93
|
const noInstall = flag("--no-install");
|
|
49
94
|
const live = flag("--live");
|
|
50
95
|
const [command, ...ids] = args;
|
|
96
|
+
// This package's recipes and those of the tools the project has installed.
|
|
97
|
+
const found = await recipeSources(dir);
|
|
98
|
+
const gathered = gatherRecipes(found.sources);
|
|
99
|
+
for (const p of [...found.problems, ...gathered.problems])
|
|
100
|
+
deps.error(`! ${p}`);
|
|
101
|
+
const { catalogue, from } = gathered;
|
|
51
102
|
if (command === "list") {
|
|
52
103
|
for (const g of GROUPS) {
|
|
53
|
-
const rs =
|
|
104
|
+
const rs = catalogue.filter((r) => r.group === g);
|
|
54
105
|
if (!rs.length)
|
|
55
106
|
continue;
|
|
56
107
|
deps.log(`${GROUP_NAMES[g]}:`);
|
|
57
108
|
for (const r of rs)
|
|
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}`);
|
|
109
|
+
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}${from[r.id] ? ` (${from[r.id]})` : ""}`);
|
|
59
110
|
}
|
|
60
111
|
return 0;
|
|
61
112
|
}
|
|
@@ -69,7 +120,7 @@ export function main(argv, deps = realDeps) {
|
|
|
69
120
|
const files = Object.fromEntries((existsSync(pagesDir) ? readdirSync(pagesDir) : []).filter((f) => f.endsWith(".ts")).map((f) => [`src/pages/${f}`, readFileSync(join(pagesDir, f), "utf8")]));
|
|
70
121
|
let problems;
|
|
71
122
|
try {
|
|
72
|
-
problems = siteProblems({ site: read(SITE_FILE), strings: read("strings/strings.en-AU.json"), files, live });
|
|
123
|
+
problems = siteProblems({ site: read(SITE_FILE), strings: read("strings/strings.en-AU.json"), files, live, catalogue });
|
|
73
124
|
}
|
|
74
125
|
catch (e) {
|
|
75
126
|
deps.error(`✗ ${e.message}`);
|
|
@@ -85,7 +136,7 @@ export function main(argv, deps = realDeps) {
|
|
|
85
136
|
deps.error(USAGE);
|
|
86
137
|
return 2;
|
|
87
138
|
}
|
|
88
|
-
const result = buildSite({ read: (p) => (existsSync(join(dir, p)) ? readFileSync(join(dir, p), "utf8") : undefined), add: ids, version: version(), list: (d) => (existsSync(join(dir, d)) ? readdirSync(join(dir, d)) : undefined) });
|
|
139
|
+
const result = buildSite({ read: (p) => (existsSync(join(dir, p)) ? readFileSync(join(dir, p), "utf8") : undefined), add: ids, catalogue, from, version: version(), list: (d) => (existsSync(join(dir, d)) ? readdirSync(join(dir, d)) : undefined) });
|
|
89
140
|
if (result.problems.length) {
|
|
90
141
|
for (const p of result.problems)
|
|
91
142
|
deps.error(`✗ ${p}`);
|
|
@@ -125,4 +176,4 @@ export function main(argv, deps = realDeps) {
|
|
|
125
176
|
}
|
|
126
177
|
const self = fileURLToPath(import.meta.url);
|
|
127
178
|
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(self))
|
|
128
|
-
process.exit(main(process.argv.slice(2)));
|
|
179
|
+
process.exit(await main(process.argv.slice(2)));
|
package/dist/gather.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Recipe } from "./recipe.ts";
|
|
2
|
+
/** The subpath a tool package exports its recipes from, as `export const RECIPES: readonly Recipe[]`. */
|
|
3
|
+
export declare const RECIPES_EXPORT = "./recipes";
|
|
4
|
+
/** One package's recipes, as it exported them. */
|
|
5
|
+
export interface RecipeSource {
|
|
6
|
+
/** Its npm name, such as @mccaskie-labs/workbench-bookings. */
|
|
7
|
+
package: string;
|
|
8
|
+
/** Its RECIPES export: unknown until checked. */
|
|
9
|
+
recipes: unknown;
|
|
10
|
+
}
|
|
11
|
+
export interface GatheredRecipes {
|
|
12
|
+
/** This package's recipes, then each source's, in the order given. */
|
|
13
|
+
catalogue: Recipe[];
|
|
14
|
+
/** Which package each gathered recipe came from, by recipe id: this package's own are left out. */
|
|
15
|
+
from: Record<string, string>;
|
|
16
|
+
/** A source that isn't a list of recipes, or a recipe id another package already has. Its recipes are left out. */
|
|
17
|
+
problems: string[];
|
|
18
|
+
}
|
|
19
|
+
/** This package's recipes and every source's, each id once. Run recipeProblems (buildSite does) on the result. */
|
|
20
|
+
export declare function gatherRecipes(sources: readonly RecipeSource[], own?: readonly Recipe[]): GatheredRecipes;
|
package/dist/gather.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Recipes from other tools (docs/site-planner.md §5, docs/builder-ready.md B5):
|
|
2
|
+
// a tool's own pages are recipes in that tool's package, exported as RECIPES
|
|
3
|
+
// from "<package>/recipes". The CLI finds the Workbench packages a project has
|
|
4
|
+
// installed and gathers theirs beside this package's own; buildSite and
|
|
5
|
+
// siteProblems take the gathered catalogue. Plain data in, plain data out.
|
|
6
|
+
import { recipeProblems } from "./recipe.js";
|
|
7
|
+
import { RECIPES } from "./recipes/index.js";
|
|
8
|
+
/** The subpath a tool package exports its recipes from, as `export const RECIPES: readonly Recipe[]`. */
|
|
9
|
+
export const RECIPES_EXPORT = "./recipes";
|
|
10
|
+
const looksLikeRecipe = (r) => !!r && typeof r === "object" && typeof r.id === "string" && Array.isArray(r.sections) && typeof r.words === "object";
|
|
11
|
+
/** This package's recipes and every source's, each id once. Run recipeProblems (buildSite does) on the result. */
|
|
12
|
+
export function gatherRecipes(sources, own = RECIPES) {
|
|
13
|
+
const catalogue = [...own];
|
|
14
|
+
const owner = new Map(own.map((r) => [r.id, "@mccaskie-labs/workbench-site"]));
|
|
15
|
+
const from = {};
|
|
16
|
+
const problems = [];
|
|
17
|
+
for (const s of [...sources].sort((a, b) => (a.package < b.package ? -1 : a.package > b.package ? 1 : 0))) {
|
|
18
|
+
if (!Array.isArray(s.recipes) || !s.recipes.every(looksLikeRecipe)) {
|
|
19
|
+
problems.push(`${s.package}: its ${RECIPES_EXPORT} export isn't a list of page recipes, so its pages are left out.`);
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const ids = s.recipes.map((r) => r.id);
|
|
23
|
+
const twice = ids.filter((id, i) => ids.indexOf(id) !== i);
|
|
24
|
+
if (twice.length) {
|
|
25
|
+
problems.push(`${s.package}: ${[...new Set(twice)].join(", ")} is in its recipes twice, so its pages are left out.`);
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const clash = s.recipes.filter((r) => owner.has(r.id));
|
|
29
|
+
if (clash.length) {
|
|
30
|
+
problems.push(`${s.package}: ${clash.map((r) => `${r.id} is already ${owner.get(r.id)}'s`).join(", ")}, so its pages are left out.`);
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
for (const r of s.recipes) {
|
|
34
|
+
catalogue.push(r);
|
|
35
|
+
owner.set(r.id, s.package);
|
|
36
|
+
from[r.id] = s.package;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// A package whose recipe can't be built is left out whole, so the site's own pages and the other tools' still build.
|
|
40
|
+
for (const pkg of [...new Set(Object.values(from))]) {
|
|
41
|
+
const bad = catalogue.filter((r) => from[r.id] === pkg).flatMap((r) => recipeProblems(r, catalogue));
|
|
42
|
+
if (!bad.length)
|
|
43
|
+
continue;
|
|
44
|
+
problems.push(`${pkg}: ${bad.join("; ")}. Its pages are left out.`);
|
|
45
|
+
for (const id of Object.keys(from))
|
|
46
|
+
if (from[id] === pkg)
|
|
47
|
+
delete from[id];
|
|
48
|
+
}
|
|
49
|
+
return { catalogue: catalogue.filter((r) => !owner.has(r.id) || owner.get(r.id) === "@mccaskie-labs/workbench-site" || r.id in from), from, problems };
|
|
50
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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, TIERS, type ActionSpec, type Area, type Group, type Recipe, type SectionSpec, type Tier } 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 PageWords, type Recipe, type SectionSpec, type Tier, type ToolSectionFunction } from "./recipe.ts";
|
|
5
5
|
export { RECIPES } from "./recipes/index.ts";
|
|
6
|
+
export { gatherRecipes, RECIPES_EXPORT, type GatheredRecipes, type RecipeSource } from "./gather.ts";
|
|
6
7
|
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,8 @@
|
|
|
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
|
+
export { gatherRecipes, RECIPES_EXPORT } from "./gather.js";
|
|
9
10
|
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";
|
|
@@ -101,6 +108,18 @@ export type SectionSpec = {
|
|
|
101
108
|
turnOn: WordKey;
|
|
102
109
|
turnOff: WordKey;
|
|
103
110
|
live: WordKey;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* A section a tool draws itself (docs/builder-ready.md B5): `fn`, exported by
|
|
114
|
+
* the tool's package `from`, is a ToolSectionFunction. The page file calls it
|
|
115
|
+
* with (request, env, ctx) before drawing, and draws what it gives back with
|
|
116
|
+
* the page's words. `words` are the keys it says, under the page's own prefix.
|
|
117
|
+
*/
|
|
118
|
+
| {
|
|
119
|
+
kind: "tool";
|
|
120
|
+
from: string;
|
|
121
|
+
fn: string;
|
|
122
|
+
words: readonly WordKey[];
|
|
104
123
|
} | {
|
|
105
124
|
kind: "look-preview";
|
|
106
125
|
home: WordKey;
|
|
@@ -122,12 +141,30 @@ export declare const SECTION_FUNCTIONS: {
|
|
|
122
141
|
readonly details: "details";
|
|
123
142
|
readonly account: "account";
|
|
124
143
|
readonly "admin-menu": "list";
|
|
144
|
+
readonly "needs-you": "needsYou";
|
|
125
145
|
readonly "enquiry-form": "enquirySection";
|
|
126
146
|
readonly enquiries: "enquiriesSection";
|
|
127
147
|
readonly "style-guide": "styleGuide";
|
|
128
148
|
readonly "look-preview": "lookPreview";
|
|
129
149
|
readonly "design-switch": "designSwitch";
|
|
150
|
+
readonly tool: "";
|
|
130
151
|
};
|
|
152
|
+
/** Looks up one of the page's words in the visitor's language, with any values it says. */
|
|
153
|
+
export type PageWords = (key: WordKey, values?: Record<string, string>) => string;
|
|
154
|
+
/**
|
|
155
|
+
* What a tool's own section exports (SectionSpec kind "tool"): called with the
|
|
156
|
+
* request, the Worker's env and who is asking before the page is drawn (it may
|
|
157
|
+
* read the database as them, with ctx.accessToken), it gives back a function
|
|
158
|
+
* that draws the section's HTML with the page's words. Every element it draws
|
|
159
|
+
* carries the tool's own wb-<tool>-* classes.
|
|
160
|
+
*/
|
|
161
|
+
export type ToolSectionFunction = (request: Request, env: object, ctx: {
|
|
162
|
+
user: {
|
|
163
|
+
id: string;
|
|
164
|
+
email: string;
|
|
165
|
+
} | null;
|
|
166
|
+
accessToken?: string;
|
|
167
|
+
}) => ((w: PageWords) => string) | Promise<(w: PageWords) => string>;
|
|
131
168
|
/** Sections whose function is in the project's own src/pages/enquiry-store.ts, which the Enquiries recipe writes. */
|
|
132
169
|
export declare const STORE_SECTIONS: ReadonlySet<SectionSpec["kind"]>;
|
|
133
170
|
/** Sections whose function comes from workbench-ui, not this package. */
|
|
@@ -192,6 +229,18 @@ export interface Recipe {
|
|
|
192
229
|
files?: Readonly<Record<string, string>>;
|
|
193
230
|
/** Workbench packages its page needs at least this version of (x.y.z): the builder raises the project's to it. */
|
|
194
231
|
packages?: Readonly<Record<string, string>>;
|
|
232
|
+
/**
|
|
233
|
+
* Its count on the admin dashboard's "needs you" (docs/default-pages.md
|
|
234
|
+
* decision 4): `fn`, exported by `file` (one of its `files`, written whenever
|
|
235
|
+
* the page is on the site), is called with (env, ctx) and gives how many are
|
|
236
|
+
* waiting, or null when they can't be counted. `label` is one of its words.
|
|
237
|
+
* Admin pages only.
|
|
238
|
+
*/
|
|
239
|
+
needsYou?: {
|
|
240
|
+
label: WordKey;
|
|
241
|
+
file: string;
|
|
242
|
+
fn: string;
|
|
243
|
+
};
|
|
195
244
|
/** Its table, as a Workbench tool's own migration: supabase/migrations/<stamp>_<name>.sql and its down file, written once. */
|
|
196
245
|
migration?: {
|
|
197
246
|
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", tool: "" };
|
|
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,12 +39,16 @@ 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":
|
|
45
47
|
return [s.heading, s.empty, s.unavailable, s.remove].filter((k) => !!k);
|
|
46
48
|
case "style-guide":
|
|
47
49
|
return [s.views, s.light, s.dark, s.admin, s.empty, s.layout];
|
|
50
|
+
case "tool":
|
|
51
|
+
return [...s.words];
|
|
48
52
|
case "design-switch":
|
|
49
53
|
return [s.on, s.off, s.turnOn, s.turnOff, s.live];
|
|
50
54
|
case "look-preview":
|
|
@@ -55,7 +59,7 @@ function sectionKeys(s) {
|
|
|
55
59
|
export function recipeKeys(r) {
|
|
56
60
|
const menu = r.menu ? [r.menu.label, r.menu.about].filter((k) => !!k) : [];
|
|
57
61
|
const links = (r.links ?? []).flatMap((l) => [l.label, l.about]);
|
|
58
|
-
return [...new Set([r.pageTitle, ...menu, ...links, ...r.sections.flatMap(sectionKeys)])];
|
|
62
|
+
return [...new Set([r.pageTitle, ...menu, ...links, ...(r.needsYou ? [r.needsYou.label] : []), ...r.sections.flatMap(sectionKeys)])];
|
|
59
63
|
}
|
|
60
64
|
/** The values a word is given when the page says it. */
|
|
61
65
|
function valuesFor(r, key) {
|
|
@@ -138,6 +142,8 @@ export function recipeProblems(r, catalogue) {
|
|
|
138
142
|
p("the account section is for members pages");
|
|
139
143
|
if (s.kind === "admin-menu" && r.area !== "admin")
|
|
140
144
|
p("the admin menu section is for admin pages");
|
|
145
|
+
if (s.kind === "needs-you" && r.area !== "admin")
|
|
146
|
+
p("the needs-you section is for admin pages");
|
|
141
147
|
if (s.kind === "enquiries" && r.area !== "admin")
|
|
142
148
|
p("the enquiries list is for admin pages");
|
|
143
149
|
if (s.kind === "enquiry-form" && r.area !== "public")
|
|
@@ -148,12 +154,22 @@ export function recipeProblems(r, catalogue) {
|
|
|
148
154
|
p("the look previewer is for admin pages");
|
|
149
155
|
if (s.kind === "design-switch" && r.area !== "admin")
|
|
150
156
|
p("design mode's switch is for admin pages");
|
|
157
|
+
if (s.kind === "tool" && (!/^@mccaskie-labs\/workbench-[a-z]+$/.test(s.from) || s.from === "@mccaskie-labs/workbench-site" || !/^[a-z][A-Za-z0-9]*$/.test(s.fn)))
|
|
158
|
+
p(`a tool section comes from another Workbench package and names its function (${s.from}, ${s.fn})`);
|
|
151
159
|
}
|
|
152
160
|
for (const l of r.links ?? [])
|
|
153
161
|
if (!/^\/admin(\/|$)/.test(l.href) || r.area !== "admin")
|
|
154
162
|
p(`link ${l.href}: only admin pages add admin menu links, to /admin addresses`);
|
|
155
163
|
if (r.menu && r.path === null)
|
|
156
164
|
p("a page with no path can't be in the menu");
|
|
165
|
+
if (r.needsYou) {
|
|
166
|
+
if (r.area !== "admin" || r.path === null)
|
|
167
|
+
p("only an admin page has a needs-you count");
|
|
168
|
+
if (!(r.needsYou.file in (r.files ?? {})))
|
|
169
|
+
p(`its needs-you count's file ${r.needsYou.file} isn't one of its files`);
|
|
170
|
+
if (!/^[a-z][A-Za-z0-9]*$/.test(r.needsYou.fn) || !(r.files?.[r.needsYou.file] ?? "").includes(`export async function ${r.needsYou.fn}(`))
|
|
171
|
+
p(`its needs-you file must export async function ${r.needsYou.fn}`);
|
|
172
|
+
}
|
|
157
173
|
if (r.migration && !/^workbench_site_[a-z0-9_]+$/.test(r.migration.name))
|
|
158
174
|
p("a migration is named workbench_site_<what>, so Control treats it as a Workbench tool's own");
|
|
159
175
|
for (const [name, v] of Object.entries(r.packages ?? {}))
|
package/dist/recipes/admin.js
CHANGED
|
@@ -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:
|
|
8
|
+
version: 2,
|
|
9
9
|
title: "Admin home",
|
|
10
|
-
does: "
|
|
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:
|
|
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
|
};
|
package/dist/sections.d.ts
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.12.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",
|