@m3ui-vue/m3ui-vue 1.2.2 → 1.3.1

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.
Files changed (241) hide show
  1. package/dist/API.md +3010 -376
  2. package/dist/MButton-Bl_BSUep.js +172 -0
  3. package/dist/MButton-Bl_BSUep.js.map +1 -0
  4. package/dist/MDialog-D_Yik8ou.js +173 -0
  5. package/dist/MDialog-D_Yik8ou.js.map +1 -0
  6. package/dist/MIconButton-DoNotQ9v.js +282 -0
  7. package/dist/MIconButton-DoNotQ9v.js.map +1 -0
  8. package/dist/MListItem-BxifHJdU.js +824 -0
  9. package/dist/MListItem-BxifHJdU.js.map +1 -0
  10. package/dist/MLoadingIndicator-BxbFhSX6.js +115 -0
  11. package/dist/MLoadingIndicator-BxbFhSX6.js.map +1 -0
  12. package/dist/MMenuItem-Bih0h4-n.js +604 -0
  13. package/dist/MMenuItem-Bih0h4-n.js.map +1 -0
  14. package/dist/MProgressBar-BCoruxA-.js +184 -0
  15. package/dist/MProgressBar-BCoruxA-.js.map +1 -0
  16. package/dist/MSeekBar-BeN9QcB3.js +435 -0
  17. package/dist/MSeekBar-BeN9QcB3.js.map +1 -0
  18. package/dist/MSegmentedButton-DL9JtJFX.js +65 -0
  19. package/dist/MSegmentedButton-DL9JtJFX.js.map +1 -0
  20. package/dist/MSlider-BVSbJlGS.js +691 -0
  21. package/dist/MSlider-BVSbJlGS.js.map +1 -0
  22. package/dist/MSpinner-C2SUnWk4.js +65 -0
  23. package/dist/MSpinner-C2SUnWk4.js.map +1 -0
  24. package/dist/MTextField-CEkWSZ2v.js +296 -0
  25. package/dist/MTextField-CEkWSZ2v.js.map +1 -0
  26. package/dist/MTooltip-CodJGEO-.js +756 -0
  27. package/dist/MTooltip-CodJGEO-.js.map +1 -0
  28. package/dist/_storageKeys-CYXsUBwK.js +18 -0
  29. package/dist/_storageKeys-CYXsUBwK.js.map +1 -0
  30. package/dist/_useEscapeStack-CjndQhqg.js +19 -0
  31. package/dist/_useEscapeStack-CjndQhqg.js.map +1 -0
  32. package/dist/api.json +1 -1
  33. package/dist/chart.js +1 -1
  34. package/dist/code-editor.js +1 -1
  35. package/dist/components/MAudioPlayer.vue.d.ts +115 -0
  36. package/dist/components/MBadge.vue.d.ts +1 -1
  37. package/dist/components/MBottomSheetScaffold.vue.d.ts +1 -1
  38. package/dist/components/MBox.vue.d.ts +1 -1
  39. package/dist/components/MButton.vue.d.ts +1 -1
  40. package/dist/components/MConfirmDialog.vue.d.ts +1 -1
  41. package/dist/components/MCopyButton.vue.d.ts +2 -2
  42. package/dist/components/MDataTable.vue.d.ts +2 -2
  43. package/dist/components/MDialog.vue.d.ts +2 -2
  44. package/dist/components/MDivider.vue.d.ts +1 -1
  45. package/dist/components/MDragHandle.vue.d.ts +1 -1
  46. package/dist/components/MDrawCanvas.vue.d.ts +150 -0
  47. package/dist/components/MDrawLayers.vue.d.ts +3 -0
  48. package/dist/components/MDrawToolbar.vue.d.ts +34 -0
  49. package/dist/components/MExportButton.vue.d.ts +1 -1
  50. package/dist/components/MFab.vue.d.ts +2 -2
  51. package/dist/components/MFabMenu.vue.d.ts +2 -2
  52. package/dist/components/MFixed.vue.d.ts +1 -1
  53. package/dist/components/MFlex.vue.d.ts +2 -2
  54. package/dist/components/MFloorPlan.vue.d.ts +248 -0
  55. package/dist/components/MFloorPlanInspector.vue.d.ts +56 -0
  56. package/dist/components/MFloorPlanToolbar.vue.d.ts +51 -0
  57. package/dist/components/MFlow.vue.d.ts +318 -0
  58. package/dist/components/MFlowControls.vue.d.ts +33 -0
  59. package/dist/components/MFlowHandle.vue.d.ts +16 -0
  60. package/dist/components/MFlowMinimap.vue.d.ts +22 -0
  61. package/dist/components/MFlowNode.vue.d.ts +35 -0
  62. package/dist/components/MGantt.vue.d.ts +141 -0
  63. package/dist/components/MGanttControls.vue.d.ts +32 -0
  64. package/dist/components/MIconButton.vue.d.ts +3 -1
  65. package/dist/components/MImageCropper.vue.d.ts +110 -0
  66. package/dist/components/MInfiniteScroll.vue.d.ts +1 -1
  67. package/dist/components/MLightbox.vue.d.ts +2 -2
  68. package/dist/components/MList.vue.d.ts +1 -1
  69. package/dist/components/MLoadingOverlay.vue.d.ts +1 -1
  70. package/dist/components/MMapControl.vue.d.ts +1 -1
  71. package/dist/components/MMapSearch.vue.d.ts +1 -1
  72. package/dist/components/MMaskField.vue.d.ts +12 -1
  73. package/dist/components/MMenu.vue.d.ts +1 -1
  74. package/dist/components/MNavigationDrawer.vue.d.ts +1 -1
  75. package/dist/components/MNumberField.vue.d.ts +11 -2
  76. package/dist/components/MPdfViewer.vue.d.ts +174 -0
  77. package/dist/components/MPullToRefresh.vue.d.ts +1 -1
  78. package/dist/components/MResourceTimeline.vue.d.ts +149 -0
  79. package/dist/components/MScheduler.vue.d.ts +3 -3
  80. package/dist/components/MScheme.vue.d.ts +1 -1
  81. package/dist/components/MSearchField.vue.d.ts +1 -1
  82. package/dist/components/MSeekBar.vue.d.ts +1 -1
  83. package/dist/components/MSimpleCarousel.vue.d.ts +1 -1
  84. package/dist/components/MSkeleton.vue.d.ts +1 -1
  85. package/dist/components/MSlider.vue.d.ts +2 -2
  86. package/dist/components/MSparkline.vue.d.ts +1 -1
  87. package/dist/components/MSplitter.vue.d.ts +1 -1
  88. package/dist/components/MStack.vue.d.ts +2 -2
  89. package/dist/components/MSwipeToDismiss.vue.d.ts +1 -1
  90. package/dist/components/MSwitch.vue.d.ts +1 -1
  91. package/dist/components/MTable.vue.d.ts +1 -1
  92. package/dist/components/MTagInput.vue.d.ts +12 -1
  93. package/dist/components/MTextField.vue.d.ts +13 -2
  94. package/dist/components/MToolbar.vue.d.ts +1 -1
  95. package/dist/components/MTree.vue.d.ts +2 -2
  96. package/dist/components/MVideoPlayer.vue.d.ts +253 -0
  97. package/dist/components/MVirtualTable.vue.d.ts +1 -1
  98. package/dist/components/MWindow.vue.d.ts +3 -3
  99. package/dist/components/_MFlowEdge.vue.d.ts +9 -0
  100. package/dist/components/_MFlowEdgeLabel.vue.d.ts +9 -0
  101. package/dist/components/_MFlowNodeShell.vue.d.ts +9 -0
  102. package/dist/components/_MPdfPage.vue.d.ts +76 -0
  103. package/dist/components/_MTimeBackground.vue.d.ts +14 -0
  104. package/dist/components/_MTimeHeader.vue.d.ts +20 -0
  105. package/dist/composables/_flowPanel.d.ts +2 -0
  106. package/dist/composables/_flowSlot.d.ts +5 -0
  107. package/dist/composables/_ganttTime.d.ts +41 -0
  108. package/dist/composables/_useTimeAxis.d.ts +90 -0
  109. package/dist/composables/drawGeometry.d.ts +119 -0
  110. package/dist/composables/flowFormats.d.ts +79 -0
  111. package/dist/composables/flowLayout.d.ts +45 -0
  112. package/dist/composables/flowPaths.d.ts +53 -0
  113. package/dist/composables/ganttFormats.d.ts +52 -0
  114. package/dist/composables/ganttSchedule.d.ts +99 -0
  115. package/dist/composables/useDrawing.d.ts +44 -0
  116. package/dist/composables/useFloorPlan.d.ts +58 -0
  117. package/dist/composables/useFlow.d.ts +266 -0
  118. package/dist/composables/useGantt.d.ts +87 -0
  119. package/dist/composables/useLocale.d.ts +204 -0
  120. package/dist/composables/useMediaPlayer.d.ts +101 -0
  121. package/dist/composables/usePdf.d.ts +119 -0
  122. package/dist/composables/useResourceTimeline.d.ts +70 -0
  123. package/dist/draw.d.ts +7 -0
  124. package/dist/draw.js +1702 -0
  125. package/dist/draw.js.map +1 -0
  126. package/dist/flow.d.ts +14 -0
  127. package/dist/flow.js +3547 -0
  128. package/dist/flow.js.map +1 -0
  129. package/dist/flowPaths-CUc6X373.js +161 -0
  130. package/dist/flowPaths-CUc6X373.js.map +1 -0
  131. package/dist/gantt.d.ts +12 -0
  132. package/dist/gantt.js +3575 -0
  133. package/dist/gantt.js.map +1 -0
  134. package/dist/index.d.ts +9 -0
  135. package/dist/locales/index.js +1435 -7
  136. package/dist/locales/index.js.map +1 -1
  137. package/dist/m3ui-vue.css +1 -1
  138. package/dist/m3ui.js +8248 -7637
  139. package/dist/m3ui.js.map +1 -1
  140. package/dist/map.js +113 -108
  141. package/dist/map.js.map +1 -1
  142. package/dist/media.d.ts +5 -0
  143. package/dist/media.js +1311 -0
  144. package/dist/media.js.map +1 -0
  145. package/dist/pdf.d.ts +4 -0
  146. package/dist/pdf.js +1871 -0
  147. package/dist/pdf.js.map +1 -0
  148. package/dist/rich-text-editor.js +28 -26
  149. package/dist/rich-text-editor.js.map +1 -1
  150. package/dist/styles.css +1 -1
  151. package/dist/{useLocale-JYxDDeXC.js → useLocale-CaWwi-b6.js} +206 -2
  152. package/dist/useLocale-CaWwi-b6.js.map +1 -0
  153. package/dist/{useThemeTokens-y0HZpyhL.js → useThemeTokens-DQQcaWbE.js} +40 -54
  154. package/dist/useThemeTokens-DQQcaWbE.js.map +1 -0
  155. package/package.json +29 -5
  156. package/src/__tests__/MAudioPlayer.test.ts +75 -0
  157. package/src/__tests__/MDrawCanvas.test.ts +118 -0
  158. package/src/__tests__/MFloorPlan.test.ts +299 -0
  159. package/src/__tests__/MFlow.test.ts +590 -0
  160. package/src/__tests__/MGantt.test.ts +130 -0
  161. package/src/__tests__/MImageCropper.test.ts +89 -0
  162. package/src/__tests__/MPdfViewer.test.ts +235 -0
  163. package/src/__tests__/MResourceTimeline.test.ts +102 -0
  164. package/src/__tests__/MVideoPlayer.test.ts +201 -0
  165. package/src/__tests__/drawGeometry.test.ts +58 -0
  166. package/src/__tests__/fieldExpose.test.ts +30 -0
  167. package/src/__tests__/flowFormats.test.ts +185 -0
  168. package/src/__tests__/flowLayout.test.ts +113 -0
  169. package/src/__tests__/ganttFormats.test.ts +76 -0
  170. package/src/__tests__/ganttSchedule.test.ts +136 -0
  171. package/src/__tests__/pdfMock.ts +83 -0
  172. package/src/__tests__/useMediaPlayer.test.ts +182 -0
  173. package/src/__tests__/usePdf.test.ts +102 -0
  174. package/src/components/MAudioPlayer.vue +319 -0
  175. package/src/components/MDrawCanvas.vue +819 -0
  176. package/src/components/MDrawLayers.vue +114 -0
  177. package/src/components/MDrawToolbar.vue +171 -0
  178. package/src/components/MFloorPlan.vue +1080 -0
  179. package/src/components/MFloorPlanInspector.vue +169 -0
  180. package/src/components/MFloorPlanToolbar.vue +128 -0
  181. package/src/components/MFlow.vue +2060 -0
  182. package/src/components/MFlowControls.vue +110 -0
  183. package/src/components/MFlowHandle.vue +60 -0
  184. package/src/components/MFlowMinimap.vue +134 -0
  185. package/src/components/MFlowNode.vue +98 -0
  186. package/src/components/MGantt.vue +1609 -0
  187. package/src/components/MGanttControls.vue +77 -0
  188. package/src/components/MIconButton.vue +3 -1
  189. package/src/components/MImageCropper.vue +507 -0
  190. package/src/components/MMaskField.vue +13 -0
  191. package/src/components/MNumberField.vue +13 -0
  192. package/src/components/MPdfViewer.vue +1270 -0
  193. package/src/components/MResourceTimeline.vue +1020 -0
  194. package/src/components/MTagInput.vue +13 -0
  195. package/src/components/MTextField.vue +16 -0
  196. package/src/components/MVideoPlayer.vue +839 -0
  197. package/src/components/_MFlowEdge.vue +100 -0
  198. package/src/components/_MFlowEdgeLabel.vue +56 -0
  199. package/src/components/_MFlowNodeShell.vue +111 -0
  200. package/src/components/_MPdfPage.vue +456 -0
  201. package/src/components/_MTimeBackground.vue +16 -0
  202. package/src/components/_MTimeHeader.vue +31 -0
  203. package/src/composables/_flowPanel.ts +13 -0
  204. package/src/composables/_flowSlot.ts +6 -0
  205. package/src/composables/_ganttTime.ts +200 -0
  206. package/src/composables/_useTimeAxis.ts +224 -0
  207. package/src/composables/drawGeometry.ts +405 -0
  208. package/src/composables/flowFormats.ts +916 -0
  209. package/src/composables/flowLayout.ts +297 -0
  210. package/src/composables/flowPaths.ts +239 -0
  211. package/src/composables/ganttFormats.ts +366 -0
  212. package/src/composables/ganttSchedule.ts +403 -0
  213. package/src/composables/useDrawing.ts +53 -0
  214. package/src/composables/useFloorPlan.ts +73 -0
  215. package/src/composables/useFlow.ts +250 -0
  216. package/src/composables/useGantt.ts +92 -0
  217. package/src/composables/useLocale.ts +410 -0
  218. package/src/composables/useMediaPlayer.ts +406 -0
  219. package/src/composables/usePdf.ts +456 -0
  220. package/src/composables/useResourceTimeline.ts +76 -0
  221. package/src/draw.ts +25 -0
  222. package/src/flow.ts +26 -0
  223. package/src/gantt.ts +12 -0
  224. package/src/index.ts +9 -0
  225. package/src/locales/de.ts +204 -0
  226. package/src/locales/es.ts +204 -0
  227. package/src/locales/fr.ts +204 -0
  228. package/src/locales/ja.ts +204 -0
  229. package/src/locales/ko.ts +204 -0
  230. package/src/locales/pt.ts +204 -0
  231. package/src/locales/zh.ts +204 -0
  232. package/src/media.ts +5 -0
  233. package/src/pdf.ts +15 -0
  234. package/dist/MMenuItem-D4Gx_l3F.js +0 -929
  235. package/dist/MMenuItem-D4Gx_l3F.js.map +0 -1
  236. package/dist/MSlider-Dx_S3vJ9.js +0 -1506
  237. package/dist/MSlider-Dx_S3vJ9.js.map +0 -1
  238. package/dist/MTextField-Bz8JIsnl.js +0 -633
  239. package/dist/MTextField-Bz8JIsnl.js.map +0 -1
  240. package/dist/useLocale-JYxDDeXC.js.map +0 -1
  241. package/dist/useThemeTokens-y0HZpyhL.js.map +0 -1
@@ -0,0 +1,819 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A drawing surface: pens that follow a stylus' pressure, an eraser that cuts strokes (and the pen's eraser end),
4
+ * lines, arrows, rectangles, ellipses, text, lasso selection to move, scale or delete, layers, undo and redo, pan
5
+ * and pinch zoom. An infinite canvas, or pages of a fixed size. The drawing is plain data (`v-model`, a list of
6
+ * strokes, shapes and texts), exported as SVG or PNG. Put an MDrawToolbar (or your own, with `useDrawing()`) in its
7
+ * default slot. Not an M3 spec component.
8
+ *
9
+ * Gestures: draw with the pen, mouse or a finger; two fingers pan and zoom (and cancel a stroke a finger just
10
+ * started); the wheel pans, Ctrl + wheel zooms; Space + drag or the middle button pans. With `penOnly` (by default
11
+ * once a stylus has been used) fingers only pan and zoom, so a palm on the screen doesn't draw. Keys: Ctrl+Z undo,
12
+ * Ctrl+Shift+Z or Ctrl+Y redo, Delete removes the selection, Escape drops it, Ctrl+A selects everything.
13
+ *
14
+ * @slot default Overlays: a toolbar (MDrawToolbar), a layers panel (MDrawLayers), anything positioned over the canvas
15
+ * @event change Fires after every edit with the new items (the same as `update:modelValue`)
16
+ */
17
+ import { computed, nextTick, onBeforeUnmount, onMounted, provide, ref, shallowRef, useId, watch } from 'vue'
18
+ import {
19
+ constrain,
20
+ drawId,
21
+ eraseAt,
22
+ hitItem,
23
+ inLasso,
24
+ itemBox,
25
+ LINE_HEIGHT,
26
+ PENS,
27
+ shapePath,
28
+ simulatePressure,
29
+ smoothPoints,
30
+ sortByLayer,
31
+ strokePath,
32
+ svgToPng,
33
+ textBox,
34
+ toDrawSvg,
35
+ transformItem,
36
+ unionBox,
37
+ type DrawBox,
38
+ type DrawItem,
39
+ type DrawLayer,
40
+ type DrawPoint,
41
+ type DrawShapeKind,
42
+ } from '../composables/drawGeometry'
43
+ import { DRAW_KEY, type DrawExportOptions, type DrawTool } from '../composables/useDrawing'
44
+ import { useLocale } from '../composables/useLocale'
45
+
46
+ const props = withDefaults(defineProps<{
47
+ /** An endless canvas, or pages of `pageSize` stacked one under another */
48
+ mode?: 'infinite' | 'pages'
49
+ /** A page's size in drawing units (A4 at 96 dpi by default) */
50
+ pageSize?: { width: number; height: number }
51
+ /** The paper's color (pages, or the whole infinite canvas) */
52
+ paper?: string
53
+ /** A ruling drawn on the paper */
54
+ background?: 'none' | 'grid' | 'dots' | 'lines'
55
+ /** The ruling's spacing */
56
+ backgroundSize?: number
57
+ /** An image under the drawing, to trace or annotate: fills each page, or sits at (0, 0) on an infinite canvas */
58
+ backgroundImage?: string
59
+ /** Infinite canvas: where the background image goes and its size, in drawing units (fitView takes it in too) */
60
+ backgroundImageBox?: DrawBox
61
+ /** Fingers only pan and zoom: `true`, `false`, or `'auto'` (once a stylus has touched the canvas) */
62
+ penOnly?: boolean | 'auto'
63
+ /** Use the stylus' pressure (without one, speed thins the line) */
64
+ pressure?: boolean
65
+ /** How much strokes are smoothed, 0–1 */
66
+ smoothing?: number
67
+ /** The eraser's radius in screen pixels */
68
+ eraserSize?: number
69
+ /** Undo and redo */
70
+ history?: boolean
71
+ historySize?: number
72
+ /** Look only: no drawing, but pan and zoom */
73
+ readonly?: boolean
74
+ minZoom?: number
75
+ maxZoom?: number
76
+ /** Accessible name of the canvas */
77
+ label?: string
78
+ }>(), {
79
+ mode: 'infinite',
80
+ pageSize: () => ({ width: 794, height: 1123 }),
81
+ paper: '#ffffff',
82
+ background: 'none',
83
+ backgroundSize: 24,
84
+ penOnly: 'auto',
85
+ pressure: true,
86
+ smoothing: 0.5,
87
+ eraserSize: 12,
88
+ history: true,
89
+ historySize: 100,
90
+ readonly: false,
91
+ minZoom: 0.1,
92
+ maxZoom: 8,
93
+ })
94
+
95
+ /** The drawing: strokes, shapes and texts */
96
+ const items = defineModel<DrawItem[]>({ default: () => [] })
97
+ const tool = defineModel<DrawTool>('tool', { default: 'pen' })
98
+ const color = defineModel<string>('color', { default: '#1d1b20' })
99
+ /** Pen width, shape line width or font size, by tool */
100
+ const size = defineModel<number>('size', { default: 4 })
101
+ /** New rects and ellipses are filled with the color */
102
+ const fill = defineModel<boolean>('fill', { default: false })
103
+ /** Layers, bottom first (none: one implicit layer) */
104
+ const layers = defineModel<DrawLayer[]>('layers', { default: () => [] })
105
+ /** The layer new items go on (default: the top one) */
106
+ const layer = defineModel<string | undefined>('layer', { default: undefined })
107
+ /** How many pages, in `mode="pages"` */
108
+ const pages = defineModel<number>('pages', { default: 1 })
109
+ /** The selected items' ids */
110
+ const selection = defineModel<string[]>('selection', { default: () => [] })
111
+ /** Pan and zoom: screen = drawing × zoom + (x, y) */
112
+ const viewport = defineModel<{ x: number; y: number; zoom: number }>('viewport', { default: () => ({ x: 0, y: 0, zoom: 1 }) })
113
+
114
+ const emit = defineEmits<{ change: [items: DrawItem[]] }>()
115
+ const locale = useLocale()
116
+
117
+ const root = ref<HTMLElement>()
118
+ const svgEl = ref<SVGSVGElement>()
119
+ const size2 = ref({ width: 0, height: 0 })
120
+ const GAP = 24
121
+ const pageTop = (i: number) => i * (props.pageSize.height + GAP)
122
+ const isPages = computed(() => props.mode === 'pages')
123
+
124
+ // ── Items, layers, history ──────────────────────────────────────────────────────────────────────────────
125
+ // While a gesture edits (erasing, moving) it works on a draft, committed once when it ends
126
+ const draft = shallowRef<DrawItem[] | null>(null)
127
+ const shownItems = computed(() => draft.value ?? items.value)
128
+ const layerIds = computed(() => layers.value.map((l) => l.id))
129
+ const activeLayer = computed(() => layer.value ?? layers.value[layers.value.length - 1]?.id)
130
+ const layerOf = (it: DrawItem) => layers.value.find((l) => l.id === (it.layer ?? layers.value[0]?.id))
131
+ const visible = (it: DrawItem) => layerOf(it)?.visible !== false
132
+ const editable = (it: DrawItem) => visible(it) && !layerOf(it)?.locked
133
+ const ordered = computed(() => sortByLayer(shownItems.value, layerIds.value).filter(visible))
134
+
135
+ const past = shallowRef<DrawItem[][]>([])
136
+ const future = shallowRef<DrawItem[][]>([])
137
+ function commit(next: DrawItem[]) {
138
+ if (props.history) {
139
+ past.value = [...past.value, items.value].slice(-props.historySize)
140
+ future.value = []
141
+ }
142
+ items.value = next
143
+ emit('change', next)
144
+ }
145
+ function undo() {
146
+ if (!past.value.length) return
147
+ future.value = [items.value, ...future.value]
148
+ items.value = past.value[past.value.length - 1]!
149
+ past.value = past.value.slice(0, -1)
150
+ selection.value = selection.value.filter((id) => items.value.some((i) => i.id === id))
151
+ emit('change', items.value)
152
+ }
153
+ function redo() {
154
+ if (!future.value.length) return
155
+ past.value = [...past.value, items.value]
156
+ items.value = future.value[0]!
157
+ future.value = future.value.slice(1)
158
+ emit('change', items.value)
159
+ }
160
+ function clear() {
161
+ if (items.value.length) commit(items.value.filter((i) => !editable(i)))
162
+ selection.value = []
163
+ }
164
+ function deleteSelection() {
165
+ if (!selection.value.length) return
166
+ const ids = new Set(selection.value)
167
+ commit(items.value.filter((i) => !ids.has(i.id)))
168
+ selection.value = []
169
+ }
170
+
171
+ // ── Coordinates ─────────────────────────────────────────────────────────────────────────────────────────
172
+ const vp = computed(() => viewport.value)
173
+ function toContent(e: { clientX: number; clientY: number }) {
174
+ const r = root.value!.getBoundingClientRect()
175
+ return { x: (e.clientX - r.left - vp.value.x) / vp.value.zoom, y: (e.clientY - r.top - vp.value.y) / vp.value.zoom }
176
+ }
177
+ /** The page under a content point (pages mode), or undefined */
178
+ function pageAt(y: number) {
179
+ if (!isPages.value) return undefined
180
+ const i = Math.floor(y / (props.pageSize.height + GAP))
181
+ return Math.max(0, Math.min(pages.value - 1, i))
182
+ }
183
+ const local = (p: { x: number; y: number }, page: number | undefined) => ({ x: p.x, y: page === undefined ? p.y : p.y - pageTop(page) })
184
+ const offsetOf = (it: DrawItem) => (isPages.value ? pageTop(it.page ?? 0) : 0)
185
+ const clampZoom = (z: number) => Math.min(props.maxZoom, Math.max(props.minZoom, z))
186
+ function zoomAt(z: number, sx: number, sy: number) {
187
+ const v = vp.value
188
+ const nz = clampZoom(z)
189
+ viewport.value = { zoom: nz, x: sx - ((sx - v.x) / v.zoom) * nz, y: sy - ((sy - v.y) / v.zoom) * nz }
190
+ }
191
+ const zoomBy = (f: number) => zoomAt(vp.value.zoom * f, size2.value.width / 2, size2.value.height / 2)
192
+ function fitView() {
193
+ const { width, height } = size2.value
194
+ if (!width || !height) return
195
+ const b: DrawBox | null = isPages.value
196
+ ? { x: 0, y: 0, width: props.pageSize.width, height: pageTop(pages.value - 1) + props.pageSize.height }
197
+ : unionBox([...ordered.value.map((i) => itemBox(i)), ...(props.backgroundImage && props.backgroundImageBox ? [props.backgroundImageBox] : [])])
198
+ if (!b) {
199
+ viewport.value = { x: width / 2, y: height / 2, zoom: 1 }
200
+ return
201
+ }
202
+ const pad = 24
203
+ // Pages fit their width (scrolling down through them); a drawing fits whole
204
+ const z = clampZoom(isPages.value ? Math.min((width - pad * 2) / b.width, 1.5) : Math.min((width - pad * 2) / b.width, (height - pad * 2) / b.height, 2))
205
+ viewport.value = { zoom: z, x: (width - b.width * z) / 2 - b.x * z, y: isPages.value ? pad : (height - b.height * z) / 2 - b.y * z }
206
+ }
207
+
208
+ // ── Pointer gestures ────────────────────────────────────────────────────────────────────────────────────
209
+ type Gesture =
210
+ | { kind: 'draw'; id: number; page?: number; points: DrawPoint[]; pen: boolean; touch: boolean; started: number }
211
+ | { kind: 'erase'; id: number; whole: boolean; last: { x: number; y: number } }
212
+ | { kind: 'shape'; id: number; page?: number; shape: DrawShapeKind; from: [number, number]; to: [number, number] }
213
+ | { kind: 'lasso'; id: number; points: [number, number][]; add: boolean }
214
+ | { kind: 'move'; id: number; from: { x: number; y: number }; moved: boolean }
215
+ | { kind: 'scale'; id: number; origin: { x: number; y: number }; from: { x: number; y: number } }
216
+ | { kind: 'pan'; id: number; sx: number; sy: number; vx: number; vy: number }
217
+ | { kind: 'pinch'; ids: [number, number] }
218
+ const gesture = shallowRef<Gesture | null>(null)
219
+ const touches = new Map<number, { x: number; y: number }>()
220
+ let pinch0: { d: number; mx: number; my: number; vp: { x: number; y: number; zoom: number } } | null = null
221
+ const penSeen = ref(false)
222
+ const spaceHeld = ref(false)
223
+ const fingersOnlyNavigate = computed(() => props.penOnly === true || (props.penOnly === 'auto' && penSeen.value))
224
+ const live = shallowRef<DrawItem | null>(null)
225
+ const lasso = shallowRef<[number, number][] | null>(null)
226
+
227
+ const isPen = (t: DrawTool): t is 'pen' | 'brush' | 'marker' | 'highlighter' => t === 'pen' || t === 'brush' || t === 'marker' || t === 'highlighter'
228
+ const isShape = (t: DrawTool): t is DrawShapeKind => t === 'line' || t === 'arrow' || t === 'rect' || t === 'ellipse'
229
+ const pressureOf = (e: PointerEvent) => (props.pressure && e.pointerType === 'pen' && e.pressure > 0 ? e.pressure : 0.5)
230
+
231
+ function strokeFrom(g: Extract<Gesture, { kind: 'draw' }>): DrawItem {
232
+ const pen = tool.value as 'pen'
233
+ let pts = g.points
234
+ if (!(g.pen && props.pressure) && PENS[pen].thinning > 0) pts = simulatePressure(pts, size.value)
235
+ pts = smoothPoints(pts, props.smoothing, size.value).map(([x, y, p]) => [Math.round(x * 100) / 100, Math.round(y * 100) / 100, Math.round(p * 100) / 100])
236
+ return { id: 'live', type: 'stroke', pen, color: color.value, size: size.value, points: pts, layer: activeLayer.value, page: g.page }
237
+ }
238
+
239
+ function startPinch() {
240
+ const [a, b] = [...touches.values()]
241
+ if (!a || !b) return
242
+ const r = root.value!.getBoundingClientRect()
243
+ pinch0 = { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, mx: (a.x + b.x) / 2 - r.left, my: (a.y + b.y) / 2 - r.top, vp: { ...vp.value } }
244
+ gesture.value = { kind: 'pinch', ids: [...touches.keys()].slice(0, 2) as [number, number] }
245
+ }
246
+
247
+ /** Events on the drawing itself, not on what's laid over it (a toolbar, a panel, the text being typed) */
248
+ const onCanvas = (e: Event) => e.target === root.value || !!svgEl.value?.contains(e.target as Node)
249
+ function onPointerDown(e: PointerEvent) {
250
+ if (!onCanvas(e)) return
251
+ root.value!.focus({ preventScroll: true })
252
+ if (e.pointerType === 'touch') touches.set(e.pointerId, { x: e.clientX, y: e.clientY })
253
+ if (e.pointerType === 'pen') penSeen.value = true
254
+ const g = gesture.value
255
+ // A second finger: pinch (dropping a stroke a finger just began)
256
+ if (e.pointerType === 'touch' && touches.size === 2 && (!g || g.kind === 'pan' || (g.kind === 'draw' && g.touch) || g.kind === 'lasso' || g.kind === 'shape' || g.kind === 'erase')) {
257
+ if (g?.kind === 'erase') draft.value = null
258
+ live.value = null
259
+ lasso.value = null
260
+ startPinch()
261
+ return
262
+ }
263
+ if (g) return
264
+ try {
265
+ root.value!.setPointerCapture(e.pointerId)
266
+ } catch {}
267
+ const p = toContent(e)
268
+ const navigate = e.button === 1 || spaceHeld.value || tool.value === 'pan' || props.readonly || (e.pointerType === 'touch' && fingersOnlyNavigate.value)
269
+ if (navigate) {
270
+ gesture.value = { kind: 'pan', id: e.pointerId, sx: e.clientX, sy: e.clientY, vx: vp.value.x, vy: vp.value.y }
271
+ return
272
+ }
273
+ if (e.button !== 0 && !(e.pointerType === 'pen' && e.button === 5)) return
274
+ const eraserEnd = e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0)
275
+ const t = eraserEnd ? 'eraser' : tool.value
276
+ if (t === 'eraser' || t === 'stroke-eraser') {
277
+ gesture.value = { kind: 'erase', id: e.pointerId, whole: t === 'stroke-eraser', last: p }
278
+ draft.value = items.value
279
+ eraseUnder(p)
280
+ return
281
+ }
282
+ const page = pageAt(p.y)
283
+ const lp = local(p, page)
284
+ if (isPen(t)) {
285
+ gesture.value = { kind: 'draw', id: e.pointerId, page, points: [[lp.x, lp.y, pressureOf(e)]], pen: e.pointerType === 'pen', touch: e.pointerType === 'touch', started: performance.now() }
286
+ live.value = strokeFrom(gesture.value)
287
+ return
288
+ }
289
+ if (isShape(t)) {
290
+ gesture.value = { kind: 'shape', id: e.pointerId, page, shape: t, from: [lp.x, lp.y], to: [lp.x, lp.y] }
291
+ return
292
+ }
293
+ if (t === 'text') {
294
+ const hit = topHit(p, (i) => i.type === 'text')
295
+ if (hit) editText(hit as Extract<DrawItem, { type: 'text' }>)
296
+ else newText(lp, page)
297
+ e.preventDefault()
298
+ return
299
+ }
300
+ if (t === 'select') {
301
+ const corner = handleAt(p)
302
+ if (corner) {
303
+ const b = selBox.value!
304
+ const ox = corner.includes('l') ? b.x + b.width : b.x
305
+ const oy = corner.includes('t') ? b.y + b.height : b.y
306
+ gesture.value = { kind: 'scale', id: e.pointerId, origin: { x: ox, y: oy }, from: p }
307
+ draft.value = items.value
308
+ return
309
+ }
310
+ const hit = topHit(p)
311
+ const inSel = selBox.value && p.x >= selBox.value.x && p.x <= selBox.value.x + selBox.value.width && p.y >= selBox.value.y && p.y <= selBox.value.y + selBox.value.height
312
+ if (hit && !selection.value.includes(hit.id) && !inSel) selection.value = e.shiftKey ? [...selection.value, hit.id] : [hit.id]
313
+ if (hit || inSel) {
314
+ gesture.value = { kind: 'move', id: e.pointerId, from: p, moved: false }
315
+ draft.value = items.value
316
+ return
317
+ }
318
+ gesture.value = { kind: 'lasso', id: e.pointerId, points: [[p.x, p.y]], add: e.shiftKey }
319
+ lasso.value = [[p.x, p.y]]
320
+ }
321
+ }
322
+
323
+ function onPointerMove(e: PointerEvent) {
324
+ if (e.pointerType === 'touch' && touches.has(e.pointerId)) touches.set(e.pointerId, { x: e.clientX, y: e.clientY })
325
+ const g = gesture.value
326
+ if (!g) return
327
+ if (g.kind === 'pinch') {
328
+ const [a, b] = g.ids.map((id) => touches.get(id))
329
+ if (!a || !b || !pinch0) return
330
+ const r = root.value!.getBoundingClientRect()
331
+ const d = Math.hypot(a.x - b.x, a.y - b.y)
332
+ const mx = (a.x + b.x) / 2 - r.left
333
+ const my = (a.y + b.y) / 2 - r.top
334
+ const z = clampZoom(pinch0.vp.zoom * (d / pinch0.d))
335
+ // The content point under the fingers' first midpoint stays under their midpoint now
336
+ const cx = (pinch0.mx - pinch0.vp.x) / pinch0.vp.zoom
337
+ const cy = (pinch0.my - pinch0.vp.y) / pinch0.vp.zoom
338
+ viewport.value = { zoom: z, x: mx - cx * z, y: my - cy * z }
339
+ return
340
+ }
341
+ if ('id' in g && g.id !== e.pointerId) return
342
+ if (g.kind === 'pan') {
343
+ viewport.value = { ...vp.value, x: g.vx + e.clientX - g.sx, y: g.vy + e.clientY - g.sy }
344
+ return
345
+ }
346
+ const events = (e.getCoalescedEvents?.() ?? []).length ? e.getCoalescedEvents() : [e]
347
+ if (g.kind === 'draw') {
348
+ for (const ev of events) {
349
+ const lp = local(toContent(ev), g.page)
350
+ g.points.push([lp.x, lp.y, pressureOf(ev)])
351
+ }
352
+ live.value = strokeFrom(g)
353
+ return
354
+ }
355
+ const p = toContent(e)
356
+ if (g.kind === 'erase') {
357
+ // Along the way, not only where the samples land: a quick swipe still erases what it crossed
358
+ const step = props.eraserSize / vp.value.zoom / 2
359
+ for (const ev of events) {
360
+ const q = toContent(ev)
361
+ const n = Math.max(1, Math.ceil(Math.hypot(q.x - g.last.x, q.y - g.last.y) / step))
362
+ for (let i = 1; i <= n; i++) eraseUnder({ x: g.last.x + ((q.x - g.last.x) * i) / n, y: g.last.y + ((q.y - g.last.y) * i) / n })
363
+ g.last = q
364
+ }
365
+ return
366
+ }
367
+ if (g.kind === 'shape') {
368
+ const lp = local(p, g.page)
369
+ g.to = e.shiftKey ? constrain(g.shape, g.from, [lp.x, lp.y]) : [lp.x, lp.y]
370
+ live.value = { id: 'live', type: 'shape', shape: g.shape, from: g.from, to: g.to, color: color.value, size: size.value, fill: fill.value ? color.value : null, layer: activeLayer.value, page: g.page }
371
+ return
372
+ }
373
+ if (g.kind === 'lasso') {
374
+ g.points.push([p.x, p.y])
375
+ lasso.value = g.points.slice()
376
+ return
377
+ }
378
+ if (g.kind === 'move') {
379
+ const dx = p.x - g.from.x
380
+ const dy = p.y - g.from.y
381
+ if (!g.moved && Math.hypot(dx, dy) * vp.value.zoom < 3) return
382
+ g.moved = true
383
+ const ids = new Set(selection.value)
384
+ draft.value = items.value.map((i) => (ids.has(i.id) ? transformItem(i, { dx, dy }) : i))
385
+ return
386
+ }
387
+ if (g.kind === 'scale') {
388
+ const d0 = Math.hypot(g.from.x - g.origin.x, g.from.y - g.origin.y) || 1
389
+ const k = Math.max(0.05, Math.hypot(p.x - g.origin.x, p.y - g.origin.y) / d0)
390
+ const ids = new Set(selection.value)
391
+ draft.value = items.value.map((i) => (ids.has(i.id) ? transformItem(i, { sx: k, sy: k, ox: g.origin.x, oy: g.origin.y - offsetOf(i) }) : i))
392
+ }
393
+ }
394
+
395
+ function onPointerUp(e: PointerEvent) {
396
+ touches.delete(e.pointerId)
397
+ const g = gesture.value
398
+ if (!g) return
399
+ if (g.kind === 'pinch') {
400
+ if (!g.ids.includes(e.pointerId)) return
401
+ gesture.value = null
402
+ pinch0 = null
403
+ // The finger left behind keeps panning
404
+ const [id, t] = [...touches.entries()][0] ?? []
405
+ if (id !== undefined && t) gesture.value = { kind: 'pan', id, sx: t.x, sy: t.y, vx: vp.value.x, vy: vp.value.y }
406
+ return
407
+ }
408
+ if (g.id !== e.pointerId) return
409
+ gesture.value = null
410
+ const cancelled = e.type === 'pointercancel'
411
+ if (g.kind === 'draw') {
412
+ const s = strokeFrom(g)
413
+ live.value = null
414
+ if (!cancelled) commit([...items.value, { ...s, id: drawId() }])
415
+ } else if (g.kind === 'shape') {
416
+ const it = live.value
417
+ live.value = null
418
+ if (it && !cancelled && Math.hypot(g.to[0] - g.from[0], g.to[1] - g.from[1]) > 2) commit([...items.value, { ...it, id: drawId() }])
419
+ } else if (g.kind === 'erase' || g.kind === 'move' || g.kind === 'scale') {
420
+ const next = draft.value
421
+ draft.value = null
422
+ if (next && next !== items.value && !cancelled && (g.kind !== 'move' || g.moved)) commit(next)
423
+ if (g.kind === 'move' && !g.moved && !e.shiftKey) {
424
+ const hit = topHit(toContent(e))
425
+ selection.value = hit ? [hit.id] : []
426
+ }
427
+ } else if (g.kind === 'lasso') {
428
+ const poly = g.points
429
+ lasso.value = null
430
+ if (poly.length < 3) {
431
+ if (!g.add) selection.value = []
432
+ return
433
+ }
434
+ const taken = shownItems.value.filter((i) => editable(i) && inLasso(i, poly.map(([x, y]) => [x, y - offsetOf(i)]))).map((i) => i.id)
435
+ selection.value = g.add ? [...new Set([...selection.value, ...taken])] : taken
436
+ }
437
+ }
438
+
439
+ function eraseUnder(p: { x: number; y: number }) {
440
+ const r = props.eraserSize / vp.value.zoom
441
+ const g = gesture.value
442
+ const whole = g?.kind === 'erase' && g.whole
443
+ let changed = false
444
+ const next: DrawItem[] = []
445
+ for (const it of draft.value ?? items.value) {
446
+ if (!editable(it)) {
447
+ next.push(it)
448
+ continue
449
+ }
450
+ const lx = p.x
451
+ const ly = p.y - offsetOf(it)
452
+ if (whole) {
453
+ if (hitItem(it, lx, ly, r)) changed = true
454
+ else next.push(it)
455
+ continue
456
+ }
457
+ const kept = eraseAt(it, lx, ly, r)
458
+ if (kept.length !== 1 || kept[0] !== it) changed = true
459
+ next.push(...kept)
460
+ }
461
+ if (changed) draft.value = next
462
+ }
463
+
464
+ /** The topmost editable item under a content point */
465
+ function topHit(p: { x: number; y: number }, ok: (i: DrawItem) => boolean = () => true) {
466
+ const tol = 6 / vp.value.zoom
467
+ const list = ordered.value
468
+ for (let i = list.length - 1; i >= 0; i--) {
469
+ const it = list[i]!
470
+ if (editable(it) && ok(it) && hitItem(it, p.x, p.y - offsetOf(it), tol)) return it
471
+ }
472
+ return null
473
+ }
474
+
475
+ function onWheel(e: WheelEvent) {
476
+ if (!onCanvas(e)) return
477
+ e.preventDefault()
478
+ const r = root.value!.getBoundingClientRect()
479
+ if (e.ctrlKey || e.metaKey) zoomAt(vp.value.zoom * Math.exp(-e.deltaY * (e.deltaMode ? 0.05 : 0.01)), e.clientX - r.left, e.clientY - r.top)
480
+ else {
481
+ const k = e.deltaMode ? 16 : 1
482
+ const dx = e.shiftKey && !e.deltaX ? e.deltaY : e.deltaX
483
+ const dy = e.shiftKey && !e.deltaX ? 0 : e.deltaY
484
+ viewport.value = { ...vp.value, x: vp.value.x - dx * k, y: vp.value.y - dy * k }
485
+ }
486
+ }
487
+
488
+ function onKeydown(e: KeyboardEvent) {
489
+ if (!onCanvas(e)) return
490
+ const mod = e.ctrlKey || e.metaKey
491
+ if (mod && e.key.toLowerCase() === 'z') {
492
+ e.preventDefault()
493
+ if (e.shiftKey) redo()
494
+ else undo()
495
+ } else if (mod && e.key.toLowerCase() === 'y') {
496
+ e.preventDefault()
497
+ redo()
498
+ } else if (mod && e.key.toLowerCase() === 'a' && !props.readonly) {
499
+ e.preventDefault()
500
+ tool.value = 'select'
501
+ selection.value = shownItems.value.filter(editable).map((i) => i.id)
502
+ } else if ((e.key === 'Delete' || e.key === 'Backspace') && selection.value.length) {
503
+ e.preventDefault()
504
+ deleteSelection()
505
+ } else if (e.key === 'Escape') selection.value = []
506
+ else if (e.key === ' ' && !e.repeat) {
507
+ e.preventDefault()
508
+ spaceHeld.value = true
509
+ }
510
+ }
511
+ const onKeyup = (e: KeyboardEvent) => e.key === ' ' && (spaceHeld.value = false)
512
+
513
+ // ── Selection box ───────────────────────────────────────────────────────────────────────────────────────
514
+ const selBox = computed<DrawBox | null>(() => {
515
+ const ids = new Set(selection.value)
516
+ const boxes = shownItems.value.filter((i) => ids.has(i.id)).map((i) => {
517
+ const b = itemBox(i)
518
+ return { ...b, y: b.y + offsetOf(i) }
519
+ })
520
+ return unionBox(boxes)
521
+ })
522
+ const HANDLE = 10
523
+ const corners = computed(() => {
524
+ const b = selBox.value
525
+ if (!b || tool.value !== 'select') return []
526
+ return [
527
+ { id: 'tl', x: b.x, y: b.y, cursor: 'nwse-resize' },
528
+ { id: 'tr', x: b.x + b.width, y: b.y, cursor: 'nesw-resize' },
529
+ { id: 'bl', x: b.x, y: b.y + b.height, cursor: 'nesw-resize' },
530
+ { id: 'br', x: b.x + b.width, y: b.y + b.height, cursor: 'nwse-resize' },
531
+ ]
532
+ })
533
+ function handleAt(p: { x: number; y: number }) {
534
+ const r = (HANDLE * 1.2) / vp.value.zoom
535
+ return corners.value.find((c) => Math.abs(c.x - p.x) <= r && Math.abs(c.y - p.y) <= r)?.id
536
+ }
537
+ watch(tool, (t) => t !== 'select' && (selection.value = []))
538
+
539
+ // ── Text ────────────────────────────────────────────────────────────────────────────────────────────────
540
+ const editing = ref<{ id: string | null; at: [number, number]; page?: number; text: string; size: number; color: string } | null>(null)
541
+ const textarea = ref<HTMLTextAreaElement>()
542
+ function newText(lp: { x: number; y: number }, page: number | undefined) {
543
+ if (editing.value) return finishText()
544
+ const fs = Math.max(12, size.value * 4)
545
+ editing.value = { id: null, at: [lp.x, lp.y - fs * 0.6], page, text: '', size: fs, color: color.value }
546
+ nextTick(() => textarea.value?.focus())
547
+ }
548
+ function editText(t: Extract<DrawItem, { type: 'text' }>) {
549
+ editing.value = { id: t.id, at: t.at, page: t.page, text: t.text, size: t.size, color: t.color }
550
+ nextTick(() => {
551
+ textarea.value?.focus()
552
+ textarea.value?.select()
553
+ })
554
+ }
555
+ function finishText() {
556
+ const ed = editing.value
557
+ if (!ed) return
558
+ editing.value = null
559
+ const text = ed.text.replace(/\s+$/, '')
560
+ if (ed.id) {
561
+ const before = items.value.find((i) => i.id === ed.id)
562
+ if (!before) return
563
+ if (!text) commit(items.value.filter((i) => i.id !== ed.id))
564
+ else if (before.type === 'text' && before.text !== text) commit(items.value.map((i) => (i.id === ed.id ? { ...i, text } : i)))
565
+ } else if (text) {
566
+ commit([...items.value, { id: drawId(), type: 'text', at: ed.at, text, size: ed.size, color: ed.color, layer: activeLayer.value, page: ed.page }])
567
+ }
568
+ }
569
+ const textStyle = computed(() => {
570
+ const ed = editing.value
571
+ if (!ed) return {}
572
+ const z = vp.value.zoom
573
+ const top = ed.page === undefined ? 0 : pageTop(ed.page)
574
+ const lines = ed.text.split('\n')
575
+ return {
576
+ left: `${ed.at[0] * z + vp.value.x}px`,
577
+ top: `${(ed.at[1] + top) * z + vp.value.y}px`,
578
+ fontSize: `${ed.size * z}px`,
579
+ lineHeight: String(LINE_HEIGHT),
580
+ color: ed.color,
581
+ width: `${Math.max(4, ...lines.map((l) => l.length + 1)) * 0.6}em`,
582
+ height: `${lines.length * LINE_HEIGHT}em`,
583
+ }
584
+ })
585
+ function onDblclick(e: MouseEvent) {
586
+ if (tool.value !== 'select' || props.readonly) return
587
+ const hit = topHit(toContent(e), (i) => i.type === 'text')
588
+ if (hit) editText(hit as Extract<DrawItem, { type: 'text' }>)
589
+ }
590
+
591
+ // ── Drawing the items ───────────────────────────────────────────────────────────────────────────────────
592
+ const paths = new WeakMap<DrawItem, { d: string; head?: string }>()
593
+ function geometryOf(it: DrawItem) {
594
+ let g = paths.get(it)
595
+ if (!g) {
596
+ g = it.type === 'stroke' ? { d: strokePath(it) } : it.type === 'shape' ? shapePath(it) : { d: '' }
597
+ paths.set(it, g)
598
+ }
599
+ return g
600
+ }
601
+ const editingId = computed(() => editing.value?.id)
602
+ const pageList = computed(() => (isPages.value ? Array.from({ length: Math.max(1, pages.value) }, (_, i) => i) : [undefined]))
603
+ const itemsOn = (page: number | undefined) => ordered.value.filter((i) => (page === undefined ? true : (i.page ?? 0) === page) && i.id !== editingId.value)
604
+ // The infinite canvas' paper and ruling cover the visible area
605
+ const visibleArea = computed(() => {
606
+ const z = vp.value.zoom
607
+ return { x: -vp.value.x / z, y: -vp.value.y / z, width: size2.value.width / z, height: size2.value.height / z }
608
+ })
609
+ // Stable across server and client render (pattern and clip ids)
610
+ const uid = `m3d${useId().replace(/[^a-zA-Z0-9-]/g, "")}`
611
+ const rule = computed(() => props.backgroundSize)
612
+ const cursor = computed(() => {
613
+ if (gesture.value?.kind === 'pan' || gesture.value?.kind === 'pinch') return 'grabbing'
614
+ if (spaceHeld.value || tool.value === 'pan' || props.readonly) return 'grab'
615
+ if (tool.value === 'text') return 'text'
616
+ if (tool.value === 'select') return 'default'
617
+ return 'crosshair'
618
+ })
619
+
620
+ // ── Exporting ───────────────────────────────────────────────────────────────────────────────────────────
621
+ const hiddenLayers = computed(() => layers.value.filter((l) => l.visible === false).map((l) => l.id))
622
+ function exportSvg(opts: DrawExportOptions = {}) {
623
+ const font = root.value ? getComputedStyle(root.value).fontFamily : 'sans-serif'
624
+ const page = isPages.value ? opts.page ?? 0 : undefined
625
+ return toDrawSvg(items.value, {
626
+ page,
627
+ box: isPages.value ? { x: 0, y: 0, ...props.pageSize } : undefined,
628
+ background: opts.background === false ? undefined : props.paper,
629
+ hiddenLayers: hiddenLayers.value,
630
+ layers: layerIds.value,
631
+ fontFamily: font,
632
+ })
633
+ }
634
+ const exportPng = (opts: DrawExportOptions = {}) => svgToPng(exportSvg(opts), opts.scale ?? 2)
635
+
636
+ // ── Lifecycle ───────────────────────────────────────────────────────────────────────────────────────────
637
+ let ro: ResizeObserver | null = null
638
+ onMounted(() => {
639
+ const el = root.value!
640
+ el.addEventListener('wheel', onWheel, { passive: false })
641
+ const measure = () => (size2.value = { width: el.clientWidth, height: el.clientHeight })
642
+ measure()
643
+ ro = new ResizeObserver(measure)
644
+ ro.observe(el)
645
+ // Pages start fitted to the width; an infinite canvas centered on what's drawn
646
+ const v = viewport.value
647
+ if (v.x === 0 && v.y === 0 && v.zoom === 1) fitView()
648
+ })
649
+ onBeforeUnmount(() => {
650
+ ro?.disconnect()
651
+ root.value?.removeEventListener('wheel', onWheel)
652
+ })
653
+
654
+ provide(DRAW_KEY, {
655
+ tool,
656
+ color,
657
+ size,
658
+ fill,
659
+ items: computed(() => items.value),
660
+ selection,
661
+ layers: computed(() => layers.value),
662
+ setLayers: (l: DrawLayer[]) => (layers.value = l),
663
+ layer: computed({ get: () => activeLayer.value, set: (v) => (layer.value = v) }),
664
+ mode: computed(() => props.mode),
665
+ pages,
666
+ addPage: () => (pages.value = pages.value + 1),
667
+ zoom: computed(() => vp.value.zoom),
668
+ zoomIn: () => zoomBy(1.25),
669
+ zoomOut: () => zoomBy(0.8),
670
+ fitView,
671
+ canUndo: computed(() => past.value.length > 0),
672
+ canRedo: computed(() => future.value.length > 0),
673
+ undo,
674
+ redo,
675
+ clear,
676
+ deleteSelection,
677
+ exportSvg,
678
+ exportPng,
679
+ })
680
+
681
+ defineExpose({ undo, redo, clear, deleteSelection, fitView, zoomIn: () => zoomBy(1.25), zoomOut: () => zoomBy(0.8), exportSvg, exportPng, toContent })
682
+ </script>
683
+
684
+ <template>
685
+ <div
686
+ ref="root"
687
+ class="m3-draw-canvas outline-none select-none [touch-action:none]"
688
+ :style="{ cursor }"
689
+ tabindex="0"
690
+ role="application"
691
+ :aria-label="label ?? locale.drawCanvas"
692
+ @pointerdown="onPointerDown"
693
+ @pointermove="onPointerMove"
694
+ @pointerup="onPointerUp"
695
+ @pointercancel="onPointerUp"
696
+ @lostpointercapture="onPointerUp"
697
+ @dblclick="onDblclick"
698
+ @keydown="onKeydown"
699
+ @keyup="onKeyup"
700
+ @contextmenu.prevent
701
+ >
702
+ <svg ref="svgEl" class="absolute inset-0 size-full" aria-hidden="true">
703
+ <defs>
704
+ <pattern :id="`${uid}-grid`" :width="rule" :height="rule" patternUnits="userSpaceOnUse">
705
+ <path :d="`M${rule} 0H0V${rule}`" fill="none" stroke="rgba(0,0,0,.12)" :stroke-width="1 / vp.zoom" />
706
+ </pattern>
707
+ <pattern :id="`${uid}-dots`" :width="rule" :height="rule" patternUnits="userSpaceOnUse">
708
+ <circle :cx="rule / 2" :cy="rule / 2" :r="Math.max(0.8, 1.2 / vp.zoom)" fill="rgba(0,0,0,.22)" />
709
+ </pattern>
710
+ <pattern :id="`${uid}-lines`" :width="rule * 4" :height="rule * 1.25" patternUnits="userSpaceOnUse">
711
+ <path :d="`M0 ${rule * 1.25 - 0.5}H${rule * 4}`" fill="none" stroke="rgba(30,90,200,.22)" :stroke-width="1 / vp.zoom" />
712
+ </pattern>
713
+ <clipPath v-for="p in (isPages ? pageList : [])" :id="`${uid}-page${p}`" :key="p ?? 'x'">
714
+ <rect x="0" y="0" :width="pageSize.width" :height="pageSize.height" />
715
+ </clipPath>
716
+ </defs>
717
+ <g :transform="`translate(${vp.x} ${vp.y}) scale(${vp.zoom})`">
718
+ <template v-if="!isPages">
719
+ <rect v-bind="visibleArea" :fill="paper" />
720
+ <image v-if="backgroundImage" :href="backgroundImage" v-bind="backgroundImageBox ?? { x: 0, y: 0 }" preserveAspectRatio="xMidYMid slice" />
721
+ <rect v-if="background !== 'none'" v-bind="visibleArea" :fill="`url(#${uid}-${background})`" />
722
+ </template>
723
+ <g v-for="p in pageList" :key="p ?? 'all'" :transform="p === undefined ? undefined : `translate(0 ${pageTop(p)})`">
724
+ <template v-if="p !== undefined">
725
+ <rect x="0" y="0" :width="pageSize.width" :height="pageSize.height" :fill="paper" class="m3-draw-page" />
726
+ <image v-if="backgroundImage" :href="backgroundImage" x="0" y="0" :width="pageSize.width" :height="pageSize.height" preserveAspectRatio="xMidYMid meet" />
727
+ <rect v-if="background !== 'none'" x="0" y="0" :width="pageSize.width" :height="pageSize.height" :fill="`url(#${uid}-${background})`" />
728
+ </template>
729
+ <g :clip-path="p === undefined ? undefined : `url(#${uid}-page${p})`">
730
+ <template v-for="it in itemsOn(p)" :key="it.id">
731
+ <path v-if="it.type === 'stroke'" :d="geometryOf(it).d" :fill="it.color" :fill-opacity="PENS[it.pen].opacity" />
732
+ <template v-else-if="it.type === 'shape'">
733
+ <path
734
+ :d="geometryOf(it).d"
735
+ :fill="it.fill && (it.shape === 'rect' || it.shape === 'ellipse') ? it.fill : 'none'"
736
+ :stroke="it.color"
737
+ :stroke-width="it.size"
738
+ stroke-linecap="round"
739
+ stroke-linejoin="round"
740
+ />
741
+ <path v-if="geometryOf(it).head" :d="geometryOf(it).head" :fill="it.color" />
742
+ </template>
743
+ <text v-else :x="it.at[0]" :y="it.at[1]" :font-size="it.size" :fill="it.color" class="m3-draw-text">
744
+ <tspan v-for="(l, i) in it.text.split('\n')" :key="i" :x="it.at[0]" :dy="i ? it.size * LINE_HEIGHT : it.size * 0.95">{{ l || ' ' }}</tspan>
745
+ </text>
746
+ </template>
747
+ <template v-if="live && (p === undefined || live.page === p)">
748
+ <path v-if="live.type === 'stroke'" :d="strokePath(live)" :fill="live.color" :fill-opacity="PENS[live.pen].opacity" />
749
+ <template v-else-if="live.type === 'shape'">
750
+ <path :d="shapePath(live).d" :fill="live.fill && (live.shape === 'rect' || live.shape === 'ellipse') ? live.fill : 'none'" :stroke="live.color" :stroke-width="live.size" stroke-linecap="round" stroke-linejoin="round" />
751
+ <path v-if="shapePath(live).head" :d="shapePath(live).head" :fill="live.color" />
752
+ </template>
753
+ </template>
754
+ </g>
755
+ </g>
756
+ <!-- Selection -->
757
+ <polygon v-if="lasso" :points="lasso.map((q) => q.join(',')).join(' ')" class="fill-primary/8 stroke-primary" :stroke-width="1.5 / vp.zoom" :stroke-dasharray="`${4 / vp.zoom} ${3 / vp.zoom}`" />
758
+ <template v-if="selBox && tool === 'select'">
759
+ <rect
760
+ :x="selBox.x - 4 / vp.zoom"
761
+ :y="selBox.y - 4 / vp.zoom"
762
+ :width="selBox.width + 8 / vp.zoom"
763
+ :height="selBox.height + 8 / vp.zoom"
764
+ fill="none"
765
+ class="stroke-primary"
766
+ :stroke-width="1.5 / vp.zoom"
767
+ :stroke-dasharray="`${5 / vp.zoom} ${4 / vp.zoom}`"
768
+ />
769
+ <rect
770
+ v-for="h in corners"
771
+ :key="h.id"
772
+ :x="h.x - HANDLE / 2 / vp.zoom"
773
+ :y="h.y - HANDLE / 2 / vp.zoom"
774
+ :width="HANDLE / vp.zoom"
775
+ :height="HANDLE / vp.zoom"
776
+ :rx="2 / vp.zoom"
777
+ class="fill-surface stroke-primary"
778
+ :stroke-width="1.5 / vp.zoom"
779
+ :style="{ cursor: h.cursor }"
780
+ />
781
+ </template>
782
+ </g>
783
+ </svg>
784
+
785
+ <textarea
786
+ v-if="editing"
787
+ ref="textarea"
788
+ v-model="editing.text"
789
+ data-draw-overlay
790
+ class="m3-draw-text absolute resize-none overflow-hidden border-0 bg-transparent p-0 whitespace-pre outline-1 outline-primary outline-dashed"
791
+ :style="textStyle"
792
+ :aria-label="locale.drawText"
793
+ spellcheck="false"
794
+ @blur="finishText"
795
+ @keydown.esc.prevent="finishText"
796
+ @keydown.stop
797
+ />
798
+
799
+ <slot />
800
+ </div>
801
+ </template>
802
+
803
+ <style>
804
+ /* Defaults a consumer's own utilities override (absolute inset-0, another background…): none on the root itself */
805
+ @layer base {
806
+ .m3-draw-canvas {
807
+ position: relative;
808
+ overflow: hidden;
809
+ min-height: 240px;
810
+ background-color: var(--color-surface-container);
811
+ }
812
+ }
813
+ .m3-draw-page {
814
+ filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.2)) drop-shadow(0 1px 6px rgb(0 0 0 / 0.08));
815
+ }
816
+ .m3-draw-text {
817
+ font-family: var(--font-sans, sans-serif);
818
+ }
819
+ </style>