feat(webui): EULA/PRIVACY consent gate — frontend
ConsentPage shown after login, before the forced password change: tabbed EULA/PRIVACY rendered by an in-house, dependency-free markdown renderer (React elements only, XSS-safe; single-pass bounded-class inline parser to avoid ReDoS on large docs). App gate order is login -> consent -> password -> app; api client gains agreements.get / recordConsent with a 409 stale-version re-prompt that refetches the new text.
This commit is contained in:
5 files changed
+583
-31
No files matched your search
+117
-31
@@ -5,7 +5,9 @@ import { ThemeProvider } from '@/contexts/ThemeContext';
|
||||
import { SessionProvider } from '@/contexts/SessionContext';
|
||||
import { LoginPage } from '@/components/pages/login-page';
|
||||
import { ChangePasswordPage } from '@/components/pages/change-password-page';
|
||||
import { ConsentPage } from '@/components/pages/consent-page';
|
||||
import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api';
|
||||
import type { AgreementsPayload } from '@/lib/api/types';
|
||||
import { appRouter } from '@/router';
|
||||
|
||||
export default function App() {
|
||||
@@ -21,6 +23,10 @@ function AuthBoundary() {
|
||||
const [authed, setAuthed] = useState(false);
|
||||
const [mustChange, setMustChange] = useState(false);
|
||||
const [status, setStatus] = useState('未连接');
|
||||
// Agreement consent gate, shown after login but BEFORE the forced password
|
||||
// change. `agreements === null` while the post-auth fetch is in flight.
|
||||
const [agreements, setAgreements] = useState<AgreementsPayload | null>(null);
|
||||
const [needsConsent, setNeedsConsent] = useState(false);
|
||||
// The password from *this* session's login, carried into the forced
|
||||
// change-password gate so it doesn't have to render an old-password field
|
||||
// (which browsers autofill, misleading users on upgrade). Stays undefined
|
||||
@@ -38,6 +44,18 @@ function AuthBoundary() {
|
||||
[],
|
||||
);
|
||||
|
||||
const refreshAgreements = useCallback(async () => {
|
||||
try {
|
||||
const payload = await client.agreements.get();
|
||||
setAgreements(payload);
|
||||
setNeedsConsent(payload.consentRequired);
|
||||
} catch {
|
||||
// Fail open on a fetch error so a transient hiccup can't wedge the gate.
|
||||
setAgreements({ version: '', consentRequired: false, documents: [] });
|
||||
setNeedsConsent(false);
|
||||
}
|
||||
}, [client]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const ok = await client.status();
|
||||
@@ -45,54 +63,88 @@ function AuthBoundary() {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(await client.mustChangePassword());
|
||||
await refreshAgreements();
|
||||
}
|
||||
setAuthChecked(true);
|
||||
})();
|
||||
}, [client]);
|
||||
}, [client, refreshAgreements]);
|
||||
|
||||
const handleLogoutComplete = useCallback(() => {
|
||||
const handleLoggedOut = useCallback(() => {
|
||||
// Reset the URL so the next login lands on the overview page, matching
|
||||
// the pre-router behaviour.
|
||||
// the pre-router behaviour, and clear every post-auth gate.
|
||||
window.history.replaceState({}, '', '/');
|
||||
setAuthed(false);
|
||||
setStatus('未连接');
|
||||
setMustChange(false);
|
||||
setAgreements(null);
|
||||
setNeedsConsent(false);
|
||||
setLoginPassword(undefined);
|
||||
}, []);
|
||||
|
||||
const handleDecline = useCallback(async () => {
|
||||
await client.logout();
|
||||
handleLoggedOut();
|
||||
}, [client, handleLoggedOut]);
|
||||
|
||||
let view: React.ReactNode;
|
||||
if (!authChecked) {
|
||||
view = <Splash>初始化中…</Splash>;
|
||||
} else if (!authed) {
|
||||
view = (
|
||||
<LoginGate
|
||||
onAuthed={(needsChange, password) => {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(needsChange);
|
||||
setLoginPassword(password);
|
||||
void refreshAgreements();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
} else if (agreements === null) {
|
||||
view = <Splash>加载中…</Splash>;
|
||||
} else if (needsConsent) {
|
||||
view = (
|
||||
<ConsentGate
|
||||
payload={agreements}
|
||||
onAccepted={() => setNeedsConsent(false)}
|
||||
onStale={refreshAgreements}
|
||||
onDecline={handleDecline}
|
||||
/>
|
||||
);
|
||||
} else if (mustChange) {
|
||||
view = (
|
||||
<ForcedChangePasswordGate
|
||||
knownOldPassword={loginPassword}
|
||||
onSuccess={() => {
|
||||
setMustChange(false);
|
||||
setLoginPassword(undefined);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
view = (
|
||||
<SessionProvider value={{ status, onLogoutComplete: handleLoggedOut }}>
|
||||
<RouterProvider router={appRouter} />
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ApiProvider client={client}>
|
||||
<TooltipProvider delayDuration={150}>
|
||||
{!authChecked ? (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
|
||||
初始化中…
|
||||
</div>
|
||||
) : !authed ? (
|
||||
<LoginGate
|
||||
onAuthed={(needsChange, password) => {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(needsChange);
|
||||
setLoginPassword(password);
|
||||
}}
|
||||
/>
|
||||
) : mustChange ? (
|
||||
<ForcedChangePasswordGate
|
||||
knownOldPassword={loginPassword}
|
||||
onSuccess={() => {
|
||||
setMustChange(false);
|
||||
setLoginPassword(undefined);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<SessionProvider value={{ status, onLogoutComplete: handleLogoutComplete }}>
|
||||
<RouterProvider router={appRouter} />
|
||||
</SessionProvider>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
<TooltipProvider delayDuration={150}>{view}</TooltipProvider>
|
||||
</ApiProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function Splash({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) {
|
||||
const api = useApi();
|
||||
const handleLogin = useCallback(
|
||||
@@ -107,6 +159,40 @@ function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: str
|
||||
return <LoginPage onLogin={handleLogin} />;
|
||||
}
|
||||
|
||||
function ConsentGate({
|
||||
payload,
|
||||
onAccepted,
|
||||
onStale,
|
||||
onDecline,
|
||||
}: {
|
||||
payload: AgreementsPayload;
|
||||
onAccepted: () => void;
|
||||
onStale: () => void;
|
||||
onDecline: () => void;
|
||||
}) {
|
||||
const api = useApi();
|
||||
return (
|
||||
<ConsentPage
|
||||
documents={payload.documents}
|
||||
version={payload.version}
|
||||
onDecline={onDecline}
|
||||
onAccept={async () => {
|
||||
const result = await api.agreements.recordConsent(payload.version);
|
||||
if (result.success) {
|
||||
onAccepted();
|
||||
return { success: true };
|
||||
}
|
||||
// 409: the agreement text changed under us — re-fetch and re-prompt.
|
||||
if (result.currentVersion && result.currentVersion !== payload.version) {
|
||||
onStale();
|
||||
return { success: false, message: '协议已更新,已为你载入最新版本,请重新阅读后确认。' };
|
||||
}
|
||||
return { success: false, message: result.message ?? '提交失败,请重试' };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ForcedChangePasswordGate({
|
||||
knownOldPassword,
|
||||
onSuccess,
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Check, ScrollText, ShieldCheck } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { ThemeToggle } from '@/components/theme-toggle';
|
||||
import { Markdown } from '@/lib/markdown';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { AgreementDoc } from '@/lib/api/types';
|
||||
|
||||
interface ConsentPageProps {
|
||||
documents: AgreementDoc[];
|
||||
version: string;
|
||||
/** Persist acceptance. Resolves {success:false,message} to show inline. */
|
||||
onAccept: () => Promise<{ success: boolean; message?: string }>;
|
||||
/** Operator refuses — caller logs them out. */
|
||||
onDecline: () => void;
|
||||
}
|
||||
|
||||
const TAB_FALLBACK_TITLE: Record<string, string> = {
|
||||
eula: '用户协议 / EULA',
|
||||
privacy: '隐私政策 / Privacy',
|
||||
};
|
||||
|
||||
/**
|
||||
* Full-screen consent gate shown once at first login, before the forced
|
||||
* password change. The operator must accept the EULA + Privacy Notice before
|
||||
* the panel unlocks; acceptance is keyed to the agreement content version, so
|
||||
* it persists across app upgrades and re-prompts only when the text changes.
|
||||
*/
|
||||
export function ConsentPage({ documents, version, onAccept, onDecline }: ConsentPageProps) {
|
||||
const tabs = documents.length > 0 ? documents : [];
|
||||
const [activeId, setActiveId] = useState<string>(tabs[0]?.id ?? 'eula');
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const active = tabs.find((d) => d.id === activeId) ?? tabs[0];
|
||||
|
||||
const handleAccept = async () => {
|
||||
if (!agreed || submitting) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await onAccept();
|
||||
if (!result.success) {
|
||||
setError(result.message ?? '提交失败,请重试');
|
||||
setSubmitting(false);
|
||||
}
|
||||
// on success the parent unmounts this gate; no local state change needed.
|
||||
} catch {
|
||||
// Defense in depth: onAccept should never reject (client resolves errors),
|
||||
// but never leave the button stuck on "提交中…" if it somehow does.
|
||||
setError('网络错误,请重试');
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-8">
|
||||
<div
|
||||
className="pointer-events-none absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
'radial-gradient(80% 60% at 50% 0%, color-mix(in oklab, var(--primary) 18%, transparent) 0%, transparent 70%)',
|
||||
}}
|
||||
/>
|
||||
<div className="absolute right-4 top-4">
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ duration: 0.45, ease: [0.16, 1, 0.3, 1] }}
|
||||
className="relative z-10 flex w-full max-w-3xl flex-col"
|
||||
>
|
||||
<Card className="border-primary/15 shadow-xl">
|
||||
<CardContent className="flex max-h-[88vh] flex-col p-7 sm:p-9">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-2xl bg-primary/10 ring-1 ring-primary/20">
|
||||
<ScrollText className="size-6 text-primary" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-lg font-semibold tracking-tight">请阅读并同意以下协议</h1>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
首次使用前,请阅读并同意《用户协议》与《隐私政策》。同意一次后无需重复确认;仅当协议内容更新时才会再次请求确认。
|
||||
<br />
|
||||
Please read and accept the agreements below before first use. You only consent once — you'll be asked again only if the text changes.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* tab switcher */}
|
||||
<div className="mt-5 flex gap-1 rounded-lg bg-muted/60 p-1">
|
||||
{tabs.map((doc) => (
|
||||
<button
|
||||
key={doc.id}
|
||||
type="button"
|
||||
onClick={() => setActiveId(doc.id)}
|
||||
className={cn(
|
||||
'flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors',
|
||||
doc.id === activeId
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{doc.title?.split('/')[0]?.trim() || TAB_FALLBACK_TITLE[doc.id] || doc.id}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{active && (active.declaredVersion || active.effectiveDate) && (
|
||||
<p className="mt-2 text-[11px] text-muted-foreground">
|
||||
{active.declaredVersion && `版本 / Version ${active.declaredVersion}`}
|
||||
{active.declaredVersion && active.effectiveDate && ' · '}
|
||||
{active.effectiveDate && `生效 / Effective ${active.effectiveDate}`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* document body */}
|
||||
<div className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-lg border border-border bg-background/60 p-4">
|
||||
{active ? (
|
||||
<Markdown content={active.text} />
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">未能加载协议文本,请刷新页面重试。</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* agree checkbox */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAgreed((v) => !v)}
|
||||
className="mt-4 flex items-start gap-2.5 text-left"
|
||||
aria-pressed={agreed}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'mt-0.5 flex size-4 shrink-0 items-center justify-center rounded border transition-colors',
|
||||
agreed ? 'border-primary bg-primary text-primary-foreground' : 'border-input',
|
||||
)}
|
||||
>
|
||||
{agreed && <Check className="size-3" />}
|
||||
</span>
|
||||
<span className="text-xs leading-relaxed text-muted-foreground">
|
||||
我已阅读并同意《用户协议》与《隐私政策》。
|
||||
<br />
|
||||
I have read and agree to the User Agreement and the Privacy Notice.
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{error && <p className="mt-3 text-xs text-destructive">{error}</p>}
|
||||
|
||||
<div className="mt-5 flex items-center justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={onDecline} disabled={submitting}>
|
||||
不同意并退出
|
||||
</Button>
|
||||
<Button type="button" onClick={handleAccept} disabled={!agreed || submitting}>
|
||||
<ShieldCheck className="size-4" />
|
||||
{submitting ? '提交中…' : '同意并继续'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<p className="mt-3 text-center text-[10px] text-muted-foreground/70">agreements {version.slice(0, 8)}</p>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionD
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||
import {
|
||||
type AgreementsPayload,
|
||||
ApiError,
|
||||
type ApiClient,
|
||||
type ChangePasswordResult,
|
||||
@@ -47,6 +48,7 @@ class HttpApiClient implements ApiClient {
|
||||
readonly notifications: ApiClient['notifications'];
|
||||
readonly systemSettings: ApiClient['systemSettings'];
|
||||
readonly debug: ApiClient['debug'];
|
||||
readonly agreements: ApiClient['agreements'];
|
||||
|
||||
constructor(opts: CreateApiClientOptions = {}) {
|
||||
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
|
||||
@@ -185,6 +187,26 @@ class HttpApiClient implements ApiClient {
|
||||
channelId,
|
||||
}),
|
||||
};
|
||||
|
||||
this.agreements = {
|
||||
get: () => this.getJson<AgreementsPayload>('/api/agreements'),
|
||||
recordConsent: async (version) => {
|
||||
// Read the body even on non-2xx so a 409 can surface currentVersion to
|
||||
// the caller (instead of fetchJson throwing it away as an ApiError).
|
||||
// A network failure (fetch reject) must resolve to {success:false}, not
|
||||
// throw, or the consent button hangs on "提交中…" with no error shown.
|
||||
try {
|
||||
const res = await this.request('/api/agreements/record-consent', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ version }),
|
||||
});
|
||||
const data = await readJson<{ success?: boolean; message?: string; currentVersion?: string }>(res);
|
||||
return { success: res.ok && !!data.success, message: data.message, currentVersion: data.currentVersion };
|
||||
} catch (e) {
|
||||
return { success: false, message: e instanceof Error ? e.message : '网络错误,请重试' };
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- HTTP helpers ----------
|
||||
|
||||
@@ -39,6 +39,29 @@ export type LoginResult =
|
||||
|
||||
export type ChangePasswordResult = { success: boolean; message?: string };
|
||||
|
||||
export interface AgreementDoc {
|
||||
id: 'eula' | 'privacy';
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface AgreementsPayload {
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/** Whether the operator must (re-)accept before using the panel. */
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
}
|
||||
|
||||
export type RecordConsentResult = {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
/** On a 409 version-mismatch, the server's current version to re-fetch. */
|
||||
currentVersion?: string;
|
||||
};
|
||||
|
||||
export type ProcessActionResult = {
|
||||
process?: HookProcessInfo & { error?: string };
|
||||
};
|
||||
@@ -61,6 +84,14 @@ export interface ApiClient {
|
||||
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
|
||||
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
|
||||
|
||||
// ---- EULA / PRIVACY consent (shown after login, before set-password) ----
|
||||
agreements: {
|
||||
/** Fetch agreement texts + current version + whether consent is required. */
|
||||
get(): Promise<AgreementsPayload>;
|
||||
/** Record acceptance of `version`. success:false (409) carries currentVersion. */
|
||||
recordConsent(version: string): Promise<RecordConsentResult>;
|
||||
};
|
||||
|
||||
// ---- system ----
|
||||
qqList(): Promise<QQInfo[]>;
|
||||
system(): Promise<SystemInfo>;
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { Fragment, type ReactNode } from 'react';
|
||||
|
||||
/**
|
||||
* Tiny dependency-free markdown renderer, scoped to what the EULA / PRIVACY
|
||||
* documents actually use: headings (#..####), horizontal rules, blockquotes,
|
||||
* ordered / unordered lists, fenced code blocks, paragraphs, and the inline
|
||||
* spans bold / italic / code / links.
|
||||
*
|
||||
* It renders to React elements (never dangerouslySetInnerHTML), so all text is
|
||||
* auto-escaped by React and the renderer cannot introduce XSS even though the
|
||||
* source text comes over the wire. Links are additionally restricted to
|
||||
* http/https/mailto; anything else renders as plain text.
|
||||
*/
|
||||
export function Markdown({ content }: { content: string }): ReactNode {
|
||||
const blocks = parseBlocks(content.replace(/\r\n?/g, '\n'));
|
||||
return (
|
||||
<div className="sl-md space-y-3 text-sm leading-relaxed">
|
||||
{blocks.map((block, i) => (
|
||||
<Fragment key={i}>{renderBlock(block)}</Fragment>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Block =
|
||||
| { type: 'heading'; level: number; text: string }
|
||||
| { type: 'hr' }
|
||||
| { type: 'quote'; lines: string[] }
|
||||
| { type: 'ul'; items: string[] }
|
||||
| { type: 'ol'; items: string[] }
|
||||
| { type: 'code'; text: string }
|
||||
| { type: 'p'; text: string };
|
||||
|
||||
function parseBlocks(src: string): Block[] {
|
||||
const lines = src.split('\n');
|
||||
const blocks: Block[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
// blank line — skip
|
||||
if (line.trim() === '') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// fenced code block ``` ... ```
|
||||
if (/^\s*```/.test(line)) {
|
||||
const body: string[] = [];
|
||||
i++;
|
||||
while (i < lines.length && !/^\s*```/.test(lines[i])) {
|
||||
body.push(lines[i]);
|
||||
i++;
|
||||
}
|
||||
i++; // consume closing fence (or EOF)
|
||||
blocks.push({ type: 'code', text: body.join('\n') });
|
||||
continue;
|
||||
}
|
||||
|
||||
// horizontal rule
|
||||
if (/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)) {
|
||||
blocks.push({ type: 'hr' });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// heading
|
||||
const heading = line.match(/^(#{1,6})\s+(.*)$/);
|
||||
if (heading) {
|
||||
blocks.push({ type: 'heading', level: heading[1].length, text: heading[2].trim() });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// blockquote (consecutive `>` lines)
|
||||
if (/^\s*>/.test(line)) {
|
||||
const quote: string[] = [];
|
||||
while (i < lines.length && /^\s*>/.test(lines[i])) {
|
||||
quote.push(lines[i].replace(/^\s*>\s?/, ''));
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'quote', lines: quote });
|
||||
continue;
|
||||
}
|
||||
|
||||
// unordered list
|
||||
if (/^\s*[-*+]\s+/.test(line)) {
|
||||
const items: string[] = [];
|
||||
while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) {
|
||||
items.push(lines[i].replace(/^\s*[-*+]\s+/, ''));
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'ul', items });
|
||||
continue;
|
||||
}
|
||||
|
||||
// ordered list
|
||||
if (/^\s*\d+[.)]\s+/.test(line)) {
|
||||
const items: string[] = [];
|
||||
while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) {
|
||||
items.push(lines[i].replace(/^\s*\d+[.)]\s+/, ''));
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'ol', items });
|
||||
continue;
|
||||
}
|
||||
|
||||
// paragraph — gather until a blank line or a line that starts a new block
|
||||
const para: string[] = [];
|
||||
while (i < lines.length && lines[i].trim() !== '' && !startsNewBlock(lines[i])) {
|
||||
para.push(lines[i].trim());
|
||||
i++;
|
||||
}
|
||||
blocks.push({ type: 'p', text: para.join(' ') });
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function startsNewBlock(line: string): boolean {
|
||||
return (
|
||||
/^\s*```/.test(line) ||
|
||||
/^(#{1,6})\s+/.test(line) ||
|
||||
/^\s*>/.test(line) ||
|
||||
/^\s*[-*+]\s+/.test(line) ||
|
||||
/^\s*\d+[.)]\s+/.test(line) ||
|
||||
/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)
|
||||
);
|
||||
}
|
||||
|
||||
function renderBlock(block: Block): ReactNode {
|
||||
switch (block.type) {
|
||||
case 'heading': {
|
||||
const cls = [
|
||||
'text-xl font-semibold tracking-tight',
|
||||
'text-lg font-semibold tracking-tight',
|
||||
'text-base font-semibold',
|
||||
'text-sm font-semibold',
|
||||
'text-sm font-semibold text-muted-foreground',
|
||||
'text-xs font-semibold text-muted-foreground',
|
||||
][block.level - 1];
|
||||
const inner = renderInline(block.text);
|
||||
switch (block.level) {
|
||||
case 1:
|
||||
return <h1 className={cls}>{inner}</h1>;
|
||||
case 2:
|
||||
return <h2 className={cls}>{inner}</h2>;
|
||||
case 3:
|
||||
return <h3 className={cls}>{inner}</h3>;
|
||||
case 4:
|
||||
return <h4 className={cls}>{inner}</h4>;
|
||||
case 5:
|
||||
return <h5 className={cls}>{inner}</h5>;
|
||||
default:
|
||||
return <h6 className={cls}>{inner}</h6>;
|
||||
}
|
||||
}
|
||||
case 'hr':
|
||||
return <hr className="border-border" />;
|
||||
case 'quote':
|
||||
return (
|
||||
<blockquote className="border-l-2 border-primary/40 pl-3 text-muted-foreground">
|
||||
{block.lines.map((l, i) => (
|
||||
<p key={i}>{renderInline(l)}</p>
|
||||
))}
|
||||
</blockquote>
|
||||
);
|
||||
case 'ul':
|
||||
return (
|
||||
<ul className="list-disc space-y-1 pl-5">
|
||||
{block.items.map((it, i) => (
|
||||
<li key={i}>{renderInline(it)}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
case 'ol':
|
||||
return (
|
||||
<ol className="list-decimal space-y-1 pl-5">
|
||||
{block.items.map((it, i) => (
|
||||
<li key={i}>{renderInline(it)}</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
case 'code':
|
||||
return (
|
||||
<pre className="overflow-x-auto rounded-md bg-muted p-3 text-xs">
|
||||
<code>{block.text}</code>
|
||||
</pre>
|
||||
);
|
||||
case 'p':
|
||||
return <p>{renderInline(block.text)}</p>;
|
||||
}
|
||||
}
|
||||
|
||||
// Inline spans: `code`, **bold**, *italic* / _italic_, [text](url).
|
||||
//
|
||||
// Scanned in ONE pass with a global regex (lastIndex advances), and every
|
||||
// span uses a *bounded* negated class (`{1,N}`). Both matter: a greedy
|
||||
// UNbounded negated class (`[^\]]+`) on bracket-/asterisk-dense text causes
|
||||
// O(n²) catastrophic backtracking and can hang the render thread on a large
|
||||
// doc. The caps are far larger than any real inline span; anything longer
|
||||
// renders literally rather than risking a hang.
|
||||
const INLINE_RE =
|
||||
/`[^`\n]{1,2048}`|\*\*[^*\n]{1,2048}\*\*|\*[^*\n]{1,2048}\*|_[^_\n]{1,2048}_|\[[^\]\n]{1,512}\]\([^)\s]{1,2048}\)/g;
|
||||
|
||||
function renderInline(text: string): ReactNode[] {
|
||||
const out: ReactNode[] = [];
|
||||
const re = new RegExp(INLINE_RE.source, 'g'); // fresh instance: own lastIndex
|
||||
let last = 0;
|
||||
let key = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
if (m.index > last) out.push(text.slice(last, m.index));
|
||||
const tok = m[0];
|
||||
if (tok.startsWith('`')) {
|
||||
out.push(<code key={key++} className="rounded bg-muted px-1 py-0.5 text-xs">{tok.slice(1, -1)}</code>);
|
||||
} else if (tok.startsWith('**')) {
|
||||
out.push(<strong key={key++}>{renderInline(tok.slice(2, -2))}</strong>);
|
||||
} else if (tok.startsWith('*') || tok.startsWith('_')) {
|
||||
out.push(<em key={key++}>{renderInline(tok.slice(1, -1))}</em>);
|
||||
} else {
|
||||
// [label](href) — tok already matched the bounded link shape.
|
||||
const link = tok.match(/^\[([^\]]*)\]\(([^)\s]+)\)$/);
|
||||
if (link) out.push(safeLink(link[2], link[1], key++));
|
||||
else out.push(tok);
|
||||
}
|
||||
last = m.index + tok.length;
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last));
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function safeLink(href: string, label: string, key: number): ReactNode {
|
||||
const ok = /^(https?:|mailto:)/i.test(href);
|
||||
if (!ok) return <Fragment key={key}>{label}</Fragment>;
|
||||
return (
|
||||
<a key={key} href={href} target="_blank" rel="noopener noreferrer" className="text-primary underline underline-offset-2">
|
||||
{label}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user