@expressive-ui/native 0.1.1 → 0.2.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 (57) hide show
  1. package/README.md +10 -0
  2. package/dist/AppBar.d.ts +18 -0
  3. package/dist/AppBar.d.ts.map +1 -0
  4. package/dist/AppBar.js +15 -0
  5. package/dist/AppBar.js.map +1 -0
  6. package/dist/Divider.d.ts +10 -0
  7. package/dist/Divider.d.ts.map +1 -0
  8. package/dist/Divider.js +10 -0
  9. package/dist/Divider.js.map +1 -0
  10. package/dist/Feedback.d.ts +42 -0
  11. package/dist/Feedback.d.ts.map +1 -0
  12. package/dist/Feedback.js +26 -0
  13. package/dist/Feedback.js.map +1 -0
  14. package/dist/FileUpload.d.ts +13 -0
  15. package/dist/FileUpload.d.ts.map +1 -0
  16. package/dist/FileUpload.js +29 -0
  17. package/dist/FileUpload.js.map +1 -0
  18. package/dist/NumberField.d.ts +18 -0
  19. package/dist/NumberField.d.ts.map +1 -0
  20. package/dist/NumberField.js +20 -0
  21. package/dist/NumberField.js.map +1 -0
  22. package/dist/Pickers.d.ts +2 -0
  23. package/dist/Pickers.d.ts.map +1 -1
  24. package/dist/Pickers.js +19 -16
  25. package/dist/Pickers.js.map +1 -1
  26. package/dist/RangeSlider.d.ts +11 -0
  27. package/dist/RangeSlider.d.ts.map +1 -0
  28. package/dist/RangeSlider.js +63 -0
  29. package/dist/RangeSlider.js.map +1 -0
  30. package/dist/Select.d.ts +31 -0
  31. package/dist/Select.d.ts.map +1 -0
  32. package/dist/Select.js +22 -0
  33. package/dist/Select.js.map +1 -0
  34. package/dist/Snackbar.d.ts +17 -0
  35. package/dist/Snackbar.d.ts.map +1 -0
  36. package/dist/Snackbar.js +36 -0
  37. package/dist/Snackbar.js.map +1 -0
  38. package/dist/Toolbar.d.ts +5 -2
  39. package/dist/Toolbar.d.ts.map +1 -1
  40. package/dist/Toolbar.js +10 -6
  41. package/dist/Toolbar.js.map +1 -1
  42. package/dist/index.d.ts +8 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +8 -0
  45. package/dist/index.js.map +1 -1
  46. package/package.json +4 -4
  47. package/src/AppBar.tsx +30 -0
  48. package/src/Divider.tsx +9 -0
  49. package/src/Feedback.tsx +23 -0
  50. package/src/FileUpload.tsx +16 -0
  51. package/src/NumberField.tsx +13 -0
  52. package/src/Pickers.tsx +10 -9
  53. package/src/RangeSlider.tsx +65 -0
  54. package/src/Select.tsx +36 -0
  55. package/src/Snackbar.tsx +35 -0
  56. package/src/Toolbar.tsx +16 -9
  57. package/src/index.ts +10 -0
@@ -0,0 +1,65 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { PanResponder, View } from 'react-native';
3
+ import { moveSliderThumb, resolveSlider, sliderStops, useRangeSlider, valueRatio, type SliderRange } from '@expressive-ui/core';
4
+ import type { SliderProps } from './Inputs.js';
5
+ import { T, withAlpha } from './primitives.js';
6
+ import { useExpressiveTheme } from './theme.js';
7
+ export type { SliderRange } from '@expressive-ui/core';
8
+ export type RangeSliderProps = Omit<SliderProps, 'value' | 'onChange' | 'onPreview' | 'icon'> & {
9
+ value: SliderRange; onChange?: (value: [number, number]) => void; onPreview?: (value: [number, number] | null) => void;
10
+ thumbLabels?: readonly [string, string];
11
+ };
12
+ export function RangeSlider({ value, min = 0, max = 100, step = 1, onChange, onPreview, label, thumbLabels, size = 'sm', stops = false, format = String, showValue = true, disabled = false, style }: RangeSliderProps) {
13
+ const { colors, locale } = useExpressiveTheme();
14
+ const labels = thumbLabels ?? (locale.startsWith('pt') ? ['Mínimo', 'Máximo'] : ['Minimum', 'Maximum']);
15
+ const [width, setWidth] = useState(0);
16
+ const state = useRangeSlider({ value, min, max, step, onChange, onPreview });
17
+ const surface = useRef<View>(null);
18
+ const start = useRef({ page: 0, local: 0 });
19
+ const gesture = useRef({ id: 0, ready: false, ended: false, cancelled: false, page: 0 });
20
+ const latest = useRef({ state, width, min, max, disabled }); latest.current = { state, width, min, max, disabled };
21
+ const spec = resolveSlider({ size, disabled });
22
+ const at = (pageX: number) => { const p = latest.current; return p.min + Math.max(0, Math.min(1, (start.current.local + pageX - start.current.page) / Math.max(1, p.width))) * (p.max - p.min); };
23
+ const responder = useRef(PanResponder.create({
24
+ onStartShouldSetPanResponder: () => !latest.current.disabled,
25
+ onMoveShouldSetPanResponder: () => !latest.current.disabled,
26
+ onPanResponderTerminationRequest: () => false,
27
+ onPanResponderGrant: event => {
28
+ // measure() yields page coordinates even when the touch lands on a child handle.
29
+ const page = event.nativeEvent.pageX;
30
+ const session = { id: gesture.current.id + 1, ready: false, ended: false, cancelled: false, page };
31
+ gesture.current = session;
32
+ surface.current?.measure((_x, _y, _w, _h, pageX) => {
33
+ if (latest.current.disabled || session.cancelled || gesture.current !== session) return;
34
+ start.current = { page, local: page - pageX };
35
+ const next = at(page), p = latest.current;
36
+ const thumb: 0 | 1 = Math.abs(next - p.state.shown[0]) < Math.abs(next - p.state.shown[1]) ? 0 : 1;
37
+ p.state.begin(thumb); session.ready = true; p.state.move(at(session.page)); if (session.ended) p.state.commit();
38
+ });
39
+ },
40
+ onPanResponderMove: event => { gesture.current.page = event.nativeEvent.pageX; if (gesture.current.ready) latest.current.state.move(at(event.nativeEvent.pageX)); },
41
+ onPanResponderRelease: event => { gesture.current.ended = true; gesture.current.page = event.nativeEvent.pageX; if (gesture.current.ready) { latest.current.state.move(at(event.nativeEvent.pageX)); latest.current.state.commit(); } },
42
+ onPanResponderTerminate: () => { gesture.current.cancelled = true; latest.current.state.cancel(); },
43
+ })).current;
44
+ useEffect(() => { if (disabled) { gesture.current.cancelled = true; latest.current.state.cancel(); } }, [disabled]);
45
+ const positions: [number, number] = [valueRatio(state.shown[0], min, max), valueRatio(state.shown[1], min, max)];
46
+ return <View accessibilityLabel={label} style={[{ height: Math.max(48, spec.handleHeight), opacity: spec.disabledOpacity }, style]}>
47
+ <View ref={surface} collapsable={false} onLayout={event => setWidth(event.nativeEvent.layout.width)} {...responder.panHandlers} style={{ flex: 1 }}>
48
+ <View pointerEvents="none" style={{ position: 'absolute', left: 0, right: 0, top: (spec.handleHeight - spec.track) / 2, height: spec.track, borderRadius: spec.radius.outer, backgroundColor: withAlpha(colors[spec.inactive], disabled ? .12 : 1) }}>
49
+ <View style={{ position: 'absolute', left: positions[0] * width, width: Math.max(0, (positions[1] - positions[0]) * width), height: spec.track, borderRadius: spec.radius.inner, backgroundColor: colors[spec.active] }} />
50
+ {stops ? sliderStops(min, max, step).map(s => <View key={s} style={{ position: 'absolute', left: s * width - 2, top: spec.track / 2 - 2, width: 4, height: 4, borderRadius: 2, backgroundColor: colors[s >= positions[0] && s <= positions[1] ? spec.stopOnActive : spec.stopOnInactive] }} />) : null}
51
+ </View>
52
+ {([0, 1] as const).map(thumb => <View key={thumb} accessible accessibilityRole="adjustable" accessibilityLabel={`${label}: ${labels[thumb]}`} accessibilityState={{ disabled }}
53
+ accessibilityValue={{ min: thumb === 0 ? min : state.shown[0], max: thumb === 0 ? state.shown[1] : max, now: state.shown[thumb], text: format(state.shown[thumb]) }}
54
+ accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]} onAccessibilityAction={event => {
55
+ if (disabled) return;
56
+ const action = event.nativeEvent.actionName;
57
+ if (action !== 'increment' && action !== 'decrement') return;
58
+ onChange?.(moveSliderThumb(state.shown, thumb, state.shown[thumb] + (action === 'increment' ? step : -step), min, max, step));
59
+ }} style={{ position: 'absolute', left: Math.max(0, Math.min(Math.max(0, width - 48), positions[thumb] * width - 24)), width: 48, height: spec.handleHeight, alignItems: 'center' }}>
60
+ <View pointerEvents="none" style={{ position: 'absolute', left: positions[thumb] * width - spec.gap - Math.max(0, Math.min(Math.max(0, width - 48), positions[thumb] * width - 24)) - 2, width: 4, height: spec.handleHeight, borderRadius: 2, backgroundColor: colors[spec.active], borderWidth: spec.gap, borderColor: colors.surface, boxSizing: 'content-box' }} />
61
+ {showValue && state.dragging ? <View pointerEvents="none" style={{ position: 'absolute', bottom: spec.handleHeight + 4, paddingHorizontal: 12, paddingVertical: 8, borderRadius: 24, backgroundColor: colors.inverseSurface }}><T variant="labelLarge" color="inverseOnSurface">{format(state.shown[thumb])}</T></View> : null}
62
+ </View>)}
63
+ </View>
64
+ </View>;
65
+ }
package/src/Select.tsx ADDED
@@ -0,0 +1,36 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { Pressable, ScrollView, View, type StyleProp, type ViewStyle } from 'react-native';
3
+ import { useOptionSearch, type SelectOption, type OptionLoader } from '@expressive-ui/core';
4
+ import { Dialog } from './Dialogs.js';
5
+ import { TextField } from './Fields.js';
6
+ import { Button } from './Button.js';
7
+ import { Icon, T } from './primitives.js';
8
+ import { useExpressiveTheme } from './theme.js';
9
+ export type { SelectOption, OptionLoader } from '@expressive-ui/core';
10
+ export type SelectProps = { label:string; options:readonly SelectOption[]; value?:string; defaultValue?:string; onChange?:(value:string,option:SelectOption)=>void; variant?:'filled'|'outlined'; placeholder?:string; supportingText?:string; error?:string|boolean; required?:boolean; disabled?:boolean; leadingIcon?:string; maxHeight?:number; style?:StyleProp<ViewStyle> };
11
+ export type AutocompleteProps = SelectProps & { loadOptions?:OptionLoader; onQueryChange?:(query:string)=>void; debounce?:number; emptyText?:string; loadingText?:string; loadErrorText?:string };
12
+ export function Select(props:SelectProps){return <SelectionField {...props} editable={false}/>;}
13
+ export function Autocomplete(props:AutocompleteProps){return <SelectionField {...props} editable/>;}
14
+ export const Combobox=Autocomplete;
15
+ function SelectionField({label,options,value:controlled,defaultValue='',onChange,variant='outlined',placeholder,supportingText,error,required,disabled,leadingIcon,maxHeight=320,style,editable,loadOptions,onQueryChange,debounce,emptyText,loadingText,loadErrorText}:AutocompleteProps&{editable:boolean}){
16
+ const {colors,locale,labels}=useExpressiveTheme(),pt=locale.startsWith('pt');
17
+ const [inner,setInner]=useState(defaultValue),value=controlled??inner,[open,setOpen]=useState(false),[query,setQuery]=useState('');
18
+ const cached=useRef<SelectOption|undefined>(undefined),selected=options.find(option=>option.value===value)??(cached.current?.value===value?cached.current:undefined);
19
+ const result=useOptionSearch(editable&&open?query:'',options,editable?loadOptions:undefined,debounce),shown=editable?result.options:options;
20
+ useEffect(()=>{if(disabled)setOpen(false);},[disabled]);
21
+ return <View style={[{gap:6,opacity:disabled? .38 :1},style]}>
22
+ <T variant="labelMedium">{label}{required?' *':''}</T>
23
+ <Pressable accessibilityRole="combobox" accessibilityLabel={`${label}${required ? (pt ? ', obrigatório' : ', required') : ''}`} accessibilityValue={{text:selected?.label??''}} accessibilityState={{expanded:open,disabled:!!disabled}} accessibilityHint={typeof error==='string'?error:supportingText} disabled={disabled} onPress={()=>{setQuery('');setOpen(true);}} style={{minHeight:56,padding:14,borderWidth:variant==='outlined'?1:0,borderBottomWidth:1,borderColor:error?colors.error:colors.outline,borderRadius:12,backgroundColor:variant==='filled'?colors.surfaceContainerHighest:colors.surface,flexDirection:'row',alignItems:'center',gap:12}}>
24
+ {leadingIcon?<Icon name={leadingIcon}/>:null}<T style={{flex:1}}>{selected?.label??placeholder??(pt?'Selecione':'Select')}</T><Icon name="arrow_drop_down"/>
25
+ </Pressable>
26
+ {error||supportingText?<T variant="bodySmall" color={error?'error':'onSurfaceVariant'}>{typeof error==='string'?error:supportingText}</T>:null}
27
+ <Dialog open={open} onClose={()=>setOpen(false)} headline={label} actions={[{label:labels.close,onPress:()=>setOpen(false)}]}>
28
+ {editable?<TextField label={label} value={query} onChange={next=>{setQuery(next);onQueryChange?.(next);}} placeholder={placeholder}/>:null}
29
+ <ScrollView style={{maxHeight}} keyboardShouldPersistTaps="handled">
30
+ {result.loading?<T accessibilityLiveRegion="polite">{loadingText??(pt?'Carregando…':'Loading…')}</T>:result.error?<View><T accessibilityRole="alert">{loadErrorText??(pt?'Não foi possível carregar.':'Could not load options.')}</T><Button variant="text" action={{id:'select.retry',label:pt?'Tentar novamente':'Retry'}} onPress={result.retry}/></View>:!shown.length?<T accessibilityLiveRegion="polite">{emptyText??(pt?'Nenhum resultado.':'No results.')}</T>:shown.map(option=><Pressable key={option.value} accessibilityRole="button" accessibilityState={{selected:option.value===value,disabled:!!option.disabled}} disabled={option.disabled} onPress={()=>{cached.current=option;setInner(option.value);onChange?.(option.value,option);setOpen(false);}} style={{minHeight:48,padding:14,marginVertical:2,borderRadius:12,flexDirection:'row',alignItems:'center',gap:12,opacity:option.disabled? .38 :1,backgroundColor:option.value===value?colors.secondaryContainer:colors.surface}}>
31
+ {option.icon?<Icon name={option.icon}/>:null}<View style={{flex:1}}><T>{option.label}</T>{option.supportingText?<T variant="bodySmall" color="onSurfaceVariant">{option.supportingText}</T>:null}</View>{option.value===value?<Icon name="check"/>:null}
32
+ </Pressable>)}
33
+ </ScrollView>
34
+ </Dialog>
35
+ </View>;
36
+ }
@@ -0,0 +1,35 @@
1
+ import { useEffect, useState, type ReactNode } from 'react';
2
+ import { AccessibilityInfo, AppState, Platform, Pressable, View, type StyleProp, type ViewStyle } from 'react-native';
3
+ import { SnackbarContext, useSnackbarQueue, useSnackbarTimer, type SnackbarMessage, type SnackbarCloseReason } from '@expressive-ui/core';
4
+ import { T } from './primitives.js';
5
+ import { useExpressiveTheme } from './theme.js';
6
+ export { useSnackbar } from '@expressive-ui/core';
7
+ export type { SnackbarMessage, SnackbarCloseReason } from '@expressive-ui/core';
8
+ export type SnackbarProps = SnackbarMessage & { open: boolean; style?: StyleProp<ViewStyle> };
9
+ export function Snackbar({ open, message, action, duration = action ? 0 : 5000, dismissible = true, onClose, style }: SnackbarProps) {
10
+ const { colors, labels } = useExpressiveTheme();
11
+ const [background, setBackground] = useState(AppState.currentState !== 'active');
12
+ const [screenReader, setScreenReader] = useState(true);
13
+ useEffect(() => {
14
+ let active = true;
15
+ AccessibilityInfo.isScreenReaderEnabled().then(value => { if (active) setScreenReader(value); }).catch(() => {});
16
+ const reader = AccessibilityInfo.addEventListener('screenReaderChanged', setScreenReader);
17
+ const app = AppState.addEventListener('change', state => setBackground(state !== 'active'));
18
+ return () => { active = false; reader.remove(); app.remove(); };
19
+ }, []);
20
+ useEffect(() => { if (open && Platform.OS === 'ios') AccessibilityInfo.announceForAccessibility(message); }, [open, message]);
21
+ useSnackbarTimer(open, duration, background || screenReader, onClose);
22
+ if (!open) return null;
23
+ return <View style={[{ minHeight: 48, borderRadius: 4, paddingHorizontal: 16, paddingVertical: 8, backgroundColor: colors.inverseSurface, flexDirection: 'row', alignItems: 'center', gap: 8 }, style]}>
24
+ <T variant="bodyMedium" color="inverseOnSurface" accessibilityLiveRegion="polite" style={{ flex: 1 }}>{message}</T>
25
+ {action ? <Pressable accessibilityRole="button" onPress={() => { try { action.onPress(); } finally { onClose?.('action'); } }} style={{ minHeight: 48, paddingHorizontal: 8, justifyContent: 'center' }}><T variant="labelLarge" color="inversePrimary">{action.label}</T></Pressable> : null}
26
+ {dismissible ? <Pressable accessibilityRole="button" accessibilityLabel={labels.close} onPress={() => onClose?.('dismiss')} style={{ minWidth: 48, minHeight: 48, alignItems: 'center', justifyContent: 'center' }}><T variant="titleLarge" color="inverseOnSurface">×</T></Pressable> : null}
27
+ </View>;
28
+ }
29
+ export type SnackbarProviderProps = { children: ReactNode; bottomInset?: number; style?: StyleProp<ViewStyle> };
30
+ export function SnackbarProvider({ children, bottomInset = 0, style }: SnackbarProviderProps) {
31
+ const { controller, entry, close } = useSnackbarQueue();
32
+ return <SnackbarContext.Provider value={controller}>{children}<View pointerEvents="box-none" style={[{ position: 'absolute', bottom: 16 + bottomInset, left: 16, right: 16, zIndex: 1000, maxWidth: 560, alignSelf: 'center' }, style]}>
33
+ {entry ? <Snackbar key={entry.id} {...entry} open onClose={(reason: SnackbarCloseReason) => close(entry.id, reason)} /> : null}
34
+ </View></SnackbarContext.Provider>;
35
+ }
package/src/Toolbar.tsx CHANGED
@@ -1,28 +1,35 @@
1
- import { Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
2
- import { resolveToolbar, type RuntimeProps } from '@expressive-ui/core';
1
+ import { Animated, Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
2
+ import { resolveToolbar, useScrollCollapsed, type ScrollBehavior, type RuntimeProps } from '@expressive-ui/core';
3
3
  import type { FabVariant, ToolbarData } from '@expressive-ui/schema';
4
4
  import { tokens } from '@expressive-ui/tokens';
5
5
  import { Fab } from './Fab.js';
6
6
  import { Icon, T, withAlpha } from './primitives.js';
7
- import { useExpressiveTheme } from './theme.js';
7
+ import { useExpressiveTheme, useSpringValue } from './theme.js';
8
8
 
9
9
  export type ToolbarProps = ToolbarData &
10
10
  RuntimeProps & {
11
11
  /** Item selecionado: fica em pílula e mostra o rótulo, como o Dock do mobile-app-rhosse. */
12
12
  value?: string;
13
+ scrollBehavior?: ScrollBehavior;
14
+ scrollOffset?: number;
15
+ scrollThreshold?: number;
13
16
  /** Área segura inferior da toolbar docked. */
14
17
  bottomInset?: number;
15
18
  style?: StyleProp<ViewStyle>;
16
19
  };
17
20
 
18
21
  /** 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();
22
+ export function Toolbar({ items, fab, type, color, orientation, value, scrollBehavior = 'none', scrollOffset = 0, scrollThreshold = 24, bottomInset = 0, onAction, index: _, children: __, style }: ToolbarProps) {
23
+ const { colors, mode, locale } = useExpressiveTheme();
21
24
  const spec = resolveToolbar({ type, color, orientation });
25
+ const { collapsed, setCollapsed } = useScrollCollapsed(scrollOffset, scrollBehavior !== 'none', scrollThreshold);
26
+ const compact = collapsed && scrollBehavior === 'collapse';
27
+ const hidden = collapsed && scrollBehavior === 'hide';
28
+ const visibility = useSpringValue(hidden ? 0 : 1, 'effectsFast');
22
29
  const floating = spec.type === 'floating';
23
30
  return (
24
- <View style={[styles.wrap, spec.vertical && styles.wrapVertical, !floating && { alignSelf: 'stretch' }, style]}>
25
- <View
31
+ <Animated.View accessibilityElementsHidden={hidden} importantForAccessibility={hidden ? 'no-hide-descendants' : 'auto'} pointerEvents={hidden ? 'none' : 'auto'} style={[styles.wrap, { opacity: visibility }, spec.vertical && styles.wrapVertical, !floating && { alignSelf: 'stretch' }, style]}>
32
+ {compact ? <Pressable accessibilityRole="button" accessibilityLabel={locale.startsWith('pt') ? 'Expandir ações' : 'Expand actions'} accessibilityState={{ expanded: false }} onPress={() => setCollapsed(false)} style={{ width: 56, height: 56, borderRadius: 28, alignItems: 'center', justifyContent: 'center', backgroundColor: colors[spec.container] }}><Icon name="more_horiz" color={spec.content} /></Pressable> : <View
26
33
  accessibilityRole="toolbar"
27
34
  style={[
28
35
  styles.bar,
@@ -46,11 +53,11 @@ export function Toolbar({ items, fab, type, color, orientation, value, bottomIns
46
53
  </View>
47
54
  );
48
55
  })}
49
- </View>
56
+ </View>}
50
57
  {fab && floating ? (
51
58
  <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
59
  ) : null}
53
- </View>
60
+ </Animated.View>
54
61
  );
55
62
  }
56
63
 
package/src/index.ts CHANGED
@@ -18,3 +18,13 @@ export * from './Transition.js';
18
18
  export * from './Search.js';
19
19
  export * from './Toolbar.js';
20
20
  export * from './Pickers.js';
21
+
22
+ export * from './AppBar.js';
23
+ export * from './Divider.js';
24
+ export * from './Snackbar.js';
25
+ export * from './RangeSlider.js';
26
+
27
+ export * from './Select.js';
28
+ export * from './Feedback.js';
29
+ export * from './NumberField.js';
30
+ export * from './FileUpload.js';