Architecture

State and persistence

The bill store, undo/redo, autosave, the localStorage schema and the migration from version 1.

A documentação técnica está em inglês.

All app state lives in one small external store: src/features/bill/store.ts. It wraps the pure billReducer with the things a reducer shouldn't do itself — remembering history, writing to storage, talking to other tabs.

Why an external store

React context with a reducer re-renders every consumer on every change. With a bill of 30 items and live totals, that means each keystroke in the title re-renders every item card. The store uses useSyncExternalStore with selectors instead:

const people = useBillStore((s) => s.bill.people); // re-renders only when people change
const breakdown = useBreakdown();                   // memoized per bill object
dispatch({ type: 'person/add', names: ['Ana'] });

Selectors must return values that already exist in the state (or primitives). Returning a new object or array from a selector would re-render on every change — derive inside the component instead.

Actions

Every change is a BillAction handled by billReducer (src/lib/bill/reducer.ts). The reducer is pure and returns the same reference when nothing changed, which the store uses to skip renders, undo entries and writes.

GroupActions
Billbill/title, bill/currency
Peopleperson/add (accepts several names), person/rename, person/remove
Itemsitem/add, item/update, item/remove, item/toggle, item/portions, item/assign, item/assignAllUnassigned
Adjustmentsadjustment/add, adjustment/update, adjustment/toggle, adjustment/remove, service/set
Paymentpayment/plan, payment/paid, settle/toggle, pix/set

Undo and redo

  • Every structural change pushes the previous bill onto a stack (max 60).
  • Text-like edits to the same target within 1.2 s collapse into one step, so undoing a rename doesn't go letter by letter.
  • Ctrl/⌘+Z and Ctrl/⌘+Shift+Z work anywhere outside text fields (where the browser's own undo applies).
  • Removing a person, item or fee shows a toast with Undo, which calls the same global undo.
  • Opening another bill clears both stacks.

Autosave

Writes are debounced by 250 ms and flushed on pagehide and visibilitychange → hidden (the last reliable moment on mobile). Empty bills — no people and no items — are never saved, so opening the app doesn't litter the history.

When another tab saves the bill that's open here, the storage event brings it in if it's newer.

Storage schema

All keys share the splitmize:v2: prefix (src/lib/storage.ts). Every read and write is wrapped so private mode, quota errors or corrupted JSON degrade to "nothing saved" instead of a crash.

KeyValue
splitmize:v2:bill:<id>A full Bill (see src/lib/bill/types.ts).
splitmize:v2:indexBillSummary[] — title, dates, currency, total and people for the history list, newest first.
splitmize:v2:activeId of the bill to reopen.
splitmize:v2:recent-peopleUp to 16 names, most recent first, offered as quick-add chips.
splitmize:v2:recent-itemsUp to 80 item names, offered as suggestions in the item field.
splitmize:v2:prefs{ currency?, servicePercent? } — defaults for new bills.
splitmize:v2:themelight / dark (absent = follow the system).
splitmize:v2:migrated-v1Timestamp of the localStorage migration below.
splitmize:v2:migrated-sqliteTimestamp of the SQLite migration below.

Migrating from version 1

There were two generations of 1.x storage. Both are imported automatically, in the background, the first time 2.0 loads — and neither is modified or deleted.

1.0: localStorage sessions

Splitmize 1.0 stored sessions as splitmizeSession_<id> with people and items keyed by name. On first load, the store converts every such session with migrateV1 (src/lib/bill/migrate.ts):

  • names become ids, consumptionMap becomes shares;
  • serviceCharge becomes a service adjustment (keeping who paid it);
  • each extra fee becomes a percent or fixed/equal adjustment for everyone — the old behaviour;
  • payments[name].paid becomes settled[personId];
  • locale date strings ("14/11/2024 21:40") are parsed day-first.

Sessions with no people and no items (v1 created one every time the app opened) are skipped. The old keys are left untouched, so nothing is lost if something goes wrong; a toast tells the user how many bills were brought over.

1.1: SQLite in IndexedDB

Splitmize 1.1 (December 2025) moved history to a SQLite database run by sql.js and saved as one file in IndexedDB (splitmize_sqlite → store files → key main), with global catalogs of people and item names.

src/features/bill/legacy-sqlite.ts opens that IndexedDB database without creating it (an upgrade event means it didn't exist, so the request is aborted). Only when the file is there does it load sql.js and public/sql-wasm.wasm (~690 kB) — new visitors never download them. importLegacyDatabase in src/lib/bill/migrate-sqlite.ts then:

  • reads both 1.1 schemas (per-session rows, and the later catalog-backed rows) into the 1.0 in-memory shape and runs the same migrateV1 converter;
  • reads English sessions' dates month-first (12/8/25, 9:40 PM), falling back to the row's created_at;
  • turns the people catalog into recent names (quick-add chips) and the item catalog into suggestions for the item field.

Legacy bills get a stable id derived from the old session id (legacyBillId), so a session present both in localStorage and in SQLite becomes one bill, and a retry overwrites instead of duplicating. If the import fails (for example offline before the wasm is cached), the flag stays unset and it runs again on the next visit.

The test suite builds real 1.1 databases from the original schema (src/lib/__tests__/fixtures/legacy-sqlite-schema.ts) and checks the converted totals cent by cent.

Initialization and hydration

The server renders /split with a deterministic placeholder bill, and the first client render uses the same snapshot (getServerSnapshot), so hydration always matches. billStore.init(locale) then runs in an effect: migrate, load the active bill (or create one with a currency guessed from the page language and browser region), and flip ready. Until then the workbench shows a skeleton.

Editar esta página no GitHub