@team-antioch/sc2-set-finder 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/finder.js ADDED
@@ -0,0 +1,82 @@
1
+ // The Set Finder (docs/adr/0001, 0002): the kit's finder over the sets' cards, with their keyword
2
+ // search and tags, and `find`, which narrows an ask and has Jev rank it in one call, for a caller
3
+ // with no page (sc2-adjutant's find_sets tool, the test command). The page's server asks the same
4
+ // finder's `narrow` and ranks through the kit's asker.
5
+ //
6
+ // There are about eighty sets, and the kit's nearest cards are about two hundred, so every set
7
+ // would be a candidate and Jev would grade them all. Each ask is cut to the best 24 of the merge,
8
+ // which holds every set a keyword found and the nearest of the rest.
9
+ import path from "node:path";
10
+ import { openFinder as kitOpenFinder, vectorCacheFile } from "@team-antioch/sc2-finder-kit/finder.js";
11
+ import { jevRankBudget } from "@team-antioch/sc2-finder-kit/jev-ranker.js";
12
+ import { orderByFit, RankerError } from "@team-antioch/sc2-finder-kit/ranker.js";
13
+ import { keywordSearch, tagMatches } from "./narrow.js";
14
+ import { JEV_WORDING } from "./wording.js";
15
+ /** How many of the merged candidates an ask keeps for the ranker and the page. */
16
+ export const SET_LIMIT = 24;
17
+ /** What Jev takes in one request, counted for the sets' cards (docs/adr/0002); 24 cards are far below it. */
18
+ export const SET_RANK_BUDGET = jevRankBudget(JEV_WORDING);
19
+ /** The sets' vectors in their own file, so the other finders, which share the cache folder, and this one don't replace each other's. */
20
+ export const setVectorCacheFile = (model, cacheDir) => {
21
+ const file = vectorCacheFile(model, cacheDir);
22
+ return path.join(path.dirname(file), `sets-${path.basename(file)}`);
23
+ };
24
+ export const NOT_RANKED = "rank: false asked for the narrowing alone";
25
+ const NO_RANKER = "no ranker";
26
+ const NOTHING_TO_RANK = "the narrowing found nothing to rank";
27
+ export async function openSetFinder({ cards, embedder, cacheFile, ranker, off, cap, translator, languageDetector, rankBudget = SET_RANK_BUDGET }) {
28
+ const finder = await kitOpenFinder({
29
+ load: async () => ({ cards }),
30
+ cards: (sources) => sources.cards,
31
+ // Pinned tags the search doesn't take, the kit checks on its matches.
32
+ keyword: (sources, ask) => keywordSearch(sources.cards, ask),
33
+ tagMatches,
34
+ // A set needs no map dependency.
35
+ provides: () => false,
36
+ rankBudget,
37
+ embedder,
38
+ cacheFile,
39
+ ...(translator ? { translator } : {}),
40
+ ...(languageDetector ? { languageDetector } : {}),
41
+ });
42
+ const narrow = (ask, options = {}) => finder.narrow(ask, { limit: SET_LIMIT, ...options });
43
+ const rankerOff = ranker ? undefined : (off ?? NO_RANKER);
44
+ return {
45
+ get cards() {
46
+ return finder.cards;
47
+ },
48
+ get sources() {
49
+ return finder.sources;
50
+ },
51
+ embeddedOnOpen: finder.embeddedOnOpen,
52
+ reload: () => finder.reload(),
53
+ close: () => finder.close(),
54
+ narrow,
55
+ rankerOff,
56
+ async find(ask, { rank = true, tags = [], limit = SET_LIMIT, signal } = {}) {
57
+ const narrowing = await narrow(ask, { tags, limit });
58
+ const candidates = narrowing.candidates;
59
+ const timings = { narrow: narrowing.timings.total + (narrowing.timings.translate ?? 0) };
60
+ const unranked = (notRanked, cost = 0) => ({ ask, sets: candidates, ranked: false, notRanked, cost, timings });
61
+ if (!rank)
62
+ return unranked(NOT_RANKED);
63
+ if (!ranker)
64
+ return unranked(rankerOff);
65
+ if (candidates.length === 0)
66
+ return unranked(NOTHING_TO_RANK);
67
+ if (cap && !cap.allows())
68
+ return unranked(cap.reason);
69
+ try {
70
+ const ranking = await ranker.rank({ ask, tags, candidates: candidates.map(({ card }) => card) }, signal ? { signal } : {});
71
+ cap?.record(ranking.cost);
72
+ return { ask, sets: orderByFit(candidates, ranking.grades), ranked: true, cost: ranking.cost, timings: { ...timings, rank: ranking.timings.total } };
73
+ }
74
+ catch (error) {
75
+ if (!(error instanceof RankerError))
76
+ throw error;
77
+ cap?.record(error.cost);
78
+ return unranked(`Jev didn't answer (${error.message}), so the narrowing's order is shown`, error.cost);
79
+ }
80
+ },
81
+ };
82
+ }
@@ -0,0 +1,5 @@
1
+ import { type LoginOptions as KitLoginOptions } from "@team-antioch/sc2-finder-kit/login.js";
2
+ export { logout, type KeyCheck, type KeyCheckResult, typesafeKeyCheck } from "@team-antioch/sc2-finder-kit/login.js";
3
+ export type LoginOptions = Omit<KitLoginOptions, "command">;
4
+ /** Asks for the key, checks it and saves it. Returns the exit code: 0 saved, 1 not, 130 cancelled. */
5
+ export declare const login: (options?: LoginOptions) => Promise<number>;
package/dist/login.js ADDED
@@ -0,0 +1,6 @@
1
+ // `sc2-set-finder login` and `logout`: the kit's, naming this package in what they print.
2
+ import { login as kitLogin } from "@team-antioch/sc2-finder-kit/login.js";
3
+ import { PACKAGE_NAME } from "./package-name.js";
4
+ export { logout, typesafeKeyCheck } from "@team-antioch/sc2-finder-kit/login.js";
5
+ /** Asks for the key, checks it and saves it. Returns the exit code: 0 saved, 1 not, 130 cancelled. */
6
+ export const login = (options = {}) => kitLogin({ ...options, command: PACKAGE_NAME });
@@ -0,0 +1,19 @@
1
+ import type { Tag } from "@team-antioch/sc2-finder-kit/card.js";
2
+ import type { SetCard } from "./cards.ts";
3
+ export type { Tag } from "@team-antioch/sc2-finder-kit/card.js";
4
+ /** Every facet a tag can name. */
5
+ export declare const FACETS: readonly ["kind", "facet"];
6
+ export type Facet = (typeof FACETS)[number];
7
+ export declare const facetOf: (text: string) => Facet | undefined;
8
+ /** The kinds a `kind` value names, lower case. */
9
+ export declare const kindsOf: (value: string) => string[];
10
+ /** Whether a tag matches a card, case aside. An unknown facet matches nothing. */
11
+ export declare function tagMatches(card: SetCard, tag: Tag): boolean;
12
+ /** The keyword search's words for an ask: its words, less the ones that say nothing about a place, plurals aside. */
13
+ export declare const askWords: (ask: string) => string[];
14
+ /**
15
+ * The cards an ask's words are found in, best first: each word counts once, at its best place (the
16
+ * name, id or kind, the facets, what it could stand in for, then the look and its places), and a
17
+ * card with more of the ask's words comes before one with fewer.
18
+ */
19
+ export declare function keywordSearch(cards: Iterable<SetCard>, ask: string): SetCard[];
package/dist/narrow.js ADDED
@@ -0,0 +1,69 @@
1
+ // The Set Finder's side of the narrowing (docs/adr/0001, 0002): its keyword search and what its
2
+ // tags match. The kit merges the keyword matches with the nearest cards by embedding. There are
3
+ // about eighty sets, so the search is a plain scan of every card.
4
+ //
5
+ // kind one kind, or several comma apart (`room, exterior`): the page's kind chips pin it
6
+ // facet one of the look's facets, such as `ship bridge`
7
+ /** Every facet a tag can name. */
8
+ export const FACETS = ["kind", "facet"];
9
+ export const facetOf = (text) => FACETS.find((facet) => facet === text.toLowerCase().trim());
10
+ /** The kinds a `kind` value names, lower case. */
11
+ export const kindsOf = (value) => value
12
+ .split(",")
13
+ .map((kind) => kind.trim().toLowerCase())
14
+ .filter(Boolean);
15
+ /** Whether a tag matches a card, case aside. An unknown facet matches nothing. */
16
+ export function tagMatches(card, tag) {
17
+ const facet = facetOf(tag.facet);
18
+ switch (facet) {
19
+ case "kind":
20
+ return kindsOf(tag.value).includes(card.look.kind);
21
+ case "facet":
22
+ return card.look.facets.some((value) => value.toLowerCase() === tag.value.toLowerCase().trim());
23
+ case undefined:
24
+ return false;
25
+ default:
26
+ return facet;
27
+ }
28
+ }
29
+ /** Words of an ask that say nothing about a place: left out of the keyword search, which matches any word. */
30
+ const STOP_WORDS = new Set(("a an and any are as at be by can could for from has have he her his i if in inside into is it its like look looks me my of on onto or out over " +
31
+ "place set she so some somewhere something that the their them then there these they thing this to under up was we what where which with would you your").split(" "));
32
+ /** A word without its plural, so "corridors" finds "corridor". */
33
+ const stem = (word) => (word.length > 3 ? word.replace(/(?:es|s)$/, "") : word);
34
+ const words = (text) => new Set((text.toLowerCase().match(/[a-z0-9]+/g) ?? []).map(stem));
35
+ /** The keyword search's words for an ask: its words, less the ones that say nothing about a place, plurals aside. */
36
+ export const askWords = (ask) => [...new Set((ask.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter((word) => !STOP_WORDS.has(word)).map(stem))];
37
+ /** What a word is worth by where it is found: the name, kind and facets say what the set is, the look mentions what is in it. */
38
+ const WEIGHTS = { name: 4, facets: 3, uses: 2, look: 1 };
39
+ /**
40
+ * The cards an ask's words are found in, best first: each word counts once, at its best place (the
41
+ * name, id or kind, the facets, what it could stand in for, then the look and its places), and a
42
+ * card with more of the ask's words comes before one with fewer.
43
+ */
44
+ export function keywordSearch(cards, ask) {
45
+ const wanted = askWords(ask);
46
+ if (wanted.length === 0)
47
+ return [];
48
+ const scored = [...cards].map((card) => {
49
+ const fields = [
50
+ ["name", words(`${card.name} ${card.id} ${card.look.kind}`)],
51
+ ["facets", words(card.look.facets.join(" "))],
52
+ ["uses", words(card.look.standsInFor.join(" "))],
53
+ ["look", words(`${card.look.look} ${(card.look.rooms ?? []).join(" ")}`)],
54
+ ];
55
+ let found = 0;
56
+ let score = 0;
57
+ for (const word of wanted) {
58
+ const best = Math.max(0, ...fields.filter(([, has]) => has.has(word)).map(([field]) => WEIGHTS[field]));
59
+ if (best)
60
+ found++;
61
+ score += best;
62
+ }
63
+ return { card, found, score };
64
+ });
65
+ return scored
66
+ .filter((entry) => entry.found > 0)
67
+ .sort((a, b) => b.found - a.found || b.score - a.score || a.card.id.localeCompare(b.card.id))
68
+ .map((entry) => entry.card);
69
+ }
@@ -0,0 +1,2 @@
1
+ /** The package's name: what its commands are run as with npx. */
2
+ export declare const PACKAGE_NAME = "@team-antioch/sc2-set-finder";
@@ -0,0 +1,2 @@
1
+ /** The package's name: what its commands are run as with npx. */
2
+ export const PACKAGE_NAME = "@team-antioch/sc2-set-finder";
package/dist/page.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { SetCard } from "./cards.ts";
2
+ /** The gallery page: self-contained, with no credential or path in it; everything else comes from the process. */
3
+ export declare function finderPage(): string;
4
+ /** One set's page: its look in full, its pictures beside their frames in game, its plan and overview, and what its look rests on. */
5
+ export declare function setPage(card: SetCard): string;
package/dist/page.js ADDED
@@ -0,0 +1,400 @@
1
+ // The Set Finder's pages, served by its process (server.ts). The gallery: with nothing asked it
2
+ // shows every set by name (from /cards); the mapper types the place they need, and the process sends
3
+ // the narrowing's cards, then the ranked order, as events. The page keeps one element per card, so a
4
+ // re-sort moves the cards it has instead of drawing new ones. The kind chips pin a `kind` tag
5
+ // (narrow.ts), and hide the other kinds' cards in the gallery. A set's own page has its look in
6
+ // full, each card picture beside its frame filmed in game, and its plan and overview.
7
+ import { SET_KINDS } from "@team-antioch/sc2-asset-catalog/catalog/set-looks.js";
8
+ import { escapeHtml, sizeLine } from "./card-html.js";
9
+ const STYLE = `
10
+ :root { color-scheme: light dark; --bg: #f5f5f3; --card: #fff; --ink: #1a1a1a; --dim: #666; --line: #e0e0dc; --chip: #eef0f2; --accent: #2c5a85; }
11
+ @media (prefers-color-scheme: dark) { :root { --bg: #161719; --card: #1f2124; --ink: #e8e8ea; --dim: #9a9aa0; --line: #33363b; --chip: #2a2d31; --accent: #7db7e0; } }
12
+ body { background: var(--bg); color: var(--ink); font: 16px/1.45 -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; margin: 0 auto; max-width: 1400px; padding: 1.5rem 2rem 4rem; }
13
+ a { color: var(--accent); }
14
+ h1 { margin: 0 0 0.25rem; }
15
+ code { font-size: 0.85rem; background: var(--chip); padding: 0 0.25rem; border-radius: 3px; overflow-wrap: anywhere; }
16
+ .bar { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin: 0.5rem 0; }
17
+ #ask { font: inherit; font-size: 1.3rem; width: 100%; box-sizing: border-box; padding: 0.5rem 0.75rem; border: 1px solid #bbb; border-radius: 6px; background: var(--card); color: var(--ink); }
18
+ .status { color: var(--dim); font-size: 0.9rem; min-height: 1.3em; }
19
+ .status.failed { color: #c33; }
20
+ .kinds { display: flex; flex-wrap: wrap; gap: 0.4rem; margin: 0.5rem 0; }
21
+ .kinds button { font: inherit; font-size: 0.9rem; border: 1px solid var(--line); background: var(--card); color: var(--ink); border-radius: 999px; padding: 0.1rem 0.7rem; cursor: pointer; }
22
+ .kinds button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }
23
+ .tags { display: flex; flex-wrap: wrap; gap: 0.4rem; margin: 0.5rem 0; min-height: 1.6rem; }
24
+ .tag { display: inline-flex; gap: 0.3rem; align-items: center; background: var(--chip); border-radius: 999px; padding: 0.1rem 0.6rem; font-size: 0.9rem; }
25
+ .tag.pinned { background: var(--accent); color: #fff; }
26
+ .tag button { font: inherit; font-size: 0.8rem; border: none; background: none; color: inherit; cursor: pointer; padding: 0 0.15rem; text-decoration: underline; }
27
+ .layout { display: grid; grid-template-columns: 1fr 300px; gap: 1.5rem; align-items: start; }
28
+ @media (max-width: 800px) { body { padding: 1rem; } .layout { grid-template-columns: 1fr; } }
29
+ .tray { position: sticky; top: 1rem; background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 0.75rem; font-size: 0.9rem; }
30
+ .tray h2 { font-size: 1rem; margin: 0 0 0.5rem; }
31
+ .tray ol { margin: 0 0 0.5rem; padding-left: 1.2rem; }
32
+ .tray li { margin-bottom: 0.5rem; overflow-wrap: anywhere; }
33
+ .tray .from { color: var(--dim); }
34
+ .tray .buttons { display: flex; flex-wrap: wrap; gap: 0.4rem; }
35
+ .cards { list-style: none; padding: 0; margin: 0.5rem 0 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem; }
36
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: 8px; overflow: hidden; display: flex; flex-direction: column; }
37
+ .card[hidden] { display: none; }
38
+ .card.ticked { outline: 3px solid var(--accent); }
39
+ .first { display: block; aspect-ratio: 16 / 9; background: #000; }
40
+ .first img { width: 100%; height: 100%; object-fit: cover; display: block; }
41
+ .strip { display: flex; gap: 2px; background: var(--line); }
42
+ .strip img { flex: 1; min-width: 0; aspect-ratio: 16 / 9; object-fit: cover; cursor: pointer; display: block; }
43
+ .body { padding: 0.6rem 0.75rem 0.75rem; }
44
+ .card header label { cursor: pointer; }
45
+ .card .open { float: right; font-size: 0.85rem; }
46
+ .name { font-weight: bold; overflow-wrap: anywhere; }
47
+ .facts { display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; font-size: 0.85rem; color: var(--dim); margin: 0.3rem 0; }
48
+ .level:empty { display: none; }
49
+ .level { font-weight: bold; color: var(--ink); }
50
+ .badge { background: #f1e6c8; color: #1a1a1a; border-radius: 4px; padding: 0 0.35rem; }
51
+ .badge.quiet { background: var(--chip); color: var(--dim); }
52
+ .look { margin: 0.4rem 0; display: -webkit-box; -webkit-line-clamp: 5; -webkit-box-orient: vertical; overflow: hidden; cursor: pointer; }
53
+ .look.open { display: block; }
54
+ .facets { display: flex; flex-wrap: wrap; gap: 0.25rem; margin: 0.3rem 0; }
55
+ .facets span { background: var(--chip); border-radius: 4px; padding: 0 0.35rem; font-size: 0.8rem; }
56
+ .uses { color: var(--dim); font-size: 0.85rem; margin: 0.4rem 0 0; }
57
+ button { font: inherit; }
58
+ .taken { margin-top: 0.75rem; }
59
+ .taken textarea { font: inherit; font-size: 0.85rem; width: 100%; box-sizing: border-box; height: 7rem; }
60
+ dialog.inputs { border: 1px solid #ccc; border-radius: 8px; padding: 1rem 1.25rem; max-width: 32rem; }
61
+ dialog.inputs label { display: block; margin: 0.5rem 0; }
62
+ dialog.inputs input { font: inherit; width: 100%; box-sizing: border-box; }
63
+ .error { color: #c33; }
64
+ .detail { max-width: 1200px; margin: 0 auto; }
65
+ .pair { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 14px; }
66
+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 10px; }
67
+ @media (max-width: 700px) { .pair { grid-template-columns: 1fr; } }
68
+ figure { margin: 0; }
69
+ figure img { width: 100%; display: block; border: 1px solid var(--line); }
70
+ figcaption { font-size: 0.8rem; color: var(--dim); margin-top: 3px; }
71
+ .missing { aspect-ratio: 16 / 9; display: grid; place-items: center; border: 1px dashed var(--line); color: var(--dim); font-size: 0.85rem; }
72
+ `;
73
+ // The page's own script: asks, events, cards, the kind chips, ticks, tags, the tray and its actions.
74
+ const SCRIPT = `
75
+ const $ = (selector) => document.querySelector(selector);
76
+ const askBox = $("#ask"), statusLine = $("#status"), grid = $("#cards"), tagsRow = $("#tags"), trayBox = $("#tray"), takenBox = $("#taken"), kindsRow = $("#kinds");
77
+ const inputsDialog = $("dialog.inputs");
78
+ const KINDS = ${JSON.stringify(SET_KINDS)};
79
+ let state = { tags: [], tray: { items: [], copy: "" }, actions: [], ranker: null, off: null, idleMs: 1500, spend: 0, budget: null, capped: null, tickLog: false };
80
+ // Every set, by name: what the gallery shows with nothing asked.
81
+ let gallery = [];
82
+ // The ask the cards on the page came from: what a tick is filed under.
83
+ let shown = { text: "", ranked: false };
84
+ let pendingAction;
85
+ const elements = new Map();
86
+ const drawn = new WeakMap();
87
+
88
+ const post = async (route, body = {}) => {
89
+ const response = await fetch(route, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
90
+ const answer = await response.json();
91
+ if (!response.ok) throw new Error(answer.error || response.statusText);
92
+ return answer;
93
+ };
94
+ const escapeText = (text) => String(text).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
95
+ const ask = (mode) => post("/ask", { text: askBox.value, mode }).catch(showError);
96
+ const showError = (error) => { statusLine.textContent = error.message; statusLine.className = "status failed"; };
97
+ const say = (text) => { statusLine.textContent = text; statusLine.className = "status"; };
98
+ const currentAsk = () => askBox.value.trim();
99
+ const update = (next) => { state = next; render(); };
100
+ const money = (amount) => "$" + amount.toFixed(amount < 1 ? 4 : 2);
101
+ const spent = () => money(state.spend) + (state.budget !== null ? " of " + money(state.budget) : "") + " this session";
102
+
103
+ /** The kinds the chips pick: none picked shows every kind. */
104
+ const picked = () => new Set([...kindsRow.querySelectorAll("button[aria-pressed=true]")].map((b) => b.value));
105
+ const showsKind = (kind) => { const kinds = picked(); return kinds.size === 0 || kinds.has(kind); };
106
+
107
+ const showGallery = () => { place(gallery, "", false); say(gallery.length + " sets"); };
108
+
109
+ askBox.addEventListener("input", () => {
110
+ if (!currentAsk()) showGallery();
111
+ ask("type");
112
+ });
113
+ askBox.addEventListener("keydown", (event) => { if (event.key === "Enter") { event.preventDefault(); if (state.ranker && !state.capped && !(shown.ranked && shown.text === currentAsk())) say("Ranking..."); ask("enter"); } });
114
+
115
+ const inTray = () => new Set(state.tray.items.map(({ id }) => id));
116
+
117
+ /** Puts the cards in this order, moving the ones shown: each slides from where it was, so nothing jumps. */
118
+ function place(cards, text, ranked) {
119
+ shown = { text: text.trim(), ranked };
120
+ const before = new Map();
121
+ for (const [id, element] of elements) if (element.isConnected) before.set(id, element.getBoundingClientRect());
122
+ const ticked = inTray();
123
+ const order = cards.map((card) => {
124
+ let element = elements.get(card.id);
125
+ if (!element) {
126
+ element = document.createElement("li");
127
+ element.className = "card";
128
+ element.dataset.id = card.id;
129
+ elements.set(card.id, element);
130
+ }
131
+ if (drawn.get(element) !== card.html) {
132
+ element.innerHTML = card.html;
133
+ drawn.set(element, card.html);
134
+ element.dataset.kind = element.querySelector(".kind").textContent;
135
+ }
136
+ element.querySelector(".level").textContent = card.level === undefined ? "" : card.level.toFixed(1) + " " + card.levelName;
137
+ const box = element.querySelector("input.tick");
138
+ box.checked = ticked.has(card.id);
139
+ element.classList.toggle("ticked", box.checked);
140
+ element.hidden = !showsKind(element.dataset.kind);
141
+ return element;
142
+ });
143
+ grid.replaceChildren(...order);
144
+ for (const element of order) {
145
+ const was = before.get(element.dataset.id);
146
+ if (!was) continue;
147
+ const now = element.getBoundingClientRect();
148
+ const dx = was.left - now.left, dy = was.top - now.top;
149
+ if (dx || dy) element.animate([{ transform: "translate(" + dx + "px, " + dy + "px)" }, { transform: "none" }], { duration: 250, easing: "ease-out" });
150
+ }
151
+ }
152
+
153
+ const events = new EventSource("/events");
154
+ events.addEventListener("state", (event) => update(JSON.parse(event.data)));
155
+ events.addEventListener("narrowed", (event) => {
156
+ const data = JSON.parse(event.data);
157
+ if (data.text.trim() !== currentAsk() || !currentAsk()) return;
158
+ place(data.cards, data.text, false);
159
+ say(data.cards.length + " found in " + data.ms + " ms" + (state.ranker && !state.capped ? "; ranking when you press Enter or pause" : ""));
160
+ });
161
+ events.addEventListener("ranked", (event) => {
162
+ const data = JSON.parse(event.data);
163
+ state.spend = data.spend;
164
+ if (data.text.trim() !== currentAsk()) return;
165
+ place(data.cards, data.text, true);
166
+ say(data.cards.length + " ranked by Jev in " + data.ms + " ms · " + spent());
167
+ });
168
+ events.addEventListener("failed", (event) => {
169
+ const data = JSON.parse(event.data);
170
+ if (data.text.trim() === currentAsk()) showError(new Error(data.message));
171
+ });
172
+ events.addEventListener("capped", (event) => {
173
+ const data = JSON.parse(event.data);
174
+ if (data.text.trim() === currentAsk()) showError(new Error("Not ranked: " + data.reason + "."));
175
+ });
176
+
177
+ grid.addEventListener("change", async (event) => {
178
+ const box = event.target.closest("input.tick");
179
+ if (!box) return;
180
+ const id = box.closest(".card").dataset.id;
181
+ // A tick from the gallery is filed under the set's own name: the kit files every tick under an ask.
182
+ const from = shown.text || gallery.find((card) => card.id === id)?.name || id;
183
+ try { update(await post("/tick", { ask: from, id, ticked: box.checked })); }
184
+ catch (error) { box.checked = !box.checked; showError(error); }
185
+ });
186
+
187
+ // A look opens in full; a strip picture swaps with the large one.
188
+ grid.addEventListener("click", (event) => {
189
+ if (event.target.matches(".look")) return void event.target.classList.toggle("open");
190
+ if (!event.target.matches(".strip img")) return;
191
+ const large = event.target.closest(".card").querySelector(".first img");
192
+ const [small, big] = [{ src: event.target.dataset.large, title: event.target.title }, { src: large.dataset.large, title: large.title }];
193
+ large.src = small.src; large.dataset.large = small.src; large.title = large.alt = small.title;
194
+ event.target.src = big.src; event.target.dataset.large = big.src; event.target.title = event.target.alt = big.title;
195
+ });
196
+
197
+ kindsRow.replaceChildren(...KINDS.map((kind) => {
198
+ const chip = document.createElement("button");
199
+ chip.type = "button";
200
+ chip.value = kind;
201
+ chip.textContent = kind;
202
+ chip.setAttribute("aria-pressed", "false");
203
+ return chip;
204
+ }));
205
+ kindsRow.addEventListener("click", async (event) => {
206
+ const chip = event.target.closest("button");
207
+ if (!chip) return;
208
+ chip.setAttribute("aria-pressed", String(chip.getAttribute("aria-pressed") !== "true"));
209
+ for (const element of elements.values()) element.hidden = !showsKind(element.dataset.kind);
210
+ // With an ask, the kinds are a pinned tag, so the narrowing keeps only them.
211
+ try {
212
+ let next = state;
213
+ for (const tag of state.tags.filter((t) => t.pinned && t.facet === "kind")) next = await post("/tag", { facet: "kind", value: tag.value, action: "unpin" });
214
+ const kinds = [...picked()];
215
+ if (kinds.length) next = await post("/tag", { facet: "kind", value: kinds.join(", "), action: "pin" });
216
+ update(next);
217
+ if (currentAsk()) ask("refresh");
218
+ } catch (error) { showError(error); }
219
+ });
220
+
221
+ /** Copies on the click itself, so the browser counts it as the mapper's; else shows the text selected to copy by hand. */
222
+ function copy(text, what) {
223
+ const fallback = () => showTaken({ message: "Copy " + what + " by hand:", text, copied: false });
224
+ if (!navigator.clipboard) return fallback();
225
+ navigator.clipboard.writeText(text).then(() => say("Copied " + what + "."), fallback);
226
+ }
227
+
228
+ function showTaken(done) {
229
+ takenBox.hidden = false;
230
+ takenBox.querySelector("p").textContent = done.message;
231
+ const area = takenBox.querySelector("textarea");
232
+ area.hidden = done.text === undefined || done.copied === true;
233
+ area.value = done.text ?? "";
234
+ if (!area.hidden) area.select();
235
+ }
236
+
237
+ function render() {
238
+ const tray = state.tray;
239
+ trayBox.querySelector("ol").replaceChildren(...tray.items.map((item) => {
240
+ const entry = document.createElement("li");
241
+ entry.innerHTML = "<strong>" + escapeText(item.name) + "</strong> <code>" + escapeText(item.id) + "</code>" + (item.level !== undefined ? " · " + item.level.toFixed(1) + " " + escapeText(item.levelName) : "") +
242
+ '<div class="from">from “' + escapeText(item.ask) + '”</div><button data-do="copy">Copy</button> <button data-do="untick">Untick</button>';
243
+ entry.querySelector('[data-do="copy"]').addEventListener("click", () => copy(item.copy, item.id));
244
+ entry.querySelector('[data-do="untick"]').addEventListener("click", () => post("/tick", { ask: item.ask, id: item.id, ticked: false }).then(update).catch(showError));
245
+ return entry;
246
+ }));
247
+ trayBox.querySelector(".empty").hidden = tray.items.length > 0;
248
+ const buttons = trayBox.querySelector(".buttons");
249
+ buttons.hidden = tray.items.length === 0;
250
+ buttons.replaceChildren();
251
+ const button = (label, title, run) => { const b = document.createElement("button"); b.textContent = label; b.title = title; b.addEventListener("click", run); buttons.append(b); };
252
+ button("Copy all", "Copies every set's id, name and Cutscene Editor files, a line each", () => copy(tray.copy, "the tray"));
253
+ button("Clear", "Empties the tray", () => post("/clear").then(update).catch(showError));
254
+ state.actions.forEach((action, index) => button(action.label, action.title, () => startAction(index)));
255
+ trayBox.querySelector(".logged").hidden = !state.tickLog;
256
+
257
+ // The kind chips stand for the pinned kind tag, so it isn't shown again among the tags.
258
+ tagsRow.replaceChildren(...state.tags.filter((tag) => !(tag.pinned && tag.facet === "kind")).map((tag) => {
259
+ const chip = document.createElement("span");
260
+ chip.className = "tag" + (tag.pinned ? " pinned" : "");
261
+ chip.innerHTML = escapeText(tag.facet + ": " + tag.value) + ' <button data-action="' + (tag.pinned ? "unpin" : "pin") + '">' + (tag.pinned ? "unpin" : "pin") + '</button><button data-action="drop">drop</button>';
262
+ chip.querySelectorAll("button").forEach((b) => b.addEventListener("click", async () => {
263
+ try { update(await post("/tag", { facet: tag.facet, value: tag.value, action: b.dataset.action })); if (currentAsk()) ask("refresh"); } catch (error) { showError(error); }
264
+ }));
265
+ return chip;
266
+ }));
267
+
268
+ $("#ranker").textContent = state.ranker ? (state.capped ? "Jev is paused: " + state.capped : "Ranked by Jev · " + spent()) : "Not ranked: " + (state.off || "no ranker");
269
+ $("#idle").parentElement.hidden = !state.ranker;
270
+ $("#idle").value = (state.idleMs / 1000).toString();
271
+ const ticked = inTray();
272
+ for (const [id, element] of elements) {
273
+ const box = element.querySelector("input.tick");
274
+ box.checked = ticked.has(id);
275
+ element.classList.toggle("ticked", box.checked);
276
+ }
277
+ }
278
+
279
+ function startAction(index) {
280
+ const action = state.actions[index];
281
+ if (!action.inputs.length) return runAction(index, {});
282
+ pendingAction = index;
283
+ const form = inputsDialog.querySelector("form");
284
+ inputsDialog.querySelector("h2").textContent = action.label;
285
+ inputsDialog.querySelector(".error").textContent = "";
286
+ form.querySelector(".fields").replaceChildren(...action.inputs.map((input) => {
287
+ const label = document.createElement("label");
288
+ label.textContent = input.label + " ";
289
+ const field = document.createElement("input");
290
+ field.name = input.name;
291
+ field.placeholder = input.placeholder || "";
292
+ field.required = !!input.required;
293
+ label.append(field);
294
+ return label;
295
+ }));
296
+ inputsDialog.showModal();
297
+ form.querySelector("input")?.focus();
298
+ }
299
+
300
+ inputsDialog.querySelector("form").addEventListener("submit", (event) => {
301
+ event.preventDefault();
302
+ if (event.submitter?.value === "cancel") { pendingAction = undefined; inputsDialog.close(); return; }
303
+ const inputs = Object.fromEntries([...event.target.querySelectorAll(".fields input")].map((field) => [field.name, field.value]));
304
+ runAction(pendingAction, inputs, (error) => { inputsDialog.querySelector(".error").textContent = error.message; }).then((ran) => { if (ran) inputsDialog.close(); });
305
+ });
306
+
307
+ async function runAction(index, inputs, onError = showError) {
308
+ try {
309
+ const answer = await post("/action", { index, inputs });
310
+ update(answer);
311
+ const done = answer.done;
312
+ showTaken(done);
313
+ if (done.text !== undefined && !done.copied && navigator.clipboard) {
314
+ if (await navigator.clipboard.writeText(done.text).then(() => true, () => false)) showTaken({ ...done, copied: true });
315
+ }
316
+ return true;
317
+ } catch (error) { onError(error); return false; }
318
+ }
319
+
320
+ $("#idle").addEventListener("change", (event) => post("/settings", { idleMs: Math.round(Number(event.target.value) * 1000) }).then(update).catch(showError));
321
+
322
+ fetch("/cards").then((response) => response.json()).then((found) => {
323
+ gallery = found.cards;
324
+ if (!currentAsk()) showGallery();
325
+ else ask("enter");
326
+ }).catch(showError);
327
+ `;
328
+ /** The gallery page: self-contained, with no credential or path in it; everything else comes from the process. */
329
+ export function finderPage() {
330
+ return [
331
+ `<!doctype html>`,
332
+ `<html lang="en">`,
333
+ `<head>`,
334
+ `<meta charset="utf-8">`,
335
+ `<meta name="viewport" content="width=device-width, initial-scale=1">`,
336
+ `<title>Set Finder</title>`,
337
+ `<link rel="icon" href="data:,">`,
338
+ `<style>${STYLE}</style>`,
339
+ `</head>`,
340
+ `<body>`,
341
+ `<h1>Set Finder</h1>`,
342
+ `<input id="ask" type="search" placeholder="Where is the scene? a cramped ship corridor with a cockpit at one end" autocomplete="off" autofocus>`,
343
+ `<div class="bar"><span class="status" id="status"></span></div>`,
344
+ `<div class="kinds" id="kinds" role="group" aria-label="Kinds of set"></div>`,
345
+ `<div class="bar"><span class="status" id="ranker"></span><label>Rank after a pause of <input id="idle" type="number" min="0.25" step="0.25" style="width: 4em"> s</label></div>`,
346
+ `<div class="tags" id="tags"></div>`,
347
+ `<div class="layout">`,
348
+ `<ol class="cards" id="cards"></ol>`,
349
+ `<aside class="tray" id="tray"><h2>Tray</h2>`,
350
+ `<p class="empty">Tick sets to collect them here, then copy their ids and the Cutscene Editor files they are in.</p><ol></ol>`,
351
+ `<div class="buttons" hidden></div><p class="logged from" hidden>Ticks are logged for the test command.</p>`,
352
+ `<div class="taken" id="taken" hidden><p></p><textarea readonly aria-label="Text to copy"></textarea></div></aside>`,
353
+ `</div>`,
354
+ `<dialog class="inputs"><form method="dialog">`,
355
+ `<h2></h2>`,
356
+ `<div class="fields"></div>`,
357
+ `<p class="error"></p>`,
358
+ `<p><button value="run">Go</button> <button value="cancel" formnovalidate>Cancel</button></p>`,
359
+ `</form></dialog>`,
360
+ `<script>${SCRIPT}</script>`,
361
+ `</body>`,
362
+ `</html>`,
363
+ ``,
364
+ ].join("\n");
365
+ }
366
+ const figure = (picture, caption = picture.shows ?? "") => `<figure><a href="${escapeHtml(picture.url)}" target="_blank" rel="noopener"><img loading="lazy" src="${escapeHtml(picture.url)}" alt="${escapeHtml(caption)}"></a><figcaption>${escapeHtml(caption)}</figcaption></figure>`;
367
+ const list = (title, items) => (items.length ? `<h3>${title}</h3><ul>${items.map((item) => `<li>${escapeHtml(item)}</li>`).join("")}</ul>` : "");
368
+ /** Each chosen picture beside the same view filmed in game, or a note that there is no usable frame of it. */
369
+ const pairHtml = (picture) => `<div class="pair">${figure(picture)}${picture.inGame ? figure(picture.inGame, `in game: ${picture.shows}`) : `<div class="missing">no frame of this view filmed in game</div>`}</div>`;
370
+ /** One set's page: its look in full, its pictures beside their frames in game, its plan and overview, and what its look rests on. */
371
+ export function setPage(card) {
372
+ const { look } = card;
373
+ return [
374
+ `<!doctype html>`,
375
+ `<html lang="en">`,
376
+ `<head>`,
377
+ `<meta charset="utf-8">`,
378
+ `<meta name="viewport" content="width=device-width, initial-scale=1">`,
379
+ `<title>${escapeHtml(card.name)} · Set Finder</title>`,
380
+ `<link rel="icon" href="data:,">`,
381
+ `<style>${STYLE}</style>`,
382
+ `</head>`,
383
+ `<body><div class="detail">`,
384
+ `<p><a href="/">← Set Finder</a></p>`,
385
+ `<h1>${escapeHtml(card.name)} <small style="font-weight:normal;color:var(--dim)">${escapeHtml(card.id)}</small></h1>`,
386
+ `<p class="facts"><span class="badge">${escapeHtml(look.kind)}</span><span>${escapeHtml(card.source)}</span><span>${escapeHtml(sizeLine(card))}</span><span>look: ${escapeHtml(look.confidence)} confidence</span></p>`,
387
+ `<p>${escapeHtml(look.look)}</p>`,
388
+ `<p class="facets">${look.facets.map((facet) => `<span>${escapeHtml(facet)}</span>`).join("")}</p>`,
389
+ list("Could stand in for", look.standsInFor),
390
+ list("Places in it", look.rooms ?? []),
391
+ card.pictures.length ? `<h3>The chosen pictures, and the same views in game</h3>${card.pictures.map(pairHtml).join("")}` : "",
392
+ `<h3>Plan and overview</h3><div class="grid">${card.views.map((view) => figure(view)).join("")}</div>`,
393
+ list("Problems with the pictures", look.problems),
394
+ `<p class="uses">Look written from: ${escapeHtml(look.basis)}</p>`,
395
+ `<h3>Where it is</h3><ul>${look.files.map((file) => `<li><code>${escapeHtml(file)}</code></li>`).join("")}</ul>`,
396
+ `</div></body>`,
397
+ `</html>`,
398
+ ``,
399
+ ].join("\n");
400
+ }
@@ -0,0 +1,12 @@
1
+ import { type FinderServer, type FinderServerOptions as KitFinderServerOptions } from "@team-antioch/sc2-finder-kit/server.js";
2
+ import type { SetCard } from "./cards.ts";
3
+ import type { SetFinder } from "./finder.ts";
4
+ export { failureText, type FinderServer, type TickLogLine, type TrayAction, type TrayActionContext, type TrayActionInput, type TrayActionResult, } from "@team-antioch/sc2-finder-kit/server.js";
5
+ /** The port the page is at unless another is asked for: the Doodad Finder's is 4634 and the Music Finder's 4635. */
6
+ export declare const SET_FINDER_PORT = 4636;
7
+ /** The pictures a layer's folder may serve for a set, as the gallery names them. */
8
+ export declare const LOCAL_PICTURE: RegExp;
9
+ export type SetServerOptions = Omit<KitFinderServerOptions<SetCard>, "kind" | "finder" | "badges" | "objects"> & {
10
+ readonly finder: Pick<SetFinder, "narrow" | "cards">;
11
+ };
12
+ export declare function startSetFinderServer(options: SetServerOptions): Promise<FinderServer>;