@tallyui/components 3.14.0 → 3.15.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/components",
3
- "version": "3.14.0",
3
+ "version": "3.15.0",
4
4
  "type": "module",
5
5
  "description": "Universal POS UI components for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -28,22 +28,22 @@
28
28
  "directory": "packages/components"
29
29
  },
30
30
  "peerDependencies": {
31
- "@tallyui/core": "^3.14.0",
32
- "@tallyui/primitives": "^3.14.0",
33
- "@tallyui/theme": "^3.14.0",
31
+ "@tallyui/core": "^3.15.0",
32
+ "@tallyui/primitives": "^3.15.0",
33
+ "@tallyui/theme": "^3.15.0",
34
34
  "react": ">=18",
35
35
  "react-native": ">=0.74",
36
36
  "react-native-svg": ">=15"
37
37
  },
38
38
  "dependencies": {
39
39
  "class-variance-authority": "^0.7.1",
40
- "@tallyui/pos": "3.14.0"
40
+ "@tallyui/pos": "3.15.0"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/connector-medusa": "3.14.0",
44
- "@tallyui/connector-vendure": "3.14.0",
45
- "@tallyui/connector-woocommerce": "3.14.0",
46
- "@tallyui/mock-api": "3.14.0",
43
+ "@tallyui/connector-medusa": "3.15.0",
44
+ "@tallyui/connector-vendure": "3.15.0",
45
+ "@tallyui/connector-woocommerce": "3.15.0",
46
+ "@tallyui/mock-api": "3.15.0",
47
47
  "@types/react": ">=18",
48
48
  "react": "^19.2.4",
49
49
  "react-native-svg": "15.12.1",
@@ -0,0 +1,82 @@
1
+ // Port of WCPOS v2 `packages/core/src/screens/main/pos/cart/foot.tsx` and `cart/buttons/pay.tsx`
2
+ // (the ⋮ beside a full-width "Checkout {order_total}"), MIT, WCPOS.
3
+ import * as React from 'react';
4
+ import { Platform, Pressable, Text, View } from 'react-native';
5
+ import { formatMoney, type Money } from '@tallyui/core';
6
+ import { cn } from '@tallyui/theme';
7
+
8
+ export interface CartFootAction {
9
+ label: string;
10
+ onPress: () => void;
11
+ /** Shown in the destructive colour, e.g. a Void. */
12
+ destructive?: boolean;
13
+ }
14
+
15
+ export interface CartFootProps {
16
+ total: Money;
17
+ onCheckout: () => void;
18
+ /** The ⋮ menu's items; the ⋮ is left out when there are none. */
19
+ actions?: readonly CartFootAction[];
20
+ /** Disables Checkout only; the menu stays usable. */
21
+ disabled?: boolean;
22
+ locale?: string;
23
+ className?: string;
24
+ }
25
+
26
+ const MENU_LABEL = 'More actions';
27
+
28
+ /**
29
+ * The cart's foot: a ⋮ menu of the host's actions beside one "Checkout {total}" button, as in WCPOS v2.
30
+ * v2's ⋮ opens its Order details sheet; here the host passes the items, so it can pass one that opens its own sheet.
31
+ *
32
+ * ```tsx
33
+ * <CartFoot total={total} onCheckout={startCheckout} actions={[{ label: 'Void', onPress: voidSale, destructive: true }]} />
34
+ * ```
35
+ */
36
+ export function CartFoot({ total, onCheckout, actions = [], disabled = false, locale, className }: CartFootProps) {
37
+ const [open, setOpen] = React.useState(false);
38
+ const trigger = React.useRef<View>(null);
39
+ const menu = React.useRef<View>(null);
40
+
41
+ // Web keyboard: focus moves to the first item on open; Escape closes and hands focus back to the ⋮.
42
+ React.useEffect(() => {
43
+ if (!open || Platform.OS !== 'web' || typeof document === 'undefined') return;
44
+ (menu.current as unknown as HTMLElement | null)?.querySelector<HTMLElement>('[role="menuitem"]')?.focus();
45
+ const onKeyDown = (event: KeyboardEvent) => {
46
+ if (event.key !== 'Escape') return;
47
+ setOpen(false);
48
+ (trigger.current as unknown as HTMLElement | null)?.focus?.();
49
+ };
50
+ document.addEventListener('keydown', onKeyDown);
51
+ return () => document.removeEventListener('keydown', onKeyDown);
52
+ }, [open]);
53
+
54
+ return (
55
+ <View className={cn('gap-2', className)}>
56
+ {open && actions.length > 0 ? (
57
+ <View ref={menu} role="menu" aria-label={MENU_LABEL} testID="cart-foot-menu"
58
+ className="rounded-md border border-border bg-card p-1">
59
+ {actions.map((action, index) => (
60
+ <Pressable key={index} role="menuitem" className="min-h-11 justify-center rounded-sm px-3 py-2"
61
+ onPress={() => { setOpen(false); action.onPress(); }}>
62
+ <Text className={action.destructive ? 'text-destructive' : 'text-foreground'}>{action.label}</Text>
63
+ </Pressable>
64
+ ))}
65
+ </View>
66
+ ) : null}
67
+ <View className="flex-row gap-3">
68
+ {actions.length > 0 ? (
69
+ <Pressable ref={trigger} accessibilityRole="button" accessibilityLabel={MENU_LABEL} aria-haspopup="menu"
70
+ aria-expanded={open} testID="cart-foot-more" onPress={() => setOpen((value) => !value)}
71
+ className="min-h-12 min-w-12 items-center justify-center rounded-md border border-border bg-card">
72
+ <Text className="text-lg text-foreground">⋮</Text>
73
+ </Pressable>
74
+ ) : null}
75
+ <Pressable accessibilityRole="button" testID="cart-checkout" disabled={disabled} onPress={onCheckout}
76
+ className={cn('min-h-12 flex-1 justify-center rounded-md bg-primary px-4 py-3', disabled && 'opacity-50')}>
77
+ <Text className="text-center font-semibold text-primary-foreground">{`Checkout ${formatMoney(total, locale) ?? '—'}`}</Text>
78
+ </Pressable>
79
+ </View>
80
+ </View>
81
+ );
82
+ }
@@ -1,3 +1,4 @@
1
+ import type { ReactNode } from 'react';
1
2
  import { View } from 'react-native';
2
3
  import { formatMoney, type Money } from '@tallyui/core';
3
4
  import { cn } from '@tallyui/theme';
@@ -15,6 +16,10 @@ export interface CartLineProps extends Omit<HStackProps, 'children'> {
15
16
  lineTotal: Money;
16
17
  /** Show the Price column (default true); the Cart passes false on a narrow cart or a phone, as CartColumnHeads does. */
17
18
  showPrice?: boolean;
19
+ /** Replaces the quantity's text, e.g. a LinePopover that edits it (Cart's `lineEditor="popover"`). */
20
+ quantitySlot?: ReactNode;
21
+ /** Replaces the unit price's text (the struck regular price stays above it). */
22
+ priceSlot?: ReactNode;
18
23
  locale?: string;
19
24
  className?: string;
20
25
  }
@@ -29,14 +34,14 @@ export interface CartLineProps extends Omit<HStackProps, 'children'> {
29
34
  * <CartLine name="Coffee" quantity={2} unitPrice={unitPrice} lineTotal={lineTotal} />
30
35
  * ```
31
36
  */
32
- export function CartLine({ name, attributes, quantity, unitPrice, regularUnitPrice, lineTotal, showPrice = true, locale, className, ...props }: CartLineProps) {
37
+ export function CartLine({ name, attributes, quantity, unitPrice, regularUnitPrice, lineTotal, showPrice = true, quantitySlot, priceSlot, locale, className, ...props }: CartLineProps) {
33
38
  const options = Object.entries(attributes ?? {}).map(([key, value]) => `${key}: ${value}`).join(' · ');
34
39
  const regular = regularUnitPrice && regularUnitPrice.currency === unitPrice.currency && regularUnitPrice.amount > unitPrice.amount
35
40
  ? formatMoney(regularUnitPrice, locale) ?? '—' : null;
36
41
  return (
37
42
  <HStack space="none" className={cn('py-2.5', className)} {...props}>
38
43
  <View className={CART_COLUMNS.quantity.cell}>
39
- <Text className="text-sm tabular-nums">{quantity}</Text>
44
+ {quantitySlot ?? <Text className="text-sm tabular-nums">{quantity}</Text>}
40
45
  </View>
41
46
  <View className={CART_COLUMNS.name.cell}>
42
47
  <Text className="text-sm font-medium" numberOfLines={2}>{name}</Text>
@@ -45,7 +50,7 @@ export function CartLine({ name, attributes, quantity, unitPrice, regularUnitPri
45
50
  {showPrice ? <View className={CART_COLUMNS.price.cell}>
46
51
  {regular ? <Text accessibilityLabel={`Regular price ${regular}`} style={{ textDecorationLine: 'line-through' }}
47
52
  className="text-right text-sm tabular-nums text-muted-foreground line-through">{regular}</Text> : null}
48
- <Text className="text-right text-sm tabular-nums text-muted-foreground">{formatMoney(unitPrice, locale) ?? '—'}</Text>
53
+ {priceSlot ?? <Text className="text-right text-sm tabular-nums text-muted-foreground">{formatMoney(unitPrice, locale) ?? '—'}</Text>}
49
54
  </View> : null}
50
55
  <View className={CART_COLUMNS.total.cell}>
51
56
  <Text className="text-right text-sm font-semibold tabular-nums">{formatMoney(lineTotal, locale) ?? '—'}</Text>
package/src/cart/index.ts CHANGED
@@ -5,3 +5,4 @@ export { CartPanel, type CartPanelProps } from './cart-panel';
5
5
  export { DiscountBadge, type DiscountBadgeProps } from './discount-badge';
6
6
  export { CartNoteInput, type CartNoteInputProps } from './cart-note-input';
7
7
  export { CartLineActions, type CartLineActionsProps, type CartAction } from './cart-line-actions';
8
+ export { CartFoot, type CartFootProps, type CartFootAction } from './cart-foot';
package/src/index.ts CHANGED
@@ -63,6 +63,9 @@ export {
63
63
  type CartAction,
64
64
  CartColumnHeads,
65
65
  type CartColumnHeadsProps,
66
+ CartFoot,
67
+ type CartFootProps,
68
+ type CartFootAction,
66
69
  } from './cart';
67
70
 
68
71
  // Input components
@@ -76,6 +79,10 @@ export {
76
79
  type ChipItem,
77
80
  QuantityStepper,
78
81
  type QuantityStepperProps,
82
+ Keypad,
83
+ DIGIT_ROWS,
84
+ type KeypadKey,
85
+ type KeypadProps,
79
86
  } from './input';
80
87
 
81
88
  // Customer components
@@ -185,7 +192,7 @@ export {
185
192
  // Sale components
186
193
  export {
187
194
  Cart, CartBar, Tender, SplitTender, TenderPane, type TenderPaneProps, DiscountForm, DiscountChips, parseDiscount, discountLabel,
188
- PriceForm, parsePrice,
195
+ PriceForm, parsePrice, LinePopover, type LinePopoverProps,
189
196
  ChargeForm, type ChargeFormProps,
190
197
  Catalogue, formatStockSyncTime, Receipt, injectPrintStyle, SyncStatus, OrdersList, type OrderHistoryRow, orderReference,
191
198
  ParkedSales, type ParkedSalesProps, OpenSaleTabs, type OpenSaleTabsProps, CustomerDisplayScreen,
@@ -1,3 +1,4 @@
1
1
  export { SearchInput, type SearchInputProps } from './search-input';
2
2
  export { FilterChip, FilterChipGroup, type FilterChipProps, type FilterChipGroupProps, type ChipItem } from './filter-chip';
3
3
  export { QuantityStepper, type QuantityStepperProps } from './quantity-stepper';
4
+ export { Keypad, DIGIT_ROWS, type KeypadKey, type KeypadProps } from './keypad';
@@ -0,0 +1,38 @@
1
+ // Port of WCPOS v2 `packages/components/src/keypad/index.tsx` (monorepo main), MIT, WCPOS.
2
+ import { Pressable, Text, View } from 'react-native';
3
+ import { cn } from '@tallyui/theme';
4
+
5
+ export interface KeypadKey {
6
+ /** What a press reports: a digit, `decimal`, `backspace`, or the caller's own key. */
7
+ name: string;
8
+ /** The accessible name: the digit, or the caller's own ("Delete last digit"). */
9
+ label: string;
10
+ /** The key's text when it is not its label (`⌫`, named "Delete last digit"). */
11
+ text?: string;
12
+ /** The cells the key takes in its row (default 1). */
13
+ span?: number;
14
+ }
15
+
16
+ export interface KeypadProps {
17
+ rows: readonly (readonly KeypadKey[])[];
18
+ onPress: (name: string) => void;
19
+ /** A key is `<testID>-key-<name>`. */
20
+ testID?: string;
21
+ className?: string;
22
+ }
23
+
24
+ /** v2's DIGIT_ROWS: 123 / 456 / 789; the caller adds its own last row. */
25
+ export const DIGIT_ROWS: KeypadKey[][] = ['123', '456', '789'].map((row) => [...row].map((digit) => ({ name: digit, label: digit })));
26
+
27
+ /** Rows of keys with no display or value, as v2's Keypad: the caller owns the entry. */
28
+ export function Keypad({ rows, onPress, testID, className }: KeypadProps) {
29
+ return <View testID={testID} className={cn('gap-2', className)}>
30
+ {rows.map((row, index) => <View key={index} className="flex-row gap-2">
31
+ {row.map(({ name, label, text, span }) => <Pressable key={name} testID={testID && `${testID}-key-${name}`} accessibilityRole="button"
32
+ accessibilityLabel={label} onPress={() => onPress(name)} style={{ flex: span ?? 1 }}
33
+ className="min-h-11 items-center justify-center rounded-md border border-border bg-card px-4 py-2">
34
+ <Text className="text-xl font-semibold text-foreground">{text ?? label}</Text>
35
+ </Pressable>)}
36
+ </View>)}
37
+ </View>;
38
+ }
package/src/sale/cart.tsx CHANGED
@@ -3,14 +3,15 @@ import { Pressable, Text, View, useWindowDimensions } from 'react-native';
3
3
  import { formatMoney } from '@tallyui/core';
4
4
  import { buildReceiptData } from '@tallyui/pos';
5
5
  import type { useSale } from '@tallyui/pos';
6
- import { CartColumnHeads, CartLine, CartLineActions, CartPanel, CartTotal } from '../cart';
6
+ import { CartColumnHeads, CartFoot, CartLine, CartLineActions, CartPanel, CartTotal, type CartFootAction } from '../cart';
7
7
  import { cartShowsPrice } from '../cart/cart-columns';
8
8
  import { DiscountChips, DiscountForm } from './discount-form';
9
9
  import { PriceForm } from './price-form';
10
10
  import { ChargeForm } from './charge-form';
11
+ import { LinePopover } from './line-popover';
11
12
 
12
13
  /** `taxLabel` names each tax row; VAT isn't universal, so a platform passes its own (medusapos passes `VAT ${rate}%`). */
13
- export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, couponDiscountMinor, orderActions = true }:
14
+ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10000}%`, canEditPrice = false, onPriceChange, quickDiscounts, taxClasses, afterSubtotal, couponDiscountMinor, orderActions = true, checkout, lineEditor = 'inline' }:
14
15
  { sale: ReturnType<typeof useSale>; taxLabel?: (ratePpm: number) => string;
15
16
  taxClasses?: ReadonlyArray<{ id: string; label: string }>;
16
17
  /** Shows a Price action on each line. Pass the till's own permission; the control isn't shown without it. */
@@ -28,6 +29,12 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
28
29
  /** Cart's own Order discount and Add charge controls; pass `false` when the app hosts them in its own menu (v2's
29
30
  * cart "+" menu). Applied discounts and charges still show and can be removed. */
30
31
  orderActions?: boolean;
32
+ /** Swaps the Cash and Card terminal row for v2's foot, `CartFoot`: "Checkout {total}" calls `onCheckout`, and the
33
+ * ⋮ menu lists `actions`. Absent: the Cash and Card terminal row. */
34
+ checkout?: { onCheckout: () => void; actions?: readonly CartFootAction[] };
35
+ /** `popover`: tapping a line's quantity or price opens v2's keypad (WCPOS cart cells/quantity-keypad.tsx and
36
+ * cells/price.tsx), the price one with the quick-discount keys. Default `inline`: the − / + buttons and Price form. */
37
+ lineEditor?: 'inline' | 'popover';
31
38
  }) {
32
39
  const { order } = sale;
33
40
  const money = (amount: number) => ({ amount, currency: order.currency });
@@ -52,14 +59,27 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
52
59
  const [cartWidth, setCartWidth] = useState<number>();
53
60
  const { width: windowWidth, height: windowHeight } = useWindowDimensions();
54
61
  const showPrice = cartShowsPrice({ cartWidth, windowWidth, windowHeight });
62
+ // The price popover needs the Price column; on a narrow cart the Price action and form stay.
63
+ const pricePopover = lineEditor === 'popover' && canEditPrice && showPrice;
64
+ // A line's price write, from the Price form or the price popover; the reason is passed only to onPriceChange.
65
+ const applyPrice = (line: typeof order.lineItems[number], amount: number, reason?: string) => {
66
+ const fromMinor = line.unitPriceMinor;
67
+ const refused = sale.setUnitPrice(line.id, amount);
68
+ if (refused === null) onPriceChange?.({ lineId: line.id, fromMinor, toMinor: amount, reason });
69
+ return refused;
70
+ };
55
71
  const renderItem = (line: typeof order.lineItems[number]) => <>
56
72
  <CartLine name={line.name} attributes={line.attributes} quantity={line.quantity} unitPrice={money(line.unitPriceMinor)}
57
73
  regularUnitPrice={line.regularUnitPriceMinor === undefined ? undefined : money(line.regularUnitPriceMinor)}
58
- lineTotal={money(display(line.id).amountMinor)} showPrice={showPrice} />
74
+ lineTotal={money(display(line.id).amountMinor)} showPrice={showPrice}
75
+ quantitySlot={lineEditor === 'popover' ? <LinePopover kind="quantity" lineName={line.name} currency={order.currency}
76
+ value={line.quantity} onApply={(quantity) => { sale.setQuantity(line.id, quantity); return null; }} /> : undefined}
77
+ priceSlot={pricePopover ? <LinePopover kind="price" lineName={line.name} currency={order.currency} value={line.unitPriceMinor}
78
+ quickDiscounts={quickDiscounts} textClassName="text-right text-muted-foreground" onApply={(amount) => applyPrice(line, amount)} /> : undefined} />
59
79
  <DiscountChips discounts={line.discounts} amounts={display(line.id).discounts} currency={order.currency} onRemove={sale.removeDiscount} />
60
80
  <CartLineActions actions={[
61
81
  { id: 'discount', label: 'Discount', color: 'text-primary', onPress: () => setForm({ type: 'discount', lineId: line.id }) },
62
- ...(canEditPrice ? [{ id: 'price', label: 'Price', color: 'text-primary', onPress: () => setForm({ type: 'price', lineId: line.id }) }] : []),
82
+ ...(canEditPrice && !pricePopover ? [{ id: 'price', label: 'Price', color: 'text-primary', onPress: () => setForm({ type: 'price', lineId: line.id }) }] : []),
63
83
  ]}>
64
84
  <View className="flex-row gap-4 px-3 py-2">
65
85
  <Pressable accessibilityRole="button" accessibilityLabel={`Decrease ${line.name}`}
@@ -71,14 +91,9 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
71
91
  </View>
72
92
  </CartLineActions>
73
93
  {discountForm(line.id, `Discount on ${line.name}`)}
74
- {canEditPrice && form?.type === 'price' && form.lineId === line.id ? <PriceForm key={line.id} lineName={line.name}
94
+ {canEditPrice && !pricePopover && form?.type === 'price' && form.lineId === line.id ? <PriceForm key={line.id} lineName={line.name}
75
95
  currency={order.currency} currentMinor={line.unitPriceMinor} quickDiscounts={quickDiscounts} onClose={() => setForm(null)}
76
- onApply={(amount, reason) => {
77
- const fromMinor = line.unitPriceMinor;
78
- const refused = sale.setUnitPrice(line.id, amount);
79
- if (refused === null) onPriceChange?.({ lineId: line.id, fromMinor, toMinor: amount, reason });
80
- return refused;
81
- }} /> : null}
96
+ onApply={(amount, reason) => applyPrice(line, amount, reason)} /> : null}
82
97
  </>;
83
98
  return <View dataSet={{ print: 'hide' }} className="flex-1 min-h-0" onLayout={(event) => setCartWidth(event.nativeEvent.layout.width)}>
84
99
  <CartColumnHeads showPrice={showPrice} />
@@ -119,14 +134,15 @@ export function Cart({ sale, taxLabel = (ratePpm: number) => `Tax ${ratePpm / 10
119
134
  discount={money(couponDiscountMinor === undefined ? totals.discountMinor : Math.max(0, totals.discountMinor - couponDiscountMinor))}
120
135
  taxLines={taxRows} taxInclusive={totals.taxInclusive} afterSubtotal={afterSubtotal} />
121
136
  {sale.error ? <Text accessibilityRole="alert" className="text-destructive">{sale.error}</Text> : null}
122
- <View className="flex-row gap-3">
137
+ {checkout ? <CartFoot total={money(totals.totalMinor)} onCheckout={checkout.onCheckout} actions={checkout.actions}
138
+ disabled={!order.lineItems.length} /> : <View className="flex-row gap-3">
123
139
  <Pressable accessibilityRole="button" disabled={!order.lineItems.length} onPress={() => sale.startTender('cash')} className={pay}>
124
140
  <Text className="text-center font-semibold text-primary-foreground">Cash</Text>
125
141
  </Pressable>
126
142
  <Pressable accessibilityRole="button" disabled={!order.lineItems.length} onPress={() => sale.startTender('external')} className={pay}>
127
143
  <Text className="text-center font-semibold text-primary-foreground">Card terminal</Text>
128
144
  </Pressable>
129
- </View>
145
+ </View>}
130
146
  </View>} />
131
147
  </View>;
132
148
  }
package/src/sale/index.ts CHANGED
@@ -4,6 +4,7 @@ export { Tender, SplitTender } from './tender';
4
4
  export { TenderPane, type TenderPaneProps } from './tender-pane';
5
5
  export { DiscountForm, DiscountChips, parseDiscount, discountLabel } from './discount-form';
6
6
  export { PriceForm, parsePrice } from './price-form';
7
+ export { LinePopover, type LinePopoverProps } from './line-popover';
7
8
  export { ChargeForm, type ChargeFormProps } from './charge-form';
8
9
  export { Catalogue, formatStockSyncTime } from './catalogue';
9
10
  export { Receipt } from './receipt';
@@ -0,0 +1,145 @@
1
+ // Port of WCPOS v2 (monorepo main) packages/components/src/quantity-keypad/ and price-keypad/ (index.tsx and
2
+ // reducer.ts), lib/decimal-entry.ts and keypad/index.tsx's decimalRow, as the cart cells open them
3
+ // (packages/core/src/screens/main/pos/cart/cells/quantity-keypad.tsx and cells/price.tsx); MIT, WCPOS.
4
+ import { useEffect, useId, useRef, useState, type ReactNode, type RefObject } from 'react';
5
+ import { Platform, Pressable, StyleSheet, Text, View } from 'react-native';
6
+ import { formatMoney, minorUnitDigits } from '@tallyui/core';
7
+ import { Popover } from '@tallyui/primitives';
8
+ import { cn } from '@tallyui/theme';
9
+ import { DIGIT_ROWS, Keypad, type KeypadKey } from '../input/keypad';
10
+ import { lessPercent, parsePrice, QuickDiscountKeys, quickKeys } from './price-form';
11
+
12
+ /** nav-drawer.tsx's focus targets. */
13
+ const FOCUSABLE = 'button, [href], input, [tabindex]:not([tabindex="-1"])';
14
+ const BACKSPACE: KeypadKey = { name: 'backspace', label: 'Delete last digit', text: '⌫' };
15
+ const button = 'min-h-11 flex-1 items-center justify-center rounded-md border border-border px-3 py-2';
16
+
17
+ /** v2's typeDecimal: `.` once and only with places, a digit past the places refused, a lone 0 replaced. */
18
+ function typeDecimal(buffer: string, key: string, places: number): string {
19
+ if (key === 'backspace') return buffer.slice(0, -1);
20
+ if (key === 'decimal') return places > 0 && !buffer.includes('.') ? `${buffer || '0'}.` : buffer;
21
+ if (!/^[0-9]$/.test(key)) return buffer;
22
+ const point = buffer.indexOf('.');
23
+ if (point >= 0) return buffer.length - point > places ? buffer : buffer + key;
24
+ return buffer === '0' ? key : buffer + key;
25
+ }
26
+
27
+ export interface LinePopoverProps {
28
+ /** `quantity` takes whole numbers only, with no decimal key (decimal quantities need an ADR first, TallyUI#486). */
29
+ kind: 'quantity' | 'price';
30
+ lineName: string;
31
+ /** The order's currency: the price's format and its decimal places. */
32
+ currency: string;
33
+ /** The stored quantity, or the unit price in integer minor units. */
34
+ value: number;
35
+ /** Writes the new value; returns a refusal to show, or null once applied. */
36
+ onApply: (value: number) => string | null;
37
+ /** Price only: v2's quick-discount keys, the first three valid percentages (as PriceForm's). */
38
+ quickDiscounts?: readonly number[];
39
+ /** The trigger's text classes (the cell's alignment and tone). */
40
+ textClassName?: string;
41
+ }
42
+
43
+ /**
44
+ * A cart line's quantity or price that opens v2's keypad: the cashier types (or picks a quick discount),
45
+ * Apply writes through `onApply`, and Cancel, Escape or a press outside close without writing.
46
+ */
47
+ export function LinePopover({ kind, lineName, currency, value, onApply, quickDiscounts, textClassName }: LinePopoverProps) {
48
+ const [open, setOpen] = useState(false);
49
+ // v2's entry: the typed buffer (`.` as its separator), or the lit quick key, a percentage off `value`.
50
+ const [entry, setEntry] = useState<{ buffer: string; percent?: number }>({ buffer: '' });
51
+ const [error, setError] = useState<string | null>(null);
52
+ const titleId = useId();
53
+ const price = kind === 'price';
54
+ const places = price ? minorUnitDigits(currency) : 0;
55
+ const format = (amount: number) => price ? formatMoney({ amount, currency }) ?? '—' : String(amount);
56
+ const keys = price ? quickKeys(quickDiscounts) : [];
57
+ const { buffer, percent } = entry;
58
+ // A lone `0.` is not typing, so a stray tap never zeroes the line (v2's draftPrice); a typed 0 quantity writes nothing.
59
+ const typed = buffer === '0.' ? '' : buffer.replace(/\.$/, '');
60
+ const draft = !price ? (Number.parseInt(typed, 10) > 0 ? Number.parseInt(typed, 10) : undefined)
61
+ : percent !== undefined ? lessPercent(value, percent) : typed ? parsePrice(typed, currency) : undefined;
62
+ const title = `${price ? 'Price' : 'Quantity'} for ${lineName}`;
63
+ const rows = [...DIGIT_ROWS, places
64
+ ? [{ name: 'decimal', label: 'Decimal point', text: '.' }, { name: '0', label: '0' }, BACKSPACE]
65
+ : [{ name: '0', label: '0', span: 2 }, BACKSPACE]];
66
+
67
+ const openChange = (next: boolean) => {
68
+ if (next) { setEntry({ buffer: '' }); setError(null); }
69
+ setOpen(next);
70
+ };
71
+ const press = (name: string) => {
72
+ setEntry((now) => ({ buffer: typeDecimal(now.percent === undefined ? now.buffer : '', name, places) }));
73
+ setError(null);
74
+ };
75
+ const quick = (key: number) => {
76
+ setEntry((now) => (now.percent === key ? { buffer: '' } : { buffer: '', percent: key }));
77
+ setError(null);
78
+ };
79
+ function apply() {
80
+ if (draft === undefined || draft === value) return setOpen(false);
81
+ const refused = typeof draft === 'string' ? draft : onApply(draft);
82
+ setError(refused);
83
+ if (refused === null) setOpen(false);
84
+ }
85
+ const onKey = (key: string) => {
86
+ if (key === 'Escape') setOpen(false);
87
+ else if (/^[0-9]$/.test(key)) press(key);
88
+ else if (key === 'Backspace') press('backspace');
89
+ else if ((key === '.' || key === ',') && places) press('decimal');
90
+ };
91
+
92
+ return <Popover.Root open={open} onOpenChange={openChange}>
93
+ <Popover.Trigger testID={`${kind}-popover-trigger`} accessibilityLabel={`Edit ${kind} of ${lineName}`}
94
+ className="min-h-11 justify-center rounded-md px-1">
95
+ <Text className={cn('text-sm tabular-nums text-foreground', textClassName)}>{format(value)}</Text>
96
+ </Popover.Trigger>
97
+ <Popover.Portal>
98
+ <Popover.Overlay style={StyleSheet.absoluteFill} />
99
+ <Popover.Content testID={`${kind}-popover`} align={price ? 'end' : 'start'} sideOffset={4}
100
+ aria-labelledby={titleId} aria-describedby={undefined}
101
+ className="w-64 rounded-md border border-border bg-popover p-4 shadow-md">
102
+ <Panel onKey={onKey}>
103
+ <Text nativeID={titleId} className="font-semibold text-popover-foreground">{title}</Text>
104
+ <View className="items-end">
105
+ {percent !== undefined ? <Text className="text-sm text-muted-foreground">{`${format(value)} −${percent}%`}</Text> : null}
106
+ <Text testID={`${kind}-popover-value`} numberOfLines={1} className="text-2xl font-semibold tabular-nums text-popover-foreground">
107
+ {buffer || format(typeof draft === 'number' ? draft : value)}</Text>
108
+ </View>
109
+ {keys.length ? <QuickDiscountKeys keys={keys} percent={percent} onPress={quick} /> : null}
110
+ <Keypad testID={`${kind}-popover-keypad`} rows={rows} onPress={press} />
111
+ {error ? <Text accessibilityRole="alert" className="text-destructive">{error}</Text> : null}
112
+ <View className="flex-row gap-2">
113
+ <Pressable testID={`${kind}-popover-apply`} accessibilityRole="button" onPress={apply} className={`${button} bg-primary`}>
114
+ <Text className="font-semibold text-primary-foreground">Apply</Text></Pressable>
115
+ <Pressable testID={`${kind}-popover-cancel`} accessibilityRole="button" onPress={() => setOpen(false)} className={`${button} bg-card`}>
116
+ <Text className="text-foreground">Cancel</Text></Pressable>
117
+ </View>
118
+ </Panel>
119
+ </Popover.Content>
120
+ </Popover.Portal>
121
+ </Popover.Root>;
122
+ }
123
+
124
+ /** The open panel. Web: focus moves into it and back to where it was on close; keys go to `onKey` (nav-drawer's pattern). */
125
+ function Panel({ onKey, children }: { onKey: (key: string) => void; children: ReactNode }) {
126
+ const panel = useRef<View>(null);
127
+ useKeys(panel, onKey);
128
+ return <View ref={panel} className="gap-3">{children}</View>;
129
+ }
130
+
131
+ function useKeys(panel: RefObject<View | null>, onKey: (key: string) => void) {
132
+ const latest = useRef(onKey);
133
+ latest.current = onKey;
134
+ useEffect(() => {
135
+ if (Platform.OS !== 'web' || typeof document === 'undefined') return;
136
+ const previous = document.activeElement as HTMLElement | null;
137
+ (panel.current as unknown as HTMLElement | null)?.querySelector<HTMLElement>(FOCUSABLE)?.focus();
138
+ const onKeyDown = (event: KeyboardEvent) => latest.current(event.key);
139
+ document.addEventListener('keydown', onKeyDown);
140
+ return () => {
141
+ document.removeEventListener('keydown', onKeyDown);
142
+ previous?.focus?.();
143
+ };
144
+ }, [panel]);
145
+ }
@@ -19,9 +19,24 @@ const button = 'rounded-md border border-border px-3 py-2 min-h-11 items-center
19
19
  const QUICK_KEYS = 3;
20
20
 
21
21
  /** `currentMinor` less `percent` (to two places), half up at the minor unit, as v2's `draftPrice` rounds. */
22
- const lessPercent = (currentMinor: number, percent: number) =>
22
+ export const lessPercent = (currentMinor: number, percent: number) =>
23
23
  Math.round(currentMinor * (10000 - Math.round(percent * 100)) / 10000);
24
24
 
25
+ /** The quick keys drawn: the first three valid percentages (0 < n ≤ 100). */
26
+ export const quickKeys = (list: readonly number[] = []) => list.filter((n) => Number.isFinite(n) && n > 0 && n <= 100).slice(0, QUICK_KEYS);
27
+
28
+ /** v2's quick-discount key row; `percent` is the lit key. Shared by PriceForm and LinePopover. */
29
+ export function QuickDiscountKeys({ keys, percent, onPress }: { keys: readonly number[]; percent?: number; onPress: (key: number) => void }) {
30
+ return <View testID="price-quick-discounts" className="flex-row gap-2">
31
+ {keys.map((key) => <Pressable key={key} testID={`price-discount-${key}`} accessibilityRole="button"
32
+ accessibilityLabel={`Discount (${key}%)`} accessibilityState={{ selected: key === percent }}
33
+ aria-selected={key === percent} onPress={() => onPress(key)}
34
+ className={`${button} flex-1 ${key === percent ? 'bg-primary' : 'bg-card'}`}>
35
+ <Text className={key === percent ? 'text-primary-foreground' : 'text-foreground'}>{`−${key}%`}</Text>
36
+ </Pressable>)}
37
+ </View>;
38
+ }
39
+
25
40
  /** `onApply` returns a refusal to show inline, or null once applied. */
26
41
  export function PriceForm({ lineName, currency, currentMinor, onApply, onClose, quickDiscounts = [] }: {
27
42
  lineName: string; currency: string; currentMinor: number;
@@ -34,7 +49,7 @@ export function PriceForm({ lineName, currency, currentMinor, onApply, onClose,
34
49
  const [error, setError] = useState<string | null>(null);
35
50
  // The lit key (v2's reducer): pressing it again puts the current price back; typing starts over.
36
51
  const [percent, setPercent] = useState<number | undefined>();
37
- const keys = quickDiscounts.filter((n) => Number.isFinite(n) && n > 0 && n <= 100).slice(0, QUICK_KEYS);
52
+ const keys = quickKeys(quickDiscounts);
38
53
  const title = `Price for ${lineName}`;
39
54
  const current = formatMoney({ amount: currentMinor, currency });
40
55
  const draft = percent === undefined ? undefined : lessPercent(currentMinor, percent);
@@ -49,14 +64,8 @@ export function PriceForm({ lineName, currency, currentMinor, onApply, onClose,
49
64
  {draft === undefined ? <Text className="text-muted-foreground">{current}</Text>
50
65
  : <Text testID="price-quick-draft" className="text-muted-foreground">
51
66
  {`${current} −${percent}% → ${formatMoney({ amount: draft, currency })}`}</Text>}
52
- {keys.length ? <View testID="price-quick-discounts" className="flex-row gap-2">
53
- {keys.map((key) => <Pressable key={key} testID={`price-discount-${key}`} accessibilityRole="button"
54
- accessibilityLabel={`Discount (${key}%)`} accessibilityState={{ selected: key === percent }}
55
- aria-selected={key === percent} onPress={() => { setPercent(key === percent ? undefined : key); setText(''); setError(null); }}
56
- className={`${button} flex-1 ${key === percent ? 'bg-primary' : 'bg-card'}`}>
57
- <Text className={key === percent ? 'text-primary-foreground' : 'text-foreground'}>{`−${key}%`}</Text>
58
- </Pressable>)}
59
- </View> : null}
67
+ {keys.length ? <QuickDiscountKeys keys={keys} percent={percent}
68
+ onPress={(key) => { setPercent(key === percent ? undefined : key); setText(''); setError(null); }} /> : null}
60
69
  <TextInput testID="price-input" accessibilityLabel="Price value" value={text}
61
70
  onChangeText={(next) => { setText(next); setPercent(undefined); }}
62
71
  onSubmitEditing={apply} inputMode="decimal" placeholder={currency}
@@ -13,6 +13,7 @@ import {
13
13
  } from '@tallyui/pos';
14
14
  import { cn } from '@tallyui/theme';
15
15
  import { QUICK_CASH_STEPS } from '../checkout/cash-tendered';
16
+ import { DIGIT_ROWS, Keypad } from '../input/keypad';
16
17
 
17
18
  type Sale = ReturnType<typeof useSale>;
18
19
  type Leg = Sale['order']['payments'][number];
@@ -37,10 +38,8 @@ const STATUS_TONE: Record<PaymentLegStatus, string> = {
37
38
  pending: 'text-muted-foreground', authorized: 'text-success', captured: 'text-success', failed: 'text-destructive', voided: 'text-muted-foreground',
38
39
  };
39
40
  /** v2 tender-pane.tsx keypadRows: 123 / 456 / 789, then C, 0, backspace. No decimal key: digits shift in from the right. */
40
- const KEYPAD_ROWS: { key: TenderKey; label: string; name?: string }[][] = [
41
- ...['123', '456', '789'].map((row) => [...row].map((digit) => ({ key: digit as TenderKey, label: digit }))),
42
- [{ key: 'clear', label: 'C', name: 'Clear' }, { key: '0', label: '0' }, { key: 'backspace', label: '⌫', name: 'Delete last digit' }],
43
- ];
41
+ const KEYPAD_ROWS = [...DIGIT_ROWS,
42
+ [{ name: 'clear', label: 'Clear', text: 'C' }, { name: '0', label: '0' }, { name: 'backspace', label: 'Delete last digit', text: '⌫' }]];
44
43
  const button = 'min-h-11 justify-center rounded-md border border-border bg-card px-4 py-2';
45
44
 
46
45
  /** The captured legs since the plan began, as the reducer's `tender-recorded` and `planLegs` read them. */
@@ -148,14 +147,7 @@ export function TenderPane({ sale, state, dispatch, methods }: TenderPaneProps):
148
147
  <Text className="font-semibold text-foreground">{index === 0 ? `Exact ${money(minor)}` : money(minor)}</Text>
149
148
  </Pressable>)}
150
149
  </View> : null}
151
- <View testID="tender-keypad" className="gap-2">
152
- {KEYPAD_ROWS.map((row) => <View key={row[0].key} className="flex-row gap-2">
153
- {row.map(({ key, label, name }) => <Pressable key={key} accessibilityRole="button" accessibilityLabel={name ?? label}
154
- onPress={() => dispatch({ type: 'key', key })} className={cn(button, 'flex-1 items-center')}>
155
- <Text className="text-xl font-semibold text-foreground">{label}</Text>
156
- </Pressable>)}
157
- </View>)}
158
- </View>
150
+ <Keypad testID="tender-keypad" rows={KEYPAD_ROWS} onPress={(name) => dispatch({ type: 'key', key: name as TenderKey })} />
159
151
  {refusal ? <Text accessibilityRole="alert" className="text-destructive">{refusal}</Text> : null}
160
152
  {method ? <Pressable testID="tender-take" accessibilityRole="button" disabled={cannotTake}
161
153
  onPress={take} className={cn('rounded-md bg-primary px-4 py-3', cannotTake && 'opacity-50')}>