@a16n/web-sim 0.1.0 → 0.1.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.
- package/overrides/react-native-web/overrides.ts +8 -4
- package/overrides/react-native-web/useElementLayout.ts +12 -0
- package/package.json +5 -3
- package/src/client/app/appDocument.ts +20 -4
- package/src/client/app/fonts.ts +17 -0
- package/src/client/app/main.tsx +3 -3
- package/src/client/virtual.d.ts +2 -0
- package/src/node/appInfo.ts +2 -0
- package/src/node/appSource.ts +2 -0
- package/src/node/config.ts +1 -1
- package/src/node/fonts.ts +377 -0
- package/src/node/overrides/plugin.ts +10 -7
- package/src/node/server.ts +11 -10
- package/src/node/worklets.ts +86 -0
- package/src/runtime/index.ts +6 -0
|
@@ -23,7 +23,7 @@ function clampOpacity(prop: string, value: string): string {
|
|
|
23
23
|
export default defineOverrides('react-native-web', [
|
|
24
24
|
{
|
|
25
25
|
versions: '>=0.19 <0.22',
|
|
26
|
-
note: 'system font, press timing, paged scroll view children, Appearance.setColorScheme, TextInput keyboardAppearance, scrolling cancels a press, opacity, layout events when a view moves or mounts at zero size, and their target, iOS overscroll and pull to refresh (src/client/app/touch.ts)',
|
|
26
|
+
note: 'system font, flex: 0, press timing, paged scroll view children, Appearance.setColorScheme, TextInput keyboardAppearance, scrolling cancels a press, opacity, layout events when a view moves or mounts at zero size, and their target, iOS overscroll and pull to refresh (src/client/app/touch.ts)',
|
|
27
27
|
files: {
|
|
28
28
|
'dist/exports/RefreshControl/index.js': './RefreshControl.tsx',
|
|
29
29
|
'dist/modules/useElementLayout/index.js': './useElementLayout.ts',
|
|
@@ -36,7 +36,10 @@ export default defineOverrides('react-native-web', [
|
|
|
36
36
|
.replace("var SYSTEM_FONT_STACK = '", "var SYSTEM_FONT_STACK = 'var(--web-sim-system-font),")
|
|
37
37
|
.replace(/\} else if \(prop === 'fontFamily'\) \{[\s\S]*?\} else if \(prop === 'textDecorationLine'\) \{/, FONT_FAMILY)
|
|
38
38
|
.replace('var value = style[prop];', `var value = style[prop];\n${clampOpacity('prop', 'value')}`)
|
|
39
|
-
.replace('(style[prop], prop)', '(value, prop)')
|
|
39
|
+
.replace('(style[prop], prop)', '(value, prop)')
|
|
40
|
+
// `flex: 0` is Yoga's: inflexible, sized by its own size or content (`0 0 auto`). CSS's `flex: 0` is
|
|
41
|
+
// `0 1 0%`, which collapses a view with no height to nothing.
|
|
42
|
+
.replace(/if \(value === -1\) \{/, 'if (value === 0) {\n resolvedStyle.flexGrow = 0;\n resolvedStyle.flexShrink = 0;\n resolvedStyle.flexBasis = \'auto\';\n } else if (value === -1) {'),
|
|
40
43
|
},
|
|
41
44
|
// React Native styles gradients with `experimental_backgroundImage`, which is not a CSS property.
|
|
42
45
|
{
|
|
@@ -90,13 +93,14 @@ export default defineOverrides('react-native-web', [
|
|
|
90
93
|
// With `pagingEnabled` react-native-web wraps each child in a view for `scroll-snap-align`, which React
|
|
91
94
|
// Native doesn't. The wrapper is a column, so in a horizontal list the child no longer stretches to the list's
|
|
92
95
|
// height and a page sized `height: '100%'` (a carousel's) comes out 0 tall. Laid out along the scroll
|
|
93
|
-
// direction, the wrapper passes the stretch through.
|
|
96
|
+
// direction, the wrapper passes the stretch through. It is marked `data-web-sim-page`, so a page's onLayout
|
|
97
|
+
// measures from the list's content, as React Native's does, not from the wrapper (useElementLayout.ts).
|
|
94
98
|
{
|
|
95
99
|
file: /^dist\/(cjs\/)?exports\/ScrollView\/index\.js$/,
|
|
96
100
|
replace: (source) =>
|
|
97
101
|
source.replace(
|
|
98
102
|
'pagingEnabled && styles.pagingEnabledChild]',
|
|
99
|
-
"pagingEnabled && styles.pagingEnabledChild, pagingEnabled && horizontal && { flexDirection: 'row' }]",
|
|
103
|
+
"pagingEnabled && styles.pagingEnabledChild, pagingEnabled && horizontal && { flexDirection: 'row' }],\n dataSet: pagingEnabled && !isSticky ? { webSimPage: 'true' } : undefined",
|
|
100
104
|
),
|
|
101
105
|
},
|
|
102
106
|
// A text input's `keyboardAppearance` goes on its element, for the keyboard plugin to draw the keyboard light
|
|
@@ -30,6 +30,18 @@ let scheduled = false
|
|
|
30
30
|
* measure walks every ancestor, and counts the parent's scroll, so a list's content would seem to move as it scrolls.
|
|
31
31
|
*/
|
|
32
32
|
function frameOf(node: HTMLElement): Frame {
|
|
33
|
+
const frame = frameInParent(node)
|
|
34
|
+
const parent = node.parentElement
|
|
35
|
+
// A paged list's page sits in a wrapper React Native doesn't have (the ScrollView patch in overrides.ts): its
|
|
36
|
+
// frame is the page's in the list's content.
|
|
37
|
+
if (parent !== null && parent.dataset.webSimPage !== undefined) {
|
|
38
|
+
const page = frameInParent(parent)
|
|
39
|
+
return { ...frame, x: frame.x + page.x, y: frame.y + page.y }
|
|
40
|
+
}
|
|
41
|
+
return frame
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function frameInParent(node: HTMLElement): Frame {
|
|
33
45
|
const parent = node.parentElement
|
|
34
46
|
const width = node.offsetWidth
|
|
35
47
|
const height = node.offsetHeight
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@a16n/web-sim",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "A React Native device simulator that runs in a Chrome tab",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -34,12 +34,13 @@
|
|
|
34
34
|
"typecheck": "tsc --noEmit -p ."
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
+
"@babel/core": "^7.29.16",
|
|
37
38
|
"@phosphor-icons/react": "^2.1.10",
|
|
38
39
|
"@vitejs/plugin-react": "^5.1.0",
|
|
40
|
+
"esbuild": "^0.25.0",
|
|
39
41
|
"playwright-core": "^1.65.1",
|
|
40
42
|
"semver": "^7.7.3",
|
|
41
|
-
"vite": "^7.2.0"
|
|
42
|
-
"esbuild": "^0.25.0"
|
|
43
|
+
"vite": "^7.2.0"
|
|
43
44
|
},
|
|
44
45
|
"peerDependencies": {
|
|
45
46
|
"expo": ">=58 <59",
|
|
@@ -50,6 +51,7 @@
|
|
|
50
51
|
"react-native-web": ">=0.19 <0.22"
|
|
51
52
|
},
|
|
52
53
|
"devDependencies": {
|
|
54
|
+
"@types/babel__core": "^7.20.5",
|
|
53
55
|
"@types/node": "^24.10.0",
|
|
54
56
|
"@types/react": "~19.3.0",
|
|
55
57
|
"@types/react-dom": "~19.2.0",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { getState, subscribe } from '../../runtime/index.ts'
|
|
1
|
+
import { app, getState, subscribe } from '../../runtime/index.ts'
|
|
2
2
|
import rnwHash from 'react-native-web/dist/exports/StyleSheet/compiler/hash'
|
|
3
|
-
import { ANDROID_FONTS, installFonts } from './fonts.ts'
|
|
3
|
+
import { ANDROID_FONTS, installBundledFonts, installFonts } from './fonts.ts'
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* The app's document is the device's screen: the frame is exactly the screen's size, so the window, the visual
|
|
@@ -29,7 +29,7 @@ const rnwClass = (property: string, value: string) => `r-${property}-${rnwHash(p
|
|
|
29
29
|
* isn't a flex item, and with `left` and `right` set it spans the row, as it does in Yoga. Its position may be a class
|
|
30
30
|
* or, from an animated style (Reanimated's), inline.
|
|
31
31
|
*/
|
|
32
|
-
const rows = [rnwClass('flexDirection', 'row'), rnwClass('flexDirection', 'row-reverse')].map((name) => `.${name}`).join(', ')
|
|
32
|
+
const rows = [rnwClass('flexDirection', 'row'), rnwClass('flexDirection', 'row-reverse')].map((name) => `.${name}`).concat('[style*="flex-direction: row"]').join(', ')
|
|
33
33
|
const absolute = `.${rnwClass('position', 'absolute')}, [style*="position: absolute"]`
|
|
34
34
|
|
|
35
35
|
/**
|
|
@@ -39,9 +39,22 @@ const absolute = `.${rnwClass('position', 'absolute')}, [style*="position: absol
|
|
|
39
39
|
* it resolves its 0% basis to its content), and with React Native's `flexShrink: 0` it stays that tall: the
|
|
40
40
|
* ScrollView grows to fit its content and never scrolls. `max-height: 100%` is Yoga's bound. Views with a height or
|
|
41
41
|
* minimum height of their own, and absolutely positioned ones, keep theirs.
|
|
42
|
+
*
|
|
43
|
+
* react-native-web turns a `StyleSheet.create` style into classes and a style object written in place into an inline
|
|
44
|
+
* style, so rows and growing views are matched both ways.
|
|
42
45
|
*/
|
|
43
46
|
const notColumns = [...rows.split(', '), `.${rnwClass('overflowY', 'auto')}`, `.${rnwClass('overflowY', 'scroll')}`].map((name) => `:not(${name})`).join('')
|
|
44
|
-
const growing =
|
|
47
|
+
const growing = `:is([class*="r-flexGrow-"], [style*="flex-grow:"]:not([style*="flex-grow: 0;"])):not(${absolute}):not([class*="r-height-"]):not([class*="r-minHeight-"]):not([style*="height"])`
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A view with an `aspectRatio` and one of its width or height takes the other from the ratio, as Yoga sizes it. In CSS
|
|
51
|
+
* a stretched cross size wins over the ratio, so `{ height: 100, aspectRatio: 2 }` in a column would span the column
|
|
52
|
+
* instead of being 200 wide. `min-content` is the size through the ratio, and isn't stretched.
|
|
53
|
+
*/
|
|
54
|
+
const ratio = `:is([class*="r-aspectRatio-"], [style*="aspect-ratio"])`
|
|
55
|
+
const own = (property: string) => `:is([class*="r-${property}-"], [style^="${property}:"], [style*=" ${property}:"])`
|
|
56
|
+
const ratioWidth = `${ratio}${own('height')}:not(${own('width')})`
|
|
57
|
+
const ratioHeight = `${ratio}${own('width')}:not(${own('height')})`
|
|
45
58
|
|
|
46
59
|
const style = document.createElement('style')
|
|
47
60
|
style.textContent = `
|
|
@@ -61,9 +74,12 @@ input, textarea, [contenteditable='true'], [contenteditable=''] { user-select: t
|
|
|
61
74
|
input, textarea, button, select { font-family: inherit; }
|
|
62
75
|
:where(${rows}) > :where(:not(${absolute})) { width: fit-content; }
|
|
63
76
|
:where(${notColumns}) > :where(${growing}) { max-height: 100%; }
|
|
77
|
+
:where(${ratioWidth}) { width: min-content; }
|
|
78
|
+
:where(${ratioHeight}) { height: min-content; }
|
|
64
79
|
`
|
|
65
80
|
document.head.append(style)
|
|
66
81
|
installFonts(device.platform)
|
|
82
|
+
installBundledFonts(app().fonts?.[device.platform] ?? [])
|
|
67
83
|
document.documentElement.dataset.webSimPlatform = device.platform
|
|
68
84
|
|
|
69
85
|
/**
|
package/src/client/app/fonts.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Platform } from '../../devices/types.ts'
|
|
2
|
+
import type { BundledFont } from '../../runtime/index.ts'
|
|
2
3
|
|
|
3
4
|
declare global {
|
|
4
5
|
interface Window {
|
|
@@ -57,3 +58,19 @@ export function installFonts(platform: Platform): void {
|
|
|
57
58
|
function quote(family: string): string {
|
|
58
59
|
return /^[\w-]+$/.test(family) ? family : `"${family}"`
|
|
59
60
|
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The fonts the app's native build embeds, as `@font-face` rules under the names the platform gives them. A face
|
|
64
|
+
* declared here wins over a font of the same name installed on the computer, so the app draws the same everywhere.
|
|
65
|
+
*/
|
|
66
|
+
export function installBundledFonts(faces: BundledFont[]): void {
|
|
67
|
+
if (faces.length === 0) {
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
const style = document.createElement('style')
|
|
71
|
+
style.dataset.webSimFonts = ''
|
|
72
|
+
style.textContent = faces
|
|
73
|
+
.map((face) => `@font-face { font-family: ${JSON.stringify(face.family)}; src: url(${JSON.stringify(face.url)}); font-weight: ${face.weight}; font-style: ${face.style}; font-display: block; }`)
|
|
74
|
+
.join('\n')
|
|
75
|
+
document.head.append(style)
|
|
76
|
+
}
|
package/src/client/app/main.tsx
CHANGED
|
@@ -22,9 +22,9 @@ function reportFirstRender() {
|
|
|
22
22
|
async function start() {
|
|
23
23
|
// Loaded here, not imported above: it imports every route, so a route (or anything it imports) that throws as it
|
|
24
24
|
// loads lands in `start`'s catch and shows on the screen, rather than leaving it blank.
|
|
25
|
-
const { loadEntry, mode, routes, routesDir } = await import('virtual:web-sim/app-config')
|
|
26
|
-
if (mode === 'router' && routes !== null && routesDir !== null) {
|
|
27
|
-
const { ExpoRoot } = await
|
|
25
|
+
const { loadEntry, loadRouter, mode, routes, routesDir } = await import('virtual:web-sim/app-config')
|
|
26
|
+
if (mode === 'router' && routes !== null && routesDir !== null && loadRouter !== null) {
|
|
27
|
+
const { ExpoRoot } = await loadRouter()
|
|
28
28
|
const context = routeContext(routes, routesDir, getState().device.platform)
|
|
29
29
|
createRoot(rootElement).render(
|
|
30
30
|
<CrashReport>
|
package/src/client/virtual.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ declare module 'virtual:web-sim/app-config' {
|
|
|
6
6
|
export const routesDir: string | null
|
|
7
7
|
export const routes: Record<string, unknown> | null
|
|
8
8
|
export const loadEntry: (() => Promise<{ default?: unknown }>) | null
|
|
9
|
+
/** expo-router, imported only by an app that uses it: an app without it has nothing to resolve. */
|
|
10
|
+
export const loadRouter: (() => Promise<typeof import('expo-router')>) | null
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
declare module 'virtual:web-sim/sim-config' {
|
package/src/node/appInfo.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from 'node:fs'
|
|
2
2
|
import { createRequire } from 'node:module'
|
|
3
3
|
import path from 'node:path'
|
|
4
|
+
import { readBundledFonts } from './fonts.ts'
|
|
4
5
|
import type { AppInfo, FirebaseOptions, UserInterfaceStyle } from '../runtime/index.ts'
|
|
5
6
|
|
|
6
7
|
/** Config plugin options that set iOS usage descriptions, by plugin. */
|
|
@@ -91,6 +92,7 @@ export function readAppInfo(root: string, fallbackName: string): AppInfo {
|
|
|
91
92
|
googleServices: readGoogleServices(root, expo),
|
|
92
93
|
dependencies: readDependencies(root),
|
|
93
94
|
userInterfaceStyle: readUserInterfaceStyle(root, expo),
|
|
95
|
+
fonts: readBundledFonts(root, expo),
|
|
94
96
|
}
|
|
95
97
|
}
|
|
96
98
|
|
package/src/node/appSource.ts
CHANGED
|
@@ -123,6 +123,7 @@ export function appPage(project: Project, deviceIds: { devices: unknown[]; defau
|
|
|
123
123
|
'!**/+middleware.*',
|
|
124
124
|
])}, { eager: true });`,
|
|
125
125
|
`export const loadEntry = null;`,
|
|
126
|
+
`export const loadRouter = () => import('expo-router');`,
|
|
126
127
|
)
|
|
127
128
|
} else {
|
|
128
129
|
lines.push(
|
|
@@ -130,6 +131,7 @@ export function appPage(project: Project, deviceIds: { devices: unknown[]; defau
|
|
|
130
131
|
`export const routesDir = null;`,
|
|
131
132
|
`export const routes = null;`,
|
|
132
133
|
`export const loadEntry = () => import(${JSON.stringify(project.entry)});`,
|
|
134
|
+
`export const loadRouter = null;`,
|
|
133
135
|
)
|
|
134
136
|
}
|
|
135
137
|
return lines.join('\n')
|
package/src/node/config.ts
CHANGED
|
@@ -40,7 +40,7 @@ export type WebSimConfig = {
|
|
|
40
40
|
* before `.web.tsx`. Default true. Set false for apps whose web files are the ones to simulate.
|
|
41
41
|
*/
|
|
42
42
|
resolveNativeFiles?: boolean
|
|
43
|
-
/** Babel plugins for app code
|
|
43
|
+
/** Babel plugins for app code. web-sim adds the Worklets plugin when installed, for app and dependencies alike. */
|
|
44
44
|
babelPlugins?: unknown[]
|
|
45
45
|
port?: number
|
|
46
46
|
/**
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { inflateSync } from 'node:zlib'
|
|
5
|
+
import type { BundledFont, BundledFonts } from '../runtime/index.ts'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The fonts a native build of the app embeds, as `@font-face` rules for the simulated platform, so the app's custom
|
|
9
|
+
* fonts draw whether or not they are installed on the computer. Fonts the app loads at runtime (`useFonts`,
|
|
10
|
+
* `Font.loadAsync`) need nothing here: expo-font's web build registers those itself.
|
|
11
|
+
*
|
|
12
|
+
* Each platform names an embedded font its own way, and a family resolves here as it does on that platform:
|
|
13
|
+
*
|
|
14
|
+
* - iOS reads the names inside the file. `fontFamily` is a family name (with `fontWeight` and `fontStyle` picking the
|
|
15
|
+
* face), or one face's PostScript or full name. The files come from expo-font's config plugin (`fonts`,
|
|
16
|
+
* `ios.fonts`) and from `UIAppFonts` in the native project's `Info.plist`, which any other plugin writes to.
|
|
17
|
+
* - Android names a font by its file: `assets/fonts/Inter.ttf` is `Inter`, and `Inter_bold.ttf`, `Inter_italic.ttf`
|
|
18
|
+
* and `Inter_bold_italic.ttf` are its other styles. A family registered with `ReactFontManager.addCustomFont` (in
|
|
19
|
+
* `MainApplication`, as expo-font's object syntax does) takes its name from that call and its faces from the
|
|
20
|
+
* `res/font` XML it points at.
|
|
21
|
+
*
|
|
22
|
+
* An app without a native project for a platform (continuous native generation) may embed fonts through a config
|
|
23
|
+
* plugin web-sim can't run. When expo-font's plugin lists none for that platform either, the font files in the
|
|
24
|
+
* project (outside `node_modules`, build output and hidden folders) count as embedded.
|
|
25
|
+
*/
|
|
26
|
+
export function readBundledFonts(root: string, expo: Record<string, any>): BundledFonts {
|
|
27
|
+
const files = new FontFileIndex(root)
|
|
28
|
+
const plugin = expoFontOptions(expo)
|
|
29
|
+
const resolve = (entry: string) => resolveFontPaths(entry, root)
|
|
30
|
+
|
|
31
|
+
const ios = new FaceList(root)
|
|
32
|
+
const iosFiles = new Set<string>()
|
|
33
|
+
for (const entry of [...(plugin.fonts ?? []), ...(plugin.ios?.fonts ?? [])]) {
|
|
34
|
+
if (typeof entry === 'string') {
|
|
35
|
+
resolve(entry).forEach((file) => iosFiles.add(file))
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const iosProject = path.join(root, 'ios')
|
|
39
|
+
const appFonts = [...asStrings(expo.ios?.infoPlist?.UIAppFonts), ...(existsSync(iosProject) ? infoPlistFonts(iosProject) : [])]
|
|
40
|
+
for (const name of appFonts) {
|
|
41
|
+
const file = files.find(name, iosProject)
|
|
42
|
+
if (file !== undefined) {
|
|
43
|
+
iosFiles.add(file)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!existsSync(iosProject) && iosFiles.size === 0) {
|
|
47
|
+
files.outsideNativeProjects().forEach((file) => iosFiles.add(file))
|
|
48
|
+
}
|
|
49
|
+
for (const file of iosFiles) {
|
|
50
|
+
ios.addIos(file)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const android = new FaceList(root)
|
|
54
|
+
const androidProject = path.join(root, 'android')
|
|
55
|
+
for (const entry of [...(plugin.fonts ?? []), ...(plugin.android?.fonts ?? [])]) {
|
|
56
|
+
if (typeof entry === 'string') {
|
|
57
|
+
resolve(entry).forEach((file) => android.addAndroidAsset(file))
|
|
58
|
+
} else if (entry !== null && typeof entry === 'object' && typeof (entry as FontObject).fontFamily === 'string') {
|
|
59
|
+
const font = entry as FontObject & { fontFamily: string }
|
|
60
|
+
for (const definition of Array.isArray(font.fontDefinitions) ? font.fontDefinitions : []) {
|
|
61
|
+
const file = definition?.path ?? font.path
|
|
62
|
+
if (typeof file === 'string') {
|
|
63
|
+
resolve(file).forEach((resolved) => android.add(font.fontFamily, resolved, String(definition.weight ?? 400), definition.style === 'italic' ? 'italic' : 'normal'))
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (existsSync(androidProject)) {
|
|
69
|
+
const main = path.join(androidProject, 'app', 'src', 'main')
|
|
70
|
+
for (const file of listFonts(path.join(main, 'assets', 'fonts'))) {
|
|
71
|
+
android.addAndroidAsset(file)
|
|
72
|
+
}
|
|
73
|
+
for (const [family, resource] of customFonts(main)) {
|
|
74
|
+
for (const face of resourceFontFaces(path.join(main, 'res', 'font'), resource)) {
|
|
75
|
+
android.add(family, face.file, face.weight, face.style)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
} else if (android.faces.length === 0) {
|
|
79
|
+
files.outsideNativeProjects().forEach((file) => android.addAndroidAsset(file))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { ios: ios.faces, android: android.faces }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
type FontObject = { fontFamily?: string; path?: string; fontDefinitions?: { path?: string; weight?: number; style?: string }[] }
|
|
86
|
+
type ExpoFontOptions = { fonts?: unknown[]; ios?: { fonts?: unknown[] }; android?: { fonts?: unknown[] } }
|
|
87
|
+
|
|
88
|
+
function expoFontOptions(expo: Record<string, any>): ExpoFontOptions {
|
|
89
|
+
const plugins: unknown[] = Array.isArray(expo.plugins) ? expo.plugins : []
|
|
90
|
+
const entry = plugins.find((plugin) => Array.isArray(plugin) && plugin[0] === 'expo-font')
|
|
91
|
+
return Array.isArray(entry) && entry[1] !== null && typeof entry[1] === 'object' ? (entry[1] as ExpoFontOptions) : {}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const asStrings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])
|
|
95
|
+
|
|
96
|
+
const FONT_EXTENSIONS = ['.ttf', '.otf', '.woff', '.woff2']
|
|
97
|
+
const isFont = (file: string) => FONT_EXTENSIONS.includes(path.extname(file).toLowerCase())
|
|
98
|
+
|
|
99
|
+
function listFonts(dir: string): string[] {
|
|
100
|
+
return existsSync(dir) ? readdirSync(dir).filter(isFont).map((name) => path.join(dir, name)) : []
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A path as expo-font's plugin resolves it: relative to the project, else as a package path; a folder is its fonts. */
|
|
104
|
+
function resolveFontPaths(entry: string, root: string): string[] {
|
|
105
|
+
let file = path.resolve(root, entry)
|
|
106
|
+
if (!existsSync(file)) {
|
|
107
|
+
try {
|
|
108
|
+
file = createRequire(path.join(root, 'package.json')).resolve(entry)
|
|
109
|
+
} catch {
|
|
110
|
+
console.warn(`web-sim: expo-font's config plugin lists ${entry}, which doesn't exist`)
|
|
111
|
+
return []
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return statSync(file).isDirectory() ? listFonts(file) : isFont(file) ? [file] : []
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The font files `UIAppFonts` lists, from each `Info.plist` in the iOS project. */
|
|
118
|
+
function infoPlistFonts(iosProject: string): string[] {
|
|
119
|
+
const names: string[] = []
|
|
120
|
+
for (const entry of readdirSync(iosProject, { withFileTypes: true })) {
|
|
121
|
+
const plist = path.join(iosProject, entry.name, 'Info.plist')
|
|
122
|
+
if (!entry.isDirectory() || entry.name === 'Pods' || !existsSync(plist)) {
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
const array = /<key>UIAppFonts<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(readFileSync(plist, 'utf8'))
|
|
126
|
+
for (const [, name] of array?.[1].matchAll(/<string>([^<]+)<\/string>/g) ?? []) {
|
|
127
|
+
names.push(name.trim())
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return names
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The families `MainApplication` registers with `ReactFontManager.addCustomFont`, and the font resource of each. */
|
|
134
|
+
function customFonts(main: string): [string, string][] {
|
|
135
|
+
const found: [string, string][] = []
|
|
136
|
+
const visit = (dir: string) => {
|
|
137
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
138
|
+
const file = path.join(dir, entry.name)
|
|
139
|
+
if (entry.isDirectory()) {
|
|
140
|
+
visit(file)
|
|
141
|
+
} else if (/^MainApplication\.(kt|java)$/.test(entry.name)) {
|
|
142
|
+
for (const [, family, resource] of readFileSync(file, 'utf8').matchAll(/addCustomFont\(\s*[\w.]+\s*,\s*"([^"]+)"\s*,\s*R\.font\.(\w+)\s*\)/g)) {
|
|
143
|
+
found.push([family, resource])
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const sources = [path.join(main, 'java'), path.join(main, 'kotlin')].filter(existsSync)
|
|
149
|
+
sources.forEach(visit)
|
|
150
|
+
return found
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A `res/font` resource's faces: the `<font>`s of its XML font family, or the one font file of that name. */
|
|
154
|
+
function resourceFontFaces(resDir: string, resource: string): { file: string; weight: string; style: 'normal' | 'italic' }[] {
|
|
155
|
+
const xml = path.join(resDir, `${resource}.xml`)
|
|
156
|
+
if (!existsSync(xml)) {
|
|
157
|
+
const file = listFonts(resDir).find((candidate) => path.parse(candidate).name === resource)
|
|
158
|
+
return file === undefined ? [] : [{ file, weight: '400', style: 'normal' }]
|
|
159
|
+
}
|
|
160
|
+
const faces: { file: string; weight: string; style: 'normal' | 'italic' }[] = []
|
|
161
|
+
for (const [tag] of readFileSync(xml, 'utf8').matchAll(/<font\b[^>]*>/g)) {
|
|
162
|
+
const attribute = (name: string) => new RegExp(`(?:app|android):${name}="([^"]*)"`).exec(tag)?.[1]
|
|
163
|
+
const name = attribute('font')?.replace(/^@font\//, '')
|
|
164
|
+
const file = listFonts(resDir).find((candidate) => path.parse(candidate).name === name)
|
|
165
|
+
if (file !== undefined) {
|
|
166
|
+
faces.push({ file, weight: attribute('fontWeight') ?? '400', style: attribute('fontStyle') === 'italic' ? 'italic' : 'normal' })
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return faces
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const SKIPPED_DIRS = new Set(['node_modules', 'Pods', 'build', 'dist', 'DerivedData'])
|
|
173
|
+
|
|
174
|
+
/** The font files in the project, outside `node_modules`, build output and hidden folders. */
|
|
175
|
+
class FontFileIndex {
|
|
176
|
+
private files: string[] | null = null
|
|
177
|
+
private readonly root: string
|
|
178
|
+
|
|
179
|
+
constructor(root: string) {
|
|
180
|
+
this.root = root
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private all(): string[] {
|
|
184
|
+
if (this.files === null) {
|
|
185
|
+
this.files = []
|
|
186
|
+
const visit = (dir: string, depth: number) => {
|
|
187
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
188
|
+
if (entry.name.startsWith('.') || SKIPPED_DIRS.has(entry.name)) {
|
|
189
|
+
continue
|
|
190
|
+
}
|
|
191
|
+
const file = path.join(dir, entry.name)
|
|
192
|
+
if (entry.isDirectory() && depth < 8) {
|
|
193
|
+
visit(file, depth + 1)
|
|
194
|
+
} else if (entry.isFile() && isFont(entry.name)) {
|
|
195
|
+
this.files!.push(file)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
visit(this.root, 0)
|
|
200
|
+
}
|
|
201
|
+
return this.files
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** A file by its name, as Xcode bundles it: one in the iOS project first, then one outside the Android project. */
|
|
205
|
+
find(name: string, iosProject: string): string | undefined {
|
|
206
|
+
const matches = this.all().filter((file) => path.basename(file) === name)
|
|
207
|
+
const android = path.join(this.root, 'android') + path.sep
|
|
208
|
+
return matches.find((file) => file.startsWith(iosProject + path.sep)) ?? matches.find((file) => !file.startsWith(android)) ?? matches[0]
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
outsideNativeProjects(): string[] {
|
|
212
|
+
const native = ['ios', 'android'].map((dir) => path.join(this.root, dir) + path.sep)
|
|
213
|
+
return this.all().filter((file) => !native.some((dir) => file.startsWith(dir)))
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Android's suffixes for an asset font's other styles: `Inter_bold.ttf` is `Inter` in bold. */
|
|
218
|
+
const ASSET_STYLES: [string, string, 'normal' | 'italic'][] = [
|
|
219
|
+
['_bold_italic', '700', 'italic'],
|
|
220
|
+
['_bold', '700', 'normal'],
|
|
221
|
+
['_italic', '400', 'italic'],
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
class FaceList {
|
|
225
|
+
readonly faces: BundledFont[] = []
|
|
226
|
+
private readonly root: string
|
|
227
|
+
|
|
228
|
+
constructor(root: string) {
|
|
229
|
+
this.root = root
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
add(family: string, file: string, weight: string, style: 'normal' | 'italic'): void {
|
|
233
|
+
const url = this.url(file)
|
|
234
|
+
if (!this.faces.some((face) => face.family === family && face.weight === weight && face.style === style)) {
|
|
235
|
+
this.faces.push({ family, url, weight, style })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* An iOS font by the names in it. Its family (the typographic family, and the legacy one where they differ) picks
|
|
241
|
+
* a face by weight and style. Its PostScript and full names are that one face, whatever the weight asked for.
|
|
242
|
+
*/
|
|
243
|
+
addIos(file: string): void {
|
|
244
|
+
const font = readFontNames(file)
|
|
245
|
+
if (font === null) {
|
|
246
|
+
console.warn(`web-sim: could not read the names in ${path.relative(this.root, file)}, so it isn't loaded`)
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
const families = new Set([font.typographicFamily, font.family].filter((name): name is string => name !== undefined))
|
|
250
|
+
for (const family of families) {
|
|
251
|
+
this.add(family, file, String(font.weight), font.italic ? 'italic' : 'normal')
|
|
252
|
+
}
|
|
253
|
+
for (const name of [font.postScriptName, font.fullName]) {
|
|
254
|
+
if (name !== undefined && !families.has(name)) {
|
|
255
|
+
this.add(name, file, '1 1000', font.italic ? 'italic' : 'normal')
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** An Android asset font, named by its file. */
|
|
261
|
+
addAndroidAsset(file: string): void {
|
|
262
|
+
if (!['.ttf', '.otf'].includes(path.extname(file).toLowerCase())) {
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
const name = path.parse(file).name
|
|
266
|
+
this.add(name, file, '400', 'normal')
|
|
267
|
+
const styled = ASSET_STYLES.find(([suffix]) => name.endsWith(suffix) && name.length > suffix.length)
|
|
268
|
+
if (styled !== undefined) {
|
|
269
|
+
this.add(name.slice(0, -styled[0].length), file, styled[1], styled[2])
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Where the dev server serves a file: from the project, or through `/@fs/` when it is outside (a monorepo's). */
|
|
274
|
+
private url(file: string): string {
|
|
275
|
+
const relative = path.relative(this.root, file)
|
|
276
|
+
const outside = relative.startsWith('..') || path.isAbsolute(relative)
|
|
277
|
+
return encodeURI(outside ? `/@fs${file.split(path.sep).join('/')}` : `/${relative.split(path.sep).join('/')}`)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
type FontNames = {
|
|
282
|
+
family?: string
|
|
283
|
+
typographicFamily?: string
|
|
284
|
+
fullName?: string
|
|
285
|
+
postScriptName?: string
|
|
286
|
+
weight: number
|
|
287
|
+
italic: boolean
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The names, weight and slant of a TrueType, OpenType or WOFF font, from its `name`, `OS/2` and `head` tables. */
|
|
291
|
+
export function readFontNames(file: string): FontNames | null {
|
|
292
|
+
try {
|
|
293
|
+
const tables = readTables(readFileSync(file))
|
|
294
|
+
const name = tables.get('name')
|
|
295
|
+
if (name === undefined) {
|
|
296
|
+
return null
|
|
297
|
+
}
|
|
298
|
+
const names = readNameTable(name)
|
|
299
|
+
const os2 = tables.get('OS/2')
|
|
300
|
+
const head = tables.get('head')
|
|
301
|
+
const weight = os2 !== undefined && os2.length >= 6 ? os2.readUInt16BE(4) : 400
|
|
302
|
+
const italic = (os2 !== undefined && os2.length >= 64 && (os2.readUInt16BE(62) & 1) !== 0) || (head !== undefined && head.length >= 46 && (head.readUInt16BE(44) & 2) !== 0)
|
|
303
|
+
return {
|
|
304
|
+
family: names.get(1),
|
|
305
|
+
typographicFamily: names.get(16),
|
|
306
|
+
fullName: names.get(4),
|
|
307
|
+
postScriptName: names.get(6),
|
|
308
|
+
weight: Math.min(1000, Math.max(1, weight || 400)),
|
|
309
|
+
italic,
|
|
310
|
+
}
|
|
311
|
+
} catch {
|
|
312
|
+
return null
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function readTables(data: Buffer): Map<string, Buffer> {
|
|
317
|
+
const tables = new Map<string, Buffer>()
|
|
318
|
+
const signature = data.toString('latin1', 0, 4)
|
|
319
|
+
if (signature === 'wOFF') {
|
|
320
|
+
const count = data.readUInt16BE(12)
|
|
321
|
+
for (let i = 0; i < count; i++) {
|
|
322
|
+
const record = 44 + i * 20
|
|
323
|
+
const tag = data.toString('latin1', record, record + 4)
|
|
324
|
+
const offset = data.readUInt32BE(record + 4)
|
|
325
|
+
const compressed = data.readUInt32BE(record + 8)
|
|
326
|
+
const length = data.readUInt32BE(record + 12)
|
|
327
|
+
const bytes = data.subarray(offset, offset + compressed)
|
|
328
|
+
tables.set(tag, compressed < length ? inflateSync(bytes) : bytes)
|
|
329
|
+
}
|
|
330
|
+
return tables
|
|
331
|
+
}
|
|
332
|
+
if (signature !== '\0\x01\0\0' && signature !== 'OTTO' && signature !== 'true') {
|
|
333
|
+
// WOFF2's tables are one Brotli stream with its own directory format, and a collection holds several fonts.
|
|
334
|
+
return tables
|
|
335
|
+
}
|
|
336
|
+
const count = data.readUInt16BE(4)
|
|
337
|
+
for (let i = 0; i < count; i++) {
|
|
338
|
+
const record = 12 + i * 16
|
|
339
|
+
const offset = data.readUInt32BE(record + 8)
|
|
340
|
+
tables.set(data.toString('latin1', record, record + 4), data.subarray(offset, offset + data.readUInt32BE(record + 12)))
|
|
341
|
+
}
|
|
342
|
+
return tables
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Name IDs to strings, preferring Windows US English (UTF-16), then any Windows Unicode, then Mac Roman. */
|
|
346
|
+
function readNameTable(table: Buffer): Map<number, string> {
|
|
347
|
+
const count = table.readUInt16BE(2)
|
|
348
|
+
const strings = table.readUInt16BE(4)
|
|
349
|
+
const ranked = new Map<number, { rank: number; value: string }>()
|
|
350
|
+
for (let i = 0; i < count; i++) {
|
|
351
|
+
const record = 6 + i * 12
|
|
352
|
+
const platform = table.readUInt16BE(record)
|
|
353
|
+
const encoding = table.readUInt16BE(record + 2)
|
|
354
|
+
const language = table.readUInt16BE(record + 4)
|
|
355
|
+
const id = table.readUInt16BE(record + 6)
|
|
356
|
+
const bytes = table.subarray(strings + table.readUInt16BE(record + 10), strings + table.readUInt16BE(record + 10) + table.readUInt16BE(record + 8))
|
|
357
|
+
let rank: number
|
|
358
|
+
let value: string
|
|
359
|
+
if (platform === 3 && (encoding === 1 || encoding === 10)) {
|
|
360
|
+
rank = language === 0x409 ? 0 : 1
|
|
361
|
+
value = Buffer.from(bytes).swap16().toString('utf16le')
|
|
362
|
+
} else if (platform === 0) {
|
|
363
|
+
rank = 2
|
|
364
|
+
value = Buffer.from(bytes).swap16().toString('utf16le')
|
|
365
|
+
} else if (platform === 1 && encoding === 0) {
|
|
366
|
+
rank = 3
|
|
367
|
+
value = bytes.toString('latin1')
|
|
368
|
+
} else {
|
|
369
|
+
continue
|
|
370
|
+
}
|
|
371
|
+
const current = ranked.get(id)
|
|
372
|
+
if (value.trim() !== '' && (current === undefined || rank < current.rank)) {
|
|
373
|
+
ranked.set(id, { rank, value: value.trim() })
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return new Map([...ranked].map(([id, { value }]) => [id, value]))
|
|
377
|
+
}
|
|
@@ -5,6 +5,7 @@ import type { Plugin } from 'vite'
|
|
|
5
5
|
import { RUNTIME_ENTRY } from '../paths.ts'
|
|
6
6
|
import { devicePlatformSource } from './platformPatch.ts'
|
|
7
7
|
import { applyPatches, type FileOverride, type OverrideRegistry } from './registry.ts'
|
|
8
|
+
import type { Worklets } from '../worklets.ts'
|
|
8
9
|
|
|
9
10
|
const ORIGINAL = 'web-sim:original'
|
|
10
11
|
const ORIGINAL_PREFIX = '\0web-sim-original:'
|
|
@@ -12,11 +13,12 @@ const ORIGINAL_PREFIX = '\0web-sim-original:'
|
|
|
12
13
|
/**
|
|
13
14
|
* Applies the overrides to dependencies as Vite pre-bundles them, which is where nearly all of a package's files are
|
|
14
15
|
* loaded. The plugin is named after a hash of the overrides, because Vite keys the pre-bundle by esbuild plugin
|
|
15
|
-
* names: an edited override then rebuilds it, and browsers fetch the new bundle.
|
|
16
|
+
* names: an edited override then rebuilds it, and browsers fetch the new bundle. Worklets are compiled last, as
|
|
17
|
+
* Metro compiles them in every dependency.
|
|
16
18
|
*/
|
|
17
|
-
export function overridesEsbuild(registry: OverrideRegistry): EsbuildPlugin {
|
|
19
|
+
export function overridesEsbuild(registry: OverrideRegistry, worklets: Worklets | null = null): EsbuildPlugin {
|
|
18
20
|
return {
|
|
19
|
-
name: `web-sim-overrides-${registry.hash()}`,
|
|
21
|
+
name: `web-sim-overrides-${registry.hash()}${worklets === null ? '' : `-${worklets.key}`}`,
|
|
20
22
|
setup(build) {
|
|
21
23
|
build.onResolve({ filter: /^web-sim\/runtime$/ }, () => ({ path: RUNTIME_ENTRY }))
|
|
22
24
|
build.onResolve({ filter: /^web-sim:original$/ }, ({ importer }) => ({
|
|
@@ -33,15 +35,16 @@ export function overridesEsbuild(registry: OverrideRegistry): EsbuildPlugin {
|
|
|
33
35
|
loader: loaderFor(file),
|
|
34
36
|
resolveDir: path.dirname(file),
|
|
35
37
|
}))
|
|
36
|
-
build.onLoad({ filter: /[\\/]node_modules[\\/]/ }, ({ path: file }) => {
|
|
38
|
+
build.onLoad({ filter: /[\\/]node_modules[\\/]/ }, async ({ path: file }) => {
|
|
37
39
|
const override = registry.overrideForFile(file)
|
|
38
40
|
const loaded = override === null ? undefined : loadOverride(file, override)
|
|
39
|
-
if (
|
|
41
|
+
if (!/\.[cm]?[jt]sx?$/.test(file) || (override !== null && override.kind !== 'patch' && override.kind !== 'replace')) {
|
|
40
42
|
return loaded
|
|
41
43
|
}
|
|
42
44
|
const source = loaded?.contents ?? readFileSync(file, 'utf8')
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
let contents = registry.seesDevicePlatform(file) && override?.kind !== 'replace' ? devicePlatformSource(source, file) : source
|
|
46
|
+
contents = (await worklets?.transform(contents, loaded?.pluginData?.overrideFile ?? file)) ?? contents
|
|
47
|
+
return contents === source ? loaded : { ...loaded, contents, loader: loaded?.loader ?? loaderFor(file), resolveDir: path.dirname(file) }
|
|
45
48
|
})
|
|
46
49
|
},
|
|
47
50
|
}
|
package/src/node/server.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { existsSync, watch } from 'node:fs'
|
|
2
|
-
import { createRequire } from 'node:module'
|
|
3
2
|
import path from 'node:path'
|
|
4
3
|
import react from '@vitejs/plugin-react'
|
|
5
4
|
import { createServer, type InlineConfig, mergeConfig, type Plugin, searchForWorkspaceRoot, type ViteDevServer } from 'vite'
|
|
@@ -16,6 +15,7 @@ import { appProxy } from './proxy.ts'
|
|
|
16
15
|
import { EventStore, eventsChannel } from './events/store.ts'
|
|
17
16
|
import { type LoadedPlugin, loadPlugins } from './plugins.ts'
|
|
18
17
|
import { PlatformScope } from './platform.ts'
|
|
18
|
+
import { loadWorklets, workletsPlugin } from './worklets.ts'
|
|
19
19
|
|
|
20
20
|
export const DEFAULT_PORT = 5310
|
|
21
21
|
|
|
@@ -75,13 +75,13 @@ export async function createSimServer(context: SimContext, port: number, events
|
|
|
75
75
|
|
|
76
76
|
registry.onWarning = (warning) => console.warn(`\x1b[33mweb-sim\x1b[0m ${warning.message}`)
|
|
77
77
|
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
78
|
+
const worklets = loadWorklets(project.root)
|
|
79
|
+
// The app's own Babel plugins compile its files; the Worklets plugin compiles every file, as Metro's does: linked
|
|
80
|
+
// workspace packages outside the app here, dependencies in `overridesEsbuild` and `workletsPlugin`.
|
|
81
|
+
const babelPlugins = (file: string) => [
|
|
82
|
+
...(scope.isAppSource(file) ? (config.babelPlugins ?? []) : []),
|
|
83
|
+
...(worklets !== null && !file.startsWith(PACKAGE_ROOT + path.sep) && !file.startsWith('\0') ? [worklets.plugin] : []),
|
|
84
|
+
]
|
|
85
85
|
|
|
86
86
|
const sourceDefines = {
|
|
87
87
|
__DEV__: 'true',
|
|
@@ -107,11 +107,12 @@ export async function createSimServer(context: SimContext, port: number, events
|
|
|
107
107
|
...plugins.flatMap((plugin) => plugin.vite ?? []),
|
|
108
108
|
scope.vitePlugin(),
|
|
109
109
|
overridesPlugin(registry),
|
|
110
|
+
workletsPlugin(worklets),
|
|
110
111
|
assetRequires(scope),
|
|
111
112
|
platformChannel(scope),
|
|
112
113
|
metroSockets(),
|
|
113
114
|
react({
|
|
114
|
-
babel: (id) => ({ plugins:
|
|
115
|
+
babel: (id) => ({ plugins: babelPlugins(id.split('?')[0]) }) as never,
|
|
115
116
|
}),
|
|
116
117
|
],
|
|
117
118
|
define: sourceDefines,
|
|
@@ -132,7 +133,7 @@ export async function createSimServer(context: SimContext, port: number, events
|
|
|
132
133
|
// panel imports it, and reload the page the first time.
|
|
133
134
|
exclude: ['web-sim/shell'],
|
|
134
135
|
esbuildOptions: {
|
|
135
|
-
plugins: [scope.esbuildPlugin(), overridesEsbuild(registry)],
|
|
136
|
+
plugins: [scope.esbuildPlugin(), overridesEsbuild(registry, worklets)],
|
|
136
137
|
loader: { '.js': 'jsx' },
|
|
137
138
|
resolveExtensions: WEB_EXTENSIONS,
|
|
138
139
|
define: {
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { transformAsync } from '@babel/core'
|
|
5
|
+
import type { Plugin } from 'vite'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The Worklets Babel plugin (Reanimated 4), run where Metro runs it: over every file, the app's dependencies too.
|
|
9
|
+
* Without it, a library that calls `useAnimatedStyle(() => ...)` with no dependency array throws on the web, since
|
|
10
|
+
* Reanimated has nothing to tell it when the style's inputs change.
|
|
11
|
+
*/
|
|
12
|
+
export type Worklets = {
|
|
13
|
+
/** The plugin, for the app's own files, which `@vitejs/plugin-react` compiles with Babel already. */
|
|
14
|
+
plugin: string
|
|
15
|
+
/** Changes with the plugin's version, so pre-bundles made by another one are rebuilt. */
|
|
16
|
+
key: string
|
|
17
|
+
/** A dependency's file with its worklets compiled, or null when it has none. */
|
|
18
|
+
transform(code: string, file: string): Promise<string | null>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function loadWorklets(projectRoot: string): Worklets | null {
|
|
22
|
+
const requireFromProject = createRequire(path.join(projectRoot, 'package.json'))
|
|
23
|
+
let plugin: string
|
|
24
|
+
try {
|
|
25
|
+
plugin = requireFromProject.resolve('react-native-worklets/plugin')
|
|
26
|
+
} catch {
|
|
27
|
+
// Not a Reanimated 4 app.
|
|
28
|
+
return null
|
|
29
|
+
}
|
|
30
|
+
const version = readVersion(path.join(path.dirname(plugin), '..', 'package.json'))
|
|
31
|
+
return {
|
|
32
|
+
plugin,
|
|
33
|
+
key: `worklets-${version}`,
|
|
34
|
+
async transform(code, file) {
|
|
35
|
+
if (!mayHaveWorklets(code)) {
|
|
36
|
+
return null
|
|
37
|
+
}
|
|
38
|
+
const typescript = /\.[cm]?tsx?$/.test(file)
|
|
39
|
+
const result = await transformAsync(code, {
|
|
40
|
+
filename: file,
|
|
41
|
+
babelrc: false,
|
|
42
|
+
configFile: false,
|
|
43
|
+
compact: false,
|
|
44
|
+
retainLines: true,
|
|
45
|
+
sourceType: 'unambiguous',
|
|
46
|
+
parserOpts: { plugins: typescript ? ['jsx', 'typescript'] : ['jsx'] },
|
|
47
|
+
plugins: [plugin],
|
|
48
|
+
})
|
|
49
|
+
return result?.code ?? null
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Whether a file may hold a worklet: a `'worklet'` directive, or a call to Reanimated or Worklets, whose callbacks the
|
|
56
|
+
* plugin makes worklets of. Most files have neither, and skip Babel.
|
|
57
|
+
*/
|
|
58
|
+
export function mayHaveWorklets(code: string): boolean {
|
|
59
|
+
return /\breact-native-(?:reanimated|worklets)\b|["']worklet["']/.test(code)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Worklets in the dependencies Vite serves without pre-bundling: linked or excluded ones. `@vitejs/plugin-react`
|
|
64
|
+
* leaves `node_modules` alone, so this plugin compiles them.
|
|
65
|
+
*/
|
|
66
|
+
export function workletsPlugin(worklets: Worklets | null): Plugin {
|
|
67
|
+
return {
|
|
68
|
+
name: 'web-sim:worklets',
|
|
69
|
+
async transform(code, id) {
|
|
70
|
+
const file = id.split('?')[0]
|
|
71
|
+
if (worklets === null || file.startsWith('\0') || !file.includes(`${path.sep}node_modules${path.sep}`) || !/\.[cm]?[jt]sx?$/.test(file)) {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
const compiled = await worklets.transform(code, file)
|
|
75
|
+
return compiled === null ? null : { code: compiled, map: null }
|
|
76
|
+
},
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function readVersion(packageJson: string): string {
|
|
81
|
+
try {
|
|
82
|
+
return String(JSON.parse(readFileSync(packageJson, 'utf8')).version)
|
|
83
|
+
} catch {
|
|
84
|
+
return 'unknown'
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/runtime/index.ts
CHANGED
|
@@ -163,8 +163,14 @@ export type AppInfo = {
|
|
|
163
163
|
dependencies?: string[]
|
|
164
164
|
/** The appearance the app pins by platform, from its Expo config's `userInterfaceStyle`. */
|
|
165
165
|
userInterfaceStyle?: { ios: UserInterfaceStyle; android: UserInterfaceStyle }
|
|
166
|
+
/** The fonts a native build embeds, by platform, under the names each platform gives them (`src/node/fonts.ts`). */
|
|
167
|
+
fonts?: BundledFonts
|
|
166
168
|
}
|
|
167
169
|
|
|
170
|
+
/** One `@font-face`: a font file under a family name, for a weight (or a range, `1 1000`) and a style. */
|
|
171
|
+
export type BundledFont = { family: string; url: string; weight: string; style: 'normal' | 'italic' }
|
|
172
|
+
export type BundledFonts = { ios: BundledFont[]; android: BundledFont[] }
|
|
173
|
+
|
|
168
174
|
/**
|
|
169
175
|
* The shell's side of the simulator. It lives on the shell's window; the app reaches it through `window.parent`,
|
|
170
176
|
* which works because both share an origin. Overrides talk to it through this module and keep no state of their
|