From d42b12bebd94334061406b0610899c47ca671e0c Mon Sep 17 00:00:00 2001 From: Developer Date: Sat, 21 Nov 2026 16:01:12 -0600 Subject: [PATCH] test: the shops under load (1500 lines, 200 items, a 100-line cart, 300 sold back, a 1000-line shelf in the browser); fix: a long shelf drawn 200 rows at a time and filtered behind the typing, a catalogue saved 100 rows a statement --- CHANGELOG.md | 2 + README.md | 8 +- backend/__tests__/shop_stress.test.js | 142 ++++++++++++++++++ backend/shops/catalogueDb.js | 16 +- e2e/COVERAGE.md | 1 + e2e/README.md | 1 + e2e/tests/shop-stress.spec.ts | 72 +++++++++ frontend/src/components/ShopWindow.tsx | 38 ++++- .../components/__tests__/ShopWindow.test.tsx | 71 +++++++++ 9 files changed, 337 insertions(+), 14 deletions(-) create mode 100644 backend/__tests__/shop_stress.test.js create mode 100644 e2e/tests/shop-stress.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f5f8a27c..fd01ce0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -793,6 +793,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Changed +- **Long shop shelves stay quick.** A shelf with hundreds of lines now shows 200 at a time, with more as you scroll down, or press SHOW MORE. A line says how many there are, and filtering and sorting still cover every line. Typing in the filter no longer waits for the list to redraw. On a 1000-line shelf, sorting went from about 0.4 s to 0.15 s, and opening it from 0.6 s to 0.26 s. Saving a big catalogue is about five times faster. - **The initiative tracker for a GM running several fights.** The tracker window now opens beside the INITIATIVE menu instead of on top of it, so ACTIVE COMBATS stays in view and the GM can jump from fight to fight with the tracker open. The menu's ACTIVE COMBATS, each COMBAT #n and the scene name on the tracker were drawn in the theme's border colour and could hardly be read in any theme; they now use its text colour. Jumping to a fight whose building has lost its battle map says NO_BATTLE_MAP_FOR_THAT_SCENE instead of doing nothing. Whose turn it is is also announced to screen readers. All found by new browser journeys: one fight with two players from START to END, two fights at once with the GM jumping between them, and one fight spread over two scenes. - **The tracker counts ROUNDs in Generic and custom systems.** Its counter read TURN 3, though it counts laps of the whole order, which are rounds; Cities Without Number and Cyberpunk RED already said ROUND. It now says ROUND 3, a custom system's own word for a round where it renamed one (the WORDS page's ROUND, apart from its TURN), and Shadowrun still counts PASSes. - **ID.EXE's conditions fold away.** The HEALTH folder shows a token's conditions as chips only. Clicking one opens it underneath with its rounds left, what it does and what it changes, and TAKE OFF for whoever can change the token, in place of the small ×. One is open at a time, and CLOSE or Escape folds it away again. Players looking at someone else's token can still open a chip to read what it means. @@ -918,6 +919,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Under the hood +- **A stress test for the shops.** 200 items and a 1500-line catalogue, saved, sent to players, bought from with a 100-line cart and sold to with 300 lines at once, each within a time limit; and a 1000-line shelf opened, filtered and sorted in a real browser. - **Condition rolls asked of the player, or the GM for an NPC, on the server (8a9a2).** A condition's EACH TURN set to be rolled by the player is now asked of them when it fires (and of the GM for an NPC), said in the dice log, and kept until rolled, even across a reload. Rolled, it does what the table's roll would and the log says who rolled it ("rolled by KES", "rolled by the GM"). Only that player or the GM may roll a player's, and only the GM an NPC's; two clicks roll it once. An ask goes when its condition comes off, when a newer turn asks again, or when the fight ends. Where a token is in two fights, the log names the scene. The ROLL buttons on the sheet and the tracker come with 8a9c. - **Conditions on initiative turns, on the server (8a9a).** A condition can now do up to three things on initiative turns: at the start or end of its turn, or of the round, it rolls DAMAGE, HEAL, a save that takes it off (ROLL TO END), or a roll for the log. Damage and healing change the token's HP on their own unless the GM chooses to apply them by hand, and every roll is a line in the dice log saying whose, what, when, who rolled it and what it did. A condition can also end AT THE END OF ITS NEXT TURN. NEXT fires them in the agreed order (the turn ending, the round ending, the countdown, the round starting, the next turn starting), a new BEGIN starts round 1, and the table can switch them off. The builder's boxes, the tracker's BEGIN button, the GAME tab's switch and asking a player to roll come in the next pieces. - **What is worn, added up by column (8a5b).** Formulas can read what a character's worn items have in a NUMBER column of their type, added together: @armor_defense is the DEFENSE of everything worn of type ARMOR, so AC can be 10 + @armor_defense + @agi_mod and follow the armor as it goes on and off. Each worn item counts once, as its line has it; a line made by hand is never worn. diff --git a/README.md b/README.md index bee17537..d6b03681 100644 --- a/README.md +++ b/README.md @@ -423,7 +423,7 @@ CITY_NET/ │ │ ├── catalogueParse.js # Reads a catalogue a GM pasted or uploaded: CSV, TSV or JSON, real RFC-4180 quoting, per-line problems rather than exceptions. The only reader - the preview is a round trip to it; a section per item type (8a7a1): [GUNS], [gun] or [MELEE WEAPONS] is lines of the system's own type, a type winning over a shelf of its name, each column read as it holds (numbers, PICK ONE's own word) and checked as the builder checks an item's, a row that doesn't fit left out and said, blanks kept and noted once a row; a section that is neither a type nor a shelf said, its rows not saved │ │ ├── catalogueStore.js # Uploaded catalogues in memory, added on top of the built-in ones, never replacing them. Holds one system at a time, and consults the built-in book only when that system is CWN - every other game's shops carry only what their GM uploaded. Requires nothing, so priceOf stays synchronous and the lot stays importable from a frontend test │ │ ├── ownItems.js # The game's own items on the shelves (8a7a3a; decided 2026-11-21): each priced and IN SHOPS a line of its type's catalogue, its values and words as fields; the names of those turned off. Pure, worked out once per definition. A catalogue file held against them (againstItems, 8a7a3c1): an exact copy of an item left out, one kept out of the shops left out, one of an item's name overruling it, and how many sell themselves besides; the items turned off with a price, bought back by a shop of their type (8a7a3c2). The running game's own items (8a7a3a, ownItems.js, set by the sockets) sit under the uploaded lines: a line uploaded with an item's name wins, an item turned off keeps a line of its name off the shelves -│ │ └── catalogueDb.js # The only piece that knows uploaded catalogues live in SQLite. A save replaces one catalogue wholesale, in a transaction +│ │ └── catalogueDb.js # The only piece that knows uploaded catalogues live in SQLite. A save replaces one catalogue wholesale, in a transaction, a hundred rows a statement (8n3: a 1500-line save took a round trip a row) │ ├── tokens/ │ │ ├── conditions.js # A token's conditions as stored ([{ id, left }]): read safely, checked against what the running system offers (one twice, an unknown one, rounds out of 1 to 99 refused by name; one that ends after rounds starting at its own), shown to everyone without the rounds left, a hidden one (a house rule off) kept as it was, and counted down a round at a time for a combat's tokens (tickCombat), coming off at none; `started` kept for one ending AT THE END OF ITS NEXT TURN, through an edit too (8a9a) │ │ ├── poolHealth.js # One pool of hit points changed by an amount (8a9a): TEMP first, never below 0 nor past MAX; the HEALTH route and a condition's EACH TURN alike @@ -606,6 +606,7 @@ CITY_NET/ │ ├── shop_buy_sockets.test.js # Buying through the socket as a cart of one, the old buy handler's cases moved across whole │ ├── shop_sell_sockets.test.js # Selling through the socket as a cart with nothing to buy, the old sell handler's cases moved across whole │ ├── shop_items_on_sale.test.js # The game's own items on the shelves (8a7a3a): a price, its own or its type's PRICE column's; IN SHOPS, one saved before it by its price; checked and carried by the system file; the lines they make; under the uploads in the store (a line of an item's name wins, one turned off never sold); bought, sold back at the BUYBACK rate, not again in GIVE's type folders; a catalogue file held against them, its preview and its save (8a7a3c1) +│ ├── shop_stress.test.js # The shops under load (8n3): 200 items and a 1500-line catalogue previewed and saved, every catalogue sent to a player (its size said), a 100-line cart checked out and 300 lines sold back at once, each in time and each answer right │ ├── shop_typed_lines.test.js # Lines of an item type sold and given (8a7a2): SOLD AT, the General Store unsaid, checked and carried by the system file; a typed line placed and stacked only onto the same thing untouched; bought at a shop that sells the type and refused at one that doesn't, sold back at exactly the app's 45%, given from GIVE │ ├── shop_catalogue_types.test.js # A catalogue section per item type (8a7a1): by name, one or id in any case, spaces, columns by name; a value that doesn't fit said in the builder's words; blanks one note; a type over a shelf of its name; JSON; a section that is neither said; through the sockets, the preview by the type's name, saved under it, sent to players │ ├── shop_catalogue_parse.test.js # Reading a GM's catalogue: commas inside names, semicolons from a European Excel, a byte-order mark, a price with its symbol; problems per line, never a throw @@ -876,7 +877,7 @@ CITY_NET/ │ │ │ ├── SheetRenderer.tsx # Template-driven sheet renderer (any game system); sections may declare groupSize to collapse repeated entries, rowHidden to drop a row of one, and fields may declare presetFill (one select writing a whole stat block, as one save), fullWidth, startsRow or the tag_list type (an add/remove list stored as JSON) — only entries holding data render, plus one blank and a reveal button, so what you filled in comes back after a reload without anything storing that it should; MORTALLY WOUNDED / FRAIL banners, ability_list layout (dynamic add/remove rows with attr dropdown, cost, die, roll), hidden-tab gating; a ranked stat's picker with its worth beside it, starting at the lowest (7f1c1); a SPEND XP section where the sheet has one (7f2c1); IMPROVE BY USE's mark beside each stat that improves (7f3b); the conditions on the token said under a number they change, a stat's box and a skill's line, a typed stat's changed value the big number, clicked to edit what is typed (8a5e3); CARRYING (CarryingBlock) at the top of the tab a custom system's INVENTORY is on (8a6a) │ │ │ ├── ImportSheetDialog.tsx # Sheet import — fillable PDF, a Companion code (Cyberpunk only), or pasted JSON / stat block, plus a download of the blank form that upload expects; for a custom system the blank PDF and its JSON template side by side and UPLOAD JSON FILE; its boxes in the theme's colors, drawn inside the theme │ │ │ ├── CyberwareWindow.tsx # The body diagram and the table. Wires are measured from the live layout, since panels grow as chrome is added and where a wire starts is only knowable once laid out. Portalled to the body — rendered in place it inherits the character sheet's bounds and half the diagram is clipped away -│ │ │ ├── ShopWindow.tsx # A building that trades, on the terminal layout: BUY, SELL and CART folders, the building in the corner. One shelf tab per catalogue the shop sells, with the filter above the list. CWN shelves come from the book with CWN's own placement rules; every other system's are what the GM uploaded, placed through shopPlacement. + CART on either list fills the cart; CHECK OUT settles it on the server in one go, then places what was bought one at a time and shows a receipt. A checkout nobody answers gives up after 15 seconds. In a custom system's currencies, every price is in its catalogue's currency and the cart totals, asks and receipts per currency; never offers to buy an item installed (7e4c). A shelf of an item type (8a7a2) is named as the type and shows the type's own columns, and a line bought from it lands as one of the type +│ │ │ ├── ShopWindow.tsx # A building that trades, on the terminal layout: BUY, SELL and CART folders, the building in the corner. One shelf tab per catalogue the shop sells, with the filter above the list. CWN shelves come from the book with CWN's own placement rules; every other system's are what the GM uploaded, placed through shopPlacement. + CART on either list fills the cart; CHECK OUT settles it on the server in one go, then places what was bought one at a time and shows a receipt. A checkout nobody answers gives up after 15 seconds. In a custom system's currencies, every price is in its catalogue's currency and the cart totals, asks and receipts per currency; never offers to buy an item installed (7e4c). A shelf of an item type (8a7a2) is named as the type and shows the type's own columns, and a line bought from it lands as one of the type. A long shelf drawn 200 rows at a time, more on scrolling or SHOW MORE, and filtered a step behind the typing (8n3: a 1000-line shelf took 400 ms to sort in Chromium) │ │ │ ├── shopCart.ts # The cart's arithmetic, pure: one line per thing bought (with a count), one per thing sold, totals both ways and the net, the sell half grouped as the server takes it, and what the character would carry afterwards. What the player is shown - the server works the money out again. In a custom system's currencies, one total per currency with its shortfall and the ways it may be covered │ │ │ ├── TerminalWindow.tsx # The shared terminal layout: the picture and folders down the left, the open folder on the right, buttons along the bottom. Folders switch by click or the arrow keys, and one can blink for attention; the panel is as tall as what it holds, or in 'list' mode keeps its top still while a table scrolls under it. What goes in the folders is the caller's │ │ │ ├── TokenWindow.tsx # A token's window on TerminalWindow: INFO (headed with the player's name, their public handle and role first), HEALTH, QUICK ACTIONS on your own token, GM NOTES for the main admin on NPCs. Health panels and the GM's defense and initiative sections come in as slots; which ones a viewer gets is tokenView() @@ -1075,7 +1076,7 @@ CITY_NET/ │ │ │ ├── BuildingExtrasEditor.test.tsx # The photo and GM notes staged until UPDATE_DATA_POINT, sending exactly what was staged, reporting every failure, never overwriting notes it couldn't load │ │ │ ├── CatalogueWindow.test.tsx # Adding to the shops: SAVE only ever stores text that was previewed; DOWNLOAD ITEMS and the item lines and near misses in a preview, none on a game without items (7e3c); a type's section by its name, its problem, a blank noted, the save (8a7a1); the file held against the game's items: the count, overrules, left out (8a7a3c1) │ │ │ ├── EmptyShopSteps.test.tsx # An empty shop telling the GM how to stock it, where the shop is set up -│ │ │ ├── ShopWindow.test.tsx # The shop: what a building carries, and nothing reaching a sheet until the server says the account was charged +│ │ │ ├── ShopWindow.test.tsx # The shop: what a building carries, and nothing reaching a sheet until the server says the account was charged; a 1000-line shelf paged, filtered and sorted in time, the last page's count, 300 lines of gear on SELL (8n3) │ │ │ ├── CyberwareWindow.cybermods.test.tsx # Fitting a cyberware mod the way a player reaches it, the UI honouring the server's fitting rules │ │ │ ├── SheetCyberware.test.tsx # The sheet showing what the chrome does, so a correct effects layer is actually read │ │ │ ├── InventorySection.test.tsx # The inventory table editing one field cleanly, though every keystroke rewrites the whole list @@ -1558,6 +1559,7 @@ CITY_NET/ │ ├── catalogue-and-items.spec.ts # A catalogue held against the game's items (8a7a3c1): the Pistol overruling 200 → 260, an exact Cutlass and a ring kept out of the shops left out, ALSO ON SALE FROM ITEMS; saved, the game's Cutlass behind a # in DOWNLOAD CURRENT │ ├── shop-typed-lines.spec.ts # Lines of an item type at the table (8a7a2): a [GUNS] catalogue saved, the General Store's GUNS shelf in the type's columns, a Pistol bought and landing as a Gun with its damage and ammo, another given from GIVE.EXE stacked onto it │ ├── shop-items-on-sale.spec.ts # The game's own items at the table (8a7a3a): a Pistol priced on ITEMS, no catalogue saved, on the General Store's WEAPONS shelf at 200 and a ring kept out of the shops not; bought, a Weapon on the gear with its damage; sold back from the window at the store's 50%, 900 left and off the sheet (8a7a3c2) +│ ├── shop-stress.spec.ts # A 1000-line shelf in the browser (8n3): saved, opened 200 at a time, scrolled for more, filtered as typed and sorted both ways, each in time, the times logged │ ├── shop-items-catalogue.spec.ts # Items in the shops (7e3c): DOWNLOAD ITEMS, a price filled in, the preview naming the ring and a near miss, saved, on sale in GIVE.EXE's catalogue │ ├── sheet-level-up.spec.ts # Going up a level (7d2b): XP reaches it and the player goes up, one class of two, the rest carrying over; milestone's level given by the GM and taken by the player; LEVEL_DOWN; an uploaded sheet bringing its XP (7d2c); LEVEL_UP.EXE: which class, left and come back to, what it unlocks, FINISH (7d3a); a pick the new level opens, then a new class (7d3b) │ ├── sheet-level-record.spec.ts # What each level gained (7d7b2): the GM clears a past roll, the player rolls it again, the maximum follows; the GM sets one; an uploaded HP MAX the base, one line, cleared by the GM (7d7c) diff --git a/backend/__tests__/shop_stress.test.js b/backend/__tests__/shop_stress.test.js new file mode 100644 index 00000000..c00bf9c6 --- /dev/null +++ b/backend/__tests__/shop_stress.test.js @@ -0,0 +1,142 @@ +/** + * The shops under load (8n3; asked by the user 2026-11-21, "a stress test for the store like having 1000+ items"): a game with + * 200 items of its own (the most a system holds) and a catalogue of 1500 lines across three types and a shelf. The file + * previewed and saved; every catalogue sent to a player; a cart of 100 lines checked out; 300 lines of gear sold back at once. + * Each within about twenty times what it took on a desk (CI is several times slower), and each answer still right at that size. + */ + +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import { createRequire } from 'module'; +import jwt from 'jsonwebtoken'; +import { makeTestDb, get, run } from './helpers/testDb.js'; +import { untilValue, drain } from './helpers/until.js'; + +process.env.JWT_SECRET = 'test-secret'; +const require_ = createRequire(import.meta.url); +const store = require_('../shops/catalogueStore'); +const runtime = require_('../systemBuilder/runtime'); +const { checkDefinition } = require_('../systemBuilder/definition'); +const socketsFactory = (await import('../sockets/index.js')).default; + +const ID = 'sys_stressstressstre'; +const LINES = 1500; +const ITEMS = 200; +const TYPES = [ + { id: 'weapons', label: 'WEAPONS', one: 'Weapon', columns: [{ id: 'damage', label: 'DAMAGE', kind: 'damage' }, { id: 'ammo', label: 'AMMO', kind: 'count' }, { id: 'price', label: 'PRICE', kind: 'number' }] }, + { id: 'armor', label: 'ARMOR', one: 'Armor', columns: [{ id: 'defense', label: 'DEFENSE', kind: 'number' }, { id: 'grade', label: 'GRADE', kind: 'pick', options: ['LIGHT', 'HEAVY'] }] }, + { id: 'potions', label: 'POTIONS', one: 'Potion', columns: [{ id: 'heals', label: 'HEALS', kind: 'dice' }] }, +]; +/** 200 items, a third of each type, every one priced and IN SHOPS. */ +const ITEM_LIST = Array.from({ length: ITEMS }, (_, i) => { + const t = TYPES[i % 3]; + const values = t.id === 'weapons' ? { damage: '1d6', ammo: 6, price: 100 + i } : t.id === 'armor' ? { defense: 1 + (i % 5), grade: 'LIGHT' } : { heals: '2d4' }; + return { id: `own_${i}`, label: `Own Thing ${i}`, type: t.id, values, ...(t.id === 'weapons' ? {} : { price: 50 + i }), in_shops: true }; +}); +const SYSTEM = { format: 1, name: 'Stress', core: { health: { model: 'pool' } }, stats: [{ id: 'abilities', label: 'ABILITIES', stats: [{ id: 'might', label: 'Might' }] }], items: { types: TYPES, list: ITEM_LIST } }; + +/** 1500 lines: 400 of each type and 300 of GEAR (a shelf: this game has no type called GEAR). */ +const FILE = [ + '[WEAPONS]', 'name, price, damage, ammo', + ...Array.from({ length: 400 }, (_, i) => `Gun ${i}, ${10 + i}, 1d${4 + (i % 3) * 2}, ${i % 12}`), + '[ARMOR]', 'name, price, defense, grade', + ...Array.from({ length: 400 }, (_, i) => `Vest ${i}, ${20 + i}, ${i % 9}, ${i % 2 ? 'HEAVY' : 'LIGHT'}`), + '[POTIONS]', 'name, price, heals', + ...Array.from({ length: 400 }, (_, i) => `Tonic ${i}, ${5 + i}, ${1 + (i % 4)}d4`), + '[gear]', 'name, price', + ...Array.from({ length: 300 }, (_, i) => `Thing ${i}, ${1 + i}`), +].join('\n'); + +/** Milliseconds a step took. */ +const timed = async (work) => { const t = performance.now(); const out = await work(); return { out, ms: performance.now() - t }; }; + +let db; +let goods; +const boot = async (who, admin) => { + const emitted = []; + let connect; + const io = { on: (e, cb) => { if (e === 'connection') connect = cb; }, emit: (event, data) => emitted.push({ event, data }), to: () => ({ emit: () => {} }) }; + socketsFactory(io, db, { elevatedUsers: new Set(), emitUpdate: vi.fn(), recordAction: vi.fn() }); + const handlers = {}; + connect({ id: `s-${who}-${Math.random()}`, on: (e, fn) => { handlers[e] = fn; }, emit: (event, data) => emitted.push({ event, data }), broadcast: { emit: () => {} }, use: () => {}, join: () => {} }); + handlers.identify(admin ? { userName: who, isAdmin: true, token: jwt.sign({ id: 1, username: who, role: 'admin', isTemporary: false }, 'test-secret') } : who); + await drain(db); + return { handlers, emitted }; +}; +const last = (emitted, event) => untilValue(() => [...emitted].reverse().find((e) => e.event === event), Boolean, { label: event, timeout: 30_000 }); +const report = {}; + +beforeAll(async () => { + store.clear(); + db = await makeTestDb(); + await run(db, `CREATE TABLE IF NOT EXISTS shop_catalogues (system TEXT NOT NULL, catalogue TEXT NOT NULL, id TEXT NOT NULL, + name TEXT NOT NULL, price REAL NOT NULL DEFAULT 0, fields TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (system, catalogue, id))`); + const def = JSON.stringify(SYSTEM); + await run(db, 'INSERT INTO custom_systems (id, name, draft, published, version) VALUES (?, ?, ?, ?, 1)', [ID, 'Stress', def, def]); + await new Promise((resolve) => runtime.load(db, resolve)); + await run(db, "INSERT INTO global_settings (key, value) VALUES ('game_system', ?)", [ID]); + goods = (await run(db, "INSERT INTO locations (name, x, y, z, shape, building_type) VALUES ('Goods', 0, 0, 0, 'box', 'general_store')")).lastID; + await run(db, 'INSERT INTO bank_accounts (username, system, balance, debt) VALUES (?, ?, 100000000, 0)', ['kes', ID]); + await run(db, 'INSERT INTO character_sheets (username, system, data, is_npc) VALUES (?, ?, ?, 0)', ['kes', ID, JSON.stringify({ inventory: '[]' })]); +}, 60_000); + +describe('the shops under load', () => { + it('the game itself is sound: 200 items, three types, no problems', () => { + expect(checkDefinition(SYSTEM).problems).toEqual([]); + }); + + it('a 1500-line file previewed, then saved, each in time, every line read', async () => { + const gm = await boot('gm', true); + const preview = await timed(async () => { gm.handlers.previewCatalogue({ text: FILE }); return (await last(gm.emitted, 'cataloguePreview')).data; }); + expect(preview.out.problems).toEqual([]); + expect(preview.out.summary.map((s) => [s.label ?? s.catalogue, s.count])).toEqual([['WEAPONS', 400], ['ARMOR', 400], ['POTIONS', 400], ['gear', 300]]); + expect(preview.out.items.onSale).toBe(ITEMS); + const saved = await timed(async () => { gm.handlers.saveCatalogue({ text: FILE }); return (await last(gm.emitted, 'catalogueSaved')).data; }); + expect(saved.out.ok).toBe(true); + expect((await get(db, 'SELECT COUNT(*) AS n FROM shop_catalogues WHERE system = ?', [ID])).n).toBe(LINES); + report.preview = Math.round(preview.ms); + report.save = Math.round(saved.ms); + expect(preview.ms).toBeLessThan(1_000); + expect(saved.ms).toBeLessThan(3_000); + }, 60_000); + + it('every catalogue sent to a player in time: 1500 lines and 200 items, the payload\'s size said', async () => { + const kes = await boot('kes', false); + const sent = await timed(async () => { kes.emitted.length = 0; kes.handlers.requestCatalogues(); return (await last(kes.emitted, 'catalogues')).data; }); + const lines = Object.values(sent.out.entries).flat().filter((e) => e.source === 'uploaded' || e.source === 'items'); + expect(lines).toHaveLength(LINES + ITEMS); + report.send = Math.round(sent.ms); + report.payloadKb = Math.round(JSON.stringify(sent.out).length / 1024); + expect(sent.ms).toBeLessThan(1_000); + // Under a megabyte, as everything sent to a browser here is. + expect(JSON.stringify(sent.out).length).toBeLessThan(1_000_000); + }, 60_000); + + it('a cart of 100 lines checked out in time, each at its price', async () => { + const kes = await boot('kes', false); + const buys = [ + ...Array.from({ length: 50 }, (_, i) => ({ catalogue: 'type:weapons', itemId: `gun_${i}`, qty: 1 })), + ...Array.from({ length: 50 }, (_, i) => ({ catalogue: 'type:weapons', itemId: `item:own_${i * 3}`, qty: 1 })), + ]; + const done = await timed(async () => { kes.handlers.checkoutShop({ locationId: goods, buys }); return (await last(kes.emitted, 'shopCheckout')).data; }); + expect(done.out.ok, JSON.stringify(done.out).slice(0, 300)).toBe(true); + const expected = Array.from({ length: 50 }, (_, i) => 10 + i).reduce((a, b) => a + b, 0) + Array.from({ length: 50 }, (_, i) => 100 + i * 3).reduce((a, b) => a + b, 0); + expect(done.out.buyTotal).toBe(expected); + report.checkout = Math.round(done.ms); + expect(done.ms).toBeLessThan(1_000); + }, 60_000); + + it('300 lines of gear sold back at once, in time, each paid at the shop\'s rate', async () => { + const gear = Array.from({ length: 300 }, (_, i) => ({ name: `Gun ${i}`, qty: 1, enc: '', bundled: false, carry: 'stowed', location: '', type: 'weapons', values: { damage: '1d4', ammo: 0 } })); + await run(db, 'UPDATE character_sheets SET data = ? WHERE username = ?', [JSON.stringify({ inventory: JSON.stringify(gear) }), 'kes']); + const kes = await boot('kes', false); + const sells = gear.map((_, i) => ({ catalogue: 'type:weapons', id: `gun_${i}`, qty: 1 })); + const done = await timed(async () => { kes.handlers.checkoutShop({ locationId: goods, buys: [], sells }); return (await last(kes.emitted, 'shopCheckout')).data; }); + expect(done.out.ok, JSON.stringify(done.out).slice(0, 300)).toBe(true); + // The app's 45% of each, rounded down line by line. + expect(done.out.payout).toBe(gear.reduce((n, _, i) => n + Math.floor(((10 + i) * 45) / 100), 0)); + report.sellBack = Math.round(done.ms); + expect(done.ms).toBeLessThan(3_000); + // What it took, for the record. + console.log('shop stress (ms, KB):', JSON.stringify(report)); + }, 60_000); +}); diff --git a/backend/shops/catalogueDb.js b/backend/shops/catalogueDb.js index de38eb2e..7b4c98a2 100644 --- a/backend/shops/catalogueDb.js +++ b/backend/shops/catalogueDb.js @@ -58,6 +58,9 @@ const refresh = (db, system, cb = () => {}) => { }); }; +/** Rows written a statement when a catalogue is saved (8n3). */ +const INSERT_BATCH = 100; + const q = (db, sql, params = []) => new Promise((resolve, reject) => { db.run(sql, params, (err) => (err ? reject(err) : resolve())); }); @@ -81,13 +84,16 @@ const replaceCatalogues = (db, system, sections, cb) => { try { for (const [catalogue, entries] of Object.entries(sections || {})) { await q(db, 'DELETE FROM shop_catalogues WHERE system = ? AND catalogue = ?', [system, catalogue]); - for (const entry of entries || []) { - if (!entry || !entry.id) continue; + // A hundred rows a statement (8n3): the shop stress test found a 1500-line file took one round trip a row, its + // save as slow as the database's answers times 1500. Six values a row keeps each well under SQLite's 999. + const rows = (entries || []).filter((entry) => entry && entry.id); + for (let at = 0; at < rows.length; at += INSERT_BATCH) { + const batch = rows.slice(at, at + INSERT_BATCH); await q(db, `INSERT INTO shop_catalogues (system, catalogue, id, name, price, fields) - VALUES (?, ?, ?, ?, ?, ?)`, - [system, catalogue, entry.id, String(entry.name || ''), - Number(entry.price) || 0, JSON.stringify(entry.fields || {})]); + VALUES ${batch.map(() => '(?, ?, ?, ?, ?, ?)').join(', ')}`, + batch.flatMap((entry) => [system, catalogue, entry.id, String(entry.name || ''), + Number(entry.price) || 0, JSON.stringify(entry.fields || {})])); } } await q(db, 'COMMIT'); diff --git a/e2e/COVERAGE.md b/e2e/COVERAGE.md index 94aa3c4a..06e77c10 100644 --- a/e2e/COVERAGE.md +++ b/e2e/COVERAGE.md @@ -33,6 +33,7 @@ panel), so a control that looks fine but does nothing is caught for all of them. | NPC tiers off | | `parts_tiers` | | **GAP**, with family 8 (NPC tiers): the tier picker is on an NPC token in the 3D map | | GIVE ITEM and shop catalogues | a catalogue typed in, an item given with a note | `shops_give`, `shop_catalogue_*` | `player-journey`, `shop-cart-items` (a catalogue saved while a player is online, bought by them through the cart, 8n1), `shop-cart` (CWN's book: bought and sold back, 8n1), `give-item` (a ring and two ropes given, on the sheet as bought ones are, in GIVEN, 8n2) | **AT THE TABLE** | | Shop catalogues by item type | a section per item type (8a7a1), its columns checked, blanks kept | `shop_catalogue_types`, `catalogueTypes` | `catalogue-types`, `shop-typed-lines` (bought at the General Store and given, landing typed, 8a7a2) | **AT THE TABLE** | +| The shops under load | 1000+ lines on a shelf, 200 items, a full cart, a long gear list (8n3); a long shelf drawn 200 rows at a time | `shop_stress`, `ShopWindow` | `shop-stress` | **AT THE TABLE** | | An item type's SOLD AT | the kinds of shop that sell its lines (8a7a2), the General Store where unsaid; set in the builder in 8a7b | `shop_typed_lines`, `typedShelves` | `shop-typed-lines` (unsaid: the General Store) | **AT THE TABLE** unsaid; a kind of shop picked waits for 8a7b's box | | An item's PRICE and IN SHOPS | priced and IN SHOPS, it sells itself at its type's shops (8a7a3a); off, never sold, not even from a file, but bought back at its price by a shop of its type (8a7a3c2); a type's PRICE column read as its price; set on ITEMS under TYPE, NOT SOLD in the list, a new item's price asked for (8a7a3b1); in the ITEMS import and downloads, price and in shops columns (8a7a3b2) | `shop_items_on_sale`, `itemPrice`, `ItemsPage`, `system_builder_items_import`, `itemsImport` | `shop-items-on-sale` (a type's PRICE column; a ring turned off; sold back from the window at 50%), `builder-item-price` (set by clicks), `builder-items-import` (imported priced and IN SHOPS) | **AT THE TABLE** | | A catalogue file held against the game's items | an exact copy of an item left out, an item kept out of the shops left out, one of an item's name overruling it, ALSO ON SALE FROM ITEMS (8a7a3c1) | `shop_items_on_sale`, `CatalogueWindow` | `catalogue-and-items` | **AT THE TABLE** | diff --git a/e2e/README.md b/e2e/README.md index c36341f5..1689439c 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -216,6 +216,7 @@ kept; the job itself stops at 30 (`timeout-minutes`), for a hang outside the tes | `tests/give-item.spec.ts` | GIVE.EXE at the table, a safety net before 8a7 (8n2). A custom system's catalogue from DOWNLOAD ITEMS, its ring priced and a rope added; the player opens their sheet once; the GM gives the ring, then two ropes: found in ITEMS, the player ticked in TO, GIVE 2 × ROPE TO 1. Free, and on the sheet as bought ones are, the ring known as the item it is; GIVEN lists both | | `tests/shop-cart.spec.ts` | The shop at the table, a safety net before 8a7 (8n1). Cities Without Number's Gun Shop from the book: the GM pays the player 1,000 from PAYROLL.EXE in the GAME tab's BANK, the player opens the shop from QUICK_ACCESS, its header says 1,000cr; a Light Pistol into the cart and CHECK OUT, 800cr and the pistol on the sheet; SELL, the pistol into the cart and CHECK OUT, 890cr (45% back) and the pistol gone | | `tests/shop-cart-items.spec.ts` | A custom system's General Store at the table (8n1). The GM starts a catalogue from DOWNLOAD ITEMS, the ring priced at 500 and a rope at 5, and saves it while the player is online (this found the player's shops empty: fixed); pays the player 1,000; the player's store has both lines, both bought through the cart, the receipt saying 505 paid and 495 left; both in the inventory, the ring known as the item it is, to WEAR and ATTUNE | +| `tests/shop-stress.spec.ts` | The shop under load in a real browser (8n3, the user asked for a 1000+ item stress test). A GUNS shelf of 1000 lines saved from SHOP_CATALOGUES; the player opens it (200 rows and SHOWING 200 OF 1000), scrolls to the end for 200 more, filters it key by key to Gun 99 (11 rows, found past the first page), clears it and sorts by PRICE both ways (Gun 0 and Gun 999 at the top in turn). Each step under 5 s; on a desk each took under half a second, and the times are logged. | | `tests/shop-items-on-sale.spec.ts` | The game's own items at the table (8a7a3a), found by the user testing 8a7a2. A game whose WEAPONS type has a PRICE column, its Pistol priced 200 and a Ring of Might kept out of the shops, and no catalogue saved: the player's General Store has the Pistol on its WEAPONS shelf at 200 with its damage, never the ring, and no empty-shop steps; bought through the cart, it lands on the gear as a Weapon with its damage; sold back from the window at the store's 50% (8a7a3c2), 900 left and off the sheet. Run once without the window's fix, it fails at that balance. | | `tests/shop-typed-lines.spec.ts` | Lines of an item type at the table (8a7a2). A game with a GUNS type (DAMAGE, AMMO) and no SOLD AT, so sold at the General Store: the GM saves a [GUNS] catalogue with a Pistol and pays the player 1000; the player's General Store has a GUNS tab saying GOES INTO YOUR GEAR AS A GUN, sortable by DAMAGE and AMMO; the Pistol bought through the cart lands on the sheet as a Gun with its damage and ammo, and one given from GIVE.EXE stacks onto it. | | `tests/catalogue-and-items.spec.ts` | A catalogue file held against the game's own items (8a7a3c1). WEAPONS selling a Pistol at 200 and a Cutlass at 120 by themselves, a Ring of Might kept out of the shops: a file with the Pistol at 260, the Cutlass exactly as it is, the Ring and a Hand Cannon previews as WEAPONS ×2, ALSO ON SALE FROM ITEMS: 2 (1 overruled by this file), the Pistol overruling 200 → 260, the Cutlass and the Ring left out and why; saved as WEAPONS ×2, DOWNLOAD CURRENT has the Pistol at 260, the Hand Cannon and the game's Cutlass behind a #, no Ring. | diff --git a/e2e/tests/shop-stress.spec.ts b/e2e/tests/shop-stress.spec.ts new file mode 100644 index 00000000..c725e028 --- /dev/null +++ b/e2e/tests/shop-stress.spec.ts @@ -0,0 +1,72 @@ +import { test, expect } from '@playwright/test'; +import { signInAsGm, signInAsPlayer, gmToken, asGm, runningSystem, approvedPlayer, openGameSystem } from './helpers'; +import { playerToken } from './shops'; + +// The shop under load in a real browser (8n3; the user, 2026-11-21: "a stress test for the store like having 1000+ items"). +// A GUNS shelf of 1000 lines saved from SHOP_CATALOGUES; the player opens it (drawn 200 at a time, more on scrolling), filters +// it as they type and sorts it by PRICE both ways, each within a time limit with room for CI, the right rows each time across +// all 1000. The times are logged. + +const SYSTEM = (name: string) => ({ + format: 1, name, core: { health: { model: 'pool' } }, + stats: [{ id: 'abilities', label: 'ABILITIES', stats: [{ id: 'might', label: 'Might' }] }], + items: { types: [{ id: 'guns', label: 'GUNS', one: 'Gun', columns: [{ id: 'damage', label: 'DAMAGE', kind: 'damage' }, { id: 'ammo', label: 'AMMO', kind: 'count' }] }], list: [] }, +}); +const FILE = ['[GUNS]', 'name, price, damage, ammo', ...Array.from({ length: 1000 }, (_, i) => `Gun ${i}, ${10 + i}, 1d${4 + (i % 3) * 2}, ${i % 12}`)].join('\n'); + +test('a 1000-line shelf: saved, opened, filtered as typed and sorted both ways, each in time (8n3)', async ({ page, browser, request }, info) => { + test.setTimeout(240_000); + const again = info.retry ? `_${info.retry + 1}` : ''; + const gm = await gmToken(request); + await runningSystem(request, gm, SYSTEM(`Stressfall${again}`)); + const player = { username: `e2e_stressfall${again}`, password: 'e2e-player-password' }; + await approvedPlayer(request, gm, player); + await playerToken(request, gm, player.username); + const shop = `STRESS_GOODS${again}`; + const made = await asGm(request, gm, 'post', '/api/locations', { name: shop, description: '', shape: 'box', x: 12, y: 0, z: 12, width: 2, height: 2, depth: 2 }); + const typed = await request.patch(`/api/locations/${made.data[0].id}/building-type`, { data: { building_type: 'general_store' }, headers: { Authorization: `Bearer ${gm}` } }); + expect(typed.ok(), await typed.text()).toBe(true); + + // The GM saves the 1000 lines. + await page.setViewportSize({ width: 1280, height: 800 }); + await signInAsGm(page); + await openGameSystem(page); + await page.getByRole('button', { name: 'SHOP_CATALOGUES', exact: true }).click(); + await page.getByLabel('Catalogue text').fill(FILE); + await page.getByRole('button', { name: 'PREVIEW', exact: true }).click(); + await expect(page.getByText('1000 ROWS READ')).toBeVisible({ timeout: 30_000 }); + await page.getByRole('button', { name: 'SAVE', exact: true }).click(); + await expect(page.getByText('Saved: GUNS ×1000. The shops have it now.')).toBeVisible({ timeout: 30_000 }); + + // The player's store. + const context = await browser.newContext({ baseURL: info.project.use.baseURL, viewport: { width: 1280, height: 800 } }); + const mine = await context.newPage(); + await signInAsPlayer(mine, player); + await mine.getByRole('button', { name: 'QUICK_ACCESS', exact: true }).click(); + const list = mine.locator('.quick-access-panel'); + await list.getByText(/DEFINED_STRUCTURES/).click(); + await list.getByText(shop, { exact: true }).click(); + await mine.getByRole('button', { name: 'SHOP', exact: true }).click(); + const window = mine.locator('.win95-window', { has: mine.getByText(`SHOP.EXE · ${shop}`, { exact: true }) }); + const rows = window.getByRole('button', { name: /^Add Gun \d+ to the cart$/ }); + const took: Record = {}; + const time = async (name: string, work: () => Promise) => { const t = Date.now(); await work(); took[name] = Date.now() - t; }; + + await time('open', async () => { await window.getByRole('tab', { name: 'GUNS' }).click({ timeout: 30_000 }); await expect(rows).toHaveCount(200, { timeout: 30_000 }); }); + await expect(window.getByText('SHOWING 200 OF 1000 · SCROLL OR FILTER FOR THE REST')).toBeVisible(); + // Scrolled to the end of the page: 200 more. + await time('scroll', async () => { await rows.last().scrollIntoViewIfNeeded(); await expect(rows).toHaveCount(400, { timeout: 30_000 }); }); + // Typed a key at a time, as a player does. + await time('filter', async () => { await window.getByLabel('Filter stock').pressSequentially('Gun 99'); await expect(rows).toHaveCount(11, { timeout: 30_000 }); }); + await time('clear', async () => { await window.getByLabel('Filter stock').fill(''); await expect(rows).toHaveCount(200, { timeout: 30_000 }); }); + const top = () => rows.first().getAttribute('aria-label'); + const before = await top(); + await time('sort', async () => { await window.getByLabel('Sort by PRICE').click(); await expect.poll(top, { timeout: 30_000 }).not.toBe(before); }); + const first = await top(); + await time('reverse', async () => { await window.getByLabel('Sort by PRICE').click(); await expect.poll(top, { timeout: 30_000 }).not.toBe(first); }); + expect([first, await top()].sort()).toEqual(['Add Gun 0 to the cart', 'Add Gun 999 to the cart']); + console.log('shop stress in the browser (ms):', JSON.stringify(took)); + // Each step took under half a second on a desk (2026-11-21); CI is several times slower. + for (const [step, ms] of Object.entries(took)) expect(ms, step).toBeLessThan(5_000); + await context.close(); +}); diff --git a/frontend/src/components/ShopWindow.tsx b/frontend/src/components/ShopWindow.tsx index d61b5106..b4ae2f43 100644 --- a/frontend/src/components/ShopWindow.tsx +++ b/frontend/src/components/ShopWindow.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import React, { useDeferredValue, useEffect, useState } from 'react'; import { TerminalWindow } from './TerminalWindow'; import { buildingTypeById, shelvedIn, catalogueById, typeLabel, catalogueLabel, itemTypeOfShelf, type ShopStock, @@ -123,6 +123,9 @@ const cell: React.CSSProperties = { const credits = (n: number): string => (n === 0 ? 'N/A' : `${n.toLocaleString()}cr`); /** How long a checkout waits for the server before saying it got no answer. */ +/** How many of a shelf's rows are drawn at a time (8n3): every built-in shelf is shorter, a GM's long catalogue a page at a time. */ +export const SHELF_PAGE = 200; + export const CHECKOUT_TIMEOUT_MS = 15_000; /** Credits with a sign, for the cart: a total can be nothing, or the shop paying you. */ @@ -1383,9 +1386,11 @@ export function ShopWindow({ })(); /** The open shelf, filtered and sorted. Small lists, so done plainly on each render. */ + // What the shelf is filtered by: a step behind what is typed (8n3), so a long shelf never holds up the box being typed in. + const shownFilter = useDeferredValue(filter); const rows: any[] = (() => { if (!shelf) return []; - const q = filter.trim().toLowerCase(); + const q = shownFilter.trim().toLowerCase(); let list = shelf.rows; // The weapon shelf's own narrowing. Both on, or both off, means no opinion. if (shelf.id === 'weapons' && kinds.ranged !== kinds.melee) { @@ -1396,6 +1401,19 @@ export function ShopWindow({ return applySort(list, sort, shelf.columns); })(); + /** + * A long shelf drawn a page at a time (8n3; the shop stress test found a 1000-line shelf took 400 ms to sort and up to + * 360 ms a key to filter in Chromium): the first SHELF_PAGE rows, SHELF_PAGE more on scrolling near the end or SHOW MORE. + * Every row is still there to scroll to or filter for. Back to the first page on another shelf, filter or sort. + */ + const [shownCount, setShownCount] = useState(SHELF_PAGE); + const firstPage = () => setShownCount(SHELF_PAGE); + const showMore = () => setShownCount((n) => n + SHELF_PAGE); + const nearEnd = (e: React.UIEvent) => { + const box = e.currentTarget; + if (shownCount < rows.length && box.scrollTop + box.clientHeight >= box.scrollHeight - 120) showMore(); + }; + /** * Switching shelves clears the sort and the filter. * @@ -1407,6 +1425,7 @@ export function ShopWindow({ setPicked(id); setSort({ key: '', dir: null }); setFilter(''); + firstPage(); setRefused(null); }; @@ -1747,7 +1766,7 @@ export function ShopWindow({ <> setFilter(e.target.value)} + onChange={(e) => { setFilter(e.target.value); firstPage(); }} placeholder={shelf.filterHint} aria-label="Filter stock" style={{ @@ -1768,14 +1787,14 @@ export function ShopWindow({ )} -
+
{Object.entries(shelf.columns).map(([key, col]) => ( - {rows.map((row) => { + {rows.slice(0, shownCount).map((row) => { const key = shelf.rowKey(row); const inCart = cartBuys.find((l) => l.key === cartKey(shelf.id, key))?.qty ?? 0; const canBuy = shelf.buyable ? shelf.buyable(row) : true; @@ -1838,6 +1857,13 @@ export function ShopWindow({ })}
setSort((st) => nextSort(st, key, col.first))} + onClick={() => { setSort((st) => nextSort(st, key, col.first)); firstPage(); }} aria-label={`Sort by ${col.label}`} title="Click to sort — again to reverse, again for the book's own order" style={{ @@ -1789,7 +1808,7 @@ export function ShopWindow({
+ {/* Where the page ends (8n3): how many are drawn, and a button for the rest. */} + {shownCount < rows.length && ( +
+ SHOWING {shownCount} OF {rows.length} · SCROLL OR FILTER FOR THE REST + +
+ )}
{rows.length === 0 && (
diff --git a/frontend/src/components/__tests__/ShopWindow.test.tsx b/frontend/src/components/__tests__/ShopWindow.test.tsx index e0961366..e2b8ad74 100644 --- a/frontend/src/components/__tests__/ShopWindow.test.tsx +++ b/frontend/src/components/__tests__/ShopWindow.test.tsx @@ -2258,3 +2258,74 @@ describe('a shelf of an item type (8a7a2)', () => { expect(JSON.parse(written![1])).toEqual([expect.objectContaining({ name: 'Pistol', qty: 1, type: 'guns', values: { dmg: '2d6', ammo: 6 } })]); }); }); + +// ─── Under load (8n3) ─────────────────────────────────────────────────────────── +describe('a shelf of 1000 lines and a long gear list (8n3)', () => { + const SYS = 'sys_ssssssssssssssss'; + const GUNS = { id: 'guns', label: 'GUNS', one: 'Gun', sold_at: ['general_store'], columns: [{ id: 'damage', label: 'DAMAGE', kind: 'damage' }, { id: 'ammo', label: 'AMMO', kind: 'count' }] }; + const LINES = Array.from({ length: 1000 }, (_, i) => ({ id: `gun_${i}`, name: `Gun ${i}`, price: 10 + i, fields: { damage: `1d${4 + (i % 3) * 2}`, ammo: i % 12 } })); + const timed = async (work: () => unknown) => { const t = performance.now(); await work(); return performance.now() - t; }; + const took: Record = {}; + + beforeEach(() => { + clearCustomTemplates(); + clearUploaded(); + registerCustomTemplate({ id: SYS, name: 'Stress', parts: {}, derived: [], sheet: { sections: [] }, words: {}, items: { slots: [], list: [], types: [GUNS] } } as never); + loadUploaded({ 'type:guns': LINES } as never); + sheetState.sheet = { system: SYS, data: { inventory: '[]' } }; + }); + afterEach(() => { clearCustomTemplates(); clearUploaded(); }); + + it('drawn a page at a time, filtered as typed and sorted by a column across all of it, each in time', async () => { + took.open = await timed(async () => { show('general_store', 'Goods', SYS); await userEvent.click(screen.getByRole('tab', { name: 'GUNS' })); }); + const rows = () => screen.getAllByRole('button', { name: /^Add Gun \d+ to the cart$/ }); + console.log('shop window stress, open (ms):', Math.round(took.open)); + // The first 200, the rest said and a button away. + expect(rows()).toHaveLength(200); + expect(screen.getByText('SHOWING 200 OF 1000 · SCROLL OR FILTER FOR THE REST')).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', { name: 'SHOW 200 MORE' })); + expect(rows()).toHaveLength(400); + expect(screen.getByText('SHOWING 400 OF 1000 · SCROLL OR FILTER FOR THE REST')).toBeInTheDocument(); + // Typed a letter at a time, as a player does: "Gun 99" leaves Gun 99 and Gun 990 to 999, found past the first page. + took.filter = await timed(() => userEvent.type(screen.getByLabelText('Filter stock'), 'Gun 99')); + console.log('shop window stress, filter (ms):', Math.round(took.filter)); + expect(rows()).toHaveLength(11); + expect(screen.queryByText(/^SHOWING /)).toBeNull(); + await userEvent.clear(screen.getByLabelText('Filter stock')); + // A page afresh. + expect(rows()).toHaveLength(200); + // Sorted by PRICE, then the other way: the cheapest and the dearest of all 1000 at the top in turn; a sort starts + // at the first page again. + await userEvent.click(screen.getByRole('button', { name: 'SHOW 200 MORE' })); + expect(rows()).toHaveLength(400); + took.sort = await timed(() => userEvent.click(screen.getByLabelText('Sort by PRICE'))); + expect(rows()).toHaveLength(200); + const first = rows()[0].getAttribute('aria-label'); + took.reverse = await timed(() => userEvent.click(screen.getByLabelText('Sort by PRICE'))); + expect([first, rows()[0].getAttribute('aria-label')].sort()).toEqual(['Add Gun 0 to the cart', 'Add Gun 999 to the cart']); + console.log('shop window stress (ms):', JSON.stringify(Object.fromEntries(Object.entries(took).map(([k, v]) => [k, Math.round(v)])))); + // In a test page (jsdom, slower than a browser); the browser's own times are shop-stress.spec.ts's. + expect(took.open).toBeLessThan(10_000); + expect(took.filter).toBeLessThan(10_000); + expect(took.sort).toBeLessThan(10_000); + }, 120_000); + + it('the last page says how many are left; all of them, and the count goes', async () => { + loadUploaded({ 'type:guns': LINES.slice(0, 250) } as never); + show('general_store', 'Goods', SYS); + await userEvent.click(screen.getByRole('tab', { name: 'GUNS' })); + expect(screen.getByText('SHOWING 200 OF 250 · SCROLL OR FILTER FOR THE REST')).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', { name: 'SHOW 50 MORE' })); + expect(screen.getAllByRole('button', { name: /^Add Gun \d+ to the cart$/ })).toHaveLength(250); + expect(screen.queryByText(/^SHOWING /)).toBeNull(); + }); + + it('300 lines of gear on the SELL tab: listed in time, each priced as the shop buys it back', async () => { + sheetState.sheet = { system: SYS, data: { inventory: JSON.stringify(LINES.slice(0, 300).map((l) => ({ name: l.name, qty: 1, carry: 'stowed', type: 'guns', values: l.fields }))) } }; + show('general_store', 'Goods', SYS); + const ms = await timed(() => openFolder('SELL')); + expect(screen.getAllByRole('button', { name: /^Add Gun \d+ to the cart$/ })).toHaveLength(300); + console.log('shop window stress, SELL (ms):', Math.round(ms)); + expect(ms).toBeLessThan(10_000); + }, 120_000); +});