diff --git a/cook-plan/appliance-peek.js b/cook-plan/appliance-peek.js
new file mode 100644
index 0000000..b59c856
--- /dev/null
+++ b/cook-plan/appliance-peek.js
@@ -0,0 +1,113 @@
+// =============================================
+// Cook Planner — appliance-peek.js
+//
+// Hover an appliance's name anywhere on the timeline and it says what is in
+// it at that moment. The timeline tells you what to do next; this answers the
+// other question a cook asks at the oven door — what is already in there.
+//
+// Built on the popover API, so the browser handles the top layer, Escape and
+// light dismiss, and on CSS anchor positioning, so the box finds its own way
+// to the right place (with a small manual fallback for older browsers).
+// =============================================
+
+import { escHtml, formatTime } from './utils.js';
+import { applianceConfig, applianceWindows } from './appliances.js';
+import { applianceLabel } from './events.js';
+
+const HOVERS = window.matchMedia?.('(hover: hover) and (pointer: fine)').matches ?? false;
+const ANCHORED = CSS.supports?.('anchor-name', '--a') ?? false;
+
+let scheduled = [];
+let anchoredEl = null;
+
+// The combi is one box with two jobs, so peeking at either shows both.
+const sameBox = (a, b) =>
+ a === b || (a.startsWith('combi') && b.startsWith('combi'));
+
+function capacityNote(key, wins) {
+ const cfg = applianceConfig();
+ const slots = wins.reduce((n, w) => n + (w.item.shelfSlots || 1), 0);
+ if (key === 'main') return `${slots} of ${cfg.mainOvenShelves * 2} slots`;
+ if (key.startsWith('combi')) {
+ return wins.some(w => w.mode === 'MW')
+ ? 'Microwaving — nothing else can go in'
+ : `${slots} of 2 slots`;
+ }
+ return slots > 1 ? `${slots} pans` : '';
+}
+
+function peekHtml(key, at) {
+ const label = applianceLabel(key, null);
+ const wins = applianceWindows(scheduled)
+ .filter(w => sameBox(w.key, key) && w.start <= at && w.end > at)
+ .sort((a, b) => a.start - b.start);
+
+ const rows = wins.map(w => {
+ // A dish whose stretch here ends at its move time is not coming out, it is
+ // going next door -- "out" would have the cook reaching for a plate.
+ const movesOn = !w.moved && w.item._moveTo && w.end === w.item._moveTo.at;
+ const where = [
+ w.shelf && w.key === 'main' ? `Shelf ${w.shelf}` : null,
+ w.mode === 'MW' ? 'microwaving' : null,
+ w.moved ? 'moved in' : null,
+ movesOn ? `→ Main Oven ${formatTime(w.end)}` : `out ${formatTime(w.end)}`,
+ ].filter(Boolean).join(' · ');
+ return `
` : ''}
+ `;
+}
+
+// Without anchor positioning a popover would sit dead centre, which for a
+// tooltip is worse than useless -- so place it by hand in that case only.
+function placeManually(peek, el) {
+ const r = el.getBoundingClientRect();
+ peek.style.position = 'fixed';
+ peek.style.inset = 'auto';
+ peek.style.margin = '0';
+ peek.style.left = `${Math.max(8, Math.min(r.left, window.innerWidth - 360))}px`;
+ peek.style.top = `${r.bottom + 6}px`;
+}
+
+function fill(peek, el) {
+ if (anchoredEl && anchoredEl !== el) anchoredEl.style.anchorName = '';
+ anchoredEl = el;
+ if (ANCHORED) el.style.anchorName = '--appl-peek';
+ peek.innerHTML = peekHtml(el.dataset.appliance, Number(el.dataset.at));
+ if (!ANCHORED) placeManually(peek, el);
+}
+
+// showPopover/hidePopover throw if the popover is already in that state.
+const open = (peek) => { if (!peek.matches(':popover-open')) peek.showPopover(); };
+const close = (peek) => { if (peek.matches(':popover-open')) peek.hidePopover(); };
+
+// Called after every render of the schedule: the triggers are new elements
+// each time, while the popover itself lives in index.html.
+export function initAppliancePeek(items) {
+ scheduled = items;
+ const peek = document.getElementById('appliance-peek');
+ if (!peek) return;
+
+ for (const el of document.querySelectorAll('.appl-peek')) {
+ // Before the click that popovertarget turns into a toggle, so the box is
+ // already filled in by the time it opens. Covers taps and keyboard too.
+ el.addEventListener('pointerdown', () => fill(peek, el));
+ el.addEventListener('focus', () => fill(peek, el));
+
+ if (!HOVERS) continue;
+ el.addEventListener('pointerenter', (e) => {
+ if (e.pointerType !== 'mouse') return;
+ fill(peek, el);
+ open(peek);
+ });
+ el.addEventListener('pointerleave', () => close(peek));
+ }
+}
diff --git a/cook-plan/appliance-settings.js b/cook-plan/appliance-settings.js
index 5fdce3f..e84c358 100644
--- a/cook-plan/appliance-settings.js
+++ b/cook-plan/appliance-settings.js
@@ -45,6 +45,26 @@ export function renderApplianceSettings() {
).join('')}
+
+
+
+
+ min
+
+
Each oven gets a "turn it on" step this long before
+ the first dish goes in
+
+
+
+
+
+ min
+
+
How long a dish may finish early and sit covered, when
+ that is what frees an appliance for something else
+
@@ -58,10 +78,25 @@ export function renderApplianceSettings() {
if (!bound) {
el.addEventListener('click', handleClick);
+ el.addEventListener('input', handleInput);
bound = true;
}
}
+// Typed settings save as they are typed; an empty box is nothing rather than
+// zero, so it waits rather than wiping the value out from under the cursor.
+// The schedule itself is repainted when the dialog closes, as for every other
+// setting here.
+const TIME_SETTINGS = { 'set-preheat': 'preheatMins', 'set-hold': 'holdMins' };
+
+function handleInput(e) {
+ const key = TIME_SETTINGS[e.target.id];
+ if (!key || e.target.value === '') return;
+ const mins = Math.min(120, Math.max(0, parseInt(e.target.value, 10) || 0));
+ state.appliances = { ...applianceConfig(), [key]: mins };
+ savePlan();
+}
+
function handleClick(e) {
const btn = e.target.closest('button[data-val]');
const group = btn?.closest('[data-setting]');
diff --git a/cook-plan/appliances.js b/cook-plan/appliances.js
index 7587523..c93a760 100644
--- a/cook-plan/appliances.js
+++ b/cook-plan/appliances.js
@@ -4,6 +4,7 @@
import { state } from './state.js';
import { COOK_TYPE_MAP, COMBI_COOLDOWN } from './constants.js';
+import { lookupFood, pairScore, sharesTray } from './foods.js';
export function applianceConfig() {
const a = state.appliances || {};
@@ -11,9 +12,28 @@ export function applianceConfig() {
mainOvenShelves: a.mainOvenShelves ?? 2, // 1 -> 2 slots, 2 -> 4 slots
hasCombi: a.hasCombi !== false, // default true
hobCount: a.hobCount ?? 5,
+ // How long an oven takes to come up to temperature. Not a property of any
+ // dish -- it is the kitchen's, and it is why the first instruction of a
+ // roast is "turn the oven on" rather than "put the chicken in".
+ preheatMins: a.preheatMins ?? 6,
+ // How long a dish may be finished early and left covered, when that is
+ // what frees an appliance. Also the kitchen's, not the dish's: it is
+ // really a statement about how tolerant this cook is of food standing.
+ holdMins: a.holdMins ?? 15,
};
}
+// A hand-picked shelf, as a number, or null for "let the planner decide".
+// Out-of-range values (a 2-shelf plan opened with the oven set to 1 shelf)
+// fall back to automatic rather than pinning to a shelf that isn't there.
+export function shelfPrefOf(item, numShelves) {
+ const raw = item?.shelfPref;
+ if (raw === undefined || raw === null || raw === '' || raw === 'auto') return null;
+ const n = parseInt(raw, 10);
+ if (!Number.isFinite(n) || n < 1 || n > numShelves) return null;
+ return n;
+}
+
export function assignAppliances(items) {
// Sort by cookStart for deterministic assignment
const sorted = [...items].sort((a, b) => a._s.cookStart - b._s.cookStart);
@@ -44,14 +64,57 @@ export function assignAppliances(items) {
return max;
}
- // First shelf number that can fit `needed` more slots, or null.
- function firstFreeShelf(usage, start, end, excludeId, needed, numShelves, slotsPerShelf) {
+ // Which shelf to use for a dish that needs `needed` slots.
+ //
+ // Any shelf with room will do as far as capacity goes, so the deciding factor
+ // is what is already on it: a half-shelf of parsnips next to a half-shelf of
+ // potatoes is one tray and one lot of basting, while parsnips next to a
+ // crumble is two. Shelves are scored by their worst neighbour — one bad
+ // pairing is enough to spoil the tray — and an empty shelf scores a neutral
+ // 0, so a good pairing beats an empty shelf and a bad one loses to it.
+ //
+ // Returns {shelf, score} or null when the dish doesn't fit anywhere.
+ function bestShelf(usage, start, end, excludeId, needed, numShelves, slotsPerShelf, food) {
+ let best = null;
for (let shelf = 1; shelf <= numShelves; shelf++) {
- if (slotsOnShelf(usage, shelf, start, end, excludeId) + needed <= slotsPerShelf) {
- return shelf;
- }
+ if (slotsOnShelf(usage, shelf, start, end, excludeId) + needed > slotsPerShelf) continue;
+ const mates = usage.filter(u =>
+ u.itemId !== excludeId && u.shelf === shelf && u.start < end && u.end > start
+ );
+ const score = mates.length === 0
+ ? 0
+ : Math.min(...mates.map(u => pairScore(food, u.food)));
+ if (best === null || score > best.score) best = { shelf, score };
}
- return null;
+ return best;
+ }
+
+ // Microwave reservations, with the cooldown pad in front of them. The combi
+ // is either thing on demand -- what it cannot be is both at once, and it
+ // needs a few minutes off the heat before it will microwave. So an oven dish
+ // that runs up to (or over) a microwave slot is what makes the two
+ // incompatible; the device being dual-mode is not the problem.
+ function combiOvenBlocked(start, end, excludeId) {
+ return clashingMicrowave(start, end, excludeId).length > 0;
+ }
+
+ // The shelf with the most room, for when a dish fits nowhere and has to go
+ // somewhere anyway -- a smaller pile-up makes for a clearer conflict.
+ function emptiestShelf(usage, start, end, excludeId, numShelves) {
+ let best = 1, most = -1;
+ for (let shelf = 1; shelf <= numShelves; shelf++) {
+ const free = 2 - slotsOnShelf(usage, shelf, start, end, excludeId);
+ if (free > most) { most = free; best = shelf; }
+ }
+ return best;
+ }
+
+ // Microwave bookings that an oven run over [start, end) cannot live with.
+ function clashingMicrowave(start, end, excludeId) {
+ return combiUsage.filter(u =>
+ u.itemId !== excludeId && u.mode === 'microwave' &&
+ start < u.end && end + COMBI_COOLDOWN > u.start
+ );
}
function combiModeAt(start, end, excludeId) {
@@ -83,11 +146,33 @@ export function assignAppliances(items) {
const cfg = applianceConfig();
- for (const item of sorted) {
+ // Hand-picked appliances and shelves are placed first so the automatic
+ // choices route around them rather than the other way about — an override is
+ // only worth making if the rest of the plan respects it.
+ const isPinned = (item) =>
+ (item.appliancePref && item.appliancePref !== 'auto') ||
+ shelfPrefOf(item, cfg.mainOvenShelves) !== null;
+
+ // A microwave dish has exactly one home. An oven dish has two and can route
+ // around a reservation -- but only around one that is already there, so the
+ // microwave gets its slot first. Taken in clock order instead, a tray of
+ // parsnips parks itself in the combi at quarter past and the red cabbage
+ // finds the only microwave in the kitchen busy being an oven.
+ const needsMicrowave = (item) => COOK_TYPE_MAP[item.cookType]?.resource === 'combi';
+ const order = [
+ ...sorted.filter(isPinned),
+ ...sorted.filter(it => !isPinned(it) && needsMicrowave(it)),
+ ...sorted.filter(it => !isPinned(it) && !needsMicrowave(it)),
+ ];
+
+ for (const item of order) {
const { cookStart, cookEnd } = item._s;
const slots = item.shelfSlots || 1;
const pref = item.appliancePref || 'auto';
const ct = COOK_TYPE_MAP[item.cookType];
+ const food = lookupFood(item.name);
+ item._trayMates = [];
+ item._moveTo = null;
if (!ct) { item._appliance = null; continue; }
if (ct.resource === 'none') {
@@ -127,7 +212,7 @@ export function assignAppliances(items) {
const existingMode = combiModeAt(cookStart, cookEnd, item.id);
const combiFree = (existingMode === null); // microwave needs the combi entirely free
if (cooldownOk && combiFree) {
- combiUsage.push({ start: cookStart, end: cookEnd, mode: 'microwave', shelf: 1, slots: 1, itemId: item.id });
+ combiUsage.push({ start: cookStart, end: cookEnd, mode: 'microwave', shelf: 1, slots: 1, itemId: item.id, food });
item._appliance = 'combi-mw';
item._shelf = 1;
} else {
@@ -138,45 +223,209 @@ export function assignAppliances(items) {
}
if (ct.resource === 'oven') {
- const tryCombi = pref === 'combi' && cfg.hasCombi;
+ const tryCombi = pref === 'combi' || pref === 'auto';
const tryMain = pref === 'main' || pref === 'auto';
+ const pinnedShelf = shelfPrefOf(item, cfg.mainOvenShelves);
- let assigned = false;
-
- if (tryMain) {
- // Main oven: cfg.mainOvenShelves shelves x 2 slots each
- const shelf = firstFreeShelf(mainOvenUsage, cookStart, cookEnd, item.id, slots, cfg.mainOvenShelves, 2);
- if (shelf !== null) {
- mainOvenUsage.push({ start: cookStart, end: cookEnd, shelf, slots, itemId: item.id });
- item._appliance = 'main';
- item._shelf = shelf;
- assigned = true;
- }
- }
+ const takeMain = (shelf, pinned) => {
+ mainOvenUsage.push({ start: cookStart, end: cookEnd, shelf, slots, itemId: item.id, food });
+ item._appliance = 'main';
+ item._shelf = shelf;
+ if (pinned) item._shelfPinned = true;
+ };
+ const takeCombi = () => {
+ combiUsage.push({ start: cookStart, end: cookEnd, mode: 'oven', shelf: 1, slots, itemId: item.id, food });
+ item._appliance = 'combi';
+ item._shelf = 1;
+ };
- if (!assigned && (tryCombi || (pref === 'auto' && cfg.hasCombi))) {
- const existingMode = combiModeAt(cookStart, cookEnd, item.id);
- if (existingMode === null || existingMode === 'oven') {
- // Combi oven: 1 shelf x 2 slots
- const shelf = firstFreeShelf(combiUsage, cookStart, cookEnd, item.id, slots, 1, 2);
- if (shelf !== null) {
- combiUsage.push({ start: cookStart, end: cookEnd, mode: 'oven', shelf: 1, slots, itemId: item.id });
- item._appliance = 'combi';
- item._shelf = 1;
- assigned = true;
- }
- }
+ if (tryMain && pinnedShelf !== null) {
+ // A hand-picked shelf is honoured even when it overfills. Overruling
+ // the planner is the whole point of the override, and the capacity
+ // sweep in conflicts.js will say so if it doesn't fit.
+ takeMain(pinnedShelf, true);
+ continue;
}
- if (!assigned) {
- // Overflow: assign to main oven anyway (conflict will be detected)
- const shelf = firstFreeShelf(mainOvenUsage, cookStart, cookEnd, item.id, slots, cfg.mainOvenShelves, 2) ?? 1;
- mainOvenUsage.push({ start: cookStart, end: cookEnd, shelf, slots, itemId: item.id });
- item._appliance = 'main';
- item._shelf = shelf;
+ const mainOpt = tryMain
+ ? bestShelf(mainOvenUsage, cookStart, cookEnd, item.id, slots, cfg.mainOvenShelves, 2, food)
+ : null;
+
+ // The combi counts as a second oven here, and room in it beats a bad
+ // neighbour in the main one: a crumble that only fits beside the
+ // potatoes is better off on its own in the combi than sharing their
+ // shelf. Ties go to the main oven, which is what "main oven first" means.
+ const combiOpt = (tryCombi && cfg.hasCombi && !combiOvenBlocked(cookStart, cookEnd, item.id))
+ ? bestShelf(combiUsage, cookStart, cookEnd, item.id, slots, 1, 2, food)
+ : null;
+
+ // Last resort, worked out before anything is placed: would the combi take
+ // this dish if the microwave bookings in the way were given up?
+ const displaced = tryCombi && cfg.hasCombi
+ ? clashingMicrowave(cookStart, cookEnd, item.id) : [];
+ const forcedOpt = displaced.length > 0
+ ? bestShelf(combiUsage.filter(u => !displaced.includes(u)),
+ cookStart, cookEnd, item.id, slots, 1, 2, food)
+ : null;
+
+ if (mainOpt && (!combiOpt || mainOpt.score >= combiOpt.score)) {
+ takeMain(mainOpt.shelf, false);
+ } else if (combiOpt) {
+ takeCombi();
+ } else if (forcedOpt) {
+ // Nothing fits politely. Keeping the combi clear for a microwave dish is
+ // a preference, not a rule: a tray with nowhere at all to go takes the
+ // combi anyway. That makes the combi an oven for the window, so the
+ // booking it displaces is dropped rather than left holding a slot it
+ // can no longer use -- otherwise it would push the next tray out too.
+ // conflicts.js reports which microwave dish lost its slot.
+ for (const u of displaced) combiUsage.splice(combiUsage.indexOf(u), 1);
+ takeCombi();
+ } else {
+ // Nowhere fits: into the main oven anyway, and conflicts.js will say so.
+ takeMain(emptiestShelf(mainOvenUsage, cookStart, cookEnd, item.id, cfg.mainOvenShelves), false);
}
}
}
+ // A microwave dish that still has no slot may be rescuable: see if what is
+ // in the combi can move to the main oven partway through and let it in.
+ const byId = new Map(sorted.map(it => [it.id, it]));
+ for (const mw of order) {
+ if (COOK_TYPE_MAP[mw.cookType]?.resource !== 'combi') continue;
+ if (!(mw.cookTime > 0) || !cfg.hasCombi) continue;
+ if (combiUsage.some(u => u.itemId === mw.id && u.mode === 'microwave')) continue;
+ mw._relocation = tryRelocate(mw) ? 'done' : 'impossible';
+ }
+
+ annotateTrayMates(sorted, mainOvenUsage);
+ annotateTrayMates(sorted, combiUsage);
+
return sorted;
+
+ // Freeing the combi by moving what is in it.
+ //
+ // A dish is often in the combi only because the main oven was full when it
+ // went in. Shelves come free as things come out, so it can frequently move
+ // across partway through and carry on cooking in the main oven, which leaves
+ // the combi empty and cooling in time to microwave something. That is a real
+ // job for the cook, so it is only proposed when it genuinely fits: every
+ // dish in the way has to be out before the cooldown starts, and the main
+ // oven has to hold all of them, at once, for the rest of their cooking.
+ function tryRelocate(mw) {
+ const { cookStart: mwStart, cookEnd: mwEnd } = mw._s;
+ const freeBy = mwStart - COMBI_COOLDOWN;
+
+ const blockers = combiUsage.filter(u =>
+ u.mode === 'oven' && u.start < mwEnd && u.end + COMBI_COOLDOWN > mwStart
+ );
+ if (blockers.length === 0) return false;
+ // A combi chosen by hand stays chosen. Undoing an override to make room is
+ // the planner overruling the cook, which is the wrong way round.
+ if (blockers.some(u => byId.get(u.itemId)?.appliancePref === 'combi')) return false;
+
+ // The only moments worth trying are when something changes: a dish going
+ // in, or a main-oven shelf coming free.
+ const candidates = [...new Set([
+ ...blockers.map(b => b.start),
+ ...mainOvenUsage.map(u => u.end),
+ freeBy,
+ ])].filter(t => t <= freeBy).sort((a, b) => a - b);
+
+ for (const at of candidates) {
+ const moves = planMoves(blockers, at);
+ if (moves) { applyMoves(moves, mw); return true; }
+ }
+ return false;
+ }
+
+ // Can the main oven take every dish in the way, from `at` onwards, all at
+ // the same time? Longest remaining cook first: the awkward one to place
+ // should pick its shelf before the easy ones fill them.
+ function planMoves(blockers, at) {
+ const trial = [...mainOvenUsage];
+ const moves = [];
+ const hardestFirst = [...blockers].sort((a, b) =>
+ (b.end - Math.max(b.start, at)) - (a.end - Math.max(a.start, at)));
+
+ for (const b of hardestFirst) {
+ const start = Math.max(b.start, at);
+ if (start >= b.end) continue; // finished before the move: nothing to do
+ let shelf = null;
+ for (let n = 1; n <= cfg.mainOvenShelves; n++) {
+ if (slotsOnShelf(trial, n, start, b.end, b.itemId) + b.slots <= 2) { shelf = n; break; }
+ }
+ if (shelf === null) return null;
+ trial.push({ start, end: b.end, shelf, slots: b.slots, itemId: b.itemId, food: b.food });
+ moves.push({ usage: b, at: start, shelf });
+ }
+ return moves.length > 0 ? moves : null;
+ }
+
+ function applyMoves(moves, mw) {
+ for (const { usage, at, shelf } of moves) {
+ const item = byId.get(usage.itemId);
+ mainOvenUsage.push({ ...usage, start: at, shelf });
+ if (at <= usage.start) {
+ // It never goes near the combi after all: a reassignment, not a move.
+ combiUsage.splice(combiUsage.indexOf(usage), 1);
+ if (item) { item._appliance = 'main'; item._shelf = shelf; }
+ } else {
+ usage.end = at; // the combi half of its cook
+ if (item) item._moveTo = { shelf, at, forItem: mw.name };
+ }
+ }
+ combiUsage.push({
+ start: mw._s.cookStart, end: mw._s.cookEnd, mode: 'microwave',
+ shelf: 1, slots: 1, itemId: mw.id, food: lookupFood(mw.name),
+ });
+ mw._appliance = 'combi-mw';
+ mw._shelf = 1;
+ }
+}
+
+// Every stretch a dish spends in an appliance, keyed by the appliance it is
+// in. A dish that moves between ovens has two; everything else has one. Both
+// the summary cards and the hover peek read the schedule through this, so
+// neither can disagree with the other about what is where.
+export function applianceWindows(items) {
+ const wins = [];
+ for (const i of items) {
+ if (!(i.cookTime > 0)) continue;
+ const app = i._appliance;
+ if (app === 'main') {
+ wins.push({ item: i, key: 'main', shelf: i._shelf, start: i._s.cookStart, end: i._s.cookEnd });
+ } else if (app === 'combi' || app === 'combi-mw') {
+ wins.push({
+ item: i, key: app, mode: app === 'combi' ? 'oven' : 'MW',
+ start: i._s.cookStart, end: i._moveTo ? i._moveTo.at : i._s.cookEnd,
+ });
+ if (i._moveTo) {
+ wins.push({
+ item: i, key: 'main', shelf: i._moveTo.shelf,
+ start: i._moveTo.at, end: i._s.cookEnd, moved: true,
+ });
+ }
+ } else if (app?.startsWith('hob')) {
+ wins.push({ item: i, key: app, start: i._s.cookStart, end: i._s.cookEnd });
+ }
+ }
+ return wins;
+}
+
+// Note, on each dish, which of its shelf-mates it could genuinely go in one
+// tray with. Only pairings the catalogue actually recommends get a mention —
+// two things landing on the same shelf is not by itself advice worth printing.
+function annotateTrayMates(items, usage) {
+ const byId = new Map(items.map(it => [it.id, it]));
+ for (const u of usage) {
+ const item = byId.get(u.itemId);
+ if (!item || u.mode === 'microwave') continue;
+ const mates = usage.filter(o =>
+ o.itemId !== u.itemId && o.shelf === u.shelf && o.start < u.end && o.end > u.start
+ && sharesTray(u.food, o.food)
+ );
+ const names = mates.map(o => byId.get(o.itemId)?.name).filter(Boolean);
+ if (names.length) item._trayMates = [...new Set(names)];
+ }
}
diff --git a/cook-plan/clock.js b/cook-plan/clock.js
index 6222c0b..a9fdc26 100644
--- a/cook-plan/clock.js
+++ b/cook-plan/clock.js
@@ -3,31 +3,52 @@
// =============================================
import { escHtml, formatCountdown, formatTime, nowMins } from './utils.js';
+import { now as clockNow } from './sim-clock.js';
// Module-private state
let clockInterval = null;
let chimesFired = new Set();
+// The events the running clock is ticking against, kept so the simulated clock
+// can resync without the caller having to hand them back.
+let currentEvents = [];
let nextDayOffset = 0; // 1440 if the schedule is for the next calendar day
+// Which timeline stop is the current one, so a change of stage can be brought
+// into view. Null means "not looked yet" rather than "nothing is active".
+let lastStageKey = null;
+// The minute the clock was last resynced to, so that two changes landing on the
+// same minute don't sound its chime twice.
+let lastSyncMinute = null;
// In-memory notification stack — never persisted. When a chime fires we push
// the event so the user can see what triggered the sound when they tab back in.
let notifications = [];
const MAX_NOTIFICATIONS = 20;
-function addNotification(ev) {
- const id = chimeKey(ev);
+// How many of a moment's other events to name before giving up and counting.
+const NOTIFICATION_DETAIL = 3;
+
+// One notification per moment, led by its most significant event. The rest are
+// folded into the sub-line: fifteen separate cards for "serve" would bury
+// everything earlier in the stack under a single instant.
+function addNotification(lead, all) {
+ const id = chimeKey(lead);
if (notifications.some(n => n.id === id)) return;
+
+ const others = all.filter(ev => ev !== lead).map(ev => ev.label);
+ const extra = others.length > NOTIFICATION_DETAIL
+ ? [...others.slice(0, NOTIFICATION_DETAIL), `+${others.length - NOTIFICATION_DETAIL} more`]
+ : others;
+
notifications.unshift({
id,
- label: ev.label,
- sub: ev.sub,
- type: ev.type,
- time: ev.time,
+ label: lead.label,
+ sub: [lead.sub, ...extra].filter(Boolean).join(' \u00b7 ') || null,
+ type: lead.type,
+ time: lead.time,
});
if (notifications.length > MAX_NOTIFICATIONS) {
notifications = notifications.slice(0, MAX_NOTIFICATIONS);
}
- renderNotifications();
}
export function dismissNotification(id) {
@@ -70,8 +91,34 @@ export function setNextDayOffset(val) {
nextDayOffset = val;
}
+// Whether the plan belongs to tomorrow rather than today: if every event is
+// more than an hour in the past, the cook must be the next day's. It lives
+// here rather than in computeSchedule because the simulated clock can change
+// the answer without the schedule itself changing at all -- scrubbing back to
+// lunchtime makes a plan that was "tomorrow's" today's again.
+export function syncDayOffset(events) {
+ const last = events.reduce((m, ev) => Math.max(m, ev.endTime ?? ev.time), 0);
+ nextDayOffset = nowMins() > last + 60 ? 1440 : 0;
+}
+
+// Events without a dish of their own -- heating an oven, serve -- fall back to
+// the appliance, so two ovens warming up on the same minute stay distinct.
function chimeKey(ev) {
- return `${ev.time}:${ev.type}:${ev.itemId || ''}`;
+ return `${ev.time}:${ev.type}:${ev.itemId || ev.applianceKey || ''}`;
+}
+
+// Which event speaks for a moment, most significant first. The end of a cook
+// is a dozen events on one minute -- every dish ready, several out of the oven,
+// and serve -- and they are one moment, not a dozen. Only the leader is
+// sounded, so SERVE wins over the things that merely finished with it.
+const CHIME_PRIORITY = ['serve', 'move', 'cook_end', 'serve_prep', 'cook_start', 'preheat', 'prep', 'set', 'ready'];
+
+function leadEvent(evs) {
+ for (const type of CHIME_PRIORITY) {
+ const match = evs.find(ev => ev.type === type);
+ if (match) return match;
+ }
+ return evs[0];
}
// Pre-seed so past events (and events right now on first load) don't trigger
@@ -90,6 +137,9 @@ function playChime(type) {
cook_start: 523.25, // C5 -- things going in
cook_end: 783.99, // G5 -- higher/urgent: things coming out
set: 440.00, // A4 -- soft
+ move: 880.00, // A5 -- urgent: an oven door has to open now
+ preheat: 349.23, // F4 -- low: go and press a button
+ serve_prep: 659.25, // E5 -- hands needed, but nothing is burning
serve: 987.77, // B5 -- bright fanfare note
};
const freq = freqMap[type] ?? 523.25;
@@ -140,7 +190,11 @@ function playChime(type) {
}
export function startClock(events) {
+ currentEvents = events;
+ syncDayOffset(events);
initChimes(events);
+ lastStageKey = null;
+ lastSyncMinute = null;
updateClock(events);
clockInterval = setInterval(() => updateClock(events), 1000);
}
@@ -149,26 +203,52 @@ export function stopClock() {
if (clockInterval) { clearInterval(clockInterval); clockInterval = null; }
}
+// The simulated clock has moved. Everything before the new now counts as done
+// -- otherwise scrubbing back and forth would replay every chime on the way --
+// but *strictly* before, so that landing on a moment still sounds it. Stepping
+// a minute at a time through a cook to hear what it does is the whole point.
+//
+// Landing on the same minute twice does not, though: one gesture can set the
+// time and then pause it, and two bells for one landing is the complaint this
+// app has already had once.
+export function resyncClock() {
+ syncDayOffset(currentEvents);
+ const nowM = nowMins() - nextDayOffset;
+ const cutoff = nowM === lastSyncMinute ? nowM + 1 : nowM;
+ lastSyncMinute = nowM;
+ chimesFired = new Set(currentEvents.filter(ev => ev.time < cutoff).map(chimeKey));
+ lastStageKey = null;
+ if (document.getElementById('clock-time')) updateClock(currentEvents);
+}
+
function updateClock(events) {
const clockTimeEl = document.getElementById('clock-time');
const clockDateEl = document.getElementById('clock-date');
const clockNextEl = document.getElementById('clock-next');
if (!clockTimeEl) { stopClock(); return; }
- const now = new Date();
+ const now = clockNow();
const nowS = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
const nowM = Math.floor(nowS / 60) - nextDayOffset; // adjusted for next-day schedules
- // Fire chimes for events whose time has just been reached
+ // Fire a chime for events whose time has just been reached. Every one of them
+ // is marked as fired, but they share a single bell: a bell per event meant a
+ // dozen overlapping two-second tones at the end of a cook, each in its own
+ // AudioContext and so each starting a few milliseconds apart -- which came
+ // out as a ragged run of bongs rather than one chime.
+ const due = [];
for (const ev of events) {
- if (ev.time === nowM) {
- const key = chimeKey(ev);
- if (!chimesFired.has(key)) {
- chimesFired.add(key);
- playChime(ev.type);
- addNotification(ev);
- }
- }
+ if (ev.time !== nowM) continue;
+ const key = chimeKey(ev);
+ if (chimesFired.has(key)) continue;
+ chimesFired.add(key);
+ due.push(ev);
+ }
+ if (due.length > 0) {
+ const lead = leadEvent(due);
+ playChime(lead.type);
+ addNotification(lead, due);
+ renderNotifications();
}
clockTimeEl.textContent = now.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
@@ -193,7 +273,7 @@ function updateClock(events) {
// Update past/active classes on grouped timeline rows
// Each row may contain .tl-tracker elements that map back to original events
- const tlRows = document.querySelectorAll('.tl-event');
+ const tlRows = [...document.querySelectorAll('.tl-event')];
tlRows.forEach(row => {
const trackers = row.querySelectorAll('.tl-tracker');
const rowEvents = [...trackers].map(el =>
@@ -206,5 +286,79 @@ function updateClock(events) {
row.classList.toggle('tl-active', isActive && !isPast);
});
+ markCurrentStage(tlRows, nowM);
+ tickElapsed(nowM);
+
// Update appliance slots (re-render just slot bars would need full re-render; skip for perf)
}
+
+// How long each step that is currently under way has been under way: the
+// chicken went in at 14:05, and at twenty to three the thing worth knowing is
+// that it has been in for 35 minutes. Shown only between the step's start and
+// its end -- before, there is nothing to count; after, the row is past and the
+// step's full length is already printed beside it.
+function tickElapsed(nowM) {
+ for (const el of document.querySelectorAll('.tl-elapsed')) {
+ const start = Number(el.dataset.start);
+ const end = Number(el.dataset.end);
+ if (!Number.isFinite(start) || !Number.isFinite(end)) continue;
+ const running = nowM >= start && nowM <= end;
+ el.hidden = !running;
+ if (running) {
+ el.querySelector('.tl-elapsed-value').textContent = elapsedText(nowM - start);
+ }
+ }
+}
+
+// Hours and minutes, with the hours dropped when there are none. The minutes
+// are padded once hours appear so a ticking figure doesn't jump a character
+// wider between 1h 9m and 1h 10m.
+function elapsedText(mins) {
+ const m = Math.max(0, mins);
+ const h = Math.floor(m / 60);
+ return h === 0 ? `${m}m` : `${h}h ${String(m % 60).padStart(2, '0')}m`;
+}
+
+// Which stop the cook has got to.
+//
+// "In progress" is no help on its own: a turkey is in progress for two hours,
+// and so is everything that went in after it, which is how you end up with
+// half the timeline lit at once. The stage you are *up to* is the last
+// instruction whose time has come — that one gets the band, the one after it
+// gets a quieter outline, and the rest are history or still to come. Before
+// anything has started the first stop is both.
+function markCurrentStage(rows, nowM) {
+ let current = null;
+ let next = null;
+ for (const row of rows) {
+ const time = Number(row.dataset.time);
+ if (!Number.isFinite(time)) continue;
+ if (time <= nowM) current = row;
+ else if (!next) next = row;
+ }
+ if (!current) current = next;
+
+ for (const row of rows) {
+ row.classList.toggle('tl-current', row === current);
+ row.classList.toggle('tl-next', row === next && row !== current);
+ }
+
+ revealStage(current);
+}
+
+// The timeline is long and the cook is somewhere in the middle of it, so the
+// current stage is scrolled to rather than waited for. Only a *change* of stage
+// moves the page — otherwise every tick would drag the view back and there
+// would be no reading ahead.
+function revealStage(row) {
+ const key = row?.dataset.time ?? null;
+ if (key === lastStageKey) return;
+ const firstLook = lastStageKey === null;
+ lastStageKey = key;
+ if (!row) return;
+ const still = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ row.scrollIntoView({
+ block: 'center',
+ behavior: (firstLook || still) ? 'auto' : 'smooth',
+ });
+}
diff --git a/cook-plan/conflicts.js b/cook-plan/conflicts.js
index 16c88ad..3cef4c6 100644
--- a/cook-plan/conflicts.js
+++ b/cook-plan/conflicts.js
@@ -37,43 +37,88 @@ export function detectConflicts(items) {
function checkOvenConflicts() {
const cfg = applianceConfig();
const maxSlots = cfg.mainOvenShelves * 2;
- const ovenItems = items.filter(i =>
- COOK_TYPE_MAP[i.cookType]?.resource === 'oven' && i._appliance === 'main' && i._s.cookTime > 0
- );
- const usage = ovenItems.map(i => ({
- start: i._s.cookStart, end: i._s.cookEnd,
- slots: i.shelfSlots || 1, itemId: i.id,
- }));
- const over = sweepConflicts(usage, maxSlots);
+ // What is in the main oven, and when. A dish that moves across from the
+ // combi partway through its cook is in here only from the move onwards, so
+ // it is that stretch that gets swept rather than the whole cook.
+ const mainUsage = [];
+ for (const i of items) {
+ if (COOK_TYPE_MAP[i.cookType]?.resource !== 'oven' || !(i.cookTime > 0)) continue;
+ const slots = i.shelfSlots || 1;
+ if (i._appliance === 'main') {
+ mainUsage.push({ start: i._s.cookStart, end: i._s.cookEnd, shelf: i._shelf ?? 1, slots, itemId: i.id });
+ } else if (i._appliance === 'combi' && i._moveTo) {
+ mainUsage.push({ start: i._moveTo.at, end: i._s.cookEnd, shelf: i._moveTo.shelf, slots, itemId: i.id });
+ }
+ }
+ const describe = (id) => {
+ const it = items.find(i => i.id === id);
+ return it ? `"${it.name}" (${it.shelfSlots||1} slot${(it.shelfSlots||1)>1?'s':''})` : id;
+ };
+
+ const over = sweepConflicts(mainUsage, maxSlots);
const seen = new Set();
for (const { time, slots, itemIds } of over) {
const key = [...itemIds].sort().join(',');
if (seen.has(key)) continue;
seen.add(key);
- const names = itemIds.map(id => {
- const it = ovenItems.find(i => i.id === id);
- return it ? `"${it.name}" (${it.shelfSlots||1} slot${(it.shelfSlots||1)>1?'s':''})` : id;
- });
conflicts.push({
type: 'oven',
- message: `Main oven overcapacity at ${formatTime(time)}: ${names.join(', ')} = ${slots}/${maxSlots} slots.`,
+ message: `Main oven overcapacity at ${formatTime(time)}: ${itemIds.map(describe).join(', ')} = ${slots}/${maxSlots} slots.`,
itemIds,
});
}
+
+ // A shelf holds two slots however much room the oven has overall, so an
+ // oven that is only half full can still have a shelf with three things on
+ // it — by a hand-picked shelf that doesn't fit, or by the allocator having
+ // nowhere left to put something. Neither shows up in the total above.
+ const shelfSeen = new Set();
+ for (let shelf = 1; shelf <= cfg.mainOvenShelves; shelf++) {
+ const onShelf = mainUsage.filter(u => u.shelf === shelf);
+ if (onShelf.length < 2) continue;
+ for (const { time, slots, itemIds } of sweepConflicts(onShelf, 2)) {
+ const key = shelf + ':' + [...itemIds].sort().join(',');
+ if (shelfSeen.has(key)) continue;
+ shelfSeen.add(key);
+ conflicts.push({
+ type: 'oven-shelf',
+ message: `Main oven shelf ${shelf} overcapacity at ${formatTime(time)}: ${itemIds.map(describe).join(', ')} = ${slots}/2 slots. Move one to another shelf.`,
+ itemIds,
+ });
+ }
+ }
}
function checkCombiConflicts() {
+ const cfg = applianceConfig();
const combiItems = items.filter(i =>
- (i._appliance === 'combi' || i._appliance === 'combi-mw') && i._s.cookTime > 0
+ (i._appliance === 'combi' || i._appliance === 'combi-mw') && i.cookTime > 0
);
const ovenItems = combiItems.filter(i => i._appliance === 'combi');
const mwItems = combiItems.filter(i => i._appliance === 'combi-mw');
+ // The combi is the only microwave in the model, so without one these
+ // dishes have nowhere at all to cook -- not a clash, an absence.
+ if (!cfg.hasCombi && mwItems.length > 0) {
+ conflicts.push({
+ type: 'combi-capacity',
+ message: `There is no combi or microwave in the kitchen, so `
+ + `${names(mwItems)} ${mwItems.length > 1 ? 'have' : 'has'} nowhere to cook. `
+ + `Change the cook type, or turn the combi on in Settings.`,
+ itemIds: mwItems.map(i => i.id),
+ });
+ return;
+ }
+
+ // A dish that moves out to the main oven partway through holds the combi
+ // only up to the move.
+ const combiEnd = (i) => i._moveTo ? i._moveTo.at : i._s.cookEnd;
+
// Oven mode: 2-slot capacity
const ovenUsage = ovenItems.map(i => ({
- start: i._s.cookStart, end: i._s.cookEnd,
+ start: i._s.cookStart, end: combiEnd(i),
slots: i.shelfSlots || 1, itemId: i.id,
- }));
+ })).filter(u => u.end > u.start);
const ovenOver = sweepConflicts(ovenUsage, 2);
const seen = new Set();
for (const { time, slots, itemIds } of ovenOver) {
@@ -104,51 +149,55 @@ export function detectConflicts(items) {
itemIds,
});
}
- // Mode conflicts and cooldown -- still pair-wise since mode is per-item
- for (let i = 0; i < combiItems.length; i++) {
- for (let j = i + 1; j < combiItems.length; j++) {
- const a = combiItems[i], b = combiItems[j];
- const overlapStart = Math.max(a._s.cookStart, b._s.cookStart);
- const overlapEnd = Math.min(a._s.cookEnd, b._s.cookEnd);
- const modeA = a._appliance === 'combi' ? 'oven' : 'microwave';
- const modeB = b._appliance === 'combi' ? 'oven' : 'microwave';
-
- if (overlapEnd > overlapStart && modeA !== modeB) {
- conflicts.push({
- type: 'combi-mode',
- message: `Combi mode conflict: "${a.name}" needs it as ${modeA} but "${b.name}" needs it as ${modeB} during ${formatTime(overlapStart)}\u2013${formatTime(overlapEnd)}.`,
- itemIds: [a.id, b.id],
- });
- }
-
- // Cooldown: oven ends, then microwave starts
- if (modeA === 'oven' && modeB === 'microwave' && a._s.cookEnd <= b._s.cookStart) {
- const gap = b._s.cookStart - a._s.cookEnd;
- if (gap < COMBI_COOLDOWN) {
- conflicts.push({
- type: 'combi-cooldown',
- message: `Combi needs ${COMBI_COOLDOWN}m cooldown before microwave use. "${a.name}" (oven) ends ${formatTime(a._s.cookEnd)}, "${b.name}" (microwave) starts ${formatTime(b._s.cookStart)} \u2014 only ${gap}m gap.`,
- itemIds: [a.id, b.id],
- });
- }
- }
- if (modeB === 'oven' && modeA === 'microwave' && b._s.cookEnd <= a._s.cookStart) {
- const gap = a._s.cookStart - b._s.cookEnd;
- if (gap < COMBI_COOLDOWN) {
- conflicts.push({
- type: 'combi-cooldown',
- message: `Combi needs ${COMBI_COOLDOWN}m cooldown before microwave use. "${b.name}" (oven) ends ${formatTime(b._s.cookEnd)}, "${a.name}" (microwave) starts ${formatTime(a._s.cookStart)} \u2014 only ${gap}m gap.`,
- itemIds: [a.id, b.id],
- });
- }
- }
+ // Mode clashes, reported per microwave dish rather than per pair. Three
+ // trays sharing the combi oven is one problem, not three, and the combi
+ // being dual-mode is not the problem at all -- what the cook needs to know
+ // is what is tying it up and that something has to give.
+ for (const mw of mwItems) {
+ const overlapping = ovenItems.filter(o =>
+ o._s.cookStart < mw._s.cookEnd && combiEnd(o) > mw._s.cookStart
+ );
+ const tooSoon = ovenItems.filter(o =>
+ combiEnd(o) <= mw._s.cookStart
+ && mw._s.cookStart - combiEnd(o) < COMBI_COOLDOWN
+ );
+
+ // The planner has already tried to move what is in the way; saying so
+ // stops the advice being "move a dish" when there is nowhere to move it.
+ const nowhere = mw._relocation === 'impossible'
+ ? ` The main oven is full for that stretch, so there is nothing to move.`
+ : '';
+
+ if (overlapping.length > 0) {
+ const until = formatTime(Math.max(...overlapping.map(combiEnd)));
+ conflicts.push({
+ type: 'combi-mode',
+ message: `Combi is in use as an oven until ${until} (${names(overlapping)}), `
+ + `so it can't microwave "${mw.name}" at ${formatTime(mw._s.cookStart)}.`
+ + `${nowhere} Cook "${mw.name}" another way, or make room in the main oven.`,
+ itemIds: [mw.id, ...overlapping.map(o => o.id)],
+ });
+ } else if (tooSoon.length > 0) {
+ const last = tooSoon.reduce((a, b) => (combiEnd(b) > combiEnd(a) ? b : a));
+ const gap = mw._s.cookStart - combiEnd(last);
+ conflicts.push({
+ type: 'combi-cooldown',
+ message: `Combi needs ${COMBI_COOLDOWN}m to cool down before it will microwave. `
+ + `"${last.name}" comes out at ${formatTime(combiEnd(last))} and `
+ + `"${mw.name}" wants it at ${formatTime(mw._s.cookStart)} \u2014 only ${gap}m gap.`,
+ itemIds: [mw.id, last.id],
+ });
}
}
}
+ function names(arr) {
+ return arr.map(i => `"${i.name}"`).join(', ');
+ }
+
function checkHobConflicts() {
const hobItems = items.filter(i =>
- COOK_TYPE_MAP[i.cookType]?.resource === 'hob' && i._s.cookTime > 0
+ COOK_TYPE_MAP[i.cookType]?.resource === 'hob' && i.cookTime > 0
);
// Check all time slices where more than 5 items are on hobs
const events = [];
diff --git a/cook-plan/constants.js b/cook-plan/constants.js
index 9df5eba..48ab424 100644
--- a/cook-plan/constants.js
+++ b/cook-plan/constants.js
@@ -28,7 +28,10 @@ export const EV_TYPE_CHIP = {
prep: 'PREP',
cook_start: 'IN',
cook_end: 'OUT',
+ preheat: 'HEAT',
+ move: 'MOVE',
set: 'REST',
+ serve_prep: 'PLATE',
ready: 'READY',
serve: '',
};
@@ -38,7 +41,9 @@ export const DEFAULT_STATE = {
mode: 'end', // 'start' | 'end'
targetTime: '17:00',
items: [],
- appliances: { mainOvenShelves: 2, hasCombi: true, hobCount: 5 },
+ appliances: {
+ mainOvenShelves: 2, hasCombi: true, hobCount: 5, preheatMins: 6, holdMins: 15,
+ },
snapMins: 0,
};
diff --git a/cook-plan/db.js b/cook-plan/db.js
index 2d4572a..758dd2a 100644
--- a/cook-plan/db.js
+++ b/cook-plan/db.js
@@ -45,9 +45,11 @@ function itemToDoc(item) {
cookType: item.cookType || 'oven',
shelfSlots: item.shelfSlots ?? 1,
appliancePref: item.appliancePref || 'auto',
+ shelfPref: item.shelfPref ?? null,
prepTime: item.prepTime || 0,
cookTime: item.cookTime || 0,
setTime: item.setTime || 0,
+ servePrep: item.servePrep || 0,
overrideCookStart: item.overrideCookStart ?? null,
order: item.order ?? 0,
createdAt: item.createdAt ?? Date.now(),
@@ -61,9 +63,11 @@ function itemFromDoc(doc) {
cookType: doc.cookType || 'oven',
shelfSlots: doc.shelfSlots ?? 1,
appliancePref: doc.appliancePref || 'auto',
+ shelfPref: doc.shelfPref ?? null,
prepTime: doc.prepTime || 0,
cookTime: doc.cookTime || 0,
setTime: doc.setTime || 0,
+ servePrep: doc.servePrep || 0,
overrideCookStart: doc.overrideCookStart ?? null,
order: doc.order ?? 0,
createdAt: doc.createdAt ?? 0,
diff --git a/cook-plan/events.js b/cook-plan/events.js
index b62d4ba..75d61ed 100644
--- a/cook-plan/events.js
+++ b/cook-plan/events.js
@@ -4,12 +4,13 @@
import { COOK_TYPE_MAP } from './constants.js';
import { formatDuration } from './utils.js';
+import { applianceConfig } from './appliances.js';
export function buildEvents(items, serveTime) {
const events = [];
for (const item of items) {
- const { cookStart, prepStart, cookEnd, setEnd } = item._s;
+ const { cookStart, prepStart, cookEnd, setEnd, serveEnd } = item._s;
const ct = COOK_TYPE_MAP[item.cookType];
if (item.prepTime > 0) {
@@ -58,6 +59,11 @@ export function buildEvents(items, serveTime) {
applianceKey: appKey,
applianceLabel: appLabel,
shelfInfo: item._shelf ?? null,
+ // Dishes already on this shelf that this one could genuinely go in a
+ // single tray with (see foods.js). Carried separately from `sub` so the
+ // merged-event formatting below doesn't have to parse it back out.
+ trayMates: item._trayMates || [],
+ shelfPinned: !!item._shelfPinned,
ct,
});
events.push({
@@ -74,6 +80,23 @@ export function buildEvents(items, serveTime) {
});
}
+ // Started in the combi, finishes in the main oven. A real job with a time
+ // of its own, and the only reason the microwave gets its slot.
+ if (item._moveTo) {
+ events.push({
+ time: item._moveTo.at,
+ endTime: item._moveTo.at,
+ type: 'move',
+ label: `Move ${item.name} \u2192 Main Oven`,
+ sub: `Shelf ${item._moveTo.shelf} \u00b7 frees the combi for ${item._moveTo.forItem}`,
+ itemId: item.id,
+ itemName: item.name,
+ // Each move is its own instruction: two dishes going to different
+ // shelves is two jobs, not one line with a shelf missing from it.
+ applianceKey: `move-${item.id}`,
+ });
+ }
+
if (item.setTime > 0) {
events.push({
time: cookEnd,
@@ -87,12 +110,31 @@ export function buildEvents(items, serveTime) {
});
}
+ // Carving, plating, saucing: the last hands-on job, and the reason a dish
+ // that needs it has to come out of the oven earlier than one that doesn't.
+ if (item.servePrep > 0) {
+ events.push({
+ time: setEnd,
+ endTime: serveEnd,
+ type: 'serve_prep',
+ label: `${item.name} \u2014 carve / plate`,
+ sub: formatDuration(item.servePrep),
+ itemId: item.id,
+ itemName: item.name,
+ applianceKey: 'serve_prep',
+ });
+ }
+
events.push({
- time: setEnd,
- endTime: setEnd,
+ time: serveEnd,
+ endTime: serveEnd,
type: 'ready',
label: `${item.name} ready`,
- sub: null,
+ // A dish finished early to free an appliance needs covering, or the
+ // minutes it saved the plan cost it its heat.
+ sub: item._holdFor > 0 && serveEnd < serveTime
+ ? `Cover and set aside \u00b7 ${formatDuration(serveTime - serveEnd)} until serve`
+ : null,
itemId: item.id,
itemName: item.name,
applianceKey: 'ready',
@@ -102,8 +144,8 @@ export function buildEvents(items, serveTime) {
// Cooked items that are already done before serve get a "ready and waiting"
// note. Prep-only items aren't included \u2014 they're not "out of the oven".
const restingNotes = items
- .filter(it => it.cookType !== 'none' && it.cookTime > 0 && it._s.setEnd < serveTime)
- .map(it => `${it.name} been out ${formatDuration(serveTime - it._s.setEnd)}`)
+ .filter(it => it.cookType !== 'none' && it.cookTime > 0 && it._s.serveEnd < serveTime)
+ .map(it => `${it.name} been out ${formatDuration(serveTime - it._s.serveEnd)}`)
.join(' \u00b7 ');
events.push({
@@ -115,6 +157,8 @@ export function buildEvents(items, serveTime) {
itemId: null,
});
+ events.push(...preheatEvents(items, applianceConfig().preheatMins));
+
// Sort; serve goes last if same time
events.sort((a, b) => a.time - b.time || (a.type === 'serve' ? 1 : b.type === 'serve' ? -1 : 0));
@@ -122,6 +166,39 @@ export function buildEvents(items, serveTime) {
return events;
}
+// An oven does not start hot. Each one that gets used needs turning on before
+// the first dish goes into it, which is a job for the cook and so a stop on the
+// timeline -- one per oven, at its own first use. A microwave needs none, and a
+// hob heats while you stand over it.
+function preheatEvents(items, preheatMins) {
+ if (!(preheatMins > 0)) return [];
+
+ const firstUse = new Map();
+ for (const item of items) {
+ if (!(item.cookTime > 0)) continue;
+ if (COOK_TYPE_MAP[item.cookType]?.resource !== 'oven') continue;
+ const key = item._appliance;
+ if (key !== 'main' && key !== 'combi') continue;
+ const at = item._s.cookStart;
+ if (!firstUse.has(key) || at < firstUse.get(key)) firstUse.set(key, at);
+ }
+
+ return [...firstUse].map(([key, at]) => {
+ const label = applianceLabel(key, null);
+ return {
+ time: at - preheatMins,
+ endTime: at,
+ type: 'preheat',
+ label: `Heat ${label}`,
+ sub: formatDuration(preheatMins),
+ itemId: null,
+ itemName: null,
+ applianceKey: `preheat-${key}`,
+ applianceLabel: label,
+ };
+ });
+}
+
export function joinNames(names) {
if (names.length === 1) return names[0];
return names.slice(0, -1).join(', ') + ' & ' + names[names.length - 1];
@@ -141,11 +218,15 @@ export function mergedLabel(type, evs, names) {
}
case 'cook_end': {
const resource = ct?.resource;
- if (resource === 'oven' || resource === 'combi') return `${joinNames(names)} out of oven`;
+ // 'combi' as a cook type means the microwave; an oven dish that happens
+ // to be cooking in the combi has resource 'oven' like any other.
+ if (resource === 'combi') return `${joinNames(names)} out of the microwave`;
+ if (resource === 'oven') return `${joinNames(names)} out of oven`;
if (resource === 'hob') return `${joinNames(names)} off hob`;
return `${joinNames(names)} done`;
}
- case 'set': return `${joinNames(names)} \u2014 rest / set`;
+ case 'set': return `${joinNames(names)} \u2014 rest / set`;
+ case 'serve_prep': return `${joinNames(names)} \u2014 carve / plate`;
case 'ready': return `${joinNames(names)} ready`;
default: return evs[0]?.label || '';
}
@@ -199,7 +280,8 @@ export function cookStartLabel(item, ct, appLabel) {
}
export function cookEndLabel(item, ct) {
- if (ct?.resource === 'oven' || ct?.resource === 'combi') return `${item.name} out of oven`;
+ if (ct?.resource === 'combi') return `${item.name} out of the microwave`;
+ if (ct?.resource === 'oven') return `${item.name} out of oven`;
if (ct?.resource === 'hob') return `${item.name} off hob`;
return `${item.name} done`;
}
diff --git a/cook-plan/foods.js b/cook-plan/foods.js
new file mode 100644
index 0000000..85bb48b
--- /dev/null
+++ b/cook-plan/foods.js
@@ -0,0 +1,179 @@
+// =============================================
+// Cook Planner — foods.js
+//
+// A small catalogue of the things that actually turn up at a roast, with the
+// timings most recipes agree on. Two jobs:
+//
+// 1. Autocomplete. Typing "parsn" offers "Parsnips" and, with it, a cook type
+// and a set of times — the tedious part of adding a dish.
+// 2. Tray pairing. The main oven's shelves hold two half-shelf slots each, so
+// something has to decide which two dishes end up side by side. Potatoes and
+// parsnips want the same heat and the same fat and can go in one big tray;
+// a crumble next to salmon is a worse idea. `pairScore` is what the shelf
+// allocator in appliances.js consults to make that call.
+//
+// `family` groups things that are interchangeable on a tray. `heat` stands in
+// for an oven temperature the planner doesn't otherwise model — hot is roughly
+// 200°C+, mid 180–190°C, low 150–170°C. `tray` says whether a dish is loose on
+// a baking tray ('open', so it can share one) or sealed in its own dish or tin
+// ('dish' — happy to share a shelf, but never a tray).
+//
+// `serve` is the hands-on job between resting and eating — carving a joint,
+// turning out a pudding. Nearly everything is zero: a tray of parsnips goes
+// from the oven to the table.
+// =============================================
+
+// name, cookType, prep, cook, rest, serve, slots, family, heat, tray
+const RAW = [
+ // ── Big roasts ──
+ ['Turkey', 'oven', 20, 180, 30, 20, 2, 'poultry', 'mid', 'dish'],
+ ['Turkey crown', 'oven', 15, 120, 25, 15, 2, 'poultry', 'mid', 'dish'],
+ ['Roast chicken', 'oven', 10, 90, 15, 10, 2, 'poultry', 'mid', 'dish'],
+ ['Chicken thighs', 'oven', 5, 45, 5, 0, 1, 'poultry', 'mid', 'open'],
+ ['Roast duck', 'oven', 15, 120, 20, 10, 2, 'poultry', 'mid', 'dish'],
+ ['Roast goose', 'oven', 20, 150, 30, 15, 2, 'poultry', 'mid', 'dish'],
+ ['Beef joint', 'oven', 15, 90, 25, 10, 2, 'red-meat', 'hot', 'dish'],
+ ['Rib of beef', 'oven', 20, 120, 30, 15, 2, 'red-meat', 'hot', 'dish'],
+ ['Leg of lamb', 'oven', 15, 105, 25, 10, 2, 'red-meat', 'mid', 'dish'],
+ ['Shoulder of lamb', 'oven', 15, 240, 30, 10, 2, 'red-meat', 'low', 'dish'],
+ ['Pork loin', 'oven', 15, 100, 20, 10, 2, 'red-meat', 'mid', 'dish'],
+ ['Pork belly', 'oven', 20, 150, 15, 10, 2, 'red-meat', 'low', 'dish'],
+ ['Gammon joint', 'oven', 15, 120, 15, 10, 2, 'red-meat', 'mid', 'dish'],
+ ['Beef Wellington', 'oven', 30, 40, 15, 5, 2, 'pastry', 'hot', 'dish'],
+ ['Nut roast', 'oven', 20, 50, 10, 5, 1, 'veg-bake', 'mid', 'dish'],
+
+ // ── Roast veg: the tray-sharers ──
+ ['Roast potatoes', 'oven', 20, 55, 0, 0, 2, 'root-veg', 'hot', 'open'],
+ ['Hasselback potatoes', 'oven', 20, 60, 0, 0, 2, 'root-veg', 'hot', 'open'],
+ ['Parsnips', 'oven', 10, 40, 0, 0, 1, 'root-veg', 'hot', 'open'],
+ ['Honey-roast carrots', 'oven', 10, 35, 0, 0, 1, 'root-veg', 'hot', 'open'],
+ ['Roast swede', 'oven', 10, 45, 0, 0, 1, 'root-veg', 'hot', 'open'],
+ ['Roast beetroot', 'oven', 10, 50, 0, 0, 1, 'root-veg', 'hot', 'open'],
+ ['Sweet potatoes', 'oven', 10, 40, 0, 0, 1, 'root-veg', 'hot', 'open'],
+ ['Roast veg medley', 'oven', 15, 40, 0, 0, 2, 'root-veg', 'hot', 'open'],
+ ['Roast onions', 'oven', 5, 35, 0, 0, 1, 'allium', 'hot', 'open'],
+ ['Roast shallots', 'oven', 5, 30, 0, 0, 1, 'allium', 'hot', 'open'],
+ ['Roast leeks', 'oven', 5, 30, 0, 0, 1, 'allium', 'mid', 'open'],
+ ['Roast sprouts', 'oven', 8, 25, 0, 0, 1, 'brassica', 'hot', 'open'],
+ ['Roast cauliflower', 'oven', 8, 30, 0, 0, 1, 'brassica', 'hot', 'open'],
+ ['Roast broccoli', 'oven', 5, 20, 0, 0, 1, 'brassica', 'hot', 'open'],
+
+ // ── Trimmings ──
+ ['Pigs in blankets', 'oven', 10, 30, 0, 0, 1, 'sausage', 'mid', 'open'],
+ ['Pork sausages', 'oven', 2, 30, 0, 0, 1, 'sausage', 'mid', 'open'],
+ ['Stuffing balls', 'oven', 10, 30, 0, 0, 1, 'stuffing', 'mid', 'open'],
+ ['Sage & onion stuffing','oven', 10, 35, 0, 0, 1, 'stuffing', 'mid', 'dish'],
+ ['Yorkshire puddings', 'oven', 10, 22, 0, 0, 1, 'batter', 'hot', 'dish'],
+ ['Toad in the hole', 'oven', 15, 40, 0, 0, 2, 'batter', 'hot', 'dish'],
+ ['Pork crackling', 'oven', 5, 25, 0, 0, 1, 'red-meat', 'hot', 'open'],
+ ['Cauliflower cheese', 'oven', 20, 30, 5, 0, 2, 'veg-bake', 'mid', 'dish'],
+ ['Dauphinoise potatoes', 'oven', 20, 75, 10, 5, 2, 'veg-bake', 'mid', 'dish'],
+ ['Bread rolls', 'oven', 2, 10, 0, 0, 1, 'bread', 'hot', 'open'],
+ ['Garlic bread', 'oven', 2, 15, 0, 0, 1, 'bread', 'hot', 'open'],
+ ['Salmon fillets', 'oven', 5, 20, 5, 0, 1, 'fish', 'mid', 'open'],
+
+ // ── Hob ──
+ ['Mashed potatoes', 'boil', 15, 20, 0, 0, 1, 'root-veg', 'mid', 'open'],
+ ['Boiled potatoes', 'boil', 10, 20, 0, 0, 1, 'root-veg', 'mid', 'open'],
+ ['Brussels sprouts', 'boil', 10, 8, 0, 0, 1, 'brassica', 'mid', 'open'],
+ ['Carrots', 'boil', 5, 15, 0, 0, 1, 'root-veg', 'mid', 'open'],
+ ['Green beans', 'boil', 3, 6, 0, 0, 1, 'brassica', 'mid', 'open'],
+ ['Garden peas', 'boil', 2, 5, 0, 0, 1, 'brassica', 'mid', 'open'],
+ ['Cauliflower', 'boil', 5, 10, 0, 0, 1, 'brassica', 'mid', 'open'],
+ ['Broccoli', 'boil', 3, 6, 0, 0, 1, 'brassica', 'mid', 'open'],
+ ['Red cabbage', 'pan', 10, 45, 0, 0, 1, 'brassica', 'mid', 'dish'],
+ ['Gravy', 'pan', 5, 15, 0, 0, 1, 'sauce', 'mid', 'dish'],
+ ['Bread sauce', 'pan', 5, 15, 0, 0, 1, 'sauce', 'mid', 'dish'],
+ ['Cranberry sauce', 'pan', 5, 10, 0, 0, 1, 'sauce', 'mid', 'dish'],
+
+ // ── Pudding ──
+ ['Apple crumble', 'oven', 20, 40, 10, 0, 2, 'dessert', 'mid', 'dish'],
+ ['Apple pie', 'oven', 15, 45, 10, 5, 2, 'dessert', 'mid', 'dish'],
+ ['Christmas pudding', 'boil', 5, 120, 0, 5, 1, 'dessert', 'mid', 'dish'],
+ ['Mince pies', 'oven', 2, 18, 0, 0, 1, 'dessert', 'mid', 'open'],
+];
+
+export const FOODS = RAW.map(
+ ([name, cookType, prepTime, cookTime, setTime, servePrep, shelfSlots, family, heat, tray]) => ({
+ name, cookType, prepTime, cookTime, setTime, servePrep, shelfSlots, family, heat, tray,
+ })
+);
+
+export const FOOD_NAMES = FOODS.map(f => f.name);
+
+const BY_KEY = new Map(FOODS.map(f => [normalise(f.name), f]));
+
+function normalise(name) {
+ return String(name || '')
+ .toLowerCase()
+ .replace(/&/g, 'and')
+ .replace(/[^a-z0-9]+/g, ' ')
+ .trim();
+}
+
+// An exact (if punctuation-insensitive) hit only. Suggesting times for a dish
+// the cook didn't name is worse than suggesting nothing: "Roast potatoes" must
+// not quietly answer for "Potato salad".
+export function lookupFood(name) {
+ return BY_KEY.get(normalise(name)) || null;
+}
+
+// The tray-pairing model.
+//
+// Families that roast alike, so swapping one for the other on a tray changes
+// nothing that matters.
+const AFFINITY_GROUPS = [
+ ['root-veg', 'allium', 'brassica'], // all go in hot fat and come out together
+ ['sausage', 'stuffing'], // the trimmings tray
+ ['bread', 'pastry'],
+];
+
+const HEAT_INDEX = { low: 0, mid: 1, hot: 2 };
+
+// Flavours that shouldn't meet in the same fat, whatever their temperatures say.
+function clashes(a, b) {
+ const sweet = f => f.family === 'dessert';
+ if (sweet(a) !== sweet(b)) return true; // pudding beside the meat
+ const fish = f => f.family === 'fish';
+ const strong = f => ['sausage', 'stuffing', 'red-meat', 'allium'].includes(f.family);
+ if ((fish(a) && strong(b)) || (fish(b) && strong(a))) return true;
+ return false;
+}
+
+function sameGroup(a, b) {
+ return AFFINITY_GROUPS.some(g => g.includes(a.family) && g.includes(b.family));
+}
+
+// How well two dishes sit next to each other on one shelf.
+//
+// +3 the same thing, near enough — one big tray (potatoes + parsnips)
+// +2 different but cooked alike (parsnips + roast onions)
+// 0 no opinion: unknown dish, or each sealed in its own dish
+// -2 wants a markedly different oven temperature
+// -3 shouldn't share the fat at all
+//
+// Anything above 0 is a nudge towards putting them together; anything below is
+// a reason to use the other shelf first. `null` inputs (a dish not in the
+// catalogue) score 0 — an unknown is no reason to shuffle the oven around.
+export function pairScore(a, b) {
+ if (!a || !b) return 0;
+ if (clashes(a, b)) return -3;
+
+ const heatGap = Math.abs((HEAT_INDEX[a.heat] ?? 1) - (HEAT_INDEX[b.heat] ?? 1));
+ if (heatGap >= 2) return -2;
+
+ // Each in its own dish or tin: they can share the shelf, but there is no tray
+ // to share, so neither one is a reason to prefer this shelf over an empty one.
+ if (a.tray !== 'open' || b.tray !== 'open') return 0;
+
+ if (a.family === b.family) return heatGap === 0 ? 3 : 2;
+ if (sameGroup(a, b)) return heatGap === 0 ? 2 : 1;
+ return 0;
+}
+
+// Would these two actually go in one tray together? Used for the "share a tray"
+// note on the timeline, which should only appear when it's genuinely useful
+// advice rather than whenever two things happen to land on the same shelf.
+export function sharesTray(a, b) {
+ return pairScore(a, b) >= 2;
+}
diff --git a/cook-plan/index.html b/cook-plan/index.html
index 680e77c..2d31dba 100644
--- a/cook-plan/index.html
+++ b/cook-plan/index.html
@@ -41,6 +41,30 @@
Rest is the dish sitting on its own after cooking;
+ serving prep is the hands-on job after that — carving, plating, saucing.
+ Both are counted back from the serve time, so a chicken that needs ten
+ minutes of carving goes in ten minutes earlier.