diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index d2dc236..849a324 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -2,11 +2,11 @@ ## Learn by doing -On your first visit, choose **Start my first experiment**. You can also open **Learn by doing** from the playground at any time. +On your first visit, choose **Try it with me**. You can also open **Learn by doing** from the playground at any time. -The five-step exercise opens a separate Service Studio project. Select **Specialists**, change its shared team from **2** to **3**, run the changed plan, compare completed work, waiting and resource cost, then optionally save your own template. The guide highlights the actual controls and follows your applied edits and completed calculations. +The lesson opens a separate practice copy of a small help desk. You see one task at a time beside the scene. Choose **Specialists**, change **People on this team** from **2** to **3**, then choose **Apply change** and **Try this change**. The result explains requests helped, time spent waiting and team costs with clear before/after values. You can then name and save the example as a template. -You can minimize or leave the guide at any time. Existing work is saved before practice starts; **Back to my previous project** reopens it. Refreshing an active practice restores its saved draft and asks you to run again before comparing. Templates and projects stay in this browser; download project JSON for a portable backup. +**Show the full workspace** opens the complete editor; **Continue my lesson** brings the focused view back. You can also leave the guide. Existing work is saved before practice starts; **Back to my previous project** reopens it. Refreshing an active practice restores its saved draft and asks you to run again before comparing. Templates and projects stay in this browser; download project JSON for a portable backup. Choose **Explore on my own** to start without the exercise, or **Just show me the controls** for a short reference tour. diff --git a/docs/UX_GUIDE.md b/docs/UX_GUIDE.md index 5896b24..6705145 100644 --- a/docs/UX_GUIDE.md +++ b/docs/UX_GUIDE.md @@ -12,9 +12,9 @@ The team’s base availability is visible in Properties. Installed capacity, cos ## Guided first experiment -**Learn by doing** opens a five-step Service Studio practice: select Specialists, apply a shared-team change, calculate, read the comparison and optionally save a reusable template. Progress follows real edits and completed runs. Highlighted controls remain ordinary editor controls with the same validation and Undo behavior. +**Learn by doing → Try it with me** opens a separate help-desk practice copy. A focused view shows the scene and one task at a time. Choose Specialists, change **People on this team** to 3 and choose **Apply change**. **Try this change** calculates the real result; before/after values explain requests helped, waiting and team costs inside the lesson. The last task lets you name and save your own template. -The guide can be minimized or dismissed. It preserves an existing project before switching, offers a return action and resumes a saved practice after refresh. If you change other numerical inputs, it lets you keep exploring or start a fresh practice. Failed calculations and template saves remain incomplete and can be retried. The optional finish path explicitly says that no template was saved. +**Show the full workspace** reveals the complete editor; **Continue my lesson** returns to the focused view. The guide can also be dismissed. Unfinished fields must be applied or cancelled first. It preserves an existing project before switching, offers a return action and resumes a saved practice after refresh. A different team number can be corrected in place. If you change other numerical inputs in the full editor, it lets you keep exploring or start a fresh practice. Failed calculations and template saves remain incomplete and can be retried. The optional finish path explicitly says that no template was saved. A first-visit welcome is shown only when no saved project is restored. Returning users can start the exercise from the playground. **Just show me the controls** retains the short reference tour. diff --git a/package-lock.json b/package-lock.json index 95cdb48..ad55064 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "queuelab", - "version": "1.0.0-rc.15", + "version": "1.0.0-rc.16", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "queuelab", - "version": "1.0.0-rc.15", + "version": "1.0.0-rc.16", "license": "MIT", "dependencies": { "lucide-react": "1.60.0", diff --git a/package.json b/package.json index 998f97a..50c0efb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "queuelab", - "version": "1.0.0-rc.15", + "version": "1.0.0-rc.16", "private": true, "type": "module", "description": "A playable process and capacity simulation laboratory", diff --git a/scripts/learning-smoke.mjs b/scripts/learning-smoke.mjs index 4ae30a9..704156a 100644 --- a/scripts/learning-smoke.mjs +++ b/scripts/learning-smoke.mjs @@ -17,8 +17,8 @@ const state = p => p.evaluate(() => JSON.parse(window.render_game_to_text())); const ready = p => p.waitForFunction(() => { const s = JSON.parse(window.render_game_to_text?.() || '{}'); return !s.running && s.result?.status === 'completed'; }); const coach = p => p.locator('.learning-coach'); const stage = (p, name) => p.locator(`[data-learning-stage="${name}"]`).waitFor(); -const cap = p => p.locator('[data-learning-target="capacity-specialists"] input'); -const saved = p => p.locator('.workspace-footer').getByText(/^Saved in this browser/).first().waitFor(); +const cap = p => p.locator('[data-learning-team] input:visible,[data-learning-target="capacity-specialists"] input:visible'); +const saved = p => p.locator('.workspace-footer').getByText(/^Saved in this browser/).first().waitFor({ state: 'attached' }); async function fresh(width = 1440, skip = false) { const context = await browser.newContext({ viewport: { width, height: width > 740 ? 1000 : 844 }, reducedMotion: 'reduce', acceptDownloads: true }); const p = await context.newPage(); p.on('pageerror', e => errors.push(String(e))); await p.goto(origin.href); await ready(p); @@ -26,21 +26,29 @@ async function fresh(width = 1440, skip = false) { } async function start(p) { if (!await p.locator('[data-panel=learn]').count()) await p.getByRole('button', { name: 'Learn by doing', exact: true }).click(); - await p.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); await stage(p, 'select'); + await p.getByRole('button', { name: 'Try it with me', exact: true }).click(); await stage(p, 'select'); } async function change(p) { - await coach(p).getByRole('button', { name: 'Open the Steps list', exact: true }).click(); - await p.locator('[data-learning-target="step-station-b"]').press('Enter'); await stage(p, 'edit'); - await p.getByRole('button', { name: 'Show the team setting', exact: true }).click(); - await cap(p).fill('3'); await cap(p).press('Enter'); await stage(p, 'run'); + await coach(p).getByRole('button', { name: 'Choose Specialists', exact: true }).click(); await stage(p, 'edit'); + await cap(p).fill('3'); await p.getByRole('button', { name: 'Apply change', exact: true }).click(); await stage(p, 'run'); } async function compare(p) { - await coach(p).getByRole('button', { name: 'Run & compare', exact: true }).press('Enter'); - await p.locator('[data-panel=compare] [data-learning-stage=review]').waitFor(); + await coach(p).getByRole('button', { name: 'Try this change', exact: true }).press('Enter'); + await stage(p, 'review'); await p.waitForFunction(() => document.activeElement?.matches('[data-learning-heading]')); assert.equal(await p.getByRole('dialog').count(), 0); } -async function keep(p) { await p.getByRole('button', { name: 'Keep this version', exact: true }).click(); await stage(p, 'save'); } +async function keep(p) { await p.getByRole('button', { name: 'Got it. Next', exact: true }).click(); await stage(p, 'save'); } async function download(p, name) { - const next = p.waitForEvent('download'); await p.locator('.studio-save').click(); const file = await next, target = path.join(out, `${name}.json`); await file.saveAs(target); return JSON.parse(await fs.readFile(target, 'utf8')); + const focused = await p.locator('.learning-focused').count(); + if (focused) await p.getByRole('button', { name: 'Show the full workspace', exact: true }).click(); + const next = p.waitForEvent('download'); await p.locator('.studio-save').click(); const file = await next, target = path.join(out, `${name}.json`); await file.saveAs(target); + if (focused) await p.locator('[data-learning-resume]').click(); + return JSON.parse(await fs.readFile(target, 'utf8')); +} +async function templateCount(p) { + return p.evaluate(() => new Promise((resolve, reject) => { + const r = indexedDB.open('loopset-templates', 1); r.onerror = () => reject(r.error); + r.onsuccess = () => { const db = r.result, tx = db.transaction('templates'), count = tx.objectStore('templates').count(); tx.oncomplete = () => { db.close(); resolve(count.result); }; tx.onabort = () => { db.close(); reject(tx.error); }; }; + })); } async function overflow(p) { assert(await p.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)); @@ -55,29 +63,39 @@ try { await page.screenshot({ path: path.join(out, `welcome-${width}.png`) }); await start(page); const initial = await download(page, `practice-${width}`); assert.equal(initial.world, 'service'); assert.equal(initial.name, 'My first experiment'); assert.deepEqual(initial.model, JSON.parse(await fs.readFile('public/templates/service.json', 'utf8')).model); - await page.getByRole('button', { name: 'Minimize guide', exact: true }).click(); - assert(await page.locator('[data-learning-resume]').evaluate(el => el === document.activeElement)); + await page.getByRole('button', { name: 'Show the full workspace', exact: true }).click(); + await page.waitForFunction(() => document.activeElement?.matches('[data-learning-resume]')); await page.locator('[data-learning-resume]').press('Enter'); await stage(page, 'select'); - await coach(page).getByRole('button', { name: 'Open the Steps list', exact: true }).click(); - await page.locator('[data-learning-target="step-station-b"]').press('Enter'); await stage(page, 'edit'); - await page.getByRole('button', { name: 'Show the team setting', exact: true }).click(); + // The visible scene label is a real keyboard selection alternative to the lesson button. + if (width === 1440) await page.locator('.world-scene [data-station-id="station-b"]').press('Enter'); + else await page.getByRole('button', { name: 'Choose Specialists', exact: true }).click(); + await stage(page, 'edit'); + assert.equal((await state(page)).selected, 'station-b'); + assert.equal(await page.locator('.studio-inspector').isVisible(), false); assert.match(await cap(page).getAttribute('aria-describedby'), /-help learning-instruction$/); - assert(await page.locator('.learning-field-hint').isVisible()); await overflow(page); - await page.screenshot({ path: path.join(out, `edit-${width}.png`) }); - await cap(page).fill('invalid'); assert.equal(await coach(page).getAttribute('data-learning-stage'), 'edit'); - assert(await page.locator('[data-learning-target=run]').isDisabled()); await cap(page).press('Escape'); - await cap(page).fill('3'); await cap(page).press('Enter'); await stage(page, 'run'); + await overflow(page); await page.screenshot({ path: path.join(out, `edit-${width}.png`) }); + const revision = (await state(page)).revision; + await cap(page).fill('invalid'); await page.getByRole('button', { name: 'Apply change', exact: true }).click(); + assert.equal(await coach(page).getAttribute('data-learning-stage'), 'edit'); + assert.equal((await state(page)).revision, revision); + assert(await page.locator('.learning-team .ease-field-error').isVisible()); + assert(await page.getByRole('button', { name: 'Show the full workspace', exact: true }).isDisabled()); + await cap(page).press('Escape'); await cap(page).fill('4'); + await page.getByRole('button', { name: 'Apply change', exact: true }).click(); + await page.waitForFunction(() => document.querySelector('[data-learning-team] input')?.value === '4'); + await stage(page, 'edit'); assert.equal(await page.locator('[data-learning-stage=off-track]').count(), 0); + await cap(page).fill('3'); await page.getByRole('button', { name: 'Apply change', exact: true }).click(); await stage(page, 'run'); const changed = await download(page, `changed-${width}`); const expected = structuredClone(initial.model); expected.resources.find(pool => pool.id === 'specialists').capacity = 3; assert.deepEqual(changed.model, expected); assert.equal(changed.id, initial.id); await compare(page); assert.equal((await state(page)).result.stale, false); await overflow(page); await page.screenshot({ path: path.join(out, `review-${width}.png`) }); await keep(page); - await page.locator('.template-save input').fill('My trained team'); await page.locator('.template-save button[type=submit]').press('Enter'); await stage(page, 'complete'); - assert.match(await page.locator('.learning-saved').innerText(), /Template saved: My trained team/); - await page.locator('[data-template-id]').first().waitFor(); assert.equal(await page.locator('[data-template-id]').count(), 1); await overflow(page); + await page.locator('.template-save input').fill('My trained team'); await page.waitForFunction(() => !document.querySelector('.template-save button[type=submit]')?.disabled); await page.locator('.template-save button[type=submit]').press('Enter'); await stage(page, 'complete'); + assert.match(await page.locator('.learning-saved').innerText(), /Saved in My templates: My trained team/); + assert.equal(await templateCount(page), 1); await overflow(page); await coach(page).scrollIntoViewIfNeeded(); await page.screenshot({ path: path.join(out, `complete-${width}.png`) }); assert.equal(await coach(page).evaluate(el => getComputedStyle(el).animationName), 'none'); - await page.getByRole('button', { name: 'Explore this project', exact: true }).click(); await saved(page); + await page.getByRole('button', { name: 'Open the full workspace', exact: true }).click(); await saved(page); await page.reload(); await ready(page); assert.equal(await page.locator('[data-panel=learn],.learning-coach').count(), 0); assert.deepEqual((await download(page, `reopened-${width}`)).model, changed.model); await openPanel(page, 'worlds'); await page.getByRole('button', { name: /^My templates/ }).click(); await page.locator('[data-template-id]').first().waitFor(); assert.equal(await page.locator('[data-template-id]').count(), 1); @@ -101,18 +119,18 @@ try { const before = await download(page, 'original-custom'), beforeState = await state(page); const undoLabel = await page.getByRole('button', { name: /^Undo / }).getAttribute('aria-label'); await page.evaluate(() => { const transaction = IDBDatabase.prototype.transaction; window.restoreProjectWrites = () => { IDBDatabase.prototype.transaction = transaction; }; IDBDatabase.prototype.transaction = function (...args) { if (this.name === 'queuelab-projects' && args[1] === 'readwrite') throw new DOMException('Synthetic storage failure', 'QuotaExceededError'); return transaction.apply(this, args); }; }); - await page.getByRole('button', { name: 'Learn by doing', exact: true }).click(); await page.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); + await page.getByRole('button', { name: 'Learn by doing', exact: true }).click(); await page.getByRole('button', { name: 'Try it with me', exact: true }).click(); await page.locator('.learning-intro [role=alert]').filter({ hasText: 'Your current work could not be saved' }).waitFor(); assert.equal(await coach(page).count(), 0); assert.deepEqual((await state(page)).model, beforeState.model); await page.evaluate(() => window.restoreProjectWrites()); - await start(page); await page.getByRole('button', { name: 'Back to my previous project', exact: true }).click(); await ready(page); + await start(page); await page.getByRole('button', { name: 'Back to my previous project', exact: true }).click(); await coach(page).waitFor({ state: 'detached' }); await ready(page); const returned = await download(page, 'returned-custom'); assert.equal(returned.id, before.id); assert.deepEqual(returned.model, before.model); assert.deepEqual((await state(page)).result, beforeState.result); assert.equal(await page.getByRole('button', { name: /^Undo / }).getAttribute('aria-label'), undoLabel); await page.getByRole('button', { name: /^Undo / }).click(); assert.equal((await download(page, 'original-undone')).model.resources.find(pool => pool.id === 'specialists').capacity, 2); await saved(page); await start(page); // Simulate a newer valid save from another tab while practice is open. await page.evaluate(id => new Promise((resolve, reject) => { const r = indexedDB.open('queuelab-projects', 2); r.onerror = () => reject(r.error); r.onsuccess = () => { const db = r.result, tx = db.transaction('projects', 'readwrite'), get = tx.objectStore('projects').get(id); get.onsuccess = () => { const record = get.result, p = JSON.parse(record.payload); p.name = 'Newer synthetic project'; p.revision++; tx.objectStore('projects').put({ ...record, revision: p.revision, payload: JSON.stringify(p) }); }; tx.oncomplete = () => { db.close(); resolve(); }; tx.onabort = () => { db.close(); reject(tx.error); }; }; }), before.id); - await page.getByRole('button', { name: 'Back to my previous project', exact: true }).click(); await ready(page); + await page.getByRole('button', { name: 'Back to my previous project', exact: true }).click(); await coach(page).waitFor({ state: 'detached' }); await ready(page); assert.equal((await download(page, 'newer-return')).name, 'Newer synthetic project'); assert.equal(await page.getByRole('button', { name: /^Undo / }).count(), 0); await c.context.close(); checks.push('A failed preservation write blocks practice; original project, result and Undo survive practice; a newer externally saved original is reopened without stale history'); @@ -122,18 +140,18 @@ try { await page.locator('.template-save button[type=submit]').waitFor(); await page.evaluate(() => { const transaction = IDBDatabase.prototype.transaction; window.restoreTemplateWrites = () => { IDBDatabase.prototype.transaction = transaction; }; IDBDatabase.prototype.transaction = function (...args) { if (this.name === 'loopset-templates' && args[1] === 'readwrite') throw new DOMException('Synthetic quota', 'QuotaExceededError'); return transaction.apply(this, args); }; }); await page.locator('.template-save button[type=submit]').click(); await page.locator('.templates-panel [role=alert]').waitFor(); - await stage(page, 'save'); assert.equal(await page.locator('.learning-saved').count(), 0); assert.equal(await page.locator('[data-template-id]').count(), 0); + await stage(page, 'save'); assert.equal(await page.locator('.learning-saved').count(), 0); assert.equal(await templateCount(page), 0); await page.evaluate(() => window.restoreTemplateWrites()); await page.locator('.template-save button[type=submit]').click(); await stage(page, 'complete'); await c.context.close(); checks.push('A failed IndexedDB template write cannot complete the lesson or claim a save; native retry succeeds'); } phase = 'cancelled and failed practice loading'; { const c = await fresh(1440, true); page = c.page; const before = await download(page, 'before-load-failure'); await page.route('**/templates/service.json?*', route => route.fulfill({ status: 503, body: 'Unavailable' })); - await page.getByRole('button', { name: 'Learn by doing', exact: true }).click(); await page.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); + await page.getByRole('button', { name: 'Learn by doing', exact: true }).click(); await page.getByRole('button', { name: 'Try it with me', exact: true }).click(); await page.locator('.learning-intro [role=alert]').waitFor(); await page.unroute('**/templates/service.json?*'); let release, seen; const gate = new Promise(resolve => { release = resolve; }), requested = new Promise(resolve => { seen = resolve; }); await page.route('**/templates/service.json?*', async route => { seen(); await gate; await route.fulfill({ contentType: 'application/json', body: await fs.readFile('public/templates/service.json', 'utf8') }).catch(() => {}); }); - await page.getByRole('button', { name: 'Start my first experiment', exact: true }).click(); await requested; + await page.getByRole('button', { name: 'Try it with me', exact: true }).click(); await requested; await page.keyboard.press('Escape'); await page.getByRole('dialog').waitFor({ state: 'detached' }); release(); await page.locator('.studio-world-picker select').selectOption('blank'); await page.waitForFunction(() => JSON.parse(window.render_game_to_text()).workspaceMode === 'layout'); const blank = await download(page, 'after-cancelled-load'); assert.deepEqual(blank.model.nodes, []); assert.notEqual(blank.id, before.id); @@ -142,13 +160,22 @@ try { } phase = 'independent exploration'; { const c = await fresh(); page = c.page; await start(page); await change(page); - await page.getByRole('button', { name: /^Undo / }).click(); await stage(page, 'edit'); - const stations = page.getByRole('spinbutton', { name: 'Parallel stations', exact: true }); await stations.fill('4'); await stations.press('Enter'); await stage(page, 'off-track'); + await page.getByRole('button', { name: 'Show the full workspace', exact: true }).click(); + await cap(page).fill('invalid'); + await page.waitForFunction(() => document.querySelector('[data-learning-resume]')?.disabled); + await cap(page).press('Escape'); + await openPanel(page, 'worlds'); await page.locator('[data-learning-resume]').click(); + await page.getByRole('dialog').waitFor({ state: 'detached' }); await stage(page, 'run'); + await page.getByRole('button', { name: 'Show the full workspace', exact: true }).click(); + await page.getByRole('button', { name: /^Undo / }).click(); + await page.locator('.facility-canvas-tools').getByRole('button', { name: 'Steps', exact: true }).click(); + await page.getByRole('button', { name: 'Inspect Specialists', exact: true }).click(); + const stations = page.getByRole('spinbutton', { name: 'Parallel stations', exact: true }); await stations.fill('4'); await stations.press('Enter'); await page.locator('[data-learning-resume]').click(); await stage(page, 'off-track'); const different = await download(page, 'independent-idea'); await page.getByRole('button', { name: 'Leave guide', exact: true }).click(); assert.deepEqual((await download(page, 'after-leave')).model, different.model); await saved(page); await page.reload(); await ready(page); assert.equal(await page.locator('[data-panel=learn],.learning-coach').count(), 0); - await c.context.close(); checks.push('Undo returns to the relevant task; unrelated model edits are preserved and leaving the guide never resets them'); + await c.context.close(); checks.push('Native drafts block resume until applied/cancelled; resume closes advanced dialogs; Undo returns to the relevant task; unrelated model edits are preserved and leaving the guide never resets them'); } } assert.deepEqual(errors, []); const receipt = { passed: true, at: new Date().toISOString(), origin: origin.href, browser: browser.version(), scope, checks, errors }; diff --git a/src/App.tsx b/src/App.tsx index c070843..145f6b8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -184,6 +184,7 @@ export default function App() { const singleCoupling = useMemo(() => baseline && shownResult && baseline.provenance && shownResult.provenance ? buildCouplingManifest(baseline, shownResult) : null, [baseline, shownResult]); const singlePaired = Boolean(baseline && shownResult && singleCoupling?.compatibility.sameExternalDemand && singleCoupling.compatibility.sameMeasurementPolicies && baseline.demandHash === shownResult.demandHash); const learningActive = Boolean(learning && learning.projectId === project.id); + const learningFocused = learningActive && !learningMinimized; const lessonStage: LearningStage | null = learningActive ? learningStage({ session: learning!, project, baseline, result: shownResult, pending: pendingEdits, running: sim.running, valid: !hasErrors, comparable: singlePaired }) : null; const learningComparison = Boolean(learningActive && learningRunMatches(baseline, learning!.baseHash, learning!.seed) && learningRunMatches(shownResult, learning!.changedHash, learning!.seed) && singlePaired); const frame = useMemo(() => frameAt(visualProject, shownResult, time), [visualProject, shownResult, time]); @@ -236,6 +237,16 @@ export default function App() { setLearningStarting(false); setLearningError(null); updateLearning(null); learningReturn.current = null; rememberLearningWelcome(); } + function toggleLearningGuide() { + const next = !learningMinimized, origin = document.activeElement, id = live.current.project.id; + if (!next) setPanel(null); + const surface = panelGeneration.current; + setLearningMinimized(next); + requestAnimationFrame(() => { + if (live.current.project.id !== id || surface !== panelGeneration.current || focusChangedSince(origin)) return; + document.querySelector(next ? '[data-learning-resume]' : '[data-learning-toggle]')?.focus(); + }); + } function setPanel(next: Panel, opener?: HTMLElement | null, keepExperimentContext = false) { if (currentPanel.current === 'learn' && next !== 'learn') { rememberLearningWelcome(); ++learningRequest.current; learningAbort.current?.abort(); learningAbort.current = null; setLearningStarting(false); @@ -272,7 +283,7 @@ export default function App() { runPresentations.current.set(r, capturePresentation(p)); setResult(r); if (establishBaseline || !baseline) setBaseline(r); const coverage = replayManifest(r).coverage; - setTime(establishBaseline ? Math.min(p.model.horizon * .38, coverage.at(-1)?.end ?? 0) : 0); + setTime(establishBaseline || (lesson?.projectId === p.id && !learningMinimized) ? Math.min(p.model.horizon * .38, coverage.at(-1)?.end ?? 0) : 0); setPlaying(establishBaseline && coverage.length > 0 && !currentPanel.current && learningRef.current?.projectId !== p.id); manualClock.current = false; const current = live.current.project; const earlier = !sameNumericalSnapshot( @@ -295,7 +306,7 @@ export default function App() { )) return; const lesson = learningRef.current; if (lesson?.projectId === current.id && learningModelMatches(current, lesson) && learningRunMatches(completed, lesson.changedHash, lesson.seed) && learningRunMatches(baseline, lesson.baseHash, lesson.seed)) patchLearning({ ran: true, reviewed: false }); - setPanel('compare', opener); + if (lesson?.projectId !== current.id || learningMinimized) setPanel('compare', opener); return completed; } function cancelCalculation() { @@ -447,14 +458,14 @@ export default function App() { if (elements.length) elements[next].focus(); return; } - if (panel || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || !(event.target instanceof Element) || !event.target.closest('.world-workspace') || (event.target instanceof HTMLElement && ['INPUT', 'SELECT', 'TEXTAREA', 'SUMMARY', 'A'].includes(event.target.tagName))) return; + if (learningFocused || panel || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || !(event.target instanceof Element) || !event.target.closest('.world-workspace') || (event.target instanceof HTMLElement && ['INPUT', 'SELECT', 'TEXTAREA', 'SUMMARY', 'A'].includes(event.target.tagName))) return; if (event.code === 'Space' && live.current.canReplay && !(event.target instanceof HTMLButtonElement)) { event.preventDefault(); manualClock.current = false; setPlaying(p => !p); } if (event.key.toLowerCase() === 'g') { event.preventDefault(); document.querySelector('.world-scene')?.dispatchEvent(new Event('queuelab:focus')); } if (event.key.toLowerCase() === 'f') { event.preventDefault(); if (document.fullscreenElement) void document.exitFullscreen(); else void document.querySelector('.world-workspace')?.requestFullscreen?.().catch(() => setToast(m.fullScreenIsUnavailableInThisBrowser)); } }; document.addEventListener('keydown', keyboard); return () => { document.removeEventListener('keydown', keyboard); }; - }, [panel, linkFrom, moving, objectDetailsOpen, buildTrayOpen]); + }, [panel, linkFrom, moving, objectDetailsOpen, buildTrayOpen, learningFocused]); useEffect(() => { if (!toast) return; const id = setTimeout(() => setToast(null), 6000); return () => clearTimeout(id); }, [toast]); // Adopt a document's inspector before it can receive input. A deferred reset // can otherwise overwrite a Tools choice made just after the new world appears. @@ -478,9 +489,9 @@ export default function App() { let handle = 0; const key = `${project.id}:${lessonStage}`; const active = document.activeElement; - const fromGuide = active === document.body || (active instanceof HTMLElement && Boolean(active.closest('.learning-coach,.learning-intro,[data-learning-target],[inert]') || active.matches('[data-panel-opener="learn"]'))); - const focus = lessonStage === 'review' ? document.querySelector('.learning-coach [data-learning-action]') : target; - if (fromGuide && focus?.matches('input,button,select') && !focus.matches(':disabled') && !['preparing', 'complete', 'off-track'].includes(lessonStage) && focusedLearningStep.current !== key) { + const fromGuide = active === document.body || (active instanceof HTMLElement && Boolean(active.closest('.learning-coach,.learning-intro,.station-label,[data-learning-target],[inert]') || active.matches('[data-panel-opener="learn"]'))); + const focus = ['review', 'complete'].includes(lessonStage) ? document.querySelector('[data-learning-heading]') : target; + if (fromGuide && focus?.matches('input,button,select,[data-learning-heading]') && !focus.matches(':disabled') && !['preparing', 'off-track'].includes(lessonStage) && focusedLearningStep.current !== key) { focusedLearningStep.current = key; const origin = document.activeElement, surface = panelGeneration.current; handle = requestAnimationFrame(() => { @@ -855,11 +866,11 @@ export default function App() { } finally { if (token === learningRequest.current) setLearningStarting(false); } } function learningSelector(stage: LearningStage): string | null { - if (stage === 'select') return `[data-learning-target="step-${LEARNING_STEP_ID}"]`; - if (stage === 'edit') return `[data-learning-target="capacity-${LEARNING_POOL_ID}"] input`; - if (stage === 'run') return currentPanel.current === 'compare' ? '.comparison-run' : '[data-learning-target="run"]'; - if (stage === 'review') return currentPanel.current === 'compare' ? '[data-learning-target="comparison-cost"]' : '[data-panel-opener="compare"]'; - if (stage === 'save') return currentPanel.current === 'worlds' ? '.template-save input' : '.studio-world-picker select'; + if (stage === 'select') return '.world-scene [data-station-id="station-b"]'; + if (stage === 'edit') return learningMinimized ? `[data-learning-target="capacity-${LEARNING_POOL_ID}"] input` : '[data-learning-team] input'; + if (stage === 'run') return learningMinimized ? '[data-learning-target="run"]' : '.learning-coach [data-learning-action]'; + if (stage === 'review') return '.learning-results'; + if (stage === 'save') return '.learning-coach .template-save input'; return null; } function focusLearningTarget(stage: LearningStage) { @@ -884,8 +895,8 @@ export default function App() { if (original) { original.name = lm.originalPlan; patchLearning({ ran: false, reviewed: false }); await compute(original, true); } return; } - if (lessonStage === 'select') { setPanel(null); setBuildTrayOpen(false); setLibraryTab('steps'); openStepList(); focusLearningTarget('select'); return; } - if (lessonStage === 'edit') { setPanel(null); setBuildTrayOpen(false); setLibraryTab('steps'); editSceneNode(LEARNING_STEP_ID); focusLearningTarget('edit'); return; } + if (lessonStage === 'select') { editSceneNode(LEARNING_STEP_ID); return; } + if (lessonStage === 'edit') { focusLearningTarget('edit'); return; } if (lessonStage === 'run') { if (!pendingEditsRef.current && !sim.running) { const opener = document.activeElement instanceof HTMLElement ? document.activeElement : document.querySelector('[data-learning-target="run"]'); @@ -894,13 +905,11 @@ export default function App() { return; } if (lessonStage === 'review') { - if (currentPanel.current !== 'compare') { setPanel('compare'); return; } if (!learningComparison || pendingEditsRef.current) return; - patchLearning({ reviewed: true }); openTemplates('save'); return; + patchLearning({ reviewed: true }); setPanel(null); return; } if (lessonStage === 'save') { - if (currentPanel.current === 'worlds' && templateIntent === 'save') focusLearningTarget('save'); - else openTemplates('save'); + focusLearningTarget('save'); } } function onLearningTemplateSaved(snapshot: Project, template: { id: string; name: string }) { @@ -969,12 +978,17 @@ export default function App() { requestAnimationFrame(() => document.querySelector(target === 'download' ? '.studio-save' : '.studio-command-actions .studio-primary')?.focus()); } const panelTitle = (surface: Exclude) => ({ worlds: m.chooseYourLittleWorld, compare: m.aBetterPlanStartsHere, model: m.insideYourModel, data: m.keepYourWorkShareYourFindings, experiments: m.runExperiments, insights: m.yourRunInDetail, budget: m.beforeYouCalculate, history: m.yourRecentActions, help: m.helpHeading, scenario: sx.scenario, view: sx.view, rename: sx.renameProject, search: sx.search, guide: sx.guide, brief: stm.brief, learn: lm.title }[surface]); - const learningCoach = learning && lessonStage ? void learningAction()} onMinimize={() => setLearningMinimized(value => !value)} onLeave={leaveLearning} onReturn={() => void returnFromLearning()} onFinishWithoutSave={finishLearningWithoutSave} /> : null; + const learningCoach = learning && lessonStage ? pool.id === LEARNING_POOL_ID)?.capacity ?? 2} installedCapacity={project.model.resources.find(pool => pool.id === LEARNING_POOL_ID)?.installedCapacity ?? 3} + onCapacityChange={capacity => { if (live.current.project.id !== project.id || learningRef.current?.projectId !== project.id) throw new Error(lm.noLongerOpen); edit(mutateProject(live.current.project, copy => { const pool = copy.model.resources.find(item => item.id === LEARNING_POOL_ID); if (pool) pool.capacity = capacity; }), lm.edit.title); }} + baseline={learningComparison ? baseline : null} result={learningComparison ? shownResult : null} error={learningError ?? (attemptMatchesDraft ? latestAttempt?.reason ?? lm.calculationIncomplete : null)} onAction={() => void learningAction()} onMinimize={toggleLearningGuide} onLeave={leaveLearning} onReturn={() => void returnFromLearning()} onFinishWithoutSave={finishLearningWithoutSave}> + {lessonStage === 'save' && } + : null; const draftSummary = layoutOnly ? tm.layoutMode : normalBudget ? sx.quickSummary(ease.duration(project.model.horizon), number(normalBudget.groups[0].arrivalsPerRun), normalBudget.groups[0].stochastic, project.model.resources.length) : sx.reviewInputs; - return
{ if (!storageReady) earlyInteraction.current = true; }} onKeyDownCapture={() => { if (!storageReady) earlyInteraction.current = true; }}> + return
{ if (!storageReady) earlyInteraction.current = true; }} onKeyDownCapture={() => { if (!storageReady) earlyInteraction.current = true; }}>
{ event.preventDefault(); setPanel(null); }}>{m.queueLab}. -

{sx.localProject}
+

{sx.localProject}
@@ -985,10 +999,11 @@ export default function App() {
{ chooseLibraryTab(tab); showBuildTray(element); }} onResults={element => setPanel('insights', element)} onTools={openTools} onView={element => setPanel('view', element)} /> - {!panel && learningActive && learningCoach} + {!panel && learningActive && learningMinimized && learningCoach}
+ {!panel && learningFocused &&
{learningCoach}
}
{pendingEdits &&

{sx.pendingEdits}

} @@ -1002,7 +1017,7 @@ export default function App() { {selection.ids.length > 1 &&
{m.selectionSummary(selection.ids.length, selectedStep?.label ?? m.step)}
} {linkFrom && selectedStep &&
node.id === linkFrom) ?? selectedStep} onChange={(next,label) => { edit(next,label); setLinkFrom(null); setConnectionPreview(null); }} onPreview={to => setConnectionPreview(previous => to ? { owner: 'tool', from: linkFrom, to } : previous?.owner === 'tool' ? null : previous)} />
}
-
{libraryTab === 'objects' ? fm.canvasTitle : fm.processTitle}

{project.name}

+
{lm.practiceBadge}

{lm.sceneTitle}

{lm.sceneCaption}

{libraryTab === 'objects' ? fm.canvasTitle : fm.processTitle}

{project.name}

@@ -1022,7 +1037,7 @@ export default function App() {
-

{m.buildingYourLittleWorld}

}> setPlaying(false)} project={visualProject} selectedFacilityId={facilitySelection} onSelectFacility={selectFacility} onMoveFacility={moveFacility} onDropAsset={droppedLibraryAsset} quality={quality} frame={frame} selected={selected} selectedIds={selection.ids} reducedMotion={reducedMotion} moving={moving && !hasErrors && !revisionExhausted} editable={!hasErrors && !revisionExhausted} flow={sceneFlow} onSelect={selectFromWorld} onMove={moveSelected} onCapacityChange={changeCapacity} onEditNode={editSceneNode} /> +

{m.buildingYourLittleWorld}

}> setPlaying(false)} project={visualProject} selectedFacilityId={facilitySelection} onSelectFacility={selectFacility} onMoveFacility={moveFacility} onDropAsset={droppedLibraryAsset} quality={quality} frame={frame} selected={selected} selectedIds={selection.ids} reducedMotion={reducedMotion} moving={moving && !hasErrors && !revisionExhausted && !learningFocused} editable={!hasErrors && !revisionExhausted && !learningFocused} flow={sceneFlow} onSelect={selectFromWorld} onMove={moveSelected} onCapacityChange={changeCapacity} onEditNode={editSceneNode} />
{selectedStep?.label ?? m.selectionEmpty}
{layoutOnly ?

{tm.layoutHint}

: <> @@ -1042,7 +1057,7 @@ export default function App() { {objectDetailsOpen && }
{storageError && } diff --git a/src/features/LearningGuide.tsx b/src/features/LearningGuide.tsx index f74ec57..df36b69 100644 --- a/src/features/LearningGuide.tsx +++ b/src/features/LearningGuide.tsx @@ -1,19 +1,22 @@ -import { useEffect, useRef } from 'react'; -import { ArrowRight, Check, Compass, ChevronDown, LoaderCircle, X } from 'lucide-react'; +import { useRef, type ReactNode } from 'react'; +import { ArrowRight, Check, Compass, ChevronDown, Clock3, LoaderCircle, Users, CircleCheck, X } from 'lucide-react'; import { assetURL } from '../assetUrl'; import { learningMessages as m } from '../ui/messages/learning'; import { learningStages, type LearningSession, type LearningStage } from './learning'; +import { NumberField } from './EditFields'; import type { RunResult } from '../model/types'; import './learning.css'; +function ExampleFlow() { + return
    {[Users, Clock3, CircleCheck].map((Icon, i) =>
  1. )}
; +} export function LearningIntro({ busy, blocked, error, onStart, onExplore, onReference }: { busy: boolean; blocked?: string; error?: string | null; onStart: () => void; onExplore: () => void; onReference: () => void; }) { return
-

{m.welcome}

{m.introduction}

-
    {m.welcomeSteps.map((step, i) =>
  1. {i + 1}{step}
  2. )}
+

{m.welcome}

{m.introduction}

{m.practiceScope}

{blocked &&

{blocked}

} {error &&

{error}

} @@ -22,38 +25,50 @@ export function LearningIntro({ busy, blocked, error, onStart, onExplore, onRefe
; } - +function LearningResults({ before, after }: { before: RunResult; after: RunResult }) { + const money = (value: number) => new Intl.NumberFormat('en', { style: 'currency', currency: after.model.currency, maximumFractionDigits: 0 }).format(value); + const cost = after.summary.cost - before.summary.cost; + const rows = [ + [m.completedLabel, String(before.summary.completed), String(after.summary.completed), m.completedChange(after.summary.completed - before.summary.completed)], + [m.waitLabel, m.waitValue(before.summary.meanWait), m.waitValue(after.summary.meanWait), m.waitChange(after.summary.meanWait - before.summary.meanWait)], + [m.costLabel, money(before.summary.cost), money(after.summary.cost), m.costChange(cost)], + ]; + return
{rows.map(([label, a, b, change]) =>

{label}

{m.before}
{a}

{change}

)}

{m.resultLesson}

{m.lessonScope}

; +} interface CoachProps { session: LearningSession; stage: LearningStage; minimized: boolean; busy: boolean; busyLabel?: string; pending: boolean; - comparisonOpen: boolean; saveOpen: boolean; baseline: RunResult | null; result: RunResult | null; error?: string | null; + capacity: number; installedCapacity: number; onCapacityChange: (value: number) => void; + baseline: RunResult | null; result: RunResult | null; error?: string | null; children?: ReactNode; onAction: () => void; onMinimize: () => void; onLeave: () => void; onReturn: () => void; onFinishWithoutSave: () => void; } export function LearningCoach(props: CoachProps) { - const { session, stage, minimized, busy, pending, comparisonOpen, saveOpen, baseline, result, error } = props; - const resume = useRef(null), toggle = useRef(null), toggled = useRef(false); - useEffect(() => { if (toggled.current) { toggled.current = false; (minimized ? resume.current : toggle.current)?.focus(); } }, [minimized]); + const { session, stage, minimized, busy, pending, baseline, result, error } = props; + const root = useRef(null); const index = stage === 'complete' ? 4 : Math.max(0, learningStages.findIndex(item => item === stage)); const caption = m.step(index + 1); - const minimize = () => { toggled.current = true; props.onMinimize(); }; - if (minimized) return ; + if (minimized) return ; const content = stage === 'off-track' ? m.offTrack : stage === 'complete' ? null : m[stage]; - const action = stage === 'complete' ? m.continue : stage === 'review' && !comparisonOpen ? m.openComparison : stage === 'save' && saveOpen ? m.save.action : content!.action; - const formatCost = (run: RunResult) => new Intl.NumberFormat('en', { style: 'currency', currency: run.model.currency, maximumFractionDigits: 0 }).format(run.summary.cost); - return ; } diff --git a/src/features/QuickProperties.tsx b/src/features/QuickProperties.tsx index d796531..4b11719 100644 --- a/src/features/QuickProperties.tsx +++ b/src/features/QuickProperties.tsx @@ -13,7 +13,7 @@ import { NumberField, TimeField, usePendingEdit } from './EditFields'; import { ScheduleEditor, Timeline } from './ScheduleEditor'; import { easeMessages as m } from '../ui/messages/ease'; -interface Props { teamHint?: { poolId: string; text: string }; project: Project; node: ModelNode; onChange: (project: Project, label?: string) => void; onAdvanced: () => void; result?: RunResult | null; onPreviewConnection?: (targetId: string | null) => void } +interface Props { project: Project; node: ModelNode; onChange: (project: Project, label?: string) => void; onAdvanced: () => void; result?: RunResult | null; onPreviewConnection?: (targetId: string | null) => void } interface ControlProps extends Props { commit: (next: Project, label: string) => void; attempt: (action: () => void) => void } const count = (v: number) => v.toLocaleString('en', { maximumFractionDigits: 3 }); const money = (v: number, currency: string) => { try { return new Intl.NumberFormat('en', { style: 'currency', currency, maximumFractionDigits: 2 }).format(v); } catch { return `${count(v)} ${currency}`; } }; @@ -56,14 +56,13 @@ function DistributionControl({ project, node, distribution, commit, patience = f {error &&

{error}

} ; } -function TeamControl({ project, pool, service, commit, hint }: { hint?: string; project: Project; pool: ResourcePool; service: ServiceNode; commit: ControlProps['commit'] }) { +function TeamControl({ project, pool, service, commit }: { project: Project; pool: ResourcePool; service: ServiceNode; commit: ControlProps['commit'] }) { const consumers = project.model.nodes.filter((node): node is ServiceNode => node.kind === 'service' && node.resources.some(req => req.poolId === pool.id)); const requirement = service.resources.find(req => req.poolId === pool.id)!; const change = (patch: Partial) => commit(mutateProject(project, copy => { Object.assign(copy.model.resources.find(item => item.id === pool.id)!, patch); }), m.teamChanged(pool.label)); const context = `${project.id}:${pool.id}`; return
{pool.label}{m.availableUnits(pool.capacity, pool.installedCapacity)}
- {hint &&

{hint}

} change({ capacity })} help={m.unitsPerStart(requirement.units)} />
{consumers.length > 1 &&

{m.usedBy(consumers.map(node => node.label).join(', '))}

} @@ -138,7 +137,7 @@ export function QuickProperties(props: Props) { const controls: ControlProps = { ...props, commit, attempt }; return
- {node.kind === 'service' && <>
commit(mutateProject(project, copy => { const target = copy.model.nodes.find(item => item.id === node.id); if (target?.kind === 'service') target.servers = servers; }), m.stationChanged(node.label))} />
{node.resources.length > 0 &&

{m.teamHeading}

{node.resources.map(requirement => { const pool = project.model.resources.find(item => item.id === requirement.poolId); return pool ? : null; })}
{m.capacityExplanation}

{m.capacityScope}

}} + {node.kind === 'service' && <>
commit(mutateProject(project, copy => { const target = copy.model.nodes.find(item => item.id === node.id); if (target?.kind === 'service') target.servers = servers; }), m.stationChanged(node.label))} />
{node.resources.length > 0 &&

{m.teamHeading}

{node.resources.map(requirement => { const pool = project.model.resources.find(item => item.id === requirement.poolId); return pool ? : null; })}
{m.capacityExplanation}

{m.capacityScope}

}} {node.kind === 'delay' && } {node.kind === 'source' && } {node.kind === 'queue' && } diff --git a/src/features/TemplatesPanel.tsx b/src/features/TemplatesPanel.tsx index b13c9f8..d0c23e3 100644 --- a/src/features/TemplatesPanel.tsx +++ b/src/features/TemplatesPanel.tsx @@ -5,6 +5,7 @@ import { StarterGallery } from './StarterGallery'; import type { StarterId } from '../templates/catalogue'; import { EmptyState } from '../ui/EmptyState'; import { templateMessages as m } from '../ui/messages/templates'; +import { learningMessages as lm } from '../ui/messages/learning'; import { listTemplates, loadTemplate, removeTemplate, saveTemplate } from '../storage/templateStore'; import { instantiateTemplate, TEMPLATE_LIMIT, type TemplateMetadata } from '../storage/templateFormat'; import { openProjectJSON, serializeProject } from '../storage/projectFile'; @@ -13,11 +14,11 @@ import './templates.css'; export type StarterTemplate = StarterId | 'blank'; interface Props { - project: Project; intent: 'browse' | 'save'; blockedReason?: string; saveBlockedReason?: string; + project: Project; intent: 'browse' | 'save'; saveOnly?: boolean; blockedReason?: string; saveBlockedReason?: string; onSaved?: (project: Project, template: TemplateMetadata) => void; onStarter: (template: StarterTemplate) => void | Promise; onUse: (project: Project) => boolean; } -export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReason, onStarter, onUse, onSaved }: Props) { +export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReason, onStarter, onUse, onSaved, saveOnly }: Props) { const [tab, setTab] = useState<'starters' | 'mine'>(intent === 'save' ? 'mine' : 'starters'); const [showSave, setShowSave] = useState(intent === 'save'); const [failedStarter, setFailedStarter] = useState(null); @@ -31,7 +32,14 @@ export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReas void listTemplates().then(rows => { if (current) { setItems(rows); setError(''); } }).catch(error => { if (current) setError(error instanceof Error ? error.message : m.storage); }).finally(() => { if (current) setLoading(false); }); return () => { current = false; alive.current = false; operation.current++; }; }, []); - useEffect(() => { if (intent === 'save') requestAnimationFrame(() => { if (alive.current) nameInput.current?.focus(); }); }, [intent]); + useEffect(() => { + if (intent !== 'save') return; + const origin = document.activeElement; + const frame = requestAnimationFrame(() => { + if (alive.current && (document.activeElement === origin || document.activeElement === document.body)) nameInput.current?.focus(); + }); + return () => cancelAnimationFrame(frame); + }, [intent]); async function perform(action: (current: () => boolean) => Promise, starter?: StarterTemplate) { if (busyRef.current) return; const token = ++operation.current; busyRef.current = true; setBusy(true); setError(''); setStatus(''); setFailedStarter(starter ?? null); @@ -61,7 +69,7 @@ export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReas } const matches = items.filter(item => item.name.toLocaleLowerCase('en').includes(query.trim().toLocaleLowerCase('en'))); const snapshot = imported ?? project; - return
+ return

{m.intro}

@@ -72,7 +80,7 @@ export function TemplatesPanel({ project, intent, blockedReason, saveBlockedReas {error &&

{error}

} {tab === 'starters' ? void perform(async () => { await onStarter(id); }, id)} /> : <> {showSave &&

{imported ? m.importReady : m.saveTitle}

{m.saveDescription}

{m.summary(snapshot.facility?.objects.length ?? 0, snapshot.model.nodes.length)}

-
{ event.preventDefault(); save(); }}>
+
{ event.preventDefault(); save(); }}>
{!imported && saveBlockedReason &&

{saveBlockedReason}

}
} diff --git a/src/features/learning.css b/src/features/learning.css index 5885366..06d3ed0 100644 --- a/src/features/learning.css +++ b/src/features/learning.css @@ -1,10 +1,17 @@ -.learning-intro{display:grid;grid-template-columns:minmax(240px,.85fr) minmax(340px,1fr);gap:30px;align-items:center}.learning-intro-visual{overflow:hidden;border-radius:16px;background:#e6ebdf;align-self:stretch;display:grid;place-items:center;min-height:320px}.learning-intro-visual img{width:145%;max-width:none;display:block}.learning-intro-copy h3{font-size:30px;line-height:1.14;letter-spacing:-1px;color:#173a2c;margin:0 0 16px}.learning-intro-copy>p{font-size:15px;line-height:1.6;color:#4b6556}.learning-overview{list-style:none;padding:0;margin:20px 0;display:grid;grid-template-columns:1fr 1fr;gap:10px}.learning-overview li{display:flex;align-items:center;gap:8px;font-size:12px;color:#294a32}.learning-overview li>span{display:grid;place-items:center;flex:none;width:22px;height:22px;background:#e4efd7;border-radius:50%;font-size:11px;font-weight:700}.learning-scope{font-size:12px!important;line-height:1.6;color:#52664e}.learning-intro-actions{display:flex;flex-direction:column;gap:9px;margin-top:22px}.learning-primary,.learning-secondary{display:inline-flex;align-items:center;justify-content:center;gap:10px;min-height:44px;padding:12px 17px;border-radius:8px;border:1px solid #173a2c;font:inherit;font-size:13px;font-weight:650;cursor:pointer}.learning-primary{background:#173a2c;color:#fff}.learning-primary:hover:not(:disabled){background:#28573c}.learning-secondary{background:transparent;color:#173a2c;border-color:#cad8c1}.learning-primary:disabled,.learning-secondary:disabled{opacity:.55;cursor:default}.learning-text-button{background:none;border:0;padding:8px 0;color:#426339;text-decoration:underline;text-underline-offset:3px;font:inherit;font-size:12px;cursor:pointer;text-align:left}.learning-text-button:disabled{opacity:.55;cursor:default}.learning-intro-copy>.learning-text-button{display:block;margin:7px auto 0}.learning-feedback{font-size:12px!important;color:#785315!important}.learning-error{font-size:13px!important;color:#a0372b!important;line-height:1.5}.learning-coach{flex:none;padding:16px 26px 18px;background:#f2f7e9;color:#173a2c;border-bottom:1px solid #cad8bc;animation:learning-enter .2s ease-out}.learning-coach-top{display:flex;justify-content:space-between;align-items:center;font-size:11px;font-weight:700;letter-spacing:.3px}.learning-coach-top>span{display:flex;gap:7px;align-items:center}.learning-coach-top>div{display:flex;gap:5px}.learning-coach-top button{display:grid;place-items:center;min-width:32px;min-height:32px;background:transparent;border:0;border-radius:6px;color:#3d5b39;cursor:pointer}.learning-coach-top button:hover{background:#e0ecd3}.learning-progress{padding:0;margin:3px 0 14px;display:flex;gap:22px;list-style:none;max-width:690px}.learning-progress li{display:flex;align-items:center;gap:6px;color:#586d4f;font-size:11px;white-space:nowrap}.learning-progress li>span:first-child{display:grid;place-items:center;width:21px;height:21px;border-radius:50%;border:1px solid #bccbb1;font-size:10px;transition:background .18s,color .18s}.learning-progress .is-current{font-weight:750;color:#173a2c}.learning-progress .is-current>span:first-child{background:#173a2c;color:#fff;border-color:#173a2c}.learning-progress .is-done>span:first-child{background:#d4e9bb;border-color:#c2dca5;color:#25482c}.learning-coach-main{display:flex;align-items:center;gap:32px;justify-content:space-between}.learning-coach-main>div:first-child{max-width:780px}.learning-coach h3{margin:0 0 5px;font-size:23px;line-height:1.2;letter-spacing:-.6px}.learning-coach-main p{font-size:13px;line-height:1.6;margin:0;color:#415b39}.learning-step-caption{display:none}.learning-coach-actions{display:flex;align-items:flex-end;flex-direction:column;gap:2px;flex-shrink:0}.learning-coach-actions .learning-primary{min-width:180px}.learning-coach-actions .learning-text-button{text-align:right}.learning-mini{flex:none;background:#f2f7e9;border-bottom:1px solid #cad8bc;padding:9px 26px}.learning-mini button{display:flex;align-items:center;gap:10px;background:none;border:0;color:#173a2c;min-height:32px;font:inherit;font-size:12px;cursor:pointer}.learning-mini button>span{font-size:11px;color:#52664e;margin-left:8px}.learning-coach :is(button,a):focus-visible,.learning-mini button:focus-visible,.learning-intro :is(button,a):focus-visible{outline:3px solid #537b3c;outline-offset:3px}.learning-saved{display:flex;align-items:center;gap:7px;margin-top:10px!important;font-weight:650}.learning-outcomes{display:flex;gap:32px;margin:18px 0 10px;padding-top:16px;border-top:1px solid #cad8bc;flex-wrap:wrap}.learning-outcomes dt{font-size:11px;color:#52664e;margin-bottom:5px}.learning-outcomes dd{margin:0;display:flex;align-items:center;gap:10px;font-size:22px}.learning-outcomes dd>span{color:#586c4d}.learning-outcomes dd strong{font-weight:750}.learning-target{outline:3px solid #608b43!important;outline-offset:4px!important;scroll-margin:170px 20px 90px;box-shadow:0 0 0 7px #c5e99555!important;border-radius:6px}.modal-body>.learning-coach{margin:-20px -20px 22px;padding:12px 20px 18px;border-radius:0}.modal-body>.learning-mini{margin:-20px -20px 20px}.facility-studio .modal[data-panel=learn]{width:min(940px,calc(100vw - 40px))}.guided-comparison .comparison-disclosure,.guided-comparison .saved-scenarios,.guided-comparison .decision-guide,.guided-comparison .comparison-note,.guided-comparison .comparison-table .table-header small,.guided-comparison .comparison-advanced-action{display:none!important} -@keyframes learning-enter{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}} -@media(max-width:900px){.learning-intro{grid-template-columns:1fr}.learning-intro-visual{min-height:0;height:170px}.learning-intro-visual img{width:100%;max-width:600px}.learning-intro-copy h3{font-size:25px}.learning-coach-main{gap:18px}.learning-coach-actions .learning-primary{min-width:0}.learning-progress{gap:12px}.learning-coach{padding:12px 18px 16px}} -@media(max-width:740px){.learning-coach{padding:10px 16px 14px;position:sticky;top:0;z-index:35}.learning-coach-top{min-height:26px}.learning-progress{margin:3px 0 10px;gap:9px}.learning-progress li>span:last-child{display:none}.learning-progress li>span:first-child{width:22px;height:22px}.learning-step-caption{display:block;font-size:10px;font-weight:700;margin-bottom:4px;color:#52664e}.learning-coach h3{font-size:19px}.learning-coach-main{display:block}.learning-coach-main p{font-size:12px;line-height:1.5}.learning-coach-actions{margin-top:12px;align-items:stretch;gap:4px}.learning-coach-actions .learning-primary{width:100%;min-height:42px}.learning-coach-actions .learning-text-button{text-align:left;padding:5px 0}.learning-mini{padding:8px 12px}.learning-mini button{gap:7px;font-size:11px}.learning-mini button>span{font-size:10px;margin-left:0}.learning-outcomes{gap:16px}.learning-outcomes dd{font-size:18px;gap:6px}.learning-intro{gap:18px}.learning-intro-visual{height:135px}.learning-intro-copy>p{font-size:14px}.learning-overview{margin:16px 0;gap:8px}.learning-overview li{font-size:11px}.learning-intro-actions{margin-top:16px}.modal-body>.learning-coach{position:relative;top:auto;margin:-20px -20px 18px;padding:10px 16px 14px}.modal-body>.learning-mini{margin:-20px -20px 18px}.learning-target{scroll-margin-top:285px}.facility-studio .modal[data-panel=learn]{width:calc(100vw - 24px)}} -@media(prefers-reduced-motion:reduce){.learning-coach{animation:none}.learning-progress li>span:first-child{transition:none}} -.learning-reduced-motion .learning-coach{animation:none}.learning-reduced-motion .learning-progress li>span:first-child{transition:none} +.learning-intro{display:grid;grid-template-columns:1fr 1fr;gap:32px;align-items:center}.learning-intro-visual{overflow:hidden;border-radius:16px;background:#e6ebdf;display:grid;place-items:center;min-height:340px}.learning-intro-visual img{width:135%;max-width:none;display:block}.learning-intro-copy h3{font-size:30px;line-height:1.15;letter-spacing:-.8px;color:#173a2c;margin:0 0 16px}.learning-intro-copy>p{font-size:16px;line-height:1.6;color:#4b6556}.learning-scope{font-size:12px!important;line-height:1.6;color:#52664e}.learning-intro-actions{display:flex;flex-direction:column;gap:9px;margin-top:22px}.learning-primary,.learning-secondary{display:inline-flex;align-items:center;justify-content:center;gap:10px;min-height:46px;padding:13px 17px;border-radius:8px;border:1px solid #173a2c;font:inherit;font-size:14px;font-weight:650;cursor:pointer}.learning-primary{background:#173a2c;color:#fff}.learning-primary:hover:not(:disabled){background:#28573c}.learning-secondary{background:transparent;color:#173a2c;border-color:#cad8c1}.learning-primary:disabled,.learning-secondary:disabled{opacity:.55;cursor:default}.learning-text-button{background:none;border:0;padding:10px 0;color:#426339;text-decoration:underline;text-underline-offset:3px;font:inherit;font-size:12px;cursor:pointer;text-align:left;line-height:1.5}.learning-text-button:disabled{opacity:.55;cursor:default}.learning-intro-copy>.learning-text-button{display:block;margin:7px auto 0}.learning-feedback{font-size:12px!important;color:#785315!important}.learning-error{font-size:13px!important;color:#a0372b!important;line-height:1.5} +.learning-example-flow{display:flex;list-style:none;margin:24px 0;padding:0;gap:24px}.learning-example-flow li{position:relative;flex:1;display:flex;flex-direction:column;align-items:flex-start;gap:10px;font-size:12px;color:#426339;line-height:1.5}.learning-flow-arrow{position:absolute;right:-14px;top:4px;color:#849774} +.learning-coach{padding:24px;background:#fbfdf7;color:#173a2c;animation:learning-enter .2s ease-out}.learning-coach-top{display:flex;justify-content:space-between;align-items:center;font-size:12px;font-weight:650;gap:10px}.learning-coach-top>span{display:flex;gap:7px;align-items:center}.learning-coach-top>div{display:flex;gap:3px}.learning-coach-top button{display:grid;place-items:center;min-width:36px;min-height:40px;background:transparent;border:0;border-radius:6px;color:#3d5b39;cursor:pointer}.learning-coach-top button:hover{background:#e0ecd3}.learning-coach-top button:disabled{opacity:.4;cursor:default}.learning-progress{height:4px;margin:20px 0 25px;border-radius:4px;background:#e2e9d9;overflow:hidden}.learning-progress>span{height:100%;display:block;background:#608b43;transition:width .2s ease-out}.learning-step-caption{display:block;font-size:11px;font-weight:650;margin-bottom:10px;color:#52664e}.learning-coach h3{margin:0 0 14px;font-size:28px;line-height:1.2;letter-spacing:-.7px}.learning-coach-main>p{font-size:15px;line-height:1.7;margin:0 0 16px;color:#415b39}.learning-coach-actions{display:flex;flex-direction:column;gap:6px;margin-top:24px}.learning-coach-actions .learning-primary{width:100%}.learning-coach .learning-example-flow{margin:26px 0}.learning-mini{flex:none;background:#f2f7e9;border-bottom:1px solid #cad8bc;padding:9px 24px}.learning-mini button{display:flex;align-items:center;gap:10px;background:none;border:0;color:#173a2c;min-height:34px;font:inherit;font-size:12px;cursor:pointer}.learning-mini button>span{font-size:11px;color:#52664e;margin-left:8px}.learning-coach :is(button,a,input):focus-visible,.learning-mini button:focus-visible,.learning-intro :is(button,a):focus-visible{outline:3px solid #537b3c;outline-offset:3px} +.learning-team{margin:24px 0 0;padding:20px 0;border-block:1px solid #dce5d3}.learning-team .ease-field>label{font-size:14px;font-weight:650;color:#294a32}.learning-team input{background:#fff!important;color:#173a2c!important;font-size:30px!important;font-weight:650;min-height:62px!important;padding:12px 16px!important;border:1px solid #a7bf97!important;border-radius:8px;max-width:100%}.learning-team .ease-number-reading{display:none}.learning-team small{font-size:12px;color:#52664e}.learning-team .learning-scope{margin-bottom:0}.learning-applied{display:flex;align-items:center;gap:8px;padding:16px;background:#e9f3db;border-radius:8px;font-weight:650}.learning-saved{display:flex;align-items:flex-start;gap:8px;font-weight:650;padding:16px;background:#e9f3db;border-radius:8px}.learning-saved svg{flex:none}.learning-next{margin-top:24px;border-top:1px solid #dce5d3;padding-top:18px}.learning-next h4{font-size:15px;margin:0 0 8px}.learning-next p{font-size:14px;line-height:1.7;color:#415b39;margin:0} +.learning-results{margin-top:24px}.learning-result{padding:18px 0;border-top:1px solid #dce5d3}.learning-result h4{margin:0 0 13px;font-size:14px;font-weight:650}.learning-result dl{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:0}.learning-result dt{font-size:10px;color:#6a7b61;margin-bottom:7px}.learning-result dd{font-size:26px;line-height:1.2;letter-spacing:-.5px;margin:0}.learning-result dl>div:last-child dd{color:#315f25;font-weight:750}.learning-result>p{font-size:12px;font-weight:650;color:#426339;margin:13px 0 0}.learning-result-explanation{font-size:14px;line-height:1.7;color:#415b39;margin:20px 0 12px} +.learning-target{outline:3px solid #608b43!important;outline-offset:4px!important;scroll-margin:90px 20px;box-shadow:0 0 0 7px #c5e99555!important;border-radius:6px}.learning-results.learning-target{outline:none!important;box-shadow:none!important}.learning-scene-heading{display:none}.learning-focused .learning-scene-heading{display:block;position:absolute;top:32px;left:32px;z-index:3;pointer-events:none}.learning-scene-heading>span{font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:#52664e}.learning-scene-heading h2{font-size:25px;margin:10px 0 8px;letter-spacing:-.5px}.learning-scene-heading p{font-size:13px;color:#52664e;margin:0} +.learning-dock{order:2;flex:0 0 390px;width:390px;min-width:0;overflow:auto;border-left:1px solid #d7e1cf;overscroll-behavior:contain;scrollbar-width:thin}.learning-focused .studio-main{order:1;min-width:0}.learning-focused :is(.facility-workflow,.studio-header .studio-world-picker,.studio-header .studio-command-actions,.studio-library-dock,.studio-inspector,.studio-context,.quality-world-brief,.facility-canvas-tools,.studio-flow-disclosure,.quality-mobile-selection,.scene-camera-tools,.playback-controls,.studio-playback,.studio-control-deck,.studio-replay-row,.studio-metrics,.ease-pending-banner){display:none!important}.learning-focused .studio-header .studio-project-name{pointer-events:none}.learning-focused .scene-area{min-height:420px;flex:1}.learning-focused .station-label:not([data-station-id="station-b"]){display:none!important}.learning-focused .scene-label-layer .station-label[data-station-id="station-b"]{min-height:44px;font-size:14px;border:2px solid #608b43;box-shadow:0 0 0 6px #c5e99566}.learning-focused .workspace-footer>span:last-child{display:none}.learning-focused .studio-world{flex:1}.learning-focused .scene-area .world-scene{height:100%}.learning-focused .studio-body{min-height:0}.learning-focused .studio-project{flex:1} +.learning-save-panel> :not(.template-save):not(.ql-error):not(.template-status):not([role=status]){display:none!important}.learning-save-panel .template-save{margin:20px 0 0;padding:0;border:0;background:none}.learning-save-panel .template-save> :not(form){display:none!important}.learning-save-panel .template-save form{display:flex;flex-direction:column;gap:16px}.learning-save-panel .template-save label{font-size:13px;color:#294a32}.learning-save-panel .template-save input{font-size:15px;min-height:46px;background:#fff;color:#173a2c}.learning-save-panel .template-save button[type=submit]{min-height:46px;background:#173a2c;color:#fff;justify-content:center}.learning-save-panel .template-status{font-size:12px}.learning-save-panel .ql-error{margin:16px 0}.modal-body>.learning-coach{border:1px solid #d7e1cf;border-radius:12px;margin-bottom:24px} +@keyframes learning-enter{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:none}} +@media(max-width:1000px){.learning-dock{width:350px;flex-basis:350px}.learning-coach{padding:20px}.learning-coach h3{font-size:25px}.learning-intro{gap:22px}.learning-intro-copy h3{font-size:26px}} +@media(max-width:740px){.learning-intro{grid-template-columns:1fr;gap:20px}.learning-intro-visual{height:140px;min-height:0}.learning-intro-visual img{width:100%;max-width:500px}.learning-intro-copy h3{font-size:25px}.learning-intro-copy>p{font-size:14px}.learning-intro-actions{margin-top:16px}.learning-example-flow{margin:20px 0;gap:22px}.learning-example-flow li{font-size:11px;gap:8px}.learning-focused .studio-body{display:flex;flex-direction:column;overflow:visible}.learning-focused .studio-main{order:0;flex:none}.learning-dock{order:1;width:100%;flex:none;overflow:visible;border-left:0;border-top:1px solid #d7e1cf}.learning-focused .scene-area{height:250px;min-height:250px}.learning-focused .learning-scene-heading{top:16px;left:20px}.learning-scene-heading h2{font-size:20px;margin:6px 0}.learning-scene-heading p{font-size:11px}.learning-focused:has(.learning-coach:not([data-learning-stage="select"])) .studio-main{display:none}.learning-coach{padding:20px 22px 26px}.learning-coach h3{font-size:25px}.learning-coach-main>p{font-size:14px}.learning-progress{margin:12px 0 20px}.learning-coach-top button{min-width:40px}.learning-coach-actions{margin-top:20px}.learning-mini{padding:8px 12px}.learning-mini button{gap:7px;font-size:11px}.learning-mini button>span{font-size:10px;margin-left:0}.learning-focused .studio-header{min-height:60px}.learning-focused .studio-project{display:none}.learning-focused .workspace-footer{display:none}} +@media(prefers-reduced-motion:reduce){.learning-coach{animation:none}.learning-progress>span{transition:none}} +.learning-reduced-motion .learning-coach{animation:none}.learning-reduced-motion .learning-progress>span{transition:none} -.facility-studio .studio-inspector .learning-field-hint{margin:8px 0 12px;padding:10px 12px;background:#edf5e2;border-left:3px solid #608b43;color:#25482c;font-size:12px;font-weight:600;line-height:1.5} +.learning-focused .studio-brand>span{display:inline!important} -@media(max-width:359px){.modal-body>.learning-coach,.modal-body>.learning-mini{margin-top:-17px;margin-left:-17px;margin-right:-17px}} +.learning-coach [data-learning-heading]:focus{outline:none} diff --git a/src/features/learning.ts b/src/features/learning.ts index c4c2788..bdc8a8c 100644 --- a/src/features/learning.ts +++ b/src/features/learning.ts @@ -24,7 +24,12 @@ export function createLearningSession(project: Project, returnProjectId: string } export function learningModelMatches(project: Project, session: LearningSession): boolean { - return project.id === session.projectId && project.model.seed === session.seed && [session.baseHash, session.changedHash].includes(modelHash(project.model)); + if (project.id !== session.projectId || project.model.seed !== session.seed) return false; + const original = structuredClone(project.model); + const pool = original.resources.find(item => item.id === LEARNING_POOL_ID); + if (!pool) return false; + pool.capacity = 2; + return modelHash(original) === session.baseHash; } export function originalLearningProject(project: Project, session: LearningSession): Project | null { if (!learningModelMatches(project, session)) return null; diff --git a/src/ui/messages/App.ts b/src/ui/messages/App.ts index c611e4b..0055725 100644 --- a/src/ui/messages/App.ts +++ b/src/ui/messages/App.ts @@ -140,11 +140,11 @@ export const appMessages = { watchDemos: "Watch the video demos", watchDemosNewTab: "Watch the video demos (opens in a new tab)", freeOpenSource: "FREE & OPEN SOURCE ", - earlyBuild: "RC15", + earlyBuild: "RC16", syntheticExample: "SYNTHETIC EXAMPLE", openProject: "Open project", saveProject: "Download project JSON", - buildBadge: "V1 / RC15", + buildBadge: "V1 / RC16", aPlaygroundForBetterDecisions: "A PLAYGROUND FOR BETTER DECISIONS", calculationWorkLimits: "Calculation work & limits", calculationProgress: (percent: number) => `${percent}% calculating`, diff --git a/src/ui/messages/learning.ts b/src/ui/messages/learning.ts index 218e23d..ca970eb 100644 --- a/src/ui/messages/learning.ts +++ b/src/ui/messages/learning.ts @@ -1,42 +1,48 @@ export const learningMessages = { - title: 'Make your first experiment', section: 'LEARN BY DOING', entry: 'Learn by doing', - welcome: 'What happens if one more specialist joins the team?', - introduction: 'Find the busy step, change its shared team, and compare the real result. Five small steps will take you through your first real simulation.', - practiceScope: 'We will open a separate Service Studio practice project. Your current project is kept before switching.', - welcomeSteps: ['Choose a step', 'Change the team', 'Run the plan', 'Read the trade-off', 'Keep your version'], - start: 'Start my first experiment', starting: 'Preparing your practice…', explore: 'Explore on my own', reference: 'Just show me the controls', - waiting: 'Wait for the current calculation to finish, or close this guide and cancel it.', - pending: 'Apply or cancel the unfinished field first. Your draft stays here.', - opening: 'Opening project…', - storageWaiting: 'Opening your saved workspace…', - practiceName: 'My first experiment', originalPlan: 'Original plan', changedPlan: 'Your experiment', - startFailed: 'The practice project could not open. Your current project is still here. Try again.', - starterChanged: 'This starter no longer matches the exercise. You can still explore its template normally.', + title: 'Your first example', section: 'LEARN BY DOING', entry: 'Learn by doing', + welcome: 'Can one extra person reduce the wait?', + introduction: 'Loopset lets you try a change and see what happens. Let’s try it with a small help desk.', + practiceScope: 'You will use a separate practice copy. Your own project stays safe.', + welcomeSteps: ['People ask for help', 'They wait for the team', 'The team helps them'], + start: 'Try it with me', starting: 'Opening your example…', explore: 'Explore on my own', reference: 'Just show me the controls', + waiting: 'The current calculation is finishing. You can start in a moment.', + pending: 'Finish the field first: apply your change, or press Escape to cancel it.', + opening: 'Opening project…', storageWaiting: 'Opening your saved workspace…', + practiceName: 'My first experiment', originalPlan: 'Before the change', changedPlan: 'With one extra person', + startFailed: 'We could not open the example. Your project is still here. Try again.', + starterChanged: 'This example has changed and no longer fits the lesson. You can explore it from Templates.', preservationFailed: 'Your current work could not be saved. Keep it open or download a backup before starting practice.', - returnFailed: 'The previous project could not be reopened. Your current practice is still here.', - returnMissing: 'That project is no longer available in this browser. Open Files to find your saved work or keep exploring this practice.', - coach: 'Guided experiment', progress: 'Experiment progress', step: (n: number) => `Step ${n} of 5`, - labels: { select: 'Choose', edit: 'Change', run: 'Run', review: 'Compare', save: 'Keep' }, - select: { title: 'Find the Specialists step', text: 'Requests arrive, wait, and move through the team. Select Specialists in the scene or the Steps list to see what controls its capacity.', action: 'Open the Steps list' }, - edit: { title: 'Give the shared team one more unit', text: 'In Shared specialists, change Base available units from 2 to 3. Press Enter to apply it. The parallel stations can stay as they are.', action: 'Show the team setting' }, - run: { title: 'Now test your changed plan', text: 'Run & compare calculates a new result. Your original plan remains the baseline. The Play control only replays recorded work.', action: 'Run & compare' }, - review: { title: 'Read the whole trade-off', text: 'Look at completed work, waiting and resource cost together. Decide whether the change is worth its cost in this model.', action: 'Keep this version' }, - save: { title: 'Make this a reusable starting point', text: 'Give your plan a name and choose Save template. It will appear in My templates, ready to use as a new project.', action: 'Save as template' }, - preparing: { title: 'Calculating the original plan', text: 'This gives your experiment a real baseline. The next step will be ready when the calculation completes.', action: 'Wait for the result' }, - baseline: { title: 'Prepare the original comparison', text: 'This exercise needs a completed original plan. Calculate it again to continue; your changed draft stays intact.', action: 'Calculate original plan' }, - offTrack: { title: 'You are exploring a different idea', text: 'Other model inputs changed, so this is no longer the one-team exercise. Keep exploring, or start a fresh practice project. Your current version is kept.', action: 'Start a fresh practice' }, - fieldHint: 'Change 2 to 3, then press Enter to apply.', - running: 'Calculating your plan…', applyField: 'Apply or cancel the field to continue.', - calculationIncomplete: 'The calculation did not finish. Your original result is kept; try the changed plan again.', - openComparison: 'Open the comparison', - pause: 'Minimize guide', resume: 'Resume guided experiment', leave: 'Leave guide', return: 'Back to my previous project', - finishWithoutSave: 'Finish without saving a template', - completed: 'You made a real experiment.', - completedText: 'You chose a step, changed one assumption, ran the model and compared the outcome. That is the loop you can use for your own ideas.', - saved: (name: string) => `Template saved: ${name}`, - notSaved: 'No template was saved. You can save one later or download project JSON to keep an editable copy.', - continue: 'Explore this project', + returnFailed: 'We could not reopen your previous project. Your practice copy is still here.', + returnMissing: 'Your previous project is no longer in this browser. Open Files to find your saved work.', + coach: 'Let’s try it together', progress: 'Lesson progress', step: (n: number) => `Step ${n} of 5`, + labels: { select: 'Meet the example', edit: 'Add a person', run: 'Try it', review: 'See the result', save: 'Keep it' }, + select: { title: 'First, choose the help desk', text: 'People arrive with a request, wait, and get help. The desk marked Specialists is where we will make one small change.', action: 'Choose Specialists' }, + edit: { title: 'Let’s add one person', text: 'There are 2 people on the shared team. Change the number below to 3, then choose Apply change.', action: 'Apply change' }, + run: { title: 'Ready. Let’s see what happens.', text: 'You changed the team from 2 people to 3. Now Loopset will work out how many requests the team can handle in one hour.', action: 'Try this change' }, + review: { title: 'Here is what changed', text: 'Same hour. Same requests. Only the team size changed. Here is the result.', action: 'Got it. Next' }, + save: { title: 'Want to keep your example?', text: 'Save it as a template: a starting point you can open and change again later.', action: 'Save my example' }, + preparing: { title: 'Getting your example ready', text: 'We are checking what happens with the original team of 2 people.', action: 'Getting ready…' }, + baseline: { title: 'Let’s check the starting point', text: 'We need the result for 2 people before we can compare. Your change will stay here.', action: 'Check the original team' }, + offTrack: { title: 'You tried a different change', text: 'This lesson changes only the shared team. Your idea is kept. Start a fresh example to follow the lesson, or leave the guide to keep exploring.', action: 'Start a fresh practice' }, + noLongerOpen: 'This practice copy is no longer open. Reopen the lesson to continue.', + teamLabel: 'People on this team', teamHelp: 'Type 3, then choose Apply change. Enter works too.', + applied: 'Applied: 2 → 3 people', running: 'Trying your change…', applyField: 'Choose Apply change, or press Escape to cancel the field.', + calculationIncomplete: 'That calculation did not finish. Your change is kept. Try it again.', + openComparison: 'See my result', pause: 'Show the full workspace', resume: 'Continue my lesson', leave: 'Leave guide', return: 'Back to my previous project', + finishWithoutSave: 'Finish without saving a template', completed: 'You know the basic loop.', + completedText: 'Change one thing. Try it. Check the result. You can use these same steps with your own ideas.', + saved: (name: string) => `Saved in My templates: ${name}`, + notSaved: 'No template was saved. This practice project can still be downloaded or saved later.', + continue: 'Open the full workspace', templateName: 'Name your example', saveButton: 'Save my example', saving: 'Saving your example…', + before: 'Before · 2 people', after: 'After · 3 people', waitValue: (seconds: number) => `${(seconds / 60).toFixed(1)} min`, - completedLabel: 'Completed requests', waitLabel: 'Average wait', costLabel: 'Resource cost', - lessonScope: 'Synthetic practice model. Results depend on the inputs; resource cost is not total business cost.', + completedLabel: 'Requests helped', waitLabel: 'Average time waiting', costLabel: 'Cost of the teams', + completedChange: (n: number) => `${Math.abs(n)} ${n >= 0 ? 'more' : 'fewer'} requests helped`, + waitChange: (seconds: number) => `${(Math.abs(seconds) / 60).toFixed(1)} min ${seconds <= 0 ? 'less' : 'more'} waiting`, + costChange: (amount: number) => amount > 0 ? 'The larger team costs more' : amount < 0 ? 'Lower team cost' : 'The team cost is unchanged', + resultLesson: 'A larger team can reduce waiting, but also costs more. Loopset helps you compare both.', + lessonScope: 'This is a made-up example. These are modeled team costs, not all business expenses.', + sceneTitle: 'A small help desk', sceneCaption: 'Requests arrive → people wait → the team helps', + practiceBadge: 'Practice mode', nextStep: 'Next, try your own idea', + nextStepText: 'Use Templates for another example or an empty site. Build facility arranges the space; Define process changes how the work happens.', } as const; diff --git a/tests/learning.test.ts b/tests/learning.test.ts index 0142140..09943f5 100644 --- a/tests/learning.test.ts +++ b/tests/learning.test.ts @@ -50,6 +50,17 @@ describe('learn-by-doing progression', () => { expect(createLearningSession(e.project, null)).toBeNull(); expect(learningStage({ ...e, valid: false })).toBe('off-track'); }); + it('lets a learner correct a different team size without discarding the exercise', () => { + const e = exercise(); e.session.selected = true; + for (const capacity of [0, 4, 12]) { + e.project.model.resources.find(pool => pool.id === 'specialists')!.capacity = capacity; + const snapshot = structuredClone(e.project); + expect(learningModelMatches(e.project, e.session)).toBe(true); + expect(learningStage(e)).toBe('edit'); + expect(originalLearningProject(e.project, e.session)!.model).toEqual(e.original.model); + expect(e.project).toEqual(snapshot); + } + }); it('keeps completion separate from saving a template', () => { const e = exercise(); e.session.finished = true; expect(learningStage(e)).toBe('complete'); expect(e.session.savedName).toBeUndefined();