@tallyui/components 3.18.0 → 3.20.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 (60) hide show
  1. package/dist/index.d.ts +473 -37
  2. package/dist/index.js +3656 -1905
  3. package/package.json +9 -9
  4. package/src/cart/cart-columns.tsx +42 -4
  5. package/src/cart/cart-foot.tsx +2 -2
  6. package/src/cart/cart-line.tsx +42 -18
  7. package/src/cart/cart-note-input.tsx +10 -2
  8. package/src/cart/cart-panel.tsx +4 -1
  9. package/src/cart/cart-total.tsx +8 -5
  10. package/src/cart/index.ts +1 -1
  11. package/src/customer/customer-select.tsx +21 -3
  12. package/src/index.ts +27 -0
  13. package/src/input/search-input.tsx +1 -1
  14. package/src/order/index.ts +1 -0
  15. package/src/order/order-filter-bar.tsx +247 -0
  16. package/src/product/camera-scan-button.tsx +28 -0
  17. package/src/product/camera-scanner-panel.tsx +156 -0
  18. package/src/product/index.ts +5 -0
  19. package/src/product/product-table.tsx +14 -4
  20. package/src/product/scanner-viewfinder.tsx +76 -0
  21. package/src/product/variation-picker.tsx +128 -0
  22. package/src/register/register-bar.tsx +2 -6
  23. package/src/register/register-panel.tsx +47 -24
  24. package/src/register/register-side-sheet.tsx +175 -0
  25. package/src/reports/date-range-menu.tsx +109 -0
  26. package/src/reports/filters-bar.tsx +11 -21
  27. package/src/reports/hero.tsx +8 -4
  28. package/src/reports/index.ts +1 -0
  29. package/src/sale/cart.tsx +49 -10
  30. package/src/sale/catalogue.tsx +98 -21
  31. package/src/sale/charge-form.tsx +12 -6
  32. package/src/sale/customer-display-pairing.tsx +111 -0
  33. package/src/sale/index.ts +1 -0
  34. package/src/sale/line-popover.tsx +17 -1
  35. package/src/sale/order-reference.ts +1 -1
  36. package/src/sale/orders-list.tsx +1 -1
  37. package/src/settings/customer-display-settings.tsx +163 -0
  38. package/src/settings/index.ts +2 -0
  39. package/src/settings/tax-calculation-settings.tsx +97 -0
  40. package/src/shell/nav-drawer.tsx +1 -1
  41. package/src/tax/index.ts +1 -0
  42. package/src/tax/tax-based-on.tsx +196 -0
  43. package/src/ui/alert-dialog/index.tsx +1 -1
  44. package/src/ui/avatar/index.tsx +22 -4
  45. package/src/ui/button/index.tsx +1 -1
  46. package/src/ui/calendar/index.tsx +119 -0
  47. package/src/ui/calendar/month-grid.ts +40 -0
  48. package/src/ui/combobox/index.tsx +1 -1
  49. package/src/ui/dialog/index.tsx +21 -9
  50. package/src/ui/icon/chevron-down-icon.tsx +4 -0
  51. package/src/ui/icon/grip-icon.tsx +10 -0
  52. package/src/ui/icon/scan-icon.tsx +13 -0
  53. package/src/ui/icon/shopping-cart-icon.tsx +10 -0
  54. package/src/ui/icon-button/index.tsx +1 -1
  55. package/src/ui/index.ts +11 -1
  56. package/src/ui/input/index.tsx +1 -1
  57. package/src/ui/select/index.tsx +22 -4
  58. package/src/ui/slider/index.tsx +2 -2
  59. package/src/ui/switch/index.tsx +19 -8
  60. package/src/ui/textarea/index.tsx +1 -1
@@ -0,0 +1,247 @@
1
+ /**
2
+ * The Orders screen's filter pills, in WCPOS v2's order: Status, Payment Method, Customer, Cashier, Store / Created
3
+ * via, Register and Date range, with Clear all. Port of v2 `screens/main/orders/filter-bar.tsx` and its
4
+ * `filter-bar/*-pill.tsx` (MIT, WCPOS); copy is v2's English (`core.json`). Presentational: the app passes the value,
5
+ * the connector's `orderFilters` and every option list, so no platform's words live here.
6
+ */
7
+ import { Fragment, useState, type JSX, type ReactNode } from 'react';
8
+ import { Pressable, ScrollView, Text, View } from 'react-native';
9
+ import type { OrderFilterField } from '@tallyui/core';
10
+ import { presetRange, type DayRange, type OrderFilterValue } from '@tallyui/pos';
11
+ import { cn } from '@tallyui/theme';
12
+ import { rangeLabel } from '../reports/date-range-menu';
13
+ import { Button } from '../ui/button';
14
+ import { Calendar } from '../ui/calendar';
15
+ import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxTrigger } from '../ui/combobox';
16
+ import { XIcon } from '../ui/icon/x-icon';
17
+ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
18
+ import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger } from '../ui/select';
19
+ import { Text as UIText } from '../ui/text';
20
+
21
+ export interface OrderFilterOption { value: string; label: string }
22
+ export type PaymentMethodKind = 'cash' | 'card' | 'stored_value' | 'bank_transfer' | 'other';
23
+ export interface OrderFilterBarProps {
24
+ value: OrderFilterValue;
25
+ onChange(next: OrderFilterValue): void;
26
+ /** The connector's orderFilters. A pill shows only when its field is here (store pill: storeId or createdVia). */
27
+ fields: readonly OrderFilterField[];
28
+ /** What Clear all resets to and counts against (v2: cashier + store). Default {}. */
29
+ initial?: OrderFilterValue;
30
+ options?: {
31
+ status?: OrderFilterOption[];
32
+ /** Grouped by kind in this order, with a separator between groups: cash, card, stored_value, bank_transfer, other. */
33
+ paymentMethod?: (OrderFilterOption & { kind?: PaymentMethodKind })[];
34
+ customer?: OrderFilterOption[];
35
+ cashier?: OrderFilterOption[];
36
+ register?: OrderFilterOption[];
37
+ store?: OrderFilterOption[];
38
+ createdVia?: OrderFilterOption[];
39
+ };
40
+ /** The customer and cashier pills search through these when given; otherwise they filter their options locally. */
41
+ onCustomerSearch?(text: string): void;
42
+ onCashierSearch?(text: string): void;
43
+ /** IANA zone of the store, or 'device'. */
44
+ timezone: string;
45
+ now?: () => Date;
46
+ testID?: string;
47
+ }
48
+
49
+ const KINDS: readonly PaymentMethodKind[] = ['cash', 'card', 'stored_value', 'bank_transfer', 'other'];
50
+ // The chip look is ProductFilterBar's; the trigger inside it drops the form-field look of SelectTrigger/ComboboxTrigger.
51
+ const chipClass = (on: boolean) => cn('min-h-11 flex-row items-center gap-1.5 rounded-full border px-3',
52
+ on ? 'border-primary/30 bg-primary/10' : 'border-border bg-card');
53
+ const TRIGGER_RESET = 'h-auto min-h-11 w-auto justify-start rounded-none border-0 bg-transparent px-0 py-0';
54
+ const labelOf = (options: OrderFilterOption[] | undefined, value: string) => options?.find((o) => o.value === value)?.label ?? value;
55
+ const sameRange = (a?: DayRange, b?: DayRange) => a?.from === b?.from && a?.to === b?.to;
56
+ // Clear all counts pills, as v2 counts its filters: the store pill's two fields are one.
57
+ const SIMPLE = ['status', 'paymentMethod', 'customerId', 'cashierId', 'registerId'] as const;
58
+ const changedCount = (value: OrderFilterValue, initial: OrderFilterValue) =>
59
+ SIMPLE.filter((key) => value[key] !== initial[key]).length
60
+ + (value.storeId !== initial.storeId || value.createdVia !== initial.createdVia ? 1 : 0)
61
+ + (sameRange(value.dateRange, initial.dateRange) ? 0 : 1);
62
+
63
+ function Chip({ id, on, label, onClear, trigger }: {
64
+ id: string; on: boolean; label: string; onClear: () => void; trigger: (children: ReactNode) => ReactNode;
65
+ }) {
66
+ return (
67
+ <View className={chipClass(on)}>
68
+ {trigger(<Text className={cn('text-sm', on ? 'text-primary' : 'text-foreground')}>{label}</Text>)}
69
+ {on ? (
70
+ <Pressable testID={`${id}-remove`} role="button" accessibilityLabel="Remove" onPress={onClear}
71
+ hitSlop={8} className="min-h-11 min-w-8 items-center justify-center text-primary">
72
+ <XIcon size={14} />
73
+ </Pressable>
74
+ ) : null}
75
+ </View>
76
+ );
77
+ }
78
+
79
+ function SelectPill({ id, offLabel, selected, onClear, children }: {
80
+ id: string; offLabel: string; selected?: OrderFilterOption; onClear: () => void; children: ReactNode;
81
+ }) {
82
+ return (
83
+ <Select value={selected}>
84
+ <Chip id={id} on={!!selected} label={selected?.label ?? offLabel} onClear={onClear}
85
+ trigger={(label) => <SelectTrigger testID={id} className={TRIGGER_RESET}>{label}</SelectTrigger>} />
86
+ <SelectContent testID={`${id}-menu`}>{children}</SelectContent>
87
+ </Select>
88
+ );
89
+ }
90
+
91
+ function Item({ id, option, onPress }: { id: string; option: OrderFilterOption; onPress: () => void }) {
92
+ return (
93
+ <SelectItem testID={`${id}-${option.value}`} value={option.value} label={option.label} onPress={onPress}>
94
+ <Text className="text-sm text-popover-foreground">{option.label}</Text>
95
+ </SelectItem>
96
+ );
97
+ }
98
+
99
+ function ComboboxPill({ id, offLabel, placeholder, value, options, onSearch, onPick, onClear }: {
100
+ id: string; offLabel: string; placeholder: string; value?: string; options: OrderFilterOption[];
101
+ onSearch?: (text: string) => void; onPick: (value: string) => void; onClear: () => void;
102
+ }) {
103
+ const [search, setSearch] = useState('');
104
+ const selected = value === undefined ? undefined : { value, label: labelOf(options, value) };
105
+ const needle = search.trim().toLowerCase();
106
+ const shown = onSearch || !needle ? options : options.filter((o) => o.label.toLowerCase().includes(needle));
107
+ return (
108
+ <Combobox value={selected} onValueChange={(next) => { if (next) onPick(next.value); }} searchValue={search}
109
+ onSearchValueChange={(text) => { setSearch(text); onSearch?.(text); }}>
110
+ <Chip id={id} on={!!selected} label={selected?.label ?? offLabel} onClear={onClear}
111
+ trigger={(label) => <ComboboxTrigger testID={id} className={TRIGGER_RESET}>{label}</ComboboxTrigger>} />
112
+ <ComboboxContent testID={`${id}-menu`}>
113
+ <View className="border-b border-border px-2 py-1.5">
114
+ <ComboboxInput testID={`${id}-search`} placeholder={placeholder} />
115
+ </View>
116
+ {shown.map((option) => (
117
+ <ComboboxItem key={option.value} testID={`${id}-${option.value}`} value={option.value} label={option.label}>
118
+ <Text className="text-sm text-popover-foreground">{option.label}</Text>
119
+ </ComboboxItem>
120
+ ))}
121
+ {shown.length === 0 ? <ComboboxEmpty /> : null}
122
+ </ComboboxContent>
123
+ </Combobox>
124
+ );
125
+ }
126
+
127
+ function DatePill({ value, onPick, onClear, timezone, now }: {
128
+ value?: DayRange; onPick: (range: DayRange) => void; onClear: () => void; timezone: string; now?: () => Date;
129
+ }) {
130
+ const id = 'order-filter-date';
131
+ const [open, setOpen] = useState(false);
132
+ const [draft, setDraft] = useState<DayRange | null>(value ?? null);
133
+ const at = (now ?? (() => new Date()))();
134
+ const today = presetRange('today', at, timezone);
135
+ const label = !value ? 'Date range'
136
+ : sameRange(value, today) ? 'Today'
137
+ : sameRange(value, presetRange('yesterday', at, timezone)) ? 'Yesterday' : rangeLabel(value);
138
+ const openChange = (next: boolean) => {
139
+ if (next) setDraft(value ?? null);
140
+ setOpen(next);
141
+ };
142
+ const done = () => {
143
+ setOpen(false);
144
+ if (draft) onPick(draft);
145
+ };
146
+ return (
147
+ <Popover open={open} onOpenChange={openChange}>
148
+ <Chip id={id} on={!!value} label={label} onClear={onClear}
149
+ trigger={(text) => <PopoverTrigger testID={id} role="button" className="min-h-11 flex-row items-center">{text}</PopoverTrigger>} />
150
+ <PopoverContent testID={`${id}-popover`} align="start" className="w-auto p-2">
151
+ <Calendar testID={`${id}-calendar`} mode="range" value={draft} onChange={setDraft} today={today.from} />
152
+ <View className="flex-row justify-end pt-2">
153
+ <Pressable testID={`${id}-done`} accessibilityRole="button" onPress={done}
154
+ className="h-10 justify-center rounded-md bg-primary px-4 active:opacity-90">
155
+ <Text className="text-sm font-medium text-primary-foreground">Done</Text>
156
+ </Pressable>
157
+ </View>
158
+ </PopoverContent>
159
+ </Popover>
160
+ );
161
+ }
162
+
163
+ export function OrderFilterBar({
164
+ value, onChange, fields, initial = {}, options = {}, onCustomerSearch, onCashierSearch, timezone, now,
165
+ testID = 'order-filter-bar',
166
+ }: OrderFilterBarProps): JSX.Element {
167
+ const has = (field: OrderFilterField) => fields.includes(field);
168
+ const set = (patch: OrderFilterValue) => onChange({ ...value, ...patch });
169
+ const option = (list: OrderFilterOption[] | undefined, v: string | undefined) => (v === undefined ? undefined : { value: v, label: labelOf(list, v) });
170
+ const changed = changedCount(value, initial);
171
+ const payment = options.paymentMethod ?? [];
172
+ const paymentGroups = KINDS.map((kind) => payment.filter((o) => (o.kind ?? 'other') === kind)).filter((group) => group.length > 0);
173
+ const viaGroup = has('createdVia') ? options.createdVia ?? [] : [];
174
+ const storeGroup = has('storeId') ? options.store ?? [] : [];
175
+ const storeSelected = value.storeId !== undefined ? option(options.store, value.storeId) : option(options.createdVia, value.createdVia);
176
+ const customers = options.customer ?? [];
177
+ const cashiers = options.cashier ?? [];
178
+
179
+ return (
180
+ <View testID={testID} className="flex-row items-center gap-2">
181
+ <ScrollView horizontal showsHorizontalScrollIndicator={false} className="flex-1" contentContainerClassName="flex-row items-center gap-2">
182
+ {has('status') && options.status?.length ? (
183
+ <SelectPill id="order-filter-status" offLabel="Status" selected={option(options.status, value.status)}
184
+ onClear={() => set({ status: undefined })}>
185
+ {options.status.map((o) => <Item key={o.value} id="order-filter-status" option={o} onPress={() => set({ status: o.value })} />)}
186
+ </SelectPill>
187
+ ) : null}
188
+ {has('paymentMethod') ? (
189
+ <SelectPill id="order-filter-payment-method" offLabel="Payment Method" selected={option(payment, value.paymentMethod)}
190
+ onClear={() => set({ paymentMethod: undefined })}>
191
+ {paymentGroups.length === 0 ? (
192
+ <Text className="px-2 py-1.5 text-sm text-muted-foreground">No payment methods found</Text>
193
+ ) : paymentGroups.map((group, i) => (
194
+ <Fragment key={group[0].kind ?? 'other'}>
195
+ {i > 0 ? <SelectSeparator testID="order-filter-payment-method-separator" /> : null}
196
+ <SelectGroup>
197
+ {group.map((o) => <Item key={o.value} id="order-filter-payment-method" option={o} onPress={() => set({ paymentMethod: o.value })} />)}
198
+ </SelectGroup>
199
+ </Fragment>
200
+ ))}
201
+ </SelectPill>
202
+ ) : null}
203
+ {has('customerId') && (customers.length > 0 || onCustomerSearch) ? (
204
+ <ComboboxPill id="order-filter-customer" offLabel="Select Customer" placeholder="Search Customers" value={value.customerId}
205
+ options={customers} onSearch={onCustomerSearch} onPick={(v) => set({ customerId: v })} onClear={() => set({ customerId: undefined })} />
206
+ ) : null}
207
+ {has('cashierId') && (cashiers.length > 0 || onCashierSearch) ? (
208
+ <ComboboxPill id="order-filter-cashier" offLabel="Select Cashier" placeholder="Search Cashiers" value={value.cashierId}
209
+ options={cashiers} onSearch={onCashierSearch} onPick={(v) => set({ cashierId: v })} onClear={() => set({ cashierId: undefined })} />
210
+ ) : null}
211
+ {viaGroup.length > 0 || storeGroup.length > 0 ? (
212
+ <SelectPill id="order-filter-store" offLabel="Created via" selected={storeSelected}
213
+ onClear={() => set({ storeId: undefined, createdVia: undefined })}>
214
+ {viaGroup.length > 0 ? (
215
+ <SelectGroup testID="order-filter-store-created-via">
216
+ <SelectLabel className="pl-2">Created via</SelectLabel>
217
+ {viaGroup.map((o) => <Item key={o.value} id="order-filter-store" option={o} onPress={() => set({ createdVia: o.value, storeId: undefined })} />)}
218
+ </SelectGroup>
219
+ ) : null}
220
+ {viaGroup.length > 0 && storeGroup.length > 0 ? <SelectSeparator /> : null}
221
+ {storeGroup.length > 0 ? (
222
+ <SelectGroup testID="order-filter-store-stores">
223
+ <SelectLabel className="pl-2">Store</SelectLabel>
224
+ {storeGroup.map((o) => <Item key={o.value} id="order-filter-store" option={o} onPress={() => set({ storeId: o.value, createdVia: undefined })} />)}
225
+ </SelectGroup>
226
+ ) : null}
227
+ </SelectPill>
228
+ ) : null}
229
+ {has('registerId') && options.register?.length ? (
230
+ <SelectPill id="order-filter-register" offLabel="Select register" selected={option(options.register, value.registerId)}
231
+ onClear={() => set({ registerId: undefined })}>
232
+ {options.register.map((o) => <Item key={o.value} id="order-filter-register" option={o} onPress={() => set({ registerId: o.value })} />)}
233
+ </SelectPill>
234
+ ) : null}
235
+ {has('dateRange') ? (
236
+ <DatePill value={value.dateRange} onPick={(range) => set({ dateRange: range })} onClear={() => set({ dateRange: undefined })}
237
+ timezone={timezone} now={now} />
238
+ ) : null}
239
+ </ScrollView>
240
+ {changed >= 2 ? (
241
+ <Button variant="link" size="sm" testID="orders-filter-clear-all" onPress={() => onChange({ ...initial })}>
242
+ <UIText>Clear all</UIText>
243
+ </Button>
244
+ ) : null}
245
+ </View>
246
+ );
247
+ }
@@ -0,0 +1,28 @@
1
+ import { View } from 'react-native';
2
+ import { IconButton } from '../ui/icon-button';
3
+ import { ScanIcon } from '../ui/icon/scan-icon';
4
+ import { Text } from '../ui/text';
5
+ import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
6
+
7
+ export interface CameraScanButtonProps {
8
+ /** The camera scanner is showing: the button then closes it. */
9
+ open: boolean;
10
+ onPress: () => void;
11
+ testID?: string;
12
+ }
13
+
14
+ /** Opens and closes the camera scanner panel (v2 pos/products/camera-scan-button.tsx). */
15
+ export function CameraScanButton({ open, onPress, testID = 'camera-scan-button' }: CameraScanButtonProps) {
16
+ const label = open ? 'Close barcode scanner' : 'Scan barcode with camera';
17
+ return (
18
+ <Tooltip>
19
+ <TooltipTrigger asChild>
20
+ <IconButton variant={open ? 'secondary' : 'ghost'} testID={testID} accessibilityLabel={label}
21
+ accessibilityState={{ expanded: open }} onPress={onPress}>
22
+ <View className={open ? 'text-secondary-foreground' : 'text-foreground'}><ScanIcon size={20} /></View>
23
+ </IconButton>
24
+ </TooltipTrigger>
25
+ <TooltipContent><Text>{label}</Text></TooltipContent>
26
+ </Tooltip>
27
+ );
28
+ }
@@ -0,0 +1,156 @@
1
+ import { useEffect, useRef, useState, type ComponentType } from 'react';
2
+ import { Platform, View, type AccessibilityActionEvent } from 'react-native';
3
+ import type { CameraDecoder, ViewfinderStatus } from '@tallyui/pos';
4
+ import { Button } from '../ui/button';
5
+ import { IconButton } from '../ui/icon-button';
6
+ import { GripIcon } from '../ui/icon/grip-icon';
7
+ import { XIcon } from '../ui/icon/x-icon';
8
+ import { Text } from '../ui/text';
9
+ import { VStack } from '../ui/vstack';
10
+ import { ScannerViewfinder, type ViewfinderProps } from './scanner-viewfinder';
11
+
12
+ // v2 pos/products/camera-scanner-panel.tsx:24-36.
13
+ export const FLASH_DURATION_MS = 350;
14
+ export const SCANNER_MIN_HEIGHT = 96;
15
+ export const SCANNER_MAX_HEIGHT = 480;
16
+ export const SCANNER_DEFAULT_HEIGHT = 176;
17
+ const STEP = 16;
18
+ const RESIZE_HANDLE_HEIGHT = 20;
19
+ const HANDLE_SLOP = (44 - RESIZE_HANDLE_HEIGHT) / 2;
20
+
21
+ const STATUS_TEXT: Record<ViewfinderStatus, string | undefined> = {
22
+ initializing: 'Starting camera…',
23
+ scanning: undefined,
24
+ 'camera-denied': 'Camera access was denied — allow it in the browser settings and reopen the scanner.',
25
+ 'camera-unavailable': 'Camera unavailable — check that no other app is using it.',
26
+ 'decoder-error': 'Barcode decoding is failing — close the scanner and try again.',
27
+ };
28
+
29
+ const clampHeight = (height: number) => Math.min(SCANNER_MAX_HEIGHT, Math.max(SCANNER_MIN_HEIGHT, Math.round(height)));
30
+
31
+ export interface CameraScannerPanelProps {
32
+ onClose: () => void;
33
+ /** Panel height; clamped to [96, 480]. Default 176. The app persists it from onHeightChange. */
34
+ height?: number;
35
+ onHeightChange?: (height: number) => void;
36
+ /** Native permission flow; omit on web, where the browser asks on getUserMedia. */
37
+ permission?: { granted: boolean; request: () => void };
38
+ /** Default ScannerViewfinder; a native app passes its own (for example one built on expo-camera). */
39
+ viewfinder?: ComponentType<ViewfinderProps>;
40
+ decoder?: CameraDecoder;
41
+ /** v2's readiness note (storage, offline, sync starting): the app picks the copy; shown under the status. */
42
+ readiness?: string;
43
+ /** Each decode, passed straight to the viewfinder: the app passes its useCameraScan offer. */
44
+ onDetected: (code: string, symbology?: string) => void;
45
+ /** Called once on mount (the scanner opened): the app passes its useCameraScan reset. */
46
+ onOpen?: () => void;
47
+ /** The app's useCameraScan scanCount: each change after mount flashes the panel. */
48
+ scanCount?: number;
49
+ }
50
+
51
+ /** The inline camera scanner (v2 camera-scanner-panel.tsx). It calls no pos hook: the app owns useCameraScan (and
52
+ * its ScanHubProvider) and passes { onDetected: camera.offer, onOpen: camera.reset, scanCount: camera.scanCount },
53
+ * so accepted decodes reach the app's useBarcodeScanner like any device scan. */
54
+ export function CameraScannerPanel({ onClose, height: heightProp = SCANNER_DEFAULT_HEIGHT, onHeightChange, permission,
55
+ viewfinder: Viewfinder = ScannerViewfinder, decoder, readiness, onDetected, onOpen, scanCount }: CameraScannerPanelProps) {
56
+ const [status, setStatus] = useState<ViewfinderStatus>('initializing');
57
+ const [height, setHeight] = useState(() => clampHeight(heightProp));
58
+ useEffect(() => { setHeight(clampHeight(heightProp)); }, [heightProp]);
59
+ const heightRef = useRef(height);
60
+ heightRef.current = height;
61
+ const onHeightChangeRef = useRef(onHeightChange);
62
+ onHeightChangeRef.current = onHeightChange;
63
+
64
+ // Opening the scanner mounts the panel: a code scanned before it was closed may be scanned again at once.
65
+ const onOpenRef = useRef(onOpen);
66
+ onOpenRef.current = onOpen;
67
+ useEffect(() => { onOpenRef.current?.(); }, []);
68
+
69
+ // Each scanCount change after mount (re)starts the flash; the value at mount never flashes.
70
+ const [flashing, setFlashing] = useState(false);
71
+ const seenCount = useRef(scanCount);
72
+ const flashTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
73
+ useEffect(() => {
74
+ if (scanCount === seenCount.current) return;
75
+ seenCount.current = scanCount;
76
+ if (flashTimer.current !== undefined) clearTimeout(flashTimer.current);
77
+ setFlashing(true);
78
+ flashTimer.current = setTimeout(() => { flashTimer.current = undefined; setFlashing(false); }, FLASH_DURATION_MS);
79
+ }, [scanCount]);
80
+ useEffect(() => () => { if (flashTimer.current !== undefined) clearTimeout(flashTimer.current); }, []);
81
+
82
+ const adjust = (delta: number) => {
83
+ const next = clampHeight(heightRef.current + delta);
84
+ setHeight(next);
85
+ onHeightChangeRef.current?.(next);
86
+ };
87
+ const onAccessibilityAction = ({ nativeEvent }: AccessibilityActionEvent) => {
88
+ if (nativeEvent.actionName === 'increment') adjust(STEP);
89
+ else if (nativeEvent.actionName === 'decrement') adjust(-STEP);
90
+ };
91
+ // Web pointer drag: the height follows the pointer and is reported once, when the drag ends.
92
+ const dragCleanup = useRef<(() => void) | undefined>(undefined);
93
+ useEffect(() => () => dragCleanup.current?.(), []);
94
+ const startDrag = (startY: number) => {
95
+ if (Platform.OS !== 'web' || typeof window === 'undefined') return;
96
+ dragCleanup.current?.();
97
+ const startHeight = heightRef.current;
98
+ let last = startHeight;
99
+ const move = (event: PointerEvent) => {
100
+ last = clampHeight(startHeight + event.clientY - startY);
101
+ setHeight(last);
102
+ };
103
+ const end = () => {
104
+ dragCleanup.current?.();
105
+ if (last !== startHeight) onHeightChangeRef.current?.(last);
106
+ };
107
+ window.addEventListener('pointermove', move);
108
+ window.addEventListener('pointerup', end);
109
+ window.addEventListener('pointercancel', end);
110
+ dragCleanup.current = () => {
111
+ dragCleanup.current = undefined;
112
+ window.removeEventListener('pointermove', move);
113
+ window.removeEventListener('pointerup', end);
114
+ window.removeEventListener('pointercancel', end);
115
+ };
116
+ };
117
+
118
+ if (permission && !permission.granted) {
119
+ return (
120
+ <VStack space="md" className="border-border items-center rounded-md border p-4" testID="camera-permission-request">
121
+ <Text className="text-center text-sm">Camera access is needed to scan barcodes.</Text>
122
+ <Button onPress={permission.request}><Text>Allow camera</Text></Button>
123
+ </VStack>
124
+ );
125
+ }
126
+
127
+ const statusText = STATUS_TEXT[status];
128
+ return (
129
+ <View>
130
+ <View className="relative w-full overflow-hidden rounded-md bg-black" style={{ height }} testID="camera-scanner-panel">
131
+ <Viewfinder onDetected={onDetected} onStatus={setStatus} decoder={decoder} />
132
+ {flashing ? <View className="border-success pointer-events-none absolute inset-0 rounded-md border-4"
133
+ testID="camera-scanner-flash" /> : null}
134
+ <View className="absolute top-1 right-1">
135
+ <IconButton size="sm" onPress={onClose} accessibilityLabel="Close barcode scanner" testID="camera-scanner-close">
136
+ <View className="text-white"><XIcon size={16} /></View>
137
+ </IconButton>
138
+ </View>
139
+ {statusText || readiness ? (
140
+ <View className="absolute inset-x-0 bottom-0 gap-1 bg-black/60 p-2">
141
+ {statusText ? <Text className="text-center text-xs text-white" testID="camera-scanner-status">{statusText}</Text> : null}
142
+ {readiness ? <Text className="text-center text-xs text-white/80" testID="camera-scanner-readiness">{readiness}</Text> : null}
143
+ </View>
144
+ ) : null}
145
+ </View>
146
+ <View className="web:cursor-ns-resize web:hover:opacity-100 items-center justify-center opacity-40"
147
+ style={{ height: RESIZE_HANDLE_HEIGHT }} hitSlop={{ top: HANDLE_SLOP, bottom: HANDLE_SLOP }}
148
+ accessible accessibilityRole="adjustable" accessibilityLabel="Drag to resize the camera view"
149
+ accessibilityValue={{ min: SCANNER_MIN_HEIGHT, max: SCANNER_MAX_HEIGHT, now: height }}
150
+ accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]} onAccessibilityAction={onAccessibilityAction}
151
+ onPointerDown={(event) => startDrag(event.nativeEvent.clientY)} testID="camera-scanner-resize-handle">
152
+ <View className="-my-0.5 text-foreground"><GripIcon size={16} /></View>
153
+ </View>
154
+ </View>
155
+ );
156
+ }
@@ -11,4 +11,9 @@ export { ProductList, type ProductListProps } from './product-list';
11
11
  export { CategoryNav, type CategoryNavProps, type CategoryItem } from './category-nav';
12
12
  export { ProductVariantPicker, type ProductVariantPickerProps, type VariantOption } from './product-variant-picker';
13
13
  export { InCartBadge, type InCartBadgeProps } from './in-cart-badge';
14
+ export { VariationPicker, type VariationPickerProps } from './variation-picker';
14
15
  export { CategoryTile, type CategoryTileProps } from './category-tile';
16
+ export { CameraScanButton, type CameraScanButtonProps } from './camera-scan-button';
17
+ export { CameraScannerPanel, FLASH_DURATION_MS, SCANNER_MIN_HEIGHT, SCANNER_MAX_HEIGHT, SCANNER_DEFAULT_HEIGHT,
18
+ type CameraScannerPanelProps } from './camera-scanner-panel';
19
+ export { ScannerViewfinder, type ViewfinderProps } from './scanner-viewfinder';
@@ -16,11 +16,18 @@ const BATCH_ROWS = 8;
16
16
  // Keep nearby rows mounted without rendering the whole 2,000-product catalogue.
17
17
  const WINDOW_SIZE = 5;
18
18
 
19
+ // Place column content horizontally inside column-direction Views.
20
+ const ALIGN = { left: 'items-start', center: 'items-center', right: 'items-end' } as const;
21
+
19
22
  export interface ProductTableColumn<Doc = any> {
20
23
  /** Stable id; the default columns use PRODUCT_SORT_FIELDS. */
21
24
  id: string;
22
25
  /** Header label. */
23
26
  header: string;
27
+ /** Places the head and the cells' content; default left (WCPOS v2 column-style). */
28
+ align?: 'left' | 'center' | 'right';
29
+ /** Draws no head label; `header` stays the head's accessible name (v2's image column). */
30
+ hideHeader?: boolean;
24
31
  render: (doc: Doc) => ReactNode;
25
32
  /** The value the header sort orders by; omit to make the column unsortable. */
26
33
  sortValue?: (doc: Doc) => ProductSortValue;
@@ -56,7 +63,7 @@ export function defaultProductColumns(
56
63
  { id: 'name', header: 'Name', flex: 3, render: (doc) => <ProductTitle doc={doc} numberOfLines={2} /> },
57
64
  { id: 'sku', header: 'SKU', flex: 1, render: (doc) => <ProductSku doc={doc} /> },
58
65
  { id: 'barcode', header: 'Barcode', flex: 1, render: (doc) => <Text>{traits.getBarcode(doc) ?? '—'}</Text> },
59
- { id: 'price', header: 'Price', flex: 1, render: (doc) => <ProductPrice doc={doc} currencySymbol={options?.currencySymbol} /> },
66
+ { id: 'price', header: 'Price', flex: 1, align: 'right', render: (doc) => <ProductPrice doc={doc} currencySymbol={options?.currencySymbol} /> },
60
67
  { id: 'stock', header: 'Stock', flex: 1, render: (doc) => <ProductStockBadge doc={doc} showQuantity showAsOf={false} /> },
61
68
  { id: 'category', header: 'Category', flex: 2, render: (doc) => <Text>{traits.getCategoryNames(doc).join(', ') || '—'}</Text> },
62
69
  ];
@@ -110,14 +117,16 @@ export function ProductTable({
110
117
  <TableRow>
111
118
  {resolvedColumns.map((column) => (
112
119
  <TableHead key={column.id} style={{ flex: column.flex ?? 1 }}
120
+ className={cn('h-9 justify-center px-3 py-0', column.align && ALIGN[column.align])}
121
+ aria-label={column.hideHeader ? column.header : undefined}
113
122
  {...(column.sortValue ? { 'aria-sort': activeSort?.field === column.id
114
123
  ? (activeSort.dir === 'asc' ? 'ascending' : 'descending') : 'none' } : {})}>
115
124
  {column.sortValue ? (
116
125
  <Pressable accessibilityRole="button" accessibilityLabel={'Sort by ' + column.header}
117
126
  testID={'product-table-sort-' + column.id} onPress={() => changeSort(column.id)}>
118
- <Text>{column.header}{activeSort?.field === column.id ? (activeSort.dir === 'asc' ? ' ▲' : ' ▼') : ''}</Text>
127
+ <Text numberOfLines={1}>{column.hideHeader ? '' : column.header}{activeSort?.field === column.id ? (activeSort.dir === 'asc' ? ' ▲' : ' ▼') : ''}</Text>
119
128
  </Pressable>
120
- ) : <Text>{column.header}</Text>}
129
+ ) : <Text numberOfLines={1}>{column.hideHeader ? '' : column.header}</Text>}
121
130
  </TableHead>
122
131
  ))}
123
132
  </TableRow>
@@ -134,7 +143,8 @@ export function ProductTable({
134
143
  const row = (
135
144
  <TableRow testID={onSelect ? undefined : 'product-row-' + key}>
136
145
  {resolvedColumns.map((column) => (
137
- <TableCell key={column.id} style={{ flex: column.flex ?? 1 }}>{column.render(item)}</TableCell>
146
+ <TableCell key={column.id} style={{ flex: column.flex ?? 1 }}
147
+ className={cn('px-3 py-1.5', column.align && ALIGN[column.align])}>{column.render(item)}</TableCell>
138
148
  ))}
139
149
  </TableRow>
140
150
  );
@@ -0,0 +1,76 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { Platform, View } from 'react-native';
3
+ import { CAMERA_CONSTRAINTS, cameraErrorStatus, nativeBarcodeDetector, startDecodeLoop,
4
+ type CameraDecoder, type ViewfinderStatus } from '@tallyui/pos';
5
+
6
+ export interface ViewfinderProps {
7
+ onDetected: (code: string, symbology?: string) => void;
8
+ onStatus: (status: ViewfinderStatus) => void;
9
+ /** Defaults to the BarcodeDetector global where it exists; an app may pass a ponyfill with the same detect. */
10
+ decoder?: CameraDecoder;
11
+ }
12
+
13
+ function canUseCamera(): boolean {
14
+ return Platform.OS === 'web' && typeof navigator !== 'undefined' && typeof navigator.mediaDevices?.getUserMedia === 'function';
15
+ }
16
+
17
+ function stopTracks(stream: MediaStream) {
18
+ for (const track of stream.getTracks()) track.stop();
19
+ }
20
+
21
+ /** The web camera view: getUserMedia into a <video>, decoded by startDecodeLoop (v2 scanner-viewfinder.web.tsx).
22
+ * Elsewhere it reports 'camera-unavailable' and renders an empty view; a native app passes its own viewfinder
23
+ * (for example one built on expo-camera) to CameraScannerPanel. */
24
+ export function ScannerViewfinder(props: ViewfinderProps) {
25
+ const latest = useRef(props);
26
+ latest.current = props;
27
+ const videoRef = useRef<HTMLVideoElement | null>(null);
28
+ const web = canUseCamera();
29
+
30
+ useEffect(() => {
31
+ if (!web) {
32
+ latest.current.onStatus('camera-unavailable');
33
+ return;
34
+ }
35
+ let cancelled = false;
36
+ let stream: MediaStream | undefined;
37
+ let loop: { stop(): void } | undefined;
38
+ latest.current.onStatus('initializing');
39
+ navigator.mediaDevices.getUserMedia(CAMERA_CONSTRAINTS).then((media) => {
40
+ // Unmounted before the camera answered: release the late stream at once.
41
+ if (cancelled) {
42
+ stopTracks(media);
43
+ return;
44
+ }
45
+ stream = media;
46
+ const video = videoRef.current;
47
+ if (video) video.srcObject = media;
48
+ const decoder = latest.current.decoder ?? nativeBarcodeDetector();
49
+ if (!decoder) {
50
+ latest.current.onStatus('decoder-error');
51
+ return;
52
+ }
53
+ latest.current.onStatus('scanning');
54
+ loop = startDecodeLoop({
55
+ decoder,
56
+ source: video,
57
+ onDetected: (code, symbology) => latest.current.onDetected(code, symbology),
58
+ onStatus: (status) => latest.current.onStatus(status),
59
+ });
60
+ }, (error: unknown) => {
61
+ if (!cancelled) latest.current.onStatus(cameraErrorStatus(error));
62
+ });
63
+ return () => {
64
+ cancelled = true;
65
+ loop?.stop();
66
+ if (stream) stopTracks(stream);
67
+ };
68
+ }, [web]);
69
+
70
+ return (
71
+ <View className="h-full w-full" testID="scanner-viewfinder">
72
+ {web ? <video ref={videoRef} autoPlay playsInline muted
73
+ style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : null}
74
+ </View>
75
+ );
76
+ }