@umber-style/react-native 0.1.0-alpha.0 → 0.1.0-alpha.2

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 (43) hide show
  1. package/dist/CacheProvider.cjs +7 -0
  2. package/dist/CacheProvider.d.cts +4 -0
  3. package/dist/CacheProvider.d.mts +4 -0
  4. package/dist/CacheProvider.mjs +7 -0
  5. package/dist/ThemeValue.cjs +32 -15
  6. package/dist/ThemeValue.mjs +33 -16
  7. package/dist/calc.cjs +11 -8
  8. package/dist/calc.mjs +11 -8
  9. package/dist/createStyle.cjs +133 -29
  10. package/dist/createStyle.d.cts +7 -9
  11. package/dist/createStyle.d.mts +7 -9
  12. package/dist/createStyle.mjs +136 -32
  13. package/dist/defaultStyle.cjs +29 -3
  14. package/dist/defaultStyle.d.cts +15 -4
  15. package/dist/defaultStyle.d.mts +15 -4
  16. package/dist/defaultStyle.mjs +30 -4
  17. package/dist/index.cjs +11 -2
  18. package/dist/index.d.cts +10 -7
  19. package/dist/index.d.mts +10 -7
  20. package/dist/index.mjs +4 -3
  21. package/dist/mediaQuery.cjs +179 -0
  22. package/dist/mediaQuery.d.cts +1 -0
  23. package/dist/mediaQuery.mjs +178 -0
  24. package/dist/nativeTheme.cjs +51 -0
  25. package/dist/nativeTheme.d.cts +15 -0
  26. package/dist/nativeTheme.d.mts +15 -0
  27. package/dist/nativeTheme.mjs +50 -0
  28. package/dist/platform.mjs +1 -1
  29. package/dist/styled.cjs +95 -19
  30. package/dist/styled.mjs +96 -20
  31. package/dist/toNativeStyle.cjs +64 -15
  32. package/dist/toNativeStyle.mjs +65 -16
  33. package/dist/types.d.cts +78 -10
  34. package/dist/types.d.mts +78 -10
  35. package/dist/units.cjs +137 -0
  36. package/dist/units.mjs +133 -0
  37. package/dist/warnStyle.cjs +62 -18
  38. package/dist/warnStyle.mjs +61 -19
  39. package/dist/windowState.cjs +89 -0
  40. package/dist/windowState.d.cts +6 -0
  41. package/dist/windowState.d.mts +5 -0
  42. package/dist/windowState.mjs +85 -0
  43. package/package.json +3 -3
@@ -0,0 +1,179 @@
1
+ // src/mediaQuery.ts
2
+ /** A part of a query that the binding cannot evaluate: what to name in the warning. */
3
+ var Unsupported = class {
4
+ problem;
5
+ constructor(problem) {
6
+ this.problem = problem;
7
+ }
8
+ };
9
+ /** A key that is a media query: `@media` and then white space or a parenthesis. */
10
+ const MEDIA_KEY = /^@media(?=[\s(])/i;
11
+ /** `@media` in front of a query, with any white space before it. */
12
+ const MEDIA_PREFIX = /^\s*@media(?![a-z-])/i;
13
+ /** A feature in parentheses, a word, or any other character. */
14
+ const TOKEN = /\([^()]*\)|[a-z-]+|\S/g;
15
+ /** A number and its unit. */
16
+ const LENGTH = /^(-?(?:\d+(?:\.\d*)?|\.\d+))([a-z%]*)$/;
17
+ /** An operator of the range form. The white space around it is trimmed off the parts: a pattern that took it in would try each run of white space once for each of its characters. */
18
+ const RANGE = /(<=|>=|<|>|=)/;
19
+ /** The name of a feature, `min-` or `max-` and all. */
20
+ const NAME = /^[a-z-]+$/;
21
+ const SIZE = /^(min-|max-)?(width|height)$/;
22
+ const SIZE_FEATURES = /* @__PURE__ */ new Set(["width", "height"]);
23
+ const FLIPPED = {
24
+ "<": ">",
25
+ "<=": ">=",
26
+ ">": "<",
27
+ ">=": "<=",
28
+ "=": "="
29
+ };
30
+ /** The features that take a keyword, and the test of each keyword. */
31
+ const KEYWORD_FEATURES = /* @__PURE__ */ new Map([
32
+ ["orientation", /* @__PURE__ */ new Map([["portrait", (state) => state.height >= state.width], ["landscape", (state) => state.height < state.width]])],
33
+ ["prefers-color-scheme", /* @__PURE__ */ new Map([["light", (state) => state.colorScheme !== "dark"], ["dark", (state) => state.colorScheme === "dark"]])],
34
+ ["prefers-reduced-motion", /* @__PURE__ */ new Map([["reduce", (state) => state.isReducedMotion], ["no-preference", (state) => !state.isReducedMotion]])]
35
+ ]);
36
+ const matchNever = () => false;
37
+ /** Whether `key` is a media query key: `@media (...)`. */
38
+ function isMediaKey(key) {
39
+ return MEDIA_KEY.test(key);
40
+ }
41
+ /** `left` compared with `right` by `operator`. */
42
+ function compare(left, operator, right) {
43
+ switch (operator) {
44
+ case "<": return left < right;
45
+ case "<=": return left <= right;
46
+ case ">": return left > right;
47
+ case ">=": return left >= right;
48
+ default: return left === right;
49
+ }
50
+ }
51
+ /** The length `text` for a `remBase`: `px` and no unit are pixels, `rem` and `em` are `remBase` times their number. */
52
+ function readLength(text) {
53
+ const match = LENGTH.exec(text);
54
+ if (match === null) return new Unsupported(`the value "${text}"`);
55
+ const value = Number.parseFloat(match[1]);
56
+ const unit = match[2];
57
+ if (unit === "" || unit === "px") return () => value;
58
+ if (unit === "rem" || unit === "em") return (remBase) => value * remBase;
59
+ return new Unsupported(`the unit "${unit}"`);
60
+ }
61
+ /** The test of `feature operator text`: the width or the height of the window compared with a length. */
62
+ function compareSize(feature, operator, text) {
63
+ const length = readLength(text);
64
+ if (length instanceof Unsupported) return length;
65
+ return feature === "width" ? (state, remBase) => compare(state.width, operator, length(remBase)) : (state, remBase) => compare(state.height, operator, length(remBase));
66
+ }
67
+ /** The operator of a size feature with the prefix `bound`: `min-` is `>=`, `max-` is `<=`, none is `=`. */
68
+ function readBoundOperator(bound) {
69
+ if (bound === "min-") return ">=";
70
+ return bound === "max-" ? "<=" : "=";
71
+ }
72
+ /** The test of `(name: value)`. */
73
+ function readPlainFeature(name, value) {
74
+ const size = SIZE.exec(name);
75
+ if (size !== null) return compareSize(size[2], readBoundOperator(size[1]), value);
76
+ const keywords = KEYWORD_FEATURES.get(name);
77
+ if (keywords === void 0) return new Unsupported(`the media feature "${name}"`);
78
+ return keywords.get(value) ?? new Unsupported(`the value "${value}" of ${name}`);
79
+ }
80
+ /** The test of a comparison, `width >= 600px` or `600px <= width`; undefined when neither side is a size feature. */
81
+ function readComparison([left, operator, right]) {
82
+ if (SIZE_FEATURES.has(left)) return compareSize(left, operator, right);
83
+ if (SIZE_FEATURES.has(right)) return compareSize(right, FLIPPED[operator], left);
84
+ }
85
+ /** The test of a size between two lengths, `400px <= width < 800px`; undefined unless both operators point the same way: `<` and `<=`, or `>` and `>=`. */
86
+ function readBetween([low, first, feature, second, high]) {
87
+ if (first === "=" || second === "=" || first.startsWith("<") !== second.startsWith("<")) return;
88
+ const above = compareSize(feature, FLIPPED[first], low);
89
+ const below = compareSize(feature, second, high);
90
+ if (above instanceof Unsupported) return above;
91
+ if (below instanceof Unsupported) return below;
92
+ return (state, remBase) => above(state, remBase) && below(state, remBase);
93
+ }
94
+ /** The test of a range: `width >= 600px`, `600px <= width`, `400px <= width < 800px`. */
95
+ function readRange(parts) {
96
+ let read;
97
+ if (parts.length === 3) read = readComparison(parts);
98
+ else if (parts.length === 5 && SIZE_FEATURES.has(parts[2])) read = readBetween(parts);
99
+ if (read !== void 0) return read;
100
+ const name = parts.find((part) => NAME.test(part) && !SIZE_FEATURES.has(part));
101
+ return new Unsupported(name === void 0 ? `the range "${parts.join(" ")}"` : `the media feature "${name}"`);
102
+ }
103
+ /** The test of the text inside one pair of parentheses. */
104
+ function readFeature(text) {
105
+ const colon = text.indexOf(":");
106
+ if (colon >= 0) return readPlainFeature(text.slice(0, colon).trim(), text.slice(colon + 1).trim());
107
+ const parts = text.split(RANGE).map((part) => part.trim());
108
+ if (parts.length > 1) return readRange(parts);
109
+ return new Unsupported(NAME.test(text) ? `the media feature "${text}"` : `the text "(${text})"`);
110
+ }
111
+ /** Whether `token` is a feature in parentheses. */
112
+ const isFeature = (token) => token !== void 0 && token.length > 1 && token.startsWith("(");
113
+ /** The tests of the features of `tokens` from `start`, joined by `and`; `invalid` when the tokens are not that, or what the binding cannot evaluate in a feature. */
114
+ function readFeatures(tokens, start, invalid) {
115
+ const tests = [];
116
+ let index = start;
117
+ for (;;) {
118
+ const token = tokens[index++];
119
+ if (!isFeature(token)) return invalid;
120
+ const test = readFeature(token.slice(1, -1).trim());
121
+ if (test instanceof Unsupported) return test;
122
+ tests.push(test);
123
+ if (index === tokens.length) return tests;
124
+ if (tokens[index++] !== "and") return invalid;
125
+ }
126
+ }
127
+ /** The tests of a query whose media type is at `index` of `tokens`: none for the type alone, else those of the features after its `and`. */
128
+ function readTypedFeatures(tokens, index, invalid) {
129
+ const type = tokens[index];
130
+ if (type !== "all" && type !== "screen") return new Unsupported(`the media type "${type}"`);
131
+ if (index + 1 === tokens.length) return [];
132
+ if (tokens[index + 1] !== "and") return invalid;
133
+ return readFeatures(tokens, index + 2, invalid);
134
+ }
135
+ /** The test of one query of a list: `not` or `only`, a media type, and features joined by `and`. */
136
+ function readQuery(text) {
137
+ const tokens = text.match(TOKEN) ?? [];
138
+ const invalid = new Unsupported(`the text "${text}"`);
139
+ const isNegated = tokens[0] === "not";
140
+ const index = isNegated || tokens[0] === "only" ? 1 : 0;
141
+ const type = tokens[index];
142
+ const tests = type !== void 0 && NAME.test(type) ? readTypedFeatures(tokens, index, invalid) : readFeatures(tokens, index, invalid);
143
+ if (tests instanceof Unsupported) return tests;
144
+ return (state, remBase) => tests.every((test) => test(state, remBase)) !== isNegated;
145
+ }
146
+ /** `text` read as a media query list, with or without `@media` in front. */
147
+ function parseMediaQuery(text) {
148
+ const list = text.replace(MEDIA_PREFIX, "").trim().toLowerCase();
149
+ const tests = [];
150
+ for (const part of list.split(",")) {
151
+ const test = readQuery(part.trim());
152
+ if (test instanceof Unsupported) return {
153
+ matches: matchNever,
154
+ problem: test.problem
155
+ };
156
+ tests.push(test);
157
+ }
158
+ return { matches: (state, remBase) => tests.some((test) => test(state, remBase)) };
159
+ }
160
+ const queries = /* @__PURE__ */ new Map();
161
+ /**
162
+ * The media query `text` (a key `@media (...)`, or the query alone, as `matchMedia` takes it), read once
163
+ * for each text. The subset: `width`, `height` and their `min-` and `max-` forms, the range forms
164
+ * (`width >= 600px`, `600px <= width`, `400px <= width < 800px`), `orientation`, `prefers-color-scheme`
165
+ * and `prefers-reduced-motion`, joined by `and`, in a comma list (any one matches), after `not` or
166
+ * `only` and the media type `all` or `screen`. A length is in `px` or has no unit (one pixel is one
167
+ * density-independent pixel), or is in `rem` or `em` (`remBase` pixels). A query with anything else
168
+ * never matches, and has a `problem` that names it.
169
+ */
170
+ function readMediaQuery(text) {
171
+ let query = queries.get(text);
172
+ if (query === void 0) {
173
+ query = parseMediaQuery(text);
174
+ queries.set(text, query);
175
+ }
176
+ return query;
177
+ }
178
+ exports.isMediaKey = isMediaKey;
179
+ exports.readMediaQuery = readMediaQuery;
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,178 @@
1
+ // src/mediaQuery.ts
2
+ /** A part of a query that the binding cannot evaluate: what to name in the warning. */
3
+ var Unsupported = class {
4
+ problem;
5
+ constructor(problem) {
6
+ this.problem = problem;
7
+ }
8
+ };
9
+ /** A key that is a media query: `@media` and then white space or a parenthesis. */
10
+ const MEDIA_KEY = /^@media(?=[\s(])/i;
11
+ /** `@media` in front of a query, with any white space before it. */
12
+ const MEDIA_PREFIX = /^\s*@media(?![a-z-])/i;
13
+ /** A feature in parentheses, a word, or any other character. */
14
+ const TOKEN = /\([^()]*\)|[a-z-]+|\S/g;
15
+ /** A number and its unit. */
16
+ const LENGTH = /^(-?(?:\d+(?:\.\d*)?|\.\d+))([a-z%]*)$/;
17
+ /** An operator of the range form. The white space around it is trimmed off the parts: a pattern that took it in would try each run of white space once for each of its characters. */
18
+ const RANGE = /(<=|>=|<|>|=)/;
19
+ /** The name of a feature, `min-` or `max-` and all. */
20
+ const NAME = /^[a-z-]+$/;
21
+ const SIZE = /^(min-|max-)?(width|height)$/;
22
+ const SIZE_FEATURES = /* @__PURE__ */ new Set(["width", "height"]);
23
+ const FLIPPED = {
24
+ "<": ">",
25
+ "<=": ">=",
26
+ ">": "<",
27
+ ">=": "<=",
28
+ "=": "="
29
+ };
30
+ /** The features that take a keyword, and the test of each keyword. */
31
+ const KEYWORD_FEATURES = /* @__PURE__ */ new Map([
32
+ ["orientation", /* @__PURE__ */ new Map([["portrait", (state) => state.height >= state.width], ["landscape", (state) => state.height < state.width]])],
33
+ ["prefers-color-scheme", /* @__PURE__ */ new Map([["light", (state) => state.colorScheme !== "dark"], ["dark", (state) => state.colorScheme === "dark"]])],
34
+ ["prefers-reduced-motion", /* @__PURE__ */ new Map([["reduce", (state) => state.isReducedMotion], ["no-preference", (state) => !state.isReducedMotion]])]
35
+ ]);
36
+ const matchNever = () => false;
37
+ /** Whether `key` is a media query key: `@media (...)`. */
38
+ function isMediaKey(key) {
39
+ return MEDIA_KEY.test(key);
40
+ }
41
+ /** `left` compared with `right` by `operator`. */
42
+ function compare(left, operator, right) {
43
+ switch (operator) {
44
+ case "<": return left < right;
45
+ case "<=": return left <= right;
46
+ case ">": return left > right;
47
+ case ">=": return left >= right;
48
+ default: return left === right;
49
+ }
50
+ }
51
+ /** The length `text` for a `remBase`: `px` and no unit are pixels, `rem` and `em` are `remBase` times their number. */
52
+ function readLength(text) {
53
+ const match = LENGTH.exec(text);
54
+ if (match === null) return new Unsupported(`the value "${text}"`);
55
+ const value = Number.parseFloat(match[1]);
56
+ const unit = match[2];
57
+ if (unit === "" || unit === "px") return () => value;
58
+ if (unit === "rem" || unit === "em") return (remBase) => value * remBase;
59
+ return new Unsupported(`the unit "${unit}"`);
60
+ }
61
+ /** The test of `feature operator text`: the width or the height of the window compared with a length. */
62
+ function compareSize(feature, operator, text) {
63
+ const length = readLength(text);
64
+ if (length instanceof Unsupported) return length;
65
+ return feature === "width" ? (state, remBase) => compare(state.width, operator, length(remBase)) : (state, remBase) => compare(state.height, operator, length(remBase));
66
+ }
67
+ /** The operator of a size feature with the prefix `bound`: `min-` is `>=`, `max-` is `<=`, none is `=`. */
68
+ function readBoundOperator(bound) {
69
+ if (bound === "min-") return ">=";
70
+ return bound === "max-" ? "<=" : "=";
71
+ }
72
+ /** The test of `(name: value)`. */
73
+ function readPlainFeature(name, value) {
74
+ const size = SIZE.exec(name);
75
+ if (size !== null) return compareSize(size[2], readBoundOperator(size[1]), value);
76
+ const keywords = KEYWORD_FEATURES.get(name);
77
+ if (keywords === void 0) return new Unsupported(`the media feature "${name}"`);
78
+ return keywords.get(value) ?? new Unsupported(`the value "${value}" of ${name}`);
79
+ }
80
+ /** The test of a comparison, `width >= 600px` or `600px <= width`; undefined when neither side is a size feature. */
81
+ function readComparison([left, operator, right]) {
82
+ if (SIZE_FEATURES.has(left)) return compareSize(left, operator, right);
83
+ if (SIZE_FEATURES.has(right)) return compareSize(right, FLIPPED[operator], left);
84
+ }
85
+ /** The test of a size between two lengths, `400px <= width < 800px`; undefined unless both operators point the same way: `<` and `<=`, or `>` and `>=`. */
86
+ function readBetween([low, first, feature, second, high]) {
87
+ if (first === "=" || second === "=" || first.startsWith("<") !== second.startsWith("<")) return;
88
+ const above = compareSize(feature, FLIPPED[first], low);
89
+ const below = compareSize(feature, second, high);
90
+ if (above instanceof Unsupported) return above;
91
+ if (below instanceof Unsupported) return below;
92
+ return (state, remBase) => above(state, remBase) && below(state, remBase);
93
+ }
94
+ /** The test of a range: `width >= 600px`, `600px <= width`, `400px <= width < 800px`. */
95
+ function readRange(parts) {
96
+ let read;
97
+ if (parts.length === 3) read = readComparison(parts);
98
+ else if (parts.length === 5 && SIZE_FEATURES.has(parts[2])) read = readBetween(parts);
99
+ if (read !== void 0) return read;
100
+ const name = parts.find((part) => NAME.test(part) && !SIZE_FEATURES.has(part));
101
+ return new Unsupported(name === void 0 ? `the range "${parts.join(" ")}"` : `the media feature "${name}"`);
102
+ }
103
+ /** The test of the text inside one pair of parentheses. */
104
+ function readFeature(text) {
105
+ const colon = text.indexOf(":");
106
+ if (colon >= 0) return readPlainFeature(text.slice(0, colon).trim(), text.slice(colon + 1).trim());
107
+ const parts = text.split(RANGE).map((part) => part.trim());
108
+ if (parts.length > 1) return readRange(parts);
109
+ return new Unsupported(NAME.test(text) ? `the media feature "${text}"` : `the text "(${text})"`);
110
+ }
111
+ /** Whether `token` is a feature in parentheses. */
112
+ const isFeature = (token) => token !== void 0 && token.length > 1 && token.startsWith("(");
113
+ /** The tests of the features of `tokens` from `start`, joined by `and`; `invalid` when the tokens are not that, or what the binding cannot evaluate in a feature. */
114
+ function readFeatures(tokens, start, invalid) {
115
+ const tests = [];
116
+ let index = start;
117
+ for (;;) {
118
+ const token = tokens[index++];
119
+ if (!isFeature(token)) return invalid;
120
+ const test = readFeature(token.slice(1, -1).trim());
121
+ if (test instanceof Unsupported) return test;
122
+ tests.push(test);
123
+ if (index === tokens.length) return tests;
124
+ if (tokens[index++] !== "and") return invalid;
125
+ }
126
+ }
127
+ /** The tests of a query whose media type is at `index` of `tokens`: none for the type alone, else those of the features after its `and`. */
128
+ function readTypedFeatures(tokens, index, invalid) {
129
+ const type = tokens[index];
130
+ if (type !== "all" && type !== "screen") return new Unsupported(`the media type "${type}"`);
131
+ if (index + 1 === tokens.length) return [];
132
+ if (tokens[index + 1] !== "and") return invalid;
133
+ return readFeatures(tokens, index + 2, invalid);
134
+ }
135
+ /** The test of one query of a list: `not` or `only`, a media type, and features joined by `and`. */
136
+ function readQuery(text) {
137
+ const tokens = text.match(TOKEN) ?? [];
138
+ const invalid = new Unsupported(`the text "${text}"`);
139
+ const isNegated = tokens[0] === "not";
140
+ const index = isNegated || tokens[0] === "only" ? 1 : 0;
141
+ const type = tokens[index];
142
+ const tests = type !== void 0 && NAME.test(type) ? readTypedFeatures(tokens, index, invalid) : readFeatures(tokens, index, invalid);
143
+ if (tests instanceof Unsupported) return tests;
144
+ return (state, remBase) => tests.every((test) => test(state, remBase)) !== isNegated;
145
+ }
146
+ /** `text` read as a media query list, with or without `@media` in front. */
147
+ function parseMediaQuery(text) {
148
+ const list = text.replace(MEDIA_PREFIX, "").trim().toLowerCase();
149
+ const tests = [];
150
+ for (const part of list.split(",")) {
151
+ const test = readQuery(part.trim());
152
+ if (test instanceof Unsupported) return {
153
+ matches: matchNever,
154
+ problem: test.problem
155
+ };
156
+ tests.push(test);
157
+ }
158
+ return { matches: (state, remBase) => tests.some((test) => test(state, remBase)) };
159
+ }
160
+ const queries = /* @__PURE__ */ new Map();
161
+ /**
162
+ * The media query `text` (a key `@media (...)`, or the query alone, as `matchMedia` takes it), read once
163
+ * for each text. The subset: `width`, `height` and their `min-` and `max-` forms, the range forms
164
+ * (`width >= 600px`, `600px <= width`, `400px <= width < 800px`), `orientation`, `prefers-color-scheme`
165
+ * and `prefers-reduced-motion`, joined by `and`, in a comma list (any one matches), after `not` or
166
+ * `only` and the media type `all` or `screen`. A length is in `px` or has no unit (one pixel is one
167
+ * density-independent pixel), or is in `rem` or `em` (`remBase` pixels). A query with anything else
168
+ * never matches, and has a `problem` that names it.
169
+ */
170
+ function readMediaQuery(text) {
171
+ let query = queries.get(text);
172
+ if (query === void 0) {
173
+ query = parseMediaQuery(text);
174
+ queries.set(text, query);
175
+ }
176
+ return query;
177
+ }
178
+ export { isMediaKey, readMediaQuery };
@@ -0,0 +1,51 @@
1
+ let _umber_style_core = require("@umber-style/core");
2
+ const require_units = require("./units.cjs");
3
+ // src/nativeTheme.ts
4
+ /** The top-level theme keys whose values are lengths when no `lengthKeys` option is given: the default of the web. */
5
+ const DEFAULT_LENGTH_KEYS = [
6
+ "space",
7
+ "sizes",
8
+ "radii",
9
+ "fontSizes",
10
+ "borderWidths"
11
+ ];
12
+ /** Whether `value` is an object made by a literal, not a class instance. */
13
+ function isPlainObject(value) {
14
+ if (typeof value !== "object" || value === null) return false;
15
+ const prototype = Object.getPrototypeOf(value);
16
+ return prototype === Object.prototype || prototype === null;
17
+ }
18
+ /** `node` with each string that is a length (`px`, `rem` or no unit) a number; `node` itself when nothing changes. */
19
+ function convertLengths(node, remBase) {
20
+ if (typeof node === "string") return require_units.toLength(node, remBase) ?? node;
21
+ const isArray = Array.isArray(node);
22
+ if (!isArray && !isPlainObject(node)) return node;
23
+ const source = node;
24
+ let copy;
25
+ for (const key of Object.keys(source)) {
26
+ const value = source[key];
27
+ const converted = convertLengths(value, remBase);
28
+ if (converted === value) continue;
29
+ copy ??= Object.assign(isArray ? [] : {}, source);
30
+ copy[key] = converted;
31
+ }
32
+ return copy ?? node;
33
+ }
34
+ /**
35
+ * `theme` as React Native holds it: under each of `lengthKeys` (top-level keys), every string that is a
36
+ * length becomes a number, `rem` times `remBase`. Nothing else is touched (`breakpoints` and its helper
37
+ * functions included), and a theme with nothing to convert is returned as it is.
38
+ */
39
+ function toNativeTheme(theme, lengthKeys, remBase) {
40
+ const source = theme;
41
+ let changes;
42
+ for (const key of lengthKeys) {
43
+ const converted = convertLengths(source[key], remBase);
44
+ if (converted === source[key]) continue;
45
+ changes ??= {};
46
+ changes[key] = converted;
47
+ }
48
+ return changes ? (0, _umber_style_core.mergeDeep)(theme, changes) : theme;
49
+ }
50
+ exports.DEFAULT_LENGTH_KEYS = DEFAULT_LENGTH_KEYS;
51
+ exports.toNativeTheme = toNativeTheme;
@@ -0,0 +1,15 @@
1
+ /** The top-level theme keys whose values are lengths when no `lengthKeys` option is given: the default of the web. */
2
+ export declare const DEFAULT_LENGTH_KEYS: readonly ['space', 'sizes', 'radii', 'fontSizes', 'borderWidths'];
3
+ /** One of the default length keys of a theme. */
4
+ export type DefaultLengthKey = (typeof DEFAULT_LENGTH_KEYS)[number];
5
+ /**
6
+ * A theme value under a length key as React Native holds it: a string type that is a length (`'8px'`,
7
+ * `'1rem'`, `'8'`) is `number`, a plain `string` may have become one (`string | number`), any other
8
+ * string (`'50%'`, `'auto'`) and a function stay, and objects and arrays are mapped member by member.
9
+ */
10
+ export type NativeLength<V> = V extends `${number}px` | `${number}rem` | `${number}` ? number : V extends string ? string extends V ? string | number : V : V extends ((...args: never[]) => unknown) ? V : V extends object ? { [K in keyof V]: NativeLength<V[K]>; } : V;
11
+ /**
12
+ * The theme `T` as React Native holds it: the values under the default length keys (`space`, `sizes`,
13
+ * `radii`, `fontSizes`, `borderWidths`) are numbers where they were lengths, the rest is `T` itself.
14
+ */
15
+ export type NativeTheme<T> = { [K in keyof T]: K extends DefaultLengthKey ? NativeLength<T[K]> : T[K]; };
@@ -0,0 +1,15 @@
1
+ /** The top-level theme keys whose values are lengths when no `lengthKeys` option is given: the default of the web. */
2
+ export declare const DEFAULT_LENGTH_KEYS: readonly ['space', 'sizes', 'radii', 'fontSizes', 'borderWidths'];
3
+ /** One of the default length keys of a theme. */
4
+ export type DefaultLengthKey = (typeof DEFAULT_LENGTH_KEYS)[number];
5
+ /**
6
+ * A theme value under a length key as React Native holds it: a string type that is a length (`'8px'`,
7
+ * `'1rem'`, `'8'`) is `number`, a plain `string` may have become one (`string | number`), any other
8
+ * string (`'50%'`, `'auto'`) and a function stay, and objects and arrays are mapped member by member.
9
+ */
10
+ export type NativeLength<V> = V extends `${number}px` | `${number}rem` | `${number}` ? number : V extends string ? string extends V ? string | number : V : V extends ((...args: never[]) => unknown) ? V : V extends object ? { [K in keyof V]: NativeLength<V[K]>; } : V;
11
+ /**
12
+ * The theme `T` as React Native holds it: the values under the default length keys (`space`, `sizes`,
13
+ * `radii`, `fontSizes`, `borderWidths`) are numbers where they were lengths, the rest is `T` itself.
14
+ */
15
+ export type NativeTheme<T> = { [K in keyof T]: K extends DefaultLengthKey ? NativeLength<T[K]> : T[K]; };
@@ -0,0 +1,50 @@
1
+ import { mergeDeep } from "@umber-style/core";
2
+ import { toLength } from "./units.mjs";
3
+ // src/nativeTheme.ts
4
+ /** The top-level theme keys whose values are lengths when no `lengthKeys` option is given: the default of the web. */
5
+ const DEFAULT_LENGTH_KEYS = [
6
+ "space",
7
+ "sizes",
8
+ "radii",
9
+ "fontSizes",
10
+ "borderWidths"
11
+ ];
12
+ /** Whether `value` is an object made by a literal, not a class instance. */
13
+ function isPlainObject(value) {
14
+ if (typeof value !== "object" || value === null) return false;
15
+ const prototype = Object.getPrototypeOf(value);
16
+ return prototype === Object.prototype || prototype === null;
17
+ }
18
+ /** `node` with each string that is a length (`px`, `rem` or no unit) a number; `node` itself when nothing changes. */
19
+ function convertLengths(node, remBase) {
20
+ if (typeof node === "string") return toLength(node, remBase) ?? node;
21
+ const isArray = Array.isArray(node);
22
+ if (!isArray && !isPlainObject(node)) return node;
23
+ const source = node;
24
+ let copy;
25
+ for (const key of Object.keys(source)) {
26
+ const value = source[key];
27
+ const converted = convertLengths(value, remBase);
28
+ if (converted === value) continue;
29
+ copy ??= Object.assign(isArray ? [] : {}, source);
30
+ copy[key] = converted;
31
+ }
32
+ return copy ?? node;
33
+ }
34
+ /**
35
+ * `theme` as React Native holds it: under each of `lengthKeys` (top-level keys), every string that is a
36
+ * length becomes a number, `rem` times `remBase`. Nothing else is touched (`breakpoints` and its helper
37
+ * functions included), and a theme with nothing to convert is returned as it is.
38
+ */
39
+ function toNativeTheme(theme, lengthKeys, remBase) {
40
+ const source = theme;
41
+ let changes;
42
+ for (const key of lengthKeys) {
43
+ const converted = convertLengths(source[key], remBase);
44
+ if (converted === source[key]) continue;
45
+ changes ??= {};
46
+ changes[key] = converted;
47
+ }
48
+ return changes ? mergeDeep(theme, changes) : theme;
49
+ }
50
+ export { DEFAULT_LENGTH_KEYS, toNativeTheme };
package/dist/platform.mjs CHANGED
@@ -1 +1 @@
1
- export { Appearance as platformAppearance, StyleSheet as platformStyleSheet } from "react-native";
1
+ export { AccessibilityInfo as platformAccessibility, Appearance as platformAppearance, Dimensions as platformDimensions, StyleSheet as platformStyleSheet } from "react-native";
package/dist/styled.cjs CHANGED
@@ -1,44 +1,120 @@
1
1
  let react = require("react");
2
2
  const require_toNativeStyle = require("./toNativeStyle.cjs");
3
+ const require_windowState = require("./windowState.cjs");
3
4
  let react_native = require("react-native");
4
5
  // src/styled.ts
6
+ const NO_KEYS = {
7
+ isConditional: false,
8
+ hasScheme: false,
9
+ queries: []
10
+ };
11
+ /** The name a component is known by: its `displayName`, else the name of its function; undefined when it has neither. */
12
+ function readComponentName(component) {
13
+ const { displayName, name } = component;
14
+ return displayName || name || void 0;
15
+ }
16
+ /** `lists` joined, each item once, in order. */
17
+ function joinQueries(lists) {
18
+ return [...new Set(lists.flat())];
19
+ }
5
20
  /**
6
21
  * Makes `styled` for React Native. Its object styles are registered with the platform StyleSheet
7
22
  * once, when the component is made; its function styles are computed with the real theme, which
8
23
  * `useTheme` reads, on each render. A style with a `when()` or `whenScheme()` key is resolved on each
9
- * render against the nearest provider, which `useCondition` reads; it is not registered. A component
10
- * without function styles or condition keys reads no context.
24
+ * render against the nearest provider, which `useCondition` reads; it is not registered. An object style
25
+ * with media query keys and no condition key is resolved and registered once for each set of matching
26
+ * queries. A component renders again when the set of its matching queries changes (or the system color
27
+ * scheme, for a `whenScheme()` key that no provider decides); one without function styles, condition
28
+ * keys or media keys reads no context and subscribes to nothing. A `rem` length is `remBase` times its
29
+ * number. The development warnings name the component: its `name` option, else the wrapped component's.
11
30
  */
12
- function createStyled(useTheme, useCondition) {
31
+ function createStyled(useTheme, useCondition, remBase) {
13
32
  const styled = (tag, options = {}) => {
14
33
  if (typeof tag === "string") throw new TypeError(`styled needs a component on React Native, not the tag "${tag}".`);
15
34
  const { shouldForwardProp: shouldForward } = options;
35
+ const settings = {
36
+ remBase,
37
+ name: options.name ?? readComponentName(tag)
38
+ };
16
39
  return (...styles) => {
17
- const isDynamic = styles.some((style) => typeof style === "function");
18
- const isConditional = styles.some((style) => typeof style !== "function" && !!style && require_toNativeStyle.hasConditions(style));
19
- const fixed = Object.fromEntries(styles.flatMap((style, index) => typeof style === "function" || !style || require_toNativeStyle.hasConditions(style) ? [] : [[`s${index}`, require_toNativeStyle.toNativeStyle(style)]]));
20
- const registered = Object.keys(fixed).length > 0 ? react_native.StyleSheet.create(fixed) : fixed;
21
- const render = (props, theme, condition) => {
40
+ const keys = styles.map((style) => typeof style === "function" || !style ? NO_KEYS : require_toNativeStyle.collectKeys(style) ?? NO_KEYS);
41
+ const kinds = styles.map((style, index) => {
42
+ if (typeof style === "function") return "function";
43
+ if (keys[index].isConditional) return "conditional";
44
+ return keys[index].queries.length > 0 ? "window" : "fixed";
45
+ });
46
+ const queries = joinQueries(keys.map((found) => found.queries));
47
+ const hasScheme = keys.some((found) => found.hasScheme);
48
+ /** The object styles of `kind`, resolved for `state` and registered with the platform. */
49
+ const register = (kind, state) => {
50
+ const pairs = styles.flatMap((style, index) => kinds[index] === kind && style ? [[`s${index}`, require_toNativeStyle.toNativeStyle(style, void 0, settings, state)]] : []);
51
+ return pairs.length > 0 ? react_native.StyleSheet.create(Object.fromEntries(pairs)) : {};
52
+ };
53
+ const registered = register("fixed");
54
+ const byWindow = /* @__PURE__ */ new Map();
55
+ /** The styles that depend on the window only, for the key of a render: registered once for each set of matching queries. */
56
+ const readWindowStyles = (key) => {
57
+ const windowKey = key.slice(0, queries.length);
58
+ let found = byWindow.get(windowKey);
59
+ if (found === void 0) {
60
+ found = register("window", require_windowState.readWindowState());
61
+ byWindow.set(windowKey, found);
62
+ }
63
+ return found;
64
+ };
65
+ const render = (props, key = "", condition, results, state) => {
22
66
  const resolved = styles.flatMap((style, index) => {
23
- if (typeof style !== "function") return [style && require_toNativeStyle.hasConditions(style) ? require_toNativeStyle.toNativeStyle(style, condition) : registered[`s${index}`]];
24
- const result = style({
25
- ...props,
26
- theme
27
- });
28
- return result ? [require_toNativeStyle.toNativeStyle(result, condition)] : [];
67
+ switch (kinds[index]) {
68
+ case "fixed": return [registered[`s${index}`]];
69
+ case "window": return [readWindowStyles(key)[`s${index}`]];
70
+ case "conditional": return [require_toNativeStyle.toNativeStyle(style, condition, settings, state)];
71
+ default: {
72
+ const result = results[index];
73
+ return result ? [require_toNativeStyle.toNativeStyle(result, condition, settings, state)] : [];
74
+ }
75
+ }
29
76
  });
30
77
  const forwarded = {};
31
- for (const [key, value] of Object.entries(props)) if (!(key === "as" || key === "theme" || key === "style") && (!shouldForward || shouldForward(key))) forwarded[key] = value;
78
+ for (const [name, value] of Object.entries(props)) if (!(name === "as" || name === "theme" || name === "style") && (!shouldForward || shouldForward(name))) forwarded[name] = value;
32
79
  forwarded.style = [...resolved, props.style].flat(1e400).filter(Boolean);
33
80
  return (0, react.createElement)(props.as ?? tag, forwarded);
34
81
  };
35
82
  const StaticStyled = (props) => render(props);
36
- const DynamicStyled = (props) => render(props, useTheme(), useCondition());
37
- const ConditionalStyled = (props) => render(props, void 0, useCondition());
38
- if (isDynamic) return DynamicStyled;
39
- return isConditional ? ConditionalStyled : StaticStyled;
83
+ const WindowStyled = (props) => render(props, require_windowState.useMediaKey(queries, false, remBase));
84
+ const ConditionalStyled = (props) => {
85
+ const condition = useCondition();
86
+ const key = require_windowState.useMediaKey(queries, hasScheme && condition.colorScheme === void 0, remBase);
87
+ return render(props, key, condition, void 0, readStateFor(queries));
88
+ };
89
+ const DynamicStyled = (props) => {
90
+ const theme = useTheme();
91
+ const condition = useCondition();
92
+ const results = [];
93
+ let found;
94
+ for (let index = 0; index < styles.length; index++) {
95
+ const style = styles[index];
96
+ if (typeof style !== "function") continue;
97
+ const result = style({
98
+ ...props,
99
+ theme
100
+ });
101
+ results[index] = result;
102
+ if (result) found = require_toNativeStyle.collectKeys(result, found);
103
+ }
104
+ const all = found === void 0 ? queries : joinQueries([queries, found.queries]);
105
+ const shouldWatchScheme = (hasScheme || !!found?.hasScheme) && condition.colorScheme === void 0;
106
+ const key = require_windowState.useMediaKey(all, shouldWatchScheme, remBase);
107
+ return render(props, key, condition, results, readStateFor(all));
108
+ };
109
+ if (kinds.includes("function")) return DynamicStyled;
110
+ if (kinds.includes("conditional")) return ConditionalStyled;
111
+ return queries.length > 0 ? WindowStyled : StaticStyled;
40
112
  };
41
113
  };
42
114
  return styled;
43
115
  }
116
+ /** The window now, when there are queries to evaluate. */
117
+ function readStateFor(queries) {
118
+ return queries.length > 0 ? require_windowState.readWindowState() : void 0;
119
+ }
44
120
  exports.createStyled = createStyled;