@tallyui/components 3.20.1 → 4.0.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 (161) hide show
  1. package/dist/index.d.ts +1114 -90
  2. package/dist/index.js +8077 -3352
  3. package/package.json +10 -11
  4. package/src/cart/cart-charge-line.tsx +58 -0
  5. package/src/cart/cart-columns-form.tsx +98 -0
  6. package/src/cart/cart-columns.tsx +49 -18
  7. package/src/cart/cart-foot.tsx +7 -2
  8. package/src/cart/cart-line-strip.tsx +59 -0
  9. package/src/cart/cart-line.tsx +20 -8
  10. package/src/cart/cart-note-row.tsx +30 -0
  11. package/src/cart/cart-panel.tsx +9 -1
  12. package/src/cart/cart-row-motion.tsx +125 -0
  13. package/src/cart/cart-total.tsx +44 -15
  14. package/src/cart/index.ts +2 -1
  15. package/src/checkout/cash-tendered.tsx +8 -7
  16. package/src/checkout/change-display.tsx +2 -1
  17. package/src/checkout/index.ts +1 -1
  18. package/src/checkout/payment-selector.tsx +6 -2
  19. package/src/checkout/payment-types.test-d.ts +28 -0
  20. package/src/customer/address-editor.tsx +87 -0
  21. package/src/customer/address-fields.tsx +120 -0
  22. package/src/customer/customer-dropdown.tsx +200 -0
  23. package/src/customer/customer-editor.tsx +99 -0
  24. package/src/customer/customer-form.tsx +39 -5
  25. package/src/customer/customer-picker.tsx +38 -14
  26. package/src/customer/customers-list.tsx +83 -0
  27. package/src/customer/index.ts +5 -0
  28. package/src/filter/filter-pills.tsx +63 -0
  29. package/src/i18n/locales/en/components.json +85 -0
  30. package/src/index.ts +40 -2
  31. package/src/input/decimal-entry.ts +21 -0
  32. package/src/layout/checkout-layout.tsx +1 -1
  33. package/src/layout/live-tab-screen.tsx +1 -1
  34. package/src/layout/pos-layout.tsx +80 -4
  35. package/src/layout/settings-layout.tsx +1 -1
  36. package/src/layout/store-settings-choice-screen.tsx +1 -1
  37. package/src/lib/current-row.ts +13 -0
  38. package/src/lib/money-input.ts +16 -0
  39. package/src/lib/motion.ts +22 -0
  40. package/src/lib/use-reduced-motion.ts +20 -0
  41. package/src/order/index.ts +1 -1
  42. package/src/order/order-detail.tsx +123 -5
  43. package/src/order/order-filter-bar.tsx +7 -57
  44. package/src/order/order-status-badge.tsx +42 -19
  45. package/src/order/refund-form.tsx +7 -5
  46. package/src/product/camera-scan-button.tsx +2 -0
  47. package/src/product/category-nav.tsx +8 -0
  48. package/src/product/category-tile.tsx +65 -15
  49. package/src/product/in-cart-badge.tsx +55 -6
  50. package/src/product/index.ts +1 -0
  51. package/src/product/press-veil.tsx +7 -0
  52. package/src/product/product-card.tsx +5 -1
  53. package/src/product/product-grid.tsx +5 -0
  54. package/src/product/product-price.tsx +6 -3
  55. package/src/product/product-stock-badge.tsx +3 -2
  56. package/src/product/product-table.tsx +96 -8
  57. package/src/product/products-screen-columns.tsx +74 -0
  58. package/src/product/variant-tile.tsx +68 -0
  59. package/src/product/variation-picker.tsx +3 -3
  60. package/src/product/view-toggle.tsx +33 -4
  61. package/src/register/cashier-sheet.tsx +195 -0
  62. package/src/register/closure-sheet.tsx +54 -3
  63. package/src/register/handover-slip.tsx +2 -1
  64. package/src/register/index.ts +2 -1
  65. package/src/register/movement-sheet.tsx +66 -7
  66. package/src/register/open-register-card.tsx +11 -11
  67. package/src/register/register-bar.helpers.ts +17 -4
  68. package/src/register/register-bar.tsx +26 -5
  69. package/src/register/register-count.tsx +158 -24
  70. package/src/register/register-panel.tsx +16 -5
  71. package/src/register/register-side-sheet.tsx +32 -8
  72. package/src/register/switch-confirm.tsx +2 -2
  73. package/src/reports/card-panel.tsx +131 -0
  74. package/src/reports/cards.tsx +53 -36
  75. package/src/reports/hero.tsx +2 -1
  76. package/src/reports/index.ts +1 -0
  77. package/src/reports/sales-room.tsx +4 -2
  78. package/src/sale/breadcrumb.tsx +48 -0
  79. package/src/sale/cart-bar.tsx +2 -1
  80. package/src/sale/cart.tsx +127 -38
  81. package/src/sale/catalogue-settings-form.tsx +92 -0
  82. package/src/sale/catalogue.tsx +304 -42
  83. package/src/sale/category-browse.tsx +27 -0
  84. package/src/sale/charge-form.tsx +85 -21
  85. package/src/sale/customer-display-screen.tsx +22 -6
  86. package/src/sale/discount-form.tsx +132 -28
  87. package/src/sale/index.ts +6 -3
  88. package/src/sale/line-popover.tsx +72 -36
  89. package/src/sale/offered-methods.ts +16 -0
  90. package/src/sale/open-sale-tabs.tsx +58 -10
  91. package/src/sale/order-note-sheet.tsx +37 -0
  92. package/src/sale/order-reference.ts +3 -0
  93. package/src/sale/orders-list.tsx +76 -37
  94. package/src/sale/parked-sales.tsx +2 -1
  95. package/src/sale/price-form.tsx +7 -5
  96. package/src/sale/product-filter-bar.tsx +38 -5
  97. package/src/sale/receipt-sheet.tsx +243 -0
  98. package/src/sale/receipt.tsx +19 -9
  99. package/src/sale/sync-status.tsx +10 -0
  100. package/src/sale/tender-ledger.tsx +92 -0
  101. package/src/sale/tender-pane.tsx +159 -73
  102. package/src/sale/tender.tsx +10 -7
  103. package/src/sale/use-tender.ts +63 -0
  104. package/src/scale/min-target.tsx +36 -0
  105. package/src/settings/barcode-scanning-settings.tsx +164 -0
  106. package/src/settings/connector-status.tsx +1 -1
  107. package/src/settings/customer-display-settings.tsx +12 -25
  108. package/src/settings/index.ts +5 -0
  109. package/src/settings/printer-form.tsx +161 -0
  110. package/src/settings/printing-settings.tsx +268 -0
  111. package/src/settings/settings-group.tsx +2 -1
  112. package/src/settings/tax-calculation-settings.tsx +1 -1
  113. package/src/shell/added-to-cart-toast.tsx +61 -0
  114. package/src/shell/app-shell.tsx +5 -1
  115. package/src/shell/connectivity-toast.tsx +70 -0
  116. package/src/shell/index.ts +2 -0
  117. package/src/shell/nav-drawer.tsx +5 -2
  118. package/src/shell/nav-item.tsx +7 -4
  119. package/src/shell/nav-rail.tsx +9 -2
  120. package/src/ui/accordion/index.tsx +86 -8
  121. package/src/ui/alert-dialog/index.tsx +19 -5
  122. package/src/ui/combobox/index.tsx +21 -2
  123. package/src/ui/confirm-dialog/index.tsx +53 -0
  124. package/src/ui/dialog/index.tsx +68 -14
  125. package/src/ui/dialog/motion.ts +54 -0
  126. package/src/ui/icon/activity-heartbeat-icon.tsx +7 -0
  127. package/src/ui/icon/alert-circle-icon.tsx +5 -0
  128. package/src/ui/icon/alert-triangle-icon.tsx +7 -0
  129. package/src/ui/icon/banknote-icon.tsx +11 -0
  130. package/src/ui/icon/cash-register-icon.tsx +10 -0
  131. package/src/ui/icon/category-icon.tsx +7 -0
  132. package/src/ui/icon/chart-line-icon.tsx +5 -0
  133. package/src/ui/icon/check-icon.tsx +5 -0
  134. package/src/ui/icon/chevron-left-icon.tsx +4 -0
  135. package/src/ui/icon/chevron-right-icon.tsx +4 -0
  136. package/src/ui/icon/credit-card-icon.tsx +10 -0
  137. package/src/ui/icon/discount-icon.tsx +11 -0
  138. package/src/ui/icon/gift-icon.tsx +10 -0
  139. package/src/ui/icon/info-circle-icon.tsx +10 -0
  140. package/src/ui/icon/map-pin-icon.tsx +10 -0
  141. package/src/ui/icon/message-question-icon.tsx +7 -0
  142. package/src/ui/icon/pencil-icon.tsx +10 -0
  143. package/src/ui/icon/plus-icon.tsx +9 -0
  144. package/src/ui/icon/printer-icon.tsx +10 -0
  145. package/src/ui/icon/receipt-icon.tsx +7 -0
  146. package/src/ui/icon/settings-icon.tsx +10 -0
  147. package/src/ui/icon/sticky-note-icon.tsx +10 -0
  148. package/src/ui/icon/user-icon.tsx +4 -0
  149. package/src/ui/icon/users-icon.tsx +7 -0
  150. package/src/ui/icon/view-grid-icon.tsx +7 -0
  151. package/src/ui/icon/view-list-icon.tsx +7 -0
  152. package/src/ui/index.ts +24 -1
  153. package/src/ui/list-row/index.tsx +93 -0
  154. package/src/ui/notice/index.tsx +65 -0
  155. package/src/ui/select/index.tsx +2 -0
  156. package/src/ui/skeleton/index.tsx +37 -0
  157. package/src/ui/status-badge/index.tsx +43 -0
  158. package/src/ui/switch/index.tsx +1 -1
  159. package/src/ui/tabs/index.tsx +11 -2
  160. package/src/ui/toggle-group/index.tsx +3 -1
  161. package/src/ui/tone-disc/index.tsx +41 -0
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Settings › Barcode scanning › Scanning: the four values the scanner engine takes
3
+ * (`@tallyui/pos` `UseBarcodeScannerOptions`: threshold, minChars, prefix, suffix).
4
+ * Port of WCPOS v2 `packages/core/src/screens/main/settings/barcode-scanning/settings.tsx`, its first section;
5
+ * the labels are v2's English strings from core.json. Props-only: the app passes the values and saves each patch,
6
+ * as v2 saves every change at once (there is no Save button).
7
+ *
8
+ * Left out, each a later row: v2's Sound section (TallyUI has no scan-sound player, so a switch would do nothing),
9
+ * the Input sources / scanner chooser, and the test panel's key capture, timing chart and history. The app captures
10
+ * keys and runs `analyzeScanTrace`; the optional test prop draws its verdict and applies suggestions through onChange.
11
+ */
12
+ import { useState } from 'react';
13
+ import { View } from 'react-native';
14
+ import type { TraceAnalysis } from '@tallyui/pos';
15
+ import { CheckIcon } from '../ui/icon/check-icon';
16
+ import { Input } from '../ui/input';
17
+ import { Notice } from '../ui/notice';
18
+ import { Text } from '../ui/text';
19
+ import { SettingsGroup } from './settings-group';
20
+ import { SettingsRow } from './settings-row';
21
+
22
+ export interface BarcodeScanningValues {
23
+ /** Average gap between keys, in ms, below which a burst is a scan (v2 default 24). */
24
+ threshold: number;
25
+ /** Shortest code accepted as a scan (v2 default 8). */
26
+ minChars: number;
27
+ prefix: string;
28
+ suffix: string;
29
+ }
30
+
31
+ export interface BarcodeScanningSettingsProps {
32
+ values: BarcodeScanningValues;
33
+ /** Called with only the field that changed, as soon as it holds a valid value. */
34
+ onChange: (patch: Partial<BarcodeScanningValues>) => void;
35
+ className?: string;
36
+ /** v2's Barcode Scanning Test: drawn only when given. The app captures the keys and runs `analyzeScanTrace` with the
37
+ * current values; `analysis` is null before the first test scan. `capture` is the app's own capture field, drawn first. */
38
+ test?: { analysis: TraceAnalysis | null; capture?: React.ReactNode };
39
+ }
40
+
41
+ const FIELD = 'h-11 w-28';
42
+
43
+ /**
44
+ * A whole number ≥ 0, as v2's `z.coerce.number().int().min(0)` count field: digits only. While the text is empty it
45
+ * reports nothing; on blur it shows the current value again (v2's form restores the stored value the same way).
46
+ */
47
+ function CountField({ testID, label, value, onValue }: {
48
+ testID: string; label: string; value: number; onValue: (value: number) => void;
49
+ }) {
50
+ const [draft, setDraft] = useState(String(value));
51
+ // The draft follows a new value from the app (saved, reset or applied elsewhere), adjusted during render.
52
+ const [shown, setShown] = useState(value);
53
+ if (shown !== value) {
54
+ setShown(value);
55
+ setDraft(String(value));
56
+ }
57
+ return (
58
+ <Input className={FIELD}>
59
+ <Input.Field
60
+ testID={testID}
61
+ accessibilityLabel={label}
62
+ keyboardType="number-pad"
63
+ value={draft}
64
+ onChangeText={(text) => {
65
+ const digits = text.replace(/\D/g, '');
66
+ setDraft(digits);
67
+ if (digits !== '') onValue(Number(digits));
68
+ }}
69
+ onBlur={() => { if (draft === '') setDraft(String(value)); }}
70
+ />
71
+ </Input>
72
+ );
73
+ }
74
+
75
+ /** Plain controlled text, reported as typed: no trimming, since a scanner's prefix may be a space. */
76
+ function TextField({ testID, label, value, onValue }: {
77
+ testID: string; label: string; value: string; onValue: (value: string) => void;
78
+ }) {
79
+ return (
80
+ <Input className={FIELD}>
81
+ <Input.Field testID={testID} accessibilityLabel={label} value={value} onChangeText={onValue} />
82
+ </Input>
83
+ );
84
+ }
85
+
86
+ const THRESHOLD = 'Barcode Average Time Input Threshold (ms)';
87
+ const MIN_CHARS = 'Barcode Minimum Length';
88
+ const PREFIX = 'Barcode Scanner Prefix';
89
+ const SUFFIX = 'Barcode Scanner Suffix';
90
+
91
+ export function BarcodeScanningSettings({ values, onChange, className, test }: BarcodeScanningSettingsProps) {
92
+ const analysis = test?.analysis;
93
+ const avg = analysis ? Math.round(analysis.avgGapMs) : 0;
94
+ return (<>
95
+ <SettingsGroup title="Scanning" className={className}>
96
+ <SettingsRow label={THRESHOLD} action={(
97
+ <CountField testID="settings-barcode-threshold" label={THRESHOLD} value={values.threshold}
98
+ onValue={(threshold) => onChange({ threshold })} />
99
+ )} />
100
+ <SettingsRow label={MIN_CHARS} action={(
101
+ <CountField testID="settings-barcode-min-chars" label={MIN_CHARS} value={values.minChars}
102
+ onValue={(minChars) => onChange({ minChars })} />
103
+ )} />
104
+ <SettingsRow label={PREFIX} action={(
105
+ <TextField testID="settings-barcode-prefix" label={PREFIX} value={values.prefix}
106
+ onValue={(prefix) => onChange({ prefix })} />
107
+ )} />
108
+ <SettingsRow label={SUFFIX} action={(
109
+ <TextField testID="settings-barcode-suffix" label={SUFFIX} value={values.suffix}
110
+ onValue={(suffix) => onChange({ suffix })} />
111
+ )} />
112
+ </SettingsGroup>
113
+ {test && (
114
+ <SettingsGroup title="Barcode Scanning Test">
115
+ {test.capture}
116
+ {analysis && (
117
+ <View testID="barcode-test-verdict" className="gap-3 p-4">
118
+ {analysis.detectedAsScan ? (
119
+ <>
120
+ <View className="flex-row items-center gap-2">
121
+ <CheckIcon className="text-success" />
122
+ <Text testID="barcode-test-headline">{`Detected as a scan → ${analysis.code}`}</Text>
123
+ </View>
124
+ <Text testID="barcode-test-detail" className="text-sm text-muted-foreground">
125
+ {`Average keystroke gap ${avg}ms, under the ${values.threshold}ms threshold`}
126
+ </Text>
127
+ </>
128
+ ) : analysis.nearMiss ? (
129
+ <Notice tone="warning" testID="barcode-test-headline"
130
+ title={`Treated as typing — average gap ${avg}ms is above your ${values.threshold}ms threshold`} />
131
+ ) : !Number.isFinite(analysis.avgGapMs) ? (
132
+ <Text testID="barcode-test-headline">
133
+ Treated as typing — only one key pressed, so there are no gaps to measure
134
+ </Text>
135
+ ) : (
136
+ <Text testID="barcode-test-headline">
137
+ {`Treated as typing (average gap ${avg}ms) — correctly ignored`}
138
+ </Text>
139
+ )}
140
+ {analysis.suggestions.map((s) => (
141
+ <Notice key={s.kind} tone="info" testID={`barcode-test-suggestion-${s.kind}`}
142
+ title={s.kind === 'raise-threshold'
143
+ ? `Raise threshold to ${s.value}ms — your scanner averages ${avg}ms`
144
+ : s.kind === 'lower-min-chars'
145
+ ? `Lower minimum length to ${s.value} — this code is ${s.value} characters`
146
+ : `Strip leading "${s.value}" — set it as your prefix`}
147
+ actions={[{ label: 'Apply', onPress: () => onChange(s.settings), testID: `barcode-test-apply-${s.kind}` }]} />
148
+ ))}
149
+ {analysis.shiftMangled && (
150
+ <Notice tone="warning" testID="barcode-test-shift" title="Scanner is sending Shift as separate keys">
151
+ <Text>Reconfigure it to a US-keyboard / no-modifier mode.</Text>
152
+ </Notice>
153
+ )}
154
+ {analysis.trailingEnter && (
155
+ <Text testID="barcode-test-trailing-enter" className="text-sm text-muted-foreground">
156
+ Trailing Enter detected and ignored — no suffix needed
157
+ </Text>
158
+ )}
159
+ </View>
160
+ )}
161
+ </SettingsGroup>
162
+ )}
163
+ </>);
164
+ }
@@ -58,7 +58,7 @@ export function ConnectorStatus({
58
58
  {lastSync && <Text className="text-xs text-muted-foreground">Last sync: {lastSync}</Text>}
59
59
  {error && <Text className="text-xs text-destructive">{error}</Text>}
60
60
  {!!unsoldCount && (
61
- <Text className={cn('text-xs', unsoldStale ? 'text-muted-foreground' : 'text-warning')}>{formatUnsold(unsoldCount, !!unsoldStale)}</Text>
61
+ <Text className={cn('text-xs', unsoldStale ? 'text-muted-foreground' : 'text-warning-text')}>{formatUnsold(unsoldCount, !!unsoldStale)}</Text>
62
62
  )}
63
63
  </View>
64
64
  );
@@ -7,11 +7,8 @@ import { useRef, type JSX } from 'react';
7
7
  import { View } from 'react-native';
8
8
  import type { PairingError, PairingPhase, TillDisplayEntry, TillDisplayStatus } from '@tallyui/pos';
9
9
  import { cn } from '@tallyui/theme';
10
- import {
11
- AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter,
12
- AlertDialogTitle, AlertDialogTrigger,
13
- } from '../ui/alert-dialog';
14
10
  import { Button } from '../ui/button';
11
+ import { ConfirmDialog } from '../ui/confirm-dialog';
15
12
  import { Loader } from '../ui/loader';
16
13
  import { Text } from '../ui/text';
17
14
  import { SettingsGroup } from './settings-group';
@@ -20,7 +17,7 @@ export interface CustomerDisplaySettingsProps {
20
17
  /** `useTillPairing(pairing)`. */
21
18
  pairing: { phase: PairingPhase; forgetError: PairingError | null };
22
19
  /** `useTillDisplays(service)`. */
23
- displays: { status: TillDisplayStatus; displays: readonly TillDisplayEntry[] };
20
+ displays: { status: TillDisplayStatus; displays: readonly TillDisplayEntry[]; pauseReason?: 'signed_out' | 'forbidden' | 'device_refused' | null };
24
21
  onStartPairing: () => void;
25
22
  onConfirm: (claimId: string) => void;
26
23
  onDecline: (claimId: string) => void;
@@ -36,6 +33,7 @@ const PAIRING_ERRORS: Record<PairingError, string> = {
36
33
  limit: 'Too many pairing attempts. Try again in a few minutes.',
37
34
  expired: 'The code expired. Start again for a new code.',
38
35
  not_found: 'That display is no longer waiting. Ask it to enter the code again.',
36
+ device_refused: 'This till is not recognised by the store. Ask an admin to reset it.',
39
37
  network: "Can't reach the store. Check the connection and try again.",
40
38
  server: "The store couldn't finish that. Try again.",
41
39
  };
@@ -63,25 +61,12 @@ function DisplayRow({ entry, onForget }: { entry: TillDisplayEntry; onForget: (d
63
61
  <Text className="text-sm font-medium text-foreground">{name}</Text>
64
62
  <Text testID={`display-state-${displayId}`} className="text-xs text-muted-foreground">{stateOf(entry)}</Text>
65
63
  </View>
66
- <AlertDialog>
67
- <AlertDialogTrigger asChild>
68
- <Button testID={`forget-${displayId}`} variant="outline" className="min-h-11"><Text>Forget</Text></Button>
69
- </AlertDialogTrigger>
70
- <AlertDialogContent>
71
- <AlertDialogTitle>{`Forget ${name}?`}</AlertDialogTitle>
72
- <AlertDialogDescription>It will need a new code to pair again.</AlertDialogDescription>
73
- <AlertDialogFooter>
74
- <AlertDialogCancel asChild>
75
- <Button testID={`forget-cancel-${displayId}`} variant="outline" className="min-h-11"><Text>Cancel</Text></Button>
76
- </AlertDialogCancel>
77
- <AlertDialogAction asChild>
78
- <Button testID={`forget-confirm-${displayId}`} variant="destructive" className="min-h-11" onPress={() => onForget(displayId)}>
79
- <Text>Forget</Text>
80
- </Button>
81
- </AlertDialogAction>
82
- </AlertDialogFooter>
83
- </AlertDialogContent>
84
- </AlertDialog>
64
+ <ConfirmDialog
65
+ testID={`forget-dialog-${displayId}`} cancelTestID={`forget-cancel-${displayId}`} confirmTestID={`forget-confirm-${displayId}`}
66
+ title={`Forget ${name}?`} description="It will need a new code to pair again." confirmLabel="Forget"
67
+ onConfirm={() => onForget(displayId)}
68
+ trigger={<Button testID={`forget-${displayId}`} variant="outline" className="min-h-11"><Text>Forget</Text></Button>}
69
+ />
85
70
  </View>
86
71
  );
87
72
  }
@@ -96,7 +81,9 @@ export function CustomerDisplaySettings({
96
81
  else if (phase.phase !== 'confirming') lastCode.current = null;
97
82
  const shown = phase.phase === 'code' ? phase : phase.phase === 'confirming' ? lastCode.current : null;
98
83
  const busy = phase.phase === 'confirming';
99
- const statusLine = STATUS_LINES[displays.status];
84
+ // Signing in again cannot fix a till the store does not recognise (#754).
85
+ const statusLine = displays.status === 'paused' && displays.pauseReason === 'device_refused'
86
+ ? PAIRING_ERRORS.device_refused : STATUS_LINES[displays.status];
100
87
 
101
88
  return (
102
89
  <View className={cn('gap-6', className)}>
@@ -4,3 +4,8 @@ export { ConnectorStatus, type ConnectorStatusProps, type ConnectionStatus } fro
4
4
  export { DisplaySettings, type DisplaySettingsProps } from './display-settings';
5
5
  export { TaxCalculationSettings, type TaxCalculationSettingsProps } from './tax-calculation-settings';
6
6
  export { CustomerDisplaySettings, type CustomerDisplaySettingsProps } from './customer-display-settings';
7
+ export { PrintingSettings, type PrintingSettingsProps } from './printing-settings';
8
+ export { PrinterForm, type PrinterFormProps, type PrinterFormDraft } from './printer-form';
9
+ export {
10
+ BarcodeScanningSettings, type BarcodeScanningSettingsProps, type BarcodeScanningValues,
11
+ } from './barcode-scanning-settings';
@@ -0,0 +1,161 @@
1
+ import { useState, type JSX } from 'react';
2
+ import { View } from 'react-native';
3
+ import type { PrinterProfile } from '@tallyui/pos';
4
+ import { cn } from '@tallyui/theme';
5
+ import { Button } from '../ui/button';
6
+ import { Input } from '../ui/input';
7
+ import { Loader } from '../ui/loader';
8
+ import { Switch } from '../ui/switch';
9
+ import { Text } from '../ui/text';
10
+ import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group';
11
+
12
+ /** What Save and Test Print hand over; the app assigns or keeps the id. */
13
+ export type PrinterFormDraft = Omit<PrinterProfile, 'id'>;
14
+
15
+ export interface PrinterFormProps {
16
+ /** Given, edits this printer; absent, adds a new one. */
17
+ printer?: PrinterProfile;
18
+ /** Returns an inline refusal, or null once saved. A promise disables Save while pending. */
19
+ onSave: (draft: PrinterFormDraft) => string | null | Promise<string | null>;
20
+ onCancel: () => void;
21
+ /** Given, a Test Print button passes the current draft. */
22
+ onTest?: (draft: PrinterFormDraft) => void;
23
+ className?: string;
24
+ }
25
+
26
+ export function PrinterForm({ printer, onSave, onCancel, onTest, className }: PrinterFormProps): JSX.Element {
27
+ const [name, setName] = useState(printer?.name ?? '');
28
+ const [connectionType, setConnectionType] = useState<PrinterProfile['connectionType']>(printer?.connectionType ?? 'network');
29
+ const [vendor, setVendor] = useState(printer?.vendor ?? 'generic');
30
+ const [address, setAddress] = useState(printer?.address ?? '');
31
+ const [port, setPort] = useState(String(printer?.port ?? 9100));
32
+ const [language, setLanguage] = useState(printer?.language ?? 'esc-pos');
33
+ const [columns, setColumns] = useState(String(printer?.columns ?? 42));
34
+ const [autoCut, setAutoCut] = useState(printer?.autoCut ?? true);
35
+ const [autoOpenDrawer, setAutoOpenDrawer] = useState(printer?.autoOpenDrawer ?? false);
36
+ const [drawerConnector, setDrawerConnector] = useState(printer?.drawerConnector ?? 'pin2');
37
+ const [isDefault, setIsDefault] = useState(printer?.isDefault ?? false);
38
+ const [error, setError] = useState<string | null>(null);
39
+ const [saving, setSaving] = useState(false);
40
+
41
+ const draft = (): PrinterFormDraft | null => {
42
+ const failure = !name.trim() ? 'Name is required'
43
+ : connectionType === 'network' && !address.trim() ? 'Address is required'
44
+ : connectionType === 'network' && (!Number.isInteger(Number(port)) || Number(port) < 1 || Number(port) > 65535)
45
+ ? 'Port must be 1 to 65535'
46
+ : !Number.isInteger(Number(columns)) || Number(columns) < 1 ? 'Characters per line must be 1 or more' : null;
47
+ setError(failure);
48
+ if (failure) return null;
49
+ return {
50
+ name: name.trim(), connectionType, vendor, language, columns: Number(columns),
51
+ autoCut, autoOpenDrawer, drawerConnector, isDefault,
52
+ ...(connectionType !== 'system' ? { address: address.trim() } : {}),
53
+ ...(connectionType === 'network' ? { port: Number(port) } : {}),
54
+ ...(printer?.codePage !== undefined ? { codePage: printer.codePage } : {}),
55
+ ...(printer?.isBuiltIn !== undefined ? { isBuiltIn: printer.isBuiltIn } : {}),
56
+ };
57
+ };
58
+ const save = async () => {
59
+ const value = draft();
60
+ if (!value) return;
61
+ const result = onSave(value);
62
+ if (result instanceof Promise) {
63
+ setSaving(true);
64
+ try { setError(await result); }
65
+ finally { setSaving(false); }
66
+ } else setError(result);
67
+ };
68
+
69
+ return (
70
+ <View testID="printer-form" className={cn('gap-3', className)}>
71
+ <View className="gap-1">
72
+ <Text>Name</Text>
73
+ <Input><Input.Field testID="printer-form-name" accessibilityLabel="Name" value={name} onChangeText={setName} /></Input>
74
+ </View>
75
+ <View className="gap-1">
76
+ <Text>Connection</Text>
77
+ <ToggleGroup type="single" variant="outline" value={connectionType} aria-label="Connection" className="justify-start"
78
+ onValueChange={(value) => { if (value) setConnectionType(value as PrinterProfile['connectionType']); }}>
79
+ <ToggleGroupItem value="network" testID="printer-form-connection-network"><Text>Network</Text></ToggleGroupItem>
80
+ <ToggleGroupItem value="system" testID="printer-form-connection-system"><Text>Print Dialog</Text></ToggleGroupItem>
81
+ {(printer?.connectionType === 'bluetooth' || printer?.connectionType === 'usb') && (
82
+ <ToggleGroupItem value={printer.connectionType} testID={`printer-form-connection-${printer.connectionType}`}>
83
+ <Text>{printer.connectionType === 'bluetooth' ? 'Bluetooth' : 'USB'}</Text>
84
+ </ToggleGroupItem>
85
+ )}
86
+ </ToggleGroup>
87
+ </View>
88
+ <View className="gap-1">
89
+ <Text>Vendor</Text>
90
+ <ToggleGroup type="single" variant="outline" value={vendor} aria-label="Vendor" className="justify-start"
91
+ onValueChange={(value) => { if (value) setVendor(value as typeof vendor); }}>
92
+ {([['epson', 'Epson'], ['star', 'Star'], ['generic', 'Generic']] as const).map(([value, label]) => (
93
+ <ToggleGroupItem key={value} value={value} testID={`printer-form-vendor-${value}`}><Text>{label}</Text></ToggleGroupItem>
94
+ ))}
95
+ </ToggleGroup>
96
+ </View>
97
+ {connectionType !== 'system' && (
98
+ <View className="gap-1">
99
+ <Text>Address</Text>
100
+ <Input><Input.Field testID="printer-form-address" accessibilityLabel="Address" value={address} onChangeText={setAddress} /></Input>
101
+ </View>
102
+ )}
103
+ {connectionType === 'network' && (
104
+ <View className="gap-1">
105
+ <Text>Port</Text>
106
+ <Input><Input.Field testID="printer-form-port" accessibilityLabel="Port" keyboardType="number-pad"
107
+ value={port} onChangeText={(text) => setPort(text.replace(/\D/g, ''))} /></Input>
108
+ </View>
109
+ )}
110
+ <View className="gap-1">
111
+ <Text>Printer Language</Text>
112
+ <ToggleGroup type="single" variant="outline" value={language} aria-label="Printer Language" className="justify-start"
113
+ onValueChange={(value) => { if (value) setLanguage(value as typeof language); }}>
114
+ {([['esc-pos', 'ESC/POS'], ['star-prnt', 'StarPRNT'], ['star-line', 'Star Line']] as const).map(([value, label]) => (
115
+ <ToggleGroupItem key={value} value={value} testID={`printer-form-language-${value}`}><Text>{label}</Text></ToggleGroupItem>
116
+ ))}
117
+ </ToggleGroup>
118
+ </View>
119
+ <View className="gap-1">
120
+ <Text>Characters per Line</Text>
121
+ <Input><Input.Field testID="printer-form-columns" accessibilityLabel="Characters per Line" keyboardType="number-pad"
122
+ value={columns} onChangeText={(text) => setColumns(text.replace(/\D/g, ''))} /></Input>
123
+ </View>
124
+ <View className="flex-row items-center justify-between">
125
+ <Text>Auto Cut</Text>
126
+ <Switch testID="printer-form-auto-cut" accessibilityLabel="Auto Cut" checked={autoCut} onCheckedChange={setAutoCut} />
127
+ </View>
128
+ <View className="flex-row items-center justify-between">
129
+ <Text>Open Cash Drawer</Text>
130
+ <Switch testID="printer-form-open-drawer" accessibilityLabel="Open Cash Drawer" checked={autoOpenDrawer} onCheckedChange={setAutoOpenDrawer} />
131
+ </View>
132
+ {autoOpenDrawer && (
133
+ <View className="gap-1">
134
+ <Text>Drawer Connector</Text>
135
+ <ToggleGroup type="single" variant="outline" value={drawerConnector} aria-label="Drawer Connector" className="justify-start"
136
+ onValueChange={(value) => { if (value) setDrawerConnector(value as typeof drawerConnector); }}>
137
+ <ToggleGroupItem value="pin2" testID="printer-form-drawer-pin2"><Text>Pin 2</Text></ToggleGroupItem>
138
+ <ToggleGroupItem value="pin5" testID="printer-form-drawer-pin5"><Text>Pin 5</Text></ToggleGroupItem>
139
+ </ToggleGroup>
140
+ </View>
141
+ )}
142
+ <View className="flex-row items-center justify-between">
143
+ <Text>Set as Default</Text>
144
+ <Switch testID="printer-form-default" accessibilityLabel="Set as Default" checked={isDefault} onCheckedChange={setIsDefault} />
145
+ </View>
146
+ {error !== null && <Text role="alert" testID="printer-form-error" className="text-destructive">{error}</Text>}
147
+ <View className="flex-row justify-end gap-2">
148
+ <Button variant="outline" testID="printer-form-cancel" onPress={onCancel}><Text>Cancel</Text></Button>
149
+ {onTest && (
150
+ <Button variant="outline" testID="printer-form-test" onPress={() => { const value = draft(); if (value) onTest(value); }}>
151
+ <Text>Test Print</Text>
152
+ </Button>
153
+ )}
154
+ <Button testID="printer-form-save" onPress={save} disabled={saving} aria-busy={saving}>
155
+ {saving && <Loader size="sm" />}
156
+ <Text>Save</Text>
157
+ </Button>
158
+ </View>
159
+ </View>
160
+ );
161
+ }