BlueGit

timfa questward

Polish shops, dyes, and clothing: fill-safe stacks, in-world copy, and editor dyes.

NPC shops use buy/sell tabs with a bag grid and stack-aware sell actions; potions/dyes only stack on matching uses and consume without losing leftovers; spawners can author clothing dye colours; item blurbs stay in-universe.

timfa Tim Falken · pushed by timfa

Authored 2026-08-26 · 2 months ago

Hash
7860dd9888501abc9b3fc8b7a1eff897d5dd1286
Parent
c39b627a
27 files changed +1176 −240
.cursor/rules/item-descriptions.mdc added +36 −0
@@ -0,0 +1,36 @@
1 ---
2 description: Item (and station) descriptions must stay in-universe; never expose mechanics or implementation status.
3 alwaysApply: true
4 ---
5
6 # In-universe item descriptions
7
8 Player-facing `description` text on items (and craft-station blurbs shown in UI) **must** describe the thing in-world — what it is, looks like, or is for — never how the game implements it.
9
10 ## Forbidden
11
12 - Stack sizes, slots, skill levels, equip rules, UI labels
13 - Implementation status (“TBD”, “for now”, “mostly cosmetic”, “placeholder”, “tintable”, “scaffold”)
14 - Code/art notes (“shared sprite”, “overrides material colour”)
15 - Out-of-character systems talk (“your bag”, “inventory space”)
16
17 ## Allowed
18
19 - In-world craft hints at the softest end, e.g. “Smelt these ores in a furnace.”
20 - Flavor and material/origin that a character could know
21
22 ```text
23 # ❌ BAD
24 "Mostly cosmetic for now; optional dye overrides the material colour."
25 "Same colour and uses stack up to 16."
26 "Drink to apply its effect (effects TBD)."
27 "Bronze may be equipped at any Woodcutting level."
28
29 # ✅ GOOD
30 "A warm cotton sweater, soft enough for travel."
31 "Bottled colour for cloth and clothing."
32 "A bottled brew. Sip with care."
33 "A bronze axe for felling trees."
34 ```
35
36 When adding or editing item defs, write lore/flavor first; put rules in code and tooltips that are explicitly mechanical if needed later — not in `description`.
@@ -0,0 +1,36 @@
1---
2description: Item (and station) descriptions must stay in-universe; never expose mechanics or implementation status.
3alwaysApply: true
4---
5
6# In-universe item descriptions
7
8Player-facing `description` text on items (and craft-station blurbs shown in UI) **must** describe the thing in-world — what it is, looks like, or is for — never how the game implements it.
9
10## Forbidden
11
12- Stack sizes, slots, skill levels, equip rules, UI labels
13- Implementation status (“TBD”, “for now”, “mostly cosmetic”, “placeholder”, “tintable”, “scaffold”)
14- Code/art notes (“shared sprite”, “overrides material colour”)
15- Out-of-character systems talk (“your bag”, “inventory space”)
16
17## Allowed
18
19- In-world craft hints at the softest end, e.g. “Smelt these ores in a furnace.”
20- Flavor and material/origin that a character could know
21
22```text
23# ❌ BAD
24"Mostly cosmetic for now; optional dye overrides the material colour."
25"Same colour and uses stack up to 16."
26"Drink to apply its effect (effects TBD)."
27"Bronze may be equipped at any Woodcutting level."
28
29# ✅ GOOD
30"A warm cotton sweater, soft enough for travel."
31"Bottled colour for cloth and clothing."
32"A bottled brew. Sip with care."
33"A bronze axe for felling trees."
34```
35
36When adding or editing item defs, write lore/flavor first; put rules in code and tooltips that are explicitly mechanical if needed later — not in `description`.
client/editor.html +30 −0
@@ -101,6 +101,36 @@
101 101 <div id="shop-item-search-results"></div>
102 102 </div>
103 103 </div>
104
105 <div id="equip-dye-backdrop" hidden></div>
106 <div id="equip-dye-modal" hidden>
107 <header>
108 <h2 id="equip-dye-title">Dye clothing</h2>
109 <button id="equip-dye-close" type="button">Close</button>
110 </header>
111 <div class="equip-dye-body">
112 <div id="equip-dye-preview" class="equip-dye-preview" aria-hidden="true"></div>
113 <label class="equip-dye-channel">
114 <span>R</span>
115 <input id="equip-dye-r" type="range" min="0" max="255" value="200">
116 <input id="equip-dye-r-num" type="number" min="0" max="255" value="200">
117 </label>
118 <label class="equip-dye-channel">
119 <span>G</span>
120 <input id="equip-dye-g" type="range" min="0" max="255" value="80">
121 <input id="equip-dye-g-num" type="number" min="0" max="255" value="80">
122 </label>
123 <label class="equip-dye-channel">
124 <span>B</span>
125 <input id="equip-dye-b" type="range" min="0" max="255" value="120">
126 <input id="equip-dye-b-num" type="number" min="0" max="255" value="120">
127 </label>
128 <div class="equip-dye-actions">
129 <button id="equip-dye-clear" type="button">Clear dye</button>
130 <button id="equip-dye-apply" type="button">Apply</button>
131 </div>
132 </div>
133 </div>
104 134 <script src="/framework/framework.js"></script>
105 135 <script type="module" src="/src/editor/main.js"></script>
106 136 </body>
@@ -101,6 +101,36 @@
101 <div id="shop-item-search-results"></div>
101 <div id="shop-item-search-results"></div>
102 </div>
102 </div>
103 </div>
103 </div>
104
105 <div id="equip-dye-backdrop" hidden></div>
106 <div id="equip-dye-modal" hidden>
107 <header>
108 <h2 id="equip-dye-title">Dye clothing</h2>
109 <button id="equip-dye-close" type="button">Close</button>
110 </header>
111 <div class="equip-dye-body">
112 <div id="equip-dye-preview" class="equip-dye-preview" aria-hidden="true"></div>
113 <label class="equip-dye-channel">
114 <span>R</span>
115 <input id="equip-dye-r" type="range" min="0" max="255" value="200">
116 <input id="equip-dye-r-num" type="number" min="0" max="255" value="200">
117 </label>
118 <label class="equip-dye-channel">
119 <span>G</span>
120 <input id="equip-dye-g" type="range" min="0" max="255" value="80">
121 <input id="equip-dye-g-num" type="number" min="0" max="255" value="80">
122 </label>
123 <label class="equip-dye-channel">
124 <span>B</span>
125 <input id="equip-dye-b" type="range" min="0" max="255" value="120">
126 <input id="equip-dye-b-num" type="number" min="0" max="255" value="120">
127 </label>
128 <div class="equip-dye-actions">
129 <button id="equip-dye-clear" type="button">Clear dye</button>
130 <button id="equip-dye-apply" type="button">Apply</button>
131 </div>
132 </div>
133 </div>
104 <script src="/framework/framework.js"></script>
134 <script src="/framework/framework.js"></script>
105 <script type="module" src="/src/editor/main.js"></script>
135 <script type="module" src="/src/editor/main.js"></script>
106</body>
136</body>
client/index.html +34 −24
@@ -200,38 +200,48 @@
200 200 <h2 id="shop-title">Shop</h2>
201 201 <button id="shop-close" type="button">Close</button>
202 202 </header>
203 <div class="shop-body">
204 <div id="shop-grid" class="shop-grid"></div>
205 <div id="shop-detail" class="shop-detail" hidden>
206 <img id="shop-detail-icon" alt="">
207 <strong id="shop-detail-name"></strong>
208 <span id="shop-detail-price" class="hint"></span>
209 <span id="shop-detail-stock" class="hint"></span>
210 <div class="shop-buy-row">
211 <button id="shop-buy-1" type="button">Buy 1</button>
212 <button id="shop-buy-5" type="button">Buy 5</button>
213 <button id="shop-buy-10" type="button">Buy 10</button>
214 <button id="shop-buy-x" type="button">Buy x</button>
203 <p id="shop-coins" class="shop-coins">Coins: 0</p>
204 <div class="shop-tabs" role="tablist">
205 <button id="shop-tab-buy" type="button" class="shop-tab active" role="tab" aria-selected="true">Buy</button>
206 <button id="shop-tab-sell" type="button" class="shop-tab" role="tab" aria-selected="false" hidden>Sell</button>
207 </div>
208 <section id="shop-pane-buy" class="shop-pane">
209 <div class="shop-body">
210 <div id="shop-grid" class="shop-grid"></div>
211 <div id="shop-detail" class="shop-detail" hidden>
212 <img id="shop-detail-icon" alt="">
213 <strong id="shop-detail-name"></strong>
214 <span id="shop-detail-price" class="hint"></span>
215 <span id="shop-detail-stock" class="hint"></span>
216 <div class="shop-buy-row">
217 <button id="shop-buy-1" type="button">Buy 1</button>
218 <button id="shop-buy-5" type="button">Buy 5</button>
219 <button id="shop-buy-10" type="button">Buy 10</button>
220 <button id="shop-buy-x" type="button">Buy x</button>
221 </div>
222 <p id="shop-bag-warn" class="shop-bag-warn" hidden>Inventory full; purchases will be sent to your bank.</p>
215 223 </div>
216 <p id="shop-bag-warn" class="shop-bag-warn" hidden>Inventory full; purchases will be sent to your bank.</p>
217 224 </div>
218 </div>
219 <div id="shop-sell-section" class="shop-sell-section" hidden>
220 <strong>Sell to shop</strong>
221 <div id="shop-sell-list" class="shop-sell-list"></div>
222 <div id="shop-sell-detail" class="shop-sell-detail" hidden>
223 <span id="shop-sell-price" class="hint"></span>
224 <span id="shop-sell-fee" class="hint" hidden></span>
225 <button id="shop-sell-confirm" type="button">Sell 1</button>
225 </section>
226 <section id="shop-pane-sell" class="shop-pane" hidden>
227 <div class="shop-body">
228 <div id="shop-sell-grid" class="item-grid shop-sell-grid"></div>
229 <div id="shop-sell-detail" class="shop-detail shop-sell-detail" hidden>
230 <img id="shop-sell-icon" alt="">
231 <strong id="shop-sell-name"></strong>
232 <span id="shop-sell-price" class="hint"></span>
233 <span id="shop-sell-fee" class="hint" hidden></span>
234 <div id="shop-sell-actions" class="shop-buy-row"></div>
235 <p id="shop-sell-empty" class="hint" hidden></p>
236 </div>
226 237 </div>
227 </div>
228 <p id="shop-coins" class="shop-coins">Coins: 0</p>
238 </section>
229 239 </aside>
230 240
231 241 <div id="shop-qty-backdrop" class="modal-backdrop" hidden></div>
232 242 <aside id="shop-qty-panel" hidden>
233 243 <header>
234 <h2>Buy quantity</h2>
244 <h2 id="shop-qty-title">Buy quantity</h2>
235 245 <button id="shop-qty-close" type="button">Close</button>
236 246 </header>
237 247 <p id="shop-qty-hint" class="hint"></p>
@@ -200,38 +200,48 @@
200 <h2 id="shop-title">Shop</h2>
200 <h2 id="shop-title">Shop</h2>
201 <button id="shop-close" type="button">Close</button>
201 <button id="shop-close" type="button">Close</button>
202 </header>
202 </header>
203 <div class="shop-body">
203 <p id="shop-coins" class="shop-coins">Coins: 0</p>
204 <div id="shop-grid" class="shop-grid"></div>
204 <div class="shop-tabs" role="tablist">
205 <div id="shop-detail" class="shop-detail" hidden>
205 <button id="shop-tab-buy" type="button" class="shop-tab active" role="tab" aria-selected="true">Buy</button>
206 <img id="shop-detail-icon" alt="">
206 <button id="shop-tab-sell" type="button" class="shop-tab" role="tab" aria-selected="false" hidden>Sell</button>
207 <strong id="shop-detail-name"></strong>
207 </div>
208 <span id="shop-detail-price" class="hint"></span>
208 <section id="shop-pane-buy" class="shop-pane">
209 <span id="shop-detail-stock" class="hint"></span>
209 <div class="shop-body">
210 <div class="shop-buy-row">
210 <div id="shop-grid" class="shop-grid"></div>
211 <button id="shop-buy-1" type="button">Buy 1</button>
211 <div id="shop-detail" class="shop-detail" hidden>
212 <button id="shop-buy-5" type="button">Buy 5</button>
212 <img id="shop-detail-icon" alt="">
213 <button id="shop-buy-10" type="button">Buy 10</button>
213 <strong id="shop-detail-name"></strong>
214 <button id="shop-buy-x" type="button">Buy x</button>
214 <span id="shop-detail-price" class="hint"></span>
215 <span id="shop-detail-stock" class="hint"></span>
216 <div class="shop-buy-row">
217 <button id="shop-buy-1" type="button">Buy 1</button>
218 <button id="shop-buy-5" type="button">Buy 5</button>
219 <button id="shop-buy-10" type="button">Buy 10</button>
220 <button id="shop-buy-x" type="button">Buy x</button>
221 </div>
222 <p id="shop-bag-warn" class="shop-bag-warn" hidden>Inventory full; purchases will be sent to your bank.</p>
215 </div>
223 </div>
216 <p id="shop-bag-warn" class="shop-bag-warn" hidden>Inventory full; purchases will be sent to your bank.</p>
217 </div>
224 </div>
218 </div>
225 </section>
219 <div id="shop-sell-section" class="shop-sell-section" hidden>
226 <section id="shop-pane-sell" class="shop-pane" hidden>
220 <strong>Sell to shop</strong>
227 <div class="shop-body">
221 <div id="shop-sell-list" class="shop-sell-list"></div>
228 <div id="shop-sell-grid" class="item-grid shop-sell-grid"></div>
222 <div id="shop-sell-detail" class="shop-sell-detail" hidden>
229 <div id="shop-sell-detail" class="shop-detail shop-sell-detail" hidden>
223 <span id="shop-sell-price" class="hint"></span>
230 <img id="shop-sell-icon" alt="">
224 <span id="shop-sell-fee" class="hint" hidden></span>
231 <strong id="shop-sell-name"></strong>
225 <button id="shop-sell-confirm" type="button">Sell 1</button>
232 <span id="shop-sell-price" class="hint"></span>
233 <span id="shop-sell-fee" class="hint" hidden></span>
234 <div id="shop-sell-actions" class="shop-buy-row"></div>
235 <p id="shop-sell-empty" class="hint" hidden></p>
236 </div>
226 </div>
237 </div>
227 </div>
238 </section>
228 <p id="shop-coins" class="shop-coins">Coins: 0</p>
229 </aside>
239 </aside>
230
240
231 <div id="shop-qty-backdrop" class="modal-backdrop" hidden></div>
241 <div id="shop-qty-backdrop" class="modal-backdrop" hidden></div>
232 <aside id="shop-qty-panel" hidden>
242 <aside id="shop-qty-panel" hidden>
233 <header>
243 <header>
234 <h2>Buy quantity</h2>
244 <h2 id="shop-qty-title">Buy quantity</h2>
235 <button id="shop-qty-close" type="button">Close</button>
245 <button id="shop-qty-close" type="button">Close</button>
236 </header>
246 </header>
237 <p id="shop-qty-hint" class="hint"></p>
247 <p id="shop-qty-hint" class="hint"></p>
client/src/editor/tileConfigModal.js +179 −16
@@ -6,12 +6,14 @@ import {
6 6 normalizeSpawnerConfig,
7 7 MobId,
8 8 isHumanoidMob,
9 isCentralExchangeSpawner
9 isCentralExchangeSpawner,
10 spawnerEquipmentSlot
10 11 } from "/shared/definitions/mobs.js";
11 12 import { centralExchangeStaffCount } from "/shared/market/exchange.js";
12 import { ITEM_DEFINITIONS, itemDefinition } from "/shared/definitions/items.js";
13 import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js";
13 14 import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
14 15 import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
16 import { normalizeRgb } from "/shared/render/tint.js";
15 17
16 18 /** Items that can be worn in a given equipment slot. */
17 19 export function listEquippableItemsForSlot (slot)
@@ -31,6 +33,39 @@ export function listEquippableItemsForSlot (slot)
31 33 return out;
32 34 }
33 35
36 function emptyEquipDraft ()
37 {
38 return { itemId: null, dyeColor: null };
39 }
40
41 function equipDraftFromConfig (raw)
42 {
43 const { itemId, dyeColor } = spawnerEquipmentSlot(raw);
44 return {
45 itemId: itemId > 0 ? itemId : null,
46 dyeColor: dyeColor ? normalizeRgb(dyeColor) : null
47 };
48 }
49
50 function equipConfigFromDraft (draft)
51 {
52 const itemId = draft?.itemId;
53 if (itemId == null || itemId === "")
54 { return null; }
55 const id = Number(itemId) || null;
56 if (!id)
57 { return null; }
58 if (draft.dyeColor && isDyeableClothing(id))
59 { return { itemId: id, dyeColor: normalizeRgb(draft.dyeColor) }; }
60 return id;
61 }
62
63 function rgbToCss (color)
64 {
65 const c = normalizeRgb(color, { r: 0.78, g: 0.31, b: 0.47 });
66 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
67 }
68
34 69 export function initTileConfigModal ({ onSave, onRemove })
35 70 {
36 71 const backdrop = document.getElementById("tile-config-backdrop");
@@ -42,14 +77,26 @@ export function initTileConfigModal ({ onSave, onRemove })
42 77 const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null;
43 78 const itemSearchInput = document.getElementById("shop-item-search-input");
44 79 const itemSearchResults = document.getElementById("shop-item-search-results");
80 const dyeBackdrop = document.getElementById("equip-dye-backdrop");
81 const dyeModal = document.getElementById("equip-dye-modal");
82 const dyeTitle = document.getElementById("equip-dye-title");
83 const dyePreview = document.getElementById("equip-dye-preview");
84 const dyeR = document.getElementById("equip-dye-r");
85 const dyeG = document.getElementById("equip-dye-g");
86 const dyeB = document.getElementById("equip-dye-b");
87 const dyeRNum = document.getElementById("equip-dye-r-num");
88 const dyeGNum = document.getElementById("equip-dye-g-num");
89 const dyeBNum = document.getElementById("equip-dye-b-num");
45 90 let open = false;
46 91 let context = null;
47 92 /** @type {{ itemId: number, quantity: number }[]} */
48 93 let sellsDraft = [];
49 /** @type {Record<string, number|null>} */
94 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
50 95 let equipmentDraft = {};
51 96 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */
52 97 let itemSearchMode = null;
98 /** @type {string|null} */
99 let dyeEditSlot = null;
53 100
54 101 function show (visible)
55 102 {
@@ -60,6 +107,7 @@ export function initTileConfigModal ({ onSave, onRemove })
60 107 {
61 108 context = null;
62 109 closeItemSearch();
110 closeDyePicker();
63 111 }
64 112 }
65 113
@@ -139,7 +187,10 @@ export function initTileConfigModal ({ onSave, onRemove })
139 187 {
140 188 if (itemSearchMode?.kind === "equip")
141 189 {
142 equipmentDraft[itemSearchMode.slot] = item.itemId;
190 equipmentDraft[itemSearchMode.slot] = {
191 itemId: item.itemId,
192 dyeColor: null
193 };
143 194 renderEquipmentRows();
144 195 }
145 196 else
@@ -153,6 +204,88 @@ export function initTileConfigModal ({ onSave, onRemove })
153 204 }
154 205 }
155 206
207 function closeDyePicker ()
208 {
209 dyeEditSlot = null;
210 if (dyeBackdrop)
211 { dyeBackdrop.hidden = true; }
212 if (dyeModal)
213 { dyeModal.hidden = true; }
214 }
215
216 function readDyeSliders ()
217 {
218 return {
219 r: Math.min(255, Math.max(0, Number(dyeR?.value) || 0)) / 255,
220 g: Math.min(255, Math.max(0, Number(dyeG?.value) || 0)) / 255,
221 b: Math.min(255, Math.max(0, Number(dyeB?.value) || 0)) / 255
222 };
223 }
224
225 function syncDyePreview ()
226 {
227 const color = readDyeSliders();
228 if (dyePreview)
229 { dyePreview.style.background = rgbToCss(color); }
230 if (dyeRNum)
231 { dyeRNum.value = String(Math.round(color.r * 255)); }
232 if (dyeGNum)
233 { dyeGNum.value = String(Math.round(color.g * 255)); }
234 if (dyeBNum)
235 { dyeBNum.value = String(Math.round(color.b * 255)); }
236 }
237
238 function setDyeSliders (color)
239 {
240 const c = normalizeRgb(color, { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
241 const r = Math.round(c.r * 255);
242 const g = Math.round(c.g * 255);
243 const b = Math.round(c.b * 255);
244 if (dyeR)
245 { dyeR.value = String(r); }
246 if (dyeG)
247 { dyeG.value = String(g); }
248 if (dyeB)
249 { dyeB.value = String(b); }
250 syncDyePreview();
251 }
252
253 function openDyePicker (slot)
254 {
255 const draft = equipmentDraft[slot];
256 if (!draft?.itemId || !isDyeableClothing(draft.itemId) || !dyeModal || !dyeBackdrop)
257 { return; }
258 dyeEditSlot = slot;
259 const def = itemDefinition(draft.itemId);
260 if (dyeTitle)
261 { dyeTitle.textContent = `Dye — ${def?.displayName ?? slot}`; }
262 setDyeSliders(draft.dyeColor ?? { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
263 dyeBackdrop.hidden = false;
264 dyeModal.hidden = false;
265 }
266
267 function bindDyeChannel (range, num)
268 {
269 range?.addEventListener("input", () =>
270 {
271 if (num)
272 { num.value = range.value; }
273 syncDyePreview();
274 });
275 num?.addEventListener("input", () =>
276 {
277 const v = Math.min(255, Math.max(0, Number(num.value) || 0));
278 num.value = String(v);
279 if (range)
280 { range.value = String(v); }
281 syncDyePreview();
282 });
283 }
284
285 bindDyeChannel(dyeR, dyeRNum);
286 bindDyeChannel(dyeG, dyeGNum);
287 bindDyeChannel(dyeB, dyeBNum);
288
156 289 function renderSellsList ()
157 290 {
158 291 const list = form.querySelector("[data-sells-list]");
@@ -207,8 +340,10 @@ export function initTileConfigModal ({ onSave, onRemove })
207 340 list.innerHTML = "";
208 341 for (const slot of EQUIPMENT_SLOTS)
209 342 {
210 const itemId = equipmentDraft[slot] ?? null;
343 const draft = equipmentDraft[slot] ?? emptyEquipDraft();
344 const itemId = draft.itemId ?? null;
211 345 const def = itemId ? itemDefinition(itemId) : null;
346 const dyeable = itemId != null && isDyeableClothing(itemId);
212 347 const row = document.createElement("div");
213 348 row.className = "spawner-equip-row";
214 349 const label = document.createElement("span");
@@ -216,21 +351,37 @@ export function initTileConfigModal ({ onSave, onRemove })
216 351 label.textContent = slot;
217 352 const name = document.createElement("span");
218 353 name.className = "spawner-equip-name";
219 name.textContent = def?.displayName ?? "(none)";
354 if (def && draft.dyeColor)
355 {
356 const swatch = document.createElement("span");
357 swatch.className = "spawner-equip-dye-swatch";
358 swatch.style.background = rgbToCss(draft.dyeColor);
359 name.append(swatch, document.createTextNode(def.displayName));
360 }
361 else
362 { name.textContent = def?.displayName ?? "(none)"; }
220 363 const pick = document.createElement("button");
221 364 pick.type = "button";
222 365 pick.textContent = "Choose…";
223 366 pick.addEventListener("click", () => openEquipItemSearch(slot));
367 const dyeBtn = document.createElement("button");
368 dyeBtn.type = "button";
369 dyeBtn.textContent = "Dye…";
370 dyeBtn.disabled = !dyeable;
371 dyeBtn.title = dyeable
372 ? "Set clothing dye colour"
373 : "Only tailor clothing can be dyed";
374 dyeBtn.addEventListener("click", () => openDyePicker(slot));
224 375 const clear = document.createElement("button");
225 376 clear.type = "button";
226 377 clear.textContent = "Clear";
227 378 clear.disabled = itemId == null;
228 379 clear.addEventListener("click", () =>
229 380 {
230 equipmentDraft[slot] = null;
381 equipmentDraft[slot] = emptyEquipDraft();
231 382 renderEquipmentRows();
232 383 });
233 row.append(label, name, pick, clear);
384 row.append(label, name, pick, dyeBtn, clear);
234 385 list.append(row);
235 386 }
236 387 }
@@ -270,10 +421,7 @@ export function initTileConfigModal ({ onSave, onRemove })
270 421
271 422 equipmentDraft = {};
272 423 for (const slot of EQUIPMENT_SLOTS)
273 {
274 const raw = config.equipment?.[slot];
275 equipmentDraft[slot] = raw != null && raw !== "" ? Number(raw) || null : null;
276 }
424 { equipmentDraft[slot] = equipDraftFromConfig(config.equipment?.[slot]); }
277 425 queueMicrotask(() => renderEquipmentRows());
278 426
279 427 if (!exchange)
@@ -393,6 +541,24 @@ export function initTileConfigModal ({ onSave, onRemove })
393 541 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
394 542 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
395 543 itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
544 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
545 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
546 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
547 {
548 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
549 { return; }
550 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
551 closeDyePicker();
552 renderEquipmentRows();
553 });
554 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
555 {
556 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
557 { return; }
558 equipmentDraft[dyeEditSlot].dyeColor = null;
559 closeDyePicker();
560 renderEquipmentRows();
561 });
396 562
397 563 document.getElementById("tile-config-save").addEventListener("click", () =>
398 564 {
@@ -401,10 +567,7 @@ export function initTileConfigModal ({ onSave, onRemove })
401 567 const data = new FormData(form);
402 568 const equipment = {};
403 569 for (const slot of EQUIPMENT_SLOTS)
404 {
405 const raw = equipmentDraft[slot];
406 equipment[slot] = raw != null && raw !== "" ? Number(raw) || null : null;
407 }
570 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
408 571 onSave?.(context, normalizeSpawnerConfig({
409 572 mobTypeId: String(data.get("mobTypeId") || "deer"),
410 573 maxAlive: Number(data.get("maxAlive") || 3),
@@ -6,12 +6,14 @@ import {
6 normalizeSpawnerConfig,
6 normalizeSpawnerConfig,
7 MobId,
7 MobId,
8 isHumanoidMob,
8 isHumanoidMob,
9 isCentralExchangeSpawner
9 isCentralExchangeSpawner,
10 spawnerEquipmentSlot
10} from "/shared/definitions/mobs.js";
11} from "/shared/definitions/mobs.js";
11import { centralExchangeStaffCount } from "/shared/market/exchange.js";
12import { centralExchangeStaffCount } from "/shared/market/exchange.js";
12import { ITEM_DEFINITIONS, itemDefinition } from "/shared/definitions/items.js";
13import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js";
13import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
14import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
14import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
15import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
16import { normalizeRgb } from "/shared/render/tint.js";
15
17
16/** Items that can be worn in a given equipment slot. */
18/** Items that can be worn in a given equipment slot. */
17export function listEquippableItemsForSlot (slot)
19export function listEquippableItemsForSlot (slot)
@@ -31,6 +33,39 @@ export function listEquippableItemsForSlot (slot)
31 return out;
33 return out;
32}
34}
33
35
36function emptyEquipDraft ()
37{
38 return { itemId: null, dyeColor: null };
39}
40
41function equipDraftFromConfig (raw)
42{
43 const { itemId, dyeColor } = spawnerEquipmentSlot(raw);
44 return {
45 itemId: itemId > 0 ? itemId : null,
46 dyeColor: dyeColor ? normalizeRgb(dyeColor) : null
47 };
48}
49
50function equipConfigFromDraft (draft)
51{
52 const itemId = draft?.itemId;
53 if (itemId == null || itemId === "")
54 { return null; }
55 const id = Number(itemId) || null;
56 if (!id)
57 { return null; }
58 if (draft.dyeColor && isDyeableClothing(id))
59 { return { itemId: id, dyeColor: normalizeRgb(draft.dyeColor) }; }
60 return id;
61}
62
63function rgbToCss (color)
64{
65 const c = normalizeRgb(color, { r: 0.78, g: 0.31, b: 0.47 });
66 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
67}
68
34export function initTileConfigModal ({ onSave, onRemove })
69export function initTileConfigModal ({ onSave, onRemove })
35{
70{
36 const backdrop = document.getElementById("tile-config-backdrop");
71 const backdrop = document.getElementById("tile-config-backdrop");
@@ -42,14 +77,26 @@ export function initTileConfigModal ({ onSave, onRemove })
42 const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null;
77 const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null;
43 const itemSearchInput = document.getElementById("shop-item-search-input");
78 const itemSearchInput = document.getElementById("shop-item-search-input");
44 const itemSearchResults = document.getElementById("shop-item-search-results");
79 const itemSearchResults = document.getElementById("shop-item-search-results");
80 const dyeBackdrop = document.getElementById("equip-dye-backdrop");
81 const dyeModal = document.getElementById("equip-dye-modal");
82 const dyeTitle = document.getElementById("equip-dye-title");
83 const dyePreview = document.getElementById("equip-dye-preview");
84 const dyeR = document.getElementById("equip-dye-r");
85 const dyeG = document.getElementById("equip-dye-g");
86 const dyeB = document.getElementById("equip-dye-b");
87 const dyeRNum = document.getElementById("equip-dye-r-num");
88 const dyeGNum = document.getElementById("equip-dye-g-num");
89 const dyeBNum = document.getElementById("equip-dye-b-num");
45 let open = false;
90 let open = false;
46 let context = null;
91 let context = null;
47 /** @type {{ itemId: number, quantity: number }[]} */
92 /** @type {{ itemId: number, quantity: number }[]} */
48 let sellsDraft = [];
93 let sellsDraft = [];
49 /** @type {Record<string, number|null>} */
94 /** @type {Record<string, { itemId: number|null, dyeColor: {r:number,g:number,b:number}|null }>} */
50 let equipmentDraft = {};
95 let equipmentDraft = {};
51 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */
96 /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */
52 let itemSearchMode = null;
97 let itemSearchMode = null;
98 /** @type {string|null} */
99 let dyeEditSlot = null;
53
100
54 function show (visible)
101 function show (visible)
55 {
102 {
@@ -60,6 +107,7 @@ export function initTileConfigModal ({ onSave, onRemove })
60 {
107 {
61 context = null;
108 context = null;
62 closeItemSearch();
109 closeItemSearch();
110 closeDyePicker();
63 }
111 }
64 }
112 }
65
113
@@ -139,7 +187,10 @@ export function initTileConfigModal ({ onSave, onRemove })
139 {
187 {
140 if (itemSearchMode?.kind === "equip")
188 if (itemSearchMode?.kind === "equip")
141 {
189 {
142 equipmentDraft[itemSearchMode.slot] = item.itemId;
190 equipmentDraft[itemSearchMode.slot] = {
191 itemId: item.itemId,
192 dyeColor: null
193 };
143 renderEquipmentRows();
194 renderEquipmentRows();
144 }
195 }
145 else
196 else
@@ -153,6 +204,88 @@ export function initTileConfigModal ({ onSave, onRemove })
153 }
204 }
154 }
205 }
155
206
207 function closeDyePicker ()
208 {
209 dyeEditSlot = null;
210 if (dyeBackdrop)
211 { dyeBackdrop.hidden = true; }
212 if (dyeModal)
213 { dyeModal.hidden = true; }
214 }
215
216 function readDyeSliders ()
217 {
218 return {
219 r: Math.min(255, Math.max(0, Number(dyeR?.value) || 0)) / 255,
220 g: Math.min(255, Math.max(0, Number(dyeG?.value) || 0)) / 255,
221 b: Math.min(255, Math.max(0, Number(dyeB?.value) || 0)) / 255
222 };
223 }
224
225 function syncDyePreview ()
226 {
227 const color = readDyeSliders();
228 if (dyePreview)
229 { dyePreview.style.background = rgbToCss(color); }
230 if (dyeRNum)
231 { dyeRNum.value = String(Math.round(color.r * 255)); }
232 if (dyeGNum)
233 { dyeGNum.value = String(Math.round(color.g * 255)); }
234 if (dyeBNum)
235 { dyeBNum.value = String(Math.round(color.b * 255)); }
236 }
237
238 function setDyeSliders (color)
239 {
240 const c = normalizeRgb(color, { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
241 const r = Math.round(c.r * 255);
242 const g = Math.round(c.g * 255);
243 const b = Math.round(c.b * 255);
244 if (dyeR)
245 { dyeR.value = String(r); }
246 if (dyeG)
247 { dyeG.value = String(g); }
248 if (dyeB)
249 { dyeB.value = String(b); }
250 syncDyePreview();
251 }
252
253 function openDyePicker (slot)
254 {
255 const draft = equipmentDraft[slot];
256 if (!draft?.itemId || !isDyeableClothing(draft.itemId) || !dyeModal || !dyeBackdrop)
257 { return; }
258 dyeEditSlot = slot;
259 const def = itemDefinition(draft.itemId);
260 if (dyeTitle)
261 { dyeTitle.textContent = `Dye — ${def?.displayName ?? slot}`; }
262 setDyeSliders(draft.dyeColor ?? { r: 200 / 255, g: 80 / 255, b: 120 / 255 });
263 dyeBackdrop.hidden = false;
264 dyeModal.hidden = false;
265 }
266
267 function bindDyeChannel (range, num)
268 {
269 range?.addEventListener("input", () =>
270 {
271 if (num)
272 { num.value = range.value; }
273 syncDyePreview();
274 });
275 num?.addEventListener("input", () =>
276 {
277 const v = Math.min(255, Math.max(0, Number(num.value) || 0));
278 num.value = String(v);
279 if (range)
280 { range.value = String(v); }
281 syncDyePreview();
282 });
283 }
284
285 bindDyeChannel(dyeR, dyeRNum);
286 bindDyeChannel(dyeG, dyeGNum);
287 bindDyeChannel(dyeB, dyeBNum);
288
156 function renderSellsList ()
289 function renderSellsList ()
157 {
290 {
158 const list = form.querySelector("[data-sells-list]");
291 const list = form.querySelector("[data-sells-list]");
@@ -207,8 +340,10 @@ export function initTileConfigModal ({ onSave, onRemove })
207 list.innerHTML = "";
340 list.innerHTML = "";
208 for (const slot of EQUIPMENT_SLOTS)
341 for (const slot of EQUIPMENT_SLOTS)
209 {
342 {
210 const itemId = equipmentDraft[slot] ?? null;
343 const draft = equipmentDraft[slot] ?? emptyEquipDraft();
344 const itemId = draft.itemId ?? null;
211 const def = itemId ? itemDefinition(itemId) : null;
345 const def = itemId ? itemDefinition(itemId) : null;
346 const dyeable = itemId != null && isDyeableClothing(itemId);
212 const row = document.createElement("div");
347 const row = document.createElement("div");
213 row.className = "spawner-equip-row";
348 row.className = "spawner-equip-row";
214 const label = document.createElement("span");
349 const label = document.createElement("span");
@@ -216,21 +351,37 @@ export function initTileConfigModal ({ onSave, onRemove })
216 label.textContent = slot;
351 label.textContent = slot;
217 const name = document.createElement("span");
352 const name = document.createElement("span");
218 name.className = "spawner-equip-name";
353 name.className = "spawner-equip-name";
219 name.textContent = def?.displayName ?? "(none)";
354 if (def && draft.dyeColor)
355 {
356 const swatch = document.createElement("span");
357 swatch.className = "spawner-equip-dye-swatch";
358 swatch.style.background = rgbToCss(draft.dyeColor);
359 name.append(swatch, document.createTextNode(def.displayName));
360 }
361 else
362 { name.textContent = def?.displayName ?? "(none)"; }
220 const pick = document.createElement("button");
363 const pick = document.createElement("button");
221 pick.type = "button";
364 pick.type = "button";
222 pick.textContent = "Choose…";
365 pick.textContent = "Choose…";
223 pick.addEventListener("click", () => openEquipItemSearch(slot));
366 pick.addEventListener("click", () => openEquipItemSearch(slot));
367 const dyeBtn = document.createElement("button");
368 dyeBtn.type = "button";
369 dyeBtn.textContent = "Dye…";
370 dyeBtn.disabled = !dyeable;
371 dyeBtn.title = dyeable
372 ? "Set clothing dye colour"
373 : "Only tailor clothing can be dyed";
374 dyeBtn.addEventListener("click", () => openDyePicker(slot));
224 const clear = document.createElement("button");
375 const clear = document.createElement("button");
225 clear.type = "button";
376 clear.type = "button";
226 clear.textContent = "Clear";
377 clear.textContent = "Clear";
227 clear.disabled = itemId == null;
378 clear.disabled = itemId == null;
228 clear.addEventListener("click", () =>
379 clear.addEventListener("click", () =>
229 {
380 {
230 equipmentDraft[slot] = null;
381 equipmentDraft[slot] = emptyEquipDraft();
231 renderEquipmentRows();
382 renderEquipmentRows();
232 });
383 });
233 row.append(label, name, pick, clear);
384 row.append(label, name, pick, dyeBtn, clear);
234 list.append(row);
385 list.append(row);
235 }
386 }
236 }
387 }
@@ -270,10 +421,7 @@ export function initTileConfigModal ({ onSave, onRemove })
270
421
271 equipmentDraft = {};
422 equipmentDraft = {};
272 for (const slot of EQUIPMENT_SLOTS)
423 for (const slot of EQUIPMENT_SLOTS)
273 {
424 { equipmentDraft[slot] = equipDraftFromConfig(config.equipment?.[slot]); }
274 const raw = config.equipment?.[slot];
275 equipmentDraft[slot] = raw != null && raw !== "" ? Number(raw) || null : null;
276 }
277 queueMicrotask(() => renderEquipmentRows());
425 queueMicrotask(() => renderEquipmentRows());
278
426
279 if (!exchange)
427 if (!exchange)
@@ -393,6 +541,24 @@ export function initTileConfigModal ({ onSave, onRemove })
393 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
541 document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch());
394 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
542 itemSearchBackdrop?.addEventListener("click", () => closeItemSearch());
395 itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
543 itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value));
544 document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker());
545 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
546 document.getElementById("equip-dye-apply")?.addEventListener("click", () =>
547 {
548 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
549 { return; }
550 equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders();
551 closeDyePicker();
552 renderEquipmentRows();
553 });
554 document.getElementById("equip-dye-clear")?.addEventListener("click", () =>
555 {
556 if (!dyeEditSlot || !equipmentDraft[dyeEditSlot])
557 { return; }
558 equipmentDraft[dyeEditSlot].dyeColor = null;
559 closeDyePicker();
560 renderEquipmentRows();
561 });
396
562
397 document.getElementById("tile-config-save").addEventListener("click", () =>
563 document.getElementById("tile-config-save").addEventListener("click", () =>
398 {
564 {
@@ -401,10 +567,7 @@ export function initTileConfigModal ({ onSave, onRemove })
401 const data = new FormData(form);
567 const data = new FormData(form);
402 const equipment = {};
568 const equipment = {};
403 for (const slot of EQUIPMENT_SLOTS)
569 for (const slot of EQUIPMENT_SLOTS)
404 {
570 { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); }
405 const raw = equipmentDraft[slot];
406 equipment[slot] = raw != null && raw !== "" ? Number(raw) || null : null;
407 }
408 onSave?.(context, normalizeSpawnerConfig({
571 onSave?.(context, normalizeSpawnerConfig({
409 mobTypeId: String(data.get("mobTypeId") || "deer"),
572 mobTypeId: String(data.get("mobTypeId") || "deer"),
410 maxAlive: Number(data.get("maxAlive") || 3),
573 maxAlive: Number(data.get("maxAlive") || 3),
client/src/play/crafting.js +7 −2
@@ -269,7 +269,8 @@ export function initCrafting ({
269 269 return;
270 270 }
271 271 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
272 if (canStartCraft(slotsSnapshot, recipe, skill))
272 const craftOpts = { dyeSlotIndex };
273 if (canStartCraft(slotsSnapshot, recipe, skill, craftOpts))
273 274 {
274 275 statusEl.textContent = "";
275 276 craftButton.disabled = false;
@@ -279,6 +280,10 @@ export function initCrafting ({
279 280 {
280 281 statusEl.textContent = "Missing materials.";
281 282 }
283 else if (recipe.consumeDye && dyeSlotIndex != null)
284 {
285 statusEl.textContent = "Not enough bag space (need room for the result or a partially used dye).";
286 }
282 287 else
283 288 {
284 289 statusEl.textContent = "Not enough bag space for the result.";
@@ -335,7 +340,7 @@ export function initCrafting ({
335 340 if (!recipe || crafting)
336 341 { return; }
337 342 const slots = getInventorySlots?.() ?? [];
338 if (!canStartCraft(slots, recipe, stationSkillLevel()))
343 if (!canStartCraft(slots, recipe, stationSkillLevel(), { dyeSlotIndex }))
339 344 {
340 345 renderDetail();
341 346 return;
@@ -269,7 +269,8 @@ export function initCrafting ({
269 return;
269 return;
270 }
270 }
271 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
271 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
272 if (canStartCraft(slotsSnapshot, recipe, skill))
272 const craftOpts = { dyeSlotIndex };
273 if (canStartCraft(slotsSnapshot, recipe, skill, craftOpts))
273 {
274 {
274 statusEl.textContent = "";
275 statusEl.textContent = "";
275 craftButton.disabled = false;
276 craftButton.disabled = false;
@@ -279,6 +280,10 @@ export function initCrafting ({
279 {
280 {
280 statusEl.textContent = "Missing materials.";
281 statusEl.textContent = "Missing materials.";
281 }
282 }
283 else if (recipe.consumeDye && dyeSlotIndex != null)
284 {
285 statusEl.textContent = "Not enough bag space (need room for the result or a partially used dye).";
286 }
282 else
287 else
283 {
288 {
284 statusEl.textContent = "Not enough bag space for the result.";
289 statusEl.textContent = "Not enough bag space for the result.";
@@ -335,7 +340,7 @@ export function initCrafting ({
335 if (!recipe || crafting)
340 if (!recipe || crafting)
336 { return; }
341 { return; }
337 const slots = getInventorySlots?.() ?? [];
342 const slots = getInventorySlots?.() ?? [];
338 if (!canStartCraft(slots, recipe, stationSkillLevel()))
343 if (!canStartCraft(slots, recipe, stationSkillLevel(), { dyeSlotIndex }))
339 {
344 {
340 renderDetail();
345 renderDetail();
341 return;
346 return;
client/src/play/inventory.js +7 −0
@@ -315,6 +315,13 @@ export function initInventory ({
315 315 onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex })
316 316 });
317 317 }
318 if (slot.itemId === ItemId.potion && slot.instance?.kind === "potion")
319 {
320 items.push({
321 label: "Drink",
322 onSelect: () => socket.send({ type: MessageType.drinkItem, slotIndex })
323 });
324 }
318 325 items.push({
319 326 label: "Drop",
320 327 onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
@@ -315,6 +315,13 @@ export function initInventory ({
315 onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex })
315 onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex })
316 });
316 });
317 }
317 }
318 if (slot.itemId === ItemId.potion && slot.instance?.kind === "potion")
319 {
320 items.push({
321 label: "Drink",
322 onSelect: () => socket.send({ type: MessageType.drinkItem, slotIndex })
323 });
324 }
318 items.push({
325 items.push({
319 label: "Drop",
326 label: "Drop",
320 onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
327 onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
client/src/play/shop.js +241 −63
@@ -4,7 +4,7 @@ import {
4 4 itemAssetPathForStack,
5 5 formatQuantity
6 6 } from "/shared/definitions/items.js";
7 import { insertStack } from "/shared/items/inventory.js";
7 import { insertStack, stackQuantity } from "/shared/items/inventory.js";
8 8 import {
9 9 canPlayerSellToNpc,
10 10 resolveShopSellQuote
@@ -23,6 +23,10 @@ export function initShop ({
23 23 const backdrop = document.getElementById("shop-backdrop");
24 24 const panel = document.getElementById("shop-panel");
25 25 const title = document.getElementById("shop-title");
26 const tabBuy = document.getElementById("shop-tab-buy");
27 const tabSell = document.getElementById("shop-tab-sell");
28 const paneBuy = document.getElementById("shop-pane-buy");
29 const paneSell = document.getElementById("shop-pane-sell");
26 30 const grid = document.getElementById("shop-grid");
27 31 const detail = document.getElementById("shop-detail");
28 32 const detailIcon = document.getElementById("shop-detail-icon");
@@ -31,14 +35,18 @@ export function initShop ({
31 35 const detailStock = document.getElementById("shop-detail-stock");
32 36 const bagWarn = document.getElementById("shop-bag-warn");
33 37 const coinsEl = document.getElementById("shop-coins");
34 const sellSection = document.getElementById("shop-sell-section");
35 const sellList = document.getElementById("shop-sell-list");
38 const sellGrid = document.getElementById("shop-sell-grid");
36 39 const sellDetail = document.getElementById("shop-sell-detail");
40 const sellIcon = document.getElementById("shop-sell-icon");
41 const sellName = document.getElementById("shop-sell-name");
37 42 const sellPrice = document.getElementById("shop-sell-price");
38 43 const sellFee = document.getElementById("shop-sell-fee");
39 const sellConfirm = document.getElementById("shop-sell-confirm");
44 const sellActions = document.getElementById("shop-sell-actions");
45 const sellEmpty = document.getElementById("shop-sell-empty");
40 46 const qtyBackdrop = document.getElementById("shop-qty-backdrop");
41 47 const qtyPanel = document.getElementById("shop-qty-panel");
48 const qtyTitle = document.getElementById("shop-qty-title");
49 const qtyConfirm = document.getElementById("shop-qty-confirm");
42 50 const qtyInput = document.getElementById("shop-qty-input");
43 51 const qtyHint = document.getElementById("shop-qty-hint");
44 52
@@ -49,6 +57,10 @@ export function initShop ({
49 57 let buysItems = false;
50 58 let displayName = "Shop";
51 59 let sex = "male";
60 /** @type {"buy"|"sell"} */
61 let activeTab = "buy";
62 /** @type {"buy"|"sell"|null} */
63 let qtyMode = null;
52 64
53 65 function suppressWorldClick ()
54 66 {
@@ -77,19 +89,43 @@ export function initShop ({
77 89 event.stopPropagation();
78 90 suppressWorldClick();
79 91 });
92 tabBuy?.addEventListener("click", () => setTab("buy"));
93 tabSell?.addEventListener("click", () => setTab("sell"));
80 94 document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1));
81 95 document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5));
82 96 document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10));
83 document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal());
97 document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal("buy"));
84 98 document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal());
85 document.getElementById("shop-qty-confirm")?.addEventListener("click", () => confirmQtyBuy());
99 qtyConfirm?.addEventListener("click", () => confirmQtyModal());
86 100 qtyBackdrop?.addEventListener("click", () => closeQtyModal());
87 101 qtyInput?.addEventListener("keydown", (event) =>
88 102 {
89 103 if (event.key === "Enter")
90 { confirmQtyBuy(); }
104 { confirmQtyModal(); }
91 105 });
92 sellConfirm?.addEventListener("click", () => sellSelected());
106
107 function setTab (tab)
108 {
109 if (tab === "sell" && !buysItems)
110 { tab = "buy"; }
111 activeTab = tab;
112 const buyActive = tab === "buy";
113 if (tabBuy)
114 {
115 tabBuy.classList.toggle("active", buyActive);
116 tabBuy.setAttribute("aria-selected", buyActive ? "true" : "false");
117 }
118 if (tabSell)
119 {
120 tabSell.classList.toggle("active", !buyActive);
121 tabSell.setAttribute("aria-selected", buyActive ? "false" : "true");
122 }
123 if (paneBuy)
124 { paneBuy.hidden = !buyActive; }
125 if (paneSell)
126 { paneSell.hidden = buyActive; }
127 render();
128 }
93 129
94 130 function open (payload)
95 131 {
@@ -101,8 +137,10 @@ export function initShop ({
101 137 stock = Array.isArray(payload.stock) ? payload.stock : [];
102 138 if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId))
103 139 { selectedListingId = stock[0]?.listingId ?? null; }
140 if (tabSell)
141 { tabSell.hidden = !buysItems; }
104 142 closeQtyModal();
105 render();
143 setTab(buysItems && activeTab === "sell" ? "sell" : "buy");
106 144 backdrop.hidden = false;
107 145 panel.hidden = false;
108 146 suppressWorldClick();
@@ -120,6 +158,7 @@ export function initShop ({
120 158 selectedSellSlotIndex = null;
121 159 buysItems = false;
122 160 sex = "male";
161 activeTab = "buy";
123 162 suppressWorldClick();
124 163 if (notifyServer && closingNpcId)
125 164 {
@@ -176,16 +215,43 @@ export function initShop ({
176 215 });
177 216 }
178 217
179 function openQtyModal ()
218 function openQtyModal (mode)
180 219 {
181 const entry = selectedEntry();
182 if (!entry)
183 { return; }
184 const max = maxBuyable(entry);
185 if (max < 1)
186 { return; }
187 qtyInput.value = String(Math.min(max, 1));
188 qtyHint.textContent = `Max ${max}`;
220 qtyMode = mode;
221 if (mode === "buy")
222 {
223 const entry = selectedEntry();
224 if (!entry)
225 { return; }
226 const max = maxBuyable(entry);
227 if (max < 1)
228 { return; }
229 if (qtyTitle)
230 { qtyTitle.textContent = "Buy quantity"; }
231 if (qtyConfirm)
232 { qtyConfirm.textContent = "Buy"; }
233 qtyInput.min = "1";
234 qtyInput.max = String(max);
235 qtyInput.value = String(Math.min(max, 1));
236 qtyHint.textContent = `Max ${max}`;
237 }
238 else
239 {
240 const slot = selectedSellSlot();
241 if (!slot)
242 { return; }
243 const max = Math.max(1, stackQuantity(slot.quantity));
244 if (max < 4)
245 { return; }
246 if (qtyTitle)
247 { qtyTitle.textContent = "Sell quantity"; }
248 if (qtyConfirm)
249 { qtyConfirm.textContent = "Sell"; }
250 qtyInput.min = "1";
251 qtyInput.max = String(max);
252 qtyInput.value = "1";
253 qtyHint.textContent = `Max ${max}`;
254 }
189 255 qtyBackdrop.hidden = false;
190 256 qtyPanel.hidden = false;
191 257 suppressWorldClick();
@@ -195,12 +261,27 @@ export function initShop ({
195 261
196 262 function closeQtyModal ()
197 263 {
264 qtyMode = null;
198 265 qtyBackdrop.hidden = true;
199 266 qtyPanel.hidden = true;
200 267 }
201 268
202 function confirmQtyBuy ()
269 function confirmQtyModal ()
203 270 {
271 if (qtyMode === "sell")
272 {
273 const slot = selectedSellSlot();
274 if (!slot)
275 {
276 closeQtyModal();
277 return;
278 }
279 const max = Math.max(1, stackQuantity(slot.quantity));
280 const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1));
281 closeQtyModal();
282 sellQuantity(qty);
283 return;
284 }
204 285 const entry = selectedEntry();
205 286 if (!entry)
206 287 {
@@ -224,40 +305,90 @@ export function initShop ({
224 305 return slot;
225 306 }
226 307
227 function sellSelected ()
308 function sellQuantity (quantity)
228 309 {
229 310 if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot())
230 311 { return; }
312 const slot = selectedSellSlot();
313 const max = Math.max(1, stackQuantity(slot.quantity));
314 const qty = Math.min(max, Math.max(1, quantity | 0 || 1));
231 315 socket.send({
232 316 type: MessageType.sellToShop,
233 317 npcEntityId,
234 318 slotIndex: selectedSellSlotIndex,
235 quantity: 1
319 quantity: qty
236 320 });
237 321 }
238 322
323 function renderSellActions (slot)
324 {
325 if (!sellActions)
326 { return; }
327 sellActions.replaceChildren();
328 const qty = Math.max(1, stackQuantity(slot.quantity));
329 const addBtn = (label, onClick) =>
330 {
331 const btn = document.createElement("button");
332 btn.type = "button";
333 btn.textContent = label;
334 btn.addEventListener("click", onClick);
335 sellActions.append(btn);
336 };
337 if (qty <= 1)
338 {
339 addBtn("Sell", () => sellQuantity(1));
340 return;
341 }
342 addBtn("Sell 1", () => sellQuantity(1));
343 if (qty === 2)
344 {
345 addBtn("Sell all", () => sellQuantity(qty));
346 return;
347 }
348 if (qty === 3)
349 {
350 addBtn("Sell 2", () => sellQuantity(2));
351 addBtn("Sell all", () => sellQuantity(qty));
352 return;
353 }
354 addBtn("Sell x", () => openQtyModal("sell"));
355 addBtn("Sell all", () => sellQuantity(qty));
356 }
357
239 358 function renderSellDetail ()
240 359 {
241 if (!sellDetail || !sellPrice || !sellFee || !sellConfirm)
360 if (!sellDetail || !sellPrice || !sellFee)
242 361 { return; }
243 362 const slot = selectedSellSlot();
244 363 if (!slot)
245 364 {
246 365 sellDetail.hidden = true;
247 366 sellFee.hidden = true;
367 if (sellActions)
368 { sellActions.replaceChildren(); }
248 369 return;
249 370 }
250 const quote = resolveShopSellQuote(slot, { quantity: 1 });
251 if (!quote)
371 const quote = resolveShopSellQuote(slot, {
372 quantity: Math.max(1, stackQuantity(slot.quantity))
373 });
374 const unitQuote = resolveShopSellQuote(slot, { quantity: 1 });
375 if (!quote || !unitQuote)
252 376 {
253 377 sellDetail.hidden = true;
254 378 sellFee.hidden = true;
255 379 return;
256 380 }
257 381 sellDetail.hidden = false;
382 if (sellEmpty)
383 { sellEmpty.hidden = true; }
384 const name = itemDisplayName(slot);
385 if (sellName)
386 { sellName.textContent = name; }
387 if (sellIcon)
388 { applyItemIcon(sellIcon, slot, itemAssetPathForStack(slot)); }
258 389 sellPrice.textContent = quote.isCheque
259 390 ? `You receive ${formatQuantity(quote.payout)} coins`
260 : `${formatQuantity(quote.unitPrice)} coins each`;
391 : `${formatQuantity(unitQuote.unitPrice)} coins each`;
261 392 if (quote.isCheque)
262 393 {
263 394 sellFee.hidden = false;
@@ -268,73 +399,110 @@ export function initShop ({
268 399 sellFee.hidden = true;
269 400 sellFee.textContent = "";
270 401 }
271 sellConfirm.disabled = false;
402 renderSellActions(slot);
272 403 }
273 404
274 function renderSellList ()
405 function renderSellPane ()
275 406 {
276 if (!sellSection || !sellList)
407 if (!sellGrid)
277 408 { return; }
409 sellGrid.replaceChildren();
278 410 if (!buysItems)
279 {
280 sellSection.hidden = true;
281 selectedSellSlotIndex = null;
282 if (sellDetail)
283 { sellDetail.hidden = true; }
284 return;
285 }
286 sellSection.hidden = false;
287 sellList.innerHTML = "";
411 { return; }
288 412 const slots = getInventorySlots?.() ?? [];
289 413 const sellableIndexes = [];
290 414 slots.forEach((slot, slotIndex) =>
291 415 {
292 if (!slot?.itemId || !canPlayerSellToNpc(slot))
293 { return; }
294 sellableIndexes.push(slotIndex);
416 if (slot?.itemId && canPlayerSellToNpc(slot))
417 { sellableIndexes.push(slotIndex); }
295 418 });
296 419 if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex))
297 420 { selectedSellSlotIndex = null; }
298 if (selectedSellSlotIndex == null && sellableIndexes.length)
299 { selectedSellSlotIndex = sellableIndexes[0]; }
300 421 if (!sellableIndexes.length)
301 422 {
302 sellList.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;
303 423 selectedSellSlotIndex = null;
304 renderSellDetail();
424 if (sellDetail)
425 { sellDetail.hidden = true; }
426 if (sellEmpty)
427 { sellEmpty.hidden = true; }
428 const note = document.createElement("p");
429 note.className = "hint";
430 note.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;
431 sellGrid.append(note);
305 432 return;
306 433 }
307 for (const slotIndex of sellableIndexes)
434 if (sellEmpty)
435 { sellEmpty.hidden = true; }
436 if (selectedSellSlotIndex == null)
437 {
438 if (sellDetail)
439 {
440 sellDetail.hidden = false;
441 if (sellName)
442 { sellName.textContent = "Select an item"; }
443 if (sellIcon)
444 {
445 sellIcon.removeAttribute("src");
446 sellIcon.alt = "";
447 }
448 if (sellPrice)
449 { sellPrice.textContent = ""; }
450 if (sellFee)
451 { sellFee.hidden = true; }
452 if (sellActions)
453 { sellActions.replaceChildren(); }
454 }
455 }
456 slots.forEach((slot, slotIndex) =>
308 457 {
309 const slot = slots[slotIndex];
310 const row = document.createElement("button");
311 row.type = "button";
312 row.className = "shop-sell-row";
458 const button = document.createElement("button");
459 button.type = "button";
460 button.className = "item-slot";
461 const sellable = !!slot?.itemId && canPlayerSellToNpc(slot);
462 if (!slot)
463 {
464 button.disabled = true;
465 sellGrid.append(button);
466 return;
467 }
468 if (!sellable)
469 { button.classList.add("disabled"); }
313 470 if (slotIndex === selectedSellSlotIndex)
314 { row.classList.add("selected"); }
315 row.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
316 row.addEventListener("click", () =>
471 { button.classList.add("selected"); }
472 const img = document.createElement("img");
473 img.alt = itemDisplayName(slot);
474 applyItemIcon(img, slot, itemAssetPathForStack(slot));
475 button.append(img);
476 const qty = stackQuantity(slot.quantity);
477 if (qty > 1)
317 478 {
479 const count = document.createElement("span");
480 count.className = "qty";
481 count.textContent = formatQuantity(qty);
482 button.append(count);
483 }
484 button.title = itemDisplayName(slot);
485 button.addEventListener("click", () =>
486 {
487 if (!sellable)
488 { return; }
318 489 selectedSellSlotIndex = slotIndex;
319 renderSellList();
490 render();
320 491 });
321 sellList.append(row);
322 }
323 renderSellDetail();
492 sellGrid.append(button);
493 });
494 if (selectedSellSlotIndex != null)
495 { renderSellDetail(); }
324 496 }
325 497
326 function render ()
498 function renderBuyPane ()
327 499 {
328 500 grid.innerHTML = "";
329 const coins = getCoinCount?.() ?? 0;
330 coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;
331
332 501 if (!stock.length)
333 502 {
334 503 grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale.";
335 504 detail.hidden = true;
336 505 bagWarn.hidden = true;
337 renderSellList();
338 506 return;
339 507 }
340 508
@@ -364,7 +532,6 @@ export function initShop ({
364 532 {
365 533 detail.hidden = true;
366 534 bagWarn.hidden = true;
367 renderSellList();
368 535 return;
369 536 }
370 537
@@ -393,7 +560,18 @@ export function initShop ({
393 560 { buyX.disabled = max < 1; }
394 561
395 562 bagWarn.hidden = inventoryFits(entry.itemId, 1);
396 renderSellList();
563 }
564
565 function render ()
566 {
567 const coins = getCoinCount?.() ?? 0;
568 coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;
569 if (tabSell)
570 { tabSell.hidden = !buysItems; }
571 if (activeTab === "sell" && buysItems)
572 { renderSellPane(); }
573 else
574 { renderBuyPane(); }
397 575 }
398 576
399 577 function handleShopOpen (message)
@@ -4,7 +4,7 @@ import {
4 itemAssetPathForStack,
4 itemAssetPathForStack,
5 formatQuantity
5 formatQuantity
6} from "/shared/definitions/items.js";
6} from "/shared/definitions/items.js";
7import { insertStack } from "/shared/items/inventory.js";
7import { insertStack, stackQuantity } from "/shared/items/inventory.js";
8import {
8import {
9 canPlayerSellToNpc,
9 canPlayerSellToNpc,
10 resolveShopSellQuote
10 resolveShopSellQuote
@@ -23,6 +23,10 @@ export function initShop ({
23 const backdrop = document.getElementById("shop-backdrop");
23 const backdrop = document.getElementById("shop-backdrop");
24 const panel = document.getElementById("shop-panel");
24 const panel = document.getElementById("shop-panel");
25 const title = document.getElementById("shop-title");
25 const title = document.getElementById("shop-title");
26 const tabBuy = document.getElementById("shop-tab-buy");
27 const tabSell = document.getElementById("shop-tab-sell");
28 const paneBuy = document.getElementById("shop-pane-buy");
29 const paneSell = document.getElementById("shop-pane-sell");
26 const grid = document.getElementById("shop-grid");
30 const grid = document.getElementById("shop-grid");
27 const detail = document.getElementById("shop-detail");
31 const detail = document.getElementById("shop-detail");
28 const detailIcon = document.getElementById("shop-detail-icon");
32 const detailIcon = document.getElementById("shop-detail-icon");
@@ -31,14 +35,18 @@ export function initShop ({
31 const detailStock = document.getElementById("shop-detail-stock");
35 const detailStock = document.getElementById("shop-detail-stock");
32 const bagWarn = document.getElementById("shop-bag-warn");
36 const bagWarn = document.getElementById("shop-bag-warn");
33 const coinsEl = document.getElementById("shop-coins");
37 const coinsEl = document.getElementById("shop-coins");
34 const sellSection = document.getElementById("shop-sell-section");
38 const sellGrid = document.getElementById("shop-sell-grid");
35 const sellList = document.getElementById("shop-sell-list");
36 const sellDetail = document.getElementById("shop-sell-detail");
39 const sellDetail = document.getElementById("shop-sell-detail");
40 const sellIcon = document.getElementById("shop-sell-icon");
41 const sellName = document.getElementById("shop-sell-name");
37 const sellPrice = document.getElementById("shop-sell-price");
42 const sellPrice = document.getElementById("shop-sell-price");
38 const sellFee = document.getElementById("shop-sell-fee");
43 const sellFee = document.getElementById("shop-sell-fee");
39 const sellConfirm = document.getElementById("shop-sell-confirm");
44 const sellActions = document.getElementById("shop-sell-actions");
45 const sellEmpty = document.getElementById("shop-sell-empty");
40 const qtyBackdrop = document.getElementById("shop-qty-backdrop");
46 const qtyBackdrop = document.getElementById("shop-qty-backdrop");
41 const qtyPanel = document.getElementById("shop-qty-panel");
47 const qtyPanel = document.getElementById("shop-qty-panel");
48 const qtyTitle = document.getElementById("shop-qty-title");
49 const qtyConfirm = document.getElementById("shop-qty-confirm");
42 const qtyInput = document.getElementById("shop-qty-input");
50 const qtyInput = document.getElementById("shop-qty-input");
43 const qtyHint = document.getElementById("shop-qty-hint");
51 const qtyHint = document.getElementById("shop-qty-hint");
44
52
@@ -49,6 +57,10 @@ export function initShop ({
49 let buysItems = false;
57 let buysItems = false;
50 let displayName = "Shop";
58 let displayName = "Shop";
51 let sex = "male";
59 let sex = "male";
60 /** @type {"buy"|"sell"} */
61 let activeTab = "buy";
62 /** @type {"buy"|"sell"|null} */
63 let qtyMode = null;
52
64
53 function suppressWorldClick ()
65 function suppressWorldClick ()
54 {
66 {
@@ -77,19 +89,43 @@ export function initShop ({
77 event.stopPropagation();
89 event.stopPropagation();
78 suppressWorldClick();
90 suppressWorldClick();
79 });
91 });
92 tabBuy?.addEventListener("click", () => setTab("buy"));
93 tabSell?.addEventListener("click", () => setTab("sell"));
80 document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1));
94 document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1));
81 document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5));
95 document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5));
82 document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10));
96 document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10));
83 document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal());
97 document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal("buy"));
84 document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal());
98 document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal());
85 document.getElementById("shop-qty-confirm")?.addEventListener("click", () => confirmQtyBuy());
99 qtyConfirm?.addEventListener("click", () => confirmQtyModal());
86 qtyBackdrop?.addEventListener("click", () => closeQtyModal());
100 qtyBackdrop?.addEventListener("click", () => closeQtyModal());
87 qtyInput?.addEventListener("keydown", (event) =>
101 qtyInput?.addEventListener("keydown", (event) =>
88 {
102 {
89 if (event.key === "Enter")
103 if (event.key === "Enter")
90 { confirmQtyBuy(); }
104 { confirmQtyModal(); }
91 });
105 });
92 sellConfirm?.addEventListener("click", () => sellSelected());
106
107 function setTab (tab)
108 {
109 if (tab === "sell" && !buysItems)
110 { tab = "buy"; }
111 activeTab = tab;
112 const buyActive = tab === "buy";
113 if (tabBuy)
114 {
115 tabBuy.classList.toggle("active", buyActive);
116 tabBuy.setAttribute("aria-selected", buyActive ? "true" : "false");
117 }
118 if (tabSell)
119 {
120 tabSell.classList.toggle("active", !buyActive);
121 tabSell.setAttribute("aria-selected", buyActive ? "false" : "true");
122 }
123 if (paneBuy)
124 { paneBuy.hidden = !buyActive; }
125 if (paneSell)
126 { paneSell.hidden = buyActive; }
127 render();
128 }
93
129
94 function open (payload)
130 function open (payload)
95 {
131 {
@@ -101,8 +137,10 @@ export function initShop ({
101 stock = Array.isArray(payload.stock) ? payload.stock : [];
137 stock = Array.isArray(payload.stock) ? payload.stock : [];
102 if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId))
138 if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId))
103 { selectedListingId = stock[0]?.listingId ?? null; }
139 { selectedListingId = stock[0]?.listingId ?? null; }
140 if (tabSell)
141 { tabSell.hidden = !buysItems; }
104 closeQtyModal();
142 closeQtyModal();
105 render();
143 setTab(buysItems && activeTab === "sell" ? "sell" : "buy");
106 backdrop.hidden = false;
144 backdrop.hidden = false;
107 panel.hidden = false;
145 panel.hidden = false;
108 suppressWorldClick();
146 suppressWorldClick();
@@ -120,6 +158,7 @@ export function initShop ({
120 selectedSellSlotIndex = null;
158 selectedSellSlotIndex = null;
121 buysItems = false;
159 buysItems = false;
122 sex = "male";
160 sex = "male";
161 activeTab = "buy";
123 suppressWorldClick();
162 suppressWorldClick();
124 if (notifyServer && closingNpcId)
163 if (notifyServer && closingNpcId)
125 {
164 {
@@ -176,16 +215,43 @@ export function initShop ({
176 });
215 });
177 }
216 }
178
217
179 function openQtyModal ()
218 function openQtyModal (mode)
180 {
219 {
181 const entry = selectedEntry();
220 qtyMode = mode;
182 if (!entry)
221 if (mode === "buy")
183 { return; }
222 {
184 const max = maxBuyable(entry);
223 const entry = selectedEntry();
185 if (max < 1)
224 if (!entry)
186 { return; }
225 { return; }
187 qtyInput.value = String(Math.min(max, 1));
226 const max = maxBuyable(entry);
188 qtyHint.textContent = `Max ${max}`;
227 if (max < 1)
228 { return; }
229 if (qtyTitle)
230 { qtyTitle.textContent = "Buy quantity"; }
231 if (qtyConfirm)
232 { qtyConfirm.textContent = "Buy"; }
233 qtyInput.min = "1";
234 qtyInput.max = String(max);
235 qtyInput.value = String(Math.min(max, 1));
236 qtyHint.textContent = `Max ${max}`;
237 }
238 else
239 {
240 const slot = selectedSellSlot();
241 if (!slot)
242 { return; }
243 const max = Math.max(1, stackQuantity(slot.quantity));
244 if (max < 4)
245 { return; }
246 if (qtyTitle)
247 { qtyTitle.textContent = "Sell quantity"; }
248 if (qtyConfirm)
249 { qtyConfirm.textContent = "Sell"; }
250 qtyInput.min = "1";
251 qtyInput.max = String(max);
252 qtyInput.value = "1";
253 qtyHint.textContent = `Max ${max}`;
254 }
189 qtyBackdrop.hidden = false;
255 qtyBackdrop.hidden = false;
190 qtyPanel.hidden = false;
256 qtyPanel.hidden = false;
191 suppressWorldClick();
257 suppressWorldClick();
@@ -195,12 +261,27 @@ export function initShop ({
195
261
196 function closeQtyModal ()
262 function closeQtyModal ()
197 {
263 {
264 qtyMode = null;
198 qtyBackdrop.hidden = true;
265 qtyBackdrop.hidden = true;
199 qtyPanel.hidden = true;
266 qtyPanel.hidden = true;
200 }
267 }
201
268
202 function confirmQtyBuy ()
269 function confirmQtyModal ()
203 {
270 {
271 if (qtyMode === "sell")
272 {
273 const slot = selectedSellSlot();
274 if (!slot)
275 {
276 closeQtyModal();
277 return;
278 }
279 const max = Math.max(1, stackQuantity(slot.quantity));
280 const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1));
281 closeQtyModal();
282 sellQuantity(qty);
283 return;
284 }
204 const entry = selectedEntry();
285 const entry = selectedEntry();
205 if (!entry)
286 if (!entry)
206 {
287 {
@@ -224,40 +305,90 @@ export function initShop ({
224 return slot;
305 return slot;
225 }
306 }
226
307
227 function sellSelected ()
308 function sellQuantity (quantity)
228 {
309 {
229 if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot())
310 if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot())
230 { return; }
311 { return; }
312 const slot = selectedSellSlot();
313 const max = Math.max(1, stackQuantity(slot.quantity));
314 const qty = Math.min(max, Math.max(1, quantity | 0 || 1));
231 socket.send({
315 socket.send({
232 type: MessageType.sellToShop,
316 type: MessageType.sellToShop,
233 npcEntityId,
317 npcEntityId,
234 slotIndex: selectedSellSlotIndex,
318 slotIndex: selectedSellSlotIndex,
235 quantity: 1
319 quantity: qty
236 });
320 });
237 }
321 }
238
322
323 function renderSellActions (slot)
324 {
325 if (!sellActions)
326 { return; }
327 sellActions.replaceChildren();
328 const qty = Math.max(1, stackQuantity(slot.quantity));
329 const addBtn = (label, onClick) =>
330 {
331 const btn = document.createElement("button");
332 btn.type = "button";
333 btn.textContent = label;
334 btn.addEventListener("click", onClick);
335 sellActions.append(btn);
336 };
337 if (qty <= 1)
338 {
339 addBtn("Sell", () => sellQuantity(1));
340 return;
341 }
342 addBtn("Sell 1", () => sellQuantity(1));
343 if (qty === 2)
344 {
345 addBtn("Sell all", () => sellQuantity(qty));
346 return;
347 }
348 if (qty === 3)
349 {
350 addBtn("Sell 2", () => sellQuantity(2));
351 addBtn("Sell all", () => sellQuantity(qty));
352 return;
353 }
354 addBtn("Sell x", () => openQtyModal("sell"));
355 addBtn("Sell all", () => sellQuantity(qty));
356 }
357
239 function renderSellDetail ()
358 function renderSellDetail ()
240 {
359 {
241 if (!sellDetail || !sellPrice || !sellFee || !sellConfirm)
360 if (!sellDetail || !sellPrice || !sellFee)
242 { return; }
361 { return; }
243 const slot = selectedSellSlot();
362 const slot = selectedSellSlot();
244 if (!slot)
363 if (!slot)
245 {
364 {
246 sellDetail.hidden = true;
365 sellDetail.hidden = true;
247 sellFee.hidden = true;
366 sellFee.hidden = true;
367 if (sellActions)
368 { sellActions.replaceChildren(); }
248 return;
369 return;
249 }
370 }
250 const quote = resolveShopSellQuote(slot, { quantity: 1 });
371 const quote = resolveShopSellQuote(slot, {
251 if (!quote)
372 quantity: Math.max(1, stackQuantity(slot.quantity))
373 });
374 const unitQuote = resolveShopSellQuote(slot, { quantity: 1 });
375 if (!quote || !unitQuote)
252 {
376 {
253 sellDetail.hidden = true;
377 sellDetail.hidden = true;
254 sellFee.hidden = true;
378 sellFee.hidden = true;
255 return;
379 return;
256 }
380 }
257 sellDetail.hidden = false;
381 sellDetail.hidden = false;
382 if (sellEmpty)
383 { sellEmpty.hidden = true; }
384 const name = itemDisplayName(slot);
385 if (sellName)
386 { sellName.textContent = name; }
387 if (sellIcon)
388 { applyItemIcon(sellIcon, slot, itemAssetPathForStack(slot)); }
258 sellPrice.textContent = quote.isCheque
389 sellPrice.textContent = quote.isCheque
259 ? `You receive ${formatQuantity(quote.payout)} coins`
390 ? `You receive ${formatQuantity(quote.payout)} coins`
260 : `${formatQuantity(quote.unitPrice)} coins each`;
391 : `${formatQuantity(unitQuote.unitPrice)} coins each`;
261 if (quote.isCheque)
392 if (quote.isCheque)
262 {
393 {
263 sellFee.hidden = false;
394 sellFee.hidden = false;
@@ -268,73 +399,110 @@ export function initShop ({
268 sellFee.hidden = true;
399 sellFee.hidden = true;
269 sellFee.textContent = "";
400 sellFee.textContent = "";
270 }
401 }
271 sellConfirm.disabled = false;
402 renderSellActions(slot);
272 }
403 }
273
404
274 function renderSellList ()
405 function renderSellPane ()
275 {
406 {
276 if (!sellSection || !sellList)
407 if (!sellGrid)
277 { return; }
408 { return; }
409 sellGrid.replaceChildren();
278 if (!buysItems)
410 if (!buysItems)
279 {
411 { return; }
280 sellSection.hidden = true;
281 selectedSellSlotIndex = null;
282 if (sellDetail)
283 { sellDetail.hidden = true; }
284 return;
285 }
286 sellSection.hidden = false;
287 sellList.innerHTML = "";
288 const slots = getInventorySlots?.() ?? [];
412 const slots = getInventorySlots?.() ?? [];
289 const sellableIndexes = [];
413 const sellableIndexes = [];
290 slots.forEach((slot, slotIndex) =>
414 slots.forEach((slot, slotIndex) =>
291 {
415 {
292 if (!slot?.itemId || !canPlayerSellToNpc(slot))
416 if (slot?.itemId && canPlayerSellToNpc(slot))
293 { return; }
417 { sellableIndexes.push(slotIndex); }
294 sellableIndexes.push(slotIndex);
295 });
418 });
296 if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex))
419 if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex))
297 { selectedSellSlotIndex = null; }
420 { selectedSellSlotIndex = null; }
298 if (selectedSellSlotIndex == null && sellableIndexes.length)
299 { selectedSellSlotIndex = sellableIndexes[0]; }
300 if (!sellableIndexes.length)
421 if (!sellableIndexes.length)
301 {
422 {
302 sellList.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;
303 selectedSellSlotIndex = null;
423 selectedSellSlotIndex = null;
304 renderSellDetail();
424 if (sellDetail)
425 { sellDetail.hidden = true; }
426 if (sellEmpty)
427 { sellEmpty.hidden = true; }
428 const note = document.createElement("p");
429 note.className = "hint";
430 note.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;
431 sellGrid.append(note);
305 return;
432 return;
306 }
433 }
307 for (const slotIndex of sellableIndexes)
434 if (sellEmpty)
435 { sellEmpty.hidden = true; }
436 if (selectedSellSlotIndex == null)
437 {
438 if (sellDetail)
439 {
440 sellDetail.hidden = false;
441 if (sellName)
442 { sellName.textContent = "Select an item"; }
443 if (sellIcon)
444 {
445 sellIcon.removeAttribute("src");
446 sellIcon.alt = "";
447 }
448 if (sellPrice)
449 { sellPrice.textContent = ""; }
450 if (sellFee)
451 { sellFee.hidden = true; }
452 if (sellActions)
453 { sellActions.replaceChildren(); }
454 }
455 }
456 slots.forEach((slot, slotIndex) =>
308 {
457 {
309 const slot = slots[slotIndex];
458 const button = document.createElement("button");
310 const row = document.createElement("button");
459 button.type = "button";
311 row.type = "button";
460 button.className = "item-slot";
312 row.className = "shop-sell-row";
461 const sellable = !!slot?.itemId && canPlayerSellToNpc(slot);
462 if (!slot)
463 {
464 button.disabled = true;
465 sellGrid.append(button);
466 return;
467 }
468 if (!sellable)
469 { button.classList.add("disabled"); }
313 if (slotIndex === selectedSellSlotIndex)
470 if (slotIndex === selectedSellSlotIndex)
314 { row.classList.add("selected"); }
471 { button.classList.add("selected"); }
315 row.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
472 const img = document.createElement("img");
316 row.addEventListener("click", () =>
473 img.alt = itemDisplayName(slot);
474 applyItemIcon(img, slot, itemAssetPathForStack(slot));
475 button.append(img);
476 const qty = stackQuantity(slot.quantity);
477 if (qty > 1)
317 {
478 {
479 const count = document.createElement("span");
480 count.className = "qty";
481 count.textContent = formatQuantity(qty);
482 button.append(count);
483 }
484 button.title = itemDisplayName(slot);
485 button.addEventListener("click", () =>
486 {
487 if (!sellable)
488 { return; }
318 selectedSellSlotIndex = slotIndex;
489 selectedSellSlotIndex = slotIndex;
319 renderSellList();
490 render();
320 });
491 });
321 sellList.append(row);
492 sellGrid.append(button);
322 }
493 });
323 renderSellDetail();
494 if (selectedSellSlotIndex != null)
495 { renderSellDetail(); }
324 }
496 }
325
497
326 function render ()
498 function renderBuyPane ()
327 {
499 {
328 grid.innerHTML = "";
500 grid.innerHTML = "";
329 const coins = getCoinCount?.() ?? 0;
330 coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;
331
332 if (!stock.length)
501 if (!stock.length)
333 {
502 {
334 grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale.";
503 grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale.";
335 detail.hidden = true;
504 detail.hidden = true;
336 bagWarn.hidden = true;
505 bagWarn.hidden = true;
337 renderSellList();
338 return;
506 return;
339 }
507 }
340
508
@@ -364,7 +532,6 @@ export function initShop ({
364 {
532 {
365 detail.hidden = true;
533 detail.hidden = true;
366 bagWarn.hidden = true;
534 bagWarn.hidden = true;
367 renderSellList();
368 return;
535 return;
369 }
536 }
370
537
@@ -393,7 +560,18 @@ export function initShop ({
393 { buyX.disabled = max < 1; }
560 { buyX.disabled = max < 1; }
394
561
395 bagWarn.hidden = inventoryFits(entry.itemId, 1);
562 bagWarn.hidden = inventoryFits(entry.itemId, 1);
396 renderSellList();
563 }
564
565 function render ()
566 {
567 const coins = getCoinCount?.() ?? 0;
568 coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;
569 if (tabSell)
570 { tabSell.hidden = !buysItems; }
571 if (activeTab === "sell" && buysItems)
572 { renderSellPane(); }
573 else
574 { renderBuyPane(); }
397 }
575 }
398
576
399 function handleShopOpen (message)
577 function handleShopOpen (message)
client/ui/editor.css +81 −2
@@ -503,8 +503,8 @@ label { display: block; margin: 0.4rem 0; }
503 503
504 504 .spawner-equip-row {
505 505 display: grid;
506 grid-template-columns: 4.5rem 1fr auto auto;
507 gap: 0.4rem;
506 grid-template-columns: 4.5rem 1fr auto auto auto;
507 gap: 0.35rem;
508 508 align-items: center;
509 509 }
510 510
@@ -520,6 +520,85 @@ label { display: block; margin: 0.4rem 0; }
520 520 white-space: nowrap;
521 521 }
522 522
523 .spawner-equip-dye-swatch {
524 display: inline-block;
525 width: 0.85rem;
526 height: 0.85rem;
527 margin-right: 0.35rem;
528 border: 1px solid #3a4250;
529 vertical-align: -0.1rem;
530 border-radius: 2px;
531 }
532
533 #equip-dye-backdrop {
534 position: fixed;
535 inset: 0;
536 background: rgba(0, 0, 0, 0.55);
537 z-index: 23;
538 }
539
540 #equip-dye-modal {
541 position: fixed;
542 z-index: 24;
543 top: 18vh;
544 left: 50%;
545 transform: translateX(-50%);
546 width: min(340px, 90vw);
547 display: flex;
548 flex-direction: column;
549 background: #161a22;
550 border: 1px solid #3a4250;
551 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
552 }
553
554 #equip-dye-modal[hidden],
555 #equip-dye-backdrop[hidden] {
556 display: none !important;
557 }
558
559 #equip-dye-modal > header {
560 display: flex;
561 align-items: center;
562 justify-content: space-between;
563 gap: 0.75rem;
564 padding: 0.75rem 1rem;
565 border-bottom: 1px solid #2c3340;
566 }
567
568 .equip-dye-body {
569 padding: 0.85rem 1rem 1rem;
570 display: flex;
571 flex-direction: column;
572 gap: 0.55rem;
573 }
574
575 .equip-dye-preview {
576 height: 3rem;
577 border: 1px solid #3a4250;
578 border-radius: 4px;
579 background: #c85078;
580 }
581
582 .equip-dye-channel {
583 display: grid;
584 grid-template-columns: 1.25rem 1fr 3.5rem;
585 gap: 0.4rem;
586 align-items: center;
587 font-size: 0.85rem;
588 color: #9aa3b2;
589 }
590
591 .equip-dye-channel input[type="number"] {
592 width: 100%;
593 }
594
595 .equip-dye-actions {
596 display: flex;
597 justify-content: flex-end;
598 gap: 0.4rem;
599 margin-top: 0.25rem;
600 }
601
523 602 .spawner-buys-row {
524 603 display: flex;
525 604 align-items: center;
@@ -503,8 +503,8 @@ label { display: block; margin: 0.4rem 0; }
503
503
504.spawner-equip-row {
504.spawner-equip-row {
505 display: grid;
505 display: grid;
506 grid-template-columns: 4.5rem 1fr auto auto;
506 grid-template-columns: 4.5rem 1fr auto auto auto;
507 gap: 0.4rem;
507 gap: 0.35rem;
508 align-items: center;
508 align-items: center;
509}
509}
510
510
@@ -520,6 +520,85 @@ label { display: block; margin: 0.4rem 0; }
520 white-space: nowrap;
520 white-space: nowrap;
521}
521}
522
522
523.spawner-equip-dye-swatch {
524 display: inline-block;
525 width: 0.85rem;
526 height: 0.85rem;
527 margin-right: 0.35rem;
528 border: 1px solid #3a4250;
529 vertical-align: -0.1rem;
530 border-radius: 2px;
531}
532
533#equip-dye-backdrop {
534 position: fixed;
535 inset: 0;
536 background: rgba(0, 0, 0, 0.55);
537 z-index: 23;
538}
539
540#equip-dye-modal {
541 position: fixed;
542 z-index: 24;
543 top: 18vh;
544 left: 50%;
545 transform: translateX(-50%);
546 width: min(340px, 90vw);
547 display: flex;
548 flex-direction: column;
549 background: #161a22;
550 border: 1px solid #3a4250;
551 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
552}
553
554#equip-dye-modal[hidden],
555#equip-dye-backdrop[hidden] {
556 display: none !important;
557}
558
559#equip-dye-modal > header {
560 display: flex;
561 align-items: center;
562 justify-content: space-between;
563 gap: 0.75rem;
564 padding: 0.75rem 1rem;
565 border-bottom: 1px solid #2c3340;
566}
567
568.equip-dye-body {
569 padding: 0.85rem 1rem 1rem;
570 display: flex;
571 flex-direction: column;
572 gap: 0.55rem;
573}
574
575.equip-dye-preview {
576 height: 3rem;
577 border: 1px solid #3a4250;
578 border-radius: 4px;
579 background: #c85078;
580}
581
582.equip-dye-channel {
583 display: grid;
584 grid-template-columns: 1.25rem 1fr 3.5rem;
585 gap: 0.4rem;
586 align-items: center;
587 font-size: 0.85rem;
588 color: #9aa3b2;
589}
590
591.equip-dye-channel input[type="number"] {
592 width: 100%;
593}
594
595.equip-dye-actions {
596 display: flex;
597 justify-content: flex-end;
598 gap: 0.4rem;
599 margin-top: 0.25rem;
600}
601
523.spawner-buys-row {
602.spawner-buys-row {
524 display: flex;
603 display: flex;
525 align-items: center;
604 align-items: center;
client/ui/play.css +73 −49
@@ -435,6 +435,32 @@ a { color: #d4c48a; }
435 435 margin-bottom: 0.5rem;
436 436 }
437 437
438 /* Above #craft-panel so tailor dye choice is not buried under the station UI. */
439 #dye-picker-backdrop {
440 z-index: 7;
441 }
442
443 #dye-picker-panel {
444 position: fixed;
445 z-index: 8;
446 top: 50%;
447 left: 50%;
448 transform: translate(-50%, -50%);
449 width: min(420px, 94vw);
450 max-height: min(85vh, 720px);
451 overflow: auto;
452 background: #1a1e26;
453 border: 1px solid #2c3340;
454 padding: 0.85rem 1rem 1rem;
455 }
456
457 #dye-picker-panel header {
458 display: flex;
459 justify-content: space-between;
460 align-items: center;
461 margin-bottom: 0.5rem;
462 }
463
438 464 #cauldron-panel,
439 465 #cauldron-pick-panel,
440 466 #cauldron-dye-confirm-panel {
@@ -872,6 +898,8 @@ a { color: #d4c48a; }
872 898 #bank-panel[hidden],
873 899 #craft-panel[hidden],
874 900 #craft-backdrop[hidden],
901 #dye-picker-panel[hidden],
902 #dye-picker-backdrop[hidden],
875 903 #cauldron-panel[hidden],
876 904 #cauldron-backdrop[hidden],
877 905 #cauldron-pick-panel[hidden],
@@ -1016,7 +1044,7 @@ a { color: #d4c48a; }
1016 1044 left: 50%;
1017 1045 transform: translate(-50%, -50%);
1018 1046 width: min(560px, 94vw);
1019 max-height: min(75vh, 560px);
1047 max-height: min(80vh, 640px);
1020 1048 display: flex;
1021 1049 flex-direction: column;
1022 1050 background: #1a1e26;
@@ -1029,7 +1057,35 @@ a { color: #d4c48a; }
1029 1057 justify-content: space-between;
1030 1058 align-items: center;
1031 1059 gap: 0.75rem;
1032 margin-bottom: 0.75rem;
1060 margin-bottom: 0.35rem;
1061 }
1062
1063 .shop-tabs {
1064 display: flex;
1065 gap: 0.25rem;
1066 margin: 0.35rem 0 0.65rem;
1067 }
1068
1069 .shop-tab {
1070 flex: 1;
1071 font-size: 0.85rem;
1072 padding: 0.35rem 0.4rem;
1073 background: #12151b;
1074 border: 1px solid #2c3340;
1075 color: inherit;
1076 }
1077
1078 .shop-tab.active {
1079 outline: 1px solid #6a8caf;
1080 border-color: #6a8caf;
1081 }
1082
1083 .shop-pane {
1084 min-height: 0;
1085 flex: 1;
1086 display: flex;
1087 flex-direction: column;
1088 overflow: hidden;
1033 1089 }
1034 1090
1035 1091 .shop-body {
@@ -1052,6 +1108,18 @@ a { color: #d4c48a; }
1052 1108 max-height: min(50vh, 360px);
1053 1109 }
1054 1110
1111 .shop-sell-grid {
1112 align-content: start;
1113 overflow: auto;
1114 max-height: min(50vh, 360px);
1115 margin: 0;
1116 }
1117
1118 .shop-sell-grid .item-slot.disabled {
1119 opacity: 0.35;
1120 cursor: default;
1121 }
1122
1055 1123 .shop-cell {
1056 1124 width: 40px;
1057 1125 height: 40px;
@@ -1106,56 +1174,12 @@ a { color: #d4c48a; }
1106 1174 }
1107 1175
1108 1176 .shop-coins {
1109 margin: 0.75rem 0 0;
1110 padding-top: 0.55rem;
1111 border-top: 1px solid #2c3340;
1177 margin: 0;
1178 padding: 0;
1179 border: none;
1112 1180 font-weight: 600;
1113 1181 }
1114 1182
1115 .shop-sell-section {
1116 margin-top: 0.75rem;
1117 padding-top: 0.55rem;
1118 border-top: 1px solid #2c3340;
1119 display: flex;
1120 flex-direction: column;
1121 gap: 0.4rem;
1122 }
1123
1124 .shop-sell-list {
1125 display: flex;
1126 flex-direction: column;
1127 gap: 0.3rem;
1128 max-height: 8rem;
1129 overflow: auto;
1130 }
1131
1132 .shop-sell-row {
1133 display: flex;
1134 align-items: center;
1135 justify-content: space-between;
1136 gap: 0.5rem;
1137 width: 100%;
1138 text-align: left;
1139 background: transparent;
1140 border: 1px solid transparent;
1141 color: inherit;
1142 padding: 0.2rem 0.35rem;
1143 cursor: pointer;
1144 }
1145
1146 .shop-sell-row.selected {
1147 border-color: #4a5568;
1148 background: #222833;
1149 }
1150
1151 .shop-sell-detail {
1152 display: flex;
1153 flex-direction: column;
1154 align-items: flex-start;
1155 gap: 0.25rem;
1156 margin-top: 0.35rem;
1157 }
1158
1159 1183 #shop-qty-panel {
1160 1184 position: fixed;
1161 1185 z-index: 7;
@@ -435,6 +435,32 @@ a { color: #d4c48a; }
435 margin-bottom: 0.5rem;
435 margin-bottom: 0.5rem;
436}
436}
437
437
438/* Above #craft-panel so tailor dye choice is not buried under the station UI. */
439#dye-picker-backdrop {
440 z-index: 7;
441}
442
443#dye-picker-panel {
444 position: fixed;
445 z-index: 8;
446 top: 50%;
447 left: 50%;
448 transform: translate(-50%, -50%);
449 width: min(420px, 94vw);
450 max-height: min(85vh, 720px);
451 overflow: auto;
452 background: #1a1e26;
453 border: 1px solid #2c3340;
454 padding: 0.85rem 1rem 1rem;
455}
456
457#dye-picker-panel header {
458 display: flex;
459 justify-content: space-between;
460 align-items: center;
461 margin-bottom: 0.5rem;
462}
463
438#cauldron-panel,
464#cauldron-panel,
439#cauldron-pick-panel,
465#cauldron-pick-panel,
440#cauldron-dye-confirm-panel {
466#cauldron-dye-confirm-panel {
@@ -872,6 +898,8 @@ a { color: #d4c48a; }
872#bank-panel[hidden],
898#bank-panel[hidden],
873#craft-panel[hidden],
899#craft-panel[hidden],
874#craft-backdrop[hidden],
900#craft-backdrop[hidden],
901#dye-picker-panel[hidden],
902#dye-picker-backdrop[hidden],
875#cauldron-panel[hidden],
903#cauldron-panel[hidden],
876#cauldron-backdrop[hidden],
904#cauldron-backdrop[hidden],
877#cauldron-pick-panel[hidden],
905#cauldron-pick-panel[hidden],
@@ -1016,7 +1044,7 @@ a { color: #d4c48a; }
1016 left: 50%;
1044 left: 50%;
1017 transform: translate(-50%, -50%);
1045 transform: translate(-50%, -50%);
1018 width: min(560px, 94vw);
1046 width: min(560px, 94vw);
1019 max-height: min(75vh, 560px);
1047 max-height: min(80vh, 640px);
1020 display: flex;
1048 display: flex;
1021 flex-direction: column;
1049 flex-direction: column;
1022 background: #1a1e26;
1050 background: #1a1e26;
@@ -1029,7 +1057,35 @@ a { color: #d4c48a; }
1029 justify-content: space-between;
1057 justify-content: space-between;
1030 align-items: center;
1058 align-items: center;
1031 gap: 0.75rem;
1059 gap: 0.75rem;
1032 margin-bottom: 0.75rem;
1060 margin-bottom: 0.35rem;
1061}
1062
1063.shop-tabs {
1064 display: flex;
1065 gap: 0.25rem;
1066 margin: 0.35rem 0 0.65rem;
1067}
1068
1069.shop-tab {
1070 flex: 1;
1071 font-size: 0.85rem;
1072 padding: 0.35rem 0.4rem;
1073 background: #12151b;
1074 border: 1px solid #2c3340;
1075 color: inherit;
1076}
1077
1078.shop-tab.active {
1079 outline: 1px solid #6a8caf;
1080 border-color: #6a8caf;
1081}
1082
1083.shop-pane {
1084 min-height: 0;
1085 flex: 1;
1086 display: flex;
1087 flex-direction: column;
1088 overflow: hidden;
1033}
1089}
1034
1090
1035.shop-body {
1091.shop-body {
@@ -1052,6 +1108,18 @@ a { color: #d4c48a; }
1052 max-height: min(50vh, 360px);
1108 max-height: min(50vh, 360px);
1053}
1109}
1054
1110
1111.shop-sell-grid {
1112 align-content: start;
1113 overflow: auto;
1114 max-height: min(50vh, 360px);
1115 margin: 0;
1116}
1117
1118.shop-sell-grid .item-slot.disabled {
1119 opacity: 0.35;
1120 cursor: default;
1121}
1122
1055.shop-cell {
1123.shop-cell {
1056 width: 40px;
1124 width: 40px;
1057 height: 40px;
1125 height: 40px;
@@ -1106,56 +1174,12 @@ a { color: #d4c48a; }
1106}
1174}
1107
1175
1108.shop-coins {
1176.shop-coins {
1109 margin: 0.75rem 0 0;
1177 margin: 0;
1110 padding-top: 0.55rem;
1178 padding: 0;
1111 border-top: 1px solid #2c3340;
1179 border: none;
1112 font-weight: 600;
1180 font-weight: 600;
1113}
1181}
1114
1182
1115.shop-sell-section {
1116 margin-top: 0.75rem;
1117 padding-top: 0.55rem;
1118 border-top: 1px solid #2c3340;
1119 display: flex;
1120 flex-direction: column;
1121 gap: 0.4rem;
1122}
1123
1124.shop-sell-list {
1125 display: flex;
1126 flex-direction: column;
1127 gap: 0.3rem;
1128 max-height: 8rem;
1129 overflow: auto;
1130}
1131
1132.shop-sell-row {
1133 display: flex;
1134 align-items: center;
1135 justify-content: space-between;
1136 gap: 0.5rem;
1137 width: 100%;
1138 text-align: left;
1139 background: transparent;
1140 border: 1px solid transparent;
1141 color: inherit;
1142 padding: 0.2rem 0.35rem;
1143 cursor: pointer;
1144}
1145
1146.shop-sell-row.selected {
1147 border-color: #4a5568;
1148 background: #222833;
1149}
1150
1151.shop-sell-detail {
1152 display: flex;
1153 flex-direction: column;
1154 align-items: flex-start;
1155 gap: 0.25rem;
1156 margin-top: 0.35rem;
1157}
1158
1159#shop-qty-panel {
1183#shop-qty-panel {
1160 position: fixed;
1184 position: fixed;
1161 z-index: 7;
1185 z-index: 7;
server/src/crafting/service.js +17 −20
@@ -12,7 +12,7 @@ import {
12 12 } from "../../../shared/crafting/recipes.js";
13 13 import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14 14 import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
15 import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15 import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16 16 import {
17 17 attachOrigins,
18 18 craftOrigin,
@@ -103,24 +103,13 @@ function takeInputs (slots, inputs)
103 103 return { ok: true, slots: next };
104 104 }
105 105
106 /** Spend one fill level of a dye bottle (remove at 0). */
106 /** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */
107 107 function consumeDyeUse (slots, slotIndex)
108 108 {
109 const next = slots.map((slot) => (slot ? structuredClone(slot) : null));
110 const slot = next[slotIndex];
111 if (!slot || slot.itemId !== ItemId.dye || slot.instance?.kind !== "dye")
112 { return { ok: false }; }
113 const fill = Math.max(1, slot.instance.fillLevel | 0 || 4);
114 if (fill <= 1)
115 {
116 next[slotIndex] = null;
117 return { ok: true, slots: next };
118 }
119 slot.instance = {
120 ...slot.instance,
121 fillLevel: fill - 1
122 };
123 return { ok: true, slots: next };
109 return consumeFillCharge(slots, slotIndex, {
110 kind: "dye",
111 itemId: ItemId.dye
112 });
124 113 }
125 114
126 115 export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
@@ -176,12 +165,18 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
176 165 recipe = resolved.recipe;
177 166 }
178 167
179 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
168 if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeSlotIndex }))
180 169 {
181 170 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
182 171 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
183 172 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
184 173 { throw userError("Missing materials."); }
174 if (recipe.consumeDye && dyeSlotIndex != null)
175 {
176 const dyeProbe = consumeDyeUse(inventory?.slots ?? [], dyeSlotIndex);
177 if (!dyeProbe.ok)
178 { throw userError("Need bag space to separate the partially used dye."); }
179 }
185 180 throw userError("Not enough bag space for the result.");
186 181 }
187 182 if (recipe.consumeDye && dyeSlotIndex != null)
@@ -311,7 +306,7 @@ export function stepCrafting (world, now)
311 306
312 307 if (!recipe || !stationDef || !inventory
313 308 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
314 || !canCraftFitInventory(inventory.slots, recipe)
309 || !canCraftFitInventory(inventory.slots, recipe, { dyeSlotIndex: session.dyeSlotIndex })
315 310 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
316 311 {
317 312 events.push({
@@ -347,7 +342,9 @@ export function stepCrafting (world, now)
347 342 sessionId: session.sessionId,
348 343 recipeId: session.recipeId,
349 344 ok: false,
350 error: "Selected dye is missing."
345 error: dyeTaken.reason === "space"
346 ? "Need bag space to separate the partially used dye."
347 : "Selected dye is missing."
351 348 });
352 349 continue;
353 350 }
@@ -12,7 +12,7 @@ import {
12} from "../../../shared/crafting/recipes.js";
12} from "../../../shared/crafting/recipes.js";
13import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
13import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
14import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
15import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
16import {
16import {
17 attachOrigins,
17 attachOrigins,
18 craftOrigin,
18 craftOrigin,
@@ -103,24 +103,13 @@ function takeInputs (slots, inputs)
103 return { ok: true, slots: next };
103 return { ok: true, slots: next };
104}
104}
105
105
106/** Spend one fill level of a dye bottle (remove at 0). */
106/** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */
107function consumeDyeUse (slots, slotIndex)
107function consumeDyeUse (slots, slotIndex)
108{
108{
109 const next = slots.map((slot) => (slot ? structuredClone(slot) : null));
109 return consumeFillCharge(slots, slotIndex, {
110 const slot = next[slotIndex];
110 kind: "dye",
111 if (!slot || slot.itemId !== ItemId.dye || slot.instance?.kind !== "dye")
111 itemId: ItemId.dye
112 { return { ok: false }; }
112 });
113 const fill = Math.max(1, slot.instance.fillLevel | 0 || 4);
114 if (fill <= 1)
115 {
116 next[slotIndex] = null;
117 return { ok: true, slots: next };
118 }
119 slot.instance = {
120 ...slot.instance,
121 fillLevel: fill - 1
122 };
123 return { ok: true, slots: next };
124}
113}
125
114
126export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
115export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
@@ -176,12 +165,18 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
176 recipe = resolved.recipe;
165 recipe = resolved.recipe;
177 }
166 }
178
167
179 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
168 if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeSlotIndex }))
180 {
169 {
181 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
170 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
182 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
171 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
183 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
172 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
184 { throw userError("Missing materials."); }
173 { throw userError("Missing materials."); }
174 if (recipe.consumeDye && dyeSlotIndex != null)
175 {
176 const dyeProbe = consumeDyeUse(inventory?.slots ?? [], dyeSlotIndex);
177 if (!dyeProbe.ok)
178 { throw userError("Need bag space to separate the partially used dye."); }
179 }
185 throw userError("Not enough bag space for the result.");
180 throw userError("Not enough bag space for the result.");
186 }
181 }
187 if (recipe.consumeDye && dyeSlotIndex != null)
182 if (recipe.consumeDye && dyeSlotIndex != null)
@@ -311,7 +306,7 @@ export function stepCrafting (world, now)
311
306
312 if (!recipe || !stationDef || !inventory
307 if (!recipe || !stationDef || !inventory
313 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
308 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
314 || !canCraftFitInventory(inventory.slots, recipe)
309 || !canCraftFitInventory(inventory.slots, recipe, { dyeSlotIndex: session.dyeSlotIndex })
315 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
310 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
316 {
311 {
317 events.push({
312 events.push({
@@ -347,7 +342,9 @@ export function stepCrafting (world, now)
347 sessionId: session.sessionId,
342 sessionId: session.sessionId,
348 recipeId: session.recipeId,
343 recipeId: session.recipeId,
349 ok: false,
344 ok: false,
350 error: "Selected dye is missing."
345 error: dyeTaken.reason === "space"
346 ? "Need bag space to separate the partially used dye."
347 : "Selected dye is missing."
351 });
348 });
352 continue;
349 continue;
353 }
350 }
server/src/gateway/websocket.js +8 −0
@@ -189,6 +189,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
189 189 slotIndex: message.slotIndex | 0
190 190 });
191 191 break;
192 case MessageType.drinkItem:
193 requirePlaying(session);
194 simulation.enqueue(session.id, {
195 type: "drink-item",
196 characterId: session.characterId,
197 slotIndex: message.slotIndex | 0
198 });
199 break;
192 200 case MessageType.openBank:
193 201 requirePlaying(session);
194 202 simulation.enqueue(session.id, {
@@ -189,6 +189,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
189 slotIndex: message.slotIndex | 0
189 slotIndex: message.slotIndex | 0
190 });
190 });
191 break;
191 break;
192 case MessageType.drinkItem:
193 requirePlaying(session);
194 simulation.enqueue(session.id, {
195 type: "drink-item",
196 characterId: session.characterId,
197 slotIndex: message.slotIndex | 0
198 });
199 break;
192 case MessageType.openBank:
200 case MessageType.openBank:
193 requirePlaying(session);
201 requirePlaying(session);
194 simulation.enqueue(session.id, {
202 simulation.enqueue(session.id, {
server/src/items/bags.js +52 −1
@@ -17,7 +17,8 @@ import {
17 17 countItemInSlots,
18 18 cloneStack,
19 19 singleItemFromStack,
20 stackQuantity
20 stackQuantity,
21 consumeFillCharge
21 22 } from "../../../shared/items/inventory.js";
22 23 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
23 24 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
@@ -107,6 +108,8 @@ export function handleItemCommand (world, sessionId, command, now)
107 108 return openLetter(world, sessionId, command);
108 109 case "eat-item":
109 110 return eatItem(world, sessionId, command);
111 case "drink-item":
112 return drinkItem(world, sessionId, command);
110 113 default:
111 114 return null;
112 115 }
@@ -350,6 +353,54 @@ function eatItem (world, sessionId, command)
350 353 return { events: [], private: bagView(world.ecs, handle) };
351 354 }
352 355
356 function drinkItem (world, sessionId, command)
357 {
358 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
359 syncPlayerHealth(world.ecs, handle);
360 const inventory = ensureInventory(world.ecs, handle);
361 const slotIndex = command.slotIndex | 0;
362 const slot = inventory.slots[slotIndex];
363 if (!slot || slot.itemId !== ItemId.potion || slot.instance?.kind !== "potion")
364 { throw userError("That is not a potion."); }
365 const consumed = consumeFillCharge(inventory.slots, slotIndex, {
366 kind: "potion",
367 itemId: ItemId.potion,
368 returnEmptyItemId: ItemId.glassBottle
369 });
370 if (!consumed.ok)
371 {
372 if (consumed.reason === "space")
373 {
374 throw userError(
375 "Need bag space to keep the partially used potion (or empty bottle)."
376 );
377 }
378 throw userError("That inventory slot is empty.");
379 }
380 inventory.slots = consumed.slots;
381 applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
382 return { events: [], private: bagView(world.ecs, handle) };
383 }
384
385 function applyPotionEffect (ecs, handle, effect)
386 {
387 if (!effect || typeof effect !== "object")
388 { return; }
389 const health = ecs.get(handle, Component.health);
390 if (effect.type === "heal" && health)
391 {
392 const amount = Math.max(0, effect.amount | 0 || 0);
393 health.current = Math.min(health.max | 0, (health.current | 0) + amount);
394 return;
395 }
396 if (effect.type === "damage" && health)
397 {
398 const amount = Math.max(0, effect.amount | 0 || 0);
399 health.current = Math.max(0, (health.current | 0) - amount);
400 }
401 // slow / blind / queasy: stub until status-effect systems exist
402 }
403
353 404 function openBank (world, sessionId, command)
354 405 {
355 406 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -17,7 +17,8 @@ import {
17 countItemInSlots,
17 countItemInSlots,
18 cloneStack,
18 cloneStack,
19 singleItemFromStack,
19 singleItemFromStack,
20 stackQuantity
20 stackQuantity,
21 consumeFillCharge
21} from "../../../shared/items/inventory.js";
22} from "../../../shared/items/inventory.js";
22import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
23import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
23import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
@@ -107,6 +108,8 @@ export function handleItemCommand (world, sessionId, command, now)
107 return openLetter(world, sessionId, command);
108 return openLetter(world, sessionId, command);
108 case "eat-item":
109 case "eat-item":
109 return eatItem(world, sessionId, command);
110 return eatItem(world, sessionId, command);
111 case "drink-item":
112 return drinkItem(world, sessionId, command);
110 default:
113 default:
111 return null;
114 return null;
112 }
115 }
@@ -350,6 +353,54 @@ function eatItem (world, sessionId, command)
350 return { events: [], private: bagView(world.ecs, handle) };
353 return { events: [], private: bagView(world.ecs, handle) };
351}
354}
352
355
356function drinkItem (world, sessionId, command)
357{
358 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
359 syncPlayerHealth(world.ecs, handle);
360 const inventory = ensureInventory(world.ecs, handle);
361 const slotIndex = command.slotIndex | 0;
362 const slot = inventory.slots[slotIndex];
363 if (!slot || slot.itemId !== ItemId.potion || slot.instance?.kind !== "potion")
364 { throw userError("That is not a potion."); }
365 const consumed = consumeFillCharge(inventory.slots, slotIndex, {
366 kind: "potion",
367 itemId: ItemId.potion,
368 returnEmptyItemId: ItemId.glassBottle
369 });
370 if (!consumed.ok)
371 {
372 if (consumed.reason === "space")
373 {
374 throw userError(
375 "Need bag space to keep the partially used potion (or empty bottle)."
376 );
377 }
378 throw userError("That inventory slot is empty.");
379 }
380 inventory.slots = consumed.slots;
381 applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
382 return { events: [], private: bagView(world.ecs, handle) };
383}
384
385function applyPotionEffect (ecs, handle, effect)
386{
387 if (!effect || typeof effect !== "object")
388 { return; }
389 const health = ecs.get(handle, Component.health);
390 if (effect.type === "heal" && health)
391 {
392 const amount = Math.max(0, effect.amount | 0 || 0);
393 health.current = Math.min(health.max | 0, (health.current | 0) + amount);
394 return;
395 }
396 if (effect.type === "damage" && health)
397 {
398 const amount = Math.max(0, effect.amount | 0 || 0);
399 health.current = Math.max(0, (health.current | 0) - amount);
400 }
401 // slow / blind / queasy: stub until status-effect systems exist
402}
403
353function openBank (world, sessionId, command)
404function openBank (world, sessionId, command)
354{
405{
355 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
406 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
server/src/simulation/spawners.js +7 −3
@@ -5,7 +5,8 @@ import {
5 5 listAmbientMobTypes,
6 6 mobDefinition,
7 7 mobSpriteName,
8 MobId
8 MobId,
9 spawnerEquipmentSlot
9 10 } from "../../../shared/definitions/mobs.js";
10 11 import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
11 12 import { emptyEquipment } from "../../../shared/items/inventory.js";
@@ -167,13 +168,16 @@ export function mobComponents (request)
167 168 const authored = request.equipment ?? {};
168 169 for (const slot of Object.keys(equipmentSlots))
169 170 {
170 const itemId = authored[slot] | 0;
171 const { itemId, dyeColor } = spawnerEquipmentSlot(authored[slot]);
171 172 if (!itemId)
172 173 { continue; }
173 174 const itemDef = itemDefinition(itemId);
174 175 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
175 176 { continue; }
176 equipmentSlots[slot] = { itemId, quantity: 1 };
177 const stack = { itemId, quantity: 1 };
178 if (dyeColor && itemDef.dyeable)
179 { stack.instance = { kind: "clothing", dyeColor }; }
180 equipmentSlots[slot] = stack;
177 181 }
178 182 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
179 183 { components.equipment = { slots: equipmentSlots }; }
@@ -5,7 +5,8 @@ import {
5 listAmbientMobTypes,
5 listAmbientMobTypes,
6 mobDefinition,
6 mobDefinition,
7 mobSpriteName,
7 mobSpriteName,
8 MobId
8 MobId,
9 spawnerEquipmentSlot
9} from "../../../shared/definitions/mobs.js";
10} from "../../../shared/definitions/mobs.js";
10import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
11import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
11import { emptyEquipment } from "../../../shared/items/inventory.js";
12import { emptyEquipment } from "../../../shared/items/inventory.js";
@@ -167,13 +168,16 @@ export function mobComponents (request)
167 const authored = request.equipment ?? {};
168 const authored = request.equipment ?? {};
168 for (const slot of Object.keys(equipmentSlots))
169 for (const slot of Object.keys(equipmentSlots))
169 {
170 {
170 const itemId = authored[slot] | 0;
171 const { itemId, dyeColor } = spawnerEquipmentSlot(authored[slot]);
171 if (!itemId)
172 if (!itemId)
172 { continue; }
173 { continue; }
173 const itemDef = itemDefinition(itemId);
174 const itemDef = itemDefinition(itemId);
174 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
175 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
175 { continue; }
176 { continue; }
176 equipmentSlots[slot] = { itemId, quantity: 1 };
177 const stack = { itemId, quantity: 1 };
178 if (dyeColor && itemDef.dyeable)
179 { stack.instance = { kind: "clothing", dyeColor }; }
180 equipmentSlots[slot] = stack;
177 }
181 }
178 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
182 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
179 { components.equipment = { slots: equipmentSlots }; }
183 { components.equipment = { slots: equipmentSlots }; }
server/tests/fillCharge.test.js added +148 −0
@@ -0,0 +1,148 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 emptySlots,
5 insertStack,
6 stacksMatch,
7 consumeFillCharge,
8 stackQuantity
9 } from "../../shared/items/inventory.js";
10 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11 import { dyeItemInstance } from "../../shared/definitions/dyes.js";
12 import { potionItemInstance } from "../../shared/alchemy/recipes.js";
13 import { canCraftFitInventory } from "../../shared/crafting/recipes.js";
14 import { ClothTier } from "../../shared/definitions/materialTiers.js";
15 import { sweaterItemId, yarnItemId } from "../../shared/definitions/clothItems.js";
16
17 const red = { r: 0.8, g: 0.1, b: 0.1 };
18 const blue = { r: 0.1, g: 0.2, b: 0.9 };
19
20 function dyeStack (color, fillLevel, quantity = 1)
21 {
22 return {
23 itemId: ItemId.dye,
24 quantity,
25 instance: dyeItemInstance(color, fillLevel)
26 };
27 }
28
29 function potionStack (fillLevel, quantity = 1)
30 {
31 return {
32 itemId: ItemId.potion,
33 quantity,
34 instance: potionItemInstance({
35 potionKey: "greenDraught",
36 displayName: "Green draught",
37 color: { r: 0.25, g: 0.72, b: 0.35 },
38 fillLevel,
39 effect: { type: "heal", amount: 5 },
40 effectKey: "heal"
41 })
42 };
43 }
44
45 test("dyes stack only when colour and fill match", () =>
46 {
47 const def = itemDefinition(ItemId.dye);
48 const a = dyeStack(red, 4);
49 const b = dyeStack(red, 4);
50 const differentFill = dyeStack(red, 3);
51 const differentColor = dyeStack(blue, 4);
52 assert.equal(stacksMatch(a, b, def), true);
53 assert.equal(stacksMatch(a, differentFill, def), false);
54 assert.equal(stacksMatch(a, differentColor, def), false);
55 const first = insertStack(emptySlots(), { ...a, quantity: 2 }, def);
56 const second = insertStack(first.slots, differentFill, def);
57 assert.equal(second.ok, true);
58 assert.equal(stackQuantity(second.slots[0].quantity), 2);
59 assert.equal(second.slots[0].instance.fillLevel, 4);
60 assert.equal(second.slots[1].instance.fillLevel, 3);
61 });
62
63 test("potions stack only when type and fill match", () =>
64 {
65 const def = itemDefinition(ItemId.potion);
66 assert.equal(stacksMatch(potionStack(4), potionStack(4), def), true);
67 assert.equal(stacksMatch(potionStack(4), potionStack(3), def), false);
68 });
69
70 test("consumeFillCharge mutates a single bottle in place", () =>
71 {
72 const slots = emptySlots();
73 slots[0] = dyeStack(red, 3, 1);
74 const result = consumeFillCharge(slots, 0, { kind: "dye", itemId: ItemId.dye });
75 assert.equal(result.ok, true);
76 assert.equal(result.exhausted, false);
77 assert.equal(slots[0].instance.fillLevel, 3);
78 assert.equal(result.slots[0].instance.fillLevel, 2);
79 assert.equal(result.slots[0].quantity, 1);
80 });
81
82 test("consumeFillCharge peels from a multi-stack without losing the reduced bottle", () =>
83 {
84 const slots = emptySlots();
85 slots[0] = dyeStack(red, 4, 3);
86 const result = consumeFillCharge(slots, 0, { kind: "dye", itemId: ItemId.dye });
87 assert.equal(result.ok, true);
88 assert.equal(result.exhausted, false);
89 const fills = result.slots
90 .filter((slot) => slot?.itemId === ItemId.dye)
91 .flatMap((slot) => Array.from({ length: stackQuantity(slot.quantity) }, () => slot.instance.fillLevel))
92 .sort((a, b) => b - a);
93 assert.deepEqual(fills, [4, 4, 3]);
94 assert.equal(slots[0].quantity, 3);
95 });
96
97 test("consumeFillCharge returns empty bottle when last sip is drunk", () =>
98 {
99 const slots = emptySlots();
100 slots[0] = potionStack(1, 1);
101 const result = consumeFillCharge(slots, 0, {
102 kind: "potion",
103 itemId: ItemId.potion,
104 returnEmptyItemId: ItemId.glassBottle
105 });
106 assert.equal(result.ok, true);
107 assert.equal(result.exhausted, true);
108 assert.equal(result.slots[0]?.itemId, ItemId.glassBottle);
109 assert.equal(result.slots[0]?.quantity, 1);
110 });
111
112 test("consumeFillCharge refuses multi-stack split when bag is full (no item loss)", () =>
113 {
114 const slots = emptySlots();
115 for (let i = 0; i < slots.length; i++)
116 { slots[i] = { itemId: ItemId.apple, quantity: 1 }; }
117 slots[0] = dyeStack(red, 4, 2);
118 const before = structuredClone(slots);
119 const result = consumeFillCharge(slots, 0, { kind: "dye", itemId: ItemId.dye });
120 assert.equal(result.ok, false);
121 assert.equal(result.reason, "space");
122 assert.deepEqual(slots, before);
123 });
124
125 test("canCraftFitInventory accounts for dye charge split after inputs", () =>
126 {
127 const slots = emptySlots();
128 const yarn = yarnItemId(ClothTier.cotton);
129 slots[0] = { itemId: yarn, quantity: 3 };
130 slots[1] = dyeStack(red, 4, 2);
131 // Leave slot 2 empty for the craft output after dye peels into a freed yarn slot.
132 for (let i = 3; i < slots.length; i++)
133 { slots[i] = { itemId: ItemId.apple, quantity: 1 }; }
134 const recipe = {
135 output: { itemId: sweaterItemId(ClothTier.cotton), quantity: 1 },
136 inputs: [{ itemId: yarn, quantity: 3 }],
137 consumeDye: true,
138 dyeColor: red
139 };
140 assert.equal(canCraftFitInventory(slots, recipe, { dyeSlotIndex: 1 }), true);
141 // Full bag with only the yarn slot freeing: dye peel consumes that free slot → no room for sweater.
142 const tight = emptySlots();
143 tight[0] = { itemId: yarn, quantity: 3 };
144 tight[1] = dyeStack(red, 4, 2);
145 for (let i = 2; i < tight.length; i++)
146 { tight[i] = { itemId: ItemId.apple, quantity: 1 }; }
147 assert.equal(canCraftFitInventory(tight, recipe, { dyeSlotIndex: 1 }), false);
148 });
@@ -0,0 +1,148 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 emptySlots,
5 insertStack,
6 stacksMatch,
7 consumeFillCharge,
8 stackQuantity
9} from "../../shared/items/inventory.js";
10import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11import { dyeItemInstance } from "../../shared/definitions/dyes.js";
12import { potionItemInstance } from "../../shared/alchemy/recipes.js";
13import { canCraftFitInventory } from "../../shared/crafting/recipes.js";
14import { ClothTier } from "../../shared/definitions/materialTiers.js";
15import { sweaterItemId, yarnItemId } from "../../shared/definitions/clothItems.js";
16
17const red = { r: 0.8, g: 0.1, b: 0.1 };
18const blue = { r: 0.1, g: 0.2, b: 0.9 };
19
20function dyeStack (color, fillLevel, quantity = 1)
21{
22 return {
23 itemId: ItemId.dye,
24 quantity,
25 instance: dyeItemInstance(color, fillLevel)
26 };
27}
28
29function potionStack (fillLevel, quantity = 1)
30{
31 return {
32 itemId: ItemId.potion,
33 quantity,
34 instance: potionItemInstance({
35 potionKey: "greenDraught",
36 displayName: "Green draught",
37 color: { r: 0.25, g: 0.72, b: 0.35 },
38 fillLevel,
39 effect: { type: "heal", amount: 5 },
40 effectKey: "heal"
41 })
42 };
43}
44
45test("dyes stack only when colour and fill match", () =>
46{
47 const def = itemDefinition(ItemId.dye);
48 const a = dyeStack(red, 4);
49 const b = dyeStack(red, 4);
50 const differentFill = dyeStack(red, 3);
51 const differentColor = dyeStack(blue, 4);
52 assert.equal(stacksMatch(a, b, def), true);
53 assert.equal(stacksMatch(a, differentFill, def), false);
54 assert.equal(stacksMatch(a, differentColor, def), false);
55 const first = insertStack(emptySlots(), { ...a, quantity: 2 }, def);
56 const second = insertStack(first.slots, differentFill, def);
57 assert.equal(second.ok, true);
58 assert.equal(stackQuantity(second.slots[0].quantity), 2);
59 assert.equal(second.slots[0].instance.fillLevel, 4);
60 assert.equal(second.slots[1].instance.fillLevel, 3);
61});
62
63test("potions stack only when type and fill match", () =>
64{
65 const def = itemDefinition(ItemId.potion);
66 assert.equal(stacksMatch(potionStack(4), potionStack(4), def), true);
67 assert.equal(stacksMatch(potionStack(4), potionStack(3), def), false);
68});
69
70test("consumeFillCharge mutates a single bottle in place", () =>
71{
72 const slots = emptySlots();
73 slots[0] = dyeStack(red, 3, 1);
74 const result = consumeFillCharge(slots, 0, { kind: "dye", itemId: ItemId.dye });
75 assert.equal(result.ok, true);
76 assert.equal(result.exhausted, false);
77 assert.equal(slots[0].instance.fillLevel, 3);
78 assert.equal(result.slots[0].instance.fillLevel, 2);
79 assert.equal(result.slots[0].quantity, 1);
80});
81
82test("consumeFillCharge peels from a multi-stack without losing the reduced bottle", () =>
83{
84 const slots = emptySlots();
85 slots[0] = dyeStack(red, 4, 3);
86 const result = consumeFillCharge(slots, 0, { kind: "dye", itemId: ItemId.dye });
87 assert.equal(result.ok, true);
88 assert.equal(result.exhausted, false);
89 const fills = result.slots
90 .filter((slot) => slot?.itemId === ItemId.dye)
91 .flatMap((slot) => Array.from({ length: stackQuantity(slot.quantity) }, () => slot.instance.fillLevel))
92 .sort((a, b) => b - a);
93 assert.deepEqual(fills, [4, 4, 3]);
94 assert.equal(slots[0].quantity, 3);
95});
96
97test("consumeFillCharge returns empty bottle when last sip is drunk", () =>
98{
99 const slots = emptySlots();
100 slots[0] = potionStack(1, 1);
101 const result = consumeFillCharge(slots, 0, {
102 kind: "potion",
103 itemId: ItemId.potion,
104 returnEmptyItemId: ItemId.glassBottle
105 });
106 assert.equal(result.ok, true);
107 assert.equal(result.exhausted, true);
108 assert.equal(result.slots[0]?.itemId, ItemId.glassBottle);
109 assert.equal(result.slots[0]?.quantity, 1);
110});
111
112test("consumeFillCharge refuses multi-stack split when bag is full (no item loss)", () =>
113{
114 const slots = emptySlots();
115 for (let i = 0; i < slots.length; i++)
116 { slots[i] = { itemId: ItemId.apple, quantity: 1 }; }
117 slots[0] = dyeStack(red, 4, 2);
118 const before = structuredClone(slots);
119 const result = consumeFillCharge(slots, 0, { kind: "dye", itemId: ItemId.dye });
120 assert.equal(result.ok, false);
121 assert.equal(result.reason, "space");
122 assert.deepEqual(slots, before);
123});
124
125test("canCraftFitInventory accounts for dye charge split after inputs", () =>
126{
127 const slots = emptySlots();
128 const yarn = yarnItemId(ClothTier.cotton);
129 slots[0] = { itemId: yarn, quantity: 3 };
130 slots[1] = dyeStack(red, 4, 2);
131 // Leave slot 2 empty for the craft output after dye peels into a freed yarn slot.
132 for (let i = 3; i < slots.length; i++)
133 { slots[i] = { itemId: ItemId.apple, quantity: 1 }; }
134 const recipe = {
135 output: { itemId: sweaterItemId(ClothTier.cotton), quantity: 1 },
136 inputs: [{ itemId: yarn, quantity: 3 }],
137 consumeDye: true,
138 dyeColor: red
139 };
140 assert.equal(canCraftFitInventory(slots, recipe, { dyeSlotIndex: 1 }), true);
141 // Full bag with only the yarn slot freeing: dye peel consumes that free slot → no room for sweater.
142 const tight = emptySlots();
143 tight[0] = { itemId: yarn, quantity: 3 };
144 tight[1] = dyeStack(red, 4, 2);
145 for (let i = 2; i < tight.length; i++)
146 { tight[i] = { itemId: ItemId.apple, quantity: 1 }; }
147 assert.equal(canCraftFitInventory(tight, recipe, { dyeSlotIndex: 1 }), false);
148});
server/tests/shop.test.js +17 −0
@@ -96,6 +96,23 @@ test("humanoid spawner config keeps sex equipment sells quantities and buysItems
96 96 assert.equal(config.maxAlive, 1);
97 97 });
98 98
99 test("humanoid spawner equipment can store clothing dye color", () =>
100 {
101 const dyeColor = { r: 0.2, g: 0.4, b: 0.8 };
102 const config = normalizeSpawnerConfig({
103 mobTypeId: MobId.humanoid,
104 equipment: {
105 chest: { itemId: ItemId.clothShirt, dyeColor },
106 weapon: ItemId.stick
107 }
108 }, "shop-dye");
109 assert.deepEqual(config.equipment.chest, {
110 itemId: ItemId.clothShirt,
111 dyeColor
112 });
113 assert.equal(config.equipment.weapon, ItemId.stick);
114 });
115
99 116 test("buy copper ore from a spawned shopkeeper", () =>
100 117 {
101 118 const harness = makeSimulation({ workerCount: 1 });
@@ -96,6 +96,23 @@ test("humanoid spawner config keeps sex equipment sells quantities and buysItems
96 assert.equal(config.maxAlive, 1);
96 assert.equal(config.maxAlive, 1);
97});
97});
98
98
99test("humanoid spawner equipment can store clothing dye color", () =>
100{
101 const dyeColor = { r: 0.2, g: 0.4, b: 0.8 };
102 const config = normalizeSpawnerConfig({
103 mobTypeId: MobId.humanoid,
104 equipment: {
105 chest: { itemId: ItemId.clothShirt, dyeColor },
106 weapon: ItemId.stick
107 }
108 }, "shop-dye");
109 assert.deepEqual(config.equipment.chest, {
110 itemId: ItemId.clothShirt,
111 dyeColor
112 });
113 assert.equal(config.equipment.weapon, ItemId.stick);
114});
115
99test("buy copper ore from a spawned shopkeeper", () =>
116test("buy copper ore from a spawned shopkeeper", () =>
100{
117{
101 const harness = makeSimulation({ workerCount: 1 });
118 const harness = makeSimulation({ workerCount: 1 });
shared/crafting/recipes.js +18 −9
@@ -1,5 +1,5 @@
1 1 import { itemDefinition } from "../definitions/items.js";
2 import { insertStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
2 import { consumeFillCharge, insertStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
3 3
4 4 export { recipesForStation, recipeDefinition, recipeStationIds } from "./stationRecipes.js";
5 5
@@ -27,10 +27,10 @@ function takeItemPreservingSlots (slots, itemId, quantity)
27 27
28 28 /**
29 29 * Recipe shape: `{ output: { itemId, quantity }, inputs: [{ itemId, quantity }] }`.
30 * Returns whether the player has the inputs and, after consuming them, room for the output.
31 * Freed slots from consumed stacks count toward output space.
30 * Returns whether the player has the inputs and, after consuming them (and optional dye
31 * charge), room for the output. Freed slots from consumed stacks count toward output space.
32 32 */
33 export function canCraftFitInventory (slots, recipe)
33 export function canCraftFitInventory (slots, recipe, options = {})
34 34 {
35 35 if (!recipe?.output?.itemId || !Array.isArray(recipe.inputs))
36 36 { return false; }
@@ -45,13 +45,22 @@ export function canCraftFitInventory (slots, recipe)
45 45 { return false; }
46 46 next = taken.slots;
47 47 }
48 if (recipe.consumeDye && options.dyeSlotIndex != null)
49 {
50 const dyeCheck = consumeFillCharge(next, options.dyeSlotIndex | 0, { kind: "dye" });
51 if (!dyeCheck.ok)
52 { return false; }
53 next = dyeCheck.slots;
54 }
48 55 const def = itemDefinition(recipe.output.itemId);
49 56 if (!def)
50 57 { return false; }
51 const added = insertStack(next, {
58 const outStack = {
52 59 itemId: recipe.output.itemId,
53 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
54 }, def);
60 quantity: Math.max(1, recipe.output.quantity | 0 || 1),
61 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
62 };
63 const added = insertStack(next, outStack, def);
55 64 return added.ok && added.remainder === 0;
56 65 }
57 66
@@ -82,7 +91,7 @@ export function hasRecipeInputs (slots, recipe)
82 91 }
83 92
84 93 /** Whether the player meets skill, has inputs, and bag space after consumption. */
85 export function canStartCraft (slots, recipe, skillLevel = 1)
94 export function canStartCraft (slots, recipe, skillLevel = 1, options = {})
86 95 {
87 96 if (!recipe?.output?.itemId)
88 97 { return false; }
@@ -91,5 +100,5 @@ export function canStartCraft (slots, recipe, skillLevel = 1)
91 100 { return false; }
92 101 if (!hasRecipeInputs(slots, recipe))
93 102 { return false; }
94 return canCraftFitInventory(slots, recipe);
103 return canCraftFitInventory(slots, recipe, options);
95 104 }
@@ -1,5 +1,5 @@
1import { itemDefinition } from "../definitions/items.js";
1import { itemDefinition } from "../definitions/items.js";
2import { insertStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
2import { consumeFillCharge, insertStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
3
3
4export { recipesForStation, recipeDefinition, recipeStationIds } from "./stationRecipes.js";
4export { recipesForStation, recipeDefinition, recipeStationIds } from "./stationRecipes.js";
5
5
@@ -27,10 +27,10 @@ function takeItemPreservingSlots (slots, itemId, quantity)
27
27
28/**
28/**
29 * Recipe shape: `{ output: { itemId, quantity }, inputs: [{ itemId, quantity }] }`.
29 * Recipe shape: `{ output: { itemId, quantity }, inputs: [{ itemId, quantity }] }`.
30 * Returns whether the player has the inputs and, after consuming them, room for the output.
30 * Returns whether the player has the inputs and, after consuming them (and optional dye
31 * Freed slots from consumed stacks count toward output space.
31 * charge), room for the output. Freed slots from consumed stacks count toward output space.
32 */
32 */
33export function canCraftFitInventory (slots, recipe)
33export function canCraftFitInventory (slots, recipe, options = {})
34{
34{
35 if (!recipe?.output?.itemId || !Array.isArray(recipe.inputs))
35 if (!recipe?.output?.itemId || !Array.isArray(recipe.inputs))
36 { return false; }
36 { return false; }
@@ -45,13 +45,22 @@ export function canCraftFitInventory (slots, recipe)
45 { return false; }
45 { return false; }
46 next = taken.slots;
46 next = taken.slots;
47 }
47 }
48 if (recipe.consumeDye && options.dyeSlotIndex != null)
49 {
50 const dyeCheck = consumeFillCharge(next, options.dyeSlotIndex | 0, { kind: "dye" });
51 if (!dyeCheck.ok)
52 { return false; }
53 next = dyeCheck.slots;
54 }
48 const def = itemDefinition(recipe.output.itemId);
55 const def = itemDefinition(recipe.output.itemId);
49 if (!def)
56 if (!def)
50 { return false; }
57 { return false; }
51 const added = insertStack(next, {
58 const outStack = {
52 itemId: recipe.output.itemId,
59 itemId: recipe.output.itemId,
53 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
60 quantity: Math.max(1, recipe.output.quantity | 0 || 1),
54 }, def);
61 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
62 };
63 const added = insertStack(next, outStack, def);
55 return added.ok && added.remainder === 0;
64 return added.ok && added.remainder === 0;
56}
65}
57
66
@@ -82,7 +91,7 @@ export function hasRecipeInputs (slots, recipe)
82}
91}
83
92
84/** Whether the player meets skill, has inputs, and bag space after consumption. */
93/** Whether the player meets skill, has inputs, and bag space after consumption. */
85export function canStartCraft (slots, recipe, skillLevel = 1)
94export function canStartCraft (slots, recipe, skillLevel = 1, options = {})
86{
95{
87 if (!recipe?.output?.itemId)
96 if (!recipe?.output?.itemId)
88 { return false; }
97 { return false; }
@@ -91,5 +100,5 @@ export function canStartCraft (slots, recipe, skillLevel = 1)
91 { return false; }
100 { return false; }
92 if (!hasRecipeInputs(slots, recipe))
101 if (!hasRecipeInputs(slots, recipe))
93 { return false; }
102 { return false; }
94 return canCraftFitInventory(slots, recipe);
103 return canCraftFitInventory(slots, recipe, options);
95}
104}
shared/definitions/armourItems.js +1 −1
@@ -136,7 +136,7 @@ function armourDef (itemId, tier, piece)
136 136 itemId,
137 137 key,
138 138 displayName: `${tierName} ${piece.label}`,
139 description: `Worn ${tierName.toLowerCase()} ${piece.label}.`,
139 description: `Worn ${tierName.toLowerCase()} ${piece.label}, forged for the road.`,
140 140 seedValue: 12,
141 141 stackable: false,
142 142 maxStackSize: 1,
@@ -136,7 +136,7 @@ function armourDef (itemId, tier, piece)
136 itemId,
136 itemId,
137 key,
137 key,
138 displayName: `${tierName} ${piece.label}`,
138 displayName: `${tierName} ${piece.label}`,
139 description: `Worn ${tierName.toLowerCase()} ${piece.label}.`,
139 description: `Worn ${tierName.toLowerCase()} ${piece.label}, forged for the road.`,
140 seedValue: 12,
140 seedValue: 12,
141 stackable: false,
141 stackable: false,
142 maxStackSize: 1,
142 maxStackSize: 1,
shared/definitions/clothItems.js +2 −1
@@ -160,7 +160,7 @@ function sweaterDef (itemId, tier, key)
160 160 itemId,
161 161 key,
162 162 displayName: `${name} sweater`,
163 description: `A warm ${name.toLowerCase()} sweater. Mostly cosmetic for now; optional dye overrides the material colour.`,
163 description: `A warm ${name.toLowerCase()} sweater, soft enough for travel.`,
164 164 seedValue: 10,
165 165 stackable: false,
166 166 maxStackSize: 1,
@@ -170,6 +170,7 @@ function sweaterDef (itemId, tier, key)
170 170 defaultState: "sweater",
171 171 tier,
172 172 tintFromTier: true,
173 dyeable: true,
173 174 clothing: Object.freeze({ warm: true, style: true }),
174 175 equipment: Object.freeze({
175 176 slot: "chest",
@@ -160,7 +160,7 @@ function sweaterDef (itemId, tier, key)
160 itemId,
160 itemId,
161 key,
161 key,
162 displayName: `${name} sweater`,
162 displayName: `${name} sweater`,
163 description: `A warm ${name.toLowerCase()} sweater. Mostly cosmetic for now; optional dye overrides the material colour.`,
163 description: `A warm ${name.toLowerCase()} sweater, soft enough for travel.`,
164 seedValue: 10,
164 seedValue: 10,
165 stackable: false,
165 stackable: false,
166 maxStackSize: 1,
166 maxStackSize: 1,
@@ -170,6 +170,7 @@ function sweaterDef (itemId, tier, key)
170 defaultState: "sweater",
170 defaultState: "sweater",
171 tier,
171 tier,
172 tintFromTier: true,
172 tintFromTier: true,
173 dyeable: true,
173 clothing: Object.freeze({ warm: true, style: true }),
174 clothing: Object.freeze({ warm: true, style: true }),
174 equipment: Object.freeze({
175 equipment: Object.freeze({
175 slot: "chest",
176 slot: "chest",
shared/definitions/craftingItems.js +15 −15
@@ -32,7 +32,7 @@ function stub (itemId, key, displayName, category, extra = {})
32 32 itemId,
33 33 key,
34 34 displayName,
35 description: extra.description ?? "Placeholder — complete this definition when content rules are set.",
35 description: extra.description ?? "An unfinished good awaiting a proper name.",
36 36 seedValue: extra.seedValue ?? 1,
37 37 stackable: extra.stackable ?? true,
38 38 maxStackSize: extra.maxStackSize ?? DEFAULT_STACK,
@@ -49,13 +49,13 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
49 49 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
50 50 stackable: false,
51 51 maxStackSize: 1,
52 description: "Lights campfires from dropped logs."
52 description: "A small kit for striking sparks onto dry tinder."
53 53 }),
54 54 [CraftingItemId.copperOre]: Object.freeze({
55 55 itemId: CraftingItemId.copperOre,
56 56 key: "copper-ore",
57 57 displayName: "Copper ore",
58 description: "Mined copper. Smelt with tin at a furnace into bronze bars.",
58 description: "Reddish copper ore. Smelt with tin at a furnace into bronze bars.",
59 59 seedValue: 5,
60 60 stackable: true,
61 61 maxStackSize: DEFAULT_STACK,
@@ -70,7 +70,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
70 70 itemId: CraftingItemId.tinOre,
71 71 key: "tin-ore",
72 72 displayName: "Tin ore",
73 description: "Mined tin. Smelt with copper at a furnace into bronze bars.",
73 description: "Pale tin ore. Smelt with copper at a furnace into bronze bars.",
74 74 seedValue: 5,
75 75 stackable: true,
76 76 maxStackSize: DEFAULT_STACK,
@@ -85,7 +85,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
85 85 itemId: CraftingItemId.bronzeBar,
86 86 key: "bronze-bar",
87 87 displayName: "Bronze bar",
88 description: "Smelted from tin and copper. Smith at an anvil.",
88 description: "A solid bronze bar, ready for the anvil.",
89 89 seedValue: 4,
90 90 stackable: true,
91 91 maxStackSize: DEFAULT_STACK,
@@ -97,25 +97,25 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
97 97 tintFromTier: true
98 98 }),
99 99 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
100 description: "Cook at an oven or campfire."
100 description: "Fresh meat. Cook at an oven or campfire."
101 101 }),
102 102 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
103 description: "Cooked food. Eating rules TBD."
103 description: "Meat roasted until tender."
104 104 }),
105 105 [CraftingItemId.leather]: stub(CraftingItemId.leather, "leather", "Leather", ItemCategory.ingredient, {
106 description: "Dropped from certain mobs. Craft leather goods at a leatherworking station."
106 description: "Cured hide, stout enough for armour and straps."
107 107 }),
108 108 [CraftingItemId.arrowTip]: stub(CraftingItemId.arrowTip, "arrow-tip", "Arrow tip", ItemCategory.intermediate, {
109 description: "Smithed tip. Fletch into arrows at a crafting bench."
109 description: "A sharp tip waiting to be fletched onto a shaft."
110 110 }),
111 111 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
112 description: "Ammunition for bows."
112 description: "A fletched arrow for the bow."
113 113 }),
114 114 [CraftingItemId.bronzeAxe]: Object.freeze({
115 115 itemId: CraftingItemId.bronzeAxe,
116 116 key: "bronze-axe",
117 117 displayName: "Bronze axe",
118 description: "Woodcutting tool. Bronze may be equipped at any Woodcutting level.",
118 description: "A bronze axe for felling trees.",
119 119 seedValue: 8,
120 120 stackable: false,
121 121 maxStackSize: 1,
@@ -134,7 +134,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
134 134 itemId: CraftingItemId.bronzePickaxe,
135 135 key: "bronze-pickaxe",
136 136 displayName: "Bronze pickaxe",
137 description: "Mining tool. Bronze may be equipped at any Mining level.",
137 description: "A bronze pickaxe for breaking stone and ore.",
138 138 seedValue: 8,
139 139 stackable: false,
140 140 maxStackSize: 1,
@@ -152,14 +152,14 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
152 152 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
153 153 stackable: false,
154 154 maxStackSize: 1,
155 description: "Fishing tool."
155 description: "A simple rod and line for still waters."
156 156 }),
157 157 [CraftingItemId.fishingNet]: stub(CraftingItemId.fishingNet, "fishing-net", "Fishing net", ItemCategory.tool, {
158 158 stackable: false,
159 159 maxStackSize: 1,
160 description: "Fishing tool."
160 description: "A woven net for scooping fish."
161 161 }),
162 162 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
163 description: "Caught fish. Cook like raw meat."
163 description: "A fresh catch. Cook at an oven or campfire."
164 164 })
165 165 });
@@ -32,7 +32,7 @@ function stub (itemId, key, displayName, category, extra = {})
32 itemId,
32 itemId,
33 key,
33 key,
34 displayName,
34 displayName,
35 description: extra.description ?? "Placeholder — complete this definition when content rules are set.",
35 description: extra.description ?? "An unfinished good awaiting a proper name.",
36 seedValue: extra.seedValue ?? 1,
36 seedValue: extra.seedValue ?? 1,
37 stackable: extra.stackable ?? true,
37 stackable: extra.stackable ?? true,
38 maxStackSize: extra.maxStackSize ?? DEFAULT_STACK,
38 maxStackSize: extra.maxStackSize ?? DEFAULT_STACK,
@@ -49,13 +49,13 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
49 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
49 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
50 stackable: false,
50 stackable: false,
51 maxStackSize: 1,
51 maxStackSize: 1,
52 description: "Lights campfires from dropped logs."
52 description: "A small kit for striking sparks onto dry tinder."
53 }),
53 }),
54 [CraftingItemId.copperOre]: Object.freeze({
54 [CraftingItemId.copperOre]: Object.freeze({
55 itemId: CraftingItemId.copperOre,
55 itemId: CraftingItemId.copperOre,
56 key: "copper-ore",
56 key: "copper-ore",
57 displayName: "Copper ore",
57 displayName: "Copper ore",
58 description: "Mined copper. Smelt with tin at a furnace into bronze bars.",
58 description: "Reddish copper ore. Smelt with tin at a furnace into bronze bars.",
59 seedValue: 5,
59 seedValue: 5,
60 stackable: true,
60 stackable: true,
61 maxStackSize: DEFAULT_STACK,
61 maxStackSize: DEFAULT_STACK,
@@ -70,7 +70,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
70 itemId: CraftingItemId.tinOre,
70 itemId: CraftingItemId.tinOre,
71 key: "tin-ore",
71 key: "tin-ore",
72 displayName: "Tin ore",
72 displayName: "Tin ore",
73 description: "Mined tin. Smelt with copper at a furnace into bronze bars.",
73 description: "Pale tin ore. Smelt with copper at a furnace into bronze bars.",
74 seedValue: 5,
74 seedValue: 5,
75 stackable: true,
75 stackable: true,
76 maxStackSize: DEFAULT_STACK,
76 maxStackSize: DEFAULT_STACK,
@@ -85,7 +85,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
85 itemId: CraftingItemId.bronzeBar,
85 itemId: CraftingItemId.bronzeBar,
86 key: "bronze-bar",
86 key: "bronze-bar",
87 displayName: "Bronze bar",
87 displayName: "Bronze bar",
88 description: "Smelted from tin and copper. Smith at an anvil.",
88 description: "A solid bronze bar, ready for the anvil.",
89 seedValue: 4,
89 seedValue: 4,
90 stackable: true,
90 stackable: true,
91 maxStackSize: DEFAULT_STACK,
91 maxStackSize: DEFAULT_STACK,
@@ -97,25 +97,25 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
97 tintFromTier: true
97 tintFromTier: true
98 }),
98 }),
99 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
99 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
100 description: "Cook at an oven or campfire."
100 description: "Fresh meat. Cook at an oven or campfire."
101 }),
101 }),
102 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
102 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
103 description: "Cooked food. Eating rules TBD."
103 description: "Meat roasted until tender."
104 }),
104 }),
105 [CraftingItemId.leather]: stub(CraftingItemId.leather, "leather", "Leather", ItemCategory.ingredient, {
105 [CraftingItemId.leather]: stub(CraftingItemId.leather, "leather", "Leather", ItemCategory.ingredient, {
106 description: "Dropped from certain mobs. Craft leather goods at a leatherworking station."
106 description: "Cured hide, stout enough for armour and straps."
107 }),
107 }),
108 [CraftingItemId.arrowTip]: stub(CraftingItemId.arrowTip, "arrow-tip", "Arrow tip", ItemCategory.intermediate, {
108 [CraftingItemId.arrowTip]: stub(CraftingItemId.arrowTip, "arrow-tip", "Arrow tip", ItemCategory.intermediate, {
109 description: "Smithed tip. Fletch into arrows at a crafting bench."
109 description: "A sharp tip waiting to be fletched onto a shaft."
110 }),
110 }),
111 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
111 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
112 description: "Ammunition for bows."
112 description: "A fletched arrow for the bow."
113 }),
113 }),
114 [CraftingItemId.bronzeAxe]: Object.freeze({
114 [CraftingItemId.bronzeAxe]: Object.freeze({
115 itemId: CraftingItemId.bronzeAxe,
115 itemId: CraftingItemId.bronzeAxe,
116 key: "bronze-axe",
116 key: "bronze-axe",
117 displayName: "Bronze axe",
117 displayName: "Bronze axe",
118 description: "Woodcutting tool. Bronze may be equipped at any Woodcutting level.",
118 description: "A bronze axe for felling trees.",
119 seedValue: 8,
119 seedValue: 8,
120 stackable: false,
120 stackable: false,
121 maxStackSize: 1,
121 maxStackSize: 1,
@@ -134,7 +134,7 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
134 itemId: CraftingItemId.bronzePickaxe,
134 itemId: CraftingItemId.bronzePickaxe,
135 key: "bronze-pickaxe",
135 key: "bronze-pickaxe",
136 displayName: "Bronze pickaxe",
136 displayName: "Bronze pickaxe",
137 description: "Mining tool. Bronze may be equipped at any Mining level.",
137 description: "A bronze pickaxe for breaking stone and ore.",
138 seedValue: 8,
138 seedValue: 8,
139 stackable: false,
139 stackable: false,
140 maxStackSize: 1,
140 maxStackSize: 1,
@@ -152,14 +152,14 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
152 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
152 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
153 stackable: false,
153 stackable: false,
154 maxStackSize: 1,
154 maxStackSize: 1,
155 description: "Fishing tool."
155 description: "A simple rod and line for still waters."
156 }),
156 }),
157 [CraftingItemId.fishingNet]: stub(CraftingItemId.fishingNet, "fishing-net", "Fishing net", ItemCategory.tool, {
157 [CraftingItemId.fishingNet]: stub(CraftingItemId.fishingNet, "fishing-net", "Fishing net", ItemCategory.tool, {
158 stackable: false,
158 stackable: false,
159 maxStackSize: 1,
159 maxStackSize: 1,
160 description: "Fishing tool."
160 description: "A woven net for scooping fish."
161 }),
161 }),
162 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
162 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
163 description: "Caught fish. Cook like raw meat."
163 description: "A fresh catch. Cook at an oven or campfire."
164 })
164 })
165});
165});
shared/definitions/craftingStations.js +4 −4
@@ -43,7 +43,7 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
43 43 stationId: CraftingStationId.tailorBench,
44 44 displayName: "Tailor's bench",
45 45 skillId: SkillId.tailoring,
46 description: "Sew garments from yarn or cloth. Optional dye colours the result."
46 description: "Sew garments from yarn or cloth; dyes may colour the cloth."
47 47 }),
48 48 [CraftingStationId.anvil]: Object.freeze({
49 49 stationId: CraftingStationId.anvil,
@@ -61,7 +61,7 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
61 61 stationId: CraftingStationId.craftingBench,
62 62 displayName: "Crafting bench",
63 63 skillId: SkillId.crafting,
64 description: "Assemble finished parts (handles + pickaxe/axe heads, later similar kits)."
64 description: "Fit handles to tool heads and finish assembled goods."
65 65 }),
66 66 [CraftingStationId.woodworkingBench]: Object.freeze({
67 67 stationId: CraftingStationId.woodworkingBench,
@@ -73,13 +73,13 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
73 73 stationId: CraftingStationId.oven,
74 74 displayName: "Oven",
75 75 skillId: SkillId.cooking,
76 description: "Cook raw meat; low Cooking risks burning the food."
76 description: "Cook raw meat over steady heat."
77 77 }),
78 78 [CraftingStationId.fireplace]: Object.freeze({
79 79 stationId: CraftingStationId.fireplace,
80 80 displayName: "Campfire",
81 81 skillId: SkillId.cooking,
82 description: "Portable cooking like an oven but a higher burn chance.",
82 description: "An open fire for cooking on the road; food scorches more easily here.",
83 83 portable: true,
84 84 maxPerTile: 1,
85 85 durationMs: FIREPLACE_DURATION_MS
@@ -43,7 +43,7 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
43 stationId: CraftingStationId.tailorBench,
43 stationId: CraftingStationId.tailorBench,
44 displayName: "Tailor's bench",
44 displayName: "Tailor's bench",
45 skillId: SkillId.tailoring,
45 skillId: SkillId.tailoring,
46 description: "Sew garments from yarn or cloth. Optional dye colours the result."
46 description: "Sew garments from yarn or cloth; dyes may colour the cloth."
47 }),
47 }),
48 [CraftingStationId.anvil]: Object.freeze({
48 [CraftingStationId.anvil]: Object.freeze({
49 stationId: CraftingStationId.anvil,
49 stationId: CraftingStationId.anvil,
@@ -61,7 +61,7 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
61 stationId: CraftingStationId.craftingBench,
61 stationId: CraftingStationId.craftingBench,
62 displayName: "Crafting bench",
62 displayName: "Crafting bench",
63 skillId: SkillId.crafting,
63 skillId: SkillId.crafting,
64 description: "Assemble finished parts (handles + pickaxe/axe heads, later similar kits)."
64 description: "Fit handles to tool heads and finish assembled goods."
65 }),
65 }),
66 [CraftingStationId.woodworkingBench]: Object.freeze({
66 [CraftingStationId.woodworkingBench]: Object.freeze({
67 stationId: CraftingStationId.woodworkingBench,
67 stationId: CraftingStationId.woodworkingBench,
@@ -73,13 +73,13 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
73 stationId: CraftingStationId.oven,
73 stationId: CraftingStationId.oven,
74 displayName: "Oven",
74 displayName: "Oven",
75 skillId: SkillId.cooking,
75 skillId: SkillId.cooking,
76 description: "Cook raw meat; low Cooking risks burning the food."
76 description: "Cook raw meat over steady heat."
77 }),
77 }),
78 [CraftingStationId.fireplace]: Object.freeze({
78 [CraftingStationId.fireplace]: Object.freeze({
79 stationId: CraftingStationId.fireplace,
79 stationId: CraftingStationId.fireplace,
80 displayName: "Campfire",
80 displayName: "Campfire",
81 skillId: SkillId.cooking,
81 skillId: SkillId.cooking,
82 description: "Portable cooking like an oven but a higher burn chance.",
82 description: "An open fire for cooking on the road; food scorches more easily here.",
83 portable: true,
83 portable: true,
84 maxPerTile: 1,
84 maxPerTile: 1,
85 durationMs: FIREPLACE_DURATION_MS
85 durationMs: FIREPLACE_DURATION_MS
shared/definitions/dyes.js +2 −2
@@ -176,7 +176,7 @@ export const FLOWER_ITEM_DEFINITION = Object.freeze({
176 176 itemId: DyeItemId.flower,
177 177 key: "flower",
178 178 displayName: "Flower",
179 description: "A colourful flower. Mix into dye at a cauldron.",
179 description: "A colourful flower. Crush into dye at a cauldron.",
180 180 seedValue: 2,
181 181 stackable: true,
182 182 maxStackSize: 99,
@@ -191,7 +191,7 @@ export const DYE_ITEM_DEFINITION = Object.freeze({
191 191 itemId: DyeItemId.dye,
192 192 key: "dye",
193 193 displayName: "Dye",
194 description: "Bottled dye for cloth and clothing. Same colours stack up to 16.",
194 description: "Bottled colour for cloth and clothing.",
195 195 seedValue: 4,
196 196 stackable: true,
197 197 maxStackSize: 16,
@@ -176,7 +176,7 @@ export const FLOWER_ITEM_DEFINITION = Object.freeze({
176 itemId: DyeItemId.flower,
176 itemId: DyeItemId.flower,
177 key: "flower",
177 key: "flower",
178 displayName: "Flower",
178 displayName: "Flower",
179 description: "A colourful flower. Mix into dye at a cauldron.",
179 description: "A colourful flower. Crush into dye at a cauldron.",
180 seedValue: 2,
180 seedValue: 2,
181 stackable: true,
181 stackable: true,
182 maxStackSize: 99,
182 maxStackSize: 99,
@@ -191,7 +191,7 @@ export const DYE_ITEM_DEFINITION = Object.freeze({
191 itemId: DyeItemId.dye,
191 itemId: DyeItemId.dye,
192 key: "dye",
192 key: "dye",
193 displayName: "Dye",
193 displayName: "Dye",
194 description: "Bottled dye for cloth and clothing. Same colours stack up to 16.",
194 description: "Bottled colour for cloth and clothing.",
195 seedValue: 4,
195 seedValue: 4,
196 stackable: true,
196 stackable: true,
197 maxStackSize: 16,
197 maxStackSize: 16,
shared/definitions/items.js +23 −12
@@ -135,7 +135,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
135 135 itemId: ItemId.blankCheque,
136 136 key: "blank-cheque",
137 137 displayName: "Blank cheque",
138 description: "Free bank paper. Write a cheque to reserve vault goods.",
138 description: "Bank stationery for writing cheques against deposited goods.",
139 139 seedValue: 5,
140 140 stackable: true,
141 141 maxStackSize: DEFAULT_MAX_STACK,
@@ -161,7 +161,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
161 161 itemId: ItemId.clothShirt,
162 162 key: "cloth-shirt",
163 163 displayName: "Cloth shirt",
164 description: "A simple cloth shirt. Shared clothing/shirt art (tintable).",
164 description: "A simple cloth shirt, plain and practical.",
165 165 seedValue: 8,
166 166 stackable: false,
167 167 maxStackSize: 1,
@@ -169,6 +169,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
169 169 category: "finished",
170 170 iconKey: "clothing",
171 171 defaultState: "shirt",
172 dyeable: true,
173 clothing: Object.freeze({ warm: false, style: true }),
172 174 equipment: Object.freeze({
173 175 slot: EQUIPMENT_SLOT.chest,
174 176 tier: MaterialTier.bronze,
@@ -181,7 +183,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
181 183 key: "coins",
182 184 displayName: "Coin",
183 185 displayNamePlural: "Coins",
184 description: "Currency carried in your bag.",
186 description: "Hard currency of the realm.",
185 187 seedValue: 1,
186 188 stackable: true,
187 189 maxStackSize: COIN_MAX_STACK,
@@ -192,7 +194,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
192 194 itemId: ItemId.lantern,
193 195 key: "lantern",
194 196 displayName: "Lantern",
195 description: "A handheld light source. Equip in the offhand to illuminate your surroundings at night.",
197 description: "A handheld lamp that pushes back the night.",
196 198 seedValue: 12,
197 199 stackable: false,
198 200 maxStackSize: 1,
@@ -229,7 +231,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
229 231 itemId: ItemId.glassBottle,
230 232 key: "glass-bottle",
231 233 displayName: "Glass bottle",
232 description: "An empty bottle for potions and dyes.",
234 description: "A clear bottle, ready to hold a brew or dye.",
233 235 seedValue: 2,
234 236 stackable: true,
235 237 maxStackSize: DEFAULT_MAX_STACK,
@@ -243,7 +245,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
243 245 itemId: ItemId.greenHerb,
244 246 key: "green-herb",
245 247 displayName: "Green herb",
246 description: "A common herb. Gathered with plant clippers.",
248 description: "A fragrant common herb.",
247 249 seedValue: 2,
248 250 stackable: true,
249 251 maxStackSize: DEFAULT_MAX_STACK,
@@ -265,7 +267,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
265 267 itemId: ItemId.potion,
266 268 key: "potion",
267 269 displayName: "Potion",
268 description: "A bottled brew. Drink to apply its effect (effects TBD).",
270 description: "A bottled brew. Sip with care.",
269 271 seedValue: 8,
270 272 stackable: true,
271 273 maxStackSize: POTION_MAX_STACK,
@@ -278,7 +280,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
278 280 itemId: ItemId.recipePaper,
279 281 key: "recipe-paper",
280 282 displayName: "Recipe paper",
281 description: "An alchemy recipe.",
283 description: "An alchemy recipe written for a cauldron.",
282 284 seedValue: 2,
283 285 stackable: false,
284 286 maxStackSize: 1,
@@ -291,7 +293,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
291 293 itemId: ItemId.bronzePlantClippers,
292 294 key: "bronze-plant-clippers",
293 295 displayName: "Bronze plant clippers",
294 description: "Use this to gather herbs and flowers.",
296 description: "Fine shears for cutting herbs and blooms.",
295 297 seedValue: 10,
296 298 stackable: false,
297 299 maxStackSize: 1,
@@ -319,6 +321,15 @@ export function itemDefinition (itemId)
319 321 return ITEM_DEFINITIONS[itemId] ?? null;
320 322 }
321 323
324 /** Garments that accept optional `instance.dyeColor` (tailor / cloth clothing). */
325 export function isDyeableClothing (itemIdOrDef)
326 {
327 const def = typeof itemIdOrDef === "number"
328 ? itemDefinition(itemIdOrDef)
329 : itemIdOrDef;
330 return !!def?.dyeable;
331 }
332
322 333 export { formatQuantity };
323 334
324 335 export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
@@ -391,11 +402,11 @@ export function itemDescription (stack, { localCharacterId } = {})
391 402 {
392 403 const name = stack.instance.displayName ?? "Potion";
393 404 return stack.instance.unstable
394 ? `${name}. An unstable brew — effects are unpredictable.`
395 : `${name}. Drink to apply its effect.`;
405 ? `${name}. The brew smells wrong — best sipped with caution.`
406 : `${name}. A carefully bottled draught.`;
396 407 }
397 408 if (stack.itemId === ItemId.recipePaper && stack.instance?.kind === "recipe-paper")
398 { return "An alchemy recipe."; }
409 { return "Notes on how to brew a particular draught."; }
399 410 return def.description ?? "";
400 411 }
401 412
@@ -135,7 +135,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
135 itemId: ItemId.blankCheque,
135 itemId: ItemId.blankCheque,
136 key: "blank-cheque",
136 key: "blank-cheque",
137 displayName: "Blank cheque",
137 displayName: "Blank cheque",
138 description: "Free bank paper. Write a cheque to reserve vault goods.",
138 description: "Bank stationery for writing cheques against deposited goods.",
139 seedValue: 5,
139 seedValue: 5,
140 stackable: true,
140 stackable: true,
141 maxStackSize: DEFAULT_MAX_STACK,
141 maxStackSize: DEFAULT_MAX_STACK,
@@ -161,7 +161,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
161 itemId: ItemId.clothShirt,
161 itemId: ItemId.clothShirt,
162 key: "cloth-shirt",
162 key: "cloth-shirt",
163 displayName: "Cloth shirt",
163 displayName: "Cloth shirt",
164 description: "A simple cloth shirt. Shared clothing/shirt art (tintable).",
164 description: "A simple cloth shirt, plain and practical.",
165 seedValue: 8,
165 seedValue: 8,
166 stackable: false,
166 stackable: false,
167 maxStackSize: 1,
167 maxStackSize: 1,
@@ -169,6 +169,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
169 category: "finished",
169 category: "finished",
170 iconKey: "clothing",
170 iconKey: "clothing",
171 defaultState: "shirt",
171 defaultState: "shirt",
172 dyeable: true,
173 clothing: Object.freeze({ warm: false, style: true }),
172 equipment: Object.freeze({
174 equipment: Object.freeze({
173 slot: EQUIPMENT_SLOT.chest,
175 slot: EQUIPMENT_SLOT.chest,
174 tier: MaterialTier.bronze,
176 tier: MaterialTier.bronze,
@@ -181,7 +183,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
181 key: "coins",
183 key: "coins",
182 displayName: "Coin",
184 displayName: "Coin",
183 displayNamePlural: "Coins",
185 displayNamePlural: "Coins",
184 description: "Currency carried in your bag.",
186 description: "Hard currency of the realm.",
185 seedValue: 1,
187 seedValue: 1,
186 stackable: true,
188 stackable: true,
187 maxStackSize: COIN_MAX_STACK,
189 maxStackSize: COIN_MAX_STACK,
@@ -192,7 +194,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
192 itemId: ItemId.lantern,
194 itemId: ItemId.lantern,
193 key: "lantern",
195 key: "lantern",
194 displayName: "Lantern",
196 displayName: "Lantern",
195 description: "A handheld light source. Equip in the offhand to illuminate your surroundings at night.",
197 description: "A handheld lamp that pushes back the night.",
196 seedValue: 12,
198 seedValue: 12,
197 stackable: false,
199 stackable: false,
198 maxStackSize: 1,
200 maxStackSize: 1,
@@ -229,7 +231,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
229 itemId: ItemId.glassBottle,
231 itemId: ItemId.glassBottle,
230 key: "glass-bottle",
232 key: "glass-bottle",
231 displayName: "Glass bottle",
233 displayName: "Glass bottle",
232 description: "An empty bottle for potions and dyes.",
234 description: "A clear bottle, ready to hold a brew or dye.",
233 seedValue: 2,
235 seedValue: 2,
234 stackable: true,
236 stackable: true,
235 maxStackSize: DEFAULT_MAX_STACK,
237 maxStackSize: DEFAULT_MAX_STACK,
@@ -243,7 +245,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
243 itemId: ItemId.greenHerb,
245 itemId: ItemId.greenHerb,
244 key: "green-herb",
246 key: "green-herb",
245 displayName: "Green herb",
247 displayName: "Green herb",
246 description: "A common herb. Gathered with plant clippers.",
248 description: "A fragrant common herb.",
247 seedValue: 2,
249 seedValue: 2,
248 stackable: true,
250 stackable: true,
249 maxStackSize: DEFAULT_MAX_STACK,
251 maxStackSize: DEFAULT_MAX_STACK,
@@ -265,7 +267,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
265 itemId: ItemId.potion,
267 itemId: ItemId.potion,
266 key: "potion",
268 key: "potion",
267 displayName: "Potion",
269 displayName: "Potion",
268 description: "A bottled brew. Drink to apply its effect (effects TBD).",
270 description: "A bottled brew. Sip with care.",
269 seedValue: 8,
271 seedValue: 8,
270 stackable: true,
272 stackable: true,
271 maxStackSize: POTION_MAX_STACK,
273 maxStackSize: POTION_MAX_STACK,
@@ -278,7 +280,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
278 itemId: ItemId.recipePaper,
280 itemId: ItemId.recipePaper,
279 key: "recipe-paper",
281 key: "recipe-paper",
280 displayName: "Recipe paper",
282 displayName: "Recipe paper",
281 description: "An alchemy recipe.",
283 description: "An alchemy recipe written for a cauldron.",
282 seedValue: 2,
284 seedValue: 2,
283 stackable: false,
285 stackable: false,
284 maxStackSize: 1,
286 maxStackSize: 1,
@@ -291,7 +293,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
291 itemId: ItemId.bronzePlantClippers,
293 itemId: ItemId.bronzePlantClippers,
292 key: "bronze-plant-clippers",
294 key: "bronze-plant-clippers",
293 displayName: "Bronze plant clippers",
295 displayName: "Bronze plant clippers",
294 description: "Use this to gather herbs and flowers.",
296 description: "Fine shears for cutting herbs and blooms.",
295 seedValue: 10,
297 seedValue: 10,
296 stackable: false,
298 stackable: false,
297 maxStackSize: 1,
299 maxStackSize: 1,
@@ -319,6 +321,15 @@ export function itemDefinition (itemId)
319 return ITEM_DEFINITIONS[itemId] ?? null;
321 return ITEM_DEFINITIONS[itemId] ?? null;
320}
322}
321
323
324/** Garments that accept optional `instance.dyeColor` (tailor / cloth clothing). */
325export function isDyeableClothing (itemIdOrDef)
326{
327 const def = typeof itemIdOrDef === "number"
328 ? itemDefinition(itemIdOrDef)
329 : itemIdOrDef;
330 return !!def?.dyeable;
331}
332
322export { formatQuantity };
333export { formatQuantity };
323
334
324export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
335export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
@@ -391,11 +402,11 @@ export function itemDescription (stack, { localCharacterId } = {})
391 {
402 {
392 const name = stack.instance.displayName ?? "Potion";
403 const name = stack.instance.displayName ?? "Potion";
393 return stack.instance.unstable
404 return stack.instance.unstable
394 ? `${name}. An unstable brew — effects are unpredictable.`
405 ? `${name}. The brew smells wrong — best sipped with caution.`
395 : `${name}. Drink to apply its effect.`;
406 : `${name}. A carefully bottled draught.`;
396 }
407 }
397 if (stack.itemId === ItemId.recipePaper && stack.instance?.kind === "recipe-paper")
408 if (stack.itemId === ItemId.recipePaper && stack.instance?.kind === "recipe-paper")
398 { return "An alchemy recipe."; }
409 { return "Notes on how to brew a particular draught."; }
399 return def.description ?? "";
410 return def.description ?? "";
400}
411}
401
412
shared/definitions/metalItems.js +3 −3
@@ -125,7 +125,7 @@ function pickaxeDef (itemId, tier, key)
125 125 itemId,
126 126 key,
127 127 displayName: `${name} pickaxe`,
128 description: `Mining tool (${name}).`,
128 description: `A ${name.toLowerCase()} pickaxe for breaking stone and ore.`,
129 129 seedValue: 8,
130 130 stackable: false,
131 131 maxStackSize: 1,
@@ -169,7 +169,7 @@ function axeDef (itemId, tier, key)
169 169 itemId,
170 170 key,
171 171 displayName: `${name} axe`,
172 description: `Woodcutting tool (${name}).`,
172 description: `A ${name.toLowerCase()} axe for felling trees.`,
173 173 seedValue: 8,
174 174 stackable: false,
175 175 maxStackSize: 1,
@@ -192,7 +192,7 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
192 192 itemId: MetalItemId.coal,
193 193 key: "coal",
194 194 displayName: "Coal",
195 description: "Fuel for steel smelting.",
195 description: "Dark coal, hot enough to harden steel.",
196 196 seedValue: 2,
197 197 stackable: true,
198 198 maxStackSize: DEFAULT_STACK,
@@ -125,7 +125,7 @@ function pickaxeDef (itemId, tier, key)
125 itemId,
125 itemId,
126 key,
126 key,
127 displayName: `${name} pickaxe`,
127 displayName: `${name} pickaxe`,
128 description: `Mining tool (${name}).`,
128 description: `A ${name.toLowerCase()} pickaxe for breaking stone and ore.`,
129 seedValue: 8,
129 seedValue: 8,
130 stackable: false,
130 stackable: false,
131 maxStackSize: 1,
131 maxStackSize: 1,
@@ -169,7 +169,7 @@ function axeDef (itemId, tier, key)
169 itemId,
169 itemId,
170 key,
170 key,
171 displayName: `${name} axe`,
171 displayName: `${name} axe`,
172 description: `Woodcutting tool (${name}).`,
172 description: `A ${name.toLowerCase()} axe for felling trees.`,
173 seedValue: 8,
173 seedValue: 8,
174 stackable: false,
174 stackable: false,
175 maxStackSize: 1,
175 maxStackSize: 1,
@@ -192,7 +192,7 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
192 itemId: MetalItemId.coal,
192 itemId: MetalItemId.coal,
193 key: "coal",
193 key: "coal",
194 displayName: "Coal",
194 displayName: "Coal",
195 description: "Fuel for steel smelting.",
195 description: "Dark coal, hot enough to harden steel.",
196 seedValue: 2,
196 seedValue: 2,
197 stackable: true,
197 stackable: true,
198 maxStackSize: DEFAULT_STACK,
198 maxStackSize: DEFAULT_STACK,
shared/definitions/mobs.js +56 −9
@@ -212,23 +212,70 @@ function emptySpawnerEquipment ()
212 212 };
213 213 }
214 214
215 /**
216 * Spawner equipment entry: legacy itemId number, or `{ itemId, dyeColor? }` for dyed clothing.
217 * Normalized form keeps a plain number when undyed (world-save compatible).
218 */
219 function normalizeEquipmentEntry (value)
220 {
221 if (value == null || value === "" || value === "0")
222 { return null; }
223 let itemId = 0;
224 let dyeColor = null;
225 if (typeof value === "object")
226 {
227 itemId = Number(value.itemId) | 0;
228 dyeColor = normalizeDyeColor(value.dyeColor);
229 }
230 else
231 { itemId = Number(value) | 0; }
232 if (!Number.isFinite(itemId) || itemId <= 0)
233 { return null; }
234 if (!dyeColor)
235 { return itemId; }
236 return Object.freeze({ itemId, dyeColor });
237 }
238
239 function normalizeDyeColor (raw)
240 {
241 if (!raw || typeof raw !== "object")
242 { return null; }
243 const r = Number(raw.r);
244 const g = Number(raw.g);
245 const b = Number(raw.b);
246 if (![r, g, b].every(Number.isFinite))
247 { return null; }
248 const asByte = r > 1 || g > 1 || b > 1;
249 return Object.freeze({
250 r: Math.min(1, Math.max(0, asByte ? r / 255 : r)),
251 g: Math.min(1, Math.max(0, asByte ? g / 255 : g)),
252 b: Math.min(1, Math.max(0, asByte ? b / 255 : b))
253 });
254 }
255
215 256 function normalizeEquipment (raw)
216 257 {
217 258 const next = emptySpawnerEquipment();
218 259 if (!raw || typeof raw !== "object")
219 260 { return next; }
220 261 for (const slot of Object.keys(next))
262 { next[slot] = normalizeEquipmentEntry(raw[slot]); }
263 return next;
264 }
265
266 /** Resolve authored spawner equipment into itemId (+ optional dye). */
267 export function spawnerEquipmentSlot (entry)
268 {
269 if (entry == null)
270 { return { itemId: 0, dyeColor: null }; }
271 if (typeof entry === "object")
221 272 {
222 const value = raw[slot];
223 if (value == null || value === "" || value === "0")
224 {
225 next[slot] = null;
226 continue;
227 }
228 const itemId = Number(value);
229 next[slot] = Number.isFinite(itemId) && itemId > 0 ? (itemId | 0) : null;
273 return {
274 itemId: Number(entry.itemId) | 0,
275 dyeColor: entry.dyeColor ?? null
276 };
230 277 }
231 return next;
278 return { itemId: Number(entry) | 0, dyeColor: null };
232 279 }
233 280
234 281 function normalizeSells (raw)
@@ -212,23 +212,70 @@ function emptySpawnerEquipment ()
212 };
212 };
213}
213}
214
214
215/**
216 * Spawner equipment entry: legacy itemId number, or `{ itemId, dyeColor? }` for dyed clothing.
217 * Normalized form keeps a plain number when undyed (world-save compatible).
218 */
219function normalizeEquipmentEntry (value)
220{
221 if (value == null || value === "" || value === "0")
222 { return null; }
223 let itemId = 0;
224 let dyeColor = null;
225 if (typeof value === "object")
226 {
227 itemId = Number(value.itemId) | 0;
228 dyeColor = normalizeDyeColor(value.dyeColor);
229 }
230 else
231 { itemId = Number(value) | 0; }
232 if (!Number.isFinite(itemId) || itemId <= 0)
233 { return null; }
234 if (!dyeColor)
235 { return itemId; }
236 return Object.freeze({ itemId, dyeColor });
237}
238
239function normalizeDyeColor (raw)
240{
241 if (!raw || typeof raw !== "object")
242 { return null; }
243 const r = Number(raw.r);
244 const g = Number(raw.g);
245 const b = Number(raw.b);
246 if (![r, g, b].every(Number.isFinite))
247 { return null; }
248 const asByte = r > 1 || g > 1 || b > 1;
249 return Object.freeze({
250 r: Math.min(1, Math.max(0, asByte ? r / 255 : r)),
251 g: Math.min(1, Math.max(0, asByte ? g / 255 : g)),
252 b: Math.min(1, Math.max(0, asByte ? b / 255 : b))
253 });
254}
255
215function normalizeEquipment (raw)
256function normalizeEquipment (raw)
216{
257{
217 const next = emptySpawnerEquipment();
258 const next = emptySpawnerEquipment();
218 if (!raw || typeof raw !== "object")
259 if (!raw || typeof raw !== "object")
219 { return next; }
260 { return next; }
220 for (const slot of Object.keys(next))
261 for (const slot of Object.keys(next))
262 { next[slot] = normalizeEquipmentEntry(raw[slot]); }
263 return next;
264}
265
266/** Resolve authored spawner equipment into itemId (+ optional dye). */
267export function spawnerEquipmentSlot (entry)
268{
269 if (entry == null)
270 { return { itemId: 0, dyeColor: null }; }
271 if (typeof entry === "object")
221 {
272 {
222 const value = raw[slot];
273 return {
223 if (value == null || value === "" || value === "0")
274 itemId: Number(entry.itemId) | 0,
224 {
275 dyeColor: entry.dyeColor ?? null
225 next[slot] = null;
276 };
226 continue;
227 }
228 const itemId = Number(value);
229 next[slot] = Number.isFinite(itemId) && itemId > 0 ? (itemId | 0) : null;
230 }
277 }
231 return next;
278 return { itemId: Number(entry) | 0, dyeColor: null };
232}
279}
233
280
234function normalizeSells (raw)
281function normalizeSells (raw)
shared/definitions/woodItems.js +1 −1
@@ -56,7 +56,7 @@ function logDef (itemId, tier)
56 56 itemId,
57 57 key: `${tier}-log`,
58 58 displayName: `${name} log`,
59 description: `Chopped ${name.toLowerCase()}.`,
59 description: `A sturdy ${name.toLowerCase()} log.`,
60 60 seedValue: tier === WoodTier.pine ? 5 : 2,
61 61 stackable: true,
62 62 maxStackSize: DEFAULT_STACK,
@@ -56,7 +56,7 @@ function logDef (itemId, tier)
56 itemId,
56 itemId,
57 key: `${tier}-log`,
57 key: `${tier}-log`,
58 displayName: `${name} log`,
58 displayName: `${name} log`,
59 description: `Chopped ${name.toLowerCase()}.`,
59 description: `A sturdy ${name.toLowerCase()} log.`,
60 seedValue: tier === WoodTier.pine ? 5 : 2,
60 seedValue: tier === WoodTier.pine ? 5 : 2,
61 stackable: true,
61 stackable: true,
62 maxStackSize: DEFAULT_STACK,
62 maxStackSize: DEFAULT_STACK,
shared/items/inventory.js +113 −3
@@ -53,18 +53,21 @@ export function potionStackIdentity (instance)
53 53 { return null; }
54 54 const effectKey = instance.effectKey
55 55 ?? (instance.effect ? JSON.stringify(instance.effect) : "");
56 return `${instance.potionKey ?? ""}|${effectKey}`;
56 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
57 return `${instance.potionKey ?? ""}|${effectKey}|${fill}`;
57 58 }
58 59
59 /** Dye stacks merge when RGB matches exactly (fill ignored). */
60 /** Dye stacks merge when RGB and remaining uses match exactly. */
60 61 export function dyeStackIdentity (instance)
61 62 {
62 63 if (!instance || instance.kind !== "dye" || !instance.color)
63 64 { return null; }
65 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
64 66 return [
65 67 Math.round((instance.color.r ?? 0) * 1000),
66 68 Math.round((instance.color.g ?? 0) * 1000),
67 Math.round((instance.color.b ?? 0) * 1000)
69 Math.round((instance.color.b ?? 0) * 1000),
70 fill
68 71 ].join(",");
69 72 }
70 73
@@ -184,6 +187,113 @@ export function takeFromSlot (slots, slotIndex, quantity = null)
184 187 return { ok: true, slots: next, taken };
185 188 }
186 189
190 /**
191 * Spend one fill charge from a potion/dye slot without losing the leftover bottle.
192 * Single bottles always mutate in place (or become an empty bottle). Multi-stacks
193 * peel one bottle and re-insert the reduced fill; tries both split orderings so a
194 * matching stack can absorb either side. Never mutates the input slots array.
195 *
196 * @returns {{ ok: true, slots, exhausted: boolean, instance: object } | { ok: false, reason: string }}
197 */
198 export function consumeFillCharge (slots, slotIndex, {
199 kind = null,
200 itemId = null,
201 definition = null,
202 returnEmptyItemId = null
203 } = {})
204 {
205 const index = slotIndex | 0;
206 const source = slots?.[index];
207 if (!source || stackQuantity(source.quantity) <= 0)
208 { return { ok: false, reason: "empty" }; }
209 if (itemId != null && source.itemId !== itemId)
210 { return { ok: false, reason: "wrong-item" }; }
211 if (kind != null && source.instance?.kind !== kind)
212 { return { ok: false, reason: "wrong-item" }; }
213 const def = definition ?? itemDefinition(source.itemId);
214 if (!def)
215 { return { ok: false, reason: "unknown" }; }
216
217 const fill = Math.max(1, Math.min(5, source.instance?.fillLevel | 0 || 4));
218 const qty = stackQuantity(source.quantity);
219 const usedInstance = cloneStack(source.instance) ?? { kind, fillLevel: fill };
220
221 if (qty === 1)
222 {
223 const next = slots.map(cloneStack);
224 if (fill <= 1)
225 {
226 next[index] = null;
227 if (returnEmptyItemId)
228 {
229 const emptyDef = itemDefinition(returnEmptyItemId);
230 const inserted = insertStack(next, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
231 if (!inserted.ok || inserted.remainder > 0)
232 { return { ok: false, reason: "space" }; }
233 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
234 }
235 return { ok: true, slots: next, exhausted: true, instance: usedInstance };
236 }
237 next[index].instance = { ...next[index].instance, fillLevel: fill - 1 };
238 return { ok: true, slots: next, exhausted: false, instance: usedInstance };
239 }
240
241 // Multi-stack: try leaving the remainder in place, then the reduced bottle in place.
242 const reducedFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, false);
243 if (reducedFirst.ok)
244 { return { ...reducedFirst, instance: usedInstance }; }
245 const remainderFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, true);
246 if (remainderFirst.ok)
247 { return { ...remainderFirst, instance: usedInstance }; }
248 return { ok: false, reason: "space" };
249 }
250
251 function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainderStaysInSlot)
252 {
253 const peeled = takeFromSlot(slots, index, 1);
254 if (!peeled.ok || !peeled.taken)
255 { return { ok: false }; }
256
257 if (fill <= 1)
258 {
259 if (!returnEmptyItemId)
260 { return { ok: true, slots: peeled.slots, exhausted: true }; }
261 const emptyDef = itemDefinition(returnEmptyItemId);
262 const inserted = insertStack(peeled.slots, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
263 if (!inserted.ok || inserted.remainder > 0)
264 { return { ok: false }; }
265 return { ok: true, slots: inserted.slots, exhausted: true };
266 }
267
268 const reduced = {
269 itemId: peeled.taken.itemId,
270 quantity: 1,
271 instance: { ...cloneStack(peeled.taken.instance), fillLevel: fill - 1 },
272 origins: peeled.taken.origins
273 };
274 const remainder = peeled.slots[index]
275 ? cloneStack(peeled.slots[index])
276 : null;
277
278 if (!remainderStaysInSlot)
279 {
280 const inserted = insertStack(peeled.slots, reduced, def);
281 if (!inserted.ok || inserted.remainder > 0)
282 { return { ok: false }; }
283 return { ok: true, slots: inserted.slots, exhausted: false };
284 }
285
286 // Put reduced bottle back in the original slot; re-home the untouched remainder.
287 const next = peeled.slots.map(cloneStack);
288 next[index] = stackPayload(reduced, 1, normalizeOrigins(reduced));
289 if (!remainder)
290 { return { ok: true, slots: next, exhausted: false }; }
291 const inserted = insertStack(next, remainder, def);
292 if (!inserted.ok || inserted.remainder > 0)
293 { return { ok: false }; }
294 return { ok: true, slots: inserted.slots, exhausted: false };
295 }
296
187 297 /** Like insertStack, but grows the slot array when capacity runs out (vault). */
188 298 export function insertStackGrowable (slots, stack, definition)
189 299 {
@@ -53,18 +53,21 @@ export function potionStackIdentity (instance)
53 { return null; }
53 { return null; }
54 const effectKey = instance.effectKey
54 const effectKey = instance.effectKey
55 ?? (instance.effect ? JSON.stringify(instance.effect) : "");
55 ?? (instance.effect ? JSON.stringify(instance.effect) : "");
56 return `${instance.potionKey ?? ""}|${effectKey}`;
56 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
57 return `${instance.potionKey ?? ""}|${effectKey}|${fill}`;
57}
58}
58
59
59/** Dye stacks merge when RGB matches exactly (fill ignored). */
60/** Dye stacks merge when RGB and remaining uses match exactly. */
60export function dyeStackIdentity (instance)
61export function dyeStackIdentity (instance)
61{
62{
62 if (!instance || instance.kind !== "dye" || !instance.color)
63 if (!instance || instance.kind !== "dye" || !instance.color)
63 { return null; }
64 { return null; }
65 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
64 return [
66 return [
65 Math.round((instance.color.r ?? 0) * 1000),
67 Math.round((instance.color.r ?? 0) * 1000),
66 Math.round((instance.color.g ?? 0) * 1000),
68 Math.round((instance.color.g ?? 0) * 1000),
67 Math.round((instance.color.b ?? 0) * 1000)
69 Math.round((instance.color.b ?? 0) * 1000),
70 fill
68 ].join(",");
71 ].join(",");
69}
72}
70
73
@@ -184,6 +187,113 @@ export function takeFromSlot (slots, slotIndex, quantity = null)
184 return { ok: true, slots: next, taken };
187 return { ok: true, slots: next, taken };
185}
188}
186
189
190/**
191 * Spend one fill charge from a potion/dye slot without losing the leftover bottle.
192 * Single bottles always mutate in place (or become an empty bottle). Multi-stacks
193 * peel one bottle and re-insert the reduced fill; tries both split orderings so a
194 * matching stack can absorb either side. Never mutates the input slots array.
195 *
196 * @returns {{ ok: true, slots, exhausted: boolean, instance: object } | { ok: false, reason: string }}
197 */
198export function consumeFillCharge (slots, slotIndex, {
199 kind = null,
200 itemId = null,
201 definition = null,
202 returnEmptyItemId = null
203} = {})
204{
205 const index = slotIndex | 0;
206 const source = slots?.[index];
207 if (!source || stackQuantity(source.quantity) <= 0)
208 { return { ok: false, reason: "empty" }; }
209 if (itemId != null && source.itemId !== itemId)
210 { return { ok: false, reason: "wrong-item" }; }
211 if (kind != null && source.instance?.kind !== kind)
212 { return { ok: false, reason: "wrong-item" }; }
213 const def = definition ?? itemDefinition(source.itemId);
214 if (!def)
215 { return { ok: false, reason: "unknown" }; }
216
217 const fill = Math.max(1, Math.min(5, source.instance?.fillLevel | 0 || 4));
218 const qty = stackQuantity(source.quantity);
219 const usedInstance = cloneStack(source.instance) ?? { kind, fillLevel: fill };
220
221 if (qty === 1)
222 {
223 const next = slots.map(cloneStack);
224 if (fill <= 1)
225 {
226 next[index] = null;
227 if (returnEmptyItemId)
228 {
229 const emptyDef = itemDefinition(returnEmptyItemId);
230 const inserted = insertStack(next, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
231 if (!inserted.ok || inserted.remainder > 0)
232 { return { ok: false, reason: "space" }; }
233 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
234 }
235 return { ok: true, slots: next, exhausted: true, instance: usedInstance };
236 }
237 next[index].instance = { ...next[index].instance, fillLevel: fill - 1 };
238 return { ok: true, slots: next, exhausted: false, instance: usedInstance };
239 }
240
241 // Multi-stack: try leaving the remainder in place, then the reduced bottle in place.
242 const reducedFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, false);
243 if (reducedFirst.ok)
244 { return { ...reducedFirst, instance: usedInstance }; }
245 const remainderFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, true);
246 if (remainderFirst.ok)
247 { return { ...remainderFirst, instance: usedInstance }; }
248 return { ok: false, reason: "space" };
249}
250
251function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainderStaysInSlot)
252{
253 const peeled = takeFromSlot(slots, index, 1);
254 if (!peeled.ok || !peeled.taken)
255 { return { ok: false }; }
256
257 if (fill <= 1)
258 {
259 if (!returnEmptyItemId)
260 { return { ok: true, slots: peeled.slots, exhausted: true }; }
261 const emptyDef = itemDefinition(returnEmptyItemId);
262 const inserted = insertStack(peeled.slots, { itemId: returnEmptyItemId, quantity: 1 }, emptyDef);
263 if (!inserted.ok || inserted.remainder > 0)
264 { return { ok: false }; }
265 return { ok: true, slots: inserted.slots, exhausted: true };
266 }
267
268 const reduced = {
269 itemId: peeled.taken.itemId,
270 quantity: 1,
271 instance: { ...cloneStack(peeled.taken.instance), fillLevel: fill - 1 },
272 origins: peeled.taken.origins
273 };
274 const remainder = peeled.slots[index]
275 ? cloneStack(peeled.slots[index])
276 : null;
277
278 if (!remainderStaysInSlot)
279 {
280 const inserted = insertStack(peeled.slots, reduced, def);
281 if (!inserted.ok || inserted.remainder > 0)
282 { return { ok: false }; }
283 return { ok: true, slots: inserted.slots, exhausted: false };
284 }
285
286 // Put reduced bottle back in the original slot; re-home the untouched remainder.
287 const next = peeled.slots.map(cloneStack);
288 next[index] = stackPayload(reduced, 1, normalizeOrigins(reduced));
289 if (!remainder)
290 { return { ok: true, slots: next, exhausted: false }; }
291 const inserted = insertStack(next, remainder, def);
292 if (!inserted.ok || inserted.remainder > 0)
293 { return { ok: false }; }
294 return { ok: true, slots: inserted.slots, exhausted: false };
295}
296
187/** Like insertStack, but grows the slot array when capacity runs out (vault). */
297/** Like insertStack, but grows the slot array when capacity runs out (vault). */
188export function insertStackGrowable (slots, stack, definition)
298export function insertStackGrowable (slots, stack, definition)
189{
299{
shared/protocol/constants.js +1 −0
@@ -139,6 +139,7 @@ export const MessageType = Object.freeze({
139 139 skills: "SKILLS",
140 140 stamina: "STAMINA",
141 141 eatItem: "EAT_ITEM",
142 drinkItem: "DRINK_ITEM",
142 143 startCraft: "START_CRAFT",
143 144 cancelCraft: "CANCEL_CRAFT",
144 145 craftResult: "CRAFT_RESULT",
@@ -139,6 +139,7 @@ export const MessageType = Object.freeze({
139 skills: "SKILLS",
139 skills: "SKILLS",
140 stamina: "STAMINA",
140 stamina: "STAMINA",
141 eatItem: "EAT_ITEM",
141 eatItem: "EAT_ITEM",
142 drinkItem: "DRINK_ITEM",
142 startCraft: "START_CRAFT",
143 startCraft: "START_CRAFT",
143 cancelCraft: "CANCEL_CRAFT",
144 cancelCraft: "CANCEL_CRAFT",
144 craftResult: "CRAFT_RESULT",
145 craftResult: "CRAFT_RESULT",