@m3ui-vue/m3ui-vue 1.3.7 → 1.4.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.
Files changed (130) hide show
  1. package/dist/API.md +1097 -26
  2. package/dist/{MButton-D5eJiDza.js → MButton-DQMTIlaV.js} +2 -2
  3. package/dist/{MButton-D5eJiDza.js.map → MButton-DQMTIlaV.js.map} +1 -1
  4. package/dist/{MDialog-WqB0jewp.js → MDialog-cdgapGfZ.js} +2 -2
  5. package/dist/{MDialog-WqB0jewp.js.map → MDialog-cdgapGfZ.js.map} +1 -1
  6. package/dist/{MListItem-Cf-C2Ru-.js → MListItem-ZkSGIIrb.js} +2 -2
  7. package/dist/{MListItem-Cf-C2Ru-.js.map → MListItem-ZkSGIIrb.js.map} +1 -1
  8. package/dist/{MLoadingIndicator-D4GzEZoH.js → MLoadingIndicator-U6_oGx8z.js} +2 -2
  9. package/dist/{MLoadingIndicator-D4GzEZoH.js.map → MLoadingIndicator-U6_oGx8z.js.map} +1 -1
  10. package/dist/{MSeekBar-B19xoWE3.js → MSeekBar-DTZVizZg.js} +2 -2
  11. package/dist/{MSeekBar-B19xoWE3.js.map → MSeekBar-DTZVizZg.js.map} +1 -1
  12. package/dist/{MSlider-9RoiuebS.js → MSlider-CqJkEYRZ.js} +2 -2
  13. package/dist/{MSlider-9RoiuebS.js.map → MSlider-CqJkEYRZ.js.map} +1 -1
  14. package/dist/{MSpinner-BNF8MN-L.js → MSpinner-Btgc-0nb.js} +2 -2
  15. package/dist/{MSpinner-BNF8MN-L.js.map → MSpinner-Btgc-0nb.js.map} +1 -1
  16. package/dist/{MTextField-CuG0T3qh.js → MTextField-B6M0gJEO.js} +2 -2
  17. package/dist/{MTextField-CuG0T3qh.js.map → MTextField-B6M0gJEO.js.map} +1 -1
  18. package/dist/{MTooltip-Bv7yxngk.js → MTooltip-Dspji4XG.js} +4 -4
  19. package/dist/{MTooltip-Bv7yxngk.js.map → MTooltip-Dspji4XG.js.map} +1 -1
  20. package/dist/api.json +1 -1
  21. package/dist/code-editor.js +1 -1
  22. package/dist/components/MAudioPlayer.vue.d.ts +2 -2
  23. package/dist/components/MAvailabilityCalendar.vue.d.ts +83 -0
  24. package/dist/components/MBadge.vue.d.ts +1 -1
  25. package/dist/components/MBeforeAfter.vue.d.ts +61 -0
  26. package/dist/components/MBodyMap.vue.d.ts +70 -0
  27. package/dist/components/MCandlestickChart.vue.d.ts +82 -0
  28. package/dist/components/MCertificate.vue.d.ts +76 -0
  29. package/dist/components/MCreditCardInput.vue.d.ts +75 -0
  30. package/dist/components/MFlow.vue.d.ts +13 -0
  31. package/dist/components/MMortgageCalculator.vue.d.ts +83 -0
  32. package/dist/components/MOdontogram.vue.d.ts +86 -0
  33. package/dist/components/MOrderBook.vue.d.ts +89 -0
  34. package/dist/components/MOrderTicket.vue.d.ts +91 -0
  35. package/dist/components/MPosKeypad.vue.d.ts +84 -0
  36. package/dist/components/MProductConfigurator.vue.d.ts +136 -0
  37. package/dist/components/MQuiz.vue.d.ts +102 -0
  38. package/dist/components/MReceipt.vue.d.ts +93 -0
  39. package/dist/components/MSeatMap.vue.d.ts +131 -0
  40. package/dist/components/MSeekBar.vue.d.ts +1 -1
  41. package/dist/components/MSlider.vue.d.ts +2 -2
  42. package/dist/components/MSplitter.vue.d.ts +1 -1
  43. package/dist/components/MTicket.vue.d.ts +83 -0
  44. package/dist/components/MTour.vue.d.ts +52 -2
  45. package/dist/components/MVideoPlayer.vue.d.ts +1 -1
  46. package/dist/components/MVitalsChart.vue.d.ts +73 -0
  47. package/dist/composables/_printElement.d.ts +9 -0
  48. package/dist/composables/cardBrand.d.ts +25 -0
  49. package/dist/composables/flowPaths.d.ts +11 -3
  50. package/dist/composables/mortgage.d.ts +37 -0
  51. package/dist/composables/useFlow.d.ts +4 -0
  52. package/dist/composables/useLocale.d.ts +131 -0
  53. package/dist/draw.js +2 -2
  54. package/dist/flow.d.ts +1 -1
  55. package/dist/flow.js +526 -434
  56. package/dist/flow.js.map +1 -1
  57. package/dist/{flowPaths-DzW-aiET.js → flowPaths-CcWOKY4Z.js} +5 -5
  58. package/dist/flowPaths-CcWOKY4Z.js.map +1 -0
  59. package/dist/gantt.js +2 -2
  60. package/dist/index.d.ts +35 -0
  61. package/dist/locales/index.js +924 -7
  62. package/dist/locales/index.js.map +1 -1
  63. package/dist/m3ui-vue.css +1 -1
  64. package/dist/m3ui.js +8393 -3613
  65. package/dist/m3ui.js.map +1 -1
  66. package/dist/map.js +5 -5
  67. package/dist/media.js +4 -4
  68. package/dist/pdf.js +4 -4
  69. package/dist/rich-text-editor.js +4 -4
  70. package/dist/styles.css +1 -1
  71. package/dist/{useLocale-D2ucaY-l.js → useLocale-DLKJIRFi.js} +133 -2
  72. package/dist/useLocale-DLKJIRFi.js.map +1 -0
  73. package/package.json +1 -1
  74. package/src/__tests__/MAvailabilityCalendar.test.ts +85 -0
  75. package/src/__tests__/MBeforeAfter.test.ts +79 -0
  76. package/src/__tests__/MBodyMap.test.ts +60 -0
  77. package/src/__tests__/MCandlestickChart.test.ts +66 -0
  78. package/src/__tests__/MCertificate.test.ts +32 -0
  79. package/src/__tests__/MCreditCardInput.test.ts +122 -0
  80. package/src/__tests__/MFlow.test.ts +69 -0
  81. package/src/__tests__/MMortgageCalculator.test.ts +49 -0
  82. package/src/__tests__/MOdontogram.test.ts +93 -0
  83. package/src/__tests__/MOrderBook.test.ts +66 -0
  84. package/src/__tests__/MOrderTicket.test.ts +68 -0
  85. package/src/__tests__/MPosKeypad.test.ts +116 -0
  86. package/src/__tests__/MProductConfigurator.test.ts +73 -0
  87. package/src/__tests__/MQuiz.test.ts +104 -0
  88. package/src/__tests__/MReceipt.test.ts +52 -0
  89. package/src/__tests__/MSeatMap.test.ts +76 -0
  90. package/src/__tests__/MTicket.test.ts +38 -0
  91. package/src/__tests__/MTour.test.ts +102 -0
  92. package/src/__tests__/MVitalsChart.test.ts +49 -0
  93. package/src/__tests__/mortgage.test.ts +25 -0
  94. package/src/__tests__/ssr.test.ts +11 -0
  95. package/src/components/MAvailabilityCalendar.vue +460 -0
  96. package/src/components/MBeforeAfter.vue +248 -0
  97. package/src/components/MBodyMap.vue +266 -0
  98. package/src/components/MCandlestickChart.vue +479 -0
  99. package/src/components/MCertificate.vue +351 -0
  100. package/src/components/MCreditCardInput.vue +351 -0
  101. package/src/components/MFlow.vue +117 -17
  102. package/src/components/MMortgageCalculator.vue +258 -0
  103. package/src/components/MOdontogram.vue +462 -0
  104. package/src/components/MOrderBook.vue +287 -0
  105. package/src/components/MOrderTicket.vue +217 -0
  106. package/src/components/MPosKeypad.vue +406 -0
  107. package/src/components/MProductConfigurator.vue +412 -0
  108. package/src/components/MQuiz.vue +531 -0
  109. package/src/components/MReceipt.vue +249 -0
  110. package/src/components/MSeatMap.vue +431 -0
  111. package/src/components/MTicket.vue +209 -0
  112. package/src/components/MTour.vue +145 -27
  113. package/src/components/MVitalsChart.vue +303 -0
  114. package/src/composables/_printElement.ts +36 -0
  115. package/src/composables/cardBrand.ts +104 -0
  116. package/src/composables/flowPaths.ts +16 -7
  117. package/src/composables/mortgage.ts +70 -0
  118. package/src/composables/useFlow.ts +4 -0
  119. package/src/composables/useLocale.ts +277 -0
  120. package/src/flow.ts +1 -1
  121. package/src/index.ts +35 -0
  122. package/src/locales/de.ts +131 -0
  123. package/src/locales/es.ts +131 -0
  124. package/src/locales/fr.ts +131 -0
  125. package/src/locales/ja.ts +131 -0
  126. package/src/locales/ko.ts +131 -0
  127. package/src/locales/pt.ts +131 -0
  128. package/src/locales/zh.ts +131 -0
  129. package/dist/flowPaths-DzW-aiET.js.map +0 -1
  130. package/dist/useLocale-D2ucaY-l.js.map +0 -1
@@ -17,7 +17,7 @@ const emptySelection = (): FlowSelection => ({ nodes: [], edges: [] })
17
17
  * and the lock are too. Pan by dragging the background (or the wheel, or two fingers), zoom with Ctrl + wheel, a
18
18
  * trackpad or touch pinch, or a double click. Shift + drag (or `selectionOnDrag`; on touch, a long press on the
19
19
  * background) draws a selection box; Delete
20
- * removes what's selected, Ctrl+Z/Ctrl+Shift+Z undo and redo, Ctrl+C/X/V/A copy, cut, paste and select all, and
20
+ * removes what's selected, Ctrl+Z/Ctrl+Shift+Z undo and redo, Ctrl+C/X/V/D/A copy, cut, paste, duplicate and select all, and
21
21
  * the arrows move the selected nodes. A drag from a handle to another connects them; dropped on nothing it fires
22
22
  * `connect-end` with the spot, to offer a new node there. To disconnect: the × on a selected edge, Delete, dragging
23
23
  * an edge's end (or a connected input) away and dropping it on nothing. Alignment guides show while dragging one node.
@@ -80,7 +80,7 @@ import {
80
80
  type FlowXY,
81
81
  } from '../composables/useFlow'
82
82
  import { layoutLayered, layoutTree, type FlowLayout, type FlowLayoutDirection, type FlowLayoutOptions } from '../composables/flowLayout'
83
- import { distanceToPoints, edgePathPoints, getBezierPath, getRoutedPath, getSmoothStepPath, getStepPath, getStraightPath, pointsToRoute, routePoints, smoothStepPoints, type FlowEdgePath } from '../composables/flowPaths'
83
+ import { distanceToPoints, edgePathPoints, getBezierPath, getRoutedPath, getSmoothStepPath, getStepPath, getStraightPath, pointsToRoute, routePoints, smoothStepPoints, type FlowEdgePath, type FlowStepCenter } from '../composables/flowPaths'
84
84
  import { DEFAULT_SPATIAL } from '../composables/_useSpring'
85
85
  import { prefersReducedMotion } from '../composables/_springAnimation'
86
86
  import { useLocale } from '../composables/useLocale'
@@ -126,6 +126,12 @@ const props = withDefaults(defineProps<{
126
126
  * the route in `edge.route`), or drag a leg at either end to add a jog. Default off
127
127
  */
128
128
  edgesReroutable?: boolean
129
+ /**
130
+ * `smoothstep`/`step` edges from different sources whose middle runs would lie on top of each other, running the
131
+ * same way, are moved apart by this many px, so two wires never read as one (edges from the same output may share
132
+ * a run). Edges with their own `route` stay put and the others keep off them. Default 0: off
133
+ */
134
+ edgeSpacing?: number
129
135
  /** Merged into edges made by connecting (`type`, `animated`, `markerEnd`…) */
130
136
  defaultEdgeOptions?: Partial<FlowEdge>
131
137
  /** Adds an edge to `edges` when a connection is made; off, only `connect` fires */
@@ -199,6 +205,7 @@ const props = withDefaults(defineProps<{
199
205
  elementsSelectable: true,
200
206
  edgesReconnectable: true,
201
207
  edgesReroutable: false,
208
+ edgeSpacing: 0,
202
209
  autoConnect: true,
203
210
  connectionRadius: 24,
204
211
  deleteKeys: () => ['Delete', 'Backspace'],
@@ -631,7 +638,7 @@ function rawHandlePoint(nodeId: string, type: 'source' | 'target', handleId?: st
631
638
  // Arrowheads stop at a handle's rim instead of under it
632
639
  const HANDLE_RADIUS = 5
633
640
 
634
- function pathFor(type: string | undefined, p: Omit<EdgeGeometry, keyof FlowEdgePath | 'sourceInset' | 'targetInset'>): FlowEdgePath {
641
+ function pathFor(type: string | undefined, p: Omit<EdgeGeometry, keyof FlowEdgePath | 'sourceInset' | 'targetInset'> & FlowStepCenter): FlowEdgePath {
635
642
  switch (type) {
636
643
  case 'smoothstep': return getSmoothStepPath(p)
637
644
  case 'step': return getStepPath(p)
@@ -712,7 +719,7 @@ function edgeGeometry(e: FlowEdge): EdgeGeometry | null {
712
719
  if (!at) return null
713
720
  const { s, t, ends } = at
714
721
  const route = isOrthogonal(e) ? routeOf(e) : undefined
715
- const path = route ? getRoutedPath({ ...ends, route, borderRadius: edgeRoute(e) === 'step' ? 0 : 8 }) : pathFor(edgeRoute(e), ends)
722
+ const path = route ? getRoutedPath({ ...ends, route, borderRadius: edgeRoute(e) === 'step' ? 0 : 8 }) : pathFor(edgeRoute(e), { ...ends, ...lanes.value.get(e.id) })
716
723
  return { ...ends, ...path, sourceInset: s.inset, targetInset: t.inset }
717
724
  }
718
725
  function edgeCorners(e: FlowEdge): [number, number][] | null {
@@ -720,8 +727,73 @@ function edgeCorners(e: FlowEdge): [number, number][] | null {
720
727
  const at = edgeEnds(e)
721
728
  if (!at) return null
722
729
  const route = routeOf(e)
723
- return route ? routePoints({ ...at.ends, route }) : smoothStepPoints(at.ends)
724
- }
730
+ return route ? routePoints({ ...at.ends, route }) : smoothStepPoints({ ...at.ends, ...lanes.value.get(e.id) })
731
+ }
732
+
733
+ // ── Keeping parallel edges apart (edgeSpacing) ────────────────────────────────────────────────────────────
734
+ // Each step edge whose ends face each other has one free run halfway between them (vertical between left/right
735
+ // handles, horizontal between top/bottom ones). Those runs are laid out like lanes: one that would lie on another
736
+ // edge's run (same way, overlapping, from a different source) moves a spacing to either side, nearest first,
737
+ // staying between the legs. Everything else (legs, routed edges) is an obstacle that doesn't move.
738
+ const STEP_OFFSET = 20
739
+ interface Run { src: string; vertical: boolean; c: number; lo: number; hi: number }
740
+ function freeRun(ends: { sourceX: number; sourceY: number; sourcePosition: FlowPosition; targetX: number; targetY: number; targetPosition: FlowPosition }) {
741
+ const n = { left: -1, right: 1, top: -1, bottom: 1 } as const
742
+ const sH = ends.sourcePosition === 'left' || ends.sourcePosition === 'right'
743
+ const tH = ends.targetPosition === 'left' || ends.targetPosition === 'right'
744
+ if (sH !== tH) return null
745
+ const ns = n[ends.sourcePosition]
746
+ const nt = n[ends.targetPosition]
747
+ const [s, t] = sH ? [ends.sourceX, ends.targetX] : [ends.sourceY, ends.targetY]
748
+ if (ns !== -nt || (t - s) * ns < 2 * STEP_OFFSET) return null
749
+ const a = s + ns * STEP_OFFSET
750
+ const b = t + nt * STEP_OFFSET
751
+ return { vertical: sH, c: (s + t) / 2, min: Math.min(a, b), max: Math.max(a, b) }
752
+ }
753
+ const lanes = computed(() => {
754
+ const out = new Map<string, FlowStepCenter>()
755
+ const gap = props.edgeSpacing
756
+ if (!gap) return out
757
+ const placed: Run[] = []
758
+ const free: (Run & { id: string; min: number; max: number })[] = []
759
+ for (const e of visibleEdges.value) {
760
+ if (!isOrthogonal(e)) continue
761
+ const at = edgeEnds(e)
762
+ if (!at) continue
763
+ const src = `${e.source}\u0000${e.sourceHandle ?? ''}`
764
+ const route = routeOf(e)
765
+ const run = route ? null : freeRun(at.ends)
766
+ const pts = route ? routePoints({ ...at.ends, route }) : smoothStepPoints(at.ends)
767
+ for (let i = 1; i < pts.length; i++) {
768
+ const [ax, ay] = pts[i - 1]!
769
+ const [bx, by] = pts[i]!
770
+ const vertical = Math.abs(ax - bx) < 0.01
771
+ if (!vertical && Math.abs(ay - by) >= 0.01) continue
772
+ const r: Run = { src, vertical, c: vertical ? ax : ay, lo: vertical ? Math.min(ay, by) : Math.min(ax, bx), hi: vertical ? Math.max(ay, by) : Math.max(ax, bx) }
773
+ if (run && run.vertical === vertical && Math.abs(run.c - r.c) < 0.01) free.push({ ...r, id: e.id, min: run.min, max: run.max })
774
+ else placed.push(r)
775
+ }
776
+ }
777
+ const clash = (r: Run, c: number) =>
778
+ placed.some((o) => o.vertical === r.vertical && o.src !== r.src && Math.abs(o.c - c) < gap / 2 && Math.min(o.hi, r.hi) - Math.max(o.lo, r.lo) > 0.5)
779
+ // Longer runs first: they have the most to cross, and shorter ones fit around them
780
+ free.sort((a, b) => b.hi - b.lo - (a.hi - a.lo) || a.c - b.c)
781
+ for (const r of free) {
782
+ let c = r.c
783
+ for (let k = 0; k <= 16; k++) {
784
+ const step = k === 0 ? 0 : Math.ceil(k / 2) * gap * (k % 2 ? 1 : -1)
785
+ const at = r.c + step
786
+ if (at < r.min - 0.01 || at > r.max + 0.01) continue
787
+ if (!clash(r, at)) {
788
+ c = at
789
+ break
790
+ }
791
+ }
792
+ if (c !== r.c) out.set(r.id, r.vertical ? { centerX: c } : { centerY: c })
793
+ placed.push({ ...r, c })
794
+ }
795
+ return out
796
+ })
725
797
  const isReroutable = (e: FlowEdge) => !locked.value && isOrthogonal(e) && (e.reroutable ?? props.edgesReroutable)
726
798
 
727
799
  // What's drawn: groups under the edges, other nodes over them; children over their parents
@@ -911,11 +983,12 @@ function selectAll() {
911
983
  })
912
984
  }
913
985
 
914
- function copy() {
986
+ /** The selected nodes (their children too) and the edges between them, as copy() keeps them */
987
+ function selectionClip(): { nodes: FlowNode[]; edges: FlowEdge[] } | null {
915
988
  const ids = new Set(selLocal.value.nodes)
916
989
  for (const id of [...ids]) descendants(id).forEach((d) => ids.add(d))
917
- if (!ids.size) return
918
- clipboard = {
990
+ if (!ids.size) return null
991
+ return {
919
992
  nodes: nodesLocal.value.filter((n) => ids.has(n.id)).map((n) => {
920
993
  // A node copied without its group keeps its place on the canvas
921
994
  if (n.parentId && !ids.has(n.parentId)) {
@@ -926,6 +999,11 @@ function copy() {
926
999
  }),
927
1000
  edges: edgesLocal.value.filter((e) => ids.has(e.source) && ids.has(e.target)),
928
1001
  }
1002
+ }
1003
+ function copy() {
1004
+ const clip = selectionClip()
1005
+ if (!clip) return
1006
+ clipboard = clip
929
1007
  pasteCount = 0
930
1008
  }
931
1009
  function cut() {
@@ -936,21 +1014,33 @@ function cut() {
936
1014
  function paste(at?: FlowXY) {
937
1015
  if (!clipboard?.nodes.length || locked.value) return
938
1016
  pasteCount++
939
- const tops = clipboard.nodes.filter((n) => !n.parentId || !clipboard!.nodes.some((m) => m.id === n.parentId))
1017
+ place(clipboard, at, props.gridSize * 2 * pasteCount)
1018
+ }
1019
+ /** Copies of the selection a grid step or two away, leaving the clipboard alone */
1020
+ function duplicate() {
1021
+ const clip = selectionClip()
1022
+ if (!clip || locked.value) return
1023
+ place(clip, undefined, props.gridSize * 2)
1024
+ }
1025
+ /** Adds copies of `clip` (new ids), its top left at `at` or `step` from where it was, and selects them */
1026
+ function place(clip: { nodes: FlowNode[]; edges: FlowEdge[] }, at: FlowXY | undefined, step: number) {
1027
+ const tops = clip.nodes.filter((n) => !n.parentId || !clip.nodes.some((m) => m.id === n.parentId))
940
1028
  const minX = Math.min(...tops.map((n) => n.position.x))
941
1029
  const minY = Math.min(...tops.map((n) => n.position.y))
942
- const step = props.gridSize * 2 * pasteCount
943
- const dx = at ? at.x - minX : step
944
- const dy = at ? at.y - minY : step
945
- const idMap = new Map(clipboard.nodes.map((n) => [n.id, makeId('node')]))
1030
+ // On the grid, the same step as moving them would be, so a node that sat on it still does
1031
+ const gs = props.gridSize
1032
+ const onGrid = (v: number) => (props.snapToGrid && gs ? Math.round(v / gs) * gs : v)
1033
+ const dx = onGrid(at ? at.x - minX : step)
1034
+ const dy = onGrid(at ? at.y - minY : step)
1035
+ const idMap = new Map(clip.nodes.map((n) => [n.id, makeId('node')]))
946
1036
  const topIds = new Set(tops.map((n) => n.id))
947
- const nodes = clipboard.nodes.map((n) => ({
1037
+ const nodes = clip.nodes.map((n) => ({
948
1038
  ...n,
949
1039
  id: idMap.get(n.id)!,
950
1040
  parentId: n.parentId ? idMap.get(n.parentId) ?? n.parentId : undefined,
951
1041
  position: topIds.has(n.id) ? { x: n.position.x + dx, y: n.position.y + dy } : n.position,
952
1042
  }))
953
- const edges = clipboard.edges.map((e) => ({ ...e, id: makeId('edge'), source: idMap.get(e.source)!, target: idMap.get(e.target)! }))
1043
+ const edges = clip.edges.map((e) => ({ ...e, id: makeId('edge'), source: idMap.get(e.source)!, target: idMap.get(e.target)! }))
954
1044
  instantNext = true
955
1045
  commit({ nodes: [...nodesLocal.value, ...nodes], edges: edges.length ? [...edgesLocal.value, ...edges] : undefined })
956
1046
  setSelection({ nodes: nodes.map((n) => n.id), edges: edges.map((e) => e.id) })
@@ -1060,7 +1150,11 @@ function onPointerDown(e: PointerEvent) {
1060
1150
  if (gesture) return
1061
1151
  if (e.button === 2) return
1062
1152
  downTarget = t
1063
- root.value?.focus({ preventScroll: true })
1153
+ // The canvas takes the keys, except from content inside a node that handles its own (a field, a game pad, a piano
1154
+ // focusing itself on this same pointerdown would otherwise lose its focus at once). Its keys still bubble up here
1155
+ const own = t.closest(NO_DRAG)
1156
+ const ownerNode = own?.closest('[data-flow-node]')
1157
+ if (!own || !ownerNode || own === ownerNode) root.value?.focus({ preventScroll: true })
1064
1158
 
1065
1159
  const handle = t.closest<HTMLElement>('[data-flow-handle]')
1066
1160
  const reconnect = t.closest<HTMLElement>('[data-flow-reconnect]')
@@ -2025,6 +2119,7 @@ function onKeyDown(e: KeyboardEvent) {
2025
2119
  if (mod && key === 'a') { e.preventDefault(); selectAll(); return }
2026
2120
  if (mod && key === 'c') { copy(); return }
2027
2121
  if (mod && key === 'x') { e.preventDefault(); cut(); return }
2122
+ if (mod && key === 'd') { e.preventDefault(); duplicate(); return }
2028
2123
  if (mod && key === 'v') {
2029
2124
  e.preventDefault()
2030
2125
  paste(pointer.inside ? screenToFlow(pointer) : undefined)
@@ -2114,6 +2209,11 @@ const context: FlowInternals = {
2114
2209
  copy,
2115
2210
  cut,
2116
2211
  paste,
2212
+ duplicate,
2213
+ getEdgePath: (id: string) => {
2214
+ const e = edgeById.value.get(id)
2215
+ return (e && edgeGeometry(e)?.path) ?? null
2216
+ },
2117
2217
  startDrag,
2118
2218
  registerHandle,
2119
2219
  measureNode: queueMeasure,
@@ -0,0 +1,258 @@
1
+ <script lang="ts">
2
+ /** The inputs of an `MMortgageCalculator` (its v-model). */
3
+ export interface MortgageInput {
4
+ /** Price of the property */
5
+ price: number
6
+ /** Down payment, in money (not percent) */
7
+ down: number
8
+ /** Yearly interest rate, in percent */
9
+ rate: number
10
+ /** Term in years */
11
+ years: number
12
+ }
13
+ </script>
14
+
15
+ <script setup lang="ts">
16
+ /**
17
+ * A mortgage / loan calculator for a property listing or a bank: price, down payment, rate and term in, the monthly
18
+ * payment, the principal vs interest split and the yearly amortization schedule out. Supports the french system
19
+ * (the same payment every month) and the german one (the same principal every month, falling payments). The math
20
+ * is also exported on its own as `amortize()`.
21
+ *
22
+ * @slot summary Replaces the result panel. Slot props: `{ loan, monthly, schedule }`
23
+ * @event update:modelValue The inputs — powers v-model
24
+ */
25
+ import { computed, ref } from 'vue'
26
+ import MNumberField from './MNumberField.vue'
27
+ import MSlider from './MSlider.vue'
28
+ import MButton from './MButton.vue'
29
+ import { amortize } from '../composables/mortgage'
30
+ import { useLocale } from '../composables/useLocale'
31
+ import { vRipple } from '../directives/vRipple'
32
+
33
+ const locale = useLocale()
34
+
35
+ const props = withDefaults(
36
+ defineProps<{
37
+ /** The inputs (v-model) */
38
+ modelValue: MortgageInput
39
+ /** `french`: fixed payment. `german`: fixed principal, payments fall over time */
40
+ system?: 'french' | 'german'
41
+ /** Terms offered, in years */
42
+ terms?: number[]
43
+ /** Monthly costs added on top of the loan payment, e.g. property tax or insurance */
44
+ extras?: { label: string; amount: number }[]
45
+ /** ISO 4217 code to format amounts */
46
+ currency?: string
47
+ /** Fields layout: the default filled or outlined */
48
+ variant?: 'filled' | 'outlined'
49
+ /** Hides the inputs, showing only the results (for a read-only quote) */
50
+ readonly?: boolean
51
+ /** Shows the yearly schedule open */
52
+ scheduleOpen?: boolean
53
+ }>(),
54
+ {
55
+ system: 'french',
56
+ terms: () => [10, 15, 20, 25, 30],
57
+ extras: () => [],
58
+ variant: 'outlined',
59
+ readonly: false,
60
+ scheduleOpen: false,
61
+ },
62
+ )
63
+
64
+ const emit = defineEmits<{ 'update:modelValue': [MortgageInput] }>()
65
+
66
+ function update(patch: Partial<MortgageInput>) {
67
+ emit('update:modelValue', { ...props.modelValue, ...patch })
68
+ }
69
+
70
+ const loan = computed(() => Math.max(0, props.modelValue.price - props.modelValue.down))
71
+ const downPercent = computed(() => (props.modelValue.price > 0 ? (props.modelValue.down / props.modelValue.price) * 100 : 0))
72
+
73
+ const schedule = computed(() =>
74
+ amortize({ principal: loan.value, rate: props.modelValue.rate, years: props.modelValue.years, system: props.system }),
75
+ )
76
+ const extrasTotal = computed(() => props.extras.reduce((s, e) => s + e.amount, 0))
77
+ const monthly = computed(() => schedule.value.firstPayment + extrasTotal.value)
78
+
79
+ /** The schedule folded by year */
80
+ const years = computed(() => {
81
+ const out: { year: number; principal: number; interest: number; balance: number }[] = []
82
+ for (const p of schedule.value.payments) {
83
+ const y = Math.ceil(p.n / 12)
84
+ const row = out[y - 1] ?? (out[y - 1] = { year: y, principal: 0, interest: 0, balance: 0 })
85
+ row.principal += p.principal
86
+ row.interest += p.interest
87
+ row.balance = p.balance
88
+ }
89
+ return out
90
+ })
91
+
92
+ const fmt = computed(() =>
93
+ new Intl.NumberFormat(locale.lang, props.currency ? { style: 'currency', currency: props.currency, maximumFractionDigits: 0 } : { maximumFractionDigits: 0 }),
94
+ )
95
+ const fmtCents = computed(() =>
96
+ new Intl.NumberFormat(locale.lang, props.currency ? { style: 'currency', currency: props.currency } : { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
97
+ )
98
+
99
+ // Donut: principal vs interest of everything paid
100
+ const interestShare = computed(() => {
101
+ const t = schedule.value.totalPaid
102
+ return t > 0 ? schedule.value.totalInterest / t : 0
103
+ })
104
+ const R = 52
105
+ const C = 2 * Math.PI * R
106
+
107
+ const showSchedule = ref(props.scheduleOpen)
108
+
109
+ defineExpose({ loan, monthly, schedule })
110
+ </script>
111
+
112
+ <template>
113
+ <div class="m3-mortgage @container text-on-surface">
114
+ <div class="grid gap-6 @2xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
115
+ <div v-if="!readonly" class="flex flex-col gap-4">
116
+ <MNumberField
117
+ :model-value="modelValue.price"
118
+ :label="locale.mortgagePrice"
119
+ :variant="variant"
120
+ :min="0"
121
+ :step="1000"
122
+ leading-icon="home"
123
+ data-field="price"
124
+ @update:model-value="(v) => update({ price: v ?? 0, down: Math.min(modelValue.down, v ?? 0) })"
125
+ />
126
+ <div class="flex flex-col gap-1">
127
+ <MNumberField
128
+ :model-value="modelValue.down"
129
+ :label="locale.mortgageDown"
130
+ :variant="variant"
131
+ :min="0"
132
+ :max="modelValue.price"
133
+ :step="1000"
134
+ :hint="`${downPercent.toFixed(1)}%`"
135
+ leading-icon="savings"
136
+ data-field="down"
137
+ @update:model-value="(v) => update({ down: Math.min(v ?? 0, modelValue.price) })"
138
+ />
139
+ <MSlider
140
+ :model-value="Math.round(downPercent)"
141
+ :min="0"
142
+ :max="100"
143
+ :step="1"
144
+ size="xs"
145
+ :aria-label="locale.mortgageDown"
146
+ @update:model-value="(v) => update({ down: Math.round((modelValue.price * (v as number)) / 100) })"
147
+ />
148
+ </div>
149
+ <MNumberField
150
+ :model-value="modelValue.rate"
151
+ :label="locale.mortgageRate"
152
+ :variant="variant"
153
+ :min="0"
154
+ :max="100"
155
+ :step="0.05"
156
+ leading-icon="percent"
157
+ data-field="rate"
158
+ @update:model-value="(v) => update({ rate: v ?? 0 })"
159
+ />
160
+ <div>
161
+ <p class="mb-2 text-label-large text-on-surface-variant">{{ locale.mortgageTerm }}</p>
162
+ <div class="flex flex-wrap gap-2" role="radiogroup" :aria-label="locale.mortgageTerm">
163
+ <button
164
+ v-for="t in terms"
165
+ :key="t"
166
+ v-ripple
167
+ type="button"
168
+ role="radio"
169
+ :aria-checked="modelValue.years === t"
170
+ class="relative flex h-9 items-center gap-1 overflow-hidden rounded-sm border px-3 text-label-large transition-colors"
171
+ :class="modelValue.years === t
172
+ ? 'border-transparent bg-secondary-container text-on-secondary-container'
173
+ : 'border-outline-variant text-on-surface-variant'"
174
+ :data-term="t"
175
+ @click="update({ years: t })"
176
+ >
177
+ {{ locale.mortgageYears.replace('{n}', String(t)) }}
178
+ </button>
179
+ </div>
180
+ </div>
181
+ </div>
182
+
183
+ <div class="flex flex-col gap-4 rounded-lg bg-surface-container p-5">
184
+ <slot name="summary" :loan="loan" :monthly="monthly" :schedule="schedule">
185
+ <div>
186
+ <p class="text-label-large text-on-surface-variant">
187
+ {{ system === 'german' ? locale.mortgageFirstPayment : locale.mortgageMonthly }}
188
+ </p>
189
+ <p class="text-display-small font-medium tabular-nums text-primary" data-monthly>{{ fmtCents.format(monthly) }}</p>
190
+ <p v-if="extras.length" class="text-body-medium text-on-surface-variant tabular-nums" data-extras>
191
+ {{ fmtCents.format(schedule.firstPayment) }}<template v-for="e in extras" :key="e.label"> + {{ e.label }} {{ fmtCents.format(e.amount) }}</template>
192
+ </p>
193
+ <p v-if="system === 'german' && schedule.payments.length" class="text-body-medium text-on-surface-variant tabular-nums">
194
+ {{ locale.mortgageLastPayment }}: {{ fmtCents.format(schedule.lastPayment + extrasTotal) }}
195
+ </p>
196
+ </div>
197
+
198
+ <div class="flex items-center gap-5">
199
+ <svg viewBox="0 0 128 128" class="h-28 w-28 shrink-0 -rotate-90" aria-hidden="true">
200
+ <circle cx="64" cy="64" :r="R" fill="none" stroke="var(--color-primary)" stroke-width="16" />
201
+ <circle
202
+ cx="64"
203
+ cy="64"
204
+ :r="R"
205
+ fill="none"
206
+ stroke="var(--color-tertiary)"
207
+ stroke-width="16"
208
+ :stroke-dasharray="`${interestShare * C} ${C}`"
209
+ class="transition-[stroke-dasharray] duration-300"
210
+ />
211
+ </svg>
212
+ <dl class="grid flex-1 grid-cols-[auto_1fr] items-center gap-x-3 gap-y-1 text-body-medium">
213
+ <dt class="flex items-center gap-2"><span class="h-3 w-3 rounded-full bg-primary" />{{ locale.mortgageLoan }}</dt>
214
+ <dd class="text-end tabular-nums" data-loan>{{ fmt.format(loan) }}</dd>
215
+ <dt class="flex items-center gap-2"><span class="h-3 w-3 rounded-full bg-tertiary" />{{ locale.mortgageInterest }}</dt>
216
+ <dd class="text-end tabular-nums" data-interest>{{ fmt.format(schedule.totalInterest) }}</dd>
217
+ <dt class="mt-1 border-t border-outline-variant pt-1 font-medium">{{ locale.mortgageTotal }}</dt>
218
+ <dd class="mt-1 border-t border-outline-variant pt-1 text-end font-medium tabular-nums">{{ fmt.format(schedule.totalPaid) }}</dd>
219
+ </dl>
220
+ </div>
221
+ </slot>
222
+ </div>
223
+ </div>
224
+
225
+ <div v-if="years.length" class="mt-4">
226
+ <MButton variant="text" :icon="showSchedule ? 'expand_less' : 'expand_more'" :aria-expanded="showSchedule" data-toggle-schedule @click="showSchedule = !showSchedule">
227
+ {{ locale.mortgageSchedule }}
228
+ </MButton>
229
+ <div v-if="showSchedule" class="mt-2 max-h-80 overflow-auto rounded-md border border-outline-variant">
230
+ <table class="w-full text-body-medium tabular-nums" data-schedule>
231
+ <thead class="sticky top-0 bg-surface-container-high text-label-large text-on-surface-variant">
232
+ <tr>
233
+ <th class="px-3 py-2 text-start font-medium">{{ locale.mortgageYear }}</th>
234
+ <th class="px-3 py-2 text-end font-medium">{{ locale.mortgagePrincipal }}</th>
235
+ <th class="px-3 py-2 text-end font-medium">{{ locale.mortgageInterest }}</th>
236
+ <th class="px-3 py-2 text-end font-medium">{{ locale.mortgageBalance }}</th>
237
+ </tr>
238
+ </thead>
239
+ <tbody>
240
+ <tr v-for="y in years" :key="y.year" class="border-t border-outline-variant">
241
+ <td class="px-3 py-1.5">{{ y.year }}</td>
242
+ <td class="px-3 py-1.5 text-end">{{ fmt.format(y.principal) }}</td>
243
+ <td class="px-3 py-1.5 text-end">{{ fmt.format(y.interest) }}</td>
244
+ <td class="px-3 py-1.5 text-end">
245
+ <div class="flex items-center justify-end gap-2">
246
+ <span class="hidden h-1.5 w-16 overflow-hidden rounded-full bg-surface-container-highest sm:block">
247
+ <span class="block h-full bg-primary" :style="{ width: `${loan ? (y.balance / loan) * 100 : 0}%` }" />
248
+ </span>
249
+ {{ fmt.format(y.balance) }}
250
+ </div>
251
+ </td>
252
+ </tr>
253
+ </tbody>
254
+ </table>
255
+ </div>
256
+ </div>
257
+ </div>
258
+ </template>