@m3ui-vue/m3ui-vue 1.3.8 → 1.4.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 (117) hide show
  1. package/dist/API.md +1102 -20
  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/MBeforeAfter.vue.d.ts +61 -0
  25. package/dist/components/MBodyMap.vue.d.ts +70 -0
  26. package/dist/components/MCandlestickChart.vue.d.ts +82 -0
  27. package/dist/components/MCertificate.vue.d.ts +76 -0
  28. package/dist/components/MCountdown.vue.d.ts +80 -0
  29. package/dist/components/MCreditCardInput.vue.d.ts +75 -0
  30. package/dist/components/MMortgageCalculator.vue.d.ts +83 -0
  31. package/dist/components/MOdontogram.vue.d.ts +86 -0
  32. package/dist/components/MOrderBook.vue.d.ts +89 -0
  33. package/dist/components/MOrderTicket.vue.d.ts +91 -0
  34. package/dist/components/MPosKeypad.vue.d.ts +84 -0
  35. package/dist/components/MProductConfigurator.vue.d.ts +136 -0
  36. package/dist/components/MQuiz.vue.d.ts +102 -0
  37. package/dist/components/MReceipt.vue.d.ts +93 -0
  38. package/dist/components/MSeatMap.vue.d.ts +131 -0
  39. package/dist/components/MSeekBar.vue.d.ts +1 -1
  40. package/dist/components/MTicket.vue.d.ts +83 -0
  41. package/dist/components/MVideoPlayer.vue.d.ts +1 -1
  42. package/dist/components/MVitalsChart.vue.d.ts +73 -0
  43. package/dist/composables/_printElement.d.ts +9 -0
  44. package/dist/composables/cardBrand.d.ts +25 -0
  45. package/dist/composables/mortgage.d.ts +37 -0
  46. package/dist/composables/useLocale.d.ts +131 -0
  47. package/dist/draw.js +2 -2
  48. package/dist/flow.js +1 -1
  49. package/dist/gantt.js +1 -1
  50. package/dist/index.d.ts +37 -0
  51. package/dist/locales/index.js +924 -7
  52. package/dist/locales/index.js.map +1 -1
  53. package/dist/m3ui-vue.css +1 -1
  54. package/dist/m3ui.js +10125 -5263
  55. package/dist/m3ui.js.map +1 -1
  56. package/dist/map.js +5 -5
  57. package/dist/media.js +4 -4
  58. package/dist/pdf.js +4 -4
  59. package/dist/rich-text-editor.js +4 -4
  60. package/dist/styles.css +1 -1
  61. package/dist/{useLocale-D2ucaY-l.js → useLocale-DLKJIRFi.js} +133 -2
  62. package/dist/useLocale-DLKJIRFi.js.map +1 -0
  63. package/package.json +1 -1
  64. package/src/__tests__/MAvailabilityCalendar.test.ts +85 -0
  65. package/src/__tests__/MBeforeAfter.test.ts +79 -0
  66. package/src/__tests__/MBodyMap.test.ts +60 -0
  67. package/src/__tests__/MCandlestickChart.test.ts +66 -0
  68. package/src/__tests__/MCertificate.test.ts +32 -0
  69. package/src/__tests__/MCountdown.test.ts +75 -0
  70. package/src/__tests__/MCreditCardInput.test.ts +122 -0
  71. package/src/__tests__/MMortgageCalculator.test.ts +49 -0
  72. package/src/__tests__/MOdontogram.test.ts +93 -0
  73. package/src/__tests__/MOrderBook.test.ts +66 -0
  74. package/src/__tests__/MOrderTicket.test.ts +68 -0
  75. package/src/__tests__/MPosKeypad.test.ts +116 -0
  76. package/src/__tests__/MProductConfigurator.test.ts +73 -0
  77. package/src/__tests__/MQuiz.test.ts +104 -0
  78. package/src/__tests__/MReceipt.test.ts +52 -0
  79. package/src/__tests__/MSeatMap.test.ts +76 -0
  80. package/src/__tests__/MTicket.test.ts +38 -0
  81. package/src/__tests__/MVitalsChart.test.ts +49 -0
  82. package/src/__tests__/clearToNull.test.ts +30 -0
  83. package/src/__tests__/mortgage.test.ts +25 -0
  84. package/src/__tests__/ssr.test.ts +11 -0
  85. package/src/components/MAutocomplete.vue +2 -2
  86. package/src/components/MAvailabilityCalendar.vue +460 -0
  87. package/src/components/MBeforeAfter.vue +248 -0
  88. package/src/components/MBodyMap.vue +266 -0
  89. package/src/components/MCandlestickChart.vue +479 -0
  90. package/src/components/MCertificate.vue +351 -0
  91. package/src/components/MCountdown.vue +200 -0
  92. package/src/components/MCreditCardInput.vue +351 -0
  93. package/src/components/MMortgageCalculator.vue +258 -0
  94. package/src/components/MOdontogram.vue +462 -0
  95. package/src/components/MOrderBook.vue +287 -0
  96. package/src/components/MOrderTicket.vue +217 -0
  97. package/src/components/MPosKeypad.vue +406 -0
  98. package/src/components/MProductConfigurator.vue +412 -0
  99. package/src/components/MQuiz.vue +531 -0
  100. package/src/components/MReceipt.vue +249 -0
  101. package/src/components/MSeatMap.vue +431 -0
  102. package/src/components/MSelect.vue +2 -2
  103. package/src/components/MTicket.vue +209 -0
  104. package/src/components/MVitalsChart.vue +303 -0
  105. package/src/composables/_printElement.ts +36 -0
  106. package/src/composables/cardBrand.ts +104 -0
  107. package/src/composables/mortgage.ts +70 -0
  108. package/src/composables/useLocale.ts +277 -0
  109. package/src/index.ts +37 -0
  110. package/src/locales/de.ts +131 -0
  111. package/src/locales/es.ts +131 -0
  112. package/src/locales/fr.ts +131 -0
  113. package/src/locales/ja.ts +131 -0
  114. package/src/locales/ko.ts +131 -0
  115. package/src/locales/pt.ts +131 -0
  116. package/src/locales/zh.ts +131 -0
  117. package/dist/useLocale-D2ucaY-l.js.map +0 -1
@@ -0,0 +1,351 @@
1
+ <script lang="ts">
2
+ /** Value of `MCreditCardInput` (v-model). `number` holds digits only; `expiry` is `MM/YY`. */
3
+ export interface CreditCardValue {
4
+ number: string
5
+ expiry: string
6
+ cvc: string
7
+ name?: string
8
+ }
9
+
10
+ export type CreditCardField = 'number' | 'expiry' | 'cvc' | 'name'
11
+ </script>
12
+
13
+ <script setup lang="ts">
14
+ /**
15
+ * Card payment fields: number, expiry, security code and optionally the cardholder's name, with a live card
16
+ * preview that turns over while the security code is typed. The number is grouped as its network prints it
17
+ * (4-6-5 for American Express), the network is detected from the first digits, and every field is checked
18
+ * (length, Luhn checksum, a future expiry, the code's length for that network).
19
+ *
20
+ * It only collects and checks what is typed: it doesn't tokenize or send anything. Hand the value to your
21
+ * payment provider's SDK.
22
+ *
23
+ * @slot brand Replaces the network wordmark on the preview. Slot props: `{ brand, name }`
24
+ * @event update:modelValue Emitted on every change — powers v-model
25
+ * @event complete Emitted when every field becomes valid, with the value
26
+ * @event brand Emitted when the detected network changes
27
+ */
28
+ import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
29
+ import MTextField from './MTextField.vue'
30
+ import { useLocale } from '../composables/useLocale'
31
+ import {
32
+ detectCardBrand,
33
+ formatCardNumber,
34
+ isValidCardNumber,
35
+ isValidExpiry,
36
+ type CardBrand,
37
+ } from '../composables/cardBrand'
38
+
39
+ const locale = useLocale()
40
+
41
+ const props = withDefaults(
42
+ defineProps<{
43
+ /** Card value (v-model) */
44
+ modelValue: CreditCardValue
45
+ /** Shows the card preview above the fields */
46
+ preview?: boolean
47
+ /** Adds the "Name on card" field */
48
+ showName?: boolean
49
+ /** Visual style of the fields */
50
+ variant?: 'filled' | 'outlined'
51
+ /** Moves focus to the next field once one is complete and valid */
52
+ autoAdvance?: boolean
53
+ /** Error messages to show regardless of the built-in checks, e.g. a decline from the server */
54
+ errors?: Partial<Record<CreditCardField, string>>
55
+ /** Disables every field */
56
+ disabled?: boolean
57
+ }>(),
58
+ {
59
+ preview: true,
60
+ showName: false,
61
+ variant: 'filled',
62
+ autoAdvance: true,
63
+ disabled: false,
64
+ },
65
+ )
66
+
67
+ const emit = defineEmits<{
68
+ 'update:modelValue': [CreditCardValue]
69
+ complete: [CreditCardValue]
70
+ brand: [CardBrand]
71
+ }>()
72
+
73
+ const numberField = ref<InstanceType<typeof MTextField> | null>(null)
74
+ const expiryField = ref<InstanceType<typeof MTextField> | null>(null)
75
+ const cvcField = ref<InstanceType<typeof MTextField> | null>(null)
76
+ const nameField = ref<InstanceType<typeof MTextField> | null>(null)
77
+
78
+ const brandInfo = computed(() => detectCardBrand(props.modelValue.number ?? ''))
79
+ const maxDigits = computed(() => Math.max(...brandInfo.value.lengths))
80
+
81
+ const formattedNumber = computed(() => formatCardNumber(props.modelValue.number ?? ''))
82
+
83
+ const validity = computed(() => ({
84
+ number: isValidCardNumber(props.modelValue.number ?? ''),
85
+ expiry: isValidExpiry(props.modelValue.expiry ?? ''),
86
+ cvc: new RegExp(`^\\d{${brandInfo.value.cvcLength}}$`).test(props.modelValue.cvc ?? ''),
87
+ name: !props.showName || !!props.modelValue.name?.trim(),
88
+ }))
89
+ const valid = computed(() => Object.values(validity.value).every(Boolean))
90
+
91
+ watch(valid, (v) => { if (v) emit('complete', { ...props.modelValue }) })
92
+ watch(() => brandInfo.value.brand, (b) => emit('brand', b))
93
+
94
+ // A field shows its error once it has been left (or validate() was called)
95
+ const touched = reactive<Record<CreditCardField, boolean>>({ number: false, expiry: false, cvc: false, name: false })
96
+
97
+ const messages: Record<CreditCardField, () => string> = {
98
+ number: () => locale.cardInvalidNumber,
99
+ expiry: () => locale.cardInvalidExpiry,
100
+ cvc: () => locale.cardInvalidCvc,
101
+ name: () => '',
102
+ }
103
+
104
+ function errorFor(field: CreditCardField): string | undefined {
105
+ if (props.errors?.[field]) return props.errors[field]
106
+ if (!touched[field] || validity.value[field]) return undefined
107
+ return messages[field]() || undefined
108
+ }
109
+
110
+ function update(patch: Partial<CreditCardValue>) {
111
+ emit('update:modelValue', { ...props.modelValue, ...patch })
112
+ }
113
+
114
+ // Writes the reformatted text into the input (Vue skips the patch when the bound value didn't change, e.g. a
115
+ // letter or a digit past the maximum was typed) and puts the caret back after the same number of digits
116
+ function restoreCaret(field: InstanceType<typeof MTextField> | null, text: string, digitsBefore: number) {
117
+ nextTick(() => {
118
+ const el = field?.inputEl as HTMLInputElement | null | undefined
119
+ if (!el) return
120
+ if (el.value !== text) el.value = text
121
+ if (document.activeElement !== el) return
122
+ let pos = 0
123
+ let seen = 0
124
+ while (pos < el.value.length && seen < digitsBefore) {
125
+ if (/\d/.test(el.value[pos]!)) seen++
126
+ pos++
127
+ }
128
+ el.setSelectionRange(pos, pos)
129
+ })
130
+ }
131
+
132
+ function digitsBeforeCaret(field: InstanceType<typeof MTextField> | null, text: string) {
133
+ const el = field?.inputEl as HTMLInputElement | null | undefined
134
+ const caret = el?.selectionStart ?? text.length
135
+ return text.slice(0, caret).replace(/\D/g, '').length
136
+ }
137
+
138
+ function onNumber(text: string) {
139
+ const before = digitsBeforeCaret(numberField.value, text)
140
+ const digits = text.replace(/\D/g, '').slice(0, Math.max(...detectCardBrand(text).lengths))
141
+ update({ number: digits })
142
+ restoreCaret(numberField.value, formatCardNumber(digits), before)
143
+ if (props.autoAdvance && digits.length === Math.max(...detectCardBrand(digits).lengths) && isValidCardNumber(digits)) {
144
+ nextTick(() => (props.showName ? nameField.value : expiryField.value)?.focus())
145
+ }
146
+ }
147
+
148
+ function formatExpiry(digits: string) {
149
+ // A first digit above 1 can only be a single-digit month
150
+ if (digits.length === 1 && Number(digits) > 1) digits = '0' + digits
151
+ return digits.length > 2 ? `${digits.slice(0, 2)}/${digits.slice(2, 4)}` : digits
152
+ }
153
+
154
+ function onExpiry(text: string) {
155
+ const before = digitsBeforeCaret(expiryField.value, text)
156
+ const digits = text.replace(/\D/g, '').slice(0, 4)
157
+ const expiry = formatExpiry(digits)
158
+ update({ expiry })
159
+ restoreCaret(expiryField.value, expiry, before + (digits.length === 1 && expiry.length === 2 ? 1 : 0))
160
+ if (props.autoAdvance && expiry.length === 5 && isValidExpiry(expiry)) nextTick(() => cvcField.value?.focus())
161
+ }
162
+
163
+ function onCvc(text: string) {
164
+ const cvc = text.replace(/\D/g, '').slice(0, brandInfo.value.cvcLength)
165
+ update({ cvc })
166
+ restoreCaret(cvcField.value, cvc, digitsBeforeCaret(cvcField.value, text))
167
+ }
168
+
169
+ function onName(text: string) {
170
+ update({ name: text })
171
+ }
172
+
173
+ // Re-trim the security code when the network changes to one with a shorter code
174
+ watch(() => brandInfo.value.cvcLength, (len) => {
175
+ if ((props.modelValue.cvc ?? '').length > len) update({ cvc: props.modelValue.cvc.slice(0, len) })
176
+ })
177
+
178
+ const cvcFocused = ref(false)
179
+ const focusedField = ref<CreditCardField | null>(null)
180
+
181
+ onMounted(() => {
182
+ // MTextField forwards attrs to its wrapper, so input hints are set on the inputs here
183
+ const set = (f: InstanceType<typeof MTextField> | null, attrs: Record<string, string>) => {
184
+ const el = f?.inputEl as HTMLInputElement | null | undefined
185
+ if (el) for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v)
186
+ }
187
+ set(numberField.value, { inputmode: 'numeric', name: 'cc-number' })
188
+ set(expiryField.value, { inputmode: 'numeric', name: 'cc-exp', maxlength: '5' })
189
+ set(cvcField.value, { inputmode: 'numeric', name: 'cc-csc', maxlength: '4' })
190
+ set(nameField.value, { name: 'cc-name', autocapitalize: 'characters' })
191
+ })
192
+
193
+ function onFocusIn(field: CreditCardField) {
194
+ focusedField.value = field
195
+ cvcFocused.value = field === 'cvc'
196
+ }
197
+ function onFocusOut(field: CreditCardField) {
198
+ touched[field] = true
199
+ if (focusedField.value === field) focusedField.value = null
200
+ if (field === 'cvc') cvcFocused.value = false
201
+ }
202
+
203
+ // Preview: placeholder bullets where digits haven't been typed yet
204
+ const previewNumber = computed(() => {
205
+ const digits = props.modelValue.number ?? ''
206
+ const len = Math.max(digits.length, brandInfo.value.brand === 'amex' ? 15 : brandInfo.value.brand === 'diners' && digits.length <= 14 ? 14 : 16)
207
+ const { gaps } = brandInfo.value
208
+ let out = ''
209
+ for (let i = 0; i < len; i++) {
210
+ if (i > 0 && gaps.includes(i)) out += ' '
211
+ out += digits[i] ?? '•'
212
+ }
213
+ return out
214
+ })
215
+ const previewExpiry = computed(() => props.modelValue.expiry || 'MM/YY')
216
+ const previewCvc = computed(() => (props.modelValue.cvc ?? '').padEnd(brandInfo.value.cvcLength, '•'))
217
+
218
+ defineExpose({
219
+ /** Detected card network */
220
+ brand: computed(() => brandInfo.value.brand),
221
+ /** Whether every field is valid */
222
+ valid,
223
+ /** Shows the errors of every field (as if each had been visited) and returns whether all are valid */
224
+ validate: () => {
225
+ touched.number = touched.expiry = touched.cvc = touched.name = true
226
+ return valid.value
227
+ },
228
+ /** Focuses a field (the number by default) */
229
+ focus: (field: CreditCardField = 'number') =>
230
+ ({ number: numberField, expiry: expiryField, cvc: cvcField, name: nameField })[field].value?.focus(),
231
+ })
232
+ </script>
233
+
234
+ <template>
235
+ <div class="flex flex-col gap-4">
236
+ <div v-if="preview" class="m3-cc-preview mx-auto w-full max-w-[340px]" aria-hidden="true">
237
+ <div class="m3-cc-preview__inner relative aspect-[1.586]" :class="{ 'is-flipped': cvcFocused }">
238
+ <!-- Front -->
239
+ <div class="m3-cc-preview__face absolute inset-0 flex flex-col justify-between overflow-hidden rounded-xl bg-linear-135 from-primary to-tertiary p-5 text-on-primary shadow-elevation-2">
240
+ <div class="flex items-start justify-between">
241
+ <div class="h-8 w-11 rounded-md bg-on-primary/25 ring-1 ring-on-primary/30" />
242
+ <slot name="brand" :brand="brandInfo.brand" :name="brandInfo.name">
243
+ <span class="text-title-medium font-bold italic tracking-wide" :class="brandInfo.name ? 'opacity-100' : 'opacity-0'">{{ brandInfo.name }}</span>
244
+ </slot>
245
+ </div>
246
+ <div
247
+ class="m3-cc-mono text-title-large tracking-[0.12em] tabular-nums whitespace-nowrap"
248
+ :class="focusedField === 'number' ? 'opacity-100' : 'opacity-90'"
249
+ >{{ previewNumber }}</div>
250
+ <div class="flex items-end justify-between gap-3 text-label-large uppercase">
251
+ <span class="min-w-0 truncate" :class="{ 'opacity-60': !modelValue.name }">{{ modelValue.name || (showName ? locale.cardName : '') }}</span>
252
+ <span class="m3-cc-mono shrink-0 tabular-nums" :class="{ 'opacity-60': !modelValue.expiry }">{{ previewExpiry }}</span>
253
+ </div>
254
+ </div>
255
+ <!-- Back -->
256
+ <div class="m3-cc-preview__face m3-cc-preview__back absolute inset-0 overflow-hidden rounded-xl bg-linear-135 from-tertiary to-primary text-on-primary shadow-elevation-2">
257
+ <div class="mt-6 h-10 bg-on-surface/80" />
258
+ <div class="mx-5 mt-5 flex h-9 items-center justify-end rounded-sm bg-surface-container-highest px-3 text-on-surface">
259
+ <span class="m3-cc-mono text-title-medium italic tracking-widest">{{ previewCvc }}</span>
260
+ </div>
261
+ </div>
262
+ </div>
263
+ </div>
264
+
265
+ <div class="flex flex-col gap-3">
266
+ <div @focusin="onFocusIn('number')" @focusout="onFocusOut('number')">
267
+ <MTextField
268
+ ref="numberField"
269
+ :model-value="formattedNumber"
270
+ :label="locale.cardNumber"
271
+ :variant="variant"
272
+ :disabled="disabled"
273
+ autocomplete="cc-number"
274
+ leading-icon="credit_card"
275
+ :error="!!errorFor('number')"
276
+ :error-label="errorFor('number')"
277
+ @update:model-value="onNumber"
278
+ />
279
+ </div>
280
+ <div v-if="showName" @focusin="onFocusIn('name')" @focusout="onFocusOut('name')">
281
+ <MTextField
282
+ ref="nameField"
283
+ :model-value="modelValue.name ?? ''"
284
+ :label="locale.cardName"
285
+ :variant="variant"
286
+ :disabled="disabled"
287
+ autocomplete="cc-name"
288
+ :error="!!errors?.name"
289
+ :error-label="errors?.name"
290
+ @update:model-value="onName"
291
+ />
292
+ </div>
293
+ <div class="grid grid-cols-2 gap-3">
294
+ <div @focusin="onFocusIn('expiry')" @focusout="onFocusOut('expiry')">
295
+ <MTextField
296
+ ref="expiryField"
297
+ :model-value="modelValue.expiry ?? ''"
298
+ :label="locale.cardExpiry"
299
+ :variant="variant"
300
+ :disabled="disabled"
301
+ autocomplete="cc-exp"
302
+ :error="!!errorFor('expiry')"
303
+ :error-label="errorFor('expiry')"
304
+ @update:model-value="onExpiry"
305
+ />
306
+ </div>
307
+ <div @focusin="onFocusIn('cvc')" @focusout="onFocusOut('cvc')">
308
+ <MTextField
309
+ ref="cvcField"
310
+ :model-value="modelValue.cvc ?? ''"
311
+ :label="locale.cardCvc"
312
+ :variant="variant"
313
+ :disabled="disabled"
314
+ autocomplete="cc-csc"
315
+ :error="!!errorFor('cvc')"
316
+ :error-label="errorFor('cvc')"
317
+ @update:model-value="onCvc"
318
+ />
319
+ </div>
320
+ </div>
321
+ </div>
322
+ </div>
323
+ </template>
324
+
325
+ <style>
326
+ .m3-cc-preview {
327
+ perspective: 1200px;
328
+ }
329
+ .m3-cc-preview__inner {
330
+ transform-style: preserve-3d;
331
+ transition: transform 500ms cubic-bezier(0.2, 0, 0, 1);
332
+ }
333
+ .m3-cc-preview__inner.is-flipped {
334
+ transform: rotateY(180deg);
335
+ }
336
+ .m3-cc-preview__face {
337
+ backface-visibility: hidden;
338
+ -webkit-backface-visibility: hidden;
339
+ }
340
+ .m3-cc-preview__back {
341
+ transform: rotateY(180deg);
342
+ }
343
+ .m3-cc-mono {
344
+ font-family: var(--font-mono, ui-monospace, monospace);
345
+ }
346
+ @media (prefers-reduced-motion: reduce) {
347
+ .m3-cc-preview__inner {
348
+ transition: none;
349
+ }
350
+ }
351
+ </style>
@@ -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>