From 292a9e3b14554f1db7680a4b0e30eff38bdb13b2 Mon Sep 17 00:00:00 2001 From: Developer Date: Sun, 22 Nov 2026 11:43:27 -0600 Subject: [PATCH] feat: PLAYERS CHANGE GEAR on the server, off a player's gear lines keep their columns as stored and a new line comes without, the GM always may; the switch offered where a system makes its own item types --- CHANGELOG.md | 1 + README.md | 10 +-- .../system_builder_band_conditions.test.js | 8 +- .../system_builder_unique_lines.test.js | 79 ++++++++++++++++++- backend/sockets/index.js | 12 ++- backend/systemBuilder/runtime.js | 4 +- backend/systemBuilder/uniqueLines.js | 53 ++++++++++--- 7 files changed, 143 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 947a1e6d..0214459d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -929,6 +929,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Under the hood +- **PLAYERS CHANGE GEAR, on the server.** A table setting (on to start) for systems with their own item types: switched off, the server keeps every column of a player's gear lines as it was saved, and a thing a player adds comes without column values, while their names, counts and where they carry things still change. The GM can always change them. The GAME tab's switch and the sheet's side come next. - **Who changed a gear line from its item, and when.** When a line named like one of a system's items is given a value of its own in a column (the Cutlass made 2d8), the server now notes who changed it and when: the player from their sheet, or the GM on a player's or an NPC's. It is worked out from what was saved before, never taken from the sheet, kept while the value stays, and dropped when it is put back to the item's. The sheet shows this as UNIQUE next. - **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. diff --git a/README.md b/README.md index 837b8444..a82e2123 100644 --- a/README.md +++ b/README.md @@ -433,7 +433,7 @@ CITY_NET/ │ ├── sockets/ │ │ ├── tokenControl.js # Who may move a token, in one place because two move handlers ask it. An admin always may; the owner may; a friendly NPC may name players, or open to everyone. Only friendly NPCs can carry a grant, enforced here rather than by the caller, so one that reaches an enemy row through an import or a restore is inert — and anything unreadable in the column means nobody, since a malformed grant must never open a token up │ │ ├── choices.js # Picking on a custom system's sheet (7a3a): choicesAction ({ kind: pick | drop | level | use }) for the caller's own character, or the player the GM names; systemBuilder/picking.js says what may be done, this stores it through the sheet queue, works the numbers out again and tells every screen; a refusal goes back to the one who asked, in words. recoverySpend ({ pool, count }, R2a) spends recovery dice with a roll (sheets/recover.js), and kind recovery ticks them off; where the system leaves spending to the GM, a player is refused while the GM has it closed. restTake ({ rest }, R3a): a player rests their own character from their sheet where rests are finished on each sheet; the GM anyone's, always. ROLL FOR IT (7a5b2): { kind: 'roll', list, from } rolled on the secure dice, a dice-log line for everyone and the roll thrown in the tray; kits going ONLY IF not met worked out with the rest (7c4b); what an option gives, stored on it (7c4e); itemAction, wearing and attuning an item, the token following (7e3a); an install's limit read on the sheet as it is now (7e4a); spendAction, XP spent and the GM settling it (7f2a2); improveAction, an IMPROVE BY USE mark by hand (7f3a1); countAction (8a4a), a gear line's COUNT spent by its button or filled by RELOAD, answered by ack alone with the lines to ask between or why not (8a4b: said on the line that asked); FIRE and RELOAD worked out as any save is (8a5d1) -│ │ ├── index.js # All Socket.IO event handlers. Every write to a character sheet goes through sheets/mutate.js: rolls, damage, death saves, stabilisation, spell effort and vehicle hulls all touch sheets their owner is very likely looking at, and anything relative is worked out inside the write so two of them landing together both count. Sheet rolls and sheet attacks can come from an NPC's sheet (rollSheetOf): the GM's for any NPC, a player's for a friendly NPC the GM gave them, the log naming the NPC. requestTokenConditions answers a token's conditions with rounds left and modifiers to whoever may change them, and which conditions to anyone else A custom system's stat rolled as IMPROVE BY USE's MARKED BY says is marked (7f3a1).; requestSheetRoll also rolls a line of gear's DAMAGE or DICE (8a3b, { gear: { line, column } }); a band's condition following every sheet write (8a5d1); a battle map floor's start positions, SAVE and LOAD, the GM's alone: a save with no list refused rather than thrown, a player's token made once however many places are saved (8a9c2); an inventory written by updateSheetField keeps which lines are their item made unique, by whom and when (G5a) +│ │ ├── index.js # All Socket.IO event handlers. Every write to a character sheet goes through sheets/mutate.js: rolls, damage, death saves, stabilisation, spell effort and vehicle hulls all touch sheets their owner is very likely looking at, and anything relative is worked out inside the write so two of them landing together both count. Sheet rolls and sheet attacks can come from an NPC's sheet (rollSheetOf): the GM's for any NPC, a player's for a friendly NPC the GM gave them, the log naming the NPC. requestTokenConditions answers a token's conditions with rounds left and modifiers to whoever may change them, and which conditions to anyone else A custom system's stat rolled as IMPROVE BY USE's MARKED BY says is marked (7f3a1).; requestSheetRoll also rolls a line of gear's DAMAGE or DICE (8a3b, { gear: { line, column } }); a band's condition following every sheet write (8a5d1); a battle map floor's start positions, SAVE and LOAD, the GM's alone: a save with no list refused rather than thrown, a player's token made once however many places are saved (8a9c2); an inventory written by updateSheetField keeps which lines are their item made unique, by whom and when (G5a); with PLAYERS CHANGE GEAR off, a player's inventory keeps its columns as stored (G6a) │ │ ├── initiativeOrder.js # Where a combatant stands in the initiative order, so a drag stands when later rolls are sorted in: a hidden place only where its roll doesn't already put it (keepDrag, worked out from the roll every time, never from an earlier place, and every place no longer needed let go), a late joiner kept at the bottom (atBottom), Shadowrun's pass taking the place down with the roll (lowered); the roll stays the one shown │ │ ├── sceneQueue.js # One scene's initiative changes one after another (found by 8i2's journey on CI): inTurn(key, work) runs work(done) once the one before has said done; other scenes never wait; work that throws or never says done lets the next go after 5 s │ │ ├── turnAsks.js # A condition's EACH TURN rolled by the player, or the GM for an NPC (8a9a2): requestTurnAsks (every ask for the GM, a player's own for them) and turnRoll, answered by ack @@ -455,7 +455,7 @@ CITY_NET/ │ │ ├── health.js # A custom system's health model in play, as pure rules: what DAMAGE and HEAL do under each model (second tracks with overflow, damage types turning heavier on a full track, harm moving up a level, wound penalties, hit-location notes), worked out from the token and the sheet behind it; the HIT_POINTS route (routes/locations.js) uses it for a custom system whose health is not one pool │ │ ├── healthView.js # What a token's HEALTH folder is sent under a custom health model: the full detail (a second track's numbers, box marks, harm notes, the wound penalty, location notes) for the GM, a granted editor or the token's owner, and only a description (fills, the worst harm's name, WOUNDED, which locations are hurt) for everyone else; sent by the socket's requestHealthView │ │ ├── npc.js # A custom system's NPCs as data: an optional stat-block layout (checked like a sheet, and linking shared fields the same way) and GENERATE_SHEET tiers (label, token HP and defense, starting values), each box a number, a formula with @level, or dice (rolled by tierRolls.js) -│ │ ├── runtime.js # Published systems in memory for the running game: compiled once into the meta the built-in templates carry (public/combat/linked/GM-only fields, max pairs, derived recompute), reached by sheets/templates.js through a hook; the NPC tiers, reached by sheets/npcTiers.js the same way; the render copy the browser draws from, with no formulas and every word resolved; and wordIn(system, term, form, today's text) for text the server writes; partIn(system, part) for whether a part of the app is on (always, under a built-in system); conditionsIn(system) for the conditions its tokens can have (a custom system's own, or under a built-in one the standard set and the table's own, with no modifiers); definitionOf(system) for rules that read a published system whole (a rest). Each system runs with its house rules applied, the table's choice from global_settings or how each starts, read again on refresh; houseRulesIn(system) and the render copy's house_rules say which are on, hiddenConditionsIn(system) the conditions an off rule hides. The render copy carries its rolls (6b2a): each one's name, the fields with a die button for it, and its changes with their costs (the stat named, taken from or added to, and its highest when added to, 6b3a), never how it rolls; its items and slots, for the GEAR tab (7e3b); a ranked stat drawn as its rank picker, on the character's sheet and an NPC's own (7f1c1); SPEND XP's price list by name, where XP is spent (7f2a1); XP unspent and each next price, written with every save (7f2a2); IMPROVE BY USE's stats, what marks them and its rest (7f3a1); a roll's change keeping the highest or lowest die says which (keep), for the chooser; CAN CARRY worked out as @capacity on each save, and what is carried of it with its band told the sheet (8a5a); CARRYING read without the band's own condition (8a5e1); the worked-out lines written for a condition APPLIED in a system with no picks or items (8a5e3); the render copy's `switches`, which of the GAME tab's encumbrance and condition switches a system has anything for (8a6b) +│ │ ├── runtime.js # Published systems in memory for the running game: compiled once into the meta the built-in templates carry (public/combat/linked/GM-only fields, max pairs, derived recompute), reached by sheets/templates.js through a hook; the NPC tiers, reached by sheets/npcTiers.js the same way; the render copy the browser draws from, with no formulas and every word resolved; and wordIn(system, term, form, today's text) for text the server writes; partIn(system, part) for whether a part of the app is on (always, under a built-in system); conditionsIn(system) for the conditions its tokens can have (a custom system's own, or under a built-in one the standard set and the table's own, with no modifiers); definitionOf(system) for rules that read a published system whole (a rest). Each system runs with its house rules applied, the table's choice from global_settings or how each starts, read again on refresh; houseRulesIn(system) and the render copy's house_rules say which are on, hiddenConditionsIn(system) the conditions an off rule hides. The render copy carries its rolls (6b2a): each one's name, the fields with a die button for it, and its changes with their costs (the stat named, taken from or added to, and its highest when added to, 6b3a), never how it rolls; its items and slots, for the GEAR tab (7e3b); a ranked stat drawn as its rank picker, on the character's sheet and an NPC's own (7f1c1); SPEND XP's price list by name, where XP is spent (7f2a1); XP unspent and each next price, written with every save (7f2a2); IMPROVE BY USE's stats, what marks them and its rest (7f3a1); a roll's change keeping the highest or lowest die says which (keep), for the chooser; CAN CARRY worked out as @capacity on each save, and what is carried of it with its band told the sheet (8a5a); CARRYING read without the band's own condition (8a5e1); the worked-out lines written for a condition APPLIED in a system with no picks or items (8a5e3); the render copy's `switches`, which of the GAME tab's encumbrance and condition switches a system has anything for (8a6b); the switches say gear where the system makes its own item types, for PLAYERS CHANGE GEAR (G6a) │ │ ├── citysys.js # A system as a file to share (.citysys): plain JSON with a cover (name, author, version, builder, license, origin), and the map's layout, the rolls, the system's own dice and its choices beside the system so a builder from before them installs it; read as untrusted input, capped, and checked like the editor's work; never carries characters; the items beside it too (7e2a); ranks travel beside the definition (7f1a); SPEND XP's price list beside it too (7f2a1); IMPROVE BY USE beside it too (7f3a1) │ │ ├── citysysZip.js # A system as a zip to share with the pictures uploaded for it (2026-10-23): its .citysys unchanged, each picture named for what it is (images/symbols/hit.png) and IMAGES.txt saying where each is used; EXPORT without them leaves their addresses out so it falls back cleanly (a symbol its mark or first letter). Reading a zip someone sent: capped in size and count, nothing unpacked but the system and pictures in their places or past the size the zip claims, and only pictures whose hash is an address the system names stored, as an upload is │ │ ├── bonuses.js # The ways a bonus counts (7e1): an ADD, which may say where it STOPS AT (those first, then plain ones), then AT LEAST; each saying what it really gave; a condition's TIMES (rounded down), SET TO and AT MOST after every ADD and AT LEAST (8a5e1) @@ -482,7 +482,7 @@ CITY_NET/ │ │ ├── healthLevels.js # MAX HEALTH: PER LEVEL (7d5a): level 1 the full die, each level after what it kept or the average, EACH LEVEL ADDS read now, never less than 1 a level; the token's base; REROLL ALL, KEEP HIGHER, a level's gain kept outright (7d5c); ROLL TO BEAT, a pool or a die per level against the maximum, a gain of 0 kept (7d5d); each level saying how it was kept (rolled, set, cleared), level 1 set by the GM, a level averaging its own die (7d7b1); an uploaded sheet's maximum the base for its levels, and a whole upload's health (7d7c) │ │ ├── items.js # A system's items (7e2a): slots each character has so many of, items whose features need carrying, wearing or wearing in a slot, checked; at the table (7e3a): carried by a readied or stowed gear line of its name, WEAR and TAKE OFF, ATTUNE with a slot free or the GM's anyway, END, the GM's count for one character, what works; GIVE.EXE's list of them, each with what it needs and its words (itemsGivable, 7e3b); INSTALLS (7e4a): each costing against a stat or formula, ADDING TO it up to a limit or TAKING FROM it down to one, an item needing one with a COST; INSTALL with room or the GM's anyway, REMOVE, the line kept in the gear wherever it is, the cost one of its modifiers (overlaid, never written in), each install's cost, value and limit for the sheet; checks the item types and each item's type and values (8a1); encumbrance beside them, and an install's WEIGHS (8a5a); an item's PRICE and IN SHOPS, checked, one IN SHOPS needing a price (8a7a3a) │ │ ├── itemTypes.js # Item types (8a1; approved mockup item-types, 2026-11-14): each type's columns, NUMBER (a unit), TEXT, DAMAGE, DICE, COUNT (a button, a rest that refills it, the items it reloads from) and PICK ONE (its words), checked; GEAR, WEIGHT and PRICE, where a system makes none; an item's values checked against its type's columns; the types as the sheet is shown them; a line of gear's type, values and counts, from the item it is named like or its own; linesOf, the gear read as the sheet stores it, shared with gearRolls, gearCounts and encumbrance; SOLD AT (8a7a2), the kinds of shop a type's lines are sold at, the General Store where unsaid, and the type shelves a kind of building sells (typeShelvesAt); an item's price (its own, else its type's PRICE column) and whether it is IN SHOPS, one saved before the switch by whether it has a price (8a7a3a); a type's band on the sheet, EQUIPPED, USABLE or PACK, PACK where unsaid (bandOf, G1) -│ │ ├── uniqueLines.js # UNIQUE, the server's half (G5a; decided 2026-11-20): a gear line named like an item, of its type, with a column of its own that isn't the item's, is that item made unique; who changed each such column and when (`changed: { damage: { by, gm?, at } }`) worked out on every inventory write from what was stored, never from what the sheet sends; kept as it was, the writer's when changed, gone when put back +│ │ ├── uniqueLines.js # UNIQUE, the server's half (G5a; decided 2026-11-20): a gear line named like an item, of its type, with a column of its own that isn't the item's, is that item made unique; who changed each such column and when (`changed: { damage: { by, gm?, at } }`) worked out on every inventory write from what was stored, never from what the sheet sends; kept as it was, the writer's when changed, gone when put back; PLAYERS CHANGE GEAR (G6a): with the table's players_change_gear '0', keepColumns keeps a player's lines' column values as stored and a new line's none (pairLines finds the line each was) │ │ ├── encumbrance.js # Encumbrance (8a5a; approved mockup item-types, 2026-11-14, decision 7; shown, never enforced): COUNTED BY a NUMBER column, one of each times how many over the lines READIED or STOWED, an installed item only where its install WEIGHS; CAN CARRY a formula among the others (@capacity), what is carried read as @carried; bands as words at a share of it; the checks; each band and the word past them saying WHAT IT MEANS and naming an optional condition (8a5d1), the band as the sheet is told it; BAND_KEY, and CARRYING given CAN CARRY as the band reads it (8a5e1); the bands, the word past them and the condition's name given to the sheet for CARRYING on GEAR (8a6a) │ │ ├── wornSums.js # What is worn, summed by column (8a5b; approved mockup item-types, 2026-11-14, decision 6): each NUMBER column of a system's own types read as @type_column, the worn items of that type together (@armor_defense), each worn item once as its line has it; no name a stat's, formula's or level's │ │ ├── itemsImport.js # A system's items from a file (8aL3a; approved mockup items-layout, 2026-11-14): a section per type by its id or name, each column by its name or id, needs, cost where the system has an install, words, and [features]; read against the draft, matched by name, never deleting; one there under another type made it, keeping the values both have; each mistake skipped by its line, the rest going in; nothing saved. In a game with types of its own, PRICE (an item's own, where its type has no column holding it) and IN SHOPS, yes or no (8a7a3b2) @@ -633,7 +633,7 @@ CITY_NET/ │ ├── system_builder_items_worn.test.js # Items at the table (7e3a): carried, WEAR and TAKE OFF, ATTUNE and END, the GM's anyway and own count, taken off still attuned, a working item's bonuses (named by it), has() and uses, what the sheet is told; over the socket, the token following; the render copy's items and slots, and a pick's features read as before (7e3b); GIVE.EXE listing them for the GM only, giving one as a stowed line that is then worn, more joining it, the notice, one not had refused │ ├── system_builder_items_installed.test.js # Installed items (7e4a): the checks, INSTALL and REMOVE within and past the limit (ADDS TO and TAKES FROM), the GM's anyway, the cost on its stat and a formula named by the item, has(), the line gone or kept stashed, what the sheet is told, the system file, no shop buying one, over the socket │ ├── system_builder_item_types.test.js # Item types (8a1): the list, each type and column checked, each kind's own parts, each item's type and values, what the sheet is shown, a line of gear's columns from its item or its own, the system file and back unchanged -│ ├── system_builder_unique_lines.test.js # UNIQUE on the server (G5a): which columns are unique (read loosely, none for a thing made by hand or of another type), the writer's when changed, kept as it was, gone put back, never what the sheet sends, the line found where lines moved, as stored; kept by the player's socket, the GM on a player's sheet and on an NPC's; a built-in system's written as sent +│ ├── system_builder_unique_lines.test.js # UNIQUE on the server (G5a): which columns are unique (read loosely, none for a thing made by hand or of another type), the writer's when changed, kept as it was, gone put back, never what the sheet sends, the line found where lines moved, as stored; kept by the player's socket, the GM on a player's sheet and on an NPC's; a built-in system's written as sent; PLAYERS CHANGE GEAR (G6a): off, a player's columns kept and a new line's dropped, the rest landing; the GM still changes them; on or never set, as before │ ├── system_builder_ranks.test.js # Ranks with names (7f1a): the lists and the stats held as them checked, a ranked stat's worth at its step (the ends holding, a formula reading it, one read after it, a loop said), a bonus moving the step, the system file, a sheet saved working it out; the rank picker on the sheet a browser draws, an NPC's, and the import by name or step (7f1c1) │ ├── system_builder_ranks_start.test.js # Ranks making a character and levelling up (7f1c2): a ranked stat asked with its ranks and AT START, never locked as a number placed; a player's rank past AT START refused over the socket, one field or a batch, the GM's kept; an INCREASE raising a rank to its top and never stopped by a number's cap │ ├── system_builder_spend_xp.test.js # SPEND XP's price list (7f2a1): every check, the list told to the sheet by name and with the template, a stat's price from @old and @new to UP TO, a rank's to its top, an option's on the sheet as it reads, never one held or not met; the system file carrying it, a new version naming it; XP given, uploaded and on the form where it is spent @@ -681,7 +681,7 @@ CITY_NET/ │ ├── system_builder_gear_rolls.test.js # A line of gear's dice rolled (8a3b): its item's or its own, DICE as DAMAGE, the log's words, nothing to roll, and over the socket into the tray and the kept rolls; reading dice as typed without rolling, picks' levels counted, at the table answered to the asker (8a3c2) │ ├── system_builder_gear_counts.test.js # A gear line's COUNT (8a4a): FIRE spending to none, RELOAD from a carried line's quantity (used up, stashed, several asked which, never itself), a rest and one counting as it refilling, and over the socket: the player's own, the GM's named player, refusals answered to the line alone, a rest from the sheet │ ├── system_builder_encumbrance.test.js # Encumbrance (8a5a): the checks (its column, unit, CAN CARRY, bands each further, a word past them, the names refused to stats, an install's WEIGHS), what is carried (stashed, a type without the column, installed, rounding), its band, @capacity and @carried on every save and in rolls and health formulas, the system file, CAN CARRY changed in a new version; the bands given to the sheet, none without CAN CARRY (8a6a) -│ ├── system_builder_band_conditions.test.js # A band's words and condition (8a5d1): checked, the band as the sheet is told it, what to do, and at the table: on and off with log lines, one band to the next, the GM's own left alone, switched off at a table, no token, a RELOAD working the sheet out again; a band's condition APPLIED tripling Might never going round (8a5e1); the GAME tab's BAND CONDITIONS switched through the settings route taking off and putting back at once, an NPC's sheet and another game's left alone; the render copy's switches (8a6b) +│ ├── system_builder_band_conditions.test.js # A band's words and condition (8a5d1): checked, the band as the sheet is told it, what to do, and at the table: on and off with log lines, one band to the next, the GM's own left alone, switched off at a table, no token, a RELOAD working the sheet out again; a band's condition APPLIED tripling Might never going round (8a5e1); the GAME tab's BAND CONDITIONS switched through the settings route taking off and putting back at once, an NPC's sheet and another game's left alone; the render copy's switches (8a6b); the GAME tab's PLAYERS CHANGE GEAR offered only where a system makes its own item types (G6a) │ ├── system_builder_condition_modifiers.test.js # A condition's modifiers with a way (8a5e1): checked, the ways in order after every bonus, SLOWED halving Speed after a ring's +5, a reminder changing nothing, none stacking, and the token's conditions on the sheet through the route and the table's switch, a new round and a short rest taking one off; the lines written in a system with no picks or items (8a5e3) │ ├── system_builder_worn_sums.test.js # What is worn summed by column (8a5b): the names and their words, refused where a stat, formula or level has one, each worn item once, stashed or by hand not worn, a line of another type adding there, and AC reading @armor_defense as armor goes on and off │ ├── system_builder_choices_numbers.test.js # What picks do to a character's numbers: picks read from the sheet keeping only what holds (a known option, once, within what the list allows, MORE THAN ONCE for multiclassing, levels from 1 to the highest); each option's level, a list's sum and @level, a system's own level left alone; features unlocked by level; on a save, a stat's modifier reaching the formulas reading it while the stat stays as typed, a formula's added before what reads it, amounts from levels, a pick taken away taking its effects; an amount reading a formula refused, a list's sum name kept free; rolls reading the same numbers; PUBLISH's preview showing a feature changed; the picks never a player's to write diff --git a/backend/__tests__/system_builder_band_conditions.test.js b/backend/__tests__/system_builder_band_conditions.test.js index 7aba2918..4e057cd6 100644 --- a/backend/__tests__/system_builder_band_conditions.test.js +++ b/backend/__tests__/system_builder_band_conditions.test.js @@ -87,12 +87,14 @@ describe("the GAME tab's switches a system has (8a6b)", () => { return runtime.render(ID).switches; }; it('encumbrance counted, a band naming a condition, a condition APPLIED: each its own', async () => { - expect(await switchesOf(LADEN)).toEqual({ encumbrance: true, band_conditions: true, applied_conditions: false, turn_effects: false }); + expect(await switchesOf(LADEN)).toEqual({ encumbrance: true, band_conditions: true, applied_conditions: false, turn_effects: false, gear: true }); const plain = { ...LADEN, items: { ...LADEN.items, encumbrance: { column: 'weight', capacity: '10' } } }; - expect(await switchesOf(plain)).toEqual({ encumbrance: true, band_conditions: false, applied_conditions: false, turn_effects: false }); + expect(await switchesOf(plain)).toEqual({ encumbrance: true, band_conditions: false, applied_conditions: false, turn_effects: false, gear: true }); const { encumbrance, ...noCount } = LADEN.items; const applied = { ...LADEN, items: noCount, conditions: { ...LADEN.conditions, slowed: { ...LADEN.conditions.slowed, applied: true, modifiers: [{ target: 'might', amount: -1 }] } } }; - expect(await switchesOf(applied)).toEqual({ encumbrance: false, band_conditions: false, applied_conditions: true, turn_effects: false }); + expect(await switchesOf(applied)).toEqual({ encumbrance: false, band_conditions: false, applied_conditions: true, turn_effects: false, gear: true }); + // PLAYERS CHANGE GEAR (G6a): only where the system makes its own item types. + expect((await switchesOf({ ...LADEN, items: { list: [{ id: 'pack', label: 'Pack' }] } })).gear).toBe(false); // CONDITION TURN EFFECTS (8a9c): where a condition has an EACH TURN; ending at the end of its next turn alone switches nothing. const burning = { burning: { name: 'Burning', each_turn: [{ when: 'turn_start', does: 'damage', roll: '1' }] } }; expect((await switchesOf({ ...LADEN, items: noCount, conditions: { ...LADEN.conditions, ...burning } })).turn_effects).toBe(true); diff --git a/backend/__tests__/system_builder_unique_lines.test.js b/backend/__tests__/system_builder_unique_lines.test.js index 20dfc29a..a3aa45c5 100644 --- a/backend/__tests__/system_builder_unique_lines.test.js +++ b/backend/__tests__/system_builder_unique_lines.test.js @@ -15,7 +15,7 @@ import { drain, until } from './helpers/until.js'; process.env.JWT_SECRET = 'test-secret'; const require_ = createRequire(import.meta.url); -const { withChanges, uniqueColumns } = require_('../systemBuilder/uniqueLines'); +const { withChanges, uniqueColumns, keepColumns, PLAYERS_GEAR_SETTING } = require_('../systemBuilder/uniqueLines'); const runtime = require_('../systemBuilder/runtime'); const socketsFactory = require_('../sockets/index.js'); @@ -164,3 +164,80 @@ describe('kept by every write of the inventory', () => { expect((await linesOf(`id = ${npc}`))[0].changed).toEqual({ weight: { by: 'gm', gm: true, at: expect.any(String) } }); }); }); + +describe('PLAYERS CHANGE GEAR off (G6a)', () => { + it('a player\'s lines keep their columns as stored, a new one comes without; name, how many, where and the rest as sent', () => { + const stored = [line('Cutlass', { values: { damage: '2d8' } }), line('Rope')]; + const sent = [line('Cutlass', { qty: 2, carry: 'readied', values: { damage: '9d9', range: 'far' } }), line('Rope', { values: { weight: 99 } }), line('A stick', { type: 'weapons', values: { damage: '1d4' } })]; + expect(keepColumns(stored, sent)).toEqual([line('Cutlass', { qty: 2, carry: 'readied', values: { damage: '2d8' } }), line('Rope'), line('A stick', { type: 'weapons' })]); + // Found by name where lines moved; a JSON string back as one; unreadable as given. + expect(JSON.parse(keepColumns(JSON.stringify(stored), JSON.stringify([line('Rope'), line('Cutlass', { values: {} })])))).toEqual([line('Rope'), line('Cutlass', { values: { damage: '2d8' } })]); + expect(keepColumns(stored, 'nope')).toBe('nope'); + expect(PLAYERS_GEAR_SETTING).toBe('players_change_gear'); + }); +}); + +describe('PLAYERS CHANGE GEAR at the table (G6a)', () => { + let db; + let id; + + beforeEach(async () => { + db = await makeTestDb(); + await run(db, "INSERT INTO global_settings (key, value) VALUES ('game_system', 'cities_without_number')"); + const app = express(); + app.use(express.json({ limit: '2mb' })); + app.use('/api/systems', require_('../routes/systems.js')(db)); + app.use('/api/sheets', require_('../routes/sheets.js')(db, { emit: () => {}, to: () => ({ emit: () => {} }) })); + id = (await request(app).post('/api/systems').set(gm).send({ definition: BLADES })).body.id; + await new Promise((resolve) => runtime.load(db, resolve)); + await request(app).post(`/api/systems/${id}/publish`).set(gm); + await request(app).put('/api/sheets/system').set(gm).send({ system: id }); + await run(db, 'INSERT INTO character_sheets (username, system, data, is_npc) VALUES (?, ?, ?, 0)', + ['kes', id, JSON.stringify({ name: 'Kes', inventory: JSON.stringify([line('Cutlass', { values: { damage: '2d8' } })]) })]); + vi.spyOn(console, 'log').mockImplementation(() => {}); + }); + afterEach(() => vi.restoreAllMocks()); + + const connectAs = async (userName, { admin = false } = {}) => { + let connect; + socketsFactory({ on: (e, cb) => { if (e === 'connection') connect = cb; }, emit: () => {}, to: () => ({ emit: () => {} }) }, + db, { elevatedUsers: new Set(), emitUpdate: vi.fn(), recordAction: vi.fn() }); + const handlers = {}; + connect({ id: `pg-${Math.random()}`, on: (e, fn) => { handlers[e] = fn; }, emit: () => {}, broadcast: { emit: () => {} }, use: () => {}, join: () => {}, disconnect: () => {} }); + handlers.identify(admin ? { userName, isAdmin: true, token: GM } : userName); + await drain(db); + return handlers; + }; + const kesLines = async () => JSON.parse(JSON.parse((await get(db, "SELECT data FROM character_sheets WHERE username = 'kes'")).data).inventory || '[]'); + const off = () => run(db, 'INSERT INTO global_settings (key, value) VALUES (?, ?)', [PLAYERS_GEAR_SETTING, '0']); + const write = (handlers, rows) => handlers.updateSheetField({ fieldId: 'inventory', value: JSON.stringify(rows) }); + + it('off: the player\'s DAMAGE stays as it was, their new line comes without columns, the rest of the write lands', async () => { + await off(); + const kes = await connectAs('kes'); + write(kes, [line('Cutlass', { qty: 2, values: { damage: '9d9' } }), line('A stick', { type: 'weapons', values: { damage: '1d4' } })]); + await until(async () => (await kesLines()).length === 2, { label: 'written' }); + const [cutlass, stick] = await kesLines(); + expect(cutlass.qty).toBe(2); + expect(cutlass.values).toEqual({ damage: '2d8' }); + expect(stick).toEqual(line('A stick', { type: 'weapons' })); + }); + + it('off: the GM, on their own socket, still changes it', async () => { + await off(); + // The GM playing the character, as the GM: an admin socket. + await run(db, "UPDATE character_sheets SET username = 'gm' WHERE username = 'kes'"); + const gmSocket = await connectAs('gm', { admin: true }); + write(gmSocket, [line('Cutlass', { values: { damage: '3d8' } })]); + await until(async () => JSON.parse(JSON.parse((await get(db, "SELECT data FROM character_sheets WHERE username = 'gm'")).data).inventory)[0].values.damage === '3d8', { label: 'the GM\'s' }); + }); + + it('on, or never set: the player changes it, as before', async () => { + const kes = await connectAs('kes'); + write(kes, [line('Cutlass', { values: { damage: '4d8' } })]); + await until(async () => (await kesLines())[0].values.damage === '4d8', { label: 'never set' }); + await run(db, 'INSERT INTO global_settings (key, value) VALUES (?, ?)', [PLAYERS_GEAR_SETTING, '1']); + write(kes, [line('Cutlass', { values: { damage: '5d8' } })]); + await until(async () => (await kesLines())[0].values.damage === '5d8', { label: 'on' }); + }); +}); diff --git a/backend/sockets/index.js b/backend/sockets/index.js index 4e515d4e..d8b80b91 100644 --- a/backend/sockets/index.js +++ b/backend/sockets/index.js @@ -15,7 +15,7 @@ const cyberware = require('../sheets/cyberware'); const { ownToken } = require('../sheets/ownToken'); const sheetRolls = require('../sheets/rolls'); const { rollGear, readGearDice } = require('../systemBuilder/gearRolls'); -const { withChanges } = require('../systemBuilder/uniqueLines'); +const { withChanges, keepColumns, PLAYERS_GEAR_SETTING } = require('../systemBuilder/uniqueLines'); const rollEngine = require('../sheets/rollEngine'); const sheetAttack = require('../sheets/attack'); const cyberEffects = require('../sheets/cyberwareEffects'); @@ -1406,6 +1406,11 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { return; } if (linkSource) return; + // PLAYERS CHANGE GEAR (G6a): a player's inventory, with the switch off, is asked of the table first; the GM always may. + const gearOff = payload.fieldId === 'inventory' && !isAdminSocket(socket) + ? (done) => db.get('SELECT value FROM global_settings WHERE key = ?', [PLAYERS_GEAR_SETTING], (e, row) => done(!e && !!row && row.value === '0')) + : (done) => done(false); + gearOff((keepGear) => { // Through the queue rather than a bare read-then-write: a GM applying damage to // this same sheet while the player types would otherwise build its new blob from // data this edit had already replaced, and one of the two changes would vanish @@ -1421,8 +1426,10 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { // A rank past where a new character may start (7f1c2): the GM's to give. if (!isAdminSocket(socket) && pastStart(customSystems.definitionOf(system), data, payload.fieldId, payload.value)) return undefined; // The inventory: which lines are their item made unique, and by whom and when (G5a), from what was stored. + // With PLAYERS CHANGE GEAR off, a player's lines keep their columns as stored (G6a). + const sent = keepGear && customSystems.definitionOf(system) ? keepColumns(data.inventory, payload.value) : payload.value; data[payload.fieldId] = payload.fieldId === 'inventory' - ? withChanges(customSystems.definitionOf(system), data.inventory, payload.value, { by: info.userName, gm: isAdminSocket(socket) }) + ? withChanges(customSystems.definitionOf(system), data.inventory, sent, { by: info.userName, gm: isAdminSocket(socket) }) : payload.value; // If the changed field is a max, clamp the paired current field. const curField = sheetTemplates.getMaxPairs(system)[payload.fieldId]; @@ -1491,6 +1498,7 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { } } ); + }); }); }); diff --git a/backend/systemBuilder/runtime.js b/backend/systemBuilder/runtime.js index 0a605a9a..42889bbc 100644 --- a/backend/systemBuilder/runtime.js +++ b/backend/systemBuilder/runtime.js @@ -34,6 +34,7 @@ const { partOn, PARTS } = require('./parts'); const { buildingOn, buildingName, catalogueCurrency, ownBuildings } = require('./buildings'); const { currenciesOf } = require('./currencies'); const { conditionsOf } = require('./conditions'); +const { ownTypes } = require('./itemTypes'); const { loadTableConditions, tableConditionsOf } = require('./tableConditions'); const { bankOf } = require('./bank'); const { distanceOf } = require('./core'); @@ -210,10 +211,11 @@ const renderOf = (id, definition, on = new Set()) => ({ items: itemsRenderedOf(definition), // Which of the GAME tab's switches this system has anything for (8a6b): SHOW ENCUMBRANCE where it counts encumbrance, // BAND CONDITIONS where a band (or the word past them) names a condition, APPLY CONDITION MODIFIERS where a condition is APPLIED, - // CONDITION TURN EFFECTS where a condition has an EACH TURN (8a9c). + // CONDITION TURN EFFECTS where a condition has an EACH TURN (8a9c), PLAYERS CHANGE GEAR where it makes its own item types (G6a). switches: { encumbrance: encumbranceOf(definition) !== null, band_conditions: namesCondition(definition), applied_conditions: conditionsOf(definition).some((c) => c.applied), turn_effects: conditionsOf(definition).some((c) => Array.isArray(c.each_turn) && c.each_turn.length > 0), + gear: ownTypes(definition), }, }); diff --git a/backend/systemBuilder/uniqueLines.js b/backend/systemBuilder/uniqueLines.js index 4b335e97..ed801b51 100644 --- a/backend/systemBuilder/uniqueLines.js +++ b/backend/systemBuilder/uniqueLines.js @@ -10,6 +10,13 @@ // is still unique, with no one named. // // Pure; the sheet writes call it (sockets updateSheetField, the GM's PUT /api/sheets/user/:username and /npcs/:id). +// +// PLAYERS CHANGE GEAR (G6a; decided 2026-11-20, all A: a GAME tab switch, on to start; off, only the GM changes columns, +// players still name, count and move their things; the user: "the GM can still open, view and change things"). Off, a +// player's write keeps every line's column values as stored, and a line they add comes without any: keepColumns. + +/** The table's setting (global_settings): '0' switches PLAYERS CHANGE GEAR off. */ +const PLAYERS_GEAR_SETTING = 'players_change_gear'; const { typesOf, typeNamed } = require('./itemTypes'); @@ -46,6 +53,37 @@ const uniqueColumns = (definition, line) => { return of.type.columns.filter((c) => filled(own[c.id]) && !same(own[c.id], given[c.id])).map((c) => c.id); }; +/** + * The line each of `next` was in `prev`, or null for one that is new: the one in its place where it has the same name, else + * the first unclaimed of its name. Its type needn't match: a line made another type than its item's is no longer the item. + */ +const pairLines = (prev, next) => { + const claimed = new Set(); + const fits = (p, line) => isPlainObject(p) && isPlainObject(line) && key(p.name) === key(line.name); + return next.map((line, i) => { + const j = !claimed.has(i) && fits(prev[i], line) ? i : prev.findIndex((p, n) => !claimed.has(n) && fits(p, line)); + if (j < 0) return null; + claimed.add(j); + return prev[j]; + }); +}; + +/** + * A player's lines with PLAYERS CHANGE GEAR off (G6a): each line's column values as stored for the line it was, none on a + * line that is new; its name, how many, where it is and the rest as sent. In the form given; as given where unreadable. + */ +const keepColumns = (before, after) => { + const next = parse(after); + if (!next) return after; + const was = pairLines(parse(before) || [], next); + const out = next.map((line, i) => { + if (!isPlainObject(line)) return line; + const { values: _typed, ...rest } = line; + return was[i] && isPlainObject(was[i].values) ? { ...rest, values: { ...was[i].values } } : rest; + }); + return typeof after === 'string' ? JSON.stringify(out) : out; +}; + /** * The lines `after` as they are to be stored, each with `changed` worked out against `before` (what was stored): `who` is * { by: username, gm }. In the form given (a JSON string stays one); as given where the system has no definition or the @@ -57,21 +95,12 @@ const withChanges = (definition, before, after, who, at = new Date().toISOString if (!next) return after; const prev = parse(before) || []; const stamp = { by: who && typeof who.by === 'string' ? who.by : '', ...(who && who.gm ? { gm: true } : {}), at }; - // The line each was before: the one in its place where it has the same name, else the first unclaimed of its name. Its - // type needn't match: a line made another type than its item's is no longer the item, so has no unique columns anyway. - const claimed = new Set(); - const fits = (p, line) => isPlainObject(p) && key(p.name) === key(line.name); - const wasOf = (line, i) => { - const j = !claimed.has(i) && fits(prev[i], line) ? i : prev.findIndex((p, n) => !claimed.has(n) && fits(p, line)); - if (j < 0) return null; - claimed.add(j); - return prev[j]; - }; + const wasLines = pairLines(prev, next); const out = next.map((line, i) => { if (!isPlainObject(line)) return line; // What the sheet says was changed is never taken: worked out here alone. const { changed: _sent, ...rest } = line; - const was = wasOf(rest, i); + const was = wasLines[i]; const kept = was && isPlainObject(was.changed) ? was.changed : {}; const wasOwn = was && isPlainObject(was.values) ? was.values : {}; const changed = {}; @@ -83,4 +112,4 @@ const withChanges = (definition, before, after, who, at = new Date().toISOString return typeof after === 'string' ? JSON.stringify(out) : out; }; -module.exports = { withChanges, uniqueColumns, itemOf }; +module.exports = { PLAYERS_GEAR_SETTING, withChanges, keepColumns, pairLines, uniqueColumns, itemOf };