react-native-unistyles 3.7.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +2 -2
  2. package/android/src/main/java/com/unistyles/NativePlatform+android.kt +2 -15
  3. package/android/src/main/java/com/unistyles/NativePlatform+listener.kt +1 -1
  4. package/codemods/use-variants.js +155 -0
  5. package/components/native/TouchableHighlight/package.json +1 -1
  6. package/cxx/converters/TransformOriginConverter.cpp +3 -2
  7. package/cxx/core/DependencyTracker.h +162 -0
  8. package/cxx/core/StyleSheet.h +14 -0
  9. package/cxx/core/Unistyle.h +6 -3
  10. package/cxx/core/UnistylesRegistry.cpp +16 -2
  11. package/cxx/core/UnistylesRegistry.h +2 -1
  12. package/cxx/hybridObjects/HybridShadowRegistry.cpp +16 -5
  13. package/cxx/hybridObjects/HybridShadowRegistry.h +1 -1
  14. package/cxx/hybridObjects/HybridStyleSheet.cpp +8 -1
  15. package/cxx/hybridObjects/HybridUnistylesRuntime.cpp +1 -1
  16. package/cxx/parser/Parser.cpp +83 -31
  17. package/cxx/parser/Parser.h +5 -0
  18. package/cxx/shadowTree/NativeProps.h +23 -0
  19. package/cxx/shadowTree/ShadowTrafficController.h +5 -0
  20. package/cxx/shadowTree/ShadowTreeManager.cpp +73 -1
  21. package/ios/NativePlatform+ios.swift +4 -6
  22. package/ios/Unistyles.h +1 -0
  23. package/lib/commonjs/core/trackDependencies.js +10 -0
  24. package/lib/commonjs/core/trackDependencies.js.map +1 -0
  25. package/lib/commonjs/core/trackDependencies.metro.js +10 -0
  26. package/lib/commonjs/core/trackDependencies.metro.js.map +1 -0
  27. package/lib/commonjs/core/useProxifiedUnistyles/useProxifiedUnistyles.js +4 -0
  28. package/lib/commonjs/core/useProxifiedUnistyles/useProxifiedUnistyles.js.map +1 -1
  29. package/lib/commonjs/core/withUnistyles/withUnistyles.native.js +63 -14
  30. package/lib/commonjs/core/withUnistyles/withUnistyles.native.js.map +1 -1
  31. package/lib/commonjs/hooks/useMedia.js +6 -0
  32. package/lib/commonjs/hooks/useMedia.js.map +1 -1
  33. package/lib/commonjs/mocks.js +4 -2
  34. package/lib/commonjs/mocks.js.map +1 -1
  35. package/lib/commonjs/reanimated/variant/useUpdateVariantColor.js +13 -4
  36. package/lib/commonjs/reanimated/variant/useUpdateVariantColor.js.map +1 -1
  37. package/lib/commonjs/specs/ShadowRegistry/index.js +26 -1
  38. package/lib/commonjs/specs/ShadowRegistry/index.js.map +1 -1
  39. package/lib/commonjs/specs/StyleSheet/index.js +6 -1
  40. package/lib/commonjs/specs/StyleSheet/index.js.map +1 -1
  41. package/lib/commonjs/types/stylesheet.js.map +1 -1
  42. package/lib/commonjs/web/convert/index.js +2 -2
  43. package/lib/commonjs/web/convert/index.js.map +1 -1
  44. package/lib/commonjs/web/convert/style.js +6 -0
  45. package/lib/commonjs/web/convert/style.js.map +1 -1
  46. package/lib/commonjs/web/create.js +35 -6
  47. package/lib/commonjs/web/create.js.map +1 -1
  48. package/lib/commonjs/web/css/core.js +12 -2
  49. package/lib/commonjs/web/css/core.js.map +1 -1
  50. package/lib/commonjs/web/css/sheet.js +223 -0
  51. package/lib/commonjs/web/css/sheet.js.map +1 -0
  52. package/lib/commonjs/web/css/state.js +98 -78
  53. package/lib/commonjs/web/css/state.js.map +1 -1
  54. package/lib/commonjs/web/css/utils.js +1 -31
  55. package/lib/commonjs/web/css/utils.js.map +1 -1
  56. package/lib/commonjs/web/dependencyTracker.js +72 -0
  57. package/lib/commonjs/web/dependencyTracker.js.map +1 -0
  58. package/lib/commonjs/web/registry.js +73 -4
  59. package/lib/commonjs/web/registry.js.map +1 -1
  60. package/lib/commonjs/web/runtime.js +0 -1
  61. package/lib/commonjs/web/runtime.js.map +1 -1
  62. package/lib/commonjs/web/shadowRegistry.js +83 -11
  63. package/lib/commonjs/web/shadowRegistry.js.map +1 -1
  64. package/lib/commonjs/web/types.js +3 -1
  65. package/lib/commonjs/web/types.js.map +1 -1
  66. package/lib/module/core/trackDependencies.js +6 -0
  67. package/lib/module/core/trackDependencies.js.map +1 -0
  68. package/lib/module/core/trackDependencies.metro.js +6 -0
  69. package/lib/module/core/trackDependencies.metro.js.map +1 -0
  70. package/lib/module/core/useProxifiedUnistyles/useProxifiedUnistyles.js +4 -0
  71. package/lib/module/core/useProxifiedUnistyles/useProxifiedUnistyles.js.map +1 -1
  72. package/lib/module/core/withUnistyles/withUnistyles.native.js +63 -15
  73. package/lib/module/core/withUnistyles/withUnistyles.native.js.map +1 -1
  74. package/lib/module/hooks/useMedia.js +6 -0
  75. package/lib/module/hooks/useMedia.js.map +1 -1
  76. package/lib/module/mocks.js +4 -2
  77. package/lib/module/mocks.js.map +1 -1
  78. package/lib/module/reanimated/variant/useUpdateVariantColor.js +15 -5
  79. package/lib/module/reanimated/variant/useUpdateVariantColor.js.map +1 -1
  80. package/lib/module/specs/ShadowRegistry/index.js +25 -1
  81. package/lib/module/specs/ShadowRegistry/index.js.map +1 -1
  82. package/lib/module/specs/StyleSheet/index.js +6 -1
  83. package/lib/module/specs/StyleSheet/index.js.map +1 -1
  84. package/lib/module/types/stylesheet.js.map +1 -1
  85. package/lib/module/web/convert/index.js +2 -2
  86. package/lib/module/web/convert/index.js.map +1 -1
  87. package/lib/module/web/convert/style.js +6 -0
  88. package/lib/module/web/convert/style.js.map +1 -1
  89. package/lib/module/web/create.js +35 -6
  90. package/lib/module/web/create.js.map +1 -1
  91. package/lib/module/web/css/core.js +10 -1
  92. package/lib/module/web/css/core.js.map +1 -1
  93. package/lib/module/web/css/sheet.js +216 -0
  94. package/lib/module/web/css/sheet.js.map +1 -0
  95. package/lib/module/web/css/state.js +98 -78
  96. package/lib/module/web/css/state.js.map +1 -1
  97. package/lib/module/web/css/utils.js +0 -29
  98. package/lib/module/web/css/utils.js.map +1 -1
  99. package/lib/module/web/dependencyTracker.js +67 -0
  100. package/lib/module/web/dependencyTracker.js.map +1 -0
  101. package/lib/module/web/registry.js +73 -4
  102. package/lib/module/web/registry.js.map +1 -1
  103. package/lib/module/web/runtime.js +0 -1
  104. package/lib/module/web/runtime.js.map +1 -1
  105. package/lib/module/web/shadowRegistry.js +83 -11
  106. package/lib/module/web/shadowRegistry.js.map +1 -1
  107. package/lib/module/web/types.js +2 -0
  108. package/lib/module/web/types.js.map +1 -1
  109. package/lib/typescript/src/core/trackDependencies.d.ts +2 -0
  110. package/lib/typescript/src/core/trackDependencies.d.ts.map +1 -0
  111. package/lib/typescript/src/core/trackDependencies.metro.d.ts +2 -0
  112. package/lib/typescript/src/core/trackDependencies.metro.d.ts.map +1 -0
  113. package/lib/typescript/src/core/useProxifiedUnistyles/useProxifiedUnistyles.d.ts.map +1 -1
  114. package/lib/typescript/src/core/withUnistyles/withUnistyles.native.d.ts +2 -1
  115. package/lib/typescript/src/core/withUnistyles/withUnistyles.native.d.ts.map +1 -1
  116. package/lib/typescript/src/hooks/useMedia.d.ts.map +1 -1
  117. package/lib/typescript/src/reanimated/variant/useUpdateVariantColor.d.ts.map +1 -1
  118. package/lib/typescript/src/specs/ShadowRegistry/index.d.ts +1 -1
  119. package/lib/typescript/src/specs/ShadowRegistry/index.d.ts.map +1 -1
  120. package/lib/typescript/src/specs/StyleSheet/index.d.ts +3 -1
  121. package/lib/typescript/src/specs/StyleSheet/index.d.ts.map +1 -1
  122. package/lib/typescript/src/types/stylesheet.d.ts +3 -3
  123. package/lib/typescript/src/types/stylesheet.d.ts.map +1 -1
  124. package/lib/typescript/src/web/convert/style.d.ts.map +1 -1
  125. package/lib/typescript/src/web/create.d.ts.map +1 -1
  126. package/lib/typescript/src/web/css/core.d.ts +4 -1
  127. package/lib/typescript/src/web/css/core.d.ts.map +1 -1
  128. package/lib/typescript/src/web/css/sheet.d.ts +26 -0
  129. package/lib/typescript/src/web/css/sheet.d.ts.map +1 -0
  130. package/lib/typescript/src/web/css/state.d.ts +6 -6
  131. package/lib/typescript/src/web/css/state.d.ts.map +1 -1
  132. package/lib/typescript/src/web/css/utils.d.ts +0 -2
  133. package/lib/typescript/src/web/css/utils.d.ts.map +1 -1
  134. package/lib/typescript/src/web/dependencyTracker.d.ts +9 -0
  135. package/lib/typescript/src/web/dependencyTracker.d.ts.map +1 -0
  136. package/lib/typescript/src/web/registry.d.ts +9 -1
  137. package/lib/typescript/src/web/registry.d.ts.map +1 -1
  138. package/lib/typescript/src/web/runtime.d.ts.map +1 -1
  139. package/lib/typescript/src/web/shadowRegistry.d.ts.map +1 -1
  140. package/lib/typescript/src/web/types.d.ts +1 -0
  141. package/lib/typescript/src/web/types.d.ts.map +1 -1
  142. package/metro/index.d.ts +2 -12
  143. package/metro/index.js +57 -33
  144. package/package.json +64 -17
  145. package/plugin/index.d.ts +0 -7
  146. package/plugin/index.js +9 -15
  147. package/src/core/trackDependencies.metro.ts +3 -0
  148. package/src/core/trackDependencies.ts +3 -0
  149. package/src/core/useProxifiedUnistyles/useProxifiedUnistyles.ts +5 -0
  150. package/src/core/withUnistyles/withUnistyles.native.tsx +76 -17
  151. package/src/hooks/useMedia.ts +6 -0
  152. package/src/mocks.ts +5 -2
  153. package/src/reanimated/variant/useUpdateVariantColor.ts +15 -5
  154. package/src/specs/ShadowRegistry/index.ts +29 -2
  155. package/src/specs/StyleSheet/index.ts +4 -2
  156. package/src/types/stylesheet.ts +5 -4
  157. package/src/web/convert/index.ts +2 -2
  158. package/src/web/convert/style.ts +8 -0
  159. package/src/web/create.ts +45 -8
  160. package/src/web/css/core.ts +17 -3
  161. package/src/web/css/sheet.ts +274 -0
  162. package/src/web/css/state.ts +108 -95
  163. package/src/web/css/utils.ts +0 -42
  164. package/src/web/dependencyTracker.ts +71 -0
  165. package/src/web/registry.ts +88 -8
  166. package/src/web/runtime.ts +0 -1
  167. package/src/web/shadowRegistry.ts +101 -16
  168. package/src/web/types.ts +3 -0
  169. package/metro/babel-transformer.js +0 -1102
package/plugin/index.js CHANGED
@@ -91,7 +91,7 @@ var NATIVE_COMPONENTS_PATHS = {
91
91
  }
92
92
  ]
93
93
  };
94
- var METRO_UPSTREAM_TRANSFORMER_ENV = "UNISTYLES_METRO_UPSTREAM_TRANSFORMER";
94
+ var METRO_ENV = "UNISTYLES_METRO";
95
95
 
96
96
  // plugin/src/exotic.ts
97
97
  var t2 = __toESM(require("@babel/types"));
@@ -140,9 +140,6 @@ function addUnistylesImport(path2, state) {
140
140
  nodesToRemove.forEach((node) => path2.node.body.splice(path2.node.body.indexOf(node), 1));
141
141
  }
142
142
  function isInsideNodeModules(state) {
143
- if (state.opts.isMetro) {
144
- return false;
145
- }
146
143
  return state.file.opts.filename?.includes("node_modules") && !state.file.replaceWithUnistyles;
147
144
  }
148
145
  function addUnistylesRequire(path2, state) {
@@ -850,18 +847,18 @@ function index_default() {
850
847
  visitor: {
851
848
  Program: {
852
849
  enter(path2, state) {
853
- if (!state.opts.isMetro && process.env[METRO_UPSTREAM_TRANSFORMER_ENV]) {
850
+ if (process.env[METRO_ENV]) {
854
851
  throw new Error(
855
852
  "Unistyles \u{1F984}: react-native-unistyles/metro is enabled in metro.config.js, remove react-native-unistyles/plugin from babel.config.js"
856
853
  );
857
854
  }
858
- if (!state.opts.root && !state.opts.isMetro) {
855
+ if (!state.opts.root) {
859
856
  throw new Error(
860
857
  "Unistyles \u{1F984}: Babel plugin requires `root` option to be set. Please check https://www.unistyl.es/v3/other/babel-plugin#extra-configuration"
861
858
  );
862
859
  }
863
- const appRoot = toPlatformPath(import_node_path2.default.join(state.file.opts.root, state.opts.root ?? ""));
864
- if (!state.opts.isMetro && state.file.opts.root === appRoot) {
860
+ const appRoot = toPlatformPath(import_node_path2.default.join(state.file.opts.root, state.opts.root));
861
+ if (state.file.opts.root === appRoot) {
865
862
  throw new Error(
866
863
  "Unistyles \u{1F984}: Root option can't resolve to project root as it will include node_modules folder. Please check https://www.unistyl.es/v3/other/babel-plugin#extra-configuration"
867
864
  );
@@ -876,7 +873,7 @@ function index_default() {
876
873
  state.file.styleSheetLocalName = "";
877
874
  state.file.reactNativeCommonJSName = "";
878
875
  state.reactNativeImports = {};
879
- state.file.forceProcessing = state.opts.isMetro || (state.filename?.includes(appRoot) ?? false);
876
+ state.file.forceProcessing = state.filename?.includes(appRoot) ?? false;
880
877
  path2.traverse({
881
878
  BlockStatement(blockPath) {
882
879
  if (isInsideNodeModules(state)) {
@@ -887,7 +884,7 @@ function index_default() {
887
884
  });
888
885
  },
889
886
  exit(path2, state) {
890
- if (state.opts.isMetro || isInsideNodeModules(state)) {
887
+ if (isInsideNodeModules(state)) {
891
888
  return;
892
889
  }
893
890
  if (state.file.addUnistylesRequire) {
@@ -930,7 +927,7 @@ function index_default() {
930
927
  });
931
928
  },
932
929
  ImportDeclaration(path2, state) {
933
- const exoticImport = state.opts.isMetro ? void 0 : REPLACE_WITH_UNISTYLES_EXOTIC_PATHS.concat(state.opts.autoRemapImports ?? []).find(
930
+ const exoticImport = REPLACE_WITH_UNISTYLES_EXOTIC_PATHS.concat(state.opts.autoRemapImports ?? []).find(
934
931
  (exotic) => state.filename?.includes(exotic.path)
935
932
  );
936
933
  if (exoticImport) {
@@ -948,9 +945,6 @@ function index_default() {
948
945
  }
949
946
  });
950
947
  }
951
- if (state.opts.isMetro) {
952
- return;
953
- }
954
948
  if (importSource === "react-native") {
955
949
  path2.node.specifiers.forEach((specifier) => {
956
950
  if (t6.isImportSpecifier(specifier) && t6.isIdentifier(specifier.imported) && REACT_NATIVE_COMPONENT_NAMES.includes(specifier.imported.name)) {
@@ -974,7 +968,7 @@ function index_default() {
974
968
  }
975
969
  },
976
970
  MemberExpression(path2, state) {
977
- if (state.opts.isMetro || isInsideNodeModules(state)) {
971
+ if (isInsideNodeModules(state)) {
978
972
  return;
979
973
  }
980
974
  if (!state.file.reactNativeCommonJSName || !t6.isIdentifier(path2.node.object)) {
@@ -0,0 +1,3 @@
1
+ // resolved by react-native-unistyles/metro instead of trackDependencies.ts
2
+ // there is no Babel plugin, so Unistyles records what every StyleSheet reads while it runs
3
+ export const TRACK_DEPENDENCIES = true
@@ -0,0 +1,3 @@
1
+ // with the Babel plugin StyleSheets carry their dependencies (uni__dependencies)
2
+ // react-native-unistyles/metro resolves this module to trackDependencies.metro.ts
3
+ export const TRACK_DEPENDENCIES = false
@@ -72,6 +72,11 @@ export const useProxifiedUnistyles = () => {
72
72
  }
73
73
 
74
74
  useEffect(() => {
75
+ // make sure it runs after fast refesh
76
+ if (wasDisposedRef.current) {
77
+ reinitListener()
78
+ }
79
+
75
80
  return () => {
76
81
  disposeRef.current?.()
77
82
  syncedDependenciesSizeRef.current = -1
@@ -1,6 +1,7 @@
1
1
  import React, {
2
2
  useContext,
3
3
  useEffect,
4
+ useReducer,
4
5
  type ComponentProps,
5
6
  type ComponentRef,
6
7
  type ComponentType,
@@ -11,9 +12,11 @@ import type { UnistylesValues } from '../../types'
11
12
  import type { Mappings } from './types'
12
13
 
13
14
  import { ScopedThemeContext } from '../../components/ScopedThemeContext'
14
- import { type UnistyleDependency, UnistylesShadowRegistry } from '../../specs'
15
+ import { UnistyleDependency, UnistylesShadowRegistry } from '../../specs'
15
16
  import { deepMergeObjects, isAnimatedStyleHandle } from '../../utils'
17
+ import { TRACK_DEPENDENCIES } from '../trackDependencies'
16
18
  import { useProxifiedUnistyles } from '../useProxifiedUnistyles'
19
+ import { listener } from '../useProxifiedUnistyles/listener'
17
20
  import { maybeWarnAboutMultipleUnistyles } from '../warn'
18
21
 
19
22
  // @ts-expect-error
@@ -75,6 +78,38 @@ export const getSecrets = (styleProps: Record<string, any> = {}): MappedSecrets
75
78
  }
76
79
  }
77
80
 
81
+ // undefined when it can't be compared (eg. a circular value), then it always counts as changed
82
+ const serializeStyles = (styles: unknown) => {
83
+ try {
84
+ return JSON.stringify(styles)
85
+ } catch {
86
+ return undefined
87
+ }
88
+ }
89
+
90
+ // without the Babel plugin, a style depends on everything its StyleSheet read, so re-render only when it changed
91
+ // the component re-renders for theme changes anyway
92
+ export const listenToStyleChanges = (
93
+ dependencies: Array<UnistyleDependency>,
94
+ getStyles: () => unknown,
95
+ onChange: VoidFunction,
96
+ ) => {
97
+ let lastStyles = serializeStyles(getStyles())
98
+
99
+ return listener({
100
+ dependencies: dependencies.filter((dependency) => dependency !== UnistyleDependency.Theme),
101
+ updateTheme: () => {},
102
+ updateRuntime: () => {
103
+ const styles = serializeStyles(getStyles())
104
+
105
+ if (styles === undefined || styles !== lastStyles) {
106
+ lastStyles = styles
107
+ onChange()
108
+ }
109
+ },
110
+ })
111
+ }
112
+
78
113
  export const withUnistyles = <TComponent, TMappings extends GenericComponentProps<TComponent>>(
79
114
  Component: TComponent,
80
115
  mappings?: Mappings<TMappings>,
@@ -106,33 +141,57 @@ export const withUnistyles = <TComponent, TMappings extends GenericComponentProp
106
141
  // triggers the Proxy get trap which adds Theme to the dependency Set
107
142
  void (proxifiedTheme as Record<string, unknown>).__uni
108
143
 
144
+ const [, stylesChanged] = useReducer(() => ({}), {})
145
+
146
+ const getScopedSecrets = () => {
147
+ const previousScopedTheme = scope ? UnistylesShadowRegistry.getScopedTheme() : undefined
148
+
149
+ if (scope) {
150
+ UnistylesShadowRegistry.setScopedTheme(scope.name)
151
+ }
152
+
153
+ try {
154
+ const styleSecrets = getSecrets(narrowedProps.style)
155
+ const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle)
156
+
157
+ return { styleSecrets, contentContainerStyleSecrets }
158
+ } finally {
159
+ if (scope) {
160
+ UnistylesShadowRegistry.setScopedTheme(previousScopedTheme)
161
+ }
162
+ }
163
+ }
164
+
109
165
  useEffect(() => {
110
166
  const styleSecrets = getSecrets(narrowedProps.style)
111
167
  const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle)
168
+ const dependencies = Array.from(
169
+ new Set([...styleSecrets.dependencies, ...contentContainerStyleSecrets.dependencies]),
170
+ )
171
+
172
+ if (!TRACK_DEPENDENCIES) {
173
+ addDependencies(dependencies)
174
+
175
+ return
176
+ }
177
+
178
+ return listenToStyleChanges(
179
+ dependencies,
180
+ () => {
181
+ const secrets = getScopedSecrets()
112
182
 
113
- addDependencies(
114
- Array.from(new Set([...styleSecrets.dependencies, ...contentContainerStyleSecrets.dependencies])),
183
+ return [secrets.styleSecrets.styles, secrets.contentContainerStyleSecrets.styles]
184
+ },
185
+ stylesChanged,
115
186
  )
116
- }, [narrowedProps.style, narrowedProps.contentContainerStyle])
187
+ }, [narrowedProps.style, narrowedProps.contentContainerStyle, scope])
117
188
 
118
189
  const { key: mappingsKey, ...mappingsProps } = mappings ? mappings(proxifiedTheme, proxifiedRuntime) : {}
119
190
  const { key: uniPropsKey, ...unistyleProps } = narrowedProps.uniProps
120
191
  ? narrowedProps.uniProps(proxifiedTheme, proxifiedRuntime)
121
192
  : {}
122
193
 
123
- // styles resolve in the registry's scoped theme, which is already restored when this re-renders or mounts later
124
- const previousScopedTheme = scope ? UnistylesShadowRegistry.getScopedTheme() : undefined
125
-
126
- if (scope) {
127
- UnistylesShadowRegistry.setScopedTheme(scope.name)
128
- }
129
-
130
- const styleSecrets = getSecrets(narrowedProps.style)
131
- const contentContainerStyleSecrets = getSecrets(narrowedProps.contentContainerStyle)
132
-
133
- if (scope) {
134
- UnistylesShadowRegistry.setScopedTheme(previousScopedTheme)
135
- }
194
+ const { styleSecrets, contentContainerStyleSecrets } = getScopedSecrets()
136
195
 
137
196
  const finalProps = {
138
197
  ...deepMergeObjects(mappingsProps, unistyleProps, props),
@@ -1,6 +1,7 @@
1
1
  import { useEffect, useRef, useState } from 'react'
2
2
 
3
3
  import { isUnistylesMq, isValidMq, parseMq } from '../utils'
4
+ import { isServer } from '../web/utils'
4
5
 
5
6
  export const useMedia = (config: { mq: symbol }) => {
6
7
  const disposeRef = useRef(() => {})
@@ -32,6 +33,11 @@ export const useMedia = (config: { mq: symbol }) => {
32
33
  .filter(Boolean)
33
34
  .join(' and ')
34
35
 
36
+ // No viewport on the server, the content is hidden until the browser renders it
37
+ if (isServer()) {
38
+ return false
39
+ }
40
+
35
41
  const media = window.matchMedia(mediaQuery)
36
42
  const handler = (event: MediaQueryListEvent) => setIsVisible(event.matches)
37
43
 
package/src/mocks.ts CHANGED
@@ -268,10 +268,13 @@ jest.mock('react-native-unistyles', () => {
268
268
  ? styles(Object.values(_REGISTRY.themes).at(0) ?? {}, miniRuntime)
269
269
  : styles
270
270
 
271
- return {
271
+ const stylesheet = {
272
272
  ...stripVariants(resolved),
273
- useVariants: () => {},
273
+ // returns the styles, eg. for react-native-unistyles/metro
274
+ useVariants: () => stylesheet,
274
275
  }
276
+
277
+ return stylesheet
275
278
  },
276
279
  configure: (config: UnistylesConfig) => {
277
280
  if (config.breakpoints) {
@@ -6,14 +6,23 @@ import type { UseUpdateVariantColorConfig } from './types'
6
6
 
7
7
  import { UnistyleDependency } from '../../specs'
8
8
  import { services } from '../../web/services'
9
- import { getClosestBreakpointValue } from '../../web/utils'
9
+ import { getClosestBreakpointValue, isServer } from '../../web/utils'
10
+
11
+ // The first render paints this color on the server and in the browser, then the layout effect sets the real one.
12
+ // Matching the server lets the effect replace its HTML: Reanimated skips writing a value that didn't change
13
+ const INITIAL_COLOR = 'rgb(0, 0, 0)'
10
14
 
11
15
  export const useUpdateVariantColor = <T extends Record<string, any>>({
12
16
  animateCallback,
13
17
  colorKey,
14
18
  style,
15
19
  }: UseUpdateVariantColorConfig<T>) => {
20
+ // Resolves CSS variables to colors, there is no document on the server
16
21
  const [dummyDiv] = useState(() => {
22
+ if (isServer()) {
23
+ return undefined
24
+ }
25
+
17
26
  const div = document.createElement('div')
18
27
 
19
28
  div.style.display = 'none'
@@ -35,7 +44,8 @@ export const useUpdateVariantColor = <T extends Record<string, any>>({
35
44
  ? currentColor
36
45
  : (getClosestBreakpointValue<string>(services.runtime, currentColor) ?? 'rgb(0, 0, 0)')
37
46
 
38
- if (currentColorVar.startsWith('var(--')) {
47
+ // Called from effects only, which don't run on the server
48
+ if (currentColorVar.startsWith('var(--') && dummyDiv) {
39
49
  dummyDiv.style.color = currentColorVar
40
50
 
41
51
  return getComputedStyle(dummyDiv).color
@@ -43,8 +53,8 @@ export const useUpdateVariantColor = <T extends Record<string, any>>({
43
53
 
44
54
  return currentColorVar
45
55
  }, [style, colorKey])
46
- const fromValue = useSharedValue<string>(getCurrentColor())
47
- const toValue = useSharedValue<string>(getCurrentColor())
56
+ const fromValue = useSharedValue<string>(INITIAL_COLOR)
57
+ const toValue = useSharedValue<string>(INITIAL_COLOR)
48
58
 
49
59
  useEffect(() => {
50
60
  const dispose = services.listener.addListeners([UnistyleDependency.Theme], () => {
@@ -72,7 +82,7 @@ export const useUpdateVariantColor = <T extends Record<string, any>>({
72
82
  return () => dispose()
73
83
  }, [style, colorKey])
74
84
 
75
- useEffect(() => () => dummyDiv.remove(), [])
85
+ useEffect(() => () => dummyDiv?.remove(), [])
76
86
 
77
87
  return {
78
88
  fromValue,
@@ -3,10 +3,12 @@ import { NitroModules } from 'react-native-nitro-modules'
3
3
  import type { Scope } from '../../components/ScopedThemeContext'
4
4
  import type { VerifyReport } from '../../diagnostics/types'
5
5
  import type { Host } from '../../unifiber/src'
6
+ import type { FiberNode } from '../../unifiber/src/fiber'
6
7
  import type { UnistylesShadowRegistry as UnistylesShadowRegistrySpec } from './ShadowRegistry.nitro'
7
8
  import type { ShadowNode, Unistyle, ViewHandle } from './types'
8
9
 
9
10
  import { Fiber, Reanimated } from '../../unifiber/src'
11
+ import * as FiberInternals from '../../unifiber/src/fiber'
10
12
  import { StyleSheet } from '../StyleSheet'
11
13
  import { createUnistylesStyleSource } from './styleSource'
12
14
  import { traceSection } from './tracing'
@@ -24,12 +26,13 @@ interface ShadowRegistry extends UnistylesShadowRegistrySpec {
24
26
  getScopedTheme(): string | undefined
25
27
  verify(): VerifyReport
26
28
  takeCommittedInstanceHandles(): Array<any>
27
- refreshReactNodes(nodes: Array<ShadowNode>): void
29
+ refreshReactNodes(nodes: Array<ShadowNode>, includeUnpromoted: boolean): Array<number>
28
30
  }
29
31
 
30
32
  const HybridShadowRegistry = NitroModules.createHybridObject<ShadowRegistry>('UnistylesShadowRegistry')
31
33
 
32
34
  const { collectVisibleAncestors, getHostFor, getHostForInstanceHandle, getShadowNode, getShadowNodes, isHidden } = Fiber
35
+ const { committedOf, raw } = FiberInternals
33
36
 
34
37
  const { source: styleSource, bumpEpoch } = createUnistylesStyleSource({
35
38
  get: () => HybridShadowRegistry.getScopedTheme(),
@@ -47,9 +50,32 @@ const linkedHosts = new WeakMap<object, Host>()
47
50
 
48
51
  const committedHosts: Array<Host | undefined> = []
49
52
  let refreshNodes: Array<ShadowNode> = []
53
+ let refreshNodeHosts: Array<Host> = []
50
54
 
51
55
  const collectShadowNodes = (host: Host) => {
52
56
  getShadowNodes(host, refreshNodes)
57
+
58
+ while (refreshNodeHosts.length < refreshNodes.length) {
59
+ refreshNodeHosts.push(host)
60
+ }
61
+ }
62
+
63
+ const refreshUnmountedCommittedNodes = (unpromotedIndices: Array<number>) => {
64
+ const nodes: Array<ShadowNode> = []
65
+
66
+ for (let i = 0; i < unpromotedIndices.length; i++) {
67
+ const index = unpromotedIndices[i]!
68
+ const node = refreshNodes[index]
69
+ const committedFiber = raw(committedOf(refreshNodeHosts[index] as unknown as FiberNode))
70
+
71
+ if (node && committedFiber?.stateNode?.node === node) {
72
+ nodes.push(node)
73
+ }
74
+ }
75
+
76
+ if (nodes.length > 0) {
77
+ HybridShadowRegistry.refreshReactNodes(nodes, true)
78
+ }
53
79
  }
54
80
 
55
81
  // React re-attaches an untouched subtree through its root's node and only follows clones made on the JS thread.
@@ -72,13 +98,14 @@ const refreshReactNodes = () => {
72
98
  collectVisibleAncestors(committedHosts, collectShadowNodes)
73
99
 
74
100
  if (refreshNodes.length > 0) {
75
- HybridShadowRegistry.refreshReactNodes(refreshNodes)
101
+ refreshUnmountedCommittedNodes(HybridShadowRegistry.refreshReactNodes(refreshNodes, false))
76
102
  }
77
103
 
78
104
  traceSection('refreshOwners', () => owners.refresh(committedHosts))
79
105
  } finally {
80
106
  committedHosts.length = 0
81
107
  refreshNodes = []
108
+ refreshNodeHosts = []
82
109
  }
83
110
  }
84
111
 
@@ -8,6 +8,7 @@ import type { CreateUnistylesStyleSheet } from '../../types'
8
8
  import type { UnistylesStyleSheet as UnistylesStyleSheetSpec } from './UnistylesStyleSheet.nitro'
9
9
 
10
10
  import { parseBoxShadowString } from '../../core/parseBoxShadow'
11
+ import { TRACK_DEPENDENCIES } from '../../core/trackDependencies'
11
12
 
12
13
  type UnistylesThemeSettings =
13
14
  | {
@@ -48,7 +49,7 @@ export interface UnistylesStyleSheet extends UnistylesStyleSheetSpec {
48
49
  flatten: typeof NativeStyleSheetType.flatten
49
50
 
50
51
  // overridden methods
51
- init(): void
52
+ init(options: { trackDependencies: boolean }): void
52
53
  create: CreateUnistylesStyleSheet
53
54
  configure(config: UnistylesConfig): void
54
55
  jsMethods: {
@@ -69,7 +70,8 @@ HybridUnistylesStyleSheet.jsMethods = {
69
70
  parseBoxShadowString,
70
71
  }
71
72
 
72
- HybridUnistylesStyleSheet.init()
73
+ // without the Babel plugin (react-native-unistyles/metro), native records what every StyleSheet reads
74
+ HybridUnistylesStyleSheet.init({ trackDependencies: TRACK_DEPENDENCIES })
73
75
 
74
76
  type PrivateMethods = 'jsMethods' | 'init'
75
77
 
@@ -80,13 +80,14 @@ export type StyleSheetWithSuperPowers<S extends StyleSheet> =
80
80
  | ((theme: UnistylesTheme, miniRuntime: UnistylesMiniRuntime) => S)
81
81
  | S
82
82
 
83
- type UseVariantsFn<T> = {
84
- useVariants: (variants: ExtractVariantNames<T>) => void
83
+ type UseVariantsFn<S extends StyleSheet, T> = {
84
+ // returns the styles with the selected variants, react-native-unistyles/metro uses only the returned styles
85
+ useVariants: (variants: ExtractVariantNames<T>) => ReactNativeStyleSheet<S>
85
86
  }
86
87
 
87
88
  const create = <S extends StyleSheet>(
88
89
  stylesheet: StyleSheetWithSuperPowers<S>,
89
- ): ReactNativeStyleSheet<S> & UseVariantsFn<typeof stylesheet> =>
90
- stylesheet as ReactNativeStyleSheet<S> & UseVariantsFn<typeof stylesheet>
90
+ ): ReactNativeStyleSheet<S> & UseVariantsFn<S, typeof stylesheet> =>
91
+ stylesheet as ReactNativeStyleSheet<S> & UseVariantsFn<S, typeof stylesheet>
91
92
 
92
93
  export type CreateUnistylesStyleSheet = typeof create
@@ -101,8 +101,8 @@ export const convertUnistyles = (value: UnistylesValues, runtime: UnistylesRunti
101
101
  return getFontVariationSettings(unistylesValue)
102
102
  }
103
103
 
104
- // Breakpoints
105
- if (typeof unistylesValue === 'object' && unistylesValue !== null) {
104
+ // Breakpoints, arrays like fontVariant are regular values
105
+ if (typeof unistylesValue === 'object' && unistylesValue !== null && !Array.isArray(unistylesValue)) {
106
106
  return Object.entries(unistylesValue).map(([breakpointKey, breakpointValue]) => {
107
107
  return { [breakpointKey]: getBreakpointStyle(unistylesKey, breakpointValue) }
108
108
  })
@@ -121,6 +121,14 @@ const convertMap = {
121
121
  resizeMode: (value: string) => ({
122
122
  backgroundSize: value,
123
123
  }),
124
+ fontVariant: (value: string | Array<string>) => ({
125
+ fontVariant: Array.isArray(value) ? value.join(' ') : value,
126
+ }),
127
+ transformOrigin: (value: string | Array<string | number>) => ({
128
+ transformOrigin: Array.isArray(value)
129
+ ? value.map((origin) => convertNumber('transformOrigin', origin)).join(' ')
130
+ : value,
131
+ }),
124
132
  } as Record<PropertyKey, (value: any) => Record<string, any>>
125
133
 
126
134
  const convertNumber = (key: string, value: any) => {
package/src/web/create.ts CHANGED
@@ -5,14 +5,7 @@ import { assignSecrets, isServer, removeInlineStyles } from './utils'
5
5
 
6
6
  type Variants = Record<string, string | boolean | undefined>
7
7
 
8
- export const create = (stylesheet: StyleSheetWithSuperPowers<StyleSheet>) => {
9
- // For SSR
10
- if (!unistyles.services.state.isInitialized && !isServer()) {
11
- const config = window?.__UNISTYLES_STATE__?.config
12
-
13
- config && unistyles.services.state.init(config)
14
- }
15
-
8
+ const createStyleSheet = (stylesheet: StyleSheetWithSuperPowers<StyleSheet>) => {
16
9
  const computedStylesheet = unistyles.services.registry.getComputedStylesheet(stylesheet)
17
10
  const addSecrets = (
18
11
  value: any,
@@ -55,3 +48,47 @@ export const create = (stylesheet: StyleSheetWithSuperPowers<StyleSheet>) => {
55
48
 
56
49
  return createStyleSheetStyles()
57
50
  }
51
+
52
+ // On the server, a route can be loaded before StyleSheet.configure runs: Expo Router reads the matched route's
53
+ // metadata before rendering the document that imports the config. Such a StyleSheet is created on first use instead
54
+ const createOnFirstUse = (stylesheet: StyleSheetWithSuperPowers<StyleSheet>) => {
55
+ const styles = {} as ReturnType<typeof createStyleSheet>
56
+ let isCreated = false
57
+ // The styles fill the proxy's own target, so it behaves like the object create returns (writes, freeze...)
58
+ const getStyles = () => {
59
+ if (!isCreated) {
60
+ Object.assign(styles, createStyleSheet(stylesheet))
61
+ isCreated = true
62
+ }
63
+
64
+ return styles
65
+ }
66
+ // Reflect has a method for every proxy trap
67
+ const traps = Object.getOwnPropertyNames(Reflect) as Array<keyof ProxyHandler<object>>
68
+ const handler = Object.fromEntries(
69
+ traps.map((trap) => [
70
+ trap,
71
+ (_: object, ...args: Array<any>) => (Reflect[trap] as Function)(getStyles(), ...args),
72
+ ]),
73
+ )
74
+
75
+ return new Proxy(styles, handler)
76
+ }
77
+
78
+ export const create = (stylesheet: StyleSheetWithSuperPowers<StyleSheet>) => {
79
+ if (unistyles.services.state.isInitialized) {
80
+ return createStyleSheet(stylesheet)
81
+ }
82
+
83
+ // A plain object doesn't read the config, so it can be created right away
84
+ if (isServer()) {
85
+ return typeof stylesheet === 'function' ? createOnFirstUse(stylesheet) : createStyleSheet(stylesheet)
86
+ }
87
+
88
+ // For SSR
89
+ const config = window?.__UNISTYLES_STATE__?.config
90
+
91
+ config && unistyles.services.state.init(config)
92
+
93
+ return createStyleSheet(stylesheet)
94
+ }
@@ -4,6 +4,7 @@ import { isPseudoClass } from '../convert/pseudo'
4
4
  import { getMediaQuery } from '../utils'
5
5
 
6
6
  type SetProps = Parameters<CSSState['set']>[0]
7
+ type StyleTarget = Pick<CSSState, 'set'>
7
8
 
8
9
  // box-none and box-only aren't CSS values, polyfill them like react-native-web: [element, children]
9
10
  const POINTER_EVENTS: Record<string, [string, string]> = {
@@ -11,9 +12,22 @@ const POINTER_EVENTS: Record<string, [string, string]> = {
11
12
  'box-only': ['auto', 'none'],
12
13
  }
13
14
 
14
- export const getChildrenClassName = (className: string) => `:where(.${className})>*`
15
+ const CHILDREN_PREFIX = ':where(.'
16
+ const CHILDREN_SUFFIX = ')>*'
15
17
 
16
- const setStyle = (state: CSSState, props: SetProps) => {
18
+ export const getChildrenClassName = (className: string) => `${CHILDREN_PREFIX}${className}${CHILDREN_SUFFIX}`
19
+
20
+ // hash:hover, hash::before and :where(.hash)>* belong to hash. Hashes have no colons, a forChild one keeps ' > *'
21
+ export const getClassNameHash = (className: string) => {
22
+ const name = className.startsWith(CHILDREN_PREFIX)
23
+ ? className.slice(CHILDREN_PREFIX.length, -CHILDREN_SUFFIX.length)
24
+ : className
25
+ const pseudoIndex = name.indexOf(':')
26
+
27
+ return pseudoIndex === -1 ? name : name.slice(0, pseudoIndex)
28
+ }
29
+
30
+ const setStyle = (state: StyleTarget, props: SetProps) => {
17
31
  if (props.propertyKey !== 'pointerEvents') {
18
32
  state.set(props)
19
33
 
@@ -28,7 +42,7 @@ const setStyle = (state: CSSState, props: SetProps) => {
28
42
  state.set({ ...props, className: getChildrenClassName(props.className), value: childrenValue })
29
43
  }
30
44
 
31
- export const convertToCSS = (hash: string, value: Record<string, any>, state: CSSState) => {
45
+ export const convertToCSS = (hash: string, value: Record<string, any>, state: StyleTarget) => {
32
46
  Object.entries(value).forEach(([styleKey, styleValue]) => {
33
47
  if (styleKey[0] === '_') {
34
48
  const isStylePseudoClass = isPseudoClass(styleKey)