@fluxus-ui/native 0.0.0-stage → 0.3.0

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 (230) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -2
  3. package/lib/module/AudioPlayer.js +174 -0
  4. package/lib/module/AudioPlayer.js.map +1 -0
  5. package/lib/module/Avatar.js +58 -0
  6. package/lib/module/Avatar.js.map +1 -0
  7. package/lib/module/Badge.js +72 -0
  8. package/lib/module/Badge.js.map +1 -0
  9. package/lib/module/BottomSheet.js +159 -0
  10. package/lib/module/BottomSheet.js.map +1 -0
  11. package/lib/module/Bubble.js +182 -0
  12. package/lib/module/Bubble.js.map +1 -0
  13. package/lib/module/Button.js +209 -0
  14. package/lib/module/Button.js.map +1 -0
  15. package/lib/module/Card.js +79 -0
  16. package/lib/module/Card.js.map +1 -0
  17. package/lib/module/Dialog.js +137 -0
  18. package/lib/module/Dialog.js.map +1 -0
  19. package/lib/module/Disclosure.js +153 -0
  20. package/lib/module/Disclosure.js.map +1 -0
  21. package/lib/module/EmptyState.js +71 -0
  22. package/lib/module/EmptyState.js.map +1 -0
  23. package/lib/module/Link.js +97 -0
  24. package/lib/module/Link.js.map +1 -0
  25. package/lib/module/ListItem.js +89 -0
  26. package/lib/module/ListItem.js.map +1 -0
  27. package/lib/module/Menu.js +76 -0
  28. package/lib/module/Menu.js.map +1 -0
  29. package/lib/module/Message.js +51 -0
  30. package/lib/module/Message.js.map +1 -0
  31. package/lib/module/Popover.js +153 -0
  32. package/lib/module/Popover.js.map +1 -0
  33. package/lib/module/Progress.js +54 -0
  34. package/lib/module/Progress.js.map +1 -0
  35. package/lib/module/Select.js +146 -0
  36. package/lib/module/Select.js.map +1 -0
  37. package/lib/module/Skeleton.js +40 -0
  38. package/lib/module/Skeleton.js.map +1 -0
  39. package/lib/module/Slider.js +137 -0
  40. package/lib/module/Slider.js.map +1 -0
  41. package/lib/module/Spinner.js +30 -0
  42. package/lib/module/Spinner.js.map +1 -0
  43. package/lib/module/Swap.js +87 -0
  44. package/lib/module/Swap.js.map +1 -0
  45. package/lib/module/Tabs.js +118 -0
  46. package/lib/module/Tabs.js.map +1 -0
  47. package/lib/module/Text.js +47 -0
  48. package/lib/module/Text.js.map +1 -0
  49. package/lib/module/TextField.js +190 -0
  50. package/lib/module/TextField.js.map +1 -0
  51. package/lib/module/Toast.js +157 -0
  52. package/lib/module/Toast.js.map +1 -0
  53. package/lib/module/audio.js +54 -0
  54. package/lib/module/audio.js.map +1 -0
  55. package/lib/module/blur.js +55 -0
  56. package/lib/module/blur.js.map +1 -0
  57. package/lib/module/controls.js +292 -0
  58. package/lib/module/controls.js.map +1 -0
  59. package/lib/module/feel.js +24 -0
  60. package/lib/module/feel.js.map +1 -0
  61. package/lib/module/generated/tokens.js +484 -0
  62. package/lib/module/generated/tokens.js.map +1 -0
  63. package/lib/module/haptics.js +25 -0
  64. package/lib/module/haptics.js.map +1 -0
  65. package/lib/module/icon-host.js +42 -0
  66. package/lib/module/icon-host.js.map +1 -0
  67. package/lib/module/icon-shape.js +222 -0
  68. package/lib/module/icon-shape.js.map +1 -0
  69. package/lib/module/icon.js +331 -0
  70. package/lib/module/icon.js.map +1 -0
  71. package/lib/module/index.js +39 -0
  72. package/lib/module/index.js.map +1 -0
  73. package/lib/module/layout.js +75 -0
  74. package/lib/module/layout.js.map +1 -0
  75. package/lib/module/marks.js +99 -0
  76. package/lib/module/marks.js.map +1 -0
  77. package/lib/module/motion.js +95 -0
  78. package/lib/module/motion.js.map +1 -0
  79. package/lib/module/overlay.js +99 -0
  80. package/lib/module/overlay.js.map +1 -0
  81. package/lib/module/package.json +1 -0
  82. package/lib/module/pending.js +181 -0
  83. package/lib/module/pending.js.map +1 -0
  84. package/lib/module/presence.js +71 -0
  85. package/lib/module/presence.js.map +1 -0
  86. package/lib/module/press.js +32 -0
  87. package/lib/module/press.js.map +1 -0
  88. package/lib/module/screen.js +50 -0
  89. package/lib/module/screen.js.map +1 -0
  90. package/lib/module/success.js +59 -0
  91. package/lib/module/success.js.map +1 -0
  92. package/lib/module/theme.js +41 -0
  93. package/lib/module/theme.js.map +1 -0
  94. package/lib/typescript/AudioPlayer.d.ts +26 -0
  95. package/lib/typescript/AudioPlayer.d.ts.map +1 -0
  96. package/lib/typescript/Avatar.d.ts +17 -0
  97. package/lib/typescript/Avatar.d.ts.map +1 -0
  98. package/lib/typescript/Badge.d.ts +21 -0
  99. package/lib/typescript/Badge.d.ts.map +1 -0
  100. package/lib/typescript/BottomSheet.d.ts +27 -0
  101. package/lib/typescript/BottomSheet.d.ts.map +1 -0
  102. package/lib/typescript/Bubble.d.ts +23 -0
  103. package/lib/typescript/Bubble.d.ts.map +1 -0
  104. package/lib/typescript/Button.d.ts +29 -0
  105. package/lib/typescript/Button.d.ts.map +1 -0
  106. package/lib/typescript/Card.d.ts +17 -0
  107. package/lib/typescript/Card.d.ts.map +1 -0
  108. package/lib/typescript/Dialog.d.ts +34 -0
  109. package/lib/typescript/Dialog.d.ts.map +1 -0
  110. package/lib/typescript/Disclosure.d.ts +39 -0
  111. package/lib/typescript/Disclosure.d.ts.map +1 -0
  112. package/lib/typescript/EmptyState.d.ts +14 -0
  113. package/lib/typescript/EmptyState.d.ts.map +1 -0
  114. package/lib/typescript/Link.d.ts +23 -0
  115. package/lib/typescript/Link.d.ts.map +1 -0
  116. package/lib/typescript/ListItem.d.ts +20 -0
  117. package/lib/typescript/ListItem.d.ts.map +1 -0
  118. package/lib/typescript/Menu.d.ts +23 -0
  119. package/lib/typescript/Menu.d.ts.map +1 -0
  120. package/lib/typescript/Message.d.ts +14 -0
  121. package/lib/typescript/Message.d.ts.map +1 -0
  122. package/lib/typescript/Popover.d.ts +71 -0
  123. package/lib/typescript/Popover.d.ts.map +1 -0
  124. package/lib/typescript/Progress.d.ts +12 -0
  125. package/lib/typescript/Progress.d.ts.map +1 -0
  126. package/lib/typescript/Select.d.ts +30 -0
  127. package/lib/typescript/Select.d.ts.map +1 -0
  128. package/lib/typescript/Skeleton.d.ts +13 -0
  129. package/lib/typescript/Skeleton.d.ts.map +1 -0
  130. package/lib/typescript/Slider.d.ts +21 -0
  131. package/lib/typescript/Slider.d.ts.map +1 -0
  132. package/lib/typescript/Spinner.d.ts +12 -0
  133. package/lib/typescript/Spinner.d.ts.map +1 -0
  134. package/lib/typescript/Swap.d.ts +25 -0
  135. package/lib/typescript/Swap.d.ts.map +1 -0
  136. package/lib/typescript/Tabs.d.ts +18 -0
  137. package/lib/typescript/Tabs.d.ts.map +1 -0
  138. package/lib/typescript/Text.d.ts +20 -0
  139. package/lib/typescript/Text.d.ts.map +1 -0
  140. package/lib/typescript/TextField.d.ts +36 -0
  141. package/lib/typescript/TextField.d.ts.map +1 -0
  142. package/lib/typescript/Toast.d.ts +25 -0
  143. package/lib/typescript/Toast.d.ts.map +1 -0
  144. package/lib/typescript/audio.d.ts +10 -0
  145. package/lib/typescript/audio.d.ts.map +1 -0
  146. package/lib/typescript/blur.d.ts +4 -0
  147. package/lib/typescript/blur.d.ts.map +1 -0
  148. package/lib/typescript/controls.d.ts +37 -0
  149. package/lib/typescript/controls.d.ts.map +1 -0
  150. package/lib/typescript/feel.d.ts +10 -0
  151. package/lib/typescript/feel.d.ts.map +1 -0
  152. package/lib/typescript/generated/tokens.d.ts +499 -0
  153. package/lib/typescript/generated/tokens.d.ts.map +1 -0
  154. package/lib/typescript/haptics.d.ts +7 -0
  155. package/lib/typescript/haptics.d.ts.map +1 -0
  156. package/lib/typescript/icon-host.d.ts +30 -0
  157. package/lib/typescript/icon-host.d.ts.map +1 -0
  158. package/lib/typescript/icon-shape.d.ts +28 -0
  159. package/lib/typescript/icon-shape.d.ts.map +1 -0
  160. package/lib/typescript/icon.d.ts +24 -0
  161. package/lib/typescript/icon.d.ts.map +1 -0
  162. package/lib/typescript/index.d.ts +37 -0
  163. package/lib/typescript/index.d.ts.map +1 -0
  164. package/lib/typescript/layout.d.ts +24 -0
  165. package/lib/typescript/layout.d.ts.map +1 -0
  166. package/lib/typescript/marks.d.ts +23 -0
  167. package/lib/typescript/marks.d.ts.map +1 -0
  168. package/lib/typescript/motion.d.ts +30 -0
  169. package/lib/typescript/motion.d.ts.map +1 -0
  170. package/lib/typescript/overlay.d.ts +33 -0
  171. package/lib/typescript/overlay.d.ts.map +1 -0
  172. package/lib/typescript/package.json +1 -0
  173. package/lib/typescript/pending.d.ts +26 -0
  174. package/lib/typescript/pending.d.ts.map +1 -0
  175. package/lib/typescript/presence.d.ts +37 -0
  176. package/lib/typescript/presence.d.ts.map +1 -0
  177. package/lib/typescript/press.d.ts +12 -0
  178. package/lib/typescript/press.d.ts.map +1 -0
  179. package/lib/typescript/screen.d.ts +21 -0
  180. package/lib/typescript/screen.d.ts.map +1 -0
  181. package/lib/typescript/success.d.ts +13 -0
  182. package/lib/typescript/success.d.ts.map +1 -0
  183. package/lib/typescript/theme.d.ts +32 -0
  184. package/lib/typescript/theme.d.ts.map +1 -0
  185. package/package.json +123 -3
  186. package/src/AudioPlayer.tsx +106 -0
  187. package/src/Avatar.tsx +44 -0
  188. package/src/Badge.tsx +45 -0
  189. package/src/BottomSheet.tsx +109 -0
  190. package/src/Bubble.tsx +112 -0
  191. package/src/Button.tsx +168 -0
  192. package/src/Card.tsx +70 -0
  193. package/src/Dialog.tsx +93 -0
  194. package/src/Disclosure.tsx +108 -0
  195. package/src/EmptyState.tsx +51 -0
  196. package/src/Link.tsx +61 -0
  197. package/src/ListItem.tsx +78 -0
  198. package/src/Menu.tsx +57 -0
  199. package/src/Message.tsx +43 -0
  200. package/src/Popover.tsx +145 -0
  201. package/src/Progress.tsx +33 -0
  202. package/src/Select.tsx +118 -0
  203. package/src/Skeleton.tsx +28 -0
  204. package/src/Slider.tsx +107 -0
  205. package/src/Spinner.tsx +18 -0
  206. package/src/Swap.tsx +74 -0
  207. package/src/Tabs.tsx +84 -0
  208. package/src/Text.tsx +44 -0
  209. package/src/TextField.tsx +137 -0
  210. package/src/Toast.tsx +122 -0
  211. package/src/audio.tsx +56 -0
  212. package/src/blur.tsx +33 -0
  213. package/src/controls.tsx +224 -0
  214. package/src/feel.ts +22 -0
  215. package/src/generated/tokens.ts +653 -0
  216. package/src/haptics.tsx +26 -0
  217. package/src/icon-host.tsx +46 -0
  218. package/src/icon-shape.ts +213 -0
  219. package/src/icon.tsx +276 -0
  220. package/src/index.ts +36 -0
  221. package/src/layout.tsx +40 -0
  222. package/src/marks.tsx +79 -0
  223. package/src/motion.ts +94 -0
  224. package/src/overlay.tsx +77 -0
  225. package/src/pending.tsx +135 -0
  226. package/src/presence.tsx +68 -0
  227. package/src/press.ts +23 -0
  228. package/src/screen.tsx +37 -0
  229. package/src/success.tsx +48 -0
  230. package/src/theme.tsx +49 -0
package/src/marks.tsx ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Marks drawn with views, without SVG, for the pieces of the main entry: a tick, a dash and an exclamation. Each
3
+ * stroke is a bar that grows from where it starts, turned along it; the next one starts where it ends. Only
4
+ * `transform` and `opacity` move. (SPEC §15.14)
5
+ */
6
+ import { useEffect } from 'react';
7
+ import { View, type StyleProp, type ViewStyle } from 'react-native';
8
+ import Animated, { useAnimatedStyle, useSharedValue, type SharedValue } from 'react-native-reanimated';
9
+ import { spring } from './motion';
10
+
11
+ /** x1 y1 x2 y2, on the 16 × 16 grid of the icons. */
12
+ type Segment = readonly [number, number, number, number];
13
+
14
+ /** As the icon `tick`. */
15
+ export const TICK: readonly Segment[] = [
16
+ [3.5, 8.5, 6.5, 11.5],
17
+ [6.5, 11.5, 12.5, 4.5],
18
+ ];
19
+ export const DASH: readonly Segment[] = [[4, 8, 12, 8]];
20
+ /** A bar, then its dot. */
21
+ export const BANG: readonly Segment[] = [
22
+ [8, 3.5, 8, 9],
23
+ [8, 12, 8, 12],
24
+ ];
25
+
26
+ export interface MarkProps {
27
+ segments: readonly Segment[];
28
+ /** Drawn, or not; it draws and undraws on the snappy spring. */
29
+ shown: boolean;
30
+ /** Its side, in points. Default: 16. */
31
+ size?: number;
32
+ color: string;
33
+ /** The width of its stroke, in points. Default: 1.5 of every 16. */
34
+ stroke?: number;
35
+ style?: StyleProp<ViewStyle>;
36
+ testID?: string;
37
+ }
38
+
39
+ const length = ([x1, y1, x2, y2]: Segment): number => Math.hypot(x2 - x1, y2 - y1);
40
+
41
+ export function Mark({ segments, shown, size = 16, color, stroke, style, testID }: MarkProps) {
42
+ const t = useSharedValue(shown ? 1 : 0);
43
+ useEffect(() => {
44
+ t.value = spring(shown ? 1 : 0, 'snappy');
45
+ }, [shown, t]);
46
+ // A dot has no length: it takes a share of the way as if it were a short stroke.
47
+ const lengths = segments.map((s) => Math.max(length(s), 1));
48
+ const total = lengths.reduce((a, b) => a + b, 0);
49
+ let from = 0;
50
+ return (
51
+ <View testID={testID} aria-hidden pointerEvents="none" style={[{ width: size, height: size }, style]}>
52
+ {segments.map((segment, i) => {
53
+ const part = lengths[i]! / total;
54
+ const bar = <Bar key={i} segment={segment} from={from} part={part} t={t} k={size / 16} h={stroke ?? (1.5 * size) / 16} color={color} />;
55
+ from += part;
56
+ return bar;
57
+ })}
58
+ </View>
59
+ );
60
+ }
61
+
62
+ function Bar({ segment, from, part, t, k, h, color }: { segment: Segment; from: number; part: number; t: SharedValue<number>; k: number; h: number; color: string }) {
63
+ const [x1, y1, x2, y2] = segment;
64
+ const angle = Math.atan2(y2 - y1, x2 - x1);
65
+ const grow = useAnimatedStyle(() => {
66
+ const local = Math.min(1, Math.max(0, (t.value - from) / part));
67
+ // Below 2 % it is not there: the spring that unwrites it swings past 0 and would show a sliver.
68
+ return { opacity: local > 0.02 ? 1 : 0, transform: [{ rotate: `${angle}rad` }, { scaleX: Math.max(local, 0.001) }] };
69
+ });
70
+ // Round ends, as the stroke of the icons: the bar reaches half its width past each end.
71
+ return (
72
+ <Animated.View
73
+ style={[
74
+ { position: 'absolute', left: x1 * k - h / 2, top: y1 * k - h / 2, width: length(segment) * k + h, height: h, borderRadius: h / 2, backgroundColor: color, transformOrigin: [h / 2, h / 2, 0] },
75
+ grow,
76
+ ]}
77
+ />
78
+ );
79
+ }
package/src/motion.ts ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The motion vocabulary of Fluxus on Reanimated: the same names, durations and
3
+ * springs as the web (core/src/tokens.ts). With reduced motion on in the system,
4
+ * a value goes to its end at once. (SPEC §15, §15.12)
5
+ */
6
+ import { Easing, ReduceMotion, defineAnimation, makeMutable, withSpring, withTiming, type AnimationCallback } from 'react-native-reanimated';
7
+ import { motion } from './generated/tokens';
8
+
9
+ export type SpringPreset = keyof typeof motion.spring;
10
+ export type DurationToken = keyof typeof motion.duration;
11
+ export type EasingToken = keyof typeof motion.easing;
12
+
13
+ /** How many times slower than real every animation of Fluxus runs: 1 is real time. The UI thread reads `slow`. */
14
+ const slow = makeMutable(1);
15
+ let scale = 1;
16
+
17
+ /** For a screen that shows the motion, or to look at it closely: 4 makes everything four times slower. */
18
+ export const setMotionScale = (k: number): void => {
19
+ scale = Math.max(1, k);
20
+ slow.value = scale;
21
+ };
22
+
23
+ /** A duration in ms, at the speed the motion runs. On the JS thread, and safe while rendering. */
24
+ export const ms = (duration: number): number => duration * scale;
25
+
26
+ export const spring = (to: number, preset: SpringPreset = 'smooth'): number => {
27
+ 'worklet';
28
+ const k = slow.value;
29
+ const { stiffness, damping, mass } = motion.spring[preset];
30
+ // The same curve, k times longer: time stretches, the shape stays.
31
+ return withSpring(to, { stiffness: stiffness / (k * k), damping: damping / k, mass, reduceMotion: ReduceMotion.System });
32
+ };
33
+
34
+ export const timing = (to: number, duration: DurationToken = 'normal', easing: EasingToken = 'standard'): number => {
35
+ 'worklet';
36
+ const [a, b, c, d] = motion.easing[easing];
37
+ return withTiming(to, { duration: motion.duration[duration] * slow.value, easing: Easing.bezier(a, b, c, d), reduceMotion: ReduceMotion.System });
38
+ };
39
+
40
+ interface FluxSpring {
41
+ onFrame: (animation: FluxSpring, now: number) => boolean;
42
+ onStart: (animation: FluxSpring, value: number, now: number, previous: FluxSpring | undefined) => void;
43
+ toValue: number;
44
+ current: number;
45
+ velocity: number;
46
+ last: number;
47
+ callback?: AnimationCallback;
48
+ }
49
+
50
+ export interface FluxSpringConfig {
51
+ stiffness: number;
52
+ damping: number;
53
+ /** Units per second, added to the speed it already has. */
54
+ velocity?: number;
55
+ restDelta?: number;
56
+ restSpeed?: number;
57
+ }
58
+
59
+ /**
60
+ * The spring of the web (core/src/spring.ts): semi-implicit Euler in steps of 1/120 s. Started over another,
61
+ * it keeps its speed, wherever that points: a value sent back turns round, as `retarget` does on the web.
62
+ */
63
+ export function withFluxSpring(toValue: number, config: FluxSpringConfig, callback?: AnimationCallback): number {
64
+ 'worklet';
65
+ const k = slow.value;
66
+ return defineAnimation<FluxSpring>(toValue, () => {
67
+ 'worklet';
68
+ const restDelta = config.restDelta ?? 0.01;
69
+ const restSpeed = config.restSpeed ?? 0.01;
70
+ const onFrame = (a: FluxSpring, now: number): boolean => {
71
+ let left = Math.min(Math.max(0, now - a.last) / 1000, 4 / 60) / k;
72
+ a.last = now;
73
+ while (left > 0) {
74
+ const dt = Math.min(1 / 120, left);
75
+ left -= dt;
76
+ a.velocity += (-config.stiffness * (a.current - a.toValue) - config.damping * a.velocity) * dt;
77
+ a.current += a.velocity * dt;
78
+ }
79
+ if (Math.abs(a.current - a.toValue) < restDelta && Math.abs(a.velocity) < restSpeed) {
80
+ a.current = a.toValue;
81
+ a.velocity = 0;
82
+ return true;
83
+ }
84
+ return false;
85
+ };
86
+ const onStart = (a: FluxSpring, value: number, now: number, previous: FluxSpring | undefined): void => {
87
+ a.current = value;
88
+ a.last = now;
89
+ a.velocity = (previous?.velocity ?? 0) + (config.velocity ?? 0);
90
+ };
91
+ // Not its target: Reanimated skips an animation whose target is where the value already is, and a push starts there.
92
+ return { onFrame, onStart, toValue, current: Number.NaN, velocity: 0, last: 0, callback } as FluxSpring;
93
+ }) as unknown as number;
94
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * What opens above everything: a window of React Native (`Modal`) that paints and moves nothing of its own,
3
+ * where Fluxus draws the veil and moves the panel. Back on Android, Escape in a browser and the scrub of
4
+ * VoiceOver close it. (SPEC §15.8)
5
+ */
6
+ import { useEffect, useState, type ReactNode } from 'react';
7
+ import { AccessibilityInfo, Modal, Platform, Pressable, StyleSheet, View, type HostInstance, type ViewStyle } from 'react-native';
8
+ import Animated, { useAnimatedStyle, useReducedMotion, useSharedValue, type SharedValue } from 'react-native-reanimated';
9
+ import { motion } from './generated/tokens';
10
+ import { ms, spring, timing } from './motion';
11
+ import { useTheme, type Theme } from './theme';
12
+ import { ToastLayer } from './Toast';
13
+
14
+ /** A screen reader goes to it: to the title on opening, back to what opened it on closing. */
15
+ export const focusOn = (target: unknown): void => {
16
+ if (target && Platform.OS !== 'web') AccessibilityInfo.sendAccessibilityEvent(target as HostInstance, 'focus');
17
+ };
18
+
19
+ /** The surface of what floats: raised, edged, and with the one shadow of the package. */
20
+ export const floating = (theme: Theme): ViewStyle => ({
21
+ borderWidth: 1,
22
+ borderColor: theme.color['border.default'],
23
+ borderRadius: theme.size['radius.card'],
24
+ backgroundColor: theme.color['surface.raised'],
25
+ boxShadow: [{ offsetX: 0, offsetY: theme.size['space.2'], blurRadius: theme.size['space.6'], color: theme.color['shadow.tint'] }],
26
+ });
27
+
28
+ /** `mounted` outlives `open` by the time it takes to go; `t` goes 0 → 1 as it comes and back as it goes. */
29
+ export function useOverlay(open: boolean): { mounted: boolean; t: SharedValue<number> } {
30
+ const reduced = useReducedMotion();
31
+ const [mounted, setMounted] = useState(open);
32
+ const t = useSharedValue(0);
33
+ useEffect(() => {
34
+ if (open) {
35
+ setMounted(true);
36
+ t.value = spring(1, 'smooth');
37
+ return;
38
+ }
39
+ t.value = timing(0, 'fast', 'accelerate');
40
+ const timer = setTimeout(() => setMounted(false), reduced ? 0 : ms(motion.duration.fast));
41
+ return () => clearTimeout(timer);
42
+ }, [open, reduced, t]);
43
+ return { mounted, t };
44
+ }
45
+
46
+ export interface OverlayProps {
47
+ open: boolean;
48
+ /** Back on Android, Escape in a browser, the scrub of VoiceOver, and a press outside if `dismissible`. */
49
+ onClose: () => void;
50
+ /** It darkens what is behind. Default: true. */
51
+ veil?: boolean;
52
+ /** A press outside closes it. Default: true. */
53
+ dismissible?: boolean;
54
+ /** Once the window is on the screen. */
55
+ onShow?: () => void;
56
+ /** The panel, given `t`, in a box as big as the screen. */
57
+ children: (t: SharedValue<number>) => ReactNode;
58
+ }
59
+
60
+ export function Overlay({ open, onClose, veil = true, dismissible = true, onShow, children }: OverlayProps) {
61
+ const theme = useTheme();
62
+ const { mounted, t } = useOverlay(open);
63
+ const fade = useAnimatedStyle(() => ({ opacity: t.value }));
64
+ if (!mounted) return null;
65
+ return (
66
+ <Modal transparent visible animationType="none" statusBarTranslucent navigationBarTranslucent onRequestClose={onClose} onShow={onShow}>
67
+ <View style={StyleSheet.absoluteFill} onAccessibilityEscape={onClose}>
68
+ {veil && <Animated.View pointerEvents="none" style={[StyleSheet.absoluteFill, { backgroundColor: theme.color['surface.overlay'] }, fade]} />}
69
+ {/* Outside the panel. A screen reader does not find it: it has the handle, the buttons and its own gesture. */}
70
+ <Pressable aria-hidden accessible={false} tabIndex={-1} style={StyleSheet.absoluteFill} onPress={dismissible ? onClose : undefined} />
71
+ {children(t)}
72
+ {/* A notice of the app called while this is open would be behind it. */}
73
+ <ToastLayer />
74
+ </View>
75
+ </Modal>
76
+ );
77
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The wait is born from the finger, as on the web (core/src/pending.ts, SPEC §14.35): what was pressed and now
3
+ * waits fills slowly from where it was touched, never to the whole; when the answer comes it fills and goes,
4
+ * and if it failed it drains back to the finger. A wait shorter than 150 ms shows nothing; once seen, it lasts
5
+ * 400 ms at least. (SPEC §15.6, §15.9)
6
+ */
7
+ import { useEffect, useRef, useState, type ReactNode } from 'react';
8
+ import type { GestureResponderEvent, LayoutChangeEvent } from 'react-native';
9
+ import Animated, { Easing, ReduceMotion, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withTiming } from 'react-native-reanimated';
10
+ import { motion } from './generated/tokens';
11
+ import { ms } from './motion';
12
+
13
+ const DELAY = 150;
14
+ const MIN_VISIBLE = 400;
15
+ /** How far it gets by itself, of the way to the farthest corner, and the weight of its colour. */
16
+ const REACH = 0.9;
17
+ const TINT = 0.14;
18
+
19
+ /**
20
+ * `onPress` may return a promise: until it settles, what was pressed waits. If it is rejected, it failed: the
21
+ * third value is true until the next press. The rejection goes no further: the app has its own `catch`. `onEnd`
22
+ * hears how it ended, even when it ends before a render shows it waiting.
23
+ */
24
+ export function useAsyncPress<E>(onPress: ((event: E) => unknown) | null | undefined, onEnd?: (failed: boolean) => void): [waiting: boolean, run: (event: E) => void, failed: boolean] {
25
+ const [state, setState] = useState<'idle' | 'waiting' | 'failed'>('idle');
26
+ const alive = useRef(true);
27
+ useEffect(() => {
28
+ alive.current = true;
29
+ return () => {
30
+ alive.current = false;
31
+ };
32
+ }, []);
33
+ const run = (event: E): void => {
34
+ const result = onPress?.(event) as PromiseLike<unknown> | undefined;
35
+ if (typeof result?.then !== 'function') return;
36
+ setState('waiting');
37
+ const end = (next: 'idle' | 'failed') => (): void => {
38
+ if (!alive.current) return;
39
+ setState(next);
40
+ onEnd?.(next === 'failed');
41
+ };
42
+ result.then(end('idle'), end('failed'));
43
+ };
44
+ return [state === 'waiting', run, state === 'failed'];
45
+ }
46
+
47
+ /** `done` runs once `result` is fulfilled if it is a promise, and at once if it is not. If it fails, it does not run. */
48
+ export function settle(result: unknown, done: () => void): void | Promise<void> {
49
+ const promise = result as PromiseLike<unknown> | undefined;
50
+ if (typeof promise?.then !== 'function') return done();
51
+ return Promise.resolve(promise).then(done, () => undefined);
52
+ }
53
+
54
+ interface FillProps {
55
+ x: number;
56
+ y: number;
57
+ /** As far as the farthest corner. */
58
+ radius: number;
59
+ ink: string;
60
+ /** How the wait ended, once it has. */
61
+ ending: false | 'done' | 'failed';
62
+ }
63
+
64
+ /** Mounted only while something waits: at rest, what can wait carries no animated view. */
65
+ function Fill({ x, y, radius, ink, ending }: FillProps) {
66
+ const reduced = useReducedMotion();
67
+ const grow = useSharedValue(reduced ? 1 : 0);
68
+ const fade = useSharedValue(1);
69
+ useEffect(() => {
70
+ const fast = ms(motion.duration.fast);
71
+ if (ending === 'failed') grow.value = withTiming(0, { duration: ms(motion.duration.normal), reduceMotion: ReduceMotion.System });
72
+ else if (ending) {
73
+ grow.value = withTiming(1, { duration: fast, reduceMotion: ReduceMotion.System });
74
+ fade.value = withDelay(fast, withTiming(0, { duration: fast, reduceMotion: ReduceMotion.System }));
75
+ // It slows as it goes and never gets there: it does not pretend to know how long.
76
+ } else if (!reduced) grow.value = withTiming(REACH, { duration: ms(4000), easing: Easing.out(Easing.exp) });
77
+ }, [ending, reduced, grow, fade]);
78
+ const style = useAnimatedStyle(() => ({ opacity: fade.value * TINT, transform: [{ scale: grow.value }] }));
79
+ // Where the finger was, in the points of the element: `left` and `top`, not the direction of the language.
80
+ return <Animated.View pointerEvents="none" aria-hidden style={[{ position: 'absolute', left: x - radius, top: y - radius, width: 2 * radius, height: 2 * radius, borderRadius: radius, backgroundColor: ink }, style]} />;
81
+ }
82
+
83
+ /**
84
+ * For what is pressed and may wait. Give it `onPressIn` and `onLayout`, put `fill` first inside it, and clip it
85
+ * (`overflow: 'hidden'`). `ink` is the colour of its text; `failed`, whether the wait that ends now did.
86
+ */
87
+ export function usePending(waiting: boolean, ink: string, failed = false): { onPressIn: (e: GestureResponderEvent) => void; onLayout: (e: LayoutChangeEvent) => void; fill: ReactNode } {
88
+ const [phase, setPhase] = useState<'idle' | 'shown' | 'done' | 'failed'>('idle');
89
+ const how = useRef(failed);
90
+ how.current = failed;
91
+ const origin = useRef<{ x: number; y: number } | null>(null);
92
+ const size = useRef({ w: 0, h: 0 });
93
+ const since = useRef(0);
94
+ useEffect(() => {
95
+ if (waiting) {
96
+ const timer = setTimeout(() => {
97
+ since.current = Date.now();
98
+ setPhase('shown');
99
+ }, DELAY);
100
+ return () => clearTimeout(timer);
101
+ }
102
+ if (phase !== 'shown') return;
103
+ let last: ReturnType<typeof setTimeout>;
104
+ const timer = setTimeout(
105
+ () => {
106
+ setPhase(how.current ? 'failed' : 'done');
107
+ last = setTimeout(() => setPhase('idle'), ms(how.current ? motion.duration.normal : motion.duration.fast * 2));
108
+ },
109
+ Math.max(0, MIN_VISIBLE - (Date.now() - since.current)),
110
+ );
111
+ return () => {
112
+ clearTimeout(timer);
113
+ clearTimeout(last);
114
+ };
115
+ // `phase` is read, not followed: only a change of `waiting` moves it on.
116
+ }, [waiting]);
117
+ const { w, h } = size.current;
118
+ const at = origin.current ?? { x: w / 2, y: h / 2 };
119
+ return {
120
+ onPressIn(e) {
121
+ // The event gives the point in the window; the element says where it is in it.
122
+ origin.current = null;
123
+ // Pressed with a keyboard there is no point: it fills from the centre.
124
+ if (!e?.nativeEvent) return;
125
+ const { pageX, pageY } = e.nativeEvent;
126
+ (e.currentTarget as unknown as { measureInWindow?: (done: (x: number, y: number) => void) => void } | null)?.measureInWindow?.((x, y) => {
127
+ origin.current = { x: pageX - x, y: pageY - y };
128
+ });
129
+ },
130
+ onLayout(e) {
131
+ size.current = { w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height };
132
+ },
133
+ fill: phase === 'idle' ? null : <Fill x={at.x} y={at.y} radius={Math.hypot(Math.max(at.x, w - at.x), Math.max(at.y, h - at.y))} ink={ink} ending={phase === 'shown' ? false : phase} />,
134
+ };
135
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Nothing jumps: what comes fades in as it rises, what goes fades out, and what
3
+ * stays glides to its new place. The values of the web (core/src/stagger.ts),
4
+ * on the layout animations of Reanimated. With reduced motion on in the system
5
+ * they are immediate. (SPEC §15.4)
6
+ */
7
+ import type { ComponentRef, Ref } from 'react';
8
+ import { Platform, type ViewProps } from 'react-native';
9
+ import Animated, { Easing, FadeInDown, FadeOut, LinearTransition, ReduceMotion } from 'react-native-reanimated';
10
+ import { motion } from './generated/tokens';
11
+ import { ms } from './motion';
12
+
13
+ const curve = (name: keyof typeof motion.easing) => {
14
+ const [a, b, c, d] = motion.easing[name];
15
+ return Easing.bezier(a, b, c, d);
16
+ };
17
+ /** How far it rises as it comes, and how long the nth of a group waits for the one before. */
18
+ export const RISE = 12;
19
+ export const STAGGER = 70;
20
+
21
+ /** For `entering`: it fades in as it rises; `index` is its place in a group that comes together. */
22
+ export const enter = (index = 0) =>
23
+ FadeInDown.duration(ms(motion.duration.normal))
24
+ .delay(ms(index * STAGGER))
25
+ .easing(curve('decelerate'))
26
+ .withInitialValues({ transform: [{ translateY: RISE }] })
27
+ .reduceMotion(ReduceMotion.System);
28
+
29
+ /** For `exiting`: it fades out, fast. */
30
+ export const exit = () => FadeOut.duration(ms(motion.duration.fast)).easing(curve('accelerate')).reduceMotion(ReduceMotion.System);
31
+
32
+ /** For `layout`: it glides to where it is now, on the smooth spring. */
33
+ export const shift = () => {
34
+ const { stiffness, damping, mass } = motion.spring.smooth;
35
+ const k = ms(1);
36
+ return LinearTransition.springify().stiffness(stiffness / (k * k)).damping(damping / k).mass(mass).reduceMotion(ReduceMotion.System);
37
+ };
38
+
39
+ interface Presence {
40
+ entering: ReturnType<typeof enter>;
41
+ exiting: ReturnType<typeof exit>;
42
+ layout: ReturnType<typeof shift>;
43
+ }
44
+ const MADE = new Map<string, Presence>();
45
+
46
+ /**
47
+ * The three, for a view that comes, goes and moves. In a browser they are off: there Reanimated pins a view
48
+ * that has them where it first was (`position: absolute`, seen with 4.7.1), and the layout breaks.
49
+ */
50
+ export const presence = (index = 0): Partial<Presence> => {
51
+ if (Platform.OS === 'web') return {};
52
+ // One set for each place in a group, made once: a render does not build them again.
53
+ const key = `${index}:${ms(1)}`;
54
+ let made = MADE.get(key);
55
+ if (!made) MADE.set(key, (made = { entering: enter(index), exiting: exit(), layout: shift() }));
56
+ return made;
57
+ };
58
+
59
+ export interface AppearProps extends ViewProps {
60
+ /** Its place in a group that comes together: each waits a little for the one before. */
61
+ index?: number;
62
+ ref?: Ref<ComponentRef<typeof Animated.View>>;
63
+ }
64
+
65
+ /** A view that comes, goes and moves without a jump. Its siblings glide too when each is an Appear. */
66
+ export function Appear({ index = 0, ...rest }: AppearProps) {
67
+ return <Animated.View {...presence(index)} {...rest} />;
68
+ }
package/src/press.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { GestureResponderEvent, PressableProps } from 'react-native';
2
+ import { useAnimatedStyle, useSharedValue } from 'react-native-reanimated';
3
+ import { spring } from './motion';
4
+
5
+ /** As the web (core/src/press.ts): what is pressed gives a little, on the snappy spring. */
6
+ const PRESSED = 0.97;
7
+
8
+ /** The style and the two handlers of something that gives when pressed; the handlers of the app still run. */
9
+ export function usePress({ onPressIn, onPressOut }: Pick<PressableProps, 'onPressIn' | 'onPressOut'>) {
10
+ const scale = useSharedValue(1);
11
+ const style = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));
12
+ return {
13
+ style,
14
+ onPressIn: (e: GestureResponderEvent) => {
15
+ scale.value = spring(PRESSED, 'snappy');
16
+ onPressIn?.(e);
17
+ },
18
+ onPressOut: (e: GestureResponderEvent) => {
19
+ scale.value = spring(1, 'snappy');
20
+ onPressOut?.(e);
21
+ },
22
+ };
23
+ }
package/src/screen.tsx ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `@fluxus-ui/native/screen`: the ground of a screen, inside the safe area. Its own entry, so that an app that
3
+ * lays out its screens some other way does not need react-native-safe-area-context. (SPEC §15.5)
4
+ */
5
+ import type { ComponentRef, Ref } from 'react';
6
+ import { ScrollView, View, type ScrollViewProps, type ViewProps } from 'react-native';
7
+ import { SafeAreaView, type Edge } from 'react-native-safe-area-context';
8
+ import { useTheme } from './theme';
9
+
10
+ export interface ScreenProps extends ViewProps {
11
+ /** It scrolls, and the keyboard does not cover the field in use. */
12
+ scroll?: boolean;
13
+ /** Which sides keep clear of the notch and the bars. Default: all. With a header or a tab bar, leave theirs out. */
14
+ edges?: readonly Edge[];
15
+ /** The gutter of the theme around what it holds, and its gap between. Default: true. */
16
+ padded?: boolean;
17
+ /** With `scroll`: its ScrollView, to take it somewhere (`scrollToEnd` in a chat). */
18
+ scrollRef?: Ref<ComponentRef<typeof ScrollView>>;
19
+ /** With `scroll`: what else its ScrollView takes (`onScroll`, `testID`…). Its padding stays the one of the theme. */
20
+ scrollProps?: Omit<ScrollViewProps, 'children'>;
21
+ }
22
+
23
+ export function Screen({ scroll = false, edges, padded = true, scrollRef, scrollProps, style, children, ...rest }: ScreenProps) {
24
+ const theme = useTheme();
25
+ const inner = padded ? { padding: theme.size['layout.gutter'], gap: theme.size['space.4'] } : null;
26
+ return (
27
+ <SafeAreaView edges={edges} {...rest} style={[{ flex: 1, backgroundColor: theme.color['surface.page'] }, style]}>
28
+ {scroll ? (
29
+ <ScrollView keyboardShouldPersistTaps="handled" keyboardDismissMode="interactive" automaticallyAdjustKeyboardInsets {...scrollProps} ref={scrollRef} contentContainerStyle={[inner, scrollProps?.contentContainerStyle]}>
30
+ {children}
31
+ </ScrollView>
32
+ ) : (
33
+ <View style={[{ flex: 1 }, inner]}>{children}</View>
34
+ )}
35
+ </SafeAreaView>
36
+ );
37
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `Success`, of the `icon` entry: a tick drawn inside a circle, as it comes. «Tema completado», «Solicitud
3
+ * habilitada», «Pago enviado». It grows on the bouncy spring while the `check` icon goes from `off` to rest: the
4
+ * circle is drawn, then the tick. With haptics registered (`enableHaptics`), it is felt when the tick is there.
5
+ * (SPEC §15.14)
6
+ */
7
+ import { useEffect, useState } from 'react';
8
+ import Animated, { useAnimatedStyle, useSharedValue } from 'react-native-reanimated';
9
+ import { check } from '@fluxus-ui/icons';
10
+ import { feel } from './feel';
11
+ import { motion } from './generated/tokens';
12
+ import { Icon } from './icon';
13
+ import { ms, spring } from './motion';
14
+ import { useTheme } from './theme';
15
+
16
+ export interface SuccessProps {
17
+ /** What went well, for a screen reader. */
18
+ label: string;
19
+ /** Points. Default: 64. */
20
+ size?: number;
21
+ /** Default: the solid colour of success. */
22
+ color?: string;
23
+ /** When the tick is there: after `slow`. */
24
+ onShown?: () => void;
25
+ testID?: string;
26
+ }
27
+
28
+ export function Success({ label, size = 64, color, onShown, testID }: SuccessProps) {
29
+ const theme = useTheme();
30
+ const [state, setState] = useState<'off' | 'rest'>('off');
31
+ const grow = useSharedValue(0.6);
32
+ useEffect(() => {
33
+ setState('rest');
34
+ grow.value = spring(1, 'bouncy');
35
+ const timer = setTimeout(() => {
36
+ feel('success');
37
+ onShown?.();
38
+ }, ms(motion.duration.slow));
39
+ return () => clearTimeout(timer);
40
+ // Once, as it comes.
41
+ }, []);
42
+ const style = useAnimatedStyle(() => ({ transform: [{ scale: grow.value }] }));
43
+ return (
44
+ <Animated.View testID={testID} accessible role="img" aria-label={label} style={[{ alignSelf: 'center' }, style]}>
45
+ <Icon icon={check} state={state} size={size} color={color ?? theme.color['state.success.solid']} />
46
+ </Animated.View>
47
+ );
48
+ }
package/src/theme.tsx ADDED
@@ -0,0 +1,49 @@
1
+ import { createContext, useContext, useMemo, type ReactNode } from 'react';
2
+ import { useColorScheme } from 'react-native';
3
+ import { themes, type ThemeTokens } from './generated/tokens';
4
+
5
+ export type Mode = 'light' | 'dark';
6
+
7
+ /**
8
+ * The faces the app loaded (with expo-font, or linked), by weight. With a face for a weight, text takes
9
+ * that family and no `fontWeight`: Android would thicken it again. Without, the regular one and the weight.
10
+ */
11
+ export interface Fonts {
12
+ regular: string;
13
+ medium?: string;
14
+ bold?: string;
15
+ }
16
+
17
+ /** A theme in one mode: what a component reads. `Theme<typeof theme>` has the tokens of the app too, by name. */
18
+ export type Theme<T extends ThemeTokens = ThemeTokens> = Omit<T, 'color'> & {
19
+ mode: Mode;
20
+ color: T['color']['light'];
21
+ /** Without it, the font of the system. */
22
+ font?: Fonts;
23
+ };
24
+
25
+ const Context = createContext<Theme | null>(null);
26
+
27
+ export interface ThemeProviderProps {
28
+ /** Default: the base theme. */
29
+ theme?: ThemeTokens;
30
+ /** Default: what the system says. */
31
+ mode?: Mode;
32
+ /** Default: the font of the system. */
33
+ fonts?: Fonts;
34
+ children?: ReactNode;
35
+ }
36
+
37
+ export function ThemeProvider({ theme = themes.base, mode, fonts, children }: ThemeProviderProps) {
38
+ const system = useColorScheme();
39
+ const now: Mode = mode ?? (system === 'dark' ? 'dark' : 'light');
40
+ const value = useMemo<Theme>(() => ({ ...theme, mode: now, color: theme.color[now], font: fonts }), [theme, now, fonts?.regular, fonts?.medium, fonts?.bold]);
41
+ return <Context.Provider value={value}>{children}</Context.Provider>;
42
+ }
43
+
44
+ /** The theme, in the mode it is in. `useTheme<typeof theme>()` gives the app its own tokens (`app.…`), checked by name. */
45
+ export function useTheme<T extends ThemeTokens = ThemeTokens>(): Theme<T> {
46
+ const theme = useContext(Context);
47
+ if (!theme) throw new Error('@fluxus-ui/native: no theme. Wrap the app in <ThemeProvider>.');
48
+ return theme as Theme<T>;
49
+ }