nex_animation/frontend/src/components/ui/Controls.tsx

384 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { createContext, useContext } from 'react'
import type { ReactNode } from 'react'
import { cn } from '../../lib/cn'
import { Checkbox } from '../primitives'
import { Select } from '../forms/Select'
import { TAG_DENSE } from './Status'
/**
* 控件栏体系(docs/UI规范.md §1~§5 的唯一实现)。
*
* 症状:筛选栏 / 工具条 / 抽屉字段里「标签在上、控件在下」,一个字段吃掉整行;
* 同一行搜索框 38、下拉 31、复选框 16,中心线各走各的;chip 行贴住下方面板。
* 做法:布局只在这几个组件里定义,页面只给内容——
* <Ctlbar> 含控件的横条(一行、垂直居中、紧凑高度、下边距 12)
* <Field> 行内标签字段(标签在左、控件在右;grow / wide / narrow 调宽)
* <BarRight> 需要右靠的一组控件(替代写在控件上的 margin-left:auto)
* <ChipBar> chip 行(与下方内容强制呼吸 12px)
* <FormGrid> 表单级栅格作用域:一个表单只在这里定义一次列边界(12 等分)
* <FormRow> 表单里的一行(有 FormGrid 时按跨格数落位,没有时 auto-fit 自己降列)
* <Pager> 分页条(page_size 唯一的家)
* 高度一律不写在控件上:容器把 --ctl-h 压到紧凑档,行内控件跟着一起降。
*/
/** 行内字段标签的唯一尺子:Field 与 Slider 共用,抽屉里两种字段的标题必须量出同一个字号 */
export const LABEL_CLS = 'flex flex-row items-center gap-1.5 m-0 text-muted text-tiny tracking-[.3px] whitespace-nowrap'
const LABEL = LABEL_CLS
/** 字段行内标签(标签在左):文字本身不拉伸,否则被挤成两行 */
const LABEL_CHILD = '[&>label]:flex [&>label]:flex-row [&>label]:items-center [&>label]:gap-1.5 [&>label]:m-0 '
+ '[&>label]:text-muted [&>label]:text-tiny [&>label]:tracking-[.3px] [&>label]:whitespace-nowrap'
/**
* 字段内部的排布:控件的宽度靠 base.css 的 w-full + flex 收缩填满标签右侧,
* **不给 flex-1**。因为 <FormRow stack> 会把字段翻成纵向 flex,
* flex-1 的 flex-basis:0% 会接管高度——同一抽屉里 input 被拉到 46px、
* 旁边那行又是 38px,就是用户截图中「第一行明显更高」的根因。
*/
const FIELD_INNER = '[&>*]:min-w-0 [&_span:first-child]:flex-none [&_[role=checkbox]]:flex-none [&_[role=radio]]:flex-none'
export function Ctlbar({ children, className, as: As = 'div' }: { children: ReactNode; className?: string; as?: any }) {
return (
<As className={cn('[--ctl-h:var(--ctl-h-md)] [--label-w:0px] flex items-center flex-wrap gap-y-2 gap-x-[10px] min-w-0 mb-3',
'[&>*]:min-w-0', LABEL_CHILD, className)}>
{children}
</As>
)
}
/** 卡片内部的动作行:布局同 Ctlbar,但不带 12px 下边距(否则卡片里凭空多一段空白) */
export function CardActions({ children, className }: { children: ReactNode; className?: string }) {
return (
<div className={cn('[--ctl-h:var(--ctl-h-md)] [--label-w:0px] flex items-center flex-wrap gap-y-2 gap-x-[10px] min-w-0 [&>*]:min-w-0', className)}>
{children}
</div>
)
}
export function BarRight({ children, className }: { children: ReactNode; className?: string }) {
return <div className={cn('ml-auto flex items-center gap-2 flex-wrap min-w-0', className)}>{children}</div>
}
type FieldWidth = 'default' | 'grow' | 'narrow' | 'wide' | 'full'
const WIDTHS: Record<FieldWidth, string> = {
default: 'basis-[170px] shrink grow-0',
grow: 'basis-[240px] grow shrink',
narrow: 'basis-[122px] shrink grow-0',
/** .wide = 「宽字段」而不是「吃满整行」:1360px 抽屉里的下拉会撑到整行 89% */
wide: 'basis-[330px] grow shrink max-w-[min(460px,58%)]',
full: 'basis-full grow shrink'
}
/**
* 行内标签字段:`<Field label="类型">…</Field>`;stack 场景交给 <FormRow stack> 统一翻向。
* title 挂在外层 label 上:整块(标签 + 控件)都是悬停热区,和旧站 .fld[title] 一致。
*
* 标签列宽(对齐的关键):标签是 flex-none + nowrap,宽度就是文字本身,
* 于是「显示名」的输入框比「角色」右移 14px——同一张表单里每条控件的左边缘都不同。
* 现在标签至少占 --label-w:表单栅格(FormRow)把它抬到 --field-label-w=66px,
* 同行同列共用一条控件左边界;筛选条这类贴边排版的容器把它压回 0px(保持老样子)。
* 只给下限不给上限:超过 66px 的长标题(「覆盖负面提示词(可选)」)宁可把控件顶右,
* 也不截断标题。宽度是量出来的,见 tokens.css --field-label-w。
*
* ⚠️ 下限必须写在**容器**上(`[&>span:first-child]`),不能只写在标签 span 自己那句
* `min-w-(--label-w)` 里:同一个 Field 还带着 `[&>*]:min-w-0`(让长控件能收缩),
* 它编译成 `.min-w-0 > *`,和 `.min-w-\(--label-w\)` 同为 0-1-0 特指度,
* 而 Tailwind 把 `min-w-0` 排在自定义值之后 → 后者赢,标签的 66px 下限被无声清零。
* /account 的「登录名 30.9 / 邮箱 20.6 / 当前密码 41.2」就是这么来的。
* `span:first-child` 多一个伪类(0-2-1)才压得住;span 上那句留着,是为了
* 让脱离 Field 复用 LABEL_CLS 的地方也有同一个下限。
*/
export function Field({ label, required, children, width = 'default', className, hint, title }: {
label?: ReactNode; required?: boolean; children: ReactNode; width?: FieldWidth; className?: string; hint?: ReactNode
title?: string
}) {
return (
<label title={title} data-full={width === 'full' ? '' : undefined}
className={cn(LABEL, FIELD_INNER, WIDTHS[width], 'min-w-0',
// 标签列宽的下限(写法原因见上面的 ⚠️):只有真的传了 label 才加,
// 否则无标签字段的第一个 span 会被当成标签列撑到 66px。
label && '[&>span:first-child]:min-w-(--label-w)',
// 带 hint 的字段翻成两列栅格:标签在左上、控件在右上、说明贴在控件下面。
// 不能只是 flex-wrap——base.css 里控件是 w-full,一换行控件就被整体挤到第二行,
// 标签跑回上面,同一栅格里就成了「一个横排、两个竖排」的混排(规范 R3)。
hint && 'grid grid-cols-[minmax(var(--label-w),max-content)_minmax(0,1fr)]', className)}>
{label && <span className="flex-none min-w-(--label-w)">{label}{required && <Req />}</span>}
{children}
{hint && (
<span className="col-start-2 w-full pt-[3px] text-faint text-tiny leading-[1.5] font-normal tracking-[0]">
{hint}
</span>
)}
</label>
)
}
/** 必填星号:和标签文字同一个 flex item,否则列方向 label 会把「*」顶到下一行 */
export function Req() {
return <b className="text-danger font-bold ml-[2px]">*</b>
}
/** 长字段(标签在上):抽屉/对话框里的多行文本、上传区用这个 */
export function FieldBlock({ label, required, children, className, title }: {
label?: ReactNode; required?: boolean; children: ReactNode; className?: string
/** 标签的含义/后果说明(分镜的检查器里几乎每个长字段都要一句),与 Field 保持一致 */
title?: string
}) {
return (
<label title={title} className={cn('[--ctl-h:var(--ctl-h-main)] [--label-w:0px] flex flex-col gap-[5px] mb-[10px] min-w-0', className)}>
<span className="flex items-center gap-1 text-muted text-tiny tracking-[.3px] flex-wrap whitespace-nowrap">
{label}{required && <Req />}
</span>
{children}
</label>
)
}
/**
* 12 列基准栅格:整个表单的列边界只在这里定义一次。
*
* 病灶(用户说的「字段标题不对齐」):轨道以前写在每条 FormRow 自己身上,
* 模型抽屉里「模型身份」那行 cols={3}、「并发/RPM」那行 cols={4},
* 同宽的两行列边界差了 110px,标题看着就是斜的。
* 现在基准取 12 等分(2/3/4/6 都能整除),FormRow 的 cols 退化成
* 「这一行放几个字段」= 每个字段跨 12/cols 格,任何一行都对齐同一套线。
*
* 没有 FormGrid 的孤立 FormRow 走原来的 auto-fit 路径,全站不必一次性改写;
* 只要一个表单里出现两行列数不同,就必须用 FormGrid 包起来。
*
* 它是「布局作用域」而不是又一个盒子:只发 context,不加 DOM,
* 所以能在不改动缩进结构、不新增一层 div 的前提下套住整个抽屉表单。
*/
const FormGridCtx = createContext<{ gapX: string; gapY: string } | null>(null)
export function FormGrid({ children, gap = 'loose' }: {
children: ReactNode; gap?: 'loose' | 'tight'
}) {
const spec = gap === 'tight' ? { gapX: 'gap-x-[8px]', gapY: 'gap-y-[8px]' }
: { gapX: 'gap-x-[10px]', gapY: 'gap-y-[8px]' }
return <FormGridCtx.Provider value={spec}>{children}</FormGridCtx.Provider>
}
/**
* 每行字段数 → 跨格数 + 窄屏降列。
* 降列的档位沿用原来的规则:3/4 列在 mid 以下两列、6 列在 nav 以下两列,2 列不降。
* cols 省略(原来靠 auto-fit 猜列数)在基准栅格里按每行 4 个字段处理——
* 栅格必须有一个确定的列数,这正是「轨道写在行上」会被消灭的原因。
*
* 两个「占满整行」的例外,否则长文本字段会在 12 格里被压成一小截:
* :only-child —— 整行只有一个字段(审核台那种一行一项),铺满;
* width="full" —— 字段自己声明占满(Field 挂 data-full)。
*/
// 注意:这些类名必须原样写成字面量。Tailwind 扫的是源码文本,
// 用模板字符串把 col-span-${n} 拼出来,产物 CSS 里根本不会有那条规则(踩过)。
const SPAN_FULL = '[&>[data-full]]:col-span-full [&>:only-child]:col-span-full'
const LATTICE: Record<number, string> = {
2: '[&>*:not([data-full]):not(:only-child)]:col-span-6 '
+ 'max-mid:[&>*:not([data-full]):not(:only-child)]:col-span-12 ' + SPAN_FULL,
3: '[&>*:not([data-full]):not(:only-child)]:col-span-4 '
+ 'max-mid:[&>*:not([data-full]):not(:only-child)]:col-span-6 ' + SPAN_FULL,
4: '[&>*:not([data-full]):not(:only-child)]:col-span-3 '
+ 'max-mid:[&>*:not([data-full]):not(:only-child)]:col-span-6 ' + SPAN_FULL,
6: '[&>*:not([data-full]):not(:only-child)]:col-span-2 '
+ 'max-nav:[&>*:not([data-full]):not(:only-child)]:col-span-6 ' + SPAN_FULL
}
/**
* 短字段栅格:列边界来自 <FormGrid>;stack 把标签退回控件上方。
*
* 表单容器显式声明自己是主尺寸(38px):抽屉/对话框里的字段永远同一档,
* 不会因为外面套了一层紧凑档工具条(Ctlbar / ChipBar / 抽屉动作条)
* 就整排缩水成 31px——一个容器只有一个 --ctl-h 档位。
* 同理在这里抬 --label-w:标签列宽是「表单才需要」的规则,
* 由行作用域下发,页面永远不必自己写宽度。
*/
export function FormRow({ children, cols, tight, stack, className }: {
children: ReactNode
/** 这一行放几个字段;在 FormGrid 里 = 每个字段跨 12/cols 格 */
cols?: 2 | 3 | 4 | 6
/** 更紧的一行(仅脱离 FormGrid 时生效,基准栅格里间距由表单统一) */
tight?: boolean
stack?: boolean
className?: string
}) {
const grid = useContext(FormGridCtx)
const shared = '[--ctl-h:var(--ctl-h-main)] [--label-w:var(--field-label-w)] grid mb-[10px] min-w-0 [&>*]:min-w-0 '
// 每个字段贴到自己格子的顶端:否则带 hint 的字段把行撑高之后,
// 旁边没 hint 的字段会被垂直居中,同一行三个输入框错开半行(规范 R3)。
+ '[&>*]:self-start '
// 这里必须显式 [&>*]:flex:带 hint 的字段自己是 grid,
// grid 元素不认 flex-direction,不覆盖就会在 stack 栅格里漏掉竖排。
+ (stack ? 'gap-y-[10px] [&>*]:flex [&>*]:flex-col [&>*]:items-stretch [&>*]:gap-[5px] [&>*]:w-auto [&>*:not(span)]:w-full' : '')
if (grid) {
// 间距也归 FormGrid 统管:基准 12 格下只要列间距换一个数,
// 每条列线就整体漂移(实测 10→8px 时最后一格偏 1.7px),对齐又是假的。
// 所以基准栅格里 tight 只影响纵向,横向密度由表单说了算。
return (
<div className={cn(shared, 'grid-cols-12', grid.gapX, grid.gapY, LATTICE[cols ?? 3], className)}>
{children}
</div>
)
}
const tracks = cols === undefined ? 'repeat(auto-fit,minmax(190px,1fr))'
: cols === 6 ? 'repeat(6,minmax(78px,1fr))'
: `repeat(${cols},minmax(0,1fr))`
return (
<div className={cn(shared,
// 间距照旧站 .frow(gap: 8px 10px):列间 10px 是「标签在左」不贴到上一格控件的地板,
// 之前这里只在 tight 时给 gap,非 tight 档位间距为 0,窄屏上「镜号」几乎贴着上一格的输入框。
tight ? 'gap-[8px]' : 'gap-x-[10px] gap-y-[8px]',
cols === undefined && 'max-mid:grid-cols-2',
(cols === 3 || cols === 4) && 'max-mid:grid-cols-2',
(cols === 4 || cols === 6) && 'max-nav:grid-cols-2',
className)}
style={{ gridTemplateColumns: tracks }}>
{children}
</div>
)
}
/** chip / 标签行(规范 §2):与下方内容强制呼吸 12px */
export function ChipBar({ children, label, className, top }: { children: ReactNode; label?: ReactNode; className?: string; top?: boolean }) {
return (
<div className={cn('[--ctl-h:var(--ctl-h-md)] [--label-w:0px] flex items-center gap-1.5 flex-wrap mb-3 min-w-0', top && 'mt-3', className)}>
{label && <span className="flex-none text-muted text-tiny tracking-[.6px] font-bold">{label}</span>}
{children}
</div>
)
}
/**
* 筛选/开关胶囊(.chip):**可点的**东西才属于这一族(31px,与同排按钮等高)。
*
* 只读回显(计数、能力、状态)不要在这里传 as="span",一律用 Tag / TagGroup:
* 一行里 31px 的只读胶囊和 20px 的标签并排,正是「标签样式不统一」最显眼的那处。
* as="span" 只留一个例外——文件选择器旁边「已选 xxx.mp3」这种回显,
* 它跟着同排那串可点的素材 chip 成组,而不是跟着标签成组。
*/
export function Chip({ active, children, onClick, className, title, disabled, as = 'button', href, size = 'md' }: {
active?: boolean; children: ReactNode; onClick?: () => void; className?: string; title?: string
disabled?: boolean; as?: 'button' | 'a' | 'span'; href?: string; size?: 'md' | 'sm'
}) {
const classes = cn('inline-flex items-center justify-center border whitespace-nowrap shrink-0 no-underline '
+ 'transition-colors duration-150',
// sm 档存在的唯一理由:卡片元信息行里「可点的标签」和「只读的标签」必须同高同形,
// 而 31px 的默认档会把那一行撑成工具条。尺寸取自标签令牌,不在这儿重复一遍数字。
size === 'sm'
? cn(TAG_DENSE, 'min-h-(--tag-h) px-(--tag-px) gap-(--tag-gap) [font-size:var(--tag-text)] rounded-chip')
: 'h-(--ctl-h-md) px-2 gap-[5px] text-tiny rounded-pill',
active ? 'bg-accent-fill border-accent-fill text-on-accent font-bold'
: 'bg-raise border-line-strong text-ink-3 hover:bg-active hover:text-ink',
disabled && 'opacity-40 cursor-not-allowed', className)
if (as === 'span') return <span title={title} className={classes}>{children}</span>
if (as === 'a') return <a href={href} title={title} className={classes}>{children}</a>
return <button type="button" title={title} disabled={disabled} onClick={onClick} className={classes}>{children}</button>
}
/** 选中态胶囊 + 移除叉(多选回显);removeTitle 解释叉掉之后会发生什么 */
export function TagChip({ children, onRemove, className, removeTitle }: {
children: ReactNode; onRemove?: () => void; className?: string; removeTitle?: string
}) {
return (
<span className={cn('inline-flex items-center justify-center gap-[5px] h-(--ctl-h-md) px-[9px] text-tiny rounded-pill '
+ 'border bg-accent-fill border-accent-fill text-on-accent font-bold whitespace-nowrap shrink-0', className)}>
{children}
{onRemove && (
<button type="button" onClick={onRemove} title={removeTitle} aria-label="移除"
className="grid place-items-center w-[17px] h-[17px] ml-[5px] p-0 flex-none border-0 rounded-full bg-[color-mix(in_srgb,var(--c-on-accent)_20%,transparent)] text-inherit text-[12px] leading-none hover:bg-danger hover:text-danger-ink">×</button>
)}
</span>
)
}
/**
* 分页条(规范 §5):page_size 唯一的家,筛选栏里不再出现「每页」。
*
* 档位默认覆盖表格页的常用宽度;卡片墙这类一格 150px 的网格要的是 24/60/120/全部,
* 所以档位开成入参,由页面自己给(sizes 里 0 表示不分页)。
*/
/**
* 长文本字段的统一高度(UI规范 §3):抽屉里的提示词 / 描述至少要 86px 才装得下一句完整的话,
* 同时允许用户自己继续拉长。
* 挂在**容器**上(`[&_textarea]`)而不是每个 textarea 上——往抽屉里加字段的人
* 不该再记一遍这三条类名;此前 AssetLibrary 与 Library 各抄了一份,leading 已经写歪。
*/
export const TEXTAREA_TALL = '[&_textarea]:min-h-[86px] [&_textarea]:resize-y [&_textarea]:leading-[1.65]'
const DEFAULT_SIZES = [12, 20, 24, 30, 48, 60, 120]
export function Pager({ page, pages, total, pageSize, onPageSize, onPage, extra, sizes = DEFAULT_SIZES }: {
page: number; pages: number; total?: number; pageSize?: number
onPageSize?: (size: number) => void; onPage: (page: number) => void; extra?: ReactNode
sizes?: number[]
}) {
const last = Math.max(1, pages)
return (
<div className="[--ctl-h:var(--ctl-h-md)] [--label-w:0px] flex items-center justify-center gap-[10px] flex-wrap mt-3 text-dim text-tiny">
<button type="button" className="h-(--ctl-h-md) px-2 rounded-control border border-line-strong bg-raise text-ink-3 text-body disabled:opacity-35"
disabled={page <= 1} onClick={() => onPage(page - 1)}>上一页</button>
<span>{page} / {last}{total !== undefined ? ` · 共 ${total} 条` : ''}</span>
<button type="button" className="h-(--ctl-h-md) px-2 rounded-control border border-line-strong bg-raise text-ink-3 text-body disabled:opacity-35"
disabled={page >= last} onClick={() => onPage(page + 1)}>下一页</button>
{onPageSize && (
<label className="flex items-center gap-1.5 m-0 text-muted text-tiny whitespace-nowrap">
<span className="flex-none">每页</span>
{/* 分页条是全站最后一个裸 <select>:系统箭头 + 系统弹单,和旁边 31px 的按钮不成一套。
换成 forms/Select(同一套 Radix Popover 皮肤);选项最多 8 条,不配过滤框。 */}
<Select size="sm" ariaLabel="每页条数" searchThreshold={0} placeholder="全部"
value={pageSize} onChange={(v) => onPageSize(Number(v))}
className="w-auto min-w-[64px]"
options={sizes.map((n) => ({ value: n, label: String(n || '全部') }))} />
</label>
)}
{extra}
</div>
)
}
/**
* 复选(.check):勾选框 + 文案,整块可点。
*
* 勾选框本体是 primitives/Checkbox(Radix),不再是 `<input type=checkbox>` + `accent-color`:
* 系统控件只有 3px 圆角的绿块能改颜色,形状、描边、三态都改不了,
* 和同排的自定义控件并排就是两套东西(模型抽屉的「启用模型」是现场证据)。
* 文案留在外层 <label> 里:button 属于 HTML 的 labelable 元素,
* 点文字会转成点控件,热区比原来大,同时给控件读出这个名字(不需要再写 aria-label)。
*/
export function Check({ checked, onChange, children, disabled, className, title }: {
checked: boolean; onChange: (next: boolean) => void; children: ReactNode; disabled?: boolean; className?: string; title?: string
}) {
return (
<label title={title} className={cn('inline-flex flex-row items-center gap-[7px] text-caption text-ink-3 cursor-pointer flex-none whitespace-nowrap', className)}>
<Checkbox checked={checked} disabled={disabled} onCheckedChange={(v) => onChange(v === true)} />
{children}
</label>
)
}
/**
* 文件选择(.upload):整块标签就是按钮,点哪里都能开文件对话框。
*
* 旧站把 <input type=file> 塞进 label 里 display:none,外壳用 padding 自己撑高度,
* 结果同一行里 chip 31px、上传 26px、按钮 38px 三种高度混在一起;
* 这里并进 --ctl-h 体系,容器决定档位,页面不再调 padding。
*/
export function FilePick({ label, accept, multiple, onFiles, className, title }: {
label: ReactNode; accept?: string; multiple?: boolean; onFiles: (files: File[]) => void; className?: string
/** 悬浮说明「选出来的文件会落到哪里」:一页里上传点越多越需要这句话 */
title?: string
}) {
return (
<label title={title} className={cn('inline-flex h-(--ctl-h) flex-row items-center justify-center gap-[5px] m-0 cursor-pointer '
+ 'rounded-chip border border-line-strong bg-hover px-[9px] text-tiny leading-[1.2] text-ink-2 '
+ 'whitespace-nowrap shrink-0 hover:bg-raise hover:text-ink', className)}>
{label}
{/* 选完就把 input 清空:否则连着两次选同一个文件,input.value 没变,
onChange 不再触发,用户以为「没选上」(分镜导入要反复试同一份脚本)。 */}
<input type="file" className="hidden" accept={accept} multiple={multiple}
onChange={(e) => {
const files = Array.from(e.currentTarget.files || [])
e.currentTarget.value = ''
onFiles(files)
}} />
</label>
)
}