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.
@@ -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
---2
description: Item (and station) descriptions must stay in-universe; never expose mechanics or implementation status.3
alwaysApply: true4
---5
6
# In-universe item descriptions7
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
## Forbidden11
12
- Stack sizes, slots, skill levels, equip rules, UI labels13
- 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
## Allowed18
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 know21
22
```text23
# ❌ BAD24
"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
# ✅ GOOD30
"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`.@@ -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>@@ -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>@@ -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
isCentralExchangeSpawner9
isCentralExchangeSpawner,10
spawnerEquipmentSlot10
} from "/shared/definitions/mobs.js";11
} from "/shared/definitions/mobs.js";11
import { centralExchangeStaffCount } from "/shared/market/exchange.js";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
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";14
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";14
import { listNpcShopSellableItems } from "/shared/shop/pricing.js";15
import { listNpcShopSellableItems } from "/shared/shop/pricing.js";16
import { 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. */17
export function listEquippableItemsForSlot (slot)19
export function listEquippableItemsForSlot (slot)@@ -31,6 +33,39 @@ export function listEquippableItemsForSlot (slot)31
return out;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) : null47
};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
export function initTileConfigModal ({ onSave, onRemove })69
export 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: null193
};143
renderEquipmentRows();194
renderEquipmentRows();144
}195
}145
else196
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)) / 255222
};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
else362
{ 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 = dyeable372
? "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),@@ -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
else287
else283
{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;@@ -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 })@@ -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
formatQuantity5
formatQuantity6
} from "/shared/definitions/items.js";6
} from "/shared/definitions/items.js";7
import { insertStack } from "/shared/items/inventory.js";7
import { insertStack, stackQuantity } from "/shared/items/inventory.js";8
import {8
import {9
canPlayerSellToNpc,9
canPlayerSellToNpc,10
resolveShopSellQuote10
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
else239
{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: 1319
quantity: qty236
});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.isCheque389
sellPrice.textContent = quote.isCheque259
? `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
else574
{ renderBuyPane(); }397
}575
}398
576
399
function handleShopOpen (message)577
function handleShopOpen (message)@@ -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;@@ -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;@@ -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";13
import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";13
import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";14
import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";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
import {16
import {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. */107
function consumeDyeUse (slots, slotIndex)107
function 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.dye112
{ 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 - 1122
};123
return { ok: true, slots: next };124
}113
}125
114
126
export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})115
export 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 || !inventory307
if (!recipe || !stationDef || !inventory313
|| (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
}@@ -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 | 0189
slotIndex: message.slotIndex | 0190
});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 | 0198
});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, {@@ -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
stackQuantity20
stackQuantity,21
consumeFillCharge21
} from "../../../shared/items/inventory.js";22
} from "../../../shared/items/inventory.js";22
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";23
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";23
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";24
import { 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
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.glassBottle369
});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 exist402
}403
353
function openBank (world, sessionId, command)404
function openBank (world, sessionId, command)354
{405
{355
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);406
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);@@ -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
MobId8
MobId,9
spawnerEquipmentSlot9
} from "../../../shared/definitions/mobs.js";10
} from "../../../shared/definitions/mobs.js";10
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";11
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";11
import { emptyEquipment } from "../../../shared/items/inventory.js";12
import { 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 }; }@@ -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 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import {4
emptySlots,5
insertStack,6
stacksMatch,7
consumeFillCharge,8
stackQuantity9
} 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.slots90
.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.glassBottle105
});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: red139
};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
});@@ -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 buysItems96
assert.equal(config.maxAlive, 1);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.stick107
}108
}, "shop-dye");109
assert.deepEqual(config.equipment.chest, {110
itemId: ItemId.clothShirt,111
dyeColor112
});113
assert.equal(config.equipment.weapon, ItemId.stick);114
});115
99
test("buy copper ore from a spawned shopkeeper", () =>116
test("buy copper ore from a spawned shopkeeper", () =>100
{117
{101
const harness = makeSimulation({ workerCount: 1 });118
const harness = makeSimulation({ workerCount: 1 });