Files
jobboard/app/static/roles.js
T
WolfandClaude Fable 5.1 09c5dde113 Roles as a feed, a read page, votes that move the rank, unstar
The Roles tab is news's feed row: the title opens /roles/{uid}, company,
place and age under it, the badges, a one-line excerpt (summary, else the
description's opening), and ▲ ● ▼ ★ on the right, under the text at 640px.
The company affinity control leaves the row. A passed role and a hidden
company's are dimmed and stay. The filter bar is one row: order, search and
a Filters <details> holding the rest, with a judged select and "Show hidden
companies". The list loads 60 and appends on an IntersectionObserver
sentinel; back from a read page restores the filters, rows and scroll.

GET /api/roles takes offset, defaults to 60 and answers {items, total}.
judged= is a WHERE on roles.vote. Under a ranking the served score and the
order are the stored score moved by the vote (x0.5 pass, x1.2 like, capped
at 1), so a vote shows at once without a rescore. POST and DELETE
/api/roles/{uid}/vote set and clear it; pressing the pressed stance clears.

★ saves; pressed again it calls DELETE /api/applications/{id}, which drops
the application while it is still saved and answers 409 after. save_role no
longer writes the placeholder next step.

The read page (role.html, role.js) is news's reader: a bar with back,
▲ ● ▼ ★ and ↗, the company with its affinity control, place, badges, salary,
summary, the text (fetched posting, else description) and the link out.
It offers Fetch the posting for a teaser and Summarise without a summary,
against the /text and /summarise routes B4 adds. The vote and star buttons
are judge.js, shared by the feed and the reader.

Applications: titles open the read page, the Next column is gone, a Saved
column instead, and the lede says what the page is for.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 21:51:48 +02:00

314 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* The Roles tab: the filter bar and the feed of open roles.
*
* The template renders an empty shell; everything on screen comes from the
* JSON routes in app/web/api.py. A row is news's feed row: the title (a link
* to the read page), company · place · age, the badges, a one-line excerpt,
* and ▲ ● ▼ ★ from judge.js. The company is not judged here; that is the
* Companies page and the read page.
*
* The list is paged: 60 rows, then 60 more each time a sentinel under the
* list comes within 600px of the screen (news's `loadFeed`), with the offset
* the rows already shown. Going back from a read page puts the same rows and
* the same scroll position back, from sessionStorage.
*
* 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, debounce, companies, loadCompanies, judgeButtons, loadTracked } = window;
const PAGE = 60;
/** What the list was when a read page was opened from it. */
const KEPT = "roledesk.roles";
/** @type {object[]} the rows on screen, in order */
let items = [];
/** How many roles the filters match in all. */
let total = 0;
/** @type {object[]} the enabled rankings, from /api/agents */
let agents = [];
let loading = false;
let request = 0;
const $ = (sel, root = document) => root.querySelector(sel);
const number = new Intl.NumberFormat("en");
/* Every field of the filter bar, by id, and what it holds when unset. */
const FIELDS = ["f-agent", "f-q", "f-company", "f-place", "f-function", "f-remote",
"f-days", "f-judged", "f-show-muted", "f-gated"];
/* The ones inside Filters, which the summary counts. */
const PANEL = ["f-company", "f-place", "f-function", "f-remote", "f-days", "f-judged",
"f-show-muted", "f-gated"];
const read = (id) => {
const el = document.getElementById(id);
return el.type === "checkbox" ? el.checked : el.value;
};
const write = (id, value) => {
const el = document.getElementById(id);
if (el.type === "checkbox") el.checked = Boolean(value);
else el.value = value;
};
async function loadAgents() {
agents = (await api("/api/agents")).filter((a) => a.enabled);
}
function filterParams() {
const params = new URLSearchParams();
for (const key of ["q", "company", "place"]) {
const value = $(`#f-${key}`).value.trim();
if (value) params.set(key, value);
}
for (const key of ["function", "remote", "days", "judged"]) {
const value = $(`#f-${key}`).value;
if (value) params.set(key, value);
}
if ($("#f-show-muted").checked) params.set("show_muted", "true");
const agent = $("#f-agent").value;
if (agent) {
params.set("agent", agent);
if ($("#f-gated").checked) params.set("gated", "1");
}
return params;
}
/* A reload starts the list again; an append asks for the rows after the
ones shown. `keep` asks for that many in one go, which is how the list is
put back as it was. The latch is let go only by the newest request: a
reload overtaking an append must not let a second append start with an
offset into the list being replaced. */
async function load({ append = false, keep = 0 } = {}) {
if (append && (loading || items.length >= total)) return;
const params = filterParams();
params.set("offset", String(append ? items.length : 0));
params.set("limit", String(Math.min(1000, Math.max(PAGE, keep))));
const mine = ++request;
loading = true;
let data;
try {
data = await api(`/api/roles?${params}`);
} catch (err) {
return;
} finally {
if (mine === request) loading = false;
}
if (mine !== request) return;
total = data.total;
if (append) {
items = items.concat(data.items);
renderRows(data.items);
} else {
items = data.items;
$("#roles-list").replaceChildren();
renderRows(items);
}
renderCount();
// Still within reach of the sentinel after a short page: the observer
// only fires on a change, and nothing changed, so ask again here.
requestAnimationFrame(() => {
const end = $("#roles-end").getBoundingClientRect();
if (end.top < window.innerHeight + 600) load({ append: true });
});
}
function reload() {
load().then(() => window.scrollTo(0, 0));
renderActive();
}
function relativeAge(iso) {
const then = new Date(iso);
const minutes = Math.max(0, Math.floor((Date.now() - then.getTime()) / 60000));
if (minutes < 60) return `${minutes} min ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} h ago`;
return `${Math.floor(hours / 24)} d ago`;
}
/* The summary when there is one, else the description's opening, cut at a
word. One line on screen; the stylesheet clips it. */
function excerpt(role) {
if (role.summary) return role.summary;
const text = (role.description || "").trim();
if (text.length <= 160) return text;
const cut = text.slice(0, 160);
const space = cut.lastIndexOf(" ");
return `${(space > 100 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`;
}
/* A passed role and a hidden company's are dimmed, never dropped: the pass
has to stay visible to be undone. */
function dim(li, role) {
const company = companies.get(role.company_key);
li.classList.toggle("muted", Boolean(company && company.affinity === -1));
li.classList.toggle("passed", role.vote === -1);
}
function renderRows(rows) {
const list = $("#roles-list");
const template = $("#role-row");
for (const role of rows) {
const node = template.content.cloneNode(true);
const li = node.querySelector(".role");
li.dataset.uid = role.uid;
const title = node.querySelector(".role-title");
title.textContent = role.title || "(untitled)";
title.href = `/roles/${encodeURIComponent(role.uid)}`;
node.querySelector(".role-company").textContent = role.company || "";
node.querySelector(".role-place").textContent = role.place || "";
node.querySelector(".role-age").textContent = relativeAge(role.first_seen);
node.querySelector(".role-remote").textContent = role.remote || "";
node.querySelector(".role-function").textContent = role.function || "";
if (role.score !== null && role.score !== undefined) {
const badge = node.querySelector(".role-score");
badge.textContent = role.gated_reason ? "gated" : `match ${Math.round(role.score * 100)}`;
badge.title = role.gated_reason ? "Kept out of the ranking" : "How well it matches, of 100";
node.querySelector(".role-gated").textContent = role.gated_reason || "";
if (role.gated_reason) li.classList.add("gated");
}
node.querySelector(".role-excerpt").textContent = excerpt(role);
node.querySelector(".role-actions").appendChild(judgeButtons(role, () => dim(li, role)));
list.appendChild(node);
}
}
function renderCount() {
const noun = total === 1 ? "role" : "roles";
$("#roles-count").textContent = items.length < total
? `${number.format(items.length)} of ${number.format(total)} ${noun}`
: `${number.format(total)} ${noun}`;
}
/* How many filters inside the panel are set, on its summary, so a closed
panel still says the list is narrowed. */
function renderActive() {
const set = PANEL.filter((id) => {
if (id === "f-gated" && $("#show-gated").hidden) return false;
const value = read(id);
return typeof value === "boolean" ? value : value.trim() !== "";
}).length;
$("#f-active").textContent = set ? `· ${set}` : "";
}
/* 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 = 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 : "";
$("#show-gated").hidden = !select.value;
}
/* `?q=`, `?company=`, `?place=` and `?agent=` prefill the filter bar, which
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"]) {
if (query.get(key)) $(`#f-${key}`).value = query.get(key);
}
if (query.get("company") || query.get("place")) $("#f-more").open = true;
const agent = query.get("agent");
if (agent && agents.some((a) => String(a.id) === agent)) {
$("#f-agent").value = agent;
$("#show-gated").hidden = false;
}
}
// ------------------------------------------------ back from a read page
function keep() {
const filters = {};
for (const id of FIELDS) filters[id] = read(id);
try {
sessionStorage.setItem(KEPT, JSON.stringify({
filters, count: items.length, y: window.scrollY, open: $("#f-more").open,
}));
} catch (err) { /* private mode: back is a fresh list, which is fine */ }
}
function kept() {
try {
return JSON.parse(sessionStorage.getItem(KEPT) || "null");
} catch (err) {
return null;
}
}
function cameBack() {
const [entry] = performance.getEntriesByType("navigation");
return Boolean(entry && entry.type === "back_forward");
}
async function restore(state) {
for (const [id, value] of Object.entries(state.filters || {})) {
if (document.getElementById(id)) write(id, value);
}
if (!agents.some((a) => String(a.id) === $("#f-agent").value)) write("f-agent", "");
$("#show-gated").hidden = !$("#f-agent").value;
$("#f-more").open = Boolean(state.open);
renderActive();
await load({ keep: state.count || PAGE });
window.scrollTo(0, state.y || 0);
}
document.addEventListener("DOMContentLoaded", async () => {
try {
await Promise.all([loadCompanies(), loadTracked(), loadAgents()]);
} catch (err) {
return;
}
renderAgentSelect();
const state = cameBack() ? kept() : null;
if (state) {
await restore(state);
} else {
prefill();
renderActive();
await load();
}
new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) load({ append: true });
}, { rootMargin: "600px" }).observe($("#roles-end"));
const refetch = debounce(reload, 300);
for (const key of ["q", "company", "place"]) {
$(`#f-${key}`).addEventListener("input", refetch);
}
for (const sel of ["#f-function", "#f-remote", "#f-days", "#f-judged", "#f-show-muted",
"#f-gated"]) {
$(sel).addEventListener("change", reload);
}
$("#f-agent").addEventListener("change", () => {
$("#show-gated").hidden = !$("#f-agent").value;
reload();
});
$("#filters").addEventListener("submit", (e) => e.preventDefault());
// Kept on the way out, whichever way that is, so back finds it.
window.addEventListener("pagehide", keep);
// Back from the read page without a reload (the back/forward cache): the
// rows are the ones left, but a vote or a star may have changed there.
window.addEventListener("pageshow", async (e) => {
if (!e.persisted) return;
const y = window.scrollY;
await Promise.all([loadTracked(), loadCompanies()]).catch(() => {});
await load({ keep: items.length });
window.scrollTo(0, y);
});
});
})();