feat(vscode): serving time in the work plan panel (views phase 7, step 1) #107

Merged
abiwab merged 3 commits from feat/views-p7-vscode-serving into feat/views-architecture 2026-11-05 23:48:50 +01:00
28 changed files with 827 additions and 94 deletions

View file

@ -8,7 +8,8 @@
- A client declaring `initializationOptions.views` specifies open recipe outputs via `gram/setOpenViews` and receives targeted updates in `gram/viewUpdated`: recipe and work plan views as HTML, or AST and compiled JSON as text or interactive trees. Closed outputs are no longer evaluated - A client declaring `initializationOptions.views` specifies open recipe outputs via `gram/setOpenViews` and receives targeted updates in `gram/viewUpdated`: recipe and work plan views as HTML, or AST and compiled JSON as text or interactive trees. Closed outputs are no longer evaluated
- When a recipe encounters compilation errors, open outputs are paused rather than replaced by an error card: editors retain their last valid rendered view, while localized error summaries are provided alongside standard LSP diagnostics - When a recipe encounters compilation errors, open outputs are paused rather than replaced by an error card: editors retain their last valid rendered view, while localized error summaries are provided alongside standard LSP diagnostics
- `gram/setSession` configures transient session parameters for a recipe: target serving time (projecting the work plan onto the calendar in the project's `timezone` and within its `availability`), scaling factor, pre-prepared imports in stock, and baker's percentage reference. Sessions are held per document in memory, while compiler diagnostics continue evaluating the recipe as written - `gram/setSession` configures transient session parameters for a recipe: target serving time (projecting the work plan onto the calendar in the project's `timezone` and within its `availability`), scaling factor, pre-prepared imports in stock, and baker's percentage reference. Sessions are held per document in memory, while compiler diagnostics continue evaluating the recipe as written
- The outputs a client can open are listed in the `initialize` result, each with its name in the editor's language, so an editor shows a new view of Gram without an update of its own - The outputs a client can open are listed in the `initialize` result, each with its name in the editor's language and what it reads from the plan, so an editor shows a new view of Gram without an update of its own, and offers a serving time for any view laid out in time
- A `gram/serveTimes` request gives the serving times to propose for a recipe, in words: those that work over the next seven days at the project's `mealTimes`, why the others do not, and the earliest one
**Deprecated** **Deprecated**

View file

@ -6,7 +6,7 @@
- the timeline for the chosen settings and its total and idle times, the same at any serving time - the timeline for the chosen settings and its total and idle times, the same at any serving time
- the work plan, on the calendar when a serving time is given, otherwise in days before the service - the work plan, on the calendar when a serving time is given, otherwise in days before the service
- the serving time search (the earliest serving time, and the times worth proposing in a range) from your kitchen's time zone and hours - the serving time search (the earliest serving time, and the times worth proposing in a range) from your kitchen's time zone and hours; `suggestServeTimes()` puts it in words for a serving time field: the times that work over the next days, why the others do not, and the earliest
- `views` lists the views of a recipe (the recipe, the work plan) with the formats each one offers, the settings it follows and what it needs worked out, and `render(view, input, format)` writes one of them from what `prepareViews()` gave; it returns `null` for a work plan when the recipe has no tasks. `toHTML`, `runSheetToHTML` and the other functions stay as they are - `views` lists the views of a recipe (the recipe, the work plan) with the formats each one offers, the settings it follows and what it needs worked out, and `render(view, input, format)` writes one of them from what `prepareViews()` gave; it returns `null` for a work plan when the recipe has no tasks. `toHTML`, `runSheetToHTML` and the other functions stay as they are
- `inspectors` lists the looks at the pipeline (the composed AST as an S-expression, the analyzed recipe as JSON or as a tree that folds), and `outputs` lists the views and the inspectors together, for an interface that offers both. `renderJsonTree()` writes any data as that tree, with no script (native folding, keyboard included), and `JSON_TREE_CSS` styles it with colors you set through CSS variables; `renderSExpr()` writes an AST as an S-expression - `inspectors` lists the looks at the pipeline (the composed AST as an S-expression, the analyzed recipe as JSON or as a tree that folds), and `outputs` lists the views and the inspectors together, for an interface that offers both. `renderJsonTree()` writes any data as that tree, with no script (native folding, keyboard included), and `JSON_TREE_CSS` styles it with colors you set through CSS variables; `renderSExpr()` writes an AST as an S-expression
- `describeError()` picks the error to show when a recipe stops compiling (a blocking error first, then the first error) and gives its code, message, file and position, with a title in the recipe's language, so every interface reports the same error the same way - `describeError()` picks the error to show when a recipe stops compiling (a blocking error first, then the first error) and gives its code, message, file and position, with a title in the recipe's language, so every interface reports the same error the same way

View file

@ -6,6 +6,7 @@
**Language Server / VS Code**: The editor shows the work plan of the recipe in place of the Gantt chart: **Language Server / VS Code**: The editor shows the work plan of the recipe in place of the Gantt chart:
- A new `Gram: Work Plan` command opens it next to the recipe, in days before the service (D-2, D-1, day D); it follows the `gram.miseEnPlace`, `gram.rests` and `gram.comments` settings - A new `Gram: Work Plan` command opens it next to the recipe, in days before the service (D-2, D-1, day D); it follows the `gram.miseEnPlace`, `gram.rests` and `gram.comments` settings
- A **Served at** field at the top of the work plan puts it on the calendar, with dates and clock times, in your project's time zone and hours (`timezone` and `availability` in `.gram/config.yaml`); **When to serve?** proposes the times that work over the next seven days, the earliest first, and says why the others do not. The serving time is kept per recipe while VS Code is open, never saved
**Deprecated** **Deprecated**

View file

@ -196,7 +196,7 @@ function clearServeAt() {
// biome-ignore lint/correctness/noUnusedVariables: formatEarliestLabel is used in the <template> block below, which Biome's Vue support doesn't see. // biome-ignore lint/correctness/noUnusedVariables: formatEarliestLabel is used in the <template> block below, which Biome's Vue support doesn't see.
function formatEarliestLabel(label: string): string { function formatEarliestLabel(label: string): string {
return lang.value === "fr" ? `Au plus tôt : ${label}` : `Earliest: ${label}`; return t.value.renderer.serving.earliest.replace("{when}", label);
} }
// biome-ignore lint/correctness/noUnusedVariables: filteredCandidates is used in the <template> block below, which Biome's Vue support doesn't see. // biome-ignore lint/correctness/noUnusedVariables: filteredCandidates is used in the <template> block below, which Biome's Vue support doesn't see.

View file

@ -57,13 +57,13 @@ import {
sortDiagnostics, sortDiagnostics,
} from "./diagnostics"; } from "./diagnostics";
import { import {
describeEarliestServe,
describeServeTimes,
type Format, type Format,
type ServeSuggestions,
type ViewSettings, type ViewSettings,
VIEW_SETTINGS, VIEW_SETTINGS,
prepareViews, prepareViews,
recipeSettingsToAnalyzerOptions, recipeSettingsToAnalyzerOptions,
suggestServeTimes,
} from "@gram-lang/renderer"; } from "@gram-lang/renderer";
import { import {
formatFor, formatFor,
@ -257,14 +257,6 @@ function loadPlan(): PlanSettings {
const plan = ref<PlanSettings>(loadPlan()); const plan = ref<PlanSettings>(loadPlan());
const planError = ref(""); const planError = ref("");
interface ServeSuggestions {
/** Serving times that work, best first. */
candidates: { serveAt: string; label: string; title: string }[];
/** Why the others don't, in words. */
rejected: string[];
/** The first time it can be ready if the cook starts now. */
earliest: { serveAt: string; label: string; text: string } | null;
}
const serveSuggestions = shallowRef<ServeSuggestions | null>(null); const serveSuggestions = shallowRef<ServeSuggestions | null>(null);
watch( watch(
@ -869,7 +861,6 @@ function computeServeSuggestions() {
} }
try { try {
const { timeZone } = plan.value; const { timeZone } = plan.value;
const now = new Date();
const views = prepareViews( const views = prepareViews(
result, result,
{ miseEnPlace: schedule.value, rests: rests.value }, { miseEnPlace: schedule.value, rests: rests.value },
@ -877,56 +868,13 @@ function computeServeSuggestions() {
kitchen: { kitchen: {
timeZone, timeZone,
availability: buildAvailability(plan.value), availability: buildAvailability(plan.value),
now: now.toISOString(), now: new Date().toISOString(),
}, },
}, },
); );
const localDay = (offset: number) => serveSuggestions.value = suggestServeTimes(views, {
new Intl.DateTimeFormat("en-CA", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(new Date(now.getTime() + offset * 86_400_000));
const range = { from: localDay(0), to: localDay(7) };
const search = views.findServeTimes({ ...range, limit: 6 });
const earliest = views.earliestServe();
if (!search || !earliest) {
serveSuggestions.value = null;
return;
}
const words = describeServeTimes(search, result, {
...range,
timeZone,
lang: currentLang.value, lang: currentLang.value,
}); });
const label = (serveAt: string) =>
new Intl.DateTimeFormat(currentLang.value || "en", {
timeZone: "UTC",
weekday: "short",
day: "numeric",
month: "short",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
}).format(new Date(`${serveAt}:00Z`));
serveSuggestions.value = {
candidates: search.candidates.map((c, i) => ({
serveAt: c.serveAt,
label: label(c.serveAt),
title: words[i] ?? "",
})),
rejected: words.slice(search.candidates.length),
earliest: earliest.found
? {
serveAt: earliest.found.serveAt,
label: label(earliest.found.serveAt),
text: describeEarliestServe(earliest, {
lang: currentLang.value,
}),
}
: null,
};
} catch { } catch {
serveSuggestions.value = null; serveSuggestions.value = null;
} }

View file

@ -117,7 +117,7 @@ See [Plan a meal](/docs/how-to/plan-a-meal/) for an end-to-end practical guide.
|---|---| |---|---|
| CLI | `gram plan recipe.gram --serve "2026-10-11 13:00" --available 08:00-22:00` (optional `--tz` if set in config); `--find` to look for a serving time | | CLI | `gram plan recipe.gram --serve "2026-10-11 13:00" --available 08:00-22:00` (optional `--tz` if set in config); `--find` to look for a serving time |
| Playground | The "Work plan" view and the "Plan" panel, with "When to serve?" | | Playground | The "Work plan" view and the "Plan" panel, with "When to serve?" |
| VS Code | `Gram: Work Plan`, in days before the service | | VS Code | `Gram: Work Plan`, in days before the service, or on the calendar with the **Served at** field and its "When to serve?" suggestions |
| `@gram-lang/scheduler` | `project()`, `runSheet()`, `findServeTimes()` and `earliestServe()` (see the [scheduler API reference](/docs/reference/api/scheduler/)) | | `@gram-lang/scheduler` | `project()`, `runSheet()`, `findServeTimes()` and `earliestServe()` (see the [scheduler API reference](/docs/reference/api/scheduler/)) |
| `@gram-lang/renderer` | `runSheetToText`, `runSheetToMarkdown`, `runSheetToHTML`, `runSheetToPrintHTML`, and associated modular helpers (`visitKit`, `sectionProgram`, `sectionSteps`) | | `@gram-lang/renderer` | `runSheetToText`, `runSheetToMarkdown`, `runSheetToHTML`, `runSheetToPrintHTML`, and associated modular helpers (`visitKit`, `sectionProgram`, `sectionSteps`) |

View file

@ -57,15 +57,16 @@ Available values and defaults match those of the [VS Code extension](/docs/refer
<Since v="1.4.0" /> Alongside standard LSP capabilities, the server renders recipe views (the recipe and the work plan) and inspectors (the AST and the compiled JSON) for display in editor client panels. It renders only the views currently open in the client, ensuring closed panels incur no computation overhead. <Since v="1.4.0" /> Alongside standard LSP capabilities, the server renders recipe views (the recipe and the work plan) and inspectors (the AST and the compiled JSON) for display in editor client panels. It renders only the views currently open in the client, ensuring closed panels incur no computation overhead.
A client opts into the protocol by providing `initializationOptions: { views: true }` in its `initialize` request, then communicates with the server through three custom notifications: A client opts into the protocol by providing `initializationOptions: { views: true }` in its `initialize` request, then communicates with the server through three custom notifications and one request:
| Notification | Direction | Content | | Notification | Direction | Content |
|---|---|---| |---|---|---|
| `gram/setOpenViews` | Client ➔ Server | `{ uri, viewIds }`: the complete set of active output IDs for this document (`[]` when none are open). The server immediately emits updates for each requested view. | | `gram/setOpenViews` | Client ➔ Server | `{ uri, viewIds }`: the complete set of active output IDs for this document (`[]` when none are open). The server immediately emits updates for each requested view. |
| `gram/setSession` | Client ➔ Server | `{ uri, serveAt?, scale?, stock?, bakersReference? }`: transient session parameters for the current working session. `serveAt` is an ISO-like local date and time (`"2026-10-11 13:00"`), `scale` is `{ type: "factor", value }` or `{ type: "target", id, qty, unit }`, and `stock` lists URIs of pre-prepared imports. Unrecognized properties are ignored; an empty payload clears the session. | | `gram/setSession` | Client ➔ Server | `{ uri, serveAt?, scale?, stock?, bakersReference? }`: transient session parameters for the current working session. `serveAt` is an ISO-like local date and time (`"2026-10-11 13:00"`), `scale` is `{ type: "factor", value }` or `{ type: "target", id, qty, unit }`, and `stock` lists URIs of pre-prepared imports. Unrecognized properties are ignored; an empty payload clears the session. |
| `gram/viewUpdated` | Server ➔ Client | `{ uri, outputId, kind, state, ... }`: emitted for each open output upon initial opening, and refreshed after every edit or configuration change. | | `gram/viewUpdated` | Server ➔ Client | `{ uri, outputId, kind, state, ... }`: emitted for each open output upon initial opening, and refreshed after every edit or configuration change. |
| `gram/serveTimes` (request) | Client ➔ Server | `{ uri }` → `{ candidates, rejected, earliest }` or `null`: the serving times to propose next to a serving time field, as the playground proposes them. `candidates` are the times that work over the next seven days at the project's `mealTimes` (default 12:30 and 20:00), best first, each `{ serveAt, label, title }`; `rejected` says in words why each other time does not; `earliest` is `{ serveAt, label, text }`, the first time the recipe can be ready if you start now. `null` when the recipe has nothing to schedule. Ask it only while the suggestions are shown: it plans a few dozen times. |
The `initialize` response advertises available views via `capabilities.experimental.gramViews`: `outputs` describes each output's `id`, `kind`, and localized `label` (matching the editor's language), while `strings` provides UI translations for surrounding panel controls. Output IDs align with the renderer's exported list: `recipe` and `workPlan` (`kind: "renderer"`), plus `ast`, `json`, and `json-tree` (`kind: "inspector"`). Client implementations consuming this list dynamically support newly added views without requiring client-side updates. The `initialize` response advertises available views via `capabilities.experimental.gramViews`: `outputs` describes each output's `id`, `kind`, and localized `label` (matching the editor's language), plus, for a view, what it `needs` from the plan (a view that needs `runSheet` is laid out in time, so a client offers its serving time controls), while `strings` provides UI translations for surrounding panel controls (`strings.serving` for the serving time field and its suggestions). Output IDs align with the renderer's exported list: `recipe` and `workPlan` (`kind: "renderer"`), plus `ast`, `json`, and `json-tree` (`kind: "inspector"`). Client implementations consuming this list dynamically support newly added views without requiring client-side updates.
- With `state: "ok"`, `payload` contains the rendered HTML for a view, or `null` if the recipe has no corresponding content (such as a work plan for a recipe without schedulable steps). For inspectors, `payload` is `{ presentation, language, text }`: formatted source text for a code pane (`presentation: "code"`, highlighted as `json` or `scheme`), or structured HTML for an interactive tree view (`presentation: "tree"`). - With `state: "ok"`, `payload` contains the rendered HTML for a view, or `null` if the recipe has no corresponding content (such as a work plan for a recipe without schedulable steps). For inspectors, `payload` is `{ presentation, language, text }`: formatted source text for a code pane (`presentation: "code"`, highlighted as `json` or `scheme`), or structured HTML for an interactive tree view (`presentation: "tree"`).
- With `state: "paused"`, compilation errors prevent view updates and `payload` is omitted: editor clients should retain their last valid rendered view and surface the failure via `error` (`title`, `description`, `code`, `message`, and source `range`). The error title is localized using the editor's configured locale (`locale` from `initialize`). Comprehensive error details continue to be reported via standard LSP diagnostics. - With `state: "paused"`, compilation errors prevent view updates and `payload` is omitted: editor clients should retain their last valid rendered view and surface the failure via `error` (`title`, `description`, `code`, `message`, and source `range`). The error title is localized using the editor's configured locale (`locale` from `initialize`). Comprehensive error details continue to be reported via standard LSP diagnostics.

View file

@ -25,7 +25,8 @@ A dedicated `CodeLens` button appears above the recipe title. Clicking it reveal
### 3. Work plan view ### 3. Work plan view
- **Dedicated work plan panel**: Run `Gram: Work Plan` (or click the checklist icon in the editor toolbar) to display the full schedule in a dedicated WebView independent of the live preview. It details daily kitchen presence, items to take out, tasks to perform, and background passive rests. - **Dedicated work plan panel**: Run `Gram: Work Plan` (or click the checklist icon in the editor toolbar) to display the full schedule in a dedicated WebView independent of the live preview. It details daily kitchen presence, items to take out, tasks to perform, and background passive rests.
- **Relative countdown (`D-2`, `D-1`, `Day D`)**: Without a serving time configured in the editor, the schedule is presented as a relative countdown with estimated durations per day (e.g. "about 55 min"). For exact dates, clock times, and scheduling margins, run `gram plan --serve` or open the online playground. - **Relative countdown (`D-2`, `D-1`, `Day D`)**: Without a serving time, the schedule is presented as a relative countdown with estimated durations per day (e.g. "about 55 min").
- **Serving time** <Since v="1.4.0" />: The **Served at** field at the top of the panel puts the plan on the calendar, with dates, clock times and margins, in your project's time zone and within its availability (`timezone` and `availability` in `.gram/config.yaml`). **When to serve?** proposes the times that work over the next seven days at your meal times (`mealTimes`), the earliest one first, and tells why the others do not; click one to use it. **Clear** goes back to the countdown. The serving time is kept per recipe while VS Code is open, and forgotten when you close the file or the window, so a plan is never laid out on a time already past.
- **Setting synchronization**: The view adapts dynamically to the `gram.miseEnPlace`, `gram.rests` and `gram.comments` configuration settings (detailed below). - **Setting synchronization**: The view adapts dynamically to the `gram.miseEnPlace`, `gram.rests` and `gram.comments` configuration settings (detailed below).
- **Gantt chart replacement**: The legacy `Gram: Gantt Chart` command is deprecated since version 1.4.0 (it redirects to the work plan with a one-time notice) and will be removed in version 2.0.0. - **Gantt chart replacement**: The legacy `Gram: Gantt Chart` command is deprecated since version 1.4.0 (it redirects to the work plan with a one-time notice) and will be removed in version 2.0.0.

View file

@ -117,7 +117,7 @@ Consultez [Planifier un repas](/fr/docs/how-to/plan-a-meal/) pour le guide prati
|---|---| |---|---|
| CLI | `gram plan recette.gram --serve "2026-10-11 13:00" --available 08:00-22:00` (option `--tz` facultative si configurée dans le projet) ; `--find` pour chercher une heure de service | | CLI | `gram plan recette.gram --serve "2026-10-11 13:00" --available 08:00-22:00` (option `--tz` facultative si configurée dans le projet) ; `--find` pour chercher une heure de service |
| Playground | La vue « Planning » et le volet « Planifier », avec « Quand servir ? » | | Playground | La vue « Planning » et le volet « Planifier », avec « Quand servir ? » |
| VS Code | `Gram: Work Plan`, en jours avant le service | | VS Code | `Gram: Work Plan`, en jours avant le service, ou sur le calendrier avec le champ **Service le** et ses suggestions « Quand servir ? » |
| `@gram-lang/scheduler` | `project()`, `runSheet()`, `findServeTimes()` et `earliestServe()` (voir la [référence de l'API scheduler](/fr/docs/reference/api/scheduler/)) | | `@gram-lang/scheduler` | `project()`, `runSheet()`, `findServeTimes()` et `earliestServe()` (voir la [référence de l'API scheduler](/fr/docs/reference/api/scheduler/)) |
| `@gram-lang/renderer` | `runSheetToText`, `runSheetToMarkdown`, `runSheetToHTML`, `runSheetToPrintHTML`, et les utilitaires modulaires associés (`visitKit`, `sectionProgram`, `sectionSteps`) | | `@gram-lang/renderer` | `runSheetToText`, `runSheetToMarkdown`, `runSheetToHTML`, `runSheetToPrintHTML`, et les utilitaires modulaires associés (`visitKit`, `sectionProgram`, `sectionSteps`) |

View file

@ -57,15 +57,16 @@ L'ensemble des options et valeurs par défaut correspond à la configuration de
<Since v="1.4.0" /> En complément des requêtes standardisées du protocole LSP, le serveur génère directement les vues d'une recette (la recette, le planning de préparation) ainsi que ses inspecteurs (l'AST et le JSON compilé) prêts à être affichés par l'éditeur. Le serveur ne calcule que les vues actuellement ouvertes dans le client : un panneau masqué n'induit aucun surcoût de calcul. <Since v="1.4.0" /> En complément des requêtes standardisées du protocole LSP, le serveur génère directement les vues d'une recette (la recette, le planning de préparation) ainsi que ses inspecteurs (l'AST et le JSON compilé) prêts à être affichés par l'éditeur. Le serveur ne calcule que les vues actuellement ouvertes dans le client : un panneau masqué n'induit aucun surcoût de calcul.
Le client active ce protocole en transmettant `initializationOptions: { views: true }` lors de la requête `initialize`, puis dialogue avec le serveur via trois notifications spécifiques : Le client active ce protocole en transmettant `initializationOptions: { views: true }` lors de la requête `initialize`, puis dialogue avec le serveur via trois notifications spécifiques et une requête :
| Notification | Sens | Contenu | | Notification | Sens | Contenu |
|---|---|---| |---|---|---|
| `gram/setOpenViews` | Client ➔ Serveur | `{ uri, viewIds }` : ensemble complet des identifiants de vues ouvertes pour ce document (`[]` si aucun volet n'est ouvert). Le serveur émet immédiatement les contenus correspondants. | | `gram/setOpenViews` | Client ➔ Serveur | `{ uri, viewIds }` : ensemble complet des identifiants de vues ouvertes pour ce document (`[]` si aucun volet n'est ouvert). Le serveur émet immédiatement les contenus correspondants. |
| `gram/setSession` | Client ➔ Serveur | `{ uri, serveAt?, scale?, stock?, bakersReference? }` : paramètres contextuels de la session de travail. `serveAt` est une date et heure locale (`"2026-10-11 13:00"`), `scale` spécifie un facteur `{ type: "factor", value }` ou une cible `{ type: "target", id, qty, unit }`, et `stock` liste les URI des modules déjà prêts en cuisine. Tout paramètre non reconnu est ignoré ; un objet vide réinitialise la session. | | `gram/setSession` | Client ➔ Serveur | `{ uri, serveAt?, scale?, stock?, bakersReference? }` : paramètres contextuels de la session de travail. `serveAt` est une date et heure locale (`"2026-10-11 13:00"`), `scale` spécifie un facteur `{ type: "factor", value }` ou une cible `{ type: "target", id, qty, unit }`, et `stock` liste les URI des modules déjà prêts en cuisine. Tout paramètre non reconnu est ignoré ; un objet vide réinitialise la session. |
| `gram/viewUpdated` | Serveur ➔ Client | `{ uri, outputId, kind, state, ... }` : émis pour chaque sortie ouverte lors de son affichage initial, puis actualisé après chaque modification ou ajustement des réglages. | | `gram/viewUpdated` | Serveur ➔ Client | `{ uri, outputId, kind, state, ... }` : émis pour chaque sortie ouverte lors de son affichage initial, puis actualisé après chaque modification ou ajustement des réglages. |
| `gram/serveTimes` (requête) | Client ➔ Serveur | `{ uri }` → `{ candidates, rejected, earliest }` ou `null` : les heures de service à proposer à côté d'un champ d'heure de service, comme le fait le studio en ligne. `candidates` regroupe les heures qui conviennent sur les sept prochains jours aux heures de repas du projet (`mealTimes`, par défaut 12:30 et 20:00), les meilleures d'abord, chacune sous la forme `{ serveAt, label, title }` ; `rejected` explique en toutes lettres pourquoi les autres ne conviennent pas ; `earliest` vaut `{ serveAt, label, text }`, le moment le plus proche où la recette peut être prête si vous commencez maintenant. `null` si la recette n'a rien à planifier. Ne l'interrogez que lorsque les suggestions sont affichées : elle planifie quelques dizaines d'horaires. |
La réponse à la requête `initialize` énumère l'ensemble des sorties disponibles dans `capabilities.experimental.gramViews` : `outputs` précise l'`id`, le `kind` et le `label` traduit de chaque vue (dans la langue de l'éditeur), tandis que `strings` fournit les libellés de l'interface environnante. Les identifiants correspondent aux sorties déclarées par le moteur de rendu : `recipe` et `workPlan` (`kind: "renderer"`), ainsi que `ast`, `json` et `json-tree` (`kind: "inspector"`). Un client qui construit dynamiquement son menu de vues à partir de cette liste prend ainsi en charge toute nouvelle vue ajoutée au moteur sans nécessiter de mise à jour spécifique. La réponse à la requête `initialize` énumère l'ensemble des sorties disponibles dans `capabilities.experimental.gramViews` : `outputs` précise l'`id`, le `kind` et le `label` traduit de chaque vue (dans la langue de l'éditeur), ainsi que, pour une vue, ce qu'elle lit du planning (`needs` : une vue qui lit `runSheet` est calée dans le temps, et un client lui propose donc le choix de l'heure de service), tandis que `strings` fournit les libellés de l'interface environnante (`strings.serving` pour le champ d'heure de service et ses suggestions). Les identifiants correspondent aux sorties déclarées par le moteur de rendu : `recipe` et `workPlan` (`kind: "renderer"`), ainsi que `ast`, `json` et `json-tree` (`kind: "inspector"`). Un client qui construit dynamiquement son menu de vues à partir de cette liste prend ainsi en charge toute nouvelle vue ajoutée au moteur sans nécessiter de mise à jour spécifique.
- Lorsque `state: "ok"`, `payload` contient le code HTML rendu de la vue, ou `null` si la recette ne comporte aucun contenu correspondant (par exemple un planning de préparation pour une recette dépourvue d'étapes minutées). Pour un inspecteur, `payload` contient `{ presentation, language, text }` : du texte formaté pour un volet de code (`presentation: "code"`, coloré en `json` ou en `scheme`), ou une structure HTML pour une arborescence interactive (`presentation: "tree"`). - Lorsque `state: "ok"`, `payload` contient le code HTML rendu de la vue, ou `null` si la recette ne comporte aucun contenu correspondant (par exemple un planning de préparation pour une recette dépourvue d'étapes minutées). Pour un inspecteur, `payload` contient `{ presentation, language, text }` : du texte formaté pour un volet de code (`presentation: "code"`, coloré en `json` ou en `scheme`), ou une structure HTML pour une arborescence interactive (`presentation: "tree"`).
- Lorsque `state: "paused"`, les erreurs de compilation empêchent la génération des vues et `payload` est omis : l'éditeur doit conserver le dernier état valide affiché et signaler l'erreur via la propriété `error` (`title`, `description`, `code`, `message` et `range`). Le titre de l'erreur est traduit selon la locale de l'éditeur (`locale` d'`initialize`). Les détails complets de l'erreur demeurent accessibles via les diagnostics LSP habituels. - Lorsque `state: "paused"`, les erreurs de compilation empêchent la génération des vues et `payload` est omis : l'éditeur doit conserver le dernier état valide affiché et signaler l'erreur via la propriété `error` (`title`, `description`, `code`, `message` et `range`). Le titre de l'erreur est traduit selon la locale de l'éditeur (`locale` d'`initialize`). Les détails complets de l'erreur demeurent accessibles via les diagnostics LSP habituels.

View file

@ -25,7 +25,8 @@ Un bouton `CodeLens` apparaît juste au-dessus du titre de votre recette. Un cli
### 3. Vue planning de préparation ### 3. Vue planning de préparation
- **Panneau dédié au planning** : Exécutez la commande `Gram: Work Plan` (ou cliquez sur l'icône de liste de tâches dans la barre d'outils de l'éditeur) pour afficher le planning complet dans une WebView dédiée, indépendante de l'aperçu standard. Il détaille pour chaque journée les plages de présence en cuisine, les ingrédients et le matériel à sortir, les tâches à réaliser et les temps de repos passifs. - **Panneau dédié au planning** : Exécutez la commande `Gram: Work Plan` (ou cliquez sur l'icône de liste de tâches dans la barre d'outils de l'éditeur) pour afficher le planning complet dans une WebView dédiée, indépendante de l'aperçu standard. Il détaille pour chaque journée les plages de présence en cuisine, les ingrédients et le matériel à sortir, les tâches à réaliser et les temps de repos passifs.
- **Décompte relatif (`J-2`, `J-1`, `Jour J`)** : En l'absence d'heure de service configurée dans l'éditeur, le planning est projeté sous forme de compte à rebours relatif et affiche des durées estimées par journée (ex. : « environ 55 min »). Pour obtenir des horodatages précis avec dates et marges réelles, utilisez la commande `gram plan --serve` ou le studio interactif en ligne. - **Décompte relatif (`J-2`, `J-1`, `Jour J`)** : Sans heure de service, le planning prend la forme d'un compte à rebours relatif, avec des durées estimées par journée (ex. : « environ 55 min »).
- **Heure de service** <Since v="1.4.0" /> : Le champ **Service le**, en haut du panneau, cale le planning sur le calendrier, avec les dates, les horaires et les marges, dans le fuseau horaire du projet et selon ses disponibilités (`timezone` et `availability` dans `.gram/config.yaml`). **Quand servir ?** propose les heures qui conviennent sur les sept prochains jours aux heures de repas du projet (`mealTimes`), la plus proche en tête, et explique pourquoi les autres ne conviennent pas : un clic suffit pour en choisir une. **Effacer** ramène au compte à rebours. L'heure choisie est conservée pour chaque recette tant que VS Code reste ouvert, puis oubliée à la fermeture du fichier ou de la fenêtre : le planning n'est ainsi jamais calé sur une heure déjà passée.
- **Prise en compte des réglages de projet** : La vue s'adapte instantanément aux paramètres d'ordonnancement `gram.miseEnPlace`, `gram.rests` et `gram.comments` (détaillés ci-dessous). - **Prise en compte des réglages de projet** : La vue s'adapte instantanément aux paramètres d'ordonnancement `gram.miseEnPlace`, `gram.rests` et `gram.comments` (détaillés ci-dessous).
- **Remplacement du diagramme de Gantt** : La commande historique `Gram: Gantt Chart` est dépréciée depuis la version 1.4.0 (elle ouvre désormais le planning de préparation avec un avertissement informatif) et sera définitivement retirée en version 2.0.0. - **Remplacement du diagramme de Gantt** : La commande historique `Gram: Gantt Chart` est dépréciée depuis la version 1.4.0 (elle ouvre désormais le planning de préparation avec un avertissement informatif) et sera définitivement retirée en version 2.0.0.

View file

@ -14,6 +14,16 @@ export const en = {
showError: "Show the error", showError: "Show the error",
/** An output the recipe has nothing for (a work plan with nothing to schedule). */ /** An output the recipe has nothing for (a work plan with nothing to schedule). */
outputEmpty: "Nothing to show for this recipe.", outputEmpty: "Nothing to show for this recipe.",
/** The serving time controls of a view laid out in time (the editor's panel). */
serving: {
label: "Served at",
clear: "Clear",
clearTitle: "Back to the plan in days before the service",
suggest: "When to serve?",
none: "No serving time works in the next seven days.",
whyNot: "Why not the others?",
earliest: "Earliest: {when}",
},
/** The name of each output of the renderer (`outputs`), by its id. */ /** The name of each output of the renderer (`outputs`), by its id. */
outputs: { outputs: {
recipe: "Recipe", recipe: "Recipe",

View file

@ -14,6 +14,15 @@ export const fr: GramLocale = {
viewsPausedDescription: VIEWS_PAUSED.description, viewsPausedDescription: VIEWS_PAUSED.description,
showError: "Voir l'erreur", showError: "Voir l'erreur",
outputEmpty: "Rien à afficher pour cette recette.", outputEmpty: "Rien à afficher pour cette recette.",
serving: {
label: "Service le",
clear: "Effacer",
clearTitle: "Revenir au planning en jours avant le service",
suggest: "Quand servir ?",
none: "Aucune heure de service ne convient dans les sept prochains jours.",
whyNot: "Pourquoi pas les autres ?",
earliest: "Au plus tôt : {when}",
},
outputs: { outputs: {
recipe: "Recette", recipe: "Recette",
workPlan: "Planning de préparation", workPlan: "Planning de préparation",

View file

@ -19,6 +19,7 @@ import { findProjectRootSync } from "./utils/project-root";
import { import {
readPathsConfigSync, readPathsConfigSync,
readAvailabilityConfigSync, readAvailabilityConfigSync,
readMealTimesConfigSync,
readTimeZoneConfigSync, readTimeZoneConfigSync,
} from "./utils/module-paths-config"; } from "./utils/module-paths-config";
import { affectedOpenImporters } from "./utils/module-invalidation"; import { affectedOpenImporters } from "./utils/module-invalidation";
@ -63,7 +64,7 @@ import {
parseSession, parseSession,
type Session, type Session,
} from "./session"; } from "./session";
import { describeOutputs, renderOutputs } from "./views"; import { describeOutputs, renderOutputs, serveTimesOf } from "./views";
const connection = createConnection(ProposedFeatures.all); const connection = createConnection(ProposedFeatures.all);
const documents = new TextDocuments(TextDocument); const documents = new TextDocuments(TextDocument);
@ -117,6 +118,7 @@ const projectContextCache = new Map<
paths?: Record<string, string>; paths?: Record<string, string>;
timeZone?: string; timeZone?: string;
availability?: Availability; availability?: Availability;
mealTimes?: string[];
} }
>(); >();
@ -131,6 +133,7 @@ function projectContextOf(uri: string) {
paths: readPathsConfigSync(projectRoot), paths: readPathsConfigSync(projectRoot),
timeZone: readTimeZoneConfigSync(projectRoot), timeZone: readTimeZoneConfigSync(projectRoot),
availability: readAvailabilityConfigSync(projectRoot), availability: readAvailabilityConfigSync(projectRoot),
mealTimes: readMealTimesConfigSync(projectRoot),
}; };
projectContextCache.set(dir, ctx); projectContextCache.set(dir, ctx);
} }
@ -460,6 +463,34 @@ connection.onNotification("gram/setSession", (params: unknown) => {
} }
}); });
/** The `mealTimes` of the project of `uri`, when it sets them. */
function mealTimesOf(uri: string): string[] | undefined {
if (!uri.startsWith("file:")) return undefined;
try {
return projectContextOf(uri).mealTimes;
} catch {
return undefined;
}
}
connection.onRequest("gram/serveTimes", (params: unknown) => {
const uri = (params as { uri?: unknown } | null)?.uri;
if (typeof uri !== "string") return null;
const state = viewStates.get(uri) ?? states.get(uri);
if (!state) return null;
try {
return serveTimesOf(state, {
settings,
kitchen: kitchenOf(uri),
locale,
mealTimes: mealTimesOf(uri),
});
} catch (e) {
connection.console.error(`serve times error: ${e}`);
return null;
}
});
/** /**
* Sends the views of an already compiled document: the outputs the client has * Sends the views of an already compiled document: the outputs the client has
* open, or, to an older client, the preview and the work plan. Pure output of * open, or, to an older client, the preview and the work plan. Pure output of

View file

@ -89,3 +89,34 @@ export function readAvailabilityConfigSync(
return undefined; return undefined;
} }
} }
const MEAL_TIME = /^([01]?\d|2[0-3]):[0-5]\d$/;
/**
* Reads the `mealTimes:` of `<projectRoot>/.gram/config.yaml`, the times of
* day a serving time is looked for at (the CLI's default of `gram plan
* --meal-times`). Never throws: a missing setting, or one that is not a list
* of "HH:MM", is `undefined`, and the scheduler's own times are used.
*/
export function readMealTimesConfigSync(
projectRoot: string,
): string[] | undefined {
const configPath = join(projectRoot, ".gram", "config.yaml");
if (!existsSync(configPath)) return undefined;
try {
const parsed = parse(readFileSync(configPath, "utf-8")) as
| { mealTimes?: unknown }
| undefined;
const value = parsed?.mealTimes;
if (
!Array.isArray(value) ||
value.length === 0 ||
!value.every((v) => typeof v === "string" && MEAL_TIME.test(v))
) {
return undefined;
}
return value as string[];
} catch {
return undefined;
}
}

View file

@ -4,12 +4,14 @@ import {
type InspectorDefinition, type InspectorDefinition,
type KitchenContext, type KitchenContext,
type OutputDefinition, type OutputDefinition,
type ServeSuggestions,
type StageArtifacts, type StageArtifacts,
type ViewInput, type ViewInput,
type ViewSettings, type ViewSettings,
describeError, describeError,
outputs, outputs,
prepareViews, prepareViews,
suggestServeTimes,
} from "@gram-lang/renderer"; } from "@gram-lang/renderer";
import { getDictionary } from "@gram-lang/i18n"; import { getDictionary } from "@gram-lang/i18n";
import type { DocumentState } from "./document-state"; import type { DocumentState } from "./document-state";
@ -25,8 +27,28 @@ export interface ViewsCapability {
kind: OutputDefinition["kind"]; kind: OutputDefinition["kind"];
label: string; label: string;
presentation?: InspectorDefinition["presentation"]; presentation?: InspectorDefinition["presentation"];
/**
* What a view reads from the plan (`schedule`, `runSheet`, ...): a view
* that reads the run sheet is laid out in time, so a client offers its
* serving time controls.
*/
needs?: readonly string[];
}[]; }[];
strings: { showError: string; outputEmpty: string }; strings: {
showError: string;
outputEmpty: string;
/** The serving time controls of a view laid out in time. */
serving: Record<
| "label"
| "clear"
| "clearTitle"
| "suggest"
| "none"
| "whyNot"
| "earliest",
string
>;
};
} }
export function describeOutputs(locale?: string): ViewsCapability { export function describeOutputs(locale?: string): ViewsCapability {
@ -36,11 +58,15 @@ export function describeOutputs(locale?: string): ViewsCapability {
id: output.id, id: output.id,
kind: output.kind, kind: output.kind,
label: t.outputs[output.id] ?? output.id, label: t.outputs[output.id] ?? output.id,
...(output.kind === "inspector" && { ...(output.kind === "inspector"
presentation: output.presentation, ? { presentation: output.presentation }
}), : { needs: output.needs }),
})), })),
strings: { showError: t.showError, outputEmpty: t.outputEmpty }, strings: {
showError: t.showError,
outputEmpty: t.outputEmpty,
serving: { ...t.serving },
},
}; };
} }
@ -218,3 +244,36 @@ export function renderOutputs(
} }
return updates; return updates;
} }
export interface ServeTimesOptions {
settings: ViewSettings;
kitchen: KitchenContext;
/** The language of the editor: the suggestions are words of its panel. */
locale?: string;
/** The times of day to try, from the project's `mealTimes`. */
mealTimes?: string[];
}
/**
* `gram/serveTimes`: the serving times to propose next to the serving time
* field of a view laid out in time, as the playground proposes them. Asked by
* the client only while its suggestions are shown: it plans a few dozen times.
* `null` without a compilation or without anything to schedule.
*/
export function serveTimesOf(
state: DocumentState,
options: ServeTimesOptions,
): ServeSuggestions | null {
const compilation = state.compilation;
if (!compilation) return null;
const lang = compilation.meta?.language;
const input = prepareViews(compilation, options.settings, {
...(typeof lang === "string" && { lang }),
kitchen: options.kitchen,
});
const words = options.locale ?? (typeof lang === "string" ? lang : undefined);
return suggestServeTimes(input, {
...(words !== undefined && { lang: words }),
...(options.mealTimes && { mealTimes: options.mealTimes }),
});
}

View file

@ -5,6 +5,7 @@ import { join } from "node:path";
import { import {
readPathsConfigSync, readPathsConfigSync,
readAvailabilityConfigSync, readAvailabilityConfigSync,
readMealTimesConfigSync,
readTimeZoneConfigSync, readTimeZoneConfigSync,
} from "../src/utils/module-paths-config"; } from "../src/utils/module-paths-config";
@ -137,3 +138,38 @@ describe("readAvailabilityConfigSync", () => {
).toBeUndefined(); ).toBeUndefined();
}); });
}); });
describe("readMealTimesConfigSync", () => {
const dirs: string[] = [];
afterEach(async () => {
while (dirs.length > 0)
await rm(dirs.pop()!, { recursive: true, force: true });
});
async function project(configYaml?: string): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), "gram-mealcfg-"));
dirs.push(dir);
if (configYaml !== undefined) {
await mkdir(join(dir, ".gram"));
await writeFile(join(dir, ".gram", "config.yaml"), configYaml, "utf-8");
}
return dir;
}
it("reads the meal times of the project", async () => {
expect(
readMealTimesConfigSync(await project('mealTimes: ["12:00", "19:30"]\n')),
).toEqual(["12:00", "19:30"]);
});
it("is undefined without them, or with a time it cannot read", async () => {
expect(readMealTimesConfigSync(await project())).toBeUndefined();
expect(
readMealTimesConfigSync(await project('mealTimes: ["noon"]\n')),
).toBeUndefined();
expect(
readMealTimesConfigSync(await project("mealTimes: 12:00\n")),
).toBeUndefined();
});
});

View file

@ -81,6 +81,52 @@ describe("the views protocol", () => {
expect(listed.find((o) => o.id === "workPlan")?.label).toBe("Work plan"); expect(listed.find((o) => o.id === "workPlan")?.label).toBe("Work plan");
}, 20_000); }, 20_000);
it("says what each view reads, and the words of the serving time controls", async () => {
client = new Client();
const result = (await client.start({ views: true })) as {
capabilities: {
experimental?: {
gramViews?: {
outputs: { id: string; needs?: string[] }[];
strings: { serving?: Record<string, string> };
};
};
};
};
const views = result.capabilities.experimental?.gramViews;
for (const output of outputs) {
const listed = views?.outputs.find((o) => o.id === output.id);
if (output.kind === "renderer") {
expect(listed?.needs).toEqual([...output.needs]);
} else {
expect(listed?.needs).toBeUndefined();
}
}
expect(views?.strings.serving?.label).toBe("Served at");
}, 20_000);
it("proposes serving times for a document on gram/serveTimes", async () => {
client = new Client();
await client.start({ views: true });
client.open(TART("Tart"));
client.notify("gram/setOpenViews", { uri: URI, viewIds: ["workPlan"] });
await waitFor(client, (u) => u.outputId === "workPlan");
const suggestions = (await client.request("gram/serveTimes", {
uri: URI,
})) as {
candidates: { serveAt: string; label: string; title: string }[];
earliest: { serveAt: string; text: string } | null;
} | null;
expect(suggestions?.candidates.length).toBeGreaterThan(0);
expect(suggestions?.candidates[0]?.serveAt).toMatch(
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,
);
expect(suggestions?.earliest?.text).toBeString();
expect(
await client.request("gram/serveTimes", { uri: "file:///nowhere.gram" }),
).toBeNull();
}, 20_000);
it("sends nothing to a views client until it says what is open", async () => { it("sends nothing to a views client until it says what is open", async () => {
client = new Client(); client = new Client();
await client.start({ views: true }); await client.start({ views: true });

View file

@ -98,6 +98,10 @@ export { runSheetToPrintHTML } from "./views/work-plan/print";
export { export {
describeEarliestServe, describeEarliestServe,
describeServeTimes, describeServeTimes,
type ServeSuggestion,
type ServeSuggestions,
type SuggestServeOptions,
suggestServeTimes,
} from "./views/work-plan/serve-times"; } from "./views/work-plan/serve-times";
export type { export type {
RunSheetDayModel, RunSheetDayModel,

View file

@ -4,7 +4,10 @@ import {
type EarliestServe, type EarliestServe,
type ServeCandidate, type ServeCandidate,
type ServeSearch, type ServeSearch,
parseInstant,
toLocalIso,
} from "@gram-lang/scheduler"; } from "@gram-lang/scheduler";
import type { ViewInput } from "../../prepare-views";
import { describeProblems } from "./model"; import { describeProblems } from "./model";
import type { RunSheetRenderOptions } from "./model"; import type { RunSheetRenderOptions } from "./model";
import type { RenderableCompilationResult } from "../../types"; import type { RenderableCompilationResult } from "../../types";
@ -118,3 +121,102 @@ export function describeEarliestServe(
until: whenOf(result.searchedUntil, options.lang), until: whenOf(result.searchedUntil, options.lang),
}); });
} }
/** A serving time to propose: when, its short label, and why it works. */
export interface ServeSuggestion {
/** A local date-time, "2026-10-11T13:00", in the kitchen's time zone. */
serveAt: string;
/** "Sat 17 Oct, 20:00". */
label: string;
/** The sentence of `describeServeTimes` for it. */
title: string;
}
/** What a surface proposes next to its serving time field. */
export interface ServeSuggestions {
/** The serving times that work, best first. */
candidates: ServeSuggestion[];
/** Why each of the others does not, in words. */
rejected: string[];
/** The first time it can be ready if the cook starts now, or `null`. */
earliest: { serveAt: string; label: string; text: string } | null;
}
export interface SuggestServeOptions {
lang?: string;
/** How many days ahead to try, from today. Default 7. */
days?: number;
/** How many working times to propose. Default 6. */
limit?: number;
/** The times of day to try. Default the scheduler's (12:30, 20:00). */
mealTimes?: string[];
}
/** "Sat 17 Oct, 20:00", in the reader's language. */
function shortLabel(serveAt: string, lang?: string): string {
return new Intl.DateTimeFormat(lang || "en", {
timeZone: "UTC",
weekday: "short",
day: "numeric",
month: "short",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
}).format(new Date(`${serveAt}:00Z`));
}
function addDays(date: string, days: number): string {
const [y, m, d] = date.split("-").map(Number) as [number, number, number];
return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
}
/**
* The serving times to propose for a prepared recipe, in words: those that
* work over the next days at the meal times, best first, why the others do
* not, and the earliest from now. The same for every surface that suggests a
* serving time (the playground, the editor's work plan). `null` without a
* kitchen or without anything to schedule.
*/
export function suggestServeTimes(
input: ViewInput,
options: SuggestServeOptions = {},
): ServeSuggestions | null {
const kitchen = input.kitchen;
const tasks = (input.recipe.tasks as { tasks?: unknown[] } | undefined)
?.tasks;
if (!kitchen || !input.projection || !tasks?.length) return null;
const { timeZone } = kitchen;
const now = kitchen.now ?? new Date().toISOString();
const today = toLocalIso(parseInstant(now, timeZone), timeZone).slice(0, 10);
const range = { from: today, to: addDays(today, options.days ?? 7) };
const search = input.findServeTimes({
...range,
limit: options.limit ?? 6,
...(options.mealTimes && { mealTimes: options.mealTimes }),
});
const earliest = input.earliestServe();
if (!search || !earliest) return null;
const lang = options.lang ?? input.lang;
const words = describeServeTimes(search, input.recipe, {
...range,
timeZone,
...(lang !== undefined && { lang }),
});
return {
candidates: search.candidates.map((c, i) => ({
serveAt: c.serveAt,
label: shortLabel(c.serveAt, lang),
title: words[i] ?? "",
})),
rejected: words.slice(search.candidates.length),
earliest: earliest.found
? {
serveAt: earliest.found.serveAt,
label: shortLabel(earliest.found.serveAt, lang),
text: describeEarliestServe(earliest, {
...(lang !== undefined && { lang }),
}),
}
: null,
};
}

Some files were not shown because too many files have changed in this diff Show more