@aiti-ai/aiti-msg-share 0.0.0-stage → 0.1.8

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.
@@ -0,0 +1,806 @@
1
+ /**
2
+ * aiti-msg-share client — share dialog, target manager and host entry points.
3
+ *
4
+ * Renders via ctx.h and the host's dialogs slot (data-ext-float contract).
5
+ * Other extensions call our service: aiti-msg-share.openShare(payload).
6
+ * QR codes are generated here (browser side) with qrcode — the provider package
7
+ * stops at URL generation.
8
+ */
9
+ import QRCode from "qrcode";
10
+
11
+ const RECENT_KEY = "pi-web:recent-share-targets";
12
+ const API = (path) => `/api/extensions/aiti-msg-share/${path}`;
13
+
14
+ /** i18n lookup via host ctx.t (extman pattern); {param} interpolation. */
15
+ let tFn = null;
16
+ function kindLabel(k) { return shareT("share.kind." + k); }
17
+
18
+ /** Image/binary extension maps — must stay in sync with the server's classifyFile. */
19
+ const IMG_EXT = /\.(png|jpe?g|gif|webp|bmp|svg|ico|avif)$/i;
20
+ const BIN_EXT = /\.(pdf|zip|7z|rar|gz|tgz|tar|bz2|xz|mp3|wav|ogg|flac|mp4|mkv|webm|mov|avi|docx|doc|xlsx|xls|pptx|epub|bin|exe|dmg|iso|apk|psd|woff2?|ttf)$/i;
21
+
22
+ /** Content kind of the pending share: decides which targets are compatible. */
23
+ function contentKind() {
24
+ if (state.kind === "image") return "image";
25
+ if (state.kind === "file" && state.payload?.filePath) {
26
+ const f = state.payload.filePath;
27
+ if (IMG_EXT.test(f)) return "image";
28
+ if (BIN_EXT.test(f)) return "file";
29
+ }
30
+ return "text";
31
+ }
32
+ function supportsKind(t, kind) { return !(t.kinds || []).length || (t.kinds || []).includes(kind); }
33
+ function shareT(key, params) {
34
+ if (!tFn) return key;
35
+ try {
36
+ const raw = tFn(key, params);
37
+ if (!params) return raw;
38
+ return raw.replace(/\{(\w+)\}/g, (_m, k) => String(params[k] ?? ""));
39
+ } catch { return key; }
40
+ }
41
+
42
+ let h = null;
43
+ let ctxRef = null;
44
+ let apiUrlFn = null;
45
+ const state = {
46
+ open: false, manager: false, loading: true,
47
+ targets: [], history: [],
48
+ payload: null, kind: "message", text: "", rawText: "", baseText: "", title: "", tags: "",
49
+ // Which page-context fields get prepended to the shared content (multi-select).
50
+ stamp: { os: true, browser: true, url: false, sessionId: true, sessionName: true },
51
+ targetId: null, meta: {}, redact: true, redactHits: [],
52
+ result: null, busy: false, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", search: "", probe: [],
53
+ editing: null, form: {},
54
+ /** Local favourite sinks (share-sink topic): { ok, message, action } of the last run. */
55
+ sinkResult: null, sinkBusy: "",
56
+ };
57
+ const listeners = new Set();
58
+
59
+ /** Host locale: window.__PI_LOCALE__ is set by the host layout ("en" | "zh-CN"/"zh-*"). */
60
+ function locale() {
61
+ try { return (typeof window !== "undefined" && String(window.__PI_LOCALE__ || "").startsWith("zh")) ? "zh" : "en"; }
62
+ catch { return "en"; }
63
+ }
64
+ /** Bilingual catalog data: note may be a {zh,en} pair (remote overlay) or a plain string. */
65
+ function noteText(note) {
66
+ if (!note) return "";
67
+ if (typeof note === "object") return String(note[locale()] || note.zh || note.en || "").trim();
68
+ return String(note);
69
+ }
70
+
71
+ function api(path) {
72
+ // Use the host's apiUrl() (basePath-aware, /dev-safe) when available; fall back
73
+ // to the absolute extension API path otherwise.
74
+ return apiUrlFn ? apiUrlFn(`/api/extensions/aiti-msg-share/${path}`) : API(path);
75
+ }
76
+ async function getJSON(path, opts) {
77
+ let r, data;
78
+ try {
79
+ r = await fetch(api(path), opts);
80
+ } catch (e) {
81
+ const err = new Error(`无法连接 pi-web 服务:${e?.message || e}`);
82
+ err.detail = String(e?.message || e);
83
+ throw err;
84
+ }
85
+ data = await r.json().catch(() => ({}));
86
+ if (!r.ok || data.ok === false) {
87
+ const err = new Error(data.error || `HTTP ${r.status} (${api(path)})`);
88
+ err.detail = data.detail || `${r.status} ${api(path)}`;
89
+ err.kind = data.errorCode || data.errorKind;
90
+ err.targetId = data.errorTarget;
91
+ err.providerLabel = data.providerLabel;
92
+ throw err;
93
+ }
94
+ return data;
95
+ }
96
+
97
+ function recentGet() {
98
+ try { return JSON.parse(window.localStorage.getItem(RECENT_KEY) || "[]"); } catch { return []; }
99
+ }
100
+ function recentAdd(id) {
101
+ if (!id) return;
102
+ const next = [id, ...recentGet().filter((x) => x !== id)].slice(0, 10);
103
+ try { window.localStorage.setItem(RECENT_KEY, JSON.stringify(next)); } catch {}
104
+ }
105
+ function recentClear() { try { window.localStorage.removeItem(RECENT_KEY); } catch {} }
106
+
107
+ function set(partial) { Object.assign(state, partial); emit(); }
108
+
109
+ /** Pick a target for the pending share and return to the share dialog. */
110
+ function chooseTarget(id) {
111
+ recentAdd(id);
112
+ set({ targetId: id, manager: false, editing: null, error: "", errorDetail: "" });
113
+ }
114
+ function emit() { listeners.forEach((fn) => fn()); }
115
+
116
+ // Content-kind labels resolved via shareT() at render time; status uses icons only.
117
+ const STATUS_ICONS = { recent: "🕘", recommended: "★", dead: "⚠", legacy: "⚠" };
118
+ const CFG_BADGE = {
119
+ anonymous: { icon: "🟢", key: "share.cfg.anonymous", color: "var(--accent, #4d8dff)" },
120
+ ready: { icon: "✓", key: "share.cfg.ready", color: "var(--accent, #4d8dff)" },
121
+ "needs-setup": { icon: "🟠", key: "share.cfg.needs", color: "#d9a13c" },
122
+ dead: { icon: "💀", key: "share.cfg.dead", color: "var(--text-muted, #8b909b)" },
123
+ };
124
+
125
+ const ICONS = {
126
+ share: '<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.6" y1="10.5" x2="15.4" y2="6.5"/><line x1="8.6" y1="13.5" x2="15.4" y2="17.5"/>',
127
+ close: '<path d="M18 6 6 18M6 6l12 12"/>',
128
+ gear: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1-2.8 2.8-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.6V21h-4v-.1A1.7 1.7 0 0 0 8.9 19a1.7 1.7 0 0 0-1.9.3l-.1.1L4.1 16.6l.1-.1a1.7 1.7 0 0 0 .3-1.9A1.7 1.7 0 0 0 3 13.5H3v-3h.1a1.7 1.7 0 0 0 1.6-1 1.7 1.7 0 0 0-.3-1.9L4.3 7.5 7.1 4.7l.1.1a1.7 1.7 0 0 0 1.9.3h.1a1.7 1.7 0 0 0 1-1.6V3h4v.1a1.7 1.7 0 0 0 1 1.6 1.7 1.7 0 0 0 1.9-.3l.1-.1 2.8 2.8-.1.1a1.7 1.7 0 0 0-.3 1.9v.1a1.7 1.7 0 0 0 1.6 1H21v4h-.1a1.7 1.7 0 0 0-1.6 1z"/>',
129
+ };
130
+
131
+ function icon(name, size = 13) {
132
+ const markup = ICONS[name];
133
+ if (!markup) return null;
134
+ // The glyphs mix circles/lines/paths, so the markup must land in the DOM as
135
+ //-is (a single <path d> wrapper would render nothing — that was the bug that
136
+ // made the share icon invisible on the message buttons).
137
+ return h("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
138
+ strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true",
139
+ dangerouslySetInnerHTML: { __html: markup } });
140
+ }
141
+
142
+ // Share icon handed to topic consumers (session-manager more-menu, editor
143
+ // toolbars, msg-smart popover): { svg } = inner markup of a 24×24 line icon,
144
+ // the same form manifest declarative icons use; consumers without {svg}
145
+ // support ignore it and keep their text label.
146
+ const SHARE_ICON = { svg: ICONS.share };
147
+
148
+ function btn(label, onClick, opts = {}) {
149
+ return h("button", {
150
+ type: "button", onClick,
151
+ title: opts.title || label,
152
+ style: { border: "1px solid " + (opts.primary ? "var(--accent, #4d8dff)" : "var(--border, #34363c)"),
153
+ background: opts.primary ? "var(--accent, #4d8dff)" : "var(--bg-hover, #25272c)", color: opts.primary ? "#fff" : "var(--text, #d8dade)",
154
+ borderRadius: 7, padding: "5px 12px", fontSize: 12, cursor: "pointer", opacity: opts.disabled ? 0.5 : 1 },
155
+ disabled: opts.disabled,
156
+ }, label);
157
+ }
158
+
159
+ /** Open the share dialog with a payload (also the cross-extension service). */
160
+ function openShare(payload = {}) {
161
+ const kind = payload.kind || "message";
162
+ const raw = payload.text || "";
163
+ primeSinks();
164
+ set({ open: true, manager: false, payload, kind,
165
+ text: raw, rawText: raw, baseText: raw, title: payload.title || "",
166
+ tags: payload.tags || "", targetId: payload.targetId || null,
167
+ result: null, error: "", errorDetail: "", errorCode: "", errorTarget: "", errorProvider: "", redact: true, redactHits: [],
168
+ sinkResult: null, sinkBusy: "" });
169
+ void refresh();
170
+ // Compose from scratch so the page-info stamp reflects this dialog's context.
171
+ void refreshPreview();
172
+ return true;
173
+ }
174
+
175
+ async function refresh(force = false) {
176
+ set({ loading: true });
177
+ try {
178
+ const [catalog, history, probe] = await Promise.all([
179
+ getJSON("catalog"), getJSON("history"), getJSON("probe", { method: "POST" }).catch(() => ({ services: [] })),
180
+ ]);
181
+ const targets = catalog.targets || [];
182
+ set({ targets, history: history.items || [], probe: probe.services || [], loading: false,
183
+ targetId: state.targetId || targets.find((t) => t.recommended)?.id || targets[0]?.id });
184
+ if (force) await getJSON("refresh", { method: "POST" }).catch(() => {});
185
+ } catch (e) { set({ loading: false, error: e.message, errorDetail: e.detail || "catalog/history" }); }
186
+ }
187
+
188
+ function targetCard(target, selected, badge) {
189
+ const disabled = target.status === "dead" || target.enabled === false;
190
+ return h("button", { type: "button", key: target.id, disabled,
191
+ onClick: () => set({ targetId: target.id, error: "" }),
192
+ title: noteText(target.note) || target.name,
193
+ style: { display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 9px",
194
+ border: "1px solid " + (selected ? "var(--accent, #4d8dff)" : "var(--border, #34363c)"), borderRadius: 8,
195
+ background: selected ? "rgba(77, 141, 255, 0.15)" : "var(--bg-hover, #25272c)", color: disabled ? "var(--text-muted, #8b909b)" : "var(--text, #d8dade)",
196
+ fontSize: 12, cursor: "pointer", opacity: disabled ? 0.45 : 1 } },
197
+ h("span", null, STATUS_ICONS[badge] || "🔗"),
198
+ target.name || target.id,
199
+ ...(target.kinds?.length ? [h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 10 } },
200
+ target.kinds.map(kindLabel).join("/"))] : []),
201
+ ...(() => { const b = CFG_BADGE[target.configState]; return b
202
+ ? [h("span", { title: shareT(b.key), style: { fontSize: 10 } }, b.icon)] : []; })());
203
+ }
204
+
205
+ /**
206
+ * Local "favourite" sinks — the second, semantically different provider family.
207
+ *
208
+ * Contract (owned here): other extensions publish to the `share-sink` topic:
209
+ * { id, order?, label, icon? { svg }, accepts?(payload), save(payload) → { ok, message?, action?: { label, run } } }
210
+ * Sinks store locally (no upload, no URL, no redaction) — unlike content-share *target*
211
+ * providers, which are upload destinations. payload.text is the UNREDACTED body on purpose.
212
+ *
213
+ * A built-in "copy" sink always exists, mirroring mobile share sheets where copy/save sit
214
+ * next to the network targets.
215
+ */
216
+ /** Fixed sink partners shipped with this product (commands + prompt snippets). Lazy clients
217
+ * register their sink only after materializing, so opening the dialog primes them once;
218
+ * any other provider that happens to be loaded is picked up by the topic read anyway. */
219
+ const SINK_PRIME_EXTS = ["aiti-cmd", "aiti-prompts"];
220
+ let sunkPrimed = false;
221
+ function primeSinks() {
222
+ if (sunkPrimed) return;
223
+ sunkPrimed = true;
224
+ const ensure = ctxRef?.ensureMaterialized;
225
+ if (typeof ensure !== "function") return;
226
+ for (const id of SINK_PRIME_EXTS) {
227
+ try { Promise.resolve(ensure(id)).then(() => emit()).catch(() => {}); } catch (e) { /* ignore */ }
228
+ }
229
+ }
230
+
231
+ function sinkItems() {
232
+ const items = [];
233
+ items.push({
234
+ id: "copy", order: -1000, builtin: true,
235
+ get label() { return shareT("share.sink.copy"); },
236
+ icon: { svg: '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>' },
237
+ run: async () => {
238
+ try { await navigator.clipboard.writeText(state.text); return { ok: true, message: shareT("share.sink.copied") }; }
239
+ catch (e) { return { ok: false, message: String((e && e.message) || e) }; }
240
+ },
241
+ });
242
+ try {
243
+ for (const it of (ctxRef?.getTopicItems?.("share-sink") || [])) if (it && it.id) items.push(it);
244
+ } catch (e) { /* topic registry absent (old host) — copy only */ }
245
+ return items.sort((a, b) => (Number(a.order) || 100) - (Number(b.order) || 100));
246
+ }
247
+
248
+ /** Strip the "page info" stamp block (leading `> **Label**: value` lines) from a body. */
249
+ function stripStamp(text) {
250
+ const lines = String(text || "").split("\n");
251
+ let i = 0;
252
+ while (i < lines.length && /^>\s*\*\*[^*]+\*\*\s*:/.test(lines[i])) i++;
253
+ return lines.slice(i).join("\n").trim();
254
+ }
255
+
256
+ /** Sink payload: original body (unredacted, page-info stamp removed) + share metadata. */
257
+ function sinkPayload() {
258
+ // baseText is the unredacted body; when it is empty the textarea content is the only source
259
+ // (e.g. a session share fills the body server-side, so the preview holds the stamp only).
260
+ // Either way the stamp is metadata for external sharing — never part of a local favourite.
261
+ const raw = (typeof state.baseText === "string" && state.baseText.length) ? state.baseText : state.text;
262
+ return { ...(state.payload || {}), kind: state.kind, text: stripStamp(raw), title: state.title, tags: state.tags };
263
+ }
264
+
265
+ async function runSink(item) {
266
+ if (state.sinkBusy) return;
267
+ const payload = sinkPayload();
268
+ if (!item.builtin && typeof item.accepts === "function") {
269
+ let ok = false;
270
+ try { ok = !!item.accepts(payload); } catch (e) { ok = false; }
271
+ if (!ok) {
272
+ const empty = !String(payload.text || "").trim();
273
+ set({ sinkResult: { ok: false, message: empty ? shareT("share.sink.empty") : shareT("share.sink.unsupported") } });
274
+ return;
275
+ }
276
+ }
277
+ set({ sinkBusy: item.id, sinkResult: null });
278
+ try {
279
+ const r = item.builtin ? await item.run(payload) : await item.save(payload);
280
+ set({ sinkBusy: "", sinkResult: r || { ok: true } });
281
+ } catch (e) {
282
+ set({ sinkBusy: "", sinkResult: { ok: false, message: String((e && e.message) || e) } });
283
+ }
284
+ }
285
+
286
+ function sinkSection() {
287
+ const items = sinkItems();
288
+ if (!items.length) return null;
289
+ const res = state.sinkResult;
290
+ return h("div", null,
291
+ h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, marginBottom: 5 } }, shareT("share.sinks")),
292
+ h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6 } },
293
+ ...items.map((it) => {
294
+ const label = typeof it.label === "function" ? it.label() : (it.label || it.id);
295
+ const svg = it.icon && it.icon.svg;
296
+ return h("button", {
297
+ type: "button", key: it.id, disabled: !!state.sinkBusy,
298
+ onClick: () => { void runSink(it); },
299
+ title: label,
300
+ style: { display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 9px",
301
+ border: "1px solid var(--border, #34363c)", borderRadius: 8,
302
+ background: "var(--bg-hover, #25272c)", color: "var(--text, #d8dade)",
303
+ fontSize: 12, cursor: state.sinkBusy ? "default" : "pointer", opacity: state.sinkBusy && state.sinkBusy !== it.id ? 0.55 : 1 },
304
+ },
305
+ svg ? h("span", { style: { display: "inline-flex" }, dangerouslySetInnerHTML: { __html: `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${svg}</svg>` } }) : null,
306
+ label,
307
+ state.sinkBusy === it.id ? h("span", { style: { fontSize: 10, opacity: 0.7 } }, "…") : null,
308
+ );
309
+ })),
310
+ res ? h("div", { style: { marginTop: 6, fontSize: 11, display: "flex", alignItems: "center", gap: 8,
311
+ color: res.ok ? "var(--ok, #4ade80)" : "#e05d5d", wordBreak: "break-word" } },
312
+ h("span", null, (res.ok ? "✓ " : "⚠ ") + (res.message || (res.ok ? shareT("share.sink.saved") : ""))),
313
+ res.ok && res.action && typeof res.action.run === "function"
314
+ ? h("button", { type: "button", onClick: () => { try { res.action.run(); } catch (e) {} },
315
+ style: { border: "1px solid var(--accent, #4d8dff)", background: "none", color: "var(--accent, #4d8dff)",
316
+ borderRadius: 6, padding: "1px 8px", fontSize: 11, cursor: "pointer" } }, res.action.label || "→")
317
+ : null) : null);
318
+ }
319
+
320
+ function targetSection() {
321
+ const recent = recentGet();
322
+ const kind = contentKind();
323
+ const compat = (x) => supportsKind(x, kind);
324
+ const t = state.targets;
325
+ const byId = new Map(t.map((x) => [x.id, x]));
326
+ const recentItems = recent.map((id) => byId.get(id)).filter(Boolean).filter(compat).slice(0, 5);
327
+ // Targets the user has configured (saved) are always visible here.
328
+ const mine = t.filter((x) => x.custom && !recent.includes(x.id) && compat(x));
329
+ const recs = t.filter((x) => x.recommended && !recent.includes(x.id) && !x.custom && compat(x)).slice(0, 8);
330
+ const shown = [];
331
+ for (const item of recentItems) shown.push(targetCard(item, state.targetId === item.id, "recent"));
332
+ for (const item of mine) shown.push(targetCard(item, state.targetId === item.id, null));
333
+ for (const item of recs) shown.push(targetCard(item, state.targetId === item.id, "recommended"));
334
+ // Currently selected but not in any of the above (picked from the manager).
335
+ const sel = byId.get(state.targetId);
336
+ if (sel && !recent.includes(sel.id) && !sel.custom && !sel.recommended) {
337
+ shown.unshift(targetCard(sel, true, null));
338
+ }
339
+ if (!recentItems.length && !mine.length && !recs.length) {
340
+ shown.push(h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, padding: "4px 2px" } },
341
+ shareT("share.noCompatible", { kind: kindLabel(kind) })));
342
+ }
343
+ shown.push(h("button", { type: "button", onClick: () => set({ manager: true }),
344
+ style: { border: "1px dashed var(--border, #34363c)", background: "none", color: "var(--text-muted, #8b909b)",
345
+ borderRadius: 8, padding: "4px 10px", fontSize: 12, cursor: "pointer" } }, shareT("share.more")));
346
+ return h("div", null,
347
+ h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, marginBottom: 5 } }, shareT("share.targets")),
348
+ h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6 } }, ...shown));
349
+ }
350
+
351
+ /** Collect page context for the optional "page info" stamp. */
352
+ function pageInfo() {
353
+ const ua = (typeof navigator !== "undefined" && navigator.userAgent) || "";
354
+ let os = "";
355
+ if (/Windows NT 10|Windows NT 11/.test(ua)) os = "Windows 10/11";
356
+ else if (/Windows/.test(ua)) os = "Windows";
357
+ else if (/Mac OS X|Macintosh/.test(ua)) os = "macOS";
358
+ else if (/Android/.test(ua)) os = "Android";
359
+ else if (/iPhone|iPad|iPod/.test(ua)) os = "iOS";
360
+ else if (/Linux/.test(ua)) os = "Linux";
361
+ let browser = "";
362
+ const b = (re, name) => { const m = ua.match(re); if (m) browser = name + " " + (m[1] || ""); };
363
+ b(/Edg\/([\d.]+)/, "Edge");
364
+ if (!browser) b(/OPR\/([\d.]+)/, "Opera");
365
+ if (!browser) b(/Chrome\/([\d.]+)/, "Chrome");
366
+ if (!browser) b(/Firefox\/([\d.]+)/, "Firefox");
367
+ if (!browser) b(/Version\/([\d.]+).*Safari/, "Safari");
368
+ const svc = ctxRef?.getExtService?.("pi-web.session");
369
+ const cur = (() => { try { return svc?.get?.() ?? svc; } catch { return null; } })();
370
+ // Verified snapshot summary: name/firstMessage live under `session`, not on the snapshot itself.
371
+ const sum = cur?.session || null;
372
+ // A shared session row (session-manager menu payload) describes its own session and wins
373
+ // over the currently active one.
374
+ const rowSess = state.payload?.session;
375
+ // List title semantics (session-manager sessionTitle): name || first message || id prefix.
376
+ const listTitle = (s) => (s ? (s.name || s.firstMessage || String(s.id || "").slice(0, 12)) : "");
377
+ // Session ID is the raw canonical id, never the display title: row id → snapshot summary id
378
+ // → verified snapshot id → payload id → URL ?session=.
379
+ const sessionId = rowSess?.id || sum?.id || cur?.sessionId
380
+ || state.payload?.sessionId || state.payload?.sessionName
381
+ || (typeof location !== "undefined" ? new URL(location.href).searchParams.get("session") : "") || "";
382
+ // Session name follows the session list title so it stays meaningful even when the
383
+ // session has no explicit name (falls back to first message, then id prefix).
384
+ const sessionName = listTitle(rowSess) || listTitle(sum) || state.payload?.sessionName || "";
385
+ return { os, browser, url: typeof location !== "undefined" ? location.href : "", sessionId, sessionName };
386
+ }
387
+
388
+ const STAMP_LABELS = { os: "share.pi.os", browser: "share.pi.browser", url: "share.pi.url", sessionId: "share.pi.sessionId", sessionName: "share.pi.sessionName" };
389
+
390
+ /** Build the stamp block from the selected fields. */
391
+ function stampBlock(stamp = state.stamp) {
392
+ const info = pageInfo();
393
+ const lines = [];
394
+ for (const key of Object.keys(STAMP_LABELS)) {
395
+ if (!stamp?.[key]) continue;
396
+ const value = info[key];
397
+ if (!value) continue;
398
+ lines.push(`> **${shareT(STAMP_LABELS[key])}**: ${value}`);
399
+ }
400
+ return lines.length ? lines.join("\n") + "\n\n" : "";
401
+ }
402
+
403
+ /** Final text = stamp block + base text. */
404
+ function composeText() {
405
+ return stampBlock() + (state.baseText ?? "");
406
+ }
407
+
408
+ /** Render a localized error message from the server's stable errorCode. */
409
+ function errorText() {
410
+ const code = state.errorCode || "";
411
+ const name = state.errorProvider || (state.targets.find((t) => t.id === state.errorTarget)?.name) || state.errorTarget || "";
412
+ const rawDetail = state.errorDetail || "";
413
+ // Provider errors can carry stack traces; keep the first meaningful chunk.
414
+ const detail = rawDetail.length > 220 ? rawDetail.slice(0, 220) + "…" : rawDetail;
415
+ const key = {
416
+ network: "share.err.network", timeout: "share.err.timeout", incomplete: "share.err.incomplete",
417
+ auth: "share.err.auth", tooLarge: "share.err.tooLarge", unavailable: "share.err.unavailable",
418
+ disabled: "share.err.disabled", unknownTarget: "share.err.unknownTarget",
419
+ noSession: "share.err.noSession", imageFetch: "share.err.imageFetch", endpoint: "share.err.endpoint",
420
+ badRequest: "share.err.badRequest", badSxcu: "share.err.badSxcu", noProbe: "share.err.noProbe",
421
+ forbidden: "share.err.forbidden", kind: "share.err.kind",
422
+ }[code];
423
+ if (key) return shareT(key, { name, detail });
424
+ return state.error || shareT("share.err.generic", { detail });
425
+ }
426
+
427
+ /** Rebuild the preview after stamp/redact changes. */
428
+ async function refreshPreview() {
429
+ const raw = composeText();
430
+ set({ rawText: raw });
431
+ await applyRedaction(raw, state.redact);
432
+ }
433
+
434
+ /** Checkbox group for page-context stamping (rendered in the preview header). */
435
+ function stampToggles() {
436
+ return h("span", { style: { display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" } },
437
+ ...Object.keys(STAMP_LABELS).map((key) => h("label", { key, title: shareT(STAMP_LABELS[key]),
438
+ style: { display: "flex", gap: 3, alignItems: "center", cursor: "pointer", fontSize: 10,
439
+ color: state.stamp[key] ? "var(--accent, #4d8dff)" : "var(--text-muted, #8b909b)" } },
440
+ h("input", { type: "checkbox", checked: !!state.stamp[key],
441
+ onChange: (e) => {
442
+ set({ stamp: { ...state.stamp, [key]: e.target.checked } });
443
+ void refreshPreview();
444
+ } }),
445
+ shareT(STAMP_LABELS[key]))));
446
+ }
447
+ async function applyRedaction(raw, redact) {
448
+ try {
449
+ const r = await getJSON("preview-redact", { method: "POST",
450
+ headers: { "content-type": "application/json" },
451
+ body: JSON.stringify({ text: raw, redact }) });
452
+ set({ text: r.text, redactHits: r.hits || [], redact });
453
+ } catch (e) {
454
+ // Server unavailable → keep showing raw text with no redaction claim.
455
+ set({ text: raw, redactHits: [], redact });
456
+ }
457
+ }
458
+
459
+ function previewSection() {
460
+ return h("div", null,
461
+ // Header row: label | page-info multi-select | redact toggle
462
+ h("div", { style: { display: "flex", alignItems: "center", gap: 10, marginBottom: 5, flexWrap: "wrap" } },
463
+ h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11 } }, shareT("share.preview")),
464
+ h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 10, opacity: 0.8 } }, shareT("share.pageInfo") + ":"),
465
+ stampToggles(),
466
+ h("label", { title: shareT("share.redactAuto"),
467
+ style: { marginLeft: "auto", display: "flex", gap: 5, alignItems: "center", cursor: "pointer",
468
+ fontSize: 11, color: state.redactHits.length ? "#d9a13c" : "var(--text-muted, #8b909b)" } },
469
+ h("input", { type: "checkbox", checked: state.redact, onChange: (e) => {
470
+ set({ redact: e.target.checked });
471
+ void applyRedaction(state.rawText, e.target.checked);
472
+ } }), shareT("share.redactToggle"),
473
+ state.redactHits.length ? ` (${state.redactHits.reduce((a, b) => a + b.count, 0)})` : "")),
474
+ h("textarea", { value: state.text, onInput: (e) => {
475
+ const v = e.target.value;
476
+ // Direct edits replace the body; the stamp block (if any) stays as typed.
477
+ set({ text: v, rawText: v, baseText: v, redactHits: [] });
478
+ },
479
+ style: { width: "100%", minHeight: 100, resize: "vertical", background: "var(--bg-hover, #25272c)",
480
+ border: "1px solid var(--border, #34363c)", color: "var(--text, #d8dade)", borderRadius: 8, padding: 9,
481
+ font: "12px/1.6 ui-monospace, Consolas, monospace" } }),
482
+ ...(state.redactHits.length ? [h("div", { style: { color: "#d9a13c", fontSize: 11, marginTop: 4 } },
483
+ "🛡 " + state.redactHits.map((x) => `${x.rule}×${x.count}`).join(" · "))] : []));
484
+ }
485
+
486
+ function resultSection() {
487
+ const r = state.result;
488
+ const rurl = r.url;
489
+ const isDeep = /^(joplin|obsidian|siyuan):/.test(rurl);
490
+ return h("div", { style: { border: "1px solid #3fbf6e55", background: "#3fbf6e10", borderRadius: 9,
491
+ padding: 11, display: "flex", gap: 12, alignItems: "center" } },
492
+ h("div", { style: { flex: 1, minWidth: 0 } },
493
+ h("a", { href: rurl, target: "_blank", rel: "noopener noreferrer", title: shareT("share.openInNewTab") || rurl,
494
+ style: { color: "var(--accent, #4d8dff)", fontFamily: "monospace", fontSize: 12, wordBreak: "break-all",
495
+ textDecoration: "none", cursor: "pointer" },
496
+ onMouseEnter: (e) => { e.currentTarget.style.textDecoration = "underline"; },
497
+ onMouseLeave: (e) => { e.currentTarget.style.textDecoration = "none"; } }, rurl),
498
+ h("div", { style: { display: "flex", gap: 7, marginTop: 9, flexWrap: "wrap" } },
499
+ btn(shareT("share.copy"), () => navigator.clipboard?.writeText(rurl).catch(() => {})),
500
+ !isDeep && typeof navigator !== "undefined" && navigator.share
501
+ ? btn(shareT("share.system"), () => navigator.share({ url: rurl, title: state.title }).catch(() => {})) : null,
502
+ r.extra?.rawUrl ? h("a", { href: r.extra.rawUrl, target: "_blank", rel: "noopener",
503
+ style: { fontSize: 12, color: "var(--accent, #4d8dff)" } }, shareT("share.raw")) : null,
504
+ r.extra?.deletionUrl ? h("a", { href: r.extra.deletionUrl, target: "_blank", rel: "noopener",
505
+ style: { fontSize: 12, color: "#e05d5d" } }, shareT("share.delete")) : null)),
506
+ h("canvas", { ref: (el) => { if (el && !isDeep) QRCode.toCanvas(el, rurl, { width: 84, margin: 1 }).catch(() => {}); },
507
+ style: { display: isDeep ? "none" : "block", width: 84, height: 84, background: "#fff", borderRadius: 6, padding: 4 } }));
508
+ }
509
+
510
+ async function doShare() {
511
+ if (!state.targetId || state.busy) return;
512
+ set({ busy: true, error: "" });
513
+ try {
514
+ // The textarea already shows the redacted text (preview-redact ran on load/toggle),
515
+ // so upload exactly what the user sees; no second redaction on the server.
516
+ const body = { ...(state.payload || {}), targetId: state.targetId, kind: state.kind,
517
+ text: state.text, title: state.title, tags: state.tags, redact: false };
518
+ // Images: load in the browser (same-origin /api/... or data: URLs — no CORS,
519
+ // no server-side fetch) and hand the server base64 bytes.
520
+ if (state.kind === "image" && body.imageSrc) {
521
+ const blob = await fetch(body.imageSrc).then((r) => { if (!r.ok) throw new Error("HTTP " + r.status); return r.blob(); })
522
+ .catch((e) => { throw Object.assign(new Error(shareT("share.err.imageFetch", { detail: e?.message || e })), { detail: String(e?.message || e) }); });
523
+ const dataUrl = await new Promise((res, rej) => {
524
+ const fr = new FileReader();
525
+ fr.onload = () => res(String(fr.result));
526
+ fr.onerror = () => rej(new Error("FileReader failed"));
527
+ fr.readAsDataURL(blob);
528
+ });
529
+ body.imageBase64 = dataUrl;
530
+ body.mime = blob.type || "image/png";
531
+ body.filename = body.filename || ("image." + (blob.type.split("/")[1] || "png").replace("jpeg", "jpg"));
532
+ }
533
+ const r = await getJSON("share", { method: "POST", headers: { "content-type": "application/json" },
534
+ body: JSON.stringify(body) });
535
+ recentAdd(state.targetId);
536
+ set({ result: r, busy: false, redactHits: r.hits || [] });
537
+ } catch (e) {
538
+ set({ busy: false, error: e.message, errorDetail: e.detail || api("share"),
539
+ errorCode: e.kind || "", errorTarget: e.targetId || "", errorProvider: e.providerLabel || "" });
540
+ }
541
+ }
542
+
543
+ /** Dialog component: React-managed re-render via a subscription + tick. */
544
+ let dialogBodyEl = null;
545
+ function ShareDialogHost() {
546
+ const [, setTick] = ctxRef.useState(0);
547
+ ctxRef.useEffect(() => {
548
+ const fn = () => setTick((n) => n + 1);
549
+ listeners.add(fn);
550
+ return () => listeners.delete(fn);
551
+ }, []);
552
+ const result = state.result;
553
+ ctxRef.useEffect(() => {
554
+ // When a share result arrives, scroll the body to reveal the URL/QR block.
555
+ if (result && dialogBodyEl) {
556
+ try { dialogBodyEl.scrollTop = dialogBodyEl.scrollHeight; } catch (e) {}
557
+ }
558
+ }, [result]);
559
+ return shareDialog();
560
+ }
561
+
562
+ function shareDialog() {
563
+ if (!state.open) return null;
564
+ if (state.manager) return managerDialog();
565
+ const head = h("div", { style: { display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", flexShrink: 0,
566
+ borderBottom: "1px solid var(--border, #34363c)", background: "var(--bg-hover, #25272c)", borderRadius: "9px 9px 0 0" } },
567
+ h("span", { style: { fontWeight: 600 } }, shareT("share.action")),
568
+ h("span", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11 } }, shareT("share.subtitle", { kind: state.kind, chars: state.text.length })),
569
+ h("div", { style: { flex: 1 } }),
570
+ h("button", { type: "button", onClick: () => set({ open: false }),
571
+ style: { background: "none", border: "none", color: "var(--text-muted, #8b909b)", cursor: "pointer", fontSize: 14 } }, "✕"));
572
+ const body = h("div", { ref: (el) => { dialogBodyEl = el; },
573
+ style: { padding: "12px 14px", display: "flex", flexDirection: "column", gap: 12, flex: 1, minHeight: 0, overflowY: "auto" } },
574
+ previewSection(), sinkSection(), targetSection(),
575
+ h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9 } },
576
+ h("input", { value: state.title, placeholder: shareT("share.titleField"), onInput: (e) => set({ title: e.target.value }),
577
+ style: { background: "var(--bg-hover, #25272c)", border: "1px solid var(--border, #34363c)", color: "var(--text, #d8dade)", borderRadius: 7, padding: "6px 9px", fontSize: 12 } }),
578
+ h("input", { value: state.tags, placeholder: shareT("share.tagsField"), onInput: (e) => set({ tags: e.target.value }),
579
+ style: { background: "var(--bg-hover, #25272c)", border: "1px solid var(--border, #34363c)", color: "var(--text, #d8dade)", borderRadius: 7, padding: "6px 9px", fontSize: 12 } })),
580
+ state.error ? h("div", { style: { border: "1px solid #e05d5d66", background: "#e05d5d18", borderRadius: 8,
581
+ padding: "8px 10px", color: "#e05d5d", fontSize: 12, userSelect: "text", cursor: "text", wordBreak: "break-word" } },
582
+ errorText(),
583
+ state.errorDetail && state.errorDetail !== errorText()
584
+ ? h("div", { style: { fontSize: 10, opacity: 0.75, marginTop: 4, fontFamily: "monospace" } }, state.errorDetail) : null,
585
+ state.errorTarget ? h("div", { style: { marginTop: 6 } },
586
+ h("button", { type: "button", onClick: () => set({ manager: true, editing: state.errorTarget } ),
587
+ style: { border: "1px solid #e05d5d", background: "none", color: "#e05d5d", borderRadius: 6,
588
+ padding: "3px 9px", fontSize: 11, cursor: "pointer" } }, shareT("share.fixTarget"))) : null) : null,
589
+ state.result ? resultSection() : null);
590
+ // Footer is pinned outside the scroll area so the action buttons never clip.
591
+ const footer = h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8, flexShrink: 0,
592
+ padding: "10px 14px", borderTop: "1px solid var(--border, #34363c)", background: "var(--bg-hover, #25272c)" } },
593
+ btn(shareT("share.manage"), () => set({ manager: true,
594
+ ...(state.errorTarget ? { editing: state.errorTarget } : {}) })),
595
+ btn(state.busy ? shareT("share.uploading") : shareT("share.action"), doShare, { primary: true, disabled: state.busy }));
596
+ return h("div", { "data-ext-float": "1", "data-ext-float-w": "640", "data-ext-float-h": "520",
597
+ style: { background: "var(--bg-panel, #1e2021)", border: "1px solid var(--border, #34363c)", borderRadius: 10,
598
+ boxShadow: "0 14px 44px #000a", overflow: "hidden", font: "13px/1.5 system-ui, sans-serif", color: "var(--text, #d8dade)",
599
+ display: "flex", flexDirection: "column", maxHeight: "88vh" } }, head, body, footer);
600
+ }
601
+
602
+ function managerDialog() {
603
+ const q = state.search.toLowerCase();
604
+ const groups = { recent: [], recommended: [], all: [] };
605
+ const recentIds = recentGet();
606
+ for (const t of state.targets) {
607
+ if (q && !(t.name || t.id).toLowerCase().includes(q)) continue;
608
+ if (recentIds.includes(t.id)) groups.recent.push(t);
609
+ else if (t.recommended) groups.recommended.push(t);
610
+ else groups.all.push(t);
611
+ }
612
+ const item = (t) => h("div", { key: t.id, onClick: () => set({ editing: t.id,
613
+ form: { ...((t.values && !Array.isArray(t.values)) ? t.values : {}) } }),
614
+ style: { display: "flex", alignItems: "center", gap: 7, padding: "5px 8px", borderRadius: 7, cursor: "pointer",
615
+ background: state.editing === t.id ? "rgba(77, 141, 255, 0.15)" : "none", opacity: t.status === "dead" ? 0.5 : 1 } },
616
+ h("span", null, t.status === "dead" ? "💀" : t.category === "archive" ? "📓" : "🔗"),
617
+ h("div", { style: { flex: 1, minWidth: 0 } },
618
+ h("div", { style: { fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, t.name || t.id),
619
+ h("div", { style: { fontSize: 10, color: "var(--text-muted, #8b909b)" } }, (t.kinds || []).map(kindLabel).join("/") + (() => { const n = noteText(t.note); return n ? " · " + n : ""; })())),
620
+ (() => { const b = CFG_BADGE[t.configState]; return b ? h("span", { title: shareT(b.key),
621
+ style: { color: b.color, fontSize: 9, whiteSpace: "nowrap", flexShrink: 0 } }, b.icon) : null; })(),
622
+ t.recommended ? h("span", { style: { color: "var(--accent, #4d8dff)", fontSize: 10 } }, "★") : null,
623
+ // "Use" closes the loop: pick this target for the pending share and return to it.
624
+ !supportsKind(t, contentKind())
625
+ ? h("span", { title: shareT("share.notCompatible", { kind: kindLabel(contentKind()) }),
626
+ style: { color: "var(--text-muted, #8b909b)", fontSize: 9, whiteSpace: "nowrap", flexShrink: 0 } }, "∅")
627
+ : t.status !== "dead" && t.configState !== "needs-setup"
628
+ ? h("button", { type: "button", title: shareT("share.useTarget"),
629
+ onClick: (e) => { e.stopPropagation(); chooseTarget(t.id); },
630
+ style: { border: "1px solid var(--accent, #4d8dff)", background: state.targetId === t.id ? "var(--accent, #4d8dff)" : "none",
631
+ color: state.targetId === t.id ? "#fff" : "var(--accent, #4d8dff)", borderRadius: 6, padding: "2px 8px",
632
+ fontSize: 10, cursor: "pointer", flexShrink: 0 } }, shareT("share.use"))
633
+ : h("button", { type: "button", title: shareT("share.setupFirst"),
634
+ onClick: (e) => { e.stopPropagation(); set({ editing: t.id, form: {} }); },
635
+ style: { border: "1px solid #d9a13c", background: "none", color: "#d9a13c", borderRadius: 6,
636
+ padding: "2px 8px", fontSize: 10, cursor: "pointer", flexShrink: 0 } }, shareT("share.setup")),
637
+ );
638
+ const edit = state.targets.find((t) => t.id === state.editing);
639
+ const fields = edit?.fields || [];
640
+ const form = edit ? h("div", { style: { flex: 1, padding: 14, display: "flex", flexDirection: "column", gap: 12, overflowY: "auto" } },
641
+ h("div", { style: { fontWeight: 600 } }, edit.name || edit.id),
642
+ (() => { const n = noteText(edit.note); return n ? h("div", { style: { fontSize: 11, color: "var(--text-muted, #8b909b)" } }, n) : null; })(),
643
+ ...fields.map((f) => {
644
+ const key = typeof f === "string" ? f : f.key;
645
+ const label = typeof f === "string" ? f : (f.label || f.key);
646
+ const type = typeof f === "string" ? "password" : (f.type || "text");
647
+ const hint = typeof f === "string" ? "" : (f.hint || "");
648
+ const opts = typeof f === "string" ? null : f.options;
649
+ return h("div", null,
650
+ h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, marginBottom: 3 } }, label + (f.required ? " *" : "")),
651
+ opts ? h("select", { value: state.form[key] ?? edit.values?.[key] ?? opts[0]?.value ?? "",
652
+ onChange: (e) => set({ form: { ...state.form, [key]: e.target.value } }),
653
+ style: { width: "100%", background: "var(--bg-hover, #25272c)", border: "1px solid var(--border, #34363c)", borderRadius: 7, padding: "6px 9px", color: "var(--text, #d8dade)" } },
654
+ ...opts.map((o) => h("option", { value: o.value }, o.label)))
655
+ : h("input", { type: type === "password" ? "password" : "text", value: state.form[key] ?? "",
656
+ placeholder: edit.values?.[key] ? shareT("share.notSet") + " " + edit.values[key] : (hint || label),
657
+ onInput: (e) => set({ form: { ...state.form, [key]: e.target.value } }),
658
+ style: { width: "100%", background: "var(--bg-hover, #25272c)", border: "1px solid var(--border, #34363c)", borderRadius: 7, padding: "6px 9px", color: "var(--text, #d8dade)" } }),
659
+ hint ? h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 10, marginTop: 3 } }, hint) : null);
660
+ }),
661
+ fields.length === 0 ? h("div", { style: { fontSize: 12, color: "var(--text-muted, #8b909b)" } },
662
+ shareT("share.noSetup")) : null,
663
+ ...(edit.custom ? [btn(shareT("share.deleteTarget"), () => void getJSON(`targets?id=${encodeURIComponent(edit.id)}`, { method: "DELETE" }).then(() => refresh()), { title: shareT("share.delete") })] : []),
664
+ btn(shareT("share.saveTest"), async () => {
665
+ try {
666
+ const saved = await getJSON("targets", { method: "POST", headers: { "content-type": "application/json" },
667
+ body: JSON.stringify({ id: edit.id, provider: edit.provider, name: edit.name, values: { ...edit.values, ...state.form } }) });
668
+ const probe = await getJSON("targets/test", { method: "POST", headers: { "content-type": "application/json" },
669
+ body: JSON.stringify({ provider: edit.provider, values: { ...edit.values, ...state.form } }) });
670
+ set({ error: probe.ok ? shareT("share.testOk") : shareT("share.testFail", { detail: probe.detail || "" }) });
671
+ void refresh(); void saved;
672
+ } catch (e) { set({ error: e.message }); }
673
+ }),
674
+ // After configuring, jump straight back into the share flow with this target.
675
+ btn(shareT("share.saveUse"), async () => {
676
+ try {
677
+ await getJSON("targets", { method: "POST", headers: { "content-type": "application/json" },
678
+ body: JSON.stringify({ id: edit.id, provider: edit.provider, name: edit.name, values: { ...edit.values, ...state.form } }) });
679
+ void refresh();
680
+ chooseTarget(edit.id);
681
+ } catch (e) { set({ error: e.message }); }
682
+ }, { primary: true })) : h("div", { style: { flex: 1, padding: 20, color: "var(--text-muted, #8b909b)" } }, shareT("share.selectTarget"));
683
+ const localProbe = state.probe.length
684
+ ? h("div", { style: { background: "#3fbf6e10", border: "1px solid #3fbf6e44", borderRadius: 7, padding: "6px 9px", fontSize: 11, color: "var(--accent, #4d8dff)" } },
685
+ shareT("share.probeDetected", { ports: state.probe.map((p) => ":" + p.port).join(", ") })) : null;
686
+ return h("div", { "data-ext-float": "1", "data-ext-float-w": "820", "data-ext-float-h": "560",
687
+ style: { display: "flex", flexDirection: "column", maxHeight: "88vh", background: "var(--bg-panel, #1e2021)", border: "1px solid var(--border, #34363c)",
688
+ borderRadius: 10, boxShadow: "0 14px 44px #000a", overflow: "hidden", color: "var(--text, #d8dade)", font: "13px/1.5 system-ui" } },
689
+ h("div", { style: { display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", background: "var(--bg-hover, #25272c)", borderBottom: "1px solid var(--border, #34363c)" } },
690
+ // Return to the share flow without losing the pending content.
691
+ h("button", { type: "button", title: shareT("share.backToShare"), onClick: () => set({ manager: false }),
692
+ style: { background: "none", border: "none", color: "var(--accent, #4d8dff)", cursor: "pointer", fontSize: 14 } }, "←"),
693
+ h("span", { style: { fontWeight: 600 } }, shareT("share.targets")),
694
+ h("div", { style: { flex: 1 } }),
695
+ btn("⟳", () => void refresh(true), { title: shareT("share.refresh") }),
696
+ h("button", { type: "button", onClick: () => set({ manager: false, open: false }),
697
+ style: { background: "none", border: "none", color: "var(--text-muted, #8b909b)", cursor: "pointer" } }, "✕")),
698
+ localProbe,
699
+ h("div", { style: { display: "flex", flex: 1, minHeight: 0 } },
700
+ h("div", { style: { width: 300, borderRight: "1px solid var(--border, #34363c)", display: "flex", flexDirection: "column" } },
701
+ h("div", { style: { padding: 8 } }, h("input", { value: state.search, placeholder: shareT("share.search"),
702
+ onInput: (e) => set({ search: e.target.value }),
703
+ style: { width: "100%", background: "var(--bg-hover, #25272c)", border: "1px solid var(--border, #34363c)", borderRadius: 7, padding: "6px 9px", color: "var(--text, #d8dade)", fontSize: 12 } })),
704
+ h("div", { style: { overflow: "auto", flex: 1, padding: "0 8px 10px" } },
705
+ groups.recent.length ? h("div", null, h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, padding: "6px" } }, shareT("share.recent")), ...groups.recent.map(item)) : null,
706
+ groups.recommended.length ? h("div", null, h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, padding: "6px" } }, shareT("share.recommended")), ...groups.recommended.map(item)) : null,
707
+ h("div", null, h("div", { style: { color: "var(--text-muted, #8b909b)", fontSize: 11, padding: "6px" } }, shareT("share.allTargets", { n: state.targets.length })), ...groups.all.map(item))),
708
+ h("div", { style: { borderTop: "1px solid var(--border, #34363c)", padding: 8, display: "flex", gap: 6 } },
709
+ btn(shareT("share.importSxcu"), () => {
710
+ const text = window.prompt(shareT("share.importPrompt"));
711
+ if (!text) return;
712
+ void getJSON("import-sxcu", { method: "POST", headers: { "content-type": "application/json" },
713
+ body: JSON.stringify({ config: text }) }).then(() => refresh()).catch((e) => set({ error: e.message }));
714
+ }),
715
+ btn(shareT("share.clearRecent"), () => { recentClear(); emit(); }))),
716
+ form),
717
+ state.error ? h("div", { style: { padding: "6px 14px", color: "var(--accent, #4d8dff)", fontSize: 11 } }, state.error) : null);
718
+ }
719
+
720
+ export default function register(ctx) {
721
+ h = ctx.h;
722
+ ctxRef = ctx;
723
+ tFn = typeof ctx.t === "function" ? ctx.t.bind(ctx) : null;
724
+ if (typeof ctx.apiUrl === "function") apiUrlFn = ctx.apiUrl.bind(ctx);
725
+
726
+ ctx.registerItems("dialogs", [{ id: "aiti-msg-share-dialog", render: () => ShareDialogHost() }]);
727
+
728
+ const shareAction = (label) => (props) => h("button", {
729
+ type: "button", title: label,
730
+ onClick: () => openShare({ kind: "message", text: props?.text || "", sessionId: props?.sessionId }),
731
+ style: { display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 8px", height: 22,
732
+ border: "none", background: "none", borderRadius: 5, color: "var(--text-dim, #8b909b)", cursor: "pointer", fontSize: 11 },
733
+ }, icon("share", 12), label);
734
+ // meta.order: 1 pins Share right after the host's built-in Copy button,
735
+ // ahead of unordered slot items (git-trace badge, quote, bookmark — manifest
736
+ // order would otherwise put aiti-git-trace first).
737
+ ctx.registerItems("userMessageActions", [{ id: "aiti-msg-share-user", render: shareAction(shareT("share.action")), meta: { order: 1 } }]);
738
+ // Assistant messages mount the same share button at both ends (meta.placement):
739
+ // long replies put one end off-screen, so top (meta row) + bottom carry identical buttons.
740
+ ctx.registerItems("assistantMessageActions", [
741
+ { id: "aiti-msg-share-assistant", render: shareAction(shareT("share.action")), meta: { order: 1 } },
742
+ { id: "aiti-msg-share-assistant-top", render: shareAction(shareT("share.action")), meta: { placement: "top", order: 1 } },
743
+ ]);
744
+ // Session row share lives in session-manager's ⋯ more-menu, not as a bare row
745
+ // button (too many row actions). Registered via that extension's topic contract.
746
+ // (sessionRowActions intentionally not used here.)
747
+ ctx.registerItems("commands", [{ id: "aiti-msg-share.center", render: () => null,
748
+ meta: { label: shareT("share.center"), onClick: () => openShare({ kind: "session" }) } }]);
749
+
750
+ if (typeof ctx.registerExtService === "function") {
751
+ ctx.registerExtService("aiti-msg-share.openShare", (payload) => openShare(payload));
752
+ }
753
+ // msg-smart extension points (topic contracts defined by that extension).
754
+ // Topic registration avoids hard-coded share buttons in msg-smart.
755
+ if (typeof ctx.registerTopicItem === "function") {
756
+ // aiti-editor extension points (contracts defined by that extension):
757
+ // image preview toolbar + file toolbar. No hard-coded share button in editor.
758
+ ctx.registerTopicItem("editor-image-action", {
759
+ id: "aiti-msg-share-image",
760
+ label: shareT("share.action"),
761
+ icon: SHARE_ICON,
762
+ onClick: (img) => openShare({ kind: "image", imageSrc: img.src, filename: img.alt || "image" }),
763
+ });
764
+ ctx.registerTopicItem("editor-file-action", {
765
+ id: "aiti-msg-share-file",
766
+ label: shareT("share.action"),
767
+ icon: SHARE_ICON,
768
+ onClick: (file) => file.selectionText
769
+ ? openShare({ kind: "selection", text: file.selectionText, title: file.filePath?.split("/").pop() })
770
+ : openShare({ kind: "file", filePath: file.filePath, filename: file.filePath?.split("/").pop() }),
771
+ });
772
+ // session-manager's ⋯ more-menu action (contract: session-row-menu-action).
773
+ ctx.registerTopicItem("session-row-menu-action", {
774
+ id: "aiti-msg-share-session",
775
+ label: shareT("share.session"),
776
+ title: shareT("share.sessionTip"),
777
+ icon: SHARE_ICON,
778
+ match: () => true,
779
+ onClick: (sess) => openShare({ kind: "session", sessionId: sess?.id,
780
+ session: sess, title: sess?.name || sess?.title || "" }),
781
+ });
782
+ // File card's first-row action (file recognition).
783
+ // `order` follows the msg-smart row order: built-in Open = 10, external = 20,
784
+ // Reveal = 30 — so Share sits right after Open and before Reveal.
785
+ ctx.registerTopicItem("msg-file-action", {
786
+ id: "aiti-msg-share-file",
787
+ label: shareT("share.action"),
788
+ title: shareT("share.fileTip"),
789
+ icon: SHARE_ICON,
790
+ type: "share",
791
+ order: 20,
792
+ match: (abs, isDir) => !isDir,
793
+ onClick: (abs) => openShare({ kind: "file", filePath: abs, filename: abs.split("/").pop() }),
794
+ });
795
+ // Top-row popover action: rendered in the first row after the new-session button
796
+ // (paragraph / code-line / selection cards). Signature: onClick(text, cwd).
797
+ ctx.registerTopicItem("msg-popover-top-action", {
798
+ id: "aiti-msg-share-popover",
799
+ label: shareT("share.action"),
800
+ title: shareT("share.content"),
801
+ icon: SHARE_ICON,
802
+ onClick: (text) => { if (text && text.trim()) openShare({ kind: "selection", text }); },
803
+ });
804
+ }
805
+ void ctxRef;
806
+ }