diff --git a/.changeset/vscode-mise-en-place-setting.md b/.changeset/vscode-mise-en-place-setting.md new file mode 100644 index 00000000..11bc4423 --- /dev/null +++ b/.changeset/vscode-mise-en-place-setting.md @@ -0,0 +1,10 @@ +--- +"@gram-lang/language-server": minor +"gram-lang": minor +--- + +**Language Server / VS Code**: A new `gram.miseEnPlace` setting chooses when the mise en place is planned, right before each section (`perSection`, the default) or all at the start (`upfront`): + +- 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 +- Changing a `gram.*` setting now reaches the language server straight away, without reloading the window (this also applies to `gram.ingredientDatabase.path`) diff --git a/packages/language-server/src/features/inlay-hints.ts b/packages/language-server/src/features/inlay-hints.ts index 33d48ea9..d69ce9a9 100644 --- a/packages/language-server/src/features/inlay-hints.ts +++ b/packages/language-server/src/features/inlay-hints.ts @@ -1,11 +1,19 @@ import { type InlayHint, InlayHintKind, Position } from "vscode-languageserver"; +import type { ScheduleMode } from "@gram-lang/renderer"; import type { DocumentState } from "../document-state"; +import { DEFAULT_MISE_EN_PLACE } from "../utils/mise-en-place-setting"; -export function provideInlayHints(state: DocumentState): InlayHint[] { +export function provideInlayHints( + state: DocumentState, + schedule: ScheduleMode = DEFAULT_MISE_EN_PLACE, +): InlayHint[] { const hints: InlayHint[] = []; if (!state.ast || !state.compilation?.metrics) return hints; const metrics = state.compilation.metrics; + // The total follows the chosen schedule (`gram.miseEnPlace`). + const totalTime = + state.compilation.schedules?.[schedule]?.totalTime ?? metrics.totalTime; let titleLine = 0; let titleChar = 0; @@ -18,8 +26,8 @@ export function provideInlayHints(state: DocumentState): InlayHint[] { } } - if (metrics.totalTime > 0) { - const totalMinutes = Math.round(metrics.totalTime); + if (totalTime > 0) { + const totalMinutes = Math.round(totalTime); const hours = Math.floor(totalMinutes / 60); const mins = totalMinutes % 60; const timeStr = diff --git a/packages/language-server/src/server.ts b/packages/language-server/src/server.ts index 5e915234..5a56dc95 100644 --- a/packages/language-server/src/server.ts +++ b/packages/language-server/src/server.ts @@ -34,12 +34,21 @@ import { } from "./features/semantic-tokens"; import type { IngredientDB } from "./ingredient-loader"; import { provideInlayHints } from "./features/inlay-hints"; +import { + DEFAULT_MISE_EN_PLACE, + parseMiseEnPlaceSetting, +} from "./utils/mise-en-place-setting"; import { provideCodeLenses } from "./features/code-lens"; import { positionToOffset } from "./utils/position"; import { resolveWorkspaceFolders } from "./utils/workspace-folders"; import { resolveFreshState } from "./utils/fresh-state"; import { reloadDbAndRefreshDiagnostics as computeDbReload } from "./utils/db-reload"; -import { toHTML, toGanttHTML, escapeHtml } from "@gram-lang/renderer"; +import { + toHTML, + toGanttHTML, + escapeHtml, + type ScheduleMode, +} from "@gram-lang/renderer"; const connection = createConnection(ProposedFeatures.all); const documents = new TextDocuments(TextDocument); @@ -148,6 +157,24 @@ 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. +let miseEnPlace: ScheduleMode = DEFAULT_MISE_EN_PLACE; + +// 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; + return changed; + } catch { + return false; + } +} + // Called from onDidChangeWatchedFiles/ // onDidChangeConfiguration without awaiting or catching the returned // promise. This function must never reject — every call site treats it as @@ -175,6 +202,7 @@ async function reloadDbAndRefreshDiagnostics(): Promise { } connection.onInitialized(async () => { + await loadMiseEnPlace(); await reloadDbAndRefreshDiagnostics(); // Watch ingredients.yaml so edits made outside the editor (gram db sync/enrich, @@ -225,6 +253,23 @@ connection.onInitialized(async () => { reloadDbAndRefreshDiagnostics().catch((e) => connection.console.error(`DB reload failed: ${e}`), ); + // A new schedule re-renders every open preview and Gantt, and refreshes + // the title hint — nothing else about the documents changed. + loadMiseEnPlace() + .then(async (changed) => { + if (!changed) return; + await Promise.all( + [...states].map(([uri, state]) => + refresh(uri, state.text, state.version), + ), + ); + await connection.languages.inlayHint.refresh().catch(() => { + // Client without inlay hint refresh: the hint updates on next edit. + }); + }) + .catch((e) => + connection.console.error(`Mise en place refresh failed: ${e}`), + ); }); }); @@ -259,7 +304,10 @@ async function refresh( // The VS Code preview ships the renderer's stylesheet (mirrored in // media/preview.css), so the CSS-only nutrition basis toggle works // there — quantities stay read-only. - const html = toHTML(state.compilation, { interactiveNutrition: true }); + const html = toHTML(state.compilation, { + interactiveNutrition: true, + schedule: miseEnPlace, + }); connection.sendNotification("gram/previewUpdated", { uri, html }); } catch (e) { console.error("HTML render error", e); @@ -268,7 +316,9 @@ async function refresh( // Rendered and sent independently from the main preview — a bug in the // Gantt renderer must not blank the HTML preview, and vice versa. try { - const ganttHtml = toGanttHTML(state.compilation, {}); + const ganttHtml = toGanttHTML(state.compilation, { + schedule: miseEnPlace, + }); connection.sendNotification("gram/ganttUpdated", { uri, html: ganttHtml, @@ -469,7 +519,7 @@ connection.languages.semanticTokens.on(({ textDocument: { uri } }) => { connection.languages.inlayHint.on(({ textDocument: { uri } }) => { const s = states.get(uri); - return s ? provideInlayHints(s) : []; + return s ? provideInlayHints(s, miseEnPlace) : []; }); 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 new file mode 100644 index 00000000..bff48a10 --- /dev/null +++ b/packages/language-server/src/utils/mise-en-place-setting.ts @@ -0,0 +1,18 @@ +import type { ScheduleMode } from "@gram-lang/renderer"; + +/** Preparation right before each section, unless the reader picks otherwise. */ +export const DEFAULT_MISE_EN_PLACE: ScheduleMode = "perSection"; + +/** + * Reads `gram.miseEnPlace` out of whatever `getConfiguration("gram")` hands + * back. Anything that isn't one of the two known values — a missing key, a + * typo, a client that returned nothing — falls back to the default, so a bad + * setting can never blank the preview. + */ +export function parseMiseEnPlaceSetting(config: unknown): ScheduleMode { + const value = (config as { miseEnPlace?: unknown } | null | undefined) + ?.miseEnPlace; + return value === "upfront" || value === "perSection" + ? value + : DEFAULT_MISE_EN_PLACE; +} diff --git a/packages/language-server/tests/inlay-hints.test.ts b/packages/language-server/tests/inlay-hints.test.ts new file mode 100644 index 00000000..ea977fde --- /dev/null +++ b/packages/language-server/tests/inlay-hints.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "bun:test"; +import { parseDocument } from "../src/document-state"; +import { provideInlayHints } from "../src/features/inlay-hints"; + +const SOURCE = `--- +title: Tart +--- + +## Pastry ~{-2d} + +Mix @flour{200g}(sifted). + +## Assembly + +Combine the pastry with @filling{300g}. +`; + +const label = (hints: ReturnType) => + hints.map((h) => h.label).join(""); + +describe("provideInlayHints follows the chosen schedule", () => { + const state = parseDocument(SOURCE); + + it("reads the total from the schedule, not from the deprecated metric", () => { + const { perSection, upfront } = state.compilation!.schedules; + expect(perSection.totalTime).not.toBe(upfront.totalTime); + + const fmt = (minutes: number) => { + const total = Math.round(minutes); + const h = Math.floor(total / 60); + const m = total % 60; + return h > 0 ? (m > 0 ? `${h}h${m}` : `${h}h`) : `${m}m`; + }; + expect(label(provideInlayHints(state, "perSection"))).toContain( + fmt(perSection.totalTime), + ); + expect(label(provideInlayHints(state, "upfront"))).toContain( + fmt(upfront.totalTime), + ); + }); + + it("defaults to the per-section schedule", () => { + expect(label(provideInlayHints(state))).toBe( + label(provideInlayHints(state, "perSection")), + ); + }); + + it("still shows nothing for a recipe that failed to compile", () => { + expect( + provideInlayHints(parseDocument("## Broken\n\nAdd @salt{1 g/l}.\n")), + ).toEqual([]); + }); +}); diff --git a/packages/language-server/tests/mise-en-place-setting.test.ts b/packages/language-server/tests/mise-en-place-setting.test.ts new file mode 100644 index 00000000..25ce38b7 --- /dev/null +++ b/packages/language-server/tests/mise-en-place-setting.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "bun:test"; +import { + DEFAULT_MISE_EN_PLACE, + parseMiseEnPlaceSetting, +} from "../src/utils/mise-en-place-setting"; + +describe("parseMiseEnPlaceSetting", () => { + it("defaults to preparing right before each section", () => { + expect(DEFAULT_MISE_EN_PLACE).toBe("perSection"); + }); + + it("reads both known values", () => { + expect(parseMiseEnPlaceSetting({ miseEnPlace: "perSection" })).toBe( + "perSection", + ); + expect(parseMiseEnPlaceSetting({ miseEnPlace: "upfront" })).toBe("upfront"); + }); + + it("falls back to the default for anything else, so a bad setting never blanks the preview", () => { + for (const bad of [ + undefined, + null, + {}, + { miseEnPlace: "" }, + { miseEnPlace: "UPFRONT" }, + { miseEnPlace: "global" }, + { miseEnPlace: 1 }, + "upfront", + ]) { + expect(parseMiseEnPlaceSetting(bad)).toBe("perSection"); + } + }); +}); diff --git a/packages/vscode-extension/package.json b/packages/vscode-extension/package.json index 016ec221..9c716028 100644 --- a/packages/vscode-extension/package.json +++ b/packages/vscode-extension/package.json @@ -102,6 +102,19 @@ "type": "string", "default": "", "description": "Path to a YAML ingredient database file. Leave empty to auto-detect .gram/ingredients.yaml in the workspace root." + }, + "gram.miseEnPlace": { + "type": "string", + "enum": [ + "perSection", + "upfront" + ], + "enumDescriptions": [ + "Each section's mise en place happens right before that section.", + "All the mise en place happens at the start of the recipe." + ], + "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." } } }, diff --git a/packages/vscode-extension/src/client-options.ts b/packages/vscode-extension/src/client-options.ts new file mode 100644 index 00000000..d1f90410 --- /dev/null +++ b/packages/vscode-extension/src/client-options.ts @@ -0,0 +1,17 @@ +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 + * database path) has no effect until the window is reloaded. + */ +export const CONFIGURATION_SECTION = "gram"; + +export function createClientOptions(): LanguageClientOptions { + return { + documentSelector: [{ scheme: "file", language: "gram" }], + synchronize: { configurationSection: CONFIGURATION_SECTION }, + }; +} diff --git a/packages/vscode-extension/src/extension.ts b/packages/vscode-extension/src/extension.ts index 2e40a1de..ecc2b4a0 100644 --- a/packages/vscode-extension/src/extension.ts +++ b/packages/vscode-extension/src/extension.ts @@ -3,9 +3,9 @@ import * as vscode from "vscode"; import type { ExtensionContext } from "vscode"; import { PreviewPanel } from "./preview"; import { GanttPanel } from "./gantt-panel"; +import { createClientOptions } from "./client-options"; import { LanguageClient, - type LanguageClientOptions, type ServerOptions, TransportKind, } from "vscode-languageclient/node"; @@ -24,9 +24,7 @@ export async function activate(context: ExtensionContext): Promise { }, }; - const clientOptions: LanguageClientOptions = { - documentSelector: [{ scheme: "file", language: "gram" }], - }; + const clientOptions = createClientOptions(); const previewHtmlCache = new Map(); const ganttHtmlCache = new Map(); diff --git a/packages/vscode-extension/tests/client-options.test.ts b/packages/vscode-extension/tests/client-options.test.ts new file mode 100644 index 00000000..3e01fbcc --- /dev/null +++ b/packages/vscode-extension/tests/client-options.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + CONFIGURATION_SECTION, + createClientOptions, +} from "../src/client-options"; + +describe("language client options", () => { + it("tells the server when a gram.* setting changes", () => { + // Without `synchronize.configurationSection` the client never sends + // workspace/didChangeConfiguration, so changing gram.miseEnPlace in the + // settings left the preview and the Gantt chart untouched. + expect(createClientOptions().synchronize?.configurationSection).toBe( + "gram", + ); + }); + + it("uses the same section the settings are declared under", () => { + const manifest = JSON.parse( + readFileSync(join(import.meta.dir, "..", "package.json"), "utf-8"), + ); + const keys = Object.keys(manifest.contributes.configuration.properties); + expect(keys.length).toBeGreaterThan(0); + for (const key of keys) { + expect(key.startsWith(`${CONFIGURATION_SECTION}.`)).toBe(true); + } + }); + + it("still selects gram files", () => { + expect(createClientOptions().documentSelector).toEqual([ + { scheme: "file", language: "gram" }, + ]); + }); +});