counter.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // Interactive Counter — a tldraw offline document script.
  2. //
  3. // HOW TO RUN IT ON YOUR MACHINE:
  4. // 1. Open tldraw offline, create or open a document.
  5. // 2. Develop → Reveal Script… (creates script/main.js + a workspace folder)
  6. // 3. Replace the contents of script/main.js with THIS file, and save.
  7. // 4. The app reruns the script automatically. You'll see a "Counter" panel
  8. // with MINUS / RESET / PLUS buttons — click them; the number updates live.
  9. // 5. File → Save to persist the script into the .tldraw file. Now the file
  10. // *is* a little app: reopen it anywhere and the buttons still work.
  11. //
  12. // This is the document-script contract (from the app's script-context.d.ts):
  13. // export default function ({ editor, helpers, signal }) { ... }
  14. // editor — the live tldraw Editor
  15. // helpers — editor-bound conveniences (richTextToPlainText, etc.)
  16. // signal — an AbortSignal fired before the script reruns / on close;
  17. // register ALL cleanup on it so re-saving never leaks listeners.
  18. import { createShapeId, toRichText } from 'tldraw'
  19. export default function ({ editor, helpers, signal }) {
  20. // Stable ids => idempotent: re-running reuses shapes instead of duplicating.
  21. const IDS = {
  22. title: createShapeId('counter-title'),
  23. display: createShapeId('counter-display'),
  24. dec: createShapeId('counter-btn-dec'),
  25. reset: createShapeId('counter-btn-reset'),
  26. inc: createShapeId('counter-btn-inc'),
  27. }
  28. // Create-if-missing helper (leaves user edits intact on rerun).
  29. function ensure(partial) {
  30. if (editor.getShape(partial.id)) return
  31. editor.createShape(partial)
  32. }
  33. editor.run(() => {
  34. ensure({
  35. id: IDS.title, type: 'text', x: 40, y: 20,
  36. props: { richText: toRichText('Counter'), size: 'xl', font: 'draw', color: 'black' },
  37. })
  38. ensure({
  39. id: IDS.display, type: 'geo', x: 40, y: 80,
  40. props: { geo: 'rectangle', w: 360, h: 160, color: 'black', fill: 'none', richText: toRichText('0'), size: 'xl' },
  41. meta: { ui: 'display', count: 0 },
  42. })
  43. // Button labels are load-bearing — the click handler finds buttons by text.
  44. ensure({
  45. id: IDS.dec, type: 'geo', x: 40, y: 270,
  46. props: { geo: 'rectangle', w: 100, h: 80, color: 'red', fill: 'solid', richText: toRichText('MINUS'), size: 'l' },
  47. meta: { ui: 'button', action: 'MINUS' },
  48. })
  49. ensure({
  50. id: IDS.reset, type: 'geo', x: 170, y: 270,
  51. props: { geo: 'rectangle', w: 100, h: 80, color: 'grey', fill: 'solid', richText: toRichText('RESET'), size: 'l' },
  52. meta: { ui: 'button', action: 'RESET' },
  53. })
  54. ensure({
  55. id: IDS.inc, type: 'geo', x: 300, y: 270,
  56. props: { geo: 'rectangle', w: 100, h: 80, color: 'green', fill: 'solid', richText: toRichText('PLUS'), size: 'l' },
  57. meta: { ui: 'button', action: 'PLUS' },
  58. })
  59. })
  60. const STEP = { MINUS: -1, PLUS: +1 }
  61. function displayShape() {
  62. return editor.getCurrentPageShapes().find((s) => s.meta && s.meta.ui === 'display')
  63. }
  64. function setCount(n) {
  65. const d = displayShape()
  66. editor.run(
  67. () =>
  68. editor.updateShape({
  69. id: d.id, type: 'geo',
  70. props: { richText: toRichText(String(n)) },
  71. meta: { ...d.meta, count: n },
  72. }),
  73. { history: 'ignore' } // keep script writes out of the user's undo stack
  74. )
  75. }
  76. function runAction(label) {
  77. const d = displayShape()
  78. const cur = d.meta && typeof d.meta.count === 'number' ? d.meta.count : 0
  79. if (label === 'RESET') setCount(0)
  80. else if (label in STEP) setCount(cur + STEP[label])
  81. }
  82. function bounds(s) {
  83. return { x: s.x, y: s.y, w: s.props.w ?? 0, h: s.props.h ?? 0 }
  84. }
  85. function inside(b, p) {
  86. return p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h
  87. }
  88. function onEvent(info) {
  89. if (!info || info.name !== 'pointer_down') return
  90. let p = null
  91. try {
  92. if (info.point && editor.screenToPage) p = editor.screenToPage(info.point)
  93. } catch {}
  94. p = p ?? editor.inputs?.currentPagePoint
  95. if (!p) return
  96. const hit = editor
  97. .getCurrentPageShapes()
  98. .find((s) => s.meta && s.meta.ui === 'button' && inside(bounds(s), p))
  99. if (hit) runAction(hit.meta.action)
  100. }
  101. editor.on('event', onEvent)
  102. signal.addEventListener('abort', () => editor.off('event', onEvent)) // required cleanup
  103. editor.zoomToFit({ animation: { duration: 200 } })
  104. }