strapi-plugin-magic-sessionmanager 4.20.0 → 4.22.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.
Files changed (33) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +104 -50
  3. package/dist/admin/{Analytics-B5GnwMtH.js → Analytics-DeDLGiCe.js} +1 -1
  4. package/dist/admin/{Analytics-B-MVQ6dQ.mjs → Analytics-WbCUmkQQ.mjs} +1 -1
  5. package/dist/admin/{App-xBOmg4g9.js → App-Bkv-W0Sv.js} +1640 -2561
  6. package/dist/admin/{App-DzbP5VPQ.mjs → App-C4bihk2K.mjs} +1610 -2531
  7. package/dist/admin/{OnlineUsersWidget-FuPPPCCV.js → OnlineUsersWidget-CSvNe2rC.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Bf3BICmx.mjs → OnlineUsersWidget-q0Z6nbbO.mjs} +1 -1
  9. package/dist/admin/{Settings-hpkloyO6.mjs → Settings-avD0DbXP.mjs} +17 -9
  10. package/dist/admin/{Settings-WRIXHLDa.js → Settings-xokFI5LO.js} +59 -51
  11. package/dist/admin/dashboardModel-BBNRgcEr.mjs +170 -0
  12. package/dist/admin/dashboardModel-D4389iIV.js +169 -0
  13. package/dist/admin/{de-Bzd14FzX.mjs → de-BQlEdBMr.mjs} +104 -4
  14. package/dist/admin/{de-Uqb30N5n.js → de-HcJ19LKI.js} +104 -4
  15. package/dist/admin/{en-CDBcocLk.js → en-DI-98CPM.js} +105 -5
  16. package/dist/admin/{en-DovyVwa5.mjs → en-DzuXWL1W.mjs} +105 -5
  17. package/dist/admin/{es-BygJxl1J.mjs → es-BfyED9YI.mjs} +104 -4
  18. package/dist/admin/{es-DA1X0RPv.js → es-Cm0Eklav.js} +104 -4
  19. package/dist/admin/{fr-CPPA27jW.js → fr-C3nzszsI.js} +104 -4
  20. package/dist/admin/{fr-DONxL73-.mjs → fr-CzFNGWq0.mjs} +104 -4
  21. package/dist/admin/index-6zc5D8eb.mjs +4729 -0
  22. package/dist/admin/index-Dk5Jqe5U.js +4730 -0
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +2 -2
  25. package/dist/admin/{pt-BMuwyaan.js → pt-BPZ6chPT.js} +104 -4
  26. package/dist/admin/{pt-D2yGNz2N.mjs → pt-DmyQnGI_.mjs} +104 -4
  27. package/dist/server/index.js +1048 -67
  28. package/dist/server/index.mjs +1048 -67
  29. package/package.json +1 -1
  30. package/dist/admin/index-DsaGGK7x.mjs +0 -2297
  31. package/dist/admin/index-Q_D-5LlE.js +0 -2298
  32. package/dist/admin/settingsTabs--7IsqMdn.mjs +0 -437
  33. package/dist/admin/settingsTabs-Dxlevody.js +0 -436
@@ -3,12 +3,12 @@ import { useFetchClient, useNotification, useClipboard, useRBAC, useQueryParams,
3
3
  import { NavLink, Link as Link$1, Routes, Route } from "react-router-dom";
4
4
  import { useMemo, useState, useEffect, useRef, useId, useCallback, useLayoutEffect } from "react";
5
5
  import { useIntl } from "react-intl";
6
- import { Typography, Flex, Loader, Button, Modal, Accordion, Box, IconButton, Link, SimpleMenu, MenuItem, Grid, Table, Thead, Tr, Th, VisuallyHidden, Tbody, Td, Tooltip, SearchForm, Searchbar, TextButton, SingleSelect, SingleSelectOption, EmptyStateLayout, LinkButton, Badge, Tabs, Dialog, Tag } from "@strapi/design-system";
7
- import { Earth, Duplicate, Cross, Eye, Trash, More, CaretDown, Download, ArrowClockwise, Check, Clock, User, ChartBubble, Cog, SignOut, Information, Webhooks, WarningCircle, Monitor, Key, Stack, Lock, CrossCircle, Shield, CheckCircle, ArrowRight } from "@strapi/icons";
6
+ import { Typography, Flex, Loader, Button, Modal, Accordion, Box, IconButton, Link, SimpleMenu, MenuItem, Grid, Table, Thead, Tr, Th, VisuallyHidden, Tbody, Td, Tooltip, SearchForm, Searchbar, TextButton, SingleSelect, SingleSelectOption, LinkButton, EmptyStateLayout, Badge, Tabs, Field, Textarea, Dialog } from "@strapi/design-system";
7
+ import { Earth, Duplicate, Cross, Eye, Trash, More, CaretDown, Download, ArrowRight, ArrowClockwise, Check, Clock, User, ChartBubble, Cog, SignOut } from "@strapi/icons";
8
8
  import { EmptyDocuments } from "@strapi/icons/symbols";
9
9
  import styled, { useTheme } from "styled-components";
10
- import { g as getSessionEndReason, a as getEndReasonPresentation, b as getTranslation, p as presentText, u as useSessionFormatters, c as getSessionStatus, d as getDevicePresentation, i as isNativeOnlySession, e as getSessionEndReasonPresentation, D as DeviceIcon, S as StatusBadge, P as PropertyList, C as ConfirmAction, t as toValidDate, f as pluginId, l as logSafeAdminError, h as PersistentAlert, R as ReadableText, j as pluginPermissions, M as MissingValue, V as ValueOrMissing, k as SESSION_STATES, m as SESSION_STATUS_PRESENTATION, n as isCancelledRequest, o as SESSION_FILTER_OPTIONS, E as END_REASON_FILTER_OPTIONS, q as PageShell, r as StatGrid, s as StatCard, v as restoreDialogFocus, w as requireSessionList, x as getBadgeColors, T as TargetLink$1 } from "./index-DsaGGK7x.mjs";
11
- import { i as isRiskSource, g as getSessionUserLabels, a as getUserEditPath, R as RISK_SETTINGS_PATH, b as RowActions, s as shouldIsolateActionKey, c as shouldRedispatchEscape, D as DASHBOARD_COMPACT_TABLE_COLUMNS, d as DASHBOARD_TABLE_COLUMNS, r as readDisclosureOpen, e as getBrowserStorage, w as writeDisclosureOpen, u as useElementWidth, p as parseDashboardQuery, A as AUTO_REFRESH_INTERVAL_MS, f as pickFocusSessionId, h as encodeSearchQuery, j as shouldUseCompactTable, P as PAGE_SIZE_OPTIONS, k as DEFAULT_PAGE_SIZE, l as getExportDeviceInfo, m as getErrorStatus, n as hasActiveFilters, S as SETTINGS_TAB_IDS, o as SETTINGS_TAB_FIELDS, q as SETTINGS_FIELD_LABELS, t as SETTINGS_TAB_LABELS } from "./settingsTabs--7IsqMdn.mjs";
10
+ import { g as getSessionEndReason, a as getEndReasonPresentation, b as getTranslation, p as presentText, u as useSessionFormatters, c as getSessionStatus, d as getDevicePresentation, i as isNativeOnlySession, e as getSessionEndReasonPresentation, D as DeviceIcon, S as StatusBadge, P as PropertyList, C as ConfirmAction, t as toValidDate, f as pluginId, l as logSafeAdminError, h as PersistentAlert, R as ReadableText, j as pluginPermissions, M as MissingValue, V as ValueOrMissing, k as SESSION_STATES, m as SESSION_STATUS_PRESENTATION, n as buildSignInParams, o as useEventList, q as SignInEventTable, r as PERIOD_OPTIONS, s as buildSignInCsv, v as SIGN_IN_FILTER_OPTIONS, w as buildActivityParams, x as buildActivityCsv, A as ActivityEventTable, y as ACTIVITY_ACTION_OPTIONS, z as ACTIVITY_ACTION_LABELS, B as downloadCsv, E as MAX_EVENT_EXPORT_ROWS, F as isCancelledRequest, G as RECENT_EVENT_LIMIT, H as buildUserActivityParams, I as RECENT_USER_EVENT_LIMIT, U as USER_ACTIVITY_API_PATH, J as USER_ACTIVITY_PAGE_PATH, K as UserEventTable, L as useElementWidth, N as SESSION_FILTER_OPTIONS, O as END_REASON_FILTER_OPTIONS, Q as PageShell, T as StatGrid, W as StatCard, X as buildSessionCsv, Y as buildSessionJson, Z as restoreDialogFocus, _ as requireSessionList, $ as getAdminStatusPresentation, a0 as getBadgeColors, a1 as useSettingsTranslate, a2 as useSecondsLeft, a3 as validateReason, a4 as REASON_MAX, a5 as formatClock, a6 as parseAdminPanelQuery, a7 as buildAdminListParams, a8 as withIdentityPlaceholders, a9 as ADMIN_FILTER_OPTIONS, aa as ADMIN_PAGE_SIZE_OPTIONS, ab as ADMIN_DEFAULT_PAGE_SIZE, ac as hasAdminFilters, ad as getSignOutErrorMessage, ae as splitDuration, af as parseActivityPageQuery, ag as EVENT_PAGE_SIZE, ah as ACTIVITY_PAGE_SIZE_OPTIONS, ai as ALL_ADMINS_FILTER_OPTIONS, aj as hasActivityPageFilters, ak as parseUserActivityQuery, al as userText, am as buildUserActivityCsv, an as USER_ACTIVITY_SETTINGS_PATH, ao as USER_ACTIVITY_FILTER_OPTIONS, ap as USER_ACTIVITY_FILTER_LABELS, aq as hasUserActivityFilters } from "./index-6zc5D8eb.mjs";
11
+ import { i as isRiskSource, g as getSessionUserLabels, a as getUserEditPath, R as RISK_SETTINGS_PATH, b as RowActions, s as shouldIsolateActionKey, c as shouldRedispatchEscape, D as DASHBOARD_COMPACT_TABLE_COLUMNS, d as DASHBOARD_TABLE_COLUMNS, r as readDisclosureOpen, e as getBrowserStorage, w as writeDisclosureOpen, p as parseDashboardQuery, A as AUTO_REFRESH_INTERVAL_MS, f as pickFocusSessionId, h as encodeSearchQuery, j as shouldUseCompactTable, P as PAGE_SIZE_OPTIONS, k as DEFAULT_PAGE_SIZE, l as getExportDeviceInfo, m as getErrorStatus, n as hasActiveFilters } from "./dashboardModel-BBNRgcEr.mjs";
12
12
  const EndReason = ({ session, reason, variant = "omega", textColor = "neutral800" }) => {
13
13
  const { formatMessage } = useIntl();
14
14
  const key = reason || getSessionEndReason(session);
@@ -90,112 +90,6 @@ function readSessionStats(payload) {
90
90
  stats.nativeOnlyAfterTracking = isCount$1(data?.nativeOnlyAfterTracking) ? data.nativeOnlyAfterTracking : null;
91
91
  return stats;
92
92
  }
93
- const CSV_HEADERS = Object.freeze([
94
- "ID",
95
- "Status",
96
- "User Email",
97
- "Username",
98
- "Device",
99
- "Browser",
100
- "OS",
101
- "IP Address",
102
- "Login Time",
103
- "Last Active",
104
- "Logout Time",
105
- "Minutes Idle",
106
- "End Reason"
107
- ]);
108
- const FORMULA_START = /^[\s\u00ad\u200b-\u200f\u2060-\u2064\ufeff]*[=+\-@\uff1d\uff0b\uff0d\uff20\t\r\n]/;
109
- const escapeCsvValue = (value) => {
110
- const text = String(value ?? "");
111
- const safe = typeof value === "string" && FORMULA_START.test(text) ? `'${text}` : text;
112
- return `"${safe.replace(/"/g, '""')}"`;
113
- };
114
- function toIsoTimestamp(value) {
115
- if (value === null || value === void 0 || value === "") return "";
116
- const date = value instanceof Date ? value : new Date(
117
- /** @type {any} */
118
- value
119
- );
120
- return Number.isFinite(date.getTime()) ? date.toISOString() : "";
121
- }
122
- function buildSessionCsv(sessions, {
123
- unavailableValue,
124
- getDeviceInfo,
125
- getSessionStatus: getSessionStatus2,
126
- getSessionEndReason: getSessionEndReason$1 = getSessionEndReason
127
- }) {
128
- const rows = Array.isArray(sessions) ? sessions : [];
129
- const csvRows = rows.map((session) => {
130
- const deviceInfo = getDeviceInfo(session, unavailableValue);
131
- const minutesIdle = Number.isFinite(session.minutesSinceActive) ? session.minutesSinceActive : "";
132
- return [
133
- session.id,
134
- getSessionStatus2(session),
135
- session.user?.email || "",
136
- session.user?.username || "",
137
- deviceInfo.device,
138
- deviceInfo.browser,
139
- deviceInfo.os,
140
- session.ipAddress || unavailableValue,
141
- toIsoTimestamp(session.loginTime),
142
- toIsoTimestamp(session.lastActive || session.loginTime),
143
- toIsoTimestamp(session.logoutTime),
144
- minutesIdle,
145
- getSessionEndReason$1(session) || ""
146
- ];
147
- });
148
- return [
149
- CSV_HEADERS.map(escapeCsvValue).join(","),
150
- ...csvRows.map((row) => row.map(escapeCsvValue).join(","))
151
- ].join("\n");
152
- }
153
- function buildSessionJson(sessions, {
154
- filterStatus,
155
- totalSessions,
156
- exportedAt,
157
- unavailableValue,
158
- getDeviceInfo,
159
- getSessionStatus: getSessionStatus2,
160
- getSessionEndReason: getSessionEndReason$1 = getSessionEndReason,
161
- truncated = false
162
- }) {
163
- const rows = Array.isArray(sessions) ? sessions : [];
164
- const exportData = {
165
- exportedAt,
166
- filter: filterStatus,
167
- totalSessions,
168
- exportedSessions: rows.length,
169
- ...truncated ? { truncated: true } : {},
170
- sessions: rows.map((session) => {
171
- const deviceInfo = getDeviceInfo(session, unavailableValue);
172
- return {
173
- id: session.id,
174
- status: getSessionStatus2(session),
175
- endReason: getSessionEndReason$1(session) || null,
176
- user: {
177
- id: session.user?.documentId || session.user?.id,
178
- email: session.user?.email,
179
- username: session.user?.username
180
- },
181
- device: {
182
- type: deviceInfo.device,
183
- browser: deviceInfo.browser,
184
- browserVersion: deviceInfo.browserVersion,
185
- os: deviceInfo.os
186
- },
187
- ipAddress: session.ipAddress || unavailableValue,
188
- loginTime: session.loginTime,
189
- lastActive: session.lastActive,
190
- logoutTime: session.logoutTime,
191
- minutesSinceActive: session.minutesSinceActive,
192
- isActive: session.isActive,
193
- isTrulyActive: session.isTrulyActive
194
- };
195
- })
196
- };
197
- return JSON.stringify(exportData, null, 2);
198
- }
199
93
  const DS_BREAKPOINTS = Object.freeze({
200
94
  small: "@media(min-width: 520px)",
201
95
  medium: "@media(min-width: 768px)",
@@ -1670,2523 +1564,1235 @@ const UntrackedSessionsNotice = ({ stats, onChanged, fallbackFocusRef }) => {
1670
1564
  )
1671
1565
  ] });
1672
1566
  };
1673
- const CLOCK_TICK_MS = 30 * 1e3;
1674
- const ANALYTICS_PATH = `/settings/${pluginId}/analytics`;
1675
- const CONFIGURATION_PATH = `/settings/${pluginId}/general`;
1676
- const PaginationTargets$2 = styled.div`
1677
- nav a {
1678
- min-width: 3.2rem;
1679
- }
1680
-
1681
- & > div {
1682
- flex-wrap: wrap;
1683
- gap: ${({ theme }) => theme.spaces[2]} ${({ theme }) => theme.spaces[4]};
1684
- }
1685
-
1686
- & > div > div > span {
1687
- white-space: nowrap;
1688
- }
1689
- `;
1690
- const downloadFile = (content, type, extension) => {
1691
- const blob = new Blob([content], { type });
1692
- const url = URL.createObjectURL(blob);
1693
- const link = document.createElement("a");
1694
- link.href = url;
1695
- link.download = `sessions-export-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.${extension}`;
1696
- link.click();
1697
- window.setTimeout(() => URL.revokeObjectURL(url), 0);
1698
- };
1699
- const HomePage = () => {
1567
+ const ADMIN_ACTIVITY_SETTINGS_PATH = `/settings/${pluginId}/general?tab=admin-activity`;
1568
+ const ADMIN_ACTIVITY_PAGE_PATH = `/plugins/${pluginId}/admin-panel/activity`;
1569
+ const useT$3 = () => {
1700
1570
  const { formatMessage } = useIntl();
1701
- const { get, post, del } = useFetchClient();
1571
+ return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
1572
+ };
1573
+ const PeriodSelect = ({ value, onChange }) => {
1574
+ const t = useT$3();
1575
+ const labels = {
1576
+ 1: t("adminPanel.activity.period.day", "Last 24 hours"),
1577
+ 7: t("adminPanel.activity.period.week", "Last 7 days"),
1578
+ 30: t("adminPanel.activity.period.month", "Last 30 days"),
1579
+ 90: t("adminPanel.activity.period.quarter", "Last 90 days"),
1580
+ all: t("adminPanel.activity.period.all", "All kept events")
1581
+ };
1582
+ return /* @__PURE__ */ jsx(
1583
+ SingleSelect,
1584
+ {
1585
+ size: "S",
1586
+ "aria-label": t("adminPanel.activity.period.label", "Period"),
1587
+ value,
1588
+ onChange: (next) => onChange(String(next)),
1589
+ children: PERIOD_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
1590
+ }
1591
+ );
1592
+ };
1593
+ const FilterTag = ({ label, onRemove, children, ...rest }) => /* @__PURE__ */ jsxs(
1594
+ Flex,
1595
+ {
1596
+ gap: 1,
1597
+ alignItems: "center",
1598
+ background: "primary100",
1599
+ borderColor: "primary200",
1600
+ hasRadius: true,
1601
+ paddingLeft: 3,
1602
+ minWidth: 0,
1603
+ ...rest,
1604
+ children: [
1605
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "semiBold", textColor: "primary700", children }),
1606
+ /* @__PURE__ */ jsx(IconButton, { label, variant: "ghost", size: "S", onClick: onRemove, children: /* @__PURE__ */ jsx(Cross, {}) })
1607
+ ]
1608
+ }
1609
+ );
1610
+ const FilterSlot = ({ children }) => /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", minWidth: 0, flex: "1 1 18rem", children });
1611
+ const EmptyText = ({ children }) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", "data-event-empty": "", children });
1612
+ const EventList = ({
1613
+ filters,
1614
+ notice,
1615
+ list,
1616
+ empty,
1617
+ renderList,
1618
+ toCsv,
1619
+ fileName,
1620
+ exportLabel,
1621
+ footer
1622
+ }) => {
1623
+ const t = useT$3();
1702
1624
  const { toggleNotification } = useNotification();
1703
- const formatters = useSessionFormatters();
1704
- const { isBelowSmall, isBelowMedium, isBelowLarge } = useBreakpoint();
1705
- const [listWidthRef, listWidth] = useElementWidth();
1706
- const [{ query }, setQuery] = useQueryParams();
1707
- const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
1708
- const dashboard = parseDashboardQuery(query);
1709
- const [sessions, setSessions] = useState([]);
1710
- const [pagination, setPagination] = useState({ total: 0, pageCount: 1 });
1711
- const [stats, setStats] = useState(EMPTY_SESSION_STATS);
1712
1625
  const [exporting, setExporting] = useState(false);
1713
- const [loading, setLoading] = useState(true);
1714
- const [refreshing, setRefreshing] = useState(false);
1715
- const [loadError, setLoadError] = useState(false);
1716
- const [hasData, setHasData] = useState(false);
1717
- const [lastUpdated, setLastUpdated] = useState(null);
1718
- const [now, setNow] = useState(() => Date.now());
1719
- const [selectedSession, setSelectedSession] = useState(null);
1720
- const [showDetailModal, setShowDetailModal] = useState(false);
1721
- const [terminatingSessionId, setTerminatingSessionId] = useState(null);
1722
- const [deletingSessionId, setDeletingSessionId] = useState(null);
1723
- const openerRef = useRef(null);
1724
- const dashboardRef = useRef(null);
1725
- const listHeadingRef = useRef(null);
1726
- const hasLoadedRef = useRef(false);
1727
- const requestIdRef = useRef(0);
1728
- const visibleIdsRef = useRef([]);
1729
- const mutationSnapshotRef = useRef([]);
1730
- const listHeadingId = `session-list-caption-${useId().replace(/:/g, "")}`;
1731
- const mutationPending = Boolean(terminatingSessionId || deletingSessionId);
1732
- const listQuery = useMemo(
1733
- () => ({
1734
- page: dashboard.page,
1735
- pageSize: dashboard.pageSize,
1736
- status: dashboard.status,
1737
- reason: dashboard.reason,
1738
- search: dashboard.search
1739
- }),
1740
- [dashboard.page, dashboard.pageSize, dashboard.status, dashboard.reason, dashboard.search]
1741
- );
1742
- useEffect(() => {
1743
- const timer = setInterval(() => setNow(Date.now()), CLOCK_TICK_MS);
1744
- return () => clearInterval(timer);
1745
- }, []);
1746
- const fetchSessions = useCallback(async () => {
1747
- const requestId = requestIdRef.current + 1;
1748
- requestIdRef.current = requestId;
1749
- if (hasLoadedRef.current) setRefreshing(true);
1750
- else setLoading(true);
1751
- try {
1752
- const [listResponse, statsResponse] = await Promise.all([
1753
- get(`/${pluginId}/sessions`, { params: buildListParams(listQuery) }),
1754
- get(`/${pluginId}/sessions/stats`)
1755
- ]);
1756
- const page = readSessionPage(listResponse.data);
1757
- const nextStats = readSessionStats(statsResponse.data);
1758
- if (requestId !== requestIdRef.current) return;
1759
- setSessions(page.rows);
1760
- setPagination(page.pagination);
1761
- setStats(nextStats);
1762
- setLoadError(false);
1763
- setHasData(true);
1764
- setLastUpdated(Date.now());
1765
- setNow(Date.now());
1766
- hasLoadedRef.current = true;
1767
- } catch (err) {
1768
- if (requestId !== requestIdRef.current || isCancelledRequest(err)) return;
1769
- setLoadError(true);
1770
- logSafeAdminError("dashboard.loadSessions", err);
1771
- } finally {
1772
- if (requestId === requestIdRef.current) {
1773
- setLoading(false);
1774
- setRefreshing(false);
1775
- }
1776
- }
1777
- }, [get, listQuery]);
1778
- useEffect(() => {
1779
- fetchSessions();
1780
- }, [fetchSessions]);
1781
- useEffect(() => {
1782
- if (showDetailModal || mutationPending) return void 0;
1783
- const interval = setInterval(() => {
1784
- fetchSessions();
1785
- }, AUTO_REFRESH_INTERVAL_MS);
1786
- return () => clearInterval(interval);
1787
- }, [showDetailModal, mutationPending, fetchSessions]);
1788
- const handleTerminateSession = async (session) => {
1789
- if (terminatingSessionId || deletingSessionId) return;
1790
- const sessionId = session.id;
1791
- mutationSnapshotRef.current = visibleIdsRef.current;
1792
- setTerminatingSessionId(sessionId);
1626
+ const total = list.meta?.pagination?.total ?? 0;
1627
+ const handleExport = async () => {
1628
+ if (exporting) return;
1629
+ setExporting(true);
1793
1630
  try {
1794
- await post(`/${pluginId}/sessions/${sessionId}/terminate`);
1795
- await fetchSessions();
1796
- toggleNotification({
1797
- type: "success",
1798
- message: t("notifications.success.sessionEnded", "Session ended.")
1799
- });
1800
- } catch (err) {
1801
- logSafeAdminError("dashboard.terminateSession", err);
1802
- if (getErrorStatus(err) === 404) {
1803
- await fetchSessions();
1631
+ const { rows, capped } = await list.exportAll();
1632
+ downloadCsv(toCsv(rows), fileName);
1633
+ if (capped) {
1804
1634
  toggleNotification({
1805
1635
  type: "warning",
1806
1636
  message: t(
1807
- "notifications.error.sessionGone",
1808
- "This session no longer exists. The list was refreshed."
1637
+ "adminPanel.activity.export.capped",
1638
+ "The export contains the newest {limit, number} events. Narrow the filter to export the rest.",
1639
+ { limit: MAX_EVENT_EXPORT_ROWS }
1809
1640
  )
1810
1641
  });
1811
- return;
1812
1642
  }
1813
- toggleNotification({
1814
- type: "danger",
1815
- message: t(
1816
- "notifications.error.endSession",
1817
- "The session could not be ended. Please try again."
1818
- )
1819
- });
1820
- throw err;
1821
- } finally {
1822
- setTerminatingSessionId(null);
1823
- }
1824
- };
1825
- const handleDeleteSession = async (session) => {
1826
- if (terminatingSessionId || deletingSessionId) return;
1827
- const sessionId = session.id;
1828
- mutationSnapshotRef.current = visibleIdsRef.current;
1829
- setDeletingSessionId(sessionId);
1830
- try {
1831
- await del(`/${pluginId}/sessions/${sessionId}`);
1832
- await fetchSessions();
1833
- toggleNotification({
1834
- type: "success",
1835
- message: t(
1836
- "notifications.success.recordDeleted",
1837
- "Session record deleted. Its token stays revoked."
1838
- )
1839
- });
1840
1643
  } catch (err) {
1841
- logSafeAdminError("dashboard.deleteSession", err);
1842
- if (getErrorStatus(err) === 404) {
1843
- await fetchSessions();
1844
- toggleNotification({
1845
- type: "warning",
1846
- message: t(
1847
- "notifications.error.sessionGone",
1848
- "This session no longer exists. The list was refreshed."
1849
- )
1850
- });
1851
- return;
1852
- }
1644
+ if (isCancelledRequest(err)) return;
1645
+ logSafeAdminError("adminPanel.activity.export", err);
1853
1646
  toggleNotification({
1854
1647
  type: "danger",
1855
- message: t(
1856
- "notifications.error.deleteRecord",
1857
- "The record could not be deleted. Please try again."
1858
- )
1648
+ message: t("adminPanel.activity.export.error", "The export could not be created.")
1859
1649
  });
1860
- throw err;
1861
1650
  } finally {
1862
- setDeletingSessionId(null);
1651
+ setExporting(false);
1863
1652
  }
1864
1653
  };
1865
- const pageSize = Number(dashboard.pageSize);
1866
- const pageResult = {
1867
- items: sessions,
1868
- total: pagination.total,
1869
- pageCount: pagination.pageCount,
1870
- startIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + 1 : 0,
1871
- endIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + sessions.length : 0
1872
- };
1873
- const visibleIds = pageResult.items.map((session) => String(session.id));
1874
- useLayoutEffect(() => {
1875
- visibleIdsRef.current = visibleIds;
1876
- });
1877
- const fetchExportRows = async () => {
1878
- const rows = [];
1879
- let cursor = null;
1880
- do {
1881
- const { data } = await get(`/${pluginId}/sessions/export`, {
1882
- params: buildExportParams(listQuery, cursor)
1883
- });
1884
- rows.push(...requireSessionList(data));
1885
- cursor = typeof data?.meta?.nextCursor === "string" ? data.meta.nextCursor : null;
1886
- } while (cursor && rows.length < MAX_EXPORT_ROWS);
1887
- const capped = rows.length > MAX_EXPORT_ROWS || Boolean(cursor) && rows.length >= MAX_EXPORT_ROWS;
1888
- return { rows: rows.slice(0, MAX_EXPORT_ROWS), capped };
1889
- };
1890
- const handleExport = async (format) => {
1891
- if (exporting) return;
1892
- setExporting(true);
1893
- try {
1894
- const { rows, capped } = await fetchExportRows();
1895
- if (format === "csv") {
1896
- const csvContent = buildSessionCsv(rows, {
1897
- unavailableValue: "",
1898
- getDeviceInfo: getExportDeviceInfo,
1899
- getSessionStatus
1900
- });
1901
- downloadFile(csvContent, "text/csv;charset=utf-8;", "csv");
1902
- } else {
1903
- const jsonContent = buildSessionJson(rows, {
1904
- filterStatus: dashboard.status,
1905
- totalSessions: stats.total,
1906
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1907
- unavailableValue: "",
1908
- getDeviceInfo: getExportDeviceInfo,
1909
- getSessionStatus,
1910
- truncated: capped
1911
- });
1912
- downloadFile(jsonContent, "application/json", "json");
1913
- }
1914
- if (capped) {
1915
- toggleNotification({
1916
- type: "warning",
1917
- message: t(
1918
- "homepage.export.capped",
1919
- "The export contains the newest {limit, number} sessions. Narrow the filter to export the rest.",
1920
- { limit: MAX_EXPORT_ROWS }
1921
- )
1922
- });
1923
- }
1924
- } catch (err) {
1925
- if (isCancelledRequest(err)) return;
1926
- logSafeAdminError(format === "csv" ? "dashboard.exportCsv" : "dashboard.exportJson", err);
1927
- toggleNotification({
1928
- type: "danger",
1929
- message: t("notifications.error.exportFailed", "The export could not be created.")
1930
- });
1931
- } finally {
1932
- setExporting(false);
1933
- }
1934
- };
1935
- const handleSessionClick = (session, opener) => {
1936
- openerRef.current = opener;
1937
- setSelectedSession(session);
1938
- setShowDetailModal(true);
1939
- };
1940
- const handleModalClose = () => {
1941
- setShowDetailModal(false);
1942
- setSelectedSession(null);
1943
- };
1944
- const handleCloseAutoFocus = (event) => {
1945
- restoreDialogFocus(event, openerRef.current, listHeadingRef.current || dashboardRef.current);
1946
- };
1947
- const getFocusFallback = useCallback(
1948
- (sessionId) => ({
1949
- get current() {
1950
- const targetId = pickFocusSessionId(
1951
- mutationSnapshotRef.current,
1952
- visibleIdsRef.current,
1953
- sessionId
1954
- );
1955
- const root = dashboardRef.current;
1956
- if (targetId && root) {
1957
- const escaped = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(targetId) : targetId;
1958
- const button = root.querySelector(`[data-session-view="${escaped}"]`);
1959
- if (button) return button;
1654
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
1655
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", justifyContent: "space-between", children: [
1656
+ /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", alignItems: "center", flex: "1 1 auto", minWidth: 0, children: filters }),
1657
+ /* @__PURE__ */ jsx(
1658
+ Button,
1659
+ {
1660
+ size: "S",
1661
+ variant: "tertiary",
1662
+ startIcon: /* @__PURE__ */ jsx(Download, {}),
1663
+ onClick: handleExport,
1664
+ loading: exporting,
1665
+ disabled: list.loading || total === 0,
1666
+ "aria-label": exportLabel,
1667
+ children: t("adminPanel.activity.export.csv", "Export CSV")
1960
1668
  }
1961
- return listHeadingRef.current;
1669
+ )
1670
+ ] }),
1671
+ notice,
1672
+ list.loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 4, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
1673
+ !list.loading && list.error ? /* @__PURE__ */ jsx(
1674
+ PersistentAlert,
1675
+ {
1676
+ variant: "danger",
1677
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
1678
+ children: t("adminPanel.activity.error", "The events could not be loaded.")
1962
1679
  }
1963
- }),
1964
- []
1965
- );
1966
- useEffect(() => {
1967
- if (!loading && !refreshing && dashboard.page > pageResult.pageCount) {
1968
- setQuery({ page: String(pageResult.pageCount) }, "push", true);
1680
+ ) : null,
1681
+ !list.loading && !list.error && list.rows.length === 0 ? empty : null,
1682
+ list.rows.length > 0 ? renderList(list.rows) : null,
1683
+ footer !== void 0 ? list.rows.length > 0 ? footer : null : list.hasMore ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", children: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: list.loadMore, loading: list.loadingMore, children: t("adminPanel.activity.showMore", "Show more") }) }) : null
1684
+ ] });
1685
+ };
1686
+ const RecordingOff = ({ children, to = ADMIN_ACTIVITY_SETTINGS_PATH }) => {
1687
+ const t = useT$3();
1688
+ return /* @__PURE__ */ jsx(
1689
+ PersistentAlert,
1690
+ {
1691
+ variant: "neutral",
1692
+ action: /* @__PURE__ */ jsx(Link, { tag: Link$1, to, children: t("adminPanel.activity.openSettings", "Open settings") }),
1693
+ children
1969
1694
  }
1970
- }, [loading, refreshing, dashboard.page, pageResult.pageCount, setQuery]);
1971
- const handleStatusChange = (value) => {
1972
- const status = String(value);
1973
- setQuery({ status: status === "all" ? void 0 : status, reason: void 0, page: "1" });
1974
- };
1975
- const handleReasonChange = (value) => {
1976
- const reason = String(value);
1977
- setQuery({ reason: reason === "all" ? void 0 : reason, page: "1" });
1978
- };
1979
- const handleSearch = useCallback(
1980
- (value) => {
1981
- setQuery({ search: encodeSearchQuery(value), _q: void 0, page: "1" }, "push", true);
1982
- },
1983
- [setQuery]
1984
1695
  );
1985
- const handleClearFilters = () => {
1986
- setQuery({ search: void 0, _q: void 0, status: void 0, reason: void 0, page: "1" });
1987
- listHeadingRef.current?.focus();
1696
+ };
1697
+ const SignInHistoryPanel = ({ admin }) => {
1698
+ const t = useT$3();
1699
+ const [event, setEvent] = useState("all");
1700
+ const [period, setPeriod] = useState("30");
1701
+ const params = useMemo(
1702
+ () => buildSignInParams({ adminId: admin.id, event, period }),
1703
+ [admin.id, event, period]
1704
+ );
1705
+ const list = useEventList({
1706
+ path: `/${pluginId}/admin-activity/sign-ins`,
1707
+ params,
1708
+ logKey: "adminPanel.activity.signIns"
1709
+ });
1710
+ const recording = list.meta?.recording;
1711
+ const labels = {
1712
+ all: t("adminPanel.activity.filter.allEvents", "All events"),
1713
+ succeeded: t("adminPanel.activity.filter.succeeded", "Sign-ins"),
1714
+ failed: t("adminPanel.activity.filter.failed", "Failed and locked out"),
1715
+ "signed-out": t("adminPanel.activity.filter.signedOut", "Sign-outs")
1988
1716
  };
1989
- const showSessionData = !loading && hasData;
1990
- const showToolbar = showSessionData && stats.total > 0;
1991
- const canExport = showSessionData && pageResult.total > 0 && !exporting;
1992
- const filtersActive = hasActiveFilters(dashboard);
1993
- const exportValues = { count: Math.min(pageResult.total, MAX_EXPORT_ROWS) };
1994
- const exportMenu = /* @__PURE__ */ jsxs(
1995
- SimpleMenu,
1717
+ return /* @__PURE__ */ jsx(
1718
+ EventList,
1996
1719
  {
1997
- label: t("homepage.export.label", "Export"),
1998
- variant: "secondary",
1999
- startIcon: /* @__PURE__ */ jsx(Download, {}),
2000
- disabled: !canExport,
2001
- children: [
2002
- /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("csv"), children: t(
2003
- "homepage.export.csv",
2004
- "{count, plural, one {Export # session as CSV} other {Export # sessions as CSV}}",
2005
- exportValues
1720
+ list,
1721
+ filters: /* @__PURE__ */ jsxs(Fragment, { children: [
1722
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
1723
+ SingleSelect,
1724
+ {
1725
+ size: "S",
1726
+ "aria-label": t("adminPanel.activity.filter.event", "Event"),
1727
+ value: event,
1728
+ onChange: (next) => setEvent(String(next)),
1729
+ children: SIGN_IN_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
1730
+ }
2006
1731
  ) }),
2007
- /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("json"), children: t(
2008
- "homepage.export.json",
2009
- "{count, plural, one {Export # session as JSON} other {Export # sessions as JSON}}",
2010
- exportValues
2011
- ) })
2012
- ]
1732
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
1733
+ ] }),
1734
+ notice: recording && !recording.signIns ? /* @__PURE__ */ jsx(RecordingOff, { children: t(
1735
+ "adminPanel.activity.signIns.off",
1736
+ "Sign-in history is turned off. New sign-ins are not recorded."
1737
+ ) }) : null,
1738
+ empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.signIns.empty", "No sign-in events in this period.") }),
1739
+ renderList: (rows) => /* @__PURE__ */ jsx(
1740
+ SignInEventTable,
1741
+ {
1742
+ rows,
1743
+ busy: list.loading,
1744
+ label: t("adminPanel.activity.signIns.listLabel", "Sign-in history of {name}", {
1745
+ name: admin.name
1746
+ })
1747
+ }
1748
+ ),
1749
+ toCsv: buildSignInCsv,
1750
+ fileName: "admin-sign-in-history",
1751
+ exportLabel: t(
1752
+ "adminPanel.activity.signIns.export",
1753
+ "Export the sign-in history of {name} as CSV",
1754
+ {
1755
+ name: admin.name
1756
+ }
1757
+ )
2013
1758
  }
2014
1759
  );
2015
- const exportAction = canExport || !showSessionData ? exportMenu : /* @__PURE__ */ jsx(Tooltip, { label: t("homepage.export.disabledHint", "No sessions match the current filter."), children: /* @__PURE__ */ jsx("span", { children: exportMenu }) });
2016
- const analyticsLabel = t("homepage.links.analytics", "Analytics");
2017
- const settingsLabel = t("homepage.links.settings", "Settings");
2018
- const primaryAction = /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", justifyContent: "flex-end", children: [
2019
- isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: ANALYTICS_PATH, label: analyticsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(ChartBubble, {}) }) : /* @__PURE__ */ jsx(
2020
- LinkButton,
2021
- {
2022
- tag: Link$1,
2023
- to: ANALYTICS_PATH,
2024
- variant: "tertiary",
2025
- size: "S",
2026
- startIcon: /* @__PURE__ */ jsx(ChartBubble, {}),
2027
- children: analyticsLabel
2028
- }
2029
- ),
2030
- isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: CONFIGURATION_PATH, label: settingsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(Cog, {}) }) : /* @__PURE__ */ jsx(
2031
- LinkButton,
2032
- {
2033
- tag: Link$1,
2034
- to: CONFIGURATION_PATH,
2035
- variant: "tertiary",
2036
- size: "S",
2037
- startIcon: /* @__PURE__ */ jsx(Cog, {}),
2038
- children: settingsLabel
2039
- }
2040
- ),
2041
- exportAction
2042
- ] });
2043
- const filterSlot = isBelowMedium ? { flex: "1 1 auto", minWidth: 0 } : void 0;
2044
- const filterControls = /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: isBelowMedium ? "nowrap" : "wrap", shrink: 0, children: [
2045
- /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2046
- SingleSelect,
2047
- {
2048
- size: "S",
2049
- "aria-label": t("homepage.filter.label", "Status"),
2050
- value: dashboard.status,
2051
- onChange: handleStatusChange,
2052
- children: SESSION_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsxs(SingleSelectOption, { value: option, children: [
2053
- option === "all" && t("homepage.filter.all", "All sessions"),
2054
- option === "open" && t("homepage.filter.open", "Open"),
2055
- option !== "all" && option !== "open" && formatters.statusLabel(option)
2056
- ] }, option))
2057
- }
2058
- ) }),
2059
- dashboard.status === "ended" ? /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2060
- SingleSelect,
2061
- {
2062
- size: "S",
2063
- "aria-label": t("homepage.filter.reasonLabel", "End reason"),
2064
- value: dashboard.reason,
2065
- onChange: handleReasonChange,
2066
- children: END_REASON_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: option === "all" ? t("homepage.filter.allReasons", "All reasons") : formatters.endReasonLabel(option) }, option))
2067
- }
2068
- ) }) : null,
2069
- /* @__PURE__ */ jsx(
2070
- IconButton,
2071
- {
2072
- label: t("homepage.actions.refresh", "Refresh sessions"),
2073
- onClick: () => fetchSessions(),
2074
- children: /* @__PURE__ */ jsx(ArrowClockwise, {})
2075
- }
2076
- )
2077
- ] });
2078
- const toolbar = /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-session-toolbar": "", children: /* @__PURE__ */ jsxs(
1760
+ };
1761
+ const ContentActivityPanel = ({ admin }) => {
1762
+ const t = useT$3();
1763
+ const [action, setAction] = useState("all");
1764
+ const [contentType, setContentType] = useState("all");
1765
+ const [period, setPeriod] = useState("30");
1766
+ const params = useMemo(
1767
+ () => buildActivityParams({ adminId: admin.id, action, contentType, period }),
1768
+ [admin.id, action, contentType, period]
1769
+ );
1770
+ const list = useEventList({
1771
+ path: `/${pluginId}/admin-activity/content`,
1772
+ params,
1773
+ logKey: "adminPanel.activity.content"
1774
+ });
1775
+ const recording = list.meta?.recording;
1776
+ const types = Array.isArray(list.meta?.contentTypes) ? list.meta.contentTypes : [];
1777
+ const noAccess = list.meta?.contentManagerAccess === false;
1778
+ let notice = null;
1779
+ if (recording && !recording.contentActivity) {
1780
+ notice = /* @__PURE__ */ jsx(RecordingOff, { children: t(
1781
+ "adminPanel.activity.content.off",
1782
+ "Content Manager activity is not recorded. An admin can turn it on in the settings; inform your team first."
1783
+ ) });
1784
+ } else if (noAccess) {
1785
+ notice = /* @__PURE__ */ jsx(PersistentAlert, { variant: "neutral", children: t(
1786
+ "adminPanel.activity.content.noAccess",
1787
+ "{name} has no Content Manager access, so there is no activity to show.",
1788
+ { name: admin.name }
1789
+ ) });
1790
+ }
1791
+ return /* @__PURE__ */ jsx(
1792
+ EventList,
1793
+ {
1794
+ list,
1795
+ filters: /* @__PURE__ */ jsxs(Fragment, { children: [
1796
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
1797
+ SingleSelect,
1798
+ {
1799
+ size: "S",
1800
+ "aria-label": t("adminPanel.activity.filter.action", "Action"),
1801
+ value: action,
1802
+ onChange: (next) => setAction(String(next)),
1803
+ children: ACTIVITY_ACTION_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: t(
1804
+ ACTIVITY_ACTION_LABELS[option].messageId,
1805
+ ACTIVITY_ACTION_LABELS[option].defaultMessage
1806
+ ) }, option))
1807
+ }
1808
+ ) }),
1809
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsxs(
1810
+ SingleSelect,
1811
+ {
1812
+ size: "S",
1813
+ "aria-label": t("adminPanel.activity.filter.contentType", "Content type"),
1814
+ value: contentType,
1815
+ onChange: (next) => setContentType(String(next)),
1816
+ children: [
1817
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "all", children: t("adminPanel.activity.filter.allTypes", "All content types") }),
1818
+ types.map((type) => /* @__PURE__ */ jsx(SingleSelectOption, { value: type.uid, children: type.name }, type.uid))
1819
+ ]
1820
+ }
1821
+ ) }),
1822
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
1823
+ ] }),
1824
+ notice,
1825
+ empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.content.empty", "No Content Manager activity in this period.") }),
1826
+ renderList: (rows) => /* @__PURE__ */ jsx(
1827
+ ActivityEventTable,
1828
+ {
1829
+ rows,
1830
+ busy: list.loading,
1831
+ label: t("adminPanel.activity.content.listLabel", "Content Manager activity of {name}", {
1832
+ name: admin.name
1833
+ })
1834
+ }
1835
+ ),
1836
+ toCsv: buildActivityCsv,
1837
+ fileName: "admin-content-activity",
1838
+ exportLabel: t(
1839
+ "adminPanel.activity.content.export",
1840
+ "Export the Content Manager activity of {name} as CSV",
1841
+ { name: admin.name }
1842
+ )
1843
+ }
1844
+ );
1845
+ };
1846
+ const RecentEvents = ({
1847
+ title,
1848
+ subtitle,
1849
+ showAllTo,
1850
+ emptyText,
1851
+ list,
1852
+ renderTable,
1853
+ dataKey
1854
+ }) => {
1855
+ const t = useT$3();
1856
+ const headingId = `recent-events-${useId().replace(/:/g, "")}`;
1857
+ return /* @__PURE__ */ jsxs(
2079
1858
  Flex,
2080
1859
  {
2081
- direction: { initial: "column", medium: "row" },
2082
- alignItems: { initial: "stretch", medium: "center" },
2083
- gap: 2,
1860
+ tag: "section",
1861
+ "aria-labelledby": headingId,
1862
+ direction: "column",
1863
+ alignItems: "stretch",
1864
+ gap: 4,
1865
+ minWidth: 0,
1866
+ ...{ [`data-${dataKey}`]: "" },
2084
1867
  children: [
2085
- /* @__PURE__ */ jsx(Flex, { flex: "1 1 auto", minWidth: 0, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsx(SessionSearch, { value: dashboard.search, onSearch: handleSearch }) }),
2086
- filterControls
1868
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "flex-end", gap: 4, wrap: "wrap", children: [
1869
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, flex: "1 1 32rem", children: [
1870
+ /* @__PURE__ */ jsx(Typography, { id: headingId, variant: "delta", tag: "h2", textColor: "neutral800", children: title }),
1871
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: subtitle })
1872
+ ] }),
1873
+ /* @__PURE__ */ jsx(
1874
+ LinkButton,
1875
+ {
1876
+ tag: Link$1,
1877
+ to: showAllTo,
1878
+ variant: "tertiary",
1879
+ endIcon: /* @__PURE__ */ jsx(ArrowRight, {}),
1880
+ "data-show-all-activity": "",
1881
+ children: t("adminPanel.activity.recent.showAll", "Show all")
1882
+ }
1883
+ )
1884
+ ] }),
1885
+ list.loading && list.rows.length === 0 ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 2, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
1886
+ !list.loading && list.error ? /* @__PURE__ */ jsx(
1887
+ PersistentAlert,
1888
+ {
1889
+ variant: "danger",
1890
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
1891
+ children: t("adminPanel.activity.error", "The events could not be loaded.")
1892
+ }
1893
+ ) : null,
1894
+ !list.loading && !list.error && list.rows.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", "data-event-empty": "", children: emptyText }) : null,
1895
+ list.rows.length > 0 ? renderTable(title) : null
2087
1896
  ]
2088
1897
  }
2089
- ) });
2090
- const lastUpdatedLine = lastUpdated ? /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: "wrap", justifyContent: "flex-end", children: [
2091
- refreshing ? /* @__PURE__ */ jsx(Loader, { small: true, role: "status", "aria-live": "polite", children: t("homepage.refreshing", "Updating sessions") }) : null,
2092
- /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", "data-last-updated": "", children: t("homepage.lastUpdated", "Last updated {time}", {
2093
- time: formatters.formatRelativeTime(lastUpdated, now)
2094
- }) })
2095
- ] }) : null;
2096
- const listProps = {
2097
- sessions: pageResult.items,
2098
- labelledBy: listHeadingId,
2099
- busy: refreshing,
2100
- onView: handleSessionClick,
2101
- onEnd: handleTerminateSession,
2102
- onDelete: handleDeleteSession,
2103
- mutationPending,
2104
- getFocusFallback
2105
- };
2106
- const statusCard = (status) => ({
2107
- onClick: () => handleStatusChange(status),
2108
- pressed: dashboard.status === status
1898
+ );
1899
+ };
1900
+ const RecentSignInActivity = ({ onOpenAdmin }) => {
1901
+ const t = useT$3();
1902
+ const params = useMemo(() => buildSignInParams({ pageSize: RECENT_EVENT_LIMIT }), []);
1903
+ const list = useEventList({
1904
+ path: `/${pluginId}/admin-activity/sign-ins`,
1905
+ params,
1906
+ logKey: "adminPanel.activity.recent"
2109
1907
  });
1908
+ if (list.meta?.recording && !list.meta.recording.signIns) return null;
2110
1909
  return /* @__PURE__ */ jsx(
2111
- PageShell,
1910
+ RecentEvents,
2112
1911
  {
2113
- headingId: "magic-sessionmanager-dashboard-title",
2114
- title: t("homepage.title", "Sessions"),
1912
+ title: t("adminPanel.activity.recent.title", "Recent security activity"),
2115
1913
  subtitle: t(
2116
- "homepage.subtitle",
2117
- "Sign-ins of your app’s users (Users & Permissions). Strapi administrators are not listed."
1914
+ "adminPanel.activity.recent.subtitle",
1915
+ "The latest sign-ins, failed attempts, sign-outs and settings changes of all admins. Select an event for its details."
2118
1916
  ),
2119
- primaryAction,
2120
- children: /* @__PURE__ */ jsxs(
2121
- Flex,
1917
+ showAllTo: ADMIN_ACTIVITY_PAGE_PATH,
1918
+ emptyText: t("adminPanel.activity.recent.empty", "No events recorded yet."),
1919
+ list,
1920
+ dataKey: "recent-activity",
1921
+ renderTable: (title) => /* @__PURE__ */ jsx(
1922
+ SignInEventTable,
2122
1923
  {
2123
- ref: dashboardRef,
2124
- tabIndex: -1,
2125
- direction: "column",
2126
- alignItems: "stretch",
2127
- gap: 6,
2128
- minWidth: 0,
2129
- children: [
2130
- /* @__PURE__ */ jsx(SessionViewNav, { current: "users" }),
2131
- !loading && loadError ? /* @__PURE__ */ jsx(
2132
- PersistentAlert,
2133
- {
2134
- variant: "danger",
2135
- closeLabel: t("common.close", "Close"),
2136
- action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: fetchSessions, children: t("common.tryAgain", "Try again") }),
2137
- children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "span", children: t("homepage.error.load", "Sessions could not be loaded.") })
2138
- }
2139
- ) : null,
2140
- showSessionData && stats.nativeOnly > 0 ? /* @__PURE__ */ jsx(
2141
- UntrackedSessionsNotice,
2142
- {
2143
- stats,
2144
- onChanged: fetchSessions,
2145
- fallbackFocusRef: dashboardRef
2146
- }
2147
- ) : null,
2148
- loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 8, children: /* @__PURE__ */ jsx(Loader, { children: t("homepage.loading", "Loading sessions") }) }) : null,
2149
- showSessionData && stats.total > 0 ? /* @__PURE__ */ jsx(HowSessionsWork, {}) : null,
2150
- showSessionData && /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
2151
- /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { tag: "h2", children: t("homepage.stats.label", "Session statistics") }) }),
2152
- /* @__PURE__ */ jsxs(StatGrid, { label: t("homepage.stats.label", "Session statistics"), children: [
2153
- /* @__PURE__ */ jsx(
2154
- StatCard,
2155
- {
2156
- icon: Check,
2157
- tone: "success",
2158
- label: t("homepage.stats.active", "Active sessions"),
2159
- value: stats.active,
2160
- description: t(
2161
- "homepage.stats.usersOnline",
2162
- "{count, plural, one {# user online} other {# users online}}",
2163
- {
2164
- count: stats.usersOnline
2165
- }
2166
- ),
2167
- ...statusCard("active")
2168
- }
2169
- ),
2170
- /* @__PURE__ */ jsx(
2171
- StatCard,
2172
- {
2173
- icon: Clock,
2174
- tone: "warning",
2175
- label: t("homepage.stats.idle", "Idle sessions"),
2176
- value: stats.idle,
2177
- ...statusCard("idle")
2178
- }
2179
- ),
2180
- /* @__PURE__ */ jsx(
2181
- StatCard,
2182
- {
2183
- icon: Cross,
2184
- tone: "neutral",
2185
- label: t("homepage.stats.ended", "Ended sessions"),
2186
- value: stats.ended,
2187
- description: t(
2188
- "homepage.stats.endedBreakdown",
2189
- "{loggedOut, number} logged out · {timedOut, number} timed out · {other, number} other reasons",
2190
- {
2191
- loggedOut: stats.loggedOut,
2192
- timedOut: stats.timedOut,
2193
- other: stats.otherReasons
2194
- }
2195
- ),
2196
- ...statusCard("ended")
2197
- }
2198
- ),
2199
- /* @__PURE__ */ jsx(
2200
- StatCard,
2201
- {
2202
- icon: User,
2203
- tone: "primary",
2204
- label: t("homepage.stats.total", "All sessions"),
2205
- value: stats.total,
2206
- ...statusCard("all")
2207
- }
2208
- )
2209
- ] })
2210
- ] }),
2211
- showToolbar && /* @__PURE__ */ jsxs(Flex, { ref: listWidthRef, direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
2212
- /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h2", children: t("homepage.list.heading", "Session list") }) }),
2213
- toolbar,
2214
- /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 4, wrap: "wrap", children: [
2215
- /* @__PURE__ */ jsx(
2216
- Typography,
2217
- {
2218
- id: listHeadingId,
2219
- ref: listHeadingRef,
2220
- tabIndex: -1,
2221
- variant: "pi",
2222
- textColor: "neutral600",
2223
- "aria-live": "polite",
2224
- "data-session-caption": "",
2225
- children: pageResult.total > 0 ? t(
2226
- "homepage.caption",
2227
- "{from, number}–{to, number} of {total, plural, one {# session} other {# sessions}}",
2228
- {
2229
- from: pageResult.startIndex,
2230
- to: pageResult.endIndex,
2231
- total: pageResult.total
2232
- }
2233
- ) : t("homepage.captionNone", "0 sessions")
2234
- }
2235
- ),
2236
- lastUpdatedLine
2237
- ] }),
2238
- pageResult.total > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
2239
- isBelowMedium ? /* @__PURE__ */ jsx(SessionCardList, { ...listProps }) : /* @__PURE__ */ jsx(
2240
- SessionTable,
2241
- {
2242
- ...listProps,
2243
- compact: shouldUseCompactTable(listWidth, isBelowLarge)
2244
- }
2245
- ),
2246
- /* @__PURE__ */ jsx(PaginationTargets$2, { children: /* @__PURE__ */ jsxs(
2247
- Pagination.Root,
2248
- {
2249
- pageCount: pageResult.pageCount,
2250
- total: pageResult.total,
2251
- defaultPageSize: Number(DEFAULT_PAGE_SIZE),
2252
- children: [
2253
- /* @__PURE__ */ jsx(Pagination.PageSize, { options: [...PAGE_SIZE_OPTIONS] }),
2254
- /* @__PURE__ */ jsx(Pagination.Links, {})
2255
- ]
2256
- }
2257
- ) })
2258
- ] }) : /* @__PURE__ */ jsx(
2259
- EmptyStateLayout,
2260
- {
2261
- icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2262
- content: t(
2263
- "homepage.noResults.description",
2264
- "No sessions match your search or filter."
2265
- ),
2266
- action: filtersActive ? /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: handleClearFilters, children: t("homepage.noResults.reset", "Clear filters") }) : null
2267
- }
2268
- )
2269
- ] }),
2270
- showSessionData && stats.total === 0 && /* @__PURE__ */ jsx(
2271
- EmptyStateLayout,
2272
- {
2273
- icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2274
- content: t(
2275
- "homepage.empty.description",
2276
- "No sessions yet. Sessions appear here when users of your app sign in."
2277
- )
2278
- }
2279
- ),
2280
- showDetailModal && selectedSession && /* @__PURE__ */ jsx(
2281
- SessionDetailModal,
2282
- {
2283
- session: selectedSession,
2284
- now,
2285
- onClose: handleModalClose,
2286
- onCloseAutoFocus: handleCloseAutoFocus,
2287
- onEndSession: handleTerminateSession
2288
- }
2289
- )
2290
- ]
1924
+ rows: list.rows,
1925
+ label: title,
1926
+ showAdmin: true,
1927
+ onOpenAdmin,
1928
+ busy: list.loading
2291
1929
  }
2292
1930
  )
2293
1931
  }
2294
1932
  );
2295
1933
  };
2296
- const ADMIN_FILTER_OPTIONS = Object.freeze(["all", "signed-in", "not-signed-in"]);
2297
- const ADMIN_PAGE_SIZE_OPTIONS = Object.freeze(["10", "25", "50", "100"]);
2298
- const ADMIN_DEFAULT_PAGE_SIZE = "25";
2299
- const ADMIN_MAX_SEARCH_LENGTH = 100;
2300
- function parseAdminPanelQuery(query = {}) {
2301
- const page = Number.parseInt(String(query?.page ?? ""), 10);
2302
- const pageSize = String(query?.pageSize ?? "");
2303
- const filter = String(query?.filter ?? "");
2304
- let search = "";
2305
- if (typeof query?.search === "string") {
2306
- try {
2307
- search = decodeURIComponent(query.search).trim();
2308
- } catch {
2309
- search = query.search.trim();
2310
- }
2311
- }
2312
- return {
2313
- page: Number.isInteger(page) && page >= 1 && page <= 1e6 ? page : 1,
2314
- pageSize: Number(
2315
- ADMIN_PAGE_SIZE_OPTIONS.includes(pageSize) ? pageSize : ADMIN_DEFAULT_PAGE_SIZE
2316
- ),
2317
- filter: ADMIN_FILTER_OPTIONS.includes(filter) ? filter : "all",
2318
- search: search.slice(0, ADMIN_MAX_SEARCH_LENGTH)
2319
- };
2320
- }
2321
- function buildAdminListParams(state) {
2322
- return {
2323
- page: state.page,
2324
- pageSize: state.pageSize,
2325
- filter: state.filter,
2326
- ...state.search ? { search: state.search } : {}
2327
- };
2328
- }
2329
- function hasAdminFilters(state) {
2330
- return state.filter !== "all" || Boolean(state.search);
2331
- }
2332
- function getAdminStatusPresentation(row) {
2333
- if (row?.account === "invited") {
2334
- return {
2335
- key: "invited",
2336
- tone: "secondary",
2337
- label: { messageId: "adminPanel.status.invited", defaultMessage: "Invited" },
2338
- detail: {
2339
- messageId: "adminPanel.status.invited.detail",
2340
- defaultMessage: "Invitation not accepted yet"
2341
- }
2342
- };
2343
- }
2344
- if (row?.account === "deactivated") {
2345
- return {
2346
- key: "deactivated",
2347
- tone: "neutral",
2348
- label: { messageId: "adminPanel.status.deactivated", defaultMessage: "Deactivated" },
2349
- detail: {
2350
- messageId: "adminPanel.status.deactivated.detail",
2351
- defaultMessage: "Cannot sign in"
2352
- }
2353
- };
2354
- }
2355
- const count = Number(row?.sessionCount) || 0;
2356
- if (count > 0) {
2357
- return {
2358
- key: "signed-in",
2359
- tone: "success",
2360
- label: { messageId: "adminPanel.status.signedIn", defaultMessage: "Signed in" },
2361
- detail: {
2362
- messageId: "adminPanel.status.signedIn.detail",
2363
- defaultMessage: "{count, plural, one {# session} other {# sessions}}",
2364
- values: { count }
2365
- }
2366
- };
2367
- }
2368
- return {
2369
- key: "not-signed-in",
2370
- tone: "neutral",
2371
- label: { messageId: "adminPanel.status.notSignedIn", defaultMessage: "Not signed in" },
2372
- detail: {
2373
- messageId: "adminPanel.status.notSignedIn.detail",
2374
- defaultMessage: "No open session"
1934
+ const RecentUserActivityList = () => {
1935
+ const { formatMessage } = useIntl();
1936
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
1937
+ const params = useMemo(() => buildUserActivityParams({ pageSize: RECENT_USER_EVENT_LIMIT }), []);
1938
+ const list = useEventList({
1939
+ path: USER_ACTIVITY_API_PATH,
1940
+ params,
1941
+ logKey: "userActivity.recent"
1942
+ });
1943
+ return /* @__PURE__ */ jsx(
1944
+ RecentEvents,
1945
+ {
1946
+ title: t("userActivity.recent.title", "Security activity"),
1947
+ subtitle: t(
1948
+ "userActivity.recent.subtitle",
1949
+ "The latest failed and refused sign-ins, lockouts, new devices, impossible travel and impersonations of your app’s users. Select an event for its details."
1950
+ ),
1951
+ showAllTo: USER_ACTIVITY_PAGE_PATH,
1952
+ emptyText: t("userActivity.recent.empty", "No security events of app users yet."),
1953
+ list,
1954
+ dataKey: "recent-user-activity",
1955
+ renderTable: (title) => /* @__PURE__ */ jsx(UserEventTable, { rows: list.rows, label: title, busy: list.loading })
2375
1956
  }
2376
- };
2377
- }
2378
- function splitDuration(seconds) {
2379
- const value = Number(seconds);
2380
- if (!Number.isFinite(value) || value <= 0) return null;
2381
- if (value % 86400 === 0) return { unit: "days", count: value / 86400 };
2382
- if (value % 3600 === 0) return { unit: "hours", count: value / 3600 };
2383
- return { unit: "minutes", count: Math.max(1, Math.round(value / 60)) };
2384
- }
2385
- function getSignOutErrorMessage(error) {
2386
- const response = (
2387
- /** @type {any} */
2388
- error?.response
2389
1957
  );
2390
- const status = Number(response?.status ?? /** @type {any} */
2391
- error?.status);
2392
- const reason = response?.data?.error?.details?.reason;
2393
- if (status === 403 && reason === "super-admin-protected") {
2394
- return {
2395
- messageId: "adminPanel.signOut.error.protected",
2396
- defaultMessage: "Only a Super Admin can sign out a Super Admin."
2397
- };
2398
- }
2399
- if (status === 403) {
2400
- return {
2401
- messageId: "adminPanel.signOut.error.forbidden",
2402
- defaultMessage: "You do not have permission to sign admins out."
2403
- };
1958
+ };
1959
+ const RecentUserActivity = () => {
1960
+ const {
1961
+ allowedActions: { canRead },
1962
+ isLoading
1963
+ } = useRBAC(pluginPermissions.userActivityRead);
1964
+ if (isLoading || !canRead) return null;
1965
+ return /* @__PURE__ */ jsx(RecentUserActivityList, {});
1966
+ };
1967
+ const CLOCK_TICK_MS = 30 * 1e3;
1968
+ const ANALYTICS_PATH = `/settings/${pluginId}/analytics`;
1969
+ const CONFIGURATION_PATH = `/settings/${pluginId}/general`;
1970
+ const PaginationTargets$3 = styled.div`
1971
+ nav a {
1972
+ min-width: 3.2rem;
2404
1973
  }
2405
- if (status === 404) {
2406
- return {
2407
- messageId: "adminPanel.signOut.error.gone",
2408
- defaultMessage: "This session has already ended. The list is up to date now."
2409
- };
1974
+
1975
+ & > div {
1976
+ flex-wrap: wrap;
1977
+ gap: ${({ theme }) => theme.spaces[2]} ${({ theme }) => theme.spaces[4]};
2410
1978
  }
2411
- if (status === 429) {
2412
- return {
2413
- messageId: "adminPanel.signOut.error.rateLimited",
2414
- defaultMessage: "Too many sign-outs in a short time. Wait a minute and try again."
2415
- };
1979
+
1980
+ & > div > div > span {
1981
+ white-space: nowrap;
2416
1982
  }
2417
- return {
2418
- messageId: "adminPanel.signOut.error.generic",
2419
- defaultMessage: "The admin could not be signed out. Try again."
2420
- };
2421
- }
2422
- function withIdentityPlaceholders(admin, placeholderName, identity) {
2423
- if (!admin || typeof admin !== "object") return admin;
2424
- const hidden = !admin.self && !admin.name;
2425
- return {
2426
- ...admin,
2427
- name: admin.name || placeholderName(admin.id),
2428
- identityHidden: hidden,
2429
- rolesHidden: hidden && identity?.roles === false
2430
- };
2431
- }
2432
- function withEventAdminNames(row, placeholderName) {
2433
- if (!row || typeof row !== "object") return row;
2434
- const fill = (admin) => admin && typeof admin === "object" && !admin.name ? { ...admin, name: placeholderName(admin.id), identityHidden: true } : admin;
2435
- return {
2436
- ...row,
2437
- ...row.admin !== void 0 ? { admin: fill(row.admin) } : {},
2438
- ...row.actor !== void 0 ? { actor: fill(row.actor) } : {}
2439
- };
2440
- }
2441
- const HIGHLIGHT_BADGE = { backgroundColor: "primary100", textColor: "neutral800" };
2442
- const keepActionKeys = (event) => {
2443
- if (shouldIsolateActionKey(event.key, true)) event.stopPropagation();
1983
+ `;
1984
+ const downloadFile = (content, type, extension) => {
1985
+ const blob = new Blob([content], { type });
1986
+ const url = URL.createObjectURL(blob);
1987
+ const link = document.createElement("a");
1988
+ link.href = url;
1989
+ link.download = `sessions-export-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.${extension}`;
1990
+ link.click();
1991
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
2444
1992
  };
2445
- const SHRINKING_ADMIN_CELL = { maxWidth: 0, width: "34%" };
2446
- const SHRINKING_ROLES_CELL = { maxWidth: 0, width: "22%" };
2447
- const useT$4 = () => {
1993
+ const HomePage = () => {
2448
1994
  const { formatMessage } = useIntl();
2449
- return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
2450
- };
2451
- const AdminIdentity = ({ admin }) => {
2452
- const t = useT$4();
2453
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, children: [
2454
- /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", minWidth: 0, children: [
2455
- /* @__PURE__ */ jsx(
2456
- Typography,
2457
- {
2458
- variant: "omega",
2459
- fontWeight: "semiBold",
2460
- textColor: "neutral800",
2461
- ellipsis: true,
2462
- title: admin.name,
2463
- children: admin.name
2464
- }
2465
- ),
2466
- admin.self ? /* @__PURE__ */ jsx(Badge, { ...HIGHLIGHT_BADGE, shrink: 0, children: t("adminPanel.you", "You") }) : null
2467
- ] }),
2468
- admin.identityHidden ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("adminPanel.identity.emailHidden", "Email hidden (needs “Read” on Users)") }) : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", ellipsis: true, title: admin.email, children: admin.email })
2469
- ] });
2470
- };
2471
- const AdminRoles = ({ admin }) => {
2472
- const t = useT$4();
2473
- const names = (admin.roles || []).map((role) => role.name).filter(Boolean);
2474
- const text = admin.rolesHidden ? t("adminPanel.roles.hidden", "Hidden (needs “Read” on Roles)") : names.length ? names.join(", ") : t("adminPanel.roles.none", "No role");
2475
- return /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", ellipsis: true, title: text, children: text });
2476
- };
2477
- const AdminStatus = ({ admin }) => {
2478
- const t = useT$4();
2479
- const status = getAdminStatusPresentation(admin);
2480
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-admin-status": status.key, children: [
2481
- /* @__PURE__ */ jsx(Badge, { ...getBadgeColors(status.tone), children: t(status.label.messageId, status.label.defaultMessage) }),
2482
- /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(status.detail.messageId, status.detail.defaultMessage, status.detail.values) })
2483
- ] });
2484
- };
2485
- const AdminTable = ({
2486
- admins,
2487
- labelledBy,
2488
- canRevoke,
2489
- onView,
2490
- onSignOutEverywhere,
2491
- busy
2492
- }) => {
2493
- const t = useT$4();
2494
- return /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-admin-table": "", children: /* @__PURE__ */ jsxs(
2495
- Table,
2496
- {
2497
- colCount: 5,
2498
- rowCount: admins.length + 1,
2499
- "aria-labelledby": labelledBy,
2500
- "aria-busy": busy,
2501
- children: [
2502
- /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
2503
- /* @__PURE__ */ jsx(Th, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.admin", "Admin") }) }),
2504
- /* @__PURE__ */ jsx(Th, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.roles", "Roles") }) }),
2505
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.status", "Status") }) }),
2506
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }) }),
2507
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("adminPanel.table.actions", "Actions") }) })
2508
- ] }) }),
2509
- /* @__PURE__ */ jsx(Tbody, { children: admins.map((admin) => /* @__PURE__ */ jsxs(Tr, { "data-admin-row": admin.id, children: [
2510
- /* @__PURE__ */ jsx(Td, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(AdminIdentity, { admin }) }),
2511
- /* @__PURE__ */ jsx(Td, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(AdminRoles, { admin }) }),
2512
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(AdminStatus, { admin }) }),
2513
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt }) }),
2514
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsxs(RowActions, { onKeyDown: keepActionKeys, children: [
2515
- /* @__PURE__ */ jsx(
2516
- IconButton,
2517
- {
2518
- label: t("adminPanel.actions.view", "View sessions of {name}", {
2519
- name: admin.name
2520
- }),
2521
- onClick: (event) => onView(admin, event.currentTarget),
2522
- children: /* @__PURE__ */ jsx(Eye, {})
2523
- }
2524
- ),
2525
- canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2526
- IconButton,
2527
- {
2528
- variant: "danger-light",
2529
- label: t(
2530
- "adminPanel.actions.signOutEverywhere",
2531
- "Sign out {name} everywhere",
2532
- {
2533
- name: admin.name
2534
- }
2535
- ),
2536
- onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2537
- children: /* @__PURE__ */ jsx(SignOut, {})
2538
- }
2539
- ) : null
2540
- ] }) })
2541
- ] }, admin.id)) })
2542
- ]
1995
+ const { get, post, del } = useFetchClient();
1996
+ const { toggleNotification } = useNotification();
1997
+ const formatters = useSessionFormatters();
1998
+ const { isBelowSmall, isBelowMedium, isBelowLarge } = useBreakpoint();
1999
+ const [listWidthRef, listWidth] = useElementWidth();
2000
+ const [{ query }, setQuery] = useQueryParams();
2001
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
2002
+ const dashboard = parseDashboardQuery(query);
2003
+ const [sessions, setSessions] = useState([]);
2004
+ const [pagination, setPagination] = useState({ total: 0, pageCount: 1 });
2005
+ const [stats, setStats] = useState(EMPTY_SESSION_STATS);
2006
+ const [exporting, setExporting] = useState(false);
2007
+ const [loading, setLoading] = useState(true);
2008
+ const [refreshing, setRefreshing] = useState(false);
2009
+ const [loadError, setLoadError] = useState(false);
2010
+ const [hasData, setHasData] = useState(false);
2011
+ const [lastUpdated, setLastUpdated] = useState(null);
2012
+ const [now, setNow] = useState(() => Date.now());
2013
+ const [selectedSession, setSelectedSession] = useState(null);
2014
+ const [showDetailModal, setShowDetailModal] = useState(false);
2015
+ const [terminatingSessionId, setTerminatingSessionId] = useState(null);
2016
+ const [deletingSessionId, setDeletingSessionId] = useState(null);
2017
+ const openerRef = useRef(null);
2018
+ const dashboardRef = useRef(null);
2019
+ const listHeadingRef = useRef(null);
2020
+ const hasLoadedRef = useRef(false);
2021
+ const requestIdRef = useRef(0);
2022
+ const visibleIdsRef = useRef([]);
2023
+ const mutationSnapshotRef = useRef([]);
2024
+ const listHeadingId = `session-list-caption-${useId().replace(/:/g, "")}`;
2025
+ const mutationPending = Boolean(terminatingSessionId || deletingSessionId);
2026
+ const listQuery = useMemo(
2027
+ () => ({
2028
+ page: dashboard.page,
2029
+ pageSize: dashboard.pageSize,
2030
+ status: dashboard.status,
2031
+ reason: dashboard.reason,
2032
+ search: dashboard.search
2033
+ }),
2034
+ [dashboard.page, dashboard.pageSize, dashboard.status, dashboard.reason, dashboard.search]
2035
+ );
2036
+ useEffect(() => {
2037
+ const timer = setInterval(() => setNow(Date.now()), CLOCK_TICK_MS);
2038
+ return () => clearInterval(timer);
2039
+ }, []);
2040
+ const fetchSessions = useCallback(async () => {
2041
+ const requestId = requestIdRef.current + 1;
2042
+ requestIdRef.current = requestId;
2043
+ if (hasLoadedRef.current) setRefreshing(true);
2044
+ else setLoading(true);
2045
+ try {
2046
+ const [listResponse, statsResponse] = await Promise.all([
2047
+ get(`/${pluginId}/sessions`, { params: buildListParams(listQuery) }),
2048
+ get(`/${pluginId}/sessions/stats`)
2049
+ ]);
2050
+ const page = readSessionPage(listResponse.data);
2051
+ const nextStats = readSessionStats(statsResponse.data);
2052
+ if (requestId !== requestIdRef.current) return;
2053
+ setSessions(page.rows);
2054
+ setPagination(page.pagination);
2055
+ setStats(nextStats);
2056
+ setLoadError(false);
2057
+ setHasData(true);
2058
+ setLastUpdated(Date.now());
2059
+ setNow(Date.now());
2060
+ hasLoadedRef.current = true;
2061
+ } catch (err) {
2062
+ if (requestId !== requestIdRef.current || isCancelledRequest(err)) return;
2063
+ setLoadError(true);
2064
+ logSafeAdminError("dashboard.loadSessions", err);
2065
+ } finally {
2066
+ if (requestId === requestIdRef.current) {
2067
+ setLoading(false);
2068
+ setRefreshing(false);
2069
+ }
2543
2070
  }
2544
- ) });
2545
- };
2546
- const AdminCardList = ({ admins, labelledBy, canRevoke, onView, onSignOutEverywhere }) => {
2547
- const t = useT$4();
2548
- return /* @__PURE__ */ jsx(
2549
- Flex,
2550
- {
2551
- tag: "ul",
2552
- direction: "column",
2553
- alignItems: "stretch",
2554
- gap: 3,
2555
- "aria-labelledby": labelledBy,
2556
- "data-admin-cards": "",
2557
- children: admins.map((admin) => /* @__PURE__ */ jsx(
2558
- Box,
2559
- {
2560
- tag: "li",
2561
- background: "neutral0",
2562
- hasRadius: true,
2563
- shadow: "tableShadow",
2564
- padding: 4,
2565
- "data-admin-row": admin.id,
2566
- children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 3, minWidth: 0, children: [
2567
- /* @__PURE__ */ jsx(AdminIdentity, { admin }),
2568
- /* @__PURE__ */ jsxs(Flex, { gap: 4, wrap: "wrap", alignItems: "flex-start", justifyContent: "space-between", children: [
2569
- /* @__PURE__ */ jsx(AdminStatus, { admin }),
2570
- /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
2571
- /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }),
2572
- /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt })
2573
- ] })
2574
- ] }),
2575
- /* @__PURE__ */ jsx(AdminRoles, { admin }),
2576
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
2577
- /* @__PURE__ */ jsx(
2578
- Button,
2579
- {
2580
- variant: "secondary",
2581
- startIcon: /* @__PURE__ */ jsx(Eye, {}),
2582
- onClick: (event) => onView(admin, event.currentTarget),
2583
- "aria-label": t("adminPanel.actions.view", "View sessions of {name}", {
2584
- name: admin.name
2585
- }),
2586
- flex: "1 1 auto",
2587
- children: t("adminPanel.actions.viewShort", "View sessions")
2588
- }
2589
- ),
2590
- canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2591
- Button,
2592
- {
2593
- variant: "danger-light",
2594
- startIcon: /* @__PURE__ */ jsx(SignOut, {}),
2595
- onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2596
- "aria-label": t(
2597
- "adminPanel.actions.signOutEverywhere",
2598
- "Sign out {name} everywhere",
2599
- {
2600
- name: admin.name
2601
- }
2602
- ),
2603
- flex: "1 1 auto",
2604
- children: t("adminPanel.actions.signOutEverywhereShort", "Sign out everywhere")
2605
- }
2606
- ) : null
2607
- ] })
2608
- ] })
2609
- },
2610
- admin.id
2611
- ))
2071
+ }, [get, listQuery]);
2072
+ useEffect(() => {
2073
+ fetchSessions();
2074
+ }, [fetchSessions]);
2075
+ useEffect(() => {
2076
+ if (showDetailModal || mutationPending) return void 0;
2077
+ const interval = setInterval(() => {
2078
+ fetchSessions();
2079
+ }, AUTO_REFRESH_INTERVAL_MS);
2080
+ return () => clearInterval(interval);
2081
+ }, [showDetailModal, mutationPending, fetchSessions]);
2082
+ const handleTerminateSession = async (session) => {
2083
+ if (terminatingSessionId || deletingSessionId) return;
2084
+ const sessionId = session.id;
2085
+ mutationSnapshotRef.current = visibleIdsRef.current;
2086
+ setTerminatingSessionId(sessionId);
2087
+ try {
2088
+ await post(`/${pluginId}/sessions/${sessionId}/terminate`);
2089
+ await fetchSessions();
2090
+ toggleNotification({
2091
+ type: "success",
2092
+ message: t("notifications.success.sessionEnded", "Session ended.")
2093
+ });
2094
+ } catch (err) {
2095
+ logSafeAdminError("dashboard.terminateSession", err);
2096
+ if (getErrorStatus(err) === 404) {
2097
+ await fetchSessions();
2098
+ toggleNotification({
2099
+ type: "warning",
2100
+ message: t(
2101
+ "notifications.error.sessionGone",
2102
+ "This session no longer exists. The list was refreshed."
2103
+ )
2104
+ });
2105
+ return;
2106
+ }
2107
+ toggleNotification({
2108
+ type: "danger",
2109
+ message: t(
2110
+ "notifications.error.endSession",
2111
+ "The session could not be ended. Please try again."
2112
+ )
2113
+ });
2114
+ throw err;
2115
+ } finally {
2116
+ setTerminatingSessionId(null);
2612
2117
  }
2613
- );
2614
- };
2615
- const SIGN_IN_FILTER_OPTIONS = Object.freeze(["all", "succeeded", "failed", "signed-out"]);
2616
- const ALL_ADMINS_FILTER_OPTIONS = Object.freeze([...SIGN_IN_FILTER_OPTIONS, "changes"]);
2617
- const ACTIVITY_ACTION_OPTIONS = Object.freeze([
2618
- "all",
2619
- "view",
2620
- "create",
2621
- "update",
2622
- "publish",
2623
- "unpublish",
2624
- "discard",
2625
- "delete",
2626
- "clone"
2627
- ]);
2628
- const PERIOD_OPTIONS = Object.freeze(["1", "7", "30", "90", "all"]);
2629
- const EVENT_PAGE_SIZE = 20;
2630
- const MAX_EVENT_EXPORT_ROWS = 1e4;
2631
- function periodStart(period, now = /* @__PURE__ */ new Date()) {
2632
- const days = Number.parseInt(period, 10);
2633
- if (!Number.isInteger(days) || days <= 0) return void 0;
2634
- return new Date(now.getTime() - days * 24 * 60 * 60 * 1e3).toISOString();
2635
- }
2636
- function buildSignInParams(filters, now) {
2637
- const params = {
2638
- page: filters.page || 1,
2639
- pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2640
- event: ALL_ADMINS_FILTER_OPTIONS.includes(filters.event) ? filters.event : "all"
2641
2118
  };
2642
- if (filters.adminId) params.adminId = String(filters.adminId);
2643
- const from = periodStart(filters.period || "all", now);
2644
- if (from) params.from = from;
2645
- return params;
2646
- }
2647
- function buildActivityParams(filters, now) {
2648
- const params = {
2649
- page: filters.page || 1,
2650
- pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2651
- action: ACTIVITY_ACTION_OPTIONS.includes(filters.action) ? filters.action : "all"
2119
+ const handleDeleteSession = async (session) => {
2120
+ if (terminatingSessionId || deletingSessionId) return;
2121
+ const sessionId = session.id;
2122
+ mutationSnapshotRef.current = visibleIdsRef.current;
2123
+ setDeletingSessionId(sessionId);
2124
+ try {
2125
+ await del(`/${pluginId}/sessions/${sessionId}`);
2126
+ await fetchSessions();
2127
+ toggleNotification({
2128
+ type: "success",
2129
+ message: t(
2130
+ "notifications.success.recordDeleted",
2131
+ "Session record deleted. Its token stays revoked."
2132
+ )
2133
+ });
2134
+ } catch (err) {
2135
+ logSafeAdminError("dashboard.deleteSession", err);
2136
+ if (getErrorStatus(err) === 404) {
2137
+ await fetchSessions();
2138
+ toggleNotification({
2139
+ type: "warning",
2140
+ message: t(
2141
+ "notifications.error.sessionGone",
2142
+ "This session no longer exists. The list was refreshed."
2143
+ )
2144
+ });
2145
+ return;
2146
+ }
2147
+ toggleNotification({
2148
+ type: "danger",
2149
+ message: t(
2150
+ "notifications.error.deleteRecord",
2151
+ "The record could not be deleted. Please try again."
2152
+ )
2153
+ });
2154
+ throw err;
2155
+ } finally {
2156
+ setDeletingSessionId(null);
2157
+ }
2158
+ };
2159
+ const pageSize = Number(dashboard.pageSize);
2160
+ const pageResult = {
2161
+ items: sessions,
2162
+ total: pagination.total,
2163
+ pageCount: pagination.pageCount,
2164
+ startIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + 1 : 0,
2165
+ endIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + sessions.length : 0
2166
+ };
2167
+ const visibleIds = pageResult.items.map((session) => String(session.id));
2168
+ useLayoutEffect(() => {
2169
+ visibleIdsRef.current = visibleIds;
2170
+ });
2171
+ const fetchExportRows = async () => {
2172
+ const rows = [];
2173
+ let cursor = null;
2174
+ do {
2175
+ const { data } = await get(`/${pluginId}/sessions/export`, {
2176
+ params: buildExportParams(listQuery, cursor)
2177
+ });
2178
+ rows.push(...requireSessionList(data));
2179
+ cursor = typeof data?.meta?.nextCursor === "string" ? data.meta.nextCursor : null;
2180
+ } while (cursor && rows.length < MAX_EXPORT_ROWS);
2181
+ const capped = rows.length > MAX_EXPORT_ROWS || Boolean(cursor) && rows.length >= MAX_EXPORT_ROWS;
2182
+ return { rows: rows.slice(0, MAX_EXPORT_ROWS), capped };
2183
+ };
2184
+ const handleExport = async (format) => {
2185
+ if (exporting) return;
2186
+ setExporting(true);
2187
+ try {
2188
+ const { rows, capped } = await fetchExportRows();
2189
+ if (format === "csv") {
2190
+ const csvContent = buildSessionCsv(rows, {
2191
+ unavailableValue: "",
2192
+ getDeviceInfo: getExportDeviceInfo,
2193
+ getSessionStatus
2194
+ });
2195
+ downloadFile(csvContent, "text/csv;charset=utf-8;", "csv");
2196
+ } else {
2197
+ const jsonContent = buildSessionJson(rows, {
2198
+ filterStatus: dashboard.status,
2199
+ totalSessions: stats.total,
2200
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
2201
+ unavailableValue: "",
2202
+ getDeviceInfo: getExportDeviceInfo,
2203
+ getSessionStatus,
2204
+ truncated: capped
2205
+ });
2206
+ downloadFile(jsonContent, "application/json", "json");
2207
+ }
2208
+ if (capped) {
2209
+ toggleNotification({
2210
+ type: "warning",
2211
+ message: t(
2212
+ "homepage.export.capped",
2213
+ "The export contains the newest {limit, number} sessions. Narrow the filter to export the rest.",
2214
+ { limit: MAX_EXPORT_ROWS }
2215
+ )
2216
+ });
2217
+ }
2218
+ } catch (err) {
2219
+ if (isCancelledRequest(err)) return;
2220
+ logSafeAdminError(format === "csv" ? "dashboard.exportCsv" : "dashboard.exportJson", err);
2221
+ toggleNotification({
2222
+ type: "danger",
2223
+ message: t("notifications.error.exportFailed", "The export could not be created.")
2224
+ });
2225
+ } finally {
2226
+ setExporting(false);
2227
+ }
2228
+ };
2229
+ const handleSessionClick = (session, opener) => {
2230
+ openerRef.current = opener;
2231
+ setSelectedSession(session);
2232
+ setShowDetailModal(true);
2233
+ };
2234
+ const handleModalClose = () => {
2235
+ setShowDetailModal(false);
2236
+ setSelectedSession(null);
2652
2237
  };
2653
- if (filters.adminId) params.adminId = String(filters.adminId);
2654
- if (filters.contentType && filters.contentType !== "all")
2655
- params.contentType = filters.contentType;
2656
- const from = periodStart(filters.period || "all", now);
2657
- if (from) params.from = from;
2658
- return params;
2659
- }
2660
- function toExportParams(params, cursor) {
2661
- const { page: _page, pageSize: _pageSize, ...rest } = params;
2662
- return cursor ? { ...rest, cursor } : rest;
2663
- }
2664
- const message = (messageId, defaultMessage) => ({ messageId, defaultMessage });
2665
- const FAILURE_REASONS = Object.freeze({
2666
- invalid_credentials: message(
2667
- "adminPanel.activity.reason.invalidCredentials",
2668
- "Wrong email or password"
2669
- ),
2670
- account_inactive: message("adminPanel.activity.reason.accountInactive", "Account is deactivated"),
2671
- login_not_allowed: message("adminPanel.activity.reason.notAllowed", "Sign-in is not allowed"),
2672
- rate_limited: message("adminPanel.activity.reason.rateLimited", "Too many attempts")
2673
- });
2674
- const appUserEvent = (key, tone, icon, messageId, defaultMessage) => ({
2675
- key,
2676
- tone,
2677
- icon,
2678
- label: message(messageId, defaultMessage),
2679
- detail: null
2680
- });
2681
- function getSignInEventPresentation(row) {
2682
- switch (row?.event) {
2683
- case "admin.sign-in":
2684
- return {
2685
- key: "sign-in",
2686
- tone: "success",
2687
- icon: "signIn",
2688
- label: message("adminPanel.activity.event.signIn", "Signed in"),
2689
- detail: row.reason === "registration" ? message("adminPanel.activity.reason.registration", "First sign-in after registration") : row.reason === "password_reset" ? message(
2690
- "adminPanel.activity.reason.passwordReset",
2691
- "Signed in after a password reset"
2692
- ) : null
2693
- };
2694
- case "admin.sign-in.failed":
2695
- return {
2696
- key: "failed",
2697
- tone: "danger",
2698
- icon: "failed",
2699
- label: message("adminPanel.activity.event.failed", "Sign-in failed"),
2700
- detail: FAILURE_REASONS[row.reason] || null
2701
- };
2702
- case "admin.lockout":
2703
- return {
2704
- key: "lockout",
2705
- tone: "danger",
2706
- icon: "lockout",
2707
- label: message("adminPanel.activity.event.lockout", "Locked out"),
2708
- detail: FAILURE_REASONS.rate_limited
2709
- };
2710
- case "admin.sign-out":
2711
- return {
2712
- key: "sign-out",
2713
- tone: "neutral",
2714
- icon: "signOut",
2715
- label: message("adminPanel.activity.event.signOut", "Signed out"),
2716
- detail: null
2717
- };
2718
- case "admin.session.revoked":
2719
- return {
2720
- key: "revoked",
2721
- tone: "warning",
2722
- icon: "revoked",
2723
- label: message("adminPanel.activity.event.revoked", "Signed out by an admin"),
2724
- detail: row.scope === "one_browser" ? message("adminPanel.activity.scope.oneBrowser", "One browser") : message("adminPanel.activity.scope.everywhere", "Every browser")
2725
- };
2726
- case "settings.updated":
2727
- return {
2728
- key: "settings",
2729
- tone: "secondary",
2730
- icon: "settings",
2731
- label: message("adminPanel.activity.event.settings", "Settings changed"),
2732
- detail: row.change?.viaToken ? message("adminPanel.activity.via.token", "With an admin API token") : null
2733
- };
2734
- case "security-log.read":
2735
- return {
2736
- key: "log-read",
2737
- tone: "secondary",
2738
- icon: "logRead",
2739
- label: message("adminPanel.activity.event.logRead", "Log read with an API token"),
2740
- detail: row.read?.list === "content" ? row.read?.exported ? message(
2741
- "adminPanel.activity.read.contentExport",
2742
- "Content Manager activity exported"
2743
- ) : message("adminPanel.activity.read.content", "Content Manager activity listed") : row.read?.exported ? message("adminPanel.activity.read.signInsExport", "Sign-in history exported") : message("adminPanel.activity.read.signIns", "Sign-in history listed")
2744
- };
2745
- case "security-log.retention.purged":
2746
- return {
2747
- key: "purged",
2748
- tone: "neutral",
2749
- icon: "purged",
2750
- label: message("adminPanel.activity.event.purged", "Old events deleted"),
2751
- detail: null
2752
- };
2753
- // App-user events (4.17 / 4.18). The admin lists of this view do not return them
2754
- // today; they get their own label and colour so any list that does shows them clearly.
2755
- case "user.sign-in.failed":
2756
- return appUserEvent(
2757
- "user-failed",
2758
- "danger",
2759
- "failed",
2760
- "adminPanel.activity.event.userFailed",
2761
- "App user sign-in failed"
2762
- );
2763
- case "user.sign-in.refused":
2764
- return appUserEvent(
2765
- "user-refused",
2766
- "danger",
2767
- "refused",
2768
- "adminPanel.activity.event.userRefused",
2769
- "App user sign-in refused"
2770
- );
2771
- case "user.lockout":
2772
- return appUserEvent(
2773
- "user-lockout",
2774
- "danger",
2775
- "lockout",
2776
- "adminPanel.activity.event.userLockout",
2777
- "App user locked out"
2778
- );
2779
- case "user.lockout.lifted":
2780
- return appUserEvent(
2781
- "user-unlock",
2782
- "secondary",
2783
- "unlock",
2784
- "adminPanel.activity.event.userUnlock",
2785
- "Lockout lifted"
2786
- );
2787
- case "user.session.limit":
2788
- return appUserEvent(
2789
- "user-limit",
2790
- "warning",
2791
- "limit",
2792
- "adminPanel.activity.event.userLimit",
2793
- "Session limit reached"
2794
- );
2795
- case "user.password-change.ended-others":
2796
- return appUserEvent(
2797
- "user-password",
2798
- "warning",
2799
- "password",
2800
- "adminPanel.activity.event.userPassword",
2801
- "Signed out after a password change"
2802
- );
2803
- case "user.sign-in.new-device":
2804
- return appUserEvent(
2805
- "user-device",
2806
- "secondary",
2807
- "device",
2808
- "adminPanel.activity.event.userNewDevice",
2809
- "Sign-in from a new device"
2810
- );
2811
- case "user.sign-in.impossible-travel":
2812
- return appUserEvent(
2813
- "user-travel",
2814
- "danger",
2815
- "travel",
2816
- "adminPanel.activity.event.userTravel",
2817
- "Impossible travel"
2818
- );
2819
- case "user.not-me":
2820
- return appUserEvent(
2821
- "user-not-me",
2822
- "danger",
2823
- "notMe",
2824
- "adminPanel.activity.event.userNotMe",
2825
- 'Reported as "This wasn’t me"'
2826
- );
2827
- case "user.data.exported":
2828
- return appUserEvent(
2829
- "user-export",
2830
- "secondary",
2831
- "export",
2832
- "adminPanel.activity.event.userExport",
2833
- "Personal data exported"
2834
- );
2835
- default:
2836
- if (typeof row?.event === "string" && row.event.startsWith("impersonation.")) {
2837
- return appUserEvent(
2838
- "impersonation",
2839
- "warning",
2840
- "impersonation",
2841
- "adminPanel.activity.event.impersonation",
2842
- "Impersonation"
2843
- );
2844
- }
2845
- if (typeof row?.event === "string" && row.event.startsWith("webhook.")) {
2846
- return appUserEvent(
2847
- "webhook",
2848
- "neutral",
2849
- "webhook",
2850
- "adminPanel.activity.event.webhook",
2851
- "Webhook delivery"
2238
+ const handleCloseAutoFocus = (event) => {
2239
+ restoreDialogFocus(event, openerRef.current, listHeadingRef.current || dashboardRef.current);
2240
+ };
2241
+ const getFocusFallback = useCallback(
2242
+ (sessionId) => ({
2243
+ get current() {
2244
+ const targetId = pickFocusSessionId(
2245
+ mutationSnapshotRef.current,
2246
+ visibleIdsRef.current,
2247
+ sessionId
2852
2248
  );
2249
+ const root = dashboardRef.current;
2250
+ if (targetId && root) {
2251
+ const escaped = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(targetId) : targetId;
2252
+ const button = root.querySelector(`[data-session-view="${escaped}"]`);
2253
+ if (button) return button;
2254
+ }
2255
+ return listHeadingRef.current;
2853
2256
  }
2854
- return {
2855
- key: "other",
2856
- tone: "neutral",
2857
- icon: "other",
2858
- label: message("adminPanel.activity.event.other", "Security event"),
2859
- detail: null
2860
- };
2861
- }
2862
- }
2863
- function getSessionStatePresentation(session) {
2864
- switch (session?.state) {
2865
- case "active":
2866
- return {
2867
- tone: "success",
2868
- label: message("adminPanel.activity.session.active", "Still signed in")
2869
- };
2870
- case "signed-out":
2871
- return {
2872
- tone: "neutral",
2873
- label: message("adminPanel.activity.session.signedOut", "Signed out")
2874
- };
2875
- case "ended":
2876
- return {
2877
- tone: "neutral",
2878
- label: message("adminPanel.activity.session.ended", "Session ended")
2879
- };
2880
- default:
2881
- return null;
2882
- }
2883
- }
2884
- const RECENT_EVENT_LIMIT = 8;
2885
- const ACTIVITY_PAGE_SIZE_OPTIONS = Object.freeze(["10", "20", "50", "100"]);
2886
- const EVENT_TABLE_MIN_WIDTH = Object.freeze({ withAdmin: 800, withoutAdmin: 740 });
2887
- const EVENT_TABLE_FULL_WIDTH = 1e3;
2888
- function getEventListLayout(width, { showAdmin = false } = {}) {
2889
- if (!width) return "full";
2890
- const min = showAdmin ? EVENT_TABLE_MIN_WIDTH.withAdmin : EVENT_TABLE_MIN_WIDTH.withoutAdmin;
2891
- if (width < min) return "stacked";
2892
- return width >= EVENT_TABLE_FULL_WIDTH ? "full" : "table";
2893
- }
2894
- function getEventPlace(row) {
2895
- return [row?.location?.city, row?.location?.country].filter(Boolean).join(", ");
2896
- }
2897
- function parseActivityPageQuery(query) {
2898
- const source = query || {};
2899
- const event = ALL_ADMINS_FILTER_OPTIONS.includes(String(source.event)) ? String(source.event) : "all";
2900
- const period = PERIOD_OPTIONS.includes(String(source.period)) ? String(source.period) : "30";
2901
- const adminId = /^[1-9][0-9]{0,11}$/.test(String(source.adminId ?? "")) ? Number(source.adminId) : null;
2902
- const page = Number.parseInt(String(source.page ?? ""), 10);
2903
- const pageSize = String(source.pageSize ?? "");
2904
- return {
2905
- event,
2906
- period,
2907
- adminId,
2908
- page: Number.isInteger(page) && page > 0 ? page : 1,
2909
- pageSize: ACTIVITY_PAGE_SIZE_OPTIONS.includes(pageSize) ? Number(pageSize) : EVENT_PAGE_SIZE
2910
- };
2911
- }
2912
- function hasActivityPageFilters(view) {
2913
- return view.event !== "all" || view.period !== "30" || view.adminId !== null;
2914
- }
2915
- function groupChangedSettings(keys) {
2916
- const list = Array.isArray(keys) ? keys.filter((key) => typeof key === "string" && key) : [];
2917
- const byTab = /* @__PURE__ */ new Map();
2918
- const unknown = [];
2919
- const seen = /* @__PURE__ */ new Set();
2920
- for (const key of list) {
2921
- const tab = SETTINGS_TAB_IDS.find((id) => SETTINGS_TAB_FIELDS[id]?.includes(key));
2922
- const entry = SETTINGS_FIELD_LABELS[key];
2923
- if (!tab || !entry) {
2924
- if (!seen.has(`raw:${key}`)) unknown.push({ key, label: null });
2925
- seen.add(`raw:${key}`);
2926
- continue;
2927
- }
2928
- if (seen.has(`label:${entry[0]}`)) continue;
2929
- seen.add(`label:${entry[0]}`);
2930
- if (!byTab.has(tab)) byTab.set(tab, []);
2931
- byTab.get(tab).push({ key, label: message(entry[0], entry[1]) });
2932
- }
2933
- const groups = SETTINGS_TAB_IDS.filter((tab) => byTab.has(tab)).map((tab) => ({
2934
- tab,
2935
- label: message(SETTINGS_TAB_LABELS[tab][0], SETTINGS_TAB_LABELS[tab][1]),
2936
- fields: byTab.get(tab)
2937
- }));
2938
- if (unknown.length) groups.push({ tab: null, label: null, fields: unknown });
2939
- return groups;
2940
- }
2941
- const ACTIVITY_ACTION_LABELS = Object.freeze({
2942
- all: message("adminPanel.activity.action.all", "All actions"),
2943
- view: message("adminPanel.activity.action.view", "Opened"),
2944
- create: message("adminPanel.activity.action.create", "Created"),
2945
- update: message("adminPanel.activity.action.update", "Edited"),
2946
- publish: message("adminPanel.activity.action.publish", "Published"),
2947
- unpublish: message("adminPanel.activity.action.unpublish", "Unpublished"),
2948
- discard: message("adminPanel.activity.action.discard", "Discarded draft"),
2949
- delete: message("adminPanel.activity.action.delete", "Deleted"),
2950
- clone: message("adminPanel.activity.action.clone", "Duplicated")
2951
- });
2952
- function getActivityTone(action) {
2953
- if (action === "publish") return "success";
2954
- if (action === "delete") return "warning";
2955
- return "neutral";
2956
- }
2957
- function getEntryPath(row) {
2958
- const type = row?.contentType;
2959
- if (!type?.exists || row.action === "delete") return null;
2960
- const uid = encodeURIComponent(type.uid);
2961
- const locale = row.entry?.locale ? `?plugins[i18n][locale]=${encodeURIComponent(row.entry.locale)}` : "";
2962
- if (type.kind === "single") return `/content-manager/single-types/${uid}${locale}`;
2963
- if (!row.entry?.documentId) return null;
2964
- return `/content-manager/collection-types/${uid}/${encodeURIComponent(row.entry.documentId)}${locale}`;
2965
- }
2966
- const SIGN_IN_CSV_HEADERS = Object.freeze([
2967
- "Time",
2968
- "Event",
2969
- "Reason",
2970
- "Admin",
2971
- "Admin ID",
2972
- "IP Address",
2973
- "IP Anonymized",
2974
- "Country",
2975
- "City",
2976
- "Browser",
2977
- "OS",
2978
- "Device",
2979
- "Session",
2980
- "Signed Out By"
2981
- ]);
2982
- const ACTIVITY_CSV_HEADERS = Object.freeze([
2983
- "Time",
2984
- "Action",
2985
- "Admin",
2986
- "Admin ID",
2987
- "Content Type",
2988
- "Content Type UID",
2989
- "Document ID",
2990
- "Locale",
2991
- "Title",
2992
- "Entries"
2993
- ]);
2994
- const toCsv = (headers, rows) => [headers, ...rows].map((cells) => cells.map(escapeCsvValue).join(",")).join("\n");
2995
- function buildSignInCsv(rows) {
2996
- return toCsv(
2997
- SIGN_IN_CSV_HEADERS,
2998
- rows.map((row) => [
2999
- row.at || "",
3000
- row.event || "",
3001
- row.reason || row.scope || "",
3002
- row.admin?.name || "",
3003
- row.admin?.id ?? "",
3004
- row.ipAddress || "",
3005
- row.ipAnonymized ? "yes" : "no",
3006
- row.location?.country || "",
3007
- row.location?.city || "",
3008
- row.browser || "",
3009
- row.os || "",
3010
- row.deviceType || "",
3011
- row.session?.state || "",
3012
- row.actor?.name || ""
3013
- ])
3014
- );
3015
- }
3016
- function buildActivityCsv(rows) {
3017
- return toCsv(
3018
- ACTIVITY_CSV_HEADERS,
3019
- rows.map((row) => [
3020
- row.at || "",
3021
- row.action || "",
3022
- row.admin?.name || "",
3023
- row.admin?.id ?? "",
3024
- row.contentType?.name || "",
3025
- row.contentType?.uid || "",
3026
- row.entry?.documentId || "",
3027
- row.entry?.locale || "",
3028
- row.entry?.title || "",
3029
- row.entry?.count ?? ""
3030
- ])
2257
+ }),
2258
+ []
3031
2259
  );
3032
- }
3033
- const settingsGroupText = (t, group) => {
3034
- const fields = group.fields.map(
3035
- (field) => field.label ? t(field.label.messageId, field.label.defaultMessage) : field.key
3036
- ).join(", ");
3037
- return group.label ? t("adminPanel.activity.settingsGroup", "{tab}: {fields}", {
3038
- tab: t(group.label.messageId, group.label.defaultMessage),
3039
- fields
3040
- }) : fields;
3041
- };
3042
- const changedSettingsText = (t, keys, { limit } = {}) => {
3043
- const groups = groupChangedSettings(keys);
3044
- const total = groups.reduce((sum, group) => sum + group.fields.length, 0);
3045
- if (!total) return "";
3046
- let budget = limit && limit > 0 ? limit : total;
3047
- const shown = [];
3048
- for (const group of groups) {
3049
- if (budget <= 0) break;
3050
- shown.push({ ...group, fields: group.fields.slice(0, budget) });
3051
- budget -= Math.min(budget, group.fields.length);
3052
- }
3053
- const named = shown.reduce((sum, group) => sum + group.fields.length, 0);
3054
- const text = shown.map((group) => settingsGroupText(t, group)).join(" · ");
3055
- return named < total ? t("adminPanel.activity.settingsMore", "{names} and {count, number} more", {
3056
- names: text,
3057
- count: total - named
3058
- }) : text;
3059
- };
3060
- const changedSettingsLines = (t, keys) => groupChangedSettings(keys).map((group) => settingsGroupText(t, group));
3061
- const noAdminText = (t, row) => row?.event === "security-log.retention.purged" ? t("adminPanel.activity.system", "System") : t("adminPanel.activity.unknownAccount", "Unknown account");
3062
- const deviceText = (t, row) => {
3063
- if (row.browser && row.os) {
3064
- return t("adminPanel.activity.browserOnOs", "{browser} on {os}", {
3065
- browser: row.browser,
3066
- os: row.os
3067
- });
3068
- }
3069
- return row.browser || row.os || "";
3070
- };
3071
- const ipText = (t, row) => {
3072
- if (!row.ipAddress) return "";
3073
- return row.ipAnonymized ? t("adminPanel.activity.ipAnonymized", "{ip} (anonymised)", { ip: row.ipAddress }) : row.ipAddress;
3074
- };
3075
- const eventDetailText = (t, row, presentation, withActor) => {
3076
- const parts = [];
3077
- if (presentation.detail) {
3078
- parts.push(t(presentation.detail.messageId, presentation.detail.defaultMessage));
3079
- }
3080
- if (Number.isInteger(row.attempts) && row.attempts > 1) {
3081
- parts.push(
3082
- t(
3083
- "adminPanel.activity.attempts",
3084
- "{count, plural, one {# attempt} other {# attempts}} within 5 minutes",
3085
- { count: row.attempts }
3086
- )
3087
- );
3088
- }
3089
- const changed = changedSettingsText(t, row.change?.keys, { limit: 3 });
3090
- if (changed) parts.push(changed);
3091
- if (Number.isInteger(row.purge?.count)) {
3092
- parts.push(
3093
- Number.isInteger(row.purge?.retentionDays) ? t(
3094
- "adminPanel.activity.purgedDetail",
3095
- "{count, plural, one {# event} other {# events}}, older than {days, plural, one {# day} other {# days}}",
3096
- { count: row.purge.count, days: row.purge.retentionDays }
3097
- ) : t("adminPanel.activity.purgedCount", "{count, plural, one {# event} other {# events}}", {
3098
- count: row.purge.count
3099
- })
3100
- );
3101
- }
3102
- if (withActor && row.actor?.name) {
3103
- parts.push(t("adminPanel.activity.byAdmin", "by {name}", { name: row.actor.name }));
3104
- }
3105
- return parts.join(" · ");
3106
- };
3107
- const contentTypeText = (row) => [row.contentType?.name, row.entry?.locale].filter(Boolean).join(" · ");
3108
- const useT$3 = () => {
3109
- const { formatMessage } = useIntl();
3110
- return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
3111
- };
3112
- const SHORT_DATE = Object.freeze({ dateStyle: "medium", timeStyle: "short" });
3113
- const FULL_DATE = Object.freeze({ dateStyle: "full", timeStyle: "medium" });
3114
- const EVENT_ICONS = Object.freeze({
3115
- signIn: CheckCircle,
3116
- failed: CrossCircle,
3117
- lockout: Lock,
3118
- signOut: SignOut,
3119
- revoked: Shield,
3120
- settings: Cog,
3121
- logRead: Key,
3122
- purged: Trash,
3123
- refused: CrossCircle,
3124
- unlock: Lock,
3125
- limit: Stack,
3126
- password: Key,
3127
- device: Monitor,
3128
- travel: Earth,
3129
- notMe: WarningCircle,
3130
- export: Download,
3131
- impersonation: User,
3132
- webhook: Webhooks,
3133
- other: Information
3134
- });
3135
- const ICON_FILL = Object.freeze({
3136
- success: "success600",
3137
- danger: "danger600",
3138
- warning: "warning700",
3139
- secondary: "secondary600",
3140
- neutral: "neutral600"
3141
- });
3142
- const stopCellKeys = (event) => {
3143
- if (event.key === "Enter" || event.key === " " || event.key === "Spacebar") {
3144
- event.stopPropagation();
3145
- }
3146
- };
3147
- const ClickableRow = styled(Tr)`
3148
- cursor: pointer;
3149
- `;
3150
- const WrapCell = styled(Td)`
3151
- white-space: normal;
3152
- `;
3153
- const NoWrap = styled.span`
3154
- white-space: nowrap;
3155
- `;
3156
- const NameButton = styled(TextButton)`
3157
- min-height: 3.2rem;
3158
- text-align: start;
3159
- `;
3160
- const StackedList = styled.ul`
3161
- margin: 0;
3162
- padding: 0;
3163
- list-style: none;
3164
- border: 1px solid ${({ theme }) => theme.colors.neutral150};
3165
- border-radius: ${({ theme }) => theme.borderRadius};
3166
- background: ${({ theme }) => theme.colors.neutral0};
3167
- min-width: 0;
3168
-
3169
- & > li + li {
3170
- border-top: 1px solid ${({ theme }) => theme.colors.neutral150};
3171
- }
3172
- `;
3173
- const StackedItem = styled.li`
3174
- cursor: pointer;
3175
- min-width: 0;
3176
- `;
3177
- const BreakAnywhere = styled(Typography)`
3178
- overflow-wrap: anywhere;
3179
- `;
3180
- const getEventBadgeColors = (tone) => tone === "danger" ? { backgroundColor: "danger100", textColor: "danger700" } : getBadgeColors(tone);
3181
- const EventBadge = ({ presentation, nowrap = false }) => {
3182
- const t = useT$3();
3183
- const Icon = EVENT_ICONS[presentation.icon] || Information;
3184
- return /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", shrink: 0, "data-event-kind": presentation.key, children: [
3185
- /* @__PURE__ */ jsx(
3186
- Icon,
3187
- {
3188
- "aria-hidden": "true",
3189
- focusable: "false",
3190
- width: "1.6rem",
3191
- height: "1.6rem",
3192
- fill: ICON_FILL[presentation.tone] || ICON_FILL.neutral
3193
- }
3194
- ),
3195
- /* @__PURE__ */ jsx(Badge, { ...getEventBadgeColors(presentation.tone), "data-event-tone": presentation.tone, children: nowrap ? /* @__PURE__ */ jsx(NoWrap, { children: t(presentation.label.messageId, presentation.label.defaultMessage) }) : t(presentation.label.messageId, presentation.label.defaultMessage) })
3196
- ] });
3197
- };
3198
- const EventTime = ({ value, compact = false }) => {
3199
- const { formatDate, formatRelativeTime } = useSessionFormatters();
3200
- const date = toValidDate(value);
3201
- if (!date) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3202
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3203
- /* @__PURE__ */ jsx(
3204
- Typography,
3205
- {
3206
- tag: "time",
3207
- dateTime: date.toISOString(),
3208
- variant: compact ? "pi" : "omega",
3209
- textColor: "neutral800",
3210
- children: /* @__PURE__ */ jsx(NoWrap, { children: formatRelativeTime(date) })
3211
- }
3212
- ),
3213
- compact ? null : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: /* @__PURE__ */ jsx(NoWrap, { children: formatDate(date, SHORT_DATE) }) })
3214
- ] });
3215
- };
3216
- const AdminName = ({ admin, row, onOpenAdmin }) => {
3217
- const t = useT$3();
3218
- if (!admin) {
3219
- return /* @__PURE__ */ jsx(Typography, { variant: onOpenAdmin ? "pi" : "omega", textColor: "neutral600", children: noAdminText(t, row) });
3220
- }
3221
- if (!onOpenAdmin) {
3222
- return /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: admin.name });
3223
- }
3224
- return /* @__PURE__ */ jsx(
3225
- NameButton,
3226
- {
3227
- onClick: (event) => {
3228
- event.stopPropagation();
3229
- onOpenAdmin(admin, event.currentTarget);
3230
- },
3231
- onKeyDown: stopCellKeys,
3232
- "aria-label": t("adminPanel.activity.openAdmin", "Open the details of {name}", {
3233
- name: admin.name
3234
- }),
3235
- children: admin.name
2260
+ useEffect(() => {
2261
+ if (!loading && !refreshing && dashboard.page > pageResult.pageCount) {
2262
+ setQuery({ page: String(pageResult.pageCount) }, "push", true);
3236
2263
  }
3237
- );
3238
- };
3239
- const SignInDetails = ({ row }) => {
3240
- const t = useT$3();
3241
- const ip = ipText(t, row);
3242
- const second = [getEventPlace(row), deviceText(t, row)].filter(Boolean).join(" · ");
3243
- if (!ip && !second) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3244
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3245
- ip ? /* @__PURE__ */ jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: ip }) : null,
3246
- second ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3247
- ] });
3248
- };
3249
- const SessionState = ({ row }) => {
3250
- const t = useT$3();
3251
- const { formatRelativeTime } = useSessionFormatters();
3252
- const state = getSessionStatePresentation(row.session);
3253
- if (!state) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3254
- const endedAt = toValidDate(row.session?.endedAt);
3255
- const second = [
3256
- endedAt ? formatRelativeTime(endedAt) : "",
3257
- row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3258
- ].filter(Boolean).join(" · ");
3259
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3260
- /* @__PURE__ */ jsx(
3261
- Typography,
3262
- {
3263
- variant: "omega",
3264
- fontWeight: state.tone === "success" ? "semiBold" : void 0,
3265
- textColor: state.tone === "success" ? "success600" : "neutral800",
3266
- "data-session-state": row.session?.state,
3267
- children: t(state.label.messageId, state.label.defaultMessage)
3268
- }
3269
- ),
3270
- second ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3271
- ] });
3272
- };
3273
- const HeaderCell = ({ children, hidden = false }) => /* @__PURE__ */ jsx(Th, { children: hidden ? /* @__PURE__ */ jsx(VisuallyHidden, { children }) : /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children }) });
3274
- const DetailsButton = ({ label, onOpen }) => /* @__PURE__ */ jsx(
3275
- IconButton,
3276
- {
3277
- variant: "ghost",
3278
- label,
3279
- withTooltip: false,
3280
- onClick: (event) => {
3281
- event.stopPropagation();
3282
- onOpen(event.currentTarget);
2264
+ }, [loading, refreshing, dashboard.page, pageResult.pageCount, setQuery]);
2265
+ const handleStatusChange = (value) => {
2266
+ const status = String(value);
2267
+ setQuery({ status: status === "all" ? void 0 : status, reason: void 0, page: "1" });
2268
+ };
2269
+ const handleReasonChange = (value) => {
2270
+ const reason = String(value);
2271
+ setQuery({ reason: reason === "all" ? void 0 : reason, page: "1" });
2272
+ };
2273
+ const handleSearch = useCallback(
2274
+ (value) => {
2275
+ setQuery({ search: encodeSearchQuery(value), _q: void 0, page: "1" }, "push", true);
3283
2276
  },
3284
- onKeyDown: stopCellKeys,
3285
- "data-event-details": "",
3286
- children: /* @__PURE__ */ jsx(Eye, {})
3287
- }
3288
- );
3289
- const ActivityEntry = ({ row }) => {
3290
- const t = useT$3();
3291
- const path = getEntryPath(row);
3292
- const name = row.entry?.count !== null && row.entry?.count !== void 0 ? t("adminPanel.activity.entries", "{count, plural, one {# entry} other {# entries}}", {
3293
- count: row.entry.count
3294
- }) : row.entry?.title || row.entry?.documentId || row.contentType?.name || "";
3295
- if (!name) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3296
- if (!path) {
3297
- return /* @__PURE__ */ jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: name });
3298
- }
3299
- return /* @__PURE__ */ jsx(
3300
- TargetLink$1,
3301
- {
3302
- tag: Link$1,
3303
- to: path,
3304
- onClick: (event) => event.stopPropagation(),
3305
- onKeyDown: stopCellKeys,
3306
- "aria-label": t("adminPanel.activity.openEntry", "Open {entry} in the Content Manager", {
3307
- entry: name
3308
- }),
3309
- children: name
3310
- }
2277
+ [setQuery]
3311
2278
  );
3312
- };
3313
- const EventDetailsModal = ({ title, items, footerAction, onClose, onCloseAutoFocus }) => {
3314
- const t = useT$3();
3315
- return /* @__PURE__ */ jsx(Modal.Root, { open: true, onOpenChange: (open) => open ? null : onClose(), children: /* @__PURE__ */ jsxs(Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
3316
- /* @__PURE__ */ jsx(Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsx(Modal.Title, { children: title }) }),
3317
- /* @__PURE__ */ jsx(Modal.Body, { children: /* @__PURE__ */ jsx(Box, { background: "neutral100", hasRadius: true, padding: { initial: 4, medium: 6 }, children: /* @__PURE__ */ jsx(PropertyList, { columns: 2, items }) }) }),
3318
- /* @__PURE__ */ jsxs(Modal.Footer, { children: [
3319
- /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: t("common.close", "Close") }) }),
3320
- footerAction || null
3321
- ] })
3322
- ] }) });
3323
- };
3324
- const useEventDetails = () => {
3325
- const [selected, setSelected] = useState(null);
3326
- const [opener, setOpener] = useState(null);
3327
- const [container, setContainer] = useState(null);
3328
- return {
3329
- selected,
3330
- setContainer,
3331
- open: (row, trigger) => {
3332
- const button = trigger?.matches?.("[data-event-details]") ? trigger : trigger?.querySelector?.("[data-event-details]");
3333
- setOpener(button || null);
3334
- setSelected(row);
3335
- },
3336
- close: () => setSelected(null),
3337
- onCloseAutoFocus: (event) => restoreDialogFocus(event, opener, container)
2279
+ const handleClearFilters = () => {
2280
+ setQuery({ search: void 0, _q: void 0, status: void 0, reason: void 0, page: "1" });
2281
+ listHeadingRef.current?.focus();
3338
2282
  };
3339
- };
3340
- const signInDetails = (t, formatDate, row) => {
3341
- const presentation = getSignInEventPresentation(row);
3342
- const label = t(presentation.label.messageId, presentation.label.defaultMessage);
3343
- const state = getSessionStatePresentation(row.session);
3344
- const revoked = presentation.key === "revoked";
3345
- const adminName = row.admin?.name || noAdminText(t, row);
3346
- const items = [
3347
- {
3348
- id: "event",
3349
- label: t("adminPanel.activity.column.event", "Event"),
3350
- render: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
3351
- /* @__PURE__ */ jsx(EventBadge, { presentation }),
3352
- presentation.detail ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(presentation.detail.messageId, presentation.detail.defaultMessage) }) : null
3353
- ] })
3354
- },
3355
- {
3356
- id: "time",
3357
- label: t("adminPanel.activity.details.exactTime", "Exact time"),
3358
- value: row.at ? formatDate(row.at, FULL_DATE) : null
3359
- },
3360
- { id: "admin", label: t("adminPanel.activity.column.admin", "Admin"), value: adminName }
3361
- ];
3362
- if (revoked) {
3363
- items.push(
3364
- {
3365
- id: "actor",
3366
- label: t("adminPanel.activity.column.doneBy", "Done by"),
3367
- value: row.actor?.name || null
3368
- },
3369
- {
3370
- id: "scope",
3371
- label: t("adminPanel.activity.details.signedOutOf", "Signed out of"),
3372
- value: Number.isInteger(row.sessionsEnded) && row.sessionsEnded >= 0 ? t(
3373
- "adminPanel.activity.details.scopeCount",
3374
- "{scope} ({count, plural, =0 {no open session} one {# session ended} other {# sessions ended}})",
3375
- {
3376
- scope: t(presentation.detail.messageId, presentation.detail.defaultMessage),
3377
- count: row.sessionsEnded
3378
- }
3379
- ) : t(presentation.detail.messageId, presentation.detail.defaultMessage)
3380
- }
3381
- );
3382
- }
3383
- if (state) {
3384
- const endedAt = toValidDate(row.session?.endedAt);
3385
- items.push({
3386
- id: "session",
3387
- label: t("adminPanel.activity.column.session", "Session"),
3388
- value: [
3389
- t(state.label.messageId, state.label.defaultMessage),
3390
- endedAt ? formatDate(endedAt, SHORT_DATE) : "",
3391
- row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3392
- ].filter(Boolean).join(" · ")
3393
- });
3394
- }
3395
- if (row.change) {
3396
- const lines = changedSettingsLines(t, row.change.keys);
3397
- items.push({
3398
- id: "settings",
3399
- label: t("adminPanel.activity.details.changedSettings", "Changed settings"),
3400
- ...lines.length ? {
3401
- render: /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-changed-settings": "", children: lines.map((line) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: line }, line)) })
3402
- } : { value: null },
3403
- fullWidth: true
3404
- });
3405
- }
3406
- if (row.purge) {
3407
- items.push(
3408
- {
3409
- id: "purged",
3410
- label: t("adminPanel.activity.details.deleted", "Deleted events"),
3411
- value: Number.isInteger(row.purge.count) ? row.purge.count : null
3412
- },
3413
- {
3414
- id: "retention",
3415
- label: t("adminPanel.activity.details.retention", "Kept for"),
3416
- value: Number.isInteger(row.purge.retentionDays) ? t("adminPanel.duration.days", "{count, plural, one {# day} other {# days}}", {
3417
- count: row.purge.retentionDays
3418
- }) : null
3419
- }
3420
- );
3421
- }
3422
- if (Number.isInteger(row.attempts) && row.attempts > 1) {
3423
- items.push({
3424
- id: "attempts",
3425
- label: t("adminPanel.activity.details.attempts", "Attempts"),
3426
- value: row.attempts
3427
- });
3428
- }
3429
- items.push(
3430
- {
3431
- id: "ip",
3432
- label: t("adminPanel.activity.details.ip", "IP address"),
3433
- value: ipText(t, row) || null,
3434
- kind: "id"
3435
- },
3436
- {
3437
- id: "place",
3438
- label: t("adminPanel.activity.details.location", "Location"),
3439
- value: getEventPlace(row) || null
3440
- },
3441
- {
3442
- id: "browser",
3443
- label: t("adminPanel.activity.details.browser", "Browser"),
3444
- value: row.browser || null
3445
- },
3446
- {
3447
- id: "os",
3448
- label: t("adminPanel.activity.details.os", "Operating system"),
3449
- value: row.os || null
3450
- },
3451
- {
3452
- id: "userAgent",
3453
- label: t("adminPanel.activity.details.userAgent", "User agent"),
3454
- value: row.userAgent || null,
3455
- kind: "id",
3456
- fullWidth: true
3457
- },
2283
+ const showSessionData = !loading && hasData;
2284
+ const showToolbar = showSessionData && stats.total > 0;
2285
+ const canExport = showSessionData && pageResult.total > 0 && !exporting;
2286
+ const filtersActive = hasActiveFilters(dashboard);
2287
+ const exportValues = { count: Math.min(pageResult.total, MAX_EXPORT_ROWS) };
2288
+ const exportMenu = /* @__PURE__ */ jsxs(
2289
+ SimpleMenu,
3458
2290
  {
3459
- id: "eventId",
3460
- label: t("adminPanel.activity.details.eventId", "Event ID"),
3461
- value: row.id,
3462
- kind: "id"
2291
+ label: t("homepage.export.label", "Export"),
2292
+ variant: "secondary",
2293
+ startIcon: /* @__PURE__ */ jsx(Download, {}),
2294
+ disabled: !canExport,
2295
+ children: [
2296
+ /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("csv"), children: t(
2297
+ "homepage.export.csv",
2298
+ "{count, plural, one {Export # session as CSV} other {Export # sessions as CSV}}",
2299
+ exportValues
2300
+ ) }),
2301
+ /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("json"), children: t(
2302
+ "homepage.export.json",
2303
+ "{count, plural, one {Export # session as JSON} other {Export # sessions as JSON}}",
2304
+ exportValues
2305
+ ) })
2306
+ ]
3463
2307
  }
3464
2308
  );
3465
- const title = row.admin?.name ? t("adminPanel.activity.details.title", "{event}: {name}", { event: label, name: adminName }) : label;
3466
- const logEvent = ["settings", "log-read", "purged"].includes(presentation.key);
3467
- const deviceFields = /* @__PURE__ */ new Set(["ip", "place", "browser", "os", "userAgent"]);
3468
- return {
3469
- title,
3470
- items: logEvent ? items.filter(
3471
- (item) => !deviceFields.has(item.id) || item.value !== null && item.value !== ""
3472
- ) : items
3473
- };
3474
- };
3475
- const activityDetails = (t, formatDate, row) => {
3476
- const label = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3477
- const action = t(label.messageId, label.defaultMessage);
3478
- return {
3479
- title: row.entry?.title ? t("adminPanel.activity.details.title", "{event}: {name}", {
3480
- event: action,
3481
- name: row.entry.title
3482
- }) : action,
3483
- items: [
3484
- {
3485
- id: "action",
3486
- label: t("adminPanel.activity.column.action", "Action"),
3487
- render: /* @__PURE__ */ jsx(Badge, { ...getBadgeColors(getActivityTone(row.action)), children: action })
3488
- },
3489
- {
3490
- id: "time",
3491
- label: t("adminPanel.activity.details.exactTime", "Exact time"),
3492
- value: row.at ? formatDate(row.at, FULL_DATE) : null
3493
- },
3494
- {
3495
- id: "entry",
3496
- label: t("adminPanel.activity.column.entry", "Entry"),
3497
- render: /* @__PURE__ */ jsx(ActivityEntry, { row })
3498
- },
3499
- {
3500
- id: "admin",
3501
- label: t("adminPanel.activity.column.admin", "Admin"),
3502
- value: row.admin?.name || null
3503
- },
2309
+ const exportAction = canExport || !showSessionData ? exportMenu : /* @__PURE__ */ jsx(Tooltip, { label: t("homepage.export.disabledHint", "No sessions match the current filter."), children: /* @__PURE__ */ jsx("span", { children: exportMenu }) });
2310
+ const analyticsLabel = t("homepage.links.analytics", "Analytics");
2311
+ const settingsLabel = t("homepage.links.settings", "Settings");
2312
+ const primaryAction = /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", justifyContent: "flex-end", children: [
2313
+ isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: ANALYTICS_PATH, label: analyticsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(ChartBubble, {}) }) : /* @__PURE__ */ jsx(
2314
+ LinkButton,
3504
2315
  {
3505
- id: "type",
3506
- label: t("adminPanel.activity.column.contentType", "Content type"),
3507
- value: row.contentType?.name || null
3508
- },
2316
+ tag: Link$1,
2317
+ to: ANALYTICS_PATH,
2318
+ variant: "tertiary",
2319
+ size: "S",
2320
+ startIcon: /* @__PURE__ */ jsx(ChartBubble, {}),
2321
+ children: analyticsLabel
2322
+ }
2323
+ ),
2324
+ isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: CONFIGURATION_PATH, label: settingsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(Cog, {}) }) : /* @__PURE__ */ jsx(
2325
+ LinkButton,
3509
2326
  {
3510
- id: "uid",
3511
- label: t("adminPanel.activity.details.uid", "Content type UID"),
3512
- value: row.contentType?.uid || null,
3513
- kind: "id"
3514
- },
2327
+ tag: Link$1,
2328
+ to: CONFIGURATION_PATH,
2329
+ variant: "tertiary",
2330
+ size: "S",
2331
+ startIcon: /* @__PURE__ */ jsx(Cog, {}),
2332
+ children: settingsLabel
2333
+ }
2334
+ ),
2335
+ exportAction
2336
+ ] });
2337
+ const filterSlot = isBelowMedium ? { flex: "1 1 auto", minWidth: 0 } : void 0;
2338
+ const filterControls = /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: isBelowMedium ? "nowrap" : "wrap", shrink: 0, children: [
2339
+ /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2340
+ SingleSelect,
3515
2341
  {
3516
- id: "documentId",
3517
- label: t("adminPanel.activity.details.documentId", "Document ID"),
3518
- value: row.entry?.documentId || null,
3519
- kind: "id"
3520
- },
2342
+ size: "S",
2343
+ "aria-label": t("homepage.filter.label", "Status"),
2344
+ value: dashboard.status,
2345
+ onChange: handleStatusChange,
2346
+ children: SESSION_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsxs(SingleSelectOption, { value: option, children: [
2347
+ option === "all" && t("homepage.filter.all", "All sessions"),
2348
+ option === "open" && t("homepage.filter.open", "Open"),
2349
+ option !== "all" && option !== "open" && formatters.statusLabel(option)
2350
+ ] }, option))
2351
+ }
2352
+ ) }),
2353
+ dashboard.status === "ended" ? /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2354
+ SingleSelect,
3521
2355
  {
3522
- id: "locale",
3523
- label: t("adminPanel.activity.details.locale", "Locale"),
3524
- value: row.entry?.locale || null
3525
- },
2356
+ size: "S",
2357
+ "aria-label": t("homepage.filter.reasonLabel", "End reason"),
2358
+ value: dashboard.reason,
2359
+ onChange: handleReasonChange,
2360
+ children: END_REASON_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: option === "all" ? t("homepage.filter.allReasons", "All reasons") : formatters.endReasonLabel(option) }, option))
2361
+ }
2362
+ ) }) : null,
2363
+ /* @__PURE__ */ jsx(
2364
+ IconButton,
3526
2365
  {
3527
- id: "eventId",
3528
- label: t("adminPanel.activity.details.eventId", "Event ID"),
3529
- value: row.id,
3530
- kind: "id"
2366
+ label: t("homepage.actions.refresh", "Refresh sessions"),
2367
+ onClick: () => fetchSessions(),
2368
+ children: /* @__PURE__ */ jsx(ArrowClockwise, {})
3531
2369
  }
3532
- ]
2370
+ )
2371
+ ] });
2372
+ const toolbar = /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-session-toolbar": "", children: /* @__PURE__ */ jsxs(
2373
+ Flex,
2374
+ {
2375
+ direction: { initial: "column", medium: "row" },
2376
+ alignItems: { initial: "stretch", medium: "center" },
2377
+ gap: 2,
2378
+ children: [
2379
+ /* @__PURE__ */ jsx(Flex, { flex: "1 1 auto", minWidth: 0, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsx(SessionSearch, { value: dashboard.search, onSearch: handleSearch }) }),
2380
+ filterControls
2381
+ ]
2382
+ }
2383
+ ) });
2384
+ const lastUpdatedLine = lastUpdated ? /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: "wrap", justifyContent: "flex-end", children: [
2385
+ refreshing ? /* @__PURE__ */ jsx(Loader, { small: true, role: "status", "aria-live": "polite", children: t("homepage.refreshing", "Updating sessions") }) : null,
2386
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", "data-last-updated": "", children: t("homepage.lastUpdated", "Last updated {time}", {
2387
+ time: formatters.formatRelativeTime(lastUpdated, now)
2388
+ }) })
2389
+ ] }) : null;
2390
+ const listProps = {
2391
+ sessions: pageResult.items,
2392
+ labelledBy: listHeadingId,
2393
+ busy: refreshing,
2394
+ onView: handleSessionClick,
2395
+ onEnd: handleTerminateSession,
2396
+ onDelete: handleDeleteSession,
2397
+ mutationPending,
2398
+ getFocusFallback
3533
2399
  };
3534
- };
3535
- const SignInEventTable = ({
3536
- rows,
3537
- label,
3538
- showAdmin = false,
3539
- onOpenAdmin,
3540
- detailsAction,
3541
- busy = false
3542
- }) => {
3543
- const t = useT$3();
3544
- const { formatDate, formatRelativeTime } = useSessionFormatters();
3545
- const [measureRef, width] = useElementWidth();
3546
- const {
3547
- selected,
3548
- open: openDetails,
3549
- close: closeDetails,
3550
- onCloseAutoFocus,
3551
- setContainer
3552
- } = useEventDetails();
3553
- const layout = getEventListLayout(width, { showAdmin });
3554
- const showDoneBy = layout === "full";
3555
- const detailsLabel = (row, presentation) => t("adminPanel.activity.details.open", "Details of {event}, {time}", {
3556
- event: t(presentation.label.messageId, presentation.label.defaultMessage),
3557
- time: formatRelativeTime(row.at)
2400
+ const statusCard = (status) => ({
2401
+ onClick: () => handleStatusChange(status),
2402
+ pressed: dashboard.status === status
3558
2403
  });
3559
- let list;
3560
- if (layout === "stacked") {
3561
- list = /* @__PURE__ */ jsx(StackedList, { "aria-label": label, "data-event-list": "stacked", children: rows.map((row) => {
3562
- const presentation = getSignInEventPresentation(row);
3563
- const state = getSessionStatePresentation(row.session);
3564
- const second = [
3565
- eventDetailText(t, row, presentation, true),
3566
- ipText(t, row),
3567
- getEventPlace(row),
3568
- deviceText(t, row),
3569
- state ? t(state.label.messageId, state.label.defaultMessage) : ""
3570
- ].filter(Boolean).join(" · ");
3571
- return /* @__PURE__ */ jsx(
3572
- StackedItem,
2404
+ return /* @__PURE__ */ jsx(
2405
+ PageShell,
2406
+ {
2407
+ headingId: "magic-sessionmanager-dashboard-title",
2408
+ title: t("homepage.title", "Sessions"),
2409
+ subtitle: t(
2410
+ "homepage.subtitle",
2411
+ "Sign-ins of your app’s users (Users & Permissions). Strapi administrators are not listed."
2412
+ ),
2413
+ primaryAction,
2414
+ children: /* @__PURE__ */ jsxs(
2415
+ Flex,
3573
2416
  {
3574
- "data-event-row": presentation.key,
3575
- "data-event-id": row.id,
3576
- onClick: (event) => openDetails(row, event.currentTarget),
3577
- children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, padding: 3, minWidth: 0, children: [
3578
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", minWidth: 0, children: [
3579
- /* @__PURE__ */ jsx(EventBadge, { presentation }),
3580
- /* @__PURE__ */ jsxs(Flex, { gap: 1, alignItems: "center", marginLeft: "auto", children: [
3581
- /* @__PURE__ */ jsx(EventTime, { value: row.at, compact: true }),
2417
+ ref: dashboardRef,
2418
+ tabIndex: -1,
2419
+ direction: "column",
2420
+ alignItems: "stretch",
2421
+ gap: 6,
2422
+ minWidth: 0,
2423
+ children: [
2424
+ /* @__PURE__ */ jsx(SessionViewNav, { current: "users" }),
2425
+ !loading && loadError ? /* @__PURE__ */ jsx(
2426
+ PersistentAlert,
2427
+ {
2428
+ variant: "danger",
2429
+ closeLabel: t("common.close", "Close"),
2430
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: fetchSessions, children: t("common.tryAgain", "Try again") }),
2431
+ children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "span", children: t("homepage.error.load", "Sessions could not be loaded.") })
2432
+ }
2433
+ ) : null,
2434
+ showSessionData && stats.nativeOnly > 0 ? /* @__PURE__ */ jsx(
2435
+ UntrackedSessionsNotice,
2436
+ {
2437
+ stats,
2438
+ onChanged: fetchSessions,
2439
+ fallbackFocusRef: dashboardRef
2440
+ }
2441
+ ) : null,
2442
+ loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 8, children: /* @__PURE__ */ jsx(Loader, { children: t("homepage.loading", "Loading sessions") }) }) : null,
2443
+ showSessionData && stats.total > 0 ? /* @__PURE__ */ jsx(HowSessionsWork, {}) : null,
2444
+ showSessionData && /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
2445
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { tag: "h2", children: t("homepage.stats.label", "Session statistics") }) }),
2446
+ /* @__PURE__ */ jsxs(StatGrid, { label: t("homepage.stats.label", "Session statistics"), children: [
2447
+ /* @__PURE__ */ jsx(
2448
+ StatCard,
2449
+ {
2450
+ icon: Check,
2451
+ tone: "success",
2452
+ label: t("homepage.stats.active", "Active sessions"),
2453
+ value: stats.active,
2454
+ description: t(
2455
+ "homepage.stats.usersOnline",
2456
+ "{count, plural, one {# user online} other {# users online}}",
2457
+ {
2458
+ count: stats.usersOnline
2459
+ }
2460
+ ),
2461
+ ...statusCard("active")
2462
+ }
2463
+ ),
2464
+ /* @__PURE__ */ jsx(
2465
+ StatCard,
2466
+ {
2467
+ icon: Clock,
2468
+ tone: "warning",
2469
+ label: t("homepage.stats.idle", "Idle sessions"),
2470
+ value: stats.idle,
2471
+ ...statusCard("idle")
2472
+ }
2473
+ ),
2474
+ /* @__PURE__ */ jsx(
2475
+ StatCard,
2476
+ {
2477
+ icon: Cross,
2478
+ tone: "neutral",
2479
+ label: t("homepage.stats.ended", "Ended sessions"),
2480
+ value: stats.ended,
2481
+ description: t(
2482
+ "homepage.stats.endedBreakdown",
2483
+ "{loggedOut, number} logged out · {timedOut, number} timed out · {other, number} other reasons",
2484
+ {
2485
+ loggedOut: stats.loggedOut,
2486
+ timedOut: stats.timedOut,
2487
+ other: stats.otherReasons
2488
+ }
2489
+ ),
2490
+ ...statusCard("ended")
2491
+ }
2492
+ ),
3582
2493
  /* @__PURE__ */ jsx(
3583
- DetailsButton,
2494
+ StatCard,
3584
2495
  {
3585
- label: detailsLabel(row, presentation),
3586
- onOpen: (trigger) => openDetails(row, trigger)
2496
+ icon: User,
2497
+ tone: "primary",
2498
+ label: t("homepage.stats.total", "All sessions"),
2499
+ value: stats.total,
2500
+ ...statusCard("all")
3587
2501
  }
3588
2502
  )
3589
2503
  ] })
3590
2504
  ] }),
3591
- showAdmin ? /* @__PURE__ */ jsx(Flex, { minWidth: 0, children: /* @__PURE__ */ jsx(AdminName, { admin: row.admin, row, onOpenAdmin }) }) : null,
3592
- second ? /* @__PURE__ */ jsx(BreakAnywhere, { variant: "pi", textColor: "neutral600", children: second }) : null
3593
- ] })
3594
- },
3595
- row.id
3596
- );
3597
- }) });
3598
- } else {
3599
- const colCount = 5 + (showAdmin ? 1 : 0) + (showDoneBy ? 1 : 0);
3600
- list = /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-event-list": layout, children: /* @__PURE__ */ jsxs(Table, { colCount, rowCount: rows.length + 1, "aria-label": label, "aria-busy": busy, children: [
3601
- /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
3602
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.time", "Time") }),
3603
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.event", "Event") }),
3604
- showAdmin ? /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.admin", "Admin") }) : null,
3605
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.details", "IP address and device") }),
3606
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.session", "Session") }),
3607
- showDoneBy ? /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.doneBy", "Done by") }) : null,
3608
- /* @__PURE__ */ jsx(HeaderCell, { hidden: true, children: t("adminPanel.table.actions", "Actions") })
3609
- ] }) }),
3610
- /* @__PURE__ */ jsx(Tbody, { children: rows.map((row) => {
3611
- const presentation = getSignInEventPresentation(row);
3612
- const eventDetail = eventDetailText(t, row, presentation, !showDoneBy);
3613
- return /* @__PURE__ */ jsxs(
3614
- ClickableRow,
3615
- {
3616
- "data-event-row": presentation.key,
3617
- "data-event-id": row.id,
3618
- onClick: (event) => openDetails(row, event.currentTarget),
3619
- children: [
3620
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(EventTime, { value: row.at }) }),
3621
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3622
- /* @__PURE__ */ jsx(EventBadge, { presentation, nowrap: true }),
3623
- eventDetail ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: eventDetail }) : null
3624
- ] }) }),
3625
- showAdmin ? /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(AdminName, { admin: row.admin, row, onOpenAdmin }) }) : null,
3626
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(SignInDetails, { row }) }),
3627
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(SessionState, { row }) }),
3628
- showDoneBy ? /* @__PURE__ */ jsx(WrapCell, { children: row.actor?.name ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: row.actor.name }) : /* @__PURE__ */ jsx(MissingValue, { variant: "omega" }) }) : null,
3629
- /* @__PURE__ */ jsx(Td, { onClick: (event) => event.stopPropagation(), children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", gap: 1, onKeyDown: stopCellKeys, children: /* @__PURE__ */ jsx(
3630
- DetailsButton,
3631
- {
3632
- label: detailsLabel(row, presentation),
3633
- onOpen: (trigger) => openDetails(row, trigger)
3634
- }
3635
- ) }) })
3636
- ]
3637
- },
3638
- row.id
3639
- );
3640
- }) })
3641
- ] }) });
3642
- }
3643
- const content = selected ? signInDetails(t, formatDate, selected) : null;
3644
- return /* @__PURE__ */ jsxs(Box, { ref: measureRef, minWidth: 0, width: "100%", children: [
3645
- /* @__PURE__ */ jsx(Box, { ref: setContainer, tabIndex: -1, minWidth: 0, children: list }),
3646
- content ? /* @__PURE__ */ jsx(
3647
- EventDetailsModal,
3648
- {
3649
- title: content.title,
3650
- items: content.items,
3651
- footerAction: detailsAction ? detailsAction(selected, closeDetails) : null,
3652
- onClose: closeDetails,
3653
- onCloseAutoFocus
3654
- }
3655
- ) : null
3656
- ] });
3657
- };
3658
- const ActivityEventTable = ({ rows, label, showAdmin = false, busy = false }) => {
3659
- const t = useT$3();
3660
- const { formatDate, formatRelativeTime } = useSessionFormatters();
3661
- const [measureRef, width] = useElementWidth();
3662
- const {
3663
- selected,
3664
- open: openDetails,
3665
- close: closeDetails,
3666
- onCloseAutoFocus,
3667
- setContainer
3668
- } = useEventDetails();
3669
- const layout = getEventListLayout(width, { showAdmin });
3670
- const actionOf = (row) => {
3671
- const entry = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3672
- return t(entry.messageId, entry.defaultMessage);
3673
- };
3674
- const detailsLabel = (row) => t("adminPanel.activity.details.open", "Details of {event}, {time}", {
3675
- event: actionOf(row),
3676
- time: formatRelativeTime(row.at)
3677
- });
3678
- const badge = (row) => /* @__PURE__ */ jsx(
3679
- Badge,
3680
- {
3681
- ...getBadgeColors(getActivityTone(row.action)),
3682
- "data-event-tone": getActivityTone(row.action),
3683
- children: actionOf(row)
3684
- }
3685
- );
3686
- let list;
3687
- if (layout === "stacked") {
3688
- list = /* @__PURE__ */ jsx(StackedList, { "aria-label": label, "data-event-list": "stacked", children: rows.map((row) => /* @__PURE__ */ jsx(
3689
- StackedItem,
3690
- {
3691
- "data-event-row": row.action,
3692
- "data-event-id": row.id,
3693
- onClick: (event) => openDetails(row, event.currentTarget),
3694
- children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, padding: 3, minWidth: 0, children: [
3695
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", minWidth: 0, children: [
3696
- badge(row),
3697
- /* @__PURE__ */ jsxs(Flex, { gap: 1, alignItems: "center", marginLeft: "auto", children: [
3698
- /* @__PURE__ */ jsx(EventTime, { value: row.at, compact: true }),
3699
- /* @__PURE__ */ jsx(
3700
- DetailsButton,
2505
+ showToolbar && /* @__PURE__ */ jsxs(Flex, { ref: listWidthRef, direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
2506
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h2", children: t("homepage.list.heading", "Session list") }) }),
2507
+ toolbar,
2508
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 4, wrap: "wrap", children: [
2509
+ /* @__PURE__ */ jsx(
2510
+ Typography,
2511
+ {
2512
+ id: listHeadingId,
2513
+ ref: listHeadingRef,
2514
+ tabIndex: -1,
2515
+ variant: "pi",
2516
+ textColor: "neutral600",
2517
+ "aria-live": "polite",
2518
+ "data-session-caption": "",
2519
+ children: pageResult.total > 0 ? t(
2520
+ "homepage.caption",
2521
+ "{from, number}–{to, number} of {total, plural, one {# session} other {# sessions}}",
2522
+ {
2523
+ from: pageResult.startIndex,
2524
+ to: pageResult.endIndex,
2525
+ total: pageResult.total
2526
+ }
2527
+ ) : t("homepage.captionNone", "0 sessions")
2528
+ }
2529
+ ),
2530
+ lastUpdatedLine
2531
+ ] }),
2532
+ pageResult.total > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
2533
+ isBelowMedium ? /* @__PURE__ */ jsx(SessionCardList, { ...listProps }) : /* @__PURE__ */ jsx(
2534
+ SessionTable,
2535
+ {
2536
+ ...listProps,
2537
+ compact: shouldUseCompactTable(listWidth, isBelowLarge)
2538
+ }
2539
+ ),
2540
+ /* @__PURE__ */ jsx(PaginationTargets$3, { children: /* @__PURE__ */ jsxs(
2541
+ Pagination.Root,
2542
+ {
2543
+ pageCount: pageResult.pageCount,
2544
+ total: pageResult.total,
2545
+ defaultPageSize: Number(DEFAULT_PAGE_SIZE),
2546
+ children: [
2547
+ /* @__PURE__ */ jsx(Pagination.PageSize, { options: [...PAGE_SIZE_OPTIONS] }),
2548
+ /* @__PURE__ */ jsx(Pagination.Links, {})
2549
+ ]
2550
+ }
2551
+ ) })
2552
+ ] }) : /* @__PURE__ */ jsx(
2553
+ EmptyStateLayout,
3701
2554
  {
3702
- label: detailsLabel(row),
3703
- onOpen: (trigger) => openDetails(row, trigger)
2555
+ icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2556
+ content: t(
2557
+ "homepage.noResults.description",
2558
+ "No sessions match your search or filter."
2559
+ ),
2560
+ action: filtersActive ? /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: handleClearFilters, children: t("homepage.noResults.reset", "Clear filters") }) : null
3704
2561
  }
3705
2562
  )
3706
- ] })
3707
- ] }),
3708
- /* @__PURE__ */ jsx(Flex, { minWidth: 0, children: /* @__PURE__ */ jsx(ActivityEntry, { row }) }),
3709
- contentTypeText(row) || showAdmin && row.admin?.name ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: [contentTypeText(row), showAdmin ? row.admin?.name : ""].filter(Boolean).join(" · ") }) : null
3710
- ] })
3711
- },
3712
- row.id
3713
- )) });
3714
- } else {
3715
- const colCount = 5 + (showAdmin ? 1 : 0);
3716
- list = /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-event-list": layout, children: /* @__PURE__ */ jsxs(Table, { colCount, rowCount: rows.length + 1, "aria-label": label, "aria-busy": busy, children: [
3717
- /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
3718
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.time", "Time") }),
3719
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.action", "Action") }),
3720
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.entry", "Entry") }),
3721
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.contentType", "Content type") }),
3722
- showAdmin ? /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.admin", "Admin") }) : null,
3723
- /* @__PURE__ */ jsx(HeaderCell, { hidden: true, children: t("adminPanel.table.actions", "Actions") })
3724
- ] }) }),
3725
- /* @__PURE__ */ jsx(Tbody, { children: rows.map((row) => /* @__PURE__ */ jsxs(
3726
- ClickableRow,
3727
- {
3728
- "data-event-row": row.action,
3729
- "data-event-id": row.id,
3730
- onClick: (event) => openDetails(row, event.currentTarget),
3731
- children: [
3732
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(EventTime, { value: row.at }) }),
3733
- /* @__PURE__ */ jsx(Td, { children: badge(row) }),
3734
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(ActivityEntry, { row }) }),
3735
- /* @__PURE__ */ jsx(WrapCell, { children: contentTypeText(row) ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: contentTypeText(row) }) : /* @__PURE__ */ jsx(MissingValue, { variant: "omega" }) }),
3736
- showAdmin ? /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(AdminName, { admin: row.admin }) }) : null,
3737
- /* @__PURE__ */ jsx(Td, { onClick: (event) => event.stopPropagation(), children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", gap: 1, onKeyDown: stopCellKeys, children: /* @__PURE__ */ jsx(
3738
- DetailsButton,
2563
+ ] }),
2564
+ showSessionData && stats.total === 0 && /* @__PURE__ */ jsx(
2565
+ EmptyStateLayout,
2566
+ {
2567
+ icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2568
+ content: t(
2569
+ "homepage.empty.description",
2570
+ "No sessions yet. Sessions appear here when users of your app sign in."
2571
+ )
2572
+ }
2573
+ ),
2574
+ /* @__PURE__ */ jsx(RecentUserActivity, {}),
2575
+ showDetailModal && selectedSession && /* @__PURE__ */ jsx(
2576
+ SessionDetailModal,
3739
2577
  {
3740
- label: detailsLabel(row),
3741
- onOpen: (trigger) => openDetails(row, trigger)
2578
+ session: selectedSession,
2579
+ now,
2580
+ onClose: handleModalClose,
2581
+ onCloseAutoFocus: handleCloseAutoFocus,
2582
+ onEndSession: handleTerminateSession
3742
2583
  }
3743
- ) }) })
2584
+ )
3744
2585
  ]
3745
- },
3746
- row.id
3747
- )) })
3748
- ] }) });
3749
- }
3750
- const content = selected ? activityDetails(t, formatDate, selected) : null;
3751
- return /* @__PURE__ */ jsxs(Box, { ref: measureRef, minWidth: 0, width: "100%", children: [
3752
- /* @__PURE__ */ jsx(Box, { ref: setContainer, tabIndex: -1, minWidth: 0, children: list }),
3753
- content ? /* @__PURE__ */ jsx(
3754
- EventDetailsModal,
3755
- {
3756
- title: content.title,
3757
- items: content.items,
3758
- onClose: closeDetails,
3759
- onCloseAutoFocus
3760
- }
3761
- ) : null
3762
- ] });
3763
- };
3764
- function useEventList({ path, params, logKey }) {
3765
- const { get } = useFetchClient();
3766
- const { formatMessage } = useIntl();
3767
- const fillNames = useCallback(
3768
- (list) => list.map(
3769
- (row) => withEventAdminNames(
3770
- row,
3771
- (id) => formatMessage(
3772
- {
3773
- id: getTranslation("adminPanel.identity.placeholder"),
3774
- defaultMessage: "Admin #{id}"
3775
- },
3776
- { id }
3777
- )
3778
- )
3779
- ),
3780
- [formatMessage]
3781
- );
3782
- const [rows, setRows] = useState([]);
3783
- const [meta, setMeta] = useState(null);
3784
- const [page, setPage] = useState(1);
3785
- const [loading, setLoading] = useState(true);
3786
- const [loadingMore, setLoadingMore] = useState(false);
3787
- const [error, setError] = useState(false);
3788
- const requestRef = useRef(0);
3789
- const key = JSON.stringify(params);
3790
- const firstPage = Number(params?.page) > 0 ? Number(params.page) : 1;
3791
- const load = useCallback(
3792
- async (nextPage) => {
3793
- const requestId = requestRef.current + 1;
3794
- requestRef.current = requestId;
3795
- if (nextPage === firstPage) setLoading(true);
3796
- else setLoadingMore(true);
3797
- try {
3798
- const response = await get(path, { params: { ...JSON.parse(key), page: nextPage } });
3799
- if (requestId !== requestRef.current) return;
3800
- const body = response?.data || {};
3801
- const data = fillNames(Array.isArray(body.data) ? body.data : []);
3802
- setRows((current) => nextPage === firstPage ? data : [...current, ...data]);
3803
- setMeta(body.meta || null);
3804
- setPage(nextPage);
3805
- setError(false);
3806
- } catch (err) {
3807
- if (requestId !== requestRef.current || isCancelledRequest(err)) return;
3808
- setError(true);
3809
- logSafeAdminError(logKey, err);
3810
- } finally {
3811
- if (requestId === requestRef.current) {
3812
- setLoading(false);
3813
- setLoadingMore(false);
3814
2586
  }
3815
- }
3816
- },
3817
- [get, path, key, logKey, fillNames, firstPage]
2587
+ )
2588
+ }
3818
2589
  );
3819
- useEffect(() => {
3820
- load(firstPage);
3821
- return () => {
3822
- requestRef.current += 1;
3823
- };
3824
- }, [load, firstPage]);
3825
- const pagination = meta?.pagination;
3826
- const hasMore = Boolean(pagination && page < pagination.pageCount);
3827
- const exportAll = useCallback(async () => {
3828
- const all = [];
3829
- let cursor = null;
3830
- do {
3831
- const response = await get(`${path}/export`, {
3832
- params: toExportParams(JSON.parse(key), cursor)
3833
- });
3834
- const body = response?.data || {};
3835
- if (!Array.isArray(body.data)) throw new Error("Invalid export response");
3836
- all.push(...fillNames(body.data));
3837
- cursor = typeof body.meta?.nextCursor === "string" ? body.meta.nextCursor : null;
3838
- } while (cursor && all.length < MAX_EVENT_EXPORT_ROWS);
3839
- return {
3840
- rows: all.slice(0, MAX_EVENT_EXPORT_ROWS),
3841
- capped: all.length > MAX_EVENT_EXPORT_ROWS || Boolean(cursor)
3842
- };
3843
- }, [get, path, key, fillNames]);
3844
- return {
3845
- rows,
3846
- meta,
3847
- loading,
3848
- loadingMore,
3849
- error,
3850
- hasMore,
3851
- loadMore: () => load(page + 1),
3852
- reload: () => load(firstPage),
3853
- exportAll
3854
- };
3855
- }
3856
- function downloadCsv(content, name) {
3857
- const blob = new Blob([content], { type: "text/csv;charset=utf-8;" });
3858
- const url = URL.createObjectURL(blob);
3859
- const link = document.createElement("a");
3860
- link.href = url;
3861
- link.download = `${name}-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.csv`;
3862
- link.click();
3863
- window.setTimeout(() => URL.revokeObjectURL(url), 0);
3864
- }
3865
- const ADMIN_ACTIVITY_SETTINGS_PATH = `/settings/${pluginId}/general?tab=admin-activity`;
3866
- const ADMIN_ACTIVITY_PAGE_PATH = `/plugins/${pluginId}/admin-panel/activity`;
2590
+ };
2591
+ const HIGHLIGHT_BADGE = { backgroundColor: "primary100", textColor: "neutral800" };
2592
+ const offersPreview = (admin, canPreview) => Boolean(canPreview) && admin.self !== true && !(admin.roles || []).some((role) => role?.superAdmin === true);
2593
+ const keepActionKeys = (event) => {
2594
+ if (shouldIsolateActionKey(event.key, true)) event.stopPropagation();
2595
+ };
2596
+ const SHRINKING_ADMIN_CELL = { maxWidth: 0, width: "34%" };
2597
+ const SHRINKING_ROLES_CELL = { maxWidth: 0, width: "22%" };
3867
2598
  const useT$2 = () => {
3868
2599
  const { formatMessage } = useIntl();
3869
2600
  return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
3870
2601
  };
3871
- const PeriodSelect = ({ value, onChange }) => {
3872
- const t = useT$2();
3873
- const labels = {
3874
- 1: t("adminPanel.activity.period.day", "Last 24 hours"),
3875
- 7: t("adminPanel.activity.period.week", "Last 7 days"),
3876
- 30: t("adminPanel.activity.period.month", "Last 30 days"),
3877
- 90: t("adminPanel.activity.period.quarter", "Last 90 days"),
3878
- all: t("adminPanel.activity.period.all", "All kept events")
3879
- };
3880
- return /* @__PURE__ */ jsx(
3881
- SingleSelect,
3882
- {
3883
- size: "S",
3884
- "aria-label": t("adminPanel.activity.period.label", "Period"),
3885
- value,
3886
- onChange: (next) => onChange(String(next)),
3887
- children: PERIOD_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
3888
- }
3889
- );
3890
- };
3891
- const FilterSlot = ({ children }) => /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", minWidth: 0, flex: "1 1 18rem", children });
3892
- const EmptyText = ({ children }) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", "data-event-empty": "", children });
3893
- const EventList = ({
3894
- filters,
3895
- notice,
3896
- list,
3897
- empty,
3898
- renderList,
3899
- toCsv: toCsv2,
3900
- fileName,
3901
- exportLabel,
3902
- footer
3903
- }) => {
2602
+ const AdminIdentity = ({ admin }) => {
3904
2603
  const t = useT$2();
3905
- const { toggleNotification } = useNotification();
3906
- const [exporting, setExporting] = useState(false);
3907
- const total = list.meta?.pagination?.total ?? 0;
3908
- const handleExport = async () => {
3909
- if (exporting) return;
3910
- setExporting(true);
3911
- try {
3912
- const { rows, capped } = await list.exportAll();
3913
- downloadCsv(toCsv2(rows), fileName);
3914
- if (capped) {
3915
- toggleNotification({
3916
- type: "warning",
3917
- message: t(
3918
- "adminPanel.activity.export.capped",
3919
- "The export contains the newest {limit, number} events. Narrow the filter to export the rest.",
3920
- { limit: MAX_EVENT_EXPORT_ROWS }
3921
- )
3922
- });
3923
- }
3924
- } catch (err) {
3925
- if (isCancelledRequest(err)) return;
3926
- logSafeAdminError("adminPanel.activity.export", err);
3927
- toggleNotification({
3928
- type: "danger",
3929
- message: t("adminPanel.activity.export.error", "The export could not be created.")
3930
- });
3931
- } finally {
3932
- setExporting(false);
3933
- }
3934
- };
3935
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
3936
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", justifyContent: "space-between", children: [
3937
- /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", alignItems: "center", flex: "1 1 auto", minWidth: 0, children: filters }),
2604
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, children: [
2605
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", minWidth: 0, children: [
3938
2606
  /* @__PURE__ */ jsx(
3939
- Button,
3940
- {
3941
- size: "S",
3942
- variant: "tertiary",
3943
- startIcon: /* @__PURE__ */ jsx(Download, {}),
3944
- onClick: handleExport,
3945
- loading: exporting,
3946
- disabled: list.loading || total === 0,
3947
- "aria-label": exportLabel,
3948
- children: t("adminPanel.activity.export.csv", "Export CSV")
3949
- }
3950
- )
3951
- ] }),
3952
- notice,
3953
- list.loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 4, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
3954
- !list.loading && list.error ? /* @__PURE__ */ jsx(
3955
- PersistentAlert,
3956
- {
3957
- variant: "danger",
3958
- action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
3959
- children: t("adminPanel.activity.error", "The events could not be loaded.")
3960
- }
3961
- ) : null,
3962
- !list.loading && !list.error && list.rows.length === 0 ? empty : null,
3963
- list.rows.length > 0 ? renderList(list.rows) : null,
3964
- footer !== void 0 ? list.rows.length > 0 ? footer : null : list.hasMore ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", children: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: list.loadMore, loading: list.loadingMore, children: t("adminPanel.activity.showMore", "Show more") }) }) : null
3965
- ] });
3966
- };
3967
- const RecordingOff = ({ children }) => {
3968
- const t = useT$2();
3969
- return /* @__PURE__ */ jsx(
3970
- PersistentAlert,
3971
- {
3972
- variant: "neutral",
3973
- action: /* @__PURE__ */ jsx(Link, { tag: Link$1, to: ADMIN_ACTIVITY_SETTINGS_PATH, children: t("adminPanel.activity.openSettings", "Open settings") }),
3974
- children
3975
- }
3976
- );
3977
- };
3978
- const SignInHistoryPanel = ({ admin }) => {
3979
- const t = useT$2();
3980
- const [event, setEvent] = useState("all");
3981
- const [period, setPeriod] = useState("30");
3982
- const params = useMemo(
3983
- () => buildSignInParams({ adminId: admin.id, event, period }),
3984
- [admin.id, event, period]
3985
- );
3986
- const list = useEventList({
3987
- path: `/${pluginId}/admin-activity/sign-ins`,
3988
- params,
3989
- logKey: "adminPanel.activity.signIns"
3990
- });
3991
- const recording = list.meta?.recording;
3992
- const labels = {
3993
- all: t("adminPanel.activity.filter.allEvents", "All events"),
3994
- succeeded: t("adminPanel.activity.filter.succeeded", "Sign-ins"),
3995
- failed: t("adminPanel.activity.filter.failed", "Failed and locked out"),
3996
- "signed-out": t("adminPanel.activity.filter.signedOut", "Sign-outs")
3997
- };
3998
- return /* @__PURE__ */ jsx(
3999
- EventList,
4000
- {
4001
- list,
4002
- filters: /* @__PURE__ */ jsxs(Fragment, { children: [
4003
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4004
- SingleSelect,
4005
- {
4006
- size: "S",
4007
- "aria-label": t("adminPanel.activity.filter.event", "Event"),
4008
- value: event,
4009
- onChange: (next) => setEvent(String(next)),
4010
- children: SIGN_IN_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
4011
- }
4012
- ) }),
4013
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
4014
- ] }),
4015
- notice: recording && !recording.signIns ? /* @__PURE__ */ jsx(RecordingOff, { children: t(
4016
- "adminPanel.activity.signIns.off",
4017
- "Sign-in history is turned off. New sign-ins are not recorded."
4018
- ) }) : null,
4019
- empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.signIns.empty", "No sign-in events in this period.") }),
4020
- renderList: (rows) => /* @__PURE__ */ jsx(
4021
- SignInEventTable,
4022
- {
4023
- rows,
4024
- busy: list.loading,
4025
- label: t("adminPanel.activity.signIns.listLabel", "Sign-in history of {name}", {
4026
- name: admin.name
4027
- })
4028
- }
4029
- ),
4030
- toCsv: buildSignInCsv,
4031
- fileName: "admin-sign-in-history",
4032
- exportLabel: t(
4033
- "adminPanel.activity.signIns.export",
4034
- "Export the sign-in history of {name} as CSV",
2607
+ Typography,
4035
2608
  {
4036
- name: admin.name
2609
+ variant: "omega",
2610
+ fontWeight: "semiBold",
2611
+ textColor: "neutral800",
2612
+ ellipsis: true,
2613
+ title: admin.name,
2614
+ children: admin.name
4037
2615
  }
4038
- )
4039
- }
4040
- );
2616
+ ),
2617
+ admin.self ? /* @__PURE__ */ jsx(Badge, { ...HIGHLIGHT_BADGE, shrink: 0, children: t("adminPanel.you", "You") }) : null
2618
+ ] }),
2619
+ admin.identityHidden ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("adminPanel.identity.emailHidden", "Email hidden (needs “Read” on Users)") }) : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", ellipsis: true, title: admin.email, children: admin.email })
2620
+ ] });
4041
2621
  };
4042
- const ContentActivityPanel = ({ admin }) => {
2622
+ const AdminRoles = ({ admin }) => {
4043
2623
  const t = useT$2();
4044
- const [action, setAction] = useState("all");
4045
- const [contentType, setContentType] = useState("all");
4046
- const [period, setPeriod] = useState("30");
4047
- const params = useMemo(
4048
- () => buildActivityParams({ adminId: admin.id, action, contentType, period }),
4049
- [admin.id, action, contentType, period]
4050
- );
4051
- const list = useEventList({
4052
- path: `/${pluginId}/admin-activity/content`,
4053
- params,
4054
- logKey: "adminPanel.activity.content"
4055
- });
4056
- const recording = list.meta?.recording;
4057
- const types = Array.isArray(list.meta?.contentTypes) ? list.meta.contentTypes : [];
4058
- const noAccess = list.meta?.contentManagerAccess === false;
4059
- let notice = null;
4060
- if (recording && !recording.contentActivity) {
4061
- notice = /* @__PURE__ */ jsx(RecordingOff, { children: t(
4062
- "adminPanel.activity.content.off",
4063
- "Content Manager activity is not recorded. An admin can turn it on in the settings; inform your team first."
4064
- ) });
4065
- } else if (noAccess) {
4066
- notice = /* @__PURE__ */ jsx(PersistentAlert, { variant: "neutral", children: t(
4067
- "adminPanel.activity.content.noAccess",
4068
- "{name} has no Content Manager access, so there is no activity to show.",
4069
- { name: admin.name }
4070
- ) });
4071
- }
4072
- return /* @__PURE__ */ jsx(
4073
- EventList,
2624
+ const names = (admin.roles || []).map((role) => role.name).filter(Boolean);
2625
+ const text = admin.rolesHidden ? t("adminPanel.roles.hidden", "Hidden (needs “Read” on Roles)") : names.length ? names.join(", ") : t("adminPanel.roles.none", "No role");
2626
+ return /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", ellipsis: true, title: text, children: text });
2627
+ };
2628
+ const AdminStatus = ({ admin }) => {
2629
+ const t = useT$2();
2630
+ const status = getAdminStatusPresentation(admin);
2631
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-admin-status": status.key, children: [
2632
+ /* @__PURE__ */ jsx(Badge, { ...getBadgeColors(status.tone), children: t(status.label.messageId, status.label.defaultMessage) }),
2633
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(status.detail.messageId, status.detail.defaultMessage, status.detail.values) })
2634
+ ] });
2635
+ };
2636
+ const AdminTable = ({
2637
+ admins,
2638
+ labelledBy,
2639
+ canRevoke,
2640
+ onView,
2641
+ onSignOutEverywhere,
2642
+ canPreview,
2643
+ onPreview,
2644
+ busy
2645
+ }) => {
2646
+ const t = useT$2();
2647
+ return /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-admin-table": "", children: /* @__PURE__ */ jsxs(
2648
+ Table,
4074
2649
  {
4075
- list,
4076
- filters: /* @__PURE__ */ jsxs(Fragment, { children: [
4077
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4078
- SingleSelect,
4079
- {
4080
- size: "S",
4081
- "aria-label": t("adminPanel.activity.filter.action", "Action"),
4082
- value: action,
4083
- onChange: (next) => setAction(String(next)),
4084
- children: ACTIVITY_ACTION_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: t(
4085
- ACTIVITY_ACTION_LABELS[option].messageId,
4086
- ACTIVITY_ACTION_LABELS[option].defaultMessage
4087
- ) }, option))
4088
- }
4089
- ) }),
4090
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsxs(
4091
- SingleSelect,
4092
- {
4093
- size: "S",
4094
- "aria-label": t("adminPanel.activity.filter.contentType", "Content type"),
4095
- value: contentType,
4096
- onChange: (next) => setContentType(String(next)),
4097
- children: [
4098
- /* @__PURE__ */ jsx(SingleSelectOption, { value: "all", children: t("adminPanel.activity.filter.allTypes", "All content types") }),
4099
- types.map((type) => /* @__PURE__ */ jsx(SingleSelectOption, { value: type.uid, children: type.name }, type.uid))
4100
- ]
4101
- }
4102
- ) }),
4103
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
4104
- ] }),
4105
- notice,
4106
- empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.content.empty", "No Content Manager activity in this period.") }),
4107
- renderList: (rows) => /* @__PURE__ */ jsx(
4108
- ActivityEventTable,
4109
- {
4110
- rows,
4111
- busy: list.loading,
4112
- label: t("adminPanel.activity.content.listLabel", "Content Manager activity of {name}", {
4113
- name: admin.name
4114
- })
4115
- }
4116
- ),
4117
- toCsv: buildActivityCsv,
4118
- fileName: "admin-content-activity",
4119
- exportLabel: t(
4120
- "adminPanel.activity.content.export",
4121
- "Export the Content Manager activity of {name} as CSV",
4122
- { name: admin.name }
4123
- )
2650
+ colCount: 5,
2651
+ rowCount: admins.length + 1,
2652
+ "aria-labelledby": labelledBy,
2653
+ "aria-busy": busy,
2654
+ children: [
2655
+ /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
2656
+ /* @__PURE__ */ jsx(Th, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.admin", "Admin") }) }),
2657
+ /* @__PURE__ */ jsx(Th, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.roles", "Roles") }) }),
2658
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.status", "Status") }) }),
2659
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }) }),
2660
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("adminPanel.table.actions", "Actions") }) })
2661
+ ] }) }),
2662
+ /* @__PURE__ */ jsx(Tbody, { children: admins.map((admin) => /* @__PURE__ */ jsxs(Tr, { "data-admin-row": admin.id, children: [
2663
+ /* @__PURE__ */ jsx(Td, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(AdminIdentity, { admin }) }),
2664
+ /* @__PURE__ */ jsx(Td, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(AdminRoles, { admin }) }),
2665
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(AdminStatus, { admin }) }),
2666
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt }) }),
2667
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsxs(RowActions, { onKeyDown: keepActionKeys, children: [
2668
+ /* @__PURE__ */ jsx(
2669
+ IconButton,
2670
+ {
2671
+ label: t("adminPanel.actions.view", "View sessions of {name}", {
2672
+ name: admin.name
2673
+ }),
2674
+ onClick: (event) => onView(admin, event.currentTarget),
2675
+ children: /* @__PURE__ */ jsx(Eye, {})
2676
+ }
2677
+ ),
2678
+ offersPreview(admin, canPreview) ? /* @__PURE__ */ jsx(
2679
+ IconButton,
2680
+ {
2681
+ label: t("adminPanel.actions.viewAs", "View as {name}", {
2682
+ name: admin.name || `#${admin.id}`
2683
+ }),
2684
+ onClick: (event) => onPreview?.(admin, event.currentTarget),
2685
+ children: /* @__PURE__ */ jsx(User, {})
2686
+ }
2687
+ ) : null,
2688
+ canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2689
+ IconButton,
2690
+ {
2691
+ variant: "danger-light",
2692
+ label: t(
2693
+ "adminPanel.actions.signOutEverywhere",
2694
+ "Sign out {name} everywhere",
2695
+ {
2696
+ name: admin.name
2697
+ }
2698
+ ),
2699
+ onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2700
+ children: /* @__PURE__ */ jsx(SignOut, {})
2701
+ }
2702
+ ) : null
2703
+ ] }) })
2704
+ ] }, admin.id)) })
2705
+ ]
4124
2706
  }
4125
- );
2707
+ ) });
4126
2708
  };
4127
- const RecentSignInActivity = ({ onOpenAdmin }) => {
2709
+ const AdminCardList = ({
2710
+ admins,
2711
+ labelledBy,
2712
+ canRevoke,
2713
+ onView,
2714
+ onSignOutEverywhere,
2715
+ canPreview,
2716
+ onPreview
2717
+ }) => {
4128
2718
  const t = useT$2();
4129
- const headingId = `recent-sign-in-activity-${useId().replace(/:/g, "")}`;
4130
- const params = useMemo(() => buildSignInParams({ pageSize: RECENT_EVENT_LIMIT }), []);
4131
- const list = useEventList({
4132
- path: `/${pluginId}/admin-activity/sign-ins`,
4133
- params,
4134
- logKey: "adminPanel.activity.recent"
4135
- });
4136
- if (list.meta?.recording && !list.meta.recording.signIns) return null;
4137
- const title = t("adminPanel.activity.recent.title", "Recent security activity");
4138
- return /* @__PURE__ */ jsxs(
2719
+ return /* @__PURE__ */ jsx(
4139
2720
  Flex,
4140
2721
  {
4141
- tag: "section",
4142
- "aria-labelledby": headingId,
2722
+ tag: "ul",
4143
2723
  direction: "column",
4144
2724
  alignItems: "stretch",
4145
- gap: 4,
4146
- minWidth: 0,
4147
- "data-recent-activity": "",
4148
- children: [
4149
- /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "flex-end", gap: 4, wrap: "wrap", children: [
4150
- /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, flex: "1 1 32rem", children: [
4151
- /* @__PURE__ */ jsx(Typography, { id: headingId, variant: "delta", tag: "h2", textColor: "neutral800", children: title }),
4152
- /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(
4153
- "adminPanel.activity.recent.subtitle",
4154
- "The latest sign-ins, failed attempts, sign-outs and settings changes of all admins. Select an event for its details."
4155
- ) })
4156
- ] }),
4157
- /* @__PURE__ */ jsx(
4158
- LinkButton,
4159
- {
4160
- tag: Link$1,
4161
- to: ADMIN_ACTIVITY_PAGE_PATH,
4162
- variant: "tertiary",
4163
- endIcon: /* @__PURE__ */ jsx(ArrowRight, {}),
4164
- "data-show-all-activity": "",
4165
- children: t("adminPanel.activity.recent.showAll", "Show all")
4166
- }
4167
- )
4168
- ] }),
4169
- list.loading && list.rows.length === 0 ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 2, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
4170
- !list.loading && list.error ? /* @__PURE__ */ jsx(
4171
- PersistentAlert,
4172
- {
4173
- variant: "danger",
4174
- action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
4175
- children: t("adminPanel.activity.error", "The events could not be loaded.")
4176
- }
4177
- ) : null,
4178
- !list.loading && !list.error && list.rows.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", children: t("adminPanel.activity.recent.empty", "No events recorded yet.") }) : null,
4179
- list.rows.length > 0 ? /* @__PURE__ */ jsx(
4180
- SignInEventTable,
4181
- {
4182
- rows: list.rows,
4183
- label: title,
4184
- showAdmin: true,
4185
- onOpenAdmin,
4186
- busy: list.loading
4187
- }
4188
- ) : null
4189
- ]
2725
+ gap: 3,
2726
+ "aria-labelledby": labelledBy,
2727
+ "data-admin-cards": "",
2728
+ children: admins.map((admin) => /* @__PURE__ */ jsx(
2729
+ Box,
2730
+ {
2731
+ tag: "li",
2732
+ background: "neutral0",
2733
+ hasRadius: true,
2734
+ shadow: "tableShadow",
2735
+ padding: 4,
2736
+ "data-admin-row": admin.id,
2737
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 3, minWidth: 0, children: [
2738
+ /* @__PURE__ */ jsx(AdminIdentity, { admin }),
2739
+ /* @__PURE__ */ jsxs(Flex, { gap: 4, wrap: "wrap", alignItems: "flex-start", justifyContent: "space-between", children: [
2740
+ /* @__PURE__ */ jsx(AdminStatus, { admin }),
2741
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
2742
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }),
2743
+ /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt })
2744
+ ] })
2745
+ ] }),
2746
+ /* @__PURE__ */ jsx(AdminRoles, { admin }),
2747
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
2748
+ /* @__PURE__ */ jsx(
2749
+ Button,
2750
+ {
2751
+ variant: "secondary",
2752
+ startIcon: /* @__PURE__ */ jsx(Eye, {}),
2753
+ onClick: (event) => onView(admin, event.currentTarget),
2754
+ "aria-label": t("adminPanel.actions.view", "View sessions of {name}", {
2755
+ name: admin.name
2756
+ }),
2757
+ flex: "1 1 auto",
2758
+ children: t("adminPanel.actions.viewShort", "View sessions")
2759
+ }
2760
+ ),
2761
+ offersPreview(admin, canPreview) ? /* @__PURE__ */ jsx(
2762
+ Button,
2763
+ {
2764
+ variant: "secondary",
2765
+ startIcon: /* @__PURE__ */ jsx(User, {}),
2766
+ onClick: (event) => onPreview?.(admin, event.currentTarget),
2767
+ "aria-label": t("adminPanel.actions.viewAs", "View as {name}", {
2768
+ name: admin.name || `#${admin.id}`
2769
+ }),
2770
+ flex: "1 1 auto",
2771
+ children: t("adminPanel.actions.viewAsShort", "View as")
2772
+ }
2773
+ ) : null,
2774
+ canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2775
+ Button,
2776
+ {
2777
+ variant: "danger-light",
2778
+ startIcon: /* @__PURE__ */ jsx(SignOut, {}),
2779
+ onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2780
+ "aria-label": t(
2781
+ "adminPanel.actions.signOutEverywhere",
2782
+ "Sign out {name} everywhere",
2783
+ {
2784
+ name: admin.name
2785
+ }
2786
+ ),
2787
+ flex: "1 1 auto",
2788
+ children: t("adminPanel.actions.signOutEverywhereShort", "Sign out everywhere")
2789
+ }
2790
+ ) : null
2791
+ ] })
2792
+ ] })
2793
+ },
2794
+ admin.id
2795
+ ))
4190
2796
  }
4191
2797
  );
4192
2798
  };
@@ -4402,8 +3008,278 @@ const AdminSessionsModal = ({
4402
3008
  ] }) })
4403
3009
  ] }) });
4404
3010
  };
3011
+ const ADMIN_PREVIEW_DURATIONS = Object.freeze([15, 30]);
3012
+ const REFUSALS = Object.freeze({
3013
+ disabled: ["impersonation.error.disabled", "Impersonation is turned off in the settings."],
3014
+ self: ["impersonation.preview.error.self", "You cannot view yourself as another admin."],
3015
+ "super-admin": [
3016
+ "impersonation.preview.error.superAdmin",
3017
+ "Super Admins cannot be viewed as another admin."
3018
+ ],
3019
+ "not-subset": [
3020
+ "impersonation.preview.error.notSubset",
3021
+ "This admin has permissions that you do not have, so you cannot view as them."
3022
+ ],
3023
+ "api-token": ["impersonation.error.apiToken", "API tokens cannot impersonate."]
3024
+ });
3025
+ const ACTION_LABELS = Object.freeze({
3026
+ create: ["impersonation.preview.action.create", "Create"],
3027
+ read: ["impersonation.preview.action.read", "Read"],
3028
+ update: ["impersonation.preview.action.update", "Update"],
3029
+ delete: ["impersonation.preview.action.delete", "Delete"],
3030
+ publish: ["impersonation.preview.action.publish", "Publish"]
3031
+ });
3032
+ const CONDITION_LABELS = Object.freeze({
3033
+ "admin::is-creator": ["impersonation.preview.condition.creator", "entries they created"],
3034
+ "admin::has-same-role-as-creator": [
3035
+ "impersonation.preview.condition.sameRole",
3036
+ "entries created by someone with the same role"
3037
+ ]
3038
+ });
3039
+ const ContentTypeRow = ({ type }) => {
3040
+ const { t } = useSettingsTranslate();
3041
+ return /* @__PURE__ */ jsx(Box, { tag: "li", padding: 3, hasRadius: true, borderColor: "neutral150", "data-preview-type": type.uid, children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
3042
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: type.name }),
3043
+ /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", children: type.actions.map((action) => {
3044
+ const label = ACTION_LABELS[action.action] ? t(...ACTION_LABELS[action.action]) : action.action;
3045
+ const restricted = action.fields !== null || action.locales !== null || action.conditions.length > 0;
3046
+ return /* @__PURE__ */ jsx(
3047
+ Badge,
3048
+ {
3049
+ backgroundColor: restricted ? "warning100" : "success100",
3050
+ textColor: "neutral800",
3051
+ children: restricted ? t("impersonation.preview.restricted", "{action} (restricted)", {
3052
+ action: label
3053
+ }) : label
3054
+ },
3055
+ action.action
3056
+ );
3057
+ }) }),
3058
+ type.actions.filter((action) => action.fields !== null || action.conditions.length > 0).map((action) => {
3059
+ const label = ACTION_LABELS[action.action] ? t(...ACTION_LABELS[action.action]) : action.action;
3060
+ return /* @__PURE__ */ jsxs(Typography, { variant: "pi", textColor: "neutral600", tag: "p", children: [
3061
+ action.fields !== null ? t(
3062
+ "impersonation.preview.fields",
3063
+ "{action}: {count, plural, one {# field} other {# fields}}",
3064
+ { action: label, count: action.fields }
3065
+ ) : null,
3066
+ action.fields !== null && action.conditions.length ? " " : null,
3067
+ action.conditions.length ? t("impersonation.preview.conditions", "{action}: only {conditions}", {
3068
+ action: label,
3069
+ conditions: action.conditions.map((id) => CONDITION_LABELS[id] ? t(...CONDITION_LABELS[id]) : id).join(", ")
3070
+ }) : null
3071
+ ] }, action.action);
3072
+ })
3073
+ ] }) });
3074
+ };
3075
+ const PreviewAdminModal = ({ admin, onClose, onCloseAutoFocus, onChanged }) => {
3076
+ const { t, tError } = useSettingsTranslate();
3077
+ const { post } = useFetchClient();
3078
+ const { toggleNotification } = useNotification();
3079
+ const [reason, setReason] = useState("");
3080
+ const [minutes, setMinutes] = useState(15);
3081
+ const [touched, setTouched] = useState(false);
3082
+ const [pending, setPending] = useState(null);
3083
+ const [failure, setFailure] = useState(null);
3084
+ const [result, setResult] = useState(null);
3085
+ const secondsLeft = useSecondsLeft(result?.impersonation?.expiresAt || null);
3086
+ const ended = Boolean(result) && secondsLeft <= 0;
3087
+ const reasonError = validateReason(reason);
3088
+ const name = result?.preview?.admin?.name || admin.name;
3089
+ const start = async () => {
3090
+ setTouched(true);
3091
+ if (reasonError) return;
3092
+ setPending("start");
3093
+ setFailure(null);
3094
+ try {
3095
+ const { data } = await post(`/${pluginId}/impersonation/admins/${admin.id}/preview`, {
3096
+ reason: reason.trim(),
3097
+ durationMinutes: minutes
3098
+ });
3099
+ setResult(data?.data || null);
3100
+ onChanged?.();
3101
+ } catch (err) {
3102
+ if (isCancelledRequest(err)) return;
3103
+ const response = err?.response;
3104
+ const code = response?.data?.error?.details?.reason;
3105
+ if (response?.status === 429) {
3106
+ setFailure(
3107
+ t(
3108
+ "impersonation.error.rateLimited",
3109
+ "Too many impersonations were started. Try again in a few minutes."
3110
+ )
3111
+ );
3112
+ } else if (REFUSALS[code]) {
3113
+ setFailure(t(...REFUSALS[code]));
3114
+ } else {
3115
+ logSafeAdminError("impersonation.preview", err);
3116
+ setFailure(t("impersonation.preview.error.start", "The preview could not be opened."));
3117
+ }
3118
+ } finally {
3119
+ setPending(null);
3120
+ }
3121
+ };
3122
+ const end = async () => {
3123
+ if (!result?.impersonation?.id) return;
3124
+ setPending("end");
3125
+ try {
3126
+ await post(`/${pluginId}/impersonation/${result.impersonation.id}/end`, {});
3127
+ toggleNotification({
3128
+ type: "success",
3129
+ message: t("impersonation.preview.ended", "Preview ended.")
3130
+ });
3131
+ onChanged?.();
3132
+ onClose();
3133
+ } catch (err) {
3134
+ logSafeAdminError("impersonation.end", err);
3135
+ toggleNotification({
3136
+ type: "danger",
3137
+ message: t("impersonation.error.end", "The impersonation could not be ended.")
3138
+ });
3139
+ } finally {
3140
+ setPending(null);
3141
+ }
3142
+ };
3143
+ const preview = result?.preview;
3144
+ const close = () => {
3145
+ if (result?.impersonation?.id && !ended) {
3146
+ post(`/${pluginId}/impersonation/${result.impersonation.id}/end`, {}).then(() => onChanged?.()).catch((err) => logSafeAdminError("impersonation.end", err));
3147
+ }
3148
+ onClose();
3149
+ };
3150
+ return /* @__PURE__ */ jsx(Modal.Root, { open: true, onOpenChange: (open) => open ? null : close(), children: /* @__PURE__ */ jsxs(Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
3151
+ /* @__PURE__ */ jsx(Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsx(Modal.Title, { children: t("impersonation.preview.title", "View as {name}", { name: name || `#${admin.id}` }) }) }),
3152
+ /* @__PURE__ */ jsx(Modal.Body, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
3153
+ failure ? /* @__PURE__ */ jsx(PersistentAlert, { variant: "danger", closeLabel: t("common.close", "Close"), children: failure }) : null,
3154
+ !result ? /* @__PURE__ */ jsxs(Fragment, { children: [
3155
+ /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
3156
+ "impersonation.preview.intro",
3157
+ "See which content types and actions this admin can use, worked out from their roles. Read-only: nobody is signed in and nothing can be changed. It is recorded in the security log."
3158
+ ) }),
3159
+ /* @__PURE__ */ jsxs(
3160
+ Field.Root,
3161
+ {
3162
+ name: "reason",
3163
+ required: true,
3164
+ error: touched && reasonError ? tError(reasonError) : void 0,
3165
+ hint: t("impersonation.preview.reason.hint", "Stored in the security log."),
3166
+ children: [
3167
+ /* @__PURE__ */ jsx(Field.Label, { children: t("impersonation.reason.label", "Reason") }),
3168
+ /* @__PURE__ */ jsx(
3169
+ Textarea,
3170
+ {
3171
+ value: reason,
3172
+ maxLength: REASON_MAX,
3173
+ placeholder: t("impersonation.reason.placeholder", "For example: ticket 4711"),
3174
+ onChange: (event) => setReason(event.target.value),
3175
+ onBlur: () => setTouched(true)
3176
+ }
3177
+ ),
3178
+ /* @__PURE__ */ jsx(Field.Hint, {}),
3179
+ /* @__PURE__ */ jsx(Field.Error, {})
3180
+ ]
3181
+ }
3182
+ ),
3183
+ /* @__PURE__ */ jsxs(Field.Root, { name: "durationMinutes", children: [
3184
+ /* @__PURE__ */ jsx(Field.Label, { children: t("impersonation.duration.label", "Duration") }),
3185
+ /* @__PURE__ */ jsx(
3186
+ SingleSelect,
3187
+ {
3188
+ value: String(minutes),
3189
+ onChange: (value) => setMinutes(Number(value)),
3190
+ children: ADMIN_PREVIEW_DURATIONS.map((value) => /* @__PURE__ */ jsx(SingleSelectOption, { value: String(value), children: t(
3191
+ "impersonation.duration.minutes",
3192
+ "{count, plural, one {# minute} other {# minutes}}",
3193
+ { count: value }
3194
+ ) }, value))
3195
+ }
3196
+ )
3197
+ ] })
3198
+ ] }) : null,
3199
+ result ? /* @__PURE__ */ jsx(
3200
+ Box,
3201
+ {
3202
+ padding: 3,
3203
+ hasRadius: true,
3204
+ background: ended ? "neutral150" : "primary100",
3205
+ borderColor: ended ? "neutral200" : "primary200",
3206
+ "data-preview-banner": "",
3207
+ children: /* @__PURE__ */ jsxs(Flex, { gap: 3, wrap: "wrap", justifyContent: "space-between", alignItems: "center", children: [
3208
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", "aria-live": "polite", children: ended ? t("impersonation.preview.banner.ended", "The preview ended.") : t(
3209
+ "impersonation.preview.banner",
3210
+ "You are viewing as {name} · read-only · ends in {time}",
3211
+ { name: name || `#${admin.id}`, time: formatClock(secondsLeft) }
3212
+ ) }),
3213
+ !ended ? /* @__PURE__ */ jsx(
3214
+ Button,
3215
+ {
3216
+ size: "S",
3217
+ variant: "danger-light",
3218
+ onClick: end,
3219
+ loading: pending === "end",
3220
+ children: t("impersonation.preview.end", "End")
3221
+ }
3222
+ ) : null
3223
+ ] })
3224
+ }
3225
+ ) : null,
3226
+ preview && !ended ? /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, "data-preview-body": "", children: [
3227
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", tag: "p", children: t("impersonation.preview.roles", "Roles: {roles}", {
3228
+ roles: preview.admin.roles.map((role) => role.name).join(", ") || "—"
3229
+ }) }),
3230
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
3231
+ /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h3", textColor: "neutral800", children: t("impersonation.preview.contentTypes", "Content types") }),
3232
+ preview.contentTypes.length ? /* @__PURE__ */ jsx(
3233
+ Flex,
3234
+ {
3235
+ tag: "ul",
3236
+ direction: "column",
3237
+ alignItems: "stretch",
3238
+ gap: 2,
3239
+ margin: 0,
3240
+ padding: 0,
3241
+ style: { listStyle: "none" },
3242
+ children: preview.contentTypes.map((type) => /* @__PURE__ */ jsx(ContentTypeRow, { type }, type.uid))
3243
+ }
3244
+ ) : /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
3245
+ "impersonation.preview.noContentTypes",
3246
+ "This admin cannot open any content type in the Content Manager."
3247
+ ) })
3248
+ ] }),
3249
+ preview.otherPermissions.length ? /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
3250
+ /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h3", textColor: "neutral800", children: t("impersonation.preview.other", "Other permissions") }),
3251
+ /* @__PURE__ */ jsx(
3252
+ Flex,
3253
+ {
3254
+ tag: "ul",
3255
+ direction: "column",
3256
+ alignItems: "stretch",
3257
+ gap: 1,
3258
+ margin: 0,
3259
+ paddingLeft: 5,
3260
+ children: preview.otherPermissions.map((permission) => /* @__PURE__ */ jsx(
3261
+ Typography,
3262
+ {
3263
+ tag: "li",
3264
+ variant: "pi",
3265
+ textColor: "neutral800",
3266
+ children: permission.name
3267
+ },
3268
+ permission.action
3269
+ ))
3270
+ }
3271
+ )
3272
+ ] }) : null
3273
+ ] }) : null
3274
+ ] }) }),
3275
+ /* @__PURE__ */ jsx(Modal.Footer, { children: result ? /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: ended ? t("impersonation.result.done", "Done") : t("impersonation.preview.close", "End and close") }) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
3276
+ /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: t("common.cancel", "Cancel") }) }),
3277
+ /* @__PURE__ */ jsx(Button, { onClick: start, loading: pending === "start", children: t("impersonation.preview.start", "View permissions") })
3278
+ ] }) })
3279
+ ] }) });
3280
+ };
4405
3281
  const SETTINGS_USERS_PATH = "/settings/users";
4406
- const PaginationTargets$1 = styled.div`
3282
+ const PaginationTargets$2 = styled.div`
4407
3283
  nav a {
4408
3284
  min-width: 3.2rem;
4409
3285
  }
@@ -4432,6 +3308,11 @@ const AdminPanelPage = () => {
4432
3308
  const {
4433
3309
  allowedActions: { canRead: canViewActivity }
4434
3310
  } = useRBAC(pluginPermissions.adminActivityRead);
3311
+ const {
3312
+ allowedActions: { canAdmins: canPreviewAdmins }
3313
+ } = useRBAC(pluginPermissions.impersonateAdmins);
3314
+ const [impersonationEnabled, setImpersonationEnabled] = useState(false);
3315
+ const [previewTarget, setPreviewTarget] = useState(null);
4435
3316
  const [admins, setAdmins] = useState([]);
4436
3317
  const [meta, setMeta] = useState(null);
4437
3318
  const [loading, setLoading] = useState(true);
@@ -4447,6 +3328,18 @@ const AdminPanelPage = () => {
4447
3328
  const dialogRequestRef = useRef(0);
4448
3329
  const hasLoadedRef = useRef(false);
4449
3330
  const openerRef = useRef(null);
3331
+ useEffect(() => {
3332
+ if (!canPreviewAdmins) return void 0;
3333
+ let current = true;
3334
+ get(`/${pluginId}/impersonation/status`).then(({ data }) => {
3335
+ if (current) setImpersonationEnabled(data?.data?.enabled === true);
3336
+ }).catch((err) => {
3337
+ if (!isCancelledRequest(err)) logSafeAdminError("impersonation.status", err);
3338
+ });
3339
+ return () => {
3340
+ current = false;
3341
+ };
3342
+ }, [canPreviewAdmins, get]);
4450
3343
  const confirmReturnRef = useRef(null);
4451
3344
  const captionRef = useRef(null);
4452
3345
  const pageRef = useRef(null);
@@ -4595,10 +3488,10 @@ const AdminPanelPage = () => {
4595
3488
  await Promise.all([fetchAdmins(), selected ? fetchDialogSessions(selected) : null]);
4596
3489
  } catch (err) {
4597
3490
  logSafeAdminError("adminPanel.signOut", err);
4598
- const message2 = getSignOutErrorMessage(err);
3491
+ const message = getSignOutErrorMessage(err);
4599
3492
  toggleNotification({
4600
3493
  type: getErrorStatus(err) === 404 ? "warning" : "danger",
4601
- message: t(message2.messageId, message2.defaultMessage)
3494
+ message: t(message.messageId, message.defaultMessage)
4602
3495
  });
4603
3496
  if (getErrorStatus(err) === 404) {
4604
3497
  await Promise.all([fetchAdmins(), selected ? fetchDialogSessions(selected) : null]);
@@ -4662,6 +3555,11 @@ const AdminPanelPage = () => {
4662
3555
  canRevoke: Boolean(canRevoke),
4663
3556
  onView: openDialog,
4664
3557
  onSignOutEverywhere: (admin, trigger) => askSignOut(admin, null, trigger),
3558
+ canPreview: Boolean(canPreviewAdmins) && impersonationEnabled,
3559
+ onPreview: (admin, trigger) => {
3560
+ openerRef.current = trigger;
3561
+ setPreviewTarget({ id: admin.id, name: admin.name });
3562
+ },
4665
3563
  busy: refreshing
4666
3564
  };
4667
3565
  const policy = meta?.policy;
@@ -4874,7 +3772,7 @@ const AdminPanelPage = () => {
4874
3772
  ] }),
4875
3773
  admins.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
4876
3774
  isBelowMedium ? /* @__PURE__ */ jsx(AdminCardList, { ...listProps }) : /* @__PURE__ */ jsx(AdminTable, { ...listProps }),
4877
- /* @__PURE__ */ jsx(PaginationTargets$1, { children: /* @__PURE__ */ jsxs(
3775
+ /* @__PURE__ */ jsx(PaginationTargets$2, { children: /* @__PURE__ */ jsxs(
4878
3776
  Pagination.Root,
4879
3777
  {
4880
3778
  pageCount: pagination.pageCount,
@@ -4919,6 +3817,14 @@ const AdminPanelPage = () => {
4919
3817
  },
4920
3818
  `${selected.id}-${dialogTab}`
4921
3819
  ) : null,
3820
+ previewTarget ? /* @__PURE__ */ jsx(
3821
+ PreviewAdminModal,
3822
+ {
3823
+ admin: previewTarget,
3824
+ onClose: () => setPreviewTarget(null),
3825
+ onCloseAutoFocus: (event) => restoreDialogFocus(event, openerRef.current, captionRef.current || pageRef.current)
3826
+ }
3827
+ ) : null,
4922
3828
  confirm ? /* @__PURE__ */ jsx(
4923
3829
  ConfirmAction,
4924
3830
  {
@@ -4940,7 +3846,7 @@ const AdminPanelPage = () => {
4940
3846
  }
4941
3847
  );
4942
3848
  };
4943
- const PaginationTargets = styled.div`
3849
+ const PaginationTargets$1 = styled.div`
4944
3850
  nav a {
4945
3851
  min-width: 3.2rem;
4946
3852
  }
@@ -5034,11 +3940,10 @@ const AdminActivityPage = () => {
5034
3940
  }
5035
3941
  ) }),
5036
3942
  view.adminId !== null ? /* @__PURE__ */ jsx(
5037
- Tag,
3943
+ FilterTag,
5038
3944
  {
5039
- icon: /* @__PURE__ */ jsx(Cross, { "aria-hidden": "true" }),
5040
3945
  label: t("adminPanel.activity.page.removeAdmin", "Show all admins again"),
5041
- onClick: () => setFilters({ adminId: void 0 }),
3946
+ onRemove: () => setFilters({ adminId: void 0 }),
5042
3947
  "data-admin-filter": view.adminId,
5043
3948
  children: t("adminPanel.activity.page.adminFilter", "Admin: {name}", { name: adminName })
5044
3949
  }
@@ -5102,6 +4007,173 @@ const AdminActivityPage = () => {
5102
4007
  "adminPanel.activity.page.export",
5103
4008
  "Export the security activity with these filters as CSV"
5104
4009
  ),
4010
+ footer: /* @__PURE__ */ jsx(PaginationTargets$1, { children: /* @__PURE__ */ jsxs(
4011
+ Pagination.Root,
4012
+ {
4013
+ pageCount: pagination.pageCount,
4014
+ total: pagination.total,
4015
+ defaultPageSize: EVENT_PAGE_SIZE,
4016
+ children: [
4017
+ /* @__PURE__ */ jsx(Pagination.PageSize, { options: [...ACTIVITY_PAGE_SIZE_OPTIONS] }),
4018
+ /* @__PURE__ */ jsx(Pagination.Links, {})
4019
+ ]
4020
+ }
4021
+ ) })
4022
+ }
4023
+ )
4024
+ }
4025
+ );
4026
+ };
4027
+ const PaginationTargets = styled.div`
4028
+ nav a {
4029
+ min-width: 3.2rem;
4030
+ }
4031
+
4032
+ & > div {
4033
+ flex-wrap: wrap;
4034
+ gap: ${({ theme }) => theme.spaces[2]} ${({ theme }) => theme.spaces[4]};
4035
+ }
4036
+
4037
+ & > div > div > span {
4038
+ white-space: nowrap;
4039
+ }
4040
+ `;
4041
+ const UserActivityPage = () => {
4042
+ const { formatMessage } = useIntl();
4043
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
4044
+ const [{ query }, setQuery] = useQueryParams();
4045
+ const view = parseUserActivityQuery(query);
4046
+ const captionRef = useRef(null);
4047
+ const params = useMemo(
4048
+ () => buildUserActivityParams({
4049
+ userId: view.userId,
4050
+ event: view.event,
4051
+ period: view.period,
4052
+ page: view.page,
4053
+ pageSize: view.pageSize
4054
+ }),
4055
+ [view.userId, view.event, view.period, view.page, view.pageSize]
4056
+ );
4057
+ const list = useEventList({
4058
+ path: USER_ACTIVITY_API_PATH,
4059
+ params,
4060
+ logKey: "userActivity.page"
4061
+ });
4062
+ const pagination = list.meta?.pagination || { pageCount: 1, total: 0 };
4063
+ useEffect(() => {
4064
+ if (!list.loading && list.meta && view.page > pagination.pageCount) {
4065
+ setQuery({ page: String(pagination.pageCount) }, "push", true);
4066
+ }
4067
+ }, [list.loading, list.meta, view.page, pagination.pageCount, setQuery]);
4068
+ const filtered = hasUserActivityFilters(view);
4069
+ const filteredUser = view.userId !== null ? list.rows.find((row) => row.user?.documentId === view.userId) : null;
4070
+ const userName = filteredUser ? userText(t, filteredUser) : t("userActivity.page.selectedUser", "Selected user");
4071
+ const setFilters = (next) => setQuery({ ...next, page: "1" });
4072
+ const clearFilters = () => {
4073
+ setQuery({ event: void 0, period: void 0, userId: void 0, page: "1" });
4074
+ captionRef.current?.focus();
4075
+ };
4076
+ const title = t("userActivity.page.title", "Security activity of app users");
4077
+ const recordingOff = list.meta?.recording && list.meta.recording.userSignIns === false;
4078
+ return /* @__PURE__ */ jsx(
4079
+ PageShell,
4080
+ {
4081
+ headingId: "magic-sessionmanager-user-activity-title",
4082
+ title,
4083
+ subtitle: t(
4084
+ "userActivity.page.subtitle",
4085
+ "Failed and refused sign-ins, lockouts, session limits, new devices, impossible travel, “This wasn’t me” reports, data exports and impersonations of your app’s users. Newest first."
4086
+ ),
4087
+ navigationAction: /* @__PURE__ */ jsx(BackButton, { fallback: SESSION_VIEW_PATHS.users }),
4088
+ children: /* @__PURE__ */ jsx(
4089
+ EventList,
4090
+ {
4091
+ list,
4092
+ filters: /* @__PURE__ */ jsxs(Fragment, { children: [
4093
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4094
+ SingleSelect,
4095
+ {
4096
+ size: "S",
4097
+ "aria-label": t("adminPanel.activity.filter.event", "Event"),
4098
+ value: view.event,
4099
+ onChange: (next) => setFilters({ event: String(next) === "all" ? void 0 : String(next) }),
4100
+ children: USER_ACTIVITY_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: t(...USER_ACTIVITY_FILTER_LABELS[option]) }, option))
4101
+ }
4102
+ ) }),
4103
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4104
+ PeriodSelect,
4105
+ {
4106
+ value: view.period,
4107
+ onChange: (next) => setFilters({ period: next === "30" ? void 0 : next })
4108
+ }
4109
+ ) }),
4110
+ view.userId !== null ? /* @__PURE__ */ jsx(
4111
+ FilterTag,
4112
+ {
4113
+ label: t("userActivity.page.removeUser", "Show all users again"),
4114
+ onRemove: () => setFilters({ userId: void 0 }),
4115
+ "data-user-filter": view.userId,
4116
+ children: t("userActivity.page.userFilter", "User: {name}", { name: userName })
4117
+ }
4118
+ ) : null
4119
+ ] }),
4120
+ notice: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
4121
+ recordingOff ? /* @__PURE__ */ jsx(RecordingOff, { to: USER_ACTIVITY_SETTINGS_PATH, children: t(
4122
+ "userActivity.page.recordingOff",
4123
+ "Failed and refused sign-ins are not recorded. The other events still are."
4124
+ ) }) : null,
4125
+ /* @__PURE__ */ jsx(
4126
+ Typography,
4127
+ {
4128
+ ref: captionRef,
4129
+ tabIndex: -1,
4130
+ variant: "pi",
4131
+ textColor: "neutral600",
4132
+ "aria-live": "polite",
4133
+ "data-activity-caption": "",
4134
+ children: t(
4135
+ "adminPanel.activity.page.caption",
4136
+ "{total, plural, =0 {No events} one {# event} other {# events}}",
4137
+ { total: pagination.total }
4138
+ )
4139
+ }
4140
+ )
4141
+ ] }),
4142
+ empty: /* @__PURE__ */ jsx(
4143
+ EmptyStateLayout,
4144
+ {
4145
+ icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
4146
+ content: filtered ? t("adminPanel.activity.page.noResults", "No events match these filters.") : t("userActivity.recent.empty", "No security events of app users yet."),
4147
+ action: filtered ? /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: clearFilters, children: t("adminPanel.noResults.reset", "Clear filters") }) : null
4148
+ }
4149
+ ),
4150
+ renderList: (rows) => /* @__PURE__ */ jsx(
4151
+ UserEventTable,
4152
+ {
4153
+ rows,
4154
+ label: title,
4155
+ busy: list.loading,
4156
+ detailsAction: (row, close) => row.user?.documentId && row.user.documentId !== view.userId ? /* @__PURE__ */ jsx(
4157
+ Button,
4158
+ {
4159
+ variant: "secondary",
4160
+ onClick: () => {
4161
+ close();
4162
+ setFilters({ userId: row.user.documentId });
4163
+ },
4164
+ children: t("userActivity.page.onlyUser", "Show only events of {name}", {
4165
+ name: userText(t, row)
4166
+ })
4167
+ }
4168
+ ) : null
4169
+ }
4170
+ ),
4171
+ toCsv: buildUserActivityCsv,
4172
+ fileName: "app-user-security-activity",
4173
+ exportLabel: t(
4174
+ "userActivity.page.export",
4175
+ "Export the security activity of app users with these filters as CSV"
4176
+ ),
5105
4177
  footer: /* @__PURE__ */ jsx(PaginationTargets, { children: /* @__PURE__ */ jsxs(
5106
4178
  Pagination.Root,
5107
4179
  {
@@ -5136,6 +4208,13 @@ const App = () => {
5136
4208
  element: /* @__PURE__ */ jsx(Page.Protect, { permissions: pluginPermissions.adminSessionsRead, children: /* @__PURE__ */ jsx(Page.Protect, { permissions: pluginPermissions.adminActivityRead, children: /* @__PURE__ */ jsx(AdminActivityPage, {}) }) })
5137
4209
  }
5138
4210
  ),
4211
+ /* @__PURE__ */ jsx(
4212
+ Route,
4213
+ {
4214
+ path: "app-users/activity",
4215
+ element: /* @__PURE__ */ jsx(Page.Protect, { permissions: pluginPermissions.userActivityRead, children: /* @__PURE__ */ jsx(UserActivityPage, {}) })
4216
+ }
4217
+ ),
5139
4218
  /* @__PURE__ */ jsx(Route, { path: "*", element: /* @__PURE__ */ jsx(HomePage, {}) })
5140
4219
  ] }) });
5141
4220
  };