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>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-09-25 21:51:48 +02:00
1 parent 7d31cca394
commit 09c5dde113
13 files changed
+1216 -192

No files matched your search

+185 -28
View File
@@ -311,38 +311,204 @@ textarea:focus-visible {
.count { color: var(--dim); font-size: .85rem; margin: .75rem 0 .5rem; }
/* roles */
/* == roles, the read page, applications ================================== */
/* The feed row and the reader are news's (`newsdesk/web/static/app.css`):
* the row a grid with a bottom rule and no card, the actions on the right
* dropping under the text at 640px, a cast vote filled rather than tinted.
* Drawn by static/roles.js, static/role.js and static/judge.js; the phone
* and touch rules for all of it are at the end of this section rather than
* in the phone section below, so the section is one piece. */
.roles { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: .5rem; }
/* The filter bar: the order, the search box, and Filters on one row at any
width. Filters is a `<details>` whose summary is lifted into that row, so
the panel it opens sits in the flow under the row and pushes the list
down instead of covering it. */
.roles-filters { display: block; position: relative; }
.filter-line { display: flex; gap: .5rem; align-items: center; margin-right: 6.75rem; }
.filter-line select { flex: 0 1 auto; max-width: 45%; }
.filter-line input[type="search"] { flex: 1 1 8rem; }
.filter-more > summary {
position: absolute; top: .75rem; right: .75rem;
display: flex; align-items: center; justify-content: center; min-width: 6rem;
padding: .4rem .6rem; line-height: 1.2;
border: 1px solid var(--line); border-radius: .3rem;
color: var(--fg); background: var(--bg); cursor: pointer;
list-style: none; white-space: nowrap;
}
.filter-more > summary::-webkit-details-marker { display: none; }
.filter-more[open] > summary { border-color: var(--accent); color: var(--accent); }
.filter-active { margin-left: .3rem; color: var(--accent); font-weight: 600; }
.filter-panel {
display: flex; flex-wrap: wrap; gap: .5rem; align-items: center;
margin-top: .75rem; padding-top: .75rem; border-top: 1px solid var(--line);
}
.filter-panel select { flex: 1 1 9rem; }
/* The feed. */
.roles {
list-style: none; margin: 0; padding: 0;
background: var(--panel);
border: 1px solid var(--line); border-radius: var(--radius);
}
.roles:empty { display: none; }
.roles-end { height: 1px; }
.role {
background: var(--panel); border: 1px solid var(--line); border-radius: .5rem;
padding: .6rem .8rem;
display: flex; flex-direction: column; gap: .35rem;
display: grid; grid-template-columns: minmax(0, 1fr) auto;
align-items: start; gap: .85rem;
padding: .8rem 1rem .85rem;
border-bottom: 1px solid var(--line);
}
.role:last-child { border-bottom: 0; }
.role-body { min-width: 0; }
.role-title {
display: block; max-width: 60ch;
color: var(--fg); text-decoration: none;
font-size: 1.05rem; font-weight: 600; line-height: 1.35;
overflow-wrap: anywhere;
}
.role-main { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; }
.role-title { font-weight: 600; text-decoration: none; }
@media (hover: hover) {
.role-title:hover { text-decoration: underline; }
.role-title:hover { text-decoration: underline; text-underline-offset: 2px; }
}
.role-company { color: var(--dim); }
.role-meta {
display: flex; flex-wrap: wrap; align-items: center; gap: .5rem;
color: var(--dim); font-size: .85rem;
.role-meta, .reader-meta {
display: flex; flex-wrap: wrap; gap: .1rem .55rem; align-items: baseline;
margin-top: .25rem; font-size: .85rem; color: var(--dim);
}
.role-meta .badge {
/* The company is how you decide whether to read on: weight and full ink. */
.role-meta b, .reader-meta b { font-weight: 600; color: var(--fg); }
.role-meta > :empty, .reader-meta > :empty { display: none; }
.role-meta > * + *::before { content: "· "; }
.role-badges { display: flex; flex-wrap: wrap; gap: .35rem; margin-top: .35rem; }
.role-badges > :empty { display: none; }
.role-badges:not(:has(> :not(:empty))) { display: none; }
.role-badges .badge {
background: transparent; color: var(--dim);
border: 1px solid var(--line); border-radius: 1rem;
padding: .05rem .55rem; font-size: .78rem;
}
.role-meta .badge:empty { display: none; }
.role-meta .role-score {
.role-badges .role-score {
color: var(--accent); border-color: color-mix(in srgb, var(--accent) 45%, var(--line));
font-variant-numeric: tabular-nums;
}
.role-gated { color: var(--error); font-size: .85rem; }
.role-age { margin-left: auto; }
.role.muted, tr.muted { opacity: .55; }
.role.gated { opacity: .7; }
.role-gated { color: var(--error); font-size: .8rem; }
.role-excerpt {
margin: .35rem 0 0; max-width: 68ch;
font-size: .9rem; color: var(--dim);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.role-excerpt:empty { display: none; }
/* A pass and a hidden company are dimmed and stay: a stray tap has to be
visible to be undone. The buttons keep full contrast, so the undo does. */
.role.muted .role-body, .role.passed .role-body { opacity: .55; }
.role.gated .role-body { opacity: .7; }
/* The Companies table dims a hidden company's row the same way. */
tr.muted { opacity: .55; }
/* ▲ ● ▼ ★, on a row and in the reader's bar (static/judge.js). */
.judge { display: flex; gap: .15rem; align-items: center; }
.judge button {
padding: .2rem .45rem; font-size: 1rem; line-height: 1;
color: var(--dim); background: none;
border: 1px solid transparent; border-radius: .3rem;
}
@media (hover: hover) {
.judge button:hover { color: var(--fg); border-color: var(--line); }
}
/* Filled when cast: a reversed glyph on solid ground reads at arm's length
where a tint does not. `--panel` for the glyph because it is the opposite
end of the scale from every fill in both schemes. */
.judge .up[aria-pressed="true"] {
color: var(--panel); background: var(--accent); border-color: var(--accent);
}
.judge .down[aria-pressed="true"] {
color: var(--panel); background: var(--error); border-color: var(--error);
}
/* Neither way is an answer and must be as loud as the other two, or it
cannot be told from unjudged; grey, since it is no direction. */
.judge .mid[aria-pressed="true"] {
color: var(--panel); background: var(--dim); border-color: var(--dim);
}
/* Saved is a different question from judging: amber, and set apart. */
.judge .star[aria-pressed="true"] {
color: var(--panel); background: var(--warn); border-color: var(--warn);
}
.judge .star { margin-left: .35rem; }
/* The read page. */
.reader {
background: var(--panel);
border: 1px solid var(--line); border-radius: var(--radius);
}
.reader-bar {
position: sticky; top: var(--header-h, 0px); z-index: 4;
display: flex; align-items: center; gap: .2rem;
padding: .35rem .6rem;
background: var(--panel);
border-bottom: 1px solid var(--line);
border-radius: var(--radius) var(--radius) 0 0;
}
.reader-bar .spacer { flex: 1; }
.reader-back, .reader-external {
display: inline-flex; align-items: center; justify-content: center;
padding: .2rem .55rem; font-size: 1rem; line-height: 1;
color: var(--dim); text-decoration: none;
border: 1px solid var(--line); border-radius: .3rem;
}
.reader-back { margin-right: .4rem; }
@media (hover: hover) {
.reader-back:hover, .reader-external:hover { color: var(--fg); border-color: var(--dim); }
}
.reader-body { padding: 1.4rem 2rem 2.5rem; overflow-wrap: anywhere; }
/* About 70 characters a line at the reading size. */
.reader-body > * { max-width: 40rem; margin-inline: auto; }
.reader-meta { align-items: center; margin-top: 0; }
.reader-meta .affinity { font-size: .85rem; }
.reader h1 { font-size: 1.6rem; line-height: 1.25; margin: .6rem auto .5rem; }
.reader .role-badges { margin-top: 0; }
.reader-salary { margin: .6rem auto 0; font-weight: 600; }
.reader-summary {
margin-top: 1.1rem; padding: .7rem .9rem;
background: color-mix(in srgb, var(--accent) 7%, var(--panel));
border-left: 3px solid var(--accent); border-radius: .3rem;
}
.reader-summary p { margin: 0; }
/* A label over a block rather than the posting's own heading. */
.reader-label {
margin: 0 0 .3rem; font-size: .72rem; font-weight: 600;
letter-spacing: .08em; text-transform: uppercase; color: var(--dim);
}
.reader-tools { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; margin-top: 1rem; }
.reader-tools:not(:has(> :not([hidden], :empty))) { display: none; }
.prose { margin-top: 1.2rem; font-size: 1.02rem; line-height: 1.7; }
.prose p { margin: 0 0 1rem; }
.reader-out { margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--line); }
/* Applications: the table is the shared `table.list`. */
table.applications td[data-label="Saved"] { white-space: nowrap; color: var(--dim); }
@media (max-width: 640px) {
.filter-line { margin-right: 6.25rem; }
.filter-more > summary { right: 10px; min-width: 5.5rem; }
/* Edge to edge, like every panel on a phone. */
.roles, .reader { margin-inline: -10px; border-radius: 0; border-inline: 0; }
.reader { margin-top: -10px; border-top: 0; }
.reader-bar { border-radius: 0; }
.role { grid-template-columns: minmax(0, 1fr); gap: .45rem; padding: .75rem 10px; }
/* Under the text and to the right, where a thumb is. Two filled blocks
side by side need a gap or they read as one control. */
.role-actions { justify-content: flex-end; gap: .4rem; }
.role-actions button { padding: .25rem .75rem; min-height: 32px; font-size: 1.2rem; }
.reader-body { padding: .9rem .75rem 1.5rem; }
.reader h1 { font-size: 1.3rem; }
}
@media (pointer: coarse) {
.filter-more > summary { min-height: 2.75rem; }
.judge button { padding: .5rem .7rem; font-size: 1.15rem; }
.reader-bar { padding: .3rem .5rem; }
.reader-back, .reader-external { min-height: 2.75rem; min-width: 2.75rem; }
}
/* == end of roles, the read page, applications ============================ */
.affinity { display: inline-flex; gap: .15rem; }
.role-main .affinity { margin-left: auto; }
@@ -357,11 +523,6 @@ textarea:focus-visible {
background: var(--error); border-color: var(--error);
}
.save { align-self: flex-start; padding: .3rem .8rem; font-weight: 600; }
.save[disabled] {
background: var(--bg); color: var(--dim); border-color: var(--line); cursor: default;
}
/* agents */
.agents { list-style: none; margin: 0 0 1rem; padding: 0; display: flex; flex-direction: column; gap: .4rem; }
@@ -437,10 +598,6 @@ 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
+22 -7
View File
@@ -2,7 +2,9 @@
*
* 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.
* refusal. A role's title opens its read page, where ★ unsaves it; one that
* was never a posting links out to where it was found, if anywhere. The
* company names come from app.js's shared company list.
*/
(function () {
"use strict";
@@ -25,17 +27,30 @@
return select;
}
/** "25 Sep", or "25 Sep 2025" when it is not this year. */
function savedOn(iso) {
const at = new Date(iso);
if (Number.isNaN(at.getTime())) return "";
const options = { day: "numeric", month: "short" };
if (at.getFullYear() !== new Date().getFullYear()) options.year = "numeric";
return at.toLocaleDateString("en-GB", options);
}
function render(applications) {
const body = $("#applications-list");
body.replaceChildren();
for (const application of applications) {
const tr = document.createElement("tr");
if (application.url) {
if (application.role_uid || application.url) {
const link = document.createElement("a");
link.href = application.url;
link.target = "_blank";
link.rel = "noopener";
link.textContent = application.role_title || "(untitled)";
if (application.role_uid) {
link.href = `/roles/${encodeURIComponent(application.role_uid)}`;
} else {
link.href = application.url;
link.target = "_blank";
link.rel = "noopener";
}
cell(tr, "Role", link);
} else {
cell(tr, "Role", application.role_title || "(untitled)");
@@ -45,8 +60,8 @@
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(" · "));
const saved = cell(tr, "Saved", savedOn(application.created_at));
saved.title = application.created_at;
body.appendChild(tr);
}
$("#applications-count").textContent =
+132
View File
@@ -0,0 +1,132 @@
/* ▲ ● ▼ ★ for one role: the feed row and the read page share them.
*
* news's `voteButtons`, `starButton` and `vote()`, adapted. Three stances and
* no stance is four states from three buttons; pressing the stance a role
* already has clears it, which is the only way back to unjudged, since ● is
* an answer ("neither way") and not the absence of one. A vote never hides a
* role: a stray tap stays on screen, pressed, and one more tap undoes it.
*
* ★ is Save. It files the role under Applications (`POST /api/applications`)
* and, pressed again, takes it back out (`DELETE /api/applications/{id}`),
* which the server allows only while the application is still at `saved`; a
* 409 is toasted by `api()` and the star stays lit.
*
* Both are optimistic: the button changes before the request and changes back
* if it fails. `api()` has already toasted the failure by then.
*
* await loadTracked();
* container.append(judgeButtons(role, (role) => row.classList.toggle(...)));
*/
(function () {
"use strict";
const { api } = window;
/** @type {Map<string, object>} role_uid -> application, for roles saved */
const tracked = new Map();
async function loadTracked() {
const applications = await api("/api/applications");
tracked.clear();
for (const a of applications) if (a.role_uid) tracked.set(a.role_uid, a);
return tracked;
}
const STANCES = [
{ value: 1, cls: "up", glyph: "▲", said: "Like" },
{ value: 0, cls: "mid", glyph: "●", said: "Neither way" },
{ value: -1, cls: "down", glyph: "▼", said: "Pass" },
];
function button(cls, glyph) {
const b = document.createElement("button");
b.type = "button";
b.className = cls;
b.textContent = glyph;
return b;
}
/* The four buttons as a fragment, bound to `role`, which they read and
write in place (`role.vote`), so the caller's copy is always current.
`onChange(role)` runs after every change, optimistic or reverted: the
feed dims a passed row with it. */
function judgeButtons(role, onChange) {
const fragment = document.createDocumentFragment();
const votes = STANCES.map((s) => {
const b = button(s.cls, s.glyph);
b.addEventListener("click", () => vote(s.value));
fragment.appendChild(b);
return b;
});
const star = button("star", "★");
star.addEventListener("click", () => toggleSave());
fragment.appendChild(star);
function paint() {
STANCES.forEach((s, i) => {
const on = role.vote === s.value;
const said = on ? `${s.said} — tap again to undo` : s.said;
votes[i].setAttribute("aria-pressed", String(on));
votes[i].title = said;
votes[i].setAttribute("aria-label", said);
});
const saved = tracked.has(role.uid);
const said = saved ? "Saved to Applications — tap to unsave" : "Save to Applications";
star.setAttribute("aria-pressed", String(saved));
star.title = said;
star.setAttribute("aria-label", said);
if (onChange) onChange(role);
}
async function vote(value) {
const before = role.vote ?? null;
const clearing = before === value;
role.vote = clearing ? null : value;
paint();
const path = `/api/roles/${encodeURIComponent(role.uid)}/vote`;
try {
const updated = clearing
? await api(path, { method: "DELETE" })
: await api(path, { method: "POST", body: { value } });
role.vote = updated.vote;
role.voted_at = updated.voted_at;
} catch (err) {
role.vote = before;
}
paint();
}
// One request at a time: a second tap while the first is in flight would
// unsave an application whose id has not come back yet.
async function toggleSave() {
if (star.disabled) return;
star.disabled = true;
const before = tracked.get(role.uid);
try {
if (before) {
tracked.delete(role.uid);
paint();
await api(`/api/applications/${encodeURIComponent(before.id)}`,
{ method: "DELETE" });
} else {
tracked.set(role.uid, { role_uid: role.uid });
paint();
tracked.set(role.uid, await api("/api/applications", {
method: "POST", body: { role_uid: role.uid, status: "saved" },
}));
}
} catch (err) {
if (before) tracked.set(role.uid, before);
else tracked.delete(role.uid);
} finally {
star.disabled = false;
}
paint();
}
paint();
return fragment;
}
Object.assign(window, { judgeButtons, loadTracked });
})();
+200
View File
@@ -0,0 +1,200 @@
/* The read page of one role, news's reader.
*
* The bar: back, ▲ ● ▼ ★ (judge.js, the same buttons as the feed row) and ↗
* to the posting. Then the company with its ★ ▲ ⊘ control, the one place a
* company is judged outside the Companies page; place, badges, salary when
* stated; the summary when there is one; the text, which is the fetched
* posting when there is one and the board's description otherwise; and the
* way out once more at the end.
*
* A search role's description is a teaser of a couple of hundred characters,
* so under 500 of them, with nothing fetched yet, the page offers "Fetch the
* posting" (`POST /api/roles/{uid}/text`). "Summarise" is offered while there
* is no summary (`POST /api/roles/{uid}/summarise`). Both answer with the
* role, and the page is drawn again from it. A summary made by the queue
* rather than at once is waited for by asking for the role again.
*/
(function () {
"use strict";
const { api, companies, loadCompanies, affinityControl, judgeButtons, loadTracked } = window;
const $ = (sel, root = document) => root.querySelector(sel);
const uid = $("#role").dataset.uid;
const path = `/api/roles/${encodeURIComponent(uid)}`;
/** Shorter than this and not fetched: the description is a teaser. */
const TEASER = 500;
/** @type {object|null} the role on screen, updated in place */
let role = null;
function relativeAge(iso) {
const minutes = Math.max(0, Math.floor((Date.now() - new Date(iso).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`;
}
function salary(r) {
const n = (v) => new Intl.NumberFormat("en").format(v);
const unit = r.currency ? `${r.currency} ` : "";
if (r.salary_min && r.salary_max && r.salary_min !== r.salary_max) {
return `${unit}${n(r.salary_min)}–${n(r.salary_max)}`;
}
if (r.salary_min || r.salary_max) {
const one = r.salary_min || r.salary_max;
return r.salary_min ? `From ${unit}${n(one)}` : `Up to ${unit}${n(one)}`;
}
return "";
}
function host(url) {
try { return new URL(url).host.replace(/^www\./, ""); } catch (e) { return ""; }
}
/* Plain text in paragraphs: a fetched page keeps its line breaks, and a
board's description is one long line, which stays one paragraph. */
function paragraphs(text) {
const box = document.createDocumentFragment();
for (const part of text.split(/\n\s*\n|\n/).map((p) => p.trim()).filter(Boolean)) {
const p = document.createElement("p");
p.textContent = part;
box.appendChild(p);
}
return box;
}
function badge(text) {
const span = document.createElement("span");
span.className = "badge";
span.textContent = text;
return span;
}
function renderAffinity() {
const slot = $("#role-affinity");
const company = companies.get(role.company_key);
// A company seen only through a search has no row of its own to judge.
if (!company) { slot.replaceChildren(); return; }
slot.replaceChildren(affinityControl(role.company_key, company.affinity, renderAffinity));
}
function render() {
document.title = `${role.title || "Role"} — roledesk`;
$("#role").removeAttribute("aria-busy");
const out = role.original_url || "";
$("#role-out").hidden = !out;
if (out) $("#role-out").href = out;
const end = $("#role-out-end");
end.hidden = !out;
if (out) {
const a = end.querySelector("a");
a.href = out;
a.textContent = `Read it on ${host(out) || "the board"} ↗`;
}
$("#role-company").textContent = role.company || "";
renderAffinity();
$("#role-place").textContent = role.place || "";
$("#role-age").textContent = role.first_seen ? relativeAge(role.first_seen) : "";
$("#role-title").textContent = role.title || "(untitled)";
const badges = [role.remote, role.function, role.seniority].filter(Boolean).map(badge);
if (role.closed_at) badges.unshift(badge("closed"));
$("#role-badges").replaceChildren(...badges);
$("#role-badges").hidden = !badges.length;
const pay = salary(role);
$("#role-salary").hidden = !pay;
$("#role-salary").textContent = pay;
const summary = $("#role-summary");
summary.hidden = !role.summary;
summary.querySelector("p").textContent = role.summary || "";
const text = (role.article_text || role.description || "").trim();
$("#role-text").replaceChildren(text ? paragraphs(text)
: Object.assign(document.createElement("p"), {
className: "muted", textContent: "The board gave no description for this one.",
}));
$("#role-summarise").hidden = Boolean(role.summary);
$("#role-fetch").hidden = Boolean(role.article_text)
|| (role.description || "").length >= TEASER;
}
function merge(updated) {
if (updated && updated.uid === role.uid) Object.assign(role, updated);
render();
}
/* Press, wait, draw again from the answer. A failure is toasted by `api()`
(a 404 included, while the route is not there yet) and the button comes
back as it was. */
async function ask(button, busy, route) {
const label = button.textContent;
button.disabled = true;
button.textContent = busy;
try {
merge(await api(`${path}/${route}`, { method: "POST" }));
return true;
} catch (err) {
return false;
} finally {
button.disabled = false;
button.textContent = label;
}
}
async function summarise() {
if (!(await ask($("#role-summarise"), "Summarising…", "summarise"))) return;
if (role.summary) return;
// Queued rather than done: ask again until it is there, for two minutes.
const note = $("#role-note");
note.textContent = "The summary appears here when it is ready.";
$("#role-summarise").hidden = true;
for (let i = 0; i < 30 && !role.summary; i++) {
await new Promise((resolve) => setTimeout(resolve, 4000));
try { merge(await api(path)); } catch (err) { break; }
}
note.textContent = "";
render();
}
/* Back is back when this page was opened from one of this app's lists, so
the list keeps its place; a link from anywhere else goes to the roles. */
function back(e) {
let from = null;
try { from = document.referrer ? new URL(document.referrer) : null; } catch (err) { /* */ }
if (from && from.origin === location.origin && history.length > 1) {
e.preventDefault();
history.back();
}
}
/* The bar sticks under the top bar, whose height is the phone's or the
desktop's, and the notch's on a standalone phone. */
function measureHeader() {
const top = document.querySelector("header.top");
if (top) document.documentElement.style.setProperty("--header-h", `${top.offsetHeight}px`);
}
document.addEventListener("DOMContentLoaded", async () => {
measureHeader();
window.addEventListener("resize", measureHeader);
$("#role-back").addEventListener("click", back);
try {
[role] = await Promise.all([api(path), loadCompanies(), loadTracked()]);
} catch (err) {
$("#role-title").textContent = "This role could not be loaded.";
return;
}
$("#role-judge").appendChild(judgeButtons(role));
render();
$("#role-summarise").addEventListener("click", summarise);
$("#role-fetch").addEventListener("click",
() => ask($("#role-fetch"), "Fetching…", "text"));
});
})();
+190 -65
View File
@@ -1,32 +1,56 @@
/* The Roles tab: the filter bar and the list of open roles.
/* 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, 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.
* 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. The catch blocks here only put the
* control back the way it was.
* carrying the server's own sentence.
*/
(function () {
"use strict";
const { api, count, debounce, companies, loadCompanies, affinityControl } = window;
const { api, debounce, companies, loadCompanies, judgeButtons, loadTracked } = window;
/** @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 = [];
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");
async function loadApplications() {
const applications = await api("/api/applications");
trackedByRole = new Map(applications.filter((a) => a.role_uid).map((a) => [a.role_uid, a]));
}
/* 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);
@@ -38,7 +62,7 @@
const value = $(`#f-${key}`).value.trim();
if (value) params.set(key, value);
}
for (const key of ["function", "remote", "days"]) {
for (const key of ["function", "remote", "days", "judged"]) {
const value = $(`#f-${key}`).value;
if (value) params.set(key, value);
}
@@ -51,13 +75,48 @@
return params;
}
async function loadRoles() {
/* 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 {
roles = await api(`/api/roles?${filterParams().toString()}`);
data = await api(`/api/roles?${params}`);
} catch (err) {
return;
} finally {
if (mine === request) loading = false;
}
renderRoles();
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) {
@@ -69,67 +128,72 @@
return `${Math.floor(hours / 24)} d ago`;
}
function renderRoles() {
/* 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");
list.replaceChildren();
for (const role of roles) {
for (const role of rows) {
const node = template.content.cloneNode(true);
const li = node.querySelector(".role");
const company = companies.get(role.company_key);
li.dataset.uid = role.uid;
if (company && company.affinity === -1) li.classList.add("muted");
const titleLink = node.querySelector(".role-title");
titleLink.textContent = role.title || "(untitled)";
titleLink.href = role.original_url || "#";
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 || "";
node.querySelector(".role-age").textContent = relativeAge(role.first_seen);
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 = "Match";
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(".affinity").replaceWith(
affinityControl(role.company_key, company ? company.affinity : 0, loadRoles));
const saveButton = node.querySelector(".save");
setSaveButton(saveButton, role.uid);
saveButton.addEventListener("click", () => saveRole(role.uid, saveButton));
node.querySelector(".role-actions").appendChild(judgeButtons(role, () => dim(li, role)));
list.appendChild(node);
}
$("#roles-count").textContent = count(roles.length, "role");
}
function setSaveButton(button, uid) {
const saved = trackedByRole.has(uid);
button.textContent = saved ? "Saved" : "Save";
button.disabled = saved;
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}`;
}
async function saveRole(uid, button) {
button.disabled = true;
button.textContent = "Saving…";
try {
const application = await api("/api/applications", {
method: "POST", body: { role_uid: uid, status: "saved" },
});
trackedByRole.set(uid, application);
setSaveButton(button, uid);
} catch (err) {
button.disabled = false;
button.textContent = "Save";
}
/* 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
@@ -155,6 +219,7 @@
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;
@@ -162,27 +227,87 @@
}
}
// ------------------------------------------------ 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(), loadApplications(), loadAgents()]);
await Promise.all([loadCompanies(), loadTracked(), loadAgents()]);
} catch (err) {
return;
}
renderAgentSelect();
prefill();
await loadRoles();
const state = cameBack() ? kept() : null;
if (state) {
await restore(state);
} else {
prefill();
renderActive();
await load();
}
const refetch = debounce(loadRoles, 300);
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-show-muted", "#f-gated"]) {
$(sel).addEventListener("change", loadRoles);
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;
loadRoles();
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);
});
});
})();