修复 AGC 模板库筛选与卡片状态的表现缺陷
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / Frontend tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell Rust crates (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / AI game creator shell Rust smoke (push) Has been cancelled

- 模板库筛选区改用共享筛选条与标签 chip:选中为实心品牌填充 + 反白文字,未选为浅底描边
- 未选中悬停不再借用品牌色(品牌色专属已选中),状态阶梯固定为静止 / 悬停 / 按下 / 选中
- 新增 getPlatformCategoryChipClassName 收敛筛选 chip 类名口径,模板库、资源画布、参考图弹窗与平台 Web 端共用
- PlatformSegmentedTabs 增加 accent 选中口径,与筛选 chip 共用 --platform-chip-* 语义色
- 修复卡片文字区按 grid auto 行排版导致的标题 / 简介 / 标签被裁:行高契约拆为分项常量,文字区固定 174
- 修复忙状态下动作行塞入第三个元素导致的按钮文案换行顶出卡片:忙状态写在触发它的按钮上
- 修复经典滚动条占宽导致的卡片区横向滚动条:按竖滚动条预留列宽后再算列宽行高
- 焦点环由 15% 透明度改为实心色并用 outline 绘制,选中项聚焦不再被状态投影盖掉
- 封面加载失败改为隐藏图片留中性底色,不再出现浏览器裂图图标
- 补充状态对比度、行高契约、滚动条预留、封面兜底与忙状态文案的回归测试
- 同步技术方案、踩坑记录与决策记录的口径
This commit is contained in:
kdletters
2026-09-23 16:46:49 +08:00
parent e8d987c207
commit e072c66ce9
21 changed files with 697 additions and 167 deletions
@@ -14,8 +14,31 @@ export const TEMPLATE_CARD_MIN_WIDTH = 250;
export const TEMPLATE_CARD_GAP = 14;
/** 封面宽高比:16:9。 */
export const TEMPLATE_CARD_COVER_RATIO = 9 / 16;
/** 卡片封面以下的文字与按钮区固定高度。 */
export const TEMPLATE_CARD_TEXT_HEIGHT = 150;
/**
* 卡片封面以下的文字与按钮区固定高度。
*
* 虚拟列表要求行高完全确定,所以文字区**不放任内容撑高**:`TemplateCard` 里每一行都
* 写死高度(标题 `h-5`、元信息 `h-4`、简介 `h-8`、标签 `h-5.5`、按钮行 `h-7`),
* 这里按同样的口径把总高算出来。两边必须同时改,下面的分项常量就是这条契约的锚点。
*/
export const TEMPLATE_CARD_TITLE_HEIGHT = 20;
export const TEMPLATE_CARD_META_HEIGHT = 16;
export const TEMPLATE_CARD_SUMMARY_HEIGHT = 32;
export const TEMPLATE_CARD_TAGS_HEIGHT = 22;
export const TEMPLATE_CARD_ACTIONS_HEIGHT = 28;
/** 文字区上下内边距(`p-3`)。 */
export const TEMPLATE_CARD_TEXT_PADDING = 12;
/** 文字区行间距(`gap-2`)。 */
export const TEMPLATE_CARD_TEXT_GAP = 8;
/** 文字区共 5 行、4 个行间距。 */
export const TEMPLATE_CARD_TEXT_HEIGHT =
TEMPLATE_CARD_TEXT_PADDING * 2 +
TEMPLATE_CARD_TITLE_HEIGHT +
TEMPLATE_CARD_META_HEIGHT +
TEMPLATE_CARD_SUMMARY_HEIGHT +
TEMPLATE_CARD_TAGS_HEIGHT +
TEMPLATE_CARD_ACTIONS_HEIGHT +
TEMPLATE_CARD_TEXT_GAP * 4;
/** 额外预渲染的行数,减小快速滚动时的白屏。 */
export const TEMPLATE_GRID_OVERSCAN_ROWS = 2;
@@ -68,6 +91,40 @@ export function computeTemplateGridLayout({
};
}
/**
* 带竖滚动条预留的布局。
*
* react-window 的内层宽度是 `列数 × 列宽`,而**经典(非 overlay)滚动条**会吃掉外层
* `clientWidth`Windows / WebView2 上竖滚动条约 15–17px,于是内层比外层可用宽度多出
* 正好一个滚动条,卡片区底部就多出一条横向滚动条。这里在「内容确实会竖向溢出」时,
* 先把滚动条宽度从容器宽度里扣掉再算列宽;不会竖向溢出时保持原口径,避免右侧留一条
* 无意义的白边。overlay 滚动条平台(占宽 0)结果与不预留完全一致。
*/
export function computeTemplateGridLayoutWithScrollbar({
containerWidth,
itemCount,
viewportHeight,
scrollbarWidth,
}: {
containerWidth: number;
itemCount: number;
viewportHeight: number;
scrollbarWidth: number;
}): TemplateGridLayout {
const full = computeTemplateGridLayout({ containerWidth, itemCount });
const reserve = Math.max(0, scrollbarWidth);
if (reserve === 0 || full.rowCount * full.rowHeight <= viewportHeight) {
return full;
}
const usableWidth = Math.max(0, containerWidth - reserve);
const reserved = computeTemplateGridLayout({
containerWidth: usableWidth,
itemCount,
});
// 预留后行数变多时,竖向溢出只会更明显,不会退回「不需要滚动条」的情况。
return reserved;
}
/** 按行切分,行尾补 `null` 占位,保证虚拟列表的列索引与条目一一对应。 */
export function buildTemplateRows(
templates: readonly GameTemplateEntry[],
@@ -127,10 +127,16 @@ export function filterGameTemplates(
});
}
/** 筛选条上的单个标签:名称 + 命中的模板数。 */
export type GameTemplateTagOption = {
tag: string;
assetCount: number;
};
/** 标签按出现次数降序,次数相同按名称排序,保证筛选条顺序稳定。 */
export function collectGameTemplateTags(
export function collectGameTemplateTagOptions(
templates: readonly GameTemplateEntry[],
): string[] {
): GameTemplateTagOption[] {
const counts = new Map<string, number>();
for (const template of templates) {
for (const tag of template.tags) {
@@ -144,7 +150,13 @@ export function collectGameTemplateTags(
([leftTag, leftCount], [rightTag, rightCount]) =>
rightCount - leftCount || leftTag.localeCompare(rightTag, 'zh-CN'),
)
.map(([tag]) => tag);
.map(([tag, assetCount]) => ({ tag, assetCount }));
}
export function collectGameTemplateTags(
templates: readonly GameTemplateEntry[],
): string[] {
return collectGameTemplateTagOptions(templates).map((option) => option.tag);
}
export function collectGameTemplateRuntimes(
@@ -21,7 +21,6 @@ import {
import { readProjectCreationDirectory } from '../app-shell/model';
import {
collectGameTemplateRuntimes,
collectGameTemplateTags,
EMPTY_TEMPLATE_LIBRARY_FILTERS,
filterGameTemplates,
type GameTemplateEntry,
@@ -298,10 +297,6 @@ export function useTemplateLibrary({
() => filterGameTemplates(templates, filters),
[templates, filters],
);
const tagOptions = useMemo(
() => collectGameTemplateTags(templates),
[templates],
);
const runtimeOptions = useMemo(
() => collectGameTemplateRuntimes(templates),
[templates],
@@ -343,7 +338,6 @@ export function useTemplateLibrary({
notice,
templates,
visibleTemplates,
tagOptions,
runtimeOptions,
installedCount,
filters,
@@ -1,5 +1,6 @@
import { type RefObject, useEffect, useId, useRef } from 'react';
import { getPlatformCategoryChipClassName } from '../../../../../packages/shared/src/components/platformCategoryChipModel';
import {
PlatformFilterPanel,
PlatformFilterPanelField,
@@ -15,19 +16,6 @@ import {
type ResourceFilterTagOption,
} from './resourceCanvasFilterModel';
/**
* 已选标签的 chip 用与既有筛选条同一套类名,保持「选中的标签长什么样」只有一处实现。
* `PlatformResourceFilterBar` 自己渲染未选标签时用的是同一个类。
*/
function resourceFilterTagChipClassName(active: boolean) {
return [
'platform-category-chip gap-1.5 px-2.5 text-xs font-bold',
active ? 'platform-category-chip--active' : null,
]
.filter(Boolean)
.join(' ');
}
type ResourceFilterPanelProps = {
onClose: () => void;
/** 关键词:右下角放大镜与 Ctrl/Cmd+F 叫出的就是这一个面板,状态由宿主持有。 */
@@ -186,7 +174,7 @@ export function ResourceFilterPanel({
key={option.tag}
type="button"
aria-pressed={active}
className={resourceFilterTagChipClassName(active)}
className={getPlatformCategoryChipClassName(active)}
onClick={() => onToggleTag(option.tag)}
>
<span>{option.tag}</span>
@@ -18,6 +18,10 @@ export type TemplateCardActions = {
/**
* 虚拟列表里的单个模板卡片:高度由行高契约固定(封面 16:9 + 固定文字区),
* 用 memo 包住,滚动时只重渲染可视区域内的少量卡片。
*
* 文字区每行都写死高度且不参与压缩(`shrink-0`):行高契约(`templateLibraryGrid.ts`
* 的 `TEMPLATE_CARD_TEXT_HEIGHT`)按同样的口径算出卡片总高,两边一旦不一致,
* 被截断的就是标题、简介和标签这些真实文字。
*/
function TemplateCardView({
template,
@@ -28,12 +32,8 @@ function TemplateCardView({
}: { template: GameTemplateEntry } & TemplateCardActions) {
const busy = busyTemplateId === template.id;
const needsDownload = needsTemplateDownload(template);
const busyLabel =
busy && busyKind === 'download'
? '正在下载模板'
: busy && busyKind === 'create'
? '正在创建项目'
: '';
const creating = busy && busyKind === 'create';
const downloading = busy && busyKind === 'download';
const meta = [
templateRuntimeLabel(template.runtime),
template.engine,
@@ -56,6 +56,11 @@ function TemplateCardView({
alt=""
loading="lazy"
decoding="async"
/* 封面读不到时留出中性的占位底色,而不是让浏览器画一个「裂图」图标。
直接改样式、不进 state:卡片是被 memo 包住的纯展示组件。 */
onError={(event) => {
event.currentTarget.style.visibility = 'hidden';
}}
/>
{template.installed ? (
<span
@@ -67,23 +72,31 @@ function TemplateCardView({
</span>
) : null}
</div>
<div className="grid min-h-0 content-start gap-2 overflow-hidden p-3">
<strong className="truncate text-[13px] text-(--platform-text-strong)">
<div className="flex min-h-0 flex-col gap-2 overflow-hidden p-3">
<strong
className="block h-5 shrink-0 truncate text-[13px] leading-5 text-(--platform-text-strong)"
title={template.title}
>
{template.title}
</strong>
<span className="truncate text-[10px] text-(--platform-text-soft)">
<span className="block h-4 shrink-0 truncate text-[10px] leading-4 text-(--platform-text-soft)">
{meta}
</span>
{template.summary ? (
<p className="m-0 line-clamp-2 text-[11px] leading-4 text-(--platform-neutral-text)">
<p className="m-0 line-clamp-2 h-8 shrink-0 text-[11px] leading-4 text-(--platform-neutral-text)">
{template.summary}
</p>
) : null}
{template.tags.length > 0 ? (
<div className="flex max-h-5.5 flex-wrap gap-1 overflow-hidden">
// 卡片只给标签一行(行高契约固定 22px)。清单模板 ≤4 个标签时正好放得下;
// 真出现超长标签集合时这一行会裁掉后半段,用 title 兜住完整列表。
<div
className="flex h-5.5 shrink-0 flex-wrap gap-1 overflow-hidden"
title={template.tags.join('、')}
>
{template.tags.map((tag) => (
<span
className="rounded-full bg-(--platform-nav-item-hover-fill) px-2 py-0.5 text-[10px] text-(--platform-text-soft)"
className="rounded-full bg-(--platform-nav-item-hover-fill) px-2 py-0.5 text-[10px] leading-4 text-(--platform-text-soft)"
key={tag}
>
{tag}
@@ -91,29 +104,32 @@ function TemplateCardView({
))}
</div>
) : null}
<div className="mt-auto flex items-center gap-2">
{/* 动作行固定高度、按钮不换行:忙状态写在**触发它的那个按钮**上,不要再往这一行
塞第三个元素 —— 卡片最小宽度只有 250px,多一段「正在下载模板」就会把两个
按钮的文案挤成两行、顶出卡片。 */}
<div className="mt-auto flex h-7 shrink-0 items-center gap-2 overflow-hidden">
<button
type="button"
className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg border border-(--platform-warm-text) bg-transparent px-2.5 py-1.5 text-[11px] text-(--platform-warm-text) disabled:cursor-default disabled:opacity-50"
className="inline-flex h-7 shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-lg border border-(--platform-warm-text) bg-transparent px-2.5 text-[11px] leading-4 text-(--platform-warm-text) disabled:cursor-default disabled:opacity-50"
disabled={busy}
onClick={() => onUse(template)}
>
{busy && busyKind === 'create' ? (
{creating ? (
<Loader2 className="animate-spin" size={12} aria-hidden="true" />
) : (
<Play size={12} aria-hidden="true" />
)}
使
{creating ? '创建中' : '使用模板'}
</button>
{/* 已下载且版本一致时不再提供下载入口;只有缺包或版本落后才显示(落后时按「更新」)。 */}
{needsDownload ? (
<button
type="button"
className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg border border-(--platform-subpanel-border) bg-transparent px-2.5 py-1.5 text-[11px] text-(--platform-text-soft) disabled:cursor-default disabled:opacity-50"
className="inline-flex h-7 shrink-0 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-lg border border-(--platform-subpanel-border) bg-transparent px-2.5 text-[11px] leading-4 text-(--platform-text-soft) disabled:cursor-default disabled:opacity-50"
disabled={busy}
onClick={() => onDownload(template)}
>
{busy && busyKind === 'download' ? (
{downloading ? (
<Loader2
className="animate-spin"
size={12}
@@ -122,14 +138,9 @@ function TemplateCardView({
) : (
<Download size={12} aria-hidden="true" />
)}
{template.installed ? '更新' : '下载'}
{downloading ? '下载中' : template.installed ? '更新' : '下载'}
</button>
) : null}
{busyLabel ? (
<span className="text-[10px] text-(--platform-text-soft)">
{busyLabel}
</span>
) : null}
</div>
</div>
</article>
@@ -1,25 +1,25 @@
import { PlatformRuntimeStatusToast } from '@genarrative/shared/components';
import {
ArrowLeft,
Loader2,
RefreshCw,
Search,
SearchX,
SlidersHorizontal,
} from 'lucide-react';
getPlatformCategoryChipClassName,
PlatformRuntimeStatusToast,
} from '@genarrative/shared/components';
import { ArrowLeft, Loader2, RefreshCw, SearchX } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { FixedSizeGrid, type GridChildComponentProps } from 'react-window';
import { PlatformResourceFilterBar } from '../../../../../packages/shared/src/components/PlatformResourceFilterBar';
import {
buildTemplateRows,
computeTemplateGridLayout,
computeTemplateGridLayoutWithScrollbar,
TEMPLATE_CARD_GAP,
TEMPLATE_GRID_OVERSCAN_ROWS,
templateGridItemKey,
} from '../../features/template-library/templateLibraryGrid';
import type { GameTemplateEntry } from '../../features/template-library/templateLibraryModel';
import { templateRuntimeLabel } from '../../features/template-library/templateLibraryModel';
import {
collectGameTemplateTagOptions,
type GameTemplateEntry,
templateRuntimeLabel,
} from '../../features/template-library/templateLibraryModel';
import type { TemplateLibraryController } from '../../features/template-library/useTemplateLibrary';
import { TemplateCard, type TemplateCardActions } from './TemplateCard';
@@ -73,15 +73,33 @@ function TemplateLibraryToast({
);
}
const chipClass =
'cursor-pointer rounded-full border border-(--platform-subpanel-border) bg-transparent px-2.5 py-1 text-[11px] text-(--platform-text-soft) transition hover:border-(--platform-warm-text) hover:text-(--platform-warm-text)';
const activeChipClass =
'cursor-pointer rounded-full border border-(--platform-warm-text) bg-transparent px-2.5 py-1 text-[11px] text-(--platform-warm-text)';
type TemplateGridCellData = TemplateCardActions & {
rows: Array<Array<GameTemplateEntry | null>>;
};
let cachedScrollbarWidth: number | null = null;
/**
* 量一次经典(非 overlay)竖滚动条的占宽:Windows / WebView2 上约 1517px,会吃掉
* grid 外层的可用宽度。overlay 滚动条平台测得 0(此时预留逻辑不生效)。
*/
function measureVerticalScrollbarWidth(): number {
if (cachedScrollbarWidth !== null) {
return cachedScrollbarWidth;
}
if (typeof document === 'undefined' || !document.body) {
return 0;
}
const probe = document.createElement('div');
probe.setAttribute('aria-hidden', 'true');
probe.style.cssText =
'position:absolute;top:-9999px;left:-9999px;width:100px;height:100px;overflow:scroll';
document.body.appendChild(probe);
cachedScrollbarWidth = Math.max(0, probe.offsetWidth - probe.clientWidth);
probe.remove();
return cachedScrollbarWidth;
}
function TemplateGridCell({
columnIndex,
rowIndex,
@@ -115,7 +133,6 @@ export default function TemplateLibraryView({
notice,
templates,
visibleTemplates,
tagOptions,
runtimeOptions,
installedCount,
filters,
@@ -201,16 +218,30 @@ export default function TemplateLibraryView({
const layout = useMemo(
() =>
computeTemplateGridLayout({
computeTemplateGridLayoutWithScrollbar({
containerWidth: viewportSize.width,
itemCount: visibleTemplates.length,
viewportHeight: viewportSize.height,
scrollbarWidth: measureVerticalScrollbarWidth(),
}),
[viewportSize.width, visibleTemplates.length],
[viewportSize.width, viewportSize.height, visibleTemplates.length],
);
const rows = useMemo(
() => buildTemplateRows(visibleTemplates, layout.columnCount),
[visibleTemplates, layout.columnCount],
);
const tagItems = useMemo(
() => collectGameTemplateTagOptions(templates),
[templates],
);
const runtimeItems = useMemo(
() =>
runtimeOptions.map((runtime) => {
const label = templateRuntimeLabel(runtime);
return { id: runtime, label, ariaLabel: `运行时筛选 ${label}` };
}),
[runtimeOptions],
);
// 换筛选条件回到列表顶部:否则筛选后条目变少会把视口留在空白处,看起来像“卡住”。
useEffect(() => {
@@ -285,83 +316,75 @@ export default function TemplateLibraryView({
</button>
</header>
{/* 标签/运行时筛选区可独立滚动:标签数量随库量增长时不会把卡片区挤出窗口。 */}
<div className="grid max-h-[24vh] shrink-0 gap-3 overflow-y-auto rounded-xl border border-(--platform-subpanel-border) [background:var(--platform-subpanel-fill)] p-3">
<div className="flex flex-wrap items-center gap-2">
<label className="inline-flex min-w-[220px] flex-1 items-center gap-2 rounded-lg border border-(--platform-subpanel-border) bg-transparent px-2.5 py-1.5">
<Search
className="text-(--platform-icon-text)"
size={14}
aria-hidden="true"
/>
<input
className="w-full border-0 bg-transparent p-0 text-[12px] text-(--platform-text-strong) outline-none"
type="search"
value={filters.query}
placeholder="搜索模板名称、玩法、标签"
aria-label="搜索模板"
onChange={(event) => setQuery(event.target.value)}
/>
</label>
{/* 搜索 + 运行时用共享筛选条(与资源画布、参考图弹窗同一套筛选 UI);
「仅看已下载」「清除筛选」是模板库自己的口径,靠右跟在同一条上。 */}
<div className="flex min-w-0 shrink-0 flex-wrap items-center gap-2">
<PlatformResourceFilterBar
ariaLabel="模板筛选"
className="min-w-0 max-w-[560px] flex-1"
search={{
value: filters.query,
label: '搜索模板',
placeholder: '搜索模板名称、玩法、标签',
onChange: setQuery,
}}
categoryItems={runtimeItems}
activeCategoryId={filters.runtime}
onCategoryChange={selectRuntime}
/>
<div className="ml-auto flex min-w-0 shrink-0 items-center gap-2">
<button
type="button"
className={filters.installedOnly ? activeChipClass : chipClass}
className={getPlatformCategoryChipClassName(filters.installedOnly)}
aria-pressed={filters.installedOnly}
onClick={() => setInstalledOnly(!filters.installedOnly)}
>
</button>
{filtersActive ? (
<button type="button" className={chipClass} onClick={clearFilters}>
<button
type="button"
className={getPlatformCategoryChipClassName(false)}
onClick={clearFilters}
>
</button>
) : null}
</div>
{runtimeOptions.length > 0 ? (
<div className="flex flex-wrap items-center gap-2">
<span className="inline-flex items-center gap-1 text-[11px] text-(--platform-text-soft)">
<SlidersHorizontal size={12} aria-hidden="true" />
</span>
{runtimeOptions.map((runtime) => (
<button
type="button"
key={runtime}
className={
filters.runtime === runtime ? activeChipClass : chipClass
}
aria-pressed={filters.runtime === runtime}
aria-label={`运行时筛选 ${templateRuntimeLabel(runtime)}`}
onClick={() => selectRuntime(runtime)}
>
{templateRuntimeLabel(runtime)}
</button>
))}
</div>
) : null}
{tagOptions.length > 0 ? (
<div className="flex flex-wrap items-center gap-2">
<span className="text-[11px] text-(--platform-text-soft)">
</span>
{tagOptions.map((tag) => (
<button
type="button"
key={tag}
className={
filters.tags.includes(tag) ? activeChipClass : chipClass
}
aria-pressed={filters.tags.includes(tag)}
aria-label={`标签筛选 ${tag}`}
onClick={() => toggleTag(tag)}
>
{tag}
</button>
))}
</div>
) : null}
</div>
{/* 标签单独一行并换行排布:标签数量随库量增长时优先换行,超过上限再滚动,
不会把卡片区挤出窗口,也不会让用户只能看到横向滚动条切掉的后半截标签。 */}
{tagItems.length > 0 ? (
<div
className="flex max-h-[20vh] min-w-0 shrink-0 flex-wrap items-center gap-1.5 overflow-y-auto"
role="group"
aria-label="模板筛选标签"
>
{tagItems.map((option) => {
const active = filters.tags.includes(option.tag);
return (
<button
type="button"
key={option.tag}
className={getPlatformCategoryChipClassName(active)}
aria-pressed={active}
aria-label={`标签筛选 ${option.tag}`}
onClick={() => toggleTag(option.tag)}
>
{option.tag}
<span
className="platform-category-chip__count"
aria-hidden="true"
>
{option.assetCount}
</span>
</button>
);
})}
</div>
) : null}
<TemplateLibraryToast message={notice} onDismiss={clearNotice} />
{error ? (
<div
@@ -371,7 +394,7 @@ export default function TemplateLibraryView({
<span>{error}</span>
<button
type="button"
className={chipClass}
className={getPlatformCategoryChipClassName(false)}
onClick={() => void refresh()}
>
@@ -393,7 +416,11 @@ export default function TemplateLibraryView({
<div className="flex items-center gap-2 text-[12px] text-(--platform-text-soft)">
<SearchX size={14} aria-hidden="true" />
<button type="button" className={chipClass} onClick={clearFilters}>
<button
type="button"
className={getPlatformCategoryChipClassName(false)}
onClick={clearFilters}
>
</button>
</div>
@@ -4,10 +4,18 @@ import {
buildTemplateRows,
computeTemplateGridColumns,
computeTemplateGridLayout,
computeTemplateGridLayoutWithScrollbar,
computeTemplateRowHeight,
TEMPLATE_CARD_ACTIONS_HEIGHT,
TEMPLATE_CARD_GAP,
TEMPLATE_CARD_META_HEIGHT,
TEMPLATE_CARD_MIN_WIDTH,
TEMPLATE_CARD_SUMMARY_HEIGHT,
TEMPLATE_CARD_TAGS_HEIGHT,
TEMPLATE_CARD_TEXT_GAP,
TEMPLATE_CARD_TEXT_HEIGHT,
TEMPLATE_CARD_TEXT_PADDING,
TEMPLATE_CARD_TITLE_HEIGHT,
} from '../src/features/template-library/templateLibraryGrid';
import type { GameTemplateEntry } from '../src/features/template-library/templateLibraryModel';
@@ -50,6 +58,19 @@ describe('computeTemplateGridColumns', () => {
});
describe('computeTemplateRowHeight', () => {
it('budgets the same height the card rows actually need', () => {
// 这些数字对应 TemplateCard 的 `h-5`/`h-4`/`h-8`/`h-5.5`/`h-7` 与 `p-3`/`gap-2`
// 行高契约比真实内容小,被截断的就是卡片里的标题与简介。
expect(TEMPLATE_CARD_TITLE_HEIGHT).toBe(20);
expect(TEMPLATE_CARD_META_HEIGHT).toBe(16);
expect(TEMPLATE_CARD_SUMMARY_HEIGHT).toBe(32);
expect(TEMPLATE_CARD_TAGS_HEIGHT).toBe(22);
expect(TEMPLATE_CARD_ACTIONS_HEIGHT).toBe(28);
expect(TEMPLATE_CARD_TEXT_PADDING).toBe(12);
expect(TEMPLATE_CARD_TEXT_GAP).toBe(8);
expect(TEMPLATE_CARD_TEXT_HEIGHT).toBe(174);
});
it('keeps cover ratio + fixed text block', () => {
// 列宽 300 → 卡片 286 → 封面 286*9/16 = 160.875 → 161
expect(computeTemplateRowHeight(300)).toBe(
@@ -94,6 +115,59 @@ describe('computeTemplateGridLayout', () => {
});
});
describe('computeTemplateGridLayoutWithScrollbar', () => {
const innerWidth = (layout: { columnCount: number; columnWidth: number }) =>
layout.columnCount * layout.columnWidth;
it('reserves the classic scrollbar width once the grid scrolls vertically', () => {
// 经典滚动条(Windows/WebView2 ≈ 17px)不在包裹层宽度里,不预留就会多出一条横向滚动条。
const plain = computeTemplateGridLayout({
containerWidth: 1184,
itemCount: 13,
});
const layout = computeTemplateGridLayoutWithScrollbar({
containerWidth: 1184,
itemCount: 13,
viewportHeight: 500,
scrollbarWidth: 17,
});
expect(layout.columnCount).toBe(4);
// 内层宽度必须落在竖滚动条左侧的可用宽度里,否则又会出现横向滚动条。
expect(innerWidth(layout)).toBeLessThanOrEqual(1184 - 17);
expect(innerWidth(layout)).toBeLessThan(innerWidth(plain));
// 行高仍按预留后的列宽算,卡片内容不会被压。
expect(layout.rowHeight).toBe(computeTemplateRowHeight(layout.columnWidth));
});
it('keeps the plain layout when nothing overflows or the scrollbar is an overlay', () => {
const plain = computeTemplateGridLayout({
containerWidth: 1184,
itemCount: 4,
});
// 只有一行:不会竖向滚动,不需要预留,右侧不留白边。
expect(
computeTemplateGridLayoutWithScrollbar({
containerWidth: 1184,
itemCount: 4,
viewportHeight: 900,
scrollbarWidth: 17,
}),
).toEqual(plain);
// overlay 滚动条占宽 0:与不预留完全一致。
expect(
computeTemplateGridLayoutWithScrollbar({
containerWidth: 1184,
itemCount: 13,
viewportHeight: 500,
scrollbarWidth: 0,
}),
).toEqual(
computeTemplateGridLayout({ containerWidth: 1184, itemCount: 13 }),
);
});
});
describe('buildTemplateRows', () => {
it('chunks entries per row and pads the tail with nulls', () => {
const rows = buildTemplateRows([entry('a'), entry('b'), entry('c')], 2);
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
collectGameTemplateRuntimes,
collectGameTemplateTagOptions,
collectGameTemplateTags,
EMPTY_TEMPLATE_LIBRARY_FILTERS,
filterGameTemplates,
@@ -145,6 +146,24 @@ describe('tag and runtime options', () => {
]);
});
it('keeps the same order while reporting how many templates carry each tag', () => {
// 筛选条上的标签 chip 要显示命中数量,顺序必须与 `collectGameTemplateTags` 完全一致。
const withBlank = [
...templates,
template({ id: 'blank-tag', tags: ['', ' ', '经营'] }),
];
const options = collectGameTemplateTagOptions(withBlank);
expect(options).toEqual([
{ tag: '经营', assetCount: 3 },
{ tag: '三消', assetCount: 1 },
{ tag: '射击', assetCount: 1 },
{ tag: '像素', assetCount: 1 },
]);
expect(options.map((option) => option.tag)).toEqual(
collectGameTemplateTags(withBlank),
);
});
it('collects distinct runtimes and labels them', () => {
expect(collectGameTemplateRuntimes(templates)).toEqual([
'godot',
@@ -8,7 +8,6 @@ import type {
TemplateLibraryFilters,
} from '../src/features/template-library/templateLibraryModel';
import {
collectGameTemplateTags,
EMPTY_TEMPLATE_LIBRARY_FILTERS,
filterGameTemplates,
} from '../src/features/template-library/templateLibraryModel';
@@ -81,7 +80,6 @@ function controller(
notice: '',
templates,
visibleTemplates: templates,
tagOptions: ['空白', '2d', 'canvas', '网页'],
runtimeOptions: ['html'],
installedCount: 1,
filters,
@@ -190,6 +188,28 @@ describe('TemplateLibraryView', () => {
expect(viewport?.querySelector('article')).not.toBeNull();
});
it('pins every card text row to the height the grid contract budgets for it', () => {
// 回归点:文字区若是 `grid` 的 auto 行,行高会按 max-content 算成「一行」,
// 标题 / 简介 / 标签会被逐行截断(现场表现为标题文字被切掉)。这里钉住
// 卡片每一行的固定高度,改动必须同时改 `TEMPLATE_CARD_*_HEIGHT` 那组常量。
render(<TemplateLibraryView controller={controller()} onBack={() => {}} />);
const card = cardFor('空白网页工程');
const textBlock = card.children[1] as HTMLElement;
const rows = Array.from(textBlock.children) as HTMLElement[];
expect(textBlock.className).toContain('flex-col');
expect(rows.map((row) => row.className)).toEqual([
expect.stringContaining('h-5'),
expect.stringContaining('h-4'),
expect.stringContaining('h-8'),
expect.stringContaining('h-5.5'),
expect.stringContaining('h-7'),
]);
// 每行都不参与压缩,否则 flex 会把文字压回去。
rows.forEach((row) => expect(row.className).toContain('shrink-0'));
});
it('offers 更新 instead of 下载 when the installed version is stale', () => {
const stale = template({
id: 'blank-web',
@@ -253,6 +273,17 @@ describe('TemplateLibraryView', () => {
expect(clearFilters).toHaveBeenCalled();
});
it('hides a cover that failed to load instead of showing a broken image', () => {
render(<TemplateLibraryView controller={controller()} onBack={() => {}} />);
const cover = cardFor('空白网页工程').querySelector(
'img',
) as HTMLImageElement;
expect(cover.style.visibility).toBe('');
fireEvent.error(cover);
expect(cover.style.visibility).toBe('hidden');
});
it('starts a download and a template project from the card actions', () => {
const downloadTemplate = vi.fn(async () => undefined);
const createProjectFromTemplate = vi.fn(async () => undefined);
@@ -289,11 +320,16 @@ describe('TemplateLibraryView', () => {
const busyCard = cardFor('空白二维画布工程');
const buttons = Array.from(busyCard.querySelectorAll('button'));
// 忙状态写在触发它的按钮上(文案就地变成「创建中」),动作行里不额外塞第三个元素,
// 否则最小卡宽(250px)下两个按钮的文案会被挤成两行、顶出卡片。
expect(buttons).toHaveLength(2);
expect(buttons.every((button) => button.hasAttribute('disabled'))).toBe(
true,
);
expect(busyCard.textContent).toContain('正在创建项目');
expect(cardFor('空白网页工程').textContent).not.toContain('正在创建项目');
expect(busyCard.textContent).toContain('创建中');
expect(busyCard.textContent).not.toContain('使用模板');
expect(cardFor('空白网页工程').textContent).toContain('使用模板');
expect(cardFor('空白网页工程').textContent).not.toContain('创建中');
});
it('shows empty, no-match, error and notice states', () => {
@@ -390,7 +426,6 @@ describe('大库量渲染(1000 条假数据)', () => {
templates: bulk,
visibleTemplates: bulk,
installedCount: bulk.filter((entry) => entry.installed).length,
tagOptions: collectGameTemplateTags(bulk),
})}
onBack={() => {}}
/>,
@@ -98,7 +98,128 @@ function contrastRatio(first: Rgba, second: Rgba) {
);
}
/** 取渐变里的色标(`linear-gradient(135deg, #b3542f, #8f3f22)` → 两个颜色)。 */
function parseGradientStops(source: string): Rgba[] {
const body = source.slice(source.indexOf('(') + 1, source.lastIndexOf(')'));
return body
.split(',')
.map((part) => part.trim())
.filter((part) => part.startsWith('#') || part.startsWith('rgb'))
.map((part) => parseCssColor(part.split(/\s+/)[0] ?? part));
}
/** 页面背景(`--platform-body-fill`)里的不透明色标:chip 实际落在这层之上。 */
function parseBodyFillUnderlays(source: string): Rgba[] {
return Array.from(source.matchAll(/#[\da-f]{6}/gi)).map((match) =>
parseCssColor(match[0]),
);
}
describe('workbench theme contrast', () => {
/**
* 筛选 chip 的两态对比:用户反馈「选中和没选中的颜色看不出差别」,根因是选中态
* 只换了低透明度的暖色底(两态对比 1.09:1)。这里把「选中 = 实心填充」这条口径
* 钉死:反白文字在渐变两端都要过 AA,且与未选底色至少差 3:1。
*/
it('keeps the chip selected state legible and distinct in both themes', () => {
const css = readFileSync(themePath, 'utf8');
const themes = [
{
name: 'light',
block: getCssBlock(css, '.platform-theme--light'),
// 浅色主题下 chip 落在页面底色上,用页面渐变的最亮与最暗色标夹住两种情况。
idleUnderlays: parseBodyFillUnderlays(
getCssVariable(
getCssBlock(css, '.platform-theme--light'),
'--platform-body-fill',
),
),
},
{
name: 'dark',
block: getCssBlock(css, '.platform-theme--dark'),
idleUnderlays: parseBodyFillUnderlays(
getCssVariable(
getCssBlock(css, '.platform-theme--dark'),
'--platform-body-fill',
),
),
},
];
expect(
parseGradientStops('linear-gradient(135deg, #b3542f, #8f3f22)'),
).toEqual([
[179, 84, 47, 1],
[143, 63, 34, 1],
]);
for (const theme of themes) {
const activeFill = parseGradientStops(
getCssVariable(theme.block, '--platform-chip-active-fill'),
);
const activeText = parseCssColor(
getCssVariable(theme.block, '--platform-chip-active-text'),
);
const idleFill = parseCssColor(
getCssVariable(theme.block, '--platform-chip-idle-fill'),
);
expect(activeFill, `${theme.name} active gradient stops`).toHaveLength(2);
expect(
theme.idleUnderlays.length,
`${theme.name} body fill stops`,
).toBeGreaterThan(0);
// 反白文字:渐变两端都要过 AA,不能只保证深的那一端。
for (const stop of activeFill) {
expect(
contrastRatio(activeText, stop),
`${theme.name} label on fill ${stop.slice(0, 3).join(',')}`,
).toBeGreaterThanOrEqual(4.5);
}
// 两态可分辨:选中填充与任意页面底色上的未选 chip 至少差 3:1。
for (const underlay of theme.idleUnderlays) {
const idleChip = compositeColor(idleFill, underlay);
for (const stop of activeFill) {
expect(
contrastRatio(stop, idleChip),
`${theme.name} selected vs idle over ${underlay.slice(0, 3).join(',')}`,
).toBeGreaterThanOrEqual(3);
}
}
}
});
/**
* 焦点环可见性:键盘用户靠它找焦点。旧口径是 15% 透明度的暖色,合成到页面底色只有
* 1.17:1——等于没有焦点提示。这里按 WCAG 非文本对比 3:1 钉住两套皮肤。
*/
it('keeps the keyboard focus ring visible in both themes', () => {
const css = readFileSync(themePath, 'utf8');
for (const selector of [
'.platform-theme--light',
'.platform-theme--dark',
]) {
const block = getCssBlock(css, selector);
const ring = parseCssColor(
getCssVariable(block, '--platform-input-focus-ring'),
);
const underlays = parseBodyFillUnderlays(
getCssVariable(block, '--platform-body-fill'),
);
expect(underlays.length, `${selector} body fill stops`).toBeGreaterThan(
0,
);
for (const underlay of underlays) {
expect(
contrastRatio(ring, underlay),
`${selector} focus ring over ${underlay.slice(0, 3).join(',')}`,
).toBeGreaterThanOrEqual(3);
}
}
});
it('keeps warm user bubbles above WCAG AA text contrast', () => {
const css = readFileSync(themePath, 'utf8');
const light = getCssBlock(css, '.platform-theme--light');