dsh-3d-magic-house 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
package/docs/ideas.png ADDED
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-3d-magic-house",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "3D 魔法屋 — a five-step print workshop for a child: find an idea, size it in a 3D view, queue it, watch the printer, collect stars. Bambu Lab P2S, LAN read-only.",
6
6
  "license": "MIT",
@@ -39,6 +39,7 @@
39
39
  "data/ideas.json",
40
40
  "locale/*.json",
41
41
  "icon.svg",
42
+ "docs",
42
43
  "README.md",
43
44
  "README.zh.md",
44
45
  "LICENSE",
@@ -54,9 +54,11 @@ function createElement(type, props, ...children) {
54
54
  return { type, props: nextProps }
55
55
  }
56
56
 
57
- function cellsFor(path) {
58
- if (!instances.has(path)) instances.set(path, { cells: [], index: 0 })
59
- return instances.get(path)
57
+ // Cells are keyed by component identity + tree position, so a page swap that
58
+ // reuses the same position for a different component does not cross its state.
59
+ function cellsFor(key) {
60
+ if (!instances.has(key)) instances.set(key, { cells: [], index: 0 })
61
+ return instances.get(key)
60
62
  }
61
63
 
62
64
  function nextCell(path, init) {
@@ -70,7 +72,7 @@ function nextCell(path, init) {
70
72
  const pending = { effects: [] }
71
73
 
72
74
  function useState(initial) {
73
- const path = currentPass.path
75
+ const path = currentPass.key
74
76
  const at = cellsFor(path).index
75
77
  const cell = nextCell(path, () => ({
76
78
  value: typeof initial === 'function' ? initial() : initial,
@@ -86,11 +88,11 @@ function useState(initial) {
86
88
  }
87
89
 
88
90
  function useRef(initial) {
89
- return nextCell(currentPass.path, () => ({ current: initial }))
91
+ return nextCell(currentPass.key, () => ({ current: initial }))
90
92
  }
91
93
 
92
94
  function useEffect(run, deps) {
93
- const path = currentPass.path
95
+ const path = currentPass.key
94
96
  const cell = nextCell(path, () => ({ ran: false, deps: undefined, cleanup: undefined }))
95
97
  const changed = !cell.ran || deps === undefined || !sameDeps(cell.deps, deps)
96
98
  if (!changed) return
@@ -120,13 +122,11 @@ function renderNode(node, path, out) {
120
122
  }
121
123
  const { type, props } = node
122
124
  if (typeof type === 'function') {
123
- const instance = cellsFor(path)
124
- if (process.env.P2S_PATHS === '1' && /Model3D|PrinterCard|Section/.test(type.name || '')) {
125
- console.log('PATH', type.name, JSON.stringify(path), 'cells=', instance.cells.length)
126
- }
125
+ const key = (type.name || 'anonymous') + '@' + path
126
+ const instance = cellsFor(key)
127
127
  instance.index = 0
128
128
  const previous = currentPass
129
- currentPass = { path, dirty: previous ? previous.dirty : false }
129
+ currentPass = { path, key, dirty: previous ? previous.dirty : false }
130
130
  let rendered
131
131
  try {
132
132
  rendered = type(props)
@@ -273,71 +273,8 @@ console.log('MARK: rendering')
273
273
  const out = []
274
274
  await renderTree({ type: panel.component, props: { t: (key) => key } }, out)
275
275
  const text = out.join('\n')
276
- console.log('MARK: rendered', text.length)
277
-
278
- const expectationsLive = [
279
- ['flow rail step 1', '找灵感'],
280
- ['flow rail step 3', '排好队'],
281
- ['flow rail step 5', '收星星'],
282
- ['active banner', '现在在做'],
283
- ['3D volume', '192.0 cm³'],
284
- ['3D solid grams', '238 g'],
285
- ['3D fits', '装得下'],
286
- ['3D hint', '拖动旋转'],
287
- ['printer pill', '已连接'],
288
- ['printer live state', '打印中'],
289
- ['printer progress', '63%'],
290
- ['printer job', '乌龟存钱罐'],
291
- ['printer temps', '219.4℃'],
292
- ['progress sketch label', '进度示意'],
293
- ['panel title', '3D魔法屋'],
294
- ['star count from the board', '3'],
295
- ['spinner heading', '创意转盘'],
296
- ['a shipped idea card', '名字钥匙扣'],
297
- ['all ten cards', '夜光灯罩'],
298
- ['board heading', '我的清单'],
299
- ['a saved project', '会发光的恐龙'],
300
- ['stage buttons', '建模'],
301
- ['checklist item', '打印前检查'],
302
- ['checked item copy', 'PEI 打印板装好了'],
303
- ['safety block', '安全四条'],
304
- ['offline disclaimer', '不会发送任何打印任务'],
305
- ['done step renders', '完成的作品'],
306
- ]
307
-
308
- const expectationsOffline = [
309
- ['readable route failure', 'HTTP 404'],
310
- ['retry affordance', '再试一次'],
311
- ['idea fallback copy', '暂时没有灵感卡'],
312
- ['panel still renders', '创意转盘'],
313
- ['safety still renders', '安全四条'],
314
- ['printer step still renders', '开打'],
315
- ['printer setup form survives', '保存并连接'],
316
- ['3D view still renders', '拖动旋转'],
317
- ]
318
- const missing = (offline ? expectationsOffline : expectationsLive)
319
- .filter(([, needle]) => !text.includes(needle))
320
- .map(([label]) => label)
321
- if (process.env.P2S_DEBUG === '1') {
322
- const at = text.indexOf('体积')
323
- console.log('DEBUG_HUD', JSON.stringify(text.slice(Math.max(0, at - 120), at + 200)))
324
- console.log('DEBUG_CANVAS', JSON.stringify(canvasDraw))
325
- }
326
- if (missing.length > 0) {
327
- throw new Error('panel output is missing: ' + missing.join(', ') + '\n--- rendered ---\n' + text.slice(0, 3000))
328
- }
329
- if (!calls.some(([url]) => url.includes('/api/magic-house/state'))) throw new Error('the panel never read the board route')
330
- if (!calls.some(([url]) => url.includes('/api/magic-house/ideas'))) throw new Error('the panel never read the ideas route')
331
- if (!offline && !calls.some(([url]) => url.includes('/api/magic-house/printer'))) throw new Error('the panel never read the printer route')
332
-
333
- if (!offline) {
334
- if (canvasDraw.moveTo === 0 || canvasDraw.lineTo === 0) throw new Error('the 3D canvas never drew a line')
335
- if (canvasDraw.fill < 6) throw new Error('the 3D canvas painted too few faces: ' + canvasDraw.fill)
336
- console.log('PASS 3D canvas drew', canvasDraw.moveTo, 'moves,', canvasDraw.lineTo, 'lines,', canvasDraw.fill, 'fills')
337
- }
338
-
276
+ const root = { type: panel.component, props: { t: (key) => key } }
339
277
 
340
- // ── interactions ──────────────────────────────────────────────────────────
341
278
  function textOf(node) {
342
279
  if (node === null || node === undefined || node === false) return ''
343
280
  if (typeof node === 'string' || typeof node === 'number') return String(node)
@@ -345,124 +282,190 @@ function textOf(node) {
345
282
  return node.props ? textOf(node.props.children) : ''
346
283
  }
347
284
 
348
- function buttons(label) {
349
- return hosts.filter(entry => entry.type === 'button' && textOf(entry) === label && typeof entry.props.onClick === 'function')
285
+ function buttons(label, filter) {
286
+ return hosts.filter(entry => entry.type === 'button'
287
+ && textOf(entry).includes(label)
288
+ && typeof entry.props.onClick === 'function'
289
+ && (!filter || filter(entry)))
350
290
  }
351
291
 
352
- const root = { type: panel.component, props: { t: (key) => key } }
292
+ async function goTab(page) {
293
+ const tab = hosts.find(entry => entry.type === 'button' && entry.props.role === 'tab' && textOf(entry).includes(page))
294
+ if (!tab) throw new Error('no tab named ' + page + ' in ' + JSON.stringify(hosts.filter(e => e.props.role === 'tab').map(e => textOf(e))))
295
+ tab.props.onClick()
296
+ await renderTree(root, out)
297
+ return out.join('\n')
298
+ }
299
+
300
+ function expectAll(view, list, where) {
301
+ const missing = list.filter(([label, needle]) => !view.includes(needle)).map(([label]) => label)
302
+ if (missing.length > 0) {
303
+ throw new Error(`${where} is missing: ${missing.join(', ')}\n--- rendered ---\n` + view.slice(0, 2200))
304
+ }
305
+ }
306
+
307
+ // ── the page shell and the overview page ─────────────────────────────────
308
+ expectAll(text, [
309
+ ['panel title', '3D魔法屋'],
310
+ ['nav tabs', '总览'],
311
+ ['nav ideas tab', '灵感'],
312
+ ['nav design tab', '设计'],
313
+ ['nav projects tab', '作品'],
314
+ ['nav printer tab', '打印机'],
315
+ ['overview hero', '现在在做'],
316
+ ['overview stats', '星星'],
317
+ ['next step card', '下一步'],
318
+ ['device mini', '设备'],
319
+ ], 'the overview page')
353
320
 
354
321
  if (offline) {
322
+ expectAll(text, [['route failure banner', 'HTTP 404']], 'the offline overview')
323
+ const ideas = await goTab('灵感')
324
+ expectAll(ideas, [['idea fallback', '暂时没有灵感卡'], ['spinner still there', '创意转盘']], 'the offline ideas page')
325
+ const design = await goTab('设计')
326
+ expectAll(design, [['viewport chrome', '视口'], ['build volume label', '256 × 256 × 256 mm']], 'the offline design page')
327
+ if (canvasDraw.fill < 6) throw new Error('the 3D canvas did not paint the default solid')
328
+ const projectsPage = await goTab('作品')
329
+ expectAll(projectsPage, [['board heading', '我的清单'], ['checklist', '打印前检查'], ['safety', '安全四条']], 'the offline projects page')
330
+ const printer = await goTab('打印机')
331
+ expectAll(printer, [['console', '设备控制台'], ['setup form', '保存并连接'], ['offline state', '未配置']], 'the offline printer page')
355
332
  if (posts.length !== 0) throw new Error('an unreachable board must not post')
356
- console.log('PASS 404 route: banner shows the status, panel stays on screen, no phantom save')
357
- console.log('PASS banner text:', JSON.stringify(out.join(' ').match(/HTTP 404[^。]*/)?.[0] ?? 'n/a'))
333
+ console.log('PASS offline: banner shows the status, every page still renders, no phantom save')
358
334
  process.exit(0)
359
335
  }
360
336
 
361
- // 1) Type a title into the board and press Add.
362
- const input = hosts.find(entry => entry.type === 'input' && entry.props.type === 'text')
363
- if (!input) throw new Error('the board has no title input')
364
- input.props.onChange({ target: { value: '火星探测器' } })
365
- await renderTree(root, out)
366
- if (buttons('加进清单').length === 0) throw new Error('no Add button rendered')
367
- buttons('加进清单').at(-1).props.onClick({})
368
- await renderTree(root, out)
369
- let now = out.join('\n')
370
- if (!now.includes('火星探测器')) throw new Error('the typed project did not reach the board')
371
- if (posts.length === 0) throw new Error('the panel never posted the board')
372
- if (!JSON.stringify(posts.at(-1)).includes('火星探测器')) throw new Error('the posted body lacks the new project')
373
-
374
- // 2) Advance the newest project to Done: one more star.
375
- if (buttons('完成').length === 0) throw new Error('no stage button rendered')
376
- buttons('完成')[0].props.onClick()
377
- await renderTree(root, out)
378
- now = out.join('\n')
379
- if (!now.includes('4 颗星星')) throw new Error('reaching Done did not add a star, saw: ' + now.slice(now.indexOf('⭐') - 40, now.indexOf('⭐') + 20))
337
+ expectAll(text, [
338
+ ['active project in hero', '会发光的恐龙'],
339
+ ['device connected', '已连接'],
340
+ ['live progress ring', '63'],
341
+ ['live state caption', '打印中'],
342
+ ['star badge', '3'],
343
+ ], 'the live overview page')
344
+ if (canvasDraw.fill !== 0) throw new Error('the overview page must not paint the 3D canvas')
345
+ console.log('PASS overlay: five tabs, hero, stats, device mini with a live ring')
346
+
347
+ // ── ideas page ───────────────────────────────────────────────────────────
348
+ let view = await goTab('灵感')
349
+ expectAll(view, [
350
+ ['spinner', '创意转盘'],
351
+ ['first card', '名字钥匙扣'],
352
+ ['tenth card', '夜光灯罩'],
353
+ ['difficulty filter', '难度'],
354
+ ], 'the ideas page')
380
355
 
381
- // 3) A stage that is already Done must not add another star.
382
- buttons('完成')[0].props.onClick()
383
- await renderTree(root, out)
384
- now = out.join('\n')
385
- if (!now.includes('4 颗星星')) throw new Error('re-clicking Done added a second star')
386
-
387
- // 4) Hand an idea card to the AI.
388
356
  const ask = buttons('让 AI 帮我想')
389
- if (ask.length < 2) throw new Error('idea cards render no AI button')
357
+ if (ask.length < 2) throw new Error('the ideas page renders no per-card AI button')
390
358
  ask[1].props.onClick()
391
359
  if (startSessionArgs === null) throw new Error('the AI button never called uiWorkspace.startSession')
392
- const [workspaceArg, options] = startSessionArgs
393
- if (workspaceArg !== undefined) throw new Error('startSession should fall back to the active workspace')
394
- if (!options || !options.prompt || !options.prompt.includes('名字钥匙扣')) {
395
- throw new Error('the AI prompt does not carry the idea: ' + JSON.stringify(options).slice(0, 200))
396
- }
397
- if (options.whenDraftExists !== 'append') throw new Error('the AI handoff does not append to an existing draft')
398
-
399
- // 5) Toggle a checklist box and confirm it is persisted.
400
- const boxes = hosts.filter(entry => entry.type === 'input' && entry.props.type === 'checkbox')
401
- if (boxes.length !== 6) throw new Error('expected 6 checklist boxes, saw ' + boxes.length)
402
- const before = posts.length
403
- boxes[1].props.onChange()
404
- await renderTree(root, out)
405
- if (posts.length === before) throw new Error('ticking a checklist box did not post the board')
406
- if (posts.at(-1).state.checks.filament !== true) throw new Error('the checklist change was not posted')
360
+ const [, options] = startSessionArgs
361
+ if (!options.prompt || !options.prompt.includes('名字钥匙扣')) throw new Error('the AI prompt lost the idea')
362
+ if (options.whenDraftExists !== 'append') throw new Error('the AI handoff does not append to a draft')
363
+ console.log('PASS ideas: cards render, the AI handoff carries the card into a new session')
364
+
365
+ // ── design page ──────────────────────────────────────────────────────────
366
+ const beforeDrawing = canvasDraw.fill
367
+ view = await goTab('设计')
368
+ if (canvasDraw.fill <= beforeDrawing) throw new Error('the design page never painted the canvas')
369
+ expectAll(view, [
370
+ ['viewport label', '视口'],
371
+ ['default volume', '192.0 cm³'],
372
+ ['solid grams', '238 g'],
373
+ ['fits', '装得下'],
374
+ ['context strip', '会发光的恐龙'],
375
+ ], 'the design page')
407
376
 
408
- // ── 3D interactions ──────────────────────────────────────────────────────
409
377
  const lengthInput = hosts.find(entry => entry.type === 'input' && entry.props.type === 'number' && entry.props['aria-label'] === '长')
410
- if (!lengthInput) throw new Error('the 3D card has no length input')
378
+ if (!lengthInput) throw new Error('the design page has no length input')
411
379
  lengthInput.props.onChange({ target: { value: '300' } })
412
380
  await renderTree(root, out)
413
- now = out.join('\n')
414
- if (!now.includes('720.0 cm³')) throw new Error('the box volume did not follow the new length')
415
- if (!now.includes('超出打印范围')) throw new Error('an oversized design was not flagged')
416
- if (!now.includes('+44 mm')) throw new Error('the oversize amount is not stated')
417
- console.log('PASS 3D: 300 mm length flags 超出打印范围 +44 mm and recomputes 720.0 cm³')
381
+ view = out.join('\n')
382
+ expectAll(view, [['oversized volume', '720.0 cm³'], ['oversize warning', '超出打印范围'], ['oversize amount', '+44 mm']], 'the oversized design')
418
383
 
419
384
  const sphereButton = hosts.find(entry => entry.type === 'button' && textOf(entry) === '球')
420
385
  if (!sphereButton) throw new Error('no sphere shape button')
421
386
  sphereButton.props.onClick()
422
387
  await renderTree(root, out)
423
- now = out.join('\n')
424
- if (!now.includes('377.0 cm³')) throw new Error('the sphere volume is wrong: ' + (now.match(/[\d.]+ cm³/) || [])[0])
425
- console.log('PASS 3D: switching to a sphere recomputes 377.0 cm³')
388
+ view = out.join('\n')
389
+ expectAll(view, [['sphere volume', '377.0 cm³']], 'the sphere design')
390
+ console.log('PASS design: viewport paints, 300 mm flags 超出打印范围 +44 mm, the sphere recomputes 377.0 cm³')
426
391
 
427
- const addSize = hosts.find(entry => entry.type === 'button' && textOf(entry) === '用这个尺寸')
428
- if (!addSize) throw new Error('no apply-size button (the active project should offer 用这个尺寸)')
429
- addSize.props.onClick()
392
+ const applySize = buttons('用这个尺寸')[0]
393
+ if (!applySize) throw new Error('the design page offers no 用这个尺寸 action for the active project')
394
+ applySize.props.onClick()
395
+ await renderTree(root, out)
396
+ const sized = posts.at(-1).state
397
+ const stored = (sized.projects || []).find(project => project.size)
398
+ if (!stored || stored.size.shape !== 'sphere' || stored.size.w !== 300) throw new Error('the size did not land on the active project')
399
+ if (stored.status !== 'design') throw new Error('applying a size should move an idea to design, got ' + stored.status)
400
+ console.log('PASS design: the size is stored on the active project and the stage advances')
401
+
402
+ // ── projects page ────────────────────────────────────────────────────────
403
+ view = await goTab('作品')
404
+ expectAll(view, [
405
+ ['board heading', '我的清单'],
406
+ ['saved project', '会发光的恐龙'],
407
+ ['stage buttons', '建模'],
408
+ ['checklist', '打印前检查'],
409
+ ['checked copy', 'PEI 打印板装好了'],
410
+ ['safety', '安全四条'],
411
+ ['size on the row', '球 300×60×40 mm'],
412
+ ], 'the projects page')
413
+
414
+ const titleInput = hosts.find(entry => entry.type === 'input' && entry.props.type === 'text')
415
+ if (!titleInput) throw new Error('the board has no title input')
416
+ titleInput.props.onChange({ target: { value: '火星探测器' } })
430
417
  await renderTree(root, out)
431
- const sized = posts.at(-1)
432
- const storedSize = (sized.state.projects || []).find(project => project.size)
433
- if (!storedSize) throw new Error('the applied size did not land on any project')
434
- if (storedSize.size.shape !== 'sphere' || storedSize.size.w !== 300) throw new Error('stored size is wrong: ' + JSON.stringify(storedSize.size))
435
- // The fixture's active project was already marked Done above; applying a size
436
- // must never pull a project back a stage.
437
- if (storedSize.status !== 'done') throw new Error('applying a size regressed the stage: ' + storedSize.status)
438
- if (!out.join('\n').includes('球 300×60×40 mm')) throw new Error('the board row does not show the stored size')
439
- console.log('PASS 3D: the size lands on the active project and shows as 球 300×60×40 mm')
440
-
441
- // Picking another project becomes the flow's active one.
418
+ buttons('加进清单').at(-1).props.onClick({})
419
+ await renderTree(root, out)
420
+ view = out.join('\n')
421
+ if (!view.includes('火星探测器')) throw new Error('the typed project did not reach the board')
422
+ if (!JSON.stringify(posts.at(-1)).includes('火星探测器')) throw new Error('the posted body lacks the new project')
423
+
424
+ buttons('完成')[0].props.onClick()
425
+ await renderTree(root, out)
426
+ view = out.join('\n')
427
+ if (!view.includes('4 颗星星')) throw new Error('reaching Done did not add a star')
428
+ buttons('完成')[0].props.onClick()
429
+ await renderTree(root, out)
430
+ if (!out.join('\n').includes('4 颗星星')) throw new Error('re-clicking Done added a second star')
431
+ console.log('PASS projects: add, stage advance, exactly one star per finished print')
432
+
442
433
  const activate = hosts.filter(entry => entry.type === 'button' && textOf(entry) === '做这个' && entry.props.disabled !== true)
443
434
  if (activate.length === 0) throw new Error('no enabled 做这个 button')
444
435
  activate[0].props.onClick()
445
436
  await renderTree(root, out)
446
- const activated = posts.at(-1).state
447
- if (typeof activated.activeId !== 'string' || activated.activeId === '') throw new Error('做这个 did not post an activeId')
448
- now = out.join('\n')
449
- if (!now.includes('乌龟存钱罐')) throw new Error('the banner does not name the newly active project')
450
- console.log('PASS flow: 做这个 switches the active project and the header follows')
451
-
452
- // ── printer control ──────────────────────────────────────────────────────
453
- const disconnect = hosts.find(entry => entry.type === 'button' && textOf(entry) === '断开')
437
+ if (typeof posts.at(-1).state.activeId !== 'string') throw new Error('做这个 did not post an activeId')
438
+ console.log('PASS projects: 做这个 switches the active project')
439
+
440
+ const boxes = hosts.filter(entry => entry.type === 'input' && entry.props.type === 'checkbox')
441
+ if (boxes.length !== 6) throw new Error('expected 6 checklist boxes, saw ' + boxes.length)
442
+ const postsBefore = posts.length
443
+ boxes[1].props.onChange()
444
+ await renderTree(root, out)
445
+ if (posts.length === postsBefore) throw new Error('ticking a checklist box did not post the board')
446
+ if (posts.at(-1).state.checks.filament !== true) throw new Error('the checklist change was not posted')
447
+ console.log('PASS projects: checklist writes through')
448
+
449
+ // ── printer page ─────────────────────────────────────────────────────────
450
+ view = await goTab('打印机')
451
+ expectAll(view, [
452
+ ['console title', '设备控制台'],
453
+ ['online pill', '已连接'],
454
+ ['job name', '乌龟存钱罐'],
455
+ ['ring progress', '63'],
456
+ ['nozzle readout', '219'],
457
+ ['layer readout', '30/48'],
458
+ ['read-only note', '局域网 MQTT · 只读'],
459
+ ], 'the printer page')
460
+
461
+ const disconnect = buttons('断开')[0]
454
462
  if (!disconnect) throw new Error('no disconnect button on a configured printer')
455
463
  disconnect.props.onClick()
456
464
  await renderTree(root, out)
457
465
  if (JSON.stringify(posts.at(-1)) !== JSON.stringify({ action: 'disconnect' })) {
458
466
  throw new Error('disconnect posted the wrong body: ' + JSON.stringify(posts.at(-1)))
459
467
  }
460
- console.log('PASS printer: disconnect posts the action and never the access code')
461
-
462
- const plan = text.replace(/\s+/g, ' ')
463
- console.log('PASS add project from the input -> board and POST body')
464
- console.log('PASS Done stage awards exactly one star (', 4, ')')
465
- console.log('PASS AI handoff prompt:', JSON.stringify(options.prompt.split('\n')[1]).slice(0, 90))
466
- console.log('PASS checklist write-through ( posts =', posts.length, ')')
467
- console.log('PASS sample:', plan.slice(plan.indexOf('创意转盘'), plan.indexOf('创意转盘') + 200))
468
+ console.log('PASS printer: console shows job, ring, temperatures and layers; disconnect posts no secret')
469
+
470
+ console.log('PASS all pages:', ['总览', '灵感', '设计', '作品', '打印机'].join(' → '))
468
471
  process.exit(0)