Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(react): 统计与口味页在极端数据下照常显示

longmeidao830a1631ce56
diff --git a/frontend/e2e/design-controls.test.ts b/frontend/e2e/design-controls.test.ts
index 97a5a6cae..53ed28966 100644
--- a/frontend/e2e/design-controls.test.ts
+++ b/frontend/e2e/design-controls.test.ts
@@ -129,8 +129,8 @@ describe('设计决定:控件、状态与首页顶部', () => {
}
});
- it('高清版卡片的封面是 150px 宽的 16/10 方块,长标题从中间省略', { timeout: 60_000 }, async () => {
- const long = '这是一个长到必须省略才放得下的文件名,用来盯住中间截断在 React 插进来的节点上也生效.mp4';
+ it('高清版卡片的封面是 150px 宽的 16/10 方块,长标题从头显示、最多两行', { timeout: 60_000 }, async () => {
+ const long = '这是一个长到必须省略才放得下的文件名,用来盯住标题从头显示而番号不被截掉.mp4';
const opened = await openQualityGoals(browser, [
qualityGoal(1, long), qualityGoal(2, 'short.mp4'),
]);
@@ -142,13 +142,18 @@ describe('设计决定:控件、状态与首页顶部', () => {
}));
assert.equal(box.width, '150px');
assert.equal(box.ratio.replaceAll(' ', ''), '16/10');
- // 中间截断由 `peach-ui.js` 入口启动的 MutationObserver 接手:React 插进来的
- // 节点不经过遗留层的渲染函数,观察器认不出它就只剩尾部省略。
const title = opened.page.locator('li[data-goal-id="1"] h3 button');
await title.waitFor({ timeout: 5_000 });
- await opened.page.locator('li[data-goal-id="1"] h3 button.middle-truncated')
- .waitFor({ timeout: 10_000 });
- assert.ok((await title.textContent())!.includes('…'), '长标题没有被省略');
+ const shown = await title.evaluate((element) => ({
+ clamp: getComputedStyle(element).webkitLineClamp,
+ middle: element.classList.contains('middle-truncated') || element.hasAttribute('data-middle-truncate'),
+ text: element.textContent,
+ hint: element.getAttribute('title'),
+ }));
+ assert.equal(shown.clamp, '2');
+ assert.equal(shown.middle, false, '标题仍被中间截断');
+ assert.equal(shown.text, long);
+ assert.equal(shown.hint, long);
assert.deepEqual(opened.problems, []);
} finally {
await opened.close();
diff --git a/frontend/src/board-skeleton.ts b/frontend/src/board-skeleton.ts
index b033d7f01..3dcfcac00 100644
--- a/frontend/src/board-skeleton.ts
+++ b/frontend/src/board-skeleton.ts
@@ -1,15 +1,12 @@
import { resolveFollowSort, SORT_OPTIONS, type SortDir, type SortKey } from './follow-sort';
import { islandButton, islandSelect } from './island-skeleton';
import { configurationSkeleton } from './configuration-skeleton';
-import { duplicatesSkeleton, qualityGoalsSkeleton, statsSkeleton } from './management-skeletons';
+import { duplicatesSkeleton, qualityGoalsSkeleton, statsSkeleton, tasteSkeleton } from './management-skeletons';
/** 等待态复用页面容器,只有异步内容使用占位。 */
const line = (width = '60%') => `<span class="skeleton" style="width:${width}"></span>`;
const lines = () => `${line('80%')}${line('48%')}`;
const repeat = (html: string, count: number) => html.repeat(count);
-const metrics = (labels: string[], className = 'metricstrip') => `<div class="${className}">${labels.map(label => `<div class="tastesummary"><span class="board-stat-label">${label}</span><b class="board-stat-value">${line('45%')}</b><small class="board-stat-footer">${line('60%')}</small></div>`).join('')}</div>`;
-const segments = (labels: string[], className: string) => `<div class="${className} skeleton-segments" data-board-segments="true">${labels.map((label,index) => `<span${index===0?' class="skeleton-segment-selected"':''}>${label}</span>`).join('')}</div>`;
-const panel = (title: string) => `<section class="insightpanel"><header>${title}</header><div class="insightpanelbody skeleton-lines">${repeat(lines(), 3)}</div></section>`;
/* 关注管理整页归 React,骨架整块画在 `.peach-react` 里,容器与按键都取 React 那侧渲染出的同一串
类名(`react/follow-manage/`、`react/components/` 与 `island-skeleton.ts`):页面那一列、读数带、
分段控件、关注列表那张填充卡、创作者卡、来源行和表格外框。只有等数据的读数画占位条。
@@ -99,7 +96,7 @@ export function boardPageSkeleton(
if (path === '/stats') {
body = statsSkeleton();
} else if (path === '/taste') {
- body = `<div class="tastepage"><header class="tastehead">${segments(['浏览器记录', 'Peach 内部'], 'insightswitch')}${line('24%')}</header><div class="tastestate"></div>${metrics(['浏览记录', '口味维度', '浏览候选', '私有导出'], 'tastesummaries')}<section class="tastehero"><div class="insightcopy"><span>浏览器画像</span><div class="skeleton skeleton-radar"></div></div><div class="tastebars skeleton-lines">${repeat(lines(), 4)}</div></section>${panel('口味分析')}<div class="board-activity-charts">${panel('浏览活动')}${panel('时间分布')}</div>${panel('标签')}</div>`;
+ body = tasteSkeleton();
} else if (path === '/follow-manage') {
body = followList(options);
} else if (path === '/configuration') {
diff --git a/frontend/src/management-skeletons.ts b/frontend/src/management-skeletons.ts
index 0c5580a5f..5937ccd90 100644
--- a/frontend/src/management-skeletons.ts
+++ b/frontend/src/management-skeletons.ts
@@ -1,4 +1,4 @@
-import { islandButton, islandSummary } from './island-skeleton';
+import { islandButton, islandSelect, islandSummary } from './island-skeleton';
const placeholder = 'relative overflow-hidden skeleton-sheen bg-background-tertiary-default rounded-lg';
const text = (width = '60%') => `<span class="${placeholder} inline-block max-w-full align-middle" style="width:${width};height:1em"></span>`;
@@ -32,6 +32,42 @@ export function statsSkeleton(): string {
</div></div>`;
}
+/** 口味页首屏,按 TastePage 默认那一页(浏览器记录)排:工具行、读数带、画像卡、两张热力图、
+ * 流向图与维度面板。分段、范围框与读取键取 React 那侧渲染出的同一串类名,只有读数与图画占位。 */
+export function tasteSkeleton(): string {
+ const segment = 'flex min-h-7 flex-none items-center gap-1.5 rounded-md px-2.5 py-1 text-body-medium whitespace-nowrap text-text-secondary data-selected:bg-background-primary-default data-selected:text-text-primary data-selected:shadow-card dark:data-selected:bg-background-primary-hover';
+ const track = (labels: string[]) => `<div class="inline-flex w-max max-w-full items-center gap-0.5 overflow-x-auto rounded-2lg bg-background-tertiary-default p-1" data-taste-segments>${labels.map((label, index) => `<span class="${segment}"${index === 0 ? ' data-selected="true"' : ''}>${label}</span>`).join('')}</div>`;
+ const metrics = ['浏览记录', '口味维度', '浏览候选', '私有导出'].map(label => `
+ <div class="min-w-0 rounded-2xl shadow-card bg-background-secondary-default flex flex-col overflow-hidden pt-4 text-left">
+ <span class="flex min-w-0 items-center gap-2 px-4 text-body-regular text-text-secondary max-sm:gap-1.5 max-sm:px-3"><i class="${placeholder} size-7 max-sm:size-6"></i>${label}</span>
+ <b class="px-4 pt-3 pb-4 text-title-1-medium max-sm:px-3 max-sm:pb-3">${text('4em')}</b>
+ <small class="mt-auto block min-h-9.5 bg-card-footer px-4 py-2.5 text-caption-1-regular max-sm:px-3 max-sm:py-2">${text('6em')}</small>
+ </div>`).join('');
+ const card = 'min-w-0 bg-background-secondary-default rounded-2xl shadow-card p-5 flex flex-col gap-4';
+ const bars = Array.from({ length: 6 }, () => `<div class="${placeholder} h-6"></div>`).join('');
+ const heat = (title: string) => `<section class="${chart}"><h3 class="text-title-2-medium text-text-primary">${title}</h3><div class="${placeholder} h-40"></div></section>`;
+ return `<div class="peach-react"><div class="mx-auto flex w-full max-w-board flex-col gap-8">
+ <div class="flex flex-col gap-5">
+ <div class="flex flex-wrap items-center justify-between gap-3">${track(['浏览器记录', 'Peach 内部'])}
+ <div class="flex flex-wrap items-center gap-2">${islandSelect('全部时间')}<span data-button-group data-split-button data-variant="primary">${islandButton({ glyph: 'compass', label: '读取浏览器历史', attrs: wait })}${islandButton({ glyph: 'chevron-down', attrs: wait })}</span></div>
+ </div>
+ <div class="inline-grid w-full grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4" data-taste-metrics>${metrics}</div>
+ <section class="${card} md:flex-row md:gap-6" data-taste-portrait>
+ <div class="flex shrink-0 flex-col gap-2 pb-5 md:w-80 md:pr-6 md:pb-0"><span class="text-caption-1-regular text-text-secondary">浏览器画像</span>
+ <svg class="h-70 w-full text-background-tertiary-default" viewBox="0 0 200 200" fill="none" stroke="currentColor" stroke-width="2">${[70, 47, 24].map(r => `<polygon points="${[0, 1, 2, 3, 4, 5].map(i => `${(100 + r * Math.sin(i * Math.PI / 3)).toFixed(1)},${(100 - r * Math.cos(i * Math.PI / 3)).toFixed(1)}`).join(' ')}"/>`).join('')}</svg>
+ <small class="text-caption-1-regular">${text('8em')}</small></div>
+ <div class="flex min-w-0 grow flex-col justify-around gap-3">${bars}</div>
+ </section>
+ <div class="inline-grid w-full items-start gap-5 lg:grid-cols-2">${heat('浏览活跃时间')}${heat('每日活跃')}</div>
+ <section class="${chart}"><h3 class="text-title-2-medium text-text-primary">创作者线索来源</h3><div class="${placeholder} h-72 max-sm:h-48"></div></section>
+ <section class="min-w-0 bg-background-secondary-default rounded-2xl shadow-card flex flex-col">
+ <div class="px-4 pt-3">${track(['标签', '创作者', '常访问网站', '浏览候选'])}</div>
+ <div class="flex flex-col gap-3 px-4 pt-3.5 pb-4">${Array.from({ length: 5 }, () => `<div class="${placeholder} h-7"></div>`).join('')}</div>
+ </section>
+ </div>
+ </div></div>`;
+}
+
/** 重复文件首屏:完整汇总、玻璃批量条、组头和两行文件,尺寸跟正文一致。 */
export function duplicatesSkeleton(): string {
const row = `<div class="duplicate-row items-center gap-3 border-t border-separator-border px-5 py-4 max-compact:p-4">
diff --git a/frontend/src/react/charts/bar-card.tsx b/frontend/src/react/charts/bar-card.tsx
index 1df1cac48..870c63c75 100644
--- a/frontend/src/react/charts/bar-card.tsx
+++ b/frontend/src/react/charts/bar-card.tsx
@@ -5,7 +5,7 @@
* (`../entry.tsx` 的 `MotionConfig`);悬停浮层是 `./chart-tip.tsx`。 */
import { EvilBarChart } from '@/registry/charts/recharts-bar-chart';
-import { CHART_CARD, ChartHead, tone } from './chart-card';
+import { CategoryTick, categoryAxisWidth, CHART_CARD, ChartEmpty, ChartHead, tone } from './chart-card';
import { ChartTip } from './chart-tip';
/** 一根柱子:显示的名字和它的数。写成类型别名,EvilCharts 的 `data` 要能当 `Record` 收。 */
@@ -14,18 +14,34 @@ export type BarRow = { name: string; value: number };
/** 数值轴留两成余量,最长那根柱子端上的数不被图框切掉。 */
export const BAR_DOMAIN: [number, (max: number) => number] = [0, (max) => max * 1.2];
+/** 横条右侧给柱端那个数留的位置(像素):最长那一条的数落在这一截里,不被图框切掉。 */
+export const BAR_LABEL_ROOM = 56;
+
+/** 柱端的数:十万以上读成「万」「亿」,柱端那一小截放得下;全数在悬停浮层里。 */
+export function shortCount(value: number): string {
+ const abs = Math.abs(value);
+ const scaled = (unit: number, name: string) => {
+ const figure = value / unit;
+ return `${figure.toLocaleString(undefined, { maximumFractionDigits: Math.abs(figure) < 100 ? 1 : 0 })}${name}`;
+ };
+ if (abs >= 1e8) return scaled(1e8, '亿');
+ if (abs >= 1e5) return scaled(1e4, '万');
+ return value.toLocaleString();
+}
+
/** 柱端的数。`position` 跟着柱子的走向:竖柱标在顶上,横条标在右端。 */
export const barLabel = (position: 'top' | 'right') => ({
position,
className: 'fill-text-secondary',
- formatter: (value: unknown) => Number(value).toLocaleString(),
+ formatter: (value: unknown) => shortCount(Number(value)),
});
-/** 浮层那一行的名字:`series` 是这一组数的叫法(「视频」「作品」),不是单位。 */
+/** 浮层那一行的名字:`series` 是这一组数的叫法(「视频」「作品」),不是单位。
+ * 一根柱子都没有数时,卡片照留,图的位置换成 `empty` 那句话。 */
export function BarCard(
- { title, unit, series, rows, color, layout = 'vertical' }:
+ { title, unit, series, rows, color, empty, layout = 'vertical' }:
{
- title: string; unit: string; series: string; rows: BarRow[]; color: string;
+ title: string; unit: string; series: string; rows: BarRow[]; color: string; empty: string;
layout?: 'vertical' | 'horizontal';
},
) {
@@ -33,22 +49,25 @@ export function BarCard(
.filter((row) => Number.isFinite(row.value) && row.value >= 0)
.map((row) => ({ name: row.name, value: row.value }));
const total = data.reduce((sum, row) => sum + row.value, 0);
- if (!total) return null;
+ if (!total) return <ChartEmpty title={title}>{empty}</ChartEmpty>;
const horizontal = layout === 'horizontal';
/* 图的容器自带 `flex-1`,放进卡片这一列 flex 里会按 0 起算、把 `h-*` 压成 0 高,换成 `flex-none`。
- 类别轴 `interval={0}`:每根柱子都要有名字,Recharts 默认会把挤在一起的名字隔一个藏掉。 */
+ 类别轴 `interval={0}`:每根柱子都要有名字,Recharts 默认会把挤在一起的名字隔一个藏掉;
+ 名字放不下就由 `CategoryTick` 截断。 */
return (
<section className={CHART_CARD} aria-label={title}>
<ChartHead title={title} figure={total.toLocaleString()} note={unit} />
<EvilBarChart data={data} config={{ value: { label: series, colors: tone(color) } }}
layout={layout} barRadius={4}
+ chartProps={horizontal ? { margin: { top: 5, right: BAR_LABEL_ROOM, bottom: 5, left: 5 } } : undefined}
className={horizontal
? 'aspect-auto h-64 flex-none text-text-secondary'
: 'aspect-auto h-56 flex-none text-text-secondary'}>
<EvilBarChart.Grid />
{horizontal
- ? <EvilBarChart.YAxis dataKey="name" interval={0} />
- : <EvilBarChart.XAxis dataKey="name" interval={0} />}
+ ? <EvilBarChart.YAxis dataKey="name" interval={0} tick={<CategoryTick along="y" />}
+ width={categoryAxisWidth(data.map((row) => row.name))} />
+ : <EvilBarChart.XAxis dataKey="name" interval={0} tick={<CategoryTick along="x" />} />}
{horizontal
? <EvilBarChart.XAxis hide domain={BAR_DOMAIN} />
: <EvilBarChart.YAxis hide domain={BAR_DOMAIN} />}
diff --git a/frontend/src/react/charts/chart-card.tsx b/frontend/src/react/charts/chart-card.tsx
index 5d11ad6a4..97abd838e 100644
--- a/frontend/src/react/charts/chart-card.tsx
+++ b/frontend/src/react/charts/chart-card.tsx
@@ -3,12 +3,81 @@
* 图表卡比读数卡大一档圆角:旧 `.board-radial-card`/`.board-heat-card`/`.board-sankey-card`
* 都是 20px。页头是两列:标题压着大数在左,那句注解贴右下角对齐大数的基线,注解长短不一
* 也不会把标题挤走。 */
+import type { ReactNode } from 'react';
+import { Text } from 'recharts';
+
import type { ChartConfig } from '@/registry/ui/recharts-chart';
import { cardClass } from '../components/card';
export const CHART_CARD = `${cardClass({ radius: 'chart' })} flex flex-col gap-4 max-sm:p-4`;
+/** 一张没有可画数据的图:标题照旧,图的位置换成一句说明。统计页与口味页的图共用。 */
+export function ChartEmpty({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <section className={CHART_CARD} aria-label={title}>
+ <h3 className="text-title-2-medium text-text-primary">{title}</h3>
+ <p className="text-body-2-regular text-text-secondary">{children}</p>
+ </section>
+ );
+}
+
+/** 量不了字宽时(没有 canvas)一个字形按多宽估,宁宽勿窄:中日文、全角符号与 emoji 按 13 算,其余按 7 算。 */
+const glyphWidth = (glyph: string) => ((glyph.codePointAt(0) ?? 0) > 0x2e7f ? 13 : 7);
+
+const graphemes = (text: string): string[] =>
+ [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text)].map((part) => part.segment);
+
+/** 坐标轴文字(12px、页面字体)的量尺,第一次用到时建。取不到 2D 画布就是 `null`。 */
+let ruler: CanvasRenderingContext2D | null | undefined;
+function measureText(text: string): number | null {
+ if (ruler === undefined) {
+ try {
+ ruler = document.createElement('canvas').getContext('2d');
+ if (ruler) ruler.font = `12px ${getComputedStyle(document.body).fontFamily || 'sans-serif'}`;
+ } catch {
+ ruler = null;
+ }
+ }
+ return ruler ? ruler.measureText(text).width : null;
+}
+
+/** 一段坐标轴文字的宽度(像素):浏览器里实量,量不了就按字形估。 */
+export const labelWidth = (text: string): number =>
+ measureText(text) ?? graphemes(text).reduce((sum, glyph) => sum + glyphWidth(glyph), 0);
+
+/** 把一个类别名截到 `room` 像素以内,截掉的部分换成省略号;放得下就原样返回。 */
+export function fitLabel(text: string, room: number): string {
+ if (labelWidth(text) <= room) return text;
+ const glyphs = graphemes(text);
+ let kept = 0;
+ while (kept < glyphs.length && labelWidth(`${glyphs.slice(0, kept + 1).join('')}…`) <= room) kept += 1;
+ return `${glyphs.slice(0, kept).join('')}…`;
+}
+
+/** 横向柱状图类别轴的宽度:跟着最长的名字走,但不超过 `cap`,柱子不被名字挤没。 */
+export const categoryAxisWidth = (names: string[], cap = 104): number =>
+ Math.min(cap, Math.max(24, ...names.map(labelWidth)) + 12);
+
+/** 类别轴上的一个名字。Recharts 把刻度的坐标、轴宽与可见刻度数交进来:竖柱按每根柱分到的
+ * 宽度截断,横条按轴宽截断。全名在 `<title>` 里,悬停浮层读的也是全名。 */
+export function CategoryTick(
+ props: {
+ along: 'x' | 'y'; payload?: { value?: unknown }; width?: number; visibleTicksCount?: number;
+ } & Record<string, unknown>,
+) {
+ const { along, payload, width = 0, visibleTicksCount = 1, ...rest } = props;
+ const name = String(payload?.value ?? '');
+ // 竖柱的名字在一根柱分到的那一格里居中,左右各留 1px;横条的名字与条之间隔着 8px 的 tickMargin。
+ const room = along === 'x' ? width / Math.max(1, visibleTicksCount) - 2 : width - 8;
+ return (
+ <g>
+ <title>{name}</title>
+ <Text {...(rest as object)}>{fitLabel(name, room)}</Text>
+ </g>
+ );
+}
+
/** 一张图的头:一个标题、一个大数、一句它此刻指的是什么。 */
export function ChartHead({ title, figure, note }: { title: string; figure: string; note: string }) {
return (
diff --git a/frontend/src/react/charts/heat-card.tsx b/frontend/src/react/charts/heat-card.tsx
index a73c4f98e..b75f1395d 100644
--- a/frontend/src/react/charts/heat-card.tsx
+++ b/frontend/src/react/charts/heat-card.tsx
@@ -7,7 +7,7 @@
import { useState } from 'react';
import type { ReactNode } from 'react';
-import { CHART_CARD, ChartHead } from './chart-card';
+import { CHART_CARD, ChartEmpty, ChartHead } from './chart-card';
import { TIP_SURFACE, TIP_SWATCH, TipRow } from './chart-tip';
import { dayCalendar, hourGrid, WEEKDAYS, type ActivityCounts, type HeatCell } from './heat';
@@ -71,10 +71,12 @@ export function HeatCard(
<section className={CHART_CARD}>
<ChartHead title={title} figure={(cell ? cell.count : total).toLocaleString()}
note={cell ? cell.label : words.unit} />
+ {/* 带坐标轴的星期 × 小时有 24 列,压到 320 以下格子和字都读不清,宁可在卡里横滚;
+ 每日那张只有 13 列,跟着卡片缩,最近几天不会藏到右边看不见的地方。 */}
<div className="relative">
<div className="min-w-0 overflow-x-auto">
<svg role="img" aria-label={title} onPointerLeave={() => setShown(-1)}
- viewBox={`0 0 ${width} ${height}`} className="block h-auto min-w-80 w-full">
+ viewBox={`0 0 ${width} ${height}`} className={axis ? 'block h-auto min-w-80 w-full' : 'block h-auto w-full'}>
{axis}
{cells.map((item, index) => {
const { x, y } = at(index);
@@ -119,24 +121,17 @@ const HOUR_AXIS = (
/** 一份活跃计数的两张热力图:星期 × 小时,和最近 91 天。
*
- * 没有可用记录时,给了 `empty` 就留一张只有那句话的卡,没给就整块不出现。 */
+ * 没有可用记录时留一张只有 `empty` 那句话的卡。 */
export function ActivityHeat(
{ activity, title, dailyTitle, words, tone, empty }:
{
activity: ActivityCounts | undefined; title: string; dailyTitle: string;
- words: HeatWords; tone: HeatTone; empty?: string;
+ words: HeatWords; tone: HeatTone; empty: string;
},
) {
const hours = hourGrid(activity);
const days = dayCalendar(activity);
- if (!days.cells.length) {
- return empty ? (
- <section className={CHART_CARD}>
- <h3 className="text-title-2-medium text-text-primary">{title}</h3>
- <p className="text-body-2-regular text-text-secondary">{empty}</p>
- </section>
- ) : null;
- }
+ if (!days.cells.length) return <ChartEmpty title={title}>{empty}</ChartEmpty>;
/* 两张卡按各自内容的高度排:星期 × 小时有 24 列,格子比每日那张小一半,同行拉成等高
会在它下面空出半张卡。 */
return (
diff --git a/frontend/src/react/evilcharts/ORIGIN.md b/frontend/src/react/evilcharts/ORIGIN.md
index 05516a188..07f985a3c 100644
--- a/frontend/src/react/evilcharts/ORIGIN.md
+++ b/frontend/src/react/evilcharts/ORIGIN.md
@@ -43,8 +43,8 @@
| 组合 | 用到的上游 | 做法 |
| --- | --- | --- |
-| `../charts/bar-card.tsx` 的 `BarCard` | `EvilBarChart` | 单系列,`ChartConfig` 只有 `value` 一个键;数值轴隐藏、留两成余量,数经 `barProps.label` 标在柱端;容器加 `flex-none`,否则在卡片的 flex 列里被压成 0 高。统计页的时长、画质、文件类型与播放次数 |
-| `../stats/radial-card.tsx` 的 `RadialCard` | `EvilRadialChart` | 键写成 `s0`…`sN`,名字放进 `label`:键会进 CSS 变量名与渐变 id,来源名、库名不能直接当键。圈的形状与点击走 `radialBarProps`,按 React 状态淡化其余段、点下钉住;图例格子由 Peach 自己画 |
-| `../taste/charts.tsx` 的 `TasteRadar` | `EvilRadarChart` | 取分数最高的三到六个口味维度,少于三个画不成面,整块不出现。画的是 `radius = √(次数 / 最大次数)` 一列,半径轴定死 `[0, 1]`,最大的维度落在外圈;浮层经 `ChartTip` 的 `valueKey` 读原始次数。`chartProps.outerRadius` 压到 58%,顶点外侧的维度名在窄栏里放得下 |
-| `../taste/charts.tsx` 的 `RankedBars` | `EvilBarChart`(`layout="horizontal"`) | 前八个口味维度,柱端标数的写法同 `BarCard`;高度按条数取档 |
+| `../charts/bar-card.tsx` 的 `BarCard` | `EvilBarChart` | 单系列,`ChartConfig` 只有 `value` 一个键;数值轴隐藏、留两成余量,数经 `barProps.label` 标在柱端,十万以上读成「万」「亿」(`shortCount`),横向布局经 `chartProps.margin` 右侧留 56px 给它;类别轴刻度换成 `../charts/chart-card.tsx` 的 `CategoryTick`,按刻度宽度截断加省略号、全名进 `<title>`,横向布局的轴宽跟着最长的名字走、封顶 104px;容器加 `flex-none`,否则在卡片的 flex 列里被压成 0 高;合计为 0 时整张图换成 `ChartEmpty` 说明卡。统计页的时长、画质、文件类型与播放次数 |
+| `../stats/radial-card.tsx` 的 `RadialCard` | `EvilRadialChart` | 键写成 `s0`…`sN`,名字放进 `label`:键会进 CSS 变量名与渐变 id,来源名、库名不能直接当键。圈的形状与点击走 `radialBarProps`,按 React 状态淡化其余段、点下钉住;图例格子由 Peach 自己画。超过六段时并掉尾部成「其余 N 项」(`radialSlices`);圈画的是 `arc` 列,不为 0 的段至少画满圈的 2%(`radialArc`),浮层经 `ChartTip` 的 `valueKey` 读原始 `value`;没有分段时换成 `ChartEmpty` 说明卡 |
+| `../taste/charts.tsx` 的 `TasteRadar` | `EvilRadarChart` | 取分数最高的三到六个口味维度,少于三个画不成面,整块不出现,画像卡只留排行条。画的是 `radius = √(次数 / 最大次数)` 一列,半径轴定死 `[0, 1]`,最大的维度落在外圈;浮层经 `ChartTip` 的 `valueKey` 读原始次数。`chartProps.outerRadius` 压到 58%;顶点外侧的维度名换成自己的 `RadarTick`,按顶点到图框边的距离截断加省略号,全名进 `<title>` |
+| `../taste/charts.tsx` 的 `RankedBars` | `EvilBarChart`(`layout="horizontal"`) | 前八个口味维度,柱端标数、右侧留白与类别轴刻度的写法同 `BarCard`;高度按条数取档 |
| `../charts/chart-tip.tsx` 的 `ChartTip` | `ChartTooltip`、`useChart`、`getPayloadConfigFromPayload` | 见上表「浮层内容」;画图的列经过刻度换算时,`valueKey` 指定浮层读原始数的那一列 |
diff --git a/frontend/src/react/stats/radial-card.tsx b/frontend/src/react/stats/radial-card.tsx
index 0b6ab418d..99a0b00e7 100644
--- a/frontend/src/react/stats/radial-card.tsx
+++ b/frontend/src/react/stats/radial-card.tsx
@@ -1,18 +1,21 @@
/* 库存的径向图:一段一圈,读数跟着指到的那一段走。
*
* 圈由 EvilCharts 的 `EvilRadialChart` 画,颜色按 `chart-1`…`chart-6` 循环,满圈是最长那段的
- * 1.1 倍(`radialCeiling`)。高亮是 React 状态:指针进出与点选各管一件事——扫过去是看一眼,
+ * 1.1 倍(`radialCeiling`)。段数超过六个时并掉尾部(`radialSlices`),不为 0 的段至少画一小截
+ * 弧(`radialArc`),浮层与读数仍是原始数。高亮是 React 状态:指针进出与点选各管一件事——扫过去是看一眼,
* 点下去是钉住。图下那排格子是同一份状态的按钮,键盘也够得着;上游的可点选图例只有一个
* 选中态,分不出「看一眼」和「钉住」,所以圈的形状与点击走 `radialBarProps` 接到这里。
* 差异登记在 `../evilcharts/ORIGIN.md`。 */
import { useState } from 'react';
import { Sector, type SectorProps } from 'recharts';
+import { fmtSize } from '@peach/legacy/core';
+
import { EvilRadialChart } from '@/registry/charts/recharts-radial-chart';
-import { CHART_CARD, sliceConfig, sliceKey } from '../charts/chart-card';
+import { CHART_CARD, ChartEmpty, sliceConfig, sliceKey } from '../charts/chart-card';
import { ChartTip } from '../charts/chart-tip';
-import { radialBarSize, radialCeiling, type RadialSlice } from './stats';
+import { radialArc, radialBarSize, radialCeiling, radialSlices, type RadialSlice } from './stats';
/** 六档图表色循环。类名写成整串,Tailwind 扫得到。 */
const TILE_SWATCH = [
@@ -31,26 +34,28 @@ const TILE_PINNED = [
];
export function RadialCard(
- { title, rows, unit = '个视频' }: { title: string; rows: RadialSlice[]; unit?: string },
+ { title, rows, empty, unit = '个视频' }: { title: string; rows: RadialSlice[]; empty: string; unit?: string },
) {
/* 钉住的那一段和指针扫过的那一段分开记:扫过去要能回到钉住的那一段,合成一个状态的话
鼠标一离开就把用户点下的选择也擦了。 */
const [pinned, setPinned] = useState(-1);
const [hovered, setHovered] = useState(-1);
- const slices = rows.filter((row) => Number.isFinite(row.value) && row.value >= 0);
- if (!slices.length) return null;
+ const slices = radialSlices(rows);
+ if (!slices.length) return <ChartEmpty title={title}>{empty}</ChartEmpty>;
const focus = hovered >= 0 ? hovered : pinned;
const total = slices.reduce((sum, row) => sum + row.value, 0);
const shown = slices[focus];
const toggle = (index: number) => setPinned((at) => (at === index ? -1 : index));
- const data = slices.map((row, index) => ({ slice: sliceKey(index), value: row.value }));
+ const ceiling = radialCeiling(slices.map((row) => row.value));
+ const data = slices.map((row, index) => (
+ { slice: sliceKey(index), value: row.value, arc: radialArc(row.value, ceiling) }));
return (
<section className={CHART_CARD}>
<header className="flex flex-wrap items-end justify-between gap-x-4 gap-y-1">
<span className="flex min-w-0 flex-col gap-1">
- <h3 className="text-title-2-medium text-text-primary">{shown ? shown.name : title}</h3>
+ <h3 className="text-title-2-medium wrap-anywhere text-text-primary">{shown ? shown.name : title}</h3>
<b className="text-display-4-medium tabular-nums text-text-primary">
{(shown ? shown.value : total).toLocaleString()}
</b>
@@ -59,9 +64,9 @@ export function RadialCard(
</header>
<div role="img" aria-label={title} onPointerLeave={() => setHovered(-1)}>
<EvilRadialChart data={data} nameKey="slice" config={sliceConfig(slices.map((row) => row.name))}
- max={radialCeiling(slices.map((row) => row.value))} innerRadius="22%"
+ max={ceiling} innerRadius="22%"
className="aspect-auto h-75 max-sm:h-65">
- <EvilRadialChart.RadialBar dataKey="value" barSize={radialBarSize(slices.length)} radialBarProps={{
+ <EvilRadialChart.RadialBar dataKey="arc" barSize={radialBarSize(slices.length)} radialBarProps={{
shape: (props: SectorProps & { index?: number }) => (
<Sector {...props}
opacity={focus >= 0 && focus !== props.index ? 0.3 : 1}
@@ -70,22 +75,23 @@ export function RadialCard(
onClick: (_entry: unknown, index: number) => toggle(index),
onMouseEnter: (_entry: unknown, index: number) => setHovered(index),
}} />
- <ChartTip nameKey="slice" hideLabel />
+ <ChartTip nameKey="slice" valueKey="value" hideLabel />
</EvilRadialChart>
</div>
<div className="inline-grid w-full grid-cols-3 gap-2 max-sm:grid-cols-2">
{slices.map((row, index) => (
- <button key={row.name} type="button" aria-pressed={pinned === index}
+ <button key={sliceKey(index)} type="button" aria-pressed={pinned === index}
onClick={() => toggle(index)}
onPointerEnter={() => setHovered(index)} onPointerLeave={() => setHovered(-1)}
onFocus={() => setHovered(index)} onBlur={() => setHovered(-1)}
className={`flex min-w-0 cursor-pointer flex-col items-start gap-1 rounded-xl bg-background-tertiary-default p-2.5 text-left outline-none aria-pressed:ring-1 aria-pressed:ring-inset focus-visible:ring-2 focus-visible:ring-border-focus-ring ${TILE_PINNED[index % 6]}`}>
- <span className="flex min-w-0 items-center gap-1.5 text-caption-1-regular text-text-secondary">
- <i aria-hidden className={`size-3 shrink-0 rounded-sm ${TILE_SWATCH[index % 6]}`} />
- {row.name}
+ {/* 名字折成几行时色块跟第一行对齐,不悬在几行中间。 */}
+ <span className="flex min-w-0 max-w-full items-start gap-1.5 text-caption-1-regular text-text-secondary">
+ <i aria-hidden className={`mt-0.5 size-3 shrink-0 rounded-sm ${TILE_SWATCH[index % 6]}`} />
+ <span className="min-w-0 wrap-anywhere">{row.name}</span>
</span>
<b className="text-title-2-medium tabular-nums text-text-primary">{row.value.toLocaleString()}</b>
- {row.detail ? <small className="text-caption-1-regular text-text-secondary">{row.detail}</small> : null}
+ {row.bytes != null ? <small className="text-caption-1-regular text-text-secondary">{fmtSize(row.bytes)}</small> : null}
</button>
))}
</div>
diff --git a/frontend/src/react/stats/stats-page.tsx b/frontend/src/react/stats/stats-page.tsx
index ecb124661..99c18ed97 100644
--- a/frontend/src/react/stats/stats-page.tsx
+++ b/frontend/src/react/stats/stats-page.tsx
@@ -33,9 +33,9 @@ import { SEGMENT, SEGMENTED_TRACK, SegmentedTabList } from '../components/segmen
import { StatCard, statCardClass, STAT_STRIP } from '../components/stat-card';
import { RadialCard } from './radial-card';
import {
- bandRows, fetchStats, lengthRows, mediumRows, percentOf, playedFor, playedItemUrl, reachedShare,
- replayRows, STATS_KEY, watchedShare, watchNote,
- type Attribution, type RecentPlay, type StatsData, type StorageVolume, type TagSource, type TopTag,
+ bandRows, fetchStats, fmtCount, known, lengthRows, mediumRows, percentText, playedFor, playedItemUrl,
+ reachedShare, replayRows, STATS_KEY, watchedShare, watchNote,
+ type Attribution, type Count, type RecentPlay, type StatsData, type StorageVolume, type TagSource, type TopTag,
} from './stats';
/** 收起时露这么多条排行。三十条一次铺开会把下面两个面板整个顶到屏外。 */
@@ -52,30 +52,42 @@ const NO_TAG_HINT = '补全资料或添加标签后,这里会显示馆藏中
const NO_WATCH_HINT = '开始播放后,这里会显示最近的真实观看证据。';
const NO_TAG_SOURCE_HINT = '刮削或手动打标之后,这里会显示每个来源覆盖了多少视频。';
const NO_VOLUME_HINT = '添加媒体文件夹后,这里会显示存储空间。';
+const NO_LIBRARY_HINT = '把媒体文件夹归进媒体库后,这里会按库显示视频数。';
+const NO_LENGTH_HINT = '探测时长后,这里会显示时长分布。';
+const NO_QUALITY_HINT = '探测画质后,这里会显示画质分布。';
+const NO_PLAY_TIME_HINT = '开始播放后,这里会显示播放落在一周的哪些时段。';
+const NO_REPLAY_HINT = '开始播放后,这里会显示每个作品播了几次。';
+
+/** 进度条的读数:超出总数时按满格画,读屏值也不越过上限。 */
+const within = (value: number, max: number) => Math.min(Math.max(value, 0), max);
/** 一格事实:一个名字配一个数。面取浮层那一档(旧 `.insightfacts .kv` 的 `--surface`),
* 比卡面亮一级。 */
-function Fact({ term, value }: { term: string; value: number }) {
+function Fact({ term, value }: { term: string; value: Count }) {
return (
<div className="flex min-h-16 min-w-0 flex-col gap-1.5 rounded-2lg bg-background-primary-default p-3">
<span className="text-caption-1-regular text-text-secondary">{term}</span>
- <b className="text-title-3-medium tabular-nums text-text-primary">{value.toLocaleString()}</b>
+ <b className="text-title-3-medium tabular-nums text-text-primary">{fmtCount(value)}</b>
</div>
);
}
/** 一条带进度的覆盖率:读数、占比与那条条共用同一对分子分母。 */
-function Coverage({ term, value, total }: { term: string; value: number; total: number }) {
+function Coverage({ term, value, total }: { term: string; value: Count; total: number }) {
+ const max = Math.max(total, 1);
return (
<div className="flex flex-col gap-1.5 border-b border-separator-border py-3 last:border-b-0">
<p className="flex items-baseline justify-between gap-3 text-body-2-regular text-text-primary">
<span>{term}</span>
<b className="tabular-nums">
- {value.toLocaleString()}
- <span className="ml-1.5 text-caption-1-regular text-text-secondary">{percentOf(value, total)}%</span>
+ {fmtCount(value)}
+ {known(value)
+ ? <span className="ml-1.5 text-caption-1-regular text-text-secondary">{percentText(value, total)}</span>
+ : null}
</b>
</p>
- <Progress label={`${term}:${value.toLocaleString()} / ${total.toLocaleString()}`} value={value} max={Math.max(total, 1)} />
+ <Progress label={`${term}:${fmtCount(value)} / ${total.toLocaleString()}`}
+ value={known(value) ? within(value, max) : 0} max={max} />
</div>
);
}
@@ -121,18 +133,18 @@ function InventoryDetail({ data, configurable, openMediaSettings }: { data: Stat
return (
<div className="flex flex-col gap-5">
<div className="inline-grid w-full gap-5 md:grid-cols-2">
- <RadialCard title="网盘与本地" rows={data.by_loc.map((row) => (
- { name: LOC[row.k] ?? row.k, value: row.videos, detail: fmtSize(row.bytes) }))} />
- <RadialCard title="媒体库" rows={data.by_library.map((row) => (
- { name: row.name, value: row.videos, detail: fmtSize(row.bytes) }))} />
+ <RadialCard title="网盘与本地" empty={NO_VIDEO_HINT} rows={data.by_loc.map((row) => (
+ { name: LOC[row.k] ?? row.k, value: row.videos, bytes: row.bytes }))} />
+ <RadialCard title="媒体库" empty={NO_LIBRARY_HINT} rows={data.by_library.map((row) => (
+ { name: row.name, value: row.videos, bytes: row.bytes }))} />
</div>
<div className="inline-grid w-full gap-5 md:grid-cols-2 xl:grid-cols-3">
<BarCard title="时长" unit="个视频" series="视频" color={INVENTORY_COLOR}
- rows={lengthRows(data.by_length)} />
+ rows={lengthRows(data.by_length)} empty={NO_LENGTH_HINT} />
<BarCard title="画质" unit="个视频" series="视频" color={INVENTORY_COLOR}
- rows={bandRows(data.by_quality)} />
+ rows={bandRows(data.by_quality)} empty={NO_QUALITY_HINT} />
<BarCard title="文件类型" unit="个条目" series="条目" color={INVENTORY_COLOR} layout="horizontal"
- rows={mediumRows(data.by_medium)} />
+ rows={mediumRows(data.by_medium)} empty={NO_VIDEO_HINT} />
</div>
</div>
);
@@ -143,9 +155,9 @@ function ViewingCharts({ data }: { data: StatsData }) {
return (
<>
<ActivityHeat activity={data.play_activity} title="播放时间" dailyTitle="每日播放"
- words={{ unit: '个作品', series: '作品', cellUnit: '个作品' }} tone={5} />
+ words={{ unit: '个作品', series: '作品', cellUnit: '个作品' }} tone={5} empty={NO_PLAY_TIME_HINT} />
<BarCard title="播放次数" unit="个作品" series="作品" color={VIEWING_COLOR}
- rows={replayRows(data.replays)} />
+ rows={replayRows(data.replays)} empty={NO_REPLAY_HINT} />
</>
);
}
@@ -175,11 +187,13 @@ function VolumeRow({ volume }: { volume: StorageVolume }) {
{total != null ? (
<b className="whitespace-nowrap tabular-nums">
{fmtSize(used)}
- <span className="ml-1.5 text-caption-1-regular text-text-secondary">{percentOf(used, total)}%</span>
+ <span className="ml-1.5 text-caption-1-regular text-text-secondary">{percentText(used, total)}</span>
</b>
) : <span className="whitespace-nowrap text-text-secondary">{volume.online ? '容量未取得' : '离线'}</span>}
</header>
- {total != null ? <Progress label={`${volume.label}空间使用率`} value={used} max={Math.max(total, 1)} /> : null}
+ {total != null
+ ? <Progress label={`${volume.label}空间使用率`} value={within(used, Math.max(total, 1))} max={Math.max(total, 1)} />
+ : null}
<p className="flex justify-between gap-3 text-caption-1-regular text-text-secondary">
<span className="min-w-0 break-words">{volume.root ?? '未映射'}</span>
{total != null
@@ -216,7 +230,7 @@ function TagRanking({ tags, tagLabel, onTag }: { tags: TopTag[] } & StatsProps)
<ExpandableRanking previewCount={RANKING_PREVIEW}
className="inline-grid w-full gap-x-6 gap-y-1 sm:grid-cols-2">
{tags.map((tag, index) => (
- <li key={tag.k} className="min-w-0">
+ <li key={`${tag.k}:${index}`} className="min-w-0">
<button type="button" onClick={() => onTag(tag.k)}
className="flex min-h-11 w-full min-w-0 cursor-pointer items-center gap-2.5 rounded-lg px-3 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-border-focus-ring">
<span className="w-6 shrink-0 text-caption-1-regular tabular-nums text-text-secondary">{index + 1}</span>
@@ -248,7 +262,8 @@ function RecentWatches({ rows }: { rows: RecentPlay[] }) {
className="block max-w-full overflow-hidden whitespace-nowrap hover:underline">{row.name}</a>
</h3>
<p className="flex flex-wrap gap-3 text-caption-1-regular text-text-secondary">
- <span>{row.creator ?? ''}</span><span>{watchNote(row)}</span>
+ {row.creator ? <span className="min-w-0 wrap-anywhere">{row.creator}</span> : null}
+ <span>{watchNote(row)}</span>
</p>
</div>
<div className="min-w-0 basis-40">
@@ -282,7 +297,8 @@ function TagSources({ sources, videos }: { sources: TagSource[]; videos: number
<small className="ml-1 text-caption-1-regular font-normal text-text-secondary">个视频</small>
</b>
</header>
- <Progress label={`${source.k} 覆盖视频`} value={source.assets} max={Math.max(videos, 1)} />
+ <Progress label={`${source.k} 覆盖视频`} value={within(source.assets, Math.max(videos, 1))}
+ max={Math.max(videos, 1)} />
<small className="text-caption-1-regular text-text-secondary">{source.n.toLocaleString()} 条标签</small>
</article>
))}
@@ -316,7 +332,8 @@ export function StatsPage(props: StatsProps) {
const storage = data.storage_summary;
const videos = data.by_loc.reduce((sum, row) => sum + row.videos, 0);
const bytes = data.by_loc.reduce((sum, row) => sum + row.bytes, 0);
- const coverage = percentOf(data.tag_cov, data.attribution.videos);
+ const coverage = known(data.tag_cov) ? percentText(data.tag_cov, data.attribution.videos) : '未取得';
+ const covered = `${fmtCount(data.tag_cov)} / ${data.attribution.videos.toLocaleString()}`;
return (
<Page>
<p className="text-caption-1-regular text-text-secondary">
@@ -327,17 +344,16 @@ export function StatsPage(props: StatsProps) {
<MetricTab id="inventory" label="馆藏视频" icon={RiDatabase2Line} accent={0}
figure={videos.toLocaleString()} detail={fmtSize(bytes)} />
<MetricTab id="viewing" label="看过" icon={RiEyeLine} accent={1}
- figure={consumption.played.toLocaleString()} detail={playedFor(consumption.play_seconds)} />
+ figure={fmtCount(consumption.played)} detail={playedFor(consumption.play_seconds)} />
<MetricTab id="coverage" label="内容标签" icon={RiPriceTag3Line} accent={2}
- figure={`${coverage}%`}
- detail={`${data.tag_cov.toLocaleString()} / ${data.attribution.videos.toLocaleString()}`} />
+ figure={coverage} detail={covered} />
<MetricTab id="storage" label="使用空间" icon={RiHardDrive2Line} accent={3}
- figure={`${storage.online} 个卷`}
+ figure={`${storage.online.toLocaleString()} 个卷`}
detail={storage.measured ? `已用 ${fmtSize(storage.used)}` : '容量未取得'} />
</TabList>
<TabPanel id="inventory"><InventoryDetail data={data} {...props} /></TabPanel>
<TabPanel id="viewing" className="flex flex-col gap-5">
- <Detail headline={<Headline term="观看" figure={consumption.played.toLocaleString()} unit="个作品有播放记录" />}>
+ <Detail headline={<Headline term="观看" figure={fmtCount(consumption.played)} unit="个作品有播放记录" />}>
<div className="inline-grid w-full gap-3 sm:grid-cols-2">
<Fact term="馆藏观看" value={consumption.library_played} />
<Fact term="在线直接观看" value={consumption.online_played} />
@@ -352,13 +368,12 @@ export function StatsPage(props: StatsProps) {
<ViewingCharts data={data} />
</TabPanel>
<TabPanel id="coverage">
- <Detail headline={<Headline term="内容标签覆盖" figure={`${coverage}%`}
- unit={`${data.tag_cov.toLocaleString()} / ${data.attribution.videos.toLocaleString()}`} />}>
+ <Detail headline={<Headline term="内容标签覆盖" figure={coverage} unit={covered} />}>
<CoverageDetail attribution={data.attribution} />
</Detail>
</TabPanel>
<TabPanel id="storage">
- <Detail headline={<Headline term="使用空间" figure={String(storage.measured)} unit="个卷已取得容量" />}>
+ <Detail headline={<Headline term="使用空间" figure={storage.measured.toLocaleString()} unit="个卷已取得容量" />}>
<StorageDetail volumes={data.storage_volumes} {...props} />
</Detail>
</TabPanel>
diff --git a/frontend/src/react/stats/stats.ts b/frontend/src/react/stats/stats.ts
index eac5871a1..41f6795aa 100644
--- a/frontend/src/react/stats/stats.ts
+++ b/frontend/src/react/stats/stats.ts
@@ -21,9 +21,12 @@ export interface LocationCount { k: string; n: number; bytes: number; videos: nu
/** 按媒体库分的库存。`name` 是用户给这个库起的名字。 */
export interface LibraryCount { k: string; name: string; icon: string; videos: number; bytes: number }
+/** 一个计数。服务端某一项取不到时回 null,页面读成「未取得」。 */
+export type Count = number | null;
+
/** 视频的资料归属:分母是 `videos`,其余几项是已经有那一项的条数。 */
export interface Attribution {
- videos: number; creator: number; code: number; studio: number; thumb: number; duration: number;
+ videos: number; creator: Count; code: Count; studio: Count; thumb: Count; duration: Count;
}
/** 一个标签来源覆盖了多少条标签、多少个视频。 */
@@ -32,8 +35,8 @@ export interface TagSource { k: string; n: number; assets: number }
export interface TopTag { k: string; n: number; cat: string }
export interface Consumption {
- played: number; library_played: number; online_played: number; play_seconds: number;
- o_total: number; liked: number; dislike: number; seen: number; trash: number; skimmed: number;
+ played: Count; library_played: Count; online_played: Count; play_seconds: Count;
+ o_total: Count; liked: Count; dislike: Count; seen: Count; trash: Count; skimmed: Count;
}
/** 按文件类型分的条目数。`k` 是 `video`/`image`/`archive` 这些媒介代号。 */
@@ -72,7 +75,7 @@ export interface StatsData {
replays: ReplayCount[];
attribution: Attribution;
tag_source: TagSource[];
- tag_cov: number;
+ tag_cov: Count;
top_tags: TopTag[];
consumption: Consumption;
recent: RecentPlay[];
@@ -90,13 +93,34 @@ export async function prefetchStats(signal: AbortSignal): Promise<void> {
await queryClient.fetchQuery({ queryKey: STATS_KEY, queryFn: () => fetchStats(signal) });
}
-/** 整数百分比。分母是 0 时读 0,不是 NaN。 */
-export const percentOf = (value: number, total: number): number =>
- total ? Math.round(value / total * 100) : 0;
+/** 取得了的计数:null、NaN 与无穷都不算。 */
+export const known = (value: Count | undefined): value is number =>
+ value != null && Number.isFinite(value);
+
+/** 一个计数的读法:千分位;取不到时读「未取得」。 */
+export const fmtCount = (value: Count | undefined): string =>
+ (known(value) ? value.toLocaleString() : '未取得');
+
+/** 整数百分比,夹在 0 到 100 之间。分母是 0 或取不到时读 0,不是 NaN。 */
+export const percentOf = (value: Count | undefined, total: Count | undefined): number =>
+ (known(value) && known(total) && total > 0
+ ? Math.min(100, Math.max(0, Math.round(value / total * 100))) : 0);
+
+/** 百分比的读法:有一点但不到 0.5% 时读「<1%」,不读成 0%。 */
+export const percentText = (value: Count | undefined, total: Count | undefined): string => {
+ const share = percentOf(value, total);
+ return !share && known(value) && value > 0 && known(total) && total > 0 ? '<1%' : `${share}%`;
+};
-/** 累计播放时长:够一小时读小时,不够读分钟。 */
-export const playedFor = (seconds: number): string =>
- seconds >= 3600 ? `${(seconds / 3600).toFixed(1)} 小时` : `${Math.round(seconds / 60)} 分钟`;
+/** 累计播放时长:不到一小时读分钟,不到 48 小时读小时,再往上读天。 */
+export const playedFor = (seconds: Count | undefined): string => {
+ if (!known(seconds)) return '未取得';
+ const value = Math.max(0, seconds);
+ if (value >= 48 * 3600) {
+ return `${(value / 86_400).toLocaleString(undefined, { maximumFractionDigits: 1 })} 天`;
+ }
+ return value >= 3600 ? `${(value / 3600).toFixed(1)} 小时` : `${Math.round(value / 60)} 分钟`;
+};
/** 真实看过的比例:播放秒数占时长,封顶 100%。时长未取得时读 0。 */
export const watchedShare = (row: RecentPlay): number =>
@@ -119,12 +143,34 @@ export const watchNote = (row: RecentPlay): string => {
export const playedItemUrl = (row: RecentPlay): string =>
`${row.kind === 'online' ? '/follow/item/' : '/item/'}${row.id}`;
-/** 径向图里的一段。 */
-export interface RadialSlice { name: string; value: number; detail: string }
+/** 径向图里的一段。`bytes` 是这一段占的体积,图例格子里读成它的大小。 */
+export interface RadialSlice { name: string; value: number; bytes?: number }
+
+/** 一张径向图最多画几圈:图表色只有六档,第七圈起颜色就和前面的重了。 */
+export const RADIAL_MAX = 6;
+
+/** 径向图要画的几段。段数超过 `RADIAL_MAX` 时留下最多的前五段,其余并成一段「其余 N 项」。
+ * 负数与非有限的值先滤掉。 */
+export function radialSlices(rows: RadialSlice[], max = RADIAL_MAX): RadialSlice[] {
+ const slices = rows.filter((row) => Number.isFinite(row.value) && row.value >= 0);
+ if (slices.length <= max) return slices;
+ const ranked = [...slices].sort((a, b) => b.value - a.value);
+ const rest = ranked.slice(max - 1);
+ return [...ranked.slice(0, max - 1), {
+ name: `其余 ${rest.length.toLocaleString()} 项`,
+ value: rest.reduce((sum, row) => sum + row.value, 0),
+ bytes: rest.reduce((sum, row) => sum + (row.bytes ?? 0), 0),
+ }];
+}
/** 满圈代表的数:最长那段留一成余量,看得出是「最多」而不是「全部」。 */
export const radialCeiling = (values: number[]): number => Math.max(1, ...values) * 1.1;
+/** 一段画多长的弧:不为 0 的段至少画满圈的 2%,和最长那段差几个数量级时也看得见。
+ * 0 就是 0,不垫高。 */
+export const radialArc = (value: number, ceiling: number): number =>
+ (value > 0 ? Math.max(value, ceiling * 0.02) : 0);
+
/** 每圈的粗细(像素)。段数多时压细,最内圈才不会缩进圆心,也不会和相邻那圈叠在一起。 */
export const radialBarSize = (count: number): number =>
Math.max(4, Math.min(14, Math.round(90 / Math.max(1, count))));
@@ -152,10 +198,10 @@ export const bandRows = (rows: BandCount[], labels: Record<string, string> = {})
export const lengthRows = (rows: BandCount[]): BarRow[] => bandRows(rows, LENGTH_LABEL);
/** 播放次数的分档:五次以内一次一档,往后并成两档,长尾不把柱子拉成一排细线。
- * 名字写短,390 宽的手机上七根柱子的类别名不互相挤掉。 */
+ * 名字只写次数,单位在图的标题里:320 宽的手机上七根柱子的类别名不互相挤掉。 */
const REPLAY_BANDS: readonly [number, number, string][] = [
- [1, 1, '1 次'], [2, 2, '2 次'], [3, 3, '3 次'], [4, 4, '4 次'], [5, 5, '5 次'],
- [6, 9, '6–9 次'], [10, Infinity, '≥10 次'],
+ [1, 1, '1'], [2, 2, '2'], [3, 3, '3'], [4, 4, '4'], [5, 5, '5'],
+ [6, 9, '6–9'], [10, Infinity, '≥10'],
];
export const replayRows = (rows: ReplayCount[]): BarRow[] =>
diff --git a/frontend/src/react/taste/charts.tsx b/frontend/src/react/taste/charts.tsx
index 05b0b8377..2c85d3718 100644
--- a/frontend/src/react/taste/charts.tsx
+++ b/frontend/src/react/taste/charts.tsx
@@ -6,18 +6,42 @@
* 是 `stroke-width`,颜色只取 BoardUI 的 `chart-*` 档;指向一条流或一个节点时读数换成它的,
* 换的是 React 状态,指针离开或焦点移走就回到总数。差异登记在 `../boardui/ORIGIN.md`。 */
import { useState } from 'react';
+import { Text } from 'recharts';
import { EvilBarChart } from '@/registry/charts/recharts-bar-chart';
import { EvilRadarChart } from '@/registry/charts/recharts-radar-chart';
-import { BAR_DOMAIN, barLabel } from '../charts/bar-card';
-import { CHART_CARD, CHART_COLORS, ChartHead, tone } from '../charts/chart-card';
+import { BAR_DOMAIN, BAR_LABEL_ROOM, barLabel } from '../charts/bar-card';
+import {
+ CategoryTick, categoryAxisWidth, CHART_CARD, CHART_COLORS, ChartHead, fitLabel, tone,
+} from '../charts/chart-card';
import { ChartTip } from '../charts/chart-tip';
import {
flowGraph, flowLabel, FLOW_LABEL_X, FLOW_NODE_WIDTH, FLOW_VIEWBOX, radarRows, RANK_MAX, topScores,
type CreatorFlow, type RankRow,
} from './taste';
+/** 雷达顶点外侧的维度名。左右两侧的名字往外排,能用的宽度是顶点到图框边;上下两个居中排,
+ * 能用的是顶点到较近那条边的两倍。放不下就截断,全名在 `<title>`、浮层与读屏名称里。 */
+function RadarTick(
+ props: { x?: number; cx?: number; textAnchor?: string; payload?: { value?: unknown } } & Record<string, unknown>,
+) {
+ const { x = 0, cx, textAnchor, payload, ...rest } = props;
+ const name = String(payload?.value ?? '');
+ const width = typeof cx === 'number' ? cx * 2 : 0;
+ const room = !width ? 56
+ : textAnchor === 'start' ? width - x
+ : textAnchor === 'end' ? x
+ : 2 * Math.min(x, width - x);
+ return (
+ <g>
+ <title>{name}</title>
+ <Text {...(rest as object)} x={x} textAnchor={textAnchor as 'start' | 'middle' | 'end' | undefined}
+ fill="currentColor" fontSize={12}>{fitLabel(name, room - 4)}</Text>
+ </g>
+ );
+}
+
/** 六档图表色循环。类名写成整串,Tailwind 扫得到。 */
const FLOW_STROKE = [
'stroke-chart-1', 'stroke-chart-2', 'stroke-chart-3',
@@ -59,7 +83,7 @@ export function TasteRadar({ rows, label }: { rows: RankRow[]; label: string })
<EvilRadarChart data={data} config={RADAR_CONFIG} chartProps={{ outerRadius: '58%' }}
className="aspect-auto h-70 text-text-secondary">
<EvilRadarChart.PolarGrid />
- <EvilRadarChart.PolarAngleAxis dataKey="name" />
+ <EvilRadarChart.PolarAngleAxis dataKey="name" tick={<RadarTick />} />
{/* 半径轴定死在 0 到 1:外圈就是最大的维度,不让 Recharts 往上取整留出空圈。网格圈跟着
这根轴的刻度走,Recharts 默认只取整数刻度,要放开小数才有四等分的圈。 */}
<EvilRadarChart.PolarRadiusAxis domain={[0, 1]} allowDecimals tick={false} />
@@ -71,15 +95,18 @@ export function TasteRadar({ rows, label }: { rows: RankRow[]; label: string })
}
/** 口味维度排行:一个维度一条横向的柱,画的是 EvilCharts 的 `EvilBarChart`,数标在柱尾。
- * 整块在纵向 flex 里撑满父级给的高度,图表容器本身是 `flex-1`。 */
+ * 整块在纵向 flex 里撑满父级给的高度,图表容器本身是 `flex-1`。维度名那一栏有宽度上限,
+ * 名字再长也只截断,不把柱子挤没。 */
export function RankedBars({ rows, label }: { rows: RankRow[]; label: string }) {
const data = topScores(rows, RANK_MAX);
if (!data.length) return null;
return (
<section aria-label={label} className={`flex grow flex-col ${RANK_HEIGHT[data.length]}`}>
<EvilBarChart data={data} config={DIMENSION_CONFIG} layout="horizontal" barRadius={4}
- chartProps={{ maxBarSize: RANK_BAR_SIZE }} className="aspect-auto text-text-secondary">
- <EvilBarChart.YAxis dataKey="name" interval={0} />
+ chartProps={{ maxBarSize: RANK_BAR_SIZE, margin: { top: 5, right: BAR_LABEL_ROOM, bottom: 5, left: 5 } }}
+ className="aspect-auto text-text-secondary">
+ <EvilBarChart.YAxis dataKey="name" interval={0} tick={<CategoryTick along="y" />}
+ width={categoryAxisWidth(data.map((row) => row.name))} />
<EvilBarChart.XAxis hide domain={BAR_DOMAIN} />
<EvilBarChart.Bar dataKey="value" enableHoverHighlight
barProps={{ dataKey: 'value', label: barLabel('right') }} />
@@ -104,10 +131,20 @@ export function CreatorSankey({ flows }: { flows: CreatorFlow[] | undefined }) {
<section className={CHART_CARD}>
<ChartHead title="创作者线索来源" figure={(shown ? shown.value : graph.total).toLocaleString()}
note={shown ? shown.label : '条线索'} />
- <div className="min-w-0 overflow-x-auto">
- <svg viewBox={`0 0 ${FLOW_VIEWBOX.width} ${FLOW_VIEWBOX.height}`} fill="none"
+ {/* 两侧各留一截给节点名,画布窄于 640 时字缩到读不清:手机上换成按线索数排的一列流向。 */}
+ <ol aria-label="来源网站与创作者线索" className="flex flex-col sm:hidden">
+ {[...graph.links].sort((a, b) => b.value - a.value).map((link) => (
+ <li key={link.key}
+ className="flex items-baseline justify-between gap-3 border-b border-separator-border py-2 text-body-2-regular text-text-primary last:border-b-0">
+ <span className="min-w-0 wrap-anywhere">{link.label}</span>
+ <b className="shrink-0 tabular-nums">{link.value.toLocaleString()}</b>
+ </li>
+ ))}
+ </ol>
+ <div className="min-w-0 max-sm:hidden">
+ <svg viewBox={`0 0 ${FLOW_VIEWBOX.width} ${graph.height}`} fill="none"
role="img" aria-label="来源网站与创作者线索"
- className="block h-auto max-h-130 min-w-160 w-full" onPointerLeave={() => setShown(null)}>
+ className="block h-auto w-full" onPointerLeave={() => setShown(null)}>
<g>
{graph.links.map((link) => (
<path key={link.key} d={link.d} strokeWidth={link.width} tabIndex={0} role="img"
@@ -145,7 +182,7 @@ export function CreatorSankey({ flows }: { flows: CreatorFlow[] | undefined }) {
</g>
</svg>
</div>
- <footer className="flex justify-between gap-3 text-caption-1-regular text-text-secondary">
+ <footer className="flex justify-between gap-3 text-caption-1-regular text-text-secondary max-sm:hidden">
<span>来源网站</span><span>创作者 · 线索占比</span>
</footer>
</section>
diff --git a/frontend/src/react/taste/taste-page.tsx b/frontend/src/react/taste/taste-page.tsx
index 3697066b1..9b70fa941 100644
--- a/frontend/src/react/taste/taste-page.tsx
+++ b/frontend/src/react/taste/taste-page.tsx
@@ -53,9 +53,9 @@ import { busyProps } from '../settings/use-action';
import { ActivityHeat } from '../charts/heat-card';
import { CreatorSankey, RankedBars, TasteRadar } from './charts';
import {
- DEFAULT_WINDOW, fetchTaste, fetchTasteJob, IDLE_POLL_MS, importTasteExport, rankDetail,
- rankShares, removeTasteSource, startTasteRefresh, tasteDate, tasteHours, tasteKey,
- TASTE_REFRESH_KEY, TASTE_WINDOWS, type RankRow, type TasteData, type TasteJob,
+ DEFAULT_WINDOW, fetchTaste, fetchTasteJob, historySpan, IDLE_POLL_MS, importTasteExport, radarRows,
+ rankDetail, rankShares, removeTasteSource, startTasteRefresh, tasteDate, tasteDimensions, tasteHours,
+ tasteKey, TASTE_REFRESH_KEY, TASTE_WINDOWS, type RankRow, type TasteData, type TasteJob,
} from './taste';
/** 收起时露这么多条名次。二十条一次铺开会把下面几块整个顶到屏外。 */
@@ -72,6 +72,12 @@ const NO_SOURCE_HINT = '导入或读取浏览记录后,这里会列出已采
const NO_LEAD_HINT = '馆藏里暂时没有对得上浏览信号的标签。';
const NO_CATEGORY_HINT = '采集浏览记录后,这里会显示聚合后的口味证据。';
const GAP_HINT = '这些词在浏览记录中出现,但 Peach 观看记录还没有对应证据';
+const NO_BROWSER_TAG_HINT = '采集浏览记录后,这里会列出浏览过的标签。';
+const NO_BROWSER_CREATOR_HINT = '采集浏览记录后,这里会列出浏览过的创作者。';
+const NO_DOMAIN_HINT = '采集浏览记录后,这里会列出常访问的网站。';
+const NO_PEACH_TAG_HINT = '在 Peach 里播放或评价作品后,这里会列出对应的标签。';
+const NO_PEACH_CREATOR_HINT = '在 Peach 里播放或评价作品后,这里会列出对应的创作者。';
+const NO_PEACH_PERFORMER_HINT = '在 Peach 里播放或评价作品后,这里会列出对应的女优。';
const GUIDE_LOCAL = '在运行 Peach 的电脑上使用浏览器:点上面的「读取浏览器历史」。';
const GUIDE_REMOTE = '记录在其他设备上:导出文件后,点上面的「导入历史文件」。多台设备的文件分别导入。';
const GUIDE_REFRESH = '需要刷新时再次读取或导入;数据源可在页面底部移除。';
@@ -171,7 +177,7 @@ function RankList({ rows, kind, visual, empty, onSignal }: RankListProps) {
const shape = 'relative isolate flex min-h-11 w-full min-w-0 items-center gap-2.5'
+ ' rounded-lg px-3 py-2 text-left';
return (
- <li key={row.name} className="min-w-0">
+ <li key={`${row.name}:${index}`} className="min-w-0">
{clickable
? <button type="button" onClick={() => onSignal(kind, row.name)}
className={`${shape} cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-border-focus-ring`}>
@@ -228,12 +234,12 @@ function AnalysisCard({ data, onSignal, navigate }:
<h3 className="text-title-2-medium text-text-primary">口味总结</h3>
{/* 结论句是这张卡的主角:旧 `.tasteleads .tastelede p` 是 20/30 的主文字色,比正文
大一档、限宽 64ch。「有多少把握」是它的注脚,旧版就是一句灰字配一枚 8px 圆点。 */}
- <p className="max-w-prose text-title-2-regular text-text-primary">{analysis.headline}</p>
+ <p className="max-w-prose text-title-2-regular wrap-anywhere text-text-primary">{analysis.headline}</p>
<p className="flex flex-wrap items-center gap-2 text-body-2-regular text-text-secondary">
<i aria-hidden className={`size-2 shrink-0 rounded-full ${confidence.level === 'high'
? 'bg-status-lime-text'
: confidence.level === 'medium' ? 'bg-status-yellow-text' : 'bg-text-tertiary'}`} />
- {confidence.label || '仍在学习'}
+ <span className="min-w-0 wrap-anywhere">{confidence.label || '仍在学习'}</span>
</p>
</header>
{analysis.points?.length ? (
@@ -252,8 +258,8 @@ function AnalysisCard({ data, onSignal, navigate }:
<button key={lead.key} type="button" onClick={lead.act}
className={`flex w-full min-w-0 cursor-pointer items-center gap-3 ${TILE} text-left outline-none hover:bg-background-primary-hover focus-visible:ring-2 focus-visible:ring-border-focus-ring`}>
<span className="flex min-w-0 grow flex-col gap-1">
- <b className="text-body-2-medium text-text-primary">{lead.title}</b>
- <small className="text-caption-1-regular text-text-secondary">{lead.detail}</small>
+ <b className="text-body-2-medium wrap-anywhere text-text-primary">{lead.title}</b>
+ <small className="text-caption-1-regular wrap-anywhere text-text-secondary">{lead.detail}</small>
</span>
<RiArrowRightSLine aria-hidden className="size-4 shrink-0 text-text-tertiary" />
</button>
@@ -368,7 +374,7 @@ function SourceList(
{`${source.browser} · ${source.host} · ${Number(source.visits || 0).toLocaleString()} 条`}
</small>
</span>
- <Button variant="secondary" size="small" aria-label={`移除 ${source.profile}`}
+ <Button variant="secondary" size="small" aria-label={`移除 ${source.profile}`} className="shrink-0"
iconOnly leadingIcon={RiDeleteBinLine} {...busyProps(remove.isPending)}
onClick={() => {
if (remove.isPending) return;
@@ -450,7 +456,8 @@ export function TastePage(props: TasteProps) {
const coverage = data.coverage || {};
const rank = data.rankings || {};
const storage = data.storage || {};
- const categories = rank.browser_categories || [];
+ const categories = tasteDimensions(rank.browser_categories || []);
+ const radar = radarRows(categories).length > 0;
const gaps = data.gaps || [];
const tagged = coverage.tagged || 0;
const identified = coverage.identified || 0;
@@ -494,17 +501,20 @@ export function TastePage(props: TasteProps) {
<div className={STAT_STRIP}>
<SummaryCard accent={0} icon={RiHistoryLine} term="浏览记录"
figure={Number(summary.history_visits || 0).toLocaleString()}
- detail={`${summary.history_sources || 0} 个数据源 · ${tasteDate(summary.range_start)}—${tasteDate(summary.range_end)}`} />
+ detail={historySpan(summary)} />
<SummaryCard accent={1} icon={RiPriceTag3Line} term="口味维度"
figure={categories.length.toLocaleString()} detail={categories[0]?.name || '尚无主维度'} />
<SummaryCard accent={2} icon={RiSearchLine} term="浏览候选" figure={gaps.length.toLocaleString()} />
<SummaryCard accent={3} icon={RiDatabase2Line} term="私有导出"
figure={Number(storage.exports || 0).toLocaleString()} detail={fmtSize(storage.bytes || 0)} />
</div>
- <section className={`${CARD} md:flex-row md:gap-6`} aria-label="浏览器画像">
- <div className="flex shrink-0 flex-col gap-2 pb-5 md:w-80 md:pr-6 md:pb-0">
+ {/* 维度不足三个画不成雷达:左栏只留标题与更新时间,排行条占满整张卡。 */}
+ <section className={radar ? `${CARD} md:flex-row md:gap-6` : CARD} aria-label="浏览器画像">
+ <div className={radar
+ ? 'flex shrink-0 flex-col gap-2 pb-5 md:w-80 md:pr-6 md:pb-0'
+ : 'flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1'}>
<span className="text-caption-1-regular text-text-secondary">浏览器画像</span>
- <TasteRadar rows={categories} label="主要口味维度" />
+ {radar ? <TasteRadar rows={categories} label="主要口味维度" /> : null}
<small className="text-caption-1-regular text-text-secondary">
{data.updated_at ? `更新于 ${tasteDate(data.updated_at)}` : '尚未采集浏览记录'}
</small>
@@ -522,9 +532,9 @@ export function TastePage(props: TasteProps) {
<CreatorSankey flows={data.creator_flows} />
<DimensionPanels label="浏览器口味维度" onSignal={onSignal}
panels={[
- { id: 'tags', name: '标签', props: { rows: rank.browser_tags || [], kind: 'tag', visual: 'none', empty: '暂无足够证据' } },
- { id: 'creators', name: '创作者', props: { rows: rank.browser_creators || [], kind: 'creator', visual: 'creator', empty: '暂无创作者证据' } },
- { id: 'domains', name: '常访问网站', props: { rows: rank.domains || [], kind: '', visual: 'domain', empty: '暂无网站证据' } },
+ { id: 'tags', name: '标签', props: { rows: rank.browser_tags || [], kind: 'tag', visual: 'none', empty: NO_BROWSER_TAG_HINT } },
+ { id: 'creators', name: '创作者', props: { rows: rank.browser_creators || [], kind: 'creator', visual: 'creator', empty: NO_BROWSER_CREATOR_HINT } },
+ { id: 'domains', name: '常访问网站', props: { rows: rank.domains || [], kind: '', visual: 'domain', empty: NO_DOMAIN_HINT } },
{ id: 'gaps', name: '浏览候选', props: { rows: gaps, kind: '', visual: 'none', empty: GAP_HINT } },
]} />
</TabPanel>
@@ -552,9 +562,9 @@ export function TastePage(props: TasteProps) {
</section>
<DimensionPanels label="Peach 口味维度" onSignal={onSignal}
panels={[
- { id: 'tags', name: '标签', props: { rows: rank.peach_tags || [], kind: 'tag', visual: 'none', empty: '暂无足够证据' } },
- { id: 'creators', name: '创作者', props: { rows: rank.peach_creators || [], kind: 'creator', visual: 'creator', empty: '暂无创作者证据' } },
- { id: 'performers', name: '女优', props: { rows: rank.peach_performers || [], kind: 'performer', visual: 'entity', empty: '暂无女优证据' } },
+ { id: 'tags', name: '标签', props: { rows: rank.peach_tags || [], kind: 'tag', visual: 'none', empty: NO_PEACH_TAG_HINT } },
+ { id: 'creators', name: '创作者', props: { rows: rank.peach_creators || [], kind: 'creator', visual: 'creator', empty: NO_PEACH_CREATOR_HINT } },
+ { id: 'performers', name: '女优', props: { rows: rank.peach_performers || [], kind: 'performer', visual: 'entity', empty: NO_PEACH_PERFORMER_HINT } },
]} />
</TabPanel>
</Tabs>
@@ -573,7 +583,7 @@ function CoverageMetric({ term, value, rest }: { term: string; value: number; re
<span>{term}</span>
<b className="tabular-nums">
{value.toLocaleString()}
- <span className="ml-1.5 text-caption-1-regular text-text-secondary">{`${rest} 项待补`}</span>
+ <span className="ml-1.5 text-caption-1-regular text-text-secondary">{`${rest.toLocaleString()} 项待补`}</span>
</b>
</p>
<Progress label={`${term}:${value.toLocaleString()} / ${total.toLocaleString()}`}
diff --git a/frontend/src/react/taste/taste.ts b/frontend/src/react/taste/taste.ts
index 629217e8d..35c9dfb1f 100644
--- a/frontend/src/react/taste/taste.ts
+++ b/frontend/src/react/taste/taste.ts
@@ -16,6 +16,7 @@ import { apiGet, apiSend, ApiError } from '../../api';
import type { BarRow } from '../charts/bar-card';
import type { ActivityCounts } from '../charts/heat';
import { queryClient } from '../query';
+import { playedFor } from '../stats/stats';
export const TASTE_URL = '/api/taste';
export const TASTE_REFRESH_URL = '/api/taste/refresh';
@@ -172,9 +173,20 @@ export const IDLE_POLL_MS = 10_000;
export const tasteDate = (value: string | null | undefined): string =>
(value ? new Date(value).toLocaleDateString('zh-CN') : '—');
-/** 累计时长:够一小时读小时,不够读分钟。与统计页同一套口径。 */
-export const tasteHours = (seconds: number): string =>
- (seconds >= 3600 ? `${(seconds / 3600).toFixed(1)} 小时` : `${Math.round(seconds / 60)} 分钟`);
+/** 浏览记录那张读数卡的脚注:几个数据源,加上记录覆盖的日期范围;两头都没有日期时不写范围。 */
+export function historySpan(summary: TasteSummary): string {
+ const sources = `${Number(summary.history_sources || 0).toLocaleString()} 个数据源`;
+ if (!summary.range_start && !summary.range_end) return sources;
+ return `${sources} · ${tasteDate(summary.range_start)}—${tasteDate(summary.range_end)}`;
+}
+
+/** 累计时长。与统计页同一套口径。 */
+export const tasteHours = playedFor;
+
+/** 「口味维度」读数:分数为正的维度才算,和雷达、排行条画出来的是同一批。 */
+export const tasteDimensions = (rows: RankRow[]): RankRow[] =>
+ rows.filter((row) => Number.isFinite(Number(row.score)) && Number(row.score) > 0)
+ .sort((a, b) => Number(b.score) - Number(a.score));
/** 一行在这一榜里的强度。浏览侧按访问次数,Peach 侧按分数,都退化到条目数。 */
export const rankStrength = (row: RankRow): number =>
@@ -184,8 +196,8 @@ export const rankStrength = (row: RankRow): number =>
export function rankDetail(row: RankRow): string {
if (row.web_visits == null) return Number(row.score || row.visits || 0).toLocaleString();
const parts: string[] = [];
- if (row.web_visits) parts.push(`浏览 ${row.web_visits}`);
- if (row.peach_items) parts.push(`Peach ${row.peach_items}`);
+ if (row.web_visits) parts.push(`浏览 ${Number(row.web_visits).toLocaleString()}`);
+ if (row.peach_items) parts.push(`Peach ${Number(row.peach_items).toLocaleString()}`);
return parts.join(' · ');
}
@@ -225,23 +237,58 @@ export interface FlowLink {
key: string; d: string; width: number; color: number;
source: number; target: number; value: number; label: string;
}
-export interface FlowGraph { nodes: FlowNode[]; links: FlowLink[]; total: number }
+export interface FlowGraph { nodes: FlowNode[]; links: FlowLink[]; total: number; height: number }
-/** 节点条宽与画布:左右各留一截给文字,视口 720×435。 */
+/** 节点条宽与画布:左右各留一截给文字,视口宽 720,高度跟着节点数走,最矮 435。 */
export const FLOW_NODE_WIDTH = 10;
export const FLOW_VIEWBOX = { width: 720, height: 435 } as const;
export const FLOW_LABEL_X = { source: 145, target: 545 } as const;
+/** 一侧最多几个节点。再多就留下线索最多的前几个,其余并成一个「其余 N …」节点。 */
+export const FLOW_SIDE_MAX = 12;
+
+/** 相邻两个节点之间的空隙,也就是两个节点中心的最小间距:节点名和它下面那行数从中心往上
+ * 约 7、往下约 22,隔 30 时小节点挤在一起,两行字也不压到下一个节点上。 */
+const FLOW_ROW = 30;
+
+/** 除去空隙之外,留给节点本身按线索数分的高度。 */
+const FLOW_NODE_ROOM = 240;
+
+/** 一侧的名字超过 `FLOW_SIDE_MAX` 个时,把线索少的那些名字映射到同一个合并节点上。 */
+function foldSide(flows: CreatorFlow[], side: 'source' | 'target', rest: (count: number) => string) {
+ const totals = new Map<string, number>();
+ for (const row of flows) totals.set(row[side], (totals.get(row[side]) ?? 0) + row.value);
+ if (totals.size <= FLOW_SIDE_MAX) return (name: string) => name;
+ const ranked = [...totals].sort((a, b) => b[1] - a[1]).map(([name]) => name);
+ const kept = new Set(ranked.slice(0, FLOW_SIDE_MAX - 1));
+ const merged = rest(ranked.length - kept.size);
+ return (name: string) => (kept.has(name) ? name : merged);
+}
+
/** 来源网站 → 创作者的流向布局。值为 0 或缺一端的流先滤掉,全空时返回 `null`。 */
export function flowGraph(rows: CreatorFlow[] = []): FlowGraph | null {
- const flows = rows.filter((row) =>
+ const valid = rows.filter((row) =>
row.source && row.target && Number.isFinite(row.value) && row.value > 0);
- if (!flows.length) return null;
+ if (!valid.length) return null;
+ const sourceOf = foldSide(valid, 'source', (count) => `其余 ${count.toLocaleString()} 个网站`);
+ const targetOf = foldSide(valid, 'target', (count) => `其余 ${count.toLocaleString()} 位创作者`);
+ const folded = new Map<string, CreatorFlow>();
+ for (const row of valid) {
+ const source = sourceOf(row.source);
+ const target = targetOf(row.target);
+ const key = JSON.stringify([source, target]);
+ const seen = folded.get(key);
+ if (seen) seen.value += row.value;
+ else folded.set(key, { source, target, value: row.value });
+ }
+ const flows = [...folded.values()];
const sources = [...new Set(flows.map((row) => row.source))];
const targets = [...new Set(flows.map((row) => row.target))];
+ const rowsOnSide = Math.max(sources.length, targets.length);
+ const bottom = Math.max(404, 16 + (rowsOnSide - 1) * FLOW_ROW + FLOW_NODE_ROOM);
const graph = sankey<{ id: string; name: string; side: 'source' | 'target' }, object>()
- .nodeId((node) => node.id).nodeWidth(FLOW_NODE_WIDTH).nodePadding(22)
- .extent([[155, 16], [535, 404]])({
+ .nodeId((node) => node.id).nodeWidth(FLOW_NODE_WIDTH).nodePadding(FLOW_ROW)
+ .extent([[155, 16], [535, bottom]])({
nodes: [
...sources.map((name) => ({ id: `source:${name}`, name, side: 'source' as const })),
...targets.map((name) => ({ id: `target:${name}`, name, side: 'target' as const })),
@@ -268,7 +315,7 @@ export function flowGraph(rows: CreatorFlow[] = []): FlowGraph | null {
label: `${from.name} → ${to.name}`,
};
});
- return { nodes, links, total };
+ return { nodes, links, total, height: bottom + FLOW_VIEWBOX.height - 404 };
}
/** 节点名字太长时截断。图里一格只有这么宽,整名在 `aria-label` 和 `<title>` 里。 */
diff --git a/frontend/test/board-skeleton.test.ts b/frontend/test/board-skeleton.test.ts
index eaec0cb9d..a83991dec 100644
--- a/frontend/test/board-skeleton.test.ts
+++ b/frontend/test/board-skeleton.test.ts
@@ -105,13 +105,16 @@ describe('Board 页面骨架', () => {
expect(root.querySelector('.follow-skeleton-surface > .group')?.textContent).toBe('全选本页');
expect(root.querySelector('[data-selection-dock]')).toBeNull();
});
- it('口味骨架保留分段背景与状态行间距', () => {
+ it('口味骨架画在 React 岛里,按浏览器记录那一页排', () => {
const root = document.createElement('div');
root.innerHTML = boardPageSkeleton('/taste');
- expect(root.querySelector('.insightswitch[data-board-segments]')).not.toBeNull();
- expect(root.querySelector('.skeleton-segment-selected')?.textContent).toBe('浏览器记录');
- expect(root.querySelector('.tastehead + .tastestate + .tastesummaries')).not.toBeNull();
- expect(root.querySelector('.tastehead .skeleton-tabs')).toBeNull();
+ expect(root.querySelector('.peach-react')).not.toBeNull();
+ expect(root.querySelector('[data-taste-segments] [data-selected]')?.textContent).toBe('浏览器记录');
+ expect([...root.querySelectorAll('[data-taste-metrics] > div > span')].map((span) => span.textContent))
+ .toEqual(['浏览记录', '口味维度', '浏览候选', '私有导出']);
+ expect(root.querySelector('[data-taste-portrait]')?.textContent).toContain('浏览器画像');
+ expect([...root.querySelectorAll('h3')].map((h3) => h3.textContent))
+ .toEqual(['浏览活跃时间', '每日活跃', '创作者线索来源']);
});
it('关注表格视图是 Board UI 表格外框,当前排序那一列带方向', () => {
const root = follow({ followLayout: 'table' });
diff --git a/frontend/test/react/stats.test.tsx b/frontend/test/react/stats.test.tsx
index 9d82a7b71..42a9953ee 100644
--- a/frontend/test/react/stats.test.tsx
+++ b/frontend/test/react/stats.test.tsx
@@ -9,9 +9,11 @@ import { notifyManager, QueryClientProvider } from '@tanstack/react-query';
import { afterEach, expect, it, vi } from 'vitest';
import { queryClient } from '../../src/react/query';
+import { shortCount } from '../../src/react/charts/bar-card';
+import { categoryAxisWidth, fitLabel, labelWidth } from '../../src/react/charts/chart-card';
import {
- lengthRows, mediumRows, prefetchStats, radialBarSize, radialCeiling, replayRows, STATS_URL, watchNote,
- type StatsData,
+ fmtCount, lengthRows, mediumRows, percentOf, percentText, playedFor, prefetchStats, radialArc,
+ radialBarSize, radialCeiling, radialSlices, replayRows, STATS_URL, watchNote, type StatsData,
} from '../../src/react/stats/stats';
import { StatsPage } from '../../src/react/stats/stats-page';
@@ -164,9 +166,9 @@ it('分布图的分档:时长换成分钟区间,文件类型多的在前,
.toEqual([{ name: '账号', value: 9 }, { name: '视频', value: 4 }, { name: 'x', value: 1 }]);
expect(replayRows([{ k: 1, n: 52 }, { k: 2, n: 13 }, { k: 4, n: 6 }, { k: 7, n: 1 }, { k: 9, n: 1 }, { k: 12, n: 2 }]))
.toEqual([
- { name: '1 次', value: 52 }, { name: '2 次', value: 13 }, { name: '3 次', value: 0 },
- { name: '4 次', value: 6 }, { name: '5 次', value: 0 }, { name: '6–9 次', value: 2 },
- { name: '≥10 次', value: 2 },
+ { name: '1', value: 52 }, { name: '2', value: 13 }, { name: '3', value: 0 },
+ { name: '4', value: 6 }, { name: '5', value: 0 }, { name: '6–9', value: 2 },
+ { name: '≥10', value: 2 },
]);
});
@@ -190,10 +192,78 @@ it('看过那一层有播放时间的两张热力图,指到一格读数换成
expect(liked?.nextElementSibling?.textContent).toBe('1');
});
-it('没有播放时间记录时看过那一层不出热力图', async () => {
+it('没有播放时间记录时看过那一层不出热力图,留一张说明卡', async () => {
const { host } = await open(payload({ play_activity: { timezone: 'UTC+08:00', days: [], hours: [] } }));
await click(tabNamed(host, '看过'));
expect(host.querySelector('[role=tabpanel] svg[role=img]')).toBeNull();
+ expect(host.querySelector('[role=tabpanel] section[aria-label="播放时间"] p')?.textContent)
+ .toBe('开始播放后,这里会显示播放落在一周的哪些时段。');
+});
+
+it('全是 0 的分布图与没有分段的径向图都换成说明卡', async () => {
+ const { host } = await open(payload({
+ by_library: [],
+ by_quality: [{ k: '4K', n: 0 }, { k: '1080P', n: 0 }],
+ }));
+ const panel = host.querySelector('[role=tabpanel]')!;
+ expect(panel.querySelector('section[aria-label="媒体库"] p')?.textContent)
+ .toBe('把媒体文件夹归进媒体库后,这里会按库显示视频数。');
+ expect(panel.querySelector('section[aria-label="画质"] p')?.textContent).toBe('探测画质后,这里会显示画质分布。');
+});
+
+it('计数取不到时读「未取得」,不白屏也不读成 NaN', async () => {
+ const { host } = await open(payload({
+ tag_cov: null,
+ attribution: { videos: 4, creator: null, code: null, studio: null, thumb: null, duration: null },
+ consumption: {
+ played: null, library_played: null, online_played: null, play_seconds: null,
+ o_total: null, liked: null, dislike: null, seen: null, trash: null, skimmed: null,
+ },
+ }));
+ const cards = [...host.querySelectorAll('[role=tablist]')[0]!.querySelectorAll('[role=tab]')];
+ expect(cards.map((tab) => tab.querySelector('b')?.textContent)).toEqual(['4', '未取得', '未取得', '1 个卷']);
+ expect(host.textContent).not.toContain('NaN');
+});
+
+it('计数加千分位,百分比夹在 0 到 100,有一点就不读 0%', () => {
+ expect(fmtCount(1234567)).toBe((1234567).toLocaleString());
+ expect(fmtCount(null)).toBe('未取得');
+ expect([percentOf(150, 100), percentOf(-3, 100), percentOf(5, 0), percentOf(null, 10)]).toEqual([100, 0, 0, 0]);
+ expect([percentText(1, 1000), percentText(0, 1000), percentText(1, 2)]).toEqual(['<1%', '0%', '50%']);
+});
+
+it('播放时长:不到一小时读分钟,不到 48 小时读小时,再往上读天', () => {
+ expect([playedFor(1800), playedFor(7200), playedFor(48 * 3600), playedFor(-5), playedFor(null)])
+ .toEqual(['30 分钟', '2.0 小时', '2 天', '0 分钟', '未取得']);
+});
+
+it('径向图超过六段并掉尾部,体积跟着合计;负数与非有限值不画', () => {
+ const rows = Array.from({ length: 8 }, (_, at) => ({ name: `库${at}`, value: 80 - at * 10, bytes: 1 }));
+ const slices = radialSlices([...rows, { name: '坏', value: -1 }, { name: '空', value: Number.NaN }]);
+ expect(slices.map((row) => row.name)).toEqual(['库0', '库1', '库2', '库3', '库4', '其余 3 项']);
+ expect(slices.at(-1)).toEqual({ name: '其余 3 项', value: 30 + 20 + 10, bytes: 3 });
+});
+
+it('不为 0 的段至少画满圈的 2%,0 仍是 0', () => {
+ expect(radialArc(1, 1000)).toBe(20);
+ expect(radialArc(500, 1000)).toBe(500);
+ expect(radialArc(0, 1000)).toBe(0);
+});
+
+it('柱端读数十万以上换成万、亿', () => {
+ expect([shortCount(99999), shortCount(123456), shortCount(1_234_567_890)])
+ .toEqual([(99999).toLocaleString(), '12.3万', '12.3亿']);
+});
+
+it('类别名放不下就截断加省略号,轴宽跟着最长的名字走并封顶', () => {
+ expect(fitLabel('短名', 60)).toBe('短名');
+ const long = '一个特别长的类别名字';
+ const cut = fitLabel(long, 60);
+ expect(cut).toMatch(/^一个.*…$/);
+ expect(long.startsWith(cut.slice(0, -1))).toBe(true);
+ expect(labelWidth(cut)).toBeLessThanOrEqual(60);
+ expect(categoryAxisWidth(['ab'])).toBe(36);
+ expect(categoryAxisWidth(['一个特别长的类别名字一个特别长的类别名字'])).toBe(104);
});
it('覆盖率那一层的每条进度用同一对分子分母,不另算一遍', async () => {
diff --git a/frontend/test/react/taste.test.tsx b/frontend/test/react/taste.test.tsx
index 805d5b066..41df0791b 100644
--- a/frontend/test/react/taste.test.tsx
+++ b/frontend/test/react/taste.test.tsx
@@ -14,8 +14,9 @@ import * as legacyUi from '@peach/legacy/ui';
import { JOB_RUNNING_POLL_MS } from '../../src/react/background-job';
import { queryClient } from '../../src/react/query';
import {
- DEFAULT_WINDOW, prefetchTaste, radarRows, RANK_MAX, TASTE_IMPORT_URL, TASTE_REFRESH_URL,
- TASTE_SOURCE_URL, TASTE_URL, topScores, type TasteData, type TasteJob,
+ DEFAULT_WINDOW, FLOW_VIEWBOX, flowGraph, historySpan, prefetchTaste, radarRows, RANK_MAX, rankDetail,
+ TASTE_IMPORT_URL, TASTE_REFRESH_URL, TASTE_SOURCE_URL, TASTE_URL, tasteDimensions, topScores,
+ type TasteData, type TasteJob,
} from '../../src/react/taste/taste';
import { TasteRadar } from '../../src/react/taste/charts';
import { TastePage } from '../../src/react/taste/taste-page';
@@ -165,6 +166,49 @@ it('口味维度取分数最高的几个:雷达三到六个,排行条最多
expect(radarRows([{ name: '甲', score: 3 }, { name: '乙', score: 1 }, { name: '丙' }])).toEqual([]);
});
+it('「口味维度」读数只数分数为正的维度,和雷达、排行条画的是同一批', () => {
+ expect(tasteDimensions([{ name: '负', score: -2 }, { name: '乙', score: 3 }, { name: '零', score: 0 },
+ { name: '甲', score: 9 }, { name: '缺' }]).map((row) => row.name)).toEqual(['甲', '乙']);
+});
+
+it('数据源与名次底下的数加千分位,没有起止日期时只读数据源数', () => {
+ expect(historySpan({ history_sources: 12345 })).toBe(`${(12345).toLocaleString()} 个数据源`);
+ expect(historySpan({ history_sources: 2, range_start: '2026-01-01', range_end: '2026-09-01' }))
+ .toMatch(/^2 个数据源 · .+—.+$/);
+ expect(rankDetail({ name: '甲', web_visits: 12345, peach_items: 6789 }))
+ .toBe(`浏览 ${(12345).toLocaleString()} · Peach ${(6789).toLocaleString()}`);
+});
+
+it('流向图一侧超过十二个节点时并掉尾部,画布跟着节点数加高,节点不挤在一起', () => {
+ const flows = Array.from({ length: 20 }, (_, at) => ({ source: 'example.com', target: `创作者${at}`, value: 40 - at }));
+ const graph = flowGraph(flows)!;
+ const targets = graph.nodes.filter((node) => node.side === 'target');
+ expect(targets).toHaveLength(12);
+ expect(targets.find((node) => node.name === '其余 9 位创作者')?.value).toBe(29 + 28 + 27 + 26 + 25 + 24 + 23 + 22 + 21);
+ expect(graph.height).toBeGreaterThan(FLOW_VIEWBOX.height);
+ const centers = targets.map((node) => node.y + node.height / 2).sort((a, b) => a - b);
+ for (let at = 1; at < centers.length; at += 1) expect(centers[at]! - centers[at - 1]!).toBeGreaterThanOrEqual(30);
+ expect(flowGraph(flows.slice(0, 3))!.height).toBe(FLOW_VIEWBOX.height);
+});
+
+it('维度不足三个时画像卡不出雷达,排行条照常出', async () => {
+ const { host } = await open({ taste: [payload({ rankings: {
+ ...payload().rankings, browser_categories: [{ name: '维度甲', score: 4 }, { name: '维度乙', score: 2 }],
+ } })] });
+ const portrait = host.querySelector('section[aria-label="浏览器画像"]')!;
+ expect(portrait.querySelector('div[role=img]')).toBeNull();
+ expect(portrait.querySelector('section[aria-label="口味维度排名"]')).not.toBeNull();
+});
+
+it('没有名次的榜给一句怎么补,不重复「暂无足够证据」', async () => {
+ const { host } = await open();
+ await click([...host.querySelectorAll('[role=tab]')].find((tab) => tab.textContent === 'Peach 内部') ?? null);
+ await click([...host.querySelectorAll('[role=tab]')].find((tab) => tab.textContent === '创作者') ?? null);
+ const panel = [...host.querySelectorAll('[role=tabpanel]')].at(-1)!;
+ expect(panel.textContent).toContain('暂无足够证据');
+ expect(panel.textContent).toContain('在 Peach 里播放或评价作品后,这里会列出对应的创作者。');
+});
+
it('雷达半径按平方根刻度:最大的维度落在外圈,浮层读的仍是原始次数', async () => {
// Recharts 靠 ResizeObserver 量容器,拿掉它就按 EvilCharts 给的初始尺寸 320 × 200 画;
// 声明减少动态效果,Recharts 不播生长动画,多边形直接是终态。
diff --git a/web/board.css b/web/board.css
index 7581d1ec2..f74efbe78 100644
--- a/web/board.css
+++ b/web/board.css
@@ -519,11 +519,7 @@ button,input,select,textarea{font-family:inherit}
.board-library-avatar svg{width:20px;height:20px;stroke-width:2}.board-library-avatar{background:none;border-radius:0}
.metricstrip{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));grid-auto-flow:row;gap:16px;overflow:visible;border:0;background:none}
.tastesummary{display:flex;flex-direction:column;min-width:0;padding:16px 0 0;border:0;border-radius:16px;background:var(--ground);overflow:hidden;text-align:left;box-shadow:0 1px 2px #00000008}
-.tastesummary>.board-stat-label{display:flex;align-items:center;gap:8px;padding:0 16px;color:var(--ink-2);font-size:14px;line-height:20px}
-.tastesummary>.board-stat-value{padding:12px 16px 16px;font-size:28px;line-height:34px;font-weight:500;color:var(--ink);font-variant-numeric:tabular-nums;letter-spacing:-.02em}
-.tastesummary>.board-stat-footer{display:block;padding:10px 16px;background:var(--board-card-foot);margin:auto 0 0;font-size:12px;line-height:18px;color:var(--muted);min-height:38px}
.insightcopy{border:0}@media(max-width:1000px){.metricstrip{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}}
-@media(max-width:480px){.board-stat-label{padding-inline:12px;font-size:13px;gap:6px}.tastesummary>.board-stat-value{padding:12px;font-size:24px;line-height:34px}.tastesummary>.board-stat-footer{padding:8px 12px}}
/* 数据按阅读目的分组,标题与内容共享边缘。 */
.tastepage{width:100%;max-width:var(--board-content)}