fix(views): what the throwaway view revealed (views phase 6) #105

Merged
abiwab merged 2 commits from fix/views-p6-findings into feat/views-architecture 2026-11-05 23:20:08 +01:00
11 changed files with 79 additions and 47 deletions

View file

@ -22,7 +22,7 @@ import {
resolveCliFormat, resolveCliFormat,
} from "../core/cli-views"; } from "../core/cli-views";
import { import {
RECIPE_VIEW_SETTINGS, EXPORT_VIEW_SETTINGS,
STEP_QTY_ALIAS_ARG, STEP_QTY_ALIAS_ARG,
readRecipeSettingArgs, readRecipeSettingArgs,
readViewSettingArgs, readViewSettingArgs,
@ -35,7 +35,7 @@ export default defineCommand({
meta: { meta: {
name: "export", name: "export",
description: description:
"Export a view of a recipe (the recipe or its work plan) to Markdown or print-ready HTML", "Export a view of a recipe (see --view) to Markdown, print-ready HTML or plain text",
}, },
args: { args: {
file: { file: {
@ -46,13 +46,13 @@ export default defineCommand({
format: { format: {
type: "string", type: "string",
description: description:
"Output format: md (Markdown), html (print-ready A4 HTML) or text (plain text). Each view offers only the formats it has (the work plan all three)", "Output format: md (Markdown), html (print-ready A4 HTML) or text (plain text), among those the chosen view has",
}, },
output: { output: {
type: "string", type: "string",
alias: "o", alias: "o",
description: description:
"Output file path (default: same directory as input, with new extension; .work-plan before it for the work plan)", "Output file path (default: same directory as input, with new extension; the view's name before it for any view but the recipe, e.g. .work-plan)",
}, },
scale: { scale: {
type: "string", type: "string",
@ -68,7 +68,7 @@ export default defineCommand({
description: "Skip ingredient database", description: "Skip ingredient database",
default: false, default: false,
}, },
...viewSettingArgs(RECIPE_VIEW_SETTINGS), ...viewSettingArgs(EXPORT_VIEW_SETTINGS),
...STEP_QTY_ALIAS_ARG, ...STEP_QTY_ALIAS_ARG,
...recipeSettingArgs(), ...recipeSettingArgs(),
"bakers-reference": { "bakers-reference": {
@ -110,7 +110,7 @@ export default defineCommand({
const bakersReference = const bakersReference =
(args["bakers-reference"] as string) || (args["bakers-reference"] as string) ||
(args["bakers-math"] ? "" : undefined); (args["bakers-math"] ? "" : undefined);
const settings = readViewSettingArgs(args, RECIPE_VIEW_SETTINGS); const settings = readViewSettingArgs(args, EXPORT_VIEW_SETTINGS);
const recipe = readRecipeSettingArgs(args); const recipe = readRecipeSettingArgs(args);
let view: ReturnType<typeof resolveExportView>; let view: ReturnType<typeof resolveExportView>;
let format: ReturnType<typeof resolveCliFormat>; let format: ReturnType<typeof resolveCliFormat>;

View file

@ -16,7 +16,7 @@ import {
import { DEFAULT_VIEW_SETTINGS } from "@gram-lang/renderer"; import { DEFAULT_VIEW_SETTINGS } from "@gram-lang/renderer";
import { cliViewName } from "../core/cli-views"; import { cliViewName } from "../core/cli-views";
import { import {
RECIPE_VIEW_SETTINGS, EXPORT_VIEW_SETTINGS,
STEP_QTY_ALIAS_ARG, STEP_QTY_ALIAS_ARG,
readRecipeSettingArgs, readRecipeSettingArgs,
readViewSettingArgs, readViewSettingArgs,
@ -29,7 +29,7 @@ export default defineCommand({
meta: { meta: {
name: "print", name: "print",
description: description:
"Generate a print-ready HTML of a view (the recipe or its work plan) and open it in the browser", "Generate a print-ready HTML of a view of a recipe (see --view) and open it in the browser",
}, },
args: { args: {
file: { file: {
@ -57,7 +57,7 @@ export default defineCommand({
description: "Skip ingredient database", description: "Skip ingredient database",
default: false, default: false,
}, },
...viewSettingArgs(RECIPE_VIEW_SETTINGS), ...viewSettingArgs(EXPORT_VIEW_SETTINGS),
...STEP_QTY_ALIAS_ARG, ...STEP_QTY_ALIAS_ARG,
...recipeSettingArgs(), ...recipeSettingArgs(),
"bakers-reference": { "bakers-reference": {
@ -91,7 +91,7 @@ export default defineCommand({
const bakersReference = const bakersReference =
(args["bakers-reference"] as string) || (args["bakers-reference"] as string) ||
(args["bakers-math"] ? "" : undefined); (args["bakers-math"] ? "" : undefined);
const settings = readViewSettingArgs(args, RECIPE_VIEW_SETTINGS); const settings = readViewSettingArgs(args, EXPORT_VIEW_SETTINGS);
const recipe = readRecipeSettingArgs(args); const recipe = readRecipeSettingArgs(args);
let view: ReturnType<typeof resolveExportView>; let view: ReturnType<typeof resolveExportView>;
try { try {

View file

@ -84,6 +84,13 @@ export function resolveCliFormat(
formats: CliFormats, formats: CliFormats,
): Format { ): Format {
const offered = cliFormatsOf(view, formats); const offered = cliFormatsOf(view, formats);
if (offered.length === 0) {
// A view shown on screen only (html alone): nothing to list.
throw new GramCLIError(
`The ${cliViewName(view.id)} view has none of the formats this command writes.`,
ExitCode.Error,
);
}
if (!offered.includes(name)) { if (!offered.includes(name)) {
const known = name in formats; const known = name in formats;
throw new GramCLIError( throw new GramCLIError(

View file

@ -10,7 +10,7 @@ const SETTING = VIEW_SETTINGS.comments;
export const COMMENTS_FLAG_VALUES: readonly string[] = flagValues(SETTING); export const COMMENTS_FLAG_VALUES: readonly string[] = flagValues(SETTING);
export const COMMENTS_FLAG_DESCRIPTION = `Whether to show the comments of the recipe (// like this): ${flagValueList(SETTING)} (default: ${flagDefault(SETTING)}). Applies to the recipe and to the work plan.`; export const COMMENTS_FLAG_DESCRIPTION = `Whether to show the comments of the recipe (// like this): ${flagValueList(SETTING)} (default: ${flagDefault(SETTING)}).`;
/** Reports and exits on an unusable value, like every setting flag. */ /** Reports and exits on an unusable value, like every setting flag. */
export function parseComments(value: unknown): CommentsMode | undefined { export function parseComments(value: unknown): CommentsMode | undefined {

View file

@ -5,6 +5,7 @@ import {
type ViewSettings, type ViewSettings,
VIEW_SETTINGS, VIEW_SETTINGS,
parseRecipeSettings, parseRecipeSettings,
views,
} from "@gram-lang/renderer"; } from "@gram-lang/renderer";
import type { ArgDef } from "citty"; import type { ArgDef } from "citty";
import { COMMENTS_FLAG_DESCRIPTION } from "./comments-flag"; import { COMMENTS_FLAG_DESCRIPTION } from "./comments-flag";
@ -183,15 +184,16 @@ export const STEP_QTY_ALIAS_ARG: Record<string, ArgDef> = {
}, },
}; };
/** Every view setting the recipe view honors: what `print`, `export` and `view` expose. */ /**
export const RECIPE_VIEW_SETTINGS: readonly ViewSettingKey[] = [ * Every view setting a view of the registry honors: what `print` and `export`
"miseEnPlace", * expose, since their `--view` picks any view. Read from the registry, so the
"rests", * setting a new view brings gets its flag here with no edit.
"comments", */
"nutritionBasis", export const EXPORT_VIEW_SETTINGS: readonly ViewSettingKey[] = (
"bakersMathOnly", Object.keys(VIEW_SETTINGS) as ViewSettingKey[]
"stepQuantities", ).filter((key) =>
]; views.some((view) => (view.honors as readonly string[]).includes(key)),
);
/** What the work plan honors: `gram plan`. */ /** What the work plan honors: `gram plan`. */
export const WORK_PLAN_SETTINGS: readonly ViewSettingKey[] = [ export const WORK_PLAN_SETTINGS: readonly ViewSettingKey[] = [

View file

@ -66,6 +66,15 @@ describe("formats", () => {
); );
}); });
it("says so when a view has none of the formats a command writes", () => {
// A view on screen only: gram export's html is the print layout.
const screenOnly = { ...recipe, id: "notes", formats: ["html"] } as const;
expect(cliFormatsOf(screenOnly, EXPORT_FORMATS)).toEqual([]);
expect(() => resolveCliFormat(screenOnly, "html", EXPORT_FORMATS)).toThrow(
"The notes view has none of the formats this command writes.",
);
});
it("gives every export format a file extension", () => { it("gives every export format a file extension", () => {
for (const name of Object.keys(EXPORT_FORMATS)) { for (const name of Object.keys(EXPORT_FORMATS)) {
expect(EXPORT_EXTENSIONS[name]).toBeString(); expect(EXPORT_EXTENSIONS[name]).toBeString();

View file

@ -3,7 +3,7 @@ import { runPipeline } from "../src/core/pipeline";
import { cleanupTmpFile, makeDb, writeTmpFile } from "./helpers"; import { cleanupTmpFile, makeDb, writeTmpFile } from "./helpers";
import { RECIPE_SETTINGS, VIEW_SETTINGS } from "@gram-lang/renderer"; import { RECIPE_SETTINGS, VIEW_SETTINGS } from "@gram-lang/renderer";
import { import {
RECIPE_VIEW_SETTINGS, EXPORT_VIEW_SETTINGS,
STEP_QTY_ALIAS_ARG, STEP_QTY_ALIAS_ARG,
readRecipeSettingArgs, readRecipeSettingArgs,
readViewSettingArgs, readViewSettingArgs,
@ -19,12 +19,12 @@ describe("setting flags", () => {
expect(settingFlagName("massStandardization")).toBe("mass-standardization"); expect(settingFlagName("massStandardization")).toBe("mass-standardization");
}); });
it("give the recipe view a flag for every view setting", () => { it("give export and print a flag for every setting a view honors", () => {
expect([...RECIPE_VIEW_SETTINGS].sort()).toEqual( expect([...EXPORT_VIEW_SETTINGS].sort()).toEqual(
Object.keys(VIEW_SETTINGS).sort(), Object.keys(VIEW_SETTINGS).sort(),
); );
const args = viewSettingArgs(RECIPE_VIEW_SETTINGS); const args = viewSettingArgs(EXPORT_VIEW_SETTINGS);
for (const key of RECIPE_VIEW_SETTINGS) { for (const key of EXPORT_VIEW_SETTINGS) {
expect(args[settingFlagName(key)]).toBeDefined(); expect(args[settingFlagName(key)]).toBeDefined();
} }
}); });
@ -46,7 +46,7 @@ describe("setting flags", () => {
describe("readViewSettingArgs", () => { describe("readViewSettingArgs", () => {
it("leaves out a setting whose flag is absent", () => { it("leaves out a setting whose flag is absent", () => {
expect(readViewSettingArgs({}, RECIPE_VIEW_SETTINGS)).toEqual({}); expect(readViewSettingArgs({}, EXPORT_VIEW_SETTINGS)).toEqual({});
}); });
it("reads the CLI spelling back to the setting's value", () => { it("reads the CLI spelling back to the setting's value", () => {
@ -58,7 +58,7 @@ describe("readViewSettingArgs", () => {
"bakers-math-only": true, "bakers-math-only": true,
"step-quantities": "hide", "step-quantities": "hide",
}, },
RECIPE_VIEW_SETTINGS, EXPORT_VIEW_SETTINGS,
), ),
).toEqual({ ).toEqual({
miseEnPlace: "perDay", miseEnPlace: "perDay",
@ -72,7 +72,7 @@ describe("readViewSettingArgs", () => {
expect( expect(
readViewSettingArgs( readViewSettingArgs(
{ nutrition: "per-100g", "step-qty": false }, { nutrition: "per-100g", "step-qty": false },
RECIPE_VIEW_SETTINGS, EXPORT_VIEW_SETTINGS,
), ),
).toEqual({ nutritionBasis: "per100g", stepQuantities: "hide" }); ).toEqual({ nutritionBasis: "per100g", stepQuantities: "hide" });
}); });
@ -86,7 +86,7 @@ describe("readViewSettingArgs", () => {
"step-quantities": "show", "step-quantities": "show",
"step-qty": false, "step-qty": false,
}, },
RECIPE_VIEW_SETTINGS, EXPORT_VIEW_SETTINGS,
), ),
).toEqual({ nutritionBasis: "total", stepQuantities: "show" }); ).toEqual({ nutritionBasis: "total", stepQuantities: "show" });
}); });
@ -107,7 +107,7 @@ describe("readViewSettingArgs", () => {
const out = spyOn(process.stdout, "write").mockImplementation(() => true); const out = spyOn(process.stdout, "write").mockImplementation(() => true);
try { try {
expect(() => expect(() =>
readViewSettingArgs({ nutrition: "bad" }, RECIPE_VIEW_SETTINGS), readViewSettingArgs({ nutrition: "bad" }, EXPORT_VIEW_SETTINGS),
).toThrow("exit"); ).toThrow("exit");
} finally { } finally {
exit.mockRestore(); exit.mockRestore();

View file

@ -31,14 +31,26 @@ describe("the view tabs and the inspector menu", () => {
const t = getDictionary("en"); const t = getDictionary("en");
const tabs = viewTabs(t); const tabs = viewTabs(t);
const menu = inspectorOptions(t); const menu = inspectorOptions(t);
expect(tabs).toEqual([ // Read from the registry, not listed here: a view added there needs no
{ label: "Recipe", value: "recipe" }, // edit in this test.
{ label: "Work plan", value: "workPlan" }, expect(tabs.map((o) => o.value)).toEqual(
]); outputs.filter((o) => o.kind === "renderer").map((o) => o.id),
expect(menu.map((o) => o.value)).toEqual(["ast", "json", "json-tree"]); );
expect(menu.map((o) => o.value)).toEqual(
outputs.filter((o) => o.kind === "inspector").map((o) => o.id),
);
expect([...tabs, ...menu].map((o) => o.value)).toEqual( expect([...tabs, ...menu].map((o) => o.value)).toEqual(
outputs.map((o) => o.id), outputs.map((o) => o.id),
); );
expect(tabs).toContainEqual({ label: "Recipe", value: "recipe" });
expect(tabs).toContainEqual({ label: "Work plan", value: "workPlan" });
});
it("names every output, in every language", () => {
for (const lang of ["en", "fr"] as const) {
const names = getDictionary(lang).renderer.outputs;
for (const output of outputs) expect(names[output.id]).toBeTruthy();
}
}); });
it("names them in the playground's language", () => { it("names them in the playground's language", () => {

View file

@ -1,4 +1,5 @@
import { afterEach, describe, expect, it } from "bun:test"; import { afterEach, describe, expect, it } from "bun:test";
import { outputs } from "@gram-lang/renderer";
import { Client, type Note, URI } from "./helpers/lsp-client"; import { Client, type Note, URI } from "./helpers/lsp-client";
/* /*
@ -76,14 +77,8 @@ describe("the views protocol", () => {
}; };
}; };
const listed = result.capabilities.experimental?.gramViews?.outputs ?? []; const listed = result.capabilities.experimental?.gramViews?.outputs ?? [];
expect(listed.map((o) => o.id)).toEqual([ expect(listed.map((o) => o.id)).toEqual(outputs.map((o) => o.id));
"recipe", expect(listed.find((o) => o.id === "workPlan")?.label).toBe("Work plan");
"workPlan",
"ast",
"json",
"json-tree",
]);
expect(listed[1]?.label).toBe("Work plan");
}, 20_000); }, 20_000);
it("sends nothing to a views client until it says what is open", async () => { it("sends nothing to a views client until it says what is open", async () => {

View file

@ -16,12 +16,13 @@ A view never imports another view. What two views share goes in `shared/`. `test
## Adding a view ## Adding a view
1. Create `src/views/<id>/`. It imports only its own files, `shared/`, the contract, the settings, the types, `prepareViews` and the pipeline packages. 1. Create `src/views/<id>/`. It imports only its own files, `shared/`, the contract, the settings, the types, `prepareViews` and the pipeline packages.
2. Write its `view.ts`, a `ViewDefinition`: its `formats` (only those it can really express), the settings it `honors`, what it `needs` from the input (`schedule`, `runSheet`, `serveTimes`), and `render()`. Return `null` when the recipe has nothing for it. 2. Write its `view.ts`, a `ViewDefinition`: its `formats` (only those it can really express, and always `html`: the editor's panel and the playground show a view in html; `gram export` writes `markdown`, `print` and `text`, and `gram print` needs `print`, so a view with `html` alone is on screen only), the settings it `honors`, what it `needs` from the input (`schedule`, `runSheet`, `serveTimes`), and `render()`. Return `null` when the recipe has nothing for it.
3. Add it to `views` in `src/views/registry.ts`, and to `outputs` in `src/outputs.ts` (written out, not spread, so a bundler can drop the views a page does not use). Give it a name in every language, under `renderer.outputs` of `@gram-lang/i18n`: the surfaces list the outputs by that name. 3. Add it to `views` in `src/views/registry.ts`, and to `outputs` in `src/outputs.ts` (written out, not spread, so a bundler can drop the views a page does not use). Give it a name in every language, under `renderer.outputs` of `@gram-lang/i18n`: the surfaces list the outputs by that name.
4. Run `tests/views-contract.test.ts`. It renders the view in each format for every fixture, checks the escaping, and checks that the view reacts to each setting it honors and to no other. If it honors a setting none of the fixtures shows, extend a fixture. 4. Run `tests/views-contract.test.ts`. It renders the view in each format for every fixture, checks the escaping, and checks that the view reacts to each setting it honors and to no other. If it honors a setting none of the fixtures shows, extend a fixture.
5. If the view brings a new setting: add its descriptor to `VIEW_SETTINGS` in `src/settings.ts`, a probe to `PROBES` in the contract test, a `gram.*` key in the VS Code extension's `package.json` (the parity test fails until it exists), and the docs in English and French. 5. If the view brings a new setting: add its descriptor to `VIEW_SETTINGS` in `src/settings.ts`, a probe to `PROBES` in the contract test, a `gram.*` key in the VS Code extension's `package.json` (the parity test fails until it exists), and the docs in English and French.
6. Document the view in English and French (what it shows, its formats, the settings it follows), and add a changeset: a new view is a new feature of every surface.
Nothing else should need an edit: the surfaces list their outputs from the registry, so a new view appears in the CLI, VS Code and the playground. Removing a view is the reverse. Nothing else should need an edit, not even a test of a surface: the surfaces list their outputs from the registry, so a new view appears in the CLI, VS Code and the playground. Removing a view is the reverse.
Every surface lists its outputs from the registry: the language server and the VS Code extension, the playground (as tabs, with the formats of each view), and the CLI (`--view` of `gram export` and `gram print`, each `--format` checked against the view's `formats`). The terminal views of `gram view` and `gram cook` are not renderer strings and stay apart. Every surface lists its outputs from the registry: the language server and the VS Code extension, the playground (as tabs, with the formats of each view), and the CLI (`--view` of `gram export` and `gram print`, each `--format` checked against the view's `formats`). The terminal views of `gram view` and `gram cook` are not renderer strings and stay apart.

View file

@ -46,11 +46,17 @@ const input = prepareViews(compiled, settings, { lang: "fr" });
describe("the views registry", () => { describe("the views registry", () => {
it("lists each view once, with formats and settings that exist", () => { it("lists each view once, with formats and settings that exist", () => {
// Read from the registry, not listed here: a view added there needs no
// edit in this test.
const ids = views.map((view) => view.id); const ids = views.map((view) => view.id);
expect(ids).toEqual(["recipe", "workPlan"]); expect(new Set(ids).size).toBe(ids.length);
expect(ids).toContain("recipe");
expect(ids).toContain("workPlan");
for (const view of views) { for (const view of views) {
expect(view.kind).toBe("renderer"); expect(view.kind).toBe("renderer");
expect(view.formats.length).toBeGreaterThan(0); // Every view can be shown on screen: the editor's panel and the
// playground's preview render it in html.
expect(view.formats).toContain("html");
for (const format of view.formats) expect(FORMATS).toContain(format); for (const format of view.formats) expect(FORMATS).toContain(format);
for (const key of view.honors) for (const key of view.honors)
expect(Object.keys(VIEW_SETTINGS)).toContain(key); expect(Object.keys(VIEW_SETTINGS)).toContain(key);