Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .bun-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1.2.23
2 changes: 2 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ jobs:

- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: .bun-version

- name: Install dependencies
run: bun install
Expand Down
226 changes: 148 additions & 78 deletions bun.lock

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions packages/uniwind/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,13 @@
"lightningcss": ">=1.30.0"
},
"devDependencies": {
"@types/bun": "1.2.23",
"@types/bun": "1.3.0",
"@types/postcss-js": "4.0.4",
"@types/culori": "4.0.1",
"@types/react": "19.2.2",
"typescript": "5.9.3",
"metro-config": "0.82.5",
"metro-config": "0.83.3",
"metro": "0.83.3",
"@babel/core": "7.28.4",
"@babel/types": "7.28.4",
"dpdm": "3.14.0",
Expand Down
3 changes: 3 additions & 0 deletions packages/uniwind/specs/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ export const injectMocks = () => {
StyleSheet: {
hairlineWidth: 1,
},
Platform: {
OS: 'ios',
},
}))
// @ts-expect-error Mock __DEV__
globalThis.__DEV__ = true
Expand Down
7 changes: 6 additions & 1 deletion packages/uniwind/src/core/native/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Dimensions } from 'react-native'
import { Dimensions, Platform } from 'react-native'
import { Orientation, StyleDependency } from '../../types'
import { ComponentState, RNStyle, Style, StyleSheets } from '../types'
import { parseBoxShadow, parseFontVariant, parseTransformsMutation, resolveGradient } from './parsers'
Expand Down Expand Up @@ -141,11 +141,16 @@ export class UniwindStoreBuilder {
if (usingVariables.size > 0) {
const styleSheet = globalThis.__uniwind__computeStylesheet(this.runtime)
const themeVars = styleSheet[`__uniwind-theme-${this.runtime.currentThemeName}`]
const platformVars = styleSheet[`__uniwind-platform-${Platform.OS}`]

if (themeVars) {
Object.assign(styleSheet, themeVars)
}

if (platformVars) {
Object.assign(styleSheet, platformVars)
}

inlineVariables.forEach((varValue, varName) => {
Object.defineProperty(styleSheet, varName, {
get: varValue,
Expand Down
9 changes: 8 additions & 1 deletion packages/uniwind/src/metro/processor/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,19 @@ export class ProcessorBuilder {

private addDeclaration(declaration: Declaration, important = false) {
const isVar = this.declarationConfig.root || this.declarationConfig.className === null
const mq = this.MQ.processMediaQueries(this.declarationConfig.mediaQueries)
const style = (() => {
if (!isVar) {
return this.stylesheets[this.declarationConfig.className!]?.at(-1)
}

if (mq.platform !== null) {
const platformKey = `__uniwind-platform-${mq.platform}`
this.vars[platformKey] ??= {}

return this.vars[platformKey]
}

if (this.declarationConfig.theme === null) {
return this.vars
}
Expand All @@ -67,7 +75,6 @@ export class ProcessorBuilder {

return this.vars[themeKey]
})()
const mq = this.MQ.processMediaQueries(this.declarationConfig.mediaQueries)

if (!isVar) {
Object.assign(style, mq)
Expand Down
4 changes: 0 additions & 4 deletions packages/uniwind/src/metro/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ export type ExtendedFileSystem = {
getSha1: WithUniwindPatch<(filename: string) => string>
}

export type DeepMutable<T> = {
-readonly [P in keyof T]: T[P] extends object ? DeepMutable<T[P]> : T[P]
}

export type UniwindConfig = {
cssEntryFile: string
themes: Array<string>
Expand Down
201 changes: 102 additions & 99 deletions packages/uniwind/src/metro/withUniwindConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { compileVirtual } from './compileVirtual'
import { getSources } from './getSources'
import { injectThemes } from './injectThemes'
import { nativeResolver, webResolver } from './resolvers'
import { DeepMutable, ExtendedBundler, ExtendedFileSystem, FileChangeEvent, Platform, UniwindConfig } from './types'
import { ExtendedBundler, ExtendedFileSystem, FileChangeEvent, Platform, UniwindConfig } from './types'
import { areSetsEqual, uniq } from './utils'

const cacheDir = path.join(__dirname, '.cache')
Expand All @@ -21,9 +21,9 @@ const getPlatformFromVirtualPath = (path: string) => {
const platforms = [Platform.iOS, Platform.Android, Platform.Web]

export const withUniwindConfig = (
config: DeepMutable<MetroConfig>,
config: MetroConfig,
uniwindConfig: UniwindConfig,
) => {
): MetroConfig => {
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir)
}
Expand Down Expand Up @@ -70,101 +70,6 @@ export const withUniwindConfig = (
})

uniwind.injectedThemesScript = getInjectedThemesScript()
config.resolver ??= {}
config.server ??= {}
config.transformer ??= {}

config.resolver.sourceExts = [
...config.resolver.sourceExts ?? [],
'css',
]
config.resolver.assetExts = config.resolver.assetExts?.filter(
ext => ext !== 'css',
)
config.resolver.resolveRequest = (context, moduleName, platform) => {
const resolver = uniwind.originalResolveRequest ?? context.resolveRequest
const platformResolver = platform === Platform.Web ? webResolver : nativeResolver
const resolved = platformResolver({
context,
moduleName,
platform,
resolver,
})

if (('filePath' in resolved && resolved.filePath !== path.join(process.cwd(), uniwindConfig.cssEntryFile))) {
return resolved
}

if (platform !== Platform.iOS && platform !== Platform.Android && platform !== Platform.Web) {
return resolved
}

return {
...resolved,
filePath: getVirtualPath(platform),
}
}

config.server.enhanceMiddleware = (middleware, metroServer) => {
const bundler = metroServer.getBundler().getBundler()

uniwind.virtualModulesPossible = bundler
.getDependencyGraph()
.then(async graph => {
uniwind.watcher = bundler.getWatcher()
// @ts-expect-error Hidden property
ensureFileSystemPatched(graph._fileSystem)
ensureBundlerPatched(bundler)

uniwind.watcher.on('change', (event: FileChangeEvent) => {
if ('eventsQueue' in event) {
if (
// Listen only to changes in JS/TS/css files
!event.eventsQueue.some(event => {
return ['.js', '.jsx', '.ts', '.tsx', '.css'].some(ext => event.filePath.endsWith(ext))
}) || event.eventsQueue.every(event => event.filePath.endsWith('uniwind.css'))
) {
return
}

const css = fs.readFileSync(uniwind.input, 'utf-8')
const candidates = new Set(uniwind.getCandidates(css))
const tailwindHasChanged = css !== uniwind.cssFile || !areSetsEqual(uniwind.candidates, candidates)

if (!tailwindHasChanged) {
return
}

uniwind.injectedThemesScript = getInjectedThemesScript()
uniwind.cssFile = css
uniwind.candidates = candidates
platforms.forEach(platform => {
uniwind.watcher?.emit(
'change',
{
eventsQueue: [{
filePath: getVirtualPath(platform),
metadata: {
modifiedTime: Date.now(),
size: 1,
type: 'virtual',
},
type: 'change',
}],
} satisfies FileChangeEvent,
)
})
}
})

uniwind.cssFile = fs.readFileSync(uniwind.input, 'utf-8')
uniwind.candidates = new Set(uniwind.getCandidates(uniwind.cssFile))

await Promise.all(platforms.map(getVirtualFile))
})

return middleware
}

const ensureFileSystemPatched = (fs: ExtendedFileSystem) => {
if (!fs.getSha1.__uniwind_patched) {
Expand Down Expand Up @@ -234,5 +139,103 @@ export const withUniwindConfig = (
return virtualFile
}

return config
return {
...config,
resolver: {
...config.resolver,
sourceExts: [
...config.resolver?.sourceExts ?? [],
'css',
],
assetExts: config.resolver?.assetExts?.filter(
ext => ext !== 'css',
),
resolveRequest: (context, moduleName, platform) => {
const resolver = uniwind.originalResolveRequest ?? context.resolveRequest
const platformResolver = platform === Platform.Web ? webResolver : nativeResolver
const resolved = platformResolver({
context,
moduleName,
platform,
resolver,
})

if (('filePath' in resolved && resolved.filePath !== path.join(process.cwd(), uniwindConfig.cssEntryFile))) {
return resolved
}

if (platform !== Platform.iOS && platform !== Platform.Android && platform !== Platform.Web) {
return resolved
}

return {
...resolved,
filePath: getVirtualPath(platform),
}
},
},
server: {
...config.server,
enhanceMiddleware: (middleware, metroServer) => {
const bundler = metroServer.getBundler().getBundler()

uniwind.virtualModulesPossible = bundler
.getDependencyGraph()
.then(async graph => {
uniwind.watcher = bundler.getWatcher()
// @ts-expect-error Hidden property
ensureFileSystemPatched(graph._fileSystem)
ensureBundlerPatched(bundler)

uniwind.watcher.on('change', (event: FileChangeEvent) => {
if ('eventsQueue' in event) {
if (
// Listen only to changes in JS/TS/css files
!event.eventsQueue.some(event => {
return ['.js', '.jsx', '.ts', '.tsx', '.css'].some(ext => event.filePath.endsWith(ext))
}) || event.eventsQueue.every(event => event.filePath.endsWith('uniwind.css'))
) {
return
}

const css = fs.readFileSync(uniwind.input, 'utf-8')
const candidates = new Set(uniwind.getCandidates(css))
const tailwindHasChanged = css !== uniwind.cssFile || !areSetsEqual(uniwind.candidates, candidates)

if (!tailwindHasChanged) {
return
}

uniwind.injectedThemesScript = getInjectedThemesScript()
uniwind.cssFile = css
uniwind.candidates = candidates
platforms.forEach(platform => {
uniwind.watcher?.emit(
'change',
{
eventsQueue: [{
filePath: getVirtualPath(platform),
metadata: {
modifiedTime: Date.now(),
size: 1,
type: 'virtual',
},
type: 'change',
}],
} satisfies FileChangeEvent,
)
})
}
})

uniwind.cssFile = fs.readFileSync(uniwind.input, 'utf-8')
uniwind.candidates = new Set(uniwind.getCandidates(uniwind.cssFile))

await Promise.all(platforms.map(getVirtualFile))
})

return middleware
},
},
}
}