@expressive-ui/native 0.0.0-stage → 0.1.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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -2
  3. package/dist/Button.d.ts +48 -0
  4. package/dist/Button.d.ts.map +1 -0
  5. package/dist/Button.js +122 -0
  6. package/dist/Button.js.map +1 -0
  7. package/dist/Carousel.d.ts +13 -0
  8. package/dist/Carousel.d.ts.map +1 -0
  9. package/dist/Carousel.js +52 -0
  10. package/dist/Carousel.js.map +1 -0
  11. package/dist/Chips.d.ts +35 -0
  12. package/dist/Chips.d.ts.map +1 -0
  13. package/dist/Chips.js +138 -0
  14. package/dist/Chips.js.map +1 -0
  15. package/dist/Dialogs.d.ts +42 -0
  16. package/dist/Dialogs.d.ts.map +1 -0
  17. package/dist/Dialogs.js +115 -0
  18. package/dist/Dialogs.js.map +1 -0
  19. package/dist/ExpressiveCard.d.ts +20 -0
  20. package/dist/ExpressiveCard.d.ts.map +1 -0
  21. package/dist/ExpressiveCard.js +71 -0
  22. package/dist/ExpressiveCard.js.map +1 -0
  23. package/dist/Fab.d.ts +16 -0
  24. package/dist/Fab.d.ts.map +1 -0
  25. package/dist/Fab.js +104 -0
  26. package/dist/Fab.js.map +1 -0
  27. package/dist/Fields.d.ts +90 -0
  28. package/dist/Fields.d.ts.map +1 -0
  29. package/dist/Fields.js +211 -0
  30. package/dist/Fields.js.map +1 -0
  31. package/dist/Grid.d.ts +8 -0
  32. package/dist/Grid.d.ts.map +1 -0
  33. package/dist/Grid.js +16 -0
  34. package/dist/Grid.js.map +1 -0
  35. package/dist/Inputs.d.ts +33 -0
  36. package/dist/Inputs.d.ts.map +1 -0
  37. package/dist/Inputs.js +172 -0
  38. package/dist/Inputs.js.map +1 -0
  39. package/dist/List.d.ts +20 -0
  40. package/dist/List.d.ts.map +1 -0
  41. package/dist/List.js +222 -0
  42. package/dist/List.js.map +1 -0
  43. package/dist/Menu.d.ts +26 -0
  44. package/dist/Menu.d.ts.map +1 -0
  45. package/dist/Menu.js +117 -0
  46. package/dist/Menu.js.map +1 -0
  47. package/dist/Navigation.d.ts +34 -0
  48. package/dist/Navigation.d.ts.map +1 -0
  49. package/dist/Navigation.js +80 -0
  50. package/dist/Navigation.js.map +1 -0
  51. package/dist/Progress.d.ts +20 -0
  52. package/dist/Progress.d.ts.map +1 -0
  53. package/dist/Progress.js +93 -0
  54. package/dist/Progress.js.map +1 -0
  55. package/dist/Search.d.ts +50 -0
  56. package/dist/Search.d.ts.map +1 -0
  57. package/dist/Search.js +121 -0
  58. package/dist/Search.js.map +1 -0
  59. package/dist/Sheets.d.ts +44 -0
  60. package/dist/Sheets.d.ts.map +1 -0
  61. package/dist/Sheets.js +128 -0
  62. package/dist/Sheets.js.map +1 -0
  63. package/dist/Toolbar.d.ts +13 -0
  64. package/dist/Toolbar.d.ts.map +1 -0
  65. package/dist/Toolbar.js +38 -0
  66. package/dist/Toolbar.js.map +1 -0
  67. package/dist/Transition.d.ts +34 -0
  68. package/dist/Transition.d.ts.map +1 -0
  69. package/dist/Transition.js +93 -0
  70. package/dist/Transition.js.map +1 -0
  71. package/dist/index.d.ts +20 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +20 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/primitives.d.ts +41 -0
  76. package/dist/primitives.d.ts.map +1 -0
  77. package/dist/primitives.js +55 -0
  78. package/dist/primitives.js.map +1 -0
  79. package/dist/theme.d.ts +57 -0
  80. package/dist/theme.d.ts.map +1 -0
  81. package/dist/theme.js +89 -0
  82. package/dist/theme.js.map +1 -0
  83. package/package.json +53 -4
  84. package/src/Button.tsx +347 -0
  85. package/src/Carousel.tsx +108 -0
  86. package/src/Chips.tsx +292 -0
  87. package/src/Dialogs.tsx +252 -0
  88. package/src/ExpressiveCard.tsx +205 -0
  89. package/src/Fab.tsx +187 -0
  90. package/src/Fields.tsx +556 -0
  91. package/src/Grid.tsx +29 -0
  92. package/src/Inputs.tsx +290 -0
  93. package/src/List.tsx +295 -0
  94. package/src/Menu.tsx +238 -0
  95. package/src/Navigation.tsx +198 -0
  96. package/src/Progress.tsx +192 -0
  97. package/src/Search.tsx +351 -0
  98. package/src/Sheets.tsx +273 -0
  99. package/src/Toolbar.tsx +88 -0
  100. package/src/Transition.tsx +155 -0
  101. package/src/index.ts +19 -0
  102. package/src/primitives.tsx +110 -0
  103. package/src/theme.tsx +125 -0
@@ -0,0 +1,88 @@
1
+ import { Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
2
+ import { resolveToolbar, type RuntimeProps } from '@expressive-ui/core';
3
+ import type { FabVariant, ToolbarData } from '@expressive-ui/schema';
4
+ import { tokens } from '@expressive-ui/tokens';
5
+ import { Fab } from './Fab.js';
6
+ import { Icon, T, withAlpha } from './primitives.js';
7
+ import { useExpressiveTheme } from './theme.js';
8
+
9
+ export type ToolbarProps = ToolbarData &
10
+ RuntimeProps & {
11
+ /** Item selecionado: fica em pílula e mostra o rótulo, como o Dock do mobile-app-rhosse. */
12
+ value?: string;
13
+ /** Área segura inferior da toolbar docked. */
14
+ bottomInset?: number;
15
+ style?: StyleProp<ViewStyle>;
16
+ };
17
+
18
+ /** Toolbar do M3 Expressive: floating (o Dock do mobile-app-rhosse, com FAB opcional) ou docked. */
19
+ export function Toolbar({ items, fab, type, color, orientation, value, bottomInset = 0, onAction, index: _, children: __, style }: ToolbarProps) {
20
+ const { colors, mode } = useExpressiveTheme();
21
+ const spec = resolveToolbar({ type, color, orientation });
22
+ const floating = spec.type === 'floating';
23
+ return (
24
+ <View style={[styles.wrap, spec.vertical && styles.wrapVertical, !floating && { alignSelf: 'stretch' }, style]}>
25
+ <View
26
+ accessibilityRole="toolbar"
27
+ style={[
28
+ styles.bar,
29
+ spec.vertical ? { flexDirection: 'column', width: spec.height, paddingVertical: spec.padding } : { height: floating ? spec.height : undefined, paddingHorizontal: spec.padding },
30
+ !floating && { flex: 1, justifyContent: 'space-around', minHeight: spec.height, paddingTop: 8, paddingBottom: Math.max(8, bottomInset) },
31
+ { gap: spec.gap, borderRadius: spec.radius, backgroundColor: colors[spec.container], boxShadow: tokens.elevation[mode][spec.elevation] },
32
+ ]}
33
+ >
34
+ {items.map((item) => {
35
+ const selected = value === item.id;
36
+ return (
37
+ <View key={item.id} style={selected ? { backgroundColor: colors[spec.selected.container], borderRadius: spec.item / 2 } : undefined}>
38
+ <ToolbarItem
39
+ item={item}
40
+ selected={selected}
41
+ vertical={spec.vertical}
42
+ tint={colors[selected ? spec.selected.content : spec.content]}
43
+ layer={colors[spec.content]}
44
+ onPress={() => onAction?.({ id: item.id, label: item.label })}
45
+ />
46
+ </View>
47
+ );
48
+ })}
49
+ </View>
50
+ {fab && floating ? (
51
+ <Fab action={{ id: fab.id, label: fab.label }} icon={fab.icon} variant={spec.fab.container as FabVariant} onPress={() => onAction?.({ id: fab.id, label: fab.label })} />
52
+ ) : null}
53
+ </View>
54
+ );
55
+ }
56
+
57
+ // Item: ícone; selecionado ganha pílula e rótulo (o fundo vem do wrapper); pressionado, cantos menores.
58
+ function ToolbarItem({ item, selected, vertical, tint, layer, onPress }: { item: ToolbarData['items'][number]; selected: boolean; vertical: boolean; tint: string; layer: string; onPress: () => void }) {
59
+ return (
60
+ <Pressable
61
+ accessibilityRole="button"
62
+ accessibilityLabel={item.label}
63
+ accessibilityState={{ selected }}
64
+ onPress={onPress}
65
+ style={({ pressed }) => [
66
+ styles.item,
67
+ selected && !vertical && styles.itemSelected,
68
+ pressed && { borderRadius: tokens.shape.medium, backgroundColor: withAlpha(layer, tokens.state.pressed) },
69
+ ]}
70
+ >
71
+ <Icon name={item.icon} tint={tint} filled={selected} />
72
+ {selected && !vertical ? (
73
+ <T variant="labelLarge" emphasized numberOfLines={1} style={{ color: tint }}>
74
+ {item.label}
75
+ </T>
76
+ ) : null}
77
+ </Pressable>
78
+ );
79
+ }
80
+
81
+ const styles = StyleSheet.create({
82
+ wrap: { flexDirection: 'row', alignItems: 'center', gap: 8 },
83
+ wrapVertical: { flexDirection: 'column' },
84
+ bar: { flexDirection: 'row', alignItems: 'center' },
85
+ item: { height: 48, minWidth: 48, paddingHorizontal: 12, borderRadius: 24, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 8 },
86
+ itemSelected: { paddingLeft: 12, paddingRight: 16 },
87
+ });
88
+
@@ -0,0 +1,155 @@
1
+ import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
2
+ import { Animated, Easing, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
3
+ import {
4
+ easingCurve,
5
+ resolveScreenTransition,
6
+ type MotionTrack,
7
+ type ScreenTransitionSpec,
8
+ type TransitionDirection,
9
+ type TransitionPattern,
10
+ } from '@expressive-ui/core';
11
+ import { useExpressiveTheme } from './theme.js';
12
+
13
+ /** Retângulo do elemento de origem relativo ao ScreenTransition (ex.: via measureLayout). */
14
+ export type TransitionOrigin = { x: number; y: number; width: number; height: number; radius?: number };
15
+
16
+ export type ScreenTransitionProps = {
17
+ /** Identidade da tela atual: trocar a chave dispara a transição. */
18
+ screenKey: string | number;
19
+ /**
20
+ * Padrão do M3. forwardBackward: avançar/voltar na hierarquia. lateral: telas irmãs (abas).
21
+ * topLevel: destinos da navegação principal. enterExit: tela que surge por cima.
22
+ * containerTransform: o retângulo `origin` cresce até virar a tela.
23
+ */
24
+ pattern?: TransitionPattern;
25
+ /** forward ao avançar (ou ir para a aba à direita); backward ao voltar. */
26
+ direction?: TransitionDirection;
27
+ /** containerTransform: de onde a tela nasce (e para onde volta). Sem ele vira enterExit. */
28
+ origin?: TransitionOrigin | null;
29
+ style?: StyleProp<ViewStyle>;
30
+ children: ReactNode;
31
+ };
32
+
33
+ type Slot = 'opacity' | 'translateX' | 'scale' | 'reveal' | 'content';
34
+ type Values = Record<Slot, Animated.Value>;
35
+ type Change = { id: number; spec: ScreenTransitionSpec; origin: TransitionOrigin | null; enter: Values; exit: Values };
36
+ type State = { key: string | number; previous: { key: string | number; node: ReactNode } | null; change: Change | null };
37
+ type Size = { width: number; height: number };
38
+
39
+ const slot = (m: MotionTrack): Slot => (m.target === 'content' ? 'content' : m.property);
40
+
41
+ // Cada trilha começa no próprio `from`; o que não anima fica no repouso (visível, no lugar).
42
+ function layerValues(tracks: MotionTrack[]): Values {
43
+ const rest: Record<Slot, number> = { opacity: 1, translateX: 0, scale: 1, reveal: 1, content: 1 };
44
+ for (const m of [...tracks].reverse()) rest[slot(m)] = m.from;
45
+ return Object.fromEntries(Object.entries(rest).map(([k, v]) => [k, new Animated.Value(v)])) as Values;
46
+ }
47
+
48
+ /**
49
+ * Troca de telas com os padrões de transição do M3. As telas ficam empilhadas (absoluteFill)
50
+ * durante a troca; a que sai não recebe toques e é desmontada no fim. O container precisa
51
+ * de tamanho (ex.: flex: 1).
52
+ */
53
+ export function ScreenTransition({ screenKey, pattern = 'forwardBackward', direction = 'forward', origin = null, style, children }: ScreenTransitionProps) {
54
+ const { colors, reduceMotion } = useExpressiveTheme();
55
+ const [size, setSize] = useState<Size>({ width: 0, height: 0 });
56
+ const committed = useRef(children);
57
+ const [state, setState] = useState<State>({ key: screenKey, previous: null, change: null });
58
+
59
+ // chave nova: a tela que estava na tela vira a que sai (estado derivado durante o render)
60
+ let current = state;
61
+ if (screenKey !== state.key) {
62
+ const hasOrigin = !!origin && size.width > 0;
63
+ const spec = resolveScreenTransition(pattern, direction, { width: size.width, hasOrigin, reduceMotion });
64
+ current = {
65
+ key: screenKey,
66
+ previous: { key: state.key, node: committed.current },
67
+ change: { id: (state.change?.id ?? 0) + 1, spec, origin: hasOrigin ? origin : null, enter: layerValues(spec.enter), exit: layerValues(spec.exit) },
68
+ };
69
+ setState(current);
70
+ }
71
+ const { previous, change } = current;
72
+
73
+ useLayoutEffect(() => {
74
+ committed.current = children;
75
+ });
76
+
77
+ useEffect(() => {
78
+ if (!change) return;
79
+ // left/top/width/height não rodam no driver nativo: com reveal, tudo vai pelo JS
80
+ const useNativeDriver = ![...change.spec.enter, ...change.spec.exit].some((m) => m.property === 'reveal');
81
+ const timings = (tracks: MotionTrack[], values: Values) =>
82
+ tracks.map((m) =>
83
+ Animated.timing(values[slot(m)], {
84
+ toValue: m.to,
85
+ duration: m.duration,
86
+ delay: m.delay,
87
+ easing: Easing.bezier(...easingCurve(m.easing)),
88
+ useNativeDriver,
89
+ }),
90
+ );
91
+ const animation = Animated.parallel([...timings(change.spec.exit, change.exit), ...timings(change.spec.enter, change.enter)]);
92
+ animation.start(({ finished }) => finished && setState((s) => (s.change?.id === change.id ? { ...s, previous: null, change: null } : s)));
93
+ return () => animation.stop();
94
+ }, [change]);
95
+
96
+ const layer = (key: string | number, node: ReactNode, values: Values | null, exiting: boolean) => {
97
+ const o = change?.origin;
98
+ const reveal = values && o && change.spec.pattern === 'containerTransform' ? values.reveal : null;
99
+ const at = (from: number, to: number) => reveal!.interpolate({ inputRange: [0, 1], outputRange: [from, to] });
100
+ const outer: Animated.WithAnimatedValue<ViewStyle> = reveal
101
+ ? {
102
+ position: 'absolute',
103
+ left: at(o!.x, 0),
104
+ top: at(o!.y, 0),
105
+ width: at(o!.width, size.width),
106
+ height: at(o!.height, size.height),
107
+ borderRadius: at(o!.radius ?? 0, 0),
108
+ overflow: 'hidden',
109
+ backgroundColor: colors.surface,
110
+ }
111
+ : fill;
112
+ return (
113
+ <Animated.View
114
+ key={key}
115
+ accessibilityElementsHidden={exiting}
116
+ importantForAccessibility={exiting ? 'no-hide-descendants' : 'auto'}
117
+ pointerEvents={exiting ? 'none' : 'auto'}
118
+ style={[
119
+ outer,
120
+ values && { opacity: values.opacity, transform: [{ translateX: values.translateX }, { scale: values.scale }] },
121
+ exiting && change?.spec.exitOnTop ? { zIndex: 1 } : null,
122
+ ]}
123
+ >
124
+ <Animated.View
125
+ style={[
126
+ reveal
127
+ ? { position: 'absolute', width: size.width, height: size.height, left: at(-o!.x, 0), top: at(-o!.y, 0) }
128
+ : fill,
129
+ values && { opacity: values.content },
130
+ ]}
131
+ >
132
+ {node}
133
+ </Animated.View>
134
+ </Animated.View>
135
+ );
136
+ };
137
+
138
+ return (
139
+ <View
140
+ style={[styles.root, style]}
141
+ onLayout={(e) => {
142
+ const { width, height } = e.nativeEvent.layout;
143
+ if (width !== size.width || height !== size.height) setSize({ width, height });
144
+ }}
145
+ >
146
+ {previous ? layer(previous.key, previous.node, change?.exit ?? null, true) : null}
147
+ {layer(current.key, children, previous ? (change?.enter ?? null) : null, false)}
148
+ </View>
149
+ );
150
+ }
151
+
152
+ const fill: ViewStyle = { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 };
153
+ const styles = StyleSheet.create({
154
+ root: { flex: 1, overflow: 'hidden' },
155
+ });
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ export * from './theme.js';
2
+ export * from './primitives.js';
3
+ export * from './ExpressiveCard.js';
4
+ export * from './Grid.js';
5
+ export * from './Button.js';
6
+ export * from './Fab.js';
7
+ export * from './Progress.js';
8
+ export * from './List.js';
9
+ export * from './Inputs.js';
10
+ export * from './Navigation.js';
11
+ export * from './Sheets.js';
12
+ export * from './Dialogs.js';
13
+ export * from './Menu.js';
14
+ export * from './Chips.js';
15
+ export * from './Fields.js';
16
+ export * from './Carousel.js';
17
+ export * from './Transition.js';
18
+ export * from './Search.js';
19
+ export * from './Toolbar.js';
@@ -0,0 +1,110 @@
1
+ import { createContext, useContext, useRef } from 'react';
2
+ import { Animated, Text, View, type StyleProp, type TextProps, type TextStyle, type ViewStyle } from 'react-native';
3
+ import Svg, { Path } from 'react-native-svg';
4
+ import { avatarTone, initialOf, shapePath, toneRoles, type ConcreteShape } from '@expressive-ui/core';
5
+ import { tokens, type ColorRole, type TypeScaleToken } from '@expressive-ui/tokens';
6
+ import { useExpressiveTheme } from './theme.js';
7
+
8
+ export function typeStyle(token: TypeScaleToken, emphasized = false): TextStyle {
9
+ const t = tokens.typography.scale[token];
10
+ const group = token.replace(/(Large|Medium|Small)$/, '') as keyof typeof tokens.typography.emphasizedWeight;
11
+ const weight = emphasized ? tokens.typography.emphasizedWeight[group] : t.weight;
12
+ return { fontSize: t.size, lineHeight: t.lineHeight, letterSpacing: t.tracking, fontWeight: String(weight) as TextStyle['fontWeight'] };
13
+ }
14
+
15
+ export function T({
16
+ variant = 'bodyMedium',
17
+ emphasized,
18
+ color = 'onSurface',
19
+ style,
20
+ ...props
21
+ }: TextProps & { variant?: TypeScaleToken; emphasized?: boolean; color?: ColorRole }) {
22
+ const { colors } = useExpressiveTheme();
23
+ return <Text {...props} style={[typeStyle(variant, emphasized), { color: colors[color] }, style]} />;
24
+ }
25
+
26
+ let warned = false;
27
+ export function Icon({
28
+ name,
29
+ size = 24,
30
+ color = 'onSurface',
31
+ tint,
32
+ filled = false,
33
+ }: {
34
+ name: string;
35
+ size?: number;
36
+ color?: ColorRole;
37
+ /** Cor já resolvida (ex.: com alfa do estado desabilitado); tem prioridade sobre `color`. */
38
+ tint?: string;
39
+ filled?: boolean;
40
+ }) {
41
+ const { colors, renderIcon } = useExpressiveTheme();
42
+ if (renderIcon) return <>{renderIcon(name, { size, color: tint ?? colors[color], filled })}</>;
43
+ if (!warned && __DEV__) {
44
+ warned = true;
45
+ console.warn('[expressive-ui] Passe renderIcon ao ExpressiveThemeProvider para exibir ícones.');
46
+ }
47
+ return <View style={{ width: size, height: size }} />;
48
+ }
49
+
50
+ export function Shape({ shape, size, color, style }: { shape: ConcreteShape; size: number; color: ColorRole; style?: StyleProp<ViewStyle> }) {
51
+ const { colors } = useExpressiveTheme();
52
+ return (
53
+ <View pointerEvents="none" style={[{ width: size, height: size }, style]}>
54
+ <Svg width={size} height={size} viewBox="0 0 100 100">
55
+ <Path d={shapePath(shape)} fill={colors[color]} />
56
+ </Svg>
57
+ </View>
58
+ );
59
+ }
60
+
61
+ /** 0 em repouso, 1 com o card pressionado/em hover. Fornecido pelo CardSurface. */
62
+ export const CardEmphasisContext = createContext<Animated.Value | null>(null);
63
+
64
+ /** Ícone sobre forma expressiva; a forma gira 30° quando o card que a contém é pressionado. */
65
+ export function ShapeIcon({
66
+ shape,
67
+ icon,
68
+ size = 44,
69
+ container,
70
+ content,
71
+ }: {
72
+ shape: ConcreteShape;
73
+ icon: string;
74
+ size?: number;
75
+ container: ColorRole;
76
+ content: ColorRole;
77
+ }) {
78
+ const emphasis = useContext(CardEmphasisContext);
79
+ const idle = useRef(new Animated.Value(0)).current;
80
+ const rotate = (emphasis ?? idle).interpolate({ inputRange: [0, 1], outputRange: ['0deg', '30deg'] });
81
+ return (
82
+ <View style={{ width: size, height: size, alignItems: 'center', justifyContent: 'center' }}>
83
+ <Animated.View style={{ position: 'absolute', transform: [{ rotate }] }}>
84
+ <Shape shape={shape} size={size} color={container} />
85
+ </Animated.View>
86
+ <Icon name={icon} size={Math.round(size * 0.5)} color={content} filled />
87
+ </View>
88
+ );
89
+ }
90
+
91
+ /** Cor com opacidade (#rrggbb → #rrggbbaa). Outros formatos voltam como estão. */
92
+ export function withAlpha(color: string, opacity: number) {
93
+ if (opacity >= 1) return color;
94
+ const hex = /^#([0-9a-f]{6})$/i.exec(color);
95
+ return hex ? `#${hex[1]}${Math.round(opacity * 255).toString(16).padStart(2, '0')}` : color;
96
+ }
97
+
98
+ /** Inicial do nome sobre um tom estável (tone1–4 pelo hash do nome), como no mobile-app-rhosse. */
99
+ export function Avatar({ name, size = 40 }: { name: string; size?: number }) {
100
+ const { colors } = useExpressiveTheme();
101
+ const roles = toneRoles(avatarTone(name));
102
+ return (
103
+ <View
104
+ importantForAccessibility="no"
105
+ style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: colors[roles.container], alignItems: 'center', justifyContent: 'center' }}
106
+ >
107
+ <Text style={{ color: colors[roles.onContainer], fontSize: size * 0.42, fontWeight: '500' }}>{initialOf(name)}</Text>
108
+ </View>
109
+ );
110
+ }
package/src/theme.tsx ADDED
@@ -0,0 +1,125 @@
1
+ import { createContext, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
2
+ import { AccessibilityInfo, Animated, Easing, useColorScheme } from 'react-native';
3
+ import { resolveLabels, springConfig, surfaceTiming, type ExpressiveLabels } from '@expressive-ui/core';
4
+ import { schemes, type ColorScheme, type MotionScheme, type SchemePair, type SpringToken, type ThemeMode } from '@expressive-ui/tokens';
5
+
6
+ export type IconRenderer = (name: string, options: { size: number; color: string; filled: boolean }) => ReactNode;
7
+
8
+ type ExpressiveTheme = {
9
+ mode: ThemeMode;
10
+ colors: ColorScheme;
11
+ locale: string;
12
+ labels: ExpressiveLabels;
13
+ reduceMotion: boolean;
14
+ motion: MotionScheme;
15
+ renderIcon: IconRenderer | null;
16
+ };
17
+
18
+ const ThemeContext = createContext<ExpressiveTheme>({
19
+ mode: 'light',
20
+ colors: schemes.light,
21
+ locale: 'pt-BR',
22
+ labels: resolveLabels('pt-BR'),
23
+ reduceMotion: false,
24
+ motion: 'expressive',
25
+ renderIcon: null,
26
+ });
27
+ export const useExpressiveTheme = () => useContext(ThemeContext);
28
+
29
+ export type ExpressiveThemeProviderProps = {
30
+ mode?: ThemeMode | 'system';
31
+ /** Esquema próprio — por exemplo createScheme(seed) de @expressive-ui/tokens/dynamic. */
32
+ scheme?: SchemePair;
33
+ /** Idioma dos textos de acessibilidade embutidos: pt-* usa português, os demais inglês. */
34
+ locale?: string;
35
+ /** Sobrescreve textos embutidos (rótulos de fechar, anúncios de reordenação etc.). */
36
+ labels?: Partial<ExpressiveLabels>;
37
+ /** Esquema de movimento do M3: expressive (molas que ultrapassam) ou standard (amortecidas). */
38
+ motion?: MotionScheme;
39
+ /**
40
+ * Ícones Material Symbols. Ex. com Expo:
41
+ * (name, { size, color }) => <MaterialIcons name={name.replace(/_/g, '-')} size={size} color={color} />
42
+ */
43
+ renderIcon?: IconRenderer;
44
+ children: ReactNode;
45
+ };
46
+
47
+ export function ExpressiveThemeProvider({ mode = 'system', scheme, locale = 'pt-BR', motion = 'expressive', labels, renderIcon, children }: ExpressiveThemeProviderProps) {
48
+ const system = useColorScheme();
49
+ const reduceMotion = useReduceMotion();
50
+ const resolved: ThemeMode = mode === 'system' ? (system === 'dark' ? 'dark' : 'light') : mode;
51
+ const value = useMemo(
52
+ () => ({ mode: resolved, colors: (scheme ?? schemes)[resolved], locale, labels: resolveLabels(locale, labels), reduceMotion, motion, renderIcon: renderIcon ?? null }),
53
+ [resolved, scheme, locale, labels, reduceMotion, motion, renderIcon],
54
+ );
55
+ return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
56
+ }
57
+
58
+ // Mesmo comportamento do useReduceMotion do mobile-app-rhosse.
59
+ export function useReduceMotion() {
60
+ const [reduce, setReduce] = useState(false);
61
+ useEffect(() => {
62
+ let active = true;
63
+ AccessibilityInfo.isReduceMotionEnabled()
64
+ .then((value) => active && setReduce(value))
65
+ .catch(() => {});
66
+ const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
67
+ return () => {
68
+ active = false;
69
+ sub.remove();
70
+ };
71
+ }, []);
72
+ return reduce;
73
+ }
74
+
75
+ /**
76
+ * Valor animado que persegue `target` com a mola do token (driver JS: borderRadius e cores
77
+ * não rodam no driver nativo). Com "reduzir movimento" salta direto para o alvo.
78
+ */
79
+ export function useSpringValue(target: number, token: SpringToken) {
80
+ const { reduceMotion, motion } = useExpressiveTheme();
81
+ const value = useRef(new Animated.Value(target)).current;
82
+ useEffect(() => {
83
+ const animation = reduceMotion
84
+ ? Animated.timing(value, { toValue: target, duration: 0, useNativeDriver: false })
85
+ : Animated.spring(value, { toValue: target, ...springConfig(token, motion), useNativeDriver: false });
86
+ animation.start();
87
+ return () => animation.stop();
88
+ }, [target, token, reduceMotion, motion, value]);
89
+ return value;
90
+ }
91
+
92
+ const exit = surfaceTiming('exit');
93
+ /** Saída de superfície do M3: mais curta que a entrada e acelerando (emphasizedAccelerate). */
94
+ export function exitTiming(value: Animated.Value, toValue = 0, useNativeDriver = true) {
95
+ return Animated.timing(value, { toValue, duration: exit.duration, easing: Easing.bezier(...exit.bezier), useNativeDriver });
96
+ }
97
+
98
+ /**
99
+ * Presença animada de sobreposições (dialogs, sheets, busca): mantém montado durante a saída.
100
+ * `progress` vai a 1 (aberto) com a mola spatialDefault e volta a 0 com a saída do M3 antes
101
+ * de desmontar; com "reduzir movimento" é instantâneo.
102
+ */
103
+ export function usePresence(open: boolean, useNativeDriver = true) {
104
+ const { reduceMotion, motion } = useExpressiveTheme();
105
+ const progress = useRef(new Animated.Value(open ? 1 : 0)).current;
106
+ const opacity = useRef(new Animated.Value(open ? 1 : 0)).current;
107
+ const [mounted, setMounted] = useState(open);
108
+ useEffect(() => {
109
+ if (open) setMounted(true);
110
+ const animation = reduceMotion
111
+ ? Animated.timing(progress, { toValue: open ? 1 : 0, duration: 0, useNativeDriver })
112
+ : open
113
+ ? Animated.spring(progress, { toValue: 1, ...springConfig('spatialDefault', motion), useNativeDriver })
114
+ : exitTiming(progress, 0, useNativeDriver);
115
+ const effect = reduceMotion
116
+ ? Animated.timing(opacity, { toValue: open ? 1 : 0, duration: 0, useNativeDriver })
117
+ : open
118
+ ? Animated.spring(opacity, { toValue: 1, ...springConfig('effectsDefault', motion), useNativeDriver })
119
+ : exitTiming(opacity, 0, useNativeDriver);
120
+ const group = Animated.parallel([animation, effect]);
121
+ group.start(({ finished }) => finished && !open && setMounted(false));
122
+ return () => group.stop();
123
+ }, [open, progress, opacity, reduceMotion, motion, useNativeDriver]);
124
+ return { progress, opacity, mounted };
125
+ }