@10x-media/analytics 0.1.0-beta.1 → 0.1.0-beta.3
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.
- package/CHANGELOG.md +64 -0
- package/README.md +1 -0
- package/dist/adapters/ga4/ga4.js +17 -7
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +5 -0
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.js +28 -17
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +1 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/binding/types.d.ts +9 -7
- package/dist/charts/TrendChart.js +17 -8
- package/dist/charts/TrendChart.js.map +1 -1
- package/dist/charts/bucket.js +31 -24
- package/dist/charts/bucket.js.map +1 -1
- package/dist/core/cacheKey.js +4 -7
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/contract.d.ts +12 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +27 -2
- package/dist/core/options.js +15 -8
- package/dist/core/options.js.map +1 -1
- package/dist/exports/rsc.d.ts +6 -3
- package/dist/exports/rsc.js +5 -2
- package/dist/fields/AnalyticsPanelClient.js +193 -0
- package/dist/fields/AnalyticsPanelClient.js.map +1 -0
- package/dist/fields/AnalyticsPanelField.d.ts +28 -0
- package/dist/fields/AnalyticsPanelField.js +54 -0
- package/dist/fields/AnalyticsPanelField.js.map +1 -0
- package/dist/fields/AnalyticsStatField.d.ts +1 -1
- package/dist/fields/AnalyticsStatField.js +14 -3
- package/dist/fields/AnalyticsStatField.js.map +1 -1
- package/dist/fields/emptyState.js +46 -0
- package/dist/fields/emptyState.js.map +1 -0
- package/dist/fields/factories.d.ts +10 -2
- package/dist/fields/factories.js +33 -4
- package/dist/fields/factories.js.map +1 -1
- package/dist/fields/readForDocument.d.ts +57 -0
- package/dist/fields/readForDocument.js +50 -10
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +29 -4
- package/dist/index.js.map +1 -1
- package/dist/native/ingest/endpoint.js +5 -2
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.js +3 -2
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/writeEvent.js +2 -1
- package/dist/native/ingest/writeEvent.js.map +1 -1
- package/dist/native/nativeAdapter.js +7 -4
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/rollupAcc.js +9 -6
- package/dist/native/rollupAcc.js.map +1 -1
- package/dist/native/rollups/bumpRollup.js +17 -1
- package/dist/native/rollups/bumpRollup.js.map +1 -1
- package/dist/native/rollups/deltas.js +2 -2
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +80 -0
- package/dist/plugin/documentEndpoint.js.map +1 -0
- package/dist/plugin/paths.js +11 -0
- package/dist/plugin/paths.js.map +1 -0
- package/dist/plugin/runtime.js +2 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/warmTask.js +1 -1
- package/dist/surfacing/engine.js +5 -5
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/sync/collection.js +11 -6
- package/dist/sync/collection.js.map +1 -1
- package/dist/sync/syncTask.js +1 -1
- package/dist/timeframe/presets.js +12 -16
- package/dist/timeframe/presets.js.map +1 -1
- package/dist/timeframe/tz.js +110 -0
- package/dist/timeframe/tz.js.map +1 -0
- package/dist/translations/de.js +78 -0
- package/dist/translations/de.js.map +1 -0
- package/dist/translations/en.js +5 -2
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/index.d.ts +2 -1
- package/dist/translations/index.js +6 -2
- package/dist/translations/index.js.map +1 -1
- package/dist/translations/keys.d.ts +5 -2
- package/dist/translations/keys.js +5 -2
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/metricKeys.js +0 -2
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +9 -1
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +10 -2
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/ComparisonDelta.js +83 -0
- package/dist/widgets/ComparisonDelta.js.map +1 -0
- package/dist/widgets/cardChrome.d.ts +8 -0
- package/dist/widgets/comparison.js +43 -0
- package/dist/widgets/comparison.js.map +1 -0
- package/dist/widgets/readForWidget.d.ts +4 -0
- package/dist/widgets/readForWidget.js +26 -11
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.js +13 -8
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.js +1 -1
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +6 -0
- package/dist/widgets/readForWidgetSeries.js +60 -40
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +148 -169
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { keys } from "../translations/keys.js";
|
|
3
|
+
import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
|
|
4
|
+
import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
5
|
+
import { DOCUMENT_PATH } from "../plugin/paths.js";
|
|
6
|
+
import { TrendChart } from "../charts/TrendChart.js";
|
|
7
|
+
import { useTranslation as useTranslation$1 } from "../translations/useTranslation.js";
|
|
8
|
+
import { AnalyticsEmptyState, isNewDocumentAnalytics } from "./emptyState.js";
|
|
9
|
+
import { formatMetricValue } from "./format.js";
|
|
10
|
+
import { ComparisonDelta } from "../widgets/ComparisonDelta.js";
|
|
11
|
+
import { bucketSeries } from "../charts/bucket.js";
|
|
12
|
+
import { useCallback, useState } from "react";
|
|
13
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
14
|
+
import { ReactSelect, useConfig, useDocumentInfo } from "@payloadcms/ui";
|
|
15
|
+
//#region src/fields/AnalyticsPanelClient.tsx
|
|
16
|
+
const STATE_KEYS = {
|
|
17
|
+
"no-path": keys.stateNoData,
|
|
18
|
+
"not-bound": keys.stateNotBound,
|
|
19
|
+
"not-configured": keys.stateNotConfigured,
|
|
20
|
+
unavailable: keys.stateUnavailable
|
|
21
|
+
};
|
|
22
|
+
const cardStyle = {
|
|
23
|
+
display: "flex",
|
|
24
|
+
flexDirection: "column",
|
|
25
|
+
gap: "0.25rem",
|
|
26
|
+
minWidth: "7rem"
|
|
27
|
+
};
|
|
28
|
+
const labelStyle = {
|
|
29
|
+
fontSize: "0.6875rem",
|
|
30
|
+
fontWeight: 600,
|
|
31
|
+
letterSpacing: "0.04em",
|
|
32
|
+
textTransform: "uppercase",
|
|
33
|
+
color: "var(--theme-elevation-500)"
|
|
34
|
+
};
|
|
35
|
+
const valueStyle = {
|
|
36
|
+
fontSize: "1.5rem",
|
|
37
|
+
fontWeight: 600,
|
|
38
|
+
lineHeight: 1.1
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Interactive per-document analytics panel: metric cards with period-over-period
|
|
42
|
+
* deltas, a daily trend for the first metric, and a timeframe picker that refetches
|
|
43
|
+
* through the authenticated document endpoint. The server component provides the
|
|
44
|
+
* initial read so first paint never flashes empty.
|
|
45
|
+
*/
|
|
46
|
+
function AnalyticsPanelClient(props) {
|
|
47
|
+
const { collectionSlug, metrics, initial, initialTimeframe, adapterId, labels } = props;
|
|
48
|
+
const { t, i18n } = useTranslation$1();
|
|
49
|
+
const locale = i18n.language ?? "en-US";
|
|
50
|
+
const { id } = useDocumentInfo();
|
|
51
|
+
const { config: { routes: { api }, serverURL } } = useConfig();
|
|
52
|
+
const [timeframe, setTimeframe] = useState(initialTimeframe);
|
|
53
|
+
const [data, setData] = useState(initial);
|
|
54
|
+
const [loading, setLoading] = useState(false);
|
|
55
|
+
const refetch = useCallback(async (preset) => {
|
|
56
|
+
if (id === void 0 || id === null) return;
|
|
57
|
+
setLoading(true);
|
|
58
|
+
try {
|
|
59
|
+
const params = new URLSearchParams({
|
|
60
|
+
collection: collectionSlug,
|
|
61
|
+
id: String(id),
|
|
62
|
+
timeframe: preset,
|
|
63
|
+
metrics: metrics.join(","),
|
|
64
|
+
compare: "1",
|
|
65
|
+
series: "1"
|
|
66
|
+
});
|
|
67
|
+
if (adapterId) params.set("dataSource", adapterId);
|
|
68
|
+
const res = await fetch(`${serverURL ?? ""}${api}${DOCUMENT_PATH}?${params}`, { credentials: "include" });
|
|
69
|
+
if (!res.ok) throw new Error(`analytics document read failed: ${res.status}`);
|
|
70
|
+
setData(await res.json());
|
|
71
|
+
} catch {
|
|
72
|
+
setData((prev) => ({
|
|
73
|
+
...prev,
|
|
74
|
+
status: "unavailable"
|
|
75
|
+
}));
|
|
76
|
+
} finally {
|
|
77
|
+
setLoading(false);
|
|
78
|
+
}
|
|
79
|
+
}, [
|
|
80
|
+
adapterId,
|
|
81
|
+
api,
|
|
82
|
+
collectionSlug,
|
|
83
|
+
id,
|
|
84
|
+
metrics,
|
|
85
|
+
serverURL
|
|
86
|
+
]);
|
|
87
|
+
const onTimeframeChange = (preset) => {
|
|
88
|
+
setTimeframe(preset);
|
|
89
|
+
refetch(preset);
|
|
90
|
+
};
|
|
91
|
+
const timeframeOptions = TIMEFRAME_PRESETS.map((p) => ({
|
|
92
|
+
value: p,
|
|
93
|
+
label: t(TIMEFRAME_KEYS[p])
|
|
94
|
+
}));
|
|
95
|
+
const firstMetric = data.supportedMetrics[0];
|
|
96
|
+
const buckets = data.points && data.points.length > 0 && firstMetric ? bucketSeries(data.points, timeframe, data.timezone).map((b) => ({
|
|
97
|
+
...b,
|
|
98
|
+
display: formatMetricValue(firstMetric, b.value, locale)
|
|
99
|
+
})) : null;
|
|
100
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
101
|
+
className: "field-type analytics-panel",
|
|
102
|
+
style: {
|
|
103
|
+
display: "flex",
|
|
104
|
+
flexDirection: "column",
|
|
105
|
+
gap: "1rem"
|
|
106
|
+
},
|
|
107
|
+
children: [/* @__PURE__ */ jsx("div", {
|
|
108
|
+
style: {
|
|
109
|
+
display: "flex",
|
|
110
|
+
justifyContent: "flex-end"
|
|
111
|
+
},
|
|
112
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
113
|
+
style: { minWidth: "11rem" },
|
|
114
|
+
children: /* @__PURE__ */ jsx(ReactSelect, {
|
|
115
|
+
isClearable: false,
|
|
116
|
+
isSearchable: false,
|
|
117
|
+
value: {
|
|
118
|
+
value: timeframe,
|
|
119
|
+
label: t(TIMEFRAME_KEYS[timeframe])
|
|
120
|
+
},
|
|
121
|
+
options: timeframeOptions,
|
|
122
|
+
onChange: (option) => {
|
|
123
|
+
const value = option?.value;
|
|
124
|
+
if (value && value !== timeframe) onTimeframeChange(value);
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
})
|
|
128
|
+
}), /* @__PURE__ */ jsx("div", {
|
|
129
|
+
style: {
|
|
130
|
+
opacity: loading ? .5 : 1,
|
|
131
|
+
transition: "opacity 0.15s"
|
|
132
|
+
},
|
|
133
|
+
children: isNewDocumentAnalytics(data) ? /* @__PURE__ */ jsx(AnalyticsEmptyState, {
|
|
134
|
+
isNew: true,
|
|
135
|
+
children: t(keys.stateNew)
|
|
136
|
+
}) : data.status !== "ok" ? /* @__PURE__ */ jsx(AnalyticsEmptyState, {
|
|
137
|
+
isNew: false,
|
|
138
|
+
children: t(STATE_KEYS[data.status])
|
|
139
|
+
}) : /* @__PURE__ */ jsxs("div", {
|
|
140
|
+
style: {
|
|
141
|
+
display: "flex",
|
|
142
|
+
flexDirection: "column",
|
|
143
|
+
gap: "1rem"
|
|
144
|
+
},
|
|
145
|
+
children: [
|
|
146
|
+
/* @__PURE__ */ jsx("div", {
|
|
147
|
+
style: {
|
|
148
|
+
display: "flex",
|
|
149
|
+
flexWrap: "wrap",
|
|
150
|
+
gap: "1.5rem"
|
|
151
|
+
},
|
|
152
|
+
children: data.supportedMetrics.map((metric) => /* @__PURE__ */ jsxs("div", {
|
|
153
|
+
style: cardStyle,
|
|
154
|
+
children: [
|
|
155
|
+
/* @__PURE__ */ jsx("span", {
|
|
156
|
+
style: labelStyle,
|
|
157
|
+
children: labels?.[metric] ?? t(METRIC_KEYS[metric])
|
|
158
|
+
}),
|
|
159
|
+
/* @__PURE__ */ jsx("span", {
|
|
160
|
+
style: valueStyle,
|
|
161
|
+
children: formatMetricValue(metric, data.metrics[metric] ?? 0, locale)
|
|
162
|
+
}),
|
|
163
|
+
data.comparisonRange ? /* @__PURE__ */ jsx(ComparisonDelta, {
|
|
164
|
+
current: data.metrics[metric] ?? 0,
|
|
165
|
+
previous: data.previousMetrics?.[metric],
|
|
166
|
+
metric,
|
|
167
|
+
locale,
|
|
168
|
+
t
|
|
169
|
+
}) : null
|
|
170
|
+
]
|
|
171
|
+
}, metric))
|
|
172
|
+
}),
|
|
173
|
+
buckets && firstMetric ? /* @__PURE__ */ jsx(TrendChart, {
|
|
174
|
+
buckets,
|
|
175
|
+
ariaLabel: `${t(METRIC_KEYS[firstMetric])} ${t(TIMEFRAME_KEYS[timeframe])}`,
|
|
176
|
+
minHeight: 140
|
|
177
|
+
}) : null,
|
|
178
|
+
/* @__PURE__ */ jsx("span", {
|
|
179
|
+
style: {
|
|
180
|
+
fontSize: "0.75rem",
|
|
181
|
+
color: "var(--theme-elevation-400)"
|
|
182
|
+
},
|
|
183
|
+
children: t(TIMEFRAME_KEYS[timeframe])
|
|
184
|
+
})
|
|
185
|
+
]
|
|
186
|
+
})
|
|
187
|
+
})]
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
//#endregion
|
|
191
|
+
export { AnalyticsPanelClient };
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=AnalyticsPanelClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AnalyticsPanelClient.js","names":["useTranslation"],"sources":["../../src/fields/AnalyticsPanelClient.tsx"],"sourcesContent":["'use client'\n\nimport { ReactSelect, useConfig, useDocumentInfo } from '@payloadcms/ui'\nimport { type CSSProperties, useCallback, useState } from 'react'\nimport { bucketSeries } from '../charts/bucket'\nimport { TrendChart } from '../charts/TrendChart'\nimport type { MetricKey } from '../core/contract'\nimport { DOCUMENT_PATH } from '../plugin/paths'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { ComparisonDelta } from '../widgets/ComparisonDelta'\nimport type { SeriesPoint } from '../widgets/readForWidgetSeries'\nimport { AnalyticsEmptyState, isNewDocumentAnalytics } from './emptyState'\nimport { formatMetricValue } from './format'\nimport type { FieldReadStatus } from './readForDocument'\n\n/** JSON-safe shape of a document analytics read, as the panel endpoint returns it. */\nexport interface PanelData {\n\tstatus: FieldReadStatus\n\tmetrics: Partial<Record<MetricKey, number>>\n\tsupportedMetrics: MetricKey[]\n\tpreviousMetrics?: Partial<Record<MetricKey, number>>\n\tcomparisonRange?: { start: string; end: string } | null\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone?: string\n\tpoints?: SeriesPoint[]\n}\n\nexport interface AnalyticsPanelClientProps {\n\tcollectionSlug: string\n\tmetrics: MetricKey[]\n\tinitial: PanelData\n\tinitialTimeframe: TimeframePreset\n\tadapterId?: string\n\t/** Metric card labels resolved to plain strings on the server. */\n\tlabels?: Partial<Record<MetricKey, string>>\n}\n\nconst STATE_KEYS: Record<Exclude<FieldReadStatus, 'ok'>, TranslationKey> = {\n\t'no-path': keys.stateNoData,\n\t'not-bound': keys.stateNotBound,\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n}\n\nconst cardStyle: CSSProperties = {\n\tdisplay: 'flex',\n\tflexDirection: 'column',\n\tgap: '0.25rem',\n\tminWidth: '7rem',\n}\nconst labelStyle: CSSProperties = {\n\tfontSize: '0.6875rem',\n\tfontWeight: 600,\n\tletterSpacing: '0.04em',\n\ttextTransform: 'uppercase',\n\tcolor: 'var(--theme-elevation-500)',\n}\nconst valueStyle: CSSProperties = { fontSize: '1.5rem', fontWeight: 600, lineHeight: 1.1 }\n\n/**\n * Interactive per-document analytics panel: metric cards with period-over-period\n * deltas, a daily trend for the first metric, and a timeframe picker that refetches\n * through the authenticated document endpoint. The server component provides the\n * initial read so first paint never flashes empty.\n */\nexport function AnalyticsPanelClient(props: AnalyticsPanelClientProps) {\n\tconst { collectionSlug, metrics, initial, initialTimeframe, adapterId, labels } = props\n\tconst { t, i18n } = useTranslation()\n\tconst locale = i18n.language ?? 'en-US'\n\tconst { id } = useDocumentInfo()\n\tconst {\n\t\tconfig: {\n\t\t\troutes: { api },\n\t\t\tserverURL,\n\t\t},\n\t} = useConfig()\n\tconst [timeframe, setTimeframe] = useState<TimeframePreset>(initialTimeframe)\n\tconst [data, setData] = useState<PanelData>(initial)\n\tconst [loading, setLoading] = useState(false)\n\n\tconst refetch = useCallback(\n\t\tasync (preset: TimeframePreset) => {\n\t\t\tif (id === undefined || id === null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsetLoading(true)\n\t\t\ttry {\n\t\t\t\tconst params = new URLSearchParams({\n\t\t\t\t\tcollection: collectionSlug,\n\t\t\t\t\tid: String(id),\n\t\t\t\t\ttimeframe: preset,\n\t\t\t\t\tmetrics: metrics.join(','),\n\t\t\t\t\tcompare: '1',\n\t\t\t\t\tseries: '1',\n\t\t\t\t})\n\t\t\t\tif (adapterId) {\n\t\t\t\t\tparams.set('dataSource', adapterId)\n\t\t\t\t}\n\t\t\t\tconst res = await fetch(`${serverURL ?? ''}${api}${DOCUMENT_PATH}?${params}`, {\n\t\t\t\t\tcredentials: 'include',\n\t\t\t\t})\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tthrow new Error(`analytics document read failed: ${res.status}`)\n\t\t\t\t}\n\t\t\t\tsetData((await res.json()) as PanelData)\n\t\t\t} catch {\n\t\t\t\tsetData((prev) => ({ ...prev, status: 'unavailable' }))\n\t\t\t} finally {\n\t\t\t\tsetLoading(false)\n\t\t\t}\n\t\t},\n\t\t[adapterId, api, collectionSlug, id, metrics, serverURL]\n\t)\n\n\tconst onTimeframeChange = (preset: TimeframePreset) => {\n\t\tsetTimeframe(preset)\n\t\tvoid refetch(preset)\n\t}\n\n\tconst timeframeOptions = TIMEFRAME_PRESETS.map((p) => ({\n\t\tvalue: p,\n\t\tlabel: t(TIMEFRAME_KEYS[p]),\n\t}))\n\tconst firstMetric = data.supportedMetrics[0]\n\tconst buckets =\n\t\tdata.points && data.points.length > 0 && firstMetric\n\t\t\t? bucketSeries(data.points, timeframe, data.timezone).map((b) => ({\n\t\t\t\t\t...b,\n\t\t\t\t\tdisplay: formatMetricValue(firstMetric, b.value, locale),\n\t\t\t\t}))\n\t\t\t: null\n\n\treturn (\n\t\t<div\n\t\t\tclassName=\"field-type analytics-panel\"\n\t\t\tstyle={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}\n\t\t>\n\t\t\t<div style={{ display: 'flex', justifyContent: 'flex-end' }}>\n\t\t\t\t<div style={{ minWidth: '11rem' }}>\n\t\t\t\t\t<ReactSelect\n\t\t\t\t\t\tisClearable={false}\n\t\t\t\t\t\tisSearchable={false}\n\t\t\t\t\t\tvalue={{ value: timeframe, label: t(TIMEFRAME_KEYS[timeframe]) }}\n\t\t\t\t\t\toptions={timeframeOptions}\n\t\t\t\t\t\tonChange={(option) => {\n\t\t\t\t\t\t\tconst value = (option as { value?: TimeframePreset } | null)?.value\n\t\t\t\t\t\t\tif (value && value !== timeframe) {\n\t\t\t\t\t\t\t\tonTimeframeChange(value)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}}\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div style={{ opacity: loading ? 0.5 : 1, transition: 'opacity 0.15s' }}>\n\t\t\t\t{isNewDocumentAnalytics(data) ? (\n\t\t\t\t\t<AnalyticsEmptyState isNew>{t(keys.stateNew)}</AnalyticsEmptyState>\n\t\t\t\t) : data.status !== 'ok' ? (\n\t\t\t\t\t<AnalyticsEmptyState isNew={false}>{t(STATE_KEYS[data.status])}</AnalyticsEmptyState>\n\t\t\t\t) : (\n\t\t\t\t\t<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>\n\t\t\t\t\t\t<div style={{ display: 'flex', flexWrap: 'wrap', gap: '1.5rem' }}>\n\t\t\t\t\t\t\t{data.supportedMetrics.map((metric) => (\n\t\t\t\t\t\t\t\t<div key={metric} style={cardStyle}>\n\t\t\t\t\t\t\t\t\t<span style={labelStyle}>{labels?.[metric] ?? t(METRIC_KEYS[metric])}</span>\n\t\t\t\t\t\t\t\t\t<span style={valueStyle}>\n\t\t\t\t\t\t\t\t\t\t{formatMetricValue(metric, data.metrics[metric] ?? 0, locale)}\n\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t{data.comparisonRange ? (\n\t\t\t\t\t\t\t\t\t\t<ComparisonDelta\n\t\t\t\t\t\t\t\t\t\t\tcurrent={data.metrics[metric] ?? 0}\n\t\t\t\t\t\t\t\t\t\t\tprevious={data.previousMetrics?.[metric]}\n\t\t\t\t\t\t\t\t\t\t\tmetric={metric}\n\t\t\t\t\t\t\t\t\t\t\tlocale={locale}\n\t\t\t\t\t\t\t\t\t\t\tt={t}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{buckets && firstMetric ? (\n\t\t\t\t\t\t\t<TrendChart\n\t\t\t\t\t\t\t\tbuckets={buckets}\n\t\t\t\t\t\t\t\tariaLabel={`${t(METRIC_KEYS[firstMetric])} ${t(TIMEFRAME_KEYS[timeframe])}`}\n\t\t\t\t\t\t\t\tminHeight={140}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t<span style={{ fontSize: '0.75rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t\t\t{t(TIMEFRAME_KEYS[timeframe])}\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAM,aAAqE;CAC1E,WAAW,KAAK;CAChB,aAAa,KAAK;CAClB,kBAAkB,KAAK;CACvB,aAAa,KAAK;AACnB;AAEA,MAAM,YAA2B;CAChC,SAAS;CACT,eAAe;CACf,KAAK;CACL,UAAU;AACX;AACA,MAAM,aAA4B;CACjC,UAAU;CACV,YAAY;CACZ,eAAe;CACf,eAAe;CACf,OAAO;AACR;AACA,MAAM,aAA4B;CAAE,UAAU;CAAU,YAAY;CAAK,YAAY;AAAI;;;;;;;AAQzF,SAAgB,qBAAqB,OAAkC;CACtE,MAAM,EAAE,gBAAgB,SAAS,SAAS,kBAAkB,WAAW,WAAW;CAClF,MAAM,EAAE,GAAG,SAASA,iBAAe;CACnC,MAAM,SAAS,KAAK,YAAY;CAChC,MAAM,EAAE,OAAO,gBAAgB;CAC/B,MAAM,EACL,QAAQ,EACP,QAAQ,EAAE,OACV,gBAEE,UAAU;CACd,MAAM,CAAC,WAAW,gBAAgB,SAA0B,gBAAgB;CAC5E,MAAM,CAAC,MAAM,WAAW,SAAoB,OAAO;CACnD,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAE5C,MAAM,UAAU,YACf,OAAO,WAA4B;EAClC,IAAI,OAAO,KAAA,KAAa,OAAO,MAC9B;EAED,WAAW,IAAI;EACf,IAAI;GACH,MAAM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@ -0,0 +1,28 @@
|
|
|
1
|
+
import { MetricKey } from "../core/contract.js";
|
|
2
|
+
import { BindingDoc } from "../binding/types.js";
|
|
3
|
+
import { TimeframePreset } from "../timeframe/presets.js";
|
|
4
|
+
import { AnalyticsMetricLabels } from "./factories.js";
|
|
5
|
+
import { StatFieldI18n } from "./AnalyticsStatField.js";
|
|
6
|
+
import { PayloadRequest } from "payload";
|
|
7
|
+
|
|
8
|
+
//#region src/fields/AnalyticsPanelField.d.ts
|
|
9
|
+
interface AnalyticsPanelFieldProps {
|
|
10
|
+
req: PayloadRequest;
|
|
11
|
+
data: BindingDoc;
|
|
12
|
+
collectionSlug: string;
|
|
13
|
+
i18n: StatFieldI18n;
|
|
14
|
+
metrics: MetricKey[];
|
|
15
|
+
timeframe: TimeframePreset;
|
|
16
|
+
adapterId?: string;
|
|
17
|
+
labels?: AnalyticsMetricLabels;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Server entry for the interactive document analytics panel: performs the initial
|
|
21
|
+
* read (with comparison and daily series) so the client renders populated, resolves
|
|
22
|
+
* metric label overrides to plain strings, and hands off to the client panel for
|
|
23
|
+
* timeframe interactivity.
|
|
24
|
+
*/
|
|
25
|
+
declare const AnalyticsPanelField: (props: AnalyticsPanelFieldProps) => Promise<import("react/jsx-runtime").JSX.Element>;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { AnalyticsPanelField };
|
|
28
|
+
//# sourceMappingURL=AnalyticsPanelField.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { asTranslate } from "../translations/server.js";
|
|
2
|
+
import { readForField } from "./readForDocument.js";
|
|
3
|
+
import { METRIC_KEYS } from "../translations/metricKeys.js";
|
|
4
|
+
import { resolveMetricLabel } from "./AnalyticsStatField.js";
|
|
5
|
+
import { jsx } from "react/jsx-runtime";
|
|
6
|
+
//#region src/fields/AnalyticsPanelField.tsx
|
|
7
|
+
/**
|
|
8
|
+
* Server entry for the interactive document analytics panel: performs the initial
|
|
9
|
+
* read (with comparison and daily series) so the client renders populated, resolves
|
|
10
|
+
* metric label overrides to plain strings, and hands off to the client panel for
|
|
11
|
+
* timeframe interactivity.
|
|
12
|
+
*/
|
|
13
|
+
const AnalyticsPanelField = async (props) => {
|
|
14
|
+
const { req, data, collectionSlug, i18n, metrics, timeframe, adapterId, labels } = props;
|
|
15
|
+
const t = asTranslate(i18n.t);
|
|
16
|
+
const { AnalyticsPanelClient } = await import("./AnalyticsPanelClient.js");
|
|
17
|
+
const result = await readForField({
|
|
18
|
+
req,
|
|
19
|
+
collectionSlug,
|
|
20
|
+
data,
|
|
21
|
+
metrics,
|
|
22
|
+
timeframe,
|
|
23
|
+
adapterId,
|
|
24
|
+
now: /* @__PURE__ */ new Date(),
|
|
25
|
+
compare: true,
|
|
26
|
+
series: true
|
|
27
|
+
});
|
|
28
|
+
const initial = {
|
|
29
|
+
status: result.status,
|
|
30
|
+
metrics: result.metrics,
|
|
31
|
+
supportedMetrics: result.supportedMetrics,
|
|
32
|
+
previousMetrics: result.previousMetrics,
|
|
33
|
+
timezone: result.timezone,
|
|
34
|
+
comparisonRange: result.comparisonRange ? {
|
|
35
|
+
start: result.comparisonRange.start.toISOString(),
|
|
36
|
+
end: result.comparisonRange.end.toISOString()
|
|
37
|
+
} : void 0,
|
|
38
|
+
points: result.points
|
|
39
|
+
};
|
|
40
|
+
const resolvedLabels = {};
|
|
41
|
+
for (const metric of metrics) resolvedLabels[metric] = resolveMetricLabel(labels?.[metric], i18n, () => t(METRIC_KEYS[metric]));
|
|
42
|
+
return /* @__PURE__ */ jsx(AnalyticsPanelClient, {
|
|
43
|
+
collectionSlug,
|
|
44
|
+
metrics,
|
|
45
|
+
initial,
|
|
46
|
+
initialTimeframe: timeframe,
|
|
47
|
+
adapterId,
|
|
48
|
+
labels: resolvedLabels
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
//#endregion
|
|
52
|
+
export { AnalyticsPanelField };
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=AnalyticsPanelField.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AnalyticsPanelField.js","names":[],"sources":["../../src/fields/AnalyticsPanelField.tsx"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { BindingDoc } from '../binding/types'\nimport type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport type { PanelData } from './AnalyticsPanelClient'\nimport { resolveMetricLabel, type StatFieldI18n } from './AnalyticsStatField'\nimport type { AnalyticsMetricLabels } from './factories'\nimport { readForField } from './readForDocument'\n\ninterface AnalyticsPanelFieldProps {\n\treq: PayloadRequest\n\tdata: BindingDoc\n\tcollectionSlug: string\n\ti18n: StatFieldI18n\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tlabels?: AnalyticsMetricLabels\n}\n\n/**\n * Server entry for the interactive document analytics panel: performs the initial\n * read (with comparison and daily series) so the client renders populated, resolves\n * metric label overrides to plain strings, and hands off to the client panel for\n * timeframe interactivity.\n */\nexport const AnalyticsPanelField = async (props: AnalyticsPanelFieldProps) => {\n\tconst { req, data, collectionSlug, i18n, metrics, timeframe, adapterId, labels } = props\n\tconst t = asTranslate(i18n.t)\n\t// Imported lazily so the /rsc export surface stays loadable outside a bundler\n\t// (plain-node scripts and workers); the client module's @payloadcms/ui chain\n\t// includes CSS only a bundler can resolve.\n\tconst { AnalyticsPanelClient } = await import('./AnalyticsPanelClient')\n\n\tconst result = await readForField({\n\t\treq,\n\t\tcollectionSlug,\n\t\tdata,\n\t\tmetrics,\n\t\ttimeframe,\n\t\tadapterId,\n\t\tnow: new Date(),\n\t\tcompare: true,\n\t\tseries: true,\n\t})\n\n\tconst initial: PanelData = {\n\t\tstatus: result.status,\n\t\tmetrics: result.metrics,\n\t\tsupportedMetrics: result.supportedMetrics,\n\t\tpreviousMetrics: result.previousMetrics,\n\t\ttimezone: result.timezone,\n\t\tcomparisonRange: result.comparisonRange\n\t\t\t? {\n\t\t\t\t\tstart: result.comparisonRange.start.toISOString(),\n\t\t\t\t\tend: result.comparisonRange.end.toISOString(),\n\t\t\t\t}\n\t\t\t: undefined,\n\t\tpoints: result.points,\n\t}\n\tconst resolvedLabels: Partial<Record<MetricKey, string>> = {}\n\tfor (const metric of metrics) {\n\t\tresolvedLabels[metric] = resolveMetricLabel(labels?.[metric], i18n, () =>\n\t\t\tt(METRIC_KEYS[metric])\n\t\t)\n\t}\n\n\treturn (\n\t\t<AnalyticsPanelClient\n\t\t\tcollectionSlug={collectionSlug}\n\t\t\tmetrics={metrics}\n\t\t\tinitial={initial}\n\t\t\tinitialTimeframe={timeframe}\n\t\t\tadapterId={adapterId}\n\t\t\tlabels={resolvedLabels}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;AA4BA,MAAa,sBAAsB,OAAO,UAAoC;CAC7E,MAAM,EAAE,KAAK,MAAM,gBAAgB,MAAM,SAAS,WAAW,WAAW,WAAW;CACnF,MAAM,IAAI,YAAY,KAAK,CAAC;CAI5B,MAAM,EAAE,yBAAyB,MAAM,OAAO;CAE9C,MAAM,SAAS,MAAM,aAAa;EACjC;EACA;EACA;EACA;EACA;EACA;EACA,qBAAK,IAAI,KAAK;EACd,SAAS;EACT,QAAQ;CACT,CAAC;CAED,MAAM,UAAqB;EAC1B,QAAQ,OAAO;EACf,SAAS,OAAO;EAChB,kBAAkB,OAAO;EACzB,iBAAiB,OAAO;EACxB,UAAU,OAAO;EACjB,iBAAiB,OAAO,kBACrB;GACA,OAAO,OAAO,gBAAgB,MAAM,YAAY;GAChD,KAAK,OAAO,gBAAgB,IAAI,YAAY;EAC7C,IACC,KAAA;EACH,QAAQ,OAAO;CAChB;CACA,MAAM,iBAAqD,CAAC;CAC5D,KAAK,MAAM,UAAU,SACpB,eAAe,UAAU,mBAAmB,SAAS,SAAS,YAC7D,EAAE,YAAY,OAAO,CACtB;CAGD,OACC,oBAAC,sBAAD;EACiB;EACP;EACA;EACT,kBAAkB;EACP;EACX,QAAQ;CACR,CAAA;AAEH"}
|
|
@@ -27,5 +27,5 @@ interface AnalyticsStatFieldProps {
|
|
|
27
27
|
*/
|
|
28
28
|
declare const AnalyticsStatField: (props: AnalyticsStatFieldProps) => Promise<import("react/jsx-runtime").JSX.Element>;
|
|
29
29
|
//#endregion
|
|
30
|
-
export { AnalyticsStatField };
|
|
30
|
+
export { AnalyticsStatField, StatFieldI18n };
|
|
31
31
|
//# sourceMappingURL=AnalyticsStatField.d.ts.map
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { keys } from "../translations/keys.js";
|
|
2
2
|
import { asTranslate } from "../translations/server.js";
|
|
3
|
+
import { readForField } from "./readForDocument.js";
|
|
3
4
|
import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
5
|
+
import { AnalyticsEmptyState, isNewDocumentAnalytics } from "./emptyState.js";
|
|
4
6
|
import { formatMetricValue } from "./format.js";
|
|
5
|
-
import { readForField } from "./readForDocument.js";
|
|
6
7
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
7
8
|
//#region src/fields/AnalyticsStatField.tsx
|
|
8
9
|
const resolveMetricLabel = (override, i18n, fallback) => {
|
|
@@ -64,10 +65,20 @@ const AnalyticsStatField = async (props) => {
|
|
|
64
65
|
adapterId,
|
|
65
66
|
now: /* @__PURE__ */ new Date()
|
|
66
67
|
});
|
|
68
|
+
if (isNewDocumentAnalytics(result)) return /* @__PURE__ */ jsx("div", {
|
|
69
|
+
className: "field-type",
|
|
70
|
+
children: /* @__PURE__ */ jsx(AnalyticsEmptyState, {
|
|
71
|
+
isNew: true,
|
|
72
|
+
children: t(keys.stateNew)
|
|
73
|
+
})
|
|
74
|
+
});
|
|
67
75
|
if (result.status !== "ok") return /* @__PURE__ */ jsx("div", {
|
|
68
76
|
className: "field-type",
|
|
69
77
|
style: { opacity: .6 },
|
|
70
|
-
children:
|
|
78
|
+
children: /* @__PURE__ */ jsx(AnalyticsEmptyState, {
|
|
79
|
+
isNew: false,
|
|
80
|
+
children: t(STATE_KEYS[result.status])
|
|
81
|
+
})
|
|
71
82
|
});
|
|
72
83
|
return /* @__PURE__ */ jsxs("div", {
|
|
73
84
|
className: "field-type",
|
|
@@ -88,6 +99,6 @@ const AnalyticsStatField = async (props) => {
|
|
|
88
99
|
});
|
|
89
100
|
};
|
|
90
101
|
//#endregion
|
|
91
|
-
export { AnalyticsStatField };
|
|
102
|
+
export { AnalyticsStatField, resolveMetricLabel };
|
|
92
103
|
|
|
93
104
|
//# sourceMappingURL=AnalyticsStatField.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsStatField.js","names":[],"sources":["../../src/fields/AnalyticsStatField.tsx"],"sourcesContent":["import type { LabelFunction, PayloadRequest } from 'payload'\nimport type { CSSProperties } from 'react'\nimport type { BindingDoc } from '../binding/types'\nimport type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport type { AnalyticsMetricLabel, AnalyticsMetricLabels } from './factories'\nimport { formatMetricValue } from './format'\nimport { type FieldReadStatus, readForField } from './readForDocument'\n\
|
|
1
|
+
{"version":3,"file":"AnalyticsStatField.js","names":[],"sources":["../../src/fields/AnalyticsStatField.tsx"],"sourcesContent":["import type { LabelFunction, PayloadRequest } from 'payload'\nimport type { CSSProperties } from 'react'\nimport type { BindingDoc } from '../binding/types'\nimport type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { AnalyticsEmptyState, isNewDocumentAnalytics } from './emptyState'\nimport type { AnalyticsMetricLabel, AnalyticsMetricLabels } from './factories'\nimport { formatMetricValue } from './format'\nimport { type FieldReadStatus, readForField } from './readForDocument'\n\nexport type StatFieldI18n = { t: unknown; language?: string }\n\ninterface AnalyticsStatFieldProps {\n\treq: PayloadRequest\n\tdata: BindingDoc\n\tcollectionSlug: string\n\ti18n: StatFieldI18n\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\tvariant: 'stat' | 'row'\n\tadapterId?: string\n\tlabels?: AnalyticsMetricLabels\n}\n\nexport const resolveMetricLabel = (\n\toverride: AnalyticsMetricLabel | undefined,\n\ti18n: StatFieldI18n,\n\tfallback: () => string\n): string => {\n\tif (typeof override === 'function') {\n\t\treturn override({ i18n, t: i18n.t } as Parameters<LabelFunction>[0])\n\t}\n\tif (typeof override === 'string') return override\n\tif (override) {\n\t\tconst language = i18n.language ?? 'en'\n\t\treturn override[language] ?? override.en ?? fallback()\n\t}\n\treturn fallback()\n}\n\nconst STATE_KEYS: Record<Exclude<FieldReadStatus, 'ok'>, TranslationKey> = {\n\t'no-path': keys.stateNoData,\n\t'not-bound': keys.stateNotBound,\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n}\n\nconst wrapStyle: CSSProperties = {\n\tdisplay: 'flex',\n\tflexWrap: 'wrap',\n\tgap: 'var(--base, 1rem)',\n\talignItems: 'flex-end',\n}\nconst cardStyle: CSSProperties = { display: 'flex', flexDirection: 'column', gap: '0.25rem' }\nconst labelStyle: CSSProperties = { fontSize: '0.75rem', opacity: 0.6, textTransform: 'uppercase' }\nconst valueStyle: CSSProperties = { fontSize: '1.5rem', fontWeight: 600, lineHeight: 1.1 }\nconst captionStyle: CSSProperties = { fontSize: '0.75rem', opacity: 0.5, width: '100%' }\n\n/**\n * Read-only server component for a per-document analytics stat (or row of stats).\n * Resolves the document's bound path, reads through the surfacing engine, and renders\n * static markup. Interactivity (timeframe picker, refresh) is intentionally deferred.\n */\nexport const AnalyticsStatField = async (props: AnalyticsStatFieldProps) => {\n\tconst { req, data, collectionSlug, i18n, metrics, timeframe, adapterId, labels } = props\n\tconst t = asTranslate(i18n.t)\n\tconst locale = i18n.language ?? 'en-US'\n\n\tconst result = await readForField({\n\t\treq,\n\t\tcollectionSlug,\n\t\tdata,\n\t\tmetrics,\n\t\ttimeframe,\n\t\tadapterId,\n\t\tnow: new Date(),\n\t})\n\n\tif (isNewDocumentAnalytics(result)) {\n\t\treturn (\n\t\t\t<div className=\"field-type\">\n\t\t\t\t<AnalyticsEmptyState isNew>{t(keys.stateNew)}</AnalyticsEmptyState>\n\t\t\t</div>\n\t\t)\n\t}\n\tif (result.status !== 'ok') {\n\t\treturn (\n\t\t\t<div className=\"field-type\" style={{ opacity: 0.6 }}>\n\t\t\t\t<AnalyticsEmptyState isNew={false}>{t(STATE_KEYS[result.status])}</AnalyticsEmptyState>\n\t\t\t</div>\n\t\t)\n\t}\n\n\treturn (\n\t\t<div className=\"field-type\" style={wrapStyle}>\n\t\t\t{result.supportedMetrics.map((metric) => (\n\t\t\t\t<div key={metric} style={cardStyle}>\n\t\t\t\t\t<span style={labelStyle}>\n\t\t\t\t\t\t{resolveMetricLabel(labels?.[metric], i18n, () => t(METRIC_KEYS[metric]))}\n\t\t\t\t\t</span>\n\t\t\t\t\t<span style={valueStyle}>\n\t\t\t\t\t\t{formatMetricValue(metric, result.metrics[metric] ?? 0, locale)}\n\t\t\t\t\t</span>\n\t\t\t\t</div>\n\t\t\t))}\n\t\t\t<span style={captionStyle}>{t(TIMEFRAME_KEYS[timeframe])}</span>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;AA2BA,MAAa,sBACZ,UACA,MACA,aACY;CACZ,IAAI,OAAO,aAAa,YACvB,OAAO,SAAS;EAAE;EAAM,GAAG,KAAK;CAAE,CAAiC;CAEpE,IAAI,OAAO,aAAa,UAAU,OAAO;CACzC,IAAI,UAEH,OAAO,SADU,KAAK,YAAY,SACL,SAAS,MAAM,SAAS;CAEtD,OAAO,SA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;GACnE,CAAA,GACN,oBAAC,QAAD;IAAM,OAAO;cACX,kBAAkB,QAAQ,OAAO,QAAQ,WAAW,GAAG,MAAM;GACzD,CAAA,CACF;KAPK,MAOL,CACL,GACD,oBAAC,QAAD;GAAM,OAAO;aAAe,EAAE,eAAe,UAAU;EAAQ,CAAA,CAC3D;;AAEP"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { jsx } from "react/jsx-runtime";
|
|
2
|
+
//#region src/fields/emptyState.tsx
|
|
3
|
+
/**
|
|
4
|
+
* A per-document read that has nothing to chart yet: either no path resolved (an unsaved
|
|
5
|
+
* or unbound document) or a bound page that has not accumulated a single tracked metric.
|
|
6
|
+
* Both read as "new" to the editor, distinct from a configuration state (not bound, no
|
|
7
|
+
* provider, unavailable) which is a message about setup, not an empty page.
|
|
8
|
+
*/
|
|
9
|
+
const isNewDocumentAnalytics = (result) => {
|
|
10
|
+
if (result.status === "no-path") return true;
|
|
11
|
+
if (result.status !== "ok") return false;
|
|
12
|
+
return result.supportedMetrics.every((metric) => !(result.metrics[metric] ?? 0));
|
|
13
|
+
};
|
|
14
|
+
const pillStyle = {
|
|
15
|
+
display: "inline-flex",
|
|
16
|
+
alignItems: "center",
|
|
17
|
+
padding: "0.125rem 0.5rem",
|
|
18
|
+
borderRadius: "999px",
|
|
19
|
+
fontSize: "0.6875rem",
|
|
20
|
+
fontWeight: 600,
|
|
21
|
+
letterSpacing: "0.03em",
|
|
22
|
+
color: "var(--theme-elevation-500)",
|
|
23
|
+
background: "var(--theme-elevation-100)"
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Empty-state marker for a per-document analytics surface. A new or dataless document
|
|
27
|
+
* shows a muted "New" pill; a configuration state shows its message inline. Free of client
|
|
28
|
+
* hooks so both the server stat field and the client panel render it the same way; the
|
|
29
|
+
* `analytics-empty-state` classes are stable hooks for overriding the look.
|
|
30
|
+
*/
|
|
31
|
+
function AnalyticsEmptyState({ isNew, children }) {
|
|
32
|
+
if (isNew) return /* @__PURE__ */ jsx("span", {
|
|
33
|
+
className: "analytics-empty-state analytics-empty-state--new",
|
|
34
|
+
style: pillStyle,
|
|
35
|
+
children
|
|
36
|
+
});
|
|
37
|
+
return /* @__PURE__ */ jsx("div", {
|
|
38
|
+
className: "analytics-empty-state",
|
|
39
|
+
style: { color: "var(--theme-elevation-400)" },
|
|
40
|
+
children
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { AnalyticsEmptyState, isNewDocumentAnalytics };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=emptyState.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emptyState.js","names":[],"sources":["../../src/fields/emptyState.tsx"],"sourcesContent":["import type { CSSProperties, ReactNode } from 'react'\nimport type { MetricKey } from '../core/contract'\nimport type { FieldReadStatus } from './readForDocument'\n\n/**\n * A per-document read that has nothing to chart yet: either no path resolved (an unsaved\n * or unbound document) or a bound page that has not accumulated a single tracked metric.\n * Both read as \"new\" to the editor, distinct from a configuration state (not bound, no\n * provider, unavailable) which is a message about setup, not an empty page.\n */\nexport const isNewDocumentAnalytics = (result: {\n\tstatus: FieldReadStatus\n\tmetrics: Partial<Record<MetricKey, number>>\n\tsupportedMetrics: MetricKey[]\n}): boolean => {\n\tif (result.status === 'no-path') {\n\t\treturn true\n\t}\n\tif (result.status !== 'ok') {\n\t\treturn false\n\t}\n\treturn result.supportedMetrics.every((metric) => !(result.metrics[metric] ?? 0))\n}\n\nconst pillStyle: CSSProperties = {\n\tdisplay: 'inline-flex',\n\talignItems: 'center',\n\tpadding: '0.125rem 0.5rem',\n\tborderRadius: '999px',\n\tfontSize: '0.6875rem',\n\tfontWeight: 600,\n\tletterSpacing: '0.03em',\n\tcolor: 'var(--theme-elevation-500)',\n\tbackground: 'var(--theme-elevation-100)',\n}\n\n/**\n * Empty-state marker for a per-document analytics surface. A new or dataless document\n * shows a muted \"New\" pill; a configuration state shows its message inline. Free of client\n * hooks so both the server stat field and the client panel render it the same way; the\n * `analytics-empty-state` classes are stable hooks for overriding the look.\n */\nexport function AnalyticsEmptyState({ isNew, children }: { isNew: boolean; children: ReactNode }) {\n\tif (isNew) {\n\t\treturn (\n\t\t\t<span className=\"analytics-empty-state analytics-empty-state--new\" style={pillStyle}>\n\t\t\t\t{children}\n\t\t\t</span>\n\t\t)\n\t}\n\treturn (\n\t\t<div className=\"analytics-empty-state\" style={{ color: 'var(--theme-elevation-400)' }}>\n\t\t\t{children}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,0BAA0B,WAIxB;CACd,IAAI,OAAO,WAAW,WACrB,OAAO;CAER,IAAI,OAAO,WAAW,MACrB,OAAO;CAER,OAAO,OAAO,iBAAiB,OAAO,WAAW,EAAE,OAAO,QAAQ,WAAW,EAAE;AAChF;AAEA,MAAM,YAA2B;CAChC,SAAS;CACT,YAAY;CACZ,SAAS;CACT,cAAc;CACd,UAAU;CACV,YAAY;CACZ,eAAe;CACf,OAAO;CACP,YAAY;AACb;;;;;;;AAQA,SAAgB,oBAAoB,EAAE,OAAO,YAAqD;CACjG,IAAI,OACH,OACC,oBAAC,QAAD;EAAM,WAAU;EAAmD,OAAO;EACxE;CACI,CAAA;CAGR,OACC,oBAAC,OAAD;EAAK,WAAU;EAAwB,OAAO,EAAE,OAAO,6BAA6B;EAClF;CACG,CAAA;AAEP"}
|
|
@@ -36,13 +36,21 @@ type AnalyticsTabOptions = {
|
|
|
36
36
|
label?: UnnamedTab['label']; /** Optional tab description. */
|
|
37
37
|
description?: UnnamedTab['description']; /** Per-metric card label overrides. */
|
|
38
38
|
labels?: AnalyticsMetricLabels;
|
|
39
|
+
/**
|
|
40
|
+
* The tab renders the interactive panel (timeframe picker, comparison, daily
|
|
41
|
+
* trend) by default; false renders the static stats row instead.
|
|
42
|
+
*/
|
|
43
|
+
interactive?: boolean;
|
|
39
44
|
};
|
|
40
45
|
declare const analyticsStat: (options: AnalyticsStatOptions) => UIField;
|
|
41
46
|
declare const analyticsStatRow: (options?: AnalyticsStatRowOptions) => UIField;
|
|
42
47
|
declare const analyticsFields: (options?: AnalyticsFieldsOptions) => UIField[];
|
|
43
48
|
/**
|
|
44
|
-
* An unnamed "Analytics" `Tab` to push into your own tabs field's `tabs` array
|
|
45
|
-
*
|
|
49
|
+
* An unnamed "Analytics" `Tab` to push into your own tabs field's `tabs` array: the
|
|
50
|
+
* interactive panel (timeframe picker, comparison deltas, daily trend) backed by the
|
|
51
|
+
* authenticated document endpoint. Pass `interactive: false` for the static stats row
|
|
52
|
+
* ({@link analyticsStatRow}) instead. Use {@link analyticsTabsField} for a standalone
|
|
53
|
+
* tabs field wrapping this tab.
|
|
46
54
|
*/
|
|
47
55
|
declare const analyticsTab: (options?: AnalyticsTabOptions) => Tab;
|
|
48
56
|
/** A ready-made tabs field containing a single {@link analyticsTab}. */
|
package/dist/fields/factories.js
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
import { keys } from "../translations/keys.js";
|
|
2
2
|
import { labelForKey } from "../translations/server.js";
|
|
3
|
+
import { de } from "../translations/de.js";
|
|
4
|
+
import { en } from "../translations/en.js";
|
|
3
5
|
//#region src/fields/factories.ts
|
|
6
|
+
/** UI fields accept static labels only, so the tab label ships as a locale map. */
|
|
7
|
+
const ANALYTICS_LABEL = {
|
|
8
|
+
de: de[keys.tabAnalytics],
|
|
9
|
+
en: en[keys.tabAnalytics]
|
|
10
|
+
};
|
|
4
11
|
const RSC_PATH = "@10x-media/analytics/rsc#AnalyticsStatField";
|
|
12
|
+
const PANEL_PATH = "@10x-media/analytics/rsc#AnalyticsPanelField";
|
|
5
13
|
const DEFAULT_ROW_METRICS = [
|
|
6
14
|
"pageviews",
|
|
7
15
|
"visitors",
|
|
@@ -11,8 +19,10 @@ const DEFAULT_ROW_METRICS = [
|
|
|
11
19
|
const statField = (name, serverProps, position) => ({
|
|
12
20
|
name,
|
|
13
21
|
type: "ui",
|
|
22
|
+
label: ANALYTICS_LABEL,
|
|
14
23
|
admin: {
|
|
15
24
|
...position ? { position } : {},
|
|
25
|
+
disableListColumn: true,
|
|
16
26
|
components: { Field: {
|
|
17
27
|
path: RSC_PATH,
|
|
18
28
|
serverProps
|
|
@@ -41,18 +51,37 @@ const analyticsFields = (options = {}) => (options.metrics ?? DEFAULT_ROW_METRIC
|
|
|
41
51
|
label: options.labels?.[metric]
|
|
42
52
|
}));
|
|
43
53
|
/**
|
|
44
|
-
* An unnamed "Analytics" `Tab` to push into your own tabs field's `tabs` array
|
|
45
|
-
*
|
|
54
|
+
* An unnamed "Analytics" `Tab` to push into your own tabs field's `tabs` array: the
|
|
55
|
+
* interactive panel (timeframe picker, comparison deltas, daily trend) backed by the
|
|
56
|
+
* authenticated document endpoint. Pass `interactive: false` for the static stats row
|
|
57
|
+
* ({@link analyticsStatRow}) instead. Use {@link analyticsTabsField} for a standalone
|
|
58
|
+
* tabs field wrapping this tab.
|
|
46
59
|
*/
|
|
47
60
|
const analyticsTab = (options = {}) => ({
|
|
48
61
|
label: options.label ?? labelForKey(keys.tabAnalytics),
|
|
49
62
|
...options.description ? { description: options.description } : {},
|
|
50
|
-
fields: [analyticsStatRow({
|
|
63
|
+
fields: [options.interactive === false ? analyticsStatRow({
|
|
51
64
|
metrics: options.metrics,
|
|
52
65
|
timeframe: options.timeframe,
|
|
53
66
|
adapter: options.adapter,
|
|
54
67
|
labels: options.labels
|
|
55
|
-
})
|
|
68
|
+
}) : {
|
|
69
|
+
name: "analytics_panel",
|
|
70
|
+
type: "ui",
|
|
71
|
+
label: ANALYTICS_LABEL,
|
|
72
|
+
admin: {
|
|
73
|
+
disableListColumn: true,
|
|
74
|
+
components: { Field: {
|
|
75
|
+
path: PANEL_PATH,
|
|
76
|
+
serverProps: {
|
|
77
|
+
metrics: options.metrics ?? DEFAULT_ROW_METRICS,
|
|
78
|
+
timeframe: options.timeframe ?? "last30days",
|
|
79
|
+
adapterId: options.adapter,
|
|
80
|
+
labels: options.labels
|
|
81
|
+
}
|
|
82
|
+
} }
|
|
83
|
+
}
|
|
84
|
+
}]
|
|
56
85
|
});
|
|
57
86
|
/** A ready-made tabs field containing a single {@link analyticsTab}. */
|
|
58
87
|
const analyticsTabsField = (options = {}) => ({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factories.js","names":[],"sources":["../../src/fields/factories.ts"],"sourcesContent":["import type { LabelFunction, StaticLabel, Tab, TabsField, UIField, UnnamedTab } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { keys } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\n\nconst RSC_PATH = '@10x-media/analytics/rsc#AnalyticsStatField'\n\nconst DEFAULT_ROW_METRICS: MetricKey[] = ['pageviews', 'visitors', 'sessions', 'avgDuration']\n\n/**\n * A metric card label override: a plain string, a locale-to-label map, or a Payload\n * label function receiving `{ t, i18n }`. Defaults to the metric's translated name.\n */\nexport type AnalyticsMetricLabel = LabelFunction | StaticLabel\n\nexport type AnalyticsMetricLabels = Partial<Record<MetricKey, AnalyticsMetricLabel>>\n\ninterface StatServerProps {\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\tvariant: 'stat' | 'row'\n\tadapterId?: string\n\tlabels?: AnalyticsMetricLabels\n}\n\ntype BaseFieldOptions = {\n\ttimeframe?: TimeframePreset\n\tadapter?: string\n\tposition?: 'sidebar'\n\tname?: string\n}\n\nexport type AnalyticsStatOptions = BaseFieldOptions & {\n\tmetric: MetricKey\n\t/** Overrides the stat's metric card label. */\n\tlabel?: AnalyticsMetricLabel\n}\n\nexport type AnalyticsStatRowOptions = BaseFieldOptions & {\n\tmetrics?: MetricKey[]\n\t/** Per-metric card label overrides. */\n\tlabels?: AnalyticsMetricLabels\n}\n\nexport type AnalyticsFieldsOptions = {\n\tmetrics?: MetricKey[]\n\ttimeframe?: TimeframePreset\n\tadapter?: string\n\t/** Per-metric card label overrides. */\n\tlabels?: AnalyticsMetricLabels\n}\n\nexport type AnalyticsTabOptions = {\n\tmetrics?: MetricKey[]\n\ttimeframe?: TimeframePreset\n\tadapter?: string\n\t/** Overrides the tab label (default: the translated \"Analytics\"). */\n\tlabel?: UnnamedTab['label']\n\t/** Optional tab description. */\n\tdescription?: UnnamedTab['description']\n\t/** Per-metric card label overrides. */\n\tlabels?: AnalyticsMetricLabels\n}\n\nconst statField = (name: string, serverProps: StatServerProps, position?: 'sidebar'): UIField => ({\n\tname,\n\ttype: 'ui',\n\tadmin: {\n\t\t...(position ? { position } : {}),\n\t\tcomponents: {\n\t\t\tField: { path: RSC_PATH, serverProps },\n\t\t},\n\t},\n})\n\nexport const analyticsStat = (options: AnalyticsStatOptions): UIField =>\n\tstatField(\n\t\toptions.name ?? `analytics_${options.metric}`,\n\t\t{\n\t\t\tmetrics: [options.metric],\n\t\t\ttimeframe: options.timeframe ?? 'last30days',\n\t\t\tvariant: 'stat',\n\t\t\tadapterId: options.adapter,\n\t\t\t...(options.label ? { labels: { [options.metric]: options.label } } : {}),\n\t\t},\n\t\toptions.position\n\t)\n\nexport const analyticsStatRow = (options: AnalyticsStatRowOptions = {}): UIField =>\n\tstatField(\n\t\toptions.name ?? 'analytics_stats',\n\t\t{\n\t\t\tmetrics: options.metrics ?? DEFAULT_ROW_METRICS,\n\t\t\ttimeframe: options.timeframe ?? 'last30days',\n\t\t\tvariant: 'row',\n\t\t\tadapterId: options.adapter,\n\t\t\tlabels: options.labels,\n\t\t},\n\t\toptions.position\n\t)\n\nexport const analyticsFields = (options: AnalyticsFieldsOptions = {}): UIField[] =>\n\t(options.metrics ?? DEFAULT_ROW_METRICS).map((metric) =>\n\t\tanalyticsStat({\n\t\t\tmetric,\n\t\t\ttimeframe: options.timeframe,\n\t\t\tadapter: options.adapter,\n\t\t\tname: `analytics_${metric}`,\n\t\t\tlabel: options.labels?.[metric],\n\t\t})\n\t)\n\n/**\n * An unnamed \"Analytics\" `Tab` to push into your own tabs field's `tabs` array
|
|
1
|
+
{"version":3,"file":"factories.js","names":[],"sources":["../../src/fields/factories.ts"],"sourcesContent":["import type { LabelFunction, StaticLabel, Tab, TabsField, UIField, UnnamedTab } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { de } from '../translations/de'\nimport { en } from '../translations/en'\nimport { keys } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\n\n/** UI fields accept static labels only, so the tab label ships as a locale map. */\nconst ANALYTICS_LABEL: Record<string, string> = {\n\tde: de[keys.tabAnalytics],\n\ten: en[keys.tabAnalytics],\n}\n\nconst RSC_PATH = '@10x-media/analytics/rsc#AnalyticsStatField'\nconst PANEL_PATH = '@10x-media/analytics/rsc#AnalyticsPanelField'\n\nconst DEFAULT_ROW_METRICS: MetricKey[] = ['pageviews', 'visitors', 'sessions', 'avgDuration']\n\n/**\n * A metric card label override: a plain string, a locale-to-label map, or a Payload\n * label function receiving `{ t, i18n }`. Defaults to the metric's translated name.\n */\nexport type AnalyticsMetricLabel = LabelFunction | StaticLabel\n\nexport type AnalyticsMetricLabels = Partial<Record<MetricKey, AnalyticsMetricLabel>>\n\ninterface StatServerProps {\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\tvariant: 'stat' | 'row'\n\tadapterId?: string\n\tlabels?: AnalyticsMetricLabels\n}\n\ntype BaseFieldOptions = {\n\ttimeframe?: TimeframePreset\n\tadapter?: string\n\tposition?: 'sidebar'\n\tname?: string\n}\n\nexport type AnalyticsStatOptions = BaseFieldOptions & {\n\tmetric: MetricKey\n\t/** Overrides the stat's metric card label. */\n\tlabel?: AnalyticsMetricLabel\n}\n\nexport type AnalyticsStatRowOptions = BaseFieldOptions & {\n\tmetrics?: MetricKey[]\n\t/** Per-metric card label overrides. */\n\tlabels?: AnalyticsMetricLabels\n}\n\nexport type AnalyticsFieldsOptions = {\n\tmetrics?: MetricKey[]\n\ttimeframe?: TimeframePreset\n\tadapter?: string\n\t/** Per-metric card label overrides. */\n\tlabels?: AnalyticsMetricLabels\n}\n\nexport type AnalyticsTabOptions = {\n\tmetrics?: MetricKey[]\n\ttimeframe?: TimeframePreset\n\tadapter?: string\n\t/** Overrides the tab label (default: the translated \"Analytics\"). */\n\tlabel?: UnnamedTab['label']\n\t/** Optional tab description. */\n\tdescription?: UnnamedTab['description']\n\t/** Per-metric card label overrides. */\n\tlabels?: AnalyticsMetricLabels\n\t/**\n\t * The tab renders the interactive panel (timeframe picker, comparison, daily\n\t * trend) by default; false renders the static stats row instead.\n\t */\n\tinteractive?: boolean\n}\n\nconst statField = (name: string, serverProps: StatServerProps, position?: 'sidebar'): UIField => ({\n\tname,\n\ttype: 'ui',\n\tlabel: ANALYTICS_LABEL,\n\tadmin: {\n\t\t...(position ? { position } : {}),\n\t\t// Read-only display fields have no cell value; a list column would render empty.\n\t\tdisableListColumn: true,\n\t\tcomponents: {\n\t\t\tField: { path: RSC_PATH, serverProps },\n\t\t},\n\t},\n})\n\nexport const analyticsStat = (options: AnalyticsStatOptions): UIField =>\n\tstatField(\n\t\toptions.name ?? `analytics_${options.metric}`,\n\t\t{\n\t\t\tmetrics: [options.metric],\n\t\t\ttimeframe: options.timeframe ?? 'last30days',\n\t\t\tvariant: 'stat',\n\t\t\tadapterId: options.adapter,\n\t\t\t...(options.label ? { labels: { [options.metric]: options.label } } : {}),\n\t\t},\n\t\toptions.position\n\t)\n\nexport const analyticsStatRow = (options: AnalyticsStatRowOptions = {}): UIField =>\n\tstatField(\n\t\toptions.name ?? 'analytics_stats',\n\t\t{\n\t\t\tmetrics: options.metrics ?? DEFAULT_ROW_METRICS,\n\t\t\ttimeframe: options.timeframe ?? 'last30days',\n\t\t\tvariant: 'row',\n\t\t\tadapterId: options.adapter,\n\t\t\tlabels: options.labels,\n\t\t},\n\t\toptions.position\n\t)\n\nexport const analyticsFields = (options: AnalyticsFieldsOptions = {}): UIField[] =>\n\t(options.metrics ?? DEFAULT_ROW_METRICS).map((metric) =>\n\t\tanalyticsStat({\n\t\t\tmetric,\n\t\t\ttimeframe: options.timeframe,\n\t\t\tadapter: options.adapter,\n\t\t\tname: `analytics_${metric}`,\n\t\t\tlabel: options.labels?.[metric],\n\t\t})\n\t)\n\n/**\n * An unnamed \"Analytics\" `Tab` to push into your own tabs field's `tabs` array: the\n * interactive panel (timeframe picker, comparison deltas, daily trend) backed by the\n * authenticated document endpoint. Pass `interactive: false` for the static stats row\n * ({@link analyticsStatRow}) instead. Use {@link analyticsTabsField} for a standalone\n * tabs field wrapping this tab.\n */\nexport const analyticsTab = (options: AnalyticsTabOptions = {}): Tab => ({\n\tlabel: options.label ?? labelForKey(keys.tabAnalytics),\n\t...(options.description ? { description: options.description } : {}),\n\tfields: [\n\t\toptions.interactive === false\n\t\t\t? analyticsStatRow({\n\t\t\t\t\tmetrics: options.metrics,\n\t\t\t\t\ttimeframe: options.timeframe,\n\t\t\t\t\tadapter: options.adapter,\n\t\t\t\t\tlabels: options.labels,\n\t\t\t\t})\n\t\t\t: {\n\t\t\t\t\tname: 'analytics_panel',\n\t\t\t\t\ttype: 'ui',\n\t\t\t\t\tlabel: ANALYTICS_LABEL,\n\t\t\t\t\tadmin: {\n\t\t\t\t\t\tdisableListColumn: true,\n\t\t\t\t\t\tcomponents: {\n\t\t\t\t\t\t\tField: {\n\t\t\t\t\t\t\t\tpath: PANEL_PATH,\n\t\t\t\t\t\t\t\tserverProps: {\n\t\t\t\t\t\t\t\t\tmetrics: options.metrics ?? DEFAULT_ROW_METRICS,\n\t\t\t\t\t\t\t\t\ttimeframe: options.timeframe ?? 'last30days',\n\t\t\t\t\t\t\t\t\tadapterId: options.adapter,\n\t\t\t\t\t\t\t\t\tlabels: options.labels,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t],\n})\n\n/** A ready-made tabs field containing a single {@link analyticsTab}. */\nexport const analyticsTabsField = (options: AnalyticsTabOptions = {}): TabsField => ({\n\ttype: 'tab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B,iBAAiB;EACjB,SAAS,QAAQ;EACjB,WAAW,QAAQ;EACnB,SAAS,QAAQ;EACjB,QAAQ,QAAQ;CACjB,CAAC,IACA;EACA,MAAM;EACN,MAAM;EACN,OAAO;EACP,OAAO;GACN,mBAAmB;GACnB,YAAY,EACX,OAAO;IACN,MAAM;IACN,aAAa;KACZ,SAAS,QAAQ,WAAW;KAC5B,WAAW,QAAQ,aAAa;KAChC,WAAW,QAAQ;KACnB,QAAQ,QAAQ;IACjB;GACD,EACD;EACD;CACD,CACH;AACD;;AAGA,MAAa,sBAAsB,UAA+B,CAAC,OAAkB;CACpF,MAAM;CACN,MAAM,CAAC,aAAa,OAAO,CAAC;AAC7B"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { DateRange, MetricKey } from "../core/contract.js";
|
|
2
|
+
import { BindingDoc } from "../binding/types.js";
|
|
3
|
+
import { TimeframePreset } from "../timeframe/presets.js";
|
|
4
|
+
import { SeriesPoint } from "../widgets/readForWidgetSeries.js";
|
|
5
|
+
import { PayloadRequest } from "payload";
|
|
6
|
+
|
|
7
|
+
//#region src/fields/readForDocument.d.ts
|
|
8
|
+
type FieldReadStatus = 'ok' | 'no-path' | 'not-bound' | 'not-configured' | 'unavailable';
|
|
9
|
+
interface FieldReadResult {
|
|
10
|
+
status: FieldReadStatus;
|
|
11
|
+
adapterId: string;
|
|
12
|
+
dateRange: DateRange;
|
|
13
|
+
/** The reporting timezone the read resolved in; the trend axis buckets in it. */
|
|
14
|
+
timezone: string;
|
|
15
|
+
metrics: Partial<Record<MetricKey, number>>;
|
|
16
|
+
/** Requested metrics the adapter supports, in request order; the set actually read. */
|
|
17
|
+
supportedMetrics: MetricKey[];
|
|
18
|
+
/** Requested metrics the adapter cannot serve, dropped from the read. */
|
|
19
|
+
droppedMetrics: MetricKey[];
|
|
20
|
+
/** Previous-window totals, present only when comparison was requested and supported. */
|
|
21
|
+
previousMetrics?: Partial<Record<MetricKey, number>>;
|
|
22
|
+
/** The previous comparable window, present only when comparison ran. */
|
|
23
|
+
comparisonRange?: DateRange;
|
|
24
|
+
/** Per-day series for the first supported metric, present only when requested. */
|
|
25
|
+
points?: SeriesPoint[];
|
|
26
|
+
}
|
|
27
|
+
interface ReadForFieldArgs {
|
|
28
|
+
req: PayloadRequest;
|
|
29
|
+
collectionSlug: string;
|
|
30
|
+
data: BindingDoc;
|
|
31
|
+
metrics: MetricKey[];
|
|
32
|
+
timeframe: TimeframePreset;
|
|
33
|
+
/** Overrides the preset window (custom range). */
|
|
34
|
+
range?: DateRange;
|
|
35
|
+
adapterId?: string;
|
|
36
|
+
now: Date;
|
|
37
|
+
/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */
|
|
38
|
+
scope?: string | null;
|
|
39
|
+
/** Also read the previous comparable window when the adapter supports comparison. */
|
|
40
|
+
compare?: boolean;
|
|
41
|
+
/** Also read a daily series for the first supported metric when the adapter can. */
|
|
42
|
+
series?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Resolve a document's analytics for one display field: look up the runtime, resolve
|
|
46
|
+
* the bound path, capability-gate the requested metrics against the active adapter,
|
|
47
|
+
* then read through the surfacing engine. Returns a discriminated status so the
|
|
48
|
+
* rendering component can show the right empty state without throwing.
|
|
49
|
+
*
|
|
50
|
+
* A metric the adapter does not support is dropped (with one warning per field
|
|
51
|
+
* render), not fatal; `unavailable` is returned only when no requested metric
|
|
52
|
+
* survives or the adapter cannot query per page at all.
|
|
53
|
+
*/
|
|
54
|
+
declare const readForField: (args: ReadForFieldArgs) => Promise<FieldReadResult>;
|
|
55
|
+
//#endregion
|
|
56
|
+
export { FieldReadResult, FieldReadStatus, ReadForFieldArgs, readForField };
|
|
57
|
+
//# sourceMappingURL=readForDocument.d.ts.map
|