@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/Toast.tsx ADDED
@@ -0,0 +1,122 @@
1
+ import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
2
+ import { AccessibilityInfo, Platform, Pressable, View } from 'react-native';
3
+ import Animated, { FadeInDown, FadeOutDown, ReduceMotion } from 'react-native-reanimated';
4
+ import { toneColors } from './Badge';
5
+ import { motion } from './generated/tokens';
6
+ import { BANG, Mark, TICK } from './marks';
7
+ import { ms } from './motion';
8
+ import { RISE, shift } from './presence';
9
+ import { Text } from './Text';
10
+ import { useTheme } from './theme';
11
+
12
+ export interface ToastInput {
13
+ title: string;
14
+ description?: string;
15
+ /** Default: 'info'. */
16
+ tone?: 'info' | 'success' | 'warning' | 'danger';
17
+ /** How long it stays, in ms; 0 stays until it is pressed. Default: 5000, and 0 for a danger. */
18
+ duration?: number;
19
+ }
20
+
21
+ const Context = createContext<((toast: ToastInput) => void) | null>(null);
22
+ /** The notices themselves: the provider paints them, and so does every window open above it. */
23
+ const Layer = createContext<ReactNode>(null);
24
+
25
+ /** Inside a window that opens above the app (`Modal`), where the notices of the app would be behind. */
26
+ export const ToastLayer = (): ReactNode => useContext(Layer);
27
+
28
+ export interface ToastProviderProps {
29
+ children?: ReactNode;
30
+ /** How far from the bottom: the app's safe area, or what a tab bar takes. Default: `space.4`. */
31
+ inset?: number;
32
+ /** What pressing one does, for a screen reader. Default: 'Dismiss'. */
33
+ dismissLabel?: string;
34
+ }
35
+
36
+ /** Said aloud on both platforms: Android reads a live region by itself, iOS has to be told. */
37
+ export const announce = (text: string): void => {
38
+ if (Platform.OS === 'ios') AccessibilityInfo.announceForAccessibility(text);
39
+ };
40
+
41
+ /** Holds the notices of the app above everything it wraps: put it once, near the root. */
42
+ export function ToastProvider({ children, inset, dismissLabel = 'Dismiss' }: ToastProviderProps) {
43
+ const theme = useTheme();
44
+ const [toasts, setToasts] = useState<readonly (ToastInput & { id: number })[]>([]);
45
+ const next = useRef(0);
46
+ const timers = useRef(new Set<ReturnType<typeof setTimeout>>());
47
+ useEffect(() => () => timers.current.forEach(clearTimeout), []);
48
+ const dismiss = useCallback((id: number) => setToasts((list) => list.filter((t) => t.id !== id)), []);
49
+ const toast = useCallback(
50
+ (input: ToastInput) => {
51
+ const id = ++next.current;
52
+ setToasts((list) => [...list, { ...input, id }]);
53
+ announce(input.description ? `${input.title}. ${input.description}` : input.title);
54
+ const ms = input.duration ?? (input.tone === 'danger' ? 0 : 5000);
55
+ if (ms) timers.current.add(setTimeout(() => dismiss(id), ms));
56
+ },
57
+ [dismiss],
58
+ );
59
+ const edge = theme.size['space.4'];
60
+ const layer = (
61
+ <View pointerEvents="box-none" style={{ position: 'absolute', start: edge, end: edge, bottom: inset ?? edge, gap: theme.size['space.2'] }}>
62
+ {toasts.map((t) => (
63
+ <Animated.View key={t.id} {...coming()}>
64
+ <Pressable
65
+ role="alert"
66
+ aria-live={t.tone === 'danger' ? 'assertive' : 'polite'}
67
+ accessibilityHint={dismissLabel}
68
+ onPress={() => dismiss(t.id)}
69
+ style={{ minHeight: theme.size['target.min'], flexDirection: 'row', alignItems: 'center', gap: theme.size['space.3'], padding: theme.size['space.3'], borderWidth: 1, borderColor: theme.color['border.default'], borderRadius: theme.size['radius.card'], backgroundColor: theme.color['surface.raised'] }}
70
+ >
71
+ <ToneMark tone={t.tone ?? 'info'} />
72
+ <View style={{ flex: 1 }}>
73
+ <Text variant="label">{t.title}</Text>
74
+ {t.description !== undefined && (
75
+ <Text variant="caption" tone="muted">
76
+ {t.description}
77
+ </Text>
78
+ )}
79
+ </View>
80
+ </Pressable>
81
+ </Animated.View>
82
+ ))}
83
+ </View>
84
+ );
85
+ return (
86
+ <Context.Provider value={toast}>
87
+ <Layer.Provider value={layer}>{children}</Layer.Provider>
88
+ {layer}
89
+ </Context.Provider>
90
+ );
91
+ }
92
+
93
+ /** `toast({ title })` shows a notice. */
94
+ export function useToast(): (toast: ToastInput) => void {
95
+ const toast = useContext(Context);
96
+ if (!toast) throw new Error('@fluxus-ui/native: no toasts. Wrap the app in <ToastProvider>, inside <ThemeProvider>.');
97
+ return toast;
98
+ }
99
+
100
+ /** Its mark, written as it comes: a tick, an exclamation, or a dot. (SPEC §15.14) */
101
+ function ToneMark({ tone }: { tone: NonNullable<ToastInput['tone']> }) {
102
+ const theme = useTheme();
103
+ const color = toneColors(theme, tone).solid;
104
+ const side = theme.size['icon.md'];
105
+ const [shown, setShown] = useState(false);
106
+ // Drawn after it is on the screen, not with it.
107
+ useEffect(() => setShown(true), []);
108
+ if (tone === 'info') return <View style={{ width: theme.size['space.2'], height: theme.size['space.2'], marginInline: (side - theme.size['space.2']) / 2, borderRadius: theme.size['space.2'], backgroundColor: color }} />;
109
+ return <Mark testID={`mark-${tone}`} segments={tone === 'success' ? TICK : BANG} shown={shown} size={side} color={color} stroke={2} />;
110
+ }
111
+
112
+ /** It comes rising and goes sinking, on the smooth spring. In a browser, as `presence`, nothing. */
113
+ const coming = () => {
114
+ if (Platform.OS === 'web') return {};
115
+ const { stiffness, damping, mass } = motion.spring.smooth;
116
+ const k = ms(1);
117
+ return {
118
+ entering: FadeInDown.springify().stiffness(stiffness / (k * k)).damping(damping / k).mass(mass).withInitialValues({ transform: [{ translateY: RISE }] }).reduceMotion(ReduceMotion.System),
119
+ exiting: FadeOutDown.springify().stiffness(stiffness / (k * k)).damping(damping / k).mass(mass).reduceMotion(ReduceMotion.System),
120
+ layout: shift(),
121
+ };
122
+ };
package/src/audio.tsx ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `@fluxus-ui/native/audio`: the player, playing with expo-audio. Its own entry, so that an app with no sound
3
+ * does not need the library. (SPEC §15.10)
4
+ */
5
+ import { useEffect, useRef, useState } from 'react';
6
+ import { useAudioPlayer, useAudioPlayerStatus, type AudioSource } from 'expo-audio';
7
+ import { AudioPlayer, type AudioPlayerProps } from './AudioPlayer';
8
+
9
+ export interface AudioProps extends Pick<AudioPlayerProps, 'labels' | 'style' | 'testID'> {
10
+ /** What to play: an address, an asset, or null while it is not known (a signed address that is still coming). */
11
+ source: AudioSource;
12
+ /** It could not be played: the app says why. */
13
+ onError?: (message: string) => void;
14
+ }
15
+
16
+ export function Audio({ source, onError, ...rest }: AudioProps) {
17
+ const player = useAudioPlayer(source);
18
+ const status = useAudioPlayerStatus(player);
19
+ // Asked to play: the button waits until the sound runs, or until it is known that it will not.
20
+ // In a browser expo-audio says once more that it is not playing at second 0: it is asked until it has moved on.
21
+ const [asked, setAsked] = useState(false);
22
+ const running = status.playing && status.currentTime > 0;
23
+ useEffect(() => {
24
+ if (running || status.error) setAsked(false);
25
+ }, [running, status.error]);
26
+ // Told once for each error, whatever function the app passes on each render.
27
+ const tell = useRef(onError);
28
+ useEffect(() => {
29
+ tell.current = onError;
30
+ });
31
+ useEffect(() => {
32
+ if (status.error) tell.current?.(status.error);
33
+ }, [status.error]);
34
+ const ended = status.didJustFinish || (status.duration > 0 && status.currentTime >= status.duration);
35
+ return (
36
+ <AudioPlayer
37
+ {...rest}
38
+ disabled={source === null}
39
+ playing={status.playing || asked}
40
+ loading={asked && !status.playing}
41
+ position={status.currentTime}
42
+ duration={status.duration}
43
+ onToggle={() => {
44
+ if (status.playing || asked) {
45
+ setAsked(false);
46
+ return player.pause();
47
+ }
48
+ setAsked(true);
49
+ // Played to the end, it starts again: once it is back at the start.
50
+ if (ended) return void player.seekTo(0).then(() => player.play());
51
+ player.play();
52
+ }}
53
+ onSeek={(seconds) => void player.seekTo(seconds)}
54
+ />
55
+ );
56
+ }
package/src/blur.tsx ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `@fluxus-ui/native/blur`: the Swap that loses focus on a phone too, with the veil of expo-blur over what changes.
3
+ * Its own entry, so that an app without it does not need expo-blur. On Android the blur needs Android 12;
4
+ * below, it only dissolves. (SPEC §15.6)
5
+ */
6
+ import { useRef, type ComponentRef } from 'react';
7
+ import { StyleSheet, type View } from 'react-native';
8
+ import { BlurTargetView, BlurView } from 'expo-blur';
9
+ import Animated, { useAnimatedProps, useAnimatedStyle } from 'react-native-reanimated';
10
+ import { presence } from './presence';
11
+ import { useSwap, type SwapProps } from './Swap';
12
+
13
+ const Veil = Animated.createAnimatedComponent(BlurView);
14
+ /** How blurred it gets at the middle of the change, of the 100 of expo-blur. */
15
+ const DEPTH = 40;
16
+
17
+ export function Swap({ id, children, style, ...rest }: SwapProps) {
18
+ const { content, t, moving } = useSwap(id, children);
19
+ const target = useRef<ComponentRef<typeof View>>(null);
20
+ const body = useAnimatedStyle(() => ({ opacity: 0.4 + 0.6 * t.value }));
21
+ const veil = useAnimatedProps(() => ({ intensity: (1 - t.value) * DEPTH }));
22
+ return (
23
+ <Animated.View layout={presence().layout} {...rest} style={style}>
24
+ <BlurTargetView ref={target}>
25
+ <Animated.View style={body}>{content}</Animated.View>
26
+ </BlurTargetView>
27
+ {/* Only while it changes: at rest there is no veil over the content. */}
28
+ {moving && <Veil pointerEvents="none" blurTarget={target} blurMethod="dimezisBlurViewSdk31Plus" animatedProps={veil} style={StyleSheet.absoluteFill} />}
29
+ </Animated.View>
30
+ );
31
+ }
32
+
33
+ export type { SwapProps };
@@ -0,0 +1,224 @@
1
+ /**
2
+ * What is switched: a checkbox, a switch and a group of radios. Each is one row to press, of 44 points at least,
3
+ * with its label and its help; the mark moves by its transform and the colours fade. (SPEC §15.7)
4
+ */
5
+ import { useEffect, useState, type ReactNode } from 'react';
6
+ import { I18nManager, Pressable, View, type PressableProps, type StyleProp, type ViewProps, type ViewStyle } from 'react-native';
7
+ import Animated, { interpolateColor, useAnimatedStyle, useSharedValue } from 'react-native-reanimated';
8
+ import { feel } from './feel';
9
+ import { fill } from './layout';
10
+ import { DASH, Mark, TICK } from './marks';
11
+ import { spring, timing } from './motion';
12
+ import { Text } from './Text';
13
+ import { useTheme } from './theme';
14
+
15
+ /** A value the app holds, or one the piece holds by itself from `defaultValue`. */
16
+ export function useControlled<T>(value: T | undefined, initial: T, onChange?: (next: T) => void): [T, (next: T) => void] {
17
+ const [own, setOwn] = useState(initial);
18
+ return [
19
+ value === undefined ? own : value,
20
+ (next) => {
21
+ if (value === undefined) setOwn(next);
22
+ onChange?.(next);
23
+ },
24
+ ];
25
+ }
26
+
27
+ interface RowProps extends Omit<PressableProps, 'children' | 'style' | 'role'> {
28
+ role: 'checkbox' | 'switch' | 'radio';
29
+ checked: boolean | 'mixed';
30
+ label: string;
31
+ hint?: string;
32
+ /** The box, the track or the ring. */
33
+ control: ReactNode;
34
+ /** A switch goes after its text; the others before. */
35
+ after?: boolean;
36
+ style?: StyleProp<ViewStyle>;
37
+ }
38
+
39
+ function Row({ role, checked, label, hint, control, after, disabled, style, ...rest }: RowProps) {
40
+ const theme = useTheme();
41
+ return (
42
+ <Pressable
43
+ role={role}
44
+ aria-checked={checked}
45
+ aria-disabled={!!disabled}
46
+ aria-label={hint ? `${label}. ${hint}` : label}
47
+ {...rest}
48
+ disabled={disabled}
49
+ style={[{ minHeight: theme.size['target.min'], flexDirection: after ? 'row-reverse' : 'row', alignItems: 'center', gap: theme.size['space.3'], paddingBlock: theme.size['space.2'], opacity: disabled ? 0.5 : 1 }, style]}
50
+ >
51
+ {control}
52
+ <View style={fill}>
53
+ <Text>{label}</Text>
54
+ {hint !== undefined && (
55
+ <Text variant="caption" tone="muted">
56
+ {hint}
57
+ </Text>
58
+ )}
59
+ </View>
60
+ </Pressable>
61
+ );
62
+ }
63
+
64
+ /** 0 → 1 as it goes on: `to` for what moves, on the snappy spring; `tint` for the colours, on the fast curve. */
65
+ function useOn(on: boolean) {
66
+ const to = useSharedValue(on ? 1 : 0);
67
+ const tint = useSharedValue(on ? 1 : 0);
68
+ useEffect(() => {
69
+ to.value = spring(on ? 1 : 0, 'snappy');
70
+ tint.value = timing(on ? 1 : 0, 'fast');
71
+ }, [on, to, tint]);
72
+ return { to, tint };
73
+ }
74
+
75
+ interface ToggleProps extends Omit<PressableProps, 'children' | 'style' | 'onPress' | 'role'> {
76
+ label: string;
77
+ hint?: string;
78
+ checked?: boolean;
79
+ defaultChecked?: boolean;
80
+ onChange?: (checked: boolean) => void;
81
+ style?: StyleProp<ViewStyle>;
82
+ }
83
+
84
+ export interface CheckboxProps extends ToggleProps {
85
+ /** Neither on nor off: some of what it stands for is chosen. */
86
+ mixed?: boolean;
87
+ }
88
+
89
+ export function Checkbox({ checked, defaultChecked = false, mixed = false, onChange, ...rest }: CheckboxProps) {
90
+ const theme = useTheme();
91
+ const c = theme.color;
92
+ const [on, set] = useControlled(checked, defaultChecked, onChange);
93
+ const { to, tint } = useOn(on || mixed);
94
+ const side = theme.size['icon.md'];
95
+ const box = useAnimatedStyle(() => ({
96
+ backgroundColor: interpolateColor(tint.value, [0, 1], [c['input.bg'], c['accent.default']]),
97
+ borderColor: interpolateColor(tint.value, [0, 1], [c['border.control'], c['accent.default']]),
98
+ }));
99
+ const ink = c['text.on-accent'];
100
+ return (
101
+ <Row
102
+ role="checkbox"
103
+ checked={mixed ? 'mixed' : on}
104
+ {...rest}
105
+ onPress={() => {
106
+ feel('selection');
107
+ set(mixed ? true : !on);
108
+ }}
109
+ control={
110
+ <Animated.View style={[{ width: side, height: side, alignItems: 'center', justifyContent: 'center', borderWidth: 1.5, borderRadius: theme.size['radius.1'] }, box]}>
111
+ {/* The tick is written as the icon writes it; a dash when it is mixed. */}
112
+ <Mark testID="tick" segments={TICK} shown={on && !mixed} size={side * 0.8} color={ink} stroke={2} style={{ position: 'absolute' }} />
113
+ <Mark testID="dash" segments={DASH} shown={mixed} size={side * 0.8} color={ink} stroke={2} style={{ position: 'absolute' }} />
114
+ </Animated.View>
115
+ }
116
+ />
117
+ );
118
+ }
119
+
120
+ export type SwitchProps = ToggleProps;
121
+
122
+ export function Switch({ checked, defaultChecked = false, onChange, ...rest }: SwitchProps) {
123
+ const theme = useTheme();
124
+ const c = theme.color;
125
+ const [on, set] = useControlled(checked, defaultChecked, onChange);
126
+ const { to, tint } = useOn(on);
127
+ const height = theme.size['control.h.sm'];
128
+ const pad = theme.size['space.1'] / 2;
129
+ const thumb = height - 2 * pad;
130
+ const travel = height * 0.75;
131
+ const way = I18nManager.isRTL ? -1 : 1;
132
+ const track = useAnimatedStyle(() => ({ backgroundColor: interpolateColor(tint.value, [0, 1], [c['border.control'], c['accent.default']]) }));
133
+ // Pressed, the knob widens towards where it would go, and gives back when let go.
134
+ const press = useSharedValue(0);
135
+ const knob = useAnimatedStyle(() => ({ transform: [{ translateX: way * to.value * travel }, { scaleX: 1 + 0.15 * press.value }] }));
136
+ return (
137
+ <Row
138
+ role="switch"
139
+ after
140
+ checked={on}
141
+ {...rest}
142
+ onPressIn={(e) => {
143
+ press.value = spring(1, 'snappy');
144
+ rest.onPressIn?.(e);
145
+ }}
146
+ onPressOut={(e) => {
147
+ press.value = spring(0, 'snappy');
148
+ rest.onPressOut?.(e);
149
+ }}
150
+ onPress={() => {
151
+ feel('selection');
152
+ set(!on);
153
+ }}
154
+ control={
155
+ <Animated.View style={[{ width: height + travel, height, padding: pad, borderRadius: height }, track]}>
156
+ <Animated.View style={[{ width: thumb, height: thumb, borderRadius: thumb, backgroundColor: c['surface.base'], transformOrigin: (on ? way < 0 : way > 0) ? 'right' : 'left' }, knob]} />
157
+ </Animated.View>
158
+ }
159
+ />
160
+ );
161
+ }
162
+
163
+ export interface RadioOption {
164
+ value: string;
165
+ label: string;
166
+ hint?: string;
167
+ disabled?: boolean;
168
+ }
169
+
170
+ export interface RadioGroupProps extends Omit<ViewProps, 'children'> {
171
+ /** The name of the group, for a screen reader. */
172
+ label: string;
173
+ options: readonly RadioOption[];
174
+ value?: string | null;
175
+ defaultValue?: string | null;
176
+ onChange?: (value: string) => void;
177
+ disabled?: boolean;
178
+ }
179
+
180
+ function Radio({ option, on, disabled, onPress }: { option: RadioOption; on: boolean; disabled: boolean; onPress: () => void }) {
181
+ const theme = useTheme();
182
+ const c = theme.color;
183
+ const { to, tint } = useOn(on);
184
+ const side = theme.size['icon.md'];
185
+ const press = useSharedValue(0);
186
+ const ring = useAnimatedStyle(() => ({ borderColor: interpolateColor(tint.value, [0, 1], [c['border.control'], c['accent.default']]), transform: [{ scale: 1 - 0.08 * press.value }] }));
187
+ const dot = useAnimatedStyle(() => ({ transform: [{ scale: to.value }] }));
188
+ return (
189
+ <Row
190
+ role="radio"
191
+ checked={on}
192
+ label={option.label}
193
+ hint={option.hint}
194
+ disabled={disabled}
195
+ onPress={onPress}
196
+ onPressIn={() => {
197
+ press.value = spring(1, 'snappy');
198
+ }}
199
+ onPressOut={() => {
200
+ press.value = spring(0, 'snappy');
201
+ }}
202
+ control={
203
+ <Animated.View style={[{ width: side, height: side, alignItems: 'center', justifyContent: 'center', borderWidth: 1.5, borderRadius: side, backgroundColor: c['input.bg'] }, ring]}>
204
+ <Animated.View style={[{ width: side / 2, height: side / 2, borderRadius: side, backgroundColor: c['accent.default'] }, dot]} />
205
+ </Animated.View>
206
+ }
207
+ />
208
+ );
209
+ }
210
+
211
+ /** One of a few, all in sight. */
212
+ export function RadioGroup({ label, options, value, defaultValue = null, onChange, disabled = false, ...rest }: RadioGroupProps) {
213
+ const [chosen, set] = useControlled<string | null>(value, defaultValue, onChange as (next: string | null) => void);
214
+ return (
215
+ <View role="radiogroup" aria-label={label} {...rest}>
216
+ {options.map((option) => (
217
+ <Radio key={option.value} option={option} on={option.value === chosen} disabled={disabled || !!option.disabled} onPress={() => {
218
+ feel('selection');
219
+ set(option.value);
220
+ }} />
221
+ ))}
222
+ </View>
223
+ );
224
+ }
package/src/feel.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The haptics of the main entry, by registration: it never imports the library of haptics. `enableHaptics()` of
3
+ * `@fluxus-ui/native/haptics` gives it the real one; without it, nothing is felt and nothing breaks. (SPEC §15.14)
4
+ */
5
+ export type HapticKind = 'success' | 'warning' | 'error' | 'light' | 'medium' | 'selection';
6
+
7
+ let felt: ((kind: HapticKind) => unknown) | null = null;
8
+
9
+ /** What makes a haptic; null for none. */
10
+ export const setHaptics = (fn: ((kind: HapticKind) => unknown) | null): void => {
11
+ felt = fn;
12
+ };
13
+
14
+ /** A haptic, if there is a way to make one. It never throws. */
15
+ export const feel = (kind: HapticKind): void => {
16
+ if (!felt) return;
17
+ try {
18
+ void Promise.resolve(felt(kind)).catch(() => undefined);
19
+ } catch {
20
+ // A haptic that fails is not felt: nothing else happens.
21
+ }
22
+ };