xiaoshuo / ui-src /src /ui.tsx
root
正文/通读工具栏统一方形图标+悬停提示;手机:侧栏全屏带返回、正文时隐藏底栏、选字批注按钮、批注底部弹层
25b6182
Raw History Blame Contribute Delete
16.5 kB
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { X, Plus, Trash2, ChevronUp, ChevronDown, Loader2 } from 'lucide-react'
import { cx } from './lib'
/* ---------- 提示 ---------- */
type Toast = { id: number; text: string; tone: 'info' | 'ok' | 'err' }
const ToastCtx = createContext<(text: string, tone?: Toast['tone']) => void>(() => {})
export const useToast = () => useContext(ToastCtx)
export function ToastHost({ children }: { children: React.ReactNode }) {
const [list, setList] = useState<Toast[]>([])
const push = useCallback((text: string, tone: Toast['tone'] = 'info') => {
const id = Date.now() + Math.random()
setList(l => [...l.slice(-3), { id, text, tone }])
setTimeout(() => setList(l => l.filter(t => t.id !== id)), tone === 'err' ? 5200 : 2800)
}, [])
return (
<ToastCtx.Provider value={push}>
{children}
<div className="toasts" role="status" aria-live="polite">
{list.map(t => <div key={t.id} className={cx('toast', `toast-${t.tone}`)}>{t.text}</div>)}
</div>
</ToastCtx.Provider>
)
}
/* ---------- 弹窗 ---------- */
export function Modal({ open, onClose, title, children, footer, width = 520, className }: {
open: boolean; onClose: () => void; title?: React.ReactNode; children: React.ReactNode; footer?: React.ReactNode; width?: number; className?: string
}) {
useEffect(() => {
if (!open) return
const on = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
window.addEventListener('keydown', on)
return () => window.removeEventListener('keydown', on)
}, [open, onClose])
if (!open) return null
return createPortal(
<div className="overlay" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
<div className={cx('modal', className)} style={{ maxWidth: width }} role="dialog" aria-modal="true">
{title != null && (
<div className="modal-head">
<h3>{title}</h3>
<button className="icon-btn" onClick={onClose} aria-label="关闭"><X size={18} /></button>
</div>
)}
<div className="modal-body">{children}</div>
{footer && <div className="modal-foot">{footer}</div>}
</div>
</div>, document.body)
}
export function Drawer({ open, onClose, title, children, width = 560, footer }: {
open: boolean; onClose: () => void; title?: React.ReactNode; children: React.ReactNode; width?: number; footer?: React.ReactNode
}) {
useEffect(() => {
if (!open) return
const on = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
window.addEventListener('keydown', on)
return () => window.removeEventListener('keydown', on)
}, [open, onClose])
if (!open) return null
return createPortal(
<div className="overlay overlay-drawer" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
<aside className="drawer" style={{ width: `min(${width}px, 100vw)` }}>
<div className="drawer-head">
<div className="drawer-title">{title}</div>
<button className="icon-btn" onClick={onClose} aria-label="关闭"><X size={18} /></button>
</div>
<div className="drawer-body">{children}</div>
{footer && <div className="drawer-foot">{footer}</div>}
</aside>
</div>, document.body)
}
/* ---------- 确认 ---------- */
type ConfirmOpts = { title: string; body?: React.ReactNode; ok?: string; danger?: boolean; typeToConfirm?: string }
const ConfirmCtx = createContext<(o: ConfirmOpts) => Promise<boolean>>(async () => false)
export const useConfirm = () => useContext(ConfirmCtx)
export function ConfirmHost({ children }: { children: React.ReactNode }) {
const [state, setState] = useState<(ConfirmOpts & { resolve: (v: boolean) => void }) | null>(null)
const [typed, setTyped] = useState('')
const ask = useCallback((o: ConfirmOpts) => new Promise<boolean>(resolve => { setTyped(''); setState({ ...o, resolve }) }), [])
const close = (v: boolean) => { state?.resolve(v); setState(null) }
const blocked = !!state?.typeToConfirm && typed.trim() !== state.typeToConfirm
return (
<ConfirmCtx.Provider value={ask}>
{children}
<Modal open={!!state} onClose={() => close(false)} title={state?.title} width={440}
footer={<>
<button className="btn ghost" onClick={() => close(false)}>取消</button>
<button className={cx('btn', state?.danger ? 'danger' : 'primary')} disabled={blocked} onClick={() => close(true)}>{state?.ok || '确定'}</button>
</>}>
{state?.body && <div className="confirm-body">{state.body}</div>}
{state?.typeToConfirm && (
<label className="field">
<span>请输入「{state.typeToConfirm}」以确认</span>
<input className="input" value={typed} onChange={e => setTyped(e.target.value)} autoFocus />
</label>
)}
</Modal>
</ConfirmCtx.Provider>
)
}
/* ---------- 小部件 ---------- */
export const Spinner = ({ size = 16, label }: { size?: number; label?: string }) => (
<span className="spinner"><Loader2 size={size} className="spin" />{label && <span>{label}</span>}</span>
)
export const Loading = ({ label = '正在加载…' }: { label?: string }) => <div className="loading"><Spinner size={18} label={label} /></div>
export const ErrorNote = ({ error, onRetry }: { error: string; onRetry?: () => void }) => (
<div className="error-note"><span>{error}</span>{onRetry && <button className="btn small ghost" onClick={onRetry}>重试</button>}</div>
)
export function Empty({ icon, title, children }: { icon?: React.ReactNode; title: string; children?: React.ReactNode }) {
return (
<div className="empty">
{icon && <div className="empty-icon">{icon}</div>}
<div className="empty-title">{title}</div>
{children && <div className="empty-body">{children}</div>}
</div>
)
}
export function Tabs<T extends string>({ value, onChange, items, className }: {
value: T; onChange: (v: T) => void; items: { id: T; label: React.ReactNode; count?: number }[]; className?: string
}) {
const ref = useRef<HTMLDivElement>(null)
const [edge, setEdge] = useState('')
useEffect(() => {
const el = ref.current; if (!el) return
const upd = () => {
const l = el.scrollLeft > 2, r = el.scrollLeft + el.clientWidth < el.scrollWidth - 2
setEdge(l && r ? 'both' : l ? 'l' : r ? 'r' : '')
}
upd()
el.addEventListener('scroll', upd, { passive: true })
const ro = new ResizeObserver(upd); ro.observe(el)
return () => { el.removeEventListener('scroll', upd); ro.disconnect() }
}, [items.length])
useEffect(() => {
const el = ref.current; const on = el?.querySelector<HTMLElement>('.tab.on')
if (!el || !on || el.scrollWidth <= el.clientWidth) return
const l = on.offsetLeft - el.offsetLeft, r = l + on.offsetWidth
if (l < el.scrollLeft + 24 || r > el.scrollLeft + el.clientWidth - 24) el.scrollTo({ left: l - (el.clientWidth - on.offsetWidth) / 2, behavior: 'smooth' })
}, [value])
const onKey = (e: React.KeyboardEvent) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
const i = items.findIndex(it => it.id === value); const n = items[(i + (e.key === 'ArrowRight' ? 1 : items.length - 1)) % items.length]
if (n) { e.preventDefault(); onChange(n.id); setTimeout(() => ref.current?.querySelector<HTMLElement>('.tab.on')?.focus(), 0) }
}
return (
<div ref={ref} className={cx('tabs', className)} role="tablist" data-edge={edge || undefined} onKeyDown={onKey}>
{items.map(it => (
<button key={it.id} role="tab" aria-selected={value === it.id} tabIndex={value === it.id ? 0 : -1} className={cx('tab', value === it.id && 'on')} onClick={() => onChange(it.id)}>
{it.label}{it.count != null && <span className="tab-count">{it.count}</span>}
</button>
))}
</div>
)
}
export function Segmented<T extends string>({ value, onChange, items }: { value: T; onChange: (v: T) => void; items: { id: T; label: React.ReactNode }[] }) {
return (
<div className="seg">
{items.map(it => <button key={it.id} className={cx(value === it.id && 'on')} onClick={() => onChange(it.id)}>{it.label}</button>)}
</div>
)
}
export function Field({ label, hint, children, className }: { label: React.ReactNode; hint?: React.ReactNode; children: React.ReactNode; className?: string }) {
return (
<label className={cx('field', className)}>
<span className="field-label">{label}</span>
{children}
{hint && <span className="field-hint">{hint}</span>}
</label>
)
}
/* 自动增高文本框 */
export function AutoText({ value, onChange, minRows = 2, className, ...rest }: {
value: string; onChange: (v: string) => void; minRows?: number; className?: string
} & Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'value' | 'onChange'>) {
// 自动撑高到能显示全部文字;右下角可以往下拖,拖大后的高度会保留
const ref = useRef<HTMLTextAreaElement>(null)
const manual = useRef(0)
const fit = () => {
const el = ref.current
if (!el || !el.offsetParent) return
el.style.height = 'auto'
el.style.height = `${Math.max(el.scrollHeight + 2, manual.current)}px`
}
useEffect(fit, [value])
useEffect(() => {
const el = ref.current
if (!el || typeof ResizeObserver === 'undefined') return
let w = el.clientWidth
const ro = new ResizeObserver(() => { if (el.clientWidth !== w) { w = el.clientWidth; fit() } else if (!el.style.height || el.style.height === 'auto') fit() })
ro.observe(el)
return () => ro.disconnect()
}, [])
const onUp = () => { const el = ref.current; if (el && el.offsetHeight > el.scrollHeight + 4) manual.current = el.offsetHeight }
return <textarea ref={ref} rows={minRows} className={cx('textarea', 'auto-text', className)} value={value} onChange={e => onChange(e.target.value)} onMouseUp={onUp} onTouchEnd={onUp} {...rest} />
}
export function Pager({ page, total, size, onChange }: { page: number; total: number; size: number; onChange: (p: number) => void }) {
const pages = Math.max(1, Math.ceil(total / size))
if (pages <= 1) return null
return (
<div className="pager">
<button className="btn small ghost" disabled={page <= 1} onClick={() => onChange(page - 1)}>上一页</button>
<span className="pager-info">第 {page} / {pages} 页 · 共 {total} 条</span>
<button className="btn small ghost" disabled={page >= pages} onClick={() => onChange(page + 1)}>下一页</button>
</div>
)
}
/* ---------- 结构化列表编辑(保留未知字段) ---------- */
export type FieldDef = { key: string; label: string; long?: boolean; placeholder?: string; type?: 'text' | 'number' | 'select'; options?: { v: string; t: string }[]; width?: number }
export function ListEditor({ items, onChange, fields, addLabel, titleKey, empty, numbered, newItem }: {
items: any[]; onChange: (v: any[]) => void; fields: FieldDef[]; addLabel: string; titleKey?: string; empty?: string; numbered?: boolean; newItem?: () => any
}) {
const list = Array.isArray(items) ? items : []
const update = (i: number, key: string, v: any) => onChange(list.map((it, j) => j === i ? { ...(typeof it === 'object' && it ? it : { [fields[0].key]: String(it ?? '') }), [key]: v } : it))
const move = (i: number, d: number) => {
const j = i + d
if (j < 0 || j >= list.length) return
const next = [...list]; [next[i], next[j]] = [next[j], next[i]]; onChange(next)
}
const add = () => onChange([...list, newItem ? newItem() : Object.fromEntries(fields.map(f => [f.key, f.type === 'number' ? list.length + 1 : '']))])
return (
<div className="list-editor">
{list.length === 0 && empty && <div className="muted small-note">{empty}</div>}
{list.map((raw, i) => {
const it = typeof raw === 'object' && raw ? raw : { [fields[0].key]: String(raw ?? '') }
return (
<div key={i} className="le-item">
<div className="le-head">
<span className="le-index">{numbered !== false ? String(i + 1).padStart(2, '0') : ''}</span>
<span className="le-title">{titleKey ? (it[titleKey] || '未命名') : ''}</span>
<span className="le-actions">
<button className="icon-btn sm" onClick={() => move(i, -1)} aria-label="上移"><ChevronUp size={14} /></button>
<button className="icon-btn sm" onClick={() => move(i, 1)} aria-label="下移"><ChevronDown size={14} /></button>
<button className="icon-btn sm danger" onClick={() => onChange(list.filter((_, j) => j !== i))} aria-label="删除"><Trash2 size={14} /></button>
</span>
</div>
<div className="le-grid">
{fields.map(f => (
<label key={f.key} className={cx('le-field', f.long && 'long')}>
<span>{f.label}</span>
{f.type === 'select' ? (
<select className="input" value={String(it[f.key] ?? '')} onChange={e => update(i, f.key, e.target.value)}>
{f.options?.map(o => <option key={o.v} value={o.v}>{o.t}</option>)}
</select>
) : f.long ? (
<AutoText value={String(it[f.key] ?? '')} onChange={v => update(i, f.key, v)} placeholder={f.placeholder} minRows={2} />
) : (
f.type === 'number'
? <input className="input" type="number" value={it[f.key] ?? ''} placeholder={f.placeholder} onChange={e => update(i, f.key, e.target.value === '' ? '' : Number(e.target.value))} />
: <AutoText className="one" value={String(it[f.key] ?? '')} onChange={v => update(i, f.key, v)} placeholder={f.placeholder} minRows={1} />
)}
</label>
))}
</div>
</div>
)
})}
<button className="btn ghost small add-btn" onClick={add}><Plus size={14} />{addLabel}</button>
</div>
)
}
/* 纯文字列表 */
export function StringList({ items, onChange, placeholder, addLabel }: { items: any[]; onChange: (v: any[]) => void; placeholder?: string; addLabel: string }) {
const list = (Array.isArray(items) ? items : []).map(x => typeof x === 'string' ? x : (x?.text ?? x?.rule ?? x?.q ?? JSON.stringify(x)))
return (
<div className="string-list">
{list.map((s, i) => (
<div key={i} className="sl-row">
<span className="sl-dot">·</span>
<AutoText className="bare one" value={s} placeholder={placeholder} minRows={1} onChange={v => onChange(list.map((x, j) => j === i ? v : x))} />
<button className="icon-btn sm danger" onClick={() => onChange(list.filter((_, j) => j !== i))} aria-label="删除"><X size={14} /></button>
</div>
))}
<button className="btn ghost small add-btn" onClick={() => onChange([...list, ''])}><Plus size={14} />{addLabel}</button>
</div>
)
}
export function Tag({ children, tone, onClick, active, title }: { children: React.ReactNode; tone?: string; onClick?: () => void; active?: boolean; title?: string }) {
const C: any = onClick ? 'button' : 'span'
return <C className={cx('tag', tone && `tag-${tone}`, active && 'on', onClick && 'clickable')} onClick={onClick} title={title}>{children}</C>
}
export function Stars({ n, max = 5 }: { n: number; max?: number }) {
return <span className="stars" title={`质量 ${n}/${max}`}>{Array.from({ length: max }, (_, i) => <i key={i} className={i < n ? 'on' : ''} />)}</span>
}
/* 工具栏方形图标按钮:只放图标,鼠标经过显示文字(手机上长按也有系统提示) */
export function TbBtn({ tip, onClick, on, primary, badge, dot, disabled, children, className }: {
tip: string; onClick?: (e: React.MouseEvent) => void; on?: boolean; primary?: boolean; badge?: number; dot?: boolean; disabled?: boolean; children: React.ReactNode; className?: string
}) {
return (
<button type="button" className={cx('tb-btn', on && 'on', primary && 'primary', className)} onClick={onClick} disabled={disabled} data-tip={tip} aria-label={tip} aria-pressed={on || undefined}>
{children}
{badge ? <em className="tb-badge">{badge > 99 ? '99+' : badge}</em> : dot ? <i className="tb-dot" /> : null}
</button>
)
}