@getcortexlabs/create-mavis 0.1.0-rc.12.2 → 0.1.0-rc.13
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 +6 -6
- package/package.json +1 -1
- package/src/adapters.mjs +76 -0
- package/src/add-target.mjs +1 -1
- package/src/capabilities.mjs +626 -0
- package/src/cli.mjs +43 -12
- package/src/doctor.mjs +77 -36
- package/src/macos.mjs +223 -56
- package/src/package-manager.mjs +12 -4
- package/src/portability.mjs +2 -1
- package/src/presets.mjs +15 -108
- package/src/scaffold.mjs +11 -3
- package/src/ui.mjs +115 -82
- package/templates/macos/examples/tasks/shared/TaskDetail.lite.tsx +57 -0
- package/templates/macos/examples/tasks/shared/TaskRow.lite.tsx +33 -0
- package/templates/macos/examples/tasks/shared/Tasks.lite.tsx +251 -0
- package/templates/macos/examples/tasks/shared/types.ts +9 -0
- package/templates/macos/mobile/src/App.vue +12 -0
- package/templates/macos/mobile/src/app.ts +7 -0
- package/templates/macos/native/Package.swift +9 -1
- package/templates/macos/native/Sources/MavisDesktop/App.swift +4 -4
- package/templates/macos/root/tsconfig.json +14 -0
- package/templates/macos/scripts/generate.mjs +35 -16
- package/templates/macos/scripts/macos.mjs +8 -3
- package/templates/macos/scripts/portable/emit-swift.mjs +1287 -0
- package/templates/macos/scripts/portable/emit-vue.mjs +615 -0
- package/templates/macos/scripts/portable/index.mjs +95 -0
- package/templates/macos/scripts/portable/model.mjs +1441 -0
- package/templates/macos/scripts/portable/program.mjs +163 -0
- package/templates/macos/shared/Welcome.lite.tsx +8 -6
- package/templates/macos/{index.html → web/index.html} +1 -1
- package/templates/macos/web/src/main.js +39 -0
- package/templates/macos/web/{style.css → src/style.css} +1 -1
- package/templates/macos/web/vite.config.mjs +3 -0
- package/templates/macos/scripts/portable.mjs +0 -395
- package/templates/macos/vite.config.mjs +0 -3
- package/templates/macos/web/main.js +0 -15
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import ts from 'typescript'
|
|
2
|
+
|
|
3
|
+
export const preludePath = 'shared/__mavis_prelude__.d.ts'
|
|
4
|
+
|
|
5
|
+
export const keys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']
|
|
6
|
+
|
|
7
|
+
/** Each primitive's properties: how a value is checked and passed to both renderers. */
|
|
8
|
+
export const primitives = {
|
|
9
|
+
MColumn: { gap: 'space', padding: 'space', label: 'string', onKeyDown: 'key' },
|
|
10
|
+
MRow: { gap: 'space', padding: 'space', label: 'string', onKeyDown: 'key' },
|
|
11
|
+
MGrid: { gap: 'space', columns: 'number', minColumnWidth: 'number' },
|
|
12
|
+
MCard: { gap: 'space', padding: 'space', tone: 'string', label: 'string', onClick: 'handler' },
|
|
13
|
+
MText: { variant: 'string', tone: 'string' },
|
|
14
|
+
MButton: {
|
|
15
|
+
text: 'string',
|
|
16
|
+
variant: 'string',
|
|
17
|
+
disabled: 'boolean',
|
|
18
|
+
onClick: 'handler',
|
|
19
|
+
shortcut: 'shortcut',
|
|
20
|
+
},
|
|
21
|
+
MInput: {
|
|
22
|
+
label: 'string',
|
|
23
|
+
value: 'string',
|
|
24
|
+
onChange: 'string-handler',
|
|
25
|
+
placeholder: 'string',
|
|
26
|
+
helperText: 'string',
|
|
27
|
+
error: 'string',
|
|
28
|
+
type: 'string',
|
|
29
|
+
multiline: 'boolean',
|
|
30
|
+
rows: 'number',
|
|
31
|
+
maxLength: 'number',
|
|
32
|
+
disabled: 'boolean',
|
|
33
|
+
readonly: 'boolean',
|
|
34
|
+
onSubmit: 'handler',
|
|
35
|
+
onEscape: 'handler',
|
|
36
|
+
ref: 'ref',
|
|
37
|
+
},
|
|
38
|
+
MCheckbox: {
|
|
39
|
+
label: 'string',
|
|
40
|
+
checked: 'boolean',
|
|
41
|
+
onChange: 'boolean-handler',
|
|
42
|
+
indeterminate: 'boolean',
|
|
43
|
+
helperText: 'string',
|
|
44
|
+
disabled: 'boolean',
|
|
45
|
+
},
|
|
46
|
+
MSelect: {
|
|
47
|
+
label: 'string',
|
|
48
|
+
value: 'optional-string',
|
|
49
|
+
options: 'options',
|
|
50
|
+
onChange: 'string-handler',
|
|
51
|
+
placeholder: 'string',
|
|
52
|
+
helperText: 'string',
|
|
53
|
+
error: 'string',
|
|
54
|
+
disabled: 'boolean',
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const union = (values) => values.map((value) => JSON.stringify(value)).join(' | ')
|
|
59
|
+
|
|
60
|
+
/** Ambient declarations for the shared sources: Mavis primitives and the Mitosis authoring API. */
|
|
61
|
+
export function prelude(theme) {
|
|
62
|
+
return `declare namespace JSX {
|
|
63
|
+
interface Element { readonly __mavisElement: true }
|
|
64
|
+
interface ElementChildrenAttribute { children: {} }
|
|
65
|
+
interface IntrinsicAttributes { key?: string | number }
|
|
66
|
+
interface IntrinsicElements {}
|
|
67
|
+
}
|
|
68
|
+
type MavisSpace = ${union(Object.keys(theme.space))}
|
|
69
|
+
type MavisVariant = ${union(Object.keys(theme.typography))}
|
|
70
|
+
type MavisTone = ${union(Object.keys(theme.colors))}
|
|
71
|
+
type MavisText = string | number | boolean
|
|
72
|
+
type MavisKey = ${union(keys)}
|
|
73
|
+
/** Command on Apple keyboards, Control elsewhere, with a letter or Enter. */
|
|
74
|
+
type MavisShortcut = ${union([...'abcdefghijklmnopqrstuvwxyz'].map((letter) => `mod+${letter}`))} | 'mod+Enter'
|
|
75
|
+
/** A field you can move focus to from an action: const titleRef = useRef<MavisFieldRef>(null). */
|
|
76
|
+
interface MavisFieldRef { focus(): void; blur(): void }
|
|
77
|
+
type SelectOption = { value: string; label: string; disabled?: boolean }
|
|
78
|
+
type MavisStack = { gap?: MavisSpace; padding?: MavisSpace; label?: string; onKeyDown?: (key: MavisKey) => void; children?: unknown }
|
|
79
|
+
declare function MColumn(props: MavisStack): JSX.Element
|
|
80
|
+
declare function MRow(props: MavisStack): JSX.Element
|
|
81
|
+
declare function MGrid(props: { gap?: MavisSpace; columns?: number; minColumnWidth?: number; children?: unknown }): JSX.Element
|
|
82
|
+
declare function MCard(props: { gap?: MavisSpace; padding?: MavisSpace; tone?: MavisTone; label?: string; onClick?: () => void; children?: unknown }): JSX.Element
|
|
83
|
+
declare function MText(props: { variant?: MavisVariant; tone?: MavisTone; children?: MavisText | MavisText[] }): JSX.Element
|
|
84
|
+
declare function MButton(props: { text: string; variant?: 'primary' | 'secondary'; disabled?: boolean; onClick: () => void; shortcut?: MavisShortcut }): JSX.Element
|
|
85
|
+
declare function MInput(props: { label: string; value: string; onChange: (value: string) => void; placeholder?: string; helperText?: string; error?: string; type?: 'text' | 'email' | 'password'; multiline?: boolean; rows?: number; maxLength?: number; disabled?: boolean; readonly?: boolean; onSubmit?: () => void; onEscape?: () => void; ref?: MavisFieldRef }): JSX.Element
|
|
86
|
+
declare function MCheckbox(props: { label: string; checked: boolean; onChange: (checked: boolean) => void; indeterminate?: boolean; helperText?: string; disabled?: boolean }): JSX.Element
|
|
87
|
+
declare function MSelect(props: { label: string; value: string | undefined; options: SelectOption[]; onChange: (value: string) => void; placeholder?: string; helperText?: string; error?: string; disabled?: boolean }): JSX.Element
|
|
88
|
+
declare module '@builder.io/mitosis' {
|
|
89
|
+
export function useStore<T extends object>(initial: T): T
|
|
90
|
+
export function useRef<T>(initial?: T | null): T
|
|
91
|
+
export function Show(props: { when: boolean; else?: JSX.Element; animate?: boolean; children?: unknown }): JSX.Element
|
|
92
|
+
export function For<T>(props: { each: readonly T[]; animate?: boolean; children: (item: T, index: number) => JSX.Element }): JSX.Element
|
|
93
|
+
}
|
|
94
|
+
`
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const compilerOptions = {
|
|
98
|
+
strict: true,
|
|
99
|
+
noEmit: true,
|
|
100
|
+
jsx: ts.JsxEmit.Preserve,
|
|
101
|
+
target: ts.ScriptTarget.ES2022,
|
|
102
|
+
module: ts.ModuleKind.ESNext,
|
|
103
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
104
|
+
allowImportingTsExtensions: false,
|
|
105
|
+
lib: ['lib.es2023.d.ts'],
|
|
106
|
+
// Reading list[i] can miss in JavaScript; make that visible in the types too.
|
|
107
|
+
noUncheckedIndexedAccess: true,
|
|
108
|
+
types: [],
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Type-checks the shared sources in memory. `files` maps a project-relative path
|
|
113
|
+
* (shared/Welcome.lite.tsx) to its text.
|
|
114
|
+
*/
|
|
115
|
+
export function createProgram(files, theme) {
|
|
116
|
+
const root = '/mavis/'
|
|
117
|
+
const texts = new Map([...files].map(([path, text]) => [root + path, text]))
|
|
118
|
+
texts.set(root + preludePath, prelude(theme))
|
|
119
|
+
const base = ts.createCompilerHost(compilerOptions)
|
|
120
|
+
const host = {
|
|
121
|
+
...base,
|
|
122
|
+
getCurrentDirectory: () => root,
|
|
123
|
+
fileExists: (name) => texts.has(name) || (!name.startsWith(root) && base.fileExists(name)),
|
|
124
|
+
readFile: (name) =>
|
|
125
|
+
texts.get(name) ?? (name.startsWith(root) ? undefined : base.readFile(name)),
|
|
126
|
+
getSourceFile(name, languageVersion) {
|
|
127
|
+
const text = texts.get(name)
|
|
128
|
+
if (text !== undefined)
|
|
129
|
+
return ts.createSourceFile(
|
|
130
|
+
name,
|
|
131
|
+
text,
|
|
132
|
+
languageVersion,
|
|
133
|
+
true,
|
|
134
|
+
name.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
|
|
135
|
+
)
|
|
136
|
+
return name.startsWith(root) ? undefined : base.getSourceFile(name, languageVersion)
|
|
137
|
+
},
|
|
138
|
+
writeFile() {},
|
|
139
|
+
directoryExists: (name) =>
|
|
140
|
+
name.startsWith(root)
|
|
141
|
+
? [...texts.keys()].some((path) => path.startsWith(name.endsWith('/') ? name : name + '/'))
|
|
142
|
+
: (base.directoryExists?.(name) ?? true),
|
|
143
|
+
getDirectories: () => [],
|
|
144
|
+
}
|
|
145
|
+
const program = ts.createProgram([...texts.keys()], compilerOptions, host)
|
|
146
|
+
const relative = (name) => name.slice(root.length)
|
|
147
|
+
const diagnostics = ts
|
|
148
|
+
.getPreEmitDiagnostics(program)
|
|
149
|
+
.filter((diagnostic) => !diagnostic.file || diagnostic.file.fileName.startsWith(root))
|
|
150
|
+
.map((diagnostic) => {
|
|
151
|
+
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
|
|
152
|
+
if (!diagnostic.file || diagnostic.start === undefined) return message
|
|
153
|
+
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
|
|
154
|
+
return `${relative(diagnostic.file.fileName)}:${line + 1}:${character + 1}: ${message}`
|
|
155
|
+
})
|
|
156
|
+
return {
|
|
157
|
+
program,
|
|
158
|
+
checker: program.getTypeChecker(),
|
|
159
|
+
diagnostics,
|
|
160
|
+
sourceFile: (path) => program.getSourceFile(root + path),
|
|
161
|
+
relative,
|
|
162
|
+
}
|
|
163
|
+
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { useStore } from '@builder.io/mitosis'
|
|
1
|
+
import { useStore, Show } from '@builder.io/mitosis'
|
|
2
2
|
|
|
3
|
-
// This
|
|
4
|
-
// Edit this source, then run the generate command before rebuilding either host.
|
|
3
|
+
// This checked subset generates every target. Edit it, then run the generate command.
|
|
5
4
|
export default function Welcome() {
|
|
6
5
|
const state = useStore({ sparks: 0 })
|
|
7
6
|
return (
|
|
@@ -11,7 +10,7 @@ export default function Welcome() {
|
|
|
11
10
|
MAVIS / FIRST LIGHT
|
|
12
11
|
</MText>
|
|
13
12
|
<MText variant="caption" tone="muted">
|
|
14
|
-
Experimental ·
|
|
13
|
+
Experimental · __MAVIS_TARGETS__
|
|
15
14
|
</MText>
|
|
16
15
|
</MRow>
|
|
17
16
|
<MColumn gap="sm">
|
|
@@ -19,7 +18,7 @@ export default function Welcome() {
|
|
|
19
18
|
<MText variant="display" tone="primary">
|
|
20
19
|
A new window.
|
|
21
20
|
</MText>
|
|
22
|
-
<MText tone="muted">Your first shared screen,
|
|
21
|
+
<MText tone="muted">Your first shared screen, at home on every target.</MText>
|
|
23
22
|
</MColumn>
|
|
24
23
|
<MColumn gap="md" padding="lg">
|
|
25
24
|
<MText variant="overline" tone="muted">
|
|
@@ -27,13 +26,16 @@ export default function Welcome() {
|
|
|
27
26
|
</MText>
|
|
28
27
|
<MText variant="title">{state.sparks}</MText>
|
|
29
28
|
<MText tone="muted">Sparks collected in this window.</MText>
|
|
29
|
+
<Show when={state.sparks > 0} animate>
|
|
30
|
+
<MText tone="primary">Motion runs through Jolt on every target.</MText>
|
|
31
|
+
</Show>
|
|
30
32
|
<MRow gap="sm">
|
|
31
33
|
<MButton text="Add a spark" onClick={() => (state.sparks = state.sparks + 1)} />
|
|
32
34
|
<MButton text="Start again" variant="secondary" onClick={() => (state.sparks = 0)} />
|
|
33
35
|
</MRow>
|
|
34
36
|
</MColumn>
|
|
35
37
|
<MText variant="caption" tone="muted">
|
|
36
|
-
One Welcome.lite.tsx ·
|
|
38
|
+
One Welcome.lite.tsx · __MAVIS_HOSTS__
|
|
37
39
|
</MText>
|
|
38
40
|
</MColumn>
|
|
39
41
|
)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createApp } from 'vue'
|
|
2
|
+
import { createMavisServices } from '@getcortexlabs/mavis-web/services'
|
|
3
|
+
import {
|
|
4
|
+
MButton,
|
|
5
|
+
MCard,
|
|
6
|
+
MCheckbox,
|
|
7
|
+
MColumn,
|
|
8
|
+
MGrid,
|
|
9
|
+
MInput,
|
|
10
|
+
MReveal,
|
|
11
|
+
MRow,
|
|
12
|
+
MSelect,
|
|
13
|
+
MText,
|
|
14
|
+
mavis,
|
|
15
|
+
midnight,
|
|
16
|
+
} from '@getcortexlabs/mavis-web'
|
|
17
|
+
import Root from './generated/__MAVIS_ROOT__.vue'
|
|
18
|
+
import '@getcortexlabs/mavis-web/style.css'
|
|
19
|
+
import './style.css'
|
|
20
|
+
|
|
21
|
+
const app = createApp(Root)
|
|
22
|
+
for (const [name, component] of Object.entries({
|
|
23
|
+
MColumn,
|
|
24
|
+
MRow,
|
|
25
|
+
MGrid,
|
|
26
|
+
MCard,
|
|
27
|
+
MText,
|
|
28
|
+
MButton,
|
|
29
|
+
MInput,
|
|
30
|
+
MCheckbox,
|
|
31
|
+
MSelect,
|
|
32
|
+
MReveal,
|
|
33
|
+
}))
|
|
34
|
+
app.component(name, component)
|
|
35
|
+
app
|
|
36
|
+
.use(
|
|
37
|
+
createMavisServices({ theme: mavis, darkTheme: midnight, appearance: '__MAVIS_APPEARANCE__' }),
|
|
38
|
+
)
|
|
39
|
+
.mount('#app')
|
|
@@ -1,395 +0,0 @@
|
|
|
1
|
-
import ts from 'typescript'
|
|
2
|
-
|
|
3
|
-
const allowed = {
|
|
4
|
-
MColumn: ['gap', 'padding'],
|
|
5
|
-
MRow: ['gap', 'padding'],
|
|
6
|
-
MText: ['variant', 'tone'],
|
|
7
|
-
MButton: ['text', 'variant', 'onClick'],
|
|
8
|
-
}
|
|
9
|
-
const reserved = new Set(
|
|
10
|
-
'self body description init let var func class struct enum protocol extension import return true false nil default switch case if else for while repeat break continue throw throws try catch await async in is as some any private public internal static typealias defer guard do super associatedtype deinit fileprivate inout operator rethrows subscript where'.split(
|
|
11
|
-
' ',
|
|
12
|
-
),
|
|
13
|
-
)
|
|
14
|
-
|
|
15
|
-
/** A deliberately bounded grammar, checked before Mitosis can drop unsupported code. */
|
|
16
|
-
export function validateSource(source) {
|
|
17
|
-
const file = ts.createSourceFile(
|
|
18
|
-
'shared/Welcome.lite.tsx',
|
|
19
|
-
source,
|
|
20
|
-
ts.ScriptTarget.Latest,
|
|
21
|
-
true,
|
|
22
|
-
ts.ScriptKind.TSX,
|
|
23
|
-
)
|
|
24
|
-
const fail = (node, message) => {
|
|
25
|
-
const { line, character } = file.getLineAndCharacterOfPosition(node.getStart(file))
|
|
26
|
-
throw new Error(`${file.fileName}:${line + 1}:${character + 1}: ${message}`)
|
|
27
|
-
}
|
|
28
|
-
if (file.parseDiagnostics.length) fail(file, 'Invalid TSX syntax.')
|
|
29
|
-
const statements = file.statements
|
|
30
|
-
const imp = statements[0]
|
|
31
|
-
if (
|
|
32
|
-
statements.length !== 2 ||
|
|
33
|
-
!imp ||
|
|
34
|
-
!ts.isImportDeclaration(imp) ||
|
|
35
|
-
imp.moduleSpecifier.text !== '@builder.io/mitosis' ||
|
|
36
|
-
imp.importClause?.name ||
|
|
37
|
-
imp.importClause?.isTypeOnly ||
|
|
38
|
-
imp.attributes ||
|
|
39
|
-
!imp.importClause?.namedBindings ||
|
|
40
|
-
!ts.isNamedImports(imp.importClause.namedBindings) ||
|
|
41
|
-
imp.importClause.namedBindings.elements.length !== 1 ||
|
|
42
|
-
imp.importClause.namedBindings.elements[0].name.text !== 'useStore' ||
|
|
43
|
-
imp.importClause.namedBindings.elements[0].propertyName
|
|
44
|
-
)
|
|
45
|
-
fail(
|
|
46
|
-
file,
|
|
47
|
-
'Import only { useStore } from @builder.io/mitosis, followed by export default function Welcome().',
|
|
48
|
-
)
|
|
49
|
-
const fn = statements[1]
|
|
50
|
-
if (
|
|
51
|
-
!ts.isFunctionDeclaration(fn) ||
|
|
52
|
-
fn.name?.text !== 'Welcome' ||
|
|
53
|
-
fn.parameters.length ||
|
|
54
|
-
fn.typeParameters ||
|
|
55
|
-
fn.asteriskToken ||
|
|
56
|
-
fn.type ||
|
|
57
|
-
fn.modifiers?.map((m) => m.kind).join(',') !==
|
|
58
|
-
[ts.SyntaxKind.ExportKeyword, ts.SyntaxKind.DefaultKeyword].join(',') ||
|
|
59
|
-
fn.body?.statements.length !== 2
|
|
60
|
-
)
|
|
61
|
-
fail(
|
|
62
|
-
fn,
|
|
63
|
-
'Use export default function Welcome() with one state declaration and one JSX return. Hooks, props and arbitrary functions are not supported yet.',
|
|
64
|
-
)
|
|
65
|
-
const declaration = fn.body.statements[0]
|
|
66
|
-
if (
|
|
67
|
-
!ts.isVariableStatement(declaration) ||
|
|
68
|
-
declaration.declarationList.flags !== ts.NodeFlags.Const ||
|
|
69
|
-
declaration.declarationList.declarations.length !== 1
|
|
70
|
-
)
|
|
71
|
-
fail(declaration, 'Declare const state = useStore({ ... }).')
|
|
72
|
-
const store = declaration.declarationList.declarations[0]
|
|
73
|
-
if (
|
|
74
|
-
!ts.isIdentifier(store.name) ||
|
|
75
|
-
store.name.text !== 'state' ||
|
|
76
|
-
store.type ||
|
|
77
|
-
!store.initializer ||
|
|
78
|
-
!ts.isCallExpression(store.initializer) ||
|
|
79
|
-
store.initializer.expression.getText(file) !== 'useStore' ||
|
|
80
|
-
store.initializer.typeArguments ||
|
|
81
|
-
store.initializer.arguments.length !== 1 ||
|
|
82
|
-
!ts.isObjectLiteralExpression(store.initializer.arguments[0])
|
|
83
|
-
)
|
|
84
|
-
fail(store, 'Declare const state = useStore({ ... }) without type arguments.')
|
|
85
|
-
const state = new Map()
|
|
86
|
-
const literal = (node) => {
|
|
87
|
-
if (ts.isStringLiteral(node)) return { kind: 'string', value: node.text }
|
|
88
|
-
if (ts.isNumericLiteral(node) && /^\d+$/.test(node.text) && Number(node.text) <= 2147483647)
|
|
89
|
-
return { kind: 'number', value: Number(node.text) }
|
|
90
|
-
if ([ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword].includes(node.kind))
|
|
91
|
-
return { kind: 'boolean', value: node.kind === ts.SyntaxKind.TrueKeyword }
|
|
92
|
-
return null
|
|
93
|
-
}
|
|
94
|
-
for (const prop of store.initializer.arguments[0].properties) {
|
|
95
|
-
if (
|
|
96
|
-
!ts.isPropertyAssignment(prop) ||
|
|
97
|
-
!ts.isIdentifier(prop.name) ||
|
|
98
|
-
reserved.has(prop.name.text) ||
|
|
99
|
-
!/^[a-z][a-zA-Z0-9]*$/.test(prop.name.text) ||
|
|
100
|
-
state.has(prop.name.text)
|
|
101
|
-
)
|
|
102
|
-
fail(prop, 'State needs unique, simple names (not Swift keywords) and literal values.')
|
|
103
|
-
const value = literal(prop.initializer)
|
|
104
|
-
if (!value)
|
|
105
|
-
fail(prop, 'State supports strings, booleans and non-negative 32-bit integer literals only.')
|
|
106
|
-
state.set(prop.name.text, value)
|
|
107
|
-
}
|
|
108
|
-
const reference = (node) =>
|
|
109
|
-
ts.isPropertyAccessExpression(node) &&
|
|
110
|
-
ts.isIdentifier(node.expression) &&
|
|
111
|
-
node.expression.text === 'state' &&
|
|
112
|
-
state.has(node.name.text)
|
|
113
|
-
? node.name.text
|
|
114
|
-
: null
|
|
115
|
-
const action = (node) => {
|
|
116
|
-
if (
|
|
117
|
-
!ts.isArrowFunction(node) ||
|
|
118
|
-
node.parameters.length ||
|
|
119
|
-
node.modifiers ||
|
|
120
|
-
node.typeParameters ||
|
|
121
|
-
node.type
|
|
122
|
-
)
|
|
123
|
-
fail(node, 'onClick supports a zero-argument arrow with one state assignment.')
|
|
124
|
-
let body = node.body
|
|
125
|
-
while (ts.isParenthesizedExpression(body)) body = body.expression
|
|
126
|
-
if (
|
|
127
|
-
!ts.isBinaryExpression(body) ||
|
|
128
|
-
body.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
|
|
129
|
-
!reference(body.left)
|
|
130
|
-
)
|
|
131
|
-
fail(body, 'Assign one declared state property, for example state.sparks = state.sparks + 1.')
|
|
132
|
-
const key = reference(body.left),
|
|
133
|
-
value = literal(body.right)
|
|
134
|
-
if (value?.kind === state.get(key).kind) return
|
|
135
|
-
if (
|
|
136
|
-
state.get(key).kind === 'number' &&
|
|
137
|
-
ts.isBinaryExpression(body.right) &&
|
|
138
|
-
reference(body.right.left) === key &&
|
|
139
|
-
body.right.operatorToken.kind === ts.SyntaxKind.PlusToken &&
|
|
140
|
-
literal(body.right.right)?.kind === 'number'
|
|
141
|
-
)
|
|
142
|
-
return
|
|
143
|
-
fail(
|
|
144
|
-
body.right,
|
|
145
|
-
'Only same-type literal assignments or integer increments are supported. Calls, effects and other expressions need a future compiler contract.',
|
|
146
|
-
)
|
|
147
|
-
}
|
|
148
|
-
const jsx = (node, parent) => {
|
|
149
|
-
if (ts.isParenthesizedExpression(node)) return jsx(node.expression, parent)
|
|
150
|
-
if (ts.isJsxText(node)) {
|
|
151
|
-
if (node.text.trim() && parent !== 'MText') fail(node, 'Put text inside MText.')
|
|
152
|
-
return
|
|
153
|
-
}
|
|
154
|
-
if (ts.isJsxExpression(node)) {
|
|
155
|
-
if (parent !== 'MText' || !node.expression || !reference(node.expression))
|
|
156
|
-
fail(node, 'Text bindings must reference one declared state property.')
|
|
157
|
-
return
|
|
158
|
-
}
|
|
159
|
-
if (!ts.isJsxElement(node) && !ts.isJsxSelfClosingElement(node))
|
|
160
|
-
fail(
|
|
161
|
-
node,
|
|
162
|
-
'Use MColumn, MRow, MText and MButton. HTML, loops, conditionals and other components are not supported yet.',
|
|
163
|
-
)
|
|
164
|
-
const tag = ts.isJsxElement(node) ? node.openingElement : node
|
|
165
|
-
const name = tag.tagName.getText(file)
|
|
166
|
-
if (!allowed[name]) fail(tag, `${name} is not part of the experimental macOS subset.`)
|
|
167
|
-
const names = new Set()
|
|
168
|
-
for (const attr of tag.attributes.properties) {
|
|
169
|
-
if (
|
|
170
|
-
!ts.isJsxAttribute(attr) ||
|
|
171
|
-
!allowed[name].includes(attr.name.text) ||
|
|
172
|
-
names.has(attr.name.text)
|
|
173
|
-
)
|
|
174
|
-
fail(
|
|
175
|
-
attr,
|
|
176
|
-
`Unsupported or duplicate ${name} property. Supported: ${allowed[name].join(', ')}.`,
|
|
177
|
-
)
|
|
178
|
-
names.add(attr.name.text)
|
|
179
|
-
if (attr.name.text === 'onClick') {
|
|
180
|
-
if (
|
|
181
|
-
!attr.initializer ||
|
|
182
|
-
!ts.isJsxExpression(attr.initializer) ||
|
|
183
|
-
!attr.initializer.expression
|
|
184
|
-
)
|
|
185
|
-
fail(attr, 'onClick needs an arrow function.')
|
|
186
|
-
action(attr.initializer.expression)
|
|
187
|
-
} else if (!attr.initializer || !ts.isStringLiteral(attr.initializer))
|
|
188
|
-
fail(attr, 'Use literal string properties; dynamic styling is not supported yet.')
|
|
189
|
-
}
|
|
190
|
-
if (name === 'MButton' && (!names.has('text') || !names.has('onClick')))
|
|
191
|
-
fail(tag, 'MButton requires text and onClick.')
|
|
192
|
-
const children = ts.isJsxElement(node)
|
|
193
|
-
? node.children.filter((c) => !ts.isJsxText(c) || c.text.trim())
|
|
194
|
-
: []
|
|
195
|
-
if (
|
|
196
|
-
name === 'MText' &&
|
|
197
|
-
(children.length !== 1 || !(ts.isJsxText(children[0]) || ts.isJsxExpression(children[0])))
|
|
198
|
-
)
|
|
199
|
-
fail(node, 'MText needs one literal text or state binding, without nested markup.')
|
|
200
|
-
if (name === 'MButton' && children.length) fail(node, 'Use the text property on MButton.')
|
|
201
|
-
children.forEach((child) => jsx(child, name))
|
|
202
|
-
}
|
|
203
|
-
const ret = fn.body.statements[1]
|
|
204
|
-
if (!ts.isReturnStatement(ret) || !ret.expression) fail(ret, 'Return the shared screen as JSX.')
|
|
205
|
-
jsx(ret.expression)
|
|
206
|
-
return state
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
const binding = (code) => ({ code, type: 'single', bindingType: 'expression' })
|
|
210
|
-
const nativeString = (text) => {
|
|
211
|
-
if (!text.isWellFormed()) throw new Error('Text must contain well-formed Unicode.')
|
|
212
|
-
return (
|
|
213
|
-
'"' +
|
|
214
|
-
Array.from(text, (char) => {
|
|
215
|
-
if (char === '\\') return '\\\\'
|
|
216
|
-
if (char === '"') return '\\"'
|
|
217
|
-
return char.codePointAt(0) < 32 ? `\\u{${char.codePointAt(0).toString(16)}}` : char
|
|
218
|
-
}).join('') +
|
|
219
|
-
'"'
|
|
220
|
-
)
|
|
221
|
-
}
|
|
222
|
-
const node = (name, properties = {}, bindings = {}, children = []) => ({
|
|
223
|
-
'@type': '@builder.io/mitosis/node',
|
|
224
|
-
name,
|
|
225
|
-
properties,
|
|
226
|
-
bindings,
|
|
227
|
-
children,
|
|
228
|
-
meta: {},
|
|
229
|
-
scope: {},
|
|
230
|
-
})
|
|
231
|
-
|
|
232
|
-
export async function compileWelcome(source, themeName = 'mavis') {
|
|
233
|
-
const state = validateSource(source)
|
|
234
|
-
const [{ parseJsx, componentToSwift, componentToVue }, core] = await Promise.all([
|
|
235
|
-
import('@builder.io/mitosis'),
|
|
236
|
-
import('@getcortexlabs/mavis-core'),
|
|
237
|
-
])
|
|
238
|
-
if (!['mavis', 'midnight'].includes(themeName)) throw new Error('Unknown starter theme.')
|
|
239
|
-
const theme = core[themeName]
|
|
240
|
-
const parsed = parseJsx(source)
|
|
241
|
-
const wrappers = []
|
|
242
|
-
// Keep string literals outside Mitosis's generic formatter: it decodes \\n.
|
|
243
|
-
// Its Swift generator still owns state, actions and the view tree.
|
|
244
|
-
const literals = []
|
|
245
|
-
const textLiteral = (value) => {
|
|
246
|
-
const key = `text${literals.length}`
|
|
247
|
-
literals.push(`static let ${key} = ${nativeString(value)}`)
|
|
248
|
-
return `MavisLiterals.${key}`
|
|
249
|
-
}
|
|
250
|
-
const nativeAction = (code) => {
|
|
251
|
-
const file = ts.createSourceFile('action.ts', code, ts.ScriptTarget.Latest, true)
|
|
252
|
-
const result = ts.transform(file, [
|
|
253
|
-
(context) => {
|
|
254
|
-
const visit = (node) =>
|
|
255
|
-
ts.isStringLiteral(node)
|
|
256
|
-
? ts.factory.createPropertyAccessExpression(
|
|
257
|
-
ts.factory.createIdentifier('MavisLiterals'),
|
|
258
|
-
textLiteral(node.text).split('.')[1],
|
|
259
|
-
)
|
|
260
|
-
: ts.visitEachChild(node, visit, context)
|
|
261
|
-
return (node) => ts.visitNode(node, visit)
|
|
262
|
-
},
|
|
263
|
-
])
|
|
264
|
-
try {
|
|
265
|
-
return ts.createPrinter().printFile(result.transformed[0]).trim()
|
|
266
|
-
} finally {
|
|
267
|
-
result.dispose()
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
const colors = Object.entries(theme.colors)
|
|
271
|
-
.map(([key, value]) => {
|
|
272
|
-
if (!/^#[0-9a-f]{6}$/i.test(value)) throw new Error(`Unsupported color token ${key}.`)
|
|
273
|
-
const hex = Number.parseInt(value.slice(1), 16)
|
|
274
|
-
return `static let ${key} = Color(red: ${((hex >> 16) & 255) / 255}, green: ${((hex >> 8) & 255) / 255}, blue: ${(hex & 255) / 255})`
|
|
275
|
-
})
|
|
276
|
-
.join('\n')
|
|
277
|
-
const token = (family, value, fallback) => {
|
|
278
|
-
const key = value ?? fallback
|
|
279
|
-
if (!Object.hasOwn(family, key))
|
|
280
|
-
throw new Error(`shared/Welcome.lite.tsx: Unsupported token ${key}.`)
|
|
281
|
-
return family[key]
|
|
282
|
-
}
|
|
283
|
-
const lower = (input) => {
|
|
284
|
-
const p = input.properties
|
|
285
|
-
let output,
|
|
286
|
-
modifiers = []
|
|
287
|
-
if (input.name === 'MColumn' || input.name === 'MRow') {
|
|
288
|
-
output = node(
|
|
289
|
-
input.name === 'MColumn' ? 'div' : 'HStack',
|
|
290
|
-
{
|
|
291
|
-
spacing: String(token(theme.space, p.gap, 'none')),
|
|
292
|
-
alignment: input.name === 'MColumn' ? 'leading' : 'center',
|
|
293
|
-
},
|
|
294
|
-
{},
|
|
295
|
-
input.children.map(lower),
|
|
296
|
-
)
|
|
297
|
-
if (Object.hasOwn(p, 'padding')) modifiers.push(`.padding(${token(theme.space, p.padding)})`)
|
|
298
|
-
} else if (input.name === 'MText') {
|
|
299
|
-
const child = input.children[0]
|
|
300
|
-
const ref = child.bindings._text?.code
|
|
301
|
-
const content = ref
|
|
302
|
-
? state.get(ref.slice(6)).kind === 'string'
|
|
303
|
-
? ref
|
|
304
|
-
: `String(${ref})`
|
|
305
|
-
: textLiteral(child.properties._text.replace(/\s*\n\s*/g, ' ').trim())
|
|
306
|
-
output = node('p', {}, { innerHTML: binding(content) })
|
|
307
|
-
const typo = token(theme.typography, p.variant, 'body')
|
|
308
|
-
const weights = {
|
|
309
|
-
normal: 'regular',
|
|
310
|
-
bold: 'bold',
|
|
311
|
-
100: 'ultraLight',
|
|
312
|
-
200: 'thin',
|
|
313
|
-
300: 'light',
|
|
314
|
-
400: 'regular',
|
|
315
|
-
500: 'medium',
|
|
316
|
-
600: 'semibold',
|
|
317
|
-
700: 'bold',
|
|
318
|
-
800: 'heavy',
|
|
319
|
-
900: 'black',
|
|
320
|
-
}
|
|
321
|
-
token(theme.colors, p.tone, 'text')
|
|
322
|
-
modifiers.push(
|
|
323
|
-
`.font(.system(size: ${typo.fontSize}, weight: .${weights[typo.fontWeight]}))`,
|
|
324
|
-
`.foregroundStyle(MavisTokens.${p.tone ?? 'text'})`,
|
|
325
|
-
'.fixedSize(horizontal: false, vertical: true)',
|
|
326
|
-
)
|
|
327
|
-
if (['title', 'heading', 'display'].includes(p.variant))
|
|
328
|
-
modifiers.push('.accessibilityAddTraits(.isHeader)')
|
|
329
|
-
} else {
|
|
330
|
-
if (!['primary', 'secondary'].includes(p.variant ?? 'primary'))
|
|
331
|
-
throw new Error(
|
|
332
|
-
'shared/Welcome.lite.tsx: MButton supports primary and secondary variants in this experiment.',
|
|
333
|
-
)
|
|
334
|
-
output = node(
|
|
335
|
-
'button',
|
|
336
|
-
{},
|
|
337
|
-
{ onClick: { ...input.bindings.onClick, code: nativeAction(input.bindings.onClick.code) } },
|
|
338
|
-
[node('p', {}, { innerHTML: binding(textLiteral(p.text)) })],
|
|
339
|
-
)
|
|
340
|
-
modifiers.push(
|
|
341
|
-
`.buttonStyle(MavisStarterButtonStyle(secondary: ${p.variant === 'secondary'}))`,
|
|
342
|
-
)
|
|
343
|
-
}
|
|
344
|
-
const name = `MavisStyle${wrappers.length}`
|
|
345
|
-
wrappers.push(`private struct ${name}<Content: View>: View {
|
|
346
|
-
let content: Content
|
|
347
|
-
init(@ViewBuilder content: () -> Content) { self.content = content() }
|
|
348
|
-
var body: some View { content\n${modifiers.join('\n')} }
|
|
349
|
-
}`)
|
|
350
|
-
return node(name, {}, {}, [output])
|
|
351
|
-
}
|
|
352
|
-
const plugin = () => ({
|
|
353
|
-
json: {
|
|
354
|
-
pre(json) {
|
|
355
|
-
for (const [key, value] of state) {
|
|
356
|
-
json.state[key].typeParameter = { number: 'Int', string: 'String', boolean: 'Bool' }[
|
|
357
|
-
value.kind
|
|
358
|
-
]
|
|
359
|
-
json.state[key].code =
|
|
360
|
-
value.kind === 'string' ? textLiteral(value.value) : String(value.value)
|
|
361
|
-
}
|
|
362
|
-
json.children = json.children.map(lower)
|
|
363
|
-
return json
|
|
364
|
-
},
|
|
365
|
-
},
|
|
366
|
-
code: {
|
|
367
|
-
post(code, _json) {
|
|
368
|
-
return `${code}\nprivate enum MavisLiterals {\n${literals.join('\n')}\n}\n${wrappers.join('\n')}`
|
|
369
|
-
},
|
|
370
|
-
},
|
|
371
|
-
})
|
|
372
|
-
const swift = componentToSwift({ includePreview: false, plugins: [plugin] })({
|
|
373
|
-
component: parsed,
|
|
374
|
-
})
|
|
375
|
-
const vue = componentToVue({ api: 'composition' })({ component: parsed })
|
|
376
|
-
return {
|
|
377
|
-
swift,
|
|
378
|
-
vue,
|
|
379
|
-
tokens: `enum MavisTokens {\n${colors}\n}
|
|
380
|
-
private struct MavisStarterButtonStyle: ButtonStyle {
|
|
381
|
-
let secondary: Bool
|
|
382
|
-
@Environment(\\.accessibilityReduceMotion) private var reduceMotion
|
|
383
|
-
func makeBody(configuration: Configuration) -> some View {
|
|
384
|
-
configuration.label
|
|
385
|
-
.font(.system(size: 15, weight: .semibold))
|
|
386
|
-
.padding(.horizontal, 20).padding(.vertical, 12)
|
|
387
|
-
.foregroundStyle(secondary ? MavisTokens.text : MavisTokens.onPrimary)
|
|
388
|
-
.background(secondary ? MavisTokens.elevated : MavisTokens.primary, in: RoundedRectangle(cornerRadius: 12))
|
|
389
|
-
.opacity(configuration.isPressed ? 0.8 : 1)
|
|
390
|
-
.scaleEffect(configuration.isPressed && !reduceMotion ? 0.98 : 1)
|
|
391
|
-
.animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: configuration.isPressed)
|
|
392
|
-
}
|
|
393
|
-
}`,
|
|
394
|
-
}
|
|
395
|
-
}
|