@octarq/plugin-links 0.0.0-stage → 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,177 @@
1
+ import { Badge, Button, StatusBadge, TD, TR, useTranslation } from "@octarq/plugin-sdk";
2
+ import { Link } from "../api";
3
+ import { Copy, Check, Archive, Trash2, QrCode, ExternalLink, Lock, Bot, Clock, Tag, BarChart3, Edit3 } from "lucide-react";
4
+
5
+ export interface LinkTableRowProps {
6
+ link: Link;
7
+ isCopied: boolean;
8
+ canDeleteLink: boolean;
9
+ onCopy: (l: Link) => void;
10
+ onAnalytics: (l: Link) => void;
11
+ onQr: (l: Link) => void;
12
+ onEdit: (l: Link) => void;
13
+ onToggleArchive: (l: Link) => void;
14
+ onDelete: (l: Link) => void;
15
+ linkURL: (l: Link) => string;
16
+ }
17
+
18
+ export function LinkTableRow({
19
+ link: l,
20
+ isCopied,
21
+ canDeleteLink,
22
+ onCopy,
23
+ onAnalytics,
24
+ onQr,
25
+ onEdit,
26
+ onToggleArchive,
27
+ onDelete,
28
+ linkURL,
29
+ }: LinkTableRowProps) {
30
+ const { t } = useTranslation();
31
+ const tagList = (l.tags || "").split(",").map((tag) => tag.trim()).filter(Boolean);
32
+ const displayTitle = l.title || l.slug;
33
+
34
+ return (
35
+ <TR key={l.id} className="hover:bg-well transition-colors group">
36
+ <TD>
37
+ <div className="flex flex-col gap-1">
38
+ <div className="text-sm font-medium text-foreground truncate max-w-[260px]" title={displayTitle}>
39
+ {displayTitle}
40
+ </div>
41
+ <div className="flex items-center gap-1.5">
42
+ <span className="font-mono text-xs text-muted-foreground truncate max-w-[200px]">
43
+ {l.host ? `${l.host}/` : "/"}
44
+ <span>{l.slug}</span>
45
+ </span>
46
+ <button
47
+ type="button"
48
+ onClick={() => onCopy(l)}
49
+ title={t("links.copyLink")}
50
+ aria-label={t("links.copyLink")}
51
+ className="p-0.5 text-muted-foreground hover:text-foreground rounded transition-colors cursor-pointer"
52
+ >
53
+ {isCopied ? (
54
+ <Check className="h-3.5 w-3.5 text-success-fg" />
55
+ ) : (
56
+ <Copy className="h-3.5 w-3.5" />
57
+ )}
58
+ </button>
59
+ <a
60
+ href={linkURL(l)}
61
+ target="_blank"
62
+ rel="noreferrer"
63
+ title={t("links.openLink")}
64
+ aria-label={t("links.openLink")}
65
+ className="p-0.5 text-muted-foreground hover:text-accent-fg rounded transition-colors"
66
+ >
67
+ <ExternalLink className="h-3.5 w-3.5" />
68
+ </a>
69
+ </div>
70
+ {tagList.length > 0 && (
71
+ <div className="flex items-center gap-1 flex-wrap mt-0.5">
72
+ {tagList.map((tag) => (
73
+ <span
74
+ key={tag}
75
+ title={tag}
76
+ aria-label={tag}
77
+ className="inline-flex items-center gap-0.5 text-[10px] text-muted-foreground bg-surface-hover px-1.5 py-0.5 rounded font-mono"
78
+ >
79
+ <Tag className="h-2.5 w-2.5 text-muted-foreground" />
80
+ <span className="truncate max-w-[120px]">{tag}</span>
81
+ </span>
82
+ ))}
83
+ </div>
84
+ )}
85
+ </div>
86
+ </TD>
87
+
88
+ <TD className="max-w-[320px] align-top">
89
+ <div className="flex flex-col gap-1">
90
+ <div className="max-w-[320px] whitespace-normal break-all font-mono text-xs text-foreground" title={l.target}>
91
+ {l.target}
92
+ </div>
93
+ <div className="flex items-center gap-1.5 flex-wrap">
94
+ {l.hasPassword && (
95
+ <span
96
+ className="inline-flex items-center gap-1 text-[10px] text-warning-fg bg-warning-bg px-1.5 py-0.5 rounded font-mono"
97
+ title={t("links.accessProtectionPassword")}
98
+ >
99
+ <Lock className="h-2.5 w-2.5" />
100
+ </span>
101
+ )}
102
+ {l.routingRules?.length ? (
103
+ <span className="inline-flex items-center gap-0.5 text-[10px] text-accent-fg bg-accent-soft px-1.5 py-0.5 rounded" title={t("links.routingRules")}>
104
+ <Bot className="h-2.5 w-2.5" />
105
+ {l.routingRules.length}
106
+ </span>
107
+ ) : null}
108
+ {l.expiresAt && (
109
+ <span className="inline-flex items-center gap-0.5 text-[10px] text-muted-foreground bg-well px-1.5 py-0.5 rounded" title={new Date(l.expiresAt).toLocaleString()}>
110
+ <Clock className="h-2.5 w-2.5" />
111
+ </span>
112
+ )}
113
+ </div>
114
+ </div>
115
+ </TD>
116
+
117
+ <TD className="text-center font-mono">
118
+ <Badge tone="default" className="text-xs font-semibold">
119
+ {l.clicks || 0}
120
+ </Badge>
121
+ </TD>
122
+
123
+ <TD className="text-center">
124
+ <StatusBadge tone={l.archived ? "paused" : "success"} className="text-[10px]">
125
+ {l.archived ? t("links.archived") : t("links.active")}
126
+ </StatusBadge>
127
+ </TD>
128
+
129
+ <TD className="text-right">
130
+ <div className="flex items-center justify-end gap-1.5">
131
+ <Button
132
+ variant="ghost"
133
+ className="p-1.5 text-xs text-muted-foreground hover:text-accent-fg"
134
+ title={t("links.tabAnalytics")}
135
+ onClick={() => onAnalytics(l)}
136
+ >
137
+ <BarChart3 className="h-4 w-4" />
138
+ </Button>
139
+ <Button
140
+ variant="ghost"
141
+ className="p-1.5 text-xs text-muted-foreground hover:text-foreground"
142
+ title={t("links.tabQr")}
143
+ onClick={() => onQr(l)}
144
+ >
145
+ <QrCode className="h-4 w-4" />
146
+ </Button>
147
+ <Button
148
+ variant="ghost"
149
+ className="p-1.5 text-xs text-muted-foreground hover:text-foreground"
150
+ title={t("links.editLink")}
151
+ onClick={() => onEdit(l)}
152
+ >
153
+ <Edit3 className="h-4 w-4" />
154
+ </Button>
155
+ <Button
156
+ variant="ghost"
157
+ className="p-1.5 text-xs text-muted-foreground hover:text-foreground"
158
+ title={l.archived ? t("links.unarchive") : t("links.archive")}
159
+ onClick={() => onToggleArchive(l)}
160
+ >
161
+ <Archive className="h-4 w-4" />
162
+ </Button>
163
+ {canDeleteLink && (
164
+ <Button
165
+ variant="ghost"
166
+ className="p-1.5 text-xs text-danger-fg/70 hover:text-danger-fg"
167
+ title={t("links.delete")}
168
+ onClick={() => onDelete(l)}
169
+ >
170
+ <Trash2 className="h-4 w-4" />
171
+ </Button>
172
+ )}
173
+ </div>
174
+ </TD>
175
+ </TR>
176
+ );
177
+ }
@@ -0,0 +1,161 @@
1
+ import { Skeleton, StatCard, useTranslation } from "@octarq/plugin-sdk";
2
+ import { useEffect, useState } from "react";
3
+ import { linksApi, Link, LinkStats } from "../api";
4
+ import { Link2, Eye, ExternalLink, Tag, Globe, Settings, Share2, Filter, Target } from "lucide-react";
5
+
6
+ export function StatsView({ link }: { link: Link }) {
7
+ const { t } = useTranslation();
8
+ const [metric, setMetric] = useState<"uv" | "pv">("uv");
9
+ const [stats, setStats] = useState<LinkStats | null>(null);
10
+
11
+ useEffect(() => {
12
+ setStats(null);
13
+ linksApi.linkStats(link.id, 30, metric).then(setStats);
14
+ }, [link.id, metric]);
15
+
16
+ if (!stats) {
17
+ return (
18
+ <div
19
+ role="status"
20
+ aria-busy="true"
21
+ aria-label={t("links.loadingAnalytics")}
22
+ className="space-y-5 min-w-0"
23
+ >
24
+ <div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
25
+ <Skeleton className="h-5 w-48" />
26
+ <div className="flex items-center gap-2 shrink-0">
27
+ <Skeleton className="h-4 w-20" />
28
+ <Skeleton className="h-7 w-24 rounded-lg" />
29
+ </div>
30
+ </div>
31
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 min-w-0">
32
+ {Array.from({ length: 3 }).map((_, i) => (
33
+ <div key={i} className="rounded-lg border border-border bg-card p-5 space-y-3">
34
+ <Skeleton className="h-3.5 w-24" />
35
+ <Skeleton className="h-7 w-16" />
36
+ </div>
37
+ ))}
38
+ </div>
39
+ <div className="rounded-lg bg-well border border-border flex h-24 items-end gap-1.5 p-3 min-w-0 overflow-hidden">
40
+ {Array.from({ length: 14 }).map((_, i) => (
41
+ <Skeleton key={i} className="flex-1 rounded-t-md" style={{ height: `${30 + ((i * 19) % 60)}%` }} />
42
+ ))}
43
+ </div>
44
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6 pt-2 border-t border-border min-w-0">
45
+ {Array.from({ length: 6 }).map((_, i) => (
46
+ <div key={i} className="space-y-2 min-w-0">
47
+ <Skeleton className="h-3 w-24" />
48
+ <div className="space-y-1.5">
49
+ <Skeleton className="h-3.5 w-full" />
50
+ <Skeleton className="h-3.5 w-5/6" />
51
+ <Skeleton className="h-3.5 w-2/3" />
52
+ </div>
53
+ </div>
54
+ ))}
55
+ </div>
56
+ </div>
57
+ );
58
+ }
59
+
60
+ return (
61
+ <div className="space-y-5 min-w-0">
62
+ <div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
63
+ <h3 className="text-sm font-semibold text-foreground uppercase tracking-wider flex items-center gap-1.5 min-w-0">
64
+ <Eye className="h-4 w-4 text-accent-fg shrink-0" />
65
+ <span className="truncate">{t("links.clickPerformanceAnalytics")}</span>
66
+ </h3>
67
+ <div className="flex items-center gap-2 shrink-0">
68
+ <span className="text-xs text-muted-foreground font-medium">
69
+ {t("links.metricMode", { mode: metric === "uv" ? t("links.uvLabel") : t("links.pvLabel") })}
70
+ </span>
71
+ <div className="inline-flex rounded-lg bg-well p-0.5 border border-border">
72
+ <button
73
+ type="button"
74
+ onClick={() => setMetric("uv")}
75
+ className={`px-2.5 py-1 text-xs font-medium rounded-md border transition-colors ${
76
+ metric === "uv"
77
+ ? "bg-card text-foreground border-border"
78
+ : "border-transparent text-muted-foreground hover:text-foreground"
79
+ }`}
80
+ >
81
+ {t("links.uvShort")}
82
+ </button>
83
+ <button
84
+ type="button"
85
+ onClick={() => setMetric("pv")}
86
+ className={`px-2.5 py-1 text-xs font-medium rounded-md border transition-colors ${
87
+ metric === "pv"
88
+ ? "bg-card text-foreground border-border"
89
+ : "border-transparent text-muted-foreground hover:text-foreground"
90
+ }`}
91
+ >
92
+ {t("links.pvShort")}
93
+ </button>
94
+ </div>
95
+ </div>
96
+ </div>
97
+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 min-w-0">
98
+ <StatCard label={t("links.totalClicks")} value={stats.total} index={0} />
99
+ <StatCard label={t("links.lastDays", { days: stats.days })} value={stats.windowed} index={1} />
100
+ <StatCard label={t("links.trackingWindow")} value={t("links.daysWindowUnit", { days: stats.series?.length || 0 })} index={2} />
101
+ </div>
102
+ <Spark series={stats.series} />
103
+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6 pt-2 border-t border-border min-w-0">
104
+ <TopList title={t("links.channels")} icon={<Share2 className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.channels} />
105
+ <TopList title={t("links.utmSources")} icon={<Tag className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.utmSources} />
106
+ <TopList title={t("links.utmMediums")} icon={<Filter className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.utmMediums} />
107
+ <TopList title={t("links.utmCampaigns")} icon={<Target className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.utmCampaigns} />
108
+ <TopList title={t("links.countries")} icon={<Globe className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.countries} />
109
+ <TopList title={t("links.regions")} icon={<ExternalLink className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.regions} />
110
+ <TopList title={t("links.devices")} icon={<Eye className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.devices} />
111
+ <TopList title={t("links.browsers")} icon={<Link2 className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.browsers} />
112
+ <TopList title={t("links.referers")} icon={<Tag className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.referers} />
113
+ {stats.variants && (
114
+ <TopList title={t("links.variants")} icon={<Settings className="h-3 w-3 text-muted-foreground mr-1 inline shrink-0" />} rows={stats.variants} />
115
+ )}
116
+ </div>
117
+ </div>
118
+ );
119
+ }
120
+
121
+ function Spark({ series }: { series: { key: string; count: number }[] }) {
122
+ const { t } = useTranslation();
123
+ if (!series || !series.length) return <p className="text-xs text-muted-foreground italic">{t("links.noClickData")}</p>;
124
+ const max = Math.max(...series.map((s) => s.count), 1);
125
+ return (
126
+ <div className="rounded-lg bg-well border border-border flex h-24 items-end gap-1 p-3 min-w-0 overflow-hidden">
127
+ {series.map((s) => (
128
+ <div
129
+ key={s.key}
130
+ title={t("links.clicksTooltip", { key: s.key, count: s.count })}
131
+ className="flex-1 min-w-[2px] rounded-t-md bg-primary/70 hover:bg-primary transition-all cursor-pointer"
132
+ style={{ height: `${(s.count / max) * 100}%`, minHeight: 3 }}
133
+ />
134
+ ))}
135
+ </div>
136
+ );
137
+ }
138
+
139
+ function TopList({ title, icon, rows }: { title: string; icon?: React.ReactNode; rows: { key: string; count: number }[] | null }) {
140
+ const { t } = useTranslation();
141
+ return (
142
+ <div className="space-y-2 min-w-0">
143
+ <div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground flex items-center min-w-0">
144
+ {icon}
145
+ <span className="truncate">{title}</span>
146
+ </div>
147
+ {!rows || rows.length === 0 ? (
148
+ <p className="text-xs text-muted-foreground italic">{t("links.emptyDash")}</p>
149
+ ) : (
150
+ <div className="space-y-1.5 min-w-0">
151
+ {rows.map((r) => (
152
+ <div key={r.key} className="flex justify-between items-center text-xs font-normal min-w-0 gap-2">
153
+ <span className="truncate text-muted-foreground font-mono min-w-0 flex-1" title={r.key || t("links.directUnknown")}>{r.key || t("links.direct")}</span>
154
+ <span className="font-mono tnum text-muted-foreground font-semibold shrink-0">{r.count}</span>
155
+ </div>
156
+ ))}
157
+ </div>
158
+ )}
159
+ </div>
160
+ );
161
+ }
@@ -0,0 +1,77 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, it, expect, vi, beforeEach } from "vitest";
3
+ import { cleanup, render, screen, waitFor } from "@testing-library/react";
4
+ import { MemoryRouter } from "react-router-dom";
5
+ import { I18nProvider } from "@octarq/plugin-sdk";
6
+
7
+ vi.mock("@octarq/plugin-sdk", async (importOriginal) => {
8
+ const ui = await importOriginal<typeof import("@octarq/plugin-sdk")>();
9
+ return {
10
+ ...ui,
11
+ Empty: (props: { children?: React.ReactNode; reason?: React.ReactNode; detail?: React.ReactNode; action?: React.ReactNode }) => (
12
+ <div data-testid="shared-empty">
13
+ {props.children}
14
+ {props.reason}
15
+ {props.detail}
16
+ {props.action}
17
+ </div>
18
+ ),
19
+ };
20
+ });
21
+
22
+ vi.mock("../api", async (importOriginal) => {
23
+ const actual = await importOriginal<typeof import("../api")>();
24
+ return {
25
+ ...actual,
26
+ linksApi: {
27
+ ...actual.linksApi,
28
+ links: vi.fn().mockResolvedValue([]),
29
+ domains: vi.fn().mockResolvedValue([]),
30
+ },
31
+ api: {
32
+ ...actual.api,
33
+ links: vi.fn().mockResolvedValue([]),
34
+ domains: vi.fn().mockResolvedValue([]),
35
+ },
36
+ };
37
+ });
38
+
39
+ import LinksPage from "./index";
40
+
41
+ beforeEach(() => {
42
+ vi.clearAllMocks();
43
+ });
44
+
45
+ afterEach(cleanup);
46
+
47
+ describe("LinksPage empty state", () => {
48
+ it("renders the shared Empty when there are no links (not a handwritten copy)", async () => {
49
+ render(
50
+ <MemoryRouter initialEntries={["/links"]}>
51
+ <I18nProvider>
52
+ <LinksPage />
53
+ </I18nProvider>
54
+ </MemoryRouter>
55
+ );
56
+
57
+ await waitFor(() => {
58
+ expect(screen.getAllByTestId("shared-empty").length).toBeGreaterThan(0);
59
+ });
60
+ });
61
+
62
+ it("offers one create button while the list is empty", async () => {
63
+ render(
64
+ <MemoryRouter initialEntries={["/links"]}>
65
+ <I18nProvider>
66
+ <LinksPage />
67
+ </I18nProvider>
68
+ </MemoryRouter>
69
+ );
70
+
71
+ await waitFor(() => {
72
+ expect(screen.getAllByTestId("shared-empty").length).toBeGreaterThan(0);
73
+ });
74
+
75
+ expect(screen.getAllByRole("button", { name: "links.newLink" })).toHaveLength(1);
76
+ });
77
+ });
@@ -0,0 +1,108 @@
1
+ // @vitest-environment happy-dom
2
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
3
+ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
4
+ import { MemoryRouter } from "react-router-dom";
5
+ import { I18nProvider, registerUIPlugin, resetRegistry, toast } from "@octarq/plugin-sdk";
6
+ import linksPlugin from "../index";
7
+ import LinksPage from "./index";
8
+
9
+ function jsonResponse(body: unknown, status = 200) {
10
+ return {
11
+ ok: status >= 200 && status < 300,
12
+ status,
13
+ json: async () => body,
14
+ headers: { get: (name: string) => (name === "content-type" ? "application/json" : null) },
15
+ };
16
+ }
17
+
18
+ describe("LinksPage CSV Export", () => {
19
+ beforeEach(() => {
20
+ cleanup();
21
+ resetRegistry();
22
+ registerUIPlugin(linksPlugin);
23
+ });
24
+
25
+ afterEach(() => {
26
+ cleanup();
27
+ vi.restoreAllMocks();
28
+ });
29
+
30
+ it("downloads links.csv from GET /api/links/export.csv when Export CSV is clicked", async () => {
31
+ const csvContent = "ID,Host,Slug,Target,Title,Clicks,CreatedAt\n1,go.link,docs,https://example.com,Docs,5,2026-01-01T00:00:00Z\n";
32
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
33
+ const method = (init?.method ?? "GET").toUpperCase();
34
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
35
+ const path = new URL(rawUrl, "http://localhost").pathname;
36
+ if (method === "GET" && path === "/api/links") return jsonResponse([]);
37
+ if (method === "GET" && path === "/api/domains") return jsonResponse([]);
38
+ if (method === "GET" && path === "/api/links/export.csv") {
39
+ return {
40
+ ok: true,
41
+ status: 200,
42
+ blob: async () => new Blob([csvContent], { type: "text/csv" }),
43
+ headers: { get: () => "text/csv" },
44
+ };
45
+ }
46
+ throw new Error(`Unexpected fetch: ${method} ${rawUrl}`);
47
+ });
48
+ vi.stubGlobal("fetch", fetchMock);
49
+
50
+ const createObjectURLSpy = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:links-csv");
51
+ const revokeObjectURLSpy = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
52
+ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
53
+
54
+ render(
55
+ <MemoryRouter initialEntries={["/links"]}>
56
+ <I18nProvider>
57
+ <LinksPage />
58
+ </I18nProvider>
59
+ </MemoryRouter>
60
+ );
61
+
62
+ const exportBtn = await screen.findByRole("button", { name: "Export CSV" });
63
+ fireEvent.click(exportBtn);
64
+
65
+ await waitFor(() => {
66
+ expect(fetchMock).toHaveBeenCalledWith(
67
+ expect.stringContaining("/api/links/export.csv"),
68
+ expect.objectContaining({ credentials: "same-origin" })
69
+ );
70
+ });
71
+ await waitFor(() => {
72
+ expect(createObjectURLSpy).toHaveBeenCalledTimes(1);
73
+ expect(clickSpy).toHaveBeenCalledTimes(1);
74
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith("blob:links-csv");
75
+ });
76
+ });
77
+
78
+ it("shows toast.error when CSV export fails", async () => {
79
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
80
+ const method = (init?.method ?? "GET").toUpperCase();
81
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
82
+ const path = new URL(rawUrl, "http://localhost").pathname;
83
+ if (method === "GET" && path === "/api/links") return jsonResponse([]);
84
+ if (method === "GET" && path === "/api/domains") return jsonResponse([]);
85
+ if (method === "GET" && path === "/api/links/export.csv") {
86
+ return { ok: false, status: 500, headers: { get: () => "application/json" } };
87
+ }
88
+ throw new Error(`Unexpected fetch: ${method} ${rawUrl}`);
89
+ });
90
+ vi.stubGlobal("fetch", fetchMock);
91
+ const toastErrorSpy = vi.spyOn(toast, "error").mockImplementation(() => "" as any);
92
+
93
+ render(
94
+ <MemoryRouter initialEntries={["/links"]}>
95
+ <I18nProvider>
96
+ <LinksPage />
97
+ </I18nProvider>
98
+ </MemoryRouter>
99
+ );
100
+
101
+ const exportBtn = await screen.findByRole("button", { name: "Export CSV" });
102
+ fireEvent.click(exportBtn);
103
+
104
+ await waitFor(() => {
105
+ expect(toastErrorSpy).toHaveBeenCalledWith("Action failed. Try again.");
106
+ });
107
+ });
108
+ });
@@ -0,0 +1,72 @@
1
+ // @vitest-environment happy-dom
2
+ import { beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
4
+ import { MemoryRouter } from "react-router-dom";
5
+ import { registerUIPlugin, resetRegistry, I18nProvider } from "@octarq/plugin-sdk";
6
+ import linksPlugin from "../index";
7
+ import LinksPage from "./index";
8
+
9
+ function jsonResponse(body: unknown, status = 200) {
10
+ return {
11
+ ok: status >= 200 && status < 300,
12
+ status,
13
+ json: async () => body,
14
+ headers: { get: (name: string) => (name === "content-type" ? "application/json" : null) },
15
+ };
16
+ }
17
+
18
+ function renderPage() {
19
+ return render(
20
+ <MemoryRouter initialEntries={["/links"]}>
21
+ <I18nProvider>
22
+ <LinksPage />
23
+ </I18nProvider>
24
+ </MemoryRouter>
25
+ );
26
+ }
27
+
28
+ describe("LinksPage — failed list load", () => {
29
+ let linkStatus = 500;
30
+
31
+ beforeEach(() => {
32
+ cleanup();
33
+ resetRegistry();
34
+ registerUIPlugin(linksPlugin);
35
+ linkStatus = 500;
36
+ vi.stubGlobal(
37
+ "fetch",
38
+ vi.fn(async (input: RequestInfo | URL) => {
39
+ const raw =
40
+ typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
41
+ const path = new URL(raw, "http://localhost").pathname;
42
+ if (path === "/api/links") {
43
+ return linkStatus >= 400
44
+ ? jsonResponse({ message: "boom" }, linkStatus)
45
+ : jsonResponse([]);
46
+ }
47
+ if (path === "/api/domains") return jsonResponse([]);
48
+ throw new Error(`unexpected request in test: ${raw}`);
49
+ })
50
+ );
51
+ });
52
+
53
+ it("shows a retryable failure instead of the empty state", async () => {
54
+ renderPage();
55
+
56
+ expect(await screen.findByText("Failed to load data")).toBeTruthy();
57
+ expect(screen.getByText("HTTP 500")).toBeTruthy();
58
+ expect(screen.queryByText("This workspace has no short links yet.")).toBeNull();
59
+ expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
60
+ });
61
+
62
+ it("recovers to the real empty state when Retry succeeds", async () => {
63
+ renderPage();
64
+
65
+ const retry = await screen.findByRole("button", { name: "Retry" });
66
+ linkStatus = 200;
67
+ fireEvent.click(retry);
68
+
69
+ expect(await screen.findByText("This workspace has no short links yet.")).toBeTruthy();
70
+ expect(screen.queryByText("Failed to load data")).toBeNull();
71
+ });
72
+ });