@tallyui/components 3.14.0 → 3.16.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.16.0",
4
4
  "type": "module",
5
5
  "description": "Universal POS UI components for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -28,22 +28,24 @@
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.16.0",
32
+ "@tallyui/primitives": "^3.16.0",
33
+ "@tallyui/theme": "^3.16.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
+ "i18next": "^26.7.1",
41
+ "react-i18next": "^17.1.12",
42
+ "@tallyui/pos": "3.16.0"
41
43
  },
42
44
  "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",
45
+ "@tallyui/connector-medusa": "3.16.0",
46
+ "@tallyui/connector-vendure": "3.16.0",
47
+ "@tallyui/connector-woocommerce": "3.16.0",
48
+ "@tallyui/mock-api": "3.16.0",
47
49
  "@types/react": ">=18",
48
50
  "react": "^19.2.4",
49
51
  "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';
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Port of WCPOS v2 (MIT) `packages/core/src/contexts/translations/index.tsx`: one i18next instance per
3
+ * provider, a locale change applied with `changeLanguage`, v2's init options and `useT`. The regional
4
+ * fallback (`fr_CA` → `fr`) is v2's `rxdb-backend.ts` `getBaseLanguage`, as `fallbackLng`. There is no
5
+ * backend: English is bundled and the app passes other languages as `resources`.
6
+ */
7
+ import * as React from 'react';
8
+ import { createInstance, type i18n as I18n, type TFunction } from 'i18next';
9
+ import { useTranslation } from 'react-i18next';
10
+ import en from './locales/en/components.json';
11
+
12
+ /** Catalogues by language code, as the app spells it (`fr`, `fr_CA`, `fr-CA`): key → string. */
13
+ export type Catalogues = Record<string, Record<string, string>>;
14
+
15
+ export interface I18nProviderProps {
16
+ /** The store's locale (`fr_CA` or `fr-CA`). Without one, the device's locale. */
17
+ locale?: string;
18
+ /** Other languages' catalogues; English is bundled. May arrive or change after mount. */
19
+ resources?: Catalogues;
20
+ children: React.ReactNode;
21
+ }
22
+
23
+ const NS = 'components';
24
+
25
+ /** `fr_CA` or `fr-CA` → `fr`, then English. */
26
+ function fallbackLng(code: string): string[] {
27
+ const parts = code.split(/[-_]/);
28
+ return parts.length > 1 ? [parts[0].toLowerCase(), 'en'] : ['en'];
29
+ }
30
+
31
+ function createI18n(locale: string, resources: Catalogues): I18n {
32
+ const instance = createInstance();
33
+ void instance.init({
34
+ lng: locale,
35
+ fallbackLng,
36
+ load: 'currentOnly',
37
+ ns: [NS],
38
+ defaultNS: NS,
39
+ // An app's `en` overrides bundled keys and keeps the rest, as addResourceBundle's deep merge does after mount.
40
+ resources: Object.fromEntries(Object.entries({ ...resources, en: { ...en, ...resources.en } }).map(([lng, catalogue]) => [lng, { [NS]: catalogue }])),
41
+ keySeparator: false,
42
+ nsSeparator: false,
43
+ initAsync: false,
44
+ interpolation: { escapeValue: false, prefix: '{', suffix: '}' },
45
+ react: { bindI18nStore: 'added' },
46
+ });
47
+ return instance;
48
+ }
49
+
50
+ const deviceLocale = () => Intl.DateTimeFormat().resolvedOptions().locale;
51
+
52
+ /** Without a provider, components read this English-only instance. */
53
+ const I18nContext = React.createContext<I18n>(createI18n('en', {}));
54
+
55
+ export function I18nProvider({ locale, resources, children }: I18nProviderProps): React.JSX.Element {
56
+ const lng = React.useMemo(() => locale ?? deviceLocale(), [locale]);
57
+ const [instance] = React.useState(() => createI18n(lng, resources ?? {}));
58
+ const added = React.useRef(resources);
59
+
60
+ React.useEffect(() => {
61
+ if (added.current === resources) return;
62
+ added.current = resources;
63
+ for (const [code, catalogue] of Object.entries(resources ?? {})) instance.addResourceBundle(code, NS, catalogue, true, true);
64
+ }, [resources, instance]);
65
+
66
+ React.useEffect(() => {
67
+ if (instance.language !== lng) void instance.changeLanguage(lng);
68
+ }, [lng, instance]);
69
+
70
+ return <I18nContext.Provider value={instance}>{children}</I18nContext.Provider>;
71
+ }
72
+
73
+ /** The components' `t`, read from the nearest `I18nProvider`, else English. Interpolation is `{name}`. */
74
+ export function useT(): TFunction {
75
+ const i18n = React.useContext(I18nContext);
76
+ const options = React.useMemo(() => ({ i18n }), [i18n]);
77
+ return useTranslation(NS, options).t;
78
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "common.back": "Back",
3
+ "common.backspace": "Delete last digit",
4
+ "common.total": "Total",
5
+ "pos_checkout.cancel_payment": "Cancel payment",
6
+ "pos_checkout.cancelled": "Cancelled",
7
+ "pos_checkout.change_due": "Change {amount}",
8
+ "pos_checkout.clear_amount": "Clear",
9
+ "pos_checkout.exact_amount": "Exact {amount}",
10
+ "pos_checkout.n_of_ways": "{n} of {ways}",
11
+ "pos_checkout.next_leg": "Next",
12
+ "pos_checkout.no_change_for_method": "Only {amount} is due — {method} can't give change",
13
+ "pos_checkout.no_payments_yet": "No payments yet",
14
+ "pos_checkout.paid_in_full": "Paid in full",
15
+ "pos_checkout.paid_of_total": "{paid} of {total} paid",
16
+ "pos_checkout.part_payment_left": "Part payment · {left} left after this",
17
+ "pos_checkout.remaining": "Remaining",
18
+ "pos_checkout.rounded_from": "Rounded from {amount}",
19
+ "pos_checkout.status_authorized": "Authorized",
20
+ "pos_checkout.status_captured": "Captured",
21
+ "pos_checkout.status_failed": "Failed",
22
+ "pos_checkout.status_pending": "Pending",
23
+ "pos_checkout.status_voided": "Voided",
24
+ "pos_checkout.take_amount_in": "Take {amount} in {method}",
25
+ "tender.complete_sale": "Complete sale",
26
+ "tender.continue": "Continue",
27
+ "tender.not_taken": "That payment wasn't taken: nothing is due, or the amount isn't valid.",
28
+ "tender.stored_will_send": "This sale is stored and will be sent. Continue to the next sale.",
29
+ "tender.terminal_reference": "Terminal reference"
30
+ }
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,
@@ -220,3 +227,6 @@ export {
220
227
 
221
228
  // Fonts
222
229
  export { FontProvider, useFontType, type FontProviderProps, type FontState, type FontStatus } from './fonts';
230
+
231
+ // i18n
232
+ export { I18nProvider, useT, type I18nProviderProps, type Catalogues } from './i18n';
@@ -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
+ }