@tallyui/components 3.12.0 → 3.13.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.
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The Sales room's filters: the period presets (worked out in store time by pos `presetRange`),
3
+ * status, cashier and register. Port of WCPOS v2 `screens/main/reports/date-button.tsx` and the
4
+ * filter choices in its `LEDGER.md`; copy is v2's English (`core.json`).
5
+ */
6
+ import { useState, type JSX } from 'react';
7
+ import { Pressable, Text, View } from 'react-native';
8
+ import { DATE_PRESETS, presetRange, type DatePreset, type DayRange } from '@tallyui/pos';
9
+ import { cn } from '@tallyui/theme';
10
+
11
+ export interface SalesOption { value: string; label: string }
12
+ export interface SalesFilters {
13
+ preset: DatePreset;
14
+ range: DayRange;
15
+ /** A single day's comparison: the day before or the same weekday last week. */
16
+ compare: 'previous' | 'week';
17
+ status: string;
18
+ cashierId: string | null;
19
+ registerId: string | null;
20
+ }
21
+ export interface SalesFiltersBarProps {
22
+ filters: SalesFilters;
23
+ onFiltersChange: (next: SalesFilters) => void;
24
+ /** IANA zone of the store, or 'device'. */
25
+ timezone: string;
26
+ /** The clock presets are worked out from; defaults to the time of the press. */
27
+ now?: () => Date;
28
+ statusOptions: SalesOption[];
29
+ cashierOptions: SalesOption[];
30
+ registerOptions: SalesOption[];
31
+ }
32
+
33
+ const PRESET_LABELS: Record<DatePreset, string> = {
34
+ today: 'Today', yesterday: 'Yesterday', thisWeek: 'This Week',
35
+ lastWeek: 'Last Week', thisMonth: 'This Month', lastMonth: 'Last Month',
36
+ };
37
+ const ALL = 'all';
38
+
39
+ /** `10 Nov` for a store day. */
40
+ export const dayLabel = (day: string): string =>
41
+ new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' }).format(new Date(`${day}T00:00:00Z`));
42
+
43
+ function ChoiceSelect({ id, value, options, onChange }: {
44
+ id: string; value: string; options: SalesOption[]; onChange: (value: string) => void;
45
+ }): JSX.Element {
46
+ const [open, setOpen] = useState(false);
47
+ const chosen = options.find((option) => option.value === value);
48
+ return (
49
+ <View className="gap-1">
50
+ <Pressable testID={id} accessibilityRole="button" onPress={() => setOpen(!open)}
51
+ className="rounded-md border border-border bg-card px-3 py-2">
52
+ <Text className="text-sm text-foreground">{chosen?.label ?? value}</Text>
53
+ </Pressable>
54
+ {open && (
55
+ <View className="rounded-md border border-border bg-card py-1">
56
+ {options.map((option) => (
57
+ <Pressable key={option.value} testID={`${id}-option-${option.value}`} accessibilityRole="radio"
58
+ accessibilityState={{ checked: option.value === value }}
59
+ onPress={() => { setOpen(false); onChange(option.value); }}
60
+ className={cn('px-3 py-2', option.value === value && 'bg-muted')}>
61
+ <Text className="text-sm text-foreground">{option.label}</Text>
62
+ </Pressable>
63
+ ))}
64
+ </View>
65
+ )}
66
+ </View>
67
+ );
68
+ }
69
+
70
+ export function SalesFiltersBar({
71
+ filters, onFiltersChange, timezone, now, statusOptions, cashierOptions, registerOptions,
72
+ }: SalesFiltersBarProps): JSX.Element {
73
+ const { range } = filters;
74
+ return (
75
+ <View testID="sales-filters" className="flex-row flex-wrap items-start gap-2">
76
+ <ChoiceSelect id="sales-filter-period" value={filters.preset}
77
+ options={DATE_PRESETS.map((preset) => ({ value: preset, label: PRESET_LABELS[preset] }))}
78
+ onChange={(value) => {
79
+ const preset = value as DatePreset;
80
+ onFiltersChange({ ...filters, preset, range: presetRange(preset, (now ?? (() => new Date()))(), timezone) });
81
+ }} />
82
+ <Text testID="sales-filter-dates" className="py-2 text-sm text-muted-foreground">
83
+ {range.from === range.to ? dayLabel(range.from) : `${dayLabel(range.from)} – ${dayLabel(range.to)}`}
84
+ </Text>
85
+ <ChoiceSelect id="sales-filter-status" value={filters.status} options={statusOptions}
86
+ onChange={(status) => onFiltersChange({ ...filters, status })} />
87
+ <ChoiceSelect id="sales-filter-cashier" value={filters.cashierId ?? ALL}
88
+ options={[{ value: ALL, label: 'Everyone' }, ...cashierOptions]}
89
+ onChange={(value) => onFiltersChange({ ...filters, cashierId: value === ALL ? null : value })} />
90
+ <ChoiceSelect id="sales-filter-register" value={filters.registerId ?? ALL}
91
+ options={[{ value: ALL, label: 'All registers' }, ...registerOptions]}
92
+ onChange={(value) => onFiltersChange({ ...filters, registerId: value === ALL ? null : value })} />
93
+ </View>
94
+ );
95
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The Sales room's hero: the period's gross, its change against the comparison period and a
3
+ * daily chart of both. Port of WCPOS v2 `screens/main/reports/hero/index.tsx` (`Difference`, the
4
+ * companions Orders · Average order · Items) and the comparison labels of its `LEDGER.md`.
5
+ * The bars are Views with theme token classes, so the chart takes its colours from the theme.
6
+ */
7
+ import type { JSX } from 'react';
8
+ import { Pressable, Text, View } from 'react-native';
9
+ import { formatMoney } from '@tallyui/core';
10
+ import type { SalesFigures } from '@tallyui/pos';
11
+ import { cn } from '@tallyui/theme';
12
+ import { Card } from '../ui/card';
13
+ import { dayLabel, type SalesFilters } from './filters-bar';
14
+
15
+ export interface SalesHeroProps {
16
+ figures: SalesFigures;
17
+ filters: SalesFilters;
18
+ onFiltersChange: (next: SalesFilters) => void;
19
+ currency: string;
20
+ }
21
+
22
+ const NO_COMPARISON = '—';
23
+ const signed = (diff: number, format: (n: number) => string) =>
24
+ diff === 0 ? '±0' : `${diff > 0 ? '+' : '−'}${format(Math.abs(diff))}`;
25
+
26
+ /** A change against the comparison, or `—` when there is nothing to compare with. */
27
+ function Difference({ testID, text, diff, suffix }: { testID: string; text?: string; diff: number; suffix?: string }): JSX.Element {
28
+ const tone = text === undefined || diff === 0 ? 'text-muted-foreground' : diff > 0 ? 'text-success' : 'text-destructive';
29
+ return (
30
+ <Text testID={testID} className={cn('text-sm', tone)} accessibilityLabel={text === undefined ? 'No comparison' : undefined}>
31
+ {text === undefined ? NO_COMPARISON : suffix ? `${text} ${suffix}` : text}
32
+ </Text>
33
+ );
34
+ }
35
+
36
+ function compareLabel(filters: SalesFilters): string {
37
+ if (filters.preset === 'thisWeek' || filters.preset === 'lastWeek') return 'vs the week before';
38
+ if (filters.preset === 'thisMonth' || filters.preset === 'lastMonth') return 'vs the month before';
39
+ if (filters.compare === 'previous') return 'vs yesterday';
40
+ const weekday = new Intl.DateTimeFormat('en-GB', { weekday: 'long', timeZone: 'UTC' }).format(new Date(`${filters.range.from}T00:00:00Z`));
41
+ return `vs last ${weekday}`;
42
+ }
43
+
44
+ export function SalesHero({ figures, filters, onFiltersChange, currency }: SalesHeroProps): JSX.Element {
45
+ const money = (minor: number) => formatMoney({ amount: minor, currency }) ?? '';
46
+ const { totals, series } = figures;
47
+ const before = figures.comparison && figures.comparison.totals.orderCount > 0 ? figures.comparison.totals : undefined;
48
+ const label = compareLabel(filters);
49
+ const grossDiff = before ? totals.grossMinor - before.grossMinor : 0;
50
+ const pct = before && before.grossMinor !== 0 ? Math.round((grossDiff / before.grossMinor) * 1000) / 10 : undefined;
51
+ const companions = [
52
+ { id: 'orders', name: 'Orders', value: totals.orderCount, prev: before?.orderCount, format: String },
53
+ { id: 'average', name: 'Average order', value: totals.averageMinor, prev: before?.averageMinor, format: money },
54
+ { id: 'items', name: 'Items', value: totals.items, prev: before?.items, format: String },
55
+ ];
56
+ const compareSeries = figures.comparison?.series ?? [];
57
+ const max = Math.max(0, ...series.map((point) => point.grossMinor), ...compareSeries.map((point) => point.grossMinor));
58
+ const height = (gross: number) => `${max > 0 ? (Math.max(0, gross) / max) * 100 : 0}%` as const;
59
+ const oneDay = filters.preset === 'today' || filters.preset === 'yesterday';
60
+
61
+ return (
62
+ <Card testID="sales-hero" className="gap-4 p-4">
63
+ <View className="flex-row flex-wrap items-end gap-3">
64
+ <Text testID="hero-total" className="text-4xl font-bold text-foreground">{money(totals.grossMinor)}</Text>
65
+ <Difference testID="hero-delta" diff={pct ?? 0} suffix={label}
66
+ text={pct === undefined ? undefined : pct === 0 ? '±0%' : signed(pct, (n) => `${n.toFixed(1)}%`)} />
67
+ </View>
68
+ {oneDay ? (
69
+ <View className="flex-row gap-2">
70
+ {(['previous', 'week'] as const).map((compare) => (
71
+ <Pressable key={compare} testID={`hero-compare-${compare}`} accessibilityRole="radio"
72
+ accessibilityState={{ checked: filters.compare === compare }}
73
+ onPress={() => onFiltersChange({ ...filters, compare })}
74
+ className={cn('rounded-md border border-border px-3 py-1', filters.compare === compare && 'bg-muted')}>
75
+ <Text className="text-sm text-foreground">{compareLabel({ ...filters, compare })}</Text>
76
+ </Pressable>
77
+ ))}
78
+ </View>
79
+ ) : (
80
+ <Text testID="hero-compare" className="text-sm text-muted-foreground">{label}</Text>
81
+ )}
82
+ <View className="flex-row flex-wrap gap-6">
83
+ {companions.map(({ id, name, value, prev, format }) => (
84
+ <View key={id} className="gap-0.5">
85
+ <Text className="text-xs text-muted-foreground">{name}</Text>
86
+ <Text testID={`hero-${id}`} className="text-lg font-semibold text-foreground">{format(value)}</Text>
87
+ <Difference testID={`hero-${id}-delta`} diff={prev === undefined ? 0 : value - prev}
88
+ text={prev === undefined ? undefined : signed(value - prev, format)} />
89
+ </View>
90
+ ))}
91
+ </View>
92
+ <View testID="hero-chart" className="h-40 flex-row items-end gap-1">
93
+ {series.map((point, i) => (
94
+ <View key={point.day} className="h-full flex-1 flex-row items-end gap-0.5">
95
+ {compareSeries[i] && (
96
+ <View testID={`hero-bar-compare-${i}`} className="flex-1 rounded-sm bg-muted-foreground opacity-30"
97
+ style={{ height: height(compareSeries[i].grossMinor) }} />
98
+ )}
99
+ <View testID={`hero-bar-${i}`} className="flex-1 rounded-sm bg-primary" style={{ height: height(point.grossMinor) }} />
100
+ </View>
101
+ ))}
102
+ </View>
103
+ {series.length > 0 && (
104
+ <View className="flex-row justify-between">
105
+ <Text className="text-xs text-muted-foreground">{dayLabel(series[0].day)}</Text>
106
+ {series.length > 1 && <Text className="text-xs text-muted-foreground">{dayLabel(series[series.length - 1].day)}</Text>}
107
+ </View>
108
+ )}
109
+ </Card>
110
+ );
111
+ }
@@ -0,0 +1,4 @@
1
+ export { SalesRoom, type SalesRoomProps } from './sales-room';
2
+ export { SalesHero, type SalesHeroProps } from './hero';
3
+ export { SalesCards, type SalesCardsProps, type SalesCardId } from './cards';
4
+ export { SalesFiltersBar, type SalesFiltersBarProps, type SalesFilters, type SalesOption } from './filters-bar';
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The Reports screen's Sales room: filters, hero and cards over one `SalesFigures` result.
3
+ * Port of the WCPOS v2 Sales room layout (`screens/main/reports/`, `LEDGER.md`). It takes the
4
+ * figures and the filter state as props; the screen works the figures out and owns the state.
5
+ */
6
+ import type { JSX } from 'react';
7
+ import { View } from 'react-native';
8
+ import type { SalesFigures } from '@tallyui/pos';
9
+ import { SalesCards, type SalesCardId } from './cards';
10
+ import { SalesFiltersBar, type SalesFiltersBarProps } from './filters-bar';
11
+ import { SalesHero } from './hero';
12
+
13
+ export interface SalesRoomProps extends SalesFiltersBarProps {
14
+ figures: SalesFigures;
15
+ currency: string;
16
+ /** Opens a card's panel. */
17
+ onOpenCard?: (card: SalesCardId) => void;
18
+ }
19
+
20
+ export function SalesRoom({ figures, filters, onFiltersChange, currency, onOpenCard, ...bar }: SalesRoomProps): JSX.Element {
21
+ return (
22
+ <View testID="sales-room" className="gap-4">
23
+ <SalesFiltersBar filters={filters} onFiltersChange={onFiltersChange} {...bar} />
24
+ <SalesHero figures={figures} filters={filters} onFiltersChange={onFiltersChange} currency={currency} />
25
+ <SalesCards figures={figures} currency={currency} onOpenCard={onOpenCard} />
26
+ </View>
27
+ );
28
+ }
package/src/sale/index.ts CHANGED
@@ -12,3 +12,4 @@ export { injectPrintStyle } from './print-style';
12
12
  export { SyncStatus } from './sync-status';
13
13
  export { OrdersList, type OrderHistoryRow } from './orders-list';
14
14
  export { ParkedSales, type ParkedSalesProps } from './parked-sales';
15
+ export { OpenSaleTabs, type OpenSaleTabsProps } from './open-sale-tabs';
@@ -0,0 +1,67 @@
1
+ import type { JSX } from 'react';
2
+ import { Pressable, ScrollView, View } from 'react-native';
3
+ import { formatMoney } from '@tallyui/core';
4
+ import type { OpenSale } from '@tallyui/pos';
5
+ import { Text } from '../ui/text';
6
+
7
+ /** Pass `openSales(sale.order, useParkedSales(drafts).parked)`; `onSelect` and `onNew` call `sale.switchSale(id)` and `sale.switchSale(null)`. */
8
+ export interface OpenSaleTabsProps {
9
+ sales: OpenSale[];
10
+ currency: string;
11
+ onSelect: (id: string) => void;
12
+ onNew: () => void;
13
+ }
14
+
15
+ /** v2 cart/tab-who.ts: the customer, or what is in the cart when the customer is a guest. */
16
+ function who(sale: OpenSale): string {
17
+ if (sale.customerName) return sale.customerName;
18
+ if (sale.itemCount === 0) return 'Guest';
19
+ return `Guest · ${sale.itemCount === 1 && sale.firstItem ? sale.firstItem : `${sale.itemCount} ${sale.itemCount === 1 ? 'item' : 'items'}`}`;
20
+ }
21
+
22
+ /**
23
+ * The open sales as cart tabs (v2 cart/tabs.tsx): who, then the Partly paid chip or else the total. The open sale's
24
+ * tab is underlined even when it is the only one; a blank cart has no tab, the + cell is its tab and reads "New".
25
+ */
26
+ export function OpenSaleTabs({ sales, currency, onSelect, onNew }: OpenSaleTabsProps): JSX.Element {
27
+ const blank = !sales.some((sale) => sale.current);
28
+ return (
29
+ <View testID="open-sale-tabs" className="h-14 flex-row items-stretch border-t border-border bg-card">
30
+ <ScrollView horizontal accessibilityRole="tablist" showsHorizontalScrollIndicator={false} className="min-w-0 flex-1">
31
+ {sales.map((sale) => {
32
+ // isPartlyPaid from @tallyui/pos, inlined: components import only types from pos (v2 cart/tab-chip.tsx).
33
+ const partly = sale.paidMinor > 0 && sale.balanceDueMinor > 0;
34
+ const status = `Partly paid · ${formatMoney({ amount: sale.balanceDueMinor, currency })} due`;
35
+ return (
36
+ <Pressable key={sale.id} testID={`open-sale-tab-${sale.id}`} accessibilityRole="tab"
37
+ accessibilityState={{ selected: sale.current }} aria-selected={sale.current} onPress={() => onSelect(sale.id)}
38
+ className={`h-full justify-center border-b-2 px-3 ${sale.current ? 'border-primary' : 'border-transparent'}`}>
39
+ <Text testID={`open-sale-tab-${sale.id}-who`} numberOfLines={1}
40
+ className={sale.current ? 'font-semibold text-foreground' : 'font-medium text-muted-foreground'}>{who(sale)}</Text>
41
+ {partly && !sale.current ? (
42
+ // Inactive tabs carry the chip; the open tab keeps only the muted words (v2 TabChip).
43
+ <View testID={`open-sale-chip-${sale.id}`} className="flex-row items-center gap-1 self-start rounded-sm bg-info/15 px-1.5 py-0.5">
44
+ <View className="h-1.5 w-1.5 rounded-full bg-info" />
45
+ <Text className="text-xs font-semibold text-foreground">{status}</Text>
46
+ </View>
47
+ ) : partly ? (
48
+ <Text testID={`open-sale-status-${sale.id}`} className="text-xs text-muted-foreground">{status}</Text>
49
+ ) : (
50
+ <Text testID={`open-sale-tab-${sale.id}-amount`} className="text-xs text-muted-foreground tabular-nums">
51
+ {formatMoney({ amount: sale.totalMinor, currency })}
52
+ </Text>
53
+ )}
54
+ </Pressable>
55
+ );
56
+ })}
57
+ </ScrollView>
58
+ <Pressable testID="new-sale-tab" accessibilityRole="tab" accessibilityLabel="New order" accessibilityState={{ selected: blank }} aria-selected={blank}
59
+ // Already on the blank cart: + is a place, not an action (v2).
60
+ onPress={() => { if (!blank) onNew(); }}
61
+ className={`h-full flex-row items-center justify-center gap-1.5 px-3 ${blank ? 'border-b-2 border-primary' : ''}`}>
62
+ <Text className={blank ? 'text-primary' : 'text-foreground'}>+</Text>
63
+ {blank && <Text testID="new-sale-tab-label" className="font-semibold">New</Text>}
64
+ </Pressable>
65
+ </View>
66
+ );
67
+ }
@@ -4,3 +4,6 @@ export function orderReference(order: { id: string; serverRefs?: { displayId?: s
4
4
  const local = order.id.slice(-8);
5
5
  return order.serverRefs?.displayId ? `${local} · #${order.serverRefs.displayId}` : local;
6
6
  }
7
+
8
+ /** The receipt and Orders say this under a note that went below order.create 7 (ADR-083 condition 2). */
9
+ export const NOTE_NOT_SENT = "The note couldn't be sent to the store.";
@@ -1,8 +1,8 @@
1
1
  import { useEffect, useRef, useState, type ReactNode } from 'react';
2
2
  import { Pressable, ScrollView, Text, View } from 'react-native';
3
3
  import { formatMoney, knownWarnings } from '@tallyui/core';
4
- import { isRequeueable, needsAttention, type OutboxState, type PosOrder } from '@tallyui/pos';
5
- import { orderReference } from './order-reference';
4
+ import { isRequeueable, needsAttention, noteDelivery, type OutboxState, type PosOrder } from '@tallyui/pos';
5
+ import { NOTE_NOT_SENT, orderReference } from './order-reference';
6
6
  import { sinceText } from './since-text';
7
7
 
8
8
  /** One order from the store's own history (ADR-052 amendment 1), mapped by the app from its platform. */
@@ -113,6 +113,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
113
113
  {order.payments.map((payment) => <Text key={payment.id} className="text-muted-foreground">
114
114
  {`${payment.method === 'cash' ? 'Cash' : 'Card terminal'} ${formatMoney({ amount: payment.amountMinor, currency: order.currency })}${payment.reference ? ` · ${payment.reference}` : ''}`}
115
115
  </Text>)}
116
+ {order.note ? <Text testID={`order-note-${order.id}`} className="text-foreground">{`Note: ${order.note}`}</Text> : null}
116
117
  </View> : null}
117
118
  {stuckEntry ? <Text className="text-destructive">
118
119
  {/* The same words for any reason, with no reason code; the hour as the status line has it (numeric, #245). */}
@@ -127,6 +128,7 @@ export function OrdersList({ orders, onRetry, formatDate = defaultFormatDate, fo
127
128
  ? `The customer's ${warning.field} couldn't be sent to the store, so the order isn't linked to them.`
128
129
  : "The terminal's payment reference couldn't be kept; the payment is recorded without it."}
129
130
  </Text>)}
131
+ {noteDelivery(order) === 'not_sent' ? <Text testID={`order-note-not-sent-${order.id}`} className="text-foreground">{NOTE_NOT_SENT}</Text> : null}
130
132
  {/* Retry is offered only for a code the outbox resends (isRequeueable). */}
131
133
  {section.title === 'Needs attention' && order.syncStatus === 'rejected' && isRequeueable(order.error?.code)
132
134
  ? <Pressable accessibilityRole="button" disabled={retryingIds.has(order.id)} onPress={async () => {
@@ -1,11 +1,11 @@
1
1
  import { useEffect, type ReactNode } from 'react';
2
2
  import { Pressable, Text, View } from 'react-native';
3
3
  import { formatMoney } from '@tallyui/core';
4
- import { buildReceiptData, type ReceiptData, type SentOrder } from '@tallyui/pos';
4
+ import { buildReceiptData, noteDelivery, type ReceiptData, type SentOrder } from '@tallyui/pos';
5
5
  import type { PosOrder } from '@tallyui/pos';
6
6
  import { injectPrintStyle } from './print-style';
7
7
  import { discountLabel } from './discount-form';
8
- import { orderReference } from './order-reference';
8
+ import { NOTE_NOT_SENT, orderReference } from './order-reference';
9
9
 
10
10
  const defaultFormatDate = (iso: string) => new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(iso));
11
11
 
@@ -86,6 +86,12 @@ export function Receipt(props: ReceiptProps) {
86
86
  : order || payment.method === 'external' ? 'Card terminal' : payment.method,
87
87
  money(payment.amountMinor) + (payment.reference ? ` · ${payment.reference}` : ''), false, index))}
88
88
  {order || receipt.changeDueMinor > 0 ? row('Change', money(receipt.changeDueMinor)) : null}
89
+ {receipt.footer.note ? <View testID="receipt-note" className="gap-1">
90
+ <Text className="text-foreground">{receipt.footer.note}</Text>
91
+ {/* ADR-083 condition 2: for the cashier, so it is not printed. */}
92
+ {receipt.footer.noteNotSent || (posOrder !== undefined && noteDelivery(posOrder) === 'not_sent')
93
+ ? <View dataSet={{ print: 'hide' }}><Text testID="receipt-note-not-sent" className="text-destructive">{NOTE_NOT_SENT}</Text></View> : null}
94
+ </View> : null}
89
95
  {footerSlot ? <View testID="receipt-footer" className="mt-3 items-center border-t border-dashed border-border pt-3">{footerSlot}</View> : null}
90
96
  <View dataSet={{ print: 'hide' }} className="flex-row gap-4">
91
97
  <Pressable accessibilityRole="button" onPress={() => { if (typeof window !== 'undefined' && typeof window.print === 'function') window.print(); }} className="rounded-md border border-border bg-card px-4 py-3">
@@ -0,0 +1,3 @@
1
+ export { ScaleProvider, useScale } from './scale-provider';
2
+ export type { ScaleProviderProps, ScaleScopeProps, ScaleState } from './scale-provider';
3
+ export { usePointer } from './use-pointer';
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Port of WCPOS v2 `packages/core/src/contexts/scale/index.tsx` and
3
+ * `packages/components/src/lib/device.ts`.
4
+ * The native scope is a prop so components do not depend on Uniwind's ScopedVariables.
5
+ */
6
+ import * as React from 'react';
7
+ import { Platform, useWindowDimensions } from 'react-native';
8
+ import type { ScaleOverride } from '@tallyui/theme';
9
+ import {
10
+ SCALE_VARIABLE_NAMES, resolveStep, scaleVariables,
11
+ type Pointer, type ScaleStep, type ScaleVariables,
12
+ } from '@tallyui/theme';
13
+ import { usePointer } from './use-pointer';
14
+
15
+ export interface ScaleScopeProps {
16
+ variables: ScaleVariables;
17
+ children?: React.ReactNode;
18
+ }
19
+
20
+ export interface ScaleState {
21
+ step: ScaleStep;
22
+ pointer: Pointer;
23
+ variables: ScaleVariables;
24
+ }
25
+
26
+ export interface ScaleProviderProps {
27
+ /** The app's stored `ui.scale` setting (from `useAppSettings` in `@tallyui/pos`); missing or unknown means Auto. */
28
+ scale?: ScaleOverride | null;
29
+ /** Scopes the variables below it on native, e.g. Uniwind's ScopedVariables. Optional: the web root mirror covers the web. */
30
+ scope?: React.ComponentType<ScaleScopeProps>;
31
+ children?: React.ReactNode;
32
+ }
33
+
34
+ const ScaleContext = React.createContext<ScaleState>({
35
+ step: 'regular',
36
+ pointer: 'coarse',
37
+ variables: scaleVariables('regular', 'coarse'),
38
+ });
39
+
40
+ /** Mirror on the root because portalled content leaves the subtree. */
41
+ function useRootScaleMirror(variables: ScaleVariables) {
42
+ React.useLayoutEffect(() => {
43
+ if (Platform.OS !== 'web' || typeof document === 'undefined') return;
44
+ const style = document.documentElement.style;
45
+ for (const name of SCALE_VARIABLE_NAMES) style.setProperty(name, `${variables[name]}px`);
46
+ return () => {
47
+ for (const name of SCALE_VARIABLE_NAMES) style.removeProperty(name);
48
+ };
49
+ }, [variables]);
50
+ }
51
+
52
+ export function ScaleProvider({ scale, scope: Scope, children }: ScaleProviderProps): React.JSX.Element {
53
+ const { width, height } = useWindowDimensions();
54
+ const pointer = usePointer();
55
+ const extent = Platform.OS === 'web' ? width : Math.min(width, height);
56
+ const step = resolveStep(scale, extent);
57
+ const variables = React.useMemo(() => scaleVariables(step, pointer), [step, pointer]);
58
+ const state = React.useMemo(() => ({ step, pointer, variables }), [step, pointer, variables]);
59
+ useRootScaleMirror(variables);
60
+
61
+ return (
62
+ <ScaleContext.Provider value={state}>
63
+ {Scope ? <Scope variables={variables}>{children}</Scope> : children}
64
+ </ScaleContext.Provider>
65
+ );
66
+ }
67
+
68
+ export function useScale(): ScaleState {
69
+ return React.useContext(ScaleContext);
70
+ }
@@ -0,0 +1,23 @@
1
+ /** Port of WCPOS v2 `packages/components/src/lib/device.ts`, without the override context. */
2
+ import { useCallback, useMemo, useSyncExternalStore } from 'react';
3
+ import { Platform } from 'react-native';
4
+ import type { Pointer } from '@tallyui/theme';
5
+
6
+ export function usePointer(): Pointer {
7
+ const queries = useMemo(() => {
8
+ if (Platform.OS !== 'web' || typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
9
+ return [];
10
+ }
11
+ return [window.matchMedia('(pointer: fine)'), window.matchMedia('(hover: hover)')];
12
+ }, []);
13
+ const subscribe = useCallback((notify: () => void) => {
14
+ for (const query of queries) query.addEventListener('change', notify);
15
+ return () => {
16
+ for (const query of queries) query.removeEventListener('change', notify);
17
+ };
18
+ }, [queries]);
19
+ const getSnapshot = useCallback((): Pointer => (
20
+ queries.length === 2 && queries.every((query) => query.matches) ? 'fine' : 'coarse'
21
+ ), [queries]);
22
+ return useSyncExternalStore(subscribe, getSnapshot, () => 'coarse');
23
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Settings › Display: theme, scale and fonts, device-local through `useAppSettings`.
3
+ * Port of WCPOS v2 `packages/core/src/screens/main/settings/theme.tsx` (`ThemeSettingsContent`,
4
+ * `ScaleSection`, `FontsSection`); the labels are v2's English strings from
5
+ * `core/contexts/translations/locales/en/core.json`. v2's icons section has no TallyUI counterpart.
6
+ */
7
+ import { Platform, View } from 'react-native';
8
+ import type { JSX } from 'react';
9
+ import { UI_SCALES, UI_THEMES, type AppSettingKey, type AppSettings, type UiScale, type UiTheme, type useAppSettings } from '@tallyui/pos';
10
+ import { FONT_SETTINGS, TYPE_SETS, cn, fontFamilyStyle } from '@tallyui/theme';
11
+ import { RadioGroup, RadioGroupItem } from '../ui/radio-group';
12
+ import { Text } from '../ui/text';
13
+ import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group';
14
+ import { SettingsGroup } from './settings-group';
15
+
16
+ type FontSetting = (typeof FONT_SETTINGS)[number];
17
+
18
+ export interface DisplaySettingsProps {
19
+ /** The hook's settings: `<DisplaySettings {...useAppSettings(db.app_settings)} />`. */
20
+ settings: Pick<AppSettings, 'ui.theme' | 'ui.scale' | 'ui.font'>;
21
+ setSetting: ReturnType<typeof useAppSettings>['setSetting'];
22
+ className?: string;
23
+ }
24
+
25
+ const THEME_OPTIONS: Record<UiTheme, { label: string; description: string }> = {
26
+ system: { label: 'System', description: 'Follow your device settings' },
27
+ light: { label: 'Light', description: 'Clean and bright' },
28
+ dark: { label: 'Dark', description: 'Easy on the eyes' },
29
+ };
30
+
31
+ const SCALE_LABELS: Record<UiScale, string> = {
32
+ auto: 'Auto', compact: 'Compact', regular: 'Regular', spacious: 'Spacious',
33
+ };
34
+
35
+ const FONT_LABELS: Record<FontSetting, string> = {
36
+ auto: 'Match theme',
37
+ system: 'System',
38
+ instrument: 'DM Sans · Instrument Serif',
39
+ grotesk: 'Space Grotesk',
40
+ fraunces: 'DM Sans · Fraunces',
41
+ manrope: 'Manrope',
42
+ };
43
+
44
+ interface OptionRowProps {
45
+ id: string;
46
+ testID: string;
47
+ label: string;
48
+ description?: string;
49
+ onSelect: () => void;
50
+ right?: JSX.Element;
51
+ }
52
+
53
+ function OptionRow({ id, testID, label, description, onSelect, right }: OptionRowProps): JSX.Element {
54
+ return (
55
+ <View className="flex-row items-center gap-3 px-4 py-3">
56
+ <RadioGroupItem value={id} testID={testID} aria-label={label} />
57
+ <View className="flex-1 gap-0.5">
58
+ <Text className="text-sm font-medium text-foreground" onPress={onSelect}>{label}</Text>
59
+ {description && <Text className="text-xs text-muted-foreground">{description}</Text>}
60
+ </View>
61
+ {right}
62
+ </View>
63
+ );
64
+ }
65
+
66
+ export function DisplaySettings({ settings, setSetting, className }: DisplaySettingsProps): JSX.Element {
67
+ const save = <K extends AppSettingKey>(key: K, value: AppSettings[K]) => {
68
+ setSetting(key, value).catch((error: unknown) => console.error('Failed to save display setting', error));
69
+ };
70
+ const theme = settings['ui.theme'];
71
+ const scale = settings['ui.scale'];
72
+ // A retired or unknown set shows Auto, as `resolveTypeSet` falls back.
73
+ const font = FONT_SETTINGS.find((id) => id === settings['ui.font']) ?? 'auto';
74
+ const isWeb = Platform.OS === 'web';
75
+
76
+ return (
77
+ <View className={cn('gap-6', className)}>
78
+ <SettingsGroup title="Theme">
79
+ <RadioGroup value={theme} onValueChange={(value) => save('ui.theme', value as UiTheme)} aria-label="Theme" className="gap-0">
80
+ {UI_THEMES.map((id) => (
81
+ <OptionRow
82
+ key={id} id={id} testID={`settings-theme-${id}`} label={THEME_OPTIONS[id].label}
83
+ description={THEME_OPTIONS[id].description} onSelect={() => save('ui.theme', id)}
84
+ />
85
+ ))}
86
+ </RadioGroup>
87
+ </SettingsGroup>
88
+
89
+ <SettingsGroup title="Scale" description="Auto follows the window size.">
90
+ <ToggleGroup
91
+ type="single" variant="outline" value={scale} aria-label="Scale" className="flex-wrap justify-start p-3"
92
+ onValueChange={(value) => { if (value) save('ui.scale', value as UiScale); }}
93
+ >
94
+ {UI_SCALES.map((id) => (
95
+ <ToggleGroupItem key={id} value={id} testID={`settings-scale-${id}`} className={cn(scale === id && 'bg-accent')}>
96
+ <Text>{SCALE_LABELS[id]}</Text>
97
+ </ToggleGroupItem>
98
+ ))}
99
+ </ToggleGroup>
100
+ </SettingsGroup>
101
+
102
+ <SettingsGroup
103
+ title="Fonts"
104
+ description="The typeface the app's text uses on this device. Match theme follows the theme you chose."
105
+ >
106
+ <RadioGroup value={font} onValueChange={(value) => save('ui.font', value)} aria-label="Fonts" className="gap-0">
107
+ {FONT_SETTINGS.map((id) => (
108
+ <OptionRow
109
+ key={id} id={id} testID={`settings-fonts-${id}`} label={FONT_LABELS[id]}
110
+ onSelect={() => save('ui.font', id)}
111
+ right={(
112
+ <Text className="text-lg text-foreground" style={id === 'auto' ? undefined : fontFamilyStyle(TYPE_SETS[id].body, isWeb)}>
113
+ Aa
114
+ </Text>
115
+ )}
116
+ />
117
+ ))}
118
+ </RadioGroup>
119
+ </SettingsGroup>
120
+ </View>
121
+ );
122
+ }
@@ -1,3 +1,4 @@
1
1
  export { SettingsRow, type SettingsRowProps } from './settings-row';
2
2
  export { SettingsGroup, type SettingsGroupProps } from './settings-group';
3
3
  export { ConnectorStatus, type ConnectorStatusProps, type ConnectionStatus } from './connector-status';
4
+ export { DisplaySettings, type DisplaySettingsProps } from './display-settings';
@@ -0,0 +1,25 @@
1
+ import * as React from 'react';
2
+ import { Platform, type TextProps } from 'react-native';
3
+ import { fontFamilyStyle } from '@tallyui/theme';
4
+ import { useFontType } from '../../fonts';
5
+
6
+ const wrappers = new Map<React.ElementType, React.ComponentType<TextProps>>();
7
+
8
+ /** Wraps a text component (RN Text or Slot) so it draws the active type set's face. Cached: the same Base always returns the same wrapper. */
9
+ export function withFont<C extends React.ElementType>(Base: C): C {
10
+ let Wrapper = wrappers.get(Base);
11
+ if (!Wrapper) {
12
+ Wrapper = function FontText({ className, style, ...props }: TextProps) {
13
+ const { type } = useFontType();
14
+ const family = /(^|\s)font-(mono|sans|serif)(\s|$)/.test(className ?? '')
15
+ ? undefined
16
+ : /(^|\s)tabular-nums(\s|$)/.test(className ?? '') ? type.num ?? type.body : type.body;
17
+ return React.createElement(Base, {
18
+ ...props, className,
19
+ style: family ? [fontFamilyStyle(family, Platform.OS === 'web'), style] : style,
20
+ });
21
+ };
22
+ wrappers.set(Base, Wrapper);
23
+ }
24
+ return Wrapper as unknown as C;
25
+ }