cc-viewer 1.8.3 → 1.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +39 -1
- package/dist/assets/{App-BJyM_MyF.js → App-QfR6J-2-.js} +2 -2
- package/dist/assets/MdxEditorPanel-BEab9H3Q.js +1 -0
- package/dist/assets/{Mobile-BZwtDySx.js → Mobile-XUIomH49.js} +1 -1
- package/dist/assets/{ProxyStatsModal-D8-y55j0.js → ProxyStatsModal-Bawmf1xu.js} +1 -1
- package/dist/assets/{_baseUniq-BvoL7sea.js → _baseUniq-D2aO8mv4.js} +1 -1
- package/dist/assets/{arc-CWSgghLO.js → arc-DOjcnBTh.js} +1 -1
- package/dist/assets/architectureDiagram-Q4EWVU46-Drea2H7X.js +1 -0
- package/dist/assets/blockDiagram-DXYQGD6D-Bc9eijBD.js +1 -0
- package/dist/assets/c4Diagram-AHTNJAMY-D-umzFnM.js +1 -0
- package/dist/assets/{channel-NrrRrxlA.js → channel-DUff3FBt.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-DJvzFKwQ.js → chunk-4BX2VUAB-CFnsROfz.js} +1 -1
- package/dist/assets/{chunk-4TB4RGXK-BtkeuMYF.js → chunk-4TB4RGXK-C95jMPjB.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-B9KZe48-.js → chunk-55IACEB6-CeWf2Y2b.js} +1 -1
- package/dist/assets/{chunk-EDXVE4YY-CrC8aHms.js → chunk-EDXVE4YY-ClUoTJxv.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-CsMZhbHS.js → chunk-FMBD7UC4-Dk62kqb8.js} +1 -1
- package/dist/assets/{chunk-OYMX7WX6-DzMU24Av.js → chunk-OYMX7WX6-CZuykSsu.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-DQg8aTq0.js → chunk-QZHKN3VN-DYtx68Um.js} +1 -1
- package/dist/assets/{chunk-YZCP3GAM-DiH0m9X5.js → chunk-YZCP3GAM-rLSq0tSC.js} +1 -1
- package/dist/assets/classDiagram-6PBFFD2Q-DT8RQXlO.js +1 -0
- package/dist/assets/classDiagram-v2-HSJHXN6E-DT8RQXlO.js +1 -0
- package/dist/assets/clone-_dhVVwEt.js +1 -0
- package/dist/assets/cose-bilkent-S5V4N54A-B5H6ewon.js +1 -0
- package/dist/assets/dagre-KV5264BT-BO2R2WP7.js +1 -0
- package/dist/assets/diagram-5BDNPKRD-Y3GNif-g.js +1 -0
- package/dist/assets/diagram-G4DWMVQ6-Du3_TylQ.js +1 -0
- package/dist/assets/diagram-MMDJMWI5-DB_Ynyjc.js +1 -0
- package/dist/assets/diagram-TYMM5635-_Rfjm82W.js +1 -0
- package/dist/assets/erDiagram-SMLLAGMA-D5XhBiiV.js +1 -0
- package/dist/assets/flowDiagram-DWJPFMVM-CxWJ7sAQ.js +1 -0
- package/dist/assets/ganttDiagram-T4ZO3ILL-D-a8fh00.js +1 -0
- package/dist/assets/gitGraphDiagram-UUTBAWPF-q5WMk0Ce.js +1 -0
- package/dist/assets/{graph-BHosumIo.js → graph-Bi8xMAuo.js} +1 -1
- package/dist/assets/index-3Z3ucdlB.js +1 -0
- package/dist/assets/index-BB66PLo6.js +1 -0
- package/dist/assets/index-BBEH6Ppx.js +1 -0
- package/dist/assets/index-BRtbpMRz.js +1 -0
- package/dist/assets/index-BWPHHS6P.js +1 -0
- package/dist/assets/index-C3wsDB-y.js +1 -0
- package/dist/assets/index-O2Mx9uLd.js +1 -0
- package/dist/assets/index-gBheYuc_.js +2 -0
- package/dist/assets/infoDiagram-42DDH7IO-CE2mUuLF.js +1 -0
- package/dist/assets/ishikawaDiagram-UXIWVN3A-C5sNQIVL.js +1 -0
- package/dist/assets/journeyDiagram-VCZTEJTY-g7HXOeyX.js +1 -0
- package/dist/assets/{jszip.min-B7ufzfHi.js → jszip.min-x3xOZxY_.js} +1 -1
- package/dist/assets/kanban-definition-6JOO6SKY-D3Mus6hc.js +1 -0
- package/dist/assets/{layout-D5zEy4mK.js → layout-05qDuweB.js} +1 -1
- package/dist/assets/{linear-BAPnyqP4.js → linear-DQEG_N-F.js} +1 -1
- package/dist/assets/{mermaid.core-C8GuIPOP.js → mermaid.core-DcaXqkk5.js} +2 -2
- package/dist/assets/{min-DP92r0cl.js → min-DSpvw5zG.js} +1 -1
- package/dist/assets/mindmap-definition-QFDTVHPH-DomUIop7.js +1 -0
- package/dist/assets/pieDiagram-DEJITSTG-COTLcC5G.js +1 -0
- package/dist/assets/quadrantDiagram-34T5L4WZ-DMg8C3Up.js +1 -0
- package/dist/assets/requirementDiagram-MS252O5E-DF9beYd7.js +1 -0
- package/dist/assets/sankeyDiagram-XADWPNL6-MvERK2UP.js +1 -0
- package/dist/assets/seqResourceLoaders-KWixB6L_.js +2 -0
- package/dist/assets/{seqResourceLoaders-DI0G5nu1.css → seqResourceLoaders-vliPauH9.css} +2 -2
- package/dist/assets/sequenceDiagram-FGHM5R23-B8k_nyzc.js +1 -0
- package/dist/assets/stateDiagram-FHFEXIEX-D-9fTYas.js +1 -0
- package/dist/assets/stateDiagram-v2-QKLJ7IA2-CO0tv8rD.js +1 -0
- package/dist/assets/timeline-definition-GMOUNBTQ-CbK1g9CO.js +1 -0
- package/dist/assets/{vendor-antd-CSjy2pdD.js → vendor-antd-FhK5cQx7.js} +1 -1
- package/dist/assets/vendor-codemirror-DL3yyKRQ.js +1 -0
- package/dist/assets/vendor-mdxeditor-DgyrvHzS.js +2 -0
- package/dist/assets/{vendor-qrcode-Bs-eoLpy.js → vendor-qrcode-BAwwP1Nd.js} +1 -1
- package/dist/assets/vendor-virtuoso-B_7lc2Ot.js +1 -0
- package/dist/assets/vennDiagram-DHZGUBPP-DYjGtMA5.js +1 -0
- package/dist/assets/{wardley-RL74JXVD-CvCX-J_r.js → wardley-RL74JXVD-Djh5alV9.js} +1 -1
- package/dist/assets/wardleyDiagram-NUSXRM2D-al50Jlxp.js +1 -0
- package/dist/assets/xychartDiagram-5P7HB3ND-Bl969-3U.js +1 -0
- package/dist/index.html +5 -4
- package/package.json +1 -1
- package/server/lib/code-search.js +82 -139
- package/server/lib/ensure-hooks.js +62 -5
- package/server/lib/launch-config.js +31 -0
- package/server/lib/search-worker.js +214 -0
- package/server/lib/session-start-bridge.js +5 -1
- package/server/lib/task-bridge.js +136 -0
- package/server/lib/task-state.js +150 -0
- package/server/lib/v2/convert.js +9 -2
- package/server/pty-manager.js +8 -2
- package/server/routes/events.js +56 -0
- package/server/server.js +61 -0
- package/dist/assets/MdxEditorPanel-fhSbMV1k.js +0 -1
- package/dist/assets/architectureDiagram-Q4EWVU46-hxmrC4g0.js +0 -1
- package/dist/assets/blockDiagram-DXYQGD6D-D3Ie-HJv.js +0 -1
- package/dist/assets/c4Diagram-AHTNJAMY-Bqi7HUr9.js +0 -1
- package/dist/assets/classDiagram-6PBFFD2Q-DiDwaKTt.js +0 -1
- package/dist/assets/classDiagram-v2-HSJHXN6E-DiDwaKTt.js +0 -1
- package/dist/assets/clone-N9s0k-Pj.js +0 -1
- package/dist/assets/cose-bilkent-S5V4N54A-Cuw7G_qy.js +0 -1
- package/dist/assets/dagre-KV5264BT-qqKh51pl.js +0 -1
- package/dist/assets/diagram-5BDNPKRD-B-pBCkaj.js +0 -1
- package/dist/assets/diagram-G4DWMVQ6-sdTDQV0t.js +0 -1
- package/dist/assets/diagram-MMDJMWI5-CelfzJxz.js +0 -1
- package/dist/assets/diagram-TYMM5635-z0RlpFuK.js +0 -1
- package/dist/assets/erDiagram-SMLLAGMA-BHI2bnGz.js +0 -1
- package/dist/assets/flowDiagram-DWJPFMVM-I1SWP3XA.js +0 -1
- package/dist/assets/ganttDiagram-T4ZO3ILL-DZh82zoq.js +0 -1
- package/dist/assets/gitGraphDiagram-UUTBAWPF-DsMWEHvH.js +0 -1
- package/dist/assets/index-CGG82Lfj.js +0 -1
- package/dist/assets/index-CiJgRlSn.js +0 -1
- package/dist/assets/index-Dn7Vc5py.js +0 -1
- package/dist/assets/index-DnekML0c.js +0 -1
- package/dist/assets/index-Uhg6tgk4.js +0 -2
- package/dist/assets/index-VFaPBr79.js +0 -1
- package/dist/assets/index-_nQUY-oI.js +0 -1
- package/dist/assets/index-s7YuKwmu.js +0 -1
- package/dist/assets/infoDiagram-42DDH7IO-DBi-2oXp.js +0 -1
- package/dist/assets/ishikawaDiagram-UXIWVN3A-fIVocwqv.js +0 -1
- package/dist/assets/journeyDiagram-VCZTEJTY-CTSi1qOI.js +0 -1
- package/dist/assets/kanban-definition-6JOO6SKY-U8kfIi3w.js +0 -1
- package/dist/assets/mindmap-definition-QFDTVHPH-CCrRqC11.js +0 -1
- package/dist/assets/pieDiagram-DEJITSTG-BrMSbuT1.js +0 -1
- package/dist/assets/quadrantDiagram-34T5L4WZ-3K-JFsjs.js +0 -1
- package/dist/assets/requirementDiagram-MS252O5E-CiqMG6uM.js +0 -1
- package/dist/assets/sankeyDiagram-XADWPNL6-CM98y9LX.js +0 -1
- package/dist/assets/seqResourceLoaders-C9ezIN-N.js +0 -2
- package/dist/assets/sequenceDiagram-FGHM5R23-C4x_1BvX.js +0 -1
- package/dist/assets/stateDiagram-FHFEXIEX-DyPisIEy.js +0 -1
- package/dist/assets/stateDiagram-v2-QKLJ7IA2-1n69gYPg.js +0 -1
- package/dist/assets/timeline-definition-GMOUNBTQ-CRnoneDr.js +0 -1
- package/dist/assets/vendor-codemirror-Clv6kvI5.js +0 -1
- package/dist/assets/vendor-mdxeditor-CtujsSUV.js +0 -2
- package/dist/assets/vendor-virtuoso-DsaYo4Fi.js +0 -1
- package/dist/assets/vennDiagram-DHZGUBPP-JQY_eM5i.js +0 -1
- package/dist/assets/wardleyDiagram-NUSXRM2D-C1ZrJXnG.js +0 -1
- package/dist/assets/xychartDiagram-5P7HB3ND-hR1VN6u6.js +0 -1
package/server/routes/events.js
CHANGED
|
@@ -90,6 +90,54 @@ function sessionStartNotify(req, res, parsedUrl, isLocal, deps) {
|
|
|
90
90
|
}
|
|
91
91
|
try { deps.onSessionStartNotify(payload); }
|
|
92
92
|
catch (err) { reportSwallowed('session-start-notify.dispatch', err); }
|
|
93
|
+
// Task-checklist boundary: reset on main-agent startup/clear, skipped for
|
|
94
|
+
// subagent events (payload.agentId). Separate deps callback so it is never
|
|
95
|
+
// swallowed by markSessionStart's source early-return.
|
|
96
|
+
try { deps.onTaskSessionBoundary?.(payload); }
|
|
97
|
+
catch (err) { reportSwallowed('task-session-boundary', err); }
|
|
98
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
99
|
+
res.end(JSON.stringify({ ok: true }));
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Task-event hook notify (task-bridge.js): TaskCreated / TaskCompleted /
|
|
104
|
+
// PostToolUse(TaskUpdate) → the task-checklist reducer. Same security shape
|
|
105
|
+
// as sessionStartNotify (loopback-only + internal token + 16KB cap); the
|
|
106
|
+
// state update + debounced SSE broadcast live behind deps.onTaskEvent
|
|
107
|
+
// (server.js → lib/task-state.js).
|
|
108
|
+
function taskEventNotify(req, res, parsedUrl, isLocal, deps) {
|
|
109
|
+
if (!isLocal) {
|
|
110
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
111
|
+
res.end(JSON.stringify({ error: 'Loopback only' }));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (req.headers['x-ccviewer-internal'] !== deps.INTERNAL_TOKEN) {
|
|
115
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
116
|
+
res.end(JSON.stringify({ error: 'Invalid bridge token' }));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
let body = '';
|
|
120
|
+
let truncated = false;
|
|
121
|
+
req.on('data', chunk => {
|
|
122
|
+
body += chunk;
|
|
123
|
+
if (body.length > 16384) { truncated = true; req.destroy(); }
|
|
124
|
+
});
|
|
125
|
+
req.on('end', () => {
|
|
126
|
+
if (truncated) {
|
|
127
|
+
console.warn('[task-event] body exceeded 16KB cap — request destroyed');
|
|
128
|
+
return; // socket already closed by destroy()
|
|
129
|
+
}
|
|
130
|
+
let payload = {};
|
|
131
|
+
let badJson = false;
|
|
132
|
+
try { payload = body ? JSON.parse(body) : {}; }
|
|
133
|
+
catch { badJson = true; console.warn('[task-event] malformed JSON body'); }
|
|
134
|
+
if (badJson) {
|
|
135
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
136
|
+
res.end(JSON.stringify({ error: 'malformed JSON body' }));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
try { deps.onTaskEvent?.(payload); }
|
|
140
|
+
catch (err) { reportSwallowed('task-event.dispatch', err); }
|
|
93
141
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
94
142
|
res.end(JSON.stringify({ ok: true }));
|
|
95
143
|
});
|
|
@@ -362,6 +410,13 @@ async function events(req, res, parsedUrl, isLocal, deps) {
|
|
|
362
410
|
// 这样 watcher 的 sendToClients 不会在 load 阶段向该客户端推送 live entry。
|
|
363
411
|
deps.clients.push(res);
|
|
364
412
|
|
|
413
|
+
// 任务清单快照补推:内存态不在冷加载数据里,页面刷新/重连后横条要等下一次
|
|
414
|
+
// 任务事件才恢复 —— 连接建立即推一份当前快照(空列表也推,清掉客户端残留)。
|
|
415
|
+
try {
|
|
416
|
+
const snap = deps.getTaskSnapshot?.();
|
|
417
|
+
if (snap) sseWrite(res, `event: task_update\ndata: ${JSON.stringify({ sessionId: snap.sessionId, tasks: snap.tasks, ts: Date.now() })}\n\n`);
|
|
418
|
+
} catch (err) { reportSwallowed('sse.task_update.snapshot', err); }
|
|
419
|
+
|
|
365
420
|
// req.on('close') 在某些异常断连时不一定立即触发;res 端 close/error 兜底保证
|
|
366
421
|
// 不会在 clients 数组里留下幽灵 res,防止 sendToClients 后续写入触发慢泄漏。
|
|
367
422
|
const removeFromClients = () => {
|
|
@@ -402,6 +457,7 @@ async function requests(req, res) {
|
|
|
402
457
|
export const eventsRoutes = [
|
|
403
458
|
{ method: 'POST', match: 'exact', path: '/api/turn-end-notify', handler: turnEndNotify },
|
|
404
459
|
{ method: 'POST', match: 'exact', path: '/api/session-start-notify', handler: sessionStartNotify },
|
|
460
|
+
{ method: 'POST', match: 'exact', path: '/api/task-event', handler: taskEventNotify },
|
|
405
461
|
{ method: 'GET', match: 'exact', path: '/events', handler: events },
|
|
406
462
|
{ method: 'GET', match: 'exact', path: '/api/requests', handler: requests },
|
|
407
463
|
];
|
package/server/server.js
CHANGED
|
@@ -100,6 +100,7 @@ import { checkAndUpdate } from './lib/updater.js';
|
|
|
100
100
|
import { loadPlugins, runWaterfallHook, runParallelHook } from './lib/plugin-loader.js';
|
|
101
101
|
import { CONTEXT_WINDOW_FILE, readModelContextSize } from './lib/context-watcher.js';
|
|
102
102
|
import { sendEventToClients } from './lib/log-watcher.js';
|
|
103
|
+
import { applyTaskEvent, resetTasks, getTaskSnapshot, shouldResetTasks } from './lib/task-state.js';
|
|
103
104
|
import { createImLogWatcher } from './lib/im/im-log-watcher.js';
|
|
104
105
|
import { unwatchAllWorkflows } from './lib/workflow-watcher.js';
|
|
105
106
|
import { backupConfigs } from './lib/config-backup.js';
|
|
@@ -599,6 +600,26 @@ const deps = {
|
|
|
599
600
|
// SessionStart hook notify → conversation-switch signal (in-terminal
|
|
600
601
|
// /resume). The source gate + V2Writer re-bind live in the interceptor.
|
|
601
602
|
onSessionStartNotify: markSessionStart,
|
|
603
|
+
// Task checklist (task-bridge.js → /api/task-event): apply to the shared
|
|
604
|
+
// in-memory reducer, then debounce-broadcast a full snapshot over SSE.
|
|
605
|
+
onTaskEvent: (payload) => {
|
|
606
|
+
try {
|
|
607
|
+
applyTaskEvent(payload);
|
|
608
|
+
_scheduleTaskUpdateBroadcast();
|
|
609
|
+
} catch (err) { reportSwallowed('task-state.apply', err); }
|
|
610
|
+
},
|
|
611
|
+
// Session-boundary reset for the task checklist. The gate itself lives in
|
|
612
|
+
// task-state.shouldResetTasks (pure, unit-tested): main-agent startup/clear
|
|
613
|
+
// resets; resume/fork to a different session resets; subagent/teammate
|
|
614
|
+
// events (payload.agentId) must not wipe the shared list.
|
|
615
|
+
onTaskSessionBoundary: (payload) => {
|
|
616
|
+
if (!shouldResetTasks(payload, getTaskSnapshot().sessionId)) return;
|
|
617
|
+
resetTasks();
|
|
618
|
+
_emitTaskUpdate();
|
|
619
|
+
},
|
|
620
|
+
// Per-connection snapshot replay for fresh SSE clients (page refresh /
|
|
621
|
+
// reconnect) — the checklist lives only in memory, not in the cold load.
|
|
622
|
+
getTaskSnapshot,
|
|
602
623
|
ensureImWatch: _ensureImWatch,
|
|
603
624
|
maskProfiles: _maskProfiles,
|
|
604
625
|
maskApiKey: _maskApiKey,
|
|
@@ -2296,6 +2317,36 @@ function _scheduleTurnEndBroadcast(sessionId, ts, transcriptPath = null) {
|
|
|
2296
2317
|
_pendingTurnEndTimers.set(sid, { timer, ts: t });
|
|
2297
2318
|
}
|
|
2298
2319
|
|
|
2320
|
+
// Task-checklist broadcast (task-bridge.js → /api/task-event → deps.onTaskEvent).
|
|
2321
|
+
// Full-snapshot semantics (never deltas): the payload is the whole current
|
|
2322
|
+
// checklist, so bursts and lost frames self-heal on the next event. 120 ms
|
|
2323
|
+
// trailing debounce coalesces multi-task flips (e.g. a batch TaskCreate turn)
|
|
2324
|
+
// into one SSE frame.
|
|
2325
|
+
const TASK_UPDATE_DEBOUNCE_MS = 120;
|
|
2326
|
+
let _taskBroadcastTimer = null;
|
|
2327
|
+
|
|
2328
|
+
function _emitTaskUpdate() {
|
|
2329
|
+
if (clients.length === 0 || !sendEventToClients) return;
|
|
2330
|
+
// Parity with _emitTurnEnd: a broadcast failure must never surface as an
|
|
2331
|
+
// uncaught exception from the debounce timer.
|
|
2332
|
+
try {
|
|
2333
|
+
const snap = getTaskSnapshot();
|
|
2334
|
+
sendEventToClients(clients, 'task_update', { sessionId: snap.sessionId, tasks: snap.tasks, ts: Date.now() });
|
|
2335
|
+
} catch (err) {
|
|
2336
|
+
console.warn('[task-update] broadcast failed:', err && err.message);
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
function _scheduleTaskUpdateBroadcast() {
|
|
2341
|
+
if (_isStopping) return;
|
|
2342
|
+
if (_taskBroadcastTimer) clearTimeout(_taskBroadcastTimer);
|
|
2343
|
+
_taskBroadcastTimer = setTimeout(() => {
|
|
2344
|
+
_taskBroadcastTimer = null;
|
|
2345
|
+
_emitTaskUpdate();
|
|
2346
|
+
}, TASK_UPDATE_DEBOUNCE_MS);
|
|
2347
|
+
if (typeof _taskBroadcastTimer.unref === 'function') _taskBroadcastTimer.unref();
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2299
2350
|
// 直接丢弃所有 pending —— 用于两条路径:(1) `_doStop` shutdown,(2) rising-edge 新请求
|
|
2300
2351
|
// 进入(按用户原始语义不算「真任务结束」,不播放)。
|
|
2301
2352
|
function _cancelAllPendingTurnEndBroadcasts() {
|
|
@@ -2471,6 +2522,16 @@ async function _doStop() {
|
|
|
2471
2522
|
clearTimeout(_updateCheckTimer);
|
|
2472
2523
|
_updateCheckTimer = null;
|
|
2473
2524
|
}
|
|
2525
|
+
// Task-checklist teardown: symmetric with _cancelAllPendingTurnEndBroadcasts.
|
|
2526
|
+
// The debounce timer is unref'd and post-stop emits are no-ops (clients is
|
|
2527
|
+
// empty), but the module-level checklist itself must not leak into the next
|
|
2528
|
+
// stop/start cycle — a client connecting before the new session's startup
|
|
2529
|
+
// boundary would otherwise get the PREVIOUS session's snapshot.
|
|
2530
|
+
if (_taskBroadcastTimer) {
|
|
2531
|
+
clearTimeout(_taskBroadcastTimer);
|
|
2532
|
+
_taskBroadcastTimer = null;
|
|
2533
|
+
}
|
|
2534
|
+
resetTasks();
|
|
2474
2535
|
resetStreamingState();
|
|
2475
2536
|
// 清 interceptor 的 live-port,避免 stop/start 循环(Electron tab 切换 / 测试)间隙内
|
|
2476
2537
|
// 早期请求向已关闭的端口 POST 丢包。新 startViewer 的 listen 回调会再次 setLivePort
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{j as jsxRuntimeExports}from"./vendor-codemirror-Clv6kvI5.js";import{a as reactExports,s as staticMethods}from"./vendor-antd-CSjy2pdD.js";import{M as MDXEditor,h as headingsPlugin,l as listsPlugin,q as quotePlugin,a as linkPlugin,b as linkDialogPlugin,i as imagePlugin,t as tablePlugin,c as codeBlockPlugin,d as codeMirrorPlugin,e as thematicBreakPlugin,m as markdownShortcutPlugin,f as diffSourcePlugin,g as toolbarPlugin,D as DiffSourceToggleWrapper,U as UndoRedo,S as Separator,B as BoldItalicUnderlineToggles,C as CodeToggle,j as BlockTypeSelect,L as ListsToggle,k as CreateLink,I as InsertImage,n as InsertTable,o as InsertCodeBlock,p as InsertThematicBreak}from"./vendor-mdxeditor-CtujsSUV.js";import{g as getLang,t}from"./index-Uhg6tgk4.js";const styles={container:"_container_odc2w_25",light:"_light_odc2w_3",contentEditable:"_contentEditable_odc2w_16"},PASSTHROUGH_TYPES=new Set(["image/png","image/gif","image/webp","image/svg+xml"]);function readAsDataURL(file){return new Promise((resolve,reject)=>{const reader=new FileReader;reader.onload=()=>resolve(reader.result),reader.onerror=()=>reject(new Error("FileReader failed")),reader.readAsDataURL(file)})}async function compressImageToDataURL(file,opts={}){if(!(file instanceof Blob))throw new Error("compressImageToDataURL: input must be a File or Blob");if(!file.type||!file.type.startsWith("image/"))throw new Error(`Unsupported file type: ${file.type||"unknown"}`);if(file.size>10485760)throw new Error(`Image too large: ${(file.size/1024/1024).toFixed(1)}MB > 10MB limit`);const maxEdge=opts.maxEdge??2e3,quality=opts.quality??.85;if(PASSTHROUGH_TYPES.has(file.type))return await readAsDataURL(file);const originalDataURL=await readAsDataURL(file),img=await(src=originalDataURL,new Promise((resolve,reject)=>{const img=new Image;img.onload=()=>resolve(img),img.onerror=()=>reject(new Error("Image decode failed")),img.src=src}));var src;const longestEdge=Math.max(img.naturalWidth,img.naturalHeight),scale=longestEdge>maxEdge?maxEdge/longestEdge:1,targetW=Math.max(1,Math.round(img.naturalWidth*scale)),targetH=Math.max(1,Math.round(img.naturalHeight*scale)),canvas=document.createElement("canvas");canvas.width=targetW,canvas.height=targetH;const ctx=canvas.getContext("2d");if(!ctx)return originalDataURL;let compressed;ctx.drawImage(img,0,0,targetW,targetH);try{compressed=canvas.toDataURL("image/jpeg",quality)}catch{return originalDataURL}return!compressed||"data:,"===compressed||compressed.length>=originalDataURL.length?originalDataURL:compressed}const TRANSLATIONS={zh:{contentArea:{editableMarkdown:"可编辑 Markdown"},dialog:{close:"关闭"},dialogControls:{cancel:"取消",save:"保存"},createLink:{text:"链接文字",textTooltip:"链接显示的文字",title:"标题",titleTooltip:"链接的 title 属性(鼠标悬停时显示)",url:"链接地址",urlPlaceholder:"请输入链接地址",saveTooltip:"保存链接",cancelTooltip:"取消编辑"},linkPreview:{open:"在新窗口打开 {{url}}",edit:"编辑链接",copyToClipboard:"复制链接到剪贴板",copied:"已复制",remove:"移除链接"},uploadImage:{dialogTitle:"插入图片",uploadInstructions:"从本地选择图片上传",addViaUrlInstructions:"或输入图片地址",addViaUrlInstructionsNoUpload:"请输入图片地址",autoCompletePlaceholder:"搜索已有图片",alt:"替代文字",title:"标题",width:"宽度",height:"高度"},imageEditor:{editImage:"编辑图片",deleteImage:"删除图片"},table:{columnMenu:"列菜单",rowMenu:"行菜单",textAlignment:"文字对齐",alignLeft:"左对齐",alignCenter:"居中",alignRight:"右对齐",insertColumnLeft:"在左侧插入列",insertColumnRight:"在右侧插入列",insertRowAbove:"在上方插入行",insertRowBelow:"在下方插入行",deleteColumn:"删除列",deleteRow:"删除行",deleteTable:"删除表格"},codeBlock:{language:"语言",inlineLanguage:"行内语言",selectLanguage:"选择语言"},codeblock:{delete:"删除代码块"},toolbar:{undo:"撤销 {{shortcut}}",redo:"重做 {{shortcut}}",bold:"加粗",italic:"斜体",underline:"下划线",removeBold:"取消加粗",removeItalic:"取消斜体",removeUnderline:"取消下划线",inlineCode:"行内代码",removeInlineCode:"取消行内代码",bulletedList:"无序列表",numberedList:"有序列表",checkList:"任务列表",toggleGroup:"列表样式",link:"插入链接",image:"插入图片",table:"插入表格",codeBlock:"插入代码块",thematicBreak:"插入分隔线",richText:"富文本",diffMode:"对比视图",source:"源代码",blockTypeSelect:{placeholder:"块类型",selectBlockTypeTooltip:"选择块类型"},blockTypes:{paragraph:"段落",heading:"标题 {{level}}",quote:"引用"}}},"zh-TW":{contentArea:{editableMarkdown:"可編輯 Markdown"},dialog:{close:"關閉"},dialogControls:{cancel:"取消",save:"儲存"},createLink:{text:"連結文字",textTooltip:"連結顯示的文字",title:"標題",titleTooltip:"連結的 title 屬性(滑鼠懸停時顯示)",url:"連結網址",urlPlaceholder:"請輸入連結網址",saveTooltip:"儲存連結",cancelTooltip:"取消編輯"},linkPreview:{open:"在新視窗開啟 {{url}}",edit:"編輯連結",copyToClipboard:"複製連結至剪貼簿",copied:"已複製",remove:"移除連結"},uploadImage:{dialogTitle:"插入圖片",uploadInstructions:"從本地選擇圖片上傳",addViaUrlInstructions:"或輸入圖片網址",addViaUrlInstructionsNoUpload:"請輸入圖片網址",autoCompletePlaceholder:"搜尋現有圖片",alt:"替代文字",title:"標題",width:"寬度",height:"高度"},imageEditor:{editImage:"編輯圖片",deleteImage:"刪除圖片"},table:{columnMenu:"欄選單",rowMenu:"列選單",textAlignment:"文字對齊",alignLeft:"靠左",alignCenter:"置中",alignRight:"靠右",insertColumnLeft:"在左側插入欄",insertColumnRight:"在右側插入欄",insertRowAbove:"在上方插入列",insertRowBelow:"在下方插入列",deleteColumn:"刪除欄",deleteRow:"刪除列",deleteTable:"刪除表格"},codeBlock:{language:"語言",inlineLanguage:"行內語言",selectLanguage:"選擇語言"},codeblock:{delete:"刪除程式碼區塊"},toolbar:{undo:"復原 {{shortcut}}",redo:"重做 {{shortcut}}",bold:"粗體",italic:"斜體",underline:"底線",removeBold:"取消粗體",removeItalic:"取消斜體",removeUnderline:"取消底線",inlineCode:"行內程式碼",removeInlineCode:"取消行內程式碼",bulletedList:"項目符號清單",numberedList:"編號清單",checkList:"工作清單",toggleGroup:"清單樣式",link:"插入連結",image:"插入圖片",table:"插入表格",codeBlock:"插入程式碼區塊",thematicBreak:"插入分隔線",richText:"所見即所得",diffMode:"比對檢視",source:"原始碼",blockTypeSelect:{placeholder:"區塊類型",selectBlockTypeTooltip:"選擇區塊類型"},blockTypes:{paragraph:"段落",heading:"標題 {{level}}",quote:"引用"}}},ja:{toolbar:{undo:"元に戻す {{shortcut}}",redo:"やり直し {{shortcut}}",bold:"太字",italic:"イタリック",underline:"下線",removeBold:"太字を解除",removeItalic:"イタリックを解除",removeUnderline:"下線を解除",inlineCode:"インラインコード",removeInlineCode:"インラインコードを解除",bulletedList:"箇条書き",numberedList:"番号付きリスト",checkList:"チェックリスト",toggleGroup:"リストスタイル",link:"リンクを挿入",image:"画像を挿入",table:"表を挿入",codeBlock:"コードブロックを挿入",thematicBreak:"区切り線を挿入",richText:"リッチテキスト",diffMode:"差分表示",source:"ソース",blockTypeSelect:{placeholder:"ブロック種別",selectBlockTypeTooltip:"ブロック種別を選択"},blockTypes:{paragraph:"段落",heading:"見出し {{level}}",quote:"引用"}}},ko:{toolbar:{undo:"실행 취소 {{shortcut}}",redo:"다시 실행 {{shortcut}}",bold:"굵게",italic:"기울임",underline:"밑줄",removeBold:"굵게 해제",removeItalic:"기울임 해제",removeUnderline:"밑줄 해제",inlineCode:"인라인 코드",removeInlineCode:"인라인 코드 해제",bulletedList:"글머리 기호 목록",numberedList:"번호 매기기 목록",checkList:"체크리스트",toggleGroup:"목록 스타일",link:"링크 삽입",image:"이미지 삽입",table:"표 삽입",codeBlock:"코드 블록 삽입",thematicBreak:"구분선 삽입",richText:"서식있는 텍스트",diffMode:"비교 보기",source:"소스",blockTypeSelect:{placeholder:"블록 유형",selectBlockTypeTooltip:"블록 유형 선택"},blockTypes:{paragraph:"단락",heading:"제목 {{level}}",quote:"인용"}}},de:{toolbar:{undo:"Rückgängig {{shortcut}}",redo:"Wiederherstellen {{shortcut}}",bold:"Fett",italic:"Kursiv",underline:"Unterstrichen",removeBold:"Fett entfernen",removeItalic:"Kursiv entfernen",removeUnderline:"Unterstrichen entfernen",inlineCode:"Inline-Code",removeInlineCode:"Inline-Code entfernen",bulletedList:"Aufzählungsliste",numberedList:"Nummerierte Liste",checkList:"Aufgabenliste",toggleGroup:"Listenstil",link:"Link einfügen",image:"Bild einfügen",table:"Tabelle einfügen",codeBlock:"Codeblock einfügen",thematicBreak:"Trennlinie einfügen",richText:"Rich-Text",diffMode:"Diff-Ansicht",source:"Quelltext",blockTypeSelect:{placeholder:"Blocktyp",selectBlockTypeTooltip:"Blocktyp auswählen"},blockTypes:{paragraph:"Absatz",heading:"Überschrift {{level}}",quote:"Zitat"}}},es:{toolbar:{undo:"Deshacer {{shortcut}}",redo:"Rehacer {{shortcut}}",bold:"Negrita",italic:"Cursiva",underline:"Subrayado",removeBold:"Quitar negrita",removeItalic:"Quitar cursiva",removeUnderline:"Quitar subrayado",inlineCode:"Código en línea",removeInlineCode:"Quitar código en línea",bulletedList:"Lista con viñetas",numberedList:"Lista numerada",checkList:"Lista de tareas",toggleGroup:"Estilo de lista",link:"Insertar enlace",image:"Insertar imagen",table:"Insertar tabla",codeBlock:"Insertar bloque de código",thematicBreak:"Insertar separador",richText:"Texto enriquecido",diffMode:"Vista comparativa",source:"Código fuente",blockTypeSelect:{placeholder:"Tipo de bloque",selectBlockTypeTooltip:"Seleccionar tipo de bloque"},blockTypes:{paragraph:"Párrafo",heading:"Encabezado {{level}}",quote:"Cita"}}},fr:{toolbar:{undo:"Annuler {{shortcut}}",redo:"Rétablir {{shortcut}}",bold:"Gras",italic:"Italique",underline:"Souligné",removeBold:"Retirer le gras",removeItalic:"Retirer l’italique",removeUnderline:"Retirer le soulignement",inlineCode:"Code en ligne",removeInlineCode:"Retirer le code en ligne",bulletedList:"Liste à puces",numberedList:"Liste numérotée",checkList:"Liste de tâches",toggleGroup:"Style de liste",link:"Insérer un lien",image:"Insérer une image",table:"Insérer un tableau",codeBlock:"Insérer un bloc de code",thematicBreak:"Insérer un séparateur",richText:"Texte enrichi",diffMode:"Vue comparative",source:"Source",blockTypeSelect:{placeholder:"Type de bloc",selectBlockTypeTooltip:"Choisir le type de bloc"},blockTypes:{paragraph:"Paragraphe",heading:"Titre {{level}}",quote:"Citation"}}},it:{toolbar:{undo:"Annulla {{shortcut}}",redo:"Ripristina {{shortcut}}",bold:"Grassetto",italic:"Corsivo",underline:"Sottolineato",removeBold:"Rimuovi grassetto",removeItalic:"Rimuovi corsivo",removeUnderline:"Rimuovi sottolineato",inlineCode:"Codice in linea",removeInlineCode:"Rimuovi codice in linea",bulletedList:"Elenco puntato",numberedList:"Elenco numerato",checkList:"Elenco di attività",toggleGroup:"Stile elenco",link:"Inserisci link",image:"Inserisci immagine",table:"Inserisci tabella",codeBlock:"Inserisci blocco di codice",thematicBreak:"Inserisci separatore",richText:"Testo formattato",diffMode:"Vista differenze",source:"Sorgente",blockTypeSelect:{placeholder:"Tipo di blocco",selectBlockTypeTooltip:"Seleziona tipo di blocco"},blockTypes:{paragraph:"Paragrafo",heading:"Titolo {{level}}",quote:"Citazione"}}},da:{toolbar:{undo:"Fortryd {{shortcut}}",redo:"Gentag {{shortcut}}",bold:"Fed",italic:"Kursiv",underline:"Understreget",removeBold:"Fjern fed",removeItalic:"Fjern kursiv",removeUnderline:"Fjern understregning",inlineCode:"Indlejret kode",removeInlineCode:"Fjern indlejret kode",bulletedList:"Punktopstilling",numberedList:"Nummereret liste",checkList:"Tjekliste",toggleGroup:"Listestil",link:"Indsæt link",image:"Indsæt billede",table:"Indsæt tabel",codeBlock:"Indsæt kodeblok",thematicBreak:"Indsæt skillelinje",richText:"Formateret tekst",diffMode:"Diff-visning",source:"Kilde",blockTypeSelect:{placeholder:"Bloktype",selectBlockTypeTooltip:"Vælg bloktype"},blockTypes:{paragraph:"Afsnit",heading:"Overskrift {{level}}",quote:"Citat"}}},pl:{toolbar:{undo:"Cofnij {{shortcut}}",redo:"Ponów {{shortcut}}",bold:"Pogrubienie",italic:"Kursywa",underline:"Podkreślenie",removeBold:"Usuń pogrubienie",removeItalic:"Usuń kursywę",removeUnderline:"Usuń podkreślenie",inlineCode:"Kod w linii",removeInlineCode:"Usuń kod w linii",bulletedList:"Lista punktowana",numberedList:"Lista numerowana",checkList:"Lista zadań",toggleGroup:"Styl listy",link:"Wstaw link",image:"Wstaw obraz",table:"Wstaw tabelę",codeBlock:"Wstaw blok kodu",thematicBreak:"Wstaw separator",richText:"Tekst sformatowany",diffMode:"Widok porównania",source:"Źródło",blockTypeSelect:{placeholder:"Typ bloku",selectBlockTypeTooltip:"Wybierz typ bloku"},blockTypes:{paragraph:"Akapit",heading:"Nagłówek {{level}}",quote:"Cytat"}}},ru:{toolbar:{undo:"Отменить {{shortcut}}",redo:"Повторить {{shortcut}}",bold:"Полужирный",italic:"Курсив",underline:"Подчёркнутый",removeBold:"Убрать полужирный",removeItalic:"Убрать курсив",removeUnderline:"Убрать подчёркивание",inlineCode:"Встроенный код",removeInlineCode:"Убрать встроенный код",bulletedList:"Маркированный список",numberedList:"Нумерованный список",checkList:"Список задач",toggleGroup:"Стиль списка",link:"Вставить ссылку",image:"Вставить изображение",table:"Вставить таблицу",codeBlock:"Вставить блок кода",thematicBreak:"Вставить разделитель",richText:"Форматированный текст",diffMode:"Вид сравнения",source:"Исходный код",blockTypeSelect:{placeholder:"Тип блока",selectBlockTypeTooltip:"Выбрать тип блока"},blockTypes:{paragraph:"Абзац",heading:"Заголовок {{level}}",quote:"Цитата"}}},ar:{toolbar:{undo:"تراجع {{shortcut}}",redo:"إعادة {{shortcut}}",bold:"عريض",italic:"مائل",underline:"تسطير",removeBold:"إزالة العريض",removeItalic:"إزالة المائل",removeUnderline:"إزالة التسطير",inlineCode:"كود مضمن",removeInlineCode:"إزالة الكود المضمن",bulletedList:"قائمة نقطية",numberedList:"قائمة مرقمة",checkList:"قائمة مهام",toggleGroup:"نمط القائمة",link:"إدراج رابط",image:"إدراج صورة",table:"إدراج جدول",codeBlock:"إدراج كتلة كود",thematicBreak:"إدراج فاصل",richText:"نص منسق",diffMode:"عرض المقارنة",source:"المصدر",blockTypeSelect:{placeholder:"نوع الكتلة",selectBlockTypeTooltip:"اختر نوع الكتلة"},blockTypes:{paragraph:"فقرة",heading:"عنوان {{level}}",quote:"اقتباس"}}},no:{toolbar:{undo:"Angre {{shortcut}}",redo:"Gjør om {{shortcut}}",bold:"Fet",italic:"Kursiv",underline:"Understreket",removeBold:"Fjern fet",removeItalic:"Fjern kursiv",removeUnderline:"Fjern understreking",inlineCode:"Inline-kode",removeInlineCode:"Fjern inline-kode",bulletedList:"Punktliste",numberedList:"Nummerert liste",checkList:"Sjekkliste",toggleGroup:"Listestil",link:"Sett inn lenke",image:"Sett inn bilde",table:"Sett inn tabell",codeBlock:"Sett inn kodeblokk",thematicBreak:"Sett inn skillelinje",richText:"Formatert tekst",diffMode:"Diff-visning",source:"Kilde",blockTypeSelect:{placeholder:"Blokktype",selectBlockTypeTooltip:"Velg blokktype"},blockTypes:{paragraph:"Avsnitt",heading:"Overskrift {{level}}",quote:"Sitat"}}},"pt-BR":{toolbar:{undo:"Desfazer {{shortcut}}",redo:"Refazer {{shortcut}}",bold:"Negrito",italic:"Itálico",underline:"Sublinhado",removeBold:"Remover negrito",removeItalic:"Remover itálico",removeUnderline:"Remover sublinhado",inlineCode:"Código em linha",removeInlineCode:"Remover código em linha",bulletedList:"Lista com marcadores",numberedList:"Lista numerada",checkList:"Lista de tarefas",toggleGroup:"Estilo da lista",link:"Inserir link",image:"Inserir imagem",table:"Inserir tabela",codeBlock:"Inserir bloco de código",thematicBreak:"Inserir separador",richText:"Texto formatado",diffMode:"Visualização de diferenças",source:"Código-fonte",blockTypeSelect:{placeholder:"Tipo de bloco",selectBlockTypeTooltip:"Selecionar tipo de bloco"},blockTypes:{paragraph:"Parágrafo",heading:"Título {{level}}",quote:"Citação"}}},th:{toolbar:{undo:"เลิกทำ {{shortcut}}",redo:"ทำซ้ำ {{shortcut}}",bold:"ตัวหนา",italic:"ตัวเอียง",underline:"ขีดเส้นใต้",removeBold:"ยกเลิกตัวหนา",removeItalic:"ยกเลิกตัวเอียง",removeUnderline:"ยกเลิกขีดเส้นใต้",inlineCode:"โค้ดในบรรทัด",removeInlineCode:"ยกเลิกโค้ดในบรรทัด",bulletedList:"รายการแบบจุด",numberedList:"รายการตัวเลข",checkList:"รายการตรวจสอบ",toggleGroup:"รูปแบบรายการ",link:"แทรกลิงก์",image:"แทรกรูปภาพ",table:"แทรกตาราง",codeBlock:"แทรกบล็อกโค้ด",thematicBreak:"แทรกเส้นคั่น",richText:"ข้อความรูปแบบ",diffMode:"มุมมองเปรียบเทียบ",source:"ซอร์ส",blockTypeSelect:{placeholder:"ประเภทบล็อก",selectBlockTypeTooltip:"เลือกประเภทบล็อก"},blockTypes:{paragraph:"ย่อหน้า",heading:"หัวข้อ {{level}}",quote:"คำพูดอ้างอิง"}}},tr:{toolbar:{undo:"Geri al {{shortcut}}",redo:"Yinele {{shortcut}}",bold:"Kalın",italic:"İtalik",underline:"Altı çizili",removeBold:"Kalını kaldır",removeItalic:"İtaliği kaldır",removeUnderline:"Altı çiziliyi kaldır",inlineCode:"Satır içi kod",removeInlineCode:"Satır içi kodu kaldır",bulletedList:"Madde işaretli liste",numberedList:"Numaralı liste",checkList:"Kontrol listesi",toggleGroup:"Liste stili",link:"Bağlantı ekle",image:"Resim ekle",table:"Tablo ekle",codeBlock:"Kod bloğu ekle",thematicBreak:"Ayraç ekle",richText:"Zengin metin",diffMode:"Karşılaştırma görünümü",source:"Kaynak",blockTypeSelect:{placeholder:"Blok türü",selectBlockTypeTooltip:"Blok türü seç"},blockTypes:{paragraph:"Paragraf",heading:"Başlık {{level}}",quote:"Alıntı"}}},uk:{toolbar:{undo:"Скасувати {{shortcut}}",redo:"Повторити {{shortcut}}",bold:"Жирний",italic:"Курсив",underline:"Підкреслений",removeBold:"Прибрати жирний",removeItalic:"Прибрати курсив",removeUnderline:"Прибрати підкреслення",inlineCode:"Вбудований код",removeInlineCode:"Прибрати вбудований код",bulletedList:"Маркований список",numberedList:"Нумерований список",checkList:"Список завдань",toggleGroup:"Стиль списку",link:"Вставити посилання",image:"Вставити зображення",table:"Вставити таблицю",codeBlock:"Вставити блок коду",thematicBreak:"Вставити роздільник",richText:"Форматований текст",diffMode:"Перегляд порівняння",source:"Джерело",blockTypeSelect:{placeholder:"Тип блоку",selectBlockTypeTooltip:"Виберіть тип блоку"},blockTypes:{paragraph:"Абзац",heading:"Заголовок {{level}}",quote:"Цитата"}}}};function mdxTranslation(key,defaultValue,interpolations){const lang=("function"==typeof getLang?getLang():"en")||"en",langTable=TRANSLATIONS[lang]||TRANSLATIONS[lang.split("-")[0]];return function(template,values){if(!values)return template;let out=template.replace(/\{\{\s*(\w+)\s*\}\}/g,(_,k)=>k in values?String(values[k]):`{{${k}}}`);return out=out.replace(/\{(\w+)\}/g,(_,k)=>k in values?String(values[k]):`{${k}}`),out}((langTable&&function(obj,path){const parts=path.split(".");let cur=obj;for(const p of parts){if(!cur||"object"!=typeof cur||!(p in cur))return;cur=cur[p]}return"string"==typeof cur?cur:void 0}(langTable,key))??defaultValue??key,interpolations)}function getDocTheme(){return"undefined"==typeof document?"dark":"light"===document.documentElement.getAttribute("data-theme")?"light":"dark"}const CODE_BLOCK_LANGUAGES={"":"Plain text",js:"JavaScript",ts:"TypeScript",jsx:"JSX",tsx:"TSX",py:"Python",sh:"Shell",bash:"Bash",json:"JSON",yaml:"YAML",md:"Markdown",html:"HTML",css:"CSS",sql:"SQL",go:"Go",rust:"Rust",java:"Java",cpp:"C++"},MdxEditorPanel=reactExports.forwardRef(function({initialMarkdown:initialMarkdown,onChange:onChange,onError:onError,onParseError:onParseError},ref){const editorRef=reactExports.useRef(null),[theme,setTheme]=reactExports.useState(getDocTheme),lang="function"==typeof getLang?getLang():"en";reactExports.useEffect(()=>{const target=document.documentElement,obs=new MutationObserver(()=>setTheme(getDocTheme()));return obs.observe(target,{attributes:!0,attributeFilter:["data-theme"]}),()=>obs.disconnect()},[]);const imageUploadHandler=reactExports.useCallback(async file=>{try{return await compressImageToDataURL(file,{maxEdge:2e3,quality:.85})}catch(err){const msg=`${t("ui.mdEditor.uploadFailed")}: ${err.message??err}`;try{staticMethods.error(msg)}catch{}throw"function"==typeof onError&&onError(err),err}},[onError]),wrapperRef=reactExports.useRef(null);return reactExports.useImperativeHandle(ref,()=>({getMarkdown:()=>{var _a,_b;return(null==(_b=null==(_a=editorRef.current)?void 0:_a.getMarkdown)?void 0:_b.call(_a))??""},setMarkdown:md=>{var _a,_b;return null==(_b=null==(_a=editorRef.current)?void 0:_a.setMarkdown)?void 0:_b.call(_a,md??"")},focus:()=>{var _a,_b;return null==(_b=null==(_a=editorRef.current)?void 0:_a.focus)?void 0:_b.call(_a)},getScrollEl:()=>{var _a;return(null==(_a=wrapperRef.current)?void 0:_a.querySelector(".mdxeditor-root-contenteditable"))||wrapperRef.current||null}}),[]),jsxRuntimeExports.jsx("div",{ref:wrapperRef,className:`${styles.container} ${"dark"===theme?`dark-theme ${styles.dark}`:styles.light}`,children:jsxRuntimeExports.jsx(MDXEditor,{ref:editorRef,markdown:initialMarkdown??"",onChange:onChange,onError:payload=>{if("function"==typeof onParseError)try{onParseError(payload)}catch{}},translation:mdxTranslation,contentEditableClassName:styles.contentEditable,plugins:[headingsPlugin(),listsPlugin(),quotePlugin(),linkPlugin(),linkDialogPlugin(),imagePlugin({imageUploadHandler:imageUploadHandler}),tablePlugin(),codeBlockPlugin({defaultCodeBlockLanguage:""}),codeMirrorPlugin({codeBlockLanguages:CODE_BLOCK_LANGUAGES}),thematicBreakPlugin(),markdownShortcutPlugin(),diffSourcePlugin({viewMode:"rich-text",diffMarkdown:initialMarkdown??""}),toolbarPlugin({toolbarContents:()=>jsxRuntimeExports.jsxs(DiffSourceToggleWrapper,{children:[jsxRuntimeExports.jsx(UndoRedo,{}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsx(BoldItalicUnderlineToggles,{}),jsxRuntimeExports.jsx(CodeToggle,{}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsx(BlockTypeSelect,{}),jsxRuntimeExports.jsx(ListsToggle,{}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsx(CreateLink,{}),jsxRuntimeExports.jsx(InsertImage,{}),jsxRuntimeExports.jsx(InsertTable,{}),jsxRuntimeExports.jsx(InsertCodeBlock,{}),jsxRuntimeExports.jsx(InsertThematicBreak,{})]})})]},lang)})});export{MdxEditorPanel as default};
|