From 43fd0e022e2f4c87f0aeb578a7126241daadcac5 Mon Sep 17 00:00:00 2001 From: abiwab Date: Sun, 4 Oct 2026 12:46:25 +0200 Subject: [PATCH 1/6] feat(renderer): expose the words of the production sheet and the instant helpers --- packages/renderer/src/index.ts | 8 ++++- packages/renderer/src/run-sheet.ts | 55 ++++++++++++++++++++++++------ packages/scheduler/src/index.ts | 1 + 3 files changed, 52 insertions(+), 12 deletions(-) diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.ts index 93b6e5f1..69631ca8 100644 --- a/packages/renderer/src/index.ts +++ b/packages/renderer/src/index.ts @@ -16,12 +16,18 @@ export { toMarkdown } from "./formatters/markdown"; export { toHTML } from "./formatters/html"; export { toPrintHTML } from "./formatters/print"; export { + describeRunSheet, runSheetToHTML, runSheetToMarkdown, runSheetToPrintHTML, runSheetToText, } from "./run-sheet"; -export type { RunSheetRenderOptions } from "./run-sheet"; +export type { + RunSheetDayModel, + RunSheetLine, + RunSheetModel, + RunSheetRenderOptions, +} from "./run-sheet"; export { formatDecimalToFraction, getQty, diff --git a/packages/renderer/src/run-sheet.ts b/packages/renderer/src/run-sheet.ts index aa064dc7..36a968b7 100644 --- a/packages/renderer/src/run-sheet.ts +++ b/packages/renderer/src/run-sheet.ts @@ -19,8 +19,17 @@ export interface RunSheetRenderOptions { formatDuration?: (minutes: number) => string; } -/** One line of the sheet, already in words. Plain text: each output escapes it its own way. */ -interface SheetLine { +/** + * One line of the sheet, already in words. Plain text: each output escapes it + * its own way. + */ +export interface RunSheetLine { + /** The id of the task in the recipe's graph. */ + task: string; + kind: RunSheetEntry["kind"]; + /** ISO instants, UTC, exact to the minute. */ + start: string; + end: string; /** "around 21:40" */ when: string; title: string; @@ -32,15 +41,17 @@ interface SheetLine { active: boolean; } -interface SheetDay { +export interface RunSheetDayModel { + /** "Saturday, October 10 · D-1" */ heading: string; - lines: SheetLine[]; + lines: RunSheetLine[]; } -interface SheetModel { +/** A production sheet in words: what every output (text, Markdown, HTML, calendar) is made from. */ +export interface RunSheetModel { title: string; servedAt: string; - days: SheetDay[]; + days: RunSheetDayModel[]; problems: string[]; } @@ -81,13 +92,24 @@ const shortDay = (date: string, lang?: string) => const fill = (template: string, values: Record) => template.replace(/\{(\w+)\}/g, (_, k: string) => values[k] ?? `{${k}}`); -/** The words of a sheet, from the plan's structure and the recipe it is for. */ +/** + * The words of a sheet, from the plan's structure and the recipe it is for: + * the title, the days with their lines, and what could not be fixed. + */ +export function describeRunSheet( + sheet: RunSheet, + data: RenderableCompilationResult, + options: RunSheetRenderOptions = {}, +): RunSheetModel { + return buildModel(sheet, data, options, 0); +} + function buildModel( sheet: RunSheet, data: RenderableCompilationResult, options: RunSheetRenderOptions, recipeIndex: number, -): SheetModel { +): RunSheetModel { const t = getDictionary(options.lang).renderer; const lang = options.lang; const step = options.roundTo && options.roundTo > 0 ? options.roundTo : 5; @@ -151,7 +173,7 @@ function buildModel( hourCycle: "h23", }).format(new Date(iso)); - const lineOf = (entry: RunSheetEntry): SheetLine => { + const lineOf = (entry: RunSheetEntry): RunSheetLine => { const startDate = entry.startLocal.slice(0, 10); const when = fill(t.runSheetAround, { time: roundedClock(entry.startLocal, step), @@ -202,10 +224,21 @@ function buildModel( }); } } - return { when, title, detail, length, note, active: entry.active }; + return { + task: entry.task, + kind: entry.kind, + start: entry.start, + end: entry.end, + when, + title, + detail, + length, + note, + active: entry.active, + }; }; - const daysOut: SheetDay[] = (recipe?.days ?? []).map((day) => ({ + const daysOut: RunSheetDayModel[] = (recipe?.days ?? []).map((day) => ({ heading: `${longDate(day.date, lang)} · ${sessionDayLabel(day.daysBefore, t)}`, lines: day.entries .filter((entry) => entry.kind !== "step" || entry.minutes > 0) diff --git a/packages/scheduler/src/index.ts b/packages/scheduler/src/index.ts index d9f5769f..220e917c 100644 --- a/packages/scheduler/src/index.ts +++ b/packages/scheduler/src/index.ts @@ -53,3 +53,4 @@ export type { TimeRange, } from "./projection"; export { WEEKDAYS, type Weekday } from "./time"; +export { parseInstant, parseLocalIso, toLocalIso, toUtcIso } from "./time"; -- 2.54.0 From ea8016439d33178977c716633f2b627ecc6f8467 Mon Sep 17 00:00:00 2001 From: abiwab Date: Sun, 4 Oct 2026 12:46:26 +0200 Subject: [PATCH 2/6] feat(cli): add gram plan, the --rests option and a calendar export --- .changeset/cli-mise-en-place-option.md | 2 + .changeset/cli-plan-command.md | 10 ++ packages/cli/package.json | 3 +- packages/cli/src/commands/cook.ts | 17 +- packages/cli/src/commands/export.ts | 7 + packages/cli/src/commands/plan.ts | 157 ++++++++++++++++++ packages/cli/src/commands/print.ts | 7 + packages/cli/src/commands/view.ts | 7 + packages/cli/src/index.ts | 1 + packages/cli/src/services/exporter.ts | 2 +- packages/cli/src/services/ics.ts | 93 +++++++++++ packages/cli/src/services/plan-flags.ts | 128 +++++++++++++++ packages/cli/src/services/planner.ts | 110 +++++++++++++ packages/cli/src/services/rests-flag.ts | 24 +++ packages/cli/src/services/viewer.ts | 4 + packages/cli/tests/ics.test.ts | 81 ++++++++++ packages/cli/tests/plan-cli.test.ts | 206 ++++++++++++++++++++++++ packages/cli/tests/plan-flags.test.ts | 128 +++++++++++++++ 18 files changed, 984 insertions(+), 3 deletions(-) create mode 100644 .changeset/cli-plan-command.md create mode 100644 packages/cli/src/commands/plan.ts create mode 100644 packages/cli/src/services/ics.ts create mode 100644 packages/cli/src/services/plan-flags.ts create mode 100644 packages/cli/src/services/planner.ts create mode 100644 packages/cli/src/services/rests-flag.ts create mode 100644 packages/cli/tests/ics.test.ts create mode 100644 packages/cli/tests/plan-cli.test.ts create mode 100644 packages/cli/tests/plan-flags.test.ts diff --git a/.changeset/cli-mise-en-place-option.md b/.changeset/cli-mise-en-place-option.md index 68a0e83d..a515bfd2 100644 --- a/.changeset/cli-mise-en-place-option.md +++ b/.changeset/cli-mise-en-place-option.md @@ -5,3 +5,5 @@ **CLI / View & Export**: `gram view`, `gram export` and `gram print` accept a new `--mise-en-place ` option, to see the recipe with the mise en place planned right before each section (the default), all at the start, or at the start of each working day: - The total and idle times shown follow the chosen option; the active and preparation times stay the same +- A new `--rests ` option does the same for a rest written as a range (`~_{12-24h}`): the shortest by default, the middle or the longest +- `gram cook` accepts both options too, for the total time it shows diff --git a/.changeset/cli-plan-command.md b/.changeset/cli-plan-command.md new file mode 100644 index 00000000..88650f63 --- /dev/null +++ b/.changeset/cli-plan-command.md @@ -0,0 +1,10 @@ +--- +"@gram-lang/cli": minor +--- + +**CLI / Plan**: A new `gram plan --serve "2026-10-11 13:00"` command plans a recipe backward from the time it is served, and writes a production sheet with a time for every task: + +- `--tz Europe/Paris` sets the time zone (this machine's by default), and `--available` says when you can cook, as many times as needed: `08:00-22:00` for every day, `fri=18:00-22:00` for a day of the week, `2026-10-09=none` for a date (nothing means all day) +- A rest written as a range (`~_{8-16h}`) is made longer or shorter to keep your own work out of the hours you are not available, and the sheet says which one and why; what cannot be fixed is listed at the end +- `--format text|md|html|json` picks the output, and `--ics plan.ics` also writes a calendar file with an event for every task and an alarm on the ones that need your hands +- `--mise-en-place`, `--rests`, `--scale` and `--stock` work as they do in `gram view` diff --git a/packages/cli/package.json b/packages/cli/package.json index 773ea430..808b2474 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -60,6 +60,7 @@ "@gram-lang/modules": "workspace:*", "@gram-lang/parser": "workspace:*", "@gram-lang/renderer": "workspace:*", + "@gram-lang/scheduler": "workspace:*", "ai": "^7.0.22", "chalk": "^6.0.1", "citty": "^0.2.2", @@ -77,4 +78,4 @@ "@types/react": "^19.2.17", "react-devtools-core": "^7.0.1" } -} \ No newline at end of file +} diff --git a/packages/cli/src/commands/cook.ts b/packages/cli/src/commands/cook.ts index 1bf5ffdf..75c9561e 100644 --- a/packages/cli/src/commands/cook.ts +++ b/packages/cli/src/commands/cook.ts @@ -12,6 +12,11 @@ import { loadDbSafe } from "../core/db"; import { runPipeline } from "../core/pipeline"; import { reportUnusedStock, resolveStockFromConfig } from "../core/stock"; import { reportRejectedIngredients } from "../ui/diagnostics"; +import { + MISE_EN_PLACE_FLAG_DESCRIPTION, + parseMiseEnPlace, +} from "../services/mise-en-place-flag"; +import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag"; import { resolveScaleArg, getScaleWarnings } from "../services/scaler"; import { prepareRecipeData } from "../ui/cook/prepare"; import App from "../ui/cook/App"; @@ -43,6 +48,14 @@ export default defineCommand({ description: "Skip ingredient database", default: false, }, + "mise-en-place": { + type: "string", + description: MISE_EN_PLACE_FLAG_DESCRIPTION, + }, + rests: { + type: "string", + description: RESTS_FLAG_DESCRIPTION, + }, stock: { type: "string", description: @@ -64,6 +77,8 @@ export default defineCommand({ config.language, config.paths, )) ?? 1; + const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]); + const rests = parseRests(args.rests); const stock = resolveStockFromConfig(args.stock, config); const s = spinner(); @@ -81,7 +96,7 @@ export default defineCommand({ stock, }); reportUnusedStock("gram cook", "cooked", stock, [{ usedStock }]); - totalTime = scheduleTimes(compiled).totalTime; + totalTime = scheduleTimes(compiled, miseEnPlace, rests).totalTime; const massMap: Record = {}; for (const item of analyzed?.result?.shopping_list ?? []) { if (item.id && typeof item.normalizedMass === "number") diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.ts index d82bab8f..1aeef5ce 100644 --- a/packages/cli/src/commands/export.ts +++ b/packages/cli/src/commands/export.ts @@ -13,6 +13,7 @@ import { MISE_EN_PLACE_FLAG_DESCRIPTION, parseMiseEnPlace, } from "../services/mise-en-place-flag"; +import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag"; import { NUTRITION_BASIS_FLAG_DESCRIPTION, parseNutritionBasis, @@ -82,6 +83,10 @@ export default defineCommand({ type: "string", description: MISE_EN_PLACE_FLAG_DESCRIPTION, }, + rests: { + type: "string", + description: RESTS_FLAG_DESCRIPTION, + }, stock: { type: "string", description: @@ -115,6 +120,7 @@ export default defineCommand({ const bakersMathOnly = args["bakers-math-only"] as boolean; const nutritionBasis = parseNutritionBasis(args.nutrition); const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]); + const rests = parseRests(args.rests); const stock = resolveStockFromConfig(args.stock, config); const outputPath = args.output @@ -134,6 +140,7 @@ export default defineCommand({ bakersMathOnly, nutritionBasis, miseEnPlace, + rests, lang: config.language, paths: config.paths, stock, diff --git a/packages/cli/src/commands/plan.ts b/packages/cli/src/commands/plan.ts new file mode 100644 index 00000000..ecf15da8 --- /dev/null +++ b/packages/cli/src/commands/plan.ts @@ -0,0 +1,157 @@ +import { defineCommand } from "citty"; +import { log } from "@clack/prompts"; +import { writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { parseInstant, toUtcIso } from "@gram-lang/scheduler"; +import { version } from "../../package.json"; +import { loadConfig } from "../core/config"; +import { resolveScaleArg } from "../services/scaler"; +import { reportUnusedStock, resolveStockFromConfig } from "../core/stock"; +import { + MISE_EN_PLACE_FLAG_DESCRIPTION, + parseMiseEnPlace, +} from "../services/mise-en-place-flag"; +import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag"; +import { + collectFlag, + parseAvailability, + parseServe, + parseTimeZone, +} from "../services/plan-flags"; +import { + PLAN_FORMATS, + type PlanFormat, + formatPlan, + planRecipe, + planToICS, +} from "../services/planner"; +import { ExitCode, GramCLIError } from "../errors"; + +export default defineCommand({ + meta: { + name: "plan", + version, + description: + "Plan a recipe backward from the time it is served: when to start each task, given when you are available", + }, + args: { + file: { + type: "positional", + required: true, + description: "Path to a .gram recipe file", + }, + serve: { + type: "string", + required: true, + description: + 'When it is served, a local date and time (e.g. "2026-10-11 13:00")', + }, + tz: { + type: "string", + description: + "IANA time zone of the serving time and of your availability (default: this machine's, e.g. Europe/Paris)", + }, + available: { + type: "string", + description: + "When you are available, repeatable: 08:00-22:00 (every day), fri=18:00-22:00 (a day of the week), 2026-10-09=none (a date). Several ranges: 08:00-09:00,18:00-22:00. Default: all day", + }, + format: { + type: "string", + description: `Output format: ${PLAN_FORMATS.join(" | ")} (default: text)`, + }, + ics: { + type: "string", + description: + "Also write the plan as an iCalendar file (events in UTC, an alarm on every task that needs your hands)", + }, + now: { + type: "string", + description: + "The present, to warn when the first task should already have started (default: now). Mostly for tests", + }, + scale: { + type: "string", + description: + "Scale factor (e.g. 1.5) or reference ingredient (e.g. farine=300g)", + }, + "mise-en-place": { + type: "string", + description: MISE_EN_PLACE_FLAG_DESCRIPTION, + }, + rests: { + type: "string", + description: RESTS_FLAG_DESCRIPTION, + }, + stock: { + type: "string", + description: + "Comma-separated @use specifiers already on hand for this plan (e.g. @bases/pate.gram,./levain.gram)", + }, + }, + async run({ args, rawArgs }) { + const file = resolve(args.file as string); + const config = await loadConfig(); + + try { + const format = String(args.format ?? "text") as PlanFormat; + if (!PLAN_FORMATS.includes(format)) { + throw new GramCLIError( + `Unknown --format value "${args.format}". Expected one of: ${PLAN_FORMATS.join(", ")}.`, + ExitCode.Error, + ); + } + const serveAt = parseServe(args.serve); + const timeZone = parseTimeZone(args.tz); + const availability = parseAvailability( + collectFlag(rawArgs ?? [], "available"), + ); + const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]); + const rests = parseRests(args.rests); + const stock = resolveStockFromConfig(args.stock, config); + const scaleFactor = + (await resolveScaleArg( + args.scale as string | undefined, + file, + null, + config.language, + config.paths, + )) ?? 1; + const now = (args.now as string | undefined) ?? new Date().toISOString(); + + const result = await planRecipe(file, { + serveAt, + timeZone, + availability, + now, + miseEnPlace, + rests, + scaleFactor, + lang: config.language, + paths: config.paths, + stock, + }); + reportUnusedStock("gram plan", "planned", stock, [result]); + + process.stdout.write(formatPlan(result, format, config.language)); + + if (args.ics) { + const path = resolve(args.ics as string); + const stamp = toUtcIso(parseInstant(now, timeZone)); + await writeFile( + path, + planToICS(result, stamp, config.language), + "utf-8", + ); + process.stderr.write(`Calendar written to ${path}\n`); + } + process.exit(ExitCode.Ok); + } catch (err) { + if (err instanceof GramCLIError) { + log.error(err.message); + process.exit(err.exitCode); + } + throw err; + } + }, +}); diff --git a/packages/cli/src/commands/print.ts b/packages/cli/src/commands/print.ts index 3bb1d891..cdc794c5 100644 --- a/packages/cli/src/commands/print.ts +++ b/packages/cli/src/commands/print.ts @@ -12,6 +12,7 @@ import { MISE_EN_PLACE_FLAG_DESCRIPTION, parseMiseEnPlace, } from "../services/mise-en-place-flag"; +import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag"; import { NUTRITION_BASIS_FLAG_DESCRIPTION, parseNutritionBasis, @@ -77,6 +78,10 @@ export default defineCommand({ type: "string", description: MISE_EN_PLACE_FLAG_DESCRIPTION, }, + rests: { + type: "string", + description: RESTS_FLAG_DESCRIPTION, + }, stock: { type: "string", description: @@ -104,6 +109,7 @@ export default defineCommand({ const bakersMathOnly = args["bakers-math-only"] as boolean; const nutritionBasis = parseNutritionBasis(args.nutrition); const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]); + const rests = parseRests(args.rests); const stock = resolveStockFromConfig(args.stock, config); let htmlPath: string; @@ -115,6 +121,7 @@ export default defineCommand({ bakersMathOnly, nutritionBasis, miseEnPlace, + rests, lang: config.language, paths: config.paths, stock, diff --git a/packages/cli/src/commands/view.ts b/packages/cli/src/commands/view.ts index be308c40..80f45ede 100644 --- a/packages/cli/src/commands/view.ts +++ b/packages/cli/src/commands/view.ts @@ -14,6 +14,7 @@ import { MISE_EN_PLACE_FLAG_DESCRIPTION, parseMiseEnPlace, } from "../services/mise-en-place-flag"; +import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag"; import { NUTRITION_BASIS_FLAG_DESCRIPTION, parseNutritionBasis, @@ -72,6 +73,10 @@ export default defineCommand({ type: "string", description: MISE_EN_PLACE_FLAG_DESCRIPTION, }, + rests: { + type: "string", + description: RESTS_FLAG_DESCRIPTION, + }, stock: { type: "string", description: @@ -100,6 +105,7 @@ export default defineCommand({ const bakersMathOnly = args["bakers-math-only"] as boolean; const nutritionBasis = parseNutritionBasis(args.nutrition); const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]); + const rests = parseRests(args.rests); const stock = resolveStockFromConfig(args.stock, config); let model; @@ -111,6 +117,7 @@ export default defineCommand({ bakersMathOnly, nutritionBasis, miseEnPlace, + rests, lang: config.language, paths: config.paths, stock, diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 870921c4..a6366767 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -79,6 +79,7 @@ const main = defineCommand({ format: () => import("./commands/format").then((m) => m.default), export: () => import("./commands/export").then((m) => m.default), print: () => import("./commands/print").then((m) => m.default), + plan: () => import("./commands/plan").then((m) => m.default), suggest: () => import("./commands/suggest").then((m) => m.default), upgrade: () => import("./commands/upgrade").then((m) => m.default), }, diff --git a/packages/cli/src/services/exporter.ts b/packages/cli/src/services/exporter.ts index 54921cfc..7537a65c 100644 --- a/packages/cli/src/services/exporter.ts +++ b/packages/cli/src/services/exporter.ts @@ -13,7 +13,7 @@ import type { IngredientData } from "@gram-lang/analyzer"; // forwarded to the pipeline, not into RendererOptions. export type ExportOptions = Pick< RendererOptions, - "hideStepQty" | "bakersMathOnly" | "nutritionBasis" | "miseEnPlace" + "hideStepQty" | "bakersMathOnly" | "nutritionBasis" | "miseEnPlace" | "rests" > & { bakersReference?: string; lang?: string; diff --git a/packages/cli/src/services/ics.ts b/packages/cli/src/services/ics.ts new file mode 100644 index 00000000..c65ea9d2 --- /dev/null +++ b/packages/cli/src/services/ics.ts @@ -0,0 +1,93 @@ +import type { RunSheetModel } from "@gram-lang/renderer"; + +const encoder = new TextEncoder(); + +/** Escapes a text value the way RFC 5545 asks: backslash, semicolon, comma, newline. */ +const escapeText = (text: string) => + text + .replace(/\\/g, "\\\\") + .replace(/;/g, ";") + .replace(/,/g, "\\,") + .replace(/\r?\n/g, "\\n"); + +/** Folds a line at 75 octets, never inside a character; a continuation starts with a space. */ +function fold(line: string): string { + if (encoder.encode(line).length <= 75) return line; + const parts: string[] = []; + let current = ""; + let size = 0; + for (const char of line) { + const width = encoder.encode(char).length; + const limit = parts.length === 0 ? 75 : 74; + if (size + width > limit) { + parts.push(current); + current = ""; + size = 0; + } + current += char; + size += width; + } + parts.push(current); + return parts.join("\r\n "); +} + +/** "2026-10-10T19:38:00Z" as "20261010T193800Z". */ +const compact = (iso: string) => iso.replace(/[-:]/g, ""); + +export interface IcsOptions { + /** DTSTAMP of every event, an ISO instant in UTC. */ + stamp: string; + /** Minutes before an active task at which its alarm rings. Default 5. */ + alarmMinutes?: number; + /** Words for the alarm text of a task that is not named in a way a reminder can use. */ + calendarName?: string; +} + +/** + * The production sheet as an iCalendar file: one event per task, in UTC (the + * calendar shows it in its own zone), and an alarm on the tasks that need the + * cook's hands. Nothing here reads the clock: the stamp is given. + */ +export function buildICS(model: RunSheetModel, options: IcsOptions): string { + const alarm = options.alarmMinutes ?? 5; + const lines: string[] = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//Gram//gram plan//EN", + "CALSCALE:GREGORIAN", + "METHOD:PUBLISH", + `X-WR-CALNAME:${escapeText(options.calendarName ?? model.title)}`, + ]; + const seen = new Map(); + for (const day of model.days) { + for (const line of day.lines) { + // A merged mise en place keeps the id of its first task: two events can share one. + const n = (seen.get(line.task) ?? 0) + 1; + seen.set(line.task, n); + const description = [line.detail, line.length, line.note] + .filter(Boolean) + .join("\n"); + lines.push( + "BEGIN:VEVENT", + `UID:${compact(line.start)}-${line.task}${n > 1 ? `-${n}` : ""}@gram-lang.org`, + `DTSTAMP:${compact(options.stamp)}`, + `DTSTART:${compact(line.start)}`, + `DTEND:${compact(line.end)}`, + `SUMMARY:${escapeText(line.title)}`, + `DESCRIPTION:${escapeText(description)}`, + ); + if (line.active) { + lines.push( + "BEGIN:VALARM", + "ACTION:DISPLAY", + `DESCRIPTION:${escapeText(line.title)}`, + `TRIGGER:-PT${alarm}M`, + "END:VALARM", + ); + } + lines.push("END:VEVENT"); + } + } + lines.push("END:VCALENDAR"); + return `${lines.map(fold).join("\r\n")}\r\n`; +} diff --git a/packages/cli/src/services/plan-flags.ts b/packages/cli/src/services/plan-flags.ts new file mode 100644 index 00000000..a18e6458 --- /dev/null +++ b/packages/cli/src/services/plan-flags.ts @@ -0,0 +1,128 @@ +import type { Availability, Weekday } from "@gram-lang/scheduler"; +import { WEEKDAYS } from "@gram-lang/scheduler"; +import { ExitCode, GramCLIError } from "../errors"; + +const fail = (message: string): never => { + throw new GramCLIError(message, ExitCode.Error); +}; + +/** + * Every value given to a flag that may be repeated (`--available a --available + * b`). citty keeps the last one of a repeated flag, so these come from the raw + * arguments, `--flag value` and `--flag=value` alike. + */ +export function collectFlag(rawArgs: string[], name: string): string[] { + const values: string[] = []; + const long = `--${name}`; + for (let i = 0; i < rawArgs.length; i++) { + const arg = rawArgs[i]!; + if (arg === long) { + const next = rawArgs[i + 1]; + if (next !== undefined) values.push(next); + i++; + } else if (arg.startsWith(`${long}=`)) { + values.push(arg.slice(long.length + 1)); + } + } + return values; +} + +/** + * `--serve "2026-10-11 13:00"`: a local date and time, in the time zone of the + * plan. A `T` instead of the space works too. + */ +export function parseServe(value: unknown): string { + const text = String(value ?? "").trim(); + const m = /^(\d{4}-\d{2}-\d{2})[T ](\d{1,2}):(\d{2})$/.exec(text); + if (!m) { + return fail( + `Expected --serve like "2026-10-11 13:00" (a local date and time), got "${text}".`, + ); + } + return `${m[1]}T${m[2]!.padStart(2, "0")}:${m[3]}`; +} + +/** `--tz Europe/Paris`: checked here so a typo is a clear message, not a stack trace. */ +export function parseTimeZone(value: unknown): string { + const zone = + typeof value === "string" && value !== "" + ? value + : Intl.DateTimeFormat().resolvedOptions().timeZone; + try { + new Intl.DateTimeFormat("en", { timeZone: zone }); + } catch { + return fail( + `Unknown time zone "${zone}". Use an IANA name like Europe/Paris.`, + ); + } + return zone; +} + +const CLOCK = /^([01]?\d|2[0-4]):([0-5]\d)$/; +const DATE = /^\d{4}-\d{2}-\d{2}$/; + +function parseRanges( + text: string, + flag: string, +): { start: string; end: string }[] { + if (text === "none") return []; + return text.split(",").map((part) => { + const [start, end, ...extra] = part.split("-"); + if ( + start === undefined || + end === undefined || + extra.length > 0 || + !CLOCK.test(start) || + !CLOCK.test(end) + ) { + return fail( + `Expected --available ${flag} like 08:00-22:00 (several: 08:00-09:00,18:00-22:00, none for no availability), got "${part}".`, + ); + } + return { start, end }; + }); +} + +/** + * `--available` entries, each one of: + * 08:00-22:00 every day + * fri=18:00-22:00 a day of the week (mon … sun) + * 2026-10-09=none a date (none: not available at all) + * Several ranges go after one key, separated by commas, and an entry may be + * repeated to add to it. Without any entry, the cook is available all day. + */ +export function parseAvailability(entries: string[]): Availability { + if (entries.length === 0) { + return { daily: [{ start: "00:00", end: "24:00" }] }; + } + const daily: { start: string; end: string }[] = []; + const weekdays: Partial> = + {}; + const dates: Record = {}; + for (const entry of entries) { + const eq = entry.indexOf("="); + if (eq === -1) { + daily.push(...parseRanges(entry, entry)); + continue; + } + const key = entry.slice(0, eq).toLowerCase(); + const ranges = parseRanges(entry.slice(eq + 1), key); + if ((WEEKDAYS as readonly string[]).includes(key)) { + weekdays[key as Weekday] = [ + ...(weekdays[key as Weekday] ?? []), + ...ranges, + ]; + } else if (DATE.test(key)) { + dates[key] = [...(dates[key] ?? []), ...ranges]; + } else { + fail( + `Unknown --available key "${key}": use a day of the week (${WEEKDAYS.join(", ")}) or a date like 2026-10-09.`, + ); + } + } + return { + daily, + ...(Object.keys(weekdays).length > 0 && { weekdays }), + ...(Object.keys(dates).length > 0 && { dates }), + }; +} diff --git a/packages/cli/src/services/planner.ts b/packages/cli/src/services/planner.ts new file mode 100644 index 00000000..f4c56746 --- /dev/null +++ b/packages/cli/src/services/planner.ts @@ -0,0 +1,110 @@ +import { + describeRunSheet, + runSheetToHTML, + runSheetToMarkdown, + runSheetToText, +} from "@gram-lang/renderer"; +import type { + CompilationResult, + MiseEnPlaceMode, + RestChoice, +} from "@gram-lang/kitchen"; +import { + type Availability, + type ProjectedPlan, + type RunSheet, + project, + runSheet, +} from "@gram-lang/scheduler"; +import { runPipeline } from "../core/pipeline"; +import { buildICS } from "./ics"; + +export type PlanFormat = "text" | "md" | "html" | "json"; +export const PLAN_FORMATS: readonly PlanFormat[] = [ + "text", + "md", + "html", + "json", +]; + +export interface PlanOptions { + /** A local date and time, "2026-10-11T13:00". */ + serveAt: string; + timeZone: string; + availability: Availability; + /** The present, for the warning about a start already behind. */ + now?: string; + miseEnPlace?: MiseEnPlaceMode; + rests?: RestChoice; + scaleFactor?: number; + lang?: string; + paths?: Record; + stock?: Set; +} + +export interface PlanResult { + compiled: CompilationResult; + plan: ProjectedPlan; + sheet: RunSheet; + usedStock: Set; +} + +/** Compiles a recipe and places it on the calendar, ending when it is served. */ +export async function planRecipe( + filePath: string, + options: PlanOptions, +): Promise { + const { compiled, usedStock } = await runPipeline(filePath, { + skipAnalyzer: true, + scaleFactor: options.scaleFactor, + lang: options.lang, + paths: options.paths, + stock: options.stock, + }); + const plan = project( + [ + { + graph: compiled.tasks, + title: compiled.title ?? undefined, + options: { miseEnPlace: options.miseEnPlace, rests: options.rests }, + }, + ], + { + serveAt: options.serveAt, + timeZone: options.timeZone, + availability: options.availability, + ...(options.now !== undefined && { now: options.now }), + }, + ); + return { compiled, plan, sheet: runSheet(plan), usedStock }; +} + +/** The sheet in one of the formats `--format` offers. */ +export function formatPlan( + result: PlanResult, + format: PlanFormat, + lang?: string, +): string { + const { compiled, plan, sheet } = result; + switch (format) { + case "text": + return runSheetToText(sheet, compiled, { lang }); + case "md": + return runSheetToMarkdown(sheet, compiled, { lang }); + case "html": + return runSheetToHTML(sheet, compiled, { lang }); + case "json": + return `${JSON.stringify({ plan, runSheet: sheet }, null, 2)}\n`; + } +} + +/** The sheet as an iCalendar file, every event stamped `stamp` (an ISO instant, UTC). */ +export function planToICS( + result: PlanResult, + stamp: string, + lang?: string, +): string { + return buildICS(describeRunSheet(result.sheet, result.compiled, { lang }), { + stamp, + }); +} diff --git a/packages/cli/src/services/rests-flag.ts b/packages/cli/src/services/rests-flag.ts new file mode 100644 index 00000000..2b3774a1 --- /dev/null +++ b/packages/cli/src/services/rests-flag.ts @@ -0,0 +1,24 @@ +import { REST_CHOICES, type RestChoice } from "@gram-lang/kitchen"; +import { ExitCode, GramCLIError, reportError } from "../errors"; + +export const RESTS_FLAG_VALUES: readonly string[] = REST_CHOICES; + +export const RESTS_FLAG_DESCRIPTION = `How long a rest written as a range (~_{12-24h}) lasts: ${RESTS_FLAG_VALUES.join(" | ")} (default: shortest). An exact rest and an active timer are not affected. Changes the total and idle times.`; + +/** + * Reports and exits on an unusable value, like `parseMiseEnPlace`: an + * argument-validation failure raised before any work starts. + */ +export function parseRests(value: unknown): RestChoice | undefined { + if (value === undefined || value === null || value === "") return undefined; + if ((REST_CHOICES as readonly unknown[]).includes(value)) { + return value as RestChoice; + } + reportError( + new GramCLIError( + `Unknown --rests value "${value}". Expected one of: ${RESTS_FLAG_VALUES.join(", ")}.`, + ExitCode.Error, + ), + ); + return process.exit(ExitCode.Error); +} diff --git a/packages/cli/src/services/viewer.ts b/packages/cli/src/services/viewer.ts index f04cf5cf..2754bc02 100644 --- a/packages/cli/src/services/viewer.ts +++ b/packages/cli/src/services/viewer.ts @@ -11,6 +11,7 @@ import { import { type CompilationResult, type MiseEnPlaceMode, + type RestChoice, scheduleTimes, } from "@gram-lang/kitchen"; import type { RecipeViewModel } from "../types"; @@ -157,6 +158,8 @@ export async function buildViewModel( nutritionBasis?: NutritionBasis; /** Which timeline the total and rest times follow. Default per section. */ miseEnPlace?: MiseEnPlaceMode; + /** How long a rest written as a range lasts. Default shortest. */ + rests?: RestChoice; lang?: string; paths?: Record; stock?: Set; @@ -192,6 +195,7 @@ export async function buildViewModel( const { totalTime: total, idleTime: rest } = scheduleTimes( compiled, opts.miseEnPlace, + opts.rests, ); const times = m && (total || rest || m.activeTime || m.preparationTime) diff --git a/packages/cli/tests/ics.test.ts b/packages/cli/tests/ics.test.ts new file mode 100644 index 00000000..ad8d89ff --- /dev/null +++ b/packages/cli/tests/ics.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "bun:test"; +import type { RunSheetModel } from "@gram-lang/renderer"; +import { buildICS } from "../src/services/ics"; + +const line = (over: Partial = {}) => ({ + task: "s0.0", + kind: "step" as const, + start: "2026-10-10T19:40:00Z", + end: "2026-10-10T20:00:00Z", + when: "around 21:40", + title: "Dough — Mix", + detail: "Mix flour, then knead; rest.", + length: "20m", + active: true, + ...over, +}); + +const model = (...lines: ReturnType[]): RunSheetModel => ({ + title: "Production sheet — Bread", + servedAt: "Served Sunday, October 11 at 13:00", + days: [{ heading: "Saturday · D-1", lines }], + problems: [], +}); + +const STAMP = { stamp: "2026-10-01T09:00:00Z" }; + +describe("buildICS", () => { + const ics = buildICS(model(line()), STAMP); + + it("is a calendar with CRLF line ends", () => { + expect(ics.startsWith("BEGIN:VCALENDAR\r\nVERSION:2.0\r\n")).toBe(true); + expect(ics.endsWith("END:VCALENDAR\r\n")).toBe(true); + expect(ics.replace(/\r\n/g, "")).not.toContain("\n"); + }); + + it("writes an event in UTC, stamped as asked, with a stable id", () => { + expect(ics).toContain("DTSTART:20261010T194000Z"); + expect(ics).toContain("DTEND:20261010T200000Z"); + expect(ics).toContain("DTSTAMP:20261001T090000Z"); + expect(ics).toContain("UID:20261010T194000Z-s0.0@gram-lang.org"); + expect(buildICS(model(line()), STAMP)).toBe(ics); + }); + + it("escapes commas, semicolons and newlines in the text", () => { + expect(ics).toContain("DESCRIPTION:Mix flour\\, then knead; rest.\\n20m"); + }); + + it("rings an alarm before a task that needs the hands, and not before a rest", () => { + expect(ics).toContain("BEGIN:VALARM"); + expect(ics).toContain("TRIGGER:-PT5M"); + const rest = buildICS( + model(line({ active: false, kind: "passive" })), + STAMP, + ); + expect(rest).not.toContain("VALARM"); + }); + + it("keeps ids unique when two events share a task", () => { + const two = buildICS( + model( + line(), + line({ start: "2026-10-10T21:00:00Z", end: "2026-10-10T21:10:00Z" }), + ), + STAMP, + ); + const uids = [...two.matchAll(/^UID:(.*)$/gm)].map((m) => m[1]); + expect(new Set(uids).size).toBe(2); + }); + + it("folds long lines at 75 octets without cutting a character", () => { + const long = buildICS( + model(line({ title: `${"é".repeat(60)} ⏲️ end` })), + STAMP, + ); + for (const physical of long.split("\r\n")) { + expect(new TextEncoder().encode(physical).length).toBeLessThanOrEqual(75); + } + const unfolded = long.replace(/\r\n /g, ""); + expect(unfolded).toContain(`SUMMARY:${"é".repeat(60)} ⏲️ end`); + }); +}); diff --git a/packages/cli/tests/plan-cli.test.ts b/packages/cli/tests/plan-cli.test.ts new file mode 100644 index 00000000..ecf732eb --- /dev/null +++ b/packages/cli/tests/plan-cli.test.ts @@ -0,0 +1,206 @@ +import { afterAll, beforeAll, describe, expect, it } from "bun:test"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +/* + * `gram plan` end to end: the real CLI is started as a process, so what is + * checked is what a user sees, from the flags to the sheet and the calendar. + */ + +const ENTRY = join(import.meta.dir, "..", "src", "index.ts"); + +const BREAD = `--- +title: Country bread +--- + +## Dough ->&dough + +[Mix] Mix @flour{500g} with @water{350ml} and knead ~{20min}. + +[Rise] Let it rise ~_{8-16h}. + +## Bake + +[Bake] Shape &dough{850g} and bake for ~{30min}. +`; + +let dir: string; +let recipe: string; + +beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), "gram-cli-plan-")); + recipe = join(dir, "bread.gram"); + await writeFile(recipe, BREAD, "utf-8"); +}); + +afterAll(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +function gram(...args: string[]) { + const run = Bun.spawnSync([process.execPath, ENTRY, ...args], { cwd: dir }); + const strip = (b: Uint8Array) => + new TextDecoder().decode(b).replace(/\x1b\[[0-9;]*m/g, ""); + return { code: run.exitCode, out: strip(run.stdout), err: strip(run.stderr) }; +} + +const PLAN = [ + "plan", + "bread.gram", + "--serve", + "2026-10-11 13:00", + "--tz", + "Europe/Paris", + "--now", + "2026-10-01T09:00:00Z", +]; + +describe("gram plan", () => { + it("prints the sheet in the language of the project, backward from the service", () => { + const { code, out } = gram(...PLAN, "--available", "08:00-22:00"); + expect(code).toBe(0); + expect(out).toContain("Production sheet — Country bread"); + expect(out).toContain("Served Sunday, October 11 at 13:00"); + expect(out).toContain("Saturday, October 10 · D-1"); + expect(out).toMatch(/around 12:30\s+Bake — Bake/); + }); + + it("stretches the rest to keep the kneading out of the night, and says so", () => { + const { out } = gram(...PLAN, "--available", "08:00-22:00"); + expect(out).toMatch(/around 21:\d\d\s+Dough — Mix/); + expect(out).toContain("Rest stretched from 8h to 14h 30m"); + }); + + it("starts in the night when nothing says otherwise, and does not stretch", () => { + const { out } = gram(...PLAN); + expect(out).toMatch(/around 04:\d\d\s+Dough — Mix/); + expect(out).not.toContain("stretched"); + }); + + it("reads availability by weekday: Saturday ending at 20:00 leaves no way to fit the kneading", () => { + // The kneading has to end the evening before, and the longest rest (16 h) + // cannot reach back from 12:30 on Sunday to 20:00 on Saturday. + const { out } = gram( + ...PLAN, + "--available", + "08:00-22:00", + "--available", + "sat=09:00-20:00", + ); + expect(out).toContain("falls when you are not available"); + const open = gram( + ...PLAN, + "--available", + "08:00-22:00", + "--available", + "sat=09:00-23:00", + ).out; + expect(open).not.toContain("falls when you are not available"); + }); + + it("reports what it could not fix", () => { + const { out } = gram( + ...PLAN, + "--available", + "08:00-22:00", + "--available", + "2026-10-10=none", + "--available", + "2026-10-11=none", + ); + expect(out).toContain("To fix"); + }); + + it("writes markdown, html or json", () => { + expect(gram(...PLAN, "--format", "md").out).toContain( + "# Production sheet — Country bread", + ); + expect(gram(...PLAN, "--format", "html").out).toContain( + '
', + ); + const json = JSON.parse(gram(...PLAN, "--format", "json").out); + expect(Object.keys(json)).toEqual(["plan", "runSheet"]); + expect(json.plan.serveAt).toBe("2026-10-11T13:00"); + }); + + it("follows --rests", () => { + const shortest = gram(...PLAN, "--rests", "shortest").out; + const longest = gram(...PLAN, "--rests", "longest").out; + expect(shortest).toMatch(/\(8h, until around 12:30\)/); + expect(longest).toMatch(/\(16h, until around Sun 12:30\)/); + }); + + it("writes a calendar, in UTC, stamped from --now, with the status on stderr", async () => { + const path = join(dir, "bread.ics"); + const { code, out, err } = gram(...PLAN, "--format", "json", "--ics", path); + expect(code).toBe(0); + expect(() => JSON.parse(out)).not.toThrow(); + expect(err).toContain("Calendar written to"); + const ics = await readFile(path, "utf-8"); + expect(ics).toContain("BEGIN:VCALENDAR"); + expect(ics).toContain("DTSTAMP:20261001T090000Z"); + expect(ics).toContain("DTEND:20261011T110000Z"); + expect(ics).toContain("BEGIN:VALARM"); + }); + + it("warns when the first task should already have started", () => { + const { out } = gram( + ...PLAN.slice(0, -1), + "2026-10-11T09:00", + "--available", + "00:00-24:00", + ); + expect(out).toContain("The first task should have started"); + }); + + it("refuses a bad serving time, zone, availability or format", () => { + for (const bad of [ + ["--serve", "sunday"], + ["--tz", "Mars/Olympus"], + ["--available", "8-22"], + ["--format", "pdf"], + ["--rests", "slowest"], + ["--mise-en-place", "later"], + ]) { + const args = [...PLAN]; + const at = args.indexOf(bad[0]!); + if (at === -1) args.push(...bad); + else args[at + 1] = bad[1]!; + const { code } = gram(...args); + expect(code).toBe(1); + } + }); + + it("needs --serve", () => { + expect(gram("plan", "bread.gram").code).not.toBe(0); + }); +}); + +describe("--rests on the other commands", () => { + it("changes the total of gram view, like --mise-en-place does", () => { + const total = (rests: string) => + /Total: ([^\s│]+(?: \d+m)?)/.exec( + gram("view", "bread.gram", "--rests", rests).out, + )?.[1]; + expect(total("shortest")).not.toBe(total("longest")); + }); + + it("is refused when unknown", () => { + expect(gram("view", "bread.gram", "--rests", "slowest").code).toBe(1); + expect(gram("export", "bread.gram", "--rests", "slowest").code).toBe(1); + expect(gram("print", "bread.gram", "--rests", "slowest").code).toBe(1); + }); + + it("is accepted by gram export", () => { + const out = gram( + "export", + "bread.gram", + "--format", + "md", + "--rests", + "longest", + ); + expect(out.code).toBe(0); + }); +}); diff --git a/packages/cli/tests/plan-flags.test.ts b/packages/cli/tests/plan-flags.test.ts new file mode 100644 index 00000000..fe6adcfe --- /dev/null +++ b/packages/cli/tests/plan-flags.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "bun:test"; +import { GramCLIError } from "../src/errors"; +import { + collectFlag, + parseAvailability, + parseServe, + parseTimeZone, +} from "../src/services/plan-flags"; + +const messageOf = (fn: () => unknown) => { + try { + fn(); + } catch (e) { + expect(e).toBeInstanceOf(GramCLIError); + return (e as Error).message; + } + throw new Error("did not throw"); +}; + +describe("collectFlag", () => { + it("reads a flag given several times, with a space or an equals sign", () => { + expect( + collectFlag( + [ + "f.gram", + "--available", + "08:00-22:00", + "--available=fri=18:00-22:00", + "--serve", + "x", + ], + "available", + ), + ).toEqual(["08:00-22:00", "fri=18:00-22:00"]); + }); + + it("finds nothing when the flag is absent or has no value", () => { + expect(collectFlag(["f.gram"], "available")).toEqual([]); + expect(collectFlag(["--available"], "available")).toEqual([]); + }); +}); + +describe("parseServe", () => { + it("reads a local date and time, with a space or a T", () => { + expect(parseServe("2026-10-11 13:00")).toBe("2026-10-11T13:00"); + expect(parseServe("2026-10-11T9:05")).toBe("2026-10-11T09:05"); + }); + + it("explains what it expects", () => { + expect(messageOf(() => parseServe("sunday"))).toContain( + '"2026-10-11 13:00"', + ); + expect(messageOf(() => parseServe(undefined))).toContain("--serve"); + }); +}); + +describe("parseTimeZone", () => { + it("accepts an IANA zone and falls back on the machine's", () => { + expect(parseTimeZone("Europe/Paris")).toBe("Europe/Paris"); + expect(parseTimeZone(undefined)).toBe( + Intl.DateTimeFormat().resolvedOptions().timeZone, + ); + }); + + it("refuses a zone that does not exist, by name", () => { + expect(messageOf(() => parseTimeZone("Mars/Olympus"))).toContain( + "Mars/Olympus", + ); + }); +}); + +describe("parseAvailability", () => { + it("is available all day without any entry", () => { + expect(parseAvailability([])).toEqual({ + daily: [{ start: "00:00", end: "24:00" }], + }); + }); + + it("reads a default range, a weekday and a date", () => { + expect( + parseAvailability(["08:00-22:00", "fri=18:00-22:00", "2026-10-09=none"]), + ).toEqual({ + daily: [{ start: "08:00", end: "22:00" }], + weekdays: { fri: [{ start: "18:00", end: "22:00" }] }, + dates: { "2026-10-09": [] }, + }); + }); + + it("takes several ranges after one key, or the same key again", () => { + expect( + parseAvailability([ + "sat=08:00-09:00,18:00-22:00", + "sat=23:00-02:00", + "07:00-08:00", + ]), + ).toEqual({ + daily: [{ start: "07:00", end: "08:00" }], + weekdays: { + sat: [ + { start: "08:00", end: "09:00" }, + { start: "18:00", end: "22:00" }, + { start: "23:00", end: "02:00" }, + ], + }, + }); + }); + + it("reads a weekday in any case, and none as not available", () => { + expect(parseAvailability(["SUN=none"])).toMatchObject({ + weekdays: { sun: [] }, + }); + }); + + it("refuses what it cannot read, saying what it expects", () => { + expect(messageOf(() => parseAvailability(["8-22"]))).toContain( + "08:00-22:00", + ); + expect(messageOf(() => parseAvailability(["fri=18:00"]))).toContain( + "18:00", + ); + expect( + messageOf(() => parseAvailability(["someday=08:00-22:00"])), + ).toContain("someday"); + expect(messageOf(() => parseAvailability(["25:00-26:00"]))).toContain( + "25:00", + ); + }); +}); -- 2.54.0 From 62668883dd1cac9f6cecf1168597912210db6f69 Mon Sep 17 00:00:00 2001 From: abiwab Date: Sun, 4 Oct 2026 12:46:26 +0200 Subject: [PATCH 3/6] feat(language-server): follow gram.rests in the preview, the Gantt chart and the hint --- .changeset/vscode-mise-en-place-setting.md | 2 + .../src/features/inlay-hints.ts | 11 +++- packages/language-server/src/server.ts | 25 +++++--- .../src/utils/mise-en-place-setting.ts | 13 ++++ .../language-server/tests/diagnostics.test.ts | 24 +++++++ .../language-server/tests/inlay-hints.test.ts | 15 +++++ .../tests/mise-en-place-refresh.test.ts | 63 ++++++++++++++++++- .../tests/mise-en-place-setting.test.ts | 27 +++++++- packages/vscode-extension/package.json | 15 +++++ .../vscode-extension/src/client-options.ts | 2 +- 10 files changed, 184 insertions(+), 13 deletions(-) diff --git a/.changeset/vscode-mise-en-place-setting.md b/.changeset/vscode-mise-en-place-setting.md index 8415e524..c24af3a8 100644 --- a/.changeset/vscode-mise-en-place-setting.md +++ b/.changeset/vscode-mise-en-place-setting.md @@ -8,3 +8,5 @@ - The preview, the Gantt chart and the total time hint next to the recipe title all follow it - Changing the setting updates every open recipe right away, and a recipe already open when the editor starts follows it too - Changing a `gram.*` setting now reaches the language server straight away, without reloading the window (this also applies to `gram.ingredientDatabase.path`) +- A new `gram.rests` setting (`shortest` by default, `balanced` or `longest`) chooses how long a rest written as a range (`~_{12-24h}`) lasts in the same three places +- A working day pushed out of its 24 hours by a long rest is flagged on its section (the new `SESSION_OVERFLOW` warning) diff --git a/packages/language-server/src/features/inlay-hints.ts b/packages/language-server/src/features/inlay-hints.ts index 0a18f8d4..9290f9c5 100644 --- a/packages/language-server/src/features/inlay-hints.ts +++ b/packages/language-server/src/features/inlay-hints.ts @@ -1,16 +1,21 @@ import { type InlayHint, InlayHintKind, Position } from "vscode-languageserver"; -import { type MiseEnPlaceMode, scheduleTimes } from "@gram-lang/kitchen"; +import { + type MiseEnPlaceMode, + type RestChoice, + scheduleTimes, +} from "@gram-lang/kitchen"; import type { DocumentState } from "../document-state"; export function provideInlayHints( state: DocumentState, schedule?: MiseEnPlaceMode, + rests?: RestChoice, ): InlayHint[] { const hints: InlayHint[] = []; if (!state.ast || !state.compilation?.metrics) return hints; - // The total follows the chosen schedule (`gram.miseEnPlace`). - const { totalTime } = scheduleTimes(state.compilation, schedule); + // The total follows the chosen timeline (`gram.miseEnPlace`, `gram.rests`). + const { totalTime } = scheduleTimes(state.compilation, schedule, rests); let titleLine = 0; let titleChar = 0; diff --git a/packages/language-server/src/server.ts b/packages/language-server/src/server.ts index 7a9068f9..00a459cb 100644 --- a/packages/language-server/src/server.ts +++ b/packages/language-server/src/server.ts @@ -34,7 +34,10 @@ import { } from "./features/semantic-tokens"; import type { IngredientDB } from "./ingredient-loader"; import { provideInlayHints } from "./features/inlay-hints"; -import { parseMiseEnPlaceSetting } from "./utils/mise-en-place-setting"; +import { + parseMiseEnPlaceSetting, + parseRestsSetting, +} from "./utils/mise-en-place-setting"; import { provideCodeLenses } from "./features/code-lens"; import { positionToOffset } from "./utils/position"; import { resolveWorkspaceFolders } from "./utils/workspace-folders"; @@ -44,6 +47,8 @@ import { toHTML, toGanttHTML, escapeHtml } from "@gram-lang/renderer"; import { DEFAULT_MISE_EN_PLACE_MODE, type MiseEnPlaceMode, + DEFAULT_REST_CHOICE, + type RestChoice, } from "@gram-lang/kitchen"; const connection = createConnection(ProposedFeatures.all); @@ -153,18 +158,22 @@ connection.onInitialize((params: InitializeParams): InitializeResult => { }; }); -// `gram.miseEnPlace`: which timeline the preview, the Gantt and the title hint -// follow. Read once at start and again whenever the settings change. +// `gram.miseEnPlace` and `gram.rests`: which timeline the preview, the Gantt and +// the title hint follow. Read once at start and again whenever the settings +// change. let miseEnPlace: MiseEnPlaceMode = DEFAULT_MISE_EN_PLACE_MODE; +let rests: RestChoice = DEFAULT_REST_CHOICE; // Never rejects (same rule as reloadDbAndRefreshDiagnostics below): a client // without workspace configuration just keeps the default. async function loadMiseEnPlace(): Promise { try { const config = await connection.workspace.getConfiguration("gram"); - const next = parseMiseEnPlaceSetting(config); - const changed = next !== miseEnPlace; - miseEnPlace = next; + const nextMode = parseMiseEnPlaceSetting(config); + const nextRests = parseRestsSetting(config); + const changed = nextMode !== miseEnPlace || nextRests !== rests; + miseEnPlace = nextMode; + rests = nextRests; return changed; } catch { return false; @@ -320,6 +329,7 @@ function renderViews(uri: string, state: DocumentState): void { const html = toHTML(state.compilation, { interactiveNutrition: true, miseEnPlace, + rests, }); connection.sendNotification("gram/previewUpdated", { uri, html }); } catch (e) { @@ -331,6 +341,7 @@ function renderViews(uri: string, state: DocumentState): void { try { const ganttHtml = toGanttHTML(state.compilation, { miseEnPlace, + rests, }); connection.sendNotification("gram/ganttUpdated", { uri, @@ -532,7 +543,7 @@ connection.languages.semanticTokens.on(({ textDocument: { uri } }) => { connection.languages.inlayHint.on(({ textDocument: { uri } }) => { const s = states.get(uri); - return s ? provideInlayHints(s, miseEnPlace) : []; + return s ? provideInlayHints(s, miseEnPlace, rests) : []; }); connection.onCodeLens(({ textDocument: { uri } }) => { diff --git a/packages/language-server/src/utils/mise-en-place-setting.ts b/packages/language-server/src/utils/mise-en-place-setting.ts index ba02431d..879fbd13 100644 --- a/packages/language-server/src/utils/mise-en-place-setting.ts +++ b/packages/language-server/src/utils/mise-en-place-setting.ts @@ -1,7 +1,10 @@ import { DEFAULT_MISE_EN_PLACE_MODE, + DEFAULT_REST_CHOICE, type MiseEnPlaceMode, + type RestChoice, isMiseEnPlaceMode, + isRestChoice, } from "@gram-lang/kitchen"; /** @@ -15,3 +18,13 @@ export function parseMiseEnPlaceSetting(config: unknown): MiseEnPlaceMode { ?.miseEnPlace; return isMiseEnPlaceMode(value) ? value : DEFAULT_MISE_EN_PLACE_MODE; } + +/** + * Reads `gram.rests` the same way: how long a rest written as a range lasts. + * Anything unknown falls back on the shortest, so a bad setting never blanks + * the preview. + */ +export function parseRestsSetting(config: unknown): RestChoice { + const value = (config as { rests?: unknown } | null | undefined)?.rests; + return isRestChoice(value) ? value : DEFAULT_REST_CHOICE; +} diff --git a/packages/language-server/tests/diagnostics.test.ts b/packages/language-server/tests/diagnostics.test.ts index 9c9ca8d6..3f96d88f 100644 --- a/packages/language-server/tests/diagnostics.test.ts +++ b/packages/language-server/tests/diagnostics.test.ts @@ -18,3 +18,27 @@ describe("provideDiagnostics — shared warningSeverity map", () => { expect(missingUnit?.severity).toBe(DiagnosticSeverity.Warning); }); }); + +describe("SESSION_OVERFLOW", () => { + const OVERFLOWING = + "---\ntitle: Bread\n---\n\n## Dough ~{-1d} ->&dough\n\nMix @flour{500g}.\n\nFerment ~_{50h}.\n\n## Bake\n\nBake &dough{500g} ~{30min}.\n"; + + it("squiggles the section whose day a long rest pushes out of its 24 hours", () => { + const state = parseDocument(OVERFLOWING); + const found = provideDiagnostics(state).filter( + (d) => d.code === "SESSION_OVERFLOW", + ); + expect(found).toHaveLength(1); + expect(found[0]!.severity).toBe(2); // warning + expect(found[0]!.message).toContain("Working day 1"); + // Anchored on the section heading's line, not at the top of the file. + expect(found[0]!.range.start.line).toBe(4); + }); + + it("is silent when the rest fits the day", () => { + const state = parseDocument(OVERFLOWING.replace("50h", "10h")); + expect( + provideDiagnostics(state).some((d) => d.code === "SESSION_OVERFLOW"), + ).toBe(false); + }); +}); diff --git a/packages/language-server/tests/inlay-hints.test.ts b/packages/language-server/tests/inlay-hints.test.ts index b7c1f7b1..bbc36f9d 100644 --- a/packages/language-server/tests/inlay-hints.test.ts +++ b/packages/language-server/tests/inlay-hints.test.ts @@ -59,3 +59,18 @@ describe("provideInlayHints follows the chosen schedule", () => { ).toEqual([]); }); }); + +describe("provideInlayHints follows the choice of rests", () => { + const state = parseDocument( + "---\ntitle: Bread\n---\n\n## Dough ->&dough\n\nKnead @flour{500g} ~{20min}, then rest ~_{8-16h}.\n\n## Bake\n\nBake &dough{500g} ~{30min}.\n", + ); + + it("reads the total of the shortest rests by default, and of the longest on request", () => { + const hint = (rests?: "shortest" | "longest") => + label(provideInlayHints(state, undefined, rests)); + expect(hint()).toBe(hint("shortest")); + expect(hint("longest")).not.toBe(hint("shortest")); + const hours = (text: string) => Number(/(\d+)h/.exec(text)?.[1]); + expect(hours(hint("longest")) - hours(hint("shortest"))).toBe(8); + }); +}); diff --git a/packages/language-server/tests/mise-en-place-refresh.test.ts b/packages/language-server/tests/mise-en-place-refresh.test.ts index 704f28f5..785589b1 100644 --- a/packages/language-server/tests/mise-en-place-refresh.test.ts +++ b/packages/language-server/tests/mise-en-place-refresh.test.ts @@ -53,6 +53,8 @@ class Client { readonly notes: Note[] = []; /** What the client answers to `workspace/configuration`. */ setting: unknown = "perSection"; + /** And to `gram.rests`. */ + rests: unknown = "shortest"; /** How long the client takes to answer it (ms). */ configDelay = 0; @@ -100,7 +102,10 @@ class Client { () => this.write({ id: message.id, - result: items.map(() => ({ miseEnPlace: this.setting })), + result: items.map(() => ({ + miseEnPlace: this.setting, + rests: this.rests, + })), }), this.configDelay, ); @@ -285,3 +290,59 @@ describe("gram.miseEnPlace in the language server", () => { expect(totalOf(html)).toBe(TOTAL.perSection); }, 20_000); }); + +// A rest written as a range: the choice of rests moves the total, and nothing +// else here does. +const RANGED = (title: string) => `--- +title: ${title} +--- + +## Dough ->&dough + +Knead @flour{500g} ~{20min}, then rest ~_{8-16h}. + +## Bake + +Bake &dough{500g} ~{30min}. +`; +const ranged = compile(getAST(RANGED("Bread"))); +const REST_TOTAL = { + shortest: fmt(scheduleTimes(ranged, undefined, "shortest").totalTime), + longest: fmt(scheduleTimes(ranged, undefined, "longest").totalTime), +}; + +describe("gram.rests in the language server", () => { + it("sanity: the shortest and the longest rests do not give the same total", () => { + expect(REST_TOTAL.longest).not.toBe(REST_TOTAL.shortest); + }); + + it("renders with the shortest rests until told otherwise", async () => { + client = new Client(); + await client.start(); + client.open(RANGED("Bread")); + const html = await client.previewMatching((h) => totalOf(h) !== undefined); + expect(totalOf(html)).toBe(REST_TOTAL.shortest); + }, 20_000); + + it("applies the setting to a recipe already open, and re-renders when it changes", async () => { + client = new Client(); + client.rests = "longest"; + client.configDelay = 300; + await client.start(); + client.open(RANGED("Bread")); + await client.previewMatching((h) => totalOf(h) === REST_TOTAL.longest); + + client.rests = "shortest"; + client.settingChanged(); + await client.previewMatching((h) => totalOf(h) === REST_TOTAL.shortest); + }, 20_000); + + it("falls back on the shortest for a value it does not know", async () => { + client = new Client(); + client.rests = "sideways"; + await client.start(); + client.open(RANGED("Bread")); + const html = await client.previewMatching((h) => totalOf(h) !== undefined); + expect(totalOf(html)).toBe(REST_TOTAL.shortest); + }, 20_000); +}); diff --git a/packages/language-server/tests/mise-en-place-setting.test.ts b/packages/language-server/tests/mise-en-place-setting.test.ts index 7d6958ef..149b5a95 100644 --- a/packages/language-server/tests/mise-en-place-setting.test.ts +++ b/packages/language-server/tests/mise-en-place-setting.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "bun:test"; import { DEFAULT_MISE_EN_PLACE_MODE } from "@gram-lang/kitchen"; -import { parseMiseEnPlaceSetting } from "../src/utils/mise-en-place-setting"; +import { + parseMiseEnPlaceSetting, + parseRestsSetting, +} from "../src/utils/mise-en-place-setting"; describe("parseMiseEnPlaceSetting", () => { it("defaults to preparing right before each section", () => { @@ -29,3 +32,25 @@ describe("parseMiseEnPlaceSetting", () => { } }); }); + +describe("parseRestsSetting", () => { + it("reads the three known values", () => { + for (const value of ["shortest", "balanced", "longest"]) { + expect(parseRestsSetting({ rests: value })).toBe(value); + } + }); + + it("falls back on the shortest for anything else", () => { + for (const bad of [ + undefined, + null, + {}, + { rests: "" }, + { rests: "LONGEST" }, + { rests: 2 }, + "longest", + ]) { + expect(parseRestsSetting(bad)).toBe("shortest"); + } + }); +}); diff --git a/packages/vscode-extension/package.json b/packages/vscode-extension/package.json index 27922cec..0e20b3f5 100644 --- a/packages/vscode-extension/package.json +++ b/packages/vscode-extension/package.json @@ -117,6 +117,21 @@ ], "default": "perSection", "description": "When the mise en place (gathering and preparing ingredients and cookware) is planned. Drives the total time in the preview, the Gantt chart and the title hint." + }, + "gram.rests": { + "type": "string", + "enum": [ + "shortest", + "balanced", + "longest" + ], + "enumDescriptions": [ + "A rest written as a range (~_{12-24h}) lasts the shortest of it: ready as early as it can be.", + "A rest written as a range lasts the middle of it.", + "A rest written as a range lasts the longest of it." + ], + "default": "shortest", + "description": "How long a rest written as a range lasts. An exact rest and an active timer (~{20-25min}, planned on its longest figure) are not affected. Drives the total time in the preview, the Gantt chart and the title hint." } } }, diff --git a/packages/vscode-extension/src/client-options.ts b/packages/vscode-extension/src/client-options.ts index d1f90410..47cc54f2 100644 --- a/packages/vscode-extension/src/client-options.ts +++ b/packages/vscode-extension/src/client-options.ts @@ -4,7 +4,7 @@ import type { LanguageClientOptions } from "vscode-languageclient/node"; * The settings section the language server reads (`gram.*`). Listing it under * `synchronize.configurationSection` is what makes the client send * `workspace/didChangeConfiguration` when one of them changes: without it the - * server is never told, so a changed `gram.miseEnPlace` (or the ingredient + * server is never told, so a changed `gram.miseEnPlace` or `gram.rests` (or the ingredient * database path) has no effect until the window is reloaded. */ export const CONFIGURATION_SECTION = "gram"; -- 2.54.0 From 24a90861e76de247036ee1b1cfe2a38081fe7515 Mon Sep 17 00:00:00 2001 From: abiwab Date: Sun, 4 Oct 2026 12:46:26 +0200 Subject: [PATCH 4/6] feat(analyzer): read the active time of a diff from the schedule --- .changeset/analyzer-diff-schedule-times.md | 2 +- packages/analyzer/src/diff.ts | 17 ++++++----- packages/analyzer/tests/diff.test.ts | 35 ++++++++++++++++++++-- 3 files changed, 43 insertions(+), 11 deletions(-) diff --git a/.changeset/analyzer-diff-schedule-times.md b/.changeset/analyzer-diff-schedule-times.md index f6d75cba..3919ff1a 100644 --- a/.changeset/analyzer-diff-schedule-times.md +++ b/.changeset/analyzer-diff-schedule-times.md @@ -3,4 +3,4 @@ "@gram-lang/cli": minor --- -**Analyzer / Diff**: `gram diff` now compares the total and idle times of the default schedule, with the mise en place right before each section, so the times it reports match what `gram view` shows by default; preparation and active times are compared as before +**Analyzer / Diff**: `gram diff` now compares the total and idle times of the default schedule, with the mise en place right before each section, so the times it reports match what `gram view` shows by default; the active time is the schedule's too, so changing the range of a cooking time (`~{20-25min}`, planned on its longest figure) shows in the comparison, and the preparation time is compared as before diff --git a/packages/analyzer/src/diff.ts b/packages/analyzer/src/diff.ts index 6e5b1c23..7e811b96 100644 --- a/packages/analyzer/src/diff.ts +++ b/packages/analyzer/src/diff.ts @@ -8,7 +8,7 @@ import type { ShoppingListItem, CompositeItem, } from "@gram-lang/kitchen"; -import { getNumericQty, scheduleTimes } from "@gram-lang/kitchen"; +import { getNumericQty, scheduleFor, scheduleTimes } from "@gram-lang/kitchen"; // Structural, analyzer-local shapes for the module-composition metadata a // `CompilationResult` may carry when it actually came from @@ -421,19 +421,22 @@ function diffIngredients( return deltas; } -// The four times a diff reports. Preparation and active time are the same in -// every mise en place schedule; total and idle time depend on the schedule, so -// they are read from the default one (preparation right before each section) -// — the same on both sides, which is all a comparison needs. +// The four times a diff reports, all read from the default timeline (mise en +// place right before each section, the shortest rests): the same on both sides, +// which is all a comparison needs. The active time is the schedule's, which +// plans a timer written as a range on its longest figure, so changing the range +// of a cooking time shows; `metrics.activeTime` (the average) is deprecated. function timingsOf( recipe: CompilationResult, ): Record { const { totalTime, idleTime } = scheduleTimes(recipe); + const schedule = scheduleFor(recipe); return { totalTime, idleTime, - activeTime: recipe.metrics?.activeTime ?? 0, - preparationTime: recipe.metrics?.preparationTime ?? 0, + activeTime: schedule?.activeTime ?? recipe.metrics?.activeTime ?? 0, + preparationTime: + schedule?.preparationTime ?? recipe.metrics?.preparationTime ?? 0, }; } diff --git a/packages/analyzer/tests/diff.test.ts b/packages/analyzer/tests/diff.test.ts index b6a9ed88..f2c69053 100644 --- a/packages/analyzer/tests/diff.test.ts +++ b/packages/analyzer/tests/diff.test.ts @@ -303,7 +303,7 @@ describe("diffRecipes — timings follow the per-section schedule", () => { expect(idle?.to).toBe(schedulesOf(b).perSection.idleTime); }); - it("still compares preparation and active time from the metrics", () => { + it("compares the preparation time of the schedule, the sum of the mise en place", () => { const a = compileRecipe(base); const b = compileRecipe(base.replace("(sifted)", "")); const { timings } = diffRecipes(a, b); @@ -320,9 +320,9 @@ describe("diffRecipes — timings follow the per-section schedule", () => { ).toEqual([]); }); - it("compares JSON stored before 1.4.0 (no schedules) through its old metrics, not as zero", () => { + it("compares JSON stored before 1.4.0 (no tasks) through its old metrics, not as zero", () => { const current = compileRecipe(base); - const { schedules: _s, ...stored } = compileRecipe(base); + const { schedule: _s, tasks: _t, ...stored } = compileRecipe(base); const timings = diffRecipes(current, stored as never).timings; // Never the "150 -> 0" a missing schedule used to read as. @@ -333,3 +333,32 @@ describe("diffRecipes — timings follow the per-section schedule", () => { expect(diffRecipes(stored as never, stored as never).timings).toEqual([]); }); }); + +describe("diffRecipes — the active time is the schedule's", () => { + const cook = (range: string) => + `## Roast\n\nRoast @chicken{1kg} for ~{${range}}.\n`; + + it("shows a change of the range of a cooking time, planned on its longest figure", () => { + const a = compileRecipe(cook("40-50min")); + const b = compileRecipe(cook("40-60min")); + const active = diffRecipes(a, b).timings.find( + (t) => t.field === "activeTime", + ); + expect(active).toEqual({ field: "activeTime", from: 50, to: 60 }); + // The deprecated metric is the average: 45 and 50. + expect(a.metrics.activeTime).toBe(45); + }); + + it("falls back on the old metric for JSON stored before 1.4.0", () => { + const a = compileRecipe(cook("40-50min")); + const { + schedule: _s, + tasks: _t, + ...stored + } = compileRecipe(cook("40-70min")); + const active = diffRecipes(a, stored as never).timings.find( + (t) => t.field === "activeTime", + ); + expect(active).toEqual({ field: "activeTime", from: 50, to: 55 }); + }); +}); -- 2.54.0 From d59c8270f351725328f072384eea3dded0cd140f Mon Sep 17 00:00:00 2001 From: abiwab Date: Sun, 4 Oct 2026 12:46:26 +0200 Subject: [PATCH 5/6] feat(i18n): add the labels of the rests and of the plan settings --- packages/i18n/src/locales/en.ts | 14 ++++++++++++++ packages/i18n/src/locales/fr.ts | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/packages/i18n/src/locales/en.ts b/packages/i18n/src/locales/en.ts index faffd777..95767fd2 100644 --- a/packages/i18n/src/locales/en.ts +++ b/packages/i18n/src/locales/en.ts @@ -16,6 +16,10 @@ export const en = { miseEnPlace: "Mise en place", miseEnPlaceTooltip: "Mise en place for this section", scheduleLabel: "Mise en place", + restsLabel: "Rests", + restsShortest: "Shortest", + restsBalanced: "Middle", + restsLongest: "Longest", schedulePerSection: "By section", scheduleUpfront: "All at the start", schedulePerSession: "By working day", @@ -136,6 +140,16 @@ export const en = { markdown: "Markdown", preview: "Preview (HTML)", gantt: "Gantt Chart", + runSheet: "Production sheet", + runSheetHint: + "Choose when it is served in the plan settings to get a production sheet, with a time for every task.", + planSummary: "Plan", + planServeAt: "Served on", + planTimeZone: "Time zone", + planAvailableFrom: "Available from", + planAvailableTo: "to", + planClear: "Clear the plan", + planInvalid: "This plan can't be made: {message}", gantt_active: "Active Task", gantt_passive: "Background Task", gantt_compact: "Compact View", diff --git a/packages/i18n/src/locales/fr.ts b/packages/i18n/src/locales/fr.ts index 78caabac..eba140bb 100644 --- a/packages/i18n/src/locales/fr.ts +++ b/packages/i18n/src/locales/fr.ts @@ -19,6 +19,10 @@ export const fr: GramLocale = { miseEnPlace: "Mise en place", miseEnPlaceTooltip: "Mise en place de cette section", scheduleLabel: "Mise en place", + restsLabel: "Repos", + restsShortest: "Les plus courts", + restsBalanced: "Au milieu", + restsLongest: "Les plus longs", schedulePerSection: "Par section", scheduleUpfront: "Tout au début", schedulePerSession: "Par journée de travail", @@ -126,6 +130,16 @@ export const fr: GramLocale = { markdown: "Markdown", preview: "Aperçu (HTML)", gantt: "Diagramme de Gantt", + runSheet: "Fiche de production", + runSheetHint: + "Choisissez l'heure du service dans les réglages du plan pour obtenir une fiche de production, avec une heure pour chaque tâche.", + planSummary: "Plan", + planServeAt: "Servi le", + planTimeZone: "Fuseau horaire", + planAvailableFrom: "Disponible de", + planAvailableTo: "à", + planClear: "Effacer le plan", + planInvalid: "Ce plan est impossible à faire : {message}", gantt_active: "Tâche active", gantt_passive: "Tâche de fond", gantt_compact: "Vue compacte", -- 2.54.0 From 8cf3c8da5d22bd0eeb6dca790c2972b997e66a02 Mon Sep 17 00:00:00 2001 From: abiwab Date: Sun, 4 Oct 2026 12:46:26 +0200 Subject: [PATCH 6/6] feat(playground): choose the rests, plan a recipe on the calendar and show its production sheet --- bun.lock | 2 + packages/docs/package.json | 3 +- .../src/components/playground/GramGantt.vue | 7 +- .../src/components/playground/GramOutput.vue | 29 +- .../components/playground/GramPlayground.vue | 311 +++++++++++++++++- 5 files changed, 342 insertions(+), 10 deletions(-) diff --git a/bun.lock b/bun.lock index 8f269345..4a8556a8 100644 --- a/bun.lock +++ b/bun.lock @@ -78,6 +78,7 @@ "@gram-lang/modules": "workspace:*", "@gram-lang/parser": "workspace:*", "@gram-lang/renderer": "workspace:*", + "@gram-lang/scheduler": "workspace:*", "ai": "^7.0.22", "chalk": "^6.0.1", "citty": "^0.2.2", @@ -116,6 +117,7 @@ "@gram-lang/modules": "workspace:*", "@gram-lang/parser": "workspace:*", "@gram-lang/renderer": "workspace:*", + "@gram-lang/scheduler": "workspace:*", "astro": "^7.3.5", "mermaid": "^12.0.0", "shiki": "^4.3.1", diff --git a/packages/docs/package.json b/packages/docs/package.json index 93291c06..d90e7005 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -31,6 +31,7 @@ "@gram-lang/modules": "workspace:*", "@gram-lang/parser": "workspace:*", "@gram-lang/renderer": "workspace:*", + "@gram-lang/scheduler": "workspace:*", "astro": "^7.3.5", "mermaid": "^12.0.0", "shiki": "^4.3.1", @@ -44,4 +45,4 @@ "@types/mdast": "^4.0.4", "starlight-links-validator": "^0.26.0" } -} \ No newline at end of file +} diff --git a/packages/docs/src/components/playground/GramGantt.vue b/packages/docs/src/components/playground/GramGantt.vue index 95e589bd..ebe0f144 100644 --- a/packages/docs/src/components/playground/GramGantt.vue +++ b/packages/docs/src/components/playground/GramGantt.vue @@ -6,13 +6,16 @@ import { attachGanttInteractivity, type GanttInteractivityHandle, } from "@gram-lang/renderer"; -import type { MiseEnPlaceMode } from "@gram-lang/kitchen"; +import type { MiseEnPlaceMode, RestChoice } from "@gram-lang/kitchen"; +import type { ProjectedPlan } from "@gram-lang/scheduler"; const { lang } = useI18n(); const props = defineProps<{ jsonData: any; schedule?: MiseEnPlaceMode; + rests?: RestChoice; + projection?: ProjectedPlan; }>(); const container = ref(null); @@ -22,6 +25,8 @@ const html = computed(() => toGanttHTML(props.jsonData, { lang: lang.value, miseEnPlace: props.schedule, + rests: props.rests, + projection: props.projection, }), ); diff --git a/packages/docs/src/components/playground/GramOutput.vue b/packages/docs/src/components/playground/GramOutput.vue index d10e422c..29f25966 100644 --- a/packages/docs/src/components/playground/GramOutput.vue +++ b/packages/docs/src/components/playground/GramOutput.vue @@ -12,7 +12,8 @@ import { import { useI18n } from "./useI18n"; import { getHighlighter, SHIKI_THEMES } from "./shikiHighlighter"; import { trackEvent } from "../../lib/umami"; -import type { MiseEnPlaceMode } from "@gram-lang/kitchen"; +import type { MiseEnPlaceMode, RestChoice } from "@gram-lang/kitchen"; +import type { ProjectedPlan } from "@gram-lang/scheduler"; import type { PlaygroundDiagnostic } from "./diagnostics"; // biome-ignore lint/correctness/noUnusedImports: used as a component in the