Two tabs and a cog: settings shell, one ranking, a script per page, the phone frame

The top bar is Roles and Applications plus health's cog. Behind the cog,
/settings/{ranking,searches,companies,pulls,messages,account} share one row
of sub-tabs, an underlined row on a desktop and pills on a phone. The old
paths answer 301 with their query string.

Ranking edits the first enabled agent, or creates one, with the intent,
the weights and the gates under Advanced. The order menu on Roles reads
Newest and Best match with one enabled agent, and names them with several.
config.yaml keeps the Copenhagen starter; the other two are commented
examples in config.example.yaml.

roles.js is split into roles.js, applications.js, ranking.js and
companies.js; count, cell, debounce, the company list and the affinity
control live once in app.js. app.css gets the phone frame after health and
newsdesk: one-row bar, edge-to-edge panels, 44px targets and 16px fields on
a coarse pointer, hover only where there is one, safe areas. The app is
installable from a manifest and roledesk-coloured icons. Every lede touched
is written for the person using the app.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Opus 5.5 committed 2026-09-25 21:29:06 +02:00
1 parent 8c4bc3112a
commit 7d31cca394
34 files changed
+848 -565

No files matched your search

+119 -14
View File
@@ -1,11 +1,14 @@
/* The whole stylesheet: the boilerplate's, with roledesk's palette in the
* custom properties (a quiet UI face and newsdesk's teal signal colour) and
* roledesk's own tabs in the section at the bottom. No build step.
* custom properties (a quiet UI face and newsdesk's teal signal colour), the
* frame (a top bar of two tabs and a cog, the settings sub-tabs), roledesk's
* own pages, and at the bottom the phone: a width query for the layout and a
* pointer query for the sizes, after newsdesk and health. No build step.
*
* The `--desk-jobs-*` block at the bottom is how `<desk-jobs>` is themed. The
* element keeps to a shadow root and reads those properties, so an app skins
* it without forking it -- which is the deal that lets the queue ship its own
* UI and still look like it belongs here.
* The `--desk-jobs-*` block is how `<desk-jobs>`, `<desk-schedules>` and
* `<auth-account>` are themed. Each keeps to a shadow root and reads those
* properties, so an app skins it without forking it -- which is the deal
* that lets the queue ship its own UI and still look like it belongs here --
* and the app cannot lay it out beyond that.
*/
:root {
@@ -45,6 +48,8 @@
}
* { box-sizing: border-box; }
/* `hidden` has to win over any class that sets `display`, such as `.check`. */
[hidden] { display: none !important; }
body {
margin: 0;
@@ -65,6 +70,8 @@ a { color: var(--accent); }
gap: var(--gap);
flex-wrap: wrap;
padding: 0.75rem 1.25rem;
/* Standalone on a phone with a notch: the bar clears the status area. */
padding-top: calc(0.75rem + env(safe-area-inset-top));
background: var(--panel);
border-bottom: 1px solid var(--line);
position: sticky;
@@ -80,7 +87,7 @@ a { color: var(--accent); }
color: var(--fg);
}
.top nav { display: flex; gap: 0.25rem; flex-wrap: wrap; }
.top nav { display: flex; gap: 0.25rem; flex-wrap: wrap; align-items: center; }
.top nav a {
padding: 0.35rem 0.7rem;
@@ -88,13 +95,40 @@ a { color: var(--accent); }
text-decoration: none;
color: var(--dim);
}
.top nav a:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); }
/* The cog: an SVG, centred in a box the height of a word. */
.top nav a.icon { display: inline-flex; align-items: center; padding-block: 0.45rem; }
/* Hover needs a pointer to hover with, and a phone has none: it fakes one on
the element last touched and leaves it there, so a tapped tab would keep a
tint it has no reason to have (newsdesk's app.css says the same). Every
`:hover` in this file is inside one of these. */
@media (hover: hover) {
.top nav a:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); }
}
.top nav a.active { background: var(--accent); color: var(--accent-fg); }
/* The settings sub-tabs, health's: an underlined row here, pills on a phone. */
.subtabs {
display: flex; gap: 4px; margin: 4px 0 14px;
border-bottom: 1px solid var(--line);
}
.subtabs a {
padding: 7px 12px;
color: var(--dim);
font-weight: 500;
text-decoration: none;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
}
@media (hover: hover) {
.subtabs a:hover { color: var(--fg); }
}
.subtabs a.active { color: var(--accent); border-bottom-color: var(--accent); }
main {
max-width: 62rem;
margin: 0 auto;
padding: 1.5rem 1.25rem 4rem;
padding-bottom: calc(4rem + env(safe-area-inset-bottom));
}
h1 { font-size: 1.6rem; margin: 0 0 0.5rem; }
@@ -243,11 +277,14 @@ desk-jobs, desk-schedules, auth-account {
--desk-jobs-gap: var(--gap);
--desk-jobs-radius: var(--radius);
}
/* The schedule table has no narrow layout of its own yet, and what overflows
a shadow root widens the page. It scrolls inside its own box instead. */
desk-schedules { overflow-x: auto; }
/* -- roledesk's tabs ------------------------------------------------------ */
/* Roles, Applications, Agents and Companies, drawn by static/roles.js. */
input, select, textarea { font: inherit; color: inherit; }
input, select, textarea { font: inherit; color: inherit; min-width: 0; max-width: 100%; }
.filters {
display: flex; flex-wrap: wrap; gap: .5rem; align-items: center;
@@ -266,7 +303,6 @@ input, select, textarea { font: inherit; color: inherit; }
display: flex; align-items: center; gap: .35rem;
color: var(--dim); font-size: .9rem; white-space: nowrap;
}
.check[hidden] { display: none; }
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible,
textarea:focus-visible {
@@ -285,7 +321,9 @@ textarea:focus-visible {
}
.role-main { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; }
.role-title { font-weight: 600; text-decoration: none; }
.role-title:hover { text-decoration: underline; }
@media (hover: hover) {
.role-title:hover { text-decoration: underline; }
}
.role-company { color: var(--dim); }
.role-meta {
display: flex; flex-wrap: wrap; align-items: center; gap: .5rem;
@@ -346,11 +384,15 @@ textarea:focus-visible {
background: var(--bg); border: 1px solid var(--line);
border-radius: .3rem; padding: .35rem .5rem; width: 100%;
}
.agent-form textarea { font-family: var(--mono); font-size: .85rem; }
/* Prose in a textarea is read in the page face; JSON is in the mono one. */
.agent-form textarea.code { font-family: var(--mono); font-size: .85rem; }
.agent-form .hint { color: var(--dim); font-size: .8rem; overflow-wrap: anywhere; }
.weights { display: flex; gap: .75rem; flex-wrap: wrap; border: 1px solid var(--line); border-radius: .3rem; }
.weights label { flex: 1 1 6rem; }
/* A label that wraps to two lines pushes its box down; the boxes stay in line. */
.weights label { flex: 1 1 6rem; justify-content: space-between; }
.agent-actions { display: flex; gap: .5rem; flex-wrap: wrap; }
.agent-form details summary { cursor: pointer; color: var(--dim); font-size: .9rem; }
.agent-form details[open] summary { margin-bottom: .5rem; }
/* sources */
@@ -365,7 +407,6 @@ textarea:focus-visible {
border-radius: .3rem; padding: .35rem .5rem;
}
.source-form input[type="number"] { max-width: 6rem; }
.source-form [hidden] { display: none; }
.sample { margin: 0; padding-left: 1.25rem; font-size: .9rem; }
.sample li { margin: .15rem 0; }
.mono { font-family: var(--mono); overflow-wrap: anywhere; }
@@ -399,3 +440,67 @@ table.list select { padding: .25rem .4rem; }
@media (max-width: 480px) {
.role-age, .role-main .affinity { margin-left: 0; }
}
/* -- the phone ------------------------------------------------------------ */
/* Two axes, and deliberately not the same one, as in newsdesk: width decides
the layout, pointer decides the sizes. A tablet is wide and touched, a
half-screen laptop window is narrow and moused, and sizing either by width
puts it in the other's clothes. */
@media (max-width: 640px) {
main { padding: 10px 10px calc(3rem + env(safe-area-inset-bottom)); }
h1 { font-size: 1.25rem; }
/* The bar stays one row: the brand keeps its word, the two tabs share what
is left, and the cog keeps its own width rather than a share. */
.top { flex-wrap: nowrap; gap: .5rem; padding: calc(4px + env(safe-area-inset-top)) .6rem 4px; }
.top nav { flex: 1; flex-wrap: nowrap; gap: .15rem; min-width: 0; }
.top nav a { flex: 1 1 auto; text-align: center; padding: .6rem .4rem; white-space: nowrap; }
.top nav a.icon { flex: 0 0 auto; justify-content: center; padding-inline: .7rem; }
/* Six sub-tabs are too many for one row, and a scrolling strip does not
show that more are off the edge. They wrap, three to a row, as pills
rather than the desktop's underlined row. */
.subtabs { flex-wrap: wrap; border-bottom: none; gap: 6px; }
.subtabs a {
flex: 1 1 30%;
padding: 7px 4px;
border-radius: 999px;
border-bottom: none;
margin-bottom: 0;
background: var(--panel);
text-align: center;
font-size: .85rem;
}
.subtabs a.active { background: var(--accent); color: var(--accent-fg); }
/* A panel runs to both edges of the screen: no side margin, border or
rounded corner, so the content keeps all but its own 10 pixels of the
width. The page background between two panels reads as a band. */
.card, .filters, .agent-form, .note {
margin-inline: -10px; border-radius: 0; border-inline: 0;
}
.card { padding: .8rem 10px; }
.row-between { flex-wrap: wrap; }
}
/* The band between two full-width panels needs more contrast than the light
page background gives a white panel; the dark one is already distinct. */
@media (max-width: 640px) and (prefers-color-scheme: light) {
:root { --bg: #e1e5e8; }
}
/* Sizes for a finger. 2.75rem is 44px at the default root size, the smallest
target a thumb hits without aiming. */
@media (pointer: coarse) {
/* Under 16px, iOS Safari zooms the page when a field takes focus, and does
not zoom back out when it loses it. */
input, select, textarea { font-size: 16px; }
button, .top nav a, .subtabs a { min-height: 2.75rem; }
.top nav a, .subtabs a { display: inline-flex; align-items: center; justify-content: center; }
.filters input[type="search"], .filters input[type="text"], .filters select,
.agent-form input, .source-form select { min-height: 2.75rem; }
.affinity button { min-width: 2.25rem; }
.check input { width: 1.25rem; height: 1.25rem; }
}
+91 -1
View File
@@ -12,6 +12,11 @@
*
* `body` may be a plain object; it is JSON-encoded with the header set, since
* forgetting the header is the failure that looks like a server bug.
*
* Beside `api` on `window`, the few helpers more than one page script uses:
* `count`, `cell`, `debounce`, and the company list with its affinity control
* (`loadCompanies`, `companies`, `affinityControl`, `setAffinity`). One copy
* each, since two copies of a helper is one of them being fixed.
*/
(function () {
@@ -69,5 +74,90 @@
window.toast.error(String(detail));
});
window.api = api;
// ----------------------------------------------------------------- helpers
/** `count(3, "role")` is "3 roles"; `many` for an irregular plural. */
function count(n, one, many) {
return `${n} ${n === 1 ? one : many || `${one}s`}`;
}
/** A `<td>` with its column name in `data-label`, which the phone layout
prints above the value once the table's head is hidden. */
function cell(tr, label, content) {
const td = document.createElement("td");
td.dataset.label = label;
if (typeof content === "string") td.textContent = content;
else td.appendChild(content);
tr.appendChild(td);
return td;
}
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
// --------------------------------------------------------------- companies
/** @type {Map<string, object>} company_key -> row from /api/companies. One
Map, refilled in place, so a script holding it sees every reload. */
const companies = new Map();
async function loadCompanies() {
const rows = await api("/api/companies");
companies.clear();
for (const c of rows) companies.set(c.key, c);
return companies;
}
const AFFINITY_LEVELS = [
{ value: -1, label: "Mute" },
{ value: 0, label: "Neutral" },
{ value: 1, label: "Like" },
{ value: 2, label: "Favourite" },
];
/* The four buttons. `onChange` runs after the server accepted the change,
so each page decides what a change means for it: the role list refetches,
since muting changes which roles come back, and the company table redraws. */
function affinityControl(companyKey, current, onChange) {
const span = document.createElement("span");
span.className = "affinity";
span.setAttribute("role", "group");
span.setAttribute("aria-label", "Company affinity");
for (const level of AFFINITY_LEVELS) {
const button = document.createElement("button");
button.type = "button";
button.dataset.value = String(level.value);
button.textContent = level.label[0];
button.title = level.label;
button.setAttribute("aria-label", level.label);
button.setAttribute("aria-pressed", String(level.value === current));
button.addEventListener("click", () => setAffinity(companyKey, level.value, onChange));
span.appendChild(button);
}
return span;
}
async function setAffinity(companyKey, affinity, onChange) {
if (!companyKey) return;
let updated;
try {
updated = await api(`/api/companies/${encodeURIComponent(companyKey)}/affinity`, {
method: "POST", body: { affinity },
});
} catch (err) {
return;
}
const company = companies.get(companyKey);
if (company) company.affinity = updated.affinity;
if (onChange) await onChange();
}
Object.assign(window, {
api, count, cell, debounce, companies, loadCompanies, affinityControl, setAffinity,
});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

+76
View File
@@ -0,0 +1,76 @@
/* The Applications tab: every saved role and its status.
*
* The template renders an empty table; the rows come from /api/applications
* and a status change is a fetch through `api()` from app.js, which toasts a
* refusal. The company names come from app.js's shared company list.
*/
(function () {
"use strict";
const { api, count, cell, companies, loadCompanies } = window;
const $ = (sel, root = document) => root.querySelector(sel);
// `ROLEDESK_STATUSES` is set by applications.html from the same `STATUSES`
// tuple the store validates against, so this list can never drift from
// what a `POST .../status` will accept.
function statusSelect(current) {
const select = document.createElement("select");
for (const status of window.ROLEDESK_STATUSES) {
const option = document.createElement("option");
option.value = status;
option.textContent = status[0].toUpperCase() + status.slice(1);
option.selected = status === current;
select.appendChild(option);
}
return select;
}
function render(applications) {
const body = $("#applications-list");
body.replaceChildren();
for (const application of applications) {
const tr = document.createElement("tr");
if (application.url) {
const link = document.createElement("a");
link.href = application.url;
link.target = "_blank";
link.rel = "noopener";
link.textContent = application.role_title || "(untitled)";
cell(tr, "Role", link);
} else {
cell(tr, "Role", application.role_title || "(untitled)");
}
const company = companies.get(application.company_key);
cell(tr, "Company", company ? company.name : application.company_key);
const select = statusSelect(application.status);
select.addEventListener("change", () => setStatus(application.id, select));
cell(tr, "Status", select);
cell(tr, "Next", [application.next_action, application.next_date]
.filter(Boolean).join(" · "));
body.appendChild(tr);
}
$("#applications-count").textContent =
count(applications.length, "tracked application");
}
async function setStatus(id, select) {
select.disabled = true;
try {
await api(`/api/applications/${encodeURIComponent(id)}/status`, {
method: "POST", body: { status: select.value },
});
render(await api("/api/applications"));
} catch (err) {
select.disabled = false;
}
}
document.addEventListener("DOMContentLoaded", async () => {
try {
const [, applications] = await Promise.all([loadCompanies(), api("/api/applications")]);
render(applications);
} catch (err) {
/* already toasted */
}
});
})();
+50
View File
@@ -0,0 +1,50 @@
/* The Companies page: every company, its open roles, and its affinity.
*
* The list is app.js's shared company list, and the affinity buttons are its
* `affinityControl`, the same ones the Roles tab draws on every row. Filtering
* is done here, over the list already loaded.
*/
(function () {
"use strict";
const { count, cell, debounce, companies, loadCompanies, affinityControl } = window;
const $ = (sel, root = document) => root.querySelector(sel);
function render() {
const q = $("#c-q").value.trim().toLowerCase();
const affinity = $("#c-affinity").value;
const rows = [...companies.values()]
.filter((c) => !q || c.name.toLowerCase().includes(q) || c.board.includes(q))
.filter((c) => affinity === "" || String(c.affinity) === affinity)
.sort((a, b) => b.open_roles - a.open_roles || a.name.localeCompare(b.name));
const body = $("#companies-list");
body.replaceChildren();
for (const company of rows) {
const tr = document.createElement("tr");
if (company.affinity === -1) tr.classList.add("muted");
const link = document.createElement("a");
link.href = `/?company=${encodeURIComponent(company.name)}`;
link.title = "This company's open roles";
link.textContent = company.name;
cell(tr, "Company", link);
cell(tr, "Board", company.board || "");
cell(tr, "Open roles", String(company.open_roles)).className = "num";
cell(tr, "Affinity", affinityControl(company.key, company.affinity, async () => render()));
body.appendChild(tr);
}
const open = rows.reduce((sum, c) => sum + c.open_roles, 0);
$("#companies-count").textContent =
`${count(rows.length, "company", "companies")}, ${count(open, "open role")}`;
}
document.addEventListener("DOMContentLoaded", async () => {
try {
await loadCompanies();
} catch (err) {
return;
}
render();
$("#c-q").addEventListener("input", debounce(render, 150));
$("#c-affinity").addEventListener("change", render);
});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

+25
View File
@@ -0,0 +1,25 @@
<!-- newsdesk's mark, three tracks filled from the bottom, in roledesk's
accent on roledesk's light page: a ranking at a glance. This is the source
of truth for the mark; icon-192, icon-512 and apple-touch-icon are the
same geometry rasterised, because a home screen will not take an SVG
everywhere. (No double hyphen anywhere in here: an SVG is parsed as XML,
where that is illegal inside a comment and kills the whole file.) -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<rect width="512" height="512" fill="#eceff1"/>
<defs>
<clipPath id="a"><rect x="116" y="116" width="56" height="280" rx="28"/></clipPath>
<clipPath id="b"><rect x="228" y="116" width="56" height="280" rx="28"/></clipPath>
<clipPath id="c"><rect x="340" y="116" width="56" height="280" rx="28"/></clipPath>
</defs>
<g clip-path="url(#a)">
<rect x="116" y="116" width="56" height="280" fill="#cfd6db"/>
<rect x="116" y="278" width="56" height="118" fill="#14655b"/>
</g>
<g clip-path="url(#b)">
<rect x="228" y="116" width="56" height="280" fill="#cfd6db"/>
<rect x="228" y="206" width="56" height="190" fill="#14655b"/>
</g>
<g clip-path="url(#c)">
<rect x="340" y="116" width="56" height="280" fill="#14655b"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
/* The Jobs tab: a button per kind.
/* The Pulls page: a button per kind.
*
* The list comes from `/api/jobs/kinds`, which is the registry, so a new
* `@job` in `app/jobs.py` is a new button and this file is not edited. What
+17
View File
@@ -0,0 +1,17 @@
{
"name": "roledesk",
"short_name": "roledesk",
"description": "Job postings from boards and searches, ranked against what you are looking for.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#eceff1",
"theme_color": "#ffffff",
"icons": [
{"src": "/static/icon-192.png", "sizes": "192x192", "type": "image/png"},
{"src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png"},
{"src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png",
"purpose": "maskable"},
{"src": "/static/icon.svg", "sizes": "any", "type": "image/svg+xml"}
]
}
+134
View File
@@ -0,0 +1,134 @@
/* The Ranking page: what Best match on the Roles tab is measured against.
*
* The UI shows one ranking. Underneath it is the first enabled search agent,
* the oldest by id, since the `agents` table still holds as many as the CLI
* or the config put there; this page edits that one and never lists, adds or
* deletes. An empty table gets its first agent on the first save.
*
* Every request goes through `api()` from app.js, so a failure is one toast
* carrying the server's own sentence.
*/
(function () {
"use strict";
const { api, count } = window;
const $ = (sel, root = document) => root.querySelector(sel);
/** The name a ranking made here is saved under; the UI never shows it
unless the CLI adds a second one. */
const NEW_NAME = "My ranking";
const DEFAULT_WEIGHTS = { fit: 0.6, recency: 0.2, affinity: 0.2 };
/** @type {object | null} the agent this page edits, null until one is saved */
let agent = null;
/* The first enabled agent, else the first at all: editing it here means it
is wanted, so a save switches it on. */
function pick(agents) {
const byId = [...agents].sort((a, b) => a.id - b.id);
return byId.find((a) => a.enabled) || byId[0] || null;
}
function fill(others) {
$("#a-intent").value = agent ? agent.intent : "";
$("#a-gates").value = JSON.stringify(agent ? agent.gates : [], null, 2);
const weights = agent ? agent.weights : DEFAULT_WEIGHTS;
$("#a-fit").value = weights.fit;
$("#a-recency").value = weights.recency;
$("#a-affinity").value = weights.affinity;
const note = $("#ranking-others");
note.hidden = !(agent && others > 0);
if (!note.hidden) {
note.textContent = `This edits "${agent.name}". ${count(others, "other ranking")} `
+ "can be picked by name in the order menu on Roles.";
}
}
async function save(event) {
event.preventDefault();
const status = $("#ranking-status");
let gates;
try {
gates = JSON.parse($("#a-gates").value || "[]");
} catch (err) {
window.toast.error(`Gates are not valid JSON: ${err.message}`);
return;
}
const body = {
name: agent ? agent.name : NEW_NAME,
intent: $("#a-intent").value,
gates,
weights: {
fit: Number($("#a-fit").value),
recency: Number($("#a-recency").value),
affinity: Number($("#a-affinity").value),
},
enabled: true,
};
if (agent) body.id = agent.id;
const button = $("#ranking-form button[type=submit]");
button.disabled = true;
try {
agent = await api("/api/agents", { method: "POST", body });
} catch (err) {
status.textContent = "";
button.disabled = false;
return;
}
await rescore(status);
button.disabled = false;
}
// Start the `score` job and wait for it, so "Saved and scored" means the
// Roles tab already orders by what was saved.
async function rescore(status) {
status.textContent = "Saved. Scoring…";
let job;
try {
job = await api("/api/jobs", { method: "POST", body: { kind: "score", payload: {} } });
} catch (err) {
status.textContent = "Saved, but scoring did not start.";
return;
}
for (let i = 0; i < 300; i += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
let snapshot;
try {
snapshot = await api("/api/jobs");
} catch (err) {
return;
}
const busy = [...snapshot.running, ...snapshot.queued].some((j) => j.id === job.id);
if (busy) continue;
const done = snapshot.recent.find((j) => j.id === job.id);
if (done && done.state !== "done") {
status.textContent = `Saved. Scoring ${done.state}.`;
if (done.error) window.toast.error(`Scoring ${done.state}: ${done.error}`);
return;
}
status.replaceChildren("Saved and scored. ");
const link = document.createElement("a");
link.href = `/?agent=${agent.id}`;
link.textContent = "See the best matches";
status.appendChild(link);
return;
}
status.replaceChildren("Saved. Scoring is still running; ");
const link = document.createElement("a");
link.href = "/settings/pulls";
link.textContent = "follow it under Pulls";
status.append(link, ".");
}
document.addEventListener("DOMContentLoaded", async () => {
let agents;
try {
agents = await api("/api/agents");
} catch (err) {
return;
}
agent = pick(agents);
fill(agents.filter((a) => a.enabled && (!agent || a.id !== agent.id)).length);
$("#ranking-form").addEventListener("submit", save);
});
})();
+16 -352
View File
@@ -1,10 +1,9 @@
/* roledesk's four tabs: Roles, Applications, Agents and Companies.
/* The Roles tab: the filter bar and the list of open roles.
*
* Each template renders an empty shell; everything on screen comes from the
* JSON routes in app/web/api.py, and every action (Save, an affinity click, a
* status change, an agent saved) is a fetch from here, not a form post. One
* script for the four, because they share the company list and the affinity
* control; `init` looks at which containers the page has.
* The template renders an empty shell; everything on screen comes from the
* JSON routes in app/web/api.py, and every action (Save, an affinity click)
* is a fetch from here, not a form post. The company list and its affinity
* control are app.js's, shared with the Companies page.
*
* Every request goes through `api()` from app.js, so a failure is one toast
* carrying the server's own sentence. The catch blocks here only put the
@@ -13,103 +12,26 @@
(function () {
"use strict";
const api = window.api;
const { api, count, debounce, companies, loadCompanies, affinityControl } = window;
/** @type {Map<string, object>} company_key -> row from /api/companies */
let companies = new Map();
/** @type {Map<string, object>} role_uid -> application, for roles already tracked */
let trackedByRole = new Map();
/** @type {object[]} the last /api/roles response, already muted-filtered by the server */
let roles = [];
/** @type {object[]} every search agent, from /api/agents */
/** @type {object[]} the enabled rankings, from /api/agents */
let agents = [];
const $ = (sel, root = document) => root.querySelector(sel);
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
function count(n, one, many) {
return `${n} ${n === 1 ? one : many || `${one}s`}`;
}
async function loadCompanies() {
const rows = await api("/api/companies");
companies = new Map(rows.map((c) => [c.key, c]));
}
async function loadApplications() {
const applications = await api("/api/applications");
trackedByRole = new Map(applications.filter((a) => a.role_uid).map((a) => [a.role_uid, a]));
return applications;
}
async function loadAgents() {
agents = await api("/api/agents");
agents = (await api("/api/agents")).filter((a) => a.enabled);
}
function cell(tr, label, content) {
const td = document.createElement("td");
td.dataset.label = label;
if (typeof content === "string") td.textContent = content;
else td.appendChild(content);
tr.appendChild(td);
return td;
}
// ---------------------------------------------------------------- affinity
const AFFINITY_LEVELS = [
{ value: -1, label: "Mute" },
{ value: 0, label: "Neutral" },
{ value: 1, label: "Like" },
{ value: 2, label: "Favourite" },
];
/* The four buttons. `onChange` runs after the server accepted the change,
so each tab decides what a change means for it: the role list refetches,
since muting changes which roles come back, and the company table redraws. */
function affinityControl(companyKey, current, onChange) {
const span = document.createElement("span");
span.className = "affinity";
span.setAttribute("role", "group");
span.setAttribute("aria-label", "Company affinity");
for (const level of AFFINITY_LEVELS) {
const button = document.createElement("button");
button.type = "button";
button.dataset.value = String(level.value);
button.textContent = level.label[0];
button.title = level.label;
button.setAttribute("aria-label", level.label);
button.setAttribute("aria-pressed", String(level.value === current));
button.addEventListener("click", () => setAffinity(companyKey, level.value, onChange));
span.appendChild(button);
}
return span;
}
async function setAffinity(companyKey, affinity, onChange) {
if (!companyKey) return;
let updated;
try {
updated = await api(`/api/companies/${encodeURIComponent(companyKey)}/affinity`, {
method: "POST", body: { affinity },
});
} catch (err) {
return;
}
const company = companies.get(companyKey);
if (company) company.affinity = updated.affinity;
await onChange();
}
// ------------------------------------------------------------------- roles
function filterParams() {
const params = new URLSearchParams();
for (const key of ["q", "company", "place"]) {
@@ -171,7 +93,7 @@
if (role.score !== null && role.score !== undefined) {
const badge = node.querySelector(".role-score");
badge.textContent = role.gated_reason ? "gated" : role.score.toFixed(2);
badge.title = "Score for the selected agent";
badge.title = "Match";
node.querySelector(".role-gated").textContent = role.gated_reason || "";
if (role.gated_reason) li.classList.add("gated");
}
@@ -210,14 +132,16 @@
}
}
// The filter bar's order: "Newest", or one agent's score. Keeps the current
// choice when the list is refreshed, unless that agent is gone.
/* The filter bar's order: Newest, or a ranking's score. One ranking is the
ordinary case and reads "Best match"; more than one only comes from the
CLI or the config, and then each is listed by name so none is lost. Keeps
the current choice when the list is refreshed, unless that one is gone. */
function renderAgentSelect() {
const select = $("#f-agent");
const current = select.value;
select.replaceChildren(new Option("Newest", ""));
for (const agent of agents) {
const label = agent.enabled ? agent.name : `${agent.name} (off)`;
const label = agents.length === 1 ? "Best match" : agent.name;
select.appendChild(new Option(label, String(agent.id)));
}
select.value = agents.some((a) => String(a.id) === current) ? current : "";
@@ -225,7 +149,7 @@
}
/* `?q=`, `?company=`, `?place=` and `?agent=` prefill the filter bar, which
is how the Companies and Agents tabs link into this one. */
is how the Companies and Ranking pages link into this one. */
function prefill() {
const query = new URLSearchParams(location.search);
for (const key of ["q", "company", "place"]) {
@@ -238,7 +162,7 @@
}
}
async function initRoles() {
document.addEventListener("DOMContentLoaded", async () => {
try {
await Promise.all([loadCompanies(), loadApplications(), loadAgents()]);
} catch (err) {
@@ -260,265 +184,5 @@
loadRoles();
});
$("#filters").addEventListener("submit", (e) => e.preventDefault());
}
// ------------------------------------------------------------ applications
// `ROLEDESK_STATUSES` is set by applications.html from the same `STATUSES`
// tuple the store validates against, so this list can never drift from
// what a `POST .../status` will accept.
function statusSelect(current) {
const select = document.createElement("select");
for (const status of window.ROLEDESK_STATUSES) {
const option = document.createElement("option");
option.value = status;
option.textContent = status[0].toUpperCase() + status.slice(1);
option.selected = status === current;
select.appendChild(option);
}
return select;
}
function renderApplications(applications) {
const body = $("#applications-list");
body.replaceChildren();
for (const application of applications) {
const tr = document.createElement("tr");
if (application.url) {
const link = document.createElement("a");
link.href = application.url;
link.target = "_blank";
link.rel = "noopener";
link.textContent = application.role_title || "(untitled)";
cell(tr, "Role", link);
} else {
cell(tr, "Role", application.role_title || "(untitled)");
}
const company = companies.get(application.company_key);
cell(tr, "Company", company ? company.name : application.company_key);
const select = statusSelect(application.status);
select.addEventListener("change", () => setStatus(application.id, select));
cell(tr, "Status", select);
cell(tr, "Next", [application.next_action, application.next_date]
.filter(Boolean).join(" · "));
body.appendChild(tr);
}
$("#applications-count").textContent =
count(applications.length, "tracked application");
}
async function setStatus(id, select) {
select.disabled = true;
try {
await api(`/api/applications/${encodeURIComponent(id)}/status`, {
method: "POST", body: { status: select.value },
});
renderApplications(await loadApplications());
} catch (err) {
select.disabled = false;
}
}
async function initApplications() {
try {
const [, applications] = await Promise.all([loadCompanies(), loadApplications()]);
renderApplications(applications);
} catch (err) {
/* already toasted */
}
}
// ------------------------------------------------------------------ agents
function renderAgents() {
const list = $("#agents-list");
list.replaceChildren();
for (const agent of agents) {
const li = document.createElement("li");
li.className = "agent";
const name = document.createElement("a");
name.href = `/?agent=${agent.id}`;
name.title = "Roles, ordered by this agent's score";
name.textContent = agent.name;
const meta = document.createElement("span");
meta.className = "agent-meta";
const gates = agent.gates.map((g) => `${g.mode} ${g.field}`).join(", ") || "no gates";
meta.textContent = `${agent.enabled ? "" : "off · "}${gates}`;
const edit = document.createElement("button");
edit.type = "button";
edit.className = "secondary";
edit.textContent = "Edit";
edit.addEventListener("click", () => fillAgentForm(agent));
li.append(name, meta, edit);
list.appendChild(li);
}
$("#agents-count").textContent = count(agents.length, "agent");
}
function fillAgentForm(agent) {
$("#agent-form-title").textContent = agent ? `Edit ${agent.name}` : "New agent";
$("#a-id").value = agent ? String(agent.id) : "";
$("#a-name").value = agent ? agent.name : "";
$("#a-intent").value = agent ? agent.intent : "";
$("#a-gates").value = JSON.stringify(agent ? agent.gates : [], null, 2);
const weights = agent ? agent.weights : { fit: 0.6, recency: 0.2, affinity: 0.2 };
$("#a-fit").value = weights.fit;
$("#a-recency").value = weights.recency;
$("#a-affinity").value = weights.affinity;
$("#a-enabled").checked = agent ? agent.enabled : true;
$("#a-delete").hidden = !agent;
$("#agent-status").textContent = "";
}
async function saveAgent(event) {
event.preventDefault();
const status = $("#agent-status");
let gates;
try {
gates = JSON.parse($("#a-gates").value || "[]");
} catch (err) {
window.toast.error(`Gates are not valid JSON: ${err.message}`);
return;
}
const id = $("#a-id").value;
const body = {
name: $("#a-name").value.trim(),
intent: $("#a-intent").value,
gates,
weights: {
fit: Number($("#a-fit").value),
recency: Number($("#a-recency").value),
affinity: Number($("#a-affinity").value),
},
enabled: $("#a-enabled").checked,
};
if (id) body.id = Number(id);
let saved;
try {
saved = await api("/api/agents", { method: "POST", body });
} catch (err) {
status.textContent = "";
return;
}
try {
await loadAgents();
renderAgents();
} catch (err) {
/* already toasted; the save itself landed */
}
fillAgentForm(saved);
await rescore(status, saved);
}
async function deleteAgent() {
const id = $("#a-id").value;
if (!id || !confirm("Delete this agent and its scores?")) return;
try {
await api(`/api/agents/${encodeURIComponent(id)}`, { method: "DELETE" });
fillAgentForm(null);
await loadAgents();
renderAgents();
} catch (err) {
/* already toasted */
}
}
// Start the `score` job and wait for it, so "Saved and scored" means the
// Roles tab already orders by what was saved.
async function rescore(status, agent) {
status.textContent = "Saved. Scoring…";
let job;
try {
job = await api("/api/jobs", { method: "POST", body: { kind: "score", payload: {} } });
} catch (err) {
status.textContent = "Saved, but scoring did not start.";
return;
}
for (let i = 0; i < 300; i += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
let snapshot;
try {
snapshot = await api("/api/jobs");
} catch (err) {
return;
}
const busy = [...snapshot.running, ...snapshot.queued].some((j) => j.id === job.id);
if (busy) continue;
const done = snapshot.recent.find((j) => j.id === job.id);
if (done && done.state !== "done") {
status.textContent = `Saved. Scoring ${done.state}.`;
if (done.error) window.toast.error(`Scoring ${done.state}: ${done.error}`);
return;
}
status.replaceChildren("Saved and scored. ");
const link = document.createElement("a");
link.href = `/?agent=${agent.id}`;
link.textContent = "See the roles";
status.appendChild(link);
return;
}
status.textContent = "Saved. Scoring is still running; see the Jobs tab.";
}
async function initAgents() {
try {
await loadAgents();
} catch (err) {
return;
}
renderAgents();
$("#agent-form").addEventListener("submit", saveAgent);
$("#a-new").addEventListener("click", () => fillAgentForm(null));
$("#a-delete").addEventListener("click", deleteAgent);
}
// --------------------------------------------------------------- companies
function renderCompanies() {
const q = $("#c-q").value.trim().toLowerCase();
const affinity = $("#c-affinity").value;
const rows = [...companies.values()]
.filter((c) => !q || c.name.toLowerCase().includes(q) || c.board.includes(q))
.filter((c) => affinity === "" || String(c.affinity) === affinity)
.sort((a, b) => b.open_roles - a.open_roles || a.name.localeCompare(b.name));
const body = $("#companies-list");
body.replaceChildren();
for (const company of rows) {
const tr = document.createElement("tr");
if (company.affinity === -1) tr.classList.add("muted");
const link = document.createElement("a");
link.href = `/?company=${encodeURIComponent(company.name)}`;
link.title = "This company's open roles";
link.textContent = company.name;
cell(tr, "Company", link);
cell(tr, "Board", company.board || "");
cell(tr, "Open roles", String(company.open_roles)).className = "num";
cell(tr, "Affinity",
affinityControl(company.key, company.affinity, async () => renderCompanies()));
body.appendChild(tr);
}
const open = rows.reduce((sum, c) => sum + c.open_roles, 0);
$("#companies-count").textContent =
`${count(rows.length, "company", "companies")}, ${count(open, "open role")}`;
}
async function initCompanies() {
try {
await loadCompanies();
} catch (err) {
return;
}
renderCompanies();
$("#c-q").addEventListener("input", debounce(renderCompanies, 150));
$("#c-affinity").addEventListener("change", renderCompanies);
}
// -------------------------------------------------------------------- init
document.addEventListener("DOMContentLoaded", () => {
if ($("#roles-list")) initRoles();
if ($("#applications-list")) initApplications();
if ($("#agents-list")) initAgents();
if ($("#companies-list")) initCompanies();
});
})();
+5 -25
View File
@@ -1,4 +1,5 @@
/* The Sources tab: saved searches, company boards, and the prune by region.
/* The Searches page under Settings: saved searches, and for now the company
* boards and the prune by region as well.
*
* The template is a shell; the lists come from /api/sources and every action
* is a fetch through `api()` from app.js, so a refusal (a search that finds
@@ -8,7 +9,7 @@
(function () {
"use strict";
const api = window.api;
const { api, count, cell, debounce } = window;
const $ = (sel, root = document) => root.querySelector(sel);
/** @type {{searches: object[], boards: object[], adzuna_key: boolean}} */
@@ -16,27 +17,6 @@
/** @type {object[]} the boards the last prune preview named */
let pruneBoards = [];
function count(n, one, many) {
return `${n} ${n === 1 ? one : many || `${one}s`}`;
}
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
function cell(tr, label, content) {
const td = document.createElement("td");
td.dataset.label = label;
if (typeof content === "string") td.textContent = content;
else td.appendChild(content);
tr.appendChild(td);
return td;
}
/** "DK 120 · EU 4 · unknown 2", the three biggest. */
function countries(source) {
const shown = source.countries.slice(0, 3)
@@ -331,8 +311,8 @@
await api("/api/jobs", { method: "POST", body: { kind: "pull", payload: {} } });
$("#pull-status").replaceChildren("Pull started. ");
const link = document.createElement("a");
link.href = "/jobs";
link.textContent = "Follow it on the Jobs tab";
link.href = "/settings/pulls";
link.textContent = "Follow it under Pulls";
$("#pull-status").appendChild(link);
} catch (err) {
/* already toasted */