Files
obs-lowerthird/public/manage.html
T
2026-11-11 21:40:57 +08:00

2284 lines
98 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>OBS Lower Third · 管理</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="data:," />
<!-- Ant Design & React via CDN -->
<script src="/libs/react.production.min.js"></script>
<script src="/libs/react-dom.production.min.js"></script>
<script src="/libs/dayjs.min.js"></script>
<script src="/libs/antd.min.js"></script>
<link rel="stylesheet" href="/libs/antd.reset.css" />
<link rel="stylesheet" href="/lrc.css" />
<!-- Babel standalone for JSX transpilation -->
<script src="/libs/babel.min.js"></script>
<style>
body { margin: 0; background: #0a0c14; min-height: 100vh; }
#root { min-height: 100vh; }
.preset-list-item { cursor: pointer; transition: all 0.15s; }
.preset-list-item:hover { background: rgba(255,255,255,0.04) !important; }
.preset-list-item.selected { background: rgba(24,144,255,0.12) !important; border-color: #1890ff !important; }
.preset-list-item.active-live { background: rgba(82,196,26,0.12) !important; border-color: #52c41a !important; }
.preset-list-item.selected.active-live { background: rgba(82,196,26,0.2) !important; border-color: #52c41a !important; }
.preview-frame-wrap {
width: 100%;
aspect-ratio: 16/9;
background: #000;
border-radius: 8px;
overflow: hidden;
position: relative;
}
.preview-frame-wrap iframe {
width: 100%;
height: 100%;
border: none;
}
.kbd-hint {
display: inline-block;
background: rgba(255,255,255,0.1);
border: 1px solid rgba(255,255,255,0.2);
border-radius: 4px;
padding: 1px 6px;
font-size: 12px;
font-family: monospace;
}
.ant-layout { background: transparent !important; }
.ant-layout-header { padding: 0 24px !important; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel" data-presets="react">
const {
Layout, Menu, Tabs, Button, Input, Select, Form, Space, Tag,
Typography, Tooltip, Modal, InputNumber, Switch, Divider,
Card, Row, Col, List, Badge, message, Popconfirm, Empty,
Drawer, Alert, Spin, ConfigProvider, theme
} = antd;
const { Header, Content, Sider } = Layout;
const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
// ── Placeholder replacement ─────────────────────────────────────────────
function fillPlaceholders(html, contentData) {
if (!html || !contentData) return html || '';
return html.replace(/\{\{(\w+)\}\}/g, (match, key) => {
return Object.prototype.hasOwnProperty.call(contentData, key)
? String(contentData[key])
: match;
});
}
// Build preview srcdoc wrapping template html in a container
function buildPreviewDoc(preset, contentData) {
if (!preset || !preset.html) return '<html><body style="background:#111;color:#666;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;font-family:sans-serif;font-size:14px;">无预览内容</body></html>';
const processed = fillPlaceholders(preset.html, contentData || {});
if (preset.kind === 'iframe') {
return processed;
}
return processed;
}
// ── Preview Component ───────────────────────────────────────────────────
function PreviewPanel({ preset, contentData }) {
const doc = buildPreviewDoc(preset, contentData);
return (
<div className="preview-frame-wrap">
<iframe
key={doc}
sandbox="allow-scripts"
srcDoc={doc}
title="预览"
/>
</div>
);
}
// ── Field Defs Editor ───────────────────────────────────────────────────
function FieldDefsEditor({ value = [], onChange }) {
const add = () => {
onChange([...value, { key: '', label: '', defaultValue: '' }]);
};
const remove = (idx) => {
const next = value.filter((_, i) => i !== idx);
onChange(next);
};
const update = (idx, field, val) => {
const next = value.map((item, i) => i === idx ? { ...item, [field]: val } : item);
onChange(next);
};
return (
<div>
{value.map((fd, idx) => (
<Space key={idx} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
<Input
placeholder="字段Key (如: mainTitle)"
value={fd.key}
onChange={e => update(idx, 'key', e.target.value)}
style={{ width: 160 }}
/>
<Input
placeholder="字段标签 (如: 主标题)"
value={fd.label}
onChange={e => update(idx, 'label', e.target.value)}
style={{ width: 140 }}
/>
<Input
placeholder="默认值"
value={fd.defaultValue}
onChange={e => update(idx, 'defaultValue', e.target.value)}
style={{ width: 180 }}
/>
<Button danger size="small" onClick={() => remove(idx)}>删除</Button>
</Space>
))}
<Button type="dashed" onClick={add} size="small">+ 添加字段</Button>
<div style={{ color: '#888', fontSize: 12, marginTop: 6 }}>
在 HTML 中用 <code style={{background:'rgba(255,255,255,0.1)',padding:'1px 4px',borderRadius:3}}>{'{{key}}'}</code> 引用字段值
</div>
</div>
);
}
// ── Appearance Presets Tab ──────────────────────────────────────────────
function AppearancePresetsTab({ presets, onRefresh }) {
const [selected, setSelected] = React.useState(null);
const [form] = Form.useForm();
const [fieldDefs, setFieldDefs] = React.useState([]);
const [previewData, setPreviewData] = React.useState({});
const [saving, setSaving] = React.useState(false);
const ap = selected ? presets.find(p => p.id === selected) : null;
// Build preview content data from fieldDefs defaults
const buildPreviewContentData = (fds) => {
const data = {};
(fds || []).forEach(fd => { data[fd.key] = fd.defaultValue || ''; });
return data;
};
const selectPreset = (p) => {
setSelected(p.id);
form.setFieldsValue({
name: p.name,
align: p.align || 'right',
html: p.html || '',
extraCss: p.extraCss || '',
});
const fds = p.fieldDefs || [];
setFieldDefs(fds);
setPreviewData(buildPreviewContentData(fds));
};
const clearForm = () => {
setSelected(null);
form.resetFields();
setFieldDefs([]);
setPreviewData({});
};
const handleSave = async () => {
try {
const values = await form.validateFields();
setSaving(true);
const body = { ...values, kind: 'iframe', fieldDefs };
let res;
if (selected) {
res = await fetch('/api/presets/' + selected, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
} else {
res = await fetch('/api/presets', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
}
if (!res.ok) throw new Error('保存失败');
message.success('外观预设已保存');
clearForm();
onRefresh();
} catch(e) {
if (e.errorFields) return; // validation error
message.error('保存失败: ' + e.message);
} finally {
setSaving(false);
}
};
const handleDelete = async (id) => {
await fetch('/api/presets/' + id, { method: 'DELETE' });
if (selected === id) clearForm();
message.success('已删除');
onRefresh();
};
// Update preview when form html changes
const htmlValue = Form.useWatch('html', form);
const currentPreviewPreset = React.useMemo(() => {
return { kind: 'iframe', html: htmlValue || (ap ? ap.html : '') };
}, [htmlValue, ap]);
return (
<Row gutter={16} style={{ height: '100%' }}>
<Col xs={24} md={8}>
<div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Text strong style={{ color: '#fff' }}>外观预设列表</Text>
<Button size="small" type="primary" onClick={clearForm}>+ 新建</Button>
</div>
{presets.length === 0
? <Empty description="暂无外观预设" />
: presets.map(p => (
<Card
key={p.id}
size="small"
className={`preset-list-item${selected === p.id ? ' selected' : ''}`}
style={{ marginBottom: 8, background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
onClick={() => selectPreset(p)}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<Text style={{ color: '#fff', fontSize: 13 }}>{p.name}</Text>
<br/>
<Text style={{ color: '#888', fontSize: 11 }}>
{(p.fieldDefs || []).length} 个字段 · 对齐: {p.align || 'right'}
</Text>
</div>
<Popconfirm
title="确认删除?"
onConfirm={e => { e.stopPropagation(); handleDelete(p.id); }}
onCancel={e => e.stopPropagation()}
>
<Button
danger size="small" type="text"
onClick={e => e.stopPropagation()}
>删除</Button>
</Popconfirm>
</div>
</Card>
))
}
</Col>
<Col xs={24} md={16}>
<Card
title={<Text style={{ color: '#fff' }}>{selected ? '编辑外观预设' : '新建外观预设'}</Text>}
style={{ background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
>
<Form form={form} layout="vertical">
<Form.Item name="name" label="预设名称" rules={[{ required: true, message: '请输入名称' }]}>
<Input placeholder="例如:晚会右侧信息区" />
</Form.Item>
<Form.Item name="align" label="对齐方式" initialValue="right">
<Select>
<Select.Option value="right">右侧</Select.Option>
<Select.Option value="center">居中</Select.Option>
<Select.Option value="left">左侧</Select.Option>
</Select>
</Form.Item>
<Form.Item label="字段定义(用于内容预设)">
<FieldDefsEditor
value={fieldDefs}
onChange={(fds) => {
setFieldDefs(fds);
setPreviewData(buildPreviewContentData(fds));
}}
/>
</Form.Item>
<Form.Item name="html" label={
<span>HTML 模板 <Text style={{ color: '#888', fontSize: 11 }}>(可用 {'{{字段Key}}'} 占位)</Text></span>
}>
<TextArea
rows={10}
placeholder={'<!DOCTYPE html>\n<html>...\n <div class="title">{{mainTitle}}</div>\n...</html>'}
style={{ fontFamily: 'monospace', fontSize: 12 }}
/>
</Form.Item>
<Form.Item name="extraCss" label="额外 CSS(可选)">
<TextArea rows={3} placeholder=".lt-container { border-radius: 24px; }" style={{ fontFamily: 'monospace', fontSize: 12 }} />
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" onClick={handleSave} loading={saving}>
{selected ? '更新预设' : '保存为新预设'}
</Button>
<Button onClick={clearForm}>清空</Button>
</Space>
</Form.Item>
</Form>
<Divider style={{ borderColor: 'rgba(255,255,255,0.1)' }} />
<div>
<Text strong style={{ color: '#aaa', fontSize: 12 }}>预设预览(使用字段默认值)</Text>
<div style={{ marginTop: 8 }}>
<PreviewPanel preset={currentPreviewPreset} contentData={previewData} />
</div>
</div>
</Card>
</Col>
</Row>
);
}
// ── Content Presets Tab ─────────────────────────────────────────────────
function ContentPresetsTab({ contentPresets, appearancePresets, onRefresh }) {
const [selected, setSelected] = React.useState(null);
const [form] = Form.useForm();
const [fields, setFields] = React.useState({});
const [saving, setSaving] = React.useState(false);
const cp = selected ? contentPresets.find(c => c.id === selected) : null;
const selectedApId = Form.useWatch('appearancePresetId', form);
const ap = appearancePresets.find(p => p.id === selectedApId);
const selectPreset = (c) => {
setSelected(c.id);
form.setFieldsValue({
name: c.name,
appearancePresetId: c.appearancePresetId,
});
setFields(c.fields || {});
};
const clearForm = () => {
setSelected(null);
form.resetFields();
setFields({});
};
const handleSave = async () => {
try {
const values = await form.validateFields();
setSaving(true);
const body = { ...values, fields };
let res;
if (selected) {
res = await fetch('/api/content-presets/' + selected, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
} else {
res = await fetch('/api/content-presets', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
}
if (!res.ok) throw new Error('保存失败');
message.success('内容预设已保存');
clearForm();
onRefresh();
} catch(e) {
if (e.errorFields) return;
message.error('保存失败: ' + e.message);
} finally {
setSaving(false);
}
};
const handleDelete = async (id) => {
await fetch('/api/content-presets/' + id, { method: 'DELETE' });
if (selected === id) clearForm();
message.success('已删除');
onRefresh();
};
// Build preview with filled fields
const previewContentData = React.useMemo(() => {
const data = {};
if (ap && ap.fieldDefs) {
ap.fieldDefs.forEach(fd => { data[fd.key] = fd.defaultValue || ''; });
}
return { ...data, ...fields };
}, [ap, fields]);
return (
<Row gutter={16}>
<Col xs={24} md={8}>
<div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Text strong style={{ color: '#fff' }}>内容预设列表</Text>
<Button size="small" type="primary" onClick={clearForm}>+ 新建</Button>
</div>
{contentPresets.length === 0
? <Empty description="暂无内容预设" />
: contentPresets.map(c => {
const linkAp = appearancePresets.find(p => p.id === c.appearancePresetId);
return (
<Card
key={c.id}
size="small"
className={`preset-list-item${selected === c.id ? ' selected' : ''}`}
style={{ marginBottom: 8, background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
onClick={() => selectPreset(c)}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<Text style={{ color: '#fff', fontSize: 13 }}>{c.name}</Text>
<br/>
<Text style={{ color: '#888', fontSize: 11 }}>
外观: {linkAp ? linkAp.name : <span style={{color:'#ff4d4f'}}>未链接</span>}
</Text>
</div>
<Popconfirm title="确认删除?" onConfirm={e => { e.stopPropagation(); handleDelete(c.id); }} onCancel={e => e.stopPropagation()}>
<Button danger size="small" type="text" onClick={e => e.stopPropagation()}>删除</Button>
</Popconfirm>
</div>
</Card>
);
})
}
</Col>
<Col xs={24} md={16}>
<Card
title={<Text style={{ color: '#fff' }}>{selected ? '编辑内容预设' : '新建内容预设'}</Text>}
style={{ background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
>
<Form form={form} layout="vertical">
<Form.Item name="name" label="预设名称" rules={[{ required: true, message: '请输入名称' }]}>
<Input placeholder="例如:节目单第三项" />
</Form.Item>
<Form.Item name="appearancePresetId" label="关联外观预设">
<Select placeholder="选择外观预设" allowClear onChange={() => setFields({})}>
{appearancePresets.map(p => (
<Select.Option key={p.id} value={p.id}>{p.name}</Select.Option>
))}
</Select>
</Form.Item>
{ap && ap.fieldDefs && ap.fieldDefs.length > 0 && (
<div>
<Divider style={{ borderColor: 'rgba(255,255,255,0.1)', marginBottom: 12 }}>填写内容字段</Divider>
{ap.fieldDefs.map(fd => (
<Form.Item key={fd.key} label={`${fd.label || fd.key}`} style={{ marginBottom: 12 }}>
<Input
placeholder={fd.defaultValue || `请输入 ${fd.label || fd.key}`}
value={fields[fd.key] !== undefined ? fields[fd.key] : (fd.defaultValue || '')}
onChange={e => setFields(prev => ({ ...prev, [fd.key]: e.target.value }))}
/>
</Form.Item>
))}
</div>
)}
{ap && (!ap.fieldDefs || ap.fieldDefs.length === 0) && (
<Alert message="该外观预设没有定义字段" type="info" showIcon style={{ marginBottom: 12 }} />
)}
<Form.Item>
<Space>
<Button type="primary" onClick={handleSave} loading={saving}>
{selected ? '更新预设' : '保存为新预设'}
</Button>
<Button onClick={clearForm}>清空</Button>
</Space>
</Form.Item>
</Form>
{ap && (
<>
<Divider style={{ borderColor: 'rgba(255,255,255,0.1)' }} />
<div>
<Text strong style={{ color: '#aaa', fontSize: 12 }}>内容预设预览</Text>
<div style={{ marginTop: 8 }}>
<PreviewPanel preset={ap} contentData={previewContentData} />
</div>
</div>
</>
)}
</Card>
</Col>
</Row>
);
}
// ── LRC helpers ─────────────────────────────────────────────────────────
function deepClone(value) {
return JSON.parse(JSON.stringify(value));
}
function formatMs(ms) {
const total = Math.max(0, Math.round(Number(ms) || 0));
const m = Math.floor(total / 60000);
const s = Math.floor((total % 60000) / 1000);
const cs = Math.floor((total % 1000) / 10);
return String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0') + '.' + String(cs).padStart(2, '0');
}
function shortText(text, max) {
const value = String(text || '').replace(/\n/g, ' / ');
return value.length > max ? value.slice(0, max) + '…' : value;
}
function ColorInput({ value, onChange, placeholder }) {
const safe = (typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value)) ? value : '#ffffff';
return (
<Space.Compact style={{ width: '100%' }}>
<input
type="color"
value={safe}
onChange={e => onChange(e.target.value)}
style={{
width: 34, height: 28, padding: 0, flex: '0 0 34px', cursor: 'pointer',
border: '1px solid rgba(255,255,255,0.15)', borderRadius: '6px 0 0 6px',
background: 'transparent'
}}
/>
<Input
value={value || ''}
placeholder={placeholder || '#ffffff'}
onChange={e => onChange(e.target.value)}
style={{ borderRadius: '0 6px 6px 0' }}
/>
</Space.Compact>
);
}
function StyleField({ label, children, span = 6 }) {
return (
<Col span={span}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>{label}</div>
{children}
</Col>
);
}
const LRC_FONT_PRESETS = [
{ value: "'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', system-ui, sans-serif", label: '系统默认(Noto / 苹方 / 雅黑)' },
{ value: "'Noto Sans SC', 'Source Han Sans SC', 'Microsoft YaHei', system-ui, sans-serif", label: '思源黑体' },
{ value: "'Microsoft YaHei', 'PingFang SC', system-ui, sans-serif", label: '微软雅黑' },
{ value: "'PingFang SC', 'Microsoft YaHei', system-ui, sans-serif", label: '苹方' },
{ value: "'SimHei', 'Microsoft YaHei', sans-serif", label: '黑体' },
{ value: "'KaiTi', 'Kaiti SC', serif", label: '楷体' },
{ value: "'Songti SC', 'SimSun', serif", label: '宋体' },
{ value: "ui-monospace, 'Cascadia Mono', Consolas, monospace", label: '等宽字体' },
];
const LRC_CSS_SNIPPETS = {
neon: `/* 霓虹发光 */
.lrc-layer .lrc-box {
border: 1px solid rgba(0, 229, 255, 0.65);
box-shadow:
0 0 22px rgba(0, 229, 255, 0.55),
inset 0 0 18px rgba(0, 229, 255, 0.18);
}
.lrc-layer .lrc-text {
text-shadow:
0 0 8px rgba(0, 229, 255, 0.95),
0 0 26px rgba(0, 229, 255, 0.55) !important;
}`,
gradient: `/* 渐变文字(逐字模式下也会应用到每个字) */
.lrc-layer .lrc-text {
background: linear-gradient(90deg, #ffd166, #ff6b6b, #a78bfa);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent !important;
}
.lrc-layer .lrc-word {
background: linear-gradient(90deg, #ffd166, #ff6b6b, #a78bfa);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}`,
bounce: `/* 自定义弹跳入场:动画选择「自定义」 */
@keyframes lrcCustomBounce {
0% { opacity: 0; transform: translateY(26px) scale(0.9); }
60% { opacity: 1; transform: translateY(-6px) scale(1.03); }
100% { opacity: 1; transform: translateY(0) scale(1); }
}
.lrc-layer.lrc-anim-custom .lrc-text {
animation: lrcCustomBounce 0.55s cubic-bezier(0.2, 0.9, 0.3, 1.2) both;
}`,
wipe: `/* 擦除入场:动画选择「自定义」 */
@keyframes lrcWipeIn {
from { clip-path: inset(0 100% 0 0); opacity: 0.4; }
to { clip-path: inset(0 0 0 0); opacity: 1; }
}
.lrc-layer.lrc-anim-custom .lrc-text {
animation: lrcWipeIn 0.6s steps(24, end) both;
}`,
stroke: `/* 描边文字 */
.lrc-layer .lrc-text {
-webkit-text-stroke: 2px rgba(0, 0, 0, 0.85);
paint-order: stroke fill;
}`,
karaoke: `/* 逐字发光:唱到哪个字就点亮哪个字 */
.lrc-layer .lrc-word {
transition: color 0.12s linear, text-shadow 0.18s ease, opacity 0.12s linear;
}
.lrc-layer .lrc-word.is-sung {
text-shadow:
0 0 10px rgba(255, 209, 102, 0.95),
0 0 24px rgba(255, 92, 141, 0.55);
}
.lrc-layer .lrc-word.is-current {
color: #ffd166 !important;
}`,
};
function LrcStyleControls({ style, onChange }) {
// 注意:onChange 接收的是「补丁」而不是完整 style,
// 这样连续快速修改多个样式时不会用旧快照互相覆盖。
const set = (patch) => onChange(patch);
const fontPreset = LRC_FONT_PRESETS.find((font) => font.value === style.fontFamily);
const appendCss = (snippet, extra = {}) => {
onChange((prevStyle) => {
const current = (prevStyle.customCss || '').trim();
return {
...extra,
customCss: (current ? current + '\n\n' : '') + snippet,
};
});
};
return (
<Row gutter={[10, 10]}>
<StyleField label="位置">
<Select value={style.position} onChange={v => set({ position: v })} style={{ width: '100%' }}>
<Select.Option value="bottom">底部</Select.Option>
<Select.Option value="center">居中</Select.Option>
<Select.Option value="top">顶部</Select.Option>
</Select>
</StyleField>
<StyleField label="水平对齐">
<Select value={style.align} onChange={v => set({ align: v })} style={{ width: '100%' }}>
<Select.Option value="center">居中</Select.Option>
<Select.Option value="left">左对齐</Select.Option>
<Select.Option value="right">右对齐</Select.Option>
</Select>
</StyleField>
<StyleField label="入场动画">
<Select value={style.animation} onChange={v => set({ animation: v })} style={{ width: '100%' }}>
<Select.Option value="fade">淡入</Select.Option>
<Select.Option value="slide">上滑</Select.Option>
<Select.Option value="zoom">缩放</Select.Option>
<Select.Option value="blur">模糊</Select.Option>
<Select.Option value="bounce">弹跳</Select.Option>
<Select.Option value="custom">自定义(写 CSS)</Select.Option>
<Select.Option value="none">无</Select.Option>
</Select>
</StyleField>
<StyleField label="显示下一句">
<Switch checked={style.showNextLine !== false} onChange={v => set({ showNextLine: v })} />
</StyleField>
<StyleField label="入场时长 (ms)">
<InputNumber
min={0} max={10000} step={50}
value={style.enterDurationMs}
onChange={v => set({ enterDurationMs: v == null ? 300 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="入场模糊半径 (px,模糊/出场用)">
<InputNumber
min={0} max={60} step={1}
value={style.blurPx}
onChange={v => set({ blurPx: v == null ? 10 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="出场动画">
<Select value={style.outro} onChange={v => set({ outro: v })} style={{ width: '100%' }}>
<Select.Option value="fade">淡出</Select.Option>
<Select.Option value="blur">模糊消散</Select.Option>
<Select.Option value="slideDown">下滑淡出</Select.Option>
<Select.Option value="slideUp">上浮淡出</Select.Option>
<Select.Option value="zoom">缩小淡出</Select.Option>
<Select.Option value="custom">自定义(写 CSS)</Select.Option>
<Select.Option value="none">无</Select.Option>
</Select>
</StyleField>
<StyleField label="出场时长 (ms)">
<InputNumber
min={0} max={10000} step={50}
value={style.outDurationMs}
onChange={v => set({ outDurationMs: v == null ? 260 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="入场后回缩到 (1 = 不回缩)">
<InputNumber
min={0.3} max={1} step={0.01}
value={style.holdShrinkTo}
onChange={v => set({ holdShrinkTo: v == null ? 1 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="回缩时长 (ms)">
<InputNumber
min={0} max={20000} step={100}
value={style.shrinkDurationMs}
onChange={v => set({ shrinkDurationMs: v == null ? 0 : v })}
style={{ width: '100%' }}
/>
</StyleField>
<StyleField label="回缩效果">
<Space style={{ height: 32 }}>
<Button
size="small"
onClick={() => set({ holdShrinkTo: 0.92, shrinkDurationMs: 1200 })}
>轻微回缩</Button>
<Button
size="small"
onClick={() => set({ holdShrinkTo: 1, shrinkDurationMs: 0 })}
disabled={Number(style.holdShrinkTo) === 1}
>关闭</Button>
</Space>
</StyleField>
<StyleField label="当前效果预览">
<Text style={{ color: '#888', fontSize: 12 }}>
入场 {Number(style.enterDurationMs || 0)}ms → 回缩到 {Number(style.holdShrinkTo || 1)}({Number(style.shrinkDurationMs || 0)}ms)
→ 出场 {Number(style.outDurationMs || 0)}ms
</Text>
</StyleField>
<StyleField label="显示背景">
<Switch
checked={style.backgroundEnabled !== false}
onChange={v => set({ backgroundEnabled: v })}
/>
</StyleField>
<StyleField label="文字阴影">
<Switch
checked={style.textShadowEnabled !== false}
onChange={v => set({ textShadowEnabled: v })}
/>
</StyleField>
<StyleField label="逐字点亮(增强型 LRC)">
<Switch checked={style.karaoke !== false} onChange={v => set({ karaoke: v })} />
</StyleField>
<StyleField label="未唱文字颜色">
<Input
value={style.karaokePendingColor || ''}
onChange={e => set({ karaokePendingColor: e.target.value })}
disabled={style.karaoke === false}
placeholder="rgba(255,255,255,0.45)"
/>
</StyleField>
<StyleField label="字号 (px)">
<InputNumber min={12} max={200} value={style.fontSize} onChange={v => set({ fontSize: v || 42 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="字重">
<Select value={style.fontWeight} onChange={v => set({ fontWeight: v })} style={{ width: '100%' }}>
{[300, 400, 500, 600, 700, 800, 900].map(w => (
<Select.Option key={w} value={w}>{w}</Select.Option>
))}
</Select>
</StyleField>
<StyleField label="字间距 (px)">
<InputNumber min={-10} max={40} step={0.5} value={style.letterSpacing} onChange={v => set({ letterSpacing: v || 0 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="行高">
<InputNumber min={0.8} max={3} step={0.05} value={style.lineHeight} onChange={v => set({ lineHeight: v || 1.35 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="文字颜色" span={8}>
<ColorInput value={style.color} onChange={v => set({ color: v })} placeholder="#ffffff" />
</StyleField>
<StyleField label="背景(支持 transparent / rgba)" span={16}>
<Input
value={style.background}
onChange={e => set({ background: e.target.value })}
placeholder="rgba(0, 0, 0, 0.55)"
disabled={style.backgroundEnabled === false}
/>
</StyleField>
<StyleField label="水平内边距">
<InputNumber min={0} max={200} value={style.paddingX} onChange={v => set({ paddingX: v || 0 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="垂直内边距">
<InputNumber min={0} max={120} value={style.paddingY} onChange={v => set({ paddingY: v || 0 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="圆角">
<InputNumber min={0} max={100} value={style.borderRadius} onChange={v => set({ borderRadius: v || 0 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="最大宽度 (%)">
<InputNumber min={20} max={100} value={style.maxWidthPercent} onChange={v => set({ maxWidthPercent: v || 86 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="距画面边缘 (vh)">
<InputNumber min={0} max={45} step={0.5} value={style.bottomOffsetVh} onChange={v => set({ bottomOffsetVh: v || 0 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="下一句缩放">
<InputNumber min={0.3} max={1} step={0.02} value={style.nextLineScale} onChange={v => set({ nextLineScale: v || 0.68 })} style={{ width: '100%' }} />
</StyleField>
<StyleField label="下一句颜色" span={10}>
<Input value={style.nextLineColor} onChange={e => set({ nextLineColor: e.target.value })} />
</StyleField>
<StyleField label="文字阴影(用上方开关启用/禁用)" span={10}>
<Input
value={style.textShadow}
onChange={e => set({ textShadow: e.target.value })}
placeholder="0 2px 12px rgba(0,0,0,.85)"
disabled={style.textShadowEnabled === false}
/>
</StyleField>
<StyleField label="字体" span={14}>
<Space.Compact style={{ width: '100%' }}>
<Select
placeholder="常用字体"
style={{ width: 180 }}
value={fontPreset ? fontPreset.value : undefined}
onChange={v => set({ fontFamily: v })}
options={LRC_FONT_PRESETS.map((font) => ({ value: font.value, label: font.label }))}
/>
<Input
value={style.fontFamily}
onChange={e => set({ fontFamily: e.target.value })}
placeholder="CSS font-family"
/>
</Space.Compact>
</StyleField>
<StyleField label="自定义 CSS / 自定义动画(.lrc-layer / .lrc-box / .lrc-text / .lrc-word)" span={24}>
<TextArea
rows={7}
value={style.customCss || ''}
onChange={e => set({ customCss: e.target.value })}
placeholder={'.lrc-layer .lrc-box { border: 1px solid #0ff; }\n@keyframes myAnim { ... }\n.lrc-layer.lrc-anim-custom .lrc-text { animation: myAnim .5s both; }'}
style={{ fontFamily: 'monospace', fontSize: 12 }}
/>
<Space wrap style={{ marginTop: 6 }}>
<Button size="small" onClick={() => appendCss(LRC_CSS_SNIPPETS.neon)}>+ 霓虹发光</Button>
<Button size="small" onClick={() => appendCss(LRC_CSS_SNIPPETS.gradient)}>+ 渐变文字</Button>
<Button size="small" onClick={() => appendCss(LRC_CSS_SNIPPETS.stroke)}>+ 描边文字</Button>
<Button size="small" onClick={() => appendCss(LRC_CSS_SNIPPETS.karaoke)}>+ 逐字发光</Button>
<Button size="small" onClick={() => appendCss(LRC_CSS_SNIPPETS.bounce, { animation: 'custom' })}>+ 弹跳入场</Button>
<Button size="small" onClick={() => appendCss(LRC_CSS_SNIPPETS.wipe, { animation: 'custom' })}>+ 擦除入场</Button>
<Button size="small" danger onClick={() => set({ customCss: '' })}>清空 CSS</Button>
</Space>
<div style={{ color: '#666', fontSize: 11, marginTop: 6 }}>
自定义 CSS 会同时应用到管理页预览和 OBS;要覆盖内置的背景/颜色/阴影等内联样式,请加 <code>!important</code>。
逐字效果需要 LRC 中包含 <code>&lt;mm:ss.xx&gt;</code> 增强时间戳;没有时间戳的行整句显示。
</div>
</StyleField>
</Row>
);
}
const LRC_OUTRO_OPTIONS = ['none', 'fade', 'blur', 'slideDown', 'slideUp', 'zoom', 'custom'];
function LrcPreviewStage({ style, cue, text, nextText, playing, elapsed, phase, configKey, fittedTiming }) {
const scale = 0.42;
const alignItems = style.position === 'top' ? 'flex-start' : (style.position === 'center' ? 'center' : 'flex-end');
const justifyContent = style.align === 'left' ? 'flex-start' : (style.align === 'right' ? 'flex-end' : 'center');
const edge = (style.bottomOffsetVh || 0) * 2.2;
const shadow = style.textShadowEnabled === false ? 'none' : style.textShadow;
const useKaraoke = style.karaoke !== false && cue
&& Array.isArray(cue.segments) && cue.segments.length >= 2;
const activeElapsed = elapsed == null ? Infinity : elapsed;
let lastSung = -1;
if (useKaraoke) {
cue.segments.forEach((segment, index) => {
if (segment.at <= activeElapsed) lastSung = index;
});
}
const outro = LRC_OUTRO_OPTIONS.includes(style.outro) ? style.outro : 'fade';
const hideText = phase === 'leaving' && outro === 'none';
// 传入的 phaseTiming 由播放循环按当前句间隔算好(入场+回缩必须塞进单句时长)
const phaseTiming = fittedTiming || {
enterMs: Number(style.enterDurationMs || 0),
shrinkMs: Number(style.shrinkDurationMs || 0)
};
const phaseKey = (cue ? cue.t : 'empty') + '|' + (phase || 'alpha') + '|' + configKey
+ '|' + phaseTiming.enterMs + '|' + phaseTiming.shrinkMs;
return (
<div
className={'lrc-preview-layer lrc-layer lrc-anim-' + (style.animation || 'fade')
+ ' lrc-out-' + outro + (phase ? ' lrc-state-' + phase : '')}
style={{
position: 'relative', width: '100%', aspectRatio: '16/9',
background: 'linear-gradient(135deg, #141826, #05070c)',
borderRadius: 8, overflow: 'hidden', display: 'flex',
alignItems, justifyContent,
paddingTop: style.position === 'top' ? edge : 0,
paddingBottom: style.position === 'bottom' ? edge : 0,
paddingLeft: 18, paddingRight: 18,
boxSizing: 'border-box',
'--lrc-in-dur': Number(phaseTiming.enterMs) + 'ms',
'--lrc-out-dur': Number(style.outDurationMs || 0) + 'ms',
'--lrc-shrink-dur': Number(phaseTiming.shrinkMs) + 'ms',
'--lrc-shrink-to': String(style.holdShrinkTo == null ? 1 : style.holdShrinkTo),
'--lrc-blur-px': Number(style.blurPx == null ? 10 : style.blurPx) + 'px'
}}
>
<div
className="lrc-box"
style={{
display: 'inline-block',
maxWidth: (style.maxWidthPercent || 86) + '%',
textAlign: 'center',
background: style.backgroundEnabled === false ? 'transparent' : style.background,
borderRadius: (style.borderRadius || 0) * scale,
padding: (style.paddingY || 0) * scale + 'px ' + (style.paddingX || 0) * scale + 'px'
}}
>
<div
key={phaseKey}
className="lrc-text"
style={{
whiteSpace: 'pre-line', wordBreak: 'break-word',
fontFamily: style.fontFamily,
fontSize: Math.max(10, (style.fontSize || 42) * scale) + 'px',
fontWeight: style.fontWeight,
color: style.color,
letterSpacing: (style.letterSpacing || 0) * scale + 'px',
lineHeight: style.lineHeight,
textShadow: shadow,
visibility: hideText ? 'hidden' : 'visible',
'--lrc-color': style.color,
'--lrc-karaoke-pending': style.karaokePendingColor || 'rgba(255, 255, 255, 0.45)'
}}
>
{useKaraoke
? cue.segments.map((segment, index) => (
<span
key={index}
className={'lrc-word ' + (index <= lastSung ? 'is-sung' : 'is-pending')
+ (index === lastSung ? ' is-current' : '')}
>{segment.text}</span>
))
: (text || '(字幕预览)')}
</div>
{style.showNextLine !== false && nextText && outro !== 'none' ? (
<div
key={'next-' + phaseKey}
className="lrc-next"
style={{
marginTop: 3, whiteSpace: 'pre-line', wordBreak: 'break-word',
fontSize: Math.max(8, (style.fontSize || 42) * scale * (style.nextLineScale || 0.68)) + 'px',
color: style.nextLineColor, fontFamily: style.fontFamily,
textShadow: shadow
}}
>{nextText}</div>
) : null}
</div>
<div style={{ position: 'absolute', top: 6, right: 8, color: 'rgba(255,255,255,0.35)', fontSize: 10 }}>
{playing ? '预览播放中' : '样式预览'}
</div>
</div>
);
}
function LrcPreviewCss({ css }) {
React.useEffect(() => {
const element = document.createElement('style');
element.setAttribute('data-lrc-preview-css', '1');
element.textContent = css || '';
document.head.appendChild(element);
return () => element.remove();
}, [css]);
return null;
}
// ── LRC Tab ─────────────────────────────────────────────────────────────
function LrcTab({ presets, lrcState, lrcDefaults, onRefresh, isActive }) {
const [selectedId, setSelectedId] = React.useState(null);
const [draft, setDraft] = React.useState(null);
const [dirty, setDirty] = React.useState(false);
const [parsed, setParsed] = React.useState(null);
const [parsing, setParsing] = React.useState(false);
const [saving, setSaving] = React.useState(false);
const [leadInMs, setLeadInMs] = React.useState(0);
const [showExcluded, setShowExcluded] = React.useState(false);
const [previewPlaying, setPreviewPlaying] = React.useState(false);
const [previewRun, setPreviewRun] = React.useState(0);
const [previewIndex, setPreviewIndex] = React.useState(-1);
const [previewElapsed, setPreviewElapsed] = React.useState(0);
const [previewPhase, setPreviewPhase] = React.useState(null);
const [previewLoop, setPreviewLoop] = React.useState(true);
const [nowTick, setNowTick] = React.useState(Date.now());
const fileRef = React.useRef(null);
const initializedRef = React.useRef(false);
const handlersRef = React.useRef({});
const makeDraft = React.useCallback(() => {
const defaults = lrcDefaults || {};
return {
id: null,
name: '未命名 LRC 字幕',
source: '',
filters: {
dropCreditLines: true,
dropUntimed: true,
creditKeywords: (defaults.creditKeywords || []).slice(),
...(defaults.filters || {})
},
range: { startIndex: 0, endIndex: null },
offsetMs: (defaults.timing && defaults.timing.offsetMs) || 0,
tailMs: (defaults.timing && defaults.timing.tailMs) || 4000,
style: { ...(defaults.style || {}) }
};
}, [lrcDefaults]);
const loadPreset = React.useCallback((id) => {
const preset = presets.find(p => p.id === id);
if (!preset) return;
setSelectedId(preset.id);
setDraft(deepClone(preset));
setDirty(false);
setParsed(null);
setPreviewPlaying(false);
}, [presets]);
React.useEffect(() => {
if (initializedRef.current) return;
if (presets.length > 0) {
initializedRef.current = true;
loadPreset(presets[0].id);
return;
}
// 服务器暂时不可用 / 还没有任何预设:先给一个空编辑器;
// 等预设列表到达后(例如断线重连)再自动载入第一条。
if (!draft) setDraft(makeDraft());
}, [presets, draft, loadPreset, makeDraft]);
const patchDraft = (updater) => {
setDraft(prev => (typeof updater === 'function' ? updater(prev) : { ...prev, ...updater }));
setDirty(true);
};
const updateSource = (source) => patchDraft(prev => ({
...prev,
source,
range: { startIndex: 0, endIndex: null }
}));
const updateFilters = (patch) => patchDraft(prev => ({
...prev,
filters: { ...prev.filters, ...patch },
range: { startIndex: 0, endIndex: null }
}));
const updateStyle = (patchOrUpdater) => patchDraft(prev => {
const patch = typeof patchOrUpdater === 'function'
? patchOrUpdater(prev.style)
: patchOrUpdater;
return { ...prev, style: { ...prev.style, ...patch } };
});
const configKey = draft ? JSON.stringify([
draft.source, draft.filters, draft.range, draft.offsetMs, draft.tailMs
]) : '';
React.useEffect(() => {
if (!draft) return undefined;
let cancelled = false;
setParsing(true);
const timer = setTimeout(async () => {
try {
const res = await fetch('/api/lrc/parse', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
source: draft.source,
filters: draft.filters,
range: draft.range,
offsetMs: draft.offsetMs,
tailMs: draft.tailMs
})
});
const data = await res.json();
if (cancelled) return;
if (!res.ok) {
setParsed({ error: data.error || '解析失败', cues: [], candidates: [], excluded: [], stats: {} });
} else {
setParsed(data);
}
} catch (e) {
if (!cancelled) {
setParsed({ error: '无法解析:' + e.message, cues: [], candidates: [], excluded: [], stats: {} });
}
} finally {
if (!cancelled) setParsing(false);
}
}, 250);
return () => { cancelled = true; clearTimeout(timer); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [configKey]);
React.useEffect(() => {
setPreviewPlaying(false);
setPreviewIndex(-1);
setPreviewElapsed(0);
setPreviewPhase(null);
}, [configKey]);
React.useEffect(() => {
if (!previewPlaying) return undefined;
const cues = (parsed && parsed.cues) || [];
if (!cues.length) {
setPreviewPlaying(false);
return undefined;
}
const style = draft.style || {};
const baseEnterMs = Math.max(0, Number(style.enterDurationMs) || 0);
const baseShrinkMs = Math.max(0, Number(style.shrinkDurationMs) || 0);
const outMs = Math.max(0, Number(style.outDurationMs) || 0);
const outro = LRC_OUTRO_OPTIONS.includes(style.outro) ? style.outro : 'fade';
const last = cues[cues.length - 1];
const outroStart = last.t + (Number(draft.tailMs) || 0);
const endAt = outroStart + (outro === 'none' ? 0 : outMs);
const loopPause = 700;
// 和 OBS 端一致:入场 + 回缩必须塞进「到下一句」的间隔里
const fitToWindow = (index) => {
const cue = cues[index];
if (!cue) return { enterMs: baseEnterMs, shrinkMs: baseShrinkMs, windowMs: 0 };
const next = cues[index + 1];
const windowMs = Math.max(0, (next ? next.t : cue.t + (Number(draft.tailMs) || 0)) - cue.t);
const available = Math.max(120, windowMs);
if (baseEnterMs + baseShrinkMs <= available) {
return { enterMs: baseEnterMs, shrinkMs: baseShrinkMs, windowMs };
}
const enterMs = Math.round(Math.min(baseEnterMs, available * 0.45));
const shrinkMs = Math.round(Math.max(120, Math.min(baseShrinkMs, available - enterMs)));
return { enterMs, shrinkMs, windowMs };
};
const startedAt = performance.now();
setPreviewIndex(-1);
setPreviewElapsed(0);
setPreviewPhase(null);
const timer = setInterval(() => {
const elapsed = performance.now() - startedAt;
let index = -1;
for (let i = 0; i < cues.length; i += 1) {
if (cues[i].t <= elapsed) index = i;
else break;
}
setPreviewIndex(index);
setPreviewElapsed(elapsed);
// 注意:预览用粗粒度 tick 判断阶段,字幕点到点之间可能只差 300ms,
// 所以用「距本句开始已过多久」而不是绝对时间,确保每句都会走完入场→回缩。
if (index >= 0 && elapsed >= outroStart) {
setPreviewPhase(outro === 'none' ? null : 'leaving');
} else if (index >= 0) {
const fitted = fitToWindow(index);
setPreviewPhase(elapsed >= cues[index].t + fitted.enterMs ? 'hold' : 'entering');
} else {
setPreviewPhase(null);
}
if (elapsed > endAt + loopPause) {
if (previewLoop) {
setPreviewRun(v => v + 1);
} else {
setPreviewPlaying(false);
setPreviewPhase(null);
}
}
}, 50);
return () => clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [previewPlaying, previewRun, parsed, previewLoop]);
React.useEffect(() => {
if (!lrcState || !lrcState.playing) return undefined;
const timer = setInterval(() => setNowTick(Date.now()), 100);
return () => clearInterval(timer);
}, [lrcState && lrcState.playing, lrcState && lrcState.anchor]);
const candidates = (parsed && parsed.candidates) || [];
const cues = (parsed && parsed.cues) || [];
const stats = (parsed && parsed.stats) || {};
const excluded = (parsed && parsed.excluded) || [];
const meta = (parsed && parsed.meta) || {};
const clampIndex = (value, fallback) => {
if (!candidates.length) return fallback;
if (value === null || value === undefined || value === '') return fallback;
const number = Number(value);
if (!Number.isFinite(number)) return fallback;
return Math.max(0, Math.min(number, candidates.length - 1));
};
const startIndex = clampIndex(draft && draft.range.startIndex, 0);
const endIndex = clampIndex(draft && draft.range.endIndex, Math.max(0, candidates.length - 1));
const liveCues = (lrcState && lrcState.playing && Array.isArray(lrcState.cues)) ? lrcState.cues : [];
let liveElapsed = 0;
if (lrcState && lrcState.playing) {
if (lrcState.paused) {
liveElapsed = lrcState.pausedElapsed || 0;
} else {
liveElapsed = Math.max(0, nowTick - lrcState.anchor);
}
}
let liveIndex = -1;
for (let i = 0; i < liveCues.length; i += 1) {
if (liveCues[i].t <= liveElapsed) liveIndex = i;
else break;
}
const liveCue = liveIndex >= 0 ? liveCues[liveIndex] : null;
const liveNext = liveCues[liveIndex + 1] || null;
const liveDuration = (lrcState && lrcState.playing) ? Math.max(0, (lrcState.endMs || 0) - (lrcState.anchor || 0)) : 0;
const previewCue = previewIndex >= 0 ? cues[previewIndex] : null;
const stageCue = previewCue || cues[0] || null;
const stageIndex = previewCue ? previewIndex : 0;
const stageElapsed = previewPlaying ? previewElapsed : Infinity;
// 未播放时直接展示「入场结束后的停留状态」,方便看清最终样式
const stagePhase = previewPlaying ? previewPhase : 'hold';
const sampleText = stageCue ? stageCue.text : '';
const sampleNext = cues[stageIndex + 1] ? cues[stageIndex + 1].text : '';
const selectedCount = cues.length;
const karaokeCount = cues.filter(cue => Array.isArray(cue.segments) && cue.segments.length >= 2).length;
// 当前舞台这句的适配时长(与 OBS 端一致:入场+回缩塞进到下一句的间隔里)
const stageFitted = (() => {
const cue = stageCue;
const style = (draft && draft.style) || {};
const base = {
enterMs: Math.max(0, Number(style.enterDurationMs) || 0),
shrinkMs: Math.max(0, Number(style.shrinkDurationMs) || 0)
};
if (!cue) return base;
const next = cues[stageIndex + 1];
const windowMs = Math.max(0, (next ? next.t : cue.t + (Number(draft.tailMs) || 0)) - cue.t);
const available = Math.max(120, windowMs);
if (base.enterMs + base.shrinkMs <= available) return { ...base, windowMs };
const enterMs = Math.round(Math.min(base.enterMs, available * 0.45));
const shrinkMs = Math.round(Math.max(120, Math.min(base.shrinkMs, available - enterMs)));
return { enterMs, shrinkMs, windowMs };
})();
const saveDraft = async (options = {}) => {
if (!draft) return null;
setSaving(true);
try {
const body = {
name: draft.name || '未命名 LRC 字幕',
source: draft.source,
filters: draft.filters,
range: draft.range,
offsetMs: draft.offsetMs,
tailMs: draft.tailMs,
style: draft.style
};
const res = await fetch(selectedId ? '/api/lrc-presets/' + selectedId : '/api/lrc-presets', {
method: selectedId ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || '保存失败');
setSelectedId(data.id);
setDraft(deepClone(data));
setDirty(false);
onRefresh();
if (!options.silent) message.success('LRC 预设已保存');
return data;
} catch (e) {
message.error(e.message || '保存失败');
return null;
} finally {
setSaving(false);
}
};
const playDraft = async () => {
if (!draft) return;
if (!draft.source.trim()) {
message.warning('请先导入或粘贴 LRC 文本');
return;
}
let presetId = selectedId;
if (!presetId) {
const saved = await saveDraft({ silent: true });
if (!saved) return;
presetId = saved.id;
}
try {
const res = await fetch('/api/lrc-presets/' + presetId + '/play', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
leadInMs,
overrides: {
source: draft.source,
filters: draft.filters,
range: draft.range,
offsetMs: draft.offsetMs,
tailMs: draft.tailMs,
style: draft.style
}
})
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || '开始失败');
const firstOffset = (data.state && data.state.cues && data.state.cues[0] ? data.state.cues[0].t : 0) + (leadInMs || 0);
message.success('已打点开始:' + (data.state.presetName || draft.name) + '(首句约 ' + formatMs(firstOffset) + ' 后出现)');
onRefresh();
} catch (e) {
message.error(e.message || '开始失败');
}
};
const playSaved = async (preset) => {
loadPreset(preset.id);
try {
const res = await fetch('/api/lrc-presets/' + preset.id + '/play', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ leadInMs })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || '开始失败');
message.success('已打点开始:' + preset.name);
onRefresh();
} catch (e) {
message.error(e.message || '开始失败');
}
};
const stopPlayback = async () => {
await fetch('/api/lrc/stop', { method: 'POST' });
onRefresh();
};
const pauseResume = async () => {
if (!lrcState || !lrcState.playing) return;
const action = lrcState.paused ? 'resume' : 'pause';
await fetch('/api/lrc/' + action, { method: 'POST' });
onRefresh();
};
const newPreset = () => {
setSelectedId(null);
setDraft(makeDraft());
setDirty(true);
setParsed(null);
setPreviewPlaying(false);
};
const deletePreset = async (preset) => {
await fetch('/api/lrc-presets/' + preset.id, { method: 'DELETE' });
if (selectedId === preset.id) newPreset();
message.success('已删除 LRC 预设');
onRefresh();
};
const handleFile = async (event) => {
const file = event.target.files && event.target.files[0];
event.target.value = '';
if (!file) return;
try {
const text = await file.text();
patchDraft(prev => ({
...prev,
source: text,
name: (!prev.name || prev.name === '未命名 LRC 字幕')
? file.name.replace(/\.lrc$/i, '')
: prev.name,
range: { startIndex: 0, endIndex: null }
}));
message.success('已导入 ' + file.name);
} catch (e) {
message.error('读取文件失败:' + e.message);
}
};
handlersRef.current = {
play: playDraft,
pauseResume,
stop: stopPlayback
};
React.useEffect(() => {
if (!isActive) return undefined;
const onKeyDown = (e) => {
const tag = (e.target && e.target.tagName) || '';
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (e.target && e.target.isContentEditable)) return;
if (e.repeat || e.ctrlKey || e.metaKey || e.altKey) return;
const handlers = handlersRef.current;
if (e.key === 'l' || e.key === 'L') {
e.preventDefault();
handlers.play && handlers.play();
} else if (e.key === 'j' || e.key === 'J') {
e.preventDefault();
handlers.pauseResume && handlers.pauseResume();
} else if (e.key === 'k' || e.key === 'K') {
e.preventDefault();
handlers.stop && handlers.stop();
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [isActive]);
if (!draft) {
return <div style={{ textAlign: 'center', padding: 40 }}><Spin /></div>;
}
const rangeOptions = candidates.map((candidate) => ({
value: candidate.index,
label: formatMs(candidate.time * 1000) + ' · ' + shortText(candidate.text, 26)
}));
return (
<div>
{isActive && <LrcPreviewCss css={draft.style.customCss} />}
{/* 播放控制 */}
<Card
size="small"
style={{ marginBottom: 12, background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
>
<Row gutter={[12, 8]} align="middle">
<Col flex="auto">
<Space wrap>
<Button type="primary" size="large" onClick={playDraft}>▶ 打点开始</Button>
<Button onClick={pauseResume} disabled={!lrcState || !lrcState.playing}>
{lrcState && lrcState.paused ? '继续' : '暂停'}
</Button>
<Button danger onClick={stopPlayback} disabled={!lrcState || !lrcState.playing}>停止</Button>
<Text style={{ color: '#aaa' }}>首句延迟</Text>
<InputNumber
min={0} max={60000} step={100} value={leadInMs}
onChange={v => setLeadInMs(Number(v) || 0)}
addonAfter="ms" style={{ width: 150 }}
/>
<Text style={{ color: '#666', fontSize: 12 }}>
快捷键 <span className="kbd-hint">L</span> 打点开始
<span className="kbd-hint" style={{ marginLeft: 6 }}>J</span> 暂停/继续
<span className="kbd-hint" style={{ marginLeft: 6 }}>K</span> 停止
</Text>
</Space>
</Col>
<Col>
{lrcState && lrcState.playing ? (
<div style={{ minWidth: 220, textAlign: 'right' }}>
<Text style={{ color: lrcState.paused ? '#faad14' : '#52c41a', fontSize: 12 }}>
{lrcState.paused ? '已暂停' : '播放中'} · {lrcState.presetName}
</Text>
<div style={{ color: '#fff', fontSize: 14, marginTop: 2 }}>
{liveCue ? liveCue.text : '(等待首句)'}
</div>
<Text style={{ color: '#888', fontSize: 11 }}>
{formatMs(Math.min(liveElapsed, liveDuration))} / {formatMs(liveDuration)}
{liveNext ? ' · 下一句:' + shortText(liveNext.text, 16) : ''}
</Text>
</div>
) : (
<Text style={{ color: '#666', fontSize: 12 }}>未播放 · 打点后首句立即开始</Text>
)}
</Col>
</Row>
</Card>
<Row gutter={16}>
{/* 预设列表 */}
<Col xs={24} md={7}>
<Card
size="small"
title={<Text style={{ color: '#fff' }}>LRC 预设</Text>}
style={{ background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
>
<Button type="dashed" block onClick={newPreset} style={{ marginBottom: 8 }}>+ 新建 LRC 预设</Button>
{presets.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={<span style={{ color: '#666' }}>暂无 LRC 预设</span>} />
) : presets.map((preset) => {
const isSelected = selectedId === preset.id;
const isPlaying = lrcState && lrcState.playing && lrcState.presetId === preset.id;
let cls = 'preset-list-item';
if (isSelected) cls += ' selected';
if (isPlaying) cls += ' active-live';
return (
<Card
key={preset.id}
size="small"
className={cls}
style={{
marginBottom: 8,
background: 'rgba(255,255,255,0.04)',
borderColor: isPlaying ? '#52c41a' : isSelected ? '#1890ff' : 'rgba(255,255,255,0.1)'
}}
onClick={() => loadPreset(preset.id)}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
<div style={{ minWidth: 0 }}>
<Space size={4} wrap>
<Text style={{ color: '#fff', fontSize: 13 }} ellipsis>{preset.name}</Text>
{isPlaying && (
<Tag color={lrcState.paused ? 'orange' : 'green'} style={{ fontSize: 10 }}>
{lrcState.paused ? '已暂停' : '播放中'}
</Tag>
)}
</Space>
<br />
<Text style={{ color: '#888', fontSize: 11 }}>
{preset.source ? preset.source.split('\n').length + ' 行 LRC' : '空 LRC'}
{dirty && isSelected ? ' · 未保存' : ''}
</Text>
</div>
<Space size={2} direction="vertical">
<Button size="small" onClick={e => { e.stopPropagation(); playSaved(preset); }}>打点</Button>
<Popconfirm
title="确认删除该 LRC 预设?"
onConfirm={e => { if (e && e.stopPropagation) e.stopPropagation(); deletePreset(preset); }}
onCancel={e => e.stopPropagation()}
>
<Button danger size="small" type="text" onClick={e => e.stopPropagation()}>删除</Button>
</Popconfirm>
</Space>
</div>
</Card>
);
})}
</Card>
</Col>
{/* 编辑器 */}
<Col xs={24} md={17}>
<Card
size="small"
title={
<Space>
<Text style={{ color: '#fff' }}>{selectedId ? '编辑 LRC 预设' : '新建 LRC 预设'}</Text>
{dirty && <Tag color="orange">未保存</Tag>}
</Space>
}
extra={
<Space>
<Button onClick={newPreset}>新建</Button>
<Button onClick={() => saveDraft()} loading={saving} type="primary">保存预设</Button>
</Space>
}
style={{ background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
>
<div style={{ marginBottom: 4, color: '#888', fontSize: 11 }}>预设名称</div>
<Input
value={draft.name}
onChange={e => patchDraft({ name: e.target.value })}
placeholder="例如:晚会歌曲 A 段字幕"
style={{ marginBottom: 12 }}
/>
<Divider orientation="left" style={{ borderColor: 'rgba(255,255,255,0.1)' }}>
<Text style={{ color: '#aaa', fontSize: 12 }}>LRC 文本</Text>
</Divider>
<Space wrap style={{ marginBottom: 8 }}>
<input ref={fileRef} type="file" accept=".lrc,.txt,text/plain" onChange={handleFile} style={{ display: 'none' }} />
<Button onClick={() => fileRef.current && fileRef.current.click()}>导入 .lrc 文件</Button>
<Button onClick={() => updateSource('')} disabled={!draft.source}>清空文本</Button>
<Text style={{ color: '#666', fontSize: 12 }}>也可以直接粘贴 LRC 文本(支持 [mm:ss.xx] 与逐字标签)</Text>
</Space>
<TextArea
rows={9}
value={draft.source}
onChange={e => updateSource(e.target.value)}
placeholder={'[ti:歌曲名]\n[ar:歌手]\n[00:12.34]第一句歌词\n[00:16.00]第二句歌词'}
style={{ fontFamily: 'monospace', fontSize: 12 }}
/>
<div style={{ marginTop: 8 }}>
<Space size={4} wrap>
{Object.entries(meta).map(([key, value]) => (
<Tag key={key} style={{ fontSize: 11 }}>{key.toUpperCase()}: {String(value)}</Tag>
))}
{parsed && parsed.metaOffsetMs ? <Tag color="purple">offset: {parsed.metaOffsetMs}ms</Tag> : null}
{parsing ? <Tag color="processing">解析中…</Tag> : null}
{parsed && parsed.error ? <Tag color="error">{parsed.error}</Tag> : null}
</Space>
</div>
{(parsed && parsed.warnings && parsed.warnings.length > 0) ? (
<Alert
type="warning" showIcon style={{ marginTop: 8 }}
message={parsed.warnings.join(';')}
/>
) : null}
<div style={{ marginTop: 8, color: '#888', fontSize: 12 }}>
总行数 {stats.sourceLines || 0} · 带时间轴歌词 {stats.timedLyricLines || 0} ·
过滤版权/制作信息 {stats.excludedCredit || 0} 行 ·
入选 {stats.keptLyricLines || 0} 行 ·
<Text style={{ color: cues.length ? '#52c41a' : '#faad14' }}>
{' '}最终字幕 {cues.length} 句 · 时长 {formatMs(parsed ? parsed.totalMs : 0)}
{karaokeCount > 0 ? ' · 逐字 ' + karaokeCount + ' 句' : ''}
</Text>
</div>
<Divider orientation="left" style={{ borderColor: 'rgba(255,255,255,0.1)' }}>
<Text style={{ color: '#aaa', fontSize: 12 }}>过滤范围(版权信息)</Text>
</Divider>
<Row gutter={[12, 10]} align="middle">
<Col span={12}>
<Space>
<Switch
checked={draft.filters.dropCreditLines !== false}
onChange={v => updateFilters({ dropCreditLines: v })}
/>
<Text style={{ color: '#ccc', fontSize: 12 }}>过滤版权 / 制作信息行</Text>
</Space>
</Col>
<Col span={12}>
<Space>
<Switch
checked={draft.filters.dropUntimed !== false}
onChange={v => updateFilters({ dropUntimed: v })}
/>
<Text style={{ color: '#ccc', fontSize: 12 }}>忽略无时间戳行</Text>
</Space>
</Col>
<Col span={24}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>
过滤关键词(命中行首附近即过滤;可回车添加)
</div>
<Select
mode="tags"
value={draft.filters.creditKeywords || []}
onChange={values => updateFilters({ creditKeywords: values })}
tokenSeparators={[',', ',']}
placeholder="作词 / 作曲 / 编曲 / 制作人 …"
style={{ width: '100%' }}
/>
<Space style={{ marginTop: 6 }}>
<Button
size="small"
onClick={() => updateFilters({ creditKeywords: (lrcDefaults && lrcDefaults.creditKeywords) || [] })}
>恢复默认关键词</Button>
<Button size="small" onClick={() => setShowExcluded(v => !v)}>
{showExcluded ? '收起' : '查看'}已过滤行({excluded.length})
</Button>
</Space>
</Col>
{showExcluded && (
<Col span={24}>
<div style={{
maxHeight: 160, overflowY: 'auto', background: 'rgba(0,0,0,0.25)',
borderRadius: 6, padding: '6px 10px'
}}>
{excluded.length === 0
? <Text style={{ color: '#666', fontSize: 12 }}>没有被过滤的行</Text>
: excluded.map((item, idx) => (
<div key={idx} style={{ fontSize: 12, color: '#888', padding: '2px 0' }}>
<Tag color="red" style={{ fontSize: 10 }}>{item.reason}</Tag>
{item.time != null ? <span style={{ color: '#666', marginRight: 6 }}>{formatMs(item.time * 1000)}</span> : null}
<span>{shortText(item.text, 60)}</span>
</div>
))
}
</div>
</Col>
)}
</Row>
<Divider orientation="left" style={{ borderColor: 'rgba(255,255,255,0.1)' }}>
<Text style={{ color: '#aaa', fontSize: 12 }}>取句范围与时间</Text>
</Divider>
<Row gutter={[12, 10]}>
<Col xs={24} md={10}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>起始句</div>
<Select
showSearch
value={candidates.length ? startIndex : undefined}
onChange={v => patchDraft(prev => {
const lastIdx = Math.max(0, candidates.length - 1);
const prevEnd = prev.range.endIndex == null ? lastIdx : Math.min(prev.range.endIndex, lastIdx);
return {
...prev,
range: { startIndex: v, endIndex: Math.max(v, prevEnd) }
};
})}
options={rangeOptions}
optionFilterProp="label"
style={{ width: '100%' }}
disabled={!candidates.length}
placeholder="先导入 LRC"
/>
</Col>
<Col xs={24} md={10}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>结束句</div>
<Select
showSearch
value={candidates.length ? endIndex : undefined}
onChange={v => patchDraft(prev => ({
...prev,
range: { startIndex: Math.min(v, startIndex), endIndex: v }
}))}
options={rangeOptions}
optionFilterProp="label"
style={{ width: '100%' }}
disabled={!candidates.length}
placeholder="先导入 LRC"
/>
</Col>
<Col xs={24} md={4}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>&nbsp;</div>
<Button
block
onClick={() => patchDraft(prev => ({ ...prev, range: { startIndex: 0, endIndex: null } }))}
disabled={!candidates.length}
>全选</Button>
</Col>
<Col xs={12} md={6}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>手动偏移 (ms)</div>
<InputNumber
min={-60000} max={60000} step={50}
value={draft.offsetMs}
onChange={v => patchDraft({ offsetMs: Number(v) || 0 })}
style={{ width: '100%' }}
addonAfter="ms"
/>
</Col>
<Col xs={12} md={6}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>末句停留 (ms)</div>
<InputNumber
min={0} max={60000} step={500}
value={draft.tailMs}
onChange={v => patchDraft({ tailMs: Number(v) || 0 })}
style={{ width: '100%' }}
addonAfter="ms"
/>
</Col>
<Col xs={24} md={12}>
<div style={{ color: '#888', fontSize: 11, marginBottom: 4 }}>时间轴说明</div>
<Text style={{ color: '#999', fontSize: 12 }}>
打点时把「起始句」当作 0 点,后续句子按 LRC 原始间隔显示;
手动偏移为正数时整体延后。已选 {selectedCount} 句。
</Text>
</Col>
</Row>
<Divider orientation="left" style={{ borderColor: 'rgba(255,255,255,0.1)' }}>
<Text style={{ color: '#aaa', fontSize: 12 }}>字幕样式与预览</Text>
</Divider>
<Row gutter={16}>
<Col xs={24} lg={12}>
<LrcPreviewStage
style={draft.style}
cue={stageCue}
text={sampleText}
nextText={sampleNext}
playing={previewPlaying}
elapsed={stageElapsed}
phase={stagePhase}
configKey={configKey}
fittedTiming={stageFitted}
/>
<Space style={{ marginTop: 8 }} wrap>
<Button
type="primary"
ghost
disabled={!cues.length}
onClick={() => { setPreviewRun(v => v + 1); setPreviewPlaying(true); }}
>▶ 试播本段</Button>
<Button disabled={!previewPlaying} onClick={() => setPreviewPlaying(false)}>停止试播</Button>
<Space size={4}>
<Switch size="small" checked={previewLoop} onChange={setPreviewLoop} />
<Text style={{ color: '#888', fontSize: 12 }}>循环</Text>
</Space>
<Text style={{ color: '#888', fontSize: 12 }}>
{previewCue ? formatMs(previewCue.t) : '—'} / {formatMs(parsed ? parsed.totalMs : 0)}
{previewPlaying && previewPhase ? ' · ' + (
previewPhase === 'entering' ? '入场中'
: previewPhase === 'hold' ? '停留 / 回缩' : '出场中'
) : ''}
</Text>
</Space>
</Col>
<Col xs={24} lg={12}>
<div style={{
maxHeight: 320, overflowY: 'auto', background: 'rgba(0,0,0,0.22)',
borderRadius: 6, padding: '6px 10px'
}}>
{candidates.length === 0 ? (
<Text style={{ color: '#666', fontSize: 12 }}>解析后在这里显示可选字幕行</Text>
) : candidates.map((candidate) => {
const active = candidate.index >= startIndex && candidate.index <= endIndex;
return (
<div
key={candidate.index}
style={{
display: 'flex', gap: 8, padding: '3px 4px', fontSize: 12,
color: active ? '#ddd' : '#555',
background: active ? 'rgba(24,144,255,0.08)' : 'transparent',
borderRadius: 4
}}
>
<span style={{ color: active ? '#1890ff' : '#444', fontFamily: 'monospace', flex: '0 0 58px' }}>
{formatMs(candidate.time * 1000)}
</span>
<span style={{ flex: 1 }}>{shortText(candidate.text, 60)}</span>
</div>
);
})}
</div>
</Col>
</Row>
<div style={{ marginTop: 14 }}>
<LrcStyleControls style={draft.style} onChange={updateStyle} />
</div>
<Divider style={{ borderColor: 'rgba(255,255,255,0.1)' }} />
<Space>
<Button type="primary" onClick={() => saveDraft()} loading={saving}>
{selectedId ? '保存修改' : '保存为新预设'}
</Button>
<Button onClick={playDraft} disabled={!draft.source.trim()}>▶ 用当前设置打点开始</Button>
<Button onClick={newPreset}>清空 / 新建</Button>
</Space>
</Card>
</Col>
</Row>
</div>
);
}
// ── Live Control Tab ────────────────────────────────────────────────────
function LiveControlTab({ contentPresets, appearancePresets, activeContentPresetId, activePresetId, autoHideDuration, onRefresh, isActive }) {
const [selectedIdx, setSelectedIdx] = React.useState(0);
const [activating, setActivating] = React.useState(false);
const [localAutoHide, setLocalAutoHide] = React.useState(autoHideDuration || 0);
const [autoHideEnabled, setAutoHideEnabled] = React.useState((autoHideDuration || 0) > 0);
const containerRef = React.useRef(null);
// Update local state when prop changes
React.useEffect(() => {
setLocalAutoHide(autoHideDuration || 0);
setAutoHideEnabled((autoHideDuration || 0) > 0);
}, [autoHideDuration]);
// Focus for keyboard navigation
React.useEffect(() => {
if (containerRef.current) containerRef.current.focus();
}, []);
const selectedCp = contentPresets[selectedIdx];
const selectedAp = selectedCp ? appearancePresets.find(p => p.id === selectedCp.appearancePresetId) : null;
// Determine preview content data
const previewData = React.useMemo(() => {
if (!selectedAp || !selectedCp) return {};
const data = {};
(selectedAp.fieldDefs || []).forEach(fd => { data[fd.key] = fd.defaultValue || ''; });
return { ...data, ...selectedCp.fields };
}, [selectedAp, selectedCp]);
const handleActivate = React.useCallback(async (cpId) => {
const id = cpId || (selectedCp ? selectedCp.id : null);
if (!id) return;
setActivating(true);
try {
const effectiveDuration = autoHideEnabled ? localAutoHide : 0;
await fetch('/api/content-presets/' + id + '/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ autoHideDuration: effectiveDuration })
});
onRefresh();
} finally {
setActivating(false);
}
}, [selectedCp, autoHideEnabled, localAutoHide, onRefresh]);
const handleClear = async () => {
await fetch('/api/clear', { method: 'POST' });
onRefresh();
};
const handleAutoHideChange = async (val) => {
setLocalAutoHide(val || 0);
const effectiveDuration = autoHideEnabled ? (val || 0) : 0;
await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ autoHideDuration: effectiveDuration })
});
onRefresh();
};
const handleAutoHideToggle = async (checked) => {
setAutoHideEnabled(checked);
const effectiveDuration = checked ? localAutoHide : 0;
await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ autoHideDuration: effectiveDuration })
});
onRefresh();
};
// Keyboard handler for the focused list container
const handleKeyDown = React.useCallback((e) => {
if (contentPresets.length === 0) return;
if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedIdx(i => Math.max(0, i - 1));
} else if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedIdx(i => Math.min(contentPresets.length - 1, i + 1));
} else if (e.key === 'Enter') {
e.preventDefault();
handleActivate();
}
}, [contentPresets.length, handleActivate]);
// Also listen globally (only when this tab is visible)
React.useEffect(() => {
if (!isActive) return undefined;
const fn = (e) => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') return;
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (e.key === 'ArrowUp') { e.preventDefault(); setSelectedIdx(i => Math.max(0, i - 1)); }
else if (e.key === 'ArrowDown') { e.preventDefault(); setSelectedIdx(i => Math.min(contentPresets.length - 1, i + 1)); }
else if (e.key === 'Enter') { e.preventDefault(); handleActivate(); }
};
window.addEventListener('keydown', fn);
return () => window.removeEventListener('keydown', fn);
}, [isActive, contentPresets.length, handleActivate]);
return (
<Row gutter={16}>
<Col xs={24} md={10}>
{/* Auto-hide settings */}
<Card
size="small"
style={{ marginBottom: 12, background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
>
<Space wrap>
<Text style={{ color: '#aaa' }}>自动隐藏:</Text>
<Switch
checked={autoHideEnabled}
onChange={handleAutoHideToggle}
checkedChildren="开"
unCheckedChildren="关"
/>
{autoHideEnabled && (
<>
<InputNumber
min={500}
max={60000}
step={500}
value={localAutoHide}
onChange={handleAutoHideChange}
addonAfter="ms"
style={{ width: 140 }}
/>
<Text style={{ color: '#888', fontSize: 12 }}>
({(localAutoHide / 1000).toFixed(1)} 秒后隐藏)
</Text>
</>
)}
</Space>
</Card>
{/* Keyboard hints */}
<div style={{ marginBottom: 8, color: '#666', fontSize: 12 }}>
<span className="kbd-hint">↑</span> <span className="kbd-hint">↓</span> 切换 &nbsp;
<span className="kbd-hint">Enter</span> 激活
</div>
{/* Content preset list */}
<div
ref={containerRef}
tabIndex={0}
onKeyDown={handleKeyDown}
style={{ outline: 'none' }}
>
{contentPresets.length === 0
? <Empty description={<span style={{color:'#666'}}>请先在"内容预设"标签页创建内容预设</span>} />
: contentPresets.map((cp, idx) => {
const isSelected = idx === selectedIdx;
const isActive = cp.id === activeContentPresetId;
const linkAp = appearancePresets.find(p => p.id === cp.appearancePresetId);
let cls = 'preset-list-item';
if (isSelected) cls += ' selected';
if (isActive) cls += ' active-live';
return (
<Card
key={cp.id}
size="small"
className={cls}
style={{
marginBottom: 6,
background: 'rgba(255,255,255,0.04)',
borderColor: isActive ? '#52c41a' : isSelected ? '#1890ff' : 'rgba(255,255,255,0.1)',
cursor: 'pointer'
}}
onClick={() => { setSelectedIdx(idx); }}
onDoubleClick={() => handleActivate(cp.id)}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div style={{ flex: 1 }}>
<Space>
<Text style={{ color: '#fff', fontSize: 13, fontWeight: isSelected ? 600 : 400 }}>
{idx + 1}. {cp.name}
</Text>
{isActive && <Tag color="green" style={{ fontSize: 10 }}>直播中</Tag>}
</Space>
<br/>
<Text style={{ color: '#888', fontSize: 11 }}>
{linkAp ? linkAp.name : <span style={{color:'#ff7875'}}>外观未关联</span>}
</Text>
</div>
<Button
type={isActive ? 'default' : 'primary'}
size="small"
loading={activating && isSelected}
onClick={e => { e.stopPropagation(); handleActivate(cp.id); }}
style={{ minWidth: 52 }}
>
{isActive ? '重激活' : '激活'}
</Button>
</div>
</Card>
);
})
}
</div>
<div style={{ marginTop: 12 }}>
<Button danger block onClick={handleClear}>🔲 清空显示(透明)</Button>
</div>
</Col>
<Col xs={24} md={14}>
<Card
title={
<Space>
<Text style={{ color: '#aaa', fontSize: 12 }}>预览:</Text>
<Text style={{ color: '#fff', fontSize: 13 }}>
{selectedCp ? selectedCp.name : '(请选择内容预设)'}
</Text>
{selectedCp && selectedAp && <Tag color="blue" style={{ fontSize: 10 }}>{selectedAp.name}</Tag>}
</Space>
}
style={{ background: 'rgba(255,255,255,0.04)', borderColor: 'rgba(255,255,255,0.1)' }}
>
{selectedAp
? <PreviewPanel preset={selectedAp} contentData={previewData} />
: <div style={{ color: '#666', textAlign: 'center', padding: 40, fontSize: 13 }}>
{contentPresets.length === 0 ? '请先创建内容预设' : selectedCp ? '该内容预设未关联外观预设' : '请选择内容预设'}
</div>
}
{selectedCp && selectedAp && (
<div style={{ marginTop: 12 }}>
<Text style={{ color: '#888', fontSize: 12 }}>字段值:</Text>
<div style={{ marginTop: 6 }}>
{(selectedAp.fieldDefs || []).map(fd => (
<div key={fd.key} style={{ display: 'flex', gap: 8, marginBottom: 4, fontSize: 12 }}>
<Text style={{ color: '#666', minWidth: 80 }}>{fd.label || fd.key}:</Text>
<Text style={{ color: '#ccc' }}>{previewData[fd.key] || fd.defaultValue || '—'}</Text>
</div>
))}
</div>
</div>
)}
</Card>
</Col>
</Row>
);
}
// ── Main App ────────────────────────────────────────────────────────────
function App() {
const [data, setData] = React.useState({
presets: [],
contentPresets: [],
lrcPresets: [],
lrcDefaults: null,
lrcState: { playing: false },
activePresetId: null,
activeContentPresetId: null,
settings: { autoHideDuration: 0 }
});
const initialTab = (() => {
const hash = (window.location.hash || '').replace('#', '');
return ['live', 'appearance', 'content', 'lrc'].includes(hash) ? hash : 'live';
})();
const [activeTab, setActiveTab] = React.useState(initialTab);
const [loading, setLoading] = React.useState(true);
const changeTab = (key) => {
setActiveTab(key);
try { window.history.replaceState(null, '', '#' + key); } catch (_) {}
};
const fetchData = async () => {
try {
const res = await fetch('/api/presets');
const d = await res.json();
setData({
presets: d.presets || [],
contentPresets: d.contentPresets || [],
lrcPresets: d.lrcPresets || [],
lrcDefaults: d.lrcDefaults || null,
lrcState: d.lrcState || { playing: false },
activePresetId: d.activePresetId || null,
activeContentPresetId: d.activeContentPresetId || null,
settings: d.settings || { autoHideDuration: 0 }
});
} catch(e) {
message.error('无法连接到服务器');
} finally {
setLoading(false);
}
};
React.useEffect(() => {
const loc = window.location;
const proto = loc.protocol === 'https:' ? 'wss:' : 'ws:';
let disposed = false;
let ws = null;
let retryTimer = null;
const connect = () => {
if (disposed) return;
ws = new WebSocket(proto + '//' + loc.host);
ws.onopen = () => {
fetchData();
};
ws.onmessage = (e) => {
try {
const msg = JSON.parse(e.data);
if (msg.type === 'activePreset') {
fetchData();
} else if (msg.type === 'lrcState') {
setData(prev => ({ ...prev, lrcState: msg.state || { playing: false } }));
}
} catch (_) {}
};
ws.onclose = () => {
if (!disposed) retryTimer = setTimeout(connect, 2000);
};
};
fetchData();
connect();
return () => {
disposed = true;
if (retryTimer) clearTimeout(retryTimer);
if (ws) ws.close();
};
}, []);
const tabs = [
{
key: 'live',
label: (
<Space>
<span>激活控制</span>
{data.activeContentPresetId && <Badge dot color="green" />}
</Space>
),
children: (
<LiveControlTab
contentPresets={data.contentPresets}
appearancePresets={data.presets}
activeContentPresetId={data.activeContentPresetId}
activePresetId={data.activePresetId}
autoHideDuration={data.settings.autoHideDuration}
onRefresh={fetchData}
isActive={activeTab === 'live'}
/>
)
},
{
key: 'appearance',
label: '外观预设',
children: (
<AppearancePresetsTab
presets={data.presets}
onRefresh={fetchData}
/>
)
},
{
key: 'content',
label: '内容预设',
children: (
<ContentPresetsTab
contentPresets={data.contentPresets}
appearancePresets={data.presets}
onRefresh={fetchData}
/>
)
},
{
key: 'lrc',
label: (
<Space>
<span>LRC 字幕</span>
{data.lrcState && data.lrcState.playing && <Badge dot color="green" />}
</Space>
),
children: (
<LrcTab
presets={data.lrcPresets}
lrcState={data.lrcState}
lrcDefaults={data.lrcDefaults}
onRefresh={fetchData}
isActive={activeTab === 'lrc'}
/>
)
}
];
return (
<ConfigProvider
theme={{
algorithm: theme.darkAlgorithm,
token: {
colorBgBase: '#0a0c14',
colorBgContainer: 'rgba(255,255,255,0.04)',
borderRadius: 8,
}
}}
>
<Layout style={{ minHeight: '100vh', background: 'transparent' }}>
<Header style={{ background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(12px)', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: '100%' }}>
<div>
<Title level={4} style={{ margin: 0, color: '#fff', display: 'inline' }}>
OBS Lower Thirds Manager
</Title>
<Text style={{ color: '#888', marginLeft: 12, fontSize: 13 }}>管理面板</Text>
</div>
<Space>
<Text style={{ color: '#666', fontSize: 12 }}>
Widget URL: <code style={{ background: 'rgba(255,255,255,0.1)', padding: '2px 6px', borderRadius: 4 }}>
{window.location.origin}/widget.html
</code>
</Text>
<Button size="small" onClick={fetchData}>刷新</Button>
</Space>
</div>
</Header>
<Content style={{ padding: '20px 24px' }}>
{loading ? (
<div style={{ display: 'flex', justifyContent: 'center', paddingTop: 80 }}>
<Spin size="large" />
</div>
) : (
<Tabs
activeKey={activeTab}
onChange={changeTab}
items={tabs}
size="large"
/>
)}
</Content>
</Layout>
</ConfigProvider>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
</script>
</body>
</html>