@octarq/plugin-links 0.1.0 → 0.2.0

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,128 @@
1
+ import { Badge, Button, ListSkeleton, PageCard, PageEmpty, PageShell, TabBar, timeAgo, toast, useTranslation } from "@octarq/plugin-sdk";
2
+ import { ShieldAlert } from "lucide-react";
3
+ import { useEffect, useState } from "react";
4
+ import { api, type AbuseReport } from "../api";
5
+
6
+ export default function AbusePage() {
7
+ const { t } = useTranslation();
8
+ const [reports, setReports] = useState<AbuseReport[]>([]);
9
+ const [loading, setLoading] = useState(true);
10
+ const [statusFilter, setStatusFilter] = useState("open");
11
+
12
+ const load = () => {
13
+ setLoading(true);
14
+ api.abuseReports(statusFilter === "all" ? "" : statusFilter)
15
+ .then(setReports)
16
+ .finally(() => setLoading(false));
17
+ };
18
+
19
+ useEffect(() => {
20
+ load();
21
+ }, [statusFilter]);
22
+
23
+ const updateStatus = async (id: number, status: string) => {
24
+ try {
25
+ await api.updateAbuseReport(id, status);
26
+ load();
27
+ } catch (e: any) {
28
+ toast.error(t("links.abuse.updateFailed", { error: e.message }));
29
+ }
30
+ };
31
+
32
+ const getStatusTone = (status: string) => {
33
+ if (status === "open") return "warning";
34
+ if (status === "reviewed") return "success";
35
+ return "secondary";
36
+ };
37
+
38
+ const getReasonTone = (reason: string) => {
39
+ if (reason === "phishing" || reason === "malware") return "danger";
40
+ if (reason === "spam") return "warning";
41
+ return "info";
42
+ };
43
+
44
+ return (
45
+ <PageShell
46
+ title={t("links.abuse.pageTitle")}
47
+ description={t("links.abuse.pageDesc")}
48
+ >
49
+ <TabBar
50
+ size="sm"
51
+ value={statusFilter}
52
+ onValueChange={setStatusFilter}
53
+ items={(["open", "reviewed", "dismissed", "all"] as const).map((filter) => ({
54
+ value: filter,
55
+ label: t("links.abuse.filter" + filter.charAt(0).toUpperCase() + filter.slice(1)),
56
+ }))}
57
+ />
58
+
59
+ {loading ? (
60
+ <ListSkeleton rows={5} ariaLabel={t("links.abuse.loading")} />
61
+ ) : reports.length === 0 ? (
62
+ <PageEmpty title={t("links.abuse.emptyState")} icon={<ShieldAlert />} />
63
+ ) : (
64
+ <div className="space-y-4">
65
+ {reports.map((r) => (
66
+ <PageCard key={r.id} className="mt-0">
67
+ <div className="flex flex-wrap items-start justify-between gap-4">
68
+ <div>
69
+ <div className="flex flex-wrap items-center gap-2">
70
+ <h3 className="text-base font-semibold text-danger-fg">/{r.slug}</h3>
71
+ <Badge tone={getReasonTone(r.reason)} className="uppercase tracking-wider">
72
+ {t("links.abuse.reason" + r.reason.charAt(0).toUpperCase() + r.reason.slice(1)) || r.reason}
73
+ </Badge>
74
+ <Badge tone={getStatusTone(r.status)} className="capitalize">
75
+ {t("links.abuse.filter" + r.status.charAt(0).toUpperCase() + r.status.slice(1)) || r.status}
76
+ </Badge>
77
+ </div>
78
+ <div className="mt-2 text-sm text-muted-foreground break-all">
79
+ {t("links.abuse.target")}{" "}
80
+ {r.target ? (
81
+ <a
82
+ href={r.target}
83
+ target="_blank"
84
+ rel="noreferrer"
85
+ className="text-accent-fg hover:underline transition-colors"
86
+ >
87
+ {r.target}
88
+ </a>
89
+ ) : (
90
+ <span className="text-muted-foreground italic">—</span>
91
+ )}
92
+ </div>
93
+ </div>
94
+ <div className="text-left sm:text-right text-xs text-muted-foreground">
95
+ <div className="font-mono tnum" title={r.createdAt}>{timeAgo(r.createdAt)}</div>
96
+ <div className="mt-1">{t("links.abuse.ip", { ip: r.reporterIp })}</div>
97
+ </div>
98
+ </div>
99
+
100
+ <div className="mt-4 text-sm text-foreground bg-well p-4 rounded-lg border border-border font-normal leading-relaxed">
101
+ {r.description || <span className="text-muted-foreground italic">{t("links.abuse.noDescription")}</span>}
102
+ </div>
103
+
104
+ {r.status === "open" && (
105
+ <div className="mt-4 flex gap-2 justify-end border-t border-border pt-4">
106
+ <Button
107
+ variant="ghost"
108
+ size="sm"
109
+ onClick={() => updateStatus(r.id, "dismissed")}
110
+ >
111
+ {t("links.abuse.dismissSafe")}
112
+ </Button>
113
+ <Button
114
+ variant="danger"
115
+ size="sm"
116
+ onClick={() => updateStatus(r.id, "reviewed")}
117
+ >
118
+ {t("links.abuse.markReviewed")}
119
+ </Button>
120
+ </div>
121
+ )}
122
+ </PageCard>
123
+ ))}
124
+ </div>
125
+ )}
126
+ </PageShell>
127
+ );
128
+ }
@@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
3
3
  import { cleanup, render, screen, waitFor, fireEvent } from "@testing-library/react";
4
4
  import { registerUIPlugin, resetRegistry, I18nProvider } from "@octarq/plugin-sdk";
5
5
  import linksPlugin from "../index";
6
- import { LinkEditorForm } from "./LinkEditorForm";
6
+ import { LinkEditorForm, localDatetimeInputToISO, toLocalDatetimeInput } from "./LinkEditorForm";
7
7
  import { Link } from "../api";
8
8
 
9
9
  function jsonResponse(body: unknown, status = 200) {
@@ -51,10 +51,10 @@ describe("LinkEditorForm", () => {
51
51
  const urlObj = new URL(rawUrl, "http://localhost");
52
52
  const path = urlObj.pathname;
53
53
 
54
- if (method === "GET" && path === "/api/ai/assist/status") {
54
+ if (method === "GET" && path === "/api/links/ai/status") {
55
55
  return jsonResponse({ configured: true, provider: "openai" });
56
56
  }
57
- if (method === "POST" && path === "/api/ai/assist/suggest-slug") {
57
+ if (method === "POST" && path === "/api/links/ai/suggest-slug") {
58
58
  return jsonResponse({ slugs: ["ai-suggest-1", "ai-suggest-2"] });
59
59
  }
60
60
  if (method === "GET" && path === "/api/links/metadata") {
@@ -92,23 +92,19 @@ describe("LinkEditorForm", () => {
92
92
  </I18nProvider>
93
93
  );
94
94
 
95
- // Verify fields are rendered
96
95
  const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz");
97
96
  expect(targetInput).toBeDefined();
98
97
 
99
98
  const slugInput = screen.getByPlaceholderText("e.g. promo2026");
100
99
  expect(slugInput).toBeDefined();
101
100
 
102
- // Save button should be disabled when target is empty
103
101
  const saveBtn = screen.getByRole("button", { name: "Save link" });
104
102
  expect((saveBtn as HTMLButtonElement).disabled).toBe(true);
105
103
 
106
- // Cancel button works
107
104
  const cancelBtn = screen.getByRole("button", { name: "Cancel" });
108
105
  fireEvent.click(cancelBtn);
109
106
  expect(onCancel).toHaveBeenCalledTimes(1);
110
107
 
111
- // Typing target enables save button
112
108
  fireEvent.change(targetInput, { target: { value: "https://acme.com/new-product" } });
113
109
  expect((saveBtn as HTMLButtonElement).disabled).toBe(false);
114
110
  });
@@ -120,7 +116,6 @@ describe("LinkEditorForm", () => {
120
116
  </I18nProvider>
121
117
  );
122
118
 
123
- // Wait for AI assist status to load
124
119
  await waitFor(() => {
125
120
  expect(screen.getByRole("button", { name: "AI suggest" })).toBeDefined();
126
121
  });
@@ -136,7 +131,6 @@ describe("LinkEditorForm", () => {
136
131
  expect(screen.getByText("ai-suggest-2")).toBeDefined();
137
132
  });
138
133
 
139
- // Clicking a suggestion chip sets the slug
140
134
  fireEvent.click(screen.getByText("ai-suggest-1"));
141
135
  const slugInput = screen.getByPlaceholderText("e.g. promo2026") as HTMLInputElement;
142
136
  expect(slugInput.value).toBe("ai-suggest-1");
@@ -146,10 +140,10 @@ describe("LinkEditorForm", () => {
146
140
  fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
147
141
  const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
148
142
  const urlObj = new URL(rawUrl, "http://localhost");
149
- if (urlObj.pathname === "/api/ai/assist/status") {
143
+ if (urlObj.pathname === "/api/links/ai/status") {
150
144
  return jsonResponse({ configured: true, provider: "openai" });
151
145
  }
152
- if (urlObj.pathname === "/api/ai/assist/suggest-slug") {
146
+ if (urlObj.pathname === "/api/links/ai/suggest-slug") {
153
147
  return jsonResponse({ message: "AI rate limit" }, 500);
154
148
  }
155
149
  throw new Error(`Unhandled fetch: ${rawUrl}`);
@@ -205,7 +199,6 @@ describe("LinkEditorForm", () => {
205
199
  const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz") as HTMLTextAreaElement;
206
200
  fireEvent.change(targetInput, { target: { value: "https://acme.com/landing" } });
207
201
 
208
- // Open UTM builder
209
202
  const utmBtn = screen.getByRole("button", { name: "UTM" });
210
203
  fireEvent.click(utmBtn);
211
204
 
@@ -219,7 +212,6 @@ describe("LinkEditorForm", () => {
219
212
  fireEvent.change(screen.getByPlaceholderText("utm_term"), { target: { value: "discount" } });
220
213
  fireEvent.change(screen.getByPlaceholderText("utm_content"), { target: { value: "header-link" } });
221
214
 
222
- // Apply UTM
223
215
  const applyBtn = screen.getByRole("button", { name: "Apply UTM parameters" });
224
216
  fireEvent.click(applyBtn);
225
217
 
@@ -235,28 +227,23 @@ describe("LinkEditorForm", () => {
235
227
  </I18nProvider>
236
228
  );
237
229
 
238
- // Add rule
239
230
  const addRuleBtn = screen.getByRole("button", { name: "Add rule" });
240
231
  fireEvent.click(addRuleBtn);
241
232
 
242
- // Initial added rule is split with weight 50
243
233
  expect(screen.getByPlaceholderText("Target URL")).toBeDefined();
244
234
  expect(screen.getByText(/Remaining to control: 50%/)).toBeDefined();
245
235
 
246
236
  const ruleTarget = screen.getByPlaceholderText("Target URL");
247
237
  fireEvent.change(ruleTarget, { target: { value: "https://acme.com/split-target" } });
248
238
 
249
- // Add a second rule
250
239
  fireEvent.click(addRuleBtn);
251
240
  const ruleTargets = screen.getAllByPlaceholderText("Target URL");
252
241
  expect(ruleTargets.length).toBe(2);
253
242
 
254
- // Delete first rule
255
243
  const deleteButtons = screen.getAllByRole("button").filter(b => b.querySelector("svg.lucide-trash-2"));
256
244
  expect(deleteButtons.length).toBe(2);
257
245
  fireEvent.click(deleteButtons[0]);
258
246
 
259
- // Only one rule remains
260
247
  expect(screen.getAllByPlaceholderText("Target URL").length).toBe(1);
261
248
  });
262
249
 
@@ -267,7 +254,7 @@ describe("LinkEditorForm", () => {
267
254
  const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
268
255
  const urlObj = new URL(rawUrl, "http://localhost");
269
256
 
270
- if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
257
+ if (method === "GET" && urlObj.pathname === "/api/links/ai/status") {
271
258
  return jsonResponse({ configured: false, provider: "" });
272
259
  }
273
260
  if (method === "POST" && urlObj.pathname === "/api/links") {
@@ -285,42 +272,34 @@ describe("LinkEditorForm", () => {
285
272
  </I18nProvider>
286
273
  );
287
274
 
288
- // Fill target
289
275
  fireEvent.change(screen.getByPlaceholderText("https://example.com/blog-post-xyz"), {
290
276
  target: { value: "https://acme.com/special-promo" },
291
277
  });
292
278
 
293
- // Fill slug
294
279
  fireEvent.change(screen.getByPlaceholderText("e.g. promo2026"), {
295
280
  target: { value: "special-slug" },
296
281
  });
297
282
 
298
- // Fill title
299
283
  fireEvent.change(screen.getByPlaceholderText("Auto-populated title for page previews"), {
300
284
  target: { value: "Special Title" },
301
285
  });
302
286
 
303
- // Fill tags
304
287
  fireEvent.change(screen.getByPlaceholderText("e.g. q3-ads, product-hunt"), {
305
288
  target: { value: "vip, promo" },
306
289
  });
307
290
 
308
- // Fill note
309
291
  fireEvent.change(screen.getByPlaceholderText("Notes visible only to team members"), {
310
292
  target: { value: "Campaign Q4" },
311
293
  });
312
294
 
313
- // Fill password
314
295
  fireEvent.change(screen.getByPlaceholderText("e.g. 123456"), {
315
296
  target: { value: "supersecret" },
316
297
  });
317
298
 
318
- // Fill redirectUrl after expiry
319
299
  fireEvent.change(screen.getByPlaceholderText("e.g. https://my-site.com/expired"), {
320
300
  target: { value: "https://acme.com/expired" },
321
301
  });
322
302
 
323
- // Submit
324
303
  const saveBtn = screen.getByRole("button", { name: "Save link" });
325
304
  fireEvent.click(saveBtn);
326
305
 
@@ -348,7 +327,7 @@ describe("LinkEditorForm", () => {
348
327
  const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
349
328
  const urlObj = new URL(rawUrl, "http://localhost");
350
329
 
351
- if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
330
+ if (method === "GET" && urlObj.pathname === "/api/links/ai/status") {
352
331
  return jsonResponse({ configured: false, provider: "" });
353
332
  }
354
333
  if (method === "PUT" && urlObj.pathname === "/api/links/101") {
@@ -371,7 +350,6 @@ describe("LinkEditorForm", () => {
371
350
  </I18nProvider>
372
351
  );
373
352
 
374
- // Verify existing fields are filled
375
353
  const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz") as HTMLTextAreaElement;
376
354
  expect(targetInput.value).toBe("https://acme.com/spring-sale");
377
355
 
@@ -385,9 +363,8 @@ describe("LinkEditorForm", () => {
385
363
  expect(tagsInput.value).toBe("promo, spring, sale");
386
364
 
387
365
  expect(screen.getByPlaceholderText("e.g. 123456")).toBeDefined();
388
- expect(screen.getByText("Optional password check")).toBeDefined();
366
+ expect(screen.getByText("Key set. Fill to overwrite, blank to keep")).toBeDefined();
389
367
 
390
- // Modify title and submit
391
368
  fireEvent.change(titleInput, { target: { value: "Updated Spring Promo 2026" } });
392
369
  const saveBtn = screen.getByRole("button", { name: "Save link" });
393
370
  fireEvent.click(saveBtn);
@@ -407,7 +384,7 @@ describe("LinkEditorForm", () => {
407
384
  const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
408
385
  const urlObj = new URL(rawUrl, "http://localhost");
409
386
 
410
- if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
387
+ if (method === "GET" && urlObj.pathname === "/api/links/ai/status") {
411
388
  return jsonResponse({ configured: false, provider: "" });
412
389
  }
413
390
  if (method === "POST" && urlObj.pathname === "/api/links") {
@@ -439,7 +416,7 @@ describe("LinkEditorForm", () => {
439
416
  const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
440
417
  const urlObj = new URL(rawUrl, "http://localhost");
441
418
 
442
- if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
419
+ if (method === "GET" && urlObj.pathname === "/api/links/ai/status") {
443
420
  return jsonResponse({ configured: false, provider: "" });
444
421
  }
445
422
  if (method === "POST" && urlObj.pathname === "/api/links") {
@@ -501,7 +478,7 @@ describe("LinkEditorForm", () => {
501
478
  if (urlObj.pathname === "/api/links/capabilities") {
502
479
  return jsonResponse({ geoReady: true, mode: "configured" });
503
480
  }
504
- if (urlObj.pathname === "/api/ai/assist/status") {
481
+ if (urlObj.pathname === "/api/links/ai/status") {
505
482
  return jsonResponse({ configured: false });
506
483
  }
507
484
  return jsonResponse({});
@@ -530,7 +507,7 @@ describe("LinkEditorForm", () => {
530
507
  if (urlObj.pathname === "/api/links/capabilities") {
531
508
  return jsonResponse({ geoReady: false, mode: "unavailable" });
532
509
  }
533
- if (urlObj.pathname === "/api/ai/assist/status") {
510
+ if (urlObj.pathname === "/api/links/ai/status") {
534
511
  return jsonResponse({ configured: false });
535
512
  }
536
513
  return jsonResponse({});
@@ -589,4 +566,70 @@ describe("LinkEditorForm", () => {
589
566
  });
590
567
  }
591
568
  });
569
+
570
+ it("converts UTC ISO and local datetime-local values without timezone drift", () => {
571
+ const iso = "2026-12-31T23:59:00.000Z";
572
+ const localStr = toLocalDatetimeInput(iso);
573
+ const expected = (() => {
574
+ const d = new Date(iso);
575
+ const pad = (n: number) => String(n).padStart(2, "0");
576
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
577
+ })();
578
+ expect(localStr).toBe(expected);
579
+ expect(localDatetimeInputToISO(localStr)).toBe(iso);
580
+
581
+ expect(toLocalDatetimeInput(null)).toBe("");
582
+ expect(toLocalDatetimeInput("not-a-date")).toBe("");
583
+ expect(localDatetimeInputToISO("")).toBeNull();
584
+ expect(localDatetimeInputToISO(null)).toBeNull();
585
+ });
586
+
587
+ it("preserves expiresAt UTC timestamp on edit round-trip and supports clearing", async () => {
588
+ let putPayloads: any[] = [];
589
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
590
+ const method = (init?.method ?? "GET").toUpperCase();
591
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
592
+ const urlObj = new URL(rawUrl, "http://localhost");
593
+ if (method === "GET" && urlObj.pathname === "/api/links/ai/status") {
594
+ return jsonResponse({ configured: false, provider: "" });
595
+ }
596
+ if (method === "GET" && urlObj.pathname === "/api/links/capabilities") {
597
+ return jsonResponse({ geoReady: false, mode: "unavailable" });
598
+ }
599
+ if (method === "PUT" && urlObj.pathname === "/api/links/101") {
600
+ const body = JSON.parse(init?.body as string);
601
+ putPayloads.push(body);
602
+ return jsonResponse({ ...existingMockLink, ...body });
603
+ }
604
+ throw new Error(`Unexpected request: ${method} ${rawUrl}`);
605
+ });
606
+
607
+ const { container } = render(
608
+ <I18nProvider>
609
+ <LinkEditorForm
610
+ link={existingMockLink}
611
+ hosts={["link.acme.com"]}
612
+ onCancel={vi.fn()}
613
+ onSaved={vi.fn()}
614
+ />
615
+ </I18nProvider>
616
+ );
617
+
618
+ const dtInput = container.querySelector('input[type="datetime-local"]') as HTMLInputElement;
619
+ expect(dtInput).not.toBeNull();
620
+ expect(dtInput.value).toBe(toLocalDatetimeInput(existingMockLink.expiresAt));
621
+
622
+ fireEvent.click(screen.getByRole("button", { name: "Save link" }));
623
+ await waitFor(() => {
624
+ expect(putPayloads.length).toBe(1);
625
+ });
626
+ expect(putPayloads[0].expiresAt).toBe("2026-12-31T23:59:00.000Z");
627
+
628
+ fireEvent.change(dtInput, { target: { value: "" } });
629
+ fireEvent.click(screen.getByRole("button", { name: "Save link" }));
630
+ await waitFor(() => {
631
+ expect(putPayloads.length).toBe(2);
632
+ });
633
+ expect(putPayloads[1].expiresAt).toBeNull();
634
+ });
592
635
  });
@@ -1,7 +1,7 @@
1
- import { Field, Switch, Button, Select, FormError, Input, Textarea, Alert, Badge, useTranslation } from "@octarq/plugin-sdk";
1
+ import { Field, Switch, Button, Select, FormError, Input, Textarea, Alert, StatusBadge, useTranslation } from "@octarq/plugin-sdk";
2
2
  import { useEffect, useState } from "react";
3
3
  import { useNavigate, useInRouterContext } from "react-router-dom";
4
- import { api, linksApi, Link, LinksCapabilities } from "../api";
4
+ import { linksApi, linksAiStatus, suggestLinkSlug, Link, LinksCapabilities } from "../api";
5
5
  import { Sparkles, Trash2, Plus } from "lucide-react";
6
6
 
7
7
  function DomainConfigNavButton({ onClick, label }: { onClick: () => void; label: string }) {
@@ -43,6 +43,26 @@ function RouterDomainConfigNavButton({ onClick, label }: { onClick: () => void;
43
43
  );
44
44
  }
45
45
 
46
+ export function toLocalDatetimeInput(iso?: string | null): string {
47
+ if (!iso) return "";
48
+ const d = new Date(iso);
49
+ if (Number.isNaN(d.getTime())) return "";
50
+ const pad = (n: number) => String(n).padStart(2, "0");
51
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
52
+ }
53
+
54
+ export function localDatetimeInputToISO(value?: string | null): string | null {
55
+ if (!value) return null;
56
+ const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(value.trim());
57
+ if (m) {
58
+ const [, y, mo, da, hh, mm, ss] = m;
59
+ const d = new Date(Number(y), Number(mo) - 1, Number(da), Number(hh), Number(mm), Number(ss ?? 0));
60
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
61
+ }
62
+ const d = new Date(value);
63
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
64
+ }
65
+
46
66
  export function LinkEditorForm({
47
67
  link,
48
68
  hosts: rawHosts = [],
@@ -57,16 +77,13 @@ export function LinkEditorForm({
57
77
  const hosts = rawHosts ?? [];
58
78
  const { t } = useTranslation();
59
79
  const [slug, setSlug] = useState(link?.slug ?? "");
60
- // New links default to the first real link host when one exists; editing an
61
- // existing link always keeps its own host. A bare "" default would drop every
62
- // new Cloud link into the cross-tenant host='' shared pool.
63
80
  const [host, setHost] = useState(() => (link ? (link.host ?? "") : hosts.length > 0 ? hosts[0] : ""));
64
81
  const [target, setTarget] = useState(link?.target ?? "");
65
82
  const [title, setTitle] = useState(link?.title ?? "");
66
83
  const [note, setNote] = useState(link?.note ?? "");
67
84
  const [tags, setTags] = useState(link?.tags ?? "");
68
- const [password, setPassword] = useState(link?.password ?? "");
69
- const [expiresAt, setExpiresAt] = useState(link?.expiresAt?.slice(0, 16) ?? "");
85
+ const [password, setPassword] = useState("");
86
+ const [expiresAt, setExpiresAt] = useState(() => toLocalDatetimeInput(link?.expiresAt));
70
87
  const [expiredUrl, setExpiredUrl] = useState(link?.expiredUrl ?? "");
71
88
  const [clickLimit, setClickLimit] = useState(link?.clickLimit ?? 0);
72
89
  const [enabled, setEnabled] = useState(link?.enabled ?? true);
@@ -80,7 +97,7 @@ export function LinkEditorForm({
80
97
  const [geoCapabilities, setGeoCapabilities] = useState<LinksCapabilities | null>(null);
81
98
 
82
99
  useEffect(() => {
83
- api.aiAssistStatus().then((s) => setAiEnabled(s.configured)).catch(() => {});
100
+ linksAiStatus().then((s) => setAiEnabled(s.configured)).catch(() => {});
84
101
  linksApi.capabilities().then(setGeoCapabilities).catch(() => setGeoCapabilities({ geoReady: false, mode: "unavailable" }));
85
102
  }, []);
86
103
 
@@ -89,7 +106,7 @@ export function LinkEditorForm({
89
106
  setAiBusy(true);
90
107
  setAiSlugs([]);
91
108
  try {
92
- const r = await api.aiSuggestSlug(target, title || undefined);
109
+ const r = await suggestLinkSlug(target, title || undefined);
93
110
  setAiSlugs(r.slugs);
94
111
  } catch {
95
112
  setErr(t("links.aiSuggestFailed"));
@@ -105,7 +122,6 @@ export function LinkEditorForm({
105
122
  const m = await linksApi.linkMetadata(target);
106
123
  if (m.title) setTitle(m.title);
107
124
  } catch {
108
- /* ignore */
109
125
  } finally {
110
126
  setFetching(false);
111
127
  }
@@ -120,22 +136,21 @@ export function LinkEditorForm({
120
136
  title,
121
137
  note,
122
138
  tags,
123
- password,
124
139
  enabled,
125
140
  expiredUrl,
126
141
  routingRules,
127
142
  clickLimit: Number(clickLimit) || 0,
128
- expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null,
143
+ expiresAt: localDatetimeInputToISO(expiresAt),
129
144
  };
145
+ if (password !== "") {
146
+ payload.password = password;
147
+ }
130
148
  try {
131
149
  let res;
132
150
  if (link) res = await linksApi.updateLink(link.id, payload);
133
151
  else res = await linksApi.createLink(payload);
134
152
  onSaved(res);
135
153
  } catch (e: any) {
136
- // The backend refuses hostless links on multi-tenant instances. That
137
- // specific 400 gets a localized line; everything else keeps the server's
138
- // own message (FormError's normal contract).
139
154
  if (e?.status === 400 && typeof e?.message === "string" && e.message.includes("host is required")) {
140
155
  setErr({ message: t("links.hostRequired"), status: 400, requestId: e.requestId });
141
156
  } else {
@@ -209,9 +224,6 @@ export function LinkEditorForm({
209
224
  value={host}
210
225
  onValueChange={setHost}
211
226
  options={[
212
- // The hostless "Default (Apex Domain)" option is only offered when
213
- // no link host exists; once one does, exposing it would let users
214
- // drop their links back into the shared host='' pool.
215
227
  ...(hosts.length === 0 ? [{ value: "", label: t("links.defaultApexDomain") }] : []),
216
228
  ...hosts.map((h) => ({ value: h, label: h })),
217
229
  ...(host && !hosts.includes(host) ? [{ value: host, label: host }] : []),
@@ -238,8 +250,8 @@ export function LinkEditorForm({
238
250
  </Field>
239
251
 
240
252
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 min-w-0">
241
- <Field label={t("links.accessProtectionPassword")} hint={t("links.passwordOptionalHint")}>
242
- <Input className="w-full font-mono text-sm min-w-0" type="text" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="e.g. 123456" />
253
+ <Field label={t("links.accessProtectionPassword")} hint={link?.hasPassword ? t("links.passwordSetHint") : t("links.passwordOptionalHint")}>
254
+ <Input className="w-full font-mono text-sm min-w-0" type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="e.g. 123456" />
243
255
  </Field>
244
256
  <Field label={t("links.totalClickLimitation")} hint={t("links.clickLimitHint")}>
245
257
  <Input
@@ -307,7 +319,6 @@ function UtmBuilder({ target, onApply }: { target: string; onApply: (url: string
307
319
  }
308
320
  onApply(u.toString());
309
321
  } catch {
310
- /* ignore */
311
322
  }
312
323
  }
313
324
  const fields: [keyof typeof utm, string][] = [
@@ -318,7 +329,7 @@ function UtmBuilder({ target, onApply }: { target: string; onApply: (url: string
318
329
  ["content", "content"],
319
330
  ];
320
331
  return (
321
- <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2.5 p-4 bg-well border border-border rounded-xl min-w-0">
332
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2.5 p-4 bg-well border border-border rounded-lg min-w-0">
322
333
  {fields.map(([k, label]) => (
323
334
  <Input
324
335
  key={k}
@@ -404,13 +415,13 @@ function RoutingRulesEditor({ rules, onChange, geoReady }: { rules: any[]; onCha
404
415
  {rule.type === "geo" && (
405
416
  <div className="flex items-center gap-2 pt-0.5">
406
417
  {geoReady ? (
407
- <Badge tone="green" shape="dot">
418
+ <StatusBadge tone="success" shape="dot">
408
419
  {t("links.geoReady", "GeoIP Active")}
409
- </Badge>
420
+ </StatusBadge>
410
421
  ) : (
411
- <Badge tone="amber" shape="dash" title={t("links.geoUnavailableDesc", "Server lacks GeoIP database. Country routing is bypassed.")}>
422
+ <StatusBadge tone="warning" shape="dash" title={t("links.geoUnavailableDesc", "Server lacks GeoIP database. Country routing is bypassed.")}>
412
423
  {t("links.geoUnavailable", "GeoIP Unavailable (bypassed)")}
413
- </Badge>
424
+ </StatusBadge>
414
425
  )}
415
426
  {!geoReady && (
416
427
  <span className="text-[11px] text-warning-fg">
@@ -39,7 +39,6 @@ export function LinkModals({
39
39
 
40
40
  return (
41
41
  <>
42
- {/* Create New Link Modal */}
43
42
  {createOpen && (
44
43
  <Modal title={t("links.createNewLink")} onClose={onCloseCreate}>
45
44
  <div className="p-1">
@@ -56,7 +55,6 @@ export function LinkModals({
56
55
  </Modal>
57
56
  )}
58
57
 
59
- {/* Edit Link Modal */}
60
58
  {editingLink && (
61
59
  <Modal
62
60
  title={`${t("links.editLink")} — ${editingLink.title || `/${editingLink.slug}`}`}
@@ -77,7 +75,6 @@ export function LinkModals({
77
75
  </Modal>
78
76
  )}
79
77
 
80
- {/* Analytics Modal */}
81
78
  {analyticsLink && (
82
79
  <Modal
83
80
  title={`${t("links.clickPerformanceAnalytics")} — ${analyticsLink.title || `/${analyticsLink.slug}`}`}
@@ -89,14 +86,14 @@ export function LinkModals({
89
86
  </Modal>
90
87
  )}
91
88
 
92
- {/* QR Code Modal */}
93
89
  {qrLink && (
94
90
  <Modal
95
91
  title={`${t("links.linkQrCode")} — ${qrLink.title || `/${qrLink.slug}`}`}
96
92
  onClose={onCloseQr}
97
93
  >
98
94
  <div className="flex flex-col items-center gap-5 py-4">
99
- <div className="bg-white p-5 rounded-2xl shadow-sm border border-border">
95
+ {/* ui-color-ok: QR modules require a solid white quiet zone in both light and dark themes */}
96
+ <div className="rounded-lg border border-border bg-white p-4">
100
97
  <img
101
98
  src={`/api/links/${qrLink.id}/qr`}
102
99
  alt={t("links.qrAlt")}