@getcortexlabs/create-mavis 0.1.0-rc.13 → 0.1.0-rc.14
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.
- package/README.md +26 -5
- package/package.json +4 -2
- package/src/adapters.mjs +7 -0
- package/src/add-macos.mjs +386 -0
- package/src/capabilities.mjs +78 -57
- package/src/cli.mjs +86 -4
- package/src/doctor.mjs +100 -18
- package/src/macos-capabilities.generated.mjs +4190 -0
- package/src/macos.mjs +147 -29
- package/src/migrate-directory.mjs +121 -0
- package/src/portability.mjs +108 -5
- package/src/scaffold.mjs +21 -2
- package/src/ui.mjs +21 -12
- package/templates/directory/host/directory-storage.ts +78 -0
- package/templates/directory/macos/DirectoryStorage.swift +68 -0
- package/templates/directory/mobile/src/app.ts +11 -8
- package/templates/directory/nuxt/app/plugins/mavis.ts +11 -8
- package/templates/directory/shared/Edit.vue +8 -5
- package/templates/directory/shared/directory-store.ts +42 -46
- package/templates/directory/vite/src/main.ts +11 -8
- package/templates/macos/examples/tasks/shared/TaskDetail.lite.tsx +2 -2
- package/templates/macos/examples/tasks/shared/Tasks.lite.tsx +2 -2
- package/templates/macos/examples/tasks/shared/types.ts +1 -0
- package/templates/macos/mobile/src/App.vue +4 -2
- package/templates/macos/native/Package.swift +3 -1
- package/templates/macos/native/Sources/MavisDesktop/App.swift +26 -11
- package/templates/macos/native/Sources/MavisDesktop/Fonts/LICENSE +45 -0
- package/templates/macos/native/Sources/MavisDesktop/Fonts/lucide.ttf +0 -0
- package/templates/macos/scripts/generate.mjs +3 -26
- package/templates/macos/scripts/macos-manifest.mjs +33 -0
- package/templates/macos/scripts/macos.mjs +20 -18
- package/templates/macos/web/index.html +1 -1
- package/templates/macos/web/src/main.js +176 -3
- package/templates/macos/web/src/mavis.js +2 -0
- package/templates/macos/web/src/style.css +2 -1
- package/templates/macos/web/vite.config.mjs +12 -1
- package/templates/migrations/directory-rc13.json +36 -0
- package/templates/mobile/src/mavis.ts +2 -82
- package/templates/mobile/webpack.config.js +4 -0
- package/templates/nuxt/app/mavis.ts +2 -84
- package/templates/vite/src/mavis.ts +2 -84
- package/templates/macos/scripts/portable/emit-swift.mjs +0 -1287
- package/templates/macos/scripts/portable/emit-vue.mjs +0 -615
- package/templates/macos/scripts/portable/index.mjs +0 -95
- package/templates/macos/scripts/portable/model.mjs +0 -1441
- package/templates/macos/scripts/portable/program.mjs +0 -163
|
@@ -1,1287 +0,0 @@
|
|
|
1
|
-
// SwiftUI output. JavaScript semantics are kept where the platforms differ: numbers are
|
|
2
|
-
// Double, text length counts UTF-16 units, number text follows Number#toString, and
|
|
3
|
-
// trim/splice/slice/Math.round follow the ECMAScript rules (see runtime below).
|
|
4
|
-
|
|
5
|
-
/** The JoltSwiftUI package every generated Mac app links. */
|
|
6
|
-
export const joltSwift = Object.freeze({
|
|
7
|
-
url: 'https://github.com/rafaelaugustos/jolt-swift.git',
|
|
8
|
-
version: '0.1.0-rc.13',
|
|
9
|
-
})
|
|
10
|
-
|
|
11
|
-
export function swiftString(text) {
|
|
12
|
-
if (!text.isWellFormed()) throw new Error('Text must contain well-formed Unicode.')
|
|
13
|
-
return `"${Array.from(text, (char) => {
|
|
14
|
-
if (char === '\\') return '\\\\'
|
|
15
|
-
if (char === '"') return '\\"'
|
|
16
|
-
const code = char.codePointAt(0)
|
|
17
|
-
// Control characters and invisible separators stay readable and unambiguous in the source.
|
|
18
|
-
return code < 0x20 ||
|
|
19
|
-
(code >= 0x7f && code <= 0x9f) ||
|
|
20
|
-
code === 0x2028 ||
|
|
21
|
-
code === 0x2029 ||
|
|
22
|
-
code === 0xfeff
|
|
23
|
-
? `\\u{${code.toString(16)}}`
|
|
24
|
-
: char
|
|
25
|
-
}).join('')}"`
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const swiftNumber = (value) => {
|
|
29
|
-
const text = String(Math.abs(value))
|
|
30
|
-
const literal = /[.e]/.test(text) ? text : `${text}.0`
|
|
31
|
-
return value < 0 || Object.is(value, -0) ? `-${literal}` : literal
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function swiftType(type) {
|
|
35
|
-
switch (type.k) {
|
|
36
|
-
case 'string':
|
|
37
|
-
return 'String'
|
|
38
|
-
case 'number':
|
|
39
|
-
return 'Double'
|
|
40
|
-
case 'boolean':
|
|
41
|
-
return 'Bool'
|
|
42
|
-
case 'record':
|
|
43
|
-
return type.name
|
|
44
|
-
case 'array':
|
|
45
|
-
return `[${swiftType(type.of)}]`
|
|
46
|
-
case 'optional':
|
|
47
|
-
return `${swiftType(type.of)}?`
|
|
48
|
-
case 'function':
|
|
49
|
-
return `(${type.params.map(swiftType).join(', ')}) -> Void`
|
|
50
|
-
}
|
|
51
|
-
throw new Error(`No Swift type for ${type.k}`)
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export class SwiftEmitter {
|
|
55
|
-
constructor(model) {
|
|
56
|
-
this.records = new Map(model.records.map((record) => [record.name, record]))
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
text(e) {
|
|
60
|
-
// The text a JavaScript template literal or + would produce for a primitive.
|
|
61
|
-
if (e.type.k === 'number') return `mavisString(${this.expr(e)})`
|
|
62
|
-
if (e.type.k === 'boolean') return `String(${this.expr(e)})`
|
|
63
|
-
return this.expr(e)
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
interpolate(parts) {
|
|
67
|
-
if (parts.length === 1 && typeof parts[0] === 'string') return swiftString(parts[0])
|
|
68
|
-
if (parts.length === 1) return this.text(parts[0])
|
|
69
|
-
return `"${parts
|
|
70
|
-
.map((part) =>
|
|
71
|
-
typeof part === 'string' ? swiftString(part).slice(1, -1) : `\\(${this.text(part)})`,
|
|
72
|
-
)
|
|
73
|
-
.join('')}"`
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
closure(e, returns) {
|
|
77
|
-
const params = e.params.map((name, i) => `${name}: ${swiftType(e.types[i])}`).join(', ')
|
|
78
|
-
return `{ (${params}) -> ${returns} in ${this.expr(e.body)} }`
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
value(prop) {
|
|
82
|
-
return 'lit' in prop ? swiftString(prop.lit) : this.expr(prop.expr)
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
expr(e) {
|
|
86
|
-
switch (e.e) {
|
|
87
|
-
case 'lit':
|
|
88
|
-
return typeof e.value === 'string'
|
|
89
|
-
? swiftString(e.value)
|
|
90
|
-
: typeof e.value === 'number'
|
|
91
|
-
? swiftNumber(e.value)
|
|
92
|
-
: String(e.value)
|
|
93
|
-
case 'undefined':
|
|
94
|
-
return 'nil'
|
|
95
|
-
case 'template':
|
|
96
|
-
return this.interpolate(e.parts)
|
|
97
|
-
case 'state':
|
|
98
|
-
case 'getter':
|
|
99
|
-
return `self.${e.name}`
|
|
100
|
-
case 'prop':
|
|
101
|
-
// Initial state is computed in init, before self is available: use the parameter.
|
|
102
|
-
return this.initializing ? e.name : `self.${e.name}`
|
|
103
|
-
case 'local':
|
|
104
|
-
return e.name
|
|
105
|
-
case 'index':
|
|
106
|
-
return `mavisAt(${this.expr(e.object)}, ${this.expr(e.index)})`
|
|
107
|
-
case 'length':
|
|
108
|
-
return e.object.type.k === 'string'
|
|
109
|
-
? `Double(${this.wrap(e.object)}.utf16.count)`
|
|
110
|
-
: `Double(${this.wrap(e.object)}.count)`
|
|
111
|
-
case 'field':
|
|
112
|
-
return `${this.wrap(e.object)}${e.optional ? '?' : ''}.${e.name}`
|
|
113
|
-
case 'math': {
|
|
114
|
-
const [a, b] = e.args.map((arg) => this.expr(arg))
|
|
115
|
-
return {
|
|
116
|
-
min: `min(${a}, ${b})`,
|
|
117
|
-
max: `max(${a}, ${b})`,
|
|
118
|
-
floor: `(${a}).rounded(.down)`,
|
|
119
|
-
ceil: `(${a}).rounded(.up)`,
|
|
120
|
-
abs: `abs(${a})`,
|
|
121
|
-
round: `mavisRound(${a})`,
|
|
122
|
-
}[e.fn]
|
|
123
|
-
}
|
|
124
|
-
case 'call':
|
|
125
|
-
return this.call(e)
|
|
126
|
-
case 'unary':
|
|
127
|
-
return `${e.op}${this.wrap(e.arg)}`
|
|
128
|
-
case 'binary':
|
|
129
|
-
return this.binary(e)
|
|
130
|
-
case 'logical':
|
|
131
|
-
return `(${this.expr(e.left)} ${e.op} ${this.expr(e.right)})`
|
|
132
|
-
case 'cond': {
|
|
133
|
-
if (!e.narrow) return `(${this.expr(e.test)} ? ${this.expr(e.then)} : ${this.expr(e.else)})`
|
|
134
|
-
const [some, none] = e.narrow.op === '!==' ? [e.then, e.else] : [e.else, e.then]
|
|
135
|
-
return `({ () -> ${swiftType(e.type)} in if let ${e.narrow.name} { return ${this.expr(some)} }; return ${this.expr(none)} })()`
|
|
136
|
-
}
|
|
137
|
-
case 'record':
|
|
138
|
-
return this.record(e)
|
|
139
|
-
case 'array':
|
|
140
|
-
return e.items.length
|
|
141
|
-
? `[${e.items.map((item) => this.expr(item)).join(', ')}]`
|
|
142
|
-
: `([] as ${swiftType(e.type)})`
|
|
143
|
-
}
|
|
144
|
-
throw new Error(`Unknown expression ${e.e}`)
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
wrap(e) {
|
|
148
|
-
return ['state', 'getter', 'prop', 'local', 'field', 'call', 'lit', 'array', 'length'].includes(
|
|
149
|
-
e.e,
|
|
150
|
-
) && !(e.e === 'lit' && typeof e.value === 'number' && e.value < 0)
|
|
151
|
-
? this.expr(e)
|
|
152
|
-
: `(${this.expr(e)})`
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
call(e) {
|
|
156
|
-
const object = this.wrap(e.object)
|
|
157
|
-
const [first, second] = e.args
|
|
158
|
-
if (e.object.type.k === 'string') {
|
|
159
|
-
switch (e.method) {
|
|
160
|
-
case 'trim':
|
|
161
|
-
return `mavisTrim(${this.expr(e.object)})`
|
|
162
|
-
case 'toLowerCase':
|
|
163
|
-
return `${object}.lowercased()`
|
|
164
|
-
case 'toUpperCase':
|
|
165
|
-
return `${object}.uppercased()`
|
|
166
|
-
case 'includes':
|
|
167
|
-
return `mavisIncludes(${this.expr(e.object)}, ${this.expr(first)})`
|
|
168
|
-
case 'startsWith':
|
|
169
|
-
return `${object}.hasPrefix(${this.expr(first)})`
|
|
170
|
-
case 'endsWith':
|
|
171
|
-
return `${object}.hasSuffix(${this.expr(first)})`
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
switch (e.method) {
|
|
175
|
-
case 'filter':
|
|
176
|
-
return `${object}.filter ${this.closure(first, 'Bool')}`
|
|
177
|
-
case 'some':
|
|
178
|
-
return `${object}.contains(where: ${this.closure(first, 'Bool')})`
|
|
179
|
-
case 'every':
|
|
180
|
-
return `${object}.allSatisfy ${this.closure(first, 'Bool')}`
|
|
181
|
-
case 'find':
|
|
182
|
-
return `${object}.first(where: ${this.closure(first, 'Bool')})`
|
|
183
|
-
case 'findIndex':
|
|
184
|
-
return `mavisFindIndex(${this.expr(e.object)}, ${this.closure(first, 'Bool')})`
|
|
185
|
-
case 'map':
|
|
186
|
-
return `${object}.map ${this.closure(first, swiftType(first.body.type))}`
|
|
187
|
-
case 'includes':
|
|
188
|
-
return `${object}.contains(${this.expr(first)})`
|
|
189
|
-
case 'slice':
|
|
190
|
-
return `mavisSlice(${this.expr(e.object)}, ${this.expr(first)}${second ? `, ${this.expr(second)}` : ''})`
|
|
191
|
-
case 'join':
|
|
192
|
-
return `${object}.joined(separator: ${this.expr(first)})`
|
|
193
|
-
case 'toSorted':
|
|
194
|
-
return `mavisSorted(${this.expr(e.object)}, ${this.closure(first, 'Double')})`
|
|
195
|
-
}
|
|
196
|
-
throw new Error(`Unknown method ${e.method}`)
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
binary(e) {
|
|
200
|
-
const left = this.expr(e.left)
|
|
201
|
-
const right = this.expr(e.right)
|
|
202
|
-
// JavaScript orders strings by UTF-16 code units.
|
|
203
|
-
if (e.strings && ['<', '>', '<=', '>='].includes(e.op))
|
|
204
|
-
return {
|
|
205
|
-
'<': `mavisBefore(${left}, ${right})`,
|
|
206
|
-
'>': `mavisBefore(${right}, ${left})`,
|
|
207
|
-
'<=': `!mavisBefore(${right}, ${left})`,
|
|
208
|
-
'>=': `!mavisBefore(${left}, ${right})`,
|
|
209
|
-
}[e.op]
|
|
210
|
-
switch (e.op) {
|
|
211
|
-
case 'concat':
|
|
212
|
-
return `(${this.text(e.left)} + ${this.text(e.right)})`
|
|
213
|
-
case '%':
|
|
214
|
-
return `${this.wrap(e.left)}.truncatingRemainder(dividingBy: ${right})`
|
|
215
|
-
case '===':
|
|
216
|
-
return `(${left} == ${right})`
|
|
217
|
-
case '!==':
|
|
218
|
-
return `(${left} != ${right})`
|
|
219
|
-
default:
|
|
220
|
-
return `(${left} ${e.op} ${right})`
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
record(e) {
|
|
225
|
-
const definition = this.records.get(e.name)
|
|
226
|
-
if (e.spread) {
|
|
227
|
-
if (!e.fields.length) return this.expr(e.spread)
|
|
228
|
-
return `mavisCopy(${this.expr(e.spread)}) { mavisValue in ${e.fields
|
|
229
|
-
.map((field) => `mavisValue.${field.name} = ${this.expr(field.value)}`)
|
|
230
|
-
.join('; ')} }`
|
|
231
|
-
}
|
|
232
|
-
const values = new Map(e.fields.map((field) => [field.name, field.value]))
|
|
233
|
-
return `${e.name}(${definition.fields
|
|
234
|
-
.map((field) => `${field.name}: ${this.expr(values.get(field.name))}`)
|
|
235
|
-
.join(', ')})`
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
path(target) {
|
|
239
|
-
return ['self', target.name, ...target.fields].join('.')
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
statements(list, indent) {
|
|
243
|
-
const pad = ' '.repeat(indent)
|
|
244
|
-
return list
|
|
245
|
-
.map((s) => {
|
|
246
|
-
switch (s.s) {
|
|
247
|
-
case 'assign':
|
|
248
|
-
return s.op === '+=' && s.target.type.k === 'string'
|
|
249
|
-
? `${pad}${this.path(s.target)} += ${this.text(s.value)}`
|
|
250
|
-
: `${pad}${this.path(s.target)} ${s.op} ${this.expr(s.value)}`
|
|
251
|
-
case 'const':
|
|
252
|
-
return `${pad}let ${s.name}: ${swiftType(s.type)} = ${this.expr(s.value)}`
|
|
253
|
-
case 'return':
|
|
254
|
-
return `${pad}return`
|
|
255
|
-
case 'guard':
|
|
256
|
-
return `${pad}guard let ${s.name} else { return }`
|
|
257
|
-
case 'iflet': {
|
|
258
|
-
const otherwise = s.else.length
|
|
259
|
-
? ` else {\n${this.statements(s.else, indent + 4)}\n${pad}}`
|
|
260
|
-
: ''
|
|
261
|
-
return `${pad}if let ${s.name} {\n${this.statements(s.then, indent + 4) || `${pad} `}\n${pad}}${otherwise}`
|
|
262
|
-
}
|
|
263
|
-
case 'action':
|
|
264
|
-
case 'callback':
|
|
265
|
-
return `${pad}self.${s.name}(${s.args.map((arg) => this.expr(arg)).join(', ')})`
|
|
266
|
-
case 'focus':
|
|
267
|
-
return `${pad}self.mavisFocus = ${swiftString(s.ref)}`
|
|
268
|
-
case 'blur':
|
|
269
|
-
return `${pad}if self.mavisFocus == ${swiftString(s.ref)} { self.mavisFocus = nil }`
|
|
270
|
-
case 'push':
|
|
271
|
-
return `${pad}${this.path(s.target)}.append(${this.expr(s.value)})`
|
|
272
|
-
case 'unshift':
|
|
273
|
-
return `${pad}${this.path(s.target)}.insert(${this.expr(s.value)}, at: 0)`
|
|
274
|
-
case 'splice':
|
|
275
|
-
return `${pad}mavisSplice(&${this.path(s.target)}, ${this.expr(s.start)}, ${this.expr(s.deleteCount)}, [${s.items.map((item) => this.expr(item)).join(', ')}])`
|
|
276
|
-
case 'if': {
|
|
277
|
-
const otherwise =
|
|
278
|
-
s.else.length === 1 && s.else[0].s === 'if'
|
|
279
|
-
? ` else ${this.statements(s.else, indent).trimStart()}`
|
|
280
|
-
: s.else.length
|
|
281
|
-
? ` else {\n${this.statements(s.else, indent + 4)}\n${pad}}`
|
|
282
|
-
: ''
|
|
283
|
-
return `${pad}if ${this.expr(s.test)} {\n${this.statements(s.then, indent + 4) || `${pad} `}\n${pad}}${otherwise}`
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
throw new Error(`Unknown statement ${s.s}`)
|
|
287
|
-
})
|
|
288
|
-
.join('\n')
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
handler(handler, indent) {
|
|
292
|
-
const params = handler.params
|
|
293
|
-
.map((param) => `${param.name}: ${swiftType(param.type)}`)
|
|
294
|
-
.join(', ')
|
|
295
|
-
const head = params ? `(${params}) in` : ''
|
|
296
|
-
const body = this.statements(handler.body, indent + 4)
|
|
297
|
-
return `{${head ? ` ${head}` : ''}\n${body}\n${' '.repeat(indent)}}`
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
view(node, indent, tokens) {
|
|
301
|
-
const pad = ' '.repeat(indent)
|
|
302
|
-
switch (node.v) {
|
|
303
|
-
case 'element': {
|
|
304
|
-
const props = node.props
|
|
305
|
-
if (node.tag === 'MButton') {
|
|
306
|
-
const label =
|
|
307
|
-
'lit' in props.text ? swiftString(props.text.lit) : this.expr(props.text.expr)
|
|
308
|
-
const variant = props.variant
|
|
309
|
-
? 'lit' in props.variant
|
|
310
|
-
? String(props.variant.lit === 'secondary')
|
|
311
|
-
: `(${this.expr(props.variant.expr)} == "secondary")`
|
|
312
|
-
: 'false'
|
|
313
|
-
const lines = [
|
|
314
|
-
`${pad}Button(action: ${this.handler(props.onClick, indent)}) {`,
|
|
315
|
-
`${pad} Text(verbatim: ${label})`,
|
|
316
|
-
`${pad}}`,
|
|
317
|
-
`${pad} .buttonStyle(MavisStarterButtonStyle(secondary: ${variant}))`,
|
|
318
|
-
]
|
|
319
|
-
if (props.disabled)
|
|
320
|
-
lines.push(
|
|
321
|
-
`${pad} .disabled(${'lit' in props.disabled ? 'true' : this.expr(props.disabled.expr)})`,
|
|
322
|
-
)
|
|
323
|
-
if (props.shortcut) {
|
|
324
|
-
const key = props.shortcut.lit.slice(4)
|
|
325
|
-
lines.push(
|
|
326
|
-
`${pad} .keyboardShortcut(${key === 'Enter' ? '.return' : `KeyEquivalent(${swiftString(key)})`}, modifiers: .command)`,
|
|
327
|
-
)
|
|
328
|
-
}
|
|
329
|
-
return lines.join('\n')
|
|
330
|
-
}
|
|
331
|
-
if (node.tag === 'MGrid' || node.tag === 'MCard') {
|
|
332
|
-
const body =
|
|
333
|
-
node.children.map((childNode) => this.view(childNode, indent + 4, tokens)).join('\n') ||
|
|
334
|
-
`${pad} EmptyView()`
|
|
335
|
-
if (node.tag === 'MGrid') {
|
|
336
|
-
// Each cell reads as a whole, in source order. Without a group per cell,
|
|
337
|
-
// assistive technology goes by position and interleaves the columns.
|
|
338
|
-
const cells =
|
|
339
|
-
node.children
|
|
340
|
-
.map((childNode) =>
|
|
341
|
-
[
|
|
342
|
-
`${pad} Group {`,
|
|
343
|
-
this.view(childNode, indent + 8, tokens),
|
|
344
|
-
`${pad} }`,
|
|
345
|
-
`${pad} .accessibilityElement(children: .contain)`,
|
|
346
|
-
].join('\n'),
|
|
347
|
-
)
|
|
348
|
-
.join('\n') || `${pad} EmptyView()`
|
|
349
|
-
const args = [
|
|
350
|
-
...(props.minColumnWidth
|
|
351
|
-
? [`minColumnWidth: ${this.expr(props.minColumnWidth.expr)}`]
|
|
352
|
-
: []),
|
|
353
|
-
...(props.columns ? [`columns: ${this.expr(props.columns.expr)}`] : []),
|
|
354
|
-
`spacing: ${tokens.space(props.gap, 'none')}`,
|
|
355
|
-
]
|
|
356
|
-
return [`${pad}MavisGrid(${args.join(', ')}) {`, cells, `${pad}}`].join('\n')
|
|
357
|
-
}
|
|
358
|
-
const tone = !props.tone
|
|
359
|
-
? 'MavisTokens.surface'
|
|
360
|
-
: 'lit' in props.tone
|
|
361
|
-
? tokens.color(props.tone.lit)
|
|
362
|
-
: `MavisTokens.tone(${this.expr(props.tone.expr)})`
|
|
363
|
-
const args = [
|
|
364
|
-
`tone: ${tone}`,
|
|
365
|
-
...(props.padding ? [`padding: ${tokens.space(props.padding)}`] : []),
|
|
366
|
-
`spacing: ${tokens.space(props.gap, 'none')}`,
|
|
367
|
-
]
|
|
368
|
-
const card = [`MavisCard(${args.join(', ')}) {`, body, `${pad}}`]
|
|
369
|
-
if (!props.onClick)
|
|
370
|
-
return [
|
|
371
|
-
`${pad}${card[0]}`,
|
|
372
|
-
...card.slice(1),
|
|
373
|
-
...(props.label
|
|
374
|
-
? [
|
|
375
|
-
`${pad} .accessibilityElement(children: .contain)`,
|
|
376
|
-
`${pad} .accessibilityLabel(Text(verbatim: ${this.value(props.label)}))`,
|
|
377
|
-
]
|
|
378
|
-
: []),
|
|
379
|
-
].join('\n')
|
|
380
|
-
// One button for assistive technology, like the Web card with role="button".
|
|
381
|
-
return [
|
|
382
|
-
`${pad}Button(action: ${this.handler(props.onClick, indent)}) {`,
|
|
383
|
-
`${pad} ${card[0]}`,
|
|
384
|
-
body
|
|
385
|
-
.split('\n')
|
|
386
|
-
.map((line) => ` ${line}`)
|
|
387
|
-
.join('\n'),
|
|
388
|
-
`${pad} }`,
|
|
389
|
-
`${pad}}`,
|
|
390
|
-
`${pad} .buttonStyle(MavisCardButtonStyle())`,
|
|
391
|
-
`${pad} .accessibilityLabel(Text(verbatim: ${this.value(props.label)}))`,
|
|
392
|
-
`${pad} .accessibilityIdentifier("mavis-card")`,
|
|
393
|
-
].join('\n')
|
|
394
|
-
}
|
|
395
|
-
if (node.tag === 'MInput') return this.input(node, indent)
|
|
396
|
-
if (node.tag === 'MCheckbox')
|
|
397
|
-
return this.control(node, indent, 'MavisCheckbox', [
|
|
398
|
-
['label', 'label'],
|
|
399
|
-
['checked', 'checked'],
|
|
400
|
-
['onChange', 'onChange'],
|
|
401
|
-
['indeterminate', 'indeterminate'],
|
|
402
|
-
['helperText', 'helperText'],
|
|
403
|
-
['disabled', 'disabled'],
|
|
404
|
-
])
|
|
405
|
-
if (node.tag === 'MSelect')
|
|
406
|
-
return this.control(node, indent, 'MavisSelect', [
|
|
407
|
-
['label', 'label'],
|
|
408
|
-
['value', 'value'],
|
|
409
|
-
['options', 'options'],
|
|
410
|
-
['onChange', 'onChange'],
|
|
411
|
-
['placeholder', 'placeholder'],
|
|
412
|
-
['helperText', 'helperText'],
|
|
413
|
-
['error', 'error'],
|
|
414
|
-
['disabled', 'disabled'],
|
|
415
|
-
])
|
|
416
|
-
const spacing = tokens.space(props.gap, 'none')
|
|
417
|
-
const stack =
|
|
418
|
-
node.tag === 'MColumn'
|
|
419
|
-
? `VStack(alignment: .leading, spacing: ${spacing})`
|
|
420
|
-
: `HStack(alignment: .center, spacing: ${spacing})`
|
|
421
|
-
const body = node.children
|
|
422
|
-
.map((childNode) => this.view(childNode, indent + 4, tokens))
|
|
423
|
-
.join('\n')
|
|
424
|
-
const lines = [`${pad}${stack} {`, body || `${pad} EmptyView()`, `${pad}}`]
|
|
425
|
-
if (props.padding) lines.push(`${pad} .padding(${tokens.space(props.padding)})`)
|
|
426
|
-
if (node.animatesList) {
|
|
427
|
-
const list = animatedFor(node)
|
|
428
|
-
const keys = list.key
|
|
429
|
-
? `${this.wrap(list.each)}.map(\\.${list.key})`
|
|
430
|
-
: this.expr(list.each)
|
|
431
|
-
lines.push(`${pad} .joltLayout(value: ${keys})`)
|
|
432
|
-
}
|
|
433
|
-
if (props.label)
|
|
434
|
-
lines.push(
|
|
435
|
-
`${pad} .accessibilityElement(children: .contain)`,
|
|
436
|
-
`${pad} .accessibilityLabel(Text(verbatim: ${this.value(props.label)}))`,
|
|
437
|
-
)
|
|
438
|
-
if (props.onKeyDown) {
|
|
439
|
-
const key = this.focusKey('stack')
|
|
440
|
-
lines.push(
|
|
441
|
-
// In the Tab order without keyboard navigation turned on, and focused by a click
|
|
442
|
-
// anywhere in it, like the Web stack with tabindex="0".
|
|
443
|
-
`${pad} .contentShape(Rectangle())`,
|
|
444
|
-
`${pad} .focusable(interactions: .edit)`,
|
|
445
|
-
`${pad} .focused($mavisFocus, equals: ${key})`,
|
|
446
|
-
`${pad} .simultaneousGesture(TapGesture().onEnded { self.mavisFocus = ${key} })`,
|
|
447
|
-
`${pad} .onKeyPress(keys: [.upArrow, .downArrow, .leftArrow, .rightArrow]) { press in`,
|
|
448
|
-
// Arrow keys also carry .function and .numericPad; only real modifiers opt out.
|
|
449
|
-
`${pad} guard press.modifiers.isDisjoint(with: [.command, .option, .control, .shift]) else { return .ignored }`,
|
|
450
|
-
`${pad} let handle: (String) -> Void = ${this.handler(props.onKeyDown, indent + 8)}`,
|
|
451
|
-
`${pad} handle(mavisKeyName(press.key))`,
|
|
452
|
-
`${pad} return .handled`,
|
|
453
|
-
`${pad} }`,
|
|
454
|
-
)
|
|
455
|
-
}
|
|
456
|
-
return lines.join('\n')
|
|
457
|
-
}
|
|
458
|
-
case 'text': {
|
|
459
|
-
const props = node.props
|
|
460
|
-
const content = this.interpolate(node.parts)
|
|
461
|
-
const lines = [`${pad}Text(verbatim: ${content})`]
|
|
462
|
-
if (!props.variant || 'lit' in props.variant) {
|
|
463
|
-
const variant = props.variant?.lit ?? 'body'
|
|
464
|
-
lines.push(`${pad} .font(${tokens.font(variant)})`)
|
|
465
|
-
if (['title', 'heading', 'display'].includes(variant))
|
|
466
|
-
lines.push(`${pad} .accessibilityAddTraits(.isHeader)`)
|
|
467
|
-
} else {
|
|
468
|
-
const variant = this.expr(props.variant.expr)
|
|
469
|
-
lines.push(`${pad} .font(MavisTokens.font(${variant}))`)
|
|
470
|
-
lines.push(
|
|
471
|
-
`${pad} .accessibilityAddTraits(MavisTokens.isHeading(${variant}) ? .isHeader : [])`,
|
|
472
|
-
)
|
|
473
|
-
}
|
|
474
|
-
lines.push(
|
|
475
|
-
!props.tone || 'lit' in props.tone
|
|
476
|
-
? `${pad} .foregroundStyle(${tokens.color(props.tone?.lit ?? 'text')})`
|
|
477
|
-
: `${pad} .foregroundStyle(MavisTokens.tone(${this.expr(props.tone.expr)}))`,
|
|
478
|
-
)
|
|
479
|
-
lines.push(`${pad} .fixedSize(horizontal: false, vertical: true)`)
|
|
480
|
-
return lines.join('\n')
|
|
481
|
-
}
|
|
482
|
-
case 'show': {
|
|
483
|
-
if (node.animate) {
|
|
484
|
-
// JoltPresence keeps leaving content until its exit finishes; Reduce Motion settles it.
|
|
485
|
-
const presence = (when, body) => [
|
|
486
|
-
`${pad}JoltPresence(${when}) {`,
|
|
487
|
-
body.map((childNode) => this.view(childNode, indent + 4, tokens)).join('\n') ||
|
|
488
|
-
`${pad} EmptyView()`,
|
|
489
|
-
`${pad}}`,
|
|
490
|
-
]
|
|
491
|
-
const shown = this.expr(node.when)
|
|
492
|
-
return [
|
|
493
|
-
...presence(shown, node.then),
|
|
494
|
-
...(node.else.length ? presence(`!${this.wrap(node.when)}`, node.else) : []),
|
|
495
|
-
].join('\n')
|
|
496
|
-
}
|
|
497
|
-
const then = node.then
|
|
498
|
-
.map((childNode) => this.view(childNode, indent + 4, tokens))
|
|
499
|
-
.join('\n')
|
|
500
|
-
const otherwise = node.else
|
|
501
|
-
.map((childNode) => this.view(childNode, indent + 4, tokens))
|
|
502
|
-
.join('\n')
|
|
503
|
-
return [
|
|
504
|
-
`${pad}if ${this.expr(node.when)} {`,
|
|
505
|
-
then || `${pad} EmptyView()`,
|
|
506
|
-
...(otherwise ? [`${pad}} else {`, otherwise] : []),
|
|
507
|
-
`${pad}}`,
|
|
508
|
-
].join('\n')
|
|
509
|
-
}
|
|
510
|
-
case 'for': {
|
|
511
|
-
const element = swiftType(node.each.type.of)
|
|
512
|
-
this.forKeys.push(node.key ? `${node.item}.${node.key}` : node.item)
|
|
513
|
-
try {
|
|
514
|
-
return this.forEach(node, indent, tokens, element, pad)
|
|
515
|
-
} finally {
|
|
516
|
-
this.forKeys.pop()
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
case 'component': {
|
|
520
|
-
if (!node.props.length) return `${pad}${node.name}()`
|
|
521
|
-
const args = node.props.map(({ name, value }) =>
|
|
522
|
-
value.handler
|
|
523
|
-
? `${name}: ${this.handler(value.handler, indent + 4)}`
|
|
524
|
-
: `${name}: ${this.expr(value.expr)}`,
|
|
525
|
-
)
|
|
526
|
-
return `${pad}${node.name}(\n${args.map((arg) => `${pad} ${arg}`).join(',\n')}\n${pad})`
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
throw new Error(`Unknown view ${node.v}`)
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
forEach(node, indent, tokens, element, pad) {
|
|
533
|
-
const keyPath = node.key ? `\\.${node.key}` : '\\.self'
|
|
534
|
-
if (!node.index)
|
|
535
|
-
return [
|
|
536
|
-
`${pad}ForEach(${this.expr(node.each)}, id: ${keyPath}) { (${node.item}: ${element}) in`,
|
|
537
|
-
this.view(node.body, indent + 4, tokens),
|
|
538
|
-
`${pad}}`,
|
|
539
|
-
].join('\n')
|
|
540
|
-
return [
|
|
541
|
-
`${pad}ForEach(Array(${this.expr(node.each)}.enumerated()), id: ${node.key ? `\\.element.${node.key}` : '\\.element'}) { entry in`,
|
|
542
|
-
`${pad} let ${node.item}: ${element} = entry.element`,
|
|
543
|
-
`${pad} let ${node.index}: Double = Double(entry.offset)`,
|
|
544
|
-
this.view(node.body, indent + 4, tokens),
|
|
545
|
-
`${pad}}`,
|
|
546
|
-
].join('\n')
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// Arguments in the helper's declaration order; Swift requires it for defaulted parameters.
|
|
550
|
-
control(node, indent, name, order, extra = []) {
|
|
551
|
-
const pad = ' '.repeat(indent)
|
|
552
|
-
const args = []
|
|
553
|
-
for (const [prop, label] of order) {
|
|
554
|
-
const value = node.props[prop]
|
|
555
|
-
if (!value) continue
|
|
556
|
-
if ('body' in value) args.push(`${label}: ${this.handler(value, indent + 4)}`)
|
|
557
|
-
else if (prop === 'options')
|
|
558
|
-
args.push(
|
|
559
|
-
`${label}: ${this.wrap(value.expr)}.map { option in MavisChoice(value: option.value, label: option.label, disabled: option.disabled ?? false) }`,
|
|
560
|
-
)
|
|
561
|
-
else args.push(`${label}: ${this.value(value)}`)
|
|
562
|
-
}
|
|
563
|
-
args.push(...extra)
|
|
564
|
-
return `${pad}${name}(\n${args.map((arg) => `${pad} ${arg}`).join(',\n')}\n${pad})`
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
// Unique per view, and per row inside For.
|
|
568
|
-
focusKey(kind) {
|
|
569
|
-
return `"${kind}${++this.fields}${this.forKeys.map((key) => `:\\(${key})`).join('')}"`
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
input(node, indent) {
|
|
573
|
-
const ref = node.props.ref?.ref
|
|
574
|
-
// Every field has a focus key: refs move focus to it, the focus border reads it.
|
|
575
|
-
const key = ref ? swiftString(ref) : this.focusKey('field')
|
|
576
|
-
const type = node.props.type?.lit ?? 'text'
|
|
577
|
-
return this.control(
|
|
578
|
-
node,
|
|
579
|
-
indent,
|
|
580
|
-
'MavisTextInput',
|
|
581
|
-
[
|
|
582
|
-
['label', 'label'],
|
|
583
|
-
['value', 'value'],
|
|
584
|
-
['onChange', 'onChange'],
|
|
585
|
-
],
|
|
586
|
-
[
|
|
587
|
-
`focus: $mavisFocus`,
|
|
588
|
-
`focusKey: ${key}`,
|
|
589
|
-
...[
|
|
590
|
-
['placeholder', 'placeholder'],
|
|
591
|
-
['helperText', 'helperText'],
|
|
592
|
-
['error', 'error'],
|
|
593
|
-
]
|
|
594
|
-
.filter(([prop]) => node.props[prop])
|
|
595
|
-
.map(([prop, label]) => `${label}: ${this.value(node.props[prop])}`),
|
|
596
|
-
...(type === 'password' ? ['secure: true'] : []),
|
|
597
|
-
...(type === 'email' ? ['email: true'] : []),
|
|
598
|
-
...[
|
|
599
|
-
['multiline', 'multiline'],
|
|
600
|
-
['rows', 'rows'],
|
|
601
|
-
['maxLength', 'maxLength'],
|
|
602
|
-
['disabled', 'disabled'],
|
|
603
|
-
['readonly', 'readonly'],
|
|
604
|
-
['onSubmit', 'onSubmit'],
|
|
605
|
-
['onEscape', 'onEscape'],
|
|
606
|
-
]
|
|
607
|
-
.filter(([prop]) => node.props[prop])
|
|
608
|
-
.map(([prop, label]) =>
|
|
609
|
-
'body' in node.props[prop]
|
|
610
|
-
? `${label}: ${this.handler(node.props[prop], indent + 4)}`
|
|
611
|
-
: `${label}: ${this.value(node.props[prop])}`,
|
|
612
|
-
),
|
|
613
|
-
],
|
|
614
|
-
)
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
component(component, tokens, header, namespace) {
|
|
618
|
-
const lines = [`// ${header}`, 'import SwiftUI', 'import JoltSwiftUI', '']
|
|
619
|
-
const indent = namespace ? 4 : 0
|
|
620
|
-
const pad = ' '.repeat(indent)
|
|
621
|
-
if (namespace) lines.push(`extension ${namespace} {`)
|
|
622
|
-
lines.push(`${pad}struct ${component.name}: View {`)
|
|
623
|
-
const inner = pad + ' '
|
|
624
|
-
for (const prop of component.props)
|
|
625
|
-
lines.push(`${inner}let ${prop.name}: ${swiftType(prop.type)}`)
|
|
626
|
-
for (const value of component.state)
|
|
627
|
-
lines.push(`${inner}@State private var ${value.name}: ${swiftType(value.type)}`)
|
|
628
|
-
if (hasInput(component.view)) lines.push(`${inner}@FocusState private var mavisFocus: String?`)
|
|
629
|
-
this.fields = 0
|
|
630
|
-
this.forKeys = []
|
|
631
|
-
if (component.props.length || component.state.length) {
|
|
632
|
-
lines.push('')
|
|
633
|
-
const params = component.props
|
|
634
|
-
.map(
|
|
635
|
-
(prop) =>
|
|
636
|
-
`${prop.name}: ${prop.type.k === 'function' ? '@escaping ' : ''}${swiftType(prop.type)}`,
|
|
637
|
-
)
|
|
638
|
-
.join(', ')
|
|
639
|
-
lines.push(`${inner}init(${params}) {`)
|
|
640
|
-
for (const prop of component.props) lines.push(`${inner} self.${prop.name} = ${prop.name}`)
|
|
641
|
-
this.initializing = true
|
|
642
|
-
for (const value of component.state)
|
|
643
|
-
lines.push(`${inner} _${value.name} = State(initialValue: ${this.expr(value.init)})`)
|
|
644
|
-
this.initializing = false
|
|
645
|
-
lines.push(`${inner}}`)
|
|
646
|
-
}
|
|
647
|
-
for (const getter of component.getters) {
|
|
648
|
-
lines.push('', `${inner}private var ${getter.name}: ${swiftType(getter.type)} {`)
|
|
649
|
-
for (const local of getter.locals)
|
|
650
|
-
lines.push(
|
|
651
|
-
`${inner} let ${local.name}: ${swiftType(local.type)} = ${this.expr(local.value)}`,
|
|
652
|
-
)
|
|
653
|
-
lines.push(`${inner} return ${this.expr(getter.expr)}`, `${inner}}`)
|
|
654
|
-
}
|
|
655
|
-
for (const action of component.actions) {
|
|
656
|
-
const params = action.params
|
|
657
|
-
.map((param) => `_ ${param.name}: ${swiftType(param.type)}`)
|
|
658
|
-
.join(', ')
|
|
659
|
-
lines.push('', `${inner}private func ${action.name}(${params}) {`)
|
|
660
|
-
const body = this.statements(action.body, indent + 8)
|
|
661
|
-
if (body) lines.push(body)
|
|
662
|
-
lines.push(`${inner}}`)
|
|
663
|
-
}
|
|
664
|
-
lines.push(
|
|
665
|
-
'',
|
|
666
|
-
`${inner}var body: some View {`,
|
|
667
|
-
this.view(component.view, indent + 8, tokens),
|
|
668
|
-
`${inner}}`,
|
|
669
|
-
)
|
|
670
|
-
lines.push(`${pad}}`)
|
|
671
|
-
if (namespace) lines.push('}')
|
|
672
|
-
lines.push('')
|
|
673
|
-
return lines.join('\n')
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
types(records, header, namespace) {
|
|
677
|
-
const lines = [`// ${header}`, 'import Foundation', '']
|
|
678
|
-
if (namespace) lines.push(`enum ${namespace} {}`, '', `extension ${namespace} {`)
|
|
679
|
-
const pad = namespace ? ' ' : ''
|
|
680
|
-
for (const record of records) {
|
|
681
|
-
lines.push(`${pad}struct ${record.name}: Hashable {`)
|
|
682
|
-
for (const field of record.fields)
|
|
683
|
-
lines.push(`${pad} var ${field.name}: ${swiftType(field.type)}`)
|
|
684
|
-
lines.push(`${pad}}`)
|
|
685
|
-
}
|
|
686
|
-
if (namespace) lines.push('}')
|
|
687
|
-
lines.push('')
|
|
688
|
-
return lines.join('\n')
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
const children = (node) => [
|
|
693
|
-
...(node.children ?? []),
|
|
694
|
-
...(node.then ?? []),
|
|
695
|
-
...(node.else ?? []),
|
|
696
|
-
...(node.body ? [node.body] : []),
|
|
697
|
-
]
|
|
698
|
-
const animatedFor = (node) =>
|
|
699
|
-
children(node)
|
|
700
|
-
.map((child) =>
|
|
701
|
-
child.v === 'for' && child.animate ? child : child.v === 'show' ? animatedFor(child) : null,
|
|
702
|
-
)
|
|
703
|
-
.find(Boolean)
|
|
704
|
-
|
|
705
|
-
function hasInput(node) {
|
|
706
|
-
if (node.tag === 'MInput' || node.props?.onKeyDown) return true
|
|
707
|
-
return [
|
|
708
|
-
...(node.children ?? []),
|
|
709
|
-
...(node.then ?? []),
|
|
710
|
-
...(node.else ?? []),
|
|
711
|
-
...(node.body ? [node.body] : []),
|
|
712
|
-
].some(hasInput)
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
export function themeTokens(theme) {
|
|
716
|
-
const weights = {
|
|
717
|
-
normal: 'regular',
|
|
718
|
-
bold: 'bold',
|
|
719
|
-
100: 'ultraLight',
|
|
720
|
-
200: 'thin',
|
|
721
|
-
300: 'light',
|
|
722
|
-
400: 'regular',
|
|
723
|
-
500: 'medium',
|
|
724
|
-
600: 'semibold',
|
|
725
|
-
700: 'bold',
|
|
726
|
-
800: 'heavy',
|
|
727
|
-
900: 'black',
|
|
728
|
-
}
|
|
729
|
-
const pick = (family, value, fallback, what) => {
|
|
730
|
-
const key = value ?? fallback
|
|
731
|
-
if (!Object.hasOwn(family, key)) throw new Error(`Unsupported ${what} token ${key}.`)
|
|
732
|
-
return family[key]
|
|
733
|
-
}
|
|
734
|
-
const font = (variant) => {
|
|
735
|
-
const typo = pick(theme.typography, variant, 'body', 'typography')
|
|
736
|
-
return `.system(size: ${typo.fontSize}, weight: .${weights[typo.fontWeight]})`
|
|
737
|
-
}
|
|
738
|
-
const tokens = {
|
|
739
|
-
space: (value, fallback) => String(pick(theme.space, value?.lit ?? value, fallback, 'space')),
|
|
740
|
-
font,
|
|
741
|
-
color: (tone) => {
|
|
742
|
-
pick(theme.colors, tone, 'text', 'color')
|
|
743
|
-
return `MavisTokens.${tone}`
|
|
744
|
-
},
|
|
745
|
-
}
|
|
746
|
-
const colors = Object.entries(theme.colors).map(([key, value]) => {
|
|
747
|
-
if (!/^#[0-9a-f]{6}$/i.test(value)) throw new Error(`Unsupported color token ${key}.`)
|
|
748
|
-
const hex = Number.parseInt(value.slice(1), 16)
|
|
749
|
-
return ` static let ${key} = Color(red: ${((hex >> 16) & 255) / 255}, green: ${((hex >> 8) & 255) / 255}, blue: ${(hex & 255) / 255})`
|
|
750
|
-
})
|
|
751
|
-
const source = `import SwiftUI
|
|
752
|
-
import JoltSwiftUI
|
|
753
|
-
|
|
754
|
-
enum MavisTokens {
|
|
755
|
-
${colors.join('\n')}
|
|
756
|
-
/// System controls draw in the theme's appearance, whatever the Mac uses.
|
|
757
|
-
static let colorScheme: ColorScheme = .${theme.appearance === 'dark' ? 'dark' : 'light'}
|
|
758
|
-
|
|
759
|
-
static func tone(_ name: String) -> Color {
|
|
760
|
-
switch name {
|
|
761
|
-
${Object.keys(theme.colors)
|
|
762
|
-
.map((key) => ` case ${swiftString(key)}: return ${key}`)
|
|
763
|
-
.join('\n')}
|
|
764
|
-
default: return text
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
static func font(_ variant: String) -> Font {
|
|
769
|
-
switch variant {
|
|
770
|
-
${Object.keys(theme.typography)
|
|
771
|
-
.map((key) => ` case ${swiftString(key)}: return ${font(key)}`)
|
|
772
|
-
.join('\n')}
|
|
773
|
-
default: return ${font('body')}
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
static func isHeading(_ variant: String) -> Bool {
|
|
778
|
-
["title", "heading", "display"].contains(variant)
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
/// MButton: Mavis tokens for the look, Jolt for the press. Jolt settles under Reduce Motion.
|
|
783
|
-
struct MavisStarterButtonStyle: ButtonStyle {
|
|
784
|
-
let secondary: Bool
|
|
785
|
-
@Environment(\\.isEnabled) private var isEnabled
|
|
786
|
-
private static let pressed = try! JoltPose(scale: ${theme.motion.pressScale})
|
|
787
|
-
func makeBody(configuration: Configuration) -> some View {
|
|
788
|
-
configuration.label
|
|
789
|
-
.font(.system(size: 15, weight: .semibold))
|
|
790
|
-
.padding(.horizontal, 20).padding(.vertical, 12)
|
|
791
|
-
.foregroundStyle(secondary ? MavisTokens.text : MavisTokens.onPrimary)
|
|
792
|
-
.background(secondary ? MavisTokens.elevated : MavisTokens.primary, in: RoundedRectangle(cornerRadius: 12))
|
|
793
|
-
.opacity(isEnabled ? 1 : 0.45)
|
|
794
|
-
.joltMotion(to: configuration.isPressed && isEnabled ? Self.pressed : .identity, transition: .spring(.snappy))
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
`
|
|
798
|
-
const input = theme.components.input
|
|
799
|
-
const radius = theme.radius[input.radius] ?? theme.radius.md
|
|
800
|
-
const body = theme.typography.body
|
|
801
|
-
const caption = theme.typography.caption
|
|
802
|
-
const card = theme.components.card
|
|
803
|
-
const cardPadding = typeof card.padding === 'number' ? card.padding : theme.space[card.padding]
|
|
804
|
-
const cardRadius = typeof card.radius === 'number' ? card.radius : theme.radius[card.radius]
|
|
805
|
-
const controls = `import SwiftUI
|
|
806
|
-
import JoltSwiftUI
|
|
807
|
-
|
|
808
|
-
/// MGrid: equal columns, as many as fit minColumnWidth, like the Web and NativeScript grid.
|
|
809
|
-
struct MavisGrid: Layout {
|
|
810
|
-
var minColumnWidth: Double? = nil
|
|
811
|
-
var columns: Double? = nil
|
|
812
|
-
var spacing: Double = 0
|
|
813
|
-
|
|
814
|
-
private func count(_ width: CGFloat) -> Int {
|
|
815
|
-
let limit = columns.map { max(1, Int($0)) }
|
|
816
|
-
guard let minColumnWidth, width.isFinite else { return limit ?? 1 }
|
|
817
|
-
let fit = max(1, Int((max(0, width) + spacing) / (minColumnWidth + spacing)))
|
|
818
|
-
return limit.map { min($0, fit) } ?? fit
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
private func rows(_ subviews: Subviews, _ width: CGFloat) -> (count: Int, column: CGFloat, heights: [CGFloat]) {
|
|
822
|
-
let count = count(width)
|
|
823
|
-
let column = max(0, (width - spacing * CGFloat(count - 1)) / CGFloat(count))
|
|
824
|
-
var heights: [CGFloat] = []
|
|
825
|
-
for start in stride(from: 0, to: subviews.count, by: count) {
|
|
826
|
-
let row = subviews[start..<min(start + count, subviews.count)]
|
|
827
|
-
heights.append(row.map { $0.sizeThatFits(ProposedViewSize(width: column, height: nil)).height }.max() ?? 0)
|
|
828
|
-
}
|
|
829
|
-
return (count, column, heights)
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
|
|
833
|
-
let width = proposal.width ?? subviews.map { $0.sizeThatFits(.unspecified).width }.max() ?? 0
|
|
834
|
-
let heights = rows(subviews, width).heights
|
|
835
|
-
return CGSize(width: width, height: heights.reduce(0, +) + spacing * CGFloat(max(0, heights.count - 1)))
|
|
836
|
-
}
|
|
837
|
-
|
|
838
|
-
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
|
|
839
|
-
let layout = rows(subviews, bounds.width)
|
|
840
|
-
var y = bounds.minY
|
|
841
|
-
for (row, height) in layout.heights.enumerated() {
|
|
842
|
-
for column in 0..<layout.count {
|
|
843
|
-
let index = row * layout.count + column
|
|
844
|
-
guard index < subviews.count else { break }
|
|
845
|
-
subviews[index].place(
|
|
846
|
-
at: CGPoint(x: bounds.minX + CGFloat(column) * (layout.column + spacing), y: y),
|
|
847
|
-
anchor: .topLeading,
|
|
848
|
-
proposal: ProposedViewSize(width: layout.column, height: height)
|
|
849
|
-
)
|
|
850
|
-
}
|
|
851
|
-
y += height + spacing
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
|
|
856
|
-
/// MCard: the theme's card surface around a column of content.
|
|
857
|
-
struct MavisCard<Content: View>: View {
|
|
858
|
-
var tone: Color = MavisTokens.surface
|
|
859
|
-
var padding: Double = ${cardPadding}
|
|
860
|
-
var spacing: Double = 0
|
|
861
|
-
@ViewBuilder var content: () -> Content
|
|
862
|
-
var body: some View {
|
|
863
|
-
VStack(alignment: .leading, spacing: spacing) { content() }
|
|
864
|
-
.padding(padding)
|
|
865
|
-
.frame(maxWidth: .infinity, alignment: .leading)
|
|
866
|
-
.background(tone, in: RoundedRectangle(cornerRadius: ${cardRadius}))
|
|
867
|
-
.overlay(RoundedRectangle(cornerRadius: ${cardRadius}).strokeBorder(MavisTokens.border, lineWidth: 1).allowsHitTesting(false))
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
/// A card with onClick: the whole surface presses, through Jolt.
|
|
872
|
-
struct MavisCardButtonStyle: ButtonStyle {
|
|
873
|
-
@Environment(\\.isEnabled) private var isEnabled
|
|
874
|
-
private static let pressed = try! JoltPose(scale: ${theme.motion.pressScale})
|
|
875
|
-
func makeBody(configuration: Configuration) -> some View {
|
|
876
|
-
configuration.label
|
|
877
|
-
.contentShape(RoundedRectangle(cornerRadius: ${cardRadius}))
|
|
878
|
-
.opacity(isEnabled ? 1 : 0.45)
|
|
879
|
-
.joltMotion(to: configuration.isPressed && isEnabled ? Self.pressed : .identity, transition: .spring(.snappy))
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
/// One MSelect option, without the shared record type so every project can use it.
|
|
884
|
-
struct MavisChoice: Hashable {
|
|
885
|
-
let value: String
|
|
886
|
-
let label: String
|
|
887
|
-
let disabled: Bool
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
private struct MavisFieldLabel: View {
|
|
891
|
-
let text: String
|
|
892
|
-
var body: some View {
|
|
893
|
-
// The control carries the label for assistive technology.
|
|
894
|
-
Text(verbatim: text)
|
|
895
|
-
.font(.system(size: ${caption.fontSize}, weight: .semibold))
|
|
896
|
-
.foregroundStyle(MavisTokens.text)
|
|
897
|
-
.accessibilityHidden(true)
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
private struct MavisFieldMessage: View {
|
|
902
|
-
let label: String
|
|
903
|
-
let text: String
|
|
904
|
-
let error: Bool
|
|
905
|
-
var body: some View {
|
|
906
|
-
Text(verbatim: text)
|
|
907
|
-
.font(${font('caption')})
|
|
908
|
-
.foregroundStyle(error ? MavisTokens.danger : MavisTokens.muted)
|
|
909
|
-
.fixedSize(horizontal: false, vertical: true)
|
|
910
|
-
.accessibilityIdentifier("mavis-message:" + label)
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
/// MInput: the value stays with the source; the field keeps a draft so maxLength and
|
|
915
|
-
/// readonly hold while typing, like the Web input.
|
|
916
|
-
struct MavisTextInput: View {
|
|
917
|
-
let label: String
|
|
918
|
-
let value: String
|
|
919
|
-
let onChange: (String) -> Void
|
|
920
|
-
let focus: FocusState<String?>.Binding
|
|
921
|
-
let focusKey: String
|
|
922
|
-
let placeholder: String
|
|
923
|
-
let helperText: String
|
|
924
|
-
let error: String
|
|
925
|
-
let secure: Bool
|
|
926
|
-
let email: Bool
|
|
927
|
-
let multiline: Bool
|
|
928
|
-
let rows: Double
|
|
929
|
-
let maxLength: Double?
|
|
930
|
-
let disabled: Bool
|
|
931
|
-
let readonly: Bool
|
|
932
|
-
let onSubmit: (() -> Void)?
|
|
933
|
-
let onEscape: (() -> Void)?
|
|
934
|
-
@State private var draft: String
|
|
935
|
-
// Values sent to the source that have not come back yet. Typing can run ahead of them.
|
|
936
|
-
@State private var pending: [String] = []
|
|
937
|
-
|
|
938
|
-
init(
|
|
939
|
-
label: String,
|
|
940
|
-
value: String,
|
|
941
|
-
onChange: @escaping (String) -> Void,
|
|
942
|
-
focus: FocusState<String?>.Binding,
|
|
943
|
-
focusKey: String,
|
|
944
|
-
placeholder: String = "",
|
|
945
|
-
helperText: String = "",
|
|
946
|
-
error: String = "",
|
|
947
|
-
secure: Bool = false,
|
|
948
|
-
email: Bool = false,
|
|
949
|
-
multiline: Bool = false,
|
|
950
|
-
rows: Double = 3,
|
|
951
|
-
maxLength: Double? = nil,
|
|
952
|
-
disabled: Bool = false,
|
|
953
|
-
readonly: Bool = false,
|
|
954
|
-
onSubmit: (() -> Void)? = nil,
|
|
955
|
-
onEscape: (() -> Void)? = nil
|
|
956
|
-
) {
|
|
957
|
-
self.label = label
|
|
958
|
-
self.value = value
|
|
959
|
-
self.onChange = onChange
|
|
960
|
-
self.focus = focus
|
|
961
|
-
self.focusKey = focusKey
|
|
962
|
-
self.placeholder = placeholder
|
|
963
|
-
self.helperText = helperText
|
|
964
|
-
self.error = error
|
|
965
|
-
self.secure = secure
|
|
966
|
-
self.email = email
|
|
967
|
-
self.multiline = multiline
|
|
968
|
-
self.rows = rows
|
|
969
|
-
self.maxLength = maxLength
|
|
970
|
-
self.disabled = disabled
|
|
971
|
-
self.readonly = readonly
|
|
972
|
-
self.onSubmit = onSubmit
|
|
973
|
-
self.onEscape = onEscape
|
|
974
|
-
_draft = State(initialValue: value)
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
private var focused: Bool { focus.wrappedValue == focusKey }
|
|
978
|
-
private var message: String { error.isEmpty ? helperText : error }
|
|
979
|
-
private var border: Color {
|
|
980
|
-
!error.isEmpty ? MavisTokens.danger : focused ? MavisTokens.primary : MavisTokens.border
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
var body: some View {
|
|
984
|
-
VStack(alignment: .leading, spacing: ${theme.space.sm}) {
|
|
985
|
-
MavisFieldLabel(text: label)
|
|
986
|
-
editor
|
|
987
|
-
.font(${font('body')})
|
|
988
|
-
.foregroundStyle(MavisTokens.text)
|
|
989
|
-
.background(readonly ? MavisTokens.elevated : MavisTokens.surface, in: RoundedRectangle(cornerRadius: ${radius}))
|
|
990
|
-
// The border only draws. Left hit-testable, it takes clicks on the field's middle line.
|
|
991
|
-
.overlay(RoundedRectangle(cornerRadius: ${radius}).strokeBorder(border, lineWidth: focused ? 2 : 1).allowsHitTesting(false))
|
|
992
|
-
.focused(focus, equals: focusKey)
|
|
993
|
-
.accessibilityLabel(Text(verbatim: label))
|
|
994
|
-
.onKeyPress(.escape) {
|
|
995
|
-
guard let onEscape else { return .ignored }
|
|
996
|
-
onEscape()
|
|
997
|
-
return .handled
|
|
998
|
-
}
|
|
999
|
-
if !message.isEmpty {
|
|
1000
|
-
MavisFieldMessage(label: label, text: message, error: !error.isEmpty)
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
.disabled(disabled)
|
|
1004
|
-
.opacity(disabled ? 0.5 : 1)
|
|
1005
|
-
.environment(\\.colorScheme, MavisTokens.colorScheme)
|
|
1006
|
-
.onChange(of: value) { _, next in
|
|
1007
|
-
if let index = pending.firstIndex(of: next) {
|
|
1008
|
-
pending.removeFirst(index + 1)
|
|
1009
|
-
} else {
|
|
1010
|
-
// Changed by the source itself: show its value.
|
|
1011
|
-
pending = []
|
|
1012
|
-
if next != draft { draft = next }
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
.onChange(of: draft) { _, next in
|
|
1016
|
-
let allowed = readonly ? value : mavisLimit(next, maxLength)
|
|
1017
|
-
if allowed != next {
|
|
1018
|
-
draft = allowed
|
|
1019
|
-
} else if next != value && pending.last != next {
|
|
1020
|
-
pending.append(next)
|
|
1021
|
-
onChange(next)
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
@ViewBuilder private var editor: some View {
|
|
1027
|
-
if multiline {
|
|
1028
|
-
TextEditor(text: $draft)
|
|
1029
|
-
.scrollContentBackground(.hidden)
|
|
1030
|
-
.frame(minHeight: rows * ${body.fontSize * input.lineHeight})
|
|
1031
|
-
.padding(.horizontal, ${input.paddingX - 5})
|
|
1032
|
-
.padding(.vertical, ${input.paddingY - 4})
|
|
1033
|
-
.overlay(alignment: .topLeading) {
|
|
1034
|
-
if draft.isEmpty && !placeholder.isEmpty {
|
|
1035
|
-
Text(verbatim: placeholder)
|
|
1036
|
-
.foregroundStyle(MavisTokens.muted)
|
|
1037
|
-
.padding(.horizontal, ${input.paddingX})
|
|
1038
|
-
.padding(.vertical, ${input.paddingY})
|
|
1039
|
-
.allowsHitTesting(false)
|
|
1040
|
-
.accessibilityHidden(true)
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
} else if secure {
|
|
1044
|
-
SecureField(text: $draft, prompt: prompt) { Text(verbatim: label) }
|
|
1045
|
-
.textFieldStyle(.plain)
|
|
1046
|
-
.labelsHidden()
|
|
1047
|
-
.onSubmit { onSubmit?() }
|
|
1048
|
-
.padding(.horizontal, ${input.paddingX})
|
|
1049
|
-
.padding(.vertical, ${input.paddingY})
|
|
1050
|
-
} else {
|
|
1051
|
-
TextField(text: $draft, prompt: prompt) { Text(verbatim: label) }
|
|
1052
|
-
.textFieldStyle(.plain)
|
|
1053
|
-
.labelsHidden()
|
|
1054
|
-
.autocorrectionDisabled(email)
|
|
1055
|
-
.onSubmit { onSubmit?() }
|
|
1056
|
-
.padding(.horizontal, ${input.paddingX})
|
|
1057
|
-
.padding(.vertical, ${input.paddingY})
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
private var prompt: Text? {
|
|
1062
|
-
placeholder.isEmpty ? nil : Text(verbatim: placeholder).foregroundStyle(MavisTokens.muted)
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
/// MCheckbox: the system checkbox. A mixed checkbox turns on when clicked, as on the Web.
|
|
1067
|
-
struct MavisCheckbox: View {
|
|
1068
|
-
let label: String
|
|
1069
|
-
let checked: Bool
|
|
1070
|
-
let onChange: (Bool) -> Void
|
|
1071
|
-
var indeterminate: Bool = false
|
|
1072
|
-
var helperText: String = ""
|
|
1073
|
-
var disabled: Bool = false
|
|
1074
|
-
|
|
1075
|
-
private var sources: [Binding<Bool>] {
|
|
1076
|
-
let source = Binding(get: { indeterminate ? false : checked }, set: { onChange($0) })
|
|
1077
|
-
// Two sources that disagree draw the mixed state.
|
|
1078
|
-
return indeterminate ? [source, .constant(true)] : [source]
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
var body: some View {
|
|
1082
|
-
VStack(alignment: .leading, spacing: ${theme.space.xs}) {
|
|
1083
|
-
Toggle(sources: sources, isOn: \\.self) {
|
|
1084
|
-
Text(verbatim: label)
|
|
1085
|
-
.font(.system(size: ${body.fontSize}, weight: .semibold))
|
|
1086
|
-
.foregroundStyle(MavisTokens.text)
|
|
1087
|
-
}
|
|
1088
|
-
.toggleStyle(.checkbox)
|
|
1089
|
-
.tint(MavisTokens.primary)
|
|
1090
|
-
if !helperText.isEmpty {
|
|
1091
|
-
MavisFieldMessage(label: label, text: helperText, error: false)
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
.disabled(disabled)
|
|
1095
|
-
.environment(\\.colorScheme, MavisTokens.colorScheme)
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
/// MSelect: a menu picker. With no value it shows the placeholder as an explicit empty choice.
|
|
1100
|
-
struct MavisSelect: View {
|
|
1101
|
-
let label: String
|
|
1102
|
-
let value: String?
|
|
1103
|
-
let options: [MavisChoice]
|
|
1104
|
-
let onChange: (String) -> Void
|
|
1105
|
-
var placeholder: String = "Select an option"
|
|
1106
|
-
var helperText: String = ""
|
|
1107
|
-
var error: String = ""
|
|
1108
|
-
var disabled: Bool = false
|
|
1109
|
-
|
|
1110
|
-
private var selected: String? {
|
|
1111
|
-
options.contains { $0.value == value } ? value : nil
|
|
1112
|
-
}
|
|
1113
|
-
private var message: String { error.isEmpty ? helperText : error }
|
|
1114
|
-
|
|
1115
|
-
var body: some View {
|
|
1116
|
-
VStack(alignment: .leading, spacing: ${theme.space.sm}) {
|
|
1117
|
-
MavisFieldLabel(text: label)
|
|
1118
|
-
Picker(selection: Binding(get: { selected }, set: { next in
|
|
1119
|
-
if let next, next != value, options.contains(where: { $0.value == next && !$0.disabled }) {
|
|
1120
|
-
onChange(next)
|
|
1121
|
-
}
|
|
1122
|
-
})) {
|
|
1123
|
-
if selected == nil {
|
|
1124
|
-
Text(verbatim: placeholder).tag(String?.none)
|
|
1125
|
-
}
|
|
1126
|
-
ForEach(options, id: \\.value) { option in
|
|
1127
|
-
Text(verbatim: option.label)
|
|
1128
|
-
.tag(Optional(option.value))
|
|
1129
|
-
.disabled(option.disabled)
|
|
1130
|
-
}
|
|
1131
|
-
} label: {
|
|
1132
|
-
Text(verbatim: label)
|
|
1133
|
-
}
|
|
1134
|
-
.pickerStyle(.menu)
|
|
1135
|
-
.labelsHidden()
|
|
1136
|
-
.tint(MavisTokens.primary)
|
|
1137
|
-
.fixedSize()
|
|
1138
|
-
if !message.isEmpty {
|
|
1139
|
-
MavisFieldMessage(label: label, text: message, error: !error.isEmpty)
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
.disabled(disabled)
|
|
1143
|
-
.environment(\\.colorScheme, MavisTokens.colorScheme)
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
`
|
|
1147
|
-
return { tokens, source, controls }
|
|
1148
|
-
}
|
|
1149
|
-
|
|
1150
|
-
export const runtime = `import SwiftUI
|
|
1151
|
-
|
|
1152
|
-
/// Number#toString(10) from ECMAScript, so text shows the same digits on the Web and macOS.
|
|
1153
|
-
func mavisString(_ value: Double) -> String {
|
|
1154
|
-
if value.isNaN { return "NaN" }
|
|
1155
|
-
if value == 0 { return "0" }
|
|
1156
|
-
if value.isInfinite { return value < 0 ? "-Infinity" : "Infinity" }
|
|
1157
|
-
if value < 0 { return "-" + mavisString(-value) }
|
|
1158
|
-
// Swift prints the shortest round-trip digits; only the layout differs from JavaScript.
|
|
1159
|
-
let printed = "\\(value)".lowercased()
|
|
1160
|
-
let parts = printed.split(separator: "e", maxSplits: 1)
|
|
1161
|
-
let mantissa = parts[0]
|
|
1162
|
-
let exponent = parts.count > 1 ? Int(parts[1])! : 0
|
|
1163
|
-
let pieces = mantissa.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: false)
|
|
1164
|
-
let whole = String(pieces[0])
|
|
1165
|
-
let fraction = pieces.count > 1 ? String(pieces[1]) : ""
|
|
1166
|
-
var digits = Array(whole + fraction)
|
|
1167
|
-
var point = whole.count + exponent
|
|
1168
|
-
while let first = digits.first, first == "0", digits.count > 1 {
|
|
1169
|
-
digits.removeFirst()
|
|
1170
|
-
point -= 1
|
|
1171
|
-
}
|
|
1172
|
-
while let last = digits.last, last == "0", digits.count > 1 { digits.removeLast() }
|
|
1173
|
-
let s = String(digits)
|
|
1174
|
-
let k = digits.count
|
|
1175
|
-
let n = point
|
|
1176
|
-
if k <= n && n <= 21 { return s + String(repeating: "0", count: n - k) }
|
|
1177
|
-
if 0 < n && n <= 21 { return String(digits[0..<n]) + "." + String(digits[n...]) }
|
|
1178
|
-
if -6 < n && n <= 0 { return "0." + String(repeating: "0", count: -n) + s }
|
|
1179
|
-
let e = n - 1
|
|
1180
|
-
let sign = e < 0 ? "-" : "+"
|
|
1181
|
-
let head = k == 1 ? s : String(digits[0]) + "." + String(digits[1...])
|
|
1182
|
-
return head + "e" + sign + String(abs(e))
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
/// String#trim: ECMAScript white space and line terminators.
|
|
1186
|
-
func mavisTrim(_ text: String) -> String {
|
|
1187
|
-
func space(_ scalar: Unicode.Scalar) -> Bool {
|
|
1188
|
-
switch scalar.value {
|
|
1189
|
-
case 0x9, 0xA, 0xB, 0xC, 0xD, 0x20, 0xA0, 0x1680, 0x2000...0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF:
|
|
1190
|
-
return true
|
|
1191
|
-
default:
|
|
1192
|
-
return false
|
|
1193
|
-
}
|
|
1194
|
-
}
|
|
1195
|
-
let scalars = text.unicodeScalars
|
|
1196
|
-
guard let start = scalars.firstIndex(where: { !space($0) }),
|
|
1197
|
-
let end = scalars.lastIndex(where: { !space($0) }) else { return "" }
|
|
1198
|
-
return String(scalars[start...end])
|
|
1199
|
-
}
|
|
1200
|
-
|
|
1201
|
-
func mavisIncludes(_ text: String, _ search: String) -> Bool {
|
|
1202
|
-
search.isEmpty || text.range(of: search, options: .literal) != nil
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
func mavisRound(_ value: Double) -> Double {
|
|
1206
|
-
let floor = value.rounded(.down)
|
|
1207
|
-
return value - floor >= 0.5 ? floor + 1 : floor
|
|
1208
|
-
}
|
|
1209
|
-
|
|
1210
|
-
func mavisFindIndex<T>(_ items: [T], _ match: (T) -> Bool) -> Double {
|
|
1211
|
-
items.firstIndex(where: match).map(Double.init) ?? -1
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
private func mavisInteger(_ value: Double) -> Double {
|
|
1215
|
-
value.isNaN ? 0 : value.rounded(.towardZero)
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
private func mavisClamp(_ value: Double, _ count: Int) -> Int {
|
|
1219
|
-
let length = Double(count)
|
|
1220
|
-
let relative = mavisInteger(value)
|
|
1221
|
-
return Int(relative < 0 ? max(length + relative, 0) : min(relative, length))
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
/// Array#splice(start, deleteCount, ...items), including negative and out-of-range indices.
|
|
1225
|
-
func mavisSplice<T>(_ items: inout [T], _ start: Double, _ deleteCount: Double, _ inserted: [T]) {
|
|
1226
|
-
let from = mavisClamp(start, items.count)
|
|
1227
|
-
let count = Int(min(max(mavisInteger(deleteCount), 0), Double(items.count - from)))
|
|
1228
|
-
items.replaceSubrange(from..<(from + count), with: inserted)
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
/// Array#slice(start, end).
|
|
1232
|
-
func mavisSlice<T>(_ items: [T], _ start: Double, _ end: Double? = nil) -> [T] {
|
|
1233
|
-
let from = mavisClamp(start, items.count)
|
|
1234
|
-
let to = end.map { mavisClamp($0, items.count) } ?? items.count
|
|
1235
|
-
return from < to ? Array(items[from..<to]) : []
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
/// list[index]: undefined unless index is a whole number inside the list.
|
|
1239
|
-
func mavisAt<T>(_ items: [T], _ index: Double) -> T? {
|
|
1240
|
-
guard index >= 0, index < Double(items.count), index == index.rounded(.towardZero) else { return nil }
|
|
1241
|
-
return items[Int(index)]
|
|
1242
|
-
}
|
|
1243
|
-
|
|
1244
|
-
/// a < b for strings in JavaScript: UTF-16 code units, not Unicode canonical order.
|
|
1245
|
-
func mavisBefore(_ a: String, _ b: String) -> Bool {
|
|
1246
|
-
a.utf16.lexicographicallyPrecedes(b.utf16)
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
/// Array#toSorted(compare): stable, and NaN counts as equal.
|
|
1250
|
-
func mavisSorted<T>(_ items: [T], _ compare: (T, T) -> Double) -> [T] {
|
|
1251
|
-
items.enumerated().sorted { a, b in
|
|
1252
|
-
let order = compare(a.element, b.element)
|
|
1253
|
-
return order < 0 || (!(order > 0) && a.offset < b.offset)
|
|
1254
|
-
}.map(\\.element)
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
/// maxLength counts UTF-16 units, like the Web; it never splits a character.
|
|
1258
|
-
func mavisLimit(_ text: String, _ maxLength: Double?) -> String {
|
|
1259
|
-
guard let maxLength, Double(text.utf16.count) > maxLength else { return text }
|
|
1260
|
-
var kept = ""
|
|
1261
|
-
var count = 0
|
|
1262
|
-
for character in text {
|
|
1263
|
-
let size = character.utf16.count
|
|
1264
|
-
if Double(count + size) > maxLength { break }
|
|
1265
|
-
kept.append(character)
|
|
1266
|
-
count += size
|
|
1267
|
-
}
|
|
1268
|
-
return kept
|
|
1269
|
-
}
|
|
1270
|
-
|
|
1271
|
-
/// The source's name for a pressed arrow key.
|
|
1272
|
-
func mavisKeyName(_ key: KeyEquivalent) -> String {
|
|
1273
|
-
switch key {
|
|
1274
|
-
case .upArrow: return "ArrowUp"
|
|
1275
|
-
case .downArrow: return "ArrowDown"
|
|
1276
|
-
case .leftArrow: return "ArrowLeft"
|
|
1277
|
-
default: return "ArrowRight"
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
/// Object spread for records: a changed copy.
|
|
1282
|
-
func mavisCopy<T>(_ value: T, _ change: (inout T) -> Void) -> T {
|
|
1283
|
-
var copy = value
|
|
1284
|
-
change(©)
|
|
1285
|
-
return copy
|
|
1286
|
-
}
|
|
1287
|
-
`
|