feat: 外观支持自定义 CSS/JS,并升级发帖工作台与积分存量看板

后台可注入全站 CSS/JS(SSR 生效,CSS 可热换);发帖/编辑改为锁一屏工作室;经济看板增加存量健康度;主题令牌与弹层误关一并收紧。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-18 04:16:32 +08:00
parent fa713bfc3f
commit 5f7193042f
41 changed files with 2297 additions and 873 deletions

View File

@@ -41,6 +41,8 @@ type updateSettingsRequest struct {
AttachmentMaxMB *int `json:"attachment_max_mb"` AttachmentMaxMB *int `json:"attachment_max_mb"`
AttachmentMaxCount *int `json:"attachment_max_count"` AttachmentMaxCount *int `json:"attachment_max_count"`
ImageMaxMB *int `json:"image_max_mb"` ImageMaxMB *int `json:"image_max_mb"`
CustomCSS *string `json:"custom_css"`
CustomJS *string `json:"custom_js"`
TimelineGitImport *string `json:"timeline_git_import"` // 超管专用;不进公开 settings / WS 广播 TimelineGitImport *string `json:"timeline_git_import"` // 超管专用;不进公开 settings / WS 广播
} }
@@ -66,6 +68,8 @@ func settingsPayload(saved service.PublicSiteSettings) gin.H {
"attachment_max_mb": saved.AttachmentMaxMB, "attachment_max_mb": saved.AttachmentMaxMB,
"attachment_max_count": saved.AttachmentMaxCount, "attachment_max_count": saved.AttachmentMaxCount,
"image_max_mb": saved.ImageMaxMB, "image_max_mb": saved.ImageMaxMB,
"custom_css": saved.CustomCSS,
"custom_js": saved.CustomJS,
} }
} }
@@ -76,7 +80,8 @@ func (req *updateSettingsRequest) hasAny() bool {
req.CodeBlockFoldLines != nil || req.UIAnimations != nil || req.AnimCodeFold != nil || req.CodeBlockFoldLines != nil || req.UIAnimations != nil || req.AnimCodeFold != nil ||
req.AnimSmoothScroll != nil || req.AnimChrome != nil || req.PostLinkNewTab != nil || req.AnimSmoothScroll != nil || req.AnimChrome != nil || req.PostLinkNewTab != nil ||
req.AttachmentExtLimit != nil || req.AttachmentExts != nil || req.AttachmentMaxMB != nil || req.AttachmentExtLimit != nil || req.AttachmentExts != nil || req.AttachmentMaxMB != nil ||
req.AttachmentMaxCount != nil || req.ImageMaxMB != nil || req.TimelineGitImport != nil req.AttachmentMaxCount != nil || req.ImageMaxMB != nil || req.CustomCSS != nil ||
req.CustomJS != nil || req.TimelineGitImport != nil
} }
// AdminGetSettings 超管读取站点设置(含 timeline_git_import,不进公开 /api/settings) // AdminGetSettings 超管读取站点设置(含 timeline_git_import,不进公开 /api/settings)
@@ -264,6 +269,26 @@ func (h *Handlers) UpdateSettings(c *gin.Context) {
return return
} }
} }
if req.CustomCSS != nil {
if err := h.Setting.SetCustomCSS(*req.CustomCSS); err != nil {
if errors.Is(err, service.ErrInvalidSiteSetting) {
c.JSON(http.StatusBadRequest, gin.H{"error": "自定义 CSS 过长或含非法闭合标签"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存站点设置失败"})
return
}
}
if req.CustomJS != nil {
if err := h.Setting.SetCustomJS(*req.CustomJS); err != nil {
if errors.Is(err, service.ErrInvalidSiteSetting) {
c.JSON(http.StatusBadRequest, gin.H{"error": "自定义 JS 过长或含非法闭合标签"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存站点设置失败"})
return
}
}
var savedAdapter string var savedAdapter string
if req.TimelineGitImport != nil { if req.TimelineGitImport != nil {

View File

@@ -0,0 +1,19 @@
package service
import "testing"
func TestSanitizeCustomSnippet(t *testing.T) {
got, err := sanitizeCustomSnippet(" body{color:red} ", "</style", MaxCustomCSSRunes)
if err != nil || got != "body{color:red}" {
t.Fatalf("trim got %q err=%v", got, err)
}
if _, err = sanitizeCustomSnippet("a</style>b", "</style", MaxCustomCSSRunes); err == nil {
t.Fatal("css closer should fail")
}
if _, err = sanitizeCustomSnippet("a</SCRIPT>b", "</script", MaxCustomJSRunes); err == nil {
t.Fatal("js closer should fail")
}
if _, err = sanitizeCustomSnippet("ok", "</script", MaxCustomJSRunes); err != nil {
t.Fatalf("valid js: %v", err)
}
}

View File

@@ -49,6 +49,10 @@ const (
SettingKeyAttachmentMaxCount = "attachment_max_count" SettingKeyAttachmentMaxCount = "attachment_max_count"
// SettingKeyImageMaxMB 正文插图上限(MB);缺行=5 // SettingKeyImageMaxMB 正文插图上限(MB);缺行=5
SettingKeyImageMaxMB = "image_max_mb" SettingKeyImageMaxMB = "image_max_mb"
// SettingKeyCustomCSS 全站自定义 CSS(外观页注入,空=无)
SettingKeyCustomCSS = "custom_css"
// SettingKeyCustomJS 全站自定义 JS(外观页注入,空=无)
SettingKeyCustomJS = "custom_js"
) )
const ( const (
@@ -70,6 +74,9 @@ const (
MinAttachmentMaxCount = 1 MinAttachmentMaxCount = 1
MaxAttachmentMaxCount = 20 MaxAttachmentMaxCount = 20
MaxAttachmentExtCount = 80 MaxAttachmentExtCount = 80
MaxCustomCSSRunes = 48000
MaxCustomJSRunes = 48000
) )
// DefaultAttachmentExts 论坛向默认允许扩展名(含安装包/脚本/网页) // DefaultAttachmentExts 论坛向默认允许扩展名(含安装包/脚本/网页)
@@ -115,6 +122,8 @@ type PublicSiteSettings struct {
AttachmentMaxMB int `json:"attachment_max_mb"` AttachmentMaxMB int `json:"attachment_max_mb"`
AttachmentMaxCount int `json:"attachment_max_count"` AttachmentMaxCount int `json:"attachment_max_count"`
ImageMaxMB int `json:"image_max_mb"` ImageMaxMB int `json:"image_max_mb"`
CustomCSS string `json:"custom_css"`
CustomJS string `json:"custom_js"`
} }
// SettingService 站点级键值设置 // SettingService 站点级键值设置
@@ -316,6 +325,18 @@ func (s *SettingService) Public() (PublicSiteSettings, error) {
return out, err return out, err
} }
out.ImageMaxMB = imgMB out.ImageMaxMB = imgMB
css, err := s.CustomCSS()
if err != nil {
return out, err
}
out.CustomCSS = css
js, err := s.CustomJS()
if err != nil {
return out, err
}
out.CustomJS = js
return out, nil return out, nil
} }
@@ -767,3 +788,65 @@ func (s *SettingService) ImageMaxBytes() (int64, error) {
} }
return int64(mb) << 20, nil return int64(mb) << 20, nil
} }
func sanitizeCustomSnippet(s, closer string, maxRunes int) (string, error) {
s = strings.TrimSpace(s)
if strings.ContainsRune(s, 0) {
return "", ErrInvalidSiteSetting
}
if utf8.RuneCountInString(s) > maxRunes {
return "", ErrInvalidSiteSetting
}
if closer != "" && strings.Contains(strings.ToLower(s), closer) {
return "", ErrInvalidSiteSetting
}
return s, nil
}
// CustomCSS 全站自定义 CSS。缺行/空=无。
func (s *SettingService) CustomCSS() (string, error) {
v, found, err := s.getValue(SettingKeyCustomCSS)
if err != nil || !found {
return "", err
}
out, nerr := sanitizeCustomSnippet(v, "</style", MaxCustomCSSRunes)
if nerr != nil {
return "", nil
}
return out, nil
}
func (s *SettingService) SetCustomCSS(css string) error {
normalized, err := sanitizeCustomSnippet(css, "</style", MaxCustomCSSRunes)
if err != nil {
return err
}
if normalized == "" {
return s.deleteKey(SettingKeyCustomCSS)
}
return s.putValue(SettingKeyCustomCSS, normalized)
}
// CustomJS 全站自定义 JS。缺行/空=无。
func (s *SettingService) CustomJS() (string, error) {
v, found, err := s.getValue(SettingKeyCustomJS)
if err != nil || !found {
return "", err
}
out, nerr := sanitizeCustomSnippet(v, "</script", MaxCustomJSRunes)
if nerr != nil {
return "", nil
}
return out, nil
}
func (s *SettingService) SetCustomJS(js string) error {
normalized, err := sanitizeCustomSnippet(js, "</script", MaxCustomJSRunes)
if err != nil {
return err
}
if normalized == "" {
return s.deleteKey(SettingKeyCustomJS)
}
return s.putValue(SettingKeyCustomJS, normalized)
}

View File

@@ -35,7 +35,7 @@ function PageRow({
return ( return (
<Link <Link
href={`/p/${p.slug}`} href={`/p/${p.slug}`}
className="block px-5 sm:px-6 py-4 sm:py-5 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]" className="block px-5 sm:px-6 py-4 sm:py-5 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]"
style={showDivider ? { borderTop: "1px solid var(--line)" } : undefined} style={showDivider ? { borderTop: "1px solid var(--line)" } : undefined}
> >
<div className="flex items-start gap-3 min-w-0"> <div className="flex items-start gap-3 min-w-0">

View File

@@ -12,6 +12,7 @@ import {
RotateCcw, RotateCcw,
Pipette, Pipette,
Sparkles, Sparkles,
FileCode2,
} from "lucide-react"; } from "lucide-react";
import { import {
AdminPageHeader, AdminPageHeader,
@@ -20,7 +21,7 @@ import {
AdminStepper, AdminStepper,
AdminSwitch, AdminSwitch,
} from "@/components/admin"; } from "@/components/admin";
import { apiUpdateSiteSettings, type PublicSettings } from "@/lib/api"; import { apiUpdateSiteSettings, type PublicSettings, type UpdateSiteSettingsBody } from "@/lib/api";
import { toast } from "@/lib/toast"; import { toast } from "@/lib/toast";
import { import {
ACCENT_PRESETS, ACCENT_PRESETS,
@@ -30,14 +31,27 @@ import {
findPreset, findPreset,
normalizeHex, normalizeHex,
} from "@/lib/theme"; } from "@/lib/theme";
import {
MAX_CUSTOM_CSS_CHARS,
MAX_CUSTOM_JS_CHARS,
SAMPLE_CUSTOM_CSS,
SAMPLE_CUSTOM_JS,
applyCustomCSS,
clipCustomSnippet,
} from "@/lib/customCode";
// 后台「外观设置」:主题色、代码块折叠与界面动画。 // 后台「外观设置」:主题色、自定义 CSS/JS、代码块折叠与界面动画。
// 主题色修改时立即对整页实时预览(仅本地),保存后才写库并对所有用户生效。 // 主题色 / 自定义 CSS 修改时立即对整页实时预览(仅本地),保存后才写库并对所有用户生效。
// 自定义 JS 不在编辑时执行,保存后整页加载生效。
export default function AppearanceAdmin({ initial }: { initial: PublicSettings }) { export default function AppearanceAdmin({ initial }: { initial: PublicSettings }) {
const router = useRouter(); const router = useRouter();
const initialAccent = initial.accent || ""; const initialAccent = initial.accent || "";
const [savedHex, setSavedHex] = useState(initialAccent); const [savedHex, setSavedHex] = useState(initialAccent);
const [draft, setDraft] = useState(initialAccent || DEFAULT_ACCENT); const [draft, setDraft] = useState(initialAccent || DEFAULT_ACCENT);
const [savedCustomCSS, setSavedCustomCSS] = useState(initial.custom_css || "");
const [customCSS, setCustomCSS] = useState(initial.custom_css || SAMPLE_CUSTOM_CSS);
const [savedCustomJS, setSavedCustomJS] = useState(initial.custom_js || "");
const [customJS, setCustomJS] = useState(initial.custom_js || SAMPLE_CUSTOM_JS);
const [codeAutoFold, setCodeAutoFold] = useState(initial.code_block_auto_fold !== false); const [codeAutoFold, setCodeAutoFold] = useState(initial.code_block_auto_fold !== false);
const [foldLines, setFoldLines] = useState( const [foldLines, setFoldLines] = useState(
Number.isFinite(initial.code_block_fold_lines) ? initial.code_block_fold_lines : 5 Number.isFinite(initial.code_block_fold_lines) ? initial.code_block_fold_lines : 5
@@ -54,6 +68,8 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const savedRef = useRef(savedHex); const savedRef = useRef(savedHex);
savedRef.current = savedHex; savedRef.current = savedHex;
const savedCSSRef = useRef(savedCustomCSS);
savedCSSRef.current = savedCustomCSS;
const normalized = useMemo(() => normalizeHex(draft), [draft]); const normalized = useMemo(() => normalizeHex(draft), [draft]);
const pair = useMemo( const pair = useMemo(
@@ -62,7 +78,12 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
); );
const preset = useMemo(() => (normalized ? findPreset(normalized) : null), [normalized]); const preset = useMemo(() => (normalized ? findPreset(normalized) : null), [normalized]);
const submitHex = normalized && normalized !== DEFAULT_ACCENT ? normalized : ""; const submitHex = normalized && normalized !== DEFAULT_ACCENT ? normalized : "";
const dirty = (savedHex || DEFAULT_ACCENT) !== (normalized || ""); const accentDirty = (savedHex || DEFAULT_ACCENT) !== (normalized || "");
const cssIsGuide = !savedCustomCSS && customCSS === SAMPLE_CUSTOM_CSS;
const jsIsGuide = !savedCustomJS && customJS === SAMPLE_CUSTOM_JS;
const cssDirty = customCSS !== savedCustomCSS && !cssIsGuide;
const jsDirty = customJS !== savedCustomJS && !jsIsGuide;
const dirty = accentDirty || cssDirty || jsDirty;
const invalid = draft.trim() !== "" && !normalized; const invalid = draft.trim() !== "" && !normalized;
useEffect(() => { useEffect(() => {
@@ -72,19 +93,35 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
}; };
}, [normalized]); }, [normalized]);
useEffect(() => {
applyCustomCSS(customCSS, true);
return () => {
applyCustomCSS(savedCSSRef.current, false);
};
}, [customCSS]);
const handleSave = async () => { const handleSave = async () => {
if (!normalized || saving) return; if (!normalized || saving) return;
const body: UpdateSiteSettingsBody = {};
if (accentDirty) body.accent = submitHex;
if (cssDirty) body.custom_css = customCSS;
if (jsDirty) body.custom_js = customJS;
if (Object.keys(body).length === 0) return;
setSaving(true); setSaving(true);
try { try {
const res = await apiUpdateSiteSettings({ accent: submitHex }); const res = await apiUpdateSiteSettings(body);
const next = (res.accent || "").toLowerCase(); const next = (res.accent || "").toLowerCase();
setSavedHex(next); setSavedHex(next);
setSavedCustomCSS(res.custom_css || "");
setSavedCustomJS(res.custom_js || "");
applyAccentTheme(next || null); applyAccentTheme(next || null);
applyCustomCSS(res.custom_css || "", false);
router.refresh(); router.refresh();
toast(next ? "主题色已保存并对全站生效" : "已恢复默认主题色"); toast(jsDirty ? "外观已保存;自定义 JS 将在整页刷新后执行" : "外观已保存并对全站生效");
} catch (e) { } catch (e) {
toast(e instanceof Error ? e.message : "保存失败", "error"); toast(e instanceof Error ? e.message : "保存失败", "error");
applyAccentTheme(savedRef.current || null); applyAccentTheme(savedRef.current || null);
applyCustomCSS(savedCSSRef.current, false);
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -92,7 +129,10 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
const discard = () => { const discard = () => {
setDraft(savedHex || DEFAULT_ACCENT); setDraft(savedHex || DEFAULT_ACCENT);
setCustomCSS(savedCustomCSS || SAMPLE_CUSTOM_CSS);
setCustomJS(savedCustomJS || SAMPLE_CUSTOM_JS);
applyAccentTheme(savedHex || null); applyAccentTheme(savedHex || null);
applyCustomCSS(savedCustomCSS, true);
}; };
const toggleCodeFold = async () => { const toggleCodeFold = async () => {
@@ -167,7 +207,7 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
<AdminPageHeader <AdminPageHeader
icon={Palette} icon={Palette}
title="外观设置" title="外观设置"
description="配置站点主题色、代码块折叠与界面动画" description="配置站点主题色、自定义 CSS/JS、代码块折叠与界面动画"
/> />
<div className="grid grid-cols-1 xl:grid-cols-3 gap-4 mb-6"> <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 mb-6">
@@ -296,7 +336,10 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
<AdminSection title="实时预览"> <AdminSection title="实时预览">
<div <div
className="rounded-[var(--r-sm)] border p-4 space-y-4" className="rounded-[var(--r-sm)] border p-4 space-y-4"
style={{ borderColor: "var(--line)", background: "var(--bg)" }} style={{
borderColor: "var(--line)",
background: "var(--bg)",
}}
> >
<div className="flex flex-wrap items-center gap-2.5"> <div className="flex flex-wrap items-center gap-2.5">
<button type="button" className="btn btn-primary btn-sm"> <button type="button" className="btn btn-primary btn-sm">
@@ -327,6 +370,7 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
</span> </span>
</div> </div>
<div className="max-w-xs"> <div className="max-w-xs">
<div className="panel p-3">
<div className="j13-bcard" aria-current="page"> <div className="j13-bcard" aria-current="page">
<span <span
className="j13-bcard-ico" className="j13-bcard-ico"
@@ -338,6 +382,7 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
</div> </div>
</div> </div>
</div> </div>
</div>
</AdminSection> </AdminSection>
</div> </div>
@@ -470,6 +515,85 @@ export default function AppearanceAdmin({ initial }: { initial: PublicSettings }
</div> </div>
</div> </div>
<AdminSection
title={
<span className="inline-flex items-center gap-1.5">
<FileCode2 size={15} /> 自定义代码
</span>
}
description="注入全站 HTML。空配置时先显示注释示例(不会自动写入);保存后才对访客生效。勿包含 </style> 或 </script>。"
className="mb-6"
>
<div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
<div>
<div className="flex items-center justify-between gap-2 mb-1">
<label className="field-label !mb-0" htmlFor="custom-css">
自定义 CSS
</label>
{customCSS !== SAMPLE_CUSTOM_CSS && (
<button
type="button"
className="btn btn-line btn-sm !h-7 !px-2.5 !text-[12px]"
onClick={() => setCustomCSS(SAMPLE_CUSTOM_CSS)}
>
填入示例
</button>
)}
</div>
<p className="meta text-[12.5px] mb-2 leading-relaxed">
覆盖令牌或组件类。本页即时预览;去掉注释后的规则才会改变外观。上限{" "}
{MAX_CUSTOM_CSS_CHARS.toLocaleString()} 字。
</p>
<textarea
id="custom-css"
className="j13-compose-field w-full font-mono text-[12.5px] leading-relaxed"
style={{ minHeight: 280 }}
spellCheck={false}
value={customCSS}
onChange={(e) => setCustomCSS(clipCustomSnippet(e.target.value, MAX_CUSTOM_CSS_CHARS))}
aria-label="自定义 CSS"
/>
<p className="meta text-[11.5px] mt-1.5 tabular-nums">
{customCSS.length.toLocaleString()} / {MAX_CUSTOM_CSS_CHARS.toLocaleString()}
{cssIsGuide ? " · 示例未保存" : ""}
</p>
</div>
<div>
<div className="flex items-center justify-between gap-2 mb-1">
<label className="field-label !mb-0" htmlFor="custom-js">
自定义 JS
</label>
{customJS !== SAMPLE_CUSTOM_JS && (
<button
type="button"
className="btn btn-line btn-sm !h-7 !px-2.5 !text-[12px]"
onClick={() => setCustomJS(SAMPLE_CUSTOM_JS)}
>
填入示例
</button>
)}
</div>
<p className="meta text-[12.5px] mb-2 leading-relaxed">
仅站长/超管可写。不在编辑时运行,保存后需整页刷新。上限{" "}
{MAX_CUSTOM_JS_CHARS.toLocaleString()} 字。
</p>
<textarea
id="custom-js"
className="j13-compose-field w-full font-mono text-[12.5px] leading-relaxed"
style={{ minHeight: 280 }}
spellCheck={false}
value={customJS}
onChange={(e) => setCustomJS(clipCustomSnippet(e.target.value, MAX_CUSTOM_JS_CHARS))}
aria-label="自定义 JS"
/>
<p className="meta text-[11.5px] mt-1.5 tabular-nums">
{customJS.length.toLocaleString()} / {MAX_CUSTOM_JS_CHARS.toLocaleString()}
{jsIsGuide ? " · 示例未保存" : ""}
</p>
</div>
</div>
</AdminSection>
<div className="flex items-center justify-between gap-3 sticky bottom-5 panel !p-3.5 pl-5 z-10"> <div className="flex items-center justify-between gap-3 sticky bottom-5 panel !p-3.5 pl-5 z-10">
<p className="text-[12.5px] meta hidden sm:block"> <p className="text-[12.5px] meta hidden sm:block">
{dirty ? "有未保存的改动,整页正处于实时预览状态" : "设置已是保存状态"} {dirty ? "有未保存的改动,整页正处于实时预览状态" : "设置已是保存状态"}

View File

@@ -157,6 +157,174 @@ function todayDelta(items: PointLedgerItem[]) {
return { granted, spent }; return { granted, spent };
} }
type FlowHealth = "low" | "ok" | "hot";
function stockFromStats(stats: EconomyStats) {
let granted = 0;
let spent = 0;
const series = stats.delta_series || [];
const seriesHas = series.some((d) => (Number(d.granted) || 0) > 0 || (Number(d.spent) || 0) > 0);
if (seriesHas) {
for (const d of series) {
granted += Math.max(0, Number(d.granted) || 0);
spent += Math.max(0, Number(d.spent) || 0);
}
} else {
for (const it of stats.recent_ledger || []) {
const n = Number(it.delta) || 0;
if (n > 0) granted += n;
else if (n < 0) spent += -n;
}
}
let frozen = 0;
for (const it of stats.recent_ledger || []) {
if (it.reason === "bounty_escrow" && (Number(it.delta) || 0) < 0) {
frozen += Math.abs(Number(it.delta));
}
}
if ((stats.escrowed_points || 0) > frozen) {
frozen = stats.escrowed_points;
}
const circulating = granted - spent;
const empty = granted <= 0 && spent <= 0 && frozen <= 0;
const rate = granted > 0 ? Math.round((spent / granted) * 100) : 0;
let health: FlowHealth = "ok";
if (rate < 20) health = "low";
else if (rate > 60) health = "hot";
return { granted, spent, circulating, frozen, empty, rate, health };
}
const HEALTH_COPY: Record<FlowHealth, string> = {
low: "积分消耗偏低,可考虑增加积分消耗场景",
ok: "积分经济体健康",
hot: "积分消耗较快,注意通胀",
};
const HEALTH_LABEL: Record<FlowHealth, string> = {
low: "偏低",
ok: "健康",
hot: "偏快",
};
function StockOverviewCard({ stats }: { stats: EconomyStats }) {
const stock = useMemo(() => stockFromStats(stats), [stats]);
const { granted, spent, circulating, frozen, empty, rate, health } = stock;
const tip = HEALTH_COPY[health];
const showFrozen = frozen > 0;
let circBarPct = granted > 0 ? Math.max(0, (circulating / granted) * 100) : 0;
const spentLabelPct = granted > 0 ? Math.min(100, (spent / granted) * 100) : 0;
const circLabelPct = granted > 0 ? Math.max(0, Math.round((Math.max(0, circulating) / granted) * 100)) : 0;
const netSpent = Math.max(0, spent - frozen);
let netSpentPct = granted > 0 ? (netSpent / granted) * 100 : 0;
let frozenPct = granted > 0 && showFrozen ? (frozen / granted) * 100 : 0;
const segSum = circBarPct + netSpentPct + frozenPct;
if (segSum > 100 && segSum > 0) {
const scale = 100 / segSum;
circBarPct *= scale;
netSpentPct *= scale;
frozenPct *= scale;
}
return (
<section className="stock-card">
<div className="flex items-start justify-between gap-3 mb-3">
<div className="min-w-0">
<h3 className="text-[14.5px] font-semibold" style={{ color: "var(--ink)" }}>
积分存量概览
</h3>
<p className="meta text-[11.5px] mt-0.5 leading-relaxed">基于全站累计流水计算</p>
</div>
{!empty ? (
<span
className={`stock-badge is-${health} shrink-0`}
title={tip}
>
流通率 {granted > 0 ? `${rate}%` : "—"} · {HEALTH_LABEL[health]}
</span>
) : null}
</div>
{empty ? (
<div className="stock-card-body items-center justify-center">
<p className="meta text-center">暂无流水,无法计算存量</p>
</div>
) : (
<div className="stock-card-body">
<div>
<p className="text-[13px]" style={{ color: "var(--ink-3)" }}>
流通中积分
</p>
<p
className="tabular-nums text-[32px] font-bold leading-none mt-1"
style={{ color: "var(--stock-circ)", fontVariantNumeric: "tabular-nums" }}
>
{fmt(circulating)}
</p>
</div>
<div>
<div
className="stock-bar"
role="img"
aria-label={`流通中 ${circLabelPct}%,消耗 ${Math.round(spentLabelPct)}%${
showFrozen ? `,托管冻结 ${fmt(frozen)}` : ""
}`}
>
{circBarPct > 0 ? (
<span className="stock-bar-seg is-circ" style={{ width: `${circBarPct}%` }} />
) : null}
{netSpentPct > 0 ? (
<span className="stock-bar-seg is-spent" style={{ width: `${netSpentPct}%` }} />
) : null}
{frozenPct > 0 ? (
<span className="stock-bar-seg is-frozen" style={{ width: `${frozenPct}%` }} />
) : null}
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-1.5 text-[12px] tabular-nums">
<span style={{ color: "var(--stock-circ)" }}>流通中 {circLabelPct}%</span>
<span style={{ color: "var(--ink-3)" }}>消耗 {Math.round(spentLabelPct)}%</span>
{showFrozen ? (
<span style={{ color: "var(--stock-frozen)" }}>托管 {fmt(frozen)}</span>
) : null}
</div>
</div>
<div>
<p className="text-[13px] flex flex-wrap items-center gap-x-4 gap-y-1" style={{ color: "var(--ink-2)" }}>
<span>
累计发放{" "}
<strong className="tabular-nums font-semibold" style={{ color: "var(--ink)" }}>
{fmt(granted)}
</strong>
</span>
<span>
累计消耗{" "}
<strong className="tabular-nums font-semibold" style={{ color: "var(--ink)" }}>
{fmt(spent)}
</strong>
</span>
{showFrozen ? (
<span>
托管冻结{" "}
<strong className="tabular-nums font-semibold" style={{ color: "var(--ink)" }}>
{fmt(frozen)}
</strong>
</span>
) : null}
</p>
{showFrozen ? (
<p className="text-[12px] mt-1.5" style={{ color: "var(--ink-3)" }}>
托管的 {fmt(frozen)} 积分处于冻结态,悬赏采纳或退回后释放
</p>
) : null}
</div>
</div>
)}
</section>
);
}
function LedgerUserLink({ user, compact }: { user: LedgerParty; compact?: boolean }) { function LedgerUserLink({ user, compact }: { user: LedgerParty; compact?: boolean }) {
const name = partyName(user); const name = partyName(user);
return ( return (
@@ -207,7 +375,7 @@ function RecentLedgerRow({ it }: { it: PointLedgerItem }) {
)} )}
{payee ? ( {payee ? (
<span className="hidden md:flex items-center gap-1.5 min-w-0 shrink-0"> <span className="hidden xl:flex items-center gap-1.5 min-w-0 shrink-0">
<ArrowRight size={13} className="shrink-0" style={{ color: "var(--ink-3)" }} aria-hidden /> <ArrowRight size={13} className="shrink-0" style={{ color: "var(--ink-3)" }} aria-hidden />
<LedgerUserLink user={payee} compact /> <LedgerUserLink user={payee} compact />
</span> </span>
@@ -306,7 +474,7 @@ export default function EconomyClient({ stats }: { stats: EconomyStats }) {
/> />
</div> </div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 [&>*]:min-w-0">
<AdminChartCard title="签到趋势" hint="近 14 日每日签到人数"> <AdminChartCard title="签到趋势" hint="近 14 日每日签到人数">
{checkinSeries.length === 0 ? ( {checkinSeries.length === 0 ? (
<p className="meta text-center py-16">暂无签到数据</p> <p className="meta text-center py-16">暂无签到数据</p>
@@ -343,11 +511,12 @@ export default function EconomyClient({ stats }: { stats: EconomyStats }) {
<NamedPieChart data={postsByType} /> <NamedPieChart data={postsByType} />
)} )}
</AdminChartCard> </AdminChartCard>
</div>
<section className="panel overflow-hidden ledger-feed"> <StockOverviewCard stats={stats} />
<section className="panel overflow-hidden flex flex-col max-h-[420px]">
<div <div
className="px-5 py-3 flex items-start justify-between gap-3 flex-wrap" className="px-4 py-3 flex items-start justify-between gap-2 flex-wrap"
style={{ borderBottom: "1px solid var(--line)" }} style={{ borderBottom: "1px solid var(--line)" }}
> >
<p className="font-medium text-[15px] pt-0.5" style={{ color: "var(--ink)" }}> <p className="font-medium text-[15px] pt-0.5" style={{ color: "var(--ink)" }}>
@@ -362,7 +531,7 @@ export default function EconomyClient({ stats }: { stats: EconomyStats }) {
onChange={setFilter} onChange={setFilter}
/> />
</div> </div>
<p className="px-5 py-2 text-[12.5px]" style={{ borderBottom: "1px solid var(--line)", color: "var(--ink-2)" }}> <p className="px-4 py-2 text-[12.5px] shrink-0" style={{ borderBottom: "1px solid var(--line)", color: "var(--ink-2)" }}>
今日 发放{" "} 今日 发放{" "}
<span className="tabular-nums font-semibold" style={{ color: "var(--ledger-in)" }}> <span className="tabular-nums font-semibold" style={{ color: "var(--ledger-in)" }}>
+{fmt(today.granted)} +{fmt(today.granted)}
@@ -373,6 +542,7 @@ export default function EconomyClient({ stats }: { stats: EconomyStats }) {
-{fmt(today.spent)} -{fmt(today.spent)}
</span> </span>
</p> </p>
<div className="flex-1 min-h-0 overflow-y-auto">
{ledger.length === 0 ? ( {ledger.length === 0 ? (
<p className="meta text-center py-10">暂无流水</p> <p className="meta text-center py-10">暂无流水</p>
) : filtered.length === 0 ? ( ) : filtered.length === 0 ? (
@@ -384,7 +554,9 @@ export default function EconomyClient({ stats }: { stats: EconomyStats }) {
))} ))}
</ul> </ul>
)} )}
</div>
</section> </section>
</div>
<p className="meta text-[12.5px] mt-5"> <p className="meta text-[12.5px] mt-5">
用户可在{" "} 用户可在{" "}

View File

@@ -41,7 +41,7 @@ function FeaturedAnnouncement({ a }: { a: Announcement }) {
return ( return (
<Link <Link
href={`/announcement/${a.id}`} href={`/announcement/${a.id}`}
className="block px-5 sm:px-6 pt-5 sm:pt-6 pb-5 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]" className="block px-5 sm:px-6 pt-5 sm:pt-6 pb-5 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]"
> >
<div className="flex items-center gap-2 flex-wrap mb-3"> <div className="flex items-center gap-2 flex-wrap mb-3">
<span <span
@@ -76,7 +76,7 @@ function AnnouncementRow({ a, showDivider }: { a: Announcement; showDivider: boo
return ( return (
<Link <Link
href={`/announcement/${a.id}`} href={`/announcement/${a.id}`}
className="block px-5 sm:px-6 py-4 sm:py-5 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]" className="block px-5 sm:px-6 py-4 sm:py-5 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]"
style={showDivider ? { borderTop: "1px solid var(--line)" } : undefined} style={showDivider ? { borderTop: "1px solid var(--line)" } : undefined}
> >
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">

View File

@@ -419,7 +419,7 @@ export default function ChatShell({
</h1> </h1>
<button <button
onClick={() => setShowCreate(true)} onClick={() => setShowCreate(true)}
className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors" className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--panel-2)] transition-colors"
style={{ color: "var(--accent)" }} style={{ color: "var(--accent)" }}
aria-label="新建群聊" aria-label="新建群聊"
data-tip="新建群聊" data-tip="新建群聊"
@@ -452,7 +452,7 @@ export default function ChatShell({
setQuery(""); setQuery("");
}} }}
aria-label="清除搜索" aria-label="清除搜索"
className="w-5 h-5 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] shrink-0" className="w-5 h-5 flex items-center justify-center rounded-full hover:bg-[var(--panel-2)] shrink-0"
style={{ color: "var(--ink-3)" }} style={{ color: "var(--ink-3)" }}
> >
<X size={12} /> <X size={12} />
@@ -484,7 +484,7 @@ export default function ChatShell({
<button <button
key={u.id} key={u.id}
onClick={() => openDM(u.id)} onClick={() => openDM(u.id)}
className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left hover:bg-[var(--accent-soft)] transition-colors" className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left hover:bg-[var(--panel-2)] transition-colors"
> >
<Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={36} /> <Avatar name={u.nickname || u.username} src={u.avatar || undefined} size={36} />
<div className="min-w-0"> <div className="min-w-0">

View File

@@ -970,7 +970,7 @@ export default function ChatRoomClient({
{embedded && ( {embedded && (
<Link <Link
href="/chat" href="/chat"
className="lg:hidden w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)]" className="lg:hidden w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--panel-2)]"
style={{ color: "var(--ink-2)" }} style={{ color: "var(--ink-2)" }}
aria-label="返回消息列表" aria-label="返回消息列表"
> >
@@ -1017,7 +1017,7 @@ export default function ChatRoomClient({
<button <button
onClick={() => togglePanel("members")} onClick={() => togglePanel("members")}
aria-label="成员列表" aria-label="成员列表"
className="w-9 h-9 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--accent-soft)]" className="w-9 h-9 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--panel-2)]"
style={{ style={{
color: rightPanel === "members" ? "var(--accent)" : "var(--ink-2)", color: rightPanel === "members" ? "var(--accent)" : "var(--ink-2)",
background: rightPanel === "members" ? "var(--accent-soft)" : undefined, background: rightPanel === "members" ? "var(--accent-soft)" : undefined,
@@ -1031,7 +1031,7 @@ export default function ChatRoomClient({
<button <button
onClick={() => togglePanel("invite")} onClick={() => togglePanel("invite")}
aria-label="邀请成员" aria-label="邀请成员"
className="w-9 h-9 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--accent-soft)]" className="w-9 h-9 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--panel-2)]"
style={{ style={{
color: rightPanel === "invite" ? "var(--accent)" : "var(--ink-2)", color: rightPanel === "invite" ? "var(--accent)" : "var(--ink-2)",
background: rightPanel === "invite" ? "var(--accent-soft)" : undefined, background: rightPanel === "invite" ? "var(--accent-soft)" : undefined,
@@ -1045,7 +1045,7 @@ export default function ChatRoomClient({
<button <button
onClick={() => togglePanel("settings")} onClick={() => togglePanel("settings")}
aria-label="群设置" aria-label="群设置"
className="w-9 h-9 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--accent-soft)]" className="w-9 h-9 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--panel-2)]"
style={{ style={{
color: rightPanel === "settings" ? "var(--accent)" : "var(--ink-2)", color: rightPanel === "settings" ? "var(--accent)" : "var(--ink-2)",
background: rightPanel === "settings" ? "var(--accent-soft)" : undefined, background: rightPanel === "settings" ? "var(--accent-soft)" : undefined,
@@ -1351,7 +1351,7 @@ export default function ChatRoomClient({
type="button" type="button"
onClick={() => setReplyTo(null)} onClick={() => setReplyTo(null)}
aria-label="取消回复" aria-label="取消回复"
className="w-6 h-6 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)]" className="w-6 h-6 flex items-center justify-center rounded-full hover:bg-[var(--panel-2)]"
style={{ color: "var(--ink-3)" }} style={{ color: "var(--ink-3)" }}
> >
<X size={13} /> <X size={13} />
@@ -1518,7 +1518,7 @@ export default function ChatRoomClient({
type="button" type="button"
onClick={() => setRightPanel(null)} onClick={() => setRightPanel(null)}
aria-label="关闭面板" aria-label="关闭面板"
className="w-7 h-7 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)]" className="w-7 h-7 flex items-center justify-center rounded-full hover:bg-[var(--panel-2)]"
style={{ color: "var(--ink-3)" }} style={{ color: "var(--ink-3)" }}
> >
<X size={14} /> <X size={14} />

View File

@@ -1,6 +1,13 @@
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "写新帖",
robots: { index: false, follow: false },
};
/** /**
* 发帖路由布局:标记 data-compose-viewport,配合 globals.css * 发帖工作台:标记 data-compose-viewport,锁一屏、隐藏页脚,
* 让舞台占满 main 剩余高度(对齐私信体量,保留页脚)。 * 把剩余高度全部留给编辑画布。
*/ */
export default function ComposeLayout({ export default function ComposeLayout({
children, children,

View File

@@ -2,8 +2,6 @@
import { useEffect, useState, Suspense } from "react"; import { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { ChevronRight } from "lucide-react";
import { apiMe } from "@/lib/api"; import { apiMe } from "@/lib/api";
import PostComposer from "@/components/PostComposer"; import PostComposer from "@/components/PostComposer";
@@ -30,7 +28,7 @@ function ComposeInner() {
if (!ready) { if (!ready) {
return ( return (
<div className="j13-compose-stage px-8 py-16 text-center"> <div className="j13-compose-stage is-studio px-8 py-16 text-center">
<p className="meta">正在准备发帖…</p> <p className="meta">正在准备发帖…</p>
</div> </div>
); );
@@ -42,17 +40,9 @@ function ComposeInner() {
export default function ComposePage() { export default function ComposePage() {
return ( return (
<div className="j13-compose-page"> <div className="j13-compose-page">
<nav className="meta -mt-4 sm:-mt-6 mb-1.5 flex items-center gap-1 text-[12.5px] leading-none shrink-0">
<Link href="/" className="hover:text-[var(--accent)] transition-colors">
首页
</Link>
<ChevronRight size={13} />
<span style={{ color: "var(--ink-2)" }}>发布新帖</span>
</nav>
<Suspense <Suspense
fallback={ fallback={
<div className="j13-compose-stage px-8 py-16 text-center"> <div className="j13-compose-stage is-studio px-8 py-16 text-center">
<p className="meta">正在准备发帖…</p> <p className="meta">正在准备发帖…</p>
</div> </div>
} }

View File

@@ -6,8 +6,8 @@
============================================================ */ ============================================================ */
:root { :root {
/* 浅色(默认)——冷调石墨:底色微蓝灰,面板纯白浮起,层次干净锐利 */ /* 浅色(默认)——中性暖灰底 + 纯白卡片浮起 */
--bg: #f6f7f9; --bg: #f7f7f5;
--panel: #ffffff; --panel: #ffffff;
--panel-2: #f2f4f7; --panel-2: #f2f4f7;
--tint: #eceff3; --tint: #eceff3;
@@ -44,18 +44,34 @@
--ledger-typed-bg: #f3e8ff; --ledger-typed-bg: #f3e8ff;
--ledger-typed-fg: #7e22ce; --ledger-typed-fg: #7e22ce;
/* 工作台语义:导航选中态 / 榜单奖牌色 */ /* 积分存量概览:分段条与健康徽章 */
--nav-active-bg: var(--accent-soft); --stock-circ: #07c05f;
--stock-spent: #d1d5db;
--stock-frozen: #f59e0b;
--stock-frozen-stripe: rgba(255, 255, 255, 0.35);
--stock-badge-ok-bg: #07c05f;
--stock-badge-ok-fg: #ffffff;
--stock-badge-hot-bg: #f59e0b;
--stock-badge-hot-fg: #ffffff;
--stock-badge-low-bg: var(--tint);
--stock-badge-low-fg: var(--ink-3);
/* 工作台语义:选中用描边+文字色指示,底保持面板色,避免品牌色铺底 */
--nav-active-bg: var(--panel);
--nav-active-ink: var(--accent); --nav-active-ink: var(--accent);
--nav-active-line: rgba(59, 91, 219, 0.22); --nav-active-line: rgba(59, 91, 219, 0.38);
--rank-1: #96620f; --rank-1: #96620f;
--rank-2: #5d6676; --rank-2: #5d6676;
--rank-3: #a05a2c; --rank-3: #a05a2c;
--shadow-sm: 0 1px 2px rgba(16, 24, 40, 0.05); --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.05);
--shadow: 0 2px 8px rgba(16, 24, 40, 0.05), 0 10px 28px rgba(16, 24, 40, 0.06); --shadow: 0 2px 8px rgba(16, 24, 40, 0.05), 0 10px 28px rgba(16, 24, 40, 0.06);
--shadow-lg: 0 6px 16px rgba(16, 24, 40, 0.08), 0 20px 48px rgba(16, 24, 40, 0.12); --shadow-lg: 0 6px 16px rgba(16, 24, 40, 0.08), 0 20px 48px rgba(16, 24, 40, 0.12);
/* 页面画布:极淡品牌绿光晕 + SVG 噪点(色值集中于此) */
--bg-halo: rgba(7, 192, 95, 0.04);
--bg-noise-opacity: 0.03;
/* next/font 构建期自托管,变量由 layout.tsx 注入; /* next/font 构建期自托管,变量由 layout.tsx 注入;
本地系统字体仅作网络字体分片就绪前的回退(PingFang/雅黑与 Noto 观感接近) */ 本地系统字体仅作网络字体分片就绪前的回退(PingFang/雅黑与 Noto 观感接近) */
--font-display: var(--font-jakarta), var(--font-noto-sc), -apple-system, --font-display: var(--font-jakarta), var(--font-noto-sc), -apple-system,
@@ -65,7 +81,7 @@
--font-mono: var(--font-jetbrains), var(--font-noto-sc), ui-monospace, --font-mono: var(--font-jetbrains), var(--font-noto-sc), ui-monospace,
"Cascadia Code", Consolas, monospace; "Cascadia Code", Consolas, monospace;
--r: 18px; --r: 12px;
--r-sm: 12px; --r-sm: 12px;
/* 顶栏 68px 条 + 1px 底边;main 桌面 py-9。侧栏 sticky 必须等于 /* 顶栏 68px 条 + 1px 底边;main 桌面 py-9。侧栏 sticky 必须等于
@@ -80,8 +96,8 @@
} }
.dark { .dark {
/* 近黑锌灰:面板逐层浮起,靛蓝提亮为长春花蓝 */ /* 近黑暖灰:面板逐层浮起,靛蓝提亮为长春花蓝 */
--bg: #0f1115; --bg: #101211;
--panel: #181b21; --panel: #181b21;
--panel-2: #20242c; --panel-2: #20242c;
--tint: #282d37; --tint: #282d37;
@@ -117,18 +133,32 @@
--ledger-typed-bg: rgba(126, 34, 206, 0.28); --ledger-typed-bg: rgba(126, 34, 206, 0.28);
--ledger-typed-fg: #e9d5ff; --ledger-typed-fg: #e9d5ff;
/* 工作台语义 */ --stock-circ: #34d399;
--nav-active-bg: rgba(141, 163, 255, 0.14); --stock-spent: #4b5563;
--stock-frozen: #fbbf24;
--stock-frozen-stripe: rgba(0, 0, 0, 0.22);
--stock-badge-ok-bg: #059669;
--stock-badge-ok-fg: #ecfdf5;
--stock-badge-hot-bg: #d97706;
--stock-badge-hot-fg: #fffbeb;
--stock-badge-low-bg: var(--tint);
--stock-badge-low-fg: var(--ink-3);
/* 工作台语义:选中不铺品牌色底 */
--nav-active-bg: var(--panel);
--nav-active-ink: #a9b8ff; --nav-active-ink: #a9b8ff;
--nav-active-line: rgba(141, 163, 255, 0.3); --nav-active-line: rgba(141, 163, 255, 0.38);
--rank-1: #e3bf74; --rank-1: #e3bf74;
--rank-2: #b9c1cd; --rank-2: #b9c1cd;
--rank-3: #e0a06e; --rank-3: #e0a06e;
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3); --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.4);
--shadow: 0 2px 8px rgba(0, 0, 0, 0.28), 0 12px 32px rgba(0, 0, 0, 0.22); --shadow: 0 2px 8px rgba(0, 0, 0, 0.28), 0 12px 32px rgba(0, 0, 0, 0.22);
--shadow-lg: 0 6px 18px rgba(0, 0, 0, 0.35), 0 24px 56px rgba(0, 0, 0, 0.3); --shadow-lg: 0 6px 18px rgba(0, 0, 0, 0.35), 0 24px 56px rgba(0, 0, 0, 0.3);
--bg-halo: rgba(7, 192, 95, 0.03);
--bg-noise-opacity: 0.04;
color-scheme: dark; color-scheme: dark;
} }
@@ -148,19 +178,14 @@ body {
isolation: isolate; /* 让 z-index:-1 的画布层停在内容之下、html 之上 */ isolation: isolate; /* 让 z-index:-1 的画布层停在内容之下、html 之上 */
} }
/* 浏览器最后一层画布:氛围光 + 石墨微粒。 /* 克制画布:fixed 伪元素(不用 background-attachment:fixed,避免移动端掉帧) */
纯 CSS(令牌 + 内联 SVG),不跟位图——跟浅/暗/accent 换肤,无限缩放,无额外请求。 */
body::before { body::before {
content: ""; content: "";
position: fixed; position: fixed;
inset: 0; inset: 0;
z-index: -1; z-index: -1;
pointer-events: none; pointer-events: none;
background-image: background: radial-gradient(ellipse 80% 50% at 50% -20%, var(--bg-halo), transparent 70%);
radial-gradient(ellipse 80% 52% at 12% -18%, color-mix(in srgb, var(--accent) 10%, transparent), transparent 62%),
radial-gradient(ellipse 48% 36% at 100% 0%, color-mix(in srgb, var(--ink) 4%, transparent), transparent 58%),
radial-gradient(ellipse 42% 28% at 78% 100%, color-mix(in srgb, var(--accent) 6%, transparent), transparent 60%),
linear-gradient(180deg, color-mix(in srgb, var(--panel) 40%, transparent) 0%, transparent 32%);
} }
body::after { body::after {
@@ -169,23 +194,11 @@ body::after {
inset: 0; inset: 0;
z-index: -1; z-index: -1;
pointer-events: none; pointer-events: none;
opacity: 0.032; opacity: var(--bg-noise-opacity);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 160 160' width='160' height='160'%3E%3Cfilter id='n' x='0' y='0' width='100%25' height='100%25'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.8' numOctaves='4' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E"); background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 160 160' width='160' height='160'%3E%3Cfilter id='n' x='0' y='0' width='100%25' height='100%25'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.8' numOctaves='4' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-size: 160px 160px; background-size: 160px 160px;
} }
.dark body::before {
background-image:
radial-gradient(ellipse 80% 52% at 12% -18%, color-mix(in srgb, var(--accent) 16%, transparent), transparent 62%),
radial-gradient(ellipse 48% 36% at 100% 0%, color-mix(in srgb, var(--ink) 6%, transparent), transparent 58%),
radial-gradient(ellipse 42% 28% at 78% 100%, color-mix(in srgb, var(--accent) 9%, transparent), transparent 60%),
linear-gradient(180deg, color-mix(in srgb, var(--panel) 22%, transparent) 0%, transparent 36%);
}
.dark body::after {
opacity: 0.05;
}
@media print { @media print {
body::before, body::before,
body::after { body::after {
@@ -399,8 +412,140 @@ body::after {
.j13-compose-typebar { .j13-compose-typebar {
display: flex; display: flex;
flex-wrap: wrap; flex-direction: column;
gap: 8px; gap: 6px;
}
.j13-compose-typeopt {
width: 100%;
display: flex;
align-items: center;
gap: 6px;
padding: 3px 4px 3px 3px;
border-radius: 12px;
border: 1px solid var(--line);
background: var(--panel);
color: var(--ink);
transition: background 0.12s ease, color 0.12s ease, border-color 0.12s ease;
}
.j13-compose-typeopt:hover:not(:has(.j13-compose-typeopt-hit:disabled)) {
border-color: color-mix(in srgb, var(--accent) 35%, var(--line));
}
.j13-compose-typeopt.is-on {
background: var(--accent-soft);
border-color: color-mix(in srgb, var(--accent) 42%, var(--line));
}
.j13-compose-typeopt.is-on.is-warn {
background: color-mix(in srgb, var(--danger-soft) 70%, var(--panel));
border-color: color-mix(in srgb, var(--danger) 36%, var(--line));
}
.j13-compose-typeopt:has(.j13-compose-typeopt-hit:disabled):not(.is-on) {
opacity: 0.45;
}
.j13-compose-typeopt-hit {
flex: 1;
min-width: 0;
display: flex;
align-items: flex-start;
gap: 10px;
padding: 6px 4px 6px 7px;
border: 0;
border-radius: 9px;
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
appearance: none;
}
.j13-compose-typeopt-hit:disabled {
cursor: not-allowed;
}
.j13-compose-typeopt-hit:focus-visible,
.j13-compose-typeopt-setup:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.j13-compose-typeopt-ico {
width: 32px;
height: 32px;
border-radius: 9px;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
background: var(--panel-2);
color: var(--ink-2);
}
.j13-compose-typeopt.is-on .j13-compose-typeopt-ico {
background: var(--accent);
color: var(--accent-on);
}
.j13-compose-typeopt.is-on.is-warn .j13-compose-typeopt-ico {
background: var(--danger);
color: #fff;
}
.j13-compose-typeopt-copy {
min-width: 0;
flex: 1;
padding-top: 1px;
}
.j13-compose-typeopt-label {
display: block;
font-size: 13.5px;
font-weight: 700;
line-height: 1.3;
color: var(--ink);
letter-spacing: -0.01em;
}
.j13-compose-typeopt-hint {
display: block;
margin-top: 2px;
font-size: 12px;
font-weight: 500;
line-height: 1.4;
color: var(--ink-3);
}
.j13-compose-typeopt.is-on .j13-compose-typeopt-hint.is-status {
color: color-mix(in srgb, var(--accent) 58%, var(--ink-2));
font-variant-numeric: tabular-nums;
}
.j13-compose-typeopt-hint.is-warn {
color: var(--danger);
font-weight: 650;
}
.j13-compose-typeopt-setup {
flex-shrink: 0;
height: 26px;
padding: 0 9px;
margin-right: 2px;
border-radius: 999px;
border: 1px solid color-mix(in srgb, var(--accent) 32%, var(--line));
background: color-mix(in srgb, var(--accent-soft) 80%, var(--panel));
color: var(--accent);
font-size: 11.5px;
font-weight: 700;
letter-spacing: 0.02em;
line-height: 1;
white-space: nowrap;
cursor: pointer;
}
.j13-compose-typeopt-setup:hover {
background: var(--accent);
color: var(--accent-on);
border-color: var(--accent);
}
.j13-compose-typeopt-setup.is-warn {
border-color: color-mix(in srgb, var(--danger) 40%, var(--line));
background: color-mix(in srgb, var(--danger-soft) 85%, var(--panel));
color: var(--danger);
}
.j13-compose-typeopt-setup.is-warn:hover {
background: var(--danger);
color: #fff;
border-color: var(--danger);
}
.dark .j13-compose-typeopt.is-on.is-warn .j13-compose-typeopt-ico,
.dark .j13-compose-typeopt-setup.is-warn:hover {
color: #1a0c0b;
} }
.j13-compose-typechip { .j13-compose-typechip {
height: 34px; height: 34px;
@@ -468,9 +613,15 @@ body::after {
width: 6.5rem; width: 6.5rem;
} }
.j13-lottery-prize-table .col-actions { .j13-lottery-prize-table .col-actions {
width: 4.5rem; width: 5.25rem;
text-align: right; text-align: right;
} }
.j13-lottery-prize-table .col-actions > span {
display: inline-flex;
}
.j13-lottery-prize-table .col-actions .btn:disabled {
pointer-events: none;
}
.j13-lottery-prize-table .j13-compose-field { .j13-lottery-prize-table .j13-compose-field {
width: 100%; width: 100%;
padding: 7px 10px; padding: 7px 10px;
@@ -1513,19 +1664,18 @@ body::after {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
height: 2.5rem; min-height: 3.25rem;
min-height: 2.5rem; padding: 8px 10px 8px 8px;
padding: 0 12px;
background: var(--panel); background: var(--panel);
border: 1px solid var(--line); border: 1px solid var(--line);
border-radius: 12px; border-radius: 12px;
color: var(--ink); color: var(--ink);
text-align: left; text-align: left;
transition: border-color 0.15s ease, box-shadow 0.15s ease; transition: background 0.12s ease, border-color 0.12s ease, box-shadow 0.15s ease;
cursor: pointer; cursor: pointer;
} }
.j13-board-trigger:hover:not(:disabled) { .j13-board-trigger:hover:not(:disabled) {
border-color: color-mix(in srgb, var(--line-2) 40%, var(--line)); border-color: color-mix(in srgb, var(--accent) 35%, var(--line));
} }
.j13-board-trigger:focus { outline: none; } .j13-board-trigger:focus { outline: none; }
.j13-board-trigger:focus-visible, .j13-board-trigger:focus-visible,
@@ -1538,17 +1688,62 @@ body::after {
opacity: 0.65; opacity: 0.65;
cursor: not-allowed; cursor: not-allowed;
} }
.j13-board-trigger.is-empty {
border-color: color-mix(in srgb, var(--accent) 48%, var(--line));
background: var(--accent-soft);
}
.j13-board-trigger.is-empty .j13-board-trigger-hint {
color: var(--accent);
font-weight: 650;
}
.j13-board-trigger-copy {
min-width: 0;
flex: 1;
}
.j13-board-trigger-name {
display: block;
font-size: 13.5px;
font-weight: 700;
line-height: 1.3;
letter-spacing: -0.01em;
}
.j13-board-trigger-hint {
display: block;
margin-top: 2px;
font-size: 12px;
font-weight: 500;
line-height: 1.35;
color: var(--ink-3);
}
.j13-board-trigger-ico { .j13-board-trigger-ico {
width: 24px; width: 32px;
height: 24px; height: 32px;
border-radius: 7px; border-radius: 9px;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-size: 11px; font-size: 13px;
font-weight: 800; font-weight: 800;
flex-shrink: 0; flex-shrink: 0;
} }
.j13-board-trigger-ico.is-placeholder {
background: var(--panel-2);
color: var(--ink-3);
}
.j13-board-option .j13-board-trigger-ico {
width: 24px;
height: 24px;
border-radius: 7px;
font-size: 11px;
}
.j13-compose-req {
margin-left: 6px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
color: var(--accent);
vertical-align: 0.05em;
}
.j13-board-menu { .j13-board-menu {
position: absolute; position: absolute;
z-index: 40; z-index: 40;
@@ -1856,36 +2051,6 @@ body::after {
min-height: 0; min-height: 0;
gap: 0; gap: 0;
} }
.j13-md-panes.is-split {
grid-template-columns: 1fr;
}
@media (min-width: 960px) {
.j13-md-panes.is-split {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
.j13-md-panes.is-split .j13-md-write-wrap {
border-right: 1px solid var(--line);
padding-right: 1rem;
margin-right: 0;
}
.j13-md-panes.is-split .j13-md-preview {
padding-left: 1rem;
}
}
/* 窄屏双栏:上下分栏仍同时显示 */
@media (max-width: 959px) {
.j13-md-panes.is-split {
grid-template-rows: minmax(220px, 1fr) minmax(220px, 1fr);
gap: 0;
}
.j13-md-panes.is-split .j13-md-write-wrap {
border-bottom: 1px solid var(--line);
padding-bottom: 0.5rem;
}
.j13-md-panes.is-split .j13-md-preview {
padding-top: 0.35rem;
}
}
.j13-md-panes > [hidden] { .j13-md-panes > [hidden] {
display: none !important; display: none !important;
} }
@@ -2363,14 +2528,23 @@ a.j13-att-cta:hover {
} }
/* 发帖/编辑:占满 main 剩余高度,减少卡片下方空余(保留页脚) */ /* 发帖/编辑工作台:锁一屏、隐藏页脚,高度全部给编辑画布 */
body:has([data-compose-viewport]) {
height: 100dvh;
max-height: 100dvh;
overflow: hidden;
}
body:has([data-compose-viewport]) > footer {
display: none;
}
body:has([data-compose-viewport]) #main { body:has([data-compose-viewport]) #main {
flex: 1 1 0;
min-height: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-height: 0; padding-top: 0.55rem;
/* 略收紧上下边距,把高度留给舞台 */ padding-bottom: 0.55rem;
padding-top: 1.15rem; overflow: hidden;
padding-bottom: 1.15rem;
} }
body:has([data-compose-viewport]) #main > [data-compose-viewport] { body:has([data-compose-viewport]) #main > [data-compose-viewport] {
flex: 1 1 auto; flex: 1 1 auto;
@@ -2379,6 +2553,283 @@ body:has([data-compose-viewport]) #main > [data-compose-viewport] {
min-height: 0; min-height: 0;
} }
/* 发帖工作台:左画布 + 右设置栏(窄屏设置收入抽屉) */
.j13-compose-stage.is-studio {
overflow: hidden;
}
.j13-compose-stage.is-studio:not(:has(.j13-compose-studio)) {
align-items: center;
justify-content: center;
}
.j13-compose-stage.is-studio .j13-compose-toolbar {
position: relative;
top: auto;
z-index: 8;
padding: 0.7rem 1rem 0.7rem 0.85rem;
background: var(--panel);
border-radius: var(--r) var(--r) 0 0;
}
.j13-compose-toolbar-lead {
display: flex;
align-items: center;
gap: 0.65rem;
min-width: 0;
}
.j13-compose-toolbar-copy {
display: flex;
flex-direction: column;
gap: 0.1rem;
min-width: 0;
}
.j13-compose-toolbar-sub {
margin: 0;
font-size: 12px;
line-height: 1.3;
color: var(--ink-3);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.j13-compose-back {
width: 34px;
height: 34px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 10px;
color: var(--ink-2);
background: transparent;
border: 0;
flex-shrink: 0;
transition: background 0.12s ease, color 0.12s ease;
}
.j13-compose-back:hover,
.j13-compose-back:focus-visible {
background: var(--accent-soft);
color: var(--accent);
}
.j13-compose-toolbar-hint {
font-size: 12px;
color: var(--ink-3);
max-width: 14rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.j13-compose-rail-toggle {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.j13-compose-rail-toggle-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.15rem;
height: 1.15rem;
padding: 0 0.3rem;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
color: var(--accent);
background: var(--accent-soft);
}
.j13-compose-draft {
flex-shrink: 0;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.7rem 1.1rem;
font-size: 13px;
color: var(--ink);
background: var(--accent-soft);
border-bottom: 1px solid color-mix(in srgb, var(--accent) 18%, transparent);
}
.j13-compose-banner-error {
flex-shrink: 0;
margin: 0;
border-radius: 0;
border-left: 0;
border-right: 0;
}
.j13-compose-studio {
flex: 1 1 auto;
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr);
position: relative;
}
.j13-compose-studio-canvas {
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
padding: 0.2rem 1.15rem 0.7rem;
overflow: hidden;
}
.j13-compose-title-row {
display: flex;
align-items: flex-end;
gap: 0.75rem;
flex-shrink: 0;
}
.j13-compose-title-count {
font-size: 12px;
color: var(--ink-3);
padding-bottom: 0.8rem;
flex-shrink: 0;
}
.j13-compose-stage.is-studio .j13-compose-canvas,
.j13-compose-stage.is-studio .j13-md-editor {
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
}
.j13-compose-stage.is-studio .j13-md-textarea,
.j13-compose-stage.is-studio .j13-md-preview {
min-height: 0;
}
.j13-compose-rail-backdrop {
display: none;
}
.j13-compose-studio-rail {
min-height: 0;
min-width: 0;
display: flex;
flex-direction: column;
gap: 1.15rem;
padding: 1rem 1.05rem 1.35rem;
overflow-y: auto;
background: color-mix(in srgb, var(--bg) 62%, var(--panel));
border-left: 1px solid var(--line);
}
.j13-compose-rail-head {
display: none;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
margin: -0.15rem 0 0.15rem;
}
.j13-compose-rail-head-title {
margin: 0;
font-size: 15px;
font-weight: 700;
color: var(--ink);
}
.j13-compose-rail-block {
display: flex;
flex-direction: column;
gap: 0.7rem;
flex-shrink: 0;
}
.j13-compose-studio-rail .j13-compose-meta {
flex-direction: column;
gap: 0.85rem;
}
.j13-compose-studio-rail .j13-compose-meta-board,
.j13-compose-studio-rail .j13-compose-meta-tags {
width: 100%;
max-width: none;
flex: none;
}
.j13-compose-studio-rail .j13-compose-typebar {
display: flex;
flex-direction: column;
gap: 6px;
}
.j13-compose-studio-rail .j13-compose-section {
padding: 0;
border: 0;
background: transparent;
border-radius: 0;
}
.j13-compose-studio-rail .j13-compose-drop {
min-height: 5.5rem;
padding: 0.8rem 0.7rem;
}
.j13-compose-studio-rail .j13-compose-drop-lead {
font-size: 13px;
}
.j13-compose-studio-rail .j13-compose-typepanel {
padding: 0.85rem 0.9rem;
}
.j13-compose-typemodal-body {
max-height: min(78vh, 42rem);
overflow-y: auto;
padding-right: 2px;
}
.j13-compose-typemodal-body .j13-compose-typepanel {
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
}
@media (max-width: 1279px) {
.j13-compose-rail-backdrop {
display: block;
position: fixed;
inset: 0;
z-index: 69;
border: 0;
padding: 0;
cursor: pointer;
background: color-mix(in srgb, var(--ink) 28%, transparent);
}
.j13-compose-studio-rail {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: auto;
width: min(100%, 24.5rem);
z-index: 70;
border-left: 1px solid var(--line);
box-shadow: var(--shadow-lg);
transform: translateX(100%);
visibility: hidden;
pointer-events: none;
transition: transform 0.22s ease, visibility 0.22s ease;
}
.j13-compose-studio-rail.is-open {
transform: translateX(0);
visibility: visible;
pointer-events: auto;
}
.j13-compose-rail-head {
display: flex;
}
}
@media (min-width: 1280px) {
.j13-compose-studio {
grid-template-columns: minmax(0, 1fr) minmax(18.5rem, 21.5rem);
}
.j13-compose-studio-canvas {
padding: 0.25rem 1.5rem 0.85rem 1.6rem;
}
.j13-compose-rail-toggle {
display: none;
}
.j13-compose-rail-head {
display: none;
}
.j13-compose-rail-backdrop {
display: none !important;
}
}
@media (max-width: 639px) {
.j13-compose-toolbar-hint {
display: none;
}
.j13-compose-studio-canvas {
padding-left: 0.9rem;
padding-right: 0.9rem;
}
}
/* 聊天页:整页锁在视口内,避免「页面滚动 + 对话区滚动」双滚动条 */ /* 聊天页:整页锁在视口内,避免「页面滚动 + 对话区滚动」双滚动条 */
body:has([data-chat-viewport]) { body:has([data-chat-viewport]) {
height: 100dvh; height: 100dvh;
@@ -2717,6 +3168,15 @@ h1, h2, h3, h4 {
border-radius: 6px; border-radius: 6px;
} }
/* skip-link / 点击主栏空白会聚焦 #main(tabIndex=-1)。
本文件 :focus-visible 未分层,会压过 Tailwind .outline-none,画出整栏主题色描边。 */
#main:focus,
#main:focus-visible,
.admin-canvas:focus,
.admin-canvas:focus-visible {
outline: none;
}
/* 消息侧栏搜索:单层描边,避免外框 + focus-visible 双线 */ /* 消息侧栏搜索:单层描边,避免外框 + focus-visible 双线 */
.j13-chat-search:focus-within { .j13-chat-search:focus-within {
border-color: var(--accent) !important; border-color: var(--accent) !important;
@@ -3135,9 +3595,6 @@ a.j13-mention-token:hover {
color: var(--accent); color: var(--accent);
} }
.ledger-feed {
max-width: 1000px;
}
.ledger-row { .ledger-row {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -3204,6 +3661,71 @@ a.j13-mention-token:hover {
line-height: 1.2; line-height: 1.2;
} }
/* 积分存量概览 */
.stock-card {
display: flex;
flex-direction: column;
min-height: 160px;
padding: 20px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
}
.stock-card-body {
display: flex;
flex-direction: column;
gap: 12px;
}
.stock-badge {
display: inline-flex;
align-items: center;
font-size: 11px;
font-weight: 600;
line-height: 1.3;
padding: 4px 10px;
border-radius: 999px;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.stock-badge.is-low {
background: var(--stock-badge-low-bg);
color: var(--stock-badge-low-fg);
}
.stock-badge.is-ok {
background: var(--stock-badge-ok-bg);
color: var(--stock-badge-ok-fg);
}
.stock-badge.is-hot {
background: var(--stock-badge-hot-bg);
color: var(--stock-badge-hot-fg);
}
.stock-bar {
display: flex;
height: 10px;
border-radius: 8px;
overflow: hidden;
background: var(--tint);
}
.stock-bar-seg {
height: 100%;
min-width: 0;
}
.stock-bar-seg.is-circ {
background: var(--stock-circ);
}
.stock-bar-seg.is-spent {
background: var(--stock-spent);
}
.stock-bar-seg.is-frozen {
background-color: var(--stock-frozen);
background-image: repeating-linear-gradient(
-45deg,
var(--stock-frozen-stripe) 0 3px,
transparent 3px 7px
);
}
.admin-toolbar { .admin-toolbar {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -4303,9 +4825,9 @@ a.j13-mention-token:hover {
background: var(--panel-2); background: var(--panel-2);
} }
.j13-tab[aria-selected="true"] { .j13-tab[aria-selected="true"] {
background: var(--accent-soft); background: var(--nav-active-bg);
border-color: color-mix(in srgb, var(--accent) 38%, var(--line)); border-color: var(--nav-active-line);
color: var(--accent); color: var(--nav-active-ink);
font-weight: 600; font-weight: 600;
} }
.j13-tab:active { .j13-tab:active {
@@ -4341,7 +4863,7 @@ a.j13-mention-token:hover {
} }
.j13-raillink:hover, .j13-raillink:hover,
.j13-raillink:focus-visible { .j13-raillink:focus-visible {
background: var(--accent-soft); background: var(--panel-2);
color: var(--ink); color: var(--ink);
} }
.j13-raillink[aria-current="page"], .j13-raillink[aria-current="page"],
@@ -4367,7 +4889,7 @@ a.j13-mention-token:hover {
transition: border-color 0.16s ease, background 0.16s ease; transition: border-color 0.16s ease, background 0.16s ease;
} }
.j13-bcard:hover { .j13-bcard:hover {
border-color: var(--nav-active-line); border-color: var(--line-2);
background: var(--panel-2); background: var(--panel-2);
} }
.j13-bcard:focus-visible { .j13-bcard:focus-visible {
@@ -4450,8 +4972,8 @@ a.j13-mention-token:hover {
} }
.j13-about-item:hover, .j13-about-item:hover,
.j13-about-item:focus-visible { .j13-about-item:focus-visible {
background: var(--accent-soft); background: var(--panel);
border-color: var(--nav-active-line); border-color: var(--line-2);
} }
.j13-about-ico { .j13-about-ico {
width: 30px; width: 30px;
@@ -4741,9 +5263,9 @@ a.j13-mention-token:hover {
} }
.j13-chip:hover, .j13-chip:hover,
.j13-chip:focus-visible { .j13-chip:focus-visible {
background: var(--accent-soft); background: var(--panel-2);
border-color: color-mix(in srgb, var(--accent) 38%, var(--line)); border-color: var(--line-2);
color: var(--accent); color: var(--ink);
} }
.j13-chip[aria-current="page"], .j13-chip[aria-current="page"],
.j13-chip[aria-current="page"]:hover, .j13-chip[aria-current="page"]:hover,
@@ -4791,7 +5313,7 @@ a.j13-mention-token:hover {
.j13-toc-link:hover, .j13-toc-link:hover,
.j13-toc-link:focus-visible { .j13-toc-link:focus-visible {
color: var(--accent); color: var(--accent);
background: var(--accent-soft); background: var(--panel-2);
} }
.j13-toc-link.is-active, .j13-toc-link.is-active,
.j13-toc-link.is-active:hover, .j13-toc-link.is-active:hover,
@@ -4799,7 +5321,7 @@ a.j13-mention-token:hover {
color: var(--accent); color: var(--accent);
font-weight: 600; font-weight: 600;
border-left-color: var(--accent); border-left-color: var(--accent);
background: var(--accent-soft); background: transparent;
} }
} }

View File

@@ -83,6 +83,8 @@ export default async function RootLayout({
const settings = await getPublicSettingsCached(); const settings = await getPublicSettingsCached();
const accent = settings.accent; const accent = settings.accent;
const accentCSS = accentStyleCSS(accent || ""); const accentCSS = accentStyleCSS(accent || "");
const customCSS = (settings.custom_css || "").trim();
const customJS = (settings.custom_js || "").trim();
const motionCfg = motionConfigFromSettings(settings); const motionCfg = motionConfigFromSettings(settings);
const motionHtmlClass = [ const motionHtmlClass = [
!motionCfg.ui_animations ? "j13-reduce-motion" : "", !motionCfg.ui_animations ? "j13-reduce-motion" : "",
@@ -117,6 +119,13 @@ export default async function RootLayout({
dangerouslySetInnerHTML={{ __html: accentCSS }} dangerouslySetInnerHTML={{ __html: accentCSS }}
/> />
) : null} ) : null}
{customCSS ? (
<style
id="j13-custom-css"
data-custom-css-source="ssr"
dangerouslySetInnerHTML={{ __html: customCSS }}
/>
) : null}
<a href="#main" className="skip-link"> <a href="#main" className="skip-link">
跳到主要内容 跳到主要内容
</a> </a>
@@ -147,9 +156,12 @@ export default async function RootLayout({
<Toaster /> <Toaster />
<TipHost /> <TipHost />
<AccountGuard /> <AccountGuard />
<ThemeSync initialAccent={accent || ""} /> <ThemeSync initialAccent={accent || ""} initialCustomCSS={customCSS} />
<VisitBeacon /> <VisitBeacon />
<RealtimeProvider userId={user ? user.id : null} /> <RealtimeProvider userId={user ? user.id : null} />
{customJS ? (
<script id="j13-custom-js" dangerouslySetInnerHTML={{ __html: customJS }} />
) : null}
</body> </body>
</html> </html>
); );

View File

@@ -103,7 +103,7 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
<button <button
key={n.id} key={n.id}
onClick={() => handleClick(n)} onClick={() => handleClick(n)}
className={`w-full text-left px-4 sm:px-5 py-4 flex items-start gap-3.5 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)] ${ className={`w-full text-left px-4 sm:px-5 py-4 flex items-start gap-3.5 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)] ${
n.is_read ? "" : "bg-[var(--panel-2)]" n.is_read ? "" : "bg-[var(--panel-2)]"
}`} }`}
style={{ style={{

View File

@@ -0,0 +1,22 @@
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "编辑帖子",
robots: { index: false, follow: false },
};
/** 编辑帖与发帖共用工作台视口(锁一屏、隐藏页脚) */
export default function EditPostLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div
data-compose-viewport
className="flex flex-col flex-1 min-h-0 w-full"
>
{children}
</div>
);
}

View File

@@ -1,7 +1,5 @@
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { notFound, redirect } from "next/navigation"; import { notFound, redirect } from "next/navigation";
import Link from "next/link";
import { ChevronRight } from "lucide-react";
import { authCookieHeader } from "@/lib/cookies"; import { authCookieHeader } from "@/lib/cookies";
import { getMeCached } from "@/lib/serverData"; import { getMeCached } from "@/lib/serverData";
import { fetchPostDetail } from "@/lib/api"; import { fetchPostDetail } from "@/lib/api";
@@ -35,25 +33,7 @@ export default async function EditPostPage({ params }: PageProps) {
} }
return ( return (
<div <div className="j13-compose-page w-full">
data-compose-viewport
className="j13-compose-page w-full"
>
<nav className="meta -mt-4 sm:-mt-6 mb-1.5 flex items-center gap-1 flex-wrap text-[12.5px] leading-none shrink-0">
<Link href="/" className="hover:text-[var(--accent)] transition-colors">
首页
</Link>
<ChevronRight size={13} />
<Link
href={`/post/${post.id}`}
className="hover:text-[var(--accent)] transition-colors truncate max-w-[12rem]"
>
帖子详情
</Link>
<ChevronRight size={13} />
<span style={{ color: "var(--ink-2)" }}>编辑</span>
</nav>
<EditPostClient <EditPostClient
postId={post.id} postId={post.id}
initialTitle={post.title} initialTitle={post.title}

View File

@@ -236,7 +236,7 @@ function AuthorPosts({ posts }: { posts: PostListItem[] }) {
<Link <Link
href={`/post/${p.id}`} href={`/post/${p.id}`}
data-tip={p.title} data-tip={p.title}
className="block rounded-[10px] px-2 py-2 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]" className="block rounded-[10px] px-2 py-2 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]"
> >
<span <span
className="block text-[13px] leading-snug line-clamp-2" className="block text-[13px] leading-snug line-clamp-2"

View File

@@ -91,13 +91,14 @@ export default function BoardPicker({
} }
}; };
const empty = !loading && !selected;
const label = loading const label = loading
? "加载板块…" ? "加载板块…"
: selected : selected
? selected.name ? selected.name
: boards.length === 0 : boards.length === 0
? "暂无可用板块" ? "暂无可用板块"
: "选择板块"; : "请选择板块";
const colorIdx = selected const colorIdx = selected
? boardColorIndex(selected, selectedIdx) ? boardColorIndex(selected, selectedIdx)
@@ -108,19 +109,28 @@ export default function BoardPicker({
<button <button
id={id} id={id}
type="button" type="button"
className="j13-board-trigger" className={`j13-board-trigger${empty ? " is-empty" : ""}`}
disabled={disabled || loading || boards.length === 0} disabled={disabled || loading || boards.length === 0}
aria-haspopup="listbox" aria-haspopup="listbox"
aria-expanded={open} aria-expanded={open}
aria-controls={listId} aria-controls={listId}
aria-invalid={empty || undefined}
onClick={() => setOpen((v) => !v)} onClick={() => setOpen((v) => !v)}
onKeyDown={onTriggerKeyDown} onKeyDown={onTriggerKeyDown}
> >
<span className={`j13-board-trigger-ico av-${colorIdx}`} aria-hidden> <span
className={`j13-board-trigger-ico${selected ? ` av-${colorIdx}` : " is-placeholder"}`}
aria-hidden
>
{(selected?.name || "板").slice(0, 1)} {(selected?.name || "板").slice(0, 1)}
</span> </span>
<span className="flex-1 min-w-0 truncate font-semibold text-[14px]"> <span className="j13-board-trigger-copy">
{label} <span className="j13-board-trigger-name">{label}</span>
{empty ? (
<span className="j13-board-trigger-hint">发布前必须选择</span>
) : loading ? (
<span className="j13-board-trigger-hint">正在加载</span>
) : null}
</span> </span>
<ChevronDown <ChevronDown
size={16} size={16}

View File

@@ -101,11 +101,7 @@ export default function ComposeAttachments({
const accept = buildAcceptAttr(limits.exts, limits.extLimit); const accept = buildAcceptAttr(limits.exts, limits.extLimit);
const hintLine = limits.extLimit const hintLine = limits.extLimit
? `单文件 ≤${limits.maxMB}MB,最多 ${limits.maxCount} 个;允许 ${ ? `单文件 ≤${limits.maxMB}MB,最多 ${limits.maxCount} 个`
limits.exts.length > 8
? limits.exts.slice(0, 8).map((e) => `.${e}`).join(" ") + "…"
: limits.exts.map((e) => `.${e}`).join(" ") || "(列表为空)"
}`
: `未限制类型,单文件 ≤${limits.maxMB}MB,最多 ${limits.maxCount} 个`; : `未限制类型,单文件 ≤${limits.maxMB}MB,最多 ${limits.maxCount} 个`;
/** 仅加入待传列表,不立刻上传 */ /** 仅加入待传列表,不立刻上传 */

View File

@@ -3,7 +3,7 @@
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
/** /**
* 站点风格确认框:基于 Modal,仅取消/关闭可关,避免点遮罩误关。 * 站点风格确认框:基于 Modal。点遮罩不关(需明确取消/关闭);ESC / 取消 / 关闭可关。
* danger 主按钮使用 btn-danger,其余用 btn-primary。 * danger 主按钮使用 btn-danger,其余用 btn-primary。
*/ */
export default function ConfirmDialog({ export default function ConfirmDialog({

View File

@@ -199,7 +199,7 @@ export default function Header({
className="sticky top-0 z-50 border-b" className="sticky top-0 z-50 border-b"
style={{ style={{
borderColor: "var(--line)", borderColor: "var(--line)",
background: "color-mix(in srgb, var(--bg) 82%, transparent)", background: "color-mix(in srgb, var(--panel) 86%, transparent)",
backdropFilter: "blur(14px)", backdropFilter: "blur(14px)",
WebkitBackdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
}} }}
@@ -426,7 +426,7 @@ function NavPill({
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-[15px] font-semibold transition-colors" className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-[15px] font-semibold transition-colors"
style={ style={
active active
? { background: "var(--accent-soft)", color: "var(--accent)" } ? { background: "transparent", color: "var(--accent)" }
: { color: "var(--ink)" } : { color: "var(--ink)" }
} }
> >
@@ -451,7 +451,7 @@ function MobileLink({
className="px-3 py-3 rounded-2xl text-[16px] font-semibold transition-colors" className="px-3 py-3 rounded-2xl text-[16px] font-semibold transition-colors"
style={{ style={{
color: active ? "var(--accent)" : "var(--ink)", color: active ? "var(--accent)" : "var(--ink)",
background: active ? "var(--accent-soft)" : "transparent", background: "transparent",
}} }}
> >
{children} {children}
@@ -484,7 +484,7 @@ function UserMenu({ user, onLogout }: { user: User; onLogout: () => void }) {
}, [open]); }, [open]);
const itemCls = const itemCls =
"w-full flex items-center gap-2.5 px-4 py-2.5 text-[13.5px] transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]"; "w-full flex items-center gap-2.5 px-4 py-2.5 text-[13.5px] transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]";
return ( return (
<div className="relative hidden lg:block" ref={menuRef}> <div className="relative hidden lg:block" ref={menuRef}>

View File

@@ -28,7 +28,6 @@ import {
Pencil, Pencil,
Maximize2, Maximize2,
Minimize2, Minimize2,
Columns2,
Lock, Lock,
ChevronDown, ChevronDown,
Upload, Upload,
@@ -61,7 +60,7 @@ type MarkdownEditorProps = {
allowReplyHide?: boolean; allowReplyHide?: boolean;
}; };
type EditorMode = "split" | "write" | "preview"; type EditorMode = "write" | "preview";
type WrapOpts = { type WrapOpts = {
before: string; before: string;
@@ -126,7 +125,7 @@ export default function MarkdownEditor({
const taRef = useRef<HTMLTextAreaElement>(null); const taRef = useRef<HTMLTextAreaElement>(null);
const fileRef = useRef<HTMLInputElement>(null); const fileRef = useRef<HTMLInputElement>(null);
const toolbarRef = useRef<HTMLDivElement>(null); const toolbarRef = useRef<HTMLDivElement>(null);
const [mode, setMode] = useState<EditorMode>("split"); const [mode, setMode] = useState<EditorMode>("write");
const deferredValue = useDeferredValue(value); const deferredValue = useDeferredValue(value);
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [fullscreen, setFullscreen] = useState(false); const [fullscreen, setFullscreen] = useState(false);
@@ -940,15 +939,6 @@ export default function MarkdownEditor({
> >
<Pencil size={12} /> 编写 <Pencil size={12} /> 编写
</button> </button>
<button
type="button"
role="tab"
aria-selected={mode === "split"}
className={mode === "split" ? "is-on" : ""}
onClick={() => setMode("split")}
>
<Columns2 size={12} /> 双栏
</button>
<button <button
type="button" type="button"
role="tab" role="tab"

View File

@@ -42,7 +42,7 @@ export default function MobilePostBar({
<button <button
type="button" type="button"
onClick={scrollToComments} onClick={scrollToComments}
className="w-11 h-11 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]" className="w-11 h-11 flex items-center justify-center rounded-full transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]"
style={{ color: "var(--ink-2)" }} style={{ color: "var(--ink-2)" }}
aria-label="跳到评论框" aria-label="跳到评论框"
> >

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { useEffect, type ReactNode } from "react"; import { useEffect, useRef, type PointerEvent, type ReactNode } from "react";
import { X } from "lucide-react"; import { X } from "lucide-react";
export type ModalProps = { export type ModalProps = {
@@ -16,7 +16,11 @@ export type ModalProps = {
maxWidthClass?: string; maxWidthClass?: string;
/** 面板额外 class(如 max-h / flex) */ /** 面板额外 class(如 max-h / flex) */
panelClassName?: string; panelClassName?: string;
/** 点遮罩关闭;表单/确认默认 false 防误关 */ /**
* 点遮罩关闭。按下与抬起都必须落在遮罩上才会关:
* 框内拖选后在遮罩松手、或在遮罩按下后拖进弹层松手,都不会关。
* 确认/扣费等仍建议关此开关。
*/
dismissOnOverlay?: boolean; dismissOnOverlay?: boolean;
/** busy 时禁用关闭与 ESC */ /** busy 时禁用关闭与 ESC */
busy?: boolean; busy?: boolean;
@@ -28,7 +32,7 @@ export type ModalProps = {
/** 自定义标题区(如带图标);提供时覆盖默认 title 行,仍渲染关闭钮除非 hideClose */ /** 自定义标题区(如带图标);提供时覆盖默认 title 行,仍渲染关闭钮除非 hideClose */
header?: ReactNode; header?: ReactNode;
hideClose?: boolean; hideClose?: boolean;
/** 是否响应 ESC;封禁告知等不可关场景设 false */ /** 是否响应 ESC;默认 true(按键非误触)。仅封禁告知等必须点确认的场景设 false */
closeOnEscape?: boolean; closeOnEscape?: boolean;
/** 内容区额外 class */ /** 内容区额外 class */
bodyClassName?: string; bodyClassName?: string;
@@ -36,7 +40,8 @@ export type ModalProps = {
/** /**
* 全站弹层壳:统一遮罩、面板、标题关闭钮与 ESC。 * 全站弹层壳:统一遮罩、面板、标题关闭钮与 ESC。
* 主 CTA 请用 btn-primary;危险操作用 btn-danger;取消用 btn-line。 * 默认:点遮罩不关;开启 dismissOnOverlay 时须按下+抬起都在遮罩上。
* ESC / 关闭钮 / 页脚按钮可关。主 CTA 用 btn-primary,危险操作用 btn-danger。
*/ */
export default function Modal({ export default function Modal({
open, open,
@@ -57,6 +62,12 @@ export default function Modal({
closeOnEscape = true, closeOnEscape = true,
bodyClassName = "", bodyClassName = "",
}: ModalProps) { }: ModalProps) {
const overlayPressedRef = useRef(false);
useEffect(() => {
overlayPressedRef.current = false;
}, [open]);
useEffect(() => { useEffect(() => {
if (!open || !closeOnEscape) return; if (!open || !closeOnEscape) return;
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
@@ -71,13 +82,33 @@ export default function Modal({
const label = const label =
ariaLabel || (typeof title === "string" ? title : undefined); ariaLabel || (typeof title === "string" ? title : undefined);
const onOverlayPointerDown = (e: PointerEvent<HTMLDivElement>) => {
overlayPressedRef.current =
e.button === 0 && e.target === e.currentTarget;
};
const onOverlayPointerUp = (e: PointerEvent<HTMLDivElement>) => {
const pressedOnOverlay = overlayPressedRef.current;
overlayPressedRef.current = false;
if (!dismissOnOverlay || busy) return;
if (e.button !== 0) return;
// 用 pointerup 的真实落点,不用 click:mousedown 在遮罩、mouseup 在面板时
// click 会合成到共同祖先(遮罩)上,造成拖进弹层仍关闭。
if (!pressedOnOverlay || e.target !== e.currentTarget) return;
onClose();
};
const onOverlayPointerCancel = () => {
overlayPressedRef.current = false;
};
return ( return (
<div <div
className={`fixed inset-0 ${zIndexClass} flex items-center justify-center p-4`} className={`fixed inset-0 ${zIndexClass} flex items-center justify-center p-4`}
style={{ background: "rgba(0,0,0,0.55)" }} style={{ background: "rgba(0,0,0,0.55)" }}
onClick={() => { onPointerDown={onOverlayPointerDown}
if (dismissOnOverlay && !busy) onClose(); onPointerUp={onOverlayPointerUp}
}} onPointerCancel={onOverlayPointerCancel}
role={role} role={role}
aria-modal="true" aria-modal="true"
aria-label={label} aria-label={label}
@@ -136,7 +167,7 @@ function CloseButton({
onClick={onClick} onClick={onClick}
disabled={disabled} disabled={disabled}
aria-label="关闭" aria-label="关闭"
className="w-7 h-7 shrink-0 flex items-center justify-center rounded-full hover:bg-[var(--accent-soft)] transition-colors disabled:opacity-50" className="w-7 h-7 shrink-0 flex items-center justify-center rounded-full hover:bg-[var(--panel-2)] transition-colors disabled:opacity-50"
style={{ color: "var(--ink-3)" }} style={{ color: "var(--ink-3)" }}
> >
<X size={15} /> <X size={15} />

View File

@@ -223,7 +223,7 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
<button <button
key={n.id} key={n.id}
onClick={() => handleClickNotification(n)} onClick={() => handleClickNotification(n)}
className={`w-full text-left px-4 py-3.5 flex items-start gap-3 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)] ${ className={`w-full text-left px-4 py-3.5 flex items-start gap-3 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)] ${
n.is_read ? "" : "bg-[var(--panel-2)]" n.is_read ? "" : "bg-[var(--panel-2)]"
}`} }`}
style={{ style={{

View File

@@ -44,7 +44,7 @@ export default function PinnedPosts({
<Link <Link
key={p.id} key={p.id}
href={`/post/${p.id}`} href={`/post/${p.id}`}
className="group relative flex items-center gap-3 sm:gap-3.5 px-4 sm:px-5 py-3.5 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)] j13-fade-up" className="group relative flex items-center gap-3 sm:gap-3.5 px-4 sm:px-5 py-3.5 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)] j13-fade-up"
style={{ style={{
...(i > 0 ? { borderTop: "1px solid var(--line)" } : {}), ...(i > 0 ? { borderTop: "1px solid var(--line)" } : {}),
animationDelay: `${i * 35}ms`, animationDelay: `${i * 35}ms`,

View File

@@ -137,7 +137,7 @@ export default function PostActions({
if (!canManage) return null; if (!canManage) return null;
const itemCls = const itemCls =
"w-full flex items-center gap-2.5 px-4 py-2.5 text-[13px] transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]"; "w-full flex items-center gap-2.5 px-4 py-2.5 text-[13px] transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]";
return ( return (
<div className="relative" ref={menuRef}> <div className="relative" ref={menuRef}>

View File

@@ -3,7 +3,7 @@
import { useState, useEffect, useRef, useCallback } from "react"; import { useState, useEffect, useRef, useCallback } from "react";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { X } from "lucide-react"; import { ArrowLeft, CircleHelp, Coins, Gift, ListChecks, MessagesSquare, SlidersHorizontal, X, type LucideIcon } from "lucide-react";
import { import {
apiCreatePost, apiCreatePost,
apiUpdatePost, apiUpdatePost,
@@ -25,19 +25,29 @@ import {
import { toast } from "@/lib/toast"; import { toast } from "@/lib/toast";
import MarkdownEditor from "@/components/MarkdownEditor"; import MarkdownEditor from "@/components/MarkdownEditor";
import BoardPicker, { BoardBadge } from "@/components/BoardPicker"; import BoardPicker, { BoardBadge } from "@/components/BoardPicker";
import ComposeAttachments, { import ComposeAttachments from "@/components/ComposeAttachments";
ComposeAttachAction,
} from "@/components/ComposeAttachments";
import DeadlinePicker, { import DeadlinePicker, {
type DeadlineMode, type DeadlineMode,
defaultCustomLocal, defaultCustomLocal,
localInputToRFC3339, localInputToRFC3339,
formatLocalPreview,
} from "@/components/DeadlinePicker"; } from "@/components/DeadlinePicker";
import Modal from "@/components/Modal";
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime"; import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
const TITLE_MAX = 256; const TITLE_MAX = 256;
const DRAFT_KEY = "j13-compose-draft"; const DRAFT_KEY = "j13-compose-draft";
const DRAFT_DEBOUNCE_MS = 600; const DRAFT_DEBOUNCE_MS = 600;
/** 与 globals.css 工作台分栏断点一致 */
const RAIL_MQ = "(max-width: 1279px)";
const TYPE_ICON: Record<PostTypeValue, LucideIcon> = {
discussion: MessagesSquare,
question: CircleHelp,
poll: ListChecks,
bounty: Coins,
lottery: Gift,
};
type ComposeDraft = { type ComposeDraft = {
title: string; title: string;
@@ -273,13 +283,39 @@ export default function PostComposer(props: PostComposerProps) {
const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null); const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const skipDraftSave = useRef(true); const skipDraftSave = useRef(true);
const formRef = useRef<HTMLFormElement>(null); const formRef = useRef<HTMLFormElement>(null);
const titleRef = useRef<HTMLInputElement>(null);
const attachSectionRef = useRef<HTMLElement | null>(null); const attachSectionRef = useRef<HTMLElement | null>(null);
const actionsErrorRef = useRef<HTMLDivElement>(null); const actionsErrorRef = useRef<HTMLDivElement>(null);
const bountyFieldRef = useRef<HTMLDivElement>(null); const bountyFieldRef = useRef<HTMLDivElement>(null);
const pendingErrorFocus = useRef<"actions" | "bounty" | "attachments" | null>(null); const pendingErrorFocus = useRef<"actions" | "bounty" | "attachments" | null>(null);
const [railOpen, setRailOpen] = useState(false);
const [typeModalOpen, setTypeModalOpen] = useState(false);
const [isNarrow, setIsNarrow] = useState(false);
const preferredBoardId = isCreate ? props.initialBoardId || 0 : 0; const preferredBoardId = isCreate ? props.initialBoardId || 0 : 0;
useEffect(() => {
const mq = window.matchMedia(RAIL_MQ);
const sync = () => setIsNarrow(mq.matches);
sync();
mq.addEventListener("change", sync);
return () => mq.removeEventListener("change", sync);
}, []);
useEffect(() => {
if (!railOpen) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setRailOpen(false);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [railOpen]);
useEffect(() => {
if (!isCreate) return;
titleRef.current?.focus();
}, [isCreate]);
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
apiGetSettings() apiGetSettings()
@@ -335,9 +371,11 @@ export default function PostComposer(props: PostComposerProps) {
const hit = preferred && list.some((b) => b.id === preferred); const hit = preferred && list.some((b) => b.id === preferred);
if (hit) { if (hit) {
setBoardId(preferred); setBoardId(preferred);
} else if (list.length > 0) { } else if (list.length === 1) {
setBoardId(list[0].id);
} else {
setBoardId((cur) => setBoardId((cur) =>
cur && list.some((b) => b.id === cur) ? cur : list[0].id cur && list.some((b) => b.id === cur) ? cur : 0
); );
} }
const draft = readDraft(); const draft = readDraft();
@@ -507,6 +545,8 @@ export default function PostComposer(props: PostComposerProps) {
}; };
const scrollToAttachments = () => { const scrollToAttachments = () => {
if (isNarrow) setRailOpen(true);
window.setTimeout(() => {
const el = const el =
attachSectionRef.current || attachSectionRef.current ||
document.getElementById("j13-compose-attachments"); document.getElementById("j13-compose-attachments");
@@ -515,9 +555,12 @@ export default function PostComposer(props: PostComposerProps) {
const drop = el?.querySelector(".j13-compose-drop") as HTMLElement | null; const drop = el?.querySelector(".j13-compose-drop") as HTMLElement | null;
drop?.focus(); drop?.focus();
}, 320); }, 320);
}, isNarrow ? 80 : 0);
}; };
const scrollToPendingUpload = () => { const scrollToPendingUpload = () => {
if (isNarrow) setRailOpen(true);
window.setTimeout(() => {
const el = const el =
attachSectionRef.current || attachSectionRef.current ||
document.getElementById("j13-compose-attachments"); document.getElementById("j13-compose-attachments");
@@ -528,6 +571,7 @@ export default function PostComposer(props: PostComposerProps) {
) as HTMLButtonElement | null; ) as HTMLButtonElement | null;
btn?.focus(); btn?.focus();
}, 320); }, 320);
}, isNarrow ? 80 : 0);
}; };
const bountyShort = const bountyShort =
@@ -567,12 +611,15 @@ export default function PostComposer(props: PostComposerProps) {
scrollToPendingUpload(); scrollToPendingUpload();
return; return;
} }
if (focus === "bounty") setTypeModalOpen(true);
window.setTimeout(() => {
const el = const el =
focus === "bounty" && bountyFieldRef.current focus === "bounty" && bountyFieldRef.current
? bountyFieldRef.current ? bountyFieldRef.current
: actionsErrorRef.current; : actionsErrorRef.current;
el?.scrollIntoView({ behavior: "smooth", block: "nearest" }); el?.scrollIntoView({ behavior: "smooth", block: "nearest" });
}, [error]); }, focus === "bounty" ? 80 : 0);
}, [error, isNarrow]);
// 待传清零后收起「尚未上传」提示(已上传或已移除) // 待传清零后收起「尚未上传」提示(已上传或已移除)
useEffect(() => { useEffect(() => {
@@ -582,6 +629,7 @@ export default function PostComposer(props: PostComposerProps) {
const handleSubmit = async (e?: React.FormEvent) => { const handleSubmit = async (e?: React.FormEvent) => {
e?.preventDefault(); e?.preventDefault();
if (loading || fileBusy) return;
if (pendingFileCount > 0) { if (pendingFileCount > 0) {
reportSubmitError( reportSubmitError(
`还有 ${pendingFileCount} 个附件尚未上传,请先上传或移除`, `还有 ${pendingFileCount} 个附件尚未上传,请先上传或移除`,
@@ -596,16 +644,19 @@ export default function PostComposer(props: PostComposerProps) {
) { ) {
const iso = localInputToRFC3339(customEndsLocal); const iso = localInputToRFC3339(customEndsLocal);
if (!iso) { if (!iso) {
setTypeModalOpen(true);
reportSubmitError("请选择有效的截止时间"); reportSubmitError("请选择有效的截止时间");
return; return;
} }
const t = Date.parse(iso); const t = Date.parse(iso);
if (!Number.isFinite(t) || t < Date.now() + 60 * 60 * 1000) { if (!Number.isFinite(t) || t < Date.now() + 60 * 60 * 1000) {
setTypeModalOpen(true);
reportSubmitError("截止时间至少晚于当前 1 小时"); reportSubmitError("截止时间至少晚于当前 1 小时");
return; return;
} }
} }
if (postType === "lottery" && !lotteryPrizesReady) { if (postType === "lottery" && !lotteryPrizesReady) {
setTypeModalOpen(true);
reportSubmitError("请填写奖品名称与数量后再发布"); reportSubmitError("请填写奖品名称与数量后再发布");
return; return;
} }
@@ -614,16 +665,41 @@ export default function PostComposer(props: PostComposerProps) {
postType === "bounty" && postType === "bounty" &&
(typeof bountyPoints !== "number" || bountyPoints < 1) (typeof bountyPoints !== "number" || bountyPoints < 1)
) { ) {
setTypeModalOpen(true);
reportSubmitError("请填写悬赏积分后再发布", "bounty"); reportSubmitError("请填写悬赏积分后再发布", "bounty");
return; return;
} }
if (bountyShort) { if (bountyShort) {
setTypeModalOpen(true);
reportSubmitError( reportSubmitError(
`积分不足(余额 ${pointsBalance},需要 ${bountyPoints})`, `积分不足(余额 ${pointsBalance},需要 ${bountyPoints})`,
"bounty" "bounty"
); );
return; return;
} }
if (!title.trim()) {
reportSubmitError("请填写标题");
titleRef.current?.focus();
return;
}
if (!content.trim()) {
reportSubmitError("请填写正文");
document.getElementById("compose-content")?.focus();
return;
}
if (isCreate && (!boardsReady || boardId <= 0)) {
if (isNarrow) setRailOpen(true);
reportSubmitError("请选择板块");
return;
}
if (
postType === "poll" &&
pollOptions.map((o) => o.trim()).filter(Boolean).length < 2
) {
setTypeModalOpen(true);
reportSubmitError("请至少填写 2 个投票选项");
return;
}
if (!canSubmit) return; if (!canSubmit) return;
setLoading(true); setLoading(true);
setError(""); setError("");
@@ -683,176 +759,174 @@ export default function PostComposer(props: PostComposerProps) {
? isCreate ? isCreate
? "发布中…" ? "发布中…"
: "保存中…" : "保存中…"
: fileBusy
? "上传中…"
: isCreate : isCreate
? "发布" ? "发布"
: "保存"; : "保存";
const cancelControl = isCreate ? ( const selectedBoardName = isCreate
<Link href={cancelHref} className="btn btn-line btn-sm"> ? boards.find((b) => b.id === boardId)?.name
取消 : props.boardName;
</Link> const typeLabel = POST_TYPES.find((t) => t.value === postType)?.label || "讨论";
) : ( const blockReason = loading
<button ? ""
type="button" : fileBusy
onClick={() => router.push(cancelHref)} ? "附件上传中"
className="btn btn-line btn-sm" : !title.trim()
? "请填写标题"
: !content.trim()
? "请填写正文"
: isCreate && (!boardsReady || boardId <= 0)
? "请选择板块"
: postType === "poll" &&
pollOptions.map((o) => o.trim()).filter(Boolean).length < 2
? "请至少填写 2 个投票选项"
: postType === "bounty" &&
(typeof bountyPoints !== "number" || bountyPoints < 1)
? "请填写悬赏积分"
: bountyShort
? "积分不足"
: postType === "lottery" && !lotteryPrizesReady
? "请填写奖品名称与数量"
: "";
const railHidden = isNarrow && !railOpen;
const typeSetupKind =
postType === "poll" || postType === "bounty" || postType === "lottery";
const pollFilled = pollOptions.map((o) => o.trim()).filter(Boolean).length;
const typeSetupReady =
postType === "poll"
? pollFilled >= 2
: postType === "bounty"
? typeof bountyPoints === "number" && bountyPoints > 0 && !bountyShort
: postType === "lottery"
? lotteryPrizesReady
: true;
const deadlineSummary = (() => {
if (!isCreate || !typeSetupKind) return "";
if (deadlineMode === "custom") {
const preview = formatLocalPreview(customEndsLocal);
return preview ? `截止 ${preview}` : "未选截止时间";
}
const days =
postType === "poll"
? pollExpireDays
: postType === "bounty"
? bountyExpireDays
: lotteryExpireDays;
return postType === "lottery" ? `${days} 天后开奖` : `${days} 天后结束`;
})();
const typeSummary = (() => {
if (postType === "poll") {
const bits = [
pollFilled >= 2 ? `${pollFilled} 个选项` : "还差选项",
pollMulti ? "多选" : "单选",
pollAnonymous ? "匿名" : "实名",
];
if (deadlineSummary) bits.push(deadlineSummary);
return bits.join(" · ");
}
if (postType === "bounty") {
const bits = [
typeof bountyPoints === "number"
? `托管 ${bountyPoints.toLocaleString("zh-CN")} 积分`
: "未填积分",
];
if (bountyShort) bits.push("余额不足");
if (deadlineSummary) bits.push(deadlineSummary);
return bits.join(" · ");
}
if (postType === "lottery") {
const bits = [
lotteryPrizesReady
? `${lotteryPrizes.length} 种奖品 · ${lotterySlotTotal} 名额`
: "奖品未填完",
];
if (deadlineSummary) bits.push(deadlineSummary);
return bits.join(" · ");
}
return "";
})();
const typeChipStatus = (() => {
if (postType === "poll") {
if (pollFilled < 2) return { text: "待设选项", warn: true };
const bits = [`${pollFilled} 选项`];
if (pollMulti) bits.push("多选");
if (isCreate) {
bits.push(
deadlineMode === "custom" ? "自选截止" : `${pollExpireDays} 天`
);
}
return { text: bits.join(" · "), warn: false };
}
if (postType === "bounty") {
if (bountyShort) return { text: "余额不足", warn: true };
if (typeof bountyPoints !== "number") return { text: "待填积分", warn: true };
const bits = [`${bountyPoints.toLocaleString("zh-CN")} 积分`];
if (isCreate) {
bits.push(
deadlineMode === "custom" ? "自选截止" : `${bountyExpireDays} 天`
);
}
return { text: bits.join(" · "), warn: false };
}
if (postType === "lottery") {
if (!lotteryPrizesReady) return { text: "待填奖品", warn: true };
const bits = [`${lotteryPrizes.length} 奖 · ${lotterySlotTotal} 名额`];
if (isCreate) {
bits.push(
deadlineMode === "custom" ? "自选截止" : `${lotteryExpireDays} 天`
);
}
return { text: bits.join(" · "), warn: false };
}
return null;
})();
const closeTypeModal = useCallback(() => setTypeModalOpen(false), []);
const completeTypeModal = () => {
if (postType === "poll" && pollFilled < 2) {
toast("请至少填写 2 个投票选项", "error");
return;
}
if (
postType === "bounty" &&
isCreate &&
(typeof bountyPoints !== "number" || bountyPoints < 1)
) {
toast("请填写悬赏积分", "error");
return;
}
if (postType === "bounty" && bountyShort) {
toast(`积分不足(余额 ${pointsBalance},需要 ${bountyPoints})`, "error");
return;
}
if (postType === "lottery" && !lotteryPrizesReady) {
toast("请填写每一行的奖品名称与数量", "error");
return;
}
setTypeModalOpen(false);
};
const onPickType = (value: PostTypeValue) => {
setPostType(value);
if (value !== "poll" && value !== "bounty" && value !== "lottery") {
setTypeModalOpen(false);
}
};
const cancelControl = (
<Link
href={cancelHref}
className="j13-compose-back"
aria-label="返回"
data-tip="返回"
> >
取消 <ArrowLeft size={18} strokeWidth={2.2} />
</button> </Link>
); );
return ( const typeSettingsForm = (
<form ref={formRef} onSubmit={handleSubmit} className="j13-compose-stage"> <>
<header className="j13-compose-toolbar"> {postType === "poll" && (
<h1 className="j13-compose-toolbar-title"> <div className="j13-compose-typepanel space-y-3">
{isCreate ? "写新帖" : "编辑帖子"}
</h1>
<div className="j13-compose-toolbar-actions">
{cancelControl}
<button
type="submit"
disabled={!canSubmit}
className="btn btn-primary btn-sm min-w-[4.5rem]"
>
{submitLabel}
</button>
</div>
</header>
<div className="j13-compose-body">
{draftBanner && (
<div
className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 rounded-[12px] text-[13px] shrink-0"
style={{
background: "var(--accent-soft)",
color: "var(--ink)",
border:
"1px solid color-mix(in srgb, var(--accent) 18%, transparent)",
}}
>
<span>
检测到未发布的本地草稿
{draftBanner.updatedAt
? `(${new Date(draftBanner.updatedAt).toLocaleString("zh-CN")})`
: ""}
</span>
<span className="flex gap-2">
<button type="button" className="btn btn-primary btn-sm" onClick={restoreDraft}>
恢复
</button>
<button type="button" className="btn btn-line btn-sm" onClick={discardDraft}>
丢弃
</button>
</span>
</div>
)}
{/* 基本信息:类型 / 板块 / 标签 / 可见性 */}
<section className="j13-compose-section" aria-label="基本信息">
<h2 className="j13-compose-section-title">基本信息</h2>
{/* 帖子类型 */}
<div className="shrink-0">
<div className="field-label mb-2">帖子类型</div>
<div className="j13-compose-typebar" role="radiogroup" aria-label="帖子类型">
{POST_TYPES.map((t) => (
<button
key={t.value}
type="button"
role="radio"
aria-checked={postType === t.value}
className={`j13-compose-typechip${postType === t.value ? " is-on" : ""}`}
disabled={loading || (!isCreate && t.value !== postType)}
data-tip={!isCreate && t.value !== postType ? "编辑时不可更改类型" : t.hint}
onClick={() => setPostType(t.value)}
>
{t.label}
</button>
))}
</div>
</div>
{/* 元信息:板块 + 标签(标签 flex 占满) + 可见性 */}
<div className="j13-compose-meta shrink-0">
<div className="j13-compose-meta-board">
<label className="field-label" htmlFor="compose-board">
板块
</label>
{isCreate ? (
<BoardPicker
id="compose-board"
boards={boards}
value={boardId}
onChange={setBoardId}
disabled={loading}
loading={!boardsReady}
/>
) : (
<BoardBadge
name={props.boardName || "未知板块"}
colorIndex={props.boardColorIndex ?? 0}
/>
)}
</div>
<div className="j13-compose-meta-tags">
<label className="field-label" htmlFor="compose-tag-input">
标签
<span className="font-normal" style={{ color: "var(--ink-3)" }}>
{" "}
· 可选,最多 12 个
</span>
</label>
<div
className="j13-tag-field"
onClick={() => document.getElementById("compose-tag-input")?.focus()}
>
{tagList.map((t) => (
<span key={t} className="chip inline-flex items-center gap-1 !py-0.5">
# {t}
<button
type="button"
data-tip={`移除 ${t}`}
aria-label={`移除标签 ${t}`}
className="opacity-60 hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
removeTag(t);
}}
>
<X size={12} />
</button>
</span>
))}
<input
id="compose-tag-input"
value={tagInput}
disabled={loading || tagList.length >= 12}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === "," || e.key === ",") {
e.preventDefault();
commitTagInput();
} else if (e.key === "Backspace" && !tagInput && tagList.length > 0) {
removeTag(tagList[tagList.length - 1]);
}
}}
onBlur={commitTagInput}
placeholder={tagList.length === 0 ? "输入后回车添加" : ""}
className="j13-tag-field-input flex-1 min-w-[8rem] self-stretch h-8 text-[13px]"
style={{ color: "var(--ink)" }}
/>
</div>
</div>
</div>
</section>
{/* 类型扩展(投票 / 悬赏 / 抽奖) */}
{(postType === "poll" || postType === "bounty" || postType === "lottery") && (
<section className="j13-compose-section" aria-label="类型设置">
<h2 className="j13-compose-section-title">类型设置</h2>
{postType === "poll" && (
<div className="j13-compose-typepanel shrink-0 space-y-3">
<p className="font-semibold text-[14px]" style={{ color: "var(--ink)" }}> <p className="font-semibold text-[14px]" style={{ color: "var(--ink)" }}>
投票选项 投票选项
</p> </p>
@@ -932,7 +1006,7 @@ export default function PostComposer(props: PostComposerProps) {
</div> </div>
)} )}
{postType === "bounty" && ( {postType === "bounty" && (
<div className="j13-compose-typepanel shrink-0 space-y-3"> <div className="j13-compose-typepanel space-y-3">
<p className="font-semibold text-[14px]" style={{ color: "var(--ink)" }}> <p className="font-semibold text-[14px]" style={{ color: "var(--ink)" }}>
悬赏积分 悬赏积分
</p> </p>
@@ -1052,7 +1126,7 @@ export default function PostComposer(props: PostComposerProps) {
</div> </div>
)} )}
{postType === "lottery" && ( {postType === "lottery" && (
<div className="j13-compose-typepanel shrink-0 space-y-3"> <div className="j13-compose-typepanel space-y-3">
<p className="font-semibold text-[14px]" style={{ color: "var(--ink)" }}> <p className="font-semibold text-[14px]" style={{ color: "var(--ink)" }}>
抽奖设置 抽奖设置
</p> </p>
@@ -1132,20 +1206,30 @@ export default function PostComposer(props: PostComposerProps) {
</td> </td>
{canEditLotteryPrizes && ( {canEditLotteryPrizes && (
<td className="col-actions"> <td className="col-actions">
{lotteryPrizes.length > 1 ? ( <span
data-tip={
lotteryPrizes.length <= 1 ? "至少保留一项" : "删除此奖品"
}
>
<button <button
type="button" type="button"
className="btn btn-line btn-sm" className="btn btn-line btn-sm"
disabled={loading} disabled={loading || lotteryPrizes.length <= 1}
onClick={() => aria-label={
setLotteryPrizes((prev) => prev.filter((_, i) => i !== idx)) lotteryPrizes.length <= 1
? "删除(至少保留一项)"
: `删除奖品 ${idx + 1}`
} }
onClick={() => {
if (lotteryPrizes.length <= 1) return;
setLotteryPrizes((prev) =>
prev.filter((_, i) => i !== idx)
);
}}
> >
删除 删除
</button> </button>
) : ( </span>
<span className="meta text-[12px]">—</span>
)}
</td> </td>
)} )}
</tr> </tr>
@@ -1192,22 +1276,236 @@ export default function PostComposer(props: PostComposerProps) {
)} )}
</div> </div>
)} )}
</section> </>
)} );
{/* 标题与正文 */} const railInner = (
<section className="j13-compose-section j13-compose-section-writing" aria-label="标题与正文"> <>
<div className="flex items-center justify-between gap-3"> <section className="j13-compose-rail-block" aria-label="板块">
<h2 className="j13-compose-section-title !mb-0">标题与正文</h2> <label className="j13-compose-section-title" htmlFor="compose-board">
<span className="meta text-[12px] tabular-nums"> 板块
{title.length}/{TITLE_MAX} {isCreate ? <span className="j13-compose-req">必选</span> : null}
</label>
{isCreate ? (
<BoardPicker
id="compose-board"
boards={boards}
value={boardId}
onChange={setBoardId}
disabled={loading}
loading={!boardsReady}
/>
) : (
<BoardBadge
name={props.boardName || "未知板块"}
colorIndex={props.boardColorIndex ?? 0}
/>
)}
</section>
<section className="j13-compose-rail-block" aria-label="基本信息">
<h2 className="j13-compose-section-title">帖子类型</h2>
<div className="j13-compose-typebar" role="radiogroup" aria-label="帖子类型">
{POST_TYPES.map((t) => {
const Icon = TYPE_ICON[t.value];
const isOn = postType === t.value;
const locked = loading || (!isCreate && t.value !== postType);
const status = isOn ? typeChipStatus : null;
const needsSetup =
t.value === "poll" || t.value === "bounty" || t.value === "lottery";
return (
<div
key={t.value}
className={`j13-compose-typeopt${isOn ? " is-on" : ""}${
status?.warn ? " is-warn" : ""
}`}
>
<button
type="button"
role="radio"
aria-checked={isOn}
className="j13-compose-typeopt-hit"
disabled={locked}
data-tip={
!isCreate && t.value !== postType ? "编辑时不可更改类型" : undefined
}
onClick={() => onPickType(t.value)}
>
<span className="j13-compose-typeopt-ico" aria-hidden>
<Icon size={16} strokeWidth={2.2} />
</span>
<span className="j13-compose-typeopt-copy">
<span className="j13-compose-typeopt-label">{t.label}</span>
<span
className={`j13-compose-typeopt-hint${
status ? (status.warn ? " is-warn" : " is-status") : ""
}`}
>
{status ? status.text : t.hint}
</span>
</span>
</button>
{isOn && needsSetup ? (
<button
type="button"
className={`j13-compose-typeopt-setup${status?.warn ? " is-warn" : ""}`}
onClick={() => setTypeModalOpen(true)}
>
{status?.warn ? "去设置" : "设置"}
</button>
) : null}
</div>
);
})}
</div>
</section>
<section className="j13-compose-rail-block" aria-label="标签">
<label className="field-label" htmlFor="compose-tag-input">
标签
<span className="font-normal" style={{ color: "var(--ink-3)" }}>
{" "}
· 可选,最多 12 个
</span>
</label>
<div
className="j13-tag-field"
onClick={() => document.getElementById("compose-tag-input")?.focus()}
>
{tagList.map((t) => (
<span key={t} className="chip inline-flex items-center gap-1 !py-0.5">
# {t}
<button
type="button"
data-tip={`移除 ${t}`}
aria-label={`移除标签 ${t}`}
className="opacity-60 hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
removeTag(t);
}}
>
<X size={12} />
</button>
</span>
))}
<input
id="compose-tag-input"
value={tagInput}
disabled={loading || tagList.length >= 12}
onChange={(e) => setTagInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === "," || e.key === ",") {
e.preventDefault();
commitTagInput();
} else if (e.key === "Backspace" && !tagInput && tagList.length > 0) {
removeTag(tagList[tagList.length - 1]);
}
}}
onBlur={commitTagInput}
placeholder={tagList.length === 0 ? "输入后回车添加" : ""}
className="j13-tag-field-input flex-1 min-w-[8rem] self-stretch h-8 text-[13px]"
style={{ color: "var(--ink)" }}
/>
</div>
</section>
<ComposeAttachments
attachments={attachments}
onChange={setAttachments}
limits={attachLimits}
disabled={loading}
onBusyChange={setFileBusy}
onPendingChange={setPendingFileCount}
sectionRef={attachSectionRef}
/>
</>
);
return (
<form ref={formRef} onSubmit={handleSubmit} className="j13-compose-stage is-studio">
<header className="j13-compose-toolbar">
<div className="j13-compose-toolbar-lead">
{cancelControl}
<div className="j13-compose-toolbar-copy min-w-0">
<h1 className="j13-compose-toolbar-title">
{isCreate ? "写新帖" : "编辑帖子"}
</h1>
<p className="j13-compose-toolbar-sub">
{selectedBoardName || (isCreate && !boardsReady ? "加载板块…" : "选择板块")}
{" · "}
{typeLabel}
</p>
</div>
</div>
<div className="j13-compose-toolbar-actions">
{blockReason ? (
<span className="j13-compose-toolbar-hint">{blockReason}</span>
) : (
<span className="j13-compose-toolbar-hint">
{isCreate ? "Ctrl/⌘+Enter 发布" : "Ctrl/⌘+Enter 保存"}
</span>
)}
<button
type="button"
className="btn btn-line btn-sm j13-compose-rail-toggle"
onClick={() => setRailOpen(true)}
aria-expanded={railOpen}
aria-controls="j13-compose-rail"
>
<SlidersHorizontal size={14} />
发布设置
{attachments.length > 0 ? (
<span className="j13-compose-rail-toggle-count">{attachments.length}</span>
) : null}
</button>
<button
type="submit"
disabled={!canSubmit}
className="btn btn-primary btn-sm min-w-[4.75rem]"
>
{submitLabel}
</button>
</div>
</header>
{draftBanner && (
<div className="j13-compose-draft" role="status">
<span>
检测到未发布的本地草稿
{draftBanner.updatedAt
? `(${new Date(draftBanner.updatedAt).toLocaleString("zh-CN")})`
: ""}
</span>
<span className="flex gap-2 shrink-0">
<button type="button" className="btn btn-primary btn-sm" onClick={restoreDraft}>
恢复
</button>
<button type="button" className="btn btn-line btn-sm" onClick={discardDraft}>
丢弃
</button>
</span> </span>
</div> </div>
<div className="shrink-0"> )}
{error ? (
<div
ref={actionsErrorRef}
className="alert-error j13-compose-banner-error"
role="alert"
>
{error}
</div>
) : null}
<div className="j13-compose-studio">
<div className="j13-compose-studio-canvas">
<div className="j13-compose-title-row">
<label className="sr-only" htmlFor="compose-title"> <label className="sr-only" htmlFor="compose-title">
标题 标题
</label> </label>
<input <input
ref={titleRef}
id="compose-title" id="compose-title"
type="text" type="text"
value={title} value={title}
@@ -1218,6 +1516,9 @@ export default function PostComposer(props: PostComposerProps) {
className="j13-compose-title" className="j13-compose-title"
disabled={loading} disabled={loading}
/> />
<span className="j13-compose-title-count tabular-nums">
{title.length}/{TITLE_MAX}
</span>
</div> </div>
<div className="j13-compose-canvas"> <div className="j13-compose-canvas">
<label className="sr-only" htmlFor="compose-content"> <label className="sr-only" htmlFor="compose-content">
@@ -1232,78 +1533,83 @@ export default function PostComposer(props: PostComposerProps) {
rows={18} rows={18}
imageMaxMB={attachLimits.imageMaxMB} imageMaxMB={attachLimits.imageMaxMB}
placeholder={ placeholder={
"从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分/密码可见)。支持粘贴与拖拽上传图片;默认双栏实时预览。" "从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分/密码可见)。支持粘贴与拖拽上传图片;右上角可切换预览。"
} }
onSubmitShortcut={() => { onSubmitShortcut={() => {
if (canSubmit) void handleSubmit(); void handleSubmit();
}} }}
/> />
</div> </div>
</section>
<ComposeAttachments
attachments={attachments}
onChange={setAttachments}
limits={attachLimits}
disabled={loading}
onBusyChange={setFileBusy}
onPendingChange={setPendingFileCount}
sectionRef={attachSectionRef}
/>
</div> </div>
<div className="j13-compose-actions"> {railOpen ? (
{error ? (
<div
ref={actionsErrorRef}
className="alert-error j13-compose-actions-error"
role="alert"
>
{error}
</div>
) : (
<p className="meta text-[12.5px] max-w-md">
{isCreate
? "普通用户发帖需审核 · Ctrl/⌘+Enter 快捷发布"
: "保存后立即生效 · 类型不可更改"}
</p>
)}
<div className="j13-compose-actions-end">
<ComposeAttachAction
count={attachments.length}
max={attachLimits.maxCount}
onClick={scrollToAttachments}
/>
{isCreate ? (
<Link href={cancelHref} className="btn btn-line !py-3">
取消
</Link>
) : (
<button <button
type="button" type="button"
onClick={() => router.push(cancelHref)} className="j13-compose-rail-backdrop"
className="btn btn-line !py-3" aria-label="关闭发布设置"
onClick={() => setRailOpen(false)}
/>
) : null}
<aside
id="j13-compose-rail"
className={`j13-compose-studio-rail${railOpen ? " is-open" : ""}`}
aria-label="发布设置"
aria-hidden={railHidden}
inert={railHidden}
> >
取消 <div className="j13-compose-rail-head">
</button> <h2 className="j13-compose-rail-head-title">发布设置</h2>
)}
<button <button
type="submit" type="button"
disabled={!canSubmit} className="j13-compose-back"
className="btn btn-primary min-w-[8.5rem] !px-7 !py-3 !text-[15px]" aria-label="关闭发布设置"
onClick={() => setRailOpen(false)}
> >
{loading <X size={18} />
? isCreate
? "发布中…"
: "保存中…"
: fileBusy
? "上传中…"
: isCreate
? "发布帖子"
: "保存修改"}
</button> </button>
</div> </div>
{railInner}
</aside>
</div> </div>
<Modal
open={typeModalOpen && typeSetupKind}
title={`${typeLabel}设置`}
description={POST_TYPES.find((t) => t.value === postType)?.hint}
onClose={closeTypeModal}
dismissOnOverlay
maxWidthClass={postType === "lottery" ? "max-w-2xl" : "max-w-xl"}
panelClassName="p-5 sm:p-6"
bodyClassName="j13-compose-typemodal-body"
footer={
<>
<span
className="meta text-[12.5px] mr-auto"
style={typeSetupReady ? undefined : { color: "var(--danger)", fontWeight: 600 }}
>
{typeSummary}
</span>
<button type="button" className="btn btn-line btn-sm" onClick={closeTypeModal}>
稍后
</button>
<button type="button" className="btn btn-primary btn-sm" onClick={completeTypeModal}>
完成
</button>
</>
}
>
<div
onKeyDown={(e) => {
if (e.key === "Enter" && (e.target as HTMLElement).tagName === "INPUT") {
e.preventDefault();
}
}}
>
{typeSettingsForm}
</div>
</Modal>
</form> </form>
); );
} }

View File

@@ -45,7 +45,7 @@ export default async function PostRow({
return ( return (
<div <div
className={`group relative flex items-center px-4 sm:px-5 border-t cursor-pointer transition-colors hover:bg-[var(--accent-soft)] focus-within:bg-[var(--accent-soft)] j13-fade-up ${ className={`group relative flex items-center px-4 sm:px-5 border-t cursor-pointer transition-colors hover:bg-[var(--panel-2)] focus-within:bg-[var(--panel-2)] j13-fade-up ${
compact ? "gap-2.5 sm:gap-3" : "gap-3.5 sm:gap-4" compact ? "gap-2.5 sm:gap-3" : "gap-3.5 sm:gap-4"
}`} }`}
style={{ style={{

View File

@@ -17,6 +17,11 @@ function pathIsChat(pathname: string | null) {
return pathname === "/chat" || pathname.startsWith("/chat/"); return pathname === "/chat" || pathname.startsWith("/chat/");
} }
function pathIsComposeStudio(pathname: string | null) {
if (!pathname) return false;
return pathname === "/compose" || /^\/post\/[^/]+\/edit\/?$/.test(pathname);
}
/** 帖子详情(非 edit)移动端有底栏,回顶需抬高 */ /** 帖子详情(非 edit)移动端有底栏,回顶需抬高 */
function pathIsPostDetail(pathname: string | null) { function pathIsPostDetail(pathname: string | null) {
if (!pathname) return false; if (!pathname) return false;
@@ -75,8 +80,8 @@ export default function SiteChrome({
return <>{children}</>; return <>{children}</>;
} }
// 聊天页锁视口、主滚动在对话区,窗口回顶无意义 // 聊天 / 发帖工作台锁视口,窗口回顶无意义
const showBackToTop = !pathIsChat(pathname); const showBackToTop = !pathIsChat(pathname) && !pathIsComposeStudio(pathname);
return ( return (
<> <>

View File

@@ -130,7 +130,7 @@ export default function StaffUserMenu({
}; };
const itemCls = const itemCls =
"w-full flex items-center gap-2.5 px-4 py-2.5 text-[13px] transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]"; "w-full flex items-center gap-2.5 px-4 py-2.5 text-[13px] transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]";
return ( return (
<div className="relative" ref={menuRef}> <div className="relative" ref={menuRef}>

View File

@@ -4,39 +4,52 @@ import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { apiGetSettings } from "@/lib/api"; import { apiGetSettings } from "@/lib/api";
import { applyAccentTheme } from "@/lib/theme"; import { applyAccentTheme } from "@/lib/theme";
import { applyCustomCSS } from "@/lib/customCode";
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime"; import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
import { import {
VISIBLE_RECONCILE_GAP_MS, VISIBLE_RECONCILE_GAP_MS,
onDocumentVisible, onDocumentVisible,
} from "@/lib/visibilityReconcile"; } from "@/lib/visibilityReconcile";
// 站点主题色同步器: // 站点外观同步器:
// 主题色由管理员在后台修改后,其他用户已打开的标签页不会因软导航重新执行根布局 // 主题色 / 自定义 CSS 由管理员在后台修改后,其他用户已打开的标签页不会因软导航重新执行根布局
// SSR,本组件通过 WS 推送 + 标签页重新可见时探测公开设置,发现变化即热替换 // SSR,本组件通过 WS 推送 + 标签页重新可见时探测公开设置,发现变化即热替换。
// accent CSS 变量(复用 lib/theme 的运行时 style 节点),无需 F5 即可换肤。 // 自定义 JS 只在整页加载时执行,不在此热替换(避免重复绑定)。
// 焦点/可见性事件可能短时间连续触发,限制实际请求间隔
const MIN_FETCH_GAP_MS = VISIBLE_RECONCILE_GAP_MS; const MIN_FETCH_GAP_MS = VISIBLE_RECONCILE_GAP_MS;
export default function ThemeSync({ initialAccent }: { initialAccent: string }) { export default function ThemeSync({
initialAccent,
initialCustomCSS,
}: {
initialAccent: string;
initialCustomCSS: string;
}) {
const pathname = usePathname(); const pathname = usePathname();
// 当前已应用的已保存色(空串=内置默认);与 SSR 注入的 style 节点保持一致
const currentRef = useRef((initialAccent || "").trim().toLowerCase()); const currentRef = useRef((initialAccent || "").trim().toLowerCase());
const cssRef = useRef((initialCustomCSS || "").trim());
const lastFetchAtRef = useRef(0); const lastFetchAtRef = useRef(0);
const inFlightRef = useRef(false); const inFlightRef = useRef(false);
useEffect(() => { useEffect(() => {
// 外观设置页存在"未保存的本地实时预览",该页面内暂停同步, // 外观设置页存在未保存的本地实时预览,暂停同步避免覆盖草稿
// 避免 HTTP 校准覆盖管理员正在预览的颜色;离开页面后 effect 重跑立即对齐
if (pathname?.startsWith("/admin/appearance")) return; if (pathname?.startsWith("/admin/appearance")) return;
let cancelled = false; let cancelled = false;
const apply = (next: string) => { const applyAccent = (next: string) => {
if (cancelled || next === currentRef.current) return; if (cancelled || next === currentRef.current) return;
currentRef.current = next; currentRef.current = next;
applyAccentTheme(next || null); applyAccentTheme(next || null);
}; };
const applyCSS = (next: string) => {
if (cancelled) return;
const text = (next || "").trim();
if (text === cssRef.current) return;
cssRef.current = text;
applyCustomCSS(text);
};
const sync = async () => { const sync = async () => {
if (inFlightRef.current) return; if (inFlightRef.current) return;
const now = Date.now(); const now = Date.now();
@@ -44,25 +57,24 @@ export default function ThemeSync({ initialAccent }: { initialAccent: string })
lastFetchAtRef.current = now; lastFetchAtRef.current = now;
inFlightRef.current = true; inFlightRef.current = true;
try { try {
// no-store:必须拿到管理员刚保存的最新值,不能走浏览器缓存 const settings = await apiGetSettings();
const { accent } = await apiGetSettings();
if (cancelled) return; if (cancelled) return;
apply((accent || "").trim().toLowerCase()); applyAccent((settings.accent || "").trim().toLowerCase());
applyCSS(settings.custom_css || "");
} catch { } catch {
// 主题同步失败静默处理,下次回前台再试,不打扰用户 // 同步失败静默,下次回前台再试
} finally { } finally {
inFlightRef.current = false; inFlightRef.current = false;
} }
}; };
// WebSocket 推送优先:管理员保存即换肤;回前台 HTTP 校准兜底
const offPush = realtime.on<RtSettingsData>(RT_SETTINGS_CHANGED, (data) => { const offPush = realtime.on<RtSettingsData>(RT_SETTINGS_CHANGED, (data) => {
if (data) apply((data.accent || "").trim().toLowerCase()); if (!data) return;
applyAccent((data.accent || "").trim().toLowerCase());
if (typeof data.custom_css === "string") applyCSS(data.custom_css);
}); });
// 仅 visibility:window focus 与 visibility 常连发,统一走限频即可
const offVisible = onDocumentVisible(() => void sync(), MIN_FETCH_GAP_MS); const offVisible = onDocumentVisible(() => void sync(), MIN_FETCH_GAP_MS);
// 离开外观页等 pathname 变化时立刻对齐一次(受 MIN_FETCH_GAP 限频)
void sync(); void sync();
return () => { return () => {

View File

@@ -54,7 +54,7 @@ export default function AdminSearchField({
type="button" type="button"
onClick={clear} onClick={clear}
aria-label="清除搜索" aria-label="清除搜索"
className="w-7 h-7 inline-flex items-center justify-center rounded-full shrink-0 transition-colors hover:bg-[var(--accent-soft)]" className="w-7 h-7 inline-flex items-center justify-center rounded-full shrink-0 transition-colors hover:bg-[var(--panel-2)]"
style={{ color: "var(--ink-3)" }} style={{ color: "var(--ink-3)" }}
> >
<X size={15} /> <X size={15} />

View File

@@ -263,7 +263,7 @@ function AdminUserMenu({ user, onLogout }: { user: User; onLogout: () => void })
}, [open]); }, [open]);
const itemCls = const itemCls =
"w-full flex items-center gap-2.5 px-4 py-2.5 text-[13.5px] transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]"; "w-full flex items-center gap-2.5 px-4 py-2.5 text-[13.5px] transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]";
return ( return (
<div className="relative" ref={menuRef}> <div className="relative" ref={menuRef}>

View File

@@ -45,14 +45,16 @@ export function AdminChartCard({
hint, hint,
children, children,
actions, actions,
className = "",
}: { }: {
title: string; title: string;
hint?: string; hint?: string;
children: React.ReactNode; children: React.ReactNode;
actions?: React.ReactNode; actions?: React.ReactNode;
className?: string;
}) { }) {
return ( return (
<div className="panel p-4 sm:p-5 flex flex-col min-h-[260px]"> <div className={`panel p-4 sm:p-5 flex flex-col ${className}`.trim()}>
<div className="flex items-start justify-between gap-2 mb-3"> <div className="flex items-start justify-between gap-2 mb-3">
<div className="min-w-0"> <div className="min-w-0">
<h3 className="text-[14.5px] font-semibold" style={{ color: "var(--ink)" }}> <h3 className="text-[14.5px] font-semibold" style={{ color: "var(--ink)" }}>
@@ -66,7 +68,7 @@ export function AdminChartCard({
</div> </div>
{/* 捕获阶段拦截 mousedown:冒泡阶段太晚,浏览器已开始 SVG 多柱选区黑框 */} {/* 捕获阶段拦截 mousedown:冒泡阶段太晚,浏览器已开始 SVG 多柱选区黑框 */}
<div <div
className="flex-1 min-h-[180px] w-full overflow-hidden select-none [&_*]:select-none [&_svg]:outline-none [&_.recharts-surface]:outline-none [&_.recharts-tooltip-cursor]:hidden" className="w-full overflow-hidden select-none [&_*]:select-none [&_svg]:outline-none [&_.recharts-surface]:outline-none [&_.recharts-tooltip-cursor]:hidden"
onMouseDownCapture={(e) => e.preventDefault()} onMouseDownCapture={(e) => e.preventDefault()}
> >
{children} {children}
@@ -144,15 +146,17 @@ export function SingleAreaChart({
dataKey, dataKey,
name, name,
color = "var(--accent)", color = "var(--accent)",
height = 200,
}: { }: {
data: { date: string; [k: string]: string | number }[]; data: { date: string; [k: string]: string | number }[];
dataKey: string; dataKey: string;
name: string; name: string;
color?: string; color?: string;
height?: number;
}) { }) {
const rows = data.map((d) => ({ ...d, label: shortDate(String(d.date)) })); const rows = data.map((d) => ({ ...d, label: shortDate(String(d.date)) }));
return ( return (
<ResponsiveContainer width="100%" height={200}> <ResponsiveContainer width="100%" height={height}>
<AreaChart data={rows} margin={{ top: 12, right: 12, left: 0, bottom: 0 }} accessibilityLayer={false}> <AreaChart data={rows} margin={{ top: 12, right: 12, left: 0, bottom: 0 }} accessibilityLayer={false}>
<CartesianGrid stroke="var(--line)" strokeDasharray="3 3" vertical={false} /> <CartesianGrid stroke="var(--line)" strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="label" tick={{ fill: "var(--ink-3)", fontSize: 11 }} axisLine={false} tickLine={false} /> <XAxis dataKey="label" tick={{ fill: "var(--ink-3)", fontSize: 11 }} axisLine={false} tickLine={false} />
@@ -183,8 +187,10 @@ export function NamedBarChart({
layout?: "vertical" | "horizontal"; layout?: "vertical" | "horizontal";
}) { }) {
if (layout === "horizontal") { if (layout === "horizontal") {
// 固定像素高度,避免 overflow 滚动条 ↔ ResponsiveContainer 互相触发闪烁
const chartH = Math.max(180, Math.min(320, data.length * 28));
return ( return (
<ResponsiveContainer width="100%" height={Math.max(180, data.length * 28)}> <ResponsiveContainer width="100%" height={chartH}>
<BarChart data={data} layout="vertical" margin={{ top: 8, right: 12, left: 8, bottom: 4 }} accessibilityLayer={false}> <BarChart data={data} layout="vertical" margin={{ top: 8, right: 12, left: 8, bottom: 4 }} accessibilityLayer={false}>
<CartesianGrid stroke="var(--line)" strokeDasharray="3 3" horizontal={false} /> <CartesianGrid stroke="var(--line)" strokeDasharray="3 3" horizontal={false} />
<XAxis type="number" tick={{ fill: "var(--ink-3)", fontSize: 11 }} axisLine={false} allowDecimals={false} /> <XAxis type="number" tick={{ fill: "var(--ink-3)", fontSize: 11 }} axisLine={false} allowDecimals={false} />

View File

@@ -296,7 +296,7 @@ function NewUsers({ users }: { users: NewUser[] }) {
<li key={u.id}> <li key={u.id}>
<Link <Link
href={`/u/${u.id}`} href={`/u/${u.id}`}
className="flex flex-col items-center gap-1.5 rounded-lg px-1 py-1 transition-colors hover:bg-[var(--accent-soft)] focus-visible:bg-[var(--accent-soft)]" className="flex flex-col items-center gap-1.5 rounded-lg px-1 py-1 transition-colors hover:bg-[var(--panel-2)] focus-visible:bg-[var(--panel-2)]"
> >
<Avatar name={name} src={u.avatar} size={38} /> <Avatar name={name} src={u.avatar} size={38} />
<span <span

View File

@@ -677,6 +677,10 @@ export interface PublicSettings {
attachment_max_count: number; attachment_max_count: number;
/** 正文插图上限 MB;缺省 5 */ /** 正文插图上限 MB;缺省 5 */
image_max_mb: number; image_max_mb: number;
/** 全站自定义 CSS;空串=无 */
custom_css: string;
/** 全站自定义 JS;空串=无(保存后整页加载生效) */
custom_js: string;
} }
/** 与后端 DefaultAttachmentExts 保持同步 */ /** 与后端 DefaultAttachmentExts 保持同步 */
@@ -711,6 +715,8 @@ const DEFAULT_PUBLIC_SETTINGS: PublicSettings = {
attachment_max_mb: 20, attachment_max_mb: 20,
attachment_max_count: 10, attachment_max_count: 10,
image_max_mb: 5, image_max_mb: 5,
custom_css: "",
custom_js: "",
}; };
function normalizeAttachmentExts(raw: unknown): string[] { function normalizeAttachmentExts(raw: unknown): string[] {
@@ -780,6 +786,8 @@ function normalizePublicSettings(data: Partial<PublicSettings> | null | undefine
attachment_max_mb: maxMB, attachment_max_mb: maxMB,
attachment_max_count: maxCount, attachment_max_count: maxCount,
image_max_mb: imageMB, image_max_mb: imageMB,
custom_css: typeof data?.custom_css === "string" ? data.custom_css : "",
custom_js: typeof data?.custom_js === "string" ? data.custom_js : "",
}; };
} }
@@ -2136,6 +2144,8 @@ export type UpdateSiteSettingsBody = {
attachment_max_mb?: number; attachment_max_mb?: number;
attachment_max_count?: number; attachment_max_count?: number;
image_max_mb?: number; image_max_mb?: number;
custom_css?: string;
custom_js?: string;
timeline_git_import?: string; timeline_git_import?: string;
}; };

100
frontend/lib/customCode.ts Normal file
View File

@@ -0,0 +1,100 @@
// 全站自定义 CSS:SSR <style id="j13-custom-css"> + 客户端 #j13-custom-css-runtime。
// 禁止对 SSR 节点 remove/改写;预览时 disable SSR,由 runtime 作为唯一源。
export const MAX_CUSTOM_CSS_CHARS = 48000;
export const MAX_CUSTOM_JS_CHARS = 48000;
/** 空配置时展示的注释模板:保存前不生效,全部注释故误保存也无副作用 */
export const SAMPLE_CUSTOM_CSS = `/* 姜十三 · 自定义 CSS 示例
* 覆盖 globals.css 令牌或组件类。保存后对全站访客生效。
* 勿写入 </style>
*
* 常用令牌:
* --bg / --panel / --ink / --accent
* --bg-halo 顶部光晕色(建议 ≤ 0.04)
* --bg-noise-opacity 噪点层透明度
* --r / --shadow-sm 卡片圆角与阴影
*/
/* 改底色与光晕(浅 / 暗成对改)
:root {
--bg: #f7f7f5;
--bg-halo: rgba(7, 192, 95, 0.04);
--bg-noise-opacity: 0.03;
--panel: #ffffff;
--r: 12px;
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.dark {
--bg: #101211;
--bg-halo: rgba(7, 192, 95, 0.03);
--bg-noise-opacity: 0.04;
}
*/
/* 关掉光晕和噪点
body::before,
body::after {
display: none;
}
*/
/* 隐藏页脚
footer { display: none; }
*/
`;
export const SAMPLE_CUSTOM_JS = `// 姜十三 · 自定义 JS 示例
// 仅整页加载执行一次(F5 / 首次进入),站内软导航不会重跑。
// 勿写入 </script>
//
// 给 <html> 打标记,便于 CSS 写 html[data-custom] .panel { ... }
// document.documentElement.dataset.custom = "1";
//
// 等 DOM 就绪后再改节点
// document.addEventListener("DOMContentLoaded", function () {
// // document.querySelector("footer")?.remove();
// });
`;
const SSR_STYLE_ID = "j13-custom-css";
const RUNTIME_STYLE_ID = "j13-custom-css-runtime";
export function clipCustomSnippet(raw: string, max: number): string {
const s = (raw || "").replace(/\u0000/g, "");
if (s.length <= max) return s;
return [...s].slice(0, max).join("");
}
function ensureRuntimeStyle(): HTMLStyleElement {
let el = document.getElementById(RUNTIME_STYLE_ID) as HTMLStyleElement | null;
if (el) return el;
el = document.createElement("style");
el.id = RUNTIME_STYLE_ID;
el.setAttribute("data-custom-css-source", "runtime");
document.body.appendChild(el);
return el;
}
function removeRuntimeStyle(): void {
document.getElementById(RUNTIME_STYLE_ID)?.remove();
}
function ssrStyle(): HTMLStyleElement | null {
return document.getElementById(SSR_STYLE_ID) as HTMLStyleElement | null;
}
/** 将自定义 CSS 应用到当前文档。preview=true 时忽略 SSR 节点(外观页草稿)。 */
export function applyCustomCSS(css: string, preview = false): void {
if (typeof document === "undefined") return;
const text = clipCustomSnippet(css, MAX_CUSTOM_CSS_CHARS).trim();
const ssr = ssrStyle();
if (ssr) ssr.disabled = preview;
if (!text) {
removeRuntimeStyle();
if (!preview && ssr) ssr.disabled = false;
return;
}
ensureRuntimeStyle().textContent = text;
}

View File

@@ -1,11 +1,11 @@
/** 帖子类型 / 可见性 / 展示文案(前后端共用约定) */ /** 帖子类型 / 可见性 / 展示文案(前后端共用约定) */
export const POST_TYPES = [ export const POST_TYPES = [
{ value: "discussion", label: "讨论", hint: "默认讨论帖" }, { value: "discussion", label: "讨论", hint: "日常交流" },
{ value: "question", label: "问答", hint: "提问求解" }, { value: "question", label: "问答", hint: "提问求解" },
{ value: "poll", label: "投票", hint: "发起投票,读者可参与" }, { value: "poll", label: "投票", hint: "收集选项意见" },
{ value: "bounty", label: "悬赏", hint: "发布时托管积分,采纳后发放" }, { value: "bounty", label: "悬赏", hint: "积分托管求解" },
{ value: "lottery", label: "抽奖", hint: "奖品类型+数量入池,评论后锁定奖品" }, { value: "lottery", label: "抽奖", hint: "评论参与开奖" },
] as const; ] as const;
export type PostTypeValue = (typeof POST_TYPES)[number]["value"]; export type PostTypeValue = (typeof POST_TYPES)[number]["value"];

View File

@@ -59,6 +59,8 @@ export interface RtSettingsData {
attachment_max_mb?: number; attachment_max_mb?: number;
attachment_max_count?: number; attachment_max_count?: number;
image_max_mb?: number; image_max_mb?: number;
custom_css?: string;
custom_js?: string;
} }
// 群聊新消息:data 为落库的 ChatMessage(含 sender) // 群聊新消息:data 为落库的 ChatMessage(含 sender)

View File

@@ -157,7 +157,7 @@ function clampForLight(hex: string): string {
function deriveDark(hex: string): string { function deriveDark(hex: string): string {
const [h, s, lRaw] = rgbToHsl(hexToRgb(hex)); const [h, s, lRaw] = rgbToHsl(hexToRgb(hex));
let l = Math.max(lRaw, 0.62); let l = Math.max(lRaw, 0.62);
const surfaces = ["#181b21", "#0f1115", "#10162b"]; const surfaces = ["#181b21", "#101211", "#10162b"];
let cur = hex; let cur = hex;
for (let i = 0; i < 120; i++) { for (let i = 0; i < 120; i++) {
cur = rgbToHex(hslToRgb([h, s, l])); cur = rgbToHex(hslToRgb([h, s, l]));
@@ -207,18 +207,18 @@ function buildAccentCSS(input: string): string {
`--accent-hi:${hi};`, `--accent-hi:${hi};`,
`--accent-soft:${rgba(light, 0.1)};`, `--accent-soft:${rgba(light, 0.1)};`,
`--accent-on:#ffffff;`, `--accent-on:#ffffff;`,
`--nav-active-bg:${rgba(light, 0.1)};`, `--nav-active-bg:var(--panel);`,
`--nav-active-ink:${light};`, `--nav-active-ink:${light};`,
`--nav-active-line:${rgba(light, 0.22)};`, `--nav-active-line:${rgba(light, 0.38)};`,
`}`, `}`,
`.dark{`, `.dark{`,
`--accent:${dark};`, `--accent:${dark};`,
`--accent-hi:${darkHi};`, `--accent-hi:${darkHi};`,
`--accent-soft:${rgba(dark, 0.16)};`, `--accent-soft:${rgba(dark, 0.16)};`,
`--accent-on:#10162b;`, `--accent-on:#10162b;`,
`--nav-active-bg:${rgba(dark, 0.14)};`, `--nav-active-bg:var(--panel);`,
`--nav-active-ink:${darkHi};`, `--nav-active-ink:${darkHi};`,
`--nav-active-line:${rgba(dark, 0.3)};`, `--nav-active-line:${rgba(dark, 0.38)};`,
`}`, `}`,
].join(""); ].join("");
} }