Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(web): 共用根因:320 宽网格、按字素取首字、格式化与提示换行

longmeidao6903fdaa0044
diff --git a/frontend/e2e/card-layout.test.ts b/frontend/e2e/card-layout.test.ts
index 979b911bd..99b984449 100644
--- a/frontend/e2e/card-layout.test.ts
+++ b/frontend/e2e/card-layout.test.ts
@@ -93,4 +93,21 @@ describe('混排作品的画面框',()=>{
}finally{await context.close()}
});
}
+ /* 大图档一格的模块宽 336px,比 320 的手机屏还宽:网格的最小列宽要让给视口,整张卡留在屏内。 */
+ for(const size of ['big','small']){
+ it(`320 宽 ${size} 版式的卡片网格不越出视口`,async()=>{
+ const context=await browser.newContext({viewport:{width:320,height:640}});
+ try{
+ const page=await context.newPage();
+ await openHome(page,size);
+ const box=await page.locator('#grid [data-media-grid]').first().evaluate(node=>({
+ right:Math.round(node.getBoundingClientRect().right),
+ card:Math.round(node.querySelector('[data-media-card]')!.getBoundingClientRect().right),
+ page:document.documentElement.scrollWidth,
+ view:document.documentElement.clientWidth,
+ }));
+ assert.ok(box.right<=box.view&&box.card<=box.view&&box.page<=box.view,JSON.stringify(box));
+ }finally{await context.close()}
+ });
+ }
});
diff --git a/frontend/src/card-art/markup.ts b/frontend/src/card-art/markup.ts
index f14940164..a448aa252 100644
--- a/frontend/src/card-art/markup.ts
+++ b/frontend/src/card-art/markup.ts
@@ -4,7 +4,7 @@
* (`./image-fallback.ts`)取不到图时换 `src`、摘掉或换成首字母,取景(`./framing.ts`)在
* 加载后往图上写内联样式与类名。React 看不见这些改动:节点归它管,重画一次就冲掉取景,
* 被兜底链摘掉的节点再交给它更新还会报错。 */
-import { esc } from '@peach/legacy/core';
+import { esc, firstGrapheme } from '@peach/legacy/core';
import { javImageKind } from '../jav-artwork';
import { imageFallbackAttrs } from './image-fallback';
@@ -121,7 +121,7 @@ export function avatarInner(name: string, ref: FaceRef | null | undefined, repId
// 这一层大多是小圆框和窄格子,厂牌标识在那里要方形图标而不是横着的字标;索引页的
// 厂牌大格是同一个模板里的例外,由调用方点名要 `large`。
const hint = focus === undefined ? (ref && ref.avatar_focus) || null : focus;
- return `<span class="ini">${esc((name || '?').slice(0, 1))}</span>`
+ return `<span class="ini">${esc(firstGrapheme(name))}</span>`
+ entityFaceImg({
kind, id: ref && ref.id, hasImage: !!(ref && ref.has_image), version: ref && ref.image_version, rep: repId, mark: markId,
logo: logoName, logoVersion: ref && ref.logo_version, logoVariant, focus: hint, thumb,
diff --git a/frontend/src/core/index.ts b/frontend/src/core/index.ts
index 90b5cc17e..3742b6750 100644
--- a/frontend/src/core/index.ts
+++ b/frontend/src/core/index.ts
@@ -19,9 +19,10 @@ const icon=(name:string,cls='')=>{
export function requestErrorMessage(cause:any,status=0):string{
const text=String(cause?.message??cause??'');
const code=Number(status||cause?.status||text.match(/\b(400|401|403|404|408|409|413|429|500|502|503|504)\b/)?.[1]);
- const messages:Record<number,string>={400:'提交内容有误,请检查输入后重试。',401:'登录已失效,请刷新页面重新登录。',403:'当前设备没有执行此操作的权限,请在运行 Peach 的电脑上操作。',404:'请求的内容已不存在,请刷新列表。',408:'请求超时,请稍后重试。',409:'当前状态不允许此操作,请刷新后重试。',413:'提交内容过大,请减少数量后重试。',429:'请求过于频繁,请稍后重试。',500:'Peach 服务处理失败,请重试;持续失败时查看托盘日志。',502:'连接上游服务失败,请检查代理或来源服务。',503:'Peach 服务暂时不可用,请稍后重试。',504:'等待服务响应超时,请稍后重试。'};
+ const messages:Record<number,string>={400:'提交内容有误,请检查输入后重试。',401:'登录已失效,请刷新页面重新登录。',403:'当前设备没有执行此操作的权限,请在运行 Peach 的电脑上操作。',404:'请求的内容已不存在,请刷新列表。',408:'请求超时,请稍后重试。',409:'当前状态不允许此操作,请刷新后重试。',413:'提交内容过大,请减少数量后重试。',429:'请求过于频繁,请稍后重试。',500:'Peach 服务处理失败,请重试;持续失败时查看托盘日志。',502:'Peach 服务没有取回结果,请稍后重试;持续失败时查看托盘日志。',503:'Peach 服务暂时不可用,请稍后重试。',504:'等待服务响应超时,请稍后重试。'};
if(/Failed to fetch|fetch failed|NetworkError|Load failed|network request failed|ERR_CONNECTION/i.test(text))return '无法连接到 Peach 服务,请确认网络连接和托盘服务已启动。';
- if(cause?.name==='TimeoutError'||/timed? ?out|timeout/i.test(text))return '等待服务响应超时,请检查连接后重试。';
+ /* 正文里的 timeout 字样只在没有状态码时才算超时:500 的堆栈里常带着某个库的 timeout 参数名。 */
+ if(cause?.name==='TimeoutError'||(!code&&/timed? ?out|timeout/i.test(text)))return '等待服务响应超时,请检查连接后重试。';
if(/[㐀-鿿]/.test(text)&&!/^请求失败[((]/.test(text))return text;
if(messages[code])return messages[code];
return '操作未完成,请重试;持续失败时查看托盘日志。';
@@ -167,14 +168,47 @@ const officialLinkText=(link:{url?:string;label?:string},kind:string,names:reado
所以判据是「有限且大于零」,不是「非空」。 */
const realDuration=(value:unknown)=>{const n=Number(value);return Number.isFinite(n)&&n>0?n:0};
-/** 秒数格式化成 `h:mm:ss`/`m:ss`;`0`、负数与非有限值都是 `—`(probe 的硬失败哨兵)。 */
-const fmtDur:(seconds:number|null|undefined)=>string=(s:any)=>{s=realDuration(s);if(!s)return'—';s=Math.round(s);const h=s/3600|0,m=(s%3600)/60|0,x=s%60;
+/** 秒数格式化成 `h:mm:ss`/`m:ss`,48 小时起写成 `N 天 N 小时`;`0`、负数与非有限值都是 `—`
+ * (probe 的硬失败哨兵)。 */
+const fmtDur:(seconds:number|null|undefined)=>string=(s:any)=>{s=realDuration(s);if(!s)return'—';s=Math.round(s);
+ if(s>=48*3600){const d=Math.floor(s/86400),hours=Math.floor((s%86400)/3600);return hours?`${d} 天 ${hours} 小时`:`${d} 天`}
+ const h=Math.floor(s/3600),m=Math.floor((s%3600)/60),x=s%60;
return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};
/** 秒数格式化成播放器时钟 `h:mm:ss`/`m:ss`;非数值当 0。 */
const fmtClock:(seconds:unknown)=>string=(s:any)=>{s=Math.max(0,Math.floor(Number(s)||0));const h=s/3600|0,m=(s%3600)/60|0,x=s%60;
return h?`${h}:${String(m).padStart(2,'0')}:${String(x).padStart(2,'0')}`:`${m}:${String(x).padStart(2,'0')}`};
-/* 网盘报的容量可以到 PB:PikPak 报 10 PiB,写成 TB 是「10240.00 TB」。 */
-const fmtSize:(bytes:number|null|undefined)=>string=(b:any)=>b>=1125899906842624?(b/1125899906842624).toFixed(2)+' PB':b>=1099511627776?(b/1099511627776).toFixed(2)+' TB':b>=1073741824?(b/1073741824).toFixed(1)+' GB':(b/1048576|0)+' MB';
+/* 网盘报的容量可以到 PB:PikPak 报 10 PiB,写成 TB 是「10240.00 TB」。不到 1 MB 写 KB,
+ 非零的最少写 1 KB,免得 1 字节读成「0」。缺值、NaN 与负数是「大小未知」;0 是真的 0——
+ 可回收空间、已下载量这类读数会是 0,单个文件的 0 字节由调用方判成未知。 */
+const fmtSize:(bytes:number|null|undefined)=>string=(value:any)=>{
+ if(value===null||value===undefined||value==='')return '大小未知';
+ const b=Number(value);
+ if(!Number.isFinite(b)||b<0)return '大小未知';
+ if(b===0)return '0 B';
+ if(b<1048576)return `${Math.max(1,Math.round(b/1024))} KB`;
+ return b>=1125899906842624?(b/1125899906842624).toFixed(2)+' PB':b>=1099511627776?(b/1099511627776).toFixed(2)+' TB':b>=1073741824?(b/1073741824).toFixed(1)+' GB':Math.floor(b/1048576)+' MB'};
+/* 名字的第一个字素:头像垫底、首字母圆框都取它。按 UTF-16 码元取会把 emoji 劈成半个代理对,
+ 画出来是「�」;肤色、ZWJ 组合与国旗也要整枚取。空名用 `fallback`。 */
+const graphemeSegmenter=typeof Intl!=='undefined'&&typeof Intl.Segmenter==='function'
+ ? new Intl.Segmenter(undefined,{granularity:'grapheme'})
+ : null;
+const graphemesOf=(value:string)=>graphemeSegmenter
+ ? Array.from(graphemeSegmenter.segment(value),part=>part.segment)
+ : Array.from(value);
+/** 开头 `count` 个字素(不加省略号):厂牌没有标识时垫的两个字用它。 */
+const leadingGraphemes=(value:unknown,count:number)=>{
+ const text=String(value??'').trim(),parts:string[]=[];
+ if(!text||count<=0)return '';
+ if(!graphemeSegmenter)return Array.from(text).slice(0,count).join('');
+ for(const part of graphemeSegmenter.segment(text)){parts.push(part.segment);if(parts.length>=count)break}
+ return parts.join('');
+};
+const firstGrapheme=(value:unknown,fallback='?')=>leadingGraphemes(value,1)||fallback;
+/** 按字素截断:超过 `max` 个字素时留前 `max - 1` 个再接「…」。 */
+const clipGraphemes=(value:unknown,max:number)=>{
+ const parts=graphemesOf(String(value??''));
+ return parts.length>max?`${parts.slice(0,Math.max(0,max-1)).join('')}…`:parts.join('');
+};
/** 来源代号到界面名称:`local`→`本地`、`115`→`115`、`pikpak`→`PikPak`、`online`→`在线`。 */
const LOC:Record<string,string>={local:'本地','115':'115',pikpak:'PikPak',online:'在线'};
/* 种子随机:FNV-1a 把「种子 + 键」压成一个 32 位数当排序键。同一个种子下顺序稳定,
@@ -219,5 +253,8 @@ export {
fmtDur,
fmtClock,
fmtSize,
+ firstGrapheme,
+ leadingGraphemes,
+ clipGraphemes,
LOC,
};
diff --git a/frontend/src/entry/index.ts b/frontend/src/entry/index.ts
index 4cff5bede..888dcf482 100644
--- a/frontend/src/entry/index.ts
+++ b/frontend/src/entry/index.ts
@@ -7,7 +7,7 @@
export {
$, seededRank, newSeed, DURATION_TAGS, cleanTagFilter, realDuration, icon, api, isAbort, mapLimit, STATE_ROUTES, ROUTE_STATES, STATE_LABELS, isCatalogPath,
ENTITY_ROUTES, ROUTE_ENTITIES, entityPath, esc, brandIcon, siteName, linkMarkUrl, siteMarkUrl, foldName,
- officialLinkText, fmtDur, fmtClock, fmtSize, LOC, requestErrorMessage,
+ officialLinkText, fmtDur, fmtClock, fmtSize, firstGrapheme, leadingGraphemes, clipGraphemes, LOC, requestErrorMessage,
} from '../core';
export { TAG_DISPLAY_NAMES, tagLabel } from '../core/tags';
export {
diff --git a/frontend/src/react/bundle.d.ts b/frontend/src/react/bundle.d.ts
index bb29bcfec..56914d942 100644
--- a/frontend/src/react/bundle.d.ts
+++ b/frontend/src/react/bundle.d.ts
@@ -465,7 +465,7 @@ export interface ToastIcons { success: string; error: string }
export interface ToastRequest {
html: string;
alert: boolean;
- /** 毫秒;0 表示不自己消失。 */
+ /** 毫秒;0 与负数按默认的 6 秒,`Infinity` 表示不自己消失。 */
timeout: number;
action: { label: string; run(button: HTMLButtonElement): void } | null;
}
diff --git a/frontend/src/react/components/media-card.css b/frontend/src/react/components/media-card.css
index 27653cd0d..39fe860fa 100644
--- a/frontend/src/react/components/media-card.css
+++ b/frontend/src/react/components/media-card.css
@@ -15,7 +15,7 @@
.peach-react [data-media-sections] { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.peach-react [data-media-grid] {
display: grid;
- grid-template-columns: repeat(auto-fill, minmax(var(--tile), 1fr));
+ grid-template-columns: repeat(auto-fill, minmax(min(100%, var(--tile)), 1fr));
gap: 24px 16px;
}
/* 铺悬停面的卡按自己的内容定高、贴行顶:同一行里横版封面挨着竖版正封时,行高由竖版撑起,
diff --git a/frontend/src/react/components/mix-card.tsx b/frontend/src/react/components/mix-card.tsx
index 176124e62..25679adaf 100644
--- a/frontend/src/react/components/mix-card.tsx
+++ b/frontend/src/react/components/mix-card.tsx
@@ -9,6 +9,7 @@
* 伪元素、`color-mix` 与相邻兄弟选择器在工具类里写不出来。 */
import { useCallback, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { avatarInner, representativeOf } from '@peach/card-art';
+import { firstGrapheme } from '@peach/legacy/core';
import { ArtSlot } from './art-slot';
import { spriteGlyph } from './sprite-glyph';
@@ -154,7 +155,7 @@ export function MixCard({
<div className="flex min-w-0 items-start gap-2.25">
{glyph
? <span data-mix-glyph="" aria-hidden><PLAY /></span>
- : <Avatars faces={faces} fallback={name.slice(0, 1)} onOpenEntity={onOpenEntity} />}
+ : <Avatars faces={faces} fallback={firstGrapheme(name)} onOpenEntity={onOpenEntity} />}
<div className="flex min-w-0 flex-1 flex-col">
<b data-mix-title="" className="truncate text-body-bold text-text-primary">{name}</b>
<span data-mix-caption="" className="mt-0.5 truncate text-caption-1-regular text-text-secondary">{caption}</span>
diff --git a/frontend/src/react/components/note.tsx b/frontend/src/react/components/note.tsx
index a816cb790..f0aa800ed 100644
--- a/frontend/src/react/components/note.tsx
+++ b/frontend/src/react/components/note.tsx
@@ -21,8 +21,9 @@ export function Note(
{/* 窄屏放不下时按钮换到下一行:挤成两个字一行的按钮比换行更难认。 */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
- {title ? <p className="text-body-medium">{title}</p> : null}
- <p className="text-body-2-regular">{children}</p>
+ {/* 正文常是服务端原话:长 URL、堆栈和多行原因照原样换行,不撑宽所在的卡。 */}
+ {title ? <p className="text-body-medium wrap-anywhere">{title}</p> : null}
+ <p className="whitespace-pre-line text-body-2-regular wrap-anywhere">{children}</p>
</div>
{action}
</div>
diff --git a/frontend/src/react/entity-hero/entity-hero-page.tsx b/frontend/src/react/entity-hero/entity-hero-page.tsx
index 1a6886842..609e6db32 100644
--- a/frontend/src/react/entity-hero/entity-hero-page.tsx
+++ b/frontend/src/react/entity-hero/entity-hero-page.tsx
@@ -11,7 +11,7 @@
import { useEffect, useRef, useState, type MouseEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { entityFaceImg, facePos } from '@peach/card-art';
-import { entityPath, esc, icon } from '@peach/legacy/core';
+import { entityPath, esc, firstGrapheme, icon } from '@peach/legacy/core';
import { Button } from '@/components/base/buttons/button';
@@ -107,7 +107,7 @@ export function EntityHeroPage({ kind, name, entity, feedNew, feedHost, actions,
<button key={person.k} type="button" data-related-performer={person.k}
onClick={() => actions.openEntity('performer', person.k)}>
<span data-hero-ring="" dangerouslySetInnerHTML={{
- __html: `<span>${esc(person.k.slice(0, 1))}</span>${costarImg(person)}` }} />
+ __html: `<span>${esc(firstGrapheme(person.k))}</span>${costarImg(person)}` }} />
<span data-hero-costar-name="">{person.k}</span>
</button>
))}
@@ -128,7 +128,7 @@ function Portrait({ kind, name, helpers, people, company }: {
}) {
/* 图只拼一次:兜底链摘掉的 `<img>`、人脸放大写进去的尺寸都留在节点上,重画时不能按
同一段 HTML 再盖回去(`dangerouslySetInnerHTML` 只在字符串变了时才重写)。 */
- const [html] = useState(() => `${helpers.portraitImg()}<span>${esc(name.slice(0, 1))}</span>`);
+ const [html] = useState(() => `${helpers.portraitImg()}<span>${esc(firstGrapheme(name))}</span>`);
return (
<div data-entity-portrait={people ? 'round' : 'square'} data-fit-native={company ? 'mark' : 'portrait'}
data-entity-kind={kind} dangerouslySetInnerHTML={{ __html: html }} />
diff --git a/frontend/src/react/follow-feed/follow-feed-page.tsx b/frontend/src/react/follow-feed/follow-feed-page.tsx
index 24e09d78e..23bb3b5ae 100644
--- a/frontend/src/react/follow-feed/follow-feed-page.tsx
+++ b/frontend/src/react/follow-feed/follow-feed-page.tsx
@@ -10,7 +10,7 @@
* `helpers.jobProgress` 盯着,跑完失效这一页的查询重取。 */
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from 'react';
import { useInfiniteQuery, useMutation, useQuery, type InfiniteData } from '@tanstack/react-query';
-import { icon, requestErrorMessage } from '@peach/legacy/core';
+import { icon, leadingGraphemes, requestErrorMessage } from '@peach/legacy/core';
import { tagLabel } from '@peach/legacy/tags';
import { emptyStateHtml, spinnerHtml } from '@peach/legacy/ui';
@@ -314,7 +314,7 @@ function Works({ rows, pressed, props, onPick }: {
{rows.map((work) => (
<button key={work[0]} type="button" data-follow-work={work[0]} aria-pressed={pressed === work[0]}
onClick={() => onPick(work[0])}>
- <span data-follow-mark="" data-fallback={String(work[1] || '').slice(0, 2)}
+ <span data-follow-mark="" data-fallback={leadingGraphemes(work[1], 2)}
dangerouslySetInnerHTML={{ __html: props.helpers.workMark(work) }} />
{work[1]}
</button>
diff --git a/frontend/src/react/follow-feed/follow-feed.css b/frontend/src/react/follow-feed/follow-feed.css
index a98e11baa..65d199b85 100644
--- a/frontend/src/react/follow-feed/follow-feed.css
+++ b/frontend/src/react/follow-feed/follow-feed.css
@@ -265,7 +265,7 @@
/* ── 列表 ── */
.peach-react [data-follow-list] {
display: grid;
- grid-template-columns: repeat(auto-fill, minmax(var(--tile), 1fr));
+ grid-template-columns: repeat(auto-fill, minmax(min(100%, var(--tile)), 1fr));
gap: 24px 16px;
}
.peach-react [data-follow-list] > [data-media-card] { align-self: start; }
diff --git a/frontend/src/react/index/index-data.ts b/frontend/src/react/index/index-data.ts
index 6f2e50c9b..84ea90946 100644
--- a/frontend/src/react/index/index-data.ts
+++ b/frontend/src/react/index/index-data.ts
@@ -8,6 +8,8 @@
* 取数归遗留壳的目录网格。 */
import type { InfiniteData, QueryKey } from '@tanstack/react-query';
+import { firstGrapheme } from '@peach/legacy/core';
+
import { apiGet } from '../../api';
import { IDENTITY_CATEGORIES } from '../../identity-filter';
import {
@@ -235,7 +237,7 @@ const COLLATOR = { numeric: true, sensitivity: 'base' } as const;
export function tagGroups<T extends { k: string }>(items: T[], label: (tag: string) => string): [string, T[]][] {
const groups = new Map<string, T[]>();
for (const item of [...items].sort((a, b) => a.k.localeCompare(b.k, 'zh-CN', COLLATOR))) {
- const first = label(item.k).normalize('NFKC').trim().charAt(0).toUpperCase();
+ const first = firstGrapheme(label(item.k).normalize('NFKC'), '').toUpperCase();
const key = /[A-Z]/.test(first) ? first : /[0-9]/.test(first) ? '#' : /[㐀-鿿]/.test(first) ? '中文' : '其他';
const group = groups.get(key);
if (group) group.push(item); else groups.set(key, [item]);
diff --git a/frontend/src/react/item-detail/item-detail-page.tsx b/frontend/src/react/item-detail/item-detail-page.tsx
index 685e9a897..23d35a548 100644
--- a/frontend/src/react/item-detail/item-detail-page.tsx
+++ b/frontend/src/react/item-detail/item-detail-page.tsx
@@ -9,7 +9,7 @@
* 把服务端回的那几个字段换进 `['item', id]`,目录网格缓存里的同一张卡一起换,不重读列表。 */
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
-import { esc, fmtDur, fmtSize, icon, requestErrorMessage } from '@peach/legacy/core';
+import { esc, firstGrapheme, fmtDur, fmtSize, icon, leadingGraphemes, requestErrorMessage } from '@peach/legacy/core';
import {
coverUrl, entityFaceImg, logoUrl, mixLabel, performerLabel, queueAvatarHtml, queueThumbHtml,
} from '@peach/card-art';
@@ -462,12 +462,12 @@ function Identity({ item, actions }: { item: DetailItem; helpers: ItemDetailHelp
const cell = (kind: string, ref: DetailEntityRef, index: number) => {
const hide = kind === 'performer' && index >= CAST_SHOWN && !castOpen;
const face = kind === 'performer'
- ? <span data-id-face="" dangerouslySetInnerHTML={{ __html: `<span>${esc(ref.name.slice(0, 1))}</span>`
+ ? <span data-id-face="" dangerouslySetInnerHTML={{ __html: `<span>${esc(firstGrapheme(ref.name))}</span>`
+ entityFaceImg({ id: ref.id, hasImage: ref.has_image, version: ref.image_version, focus: ref.avatar_focus }) }} />
: <span data-id-face="">{kind === 'studio'
- ? <><span>{ref.name.slice(0, 2)}</span>{ref.has_logo
+ ? <><span>{leadingGraphemes(ref.name, 2)}</span>{ref.has_logo
? <img src={logoUrl(ref.name, 'icon', ref.logo_version)} alt="" loading="lazy" data-drop="self" /> : null}</>
- : <span>{ref.name.slice(0, 1)}</span>}</span>;
+ : <span>{firstGrapheme(ref.name)}</span>}</span>;
const content = <>{face}<span data-id-name="">{ref.name}</span></>;
const overflowAttrs = kind === 'performer' && index >= CAST_SHOWN ? { 'data-castoverflow': '' } : {};
if (!ref.id) return <span key={`${kind}:${ref.name}`} data-id-cell={kind} title={ref.name} hidden={hide} {...overflowAttrs}>{content}</span>;
diff --git a/frontend/src/react/quality-goals/quality-goals-page.tsx b/frontend/src/react/quality-goals/quality-goals-page.tsx
index 9c7808693..2fe6d2ecd 100644
--- a/frontend/src/react/quality-goals/quality-goals-page.tsx
+++ b/frontend/src/react/quality-goals/quality-goals-page.tsx
@@ -56,7 +56,7 @@ function GoalCard({ item, openItem, searchResources, javTitleHtml, javDisplayNam
<span className="contents" dangerouslySetInnerHTML={{ __html: srcBadge(item.location, item.cost) }} />
<span>{LOC[item.location] ?? item.location}</span>
<span>{fmtDur(item.duration)}</span>
- <span>{fmtSize(item.size ?? 0)}</span>
+ <span>{Number(item.size) > 0 ? fmtSize(Number(item.size)) : '大小未知'}</span>
</p>
{item.reason
? <p className="border-t border-separator-border pt-3 text-body-2-regular text-text-secondary">
diff --git a/frontend/src/react/taste/taste-page.tsx b/frontend/src/react/taste/taste-page.tsx
index eae2a1826..3697066b1 100644
--- a/frontend/src/react/taste/taste-page.tsx
+++ b/frontend/src/react/taste/taste-page.tsx
@@ -24,7 +24,7 @@ import { Popover, Tab, TabPanel, Tabs } from 'react-aria-components';
import { MenuDialog as Dialog } from '../components/menu-dialog';
import { avatarInner } from '@peach/card-art';
-import { fmtSize, siteMarkUrl } from '@peach/legacy/core';
+import { firstGrapheme, fmtSize, siteMarkUrl } from '@peach/legacy/core';
import { confirmModal } from '@peach/legacy/ui';
import { Button } from '@/components/base/buttons/button';
@@ -99,7 +99,7 @@ function SummaryCard({ icon: Icon, term, figure, detail, accent }:
function SiteAvatar({ name, domain }: { name: string; domain: string }) {
return (
<span className="relative inline-grid size-8 shrink-0 place-items-center overflow-hidden rounded-lg bg-background-tertiary-default text-caption-1-medium text-text-secondary">
- {name.slice(0, 1).toUpperCase()}
+ {firstGrapheme(name).toUpperCase()}
<img src={siteMarkUrl({ domain })} alt="" loading="lazy" width={20} height={20}
onError={(event) => event.currentTarget.remove()}
className="absolute size-5 object-contain" />
diff --git a/frontend/src/react/taste/taste.ts b/frontend/src/react/taste/taste.ts
index 99b628e86..629217e8d 100644
--- a/frontend/src/react/taste/taste.ts
+++ b/frontend/src/react/taste/taste.ts
@@ -10,6 +10,7 @@
*
* 刷新任务是另一份真相,节律由后台推进,所以单独一个键(`['taste','refresh']`)。 */
import { sankey, sankeyLinkHorizontal } from 'd3-sankey';
+import { clipGraphemes } from '@peach/legacy/core';
import { apiGet, apiSend, ApiError } from '../../api';
import type { BarRow } from '../charts/bar-card';
@@ -271,5 +272,4 @@ export function flowGraph(rows: CreatorFlow[] = []): FlowGraph | null {
}
/** 节点名字太长时截断。图里一格只有这么宽,整名在 `aria-label` 和 `<title>` 里。 */
-export const flowLabel = (name: string): string =>
- (name.length > 18 ? `${name.slice(0, 16)}…` : name);
+export const flowLabel = (name: string): string => clipGraphemes(name, 17);
diff --git a/frontend/src/react/toaster.tsx b/frontend/src/react/toaster.tsx
index faae8623c..45ee47cf8 100644
--- a/frontend/src/react/toaster.tsx
+++ b/frontend/src/react/toaster.tsx
@@ -36,12 +36,17 @@ export const mountToaster: typeof Bundle.mountToaster = (host, icons) => {
/* 同一个 `id` 再调一次就是改写那一条:撤销的结果写回原回执,不另起一条,底部对齐的栈里
不会一进一出地跳一格。改写时 `action` 显式给成 `undefined`,Sonner 按 id 合并,不写这一项
旧的「撤销」键会留在「已撤销」旁边。 */
+/** 没给时长或给了非正数时的停留时间,同遗留壳 `toast()` 的默认值。要常驻就显式传 `Infinity`。 */
+const DEFAULT_TIMEOUT = 6000;
+
export const showToast: typeof Bundle.showToast = (id, request) => {
+ /* 没有字的回执只是一块空白条,不弹。 */
+ if (!String(request.html ?? '').trim()) return;
const show = request.alert ? toast.error : toast.success;
const action = request.action;
show(<span dangerouslySetInnerHTML={{ __html: request.html }} />, {
id,
- duration: request.timeout || Infinity,
+ duration: request.timeout > 0 ? request.timeout : DEFAULT_TIMEOUT,
action: action ? {
label: action.label,
// 点了不关:结果要写回这一条。关掉它的是随后那次改写的计时。
diff --git a/frontend/test/feedback.test.ts b/frontend/test/feedback.test.ts
index ef4bda67e..a6e557d89 100644
--- a/frontend/test/feedback.test.ts
+++ b/frontend/test/feedback.test.ts
@@ -9,6 +9,16 @@ describe('中文错误反馈',()=>{
it.each([[401,'登录已失效'],[403,'没有执行此操作的权限'],[404,'已不存在'],[429,'过于频繁'],[503,'暂时不可用'],[504,'超时']])('HTTP %s 使用明确原因', (code,reason)=>{
expect(requestErrorMessage('request failed',code)).toContain(reason);
});
+ it('正文里的 timeout 字样不把 500 读成超时',()=>{
+ expect(requestErrorMessage('Traceback: httpx.ReadTimeout raised in handler (timeout=30)',500))
+ .toBe('Peach 服务处理失败,请重试;持续失败时查看托盘日志。');
+ expect(requestErrorMessage('read timed out')).toContain('超时');
+ });
+ it('本机接口的 502 说的是 Peach 服务,不提代理',()=>{
+ const text=requestErrorMessage('Bad Gateway',502);
+ expect(text).toContain('Peach 服务');
+ expect(text).not.toContain('代理');
+ });
it('保留服务端明确的中文原因',()=>{
expect(requestErrorMessage('媒体盘没有挂载,请先连接媒体盘。',409)).toBe('媒体盘没有挂载,请先连接媒体盘。');
});
diff --git a/frontend/test/react/quality-goals.test.tsx b/frontend/test/react/quality-goals.test.tsx
index 71013ec45..a70944136 100644
--- a/frontend/test/react/quality-goals.test.tsx
+++ b/frontend/test/react/quality-goals.test.tsx
@@ -107,7 +107,7 @@ it('每条目标一张卡片,读数走遗留层同一套格式化口径', asyn
it('探测失败的时长显示占位,不显示 0 也不显示负数', async () => {
const { host } = await open(payload([goal({ duration: -1, size: 0 })]));
expect([...host.querySelectorAll('h3 ~ p > span')].map((node) => node.textContent))
- .toEqual(['', '本地', '—', '0 MB']);
+ .toEqual(['', '本地', '—', '大小未知']);
});
it('有番号封面就用番号封面,否则退回海报', async () => {
diff --git a/frontend/test/react/toaster-timeout.test.tsx b/frontend/test/react/toaster-timeout.test.tsx
new file mode 100644
index 000000000..da9c6a3c5
--- /dev/null
+++ b/frontend/test/react/toaster-timeout.test.tsx
@@ -0,0 +1,26 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const sonner = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
+vi.mock('sonner', () => ({ toast: sonner, Toaster: () => null }));
+
+import { showToast } from '../../src/react/toaster';
+
+beforeEach(() => { sonner.success.mockClear(); sonner.error.mockClear() });
+
+const durationOf = (call: unknown[] | undefined) => (call?.[1] as { duration?: number } | undefined)?.duration;
+
+it('时长给 0 或负数时按默认 6 秒消失,显式的 Infinity 才常驻', () => {
+ showToast('zero', { html: '已保存', alert: false, timeout: 0, action: null });
+ showToast('negative', { html: '已保存', alert: false, timeout: -1, action: null });
+ showToast('pinned', { html: '已保存', alert: false, timeout: Infinity, action: null });
+ showToast('short', { html: '已保存', alert: true, timeout: 4000, action: null });
+ expect(sonner.success.mock.calls.map(durationOf)).toEqual([6000, 6000, Infinity]);
+ expect(durationOf(sonner.error.mock.calls[0])).toBe(4000);
+});
+
+it('没有字的回执不弹空白条', () => {
+ showToast('empty', { html: '', alert: false, timeout: 6000, action: null });
+ showToast('blank', { html: ' \n ', alert: true, timeout: 6000, action: null });
+ expect(sonner.success).not.toHaveBeenCalled();
+ expect(sonner.error).not.toHaveBeenCalled();
+});
diff --git a/frontend/test/react/toaster.test.tsx b/frontend/test/react/toaster.test.tsx
index 35b590ba3..5620d2730 100644
--- a/frontend/test/react/toaster.test.tsx
+++ b/frontend/test/react/toaster.test.tsx
@@ -38,8 +38,8 @@ it('撤销的结果写回同一条,栈里不另起一条', async () => {
});
it('成功的勾画出来,失败的圈不画,正文按调用点给的 HTML 插入', async () => {
- await act(async () => showToast('ok', { html: '检查了 <b>3</b> 个来源', alert: false, timeout: 0, action: null }));
- await act(async () => showToast('bad', { html: '保存失败:磁盘已满', alert: true, timeout: 0, action: null }));
+ await act(async () => showToast('ok', { html: '检查了 <b>3</b> 个来源', alert: false, timeout: Infinity, action: null }));
+ await act(async () => showToast('bad', { html: '保存失败:磁盘已满', alert: true, timeout: Infinity, action: null }));
await vi.waitFor(() => expect(toastsWith('保存失败')).toHaveLength(1));
const [ok] = toastsWith('检查了');
const [bad] = toastsWith('保存失败');
diff --git a/tests/test_web_js.py b/tests/test_web_js.py
index e54a365e6..5bac26b60 100644
--- a/tests/test_web_js.py
+++ b/tests/test_web_js.py
@@ -505,6 +505,10 @@ class WebJsBehaviourTests(unittest.TestCase):
("core.js", "fmtDur", [59], "0:59"),
("core.js", "fmtDur", [61], "1:01"),
("core.js", "fmtDur", [3661], "1:01:01"),
+ # 48 小时起按天读:「1284:00:00」没人一眼读得出是五十多天。
+ ("core.js", "fmtDur", [48 * 3600 - 1], "47:59:59"),
+ ("core.js", "fmtDur", [48 * 3600], "2 天"),
+ ("core.js", "fmtDur", [4622400], "53 天 12 小时"),
# fmtClock 是播放器时间轴,0 秒是真的 0 秒。
("core.js", "fmtClock", [0], "0:00"),
("core.js", "fmtClock", [-5], "0:00"),
@@ -512,6 +516,23 @@ class WebJsBehaviourTests(unittest.TestCase):
("core.js", "fmtSize", [3 * 1024 * 1024 * 1024], "3.0 GB"),
("core.js", "fmtSize", [2 * 1024 ** 4], "2.00 TB"),
("core.js", "fmtSize", [10 * 1024 ** 5], "10.00 PB"),
+ # 不到 1 MB 写 KB,1 字节也至少是 1 KB,不读成「0 MB」。
+ ("core.js", "fmtSize", [1], "1 KB"),
+ ("core.js", "fmtSize", [512 * 1024], "512 KB"),
+ # 0 是真的 0(可回收空间、已下载量);缺值与坏值是未知。
+ ("core.js", "fmtSize", [0], "0 B"),
+ ("core.js", "fmtSize", [None], "大小未知"),
+ ("core.js", "fmtSize", ["不是数字"], "大小未知"),
+ ("core.js", "fmtSize", [-1], "大小未知"),
+ # 首字母按字素取:emoji、肤色与 ZWJ 组合整枚取,不劈成半个代理对。
+ ("core.js", "firstGrapheme", ["🦊 Fox"], "🦊"),
+ ("core.js", "firstGrapheme", ["👩🏽‍💻 Priya"], "👩🏽‍💻"),
+ ("core.js", "firstGrapheme", [" 佐藤"], "佐"),
+ ("core.js", "firstGrapheme", [""], "?"),
+ ("core.js", "firstGrapheme", [None, ""], ""),
+ ("core.js", "leadingGraphemes", ["🇯🇵Studio", 2], "🇯🇵S"),
+ ("core.js", "clipGraphemes", ["🦊" * 20, 5], "🦊🦊🦊🦊…"),
+ ("core.js", "clipGraphemes", ["短名", 5], "短名"),
])
diff --git a/web/app.js b/web/app.js
index fb642f13c..73caa0349 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1,6 +1,6 @@
import { loadSettingsPanel, settingsPanelApi, loadSidebar, sidebarApi, sidebarSkeletonHtml, transitionTheme } from './dist/peach-ui.js';
import { batchDockApi, loadBatchDock, loadManageHeader, manageHeaderApi, manageHeaderSkeletonHtml, manageHeaderView } from './dist/peach-ui.js';
-import {$, DURATION_TAGS, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, STATE_LABELS, STATE_ROUTES, api, cleanTagFilter, mapLimit, entityPath, esc, fmtClock, fmtSize, foldName, icon, isCatalogPath, newSeed, seededRank} from './js/core.js';
+import {$, DURATION_TAGS, ENTITY_ROUTES, LOC, ROUTE_ENTITIES, ROUTE_STATES, STATE_LABELS, STATE_ROUTES, api, cleanTagFilter, isAbort, mapLimit, entityPath, esc, firstGrapheme, fmtClock, fmtSize, foldName, icon, leadingGraphemes, isCatalogPath, newSeed, seededRank} from './js/core.js';
import { searchMorphFrames } from './js/search-morph.js';
import { filterScrollState } from './js/filter-scroll.js';
import { selectRange, selectionSummary, selectGroup, syncSelectionToolbar } from './dist/peach-ui.js';
@@ -1359,7 +1359,7 @@ function catalogTags(filters){
`performer-8711` 那种全身站姿照在资料页只放得到 2 倍,在这里放到 3 倍还没碰到
源图 1:1。取景与索引页同一份 sidecar、同一个换算。 */
function tierPerformer(x){
- return {name:x.k,ringHtml:`<span data-tier-initial>${esc(x.k.slice(0,1))}</span>${entityFaceImg(
+ return {name:x.k,ringHtml:`<span data-tier-initial>${esc(firstGrapheme(x.k))}</span>${entityFaceImg(
{id:x.id,hasImage:x.has_image,version:x.image_version,rep:x.has_avatar?x.rep:null,style:facePos(x.avatar_focus),focus:x.avatar_focus})}`};
}
/* 正规厂牌用官网 logo;缺失时只显示首两个字,绝不把作品截图冒充厂牌图标。
@@ -1368,7 +1368,7 @@ function tierPerformer(x){
代价是:一排 30 个厂牌里 21 个是 404,而 404 那条响应不可缓存,每次重绘再打一整轮。
`has_logo` 由 `/api/tops` 下发,判据和取图同一个函数。 */
function tierStudio(x){
- return {name:x.k,fallback:x.k.slice(0,2),
+ return {name:x.k,fallback:leadingGraphemes(x.k,2),
logo:x.has_logo?logoUrl(x.k,'icon',x.logo_version):''};
}
/* 首屏时这一块要等两个聚合查询,约一秒。铺上骨架就必须有一次真的绘制来顶掉它,哪怕取回的
@@ -2113,7 +2113,7 @@ function revealRoutedPage(container){
的头像,只挪不放大的话脸在图里占多少、在这枚圆里就占多少,一排看下来仍是身体。
没检出脸就两样都不写,圆标按样式表里的默认取景摆。 */
function followWorkMark([key,label,,icon,focus]){
- const fallback=esc(String(label||'').slice(0,2));
+ const fallback=esc(leadingGraphemes(label,2));
return icon?`<img src="/work-icon?work=${encodeURIComponent(key)}" width="128" height="128" alt="" loading="lazy"${facePos(focus)}${faceBoxAttrs(focus)}>`:fallback;
}
diff --git a/web/css/09-skeleton.css b/web/css/09-skeleton.css
index e2e105056..08f99bfd4 100644
--- a/web/css/09-skeleton.css
+++ b/web/css/09-skeleton.css
@@ -35,7 +35,7 @@
封面与下面那组之间是 8px:行距 3px 由 .mtext 的行距定,剩下 5px 记在头像格和
标题格的上边距里,两格一起加才不会把头像顶偏。
首页和关注页是同一种卡,所以共用这一块;关注页只差归属行高一点,见下面那条。 */
-.postercard-skeleton>div{grid-template-columns:repeat(auto-fill,minmax(var(--tile),1fr));gap:24px 16px}
+.postercard-skeleton>div{grid-template-columns:repeat(auto-fill,minmax(min(100%,var(--tile)),1fr));gap:24px 16px}
.postercard-skeleton .skeletoncard{grid-template-columns:38px minmax(0,1fr);column-gap:10px;row-gap:3px;
align-content:start}
/* 封面格的圆角与真卡的 `.pic` 同一枚 token,到货那一下角不变形。 */
diff --git a/web/css/12-cards.css b/web/css/12-cards.css
index cb0947915..a6f6f7fff 100644
--- a/web/css/12-cards.css
+++ b/web/css/12-cards.css
@@ -63,7 +63,7 @@ main{position:relative;z-index:1;padding:14px 16px 90px}
/* 列距 16px 是给悬停面留的:卡片悬停时底色往盒外多铺 8px(见下方 `:hover`),列距再窄,
两张卡的悬停面就顶到邻卡上。 */
.grid{gap:24px 16px}
-.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(var(--tile),1fr))}
+.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,var(--tile)),1fr))}
.card{cursor:pointer;display:flex;flex-direction:column;gap:8px;min-width:0;border-radius:var(--surface-radius);
position:relative;transition:transform .18s ease,filter .18s ease,background-color .15s ease,box-shadow .15s ease;transform-origin:center}
/* 垃圾文件队列里,视口外的卡片跳过渲染:滚动和侧栏开合时要算的只剩屏上那几十张。
diff --git a/web/css/17-overlay.css b/web/css/17-overlay.css
index c0e52dd4d..ac9e852be 100644
--- a/web/css/17-overlay.css
+++ b/web/css/17-overlay.css
@@ -8,7 +8,10 @@
--normal-border:var(--color-border-button-default);--normal-text:var(--color-text-primary);
gap:10px;border-radius:var(--floating-radius);font:var(--board-body);
box-shadow:var(--elevation-dropdown)}
-#toasts [data-sonner-toast] [data-title]{font-weight:500}
+/* 正文里的换行照写,长路径与无空格的串就地折行。一条最高占视口的四分之一,再长在条内滚:
+ 悬停展开时三条叠起来仍留在视口里,不顶出上沿。 */
+#toasts [data-sonner-toast] [data-title]{font-weight:500;white-space:pre-line;overflow-wrap:anywhere;
+ max-height:24dvh;overflow-y:auto;overscroll-behavior:contain}
#toasts [data-sonner-toast] b{font-variant-numeric:tabular-nums}
/* 字形用全站那套描边件:成功是主色的勾,失败是警示色的圈。不写 `fill:none` 就按 `fill` 的
初值涂黑,一个勾会糊成实心箭头;圆线帽是感叹号那一点的全部,平头线帽下它就消失。 */
diff --git a/web/css/21-online.css b/web/css/21-online.css
index aeeea4f56..b203dc33e 100644
--- a/web/css/21-online.css
+++ b/web/css/21-online.css
@@ -7,7 +7,7 @@
详情归 `follow-detail` 岛(`frontend/src/react/follow-detail/follow-detail.css`)。 */
.followauthors{padding:3px 0 10px;margin:0 0 2px;overscroll-behavior-inline:contain}
.followauthors .av{width:76px}
-.followlist{display:grid;grid-template-columns:repeat(auto-fill,minmax(var(--tile),1fr))}
+.followlist{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,var(--tile)),1fr))}
.followlist.followphotowall{grid-template-columns:repeat(5,minmax(0,1fr));gap:14px 10px;align-items:start}
/* 固定比例视图的媒体框在懒加载前占好高度。 */
@media (max-width:1400px){.followlist.followphotowall{grid-template-columns:repeat(4,minmax(0,1fr))}}
diff --git a/web/dist/peach-pages.js b/web/dist/peach-pages.js
index 7f09ffaa9..fcd9ba104 100644
--- a/web/dist/peach-pages.js
+++ b/web/dist/peach-pages.js
@@ -19232,10 +19232,10 @@ function bp({ tone: e, title: t, action: n, extra: r, children: i }) {
children: [/* @__PURE__ */ (0, B.jsxs)("div", {
className: "flex min-w-0 flex-1 flex-col gap-0.5",
children: [t ? /* @__PURE__ */ (0, B.jsx)("p", {
- className: "text-body-medium",
+ className: "text-body-medium wrap-anywhere",
children: t
}) : null, /* @__PURE__ */ (0, B.jsx)("p", {
- className: "text-body-2-regular",
+ className: "whitespace-pre-line text-body-2-regular wrap-anywhere",
children: i
})]
}), n]
diff --git a/web/js/core.js b/web/js/core.js
index 10a2b5511..ea4234f25 100644
--- a/web/js/core.js
+++ b/web/js/core.js
@@ -3,5 +3,5 @@
export {
$, seededRank, newSeed, DURATION_TAGS, cleanTagFilter, realDuration, icon, api, isAbort, mapLimit, STATE_ROUTES, ROUTE_STATES, STATE_LABELS, isCatalogPath,
ENTITY_ROUTES, ROUTE_ENTITIES, entityPath, esc, brandIcon, siteName, linkMarkUrl, siteMarkUrl, foldName,
- officialLinkText, fmtDur, fmtClock, fmtSize, LOC, requestErrorMessage,
+ officialLinkText, fmtDur, fmtClock, fmtSize, firstGrapheme, leadingGraphemes, clipGraphemes, LOC, requestErrorMessage,
} from '/dist/peach-entry.js';