react-native-unistyles 3.0.0-alpha.29 → 3.0.0-alpha.30

Sign up to get free protection for your applications and to get access to all the features.
Files changed (191) hide show
  1. package/cxx/common/Helpers.h +11 -0
  2. package/cxx/core/HostStyle.cpp +1 -1
  3. package/cxx/core/UnistyleWrapper.h +9 -8
  4. package/cxx/core/UnistylesCommitHook.cpp +3 -14
  5. package/cxx/core/UnistylesCommitHook.h +5 -11
  6. package/cxx/core/UnistylesMountHook.cpp +0 -1
  7. package/cxx/core/UnistylesMountHook.h +0 -2
  8. package/cxx/core/UnistylesRegistry.cpp +1 -1
  9. package/cxx/core/UnistylesRegistry.h +1 -1
  10. package/cxx/hybridObjects/HybridStyleSheet.cpp +17 -11
  11. package/cxx/hybridObjects/HybridStyleSheet.h +1 -1
  12. package/cxx/parser/Parser.cpp +20 -14
  13. package/cxx/parser/Parser.h +1 -1
  14. package/cxx/shadowTree/ShadowTrafficController.h +4 -0
  15. package/cxx/shadowTree/ShadowTreeManager.cpp +3 -4
  16. package/cxx/shadowTree/ShadowTreeManager.h +1 -1
  17. package/ios/UnistylesModuleOnLoad.mm +4 -4
  18. package/lib/commonjs/common.js.map +1 -1
  19. package/lib/commonjs/core/createUnistylesComponent.js +18 -0
  20. package/lib/commonjs/core/createUnistylesComponent.js.map +1 -0
  21. package/lib/commonjs/core/createUnistylesComponent.native.js +45 -0
  22. package/lib/commonjs/core/createUnistylesComponent.native.js.map +2 -0
  23. package/lib/commonjs/core/index.js +7 -0
  24. package/lib/commonjs/core/index.js.map +1 -1
  25. package/lib/commonjs/core/useBreakpoint.js.map +1 -1
  26. package/lib/commonjs/core/useBreakpoint.native.js.map +2 -1
  27. package/lib/commonjs/core/useTheme.js.map +2 -1
  28. package/lib/commonjs/core/useTheme.native.js.map +2 -1
  29. package/lib/commonjs/global.js +3 -0
  30. package/lib/commonjs/index.js +8 -1
  31. package/lib/commonjs/index.js.map +1 -1
  32. package/lib/commonjs/mq.js +1 -4
  33. package/lib/commonjs/mq.js.map +2 -1
  34. package/lib/commonjs/specs/NativePlatform/NativePlatform.nitro.js +5 -4
  35. package/lib/commonjs/specs/NativePlatform/NativePlatform.nitro.js.map +1 -1
  36. package/lib/commonjs/specs/NativePlatform/index.js.map +1 -1
  37. package/lib/commonjs/specs/ShadowRegistry/types.js.map +1 -1
  38. package/lib/commonjs/specs/StatusBar/index.js.map +2 -1
  39. package/lib/commonjs/specs/TurboUnistyles/index.js.map +1 -1
  40. package/lib/commonjs/specs/UnistylesRuntime/index.js.map +1 -2
  41. package/lib/commonjs/specs/index.web.js.map +1 -2
  42. package/lib/commonjs/specs/types.js +10 -10
  43. package/lib/commonjs/specs/types.js.map +2 -1
  44. package/lib/commonjs/types/accessibility.js +9 -9
  45. package/lib/commonjs/types/accessibility.js.map +1 -1
  46. package/lib/commonjs/types/common.js +3 -0
  47. package/lib/commonjs/types/core.js.map +1 -1
  48. package/lib/commonjs/types/index.js.map +2 -1
  49. package/lib/commonjs/types/stylesheet.js +1 -2
  50. package/lib/commonjs/web/convert/index.js +1 -7
  51. package/lib/commonjs/web/convert/index.js.map +2 -1
  52. package/lib/commonjs/web/convert/pseudo.js.map +2 -1
  53. package/lib/commonjs/web/convert/shadow.js.map +2 -1
  54. package/lib/commonjs/web/convert/style.js.map +2 -1
  55. package/lib/commonjs/web/convert/textShadow.js +1 -4
  56. package/lib/commonjs/web/convert/textShadow.js.map +2 -1
  57. package/lib/commonjs/web/convert/transform.js.map +2 -1
  58. package/lib/commonjs/web/convert/utils.js +1 -2
  59. package/lib/commonjs/web/convert/utils.js.map +2 -1
  60. package/lib/commonjs/web/index.js.map +2 -1
  61. package/lib/commonjs/web/listener.js.map +2 -1
  62. package/lib/commonjs/web/mock.js.map +2 -1
  63. package/lib/commonjs/web/mq.js.map +1 -1
  64. package/lib/commonjs/web/registry.js +1 -3
  65. package/lib/commonjs/web/registry.js.map +2 -1
  66. package/lib/commonjs/web/runtime.js.map +2 -1
  67. package/lib/commonjs/web/shadowRegistry.js +1 -9
  68. package/lib/commonjs/web/shadowRegistry.js.map +2 -1
  69. package/lib/commonjs/web/state.js +1 -5
  70. package/lib/commonjs/web/state.js.map +2 -1
  71. package/lib/commonjs/web/utils/common.js +1 -3
  72. package/lib/commonjs/web/utils/common.js.map +2 -1
  73. package/lib/commonjs/web/utils/index.js.map +1 -1
  74. package/lib/commonjs/web/utils/unistyle.js.map +2 -1
  75. package/lib/commonjs/web/variants/index.js.map +1 -1
  76. package/lib/commonjs/web/variants/useVariants.js +1 -2
  77. package/lib/commonjs/web/variants/useVariants.js.map +2 -1
  78. package/lib/module/core/createUnistylesComponent.js +11 -0
  79. package/lib/module/core/createUnistylesComponent.js.map +2 -0
  80. package/lib/module/core/createUnistylesComponent.native.js +39 -0
  81. package/lib/module/core/createUnistylesComponent.native.js.map +1 -0
  82. package/lib/module/core/index.js +1 -0
  83. package/lib/module/core/index.js.map +1 -1
  84. package/lib/module/core/useBreakpoint.js.map +1 -1
  85. package/lib/module/core/useBreakpoint.native.js.map +2 -1
  86. package/lib/module/core/useTheme.js.map +2 -1
  87. package/lib/module/core/useTheme.native.js.map +2 -1
  88. package/lib/module/global.js +1 -1
  89. package/lib/module/global.js.map +1 -0
  90. package/lib/module/index.js +1 -1
  91. package/lib/module/index.js.map +1 -1
  92. package/lib/module/mq.js +1 -4
  93. package/lib/module/mq.js.map +2 -1
  94. package/lib/module/specs/NativePlatform/NativePlatform.nitro.js.map +1 -1
  95. package/lib/module/specs/NativePlatform/index.js.map +1 -1
  96. package/lib/module/specs/NavigtionBar/index.js.map +2 -1
  97. package/lib/module/specs/ShadowRegistry/ShadowRegistry.nitro.js.map +1 -2
  98. package/lib/module/specs/ShadowRegistry/index.js.map +2 -1
  99. package/lib/module/specs/ShadowRegistry/types.js.map +2 -1
  100. package/lib/module/specs/StatusBar/UnistylesStatusBar.nitro.js.map +1 -2
  101. package/lib/module/specs/StatusBar/index.js.map +1 -1
  102. package/lib/module/specs/StyleSheet/UnistylesStyleSheet.nitro.js +1 -1
  103. package/lib/module/specs/StyleSheet/UnistylesStyleSheet.nitro.js.map +0 -1
  104. package/lib/module/specs/StyleSheet/index.js.map +2 -1
  105. package/lib/module/specs/TurboUnistyles/NativeTurboUnistyles.js +3 -2
  106. package/lib/module/specs/TurboUnistyles/NativeTurboUnistyles.js.map +2 -1
  107. package/lib/module/specs/UnistylesRuntime/UnistylesRuntime.nitro.js.map +2 -1
  108. package/lib/module/specs/index.js.map +1 -2
  109. package/lib/module/specs/types.js.map +1 -2
  110. package/lib/module/types/accessibility.js +1 -1
  111. package/lib/module/types/accessibility.js.map +1 -0
  112. package/lib/module/types/breakpoints.js.map +1 -0
  113. package/lib/module/types/common.js +1 -1
  114. package/lib/module/types/common.js.map +1 -0
  115. package/lib/module/types/core.js.map +1 -1
  116. package/lib/module/types/index.js.map +2 -1
  117. package/lib/module/types/variants.js.map +1 -0
  118. package/lib/module/web/convert/index.js.map +2 -1
  119. package/lib/module/web/convert/pseudo.js.map +2 -1
  120. package/lib/module/web/convert/shadow.js +1 -5
  121. package/lib/module/web/convert/utils.js +1 -2
  122. package/lib/module/web/index.js +1 -2
  123. package/lib/module/web/index.js.map +2 -1
  124. package/lib/module/web/listener.js.map +2 -1
  125. package/lib/module/web/mock.js.map +2 -1
  126. package/lib/module/web/state.js +1 -5
  127. package/lib/module/web/state.js.map +2 -1
  128. package/lib/module/web/variants/getVariants.js.map +2 -1
  129. package/lib/module/web/variants/index.js.map +1 -1
  130. package/lib/module/web/variants/useVariants.js +1 -2
  131. package/lib/module/web/variants/useVariants.js.map +2 -1
  132. package/lib/typescript/src/core/createUnistylesComponent.d.ts +6 -0
  133. package/lib/typescript/src/core/createUnistylesComponent.d.ts.map +1 -0
  134. package/lib/typescript/src/core/createUnistylesComponent.native.d.ts +6 -0
  135. package/lib/typescript/src/core/createUnistylesComponent.native.d.ts.map +1 -0
  136. package/lib/typescript/src/core/index.d.ts +1 -0
  137. package/lib/typescript/src/core/index.d.ts.map +1 -1
  138. package/lib/typescript/src/index.d.ts +1 -1
  139. package/lib/typescript/src/index.d.ts.map +1 -1
  140. package/nitrogen/generated/android/c++/JHybridNativePlatformSpec.cpp +1 -1
  141. package/nitrogen/generated/android/c++/JUnistylesNativeMiniRuntime.hpp +3 -3
  142. package/nitrogen/generated/android/unistyles+autolinking.cmake +13 -1
  143. package/nitrogen/generated/ios/Unistyles-Swift-Cxx-Bridge.hpp +4 -10
  144. package/package.json +3 -3
  145. package/src/common.js +4 -0
  146. package/src/core/createUnistylesComponent.js +6 -0
  147. package/src/core/createUnistylesComponent.native.js +31 -0
  148. package/src/core/createUnistylesComponent.native.tsx +44 -0
  149. package/src/core/createUnistylesComponent.tsx +10 -0
  150. package/src/core/index.js +3 -0
  151. package/src/core/index.ts +1 -0
  152. package/src/core/useBreakpoint.js +14 -0
  153. package/src/core/useBreakpoint.native.js +16 -0
  154. package/src/core/useTheme.js +14 -0
  155. package/src/core/useTheme.native.js +16 -0
  156. package/src/global.js +1 -0
  157. package/src/index.js +3 -0
  158. package/src/index.ts +1 -1
  159. package/src/mq.js +38 -0
  160. package/src/specs/NativePlatform/NativePlatform.nitro.js +1 -0
  161. package/src/types/accessibility.js +30 -0
  162. package/src/types/breakpoints.js +1 -0
  163. package/src/types/common.js +1 -0
  164. package/src/types/core.js +1 -0
  165. package/src/types/index.js +1 -0
  166. package/src/types/stylesheet.js +2 -0
  167. package/src/types/variants.js +1 -0
  168. package/src/web/convert/boxShadow.js +59 -0
  169. package/src/web/convert/index.js +56 -0
  170. package/src/web/convert/pseudo.js +131 -0
  171. package/src/web/convert/shadow.js +50 -0
  172. package/src/web/convert/style.js +137 -0
  173. package/src/web/convert/textShadow.js +56 -0
  174. package/src/web/convert/transform.js +65 -0
  175. package/src/web/convert/types.js +2 -0
  176. package/src/web/convert/utils.js +39 -0
  177. package/src/web/create.js +36 -0
  178. package/src/web/index.js +22 -0
  179. package/src/web/listener.js +26 -0
  180. package/src/web/mock.js +21 -0
  181. package/src/web/mq.js +14 -0
  182. package/src/web/registry.js +165 -0
  183. package/src/web/runtime.js +160 -0
  184. package/src/web/shadowRegistry.js +96 -0
  185. package/src/web/state.js +68 -0
  186. package/src/web/utils/common.js +79 -0
  187. package/src/web/utils/index.js +2 -0
  188. package/src/web/utils/unistyle.js +72 -0
  189. package/src/web/variants/getVariants.js +26 -0
  190. package/src/web/variants/index.js +2 -0
  191. package/src/web/variants/useVariants.js +50 -0
@@ -0,0 +1,56 @@
1
+ import { deepMergeObjects, warn } from '../utils';
2
+ import { validateShadow } from './shadow';
3
+ import { TEXT_SHADOW_STYLES } from './types';
4
+ import { extractShadowValue, normalizeColor, normalizeNumericValue } from './utils';
5
+ const createTextShadowValue = (style) => {
6
+ const { textShadowColor, textShadowOffset, textShadowRadius } = style;
7
+ const offsetX = normalizeNumericValue(textShadowOffset.width);
8
+ const offsetY = normalizeNumericValue(textShadowOffset.height);
9
+ const radius = normalizeNumericValue(textShadowRadius);
10
+ const color = normalizeColor(textShadowColor);
11
+ return `${offsetX} ${offsetY} ${radius} ${color}`;
12
+ };
13
+ export const getTextShadowStyle = (styles) => {
14
+ const missingStyles = TEXT_SHADOW_STYLES.filter(key => !(key in styles));
15
+ if (missingStyles.length) {
16
+ warn(`can't apply text shadow as you miss these properties: ${missingStyles.join(', ')}`);
17
+ return {};
18
+ }
19
+ const breakpointsSet = new Set();
20
+ try {
21
+ validateShadow(TEXT_SHADOW_STYLES, styles, breakpointsSet);
22
+ }
23
+ catch (error) {
24
+ if (typeof error === 'string') {
25
+ warn(error);
26
+ }
27
+ return {};
28
+ }
29
+ const breakpoints = Array.from(breakpointsSet);
30
+ // If no breakpoints were used return styles without media queries
31
+ if (breakpoints.length === 0) {
32
+ return {
33
+ textShadow: createTextShadowValue(styles)
34
+ };
35
+ }
36
+ // Create textShadow for each breakpoint
37
+ const breakpointStyles = breakpoints.map(breakpoint => {
38
+ const color = extractShadowValue('textShadowColor', breakpoint, styles);
39
+ const { width, height } = extractShadowValue('textShadowOffset', breakpoint, styles);
40
+ const radius = extractShadowValue('textShadowRadius', breakpoint, styles);
41
+ return {
42
+ [breakpoint]: {
43
+ textShadow: createTextShadowValue({
44
+ textShadowColor: color,
45
+ textShadowOffset: {
46
+ width,
47
+ height
48
+ },
49
+ textShadowRadius: radius
50
+ })
51
+ }
52
+ };
53
+ });
54
+ // Merge all breakpoints styles into one
55
+ return deepMergeObjects(...breakpointStyles);
56
+ };
@@ -0,0 +1,65 @@
1
+ import { deepMergeObjects, keyInObject } from '../utils';
2
+ import { normalizeNumericValue } from './utils';
3
+ const normalizeTransform = (key, value) => {
4
+ if (key.includes('scale')) {
5
+ return value;
6
+ }
7
+ if (typeof value === 'number') {
8
+ return normalizeNumericValue(value);
9
+ }
10
+ return value;
11
+ };
12
+ const createTransformValue = (transforms) => transforms
13
+ .map(transform => {
14
+ const [key] = Object.keys(transform);
15
+ if (!key) {
16
+ return undefined;
17
+ }
18
+ const value = transform[key];
19
+ switch (key) {
20
+ case 'matrix':
21
+ case 'matrix3d':
22
+ return `${key}(${value.join(',')})`;
23
+ default:
24
+ return `${key}(${normalizeTransform(key, value)})`;
25
+ }
26
+ })
27
+ .filter(Boolean)
28
+ .join(' ');
29
+ export const getTransformStyle = (transforms) => {
30
+ const breakpoints = new Set();
31
+ const normalTransforms = [];
32
+ transforms.forEach(transform => {
33
+ const [property] = Object.keys(transform);
34
+ if (!property) {
35
+ return;
36
+ }
37
+ const value = transform[property];
38
+ if (typeof value === 'object' && !Array.isArray(value)) {
39
+ Object.keys(value).forEach(breakpoint => breakpoints.add(breakpoint));
40
+ return;
41
+ }
42
+ normalTransforms.push(transform);
43
+ });
44
+ const breakpointTransforms = Array.from(breakpoints).flatMap(breakpoint => {
45
+ const transformsPerBreakpoint = transforms.flatMap(transform => {
46
+ const [property] = Object.keys(transform);
47
+ if (!property) {
48
+ return [];
49
+ }
50
+ const value = transform[property];
51
+ if (typeof value === 'object' && !Array.isArray(value)) {
52
+ return keyInObject(value, breakpoint) ? [{ [property]: value[breakpoint] }] : [];
53
+ }
54
+ return [];
55
+ });
56
+ return [{
57
+ [breakpoint]: {
58
+ transform: createTransformValue(transformsPerBreakpoint)
59
+ }
60
+ }];
61
+ });
62
+ return deepMergeObjects({
63
+ transform: createTransformValue(normalTransforms)
64
+ }, ...breakpointTransforms);
65
+ };
@@ -0,0 +1,2 @@
1
+ export const TEXT_SHADOW_STYLES = ['textShadowColor', 'textShadowOffset', 'textShadowRadius'];
2
+ export const BOX_SHADOW_STYLES = ['shadowColor', 'shadowRadius', 'shadowOpacity', 'shadowOffset'];
@@ -0,0 +1,39 @@
1
+ // based on react-native-web normalizer
2
+ // https://github.com/necolas/react-native-web
3
+ import normalizeColors from '@react-native/normalize-colors';
4
+ import { BOX_SHADOW_STYLES, TEXT_SHADOW_STYLES } from './types';
5
+ export const isTransform = (key, value) => key === 'transform' && Array.isArray(value);
6
+ export const isTextShadow = (key) => TEXT_SHADOW_STYLES.includes(key);
7
+ export const isBoxShadow = (key) => BOX_SHADOW_STYLES.includes(key);
8
+ export const normalizeNumericValue = (value) => value ? `${value}px` : value;
9
+ export const normalizeColor = (color, opacity = 1) => {
10
+ // If the opacity is 1 there's no need to normalize the color
11
+ if (opacity === 1) {
12
+ return color;
13
+ }
14
+ const integer = normalizeColors(color);
15
+ // If the color is an unknown format, the return value is null
16
+ if (integer === null) {
17
+ return color;
18
+ }
19
+ const hex = integer.toString(16).padStart(8, '0');
20
+ if (hex.length === 8) {
21
+ const [r = 0, g = 0, b = 0, a = 1] = hex
22
+ .split(/(?=(?:..)*$)/)
23
+ .map(x => parseInt(x, 16))
24
+ .filter(num => !isNaN(num));
25
+ return `rgba(${r},${g},${b},${(a / 255) * opacity})`;
26
+ }
27
+ return color;
28
+ };
29
+ export const extractShadowValue = (key, breakpoint, styles) => {
30
+ const value = styles[key];
31
+ if (key === 'textShadowOffset' || key === 'shadowOffset') {
32
+ const { width, height } = value;
33
+ return {
34
+ width: typeof width === 'object' ? width[breakpoint] : width,
35
+ height: typeof height === 'object' ? height[breakpoint] : height
36
+ };
37
+ }
38
+ return typeof value === 'object' ? value[breakpoint] : value;
39
+ };
@@ -0,0 +1,36 @@
1
+ import { assignSecrets, reduceObject, getStyles, deepMergeObjects } from './utils';
2
+ import { UnistylesRuntime } from './runtime';
3
+ import { createUseVariants, getVariants } from './variants';
4
+ export const create = (stylesheet) => {
5
+ const computedStylesheet = typeof stylesheet === 'function'
6
+ ? stylesheet(UnistylesRuntime.theme, UnistylesRuntime.miniRuntime)
7
+ : stylesheet;
8
+ const selectedVariants = new Map();
9
+ const copyVariants = () => Object.fromEntries(selectedVariants.entries());
10
+ const addSecrets = (value, key, args) => assignSecrets(value, {
11
+ __uni__key: key,
12
+ __uni__refs: new Set(),
13
+ __uni__stylesheet: stylesheet,
14
+ __uni__args: args,
15
+ __uni__variants: copyVariants()
16
+ });
17
+ const styles = reduceObject(computedStylesheet, (value, _key) => {
18
+ const key = String(_key);
19
+ if (typeof value === 'function') {
20
+ const dynamicStyle = (...args) => {
21
+ const result = value(...args);
22
+ const variants = Object.fromEntries(getVariants({ [key]: result }, copyVariants()));
23
+ const resultWithVariants = deepMergeObjects(result, variants[key] ?? {});
24
+ // Add secrets to result of dynamic styles function
25
+ return addSecrets(getStyles(resultWithVariants), key, args);
26
+ };
27
+ // Add secrets to dynamic styles function
28
+ return addSecrets(dynamicStyle, key);
29
+ }
30
+ // Add secrets to static styles
31
+ return addSecrets(getStyles(value), key);
32
+ });
33
+ // Inject useVariants hook to styles
34
+ createUseVariants(styles, newVariants => Object.entries(newVariants).forEach(([key, value]) => selectedVariants.set(key, value)));
35
+ return styles;
36
+ };
@@ -0,0 +1,22 @@
1
+ import { create } from './create';
2
+ import { UnistylesState } from './state';
3
+ import { deepMergeObjects } from './utils';
4
+ export const StyleSheet = {
5
+ configure: UnistylesState.init,
6
+ create,
7
+ absoluteFill: {
8
+ position: 'absolute',
9
+ left: 0,
10
+ top: 0,
11
+ right: 0,
12
+ bottom: 0,
13
+ },
14
+ compose: (a, b) => deepMergeObjects(a, b),
15
+ flatten: (...styles) => deepMergeObjects(...styles),
16
+ hairlineWidth: 1
17
+ };
18
+ export { UnistylesRuntime } from './runtime';
19
+ export { UnistylesShadowRegistry } from './shadowRegistry';
20
+ export * from './mock';
21
+ // TODO: Work on SSR
22
+ export const getSSRUnistyles = () => [];
@@ -0,0 +1,26 @@
1
+ import { UnistyleDependency } from '../specs/NativePlatform';
2
+ import { UnistylesRuntime } from './runtime';
3
+ class UnistylesListenerBuilder {
4
+ isInitialized = false;
5
+ listeners = Array.from({ length: Object.keys(UnistyleDependency).length / 2 }, () => new Set());
6
+ emitChange = (dependency) => {
7
+ this.listeners[dependency]?.forEach(listener => listener());
8
+ };
9
+ initListeners = () => {
10
+ if (this.isInitialized) {
11
+ return;
12
+ }
13
+ this.isInitialized = true;
14
+ UnistylesRuntime.darkMedia?.addEventListener('change', () => this.emitChange(UnistyleDependency.ColorScheme));
15
+ UnistylesRuntime.lightMedia?.addEventListener('change', () => this.emitChange(UnistyleDependency.ColorScheme));
16
+ window.addEventListener('orientationchange', () => this.emitChange(UnistyleDependency.Orientation));
17
+ window.addEventListener('resize', () => this.emitChange(UnistyleDependency.Dimensions));
18
+ };
19
+ addListeners = (dependencies, listener) => {
20
+ dependencies.forEach(dependency => this.listeners[dependency]?.add(listener));
21
+ return () => {
22
+ dependencies.forEach(dependency => this.listeners[dependency]?.delete(listener));
23
+ };
24
+ };
25
+ }
26
+ export const UnistylesListener = new UnistylesListenerBuilder();
@@ -0,0 +1,21 @@
1
+ export const StatusBar = {
2
+ width: 0,
3
+ height: 0,
4
+ setStyle: () => { },
5
+ setHidden: () => { },
6
+ setBackgroundColor: () => { },
7
+ equals: () => true,
8
+ toString: () => 'StatusBar',
9
+ __type: 'web',
10
+ name: 'StatusBar'
11
+ };
12
+ export const NavigationBar = {
13
+ width: 0,
14
+ height: 0,
15
+ setHidden: () => { },
16
+ setBackgroundColor: () => { },
17
+ equals: () => true,
18
+ toString: () => 'NavigationBar',
19
+ __type: 'web',
20
+ name: 'NavigationBar'
21
+ };
package/src/web/mq.js ADDED
@@ -0,0 +1,14 @@
1
+ const IS_UNISTYLES_REGEX = /:([hw])\[(\d+)(?:,\s*(\d+|Infinity))?]/;
2
+ const UNISTYLES_WIDTH_REGEX = /:(w)\[(\d+)(?:,\s*(\d+|Infinity))?]/;
3
+ const UNISTYLES_HEIGHT_REGEX = /:(h)\[(\d+)(?:,\s*(\d+|Infinity))?]/;
4
+ export const parseMq = (mq) => {
5
+ const [, width, fromW, toW] = UNISTYLES_WIDTH_REGEX.exec(mq) || [];
6
+ const [, height, fromH, toH] = UNISTYLES_HEIGHT_REGEX.exec(mq) || [];
7
+ return {
8
+ minWidth: !width || fromW === 'Infinity' ? undefined : Number(fromW),
9
+ maxWidth: !width || toW === 'Infinity' ? undefined : Number(toW),
10
+ minHeight: !height || fromH === 'Infinity' ? undefined : Number(fromH),
11
+ maxHeight: !height || toH === 'Infinity' ? undefined : Number(toH),
12
+ };
13
+ };
14
+ export const isUnistylesMq = (mq) => IS_UNISTYLES_REGEX.test(mq);
@@ -0,0 +1,165 @@
1
+ import { UnistylesRuntime } from './runtime';
2
+ import { extractMediaQueryValue, keyInObject, getMediaQuery, generateHash, extractUnistyleDependencies, deepMergeObjects } from './utils';
3
+ import { UnistylesListener } from './listener';
4
+ import { convertUnistyles } from './convert';
5
+ import { getVariants } from './variants';
6
+ class UnistylesRegistryBuilder {
7
+ stylesheets = new Map();
8
+ stylesCounter = new Map();
9
+ #styleTag = null;
10
+ disposeListenersMap = new Map();
11
+ dependenciesMap = new Map();
12
+ get styleTag() {
13
+ const tag = this.#styleTag;
14
+ if (!tag) {
15
+ const newTag = document.createElement('style');
16
+ newTag.id = 'unistyles-web';
17
+ this.#styleTag = newTag;
18
+ document.head.appendChild(newTag);
19
+ return newTag;
20
+ }
21
+ return tag;
22
+ }
23
+ getComputedStylesheet = (stylesheet) => {
24
+ if (typeof stylesheet !== 'function') {
25
+ return stylesheet;
26
+ }
27
+ const computedStylesheet = this.stylesheets.get(stylesheet);
28
+ if (computedStylesheet) {
29
+ return computedStylesheet;
30
+ }
31
+ const createdStylesheet = stylesheet(UnistylesRuntime.theme, UnistylesRuntime.miniRuntime);
32
+ const dependencies = Object.values(createdStylesheet).flatMap(value => extractUnistyleDependencies(value));
33
+ this.addDependenciesToStylesheet(stylesheet, dependencies);
34
+ this.stylesheets.set(stylesheet, createdStylesheet);
35
+ return createdStylesheet;
36
+ };
37
+ addDependenciesToStylesheet = (stylesheet, dependencies) => {
38
+ this.disposeListenersMap.get(stylesheet)?.();
39
+ const dependenciesMap = this.dependenciesMap.get(stylesheet) ?? new Set(dependencies);
40
+ dependencies.forEach(dependency => dependenciesMap.add(dependency));
41
+ const dispose = UnistylesListener.addListeners(Array.from(dependenciesMap), () => {
42
+ const newComputedStylesheet = stylesheet(UnistylesRuntime.theme, UnistylesRuntime.miniRuntime);
43
+ this.stylesheets.set(stylesheet, newComputedStylesheet);
44
+ });
45
+ this.dependenciesMap.set(stylesheet, dependenciesMap);
46
+ this.disposeListenersMap.set(stylesheet, dispose);
47
+ };
48
+ add = ({ key, value, stylesheet, args, variants }) => {
49
+ const hash = generateHash(value);
50
+ const existingCounter = this.stylesCounter.get(hash);
51
+ if (!existingCounter || existingCounter.size === 0) {
52
+ const counter = new Set();
53
+ const dependencies = extractUnistyleDependencies(value);
54
+ counter.add(value);
55
+ this.stylesCounter.set(hash, counter);
56
+ this.applyStyles(hash, convertUnistyles(value));
57
+ UnistylesListener.addListeners(dependencies, async () => {
58
+ // Move this callback to the end of the event loop
59
+ await Promise.resolve();
60
+ const newComputedStyleSheet = this.getComputedStylesheet(stylesheet);
61
+ const newValue = newComputedStyleSheet[key];
62
+ const result = typeof newValue === 'function'
63
+ ? newValue(...args)
64
+ : newValue;
65
+ const { variantsResult } = Object.fromEntries(getVariants({ variantsResult: result }, variants));
66
+ const resultWithVariants = deepMergeObjects(result, variantsResult ?? {});
67
+ this.applyStyles(hash, convertUnistyles(resultWithVariants));
68
+ });
69
+ return hash;
70
+ }
71
+ existingCounter.add(value);
72
+ return hash;
73
+ };
74
+ applyStyles = (hash, styles) => {
75
+ Object.entries(styles).forEach(([key, value]) => {
76
+ if (!this.styleTag.sheet) {
77
+ return;
78
+ }
79
+ if (typeof value === 'object' && !key.startsWith('_')) {
80
+ const mediaQuery = getMediaQuery(key);
81
+ const cssRules = Array.from(this.styleTag.sheet.cssRules);
82
+ let queryRule = cssRules.find(rule => {
83
+ if (!(rule instanceof CSSMediaRule)) {
84
+ return false;
85
+ }
86
+ return rule.media.item(0)?.includes(mediaQuery);
87
+ }) ?? null;
88
+ if (!queryRule) {
89
+ const mediaQueryValue = extractMediaQueryValue(mediaQuery);
90
+ const ruleIndex = mediaQueryValue
91
+ ? cssRules.reduce((acc, rule, ruleIndex) => {
92
+ if (!(rule instanceof CSSMediaRule)) {
93
+ return acc;
94
+ }
95
+ const ruleMediaQueryValue = extractMediaQueryValue(rule.conditionText);
96
+ if (ruleMediaQueryValue === undefined) {
97
+ return;
98
+ }
99
+ return ruleMediaQueryValue > mediaQueryValue ? ruleIndex : acc;
100
+ }, cssRules.length)
101
+ : undefined;
102
+ queryRule = this.styleTag.sheet.cssRules.item(this.styleTag.sheet.insertRule(`@media ${mediaQuery} {.${hash} {}}`, ruleIndex));
103
+ }
104
+ if (queryRule instanceof CSSMediaRule) {
105
+ Object.entries(value).forEach(([mqKey, mqValue]) => {
106
+ this.applyRule({
107
+ hash,
108
+ key: mqKey,
109
+ value: mqValue,
110
+ sheet: queryRule
111
+ });
112
+ });
113
+ }
114
+ return;
115
+ }
116
+ // Pseudo
117
+ if (typeof value === 'object') {
118
+ Object.entries(value).forEach(([pseudoKey, pseudoValue]) => {
119
+ this.applyRule({
120
+ hash: `${hash}${key.replace('_', ':')}`,
121
+ key: pseudoKey,
122
+ value: pseudoValue,
123
+ sheet: this.styleTag.sheet
124
+ });
125
+ });
126
+ return;
127
+ }
128
+ this.applyRule({
129
+ hash,
130
+ key,
131
+ value,
132
+ sheet: this.styleTag.sheet
133
+ });
134
+ });
135
+ };
136
+ applyRule = ({ hash, key, value, sheet }) => {
137
+ let rule = Array.from(sheet.cssRules).find(rule => {
138
+ if (!(rule instanceof CSSStyleRule)) {
139
+ return false;
140
+ }
141
+ // In unistyles pseudos are prefixed with ':' but in css some of them are prefixed with '::'
142
+ return rule.selectorText.replace('::', ':').includes(hash);
143
+ }) ?? null;
144
+ if (!rule) {
145
+ rule = sheet.cssRules.item(sheet.insertRule(`.${hash} {}`));
146
+ }
147
+ if (!(rule instanceof CSSStyleRule) || !keyInObject(rule.style, key)) {
148
+ return;
149
+ }
150
+ rule.style[key] = value;
151
+ };
152
+ remove = (value) => {
153
+ const hash = generateHash(value);
154
+ const existingStyles = this.stylesCounter.get(hash);
155
+ if (!existingStyles) {
156
+ return;
157
+ }
158
+ existingStyles.delete(value);
159
+ if (existingStyles.size === 0) {
160
+ const ruleIndex = Array.from(this.styleTag.sheet?.cssRules ?? []).findIndex(rule => rule.cssText.includes(`.${hash}`));
161
+ this.styleTag.sheet?.deleteRule(ruleIndex);
162
+ }
163
+ };
164
+ }
165
+ export const UnistylesRegistry = new UnistylesRegistryBuilder();
@@ -0,0 +1,160 @@
1
+ import { UnistyleDependency } from '../specs/NativePlatform';
2
+ import { ColorScheme, Orientation } from '../specs/types';
3
+ import { WebContentSizeCategory } from '../types';
4
+ import { UnistylesListener } from './listener';
5
+ import { NavigationBar, StatusBar } from './mock';
6
+ import { UnistylesState } from './state';
7
+ import { hexToRGBA, isServer, schemeToTheme } from './utils';
8
+ class UnistylesRuntimeBuilder {
9
+ lightMedia = this.getLightMedia();
10
+ darkMedia = this.getDarkMedia();
11
+ getLightMedia() {
12
+ if (isServer()) {
13
+ return null;
14
+ }
15
+ if (!this.lightMedia) {
16
+ this.lightMedia = window.matchMedia('(prefers-color-scheme: light)');
17
+ }
18
+ return this.lightMedia;
19
+ }
20
+ getDarkMedia() {
21
+ if (isServer()) {
22
+ return null;
23
+ }
24
+ if (!this.darkMedia) {
25
+ this.darkMedia = window.matchMedia('(prefers-color-scheme: dark)');
26
+ }
27
+ return this.darkMedia;
28
+ }
29
+ get colorScheme() {
30
+ switch (true) {
31
+ case this.getLightMedia()?.matches:
32
+ return ColorScheme.Light;
33
+ case this.getDarkMedia()?.matches:
34
+ return ColorScheme.Dark;
35
+ default:
36
+ return ColorScheme.Unspecified;
37
+ }
38
+ }
39
+ get themeName() {
40
+ return UnistylesState.themeName;
41
+ }
42
+ get contentSizeCategory() {
43
+ return WebContentSizeCategory.Unspecified;
44
+ }
45
+ get breakpoint() {
46
+ return UnistylesState.breakpoint;
47
+ }
48
+ get orientation() {
49
+ if (isServer()) {
50
+ return Orientation.Portrait;
51
+ }
52
+ return screen.orientation.type.includes('portrait') ? Orientation.Portrait : Orientation.Landscape;
53
+ }
54
+ get theme() {
55
+ return this.getTheme(this.themeName);
56
+ }
57
+ get pixelRatio() {
58
+ return isServer() ? 1 : window.devicePixelRatio;
59
+ }
60
+ get screen() {
61
+ if (isServer()) {
62
+ return {
63
+ width: 0,
64
+ height: 0
65
+ };
66
+ }
67
+ return {
68
+ width: window.innerWidth,
69
+ height: window.innerHeight
70
+ };
71
+ }
72
+ get fontScale() {
73
+ return 1;
74
+ }
75
+ get insets() {
76
+ return {
77
+ top: 0,
78
+ bottom: 0,
79
+ left: 0,
80
+ right: 0,
81
+ ime: 0
82
+ };
83
+ }
84
+ get statusBar() {
85
+ return StatusBar;
86
+ }
87
+ get rtl() {
88
+ return isServer() ? true : document.documentElement.dir === 'rtl';
89
+ }
90
+ get hasAdaptiveThemes() {
91
+ return UnistylesState.hasAdaptiveThemes;
92
+ }
93
+ get navigationBar() {
94
+ return NavigationBar;
95
+ }
96
+ get miniRuntime() {
97
+ return {
98
+ colorScheme: this.colorScheme,
99
+ themeName: this.themeName,
100
+ contentSizeCategory: this.contentSizeCategory,
101
+ breakpoint: this.breakpoint,
102
+ isLandscape: this.orientation === Orientation.Landscape,
103
+ isPortrait: this.orientation === Orientation.Portrait,
104
+ pixelRatio: this.pixelRatio,
105
+ screen: this.screen,
106
+ fontScale: this.fontScale,
107
+ insets: this.insets,
108
+ statusBar: {
109
+ width: this.statusBar.width,
110
+ height: this.statusBar.height
111
+ },
112
+ navigationBar: {
113
+ width: this.navigationBar.width,
114
+ height: this.navigationBar.height,
115
+ },
116
+ rtl: this.rtl,
117
+ hasAdaptiveThemes: this.hasAdaptiveThemes
118
+ };
119
+ }
120
+ setTheme = (themeName) => {
121
+ if (themeName === UnistylesRuntime.themeName) {
122
+ return;
123
+ }
124
+ UnistylesState.themeName = themeName;
125
+ UnistylesListener.emitChange(UnistyleDependency.Theme);
126
+ UnistylesListener.emitChange(UnistyleDependency.ThemeName);
127
+ };
128
+ setAdaptiveThemes = (isEnabled) => {
129
+ UnistylesState.hasAdaptiveThemes = isEnabled;
130
+ if (!isEnabled) {
131
+ return;
132
+ }
133
+ this.setTheme(schemeToTheme(UnistylesRuntime.colorScheme));
134
+ };
135
+ setRootViewBackgroundColor = (hex, alpha) => {
136
+ if (isServer()) {
137
+ return;
138
+ }
139
+ document.documentElement.style.backgroundColor = alpha ? hexToRGBA(hex, alpha) : hex;
140
+ };
141
+ setImmersiveMode = () => { };
142
+ updateTheme = (themeName, updater) => {
143
+ const oldTheme = UnistylesState.themes.get(themeName);
144
+ if (!oldTheme) {
145
+ throw new Error(`🦄 Theme "${themeName}" is not registered!`);
146
+ }
147
+ UnistylesState.themes.set(themeName, updater(oldTheme));
148
+ };
149
+ getTheme = (themeName = this.themeName) => {
150
+ if (!themeName) {
151
+ throw new Error('🦄 No theme selected!');
152
+ }
153
+ const theme = UnistylesState.themes.get(themeName);
154
+ if (!theme) {
155
+ throw new Error(`🦄 Theme "${this.themeName}" is not registered!`);
156
+ }
157
+ return theme;
158
+ };
159
+ }
160
+ export const UnistylesRuntime = new UnistylesRuntimeBuilder();