diff --git a/app.py b/app.py index 6f906e4..3f103ce 100644 --- a/app.py +++ b/app.py @@ -251,6 +251,16 @@ def quanah_update_item(identifier): return jsonify(store.payload()) +# FLAG is one of quanah.store.MARKS; anything else is refused there. +@app.put("/api/quanah/items//") +def quanah_mark_item(identifier, flag): + from quanah import store + + body = request.get_json(silent=True) or {} + store.mark_item(identifier, flag, body.get(flag)) + return jsonify(store.payload()) + + @app.delete("/api/quanah/items/") def quanah_delete_item(identifier): from quanah import store diff --git a/src/quanah/data/lines.json b/src/quanah/data/lines.json index 0d3118f..54a0c3a 100644 --- a/src/quanah/data/lines.json +++ b/src/quanah/data/lines.json @@ -30,7 +30,7 @@ "builds": [ {"key": "skill", "name": "Skill", "targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "warrior": 1, "magician": 1, "bowman": 1, "thief": 1, "pirate": 1, "crit": 1}}, - {"key": "gandi", "name": "GanDi", + {"key": "hybrid", "name": "Hybrid", "targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "crit": 3}, "jobs": {"count": 3, "default": ["magician", "thief", "bowman"]}}, {"key": "eu", "name": "EU", diff --git a/src/quanah/solver.py b/src/quanah/solver.py index e5a86a9..9222b40 100644 --- a/src/quanah/solver.py +++ b/src/quanah/solver.py @@ -1,8 +1,15 @@ """Pick one event piece per slot to fill a build's skill-line targets. -A port of the community 3L, GanDi and EU set solvers: a DP over capped line +A port of the community 3L, GanDi (Hybrid) and EU set solvers: a DP over capped line counts, one layer per slot. Lines above a target are wasted; a slot with no eligible piece is left empty. + +A piece marked "transfer" needs an orb: its lines count once moved onto the piece +worn in that slot (marked "worn"), or onto any on-class piece of the slot when none +is worn. Among equally good sets, the one needing the fewest transfers wins. + +A piece marked "preferred" is locked into its slot: the rest of the set is solved +around it, even when another piece there would score more. """ from functools import lru_cache @@ -96,43 +103,85 @@ def needs(self, state): return [base + list(pick) for pick in combinations(open_jobs, missing)] -def _layers(plan, by_slot, skip=None): - current = {tuple(0 for _ in plan.keys): {"ways": 1}} +def _layers(plan, by_slot, locked, skip=None, edges=True): + """One (slot, states) layer per slot. Each state keeps its combo count, "costs" (a bitmask: + bit N is set when some path reaches it with N transfers) and, with EDGES, the + (previous state, piece) pairs reaching it.""" + current = {tuple(0 for _ in plan.keys): {"ways": 1, "costs": 1}} layers = [] for slot in slot_keys(): if slot == skip: continue - options = by_slot.get(slot) or [None] + options = by_slot.get(slot) or [] + # Orbing costs a transfer, so a slot with a piece needing one may also stay as it is, + # unless a worn piece fills it anyway. + if not options or (slot not in locked and any(item.get("transfer") for item in options) + and not any(item.get("worn") for item in options)): + options = options + [None] + costs = [bool(item and item.get("transfer")) for item in options] + optional = options[-1] is None following = {} for state, info in current.items(): - for item in options: + idle = False # Whether a kept piece adds nothing here, making the empty option no extra combo. + for item, cost in zip(options, costs, strict=True): nxt = plan.add(state, item["lines"]) if item else state + # Never orb a piece that adds nothing, and leaving the slot empty is no extra + # combo when one of its pieces adds nothing anyway. + if nxt == state: + if (cost and slot not in locked) or (item is None and idle): + continue + idle = optional + reach = info["costs"] << cost entry = following.get(nxt) - if entry: - entry["ways"] += info["ways"] + if entry is None: + entry = following[nxt] = {"ways": info["ways"], "costs": reach, "edges": []} else: - following[nxt] = {"prev": state, "item": item, "slot": slot, "ways": info["ways"]} - layers.append(following) + entry["ways"] += info["ways"] + entry["costs"] |= reach + if edges: + entry["edges"].append((state, item)) + layers.append((slot, following)) current = following return layers -def solve(items, targets, jobs=None): - """Best set for ITEMS (dicts with id, slot, lines) under TARGETS and an optional job rule.""" - plan = _Plan(targets, jobs) - by_slot = {} - for item in items: - by_slot.setdefault(item["slot"], []).append(item) - layers = _layers(plan, by_slot) - final = layers[-1] - best_state = max(final, key=plan.score) # max() keeps the first of equal scores, like the sites. - best = plan.score(best_state) - picks, state = {}, best_state - for layer in reversed(layers): - entry = layer[state] - picks[entry["slot"]] = entry["item"] - state = entry["prev"] - # Which lines of the chosen pieces count toward the goal, in slot order. +def _combos(layers, finals, limit): + """Up to LIMIT (final state, {slot: piece}) paths into FINALS, fewest transfers first. + + Within a transfer count the first path found comes first, so the first combo is the + one the community sites pick when no piece needs a transfer. + """ + found = [] + + def walk(depth, state, budget, picks): + if len(found) >= limit: + return + if depth < 0: + if not budget: + found.append(dict(picks)) + return + slot, layer = layers[depth] + for prev, item in layer[state]["edges"]: + left = budget - bool(item and item.get("transfer")) + # Only follow an edge whose previous state is reachable with exactly LEFT + # transfers, so every step leads to a combo and no path is walked in vain. + before = layers[depth - 1][1][prev]["costs"] if depth else 1 + if left >= 0 and before >> left & 1: + picks[slot] = item + walk(depth - 1, prev, left, picks) + + final = layers[-1][1] + for orbs in range(len(layers) + 1): + for state in finals: + if final[state]["costs"] >> orbs & 1: + start = len(found) + walk(len(layers) - 1, state, orbs, {}) + found[start:] = [(state, picks) for picks in found[start:]] + return found + + +def _used(plan, picks): + """Which lines of the chosen pieces count toward the goal, in slot order.""" run, jobs_used, used = dict.fromkeys(plan.keys, 0), 0, {} for slot in slot_keys(): item = picks.get(slot) @@ -149,24 +198,69 @@ def solve(items, targets, jobs=None): run[key] += ok flags.append(ok) used[slot] = flags + return used + + +def _orbs(picks): + return sum(bool(item and item.get("transfer")) for item in picks.values()) + + +def _ids(picks): + return {slot: (picks[slot]["id"] if picks.get(slot) else None) for slot in slot_keys()} + + +COMBO_LIMIT = 100 + + +def solve(items, targets, jobs=None): + """Best set for ITEMS (dicts with id, slot, lines, optional transfer and preferred) + under TARGETS and an optional job rule. + + A complete set also lists its winning combos (at most COMBO_LIMIT), fewest transfers first. + """ + plan = _Plan(targets, jobs) + by_slot = {} + for item in items: + by_slot.setdefault(item["slot"], []).append(item) + locked = set() + for slot, pieces in by_slot.items(): + preferred = [item for item in pieces if item.get("preferred")] + if preferred: + by_slot[slot] = preferred[:1] + locked.add(slot) + layers = _layers(plan, by_slot, locked) + final = layers[-1][1] + best = max(plan.score(state) for state in final) + finals = [state for state in final if plan.score(state) == best] + done = best >= plan.goal + combos = _combos(layers, finals, COMBO_LIMIT if done else 1) + best_state, picks = combos[0] return { "score": best, "goal": plan.goal, "counts": dict(zip(plan.keys, best_state, strict=True)), - "picks": {slot: (item["id"] if item else None) for slot, item in picks.items()}, - "used": used, - "ways": final[best_state]["ways"], - "missing": plan.needs(best_state)[0] if best < plan.goal else [], - "hunt": _hunt(plan, by_slot) if best < plan.goal else [], + "picks": _ids(picks), + "used": _used(plan, picks), + "ways": sum(final[state]["ways"] for state in finals), + "orbs": _orbs(picks), + "combos": [{"picks": _ids(p), "used": _used(plan, p), "orbs": _orbs(p)} for _, p in combos] + if done else [], + "missing": plan.needs(best_state)[0] if not done else [], + "hunt": _hunt(plan, by_slot, locked) if not done else [], } -def _hunt(plan, by_slot): - """Pieces that would finish the set in one drop: (slot, lines) with no repeated line.""" +def _hunt(plan, by_slot, locked): + """Pieces that would finish the set in one drop: (slot, lines) with no repeated line. + + Orb cost is not considered; the page notes that a drop for a slot with a worn piece needs one. + """ limit = catalog()["max_lines"] found, seen = [], set() for slot in slot_keys(): - for state in _layers(plan, by_slot, skip=slot)[-1]: + if slot in locked: + continue # A drop there would not be used. + for state in _layers(plan, by_slot, locked, skip=slot, edges=False)[-1][1]: if plan.goal - plan.score(state) > limit: continue for need in plan.needs(state): diff --git a/src/quanah/store.py b/src/quanah/store.py index a86a109..fb2c3a9 100644 --- a/src/quanah/store.py +++ b/src/quanah/store.py @@ -1,7 +1,8 @@ """The saved Quanah class, build and event pieces, plus the solved best set. One global list, independent of Hascone's characters. Pieces of another class -are kept, flagged as unwearable and left out of the solver. +are kept and flagged as unwearable; the solver still uses them, as pieces whose +lines must be orbed onto an on-class piece of the same slot. """ import json @@ -20,10 +21,10 @@ def _default(): - gandi = next(b for b in solver.catalog()["builds"] if b["key"] == "gandi") + hybrid = next(b for b in solver.catalog()["builds"] if b["key"] == "hybrid") return { "class": None, - "build": {"preset": "skill", "job_mode": "custom", "jobs": list(gandi["jobs"]["default"]), "targets": {}}, + "build": {"preset": "skill", "job_mode": "custom", "jobs": list(hybrid["jobs"]["default"]), "targets": {}}, "items": [], } @@ -35,9 +36,9 @@ def read(): saved = json.loads(PATH.read_text(encoding="utf-8")) data["class"] = saved.get("class") data["build"].update(saved.get("build") or {}) - # The Skill build was first saved as "original". - if data["build"].get("preset") == "original": - data["build"]["preset"] = "skill" + # Builds first saved under older names. + renamed = {"original": "skill", "gandi": "hybrid"} + data["build"]["preset"] = renamed.get(data["build"].get("preset"), data["build"].get("preset")) # So the page shows, and later changes validate, the same targets the solver uses. data["build"]["targets"] = solver.trim_targets(data["build"].get("targets")) data["items"] = saved.get("items") or [] @@ -142,6 +143,13 @@ def add_item(slot, lines, *, raw=None, name=None, item_class=None, source="manua return item +def _piece(data, identifier): + item = next((i for i in data["items"] if i["id"] == identifier), None) + if item is None: + raise ValueError("That piece is already gone") + return item + + def update_item(identifier, slot, lines): """Correct a piece's slot and lines by hand. A scanned piece keeps what was read, marked edited.""" if slot not in solver.slot_keys(): @@ -149,22 +157,50 @@ def update_item(identifier, slot, lines): lines = validate_lines(lines) with lock: data = read() - item = next((i for i in data["items"] if i["id"] == identifier), None) - if item is None: - raise ValueError("That piece is already gone") + item = _piece(data, identifier) if (item["slot"], item["lines"]) != (slot, lines): + # A piece moved to another slot is no longer that slot's preferred or worn piece. + if item["slot"] != slot: + for flag in ONE_PER_SLOT: + item.pop(flag, None) item.update(slot=slot, lines=lines, edited=datetime.now(UTC).isoformat()) _write(data) return item +# "preferred" locks a piece into the best set and "worn" is what the player wears now, which +# the other pieces' lines would be orbed onto: one piece per slot each. "disabled" leaves a +# piece out of every combo. +ONE_PER_SLOT = ("preferred", "worn") +MARKS = (*ONE_PER_SLOT, "disabled") + + +def mark_item(identifier, flag, on): + """Give a piece FLAG (taking a one-per-slot mark from the slot's other pieces), or clear it.""" + if flag not in MARKS: + raise ValueError("Unknown mark") + if not isinstance(on, bool): + raise ValueError(f"{flag.capitalize()} must be true or false") + with lock: + data = read() + item = _piece(data, identifier) + item.pop(flag, None) + if flag in ONE_PER_SLOT: + for other in data["items"]: + if other["slot"] == item["slot"]: + other.pop(flag, None) + if on: + item[flag] = True + # A disabled piece can't be locked into the set, and starring a piece uses it again. + item.pop({"disabled": "preferred", "preferred": "disabled"}.get(flag), None) + _write(data) + return item + + def delete_item(identifier): with lock: data = read() - kept = [item for item in data["items"] if item["id"] != identifier] - if len(kept) == len(data["items"]): - raise ValueError("That piece is already gone") - data["items"] = kept + data["items"].remove(_piece(data, identifier)) _write(data) @@ -187,13 +223,19 @@ def payload(): """Everything the page needs: catalog, settings, flagged pieces and the best set.""" data = read() dupes = duplicates(data["items"]) - items = [{**item, "duplicate": item["id"] in dupes, - "wearable": bool(data["class"]) and item.get("item_class") == data["class"]} - for item in data["items"]] + worn = {item["slot"] for item in data["items"] if item.get("worn")} + items = [] + for item in data["items"]: + wearable = bool(data["class"]) and item.get("item_class") == data["class"] + # Using a piece costs an orb (a transfer) when its lines must move onto another piece: + # the piece worn in that slot, or, with none marked worn, any piece of your class. + transfer = not item.get("worn") if item["slot"] in worn else not wearable + items.append({**item, "duplicate": item["id"] in dupes, "wearable": wearable, "transfer": transfer, + **{flag: bool(item.get(flag)) for flag in MARKS}}) solution = None if data["class"]: targets, jobs = solver.resolve_build(data["build"]) - solution = solver.solve([i for i in items if i["wearable"]], targets, jobs) + solution = solver.solve([i for i in items if not i["disabled"]], targets, jobs) solution["targets"] = targets solution["jobs"] = {"count": jobs[0], "keys": list(jobs[1])} if jobs else None return {"catalog": solver.catalog(), "class": data["class"], "build": data["build"], diff --git a/src/quanah/vision.py b/src/quanah/vision.py index 47c1d62..a5f263e 100644 --- a/src/quanah/vision.py +++ b/src/quanah/vision.py @@ -12,15 +12,19 @@ """ import re +from functools import cache +import cv2 import numpy as np from equipment_scan import ( TEXT_LEFT, TEXT_RIGHT, _find_currently_equipped, + _glyph_mask, row_crop, row_regions, + template, tooltip_bottom, ) from flaming.item_tooltip import level_anchors @@ -45,16 +49,48 @@ SKILL_START = re.compile(r"^\[?\s*Hologram|Lv\.?\s*\+\s*\d", re.I) +LABEL_PIECES, LABEL_PIECES_NEEDED, LABEL_SLACK = 4, 2, 6 + + +@cache +def _label_pieces(): + """The "Currently Equipped" glyph mask cut into equal-width pieces, with each piece's x offset.""" + ref = _glyph_mask(template("currently_equipped")) + width = ref.shape[1] // LABEL_PIECES + return [(i * width, ref[:, i * width : (i + 1) * width]) for i in range(LABEL_PIECES)] + + def _is_equipped(frame, x, y): - quality, _, _ = _find_currently_equipped(frame, near=(x + EQUIPPED_DX, y - EQUIPPED_DY)) - return quality >= 0.95 + """Whether the tooltip with Required Level at (X, Y) shows "Currently Equipped". + + In an inventory hover the cursor often rests on the comparison tooltip and can + cover part of the label, so the label also counts when enough of its pieces + are found in place. + """ + lx, ly = x + EQUIPPED_DX, y - EQUIPPED_DY + quality, _, _ = _find_currently_equipped(frame, near=(lx, ly)) + if quality >= 0.95: + return True + found = 0 + for dx, piece in _label_pieces(): + top, left = max(0, ly - LABEL_SLACK), max(0, lx + dx - LABEL_SLACK) + area = frame[top : ly + piece.shape[0] + LABEL_SLACK, left : lx + dx + piece.shape[1] + LABEL_SLACK] + if area.shape[0] < piece.shape[0] or area.shape[1] < piece.shape[1]: + continue + scores = cv2.matchTemplate(_glyph_mask(area), piece, cv2.TM_CCOEFF_NORMED) + found += float(np.nan_to_num(scores).max()) >= 0.95 + return found >= LABEL_PIECES_NEEDED -def locate(frame, pointer=None, anchor=None): +def locate(frame, anchor=None): """The hovered piece's tooltip as (x, name search top, Required Level y, bottom), from one frame; no OCR. ANCHOR, the Required Level position chosen when the frame was captured (see - anchor_of), reads that same tooltip later, when the cursor is no longer known. + anchor_of), reads that same tooltip later. + + Tooltips are told apart only by the "Currently Equipped" label, never by the + cursor: in an inventory hover the game often draws the comparison tooltip + under the cursor, so the nearest tooltip is usually the wrong one. The bottom edge is used when found. A tooltip pushed against the bottom of the screen may not show it; the skill lines end well above it, so the @@ -63,19 +99,20 @@ def locate(frame, pointer=None, anchor=None): anchors = level_anchors(frame) if not anchors: raise ReadError("Hover an event item.") - hovered = [a for a in anchors if not _is_equipped(frame, *a)] if anchor is not None: if tuple(anchor) not in anchors: raise ReadError("Hover one item at a time.") lx, ly = anchor - elif len(hovered) == 1: - lx, ly = hovered[0] - elif not hovered and len(anchors) == 1: - lx, ly = anchors[0] # An Equipment-window hover shows only the equipped item. - elif pointer is not None: - lx, ly = min(hovered or anchors, key=lambda a: (a[0] - pointer[0]) ** 2 + (a[1] - pointer[1]) ** 2) else: - raise ReadError("Hover one item at a time.") + hovered = [a for a in anchors if not _is_equipped(frame, *a)] + if len(hovered) == 1: + lx, ly = hovered[0] + elif not hovered and len(anchors) == 1: + lx, ly = anchors[0] # An Equipment-window hover shows only the equipped item. + elif len(hovered) > 1: + raise ReadError("Move the cursor off the tooltips.") + else: + raise ReadError("Hover one item at a time.") x = lx - LEFT # Rows are read up to TEXT_RIGHT; the last few pixels are only the border. if x < 0 or x + TEXT_RIGHT > frame.shape[1]: diff --git a/src/scan_steps.py b/src/scan_steps.py index 5feda92..68cdda1 100644 --- a/src/scan_steps.py +++ b/src/scan_steps.py @@ -56,18 +56,18 @@ def quanah_step(body, previous=None): from flaming.stats import ReadError from quanah.vision import anchor_of, locate, same_tooltip, signature - first, scale = _frame(body) + first, _ = _frame(body) if not level_anchors(first): return None, None, None - box = locate(first, _pointer(body, scale)) + box = locate(first) mark = signature(first, box) if same_tooltip(mark, previous): raise ReadError("Captured. Hover the next item.") - second, scale = _frame(body) - again = locate(second, _pointer(body, scale)) + second, _ = _frame(body) + again = locate(second) if not same_tooltip(mark, signature(second, again)): raise ReadError("Waiting for the tooltip to finish drawing.") - # The OCR step has no cursor; it reads the tooltip chosen here. + # The OCR step reads the tooltip chosen here, by its Required Level position. return second, mark, anchor_of(again) diff --git a/tests/js/quanah.test.cjs b/tests/js/quanah.test.cjs index bf2485f..adc571b 100644 --- a/tests/js/quanah.test.cjs +++ b/tests/js/quanah.test.cjs @@ -18,27 +18,35 @@ function model(extra={}){ return {catalog,class:'warrior',build:{preset:'eu',job_mode:'custom',jobs:[],targets:{}},items,solution,...extra}; } -test('gear lists duplicates, unwearable pieces and the picked piece, escaping text',async()=>{ +test('gear lists duplicates, other-class pieces and the picked piece, escaping text',async()=>{ const {renderGear}=await import('../../web/pages/quanah.js'); const html=renderGear(model()); assert.equal((html.match(/>DuplicateBowman|undefined|null/); }); -test('pieces sit hat/cape, top/gloves, bottom/shoes, unnumbered, each with edit and delete',async()=>{ +test('pieces sit hat/cape, top/gloves, bottom/shoes, unnumbered, each with a ... menu',async()=>{ const {renderGear}=await import('../../web/pages/quanah.js'); const html=renderGear(model(),'c'); const order=[...html.matchAll(/

([^<]+)<\/h3>/g)].map(m=>m[1]); assert.deepEqual(order,['Hat','Cape','Top','Gloves','Bottom','Shoes']); assert.doesNotMatch(html,/#\d/); - assert.equal((html.match(/data-act="edit"/g)||[]).length,3); - assert.match(html,/q-piece [^"]*is-unwearable is-editing"/); + assert.equal((html.match(/data-act="menu"/g)||[]).length,3); + assert.doesNotMatch(html,/data-act="(edit|delete)"/); + assert.match(html,/q-piece [^"]*is-editing"/); assert.match(html,/title="Read as:\nDimensional Leap Lv\. \+1"/); - assert.match(html,/aria-label="Edit Hat: Dimensional Leap, White Hole, DMG"/); + assert.match(html,/aria-label="More for Hat: Dimensional Leap, White Hole, DMG"/); + // The open menu holds edit and delete for that piece only. + const open=renderGear(model(),null,0,'a'); + assert.match(open,/data-id="a" aria-haspopup="menu" aria-expanded="true"/); + assert.match(open,/role="menu">Combo ${combo+1} of ${s.combos.length}${s.ways>s.combos.length?'+':''}`:''}
    ${set}
+ ${orbs?`

${plural(orbs,'orb')} needed: ${esc(orbSlots.join(', '))}

`:''} ${wasted?'

Struck-through lines do not count toward this build.

':''} ${next} `; @@ -62,21 +81,24 @@ export function scanSummary(queue){ // Two columns, paired as the slots sit in the game: hat and cape, top and gloves, bottom and shoes. export const GEAR_ORDER=['hat','cape','top','gloves','bottom','shoes']; +const ban=''; +const shirt=''; +const star=on=>``; const pencil=''; -export function renderGear(model,editing=null){ +// MENU is the id of the piece whose "..." menu (edit, delete) is open. +export function renderGear(model,editing=null,combo=0,menu=null){ const {catalog,solution:s}=model; - const picked=new Set(Object.values(s?.picks||{}).filter(Boolean)); + const picked=new Set(Object.values(shown(s,combo)?.picks||{}).filter(Boolean)); const slots=[...catalog.slots].sort((a,b)=>GEAR_ORDER.indexOf(a.key)-GEAR_ORDER.indexOf(b.key)); return slots.map(slot=>{ const pieces=model.items.filter(i=>i.slot===slot.key); const rows=pieces.map(item=>{ - const flags=[!item.wearable&&`Can't wear · ${esc(className(catalog,item.item_class))}`, + const flags=[!item.wearable&&classFlag(model,item), item.duplicate&&'Duplicate'].filter(Boolean).join(''); const read=item.raw?.length?`Read as:\n${item.raw.join('\n')}`:''; const label=`${slot.name}: ${item.lines.map(k=>lineName(catalog,k)).join(', ')}`; - const source=item.source==='scan'?(item.edited?'Scanned, edited':'Scanned'):'Manual'; - return `
  • ${item.lines.map(k=>chip(catalog,k)).join('')}${flags}${source}
  • `; + return `
  • ${item.lines.map(k=>chip(catalog,k)).join('')}${flags}${item.id===menu?``:''}
  • `; }).join(''); return `

    ${esc(slot.name)}

    ${plural(pieces.length,'piece')}
    ${rows?`
      ${rows}
    `:`

    No ${esc(slot.name.toLowerCase())} yet

    `}
    `; }).join(''); @@ -84,33 +106,34 @@ export function renderGear(model,editing=null){ export async function mountQuanah(root){ // EDITING is the id of a saved piece loaded into the hand-entry panel, or null when adding. - let model,disposed=false,slot='hat',pending=[],confirmClear=false,editing=null; + // COMBO is the winning combo on show; any change to the pieces or build starts again at the first. + let model,disposed=false,slot='hat',pending=[],confirmClear=false,editing=null,combo=0,menu=null; let scanning=false,windows=[],selectedWindow=null,timer=0,known=new Set(),scanState=null,queue=null; root.className='quanah-page'; root.innerHTML='

    Loading Quanah...

    '; const alive=()=>!disposed&&root.isConnected; async function save(request){ - try{model=await request;remember();if(alive())draw();} + try{model=await request;combo=0;remember();if(alive())draw();} catch(error){toast(error.message);} } - // Warn once about each newly scanned piece the player can't wear. + // Note once each newly scanned piece for another class. function remember(announce=false){ for(const item of model.items){ if(known.has(item.id))continue; known.add(item.id); - if(announce&&!item.wearable)toast(`${item.name||'That piece'} is a ${className(model.catalog,item.item_class)} item. You can't wear it; don't spend resources on it.`); + if(announce&&!item.wearable)toast(`${item.name||'That piece'} is a ${className(model.catalog,item.item_class)} item. It still counts if you orb its lines onto your own ${slotName(model.catalog,item.slot).toLowerCase()}.`); } } function classPicker(){ - return `

    Choose your class

    Event pieces are class-locked. Scanned pieces for another class are flagged so you don't spend resources on them.

    ${model.catalog.classes.map(c=>``).join('')}
    `; + return `

    Choose your class

    Event pieces are class-locked. Pieces for another class still count toward the best set and are tagged with that class: orb their lines onto your own piece of the same slot.

    ${model.catalog.classes.map(c=>``).join('')}
    `; } function buildPanel(){ const {catalog,build}=model; const tabs=catalog.builds.map(b=>``).join(''); let options=''; - if(build.preset==='gandi'){ + if(build.preset==='hybrid'){ const jobs=catalog.lines.filter(l=>l.job); options=`
    ${build.job_mode==='custom'?`
    ${jobs.map(j=>{const on=build.jobs.includes(j.key);return ``;}).join('')}

    ${build.jobs.length}/3 selected. Each needs 1 line.${build.jobs.length!==3?' Until 3 are chosen, Magician, Thief and Bowman are used.':''}

    `:'

    Any 3 different job lines count, 1 each.

    '}
    `; @@ -149,6 +172,14 @@ export async function mountQuanah(root){ ${editing?`` :``}`; } + // Close the "..." menu in place; returns its button, so focus can go back to it. + function closeMenu(){ + const button=root.querySelector(`[data-act="menu"][data-id="${CSS.escape(menu)}"]`); + root.querySelector('.q-menu')?.remove(); + button?.setAttribute('aria-expanded','false'); + menu=null; + return button; + } function startEdit(id){ const item=model.items.find(i=>i.id===id);if(!item)return; editing=id;slot=item.slot;pending=[...item.lines];draw(); @@ -166,12 +197,12 @@ export async function mountQuanah(root){ const head=`

    Quanah

    Seasonal event equipment. Find the one-per-slot set that completes your build's 18 skill lines.

    `; if(!model.class){root.innerHTML=head+classPicker();return;} if(editing&&!model.items.some(i=>i.id===editing))stopEdit(); - const total=model.items.length,dupes=model.items.filter(i=>i.duplicate).length,unwearable=model.items.filter(i=>!i.wearable).length; + const total=model.items.length,dupes=model.items.filter(i=>i.duplicate).length,offclass=model.items.filter(i=>!i.wearable).length; root.innerHTML=`${head}
    ${buildPanel()}${scanPanel()}${addPanel()}

    Your pieces (${total})

    ${total?``:''}
    - ${dupes||unwearable?`

    ${[dupes&&plural(dupes,'duplicate'),unwearable&&`${unwearable} you can't wear`].filter(Boolean).join(' · ')}. Fix a misread with the pencil, or delete with ×.

    `:''} -
    ${renderGear(model,editing)}
    -
    ${renderBest(model)}
    `; + ${dupes||offclass?`

    ${[dupes&&plural(dupes,'duplicate'),offclass&&`${offclass} for another class`].filter(Boolean).join(' · ')}. Fix a misread or delete a piece from its … menu.

    `:''} +
    ${renderGear(model,editing,combo,menu)}
    +
    ${renderBest(model,combo)}
    `; if(focus)[...root.querySelectorAll('[data-act]')].find(el=>sig(el)===focus)?.focus({preventScroll:true}); } @@ -191,7 +222,7 @@ export async function mountQuanah(root){ const finished=reads.done.length!==(queue?.done.length??0); scanState=state;queue=reads; if(scanning&&!state.active){scanning=false;if(state.status==='error')toast(state.message);} - if(finished){model=await api.get('/api/quanah');remember(true);} + if(finished){model=await api.get('/api/quanah');combo=0;remember(true);} draw(); if(scanning||reads.pending.length)timer=setTimeout(poll,700); }catch(error){if(alive())timer=setTimeout(poll,2000);} @@ -210,8 +241,12 @@ export async function mountQuanah(root){ } root.addEventListener('click',e=>{ - const b=e.target.closest('[data-act]');if(!b||b.tagName==='SELECT')return; - const act=b.dataset.act,build=model.build; + const b=e.target.closest('[data-act]'),act=b?.dataset.act; + if(act==='menu'){menu=menu===b.dataset.id?null:b.dataset.id;draw();if(menu)root.querySelector('.q-menu [role="menuitem"]')?.focus();return;} + // Any other click closes the "..." menu, without a redraw so a dropdown clicked still opens. + if(menu)closeMenu(); + if(!b||b.tagName==='SELECT')return; + const build=model.build; if(act!=='clear')confirmClear=false; if(act==='class')save(api.put('/api/quanah/settings',{class:b.dataset.class})); else if(act==='preset')setBuild({preset:b.dataset.preset}); @@ -226,12 +261,18 @@ export async function mountQuanah(root){ else if(act==='edit')startEdit(b.dataset.id); else if(act==='cancel-edit'){stopEdit();draw();} else if(act==='save-edit'){const id=editing,lines=pending;stopEdit();save(api.put('/api/quanah/items/'+encodeURIComponent(id),{slot,lines}));} + else if(act==='combo'){combo=stepCombo(combo,Number(b.dataset.step),model.solution.combos.length);draw();} + else if(act in MARK){const item=model.items.find(i=>i.id===b.dataset.id);if(item)save(api.put(...markRequest(act,item)));} else if(act==='delete')save(api.delete('/api/quanah/items/'+encodeURIComponent(b.dataset.id))); else if(act==='clear'){if(confirmClear){confirmClear=false;save(api.delete('/api/quanah/items'));}else{confirmClear=true;draw();}} else if(act==='scan')startScan(); else if(act==='stop')stopScan(); else if(act==='windows')loadWindows().then(draw); }); + root.addEventListener('keydown',e=>{ + if(e.key!=='Escape'||!menu)return; + closeMenu()?.focus(); + }); root.addEventListener('change',e=>{ const act=e.target.dataset.act; if(act==='class-select')save(api.put('/api/quanah/settings',{class:e.target.value})); diff --git a/web/scanner.css b/web/scanner.css index 9bdb31f..1306c09 100644 --- a/web/scanner.css +++ b/web/scanner.css @@ -363,14 +363,19 @@ body{height:100vh;min-height:0;display:flex;flex-direction:column;overflow:hidde .q-gear-slot{padding:10px 12px;border:1px solid var(--border);border-radius:10px;background:var(--bg-elev)} .q-gear-slot header{display:flex;align-items:baseline;justify-content:space-between;margin-bottom:6px}.q-gear-slot h3{margin:0;font-size:13px} .q-gear-slot ul{display:grid;gap:4px;margin:0;padding:0;list-style:none}.q-gear-slot>p{margin:0} -.q-piece{display:flex;flex-wrap:wrap;align-items:center;gap:6px;padding:5px 6px;border:1px solid transparent;border-radius:8px} -.q-piece.is-picked{border-color:var(--accent);background:var(--accent-dim)}.q-piece.is-unwearable .q-lines{opacity:.5} +.q-piece{display:flex;flex-wrap:wrap;align-items:center;gap:4px;padding:5px 6px;border:1px solid transparent;border-radius:8px} +.q-piece.is-picked{border-color:var(--accent);background:var(--accent-dim)} .q-flag{padding:1px 7px;border-radius:999px;font-size:11px;font-weight:600} -.q-flag.is-danger{background:var(--danger-dim);color:var(--danger)}.q-flag.is-warn{background:var(--warn-dim);color:var(--warn)} -.q-source{margin-left:auto;font-size:11px;color:var(--text-muted)} +.q-flag.is-warn{background:var(--warn-dim);color:var(--warn)} +/* The buttons stay together at the right; if a row is too narrow they wrap as one group. */ +.q-actions{display:flex;gap:4px;margin-left:auto} .q-icon{display:grid;place-items:center;width:22px;height:22px;padding:0;border:1px solid var(--border);border-radius:6px;background:none;color:var(--text-muted);font-size:15px;line-height:1} .q-icon:hover,.q-icon:focus-visible{border-color:var(--accent);color:var(--accent)} .q-delete:hover,.q-delete:focus-visible{border-color:var(--danger);color:var(--danger)} +.q-pick{display:flex;flex-wrap:wrap;align-items:center;gap:6px;min-width:0}.q-equip{display:flex;align-items:center;justify-content:space-between;gap:8px}.q-combos{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-muted)} +.q-piece.is-disabled .q-lines{opacity:.45;text-decoration:line-through}.q-more{position:relative}.q-menu{position:absolute;right:0;top:calc(100% + 4px);z-index:5;display:grid;min-width:110px;padding:4px;border:1px solid var(--border);border-radius:8px;background:var(--surface);box-shadow:0 6px 18px #0006} +.q-menu button{display:flex;align-items:center;gap:8px;padding:6px 8px;border:0;border-radius:6px;background:none;color:var(--text);text-align:left;font-size:12px}.q-menu button:hover,.q-menu button:focus-visible{background:var(--accent-dim)}.q-menu .q-delete:hover,.q-menu .q-delete:focus-visible{background:var(--danger-dim);color:var(--danger)} +.q-orbs{margin:0 0 6px}.q-mark.is-on{border-color:var(--accent);color:var(--accent)}.q-flag.is-pref{background:var(--accent-dim);color:var(--accent)} .q-piece.is-editing{border-color:var(--info);background:var(--info-dim)} .q-add.is-editing{border-color:var(--info)}.q-read{margin:0 0 10px} .q-pill{padding:2px 10px;border-radius:999px;background:var(--warn-dim);color:var(--warn);font-size:12px;font-weight:600}.q-pill.is-ok{background:var(--ok-dim);color:var(--ok)}