feat(language-server): follow the gram.miseEnPlace setting #51

Merged
abiwab merged 2 commits from feat/vscode-schedule into main 2026-09-30 07:51:31 +02:00
10 changed files with 246 additions and 11 deletions

View file

@ -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`)

View file

@ -1,11 +1,19 @@
import { type InlayHint, InlayHintKind, Position } from "vscode-languageserver"; import { type InlayHint, InlayHintKind, Position } from "vscode-languageserver";
import type { ScheduleMode } from "@gram-lang/renderer";
import type { DocumentState } from "../document-state"; 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[] = []; const hints: InlayHint[] = [];
if (!state.ast || !state.compilation?.metrics) return hints; if (!state.ast || !state.compilation?.metrics) return hints;
const metrics = state.compilation.metrics; 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 titleLine = 0;
let titleChar = 0; let titleChar = 0;
@ -18,8 +26,8 @@ export function provideInlayHints(state: DocumentState): InlayHint[] {
} }
} }
if (metrics.totalTime > 0) { if (totalTime > 0) {
const totalMinutes = Math.round(metrics.totalTime); const totalMinutes = Math.round(totalTime);
const hours = Math.floor(totalMinutes / 60); const hours = Math.floor(totalMinutes / 60);
const mins = totalMinutes % 60; const mins = totalMinutes % 60;
const timeStr = const timeStr =

View file

@ -34,12 +34,21 @@ import {
} from "./features/semantic-tokens"; } from "./features/semantic-tokens";
import type { IngredientDB } from "./ingredient-loader"; import type { IngredientDB } from "./ingredient-loader";
import { provideInlayHints } from "./features/inlay-hints"; 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 { provideCodeLenses } from "./features/code-lens";
import { positionToOffset } from "./utils/position"; import { positionToOffset } from "./utils/position";
import { resolveWorkspaceFolders } from "./utils/workspace-folders"; import { resolveWorkspaceFolders } from "./utils/workspace-folders";
import { resolveFreshState } from "./utils/fresh-state"; import { resolveFreshState } from "./utils/fresh-state";
import { reloadDbAndRefreshDiagnostics as computeDbReload } from "./utils/db-reload"; 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 connection = createConnection(ProposedFeatures.all);
const documents = new TextDocuments(TextDocument); 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<boolean> {
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/ // Called from onDidChangeWatchedFiles/
// onDidChangeConfiguration without awaiting or catching the returned // onDidChangeConfiguration without awaiting or catching the returned
// promise. This function must never reject — every call site treats it as // promise. This function must never reject — every call site treats it as
@ -175,6 +202,7 @@ async function reloadDbAndRefreshDiagnostics(): Promise<void> {
} }
connection.onInitialized(async () => { connection.onInitialized(async () => {
await loadMiseEnPlace();
await reloadDbAndRefreshDiagnostics(); await reloadDbAndRefreshDiagnostics();
// Watch ingredients.yaml so edits made outside the editor (gram db sync/enrich, // Watch ingredients.yaml so edits made outside the editor (gram db sync/enrich,
@ -225,6 +253,23 @@ connection.onInitialized(async () => {
reloadDbAndRefreshDiagnostics().catch((e) => reloadDbAndRefreshDiagnostics().catch((e) =>
connection.console.error(`DB reload failed: ${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 // The VS Code preview ships the renderer's stylesheet (mirrored in
// media/preview.css), so the CSS-only nutrition basis toggle works // media/preview.css), so the CSS-only nutrition basis toggle works
// there — quantities stay read-only. // 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 }); connection.sendNotification("gram/previewUpdated", { uri, html });
} catch (e) { } catch (e) {
console.error("HTML render error", 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 // Rendered and sent independently from the main preview — a bug in the
// Gantt renderer must not blank the HTML preview, and vice versa. // Gantt renderer must not blank the HTML preview, and vice versa.
try { try {
const ganttHtml = toGanttHTML(state.compilation, {}); const ganttHtml = toGanttHTML(state.compilation, {
schedule: miseEnPlace,
});
connection.sendNotification("gram/ganttUpdated", { connection.sendNotification("gram/ganttUpdated", {
uri, uri,
html: ganttHtml, html: ganttHtml,
@ -469,7 +519,7 @@ connection.languages.semanticTokens.on(({ textDocument: { uri } }) => {
connection.languages.inlayHint.on(({ textDocument: { uri } }) => { connection.languages.inlayHint.on(({ textDocument: { uri } }) => {
const s = states.get(uri); const s = states.get(uri);
return s ? provideInlayHints(s) : []; return s ? provideInlayHints(s, miseEnPlace) : [];
}); });
connection.onCodeLens(({ textDocument: { uri } }) => { connection.onCodeLens(({ textDocument: { uri } }) => {

View file

@ -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;
}

View file

@ -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<typeof provideInlayHints>) =>
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([]);
});
});

View file

@ -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");
}
});
});

View file

@ -102,6 +102,19 @@
"type": "string", "type": "string",
"default": "", "default": "",
"description": "Path to a YAML ingredient database file. Leave empty to auto-detect .gram/ingredients.yaml in the workspace root." "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."
} }
} }
}, },

View file

@ -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 },
};
}

View file

@ -3,9 +3,9 @@ import * as vscode from "vscode";
import type { ExtensionContext } from "vscode"; import type { ExtensionContext } from "vscode";
import { PreviewPanel } from "./preview"; import { PreviewPanel } from "./preview";
import { GanttPanel } from "./gantt-panel"; import { GanttPanel } from "./gantt-panel";
import { createClientOptions } from "./client-options";
import { import {
LanguageClient, LanguageClient,
type LanguageClientOptions,
type ServerOptions, type ServerOptions,
TransportKind, TransportKind,
} from "vscode-languageclient/node"; } from "vscode-languageclient/node";
@ -24,9 +24,7 @@ export async function activate(context: ExtensionContext): Promise<void> {
}, },
}; };
const clientOptions: LanguageClientOptions = { const clientOptions = createClientOptions();
documentSelector: [{ scheme: "file", language: "gram" }],
};
const previewHtmlCache = new Map<string, string>(); const previewHtmlCache = new Map<string, string>();
const ganttHtmlCache = new Map<string, string>(); const ganttHtmlCache = new Map<string, string>();

View file

@ -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" },
]);
});
});