feat(matches): add the candidate match screen with expandable explanations

This commit is contained in:
shira committed 2026-10-09 13:55:00 +03:00
1 parent 0b11021b16
commit 28337d84cb
50 files changed
+4834 -37

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
// Public API of the match-list widget: the result of one candidate search in
// its three groups, with the explanation and the full card of each entry.
export { MatchList } from "./ui/match-list";
@@ -0,0 +1,187 @@
.root {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.title {
margin: 0;
font-size: var(--font-size-xl);
font-weight: var(--font-weight-bold);
}
.title:focus-visible {
outline-offset: 4px;
}
.basis {
display: grid;
grid-template-columns: minmax(9rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
margin: 0;
padding: var(--space-3) var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-surface);
}
.basis dt {
color: var(--color-text-secondary);
}
.basis dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.filters {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.filter {
padding: var(--space-1) var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-pill);
background: var(--color-canvas);
font-size: var(--font-size-s);
overflow-wrap: anywhere;
}
.notice {
margin: 0;
padding: var(--space-3) var(--space-4);
border-inline-start: var(--space-1) solid var(--color-accent);
background: var(--color-surface);
}
.notice[data-kind="truncated"] {
border-inline-start-style: double;
}
.switcher {
display: grid;
gap: var(--space-2);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.switcher legend {
padding: 0;
font-weight: var(--font-weight-bold);
}
.views {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.view {
position: relative;
}
.view input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
}
.view span {
display: inline-flex;
align-items: center;
min-height: 2.75rem;
padding: var(--space-2) var(--space-4);
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-pill);
background: var(--color-surface);
font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
}
.view input:checked + span {
border-color: var(--color-accent);
color: var(--color-on-accent);
background: var(--color-accent);
font-weight: var(--font-weight-bold);
}
.view input:focus-visible + span {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.group {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.group-heading {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-3);
align-items: baseline;
}
.group-title {
margin: 0;
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.group-count {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.group-description {
margin: 0;
color: var(--color-text-secondary);
}
.cards {
display: grid;
gap: var(--space-4);
margin: 0;
padding: 0;
list-style: none;
}
.cards > li {
min-width: 0;
}
.empty-reasons {
display: grid;
gap: var(--space-2);
margin: var(--space-2) 0 0;
padding-inline-start: var(--space-5);
}
@media (width < 30rem) {
.basis {
grid-template-columns: minmax(0, 1fr);
}
.basis dd + dt {
padding-block-start: var(--space-2);
}
}
@@ -0,0 +1,160 @@
import { renderToString } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import type { MatchSearchModel } from "../../../entities/match";
import {
backendHandle,
emptyMatchModelFixture,
matchFixtureNeedId as needId,
matchModelFixture,
} from "../../../entities/match/testing";
import { MatchList } from "./match-list";
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccddee01";
function render(
result: MatchSearchModel,
props: { stale?: boolean; needTitle?: string | null } = {},
): string {
return renderToString(
<MemoryRouter>
<MatchList
accountId="0199b4f2-7c1e-7d3a-9f00-aabbccddee02"
organizationId={organizationId}
result={result}
sentFilters={undefined}
needTitle={props.needTitle ?? null}
stale={props.stale ?? false}
/>
</MemoryRouter>,
);
}
describe("match list", () => {
it("prints the three groups in the product order with their labels", () => {
const html = render(matchModelFixture());
const positions = ["Подтвержденные", "Близкие варианты", "Грейд не подтвержден"].map((label) =>
html.indexOf(`>${label}</h3>`),
);
expect(positions.every((position) => position > 0)).toBe(true);
expect([...positions].sort((a, b) => a - b)).toEqual(positions);
});
it("keeps the confirmed and the declared grade on separate lines", () => {
const html = render(matchModelFixture());
expect(html).toContain("Подтвержденная категория");
expect(html).toContain("Заявленный кандидатом грейд");
expect(html).toContain("Грейд подтвержден: Middle");
expect(html).toContain("Backend, Middle. Сильное подтверждение");
});
it("offers a specialization switch when the result holds several specializations", () => {
const html = render(matchModelFixture());
expect(html).toContain("Представление по специализациям");
expect(html).toContain("Все специализации");
expect(html).toContain("Сетевое администрирование");
expect(html).toContain("Подтверждение не переносится");
});
it("offers no switch for a single specialization", () => {
const base = matchModelFixture();
const single = {
...base,
cards: base.cards.filter((card) => card.specialization === "backend"),
};
expect(render(single)).not.toContain("Представление по специализациям");
});
it("links every entry to the invitation with the organization-scoped handle, also unconfirmed ones", () => {
const html = render(matchModelFixture());
const links = [...html.matchAll(/href="(\/employer\/invitations\?[^"]+)"/g)].map(
(match) => new URL((match[1] ?? "").replaceAll("&amp;", "&"), "http://x"),
);
expect(links).toHaveLength(matchModelFixture().cards.length);
const network = links.find(
(url) => url.searchParams.get("specialization") === "network_engineer",
);
expect(network?.searchParams.get("candidate_handle")).toBe(backendHandle);
expect(network?.searchParams.get("organization_id")).toBe(organizationId);
expect(html).toContain("Пригласить кандидата");
});
it("passes the need to the invitation link when the search was based on a need", () => {
const model = matchModelFixture({
source: { kind: "need", need_id: needId, requirements_version: 4 },
});
const html = render(model, { needTitle: "Платежный backend" });
expect(html).toContain(`need_id=${needId}`);
expect(html).toContain("Платежный backend");
expect(html).toContain("версия требований 4");
});
it("shows no contact, no stable identifier and no failure reason", () => {
const html = render(matchModelFixture());
expect(html).not.toMatch(/@|\+7|telegram|email/i);
expect(html).not.toContain("candidate_id");
expect(html).not.toContain("account");
// Only the shortened alias is printed; the full handle goes into links only.
expect(html).not.toContain(`>${backendHandle}<`);
expect(html).not.toMatch(/провал|неудач/i);
});
it("keeps the explanation and the card closed until the employer asks", () => {
const html = render(matchModelFixture());
expect(html).not.toContain("Как получена позиция");
expect(html).not.toContain("Карточка кандидата</h5>");
expect(html).toContain('aria-expanded="false"');
expect(html).toContain("Показать объяснение");
expect(html).toContain("Открыть карточку");
});
it("explains a partial output without a count", () => {
const html = render(matchModelFixture({ truncated: true }));
expect(html).toContain("Показана часть выдачи; квота просмотров или предел группы");
expect(render(matchModelFixture())).not.toContain("Показана часть выдачи");
});
it("explains an empty result and keeps the filters in view", () => {
const html = render(emptyMatchModelFixture());
expect(html).toContain("По этим условиям никого не нашли");
expect(html).toContain("поиск не ослабляет их сам");
expect(html).not.toContain("Подтвержденные</h3>");
});
it("lists the filters of an empty result that the employer can change", () => {
const model = emptyMatchModelFixture();
const html = render({
...model,
source: {
kind: "bank",
filters: {
specialization: "qa",
confirmedGrade: "senior",
confirmedCategory: null,
confirmationStatus: null,
declaredGrade: null,
stack: ["kafka"],
conditions: null,
},
},
});
expect(html).toContain("Подтвержденный грейд: Senior");
expect(html).toContain("Технологии в карточке (нужны все): Kafka");
});
it("warns that the form changed after the shown result", () => {
expect(render(matchModelFixture(), { stale: true })).toContain("Условия поиска изменены");
expect(render(matchModelFixture())).not.toContain("Условия поиска изменены");
});
});
@@ -0,0 +1,319 @@
import { useEffect, useId, useRef, useState } from "react";
import {
allSpecializationsView,
appliedFiltersOf,
CandidateCardDetails,
cardsForView,
groupDescriptions,
groupLabels,
matchCardKey,
matchGroupOrder,
MatchCardView,
MatchExplanation,
shortHandle,
specializationLabels,
specializationsInResult,
type MatchCardModel,
type MatchGroup,
type MatchSearchModel,
type SpecializationView,
} from "../../../entities/match";
import type { MatchSearchFilters } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { Button, ButtonLink, EmptyState } from "../../../shared/ui";
import styles from "./match-list.module.css";
type MatchListProps = {
accountId: string;
organizationId: string;
result: MatchSearchModel;
/** Filters of the request that produced the result; a need result does not echo them. */
sentFilters: MatchSearchFilters | undefined;
/** Title of the searched need, when the search was based on a need. */
needTitle: string | null;
/** True when the form changed after this result was produced. */
stale: boolean;
};
type EntryState = { explanation: boolean; cardRequested: boolean; cardOpen: boolean };
const closedEntry: EntryState = { explanation: false, cardRequested: false, cardOpen: false };
type EntryProps = {
card: MatchCardModel;
state: EntryState;
accountId: string;
organizationId: string;
needId: string | undefined;
onChange: (next: EntryState) => void;
};
function Entry({ card, state, accountId, organizationId, needId, onChange }: EntryProps) {
const ids = useId();
const headingId = `${ids}-heading`;
const explanationId = `${ids}-explanation`;
const detailsId = `${ids}-details`;
const specialization = specializationLabels[card.specialization];
const short = shortHandle(card.candidateHandle);
return (
<MatchCardView
card={card}
headingId={headingId}
actions={
<>
<Button
variant="secondary"
aria-expanded={state.explanation}
aria-controls={state.explanation ? explanationId : undefined}
aria-describedby={headingId}
onClick={() => onChange({ ...state, explanation: !state.explanation })}
>
{state.explanation ? "Скрыть объяснение" : "Показать объяснение"}
</Button>
<Button
variant="secondary"
aria-expanded={state.cardOpen}
aria-controls={state.cardRequested ? detailsId : undefined}
aria-describedby={headingId}
onClick={() => onChange({ ...state, cardRequested: true, cardOpen: !state.cardOpen })}
>
{state.cardOpen ? "Закрыть карточку" : "Открыть карточку"}
</Button>
<ButtonLink
to={paths.employer.inviteCandidate({
organizationId,
candidateHandle: card.candidateHandle,
specialization: card.specialization,
needId,
})}
aria-label={`Пригласить кандидата ${short}, ${specialization}`}
>
Пригласить
</ButtonLink>
</>
}
>
{state.explanation ? <MatchExplanation card={card} id={explanationId} /> : null}
{state.cardRequested ? (
<CandidateCardDetails
id={detailsId}
accountId={accountId}
organizationId={organizationId}
candidateHandle={card.candidateHandle}
open={state.cardOpen}
/>
) : null}
</MatchCardView>
);
}
type GroupProps = {
group: MatchGroup;
cards: readonly MatchCardModel[];
entryStates: Readonly<Record<string, EntryState>>;
accountId: string;
organizationId: string;
needId: string | undefined;
onEntryChange: (key: string, next: EntryState) => void;
};
function Group({
group,
cards,
entryStates,
accountId,
organizationId,
needId,
onEntryChange,
}: GroupProps) {
const headingId = useId();
return (
<section className={styles.group} aria-labelledby={headingId} data-group={group}>
<div className={styles["group-heading"]}>
<h3 id={headingId} className={styles["group-title"]}>
{groupLabels[group]}
</h3>
<span className={styles["group-count"]}>{`Записей: ${cards.length}`}</span>
</div>
<p className={styles["group-description"]}>{groupDescriptions[group]}</p>
{cards.length === 0 ? (
<p className={styles.hint}>В этой группе записей нет.</p>
) : (
<ul className={styles.cards}>
{cards.map((card) => {
const key = matchCardKey(card);
return (
<li key={key}>
<Entry
card={card}
state={entryStates[key] ?? closedEntry}
accountId={accountId}
organizationId={organizationId}
needId={needId}
onChange={(next) => onEntryChange(key, next)}
/>
</li>
);
})}
</ul>
)}
</section>
);
}
/**
* The result of one search: the basis and the filters it ran with, a notice
* when the output is only part of the ranked result, a switch between the
* specializations of the result, and the three groups in the fixed order of
* the product. The widget shows what the server returned and calculates
* nothing; a result that is empty is explained without touching the filters.
*/
export function MatchList({
accountId,
organizationId,
result,
sentFilters,
needTitle,
stale,
}: MatchListProps) {
const headingRef = useRef<HTMLHeadingElement>(null);
const switcherId = useId();
const [view, setView] = useState<SpecializationView>(allSpecializationsView);
const [entryStates, setEntryStates] = useState<Record<string, EntryState>>({});
// A new result moves the reading position to its heading.
useEffect(() => {
headingRef.current?.focus();
}, [result]);
const applied = appliedFiltersOf(result.source, sentFilters);
const specializations = specializationsInResult(result.cards);
const activeView: SpecializationView =
view !== allSpecializationsView && !specializations.includes(view)
? allSpecializationsView
: view;
const visible = cardsForView(result.cards, activeView);
const needId = result.source.kind === "need" ? result.source.needId : undefined;
const basis =
result.source.kind === "need"
? `Потребность${needTitle ? ` «${needTitle}»` : ""}, версия требований ${result.source.requirementsVersion}`
: "Все профили, доступные компании";
return (
<div className={styles.root}>
<h2 ref={headingRef} tabIndex={-1} className={styles.title}>
Результат поиска
</h2>
<dl className={styles.basis}>
<dt>Основание</dt>
<dd>{basis}</dd>
<dt>Текущие фильтры</dt>
<dd>
{applied.length === 0 ? (
"Не заданы"
) : (
<ul className={styles.filters}>
{applied.map((item) => (
<li key={item.label} className={styles.filter}>
{`${item.label}: ${item.value}`}
</li>
))}
</ul>
)}
</dd>
</dl>
{stale ? (
<p className={styles.notice} role="status">
Условия поиска изменены после этого результата. Нажмите «Найти кандидатов», чтобы обновить
выдачу.
</p>
) : null}
{result.truncated ? (
<p className={styles.notice} data-kind="truncated">
Показана часть выдачи; квота просмотров или предел группы. Остальные кандидаты не
показаны, их число сервер не сообщает. Сузьте фильтры, чтобы увидеть меньше записей
целиком.
</p>
) : null}
{result.cards.length === 0 ? (
<EmptyState
title="По этим условиям никого не нашли"
description={
<>
<p>
Фильтры остаются включенными: поиск не ослабляет их сам. Измените или снимите
условия в форме и повторите поиск.
</p>
{applied.length > 0 ? (
<ul className={styles["empty-reasons"]}>
{applied.map((item) => (
<li key={item.label}>{`${item.label}: ${item.value}`}</li>
))}
</ul>
) : (
<p>
Фильтры не заданы: сейчас в банке, доступном компании, нет подходящих
опубликованных профилей.
</p>
)}
{result.source.kind === "need" ? (
<p>Грейд потребности фильтром не служит; задайте фильтр грейда сами.</p>
) : null}
</>
}
/>
) : (
<>
{specializations.length > 1 ? (
<fieldset className={styles.switcher}>
<legend>Представление по специализациям</legend>
<div className={styles.views}>
{([allSpecializationsView, ...specializations] as SpecializationView[]).map(
(option) => (
<label key={option} className={styles.view}>
<input
type="radio"
name={switcherId}
value={option}
checked={activeView === option}
onChange={() => setView(option)}
/>
<span>
{option === allSpecializationsView
? "Все специализации"
: specializationLabels[option]}
</span>
</label>
),
)}
</div>
<p className={styles.hint}>
Один кандидат может быть в нескольких специализациях. Подтверждение не переносится
между ними: у каждой записи свой статус и своя группа.
</p>
</fieldset>
) : null}
<p className={styles.hint} role="status">
{`Показано записей: ${visible.length}`}
</p>
{matchGroupOrder.map((group) => (
<Group
key={group}
group={group}
cards={visible.filter((card) => card.group === group)}
entryStates={entryStates}
accountId={accountId}
organizationId={organizationId}
needId={needId}
onEntryChange={(key, next) =>
setEntryStates((current) => ({ ...current, [key]: next }))
}
/>
))}
</>
)}
</div>
);
}