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