@10x-media/analytics 1.0.0-beta.7 → 1.0.0-beta.8
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 +48 -0
- package/README.md +8 -2
- package/dist/adapters/ga4/ga4.js +3 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +2 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/capture/slots.js +16 -5
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.d.ts +1 -0
- package/dist/capture/trackerConfig.js +28 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/BarList.d.ts +15 -1
- package/dist/charts/BarList.js +34 -18
- package/dist/charts/BarList.js.map +1 -1
- package/dist/charts/TrendChart.d.ts +16 -3
- package/dist/charts/TrendChart.js +172 -106
- package/dist/charts/TrendChart.js.map +1 -1
- package/dist/charts/bars.d.ts +2 -0
- package/dist/charts/bars.js +2 -1
- package/dist/charts/bars.js.map +1 -1
- package/dist/charts/bucket.js +10 -1
- package/dist/charts/bucket.js.map +1 -1
- package/dist/charts/spline.js +2 -2
- package/dist/charts/spline.js.map +1 -1
- package/dist/charts/styles.js +18 -1
- package/dist/charts/styles.js.map +1 -1
- package/dist/core/cacheKey.js +13 -1
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/contract.d.ts +14 -7
- package/dist/core/contract.js +29 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/granularity.js +1 -1
- package/dist/core/options.d.ts +54 -5
- package/dist/core/options.js +59 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +33 -23
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/serverEvent.d.ts +42 -0
- package/dist/core/serverEvent.js +12 -0
- package/dist/core/serverEvent.js.map +1 -0
- package/dist/exports/client.d.ts +8 -2
- package/dist/exports/client.js +6 -1
- package/dist/exports/rsc.d.ts +5 -1
- package/dist/exports/rsc.js +6 -3
- package/dist/exports/types.d.ts +12 -4
- package/dist/exports/types.js +2 -2
- package/dist/fields/AnalyticsPanelClient.js +1 -1
- package/dist/fields/AnalyticsPanelField.js +1 -1
- package/dist/fields/AnalyticsStatField.js +2 -2
- package/dist/fields/config/MetricSelectField.js +2 -2
- package/dist/fields/config/MetricSelectField.js.map +1 -1
- package/dist/fields/config/SourceSelectField.js +2 -2
- package/dist/fields/config/SourceSelectField.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +5 -1
- package/dist/fields/readForDocument.d.ts +5 -0
- package/dist/fields/readForDocument.js +5 -5
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/GoalSelectField.d.ts +7 -0
- package/dist/goals/GoalSelectField.js +77 -0
- package/dist/goals/GoalSelectField.js.map +1 -0
- package/dist/goals/collection.js +250 -0
- package/dist/goals/collection.js.map +1 -0
- package/dist/goals/currency.js +14 -0
- package/dist/goals/currency.js.map +1 -0
- package/dist/goals/fetchGoals.d.ts +18 -0
- package/dist/goals/fetchGoals.js +29 -0
- package/dist/goals/fetchGoals.js.map +1 -0
- package/dist/goals/goalField.d.ts +31 -0
- package/dist/goals/goalField.js +56 -0
- package/dist/goals/goalField.js.map +1 -0
- package/dist/goals/goalsEndpoint.d.ts +1 -0
- package/dist/goals/goalsEndpoint.js +55 -0
- package/dist/goals/goalsEndpoint.js.map +1 -0
- package/dist/goals/resolver.d.ts +8 -0
- package/dist/goals/resolver.js +147 -0
- package/dist/goals/resolver.js.map +1 -0
- package/dist/goals/trackGoalAction.d.ts +74 -0
- package/dist/goals/trackGoalAction.js +139 -0
- package/dist/goals/trackGoalAction.js.map +1 -0
- package/dist/goals/useAnalyticsGoals.d.ts +20 -0
- package/dist/goals/useAnalyticsGoals.js +67 -0
- package/dist/goals/useAnalyticsGoals.js.map +1 -0
- package/dist/index.d.ts +10 -3
- package/dist/index.js +74 -11
- package/dist/index.js.map +1 -1
- package/dist/native/ingest/device.js +11 -3
- package/dist/native/ingest/device.js.map +1 -1
- package/dist/native/ingest/endpoint.d.ts +1 -0
- package/dist/native/ingest/endpoint.js +2 -17
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.d.ts +20 -0
- package/dist/native/ingest/normalizeEvent.js +3 -2
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/serverTrack.d.ts +20 -0
- package/dist/native/ingest/serverTrack.js +99 -0
- package/dist/native/ingest/serverTrack.js.map +1 -0
- package/dist/native/ingest/validate.js +27 -0
- package/dist/native/ingest/validate.js.map +1 -0
- package/dist/native/nativeAdapter.d.ts +1 -1
- package/dist/native/nativeAdapter.js +21 -10
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/retention/pruneTask.js +1 -1
- package/dist/native/rollups/insertIfNew.js +36 -2
- package/dist/native/rollups/insertIfNew.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +27 -9
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/paths.js +5 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +113 -0
- package/dist/plugin/queryEndpoint.js.map +1 -0
- package/dist/plugin/readContextForRequest.js +71 -0
- package/dist/plugin/readContextForRequest.js.map +1 -0
- package/dist/plugin/realtimeEndpoint.js +6 -3
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/runtime.js +31 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/scopeFieldBoot.js +22 -0
- package/dist/plugin/scopeFieldBoot.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +13 -51
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/plugin/warmTask.js +0 -0
- package/dist/plugin/warmTask.js.map +1 -1
- package/dist/providers/collection.js +15 -9
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/resolver.js.map +1 -1
- package/dist/query/dates.js +64 -0
- package/dist/query/dates.js.map +1 -0
- package/dist/query/errors.d.ts +17 -0
- package/dist/query/errors.js +10 -0
- package/dist/query/errors.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +59 -0
- package/dist/query/fetchQuery.js +110 -0
- package/dist/query/fetchQuery.js.map +1 -0
- package/dist/query/parse.d.ts +22 -0
- package/dist/query/parse.js +168 -0
- package/dist/query/parse.js.map +1 -0
- package/dist/query/response.d.ts +36 -0
- package/dist/timeframe/tz.js +17 -6
- package/dist/timeframe/tz.js.map +1 -1
- package/dist/translations/ar.js +98 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +98 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +98 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +98 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +98 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +98 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +97 -0
- package/dist/translations/keys.js +98 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +98 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +1 -1
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +98 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +98 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +98 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +98 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsNavLink.d.ts +19 -0
- package/dist/view/AnalyticsNavLink.js +40 -0
- package/dist/view/AnalyticsNavLink.js.map +1 -0
- package/dist/view/AnalyticsView.d.ts +23 -0
- package/dist/view/AnalyticsView.js +45 -0
- package/dist/view/AnalyticsView.js.map +1 -0
- package/dist/view/AnalyticsViewClient.d.ts +15 -0
- package/dist/view/AnalyticsViewClient.js +189 -0
- package/dist/view/AnalyticsViewClient.js.map +1 -0
- package/dist/view/authRedirect.js +32 -0
- package/dist/view/authRedirect.js.map +1 -0
- package/dist/view/conversionRate.js +18 -0
- package/dist/view/conversionRate.js.map +1 -0
- package/dist/view/dayRange.js +68 -0
- package/dist/view/dayRange.js.map +1 -0
- package/dist/view/gating.d.ts +1 -0
- package/dist/view/gating.js +105 -0
- package/dist/view/gating.js.map +1 -0
- package/dist/view/labels.js +44 -0
- package/dist/view/labels.js.map +1 -0
- package/dist/view/registerView.js +48 -0
- package/dist/view/registerView.js.map +1 -0
- package/dist/view/sections/Breakdowns.js +157 -0
- package/dist/view/sections/Breakdowns.js.map +1 -0
- package/dist/view/sections/EmptyStates.js +92 -0
- package/dist/view/sections/EmptyStates.js.map +1 -0
- package/dist/view/sections/FilterChips.js +41 -0
- package/dist/view/sections/FilterChips.js.map +1 -0
- package/dist/view/sections/GoalsPanel.js +81 -0
- package/dist/view/sections/GoalsPanel.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +65 -0
- package/dist/view/sections/OverviewCards.js.map +1 -0
- package/dist/view/sections/RealtimeStrip.js +77 -0
- package/dist/view/sections/RealtimeStrip.js.map +1 -0
- package/dist/view/sections/Toolbar.js +179 -0
- package/dist/view/sections/Toolbar.js.map +1 -0
- package/dist/view/sections/Trend.js +119 -0
- package/dist/view/sections/Trend.js.map +1 -0
- package/dist/view/sections/styles.js +74 -0
- package/dist/view/sections/styles.js.map +1 -0
- package/dist/view/state.js +206 -0
- package/dist/view/state.js.map +1 -0
- package/dist/view/useViewQueries.js +150 -0
- package/dist/view/useViewQueries.js.map +1 -0
- package/dist/view/viewProps.d.ts +40 -0
- package/dist/view/viewProps.js +90 -0
- package/dist/view/viewProps.js.map +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +22 -4
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
- package/dist/widgets/AnalyticsGoalsWidget.js +188 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
- package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsMetricWidget.js +35 -12
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +42 -22
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsTrendWidget.js +51 -15
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/WidgetViewLink.js +17 -0
- package/dist/widgets/WidgetViewLink.js.map +1 -0
- package/dist/widgets/breakdownTypes.js +28 -1
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/cardChrome.js +31 -7
- package/dist/widgets/cardChrome.js.map +1 -1
- package/dist/widgets/range.js +43 -12
- package/dist/widgets/range.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +12 -0
- package/dist/widgets/readForWidget.js +6 -5
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +15 -0
- package/dist/widgets/readForWidgetBreakdown.js +10 -7
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +57 -0
- package/dist/widgets/readForWidgetGoals.js +126 -0
- package/dist/widgets/readForWidgetGoals.js.map +1 -0
- package/dist/widgets/readForWidgetSeries.d.ts +13 -0
- package/dist/widgets/readForWidgetSeries.js +30 -12
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +49 -6
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.js +12 -1
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.d.ts +22 -0
- package/dist/widgets/viewLink.js +83 -0
- package/dist/widgets/viewLink.js.map +1 -0
- package/package.json +9 -4
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { getRuntime, resolveGoalsDetailedFor, resolveTimezoneFor } from "../plugin/runtime.js";
|
|
2
|
+
import { resolveTimeframe } from "../timeframe/presets.js";
|
|
3
|
+
import { resolveReadContext } from "../core/scopedRead.js";
|
|
4
|
+
import { previousWindow } from "./comparison.js";
|
|
5
|
+
import { readForWidget } from "./readForWidget.js";
|
|
6
|
+
import { readForWidgetBreakdown } from "./readForWidgetBreakdown.js";
|
|
7
|
+
import { conversionRate } from "../view/conversionRate.js";
|
|
8
|
+
//#region src/widgets/readForWidgetGoals.ts
|
|
9
|
+
/**
|
|
10
|
+
* How much wider than the table the previous window is read. Both windows rank by their own
|
|
11
|
+
* conversions, so a goal in today's top rows may sit well below them in the previous window;
|
|
12
|
+
* reading only as many rows as the table shows would drop exactly those deltas. Capped at
|
|
13
|
+
* the bound every analytics query is held to.
|
|
14
|
+
*/
|
|
15
|
+
const PREVIOUS_LIMIT_FACTOR = 4;
|
|
16
|
+
const previousLimit = (limit) => Math.min(limit * PREVIOUS_LIMIT_FACTOR, 500);
|
|
17
|
+
/**
|
|
18
|
+
* Goal names for the read's own scope. A resolver that throws must not cost the widget its
|
|
19
|
+
* table, so the rows fall back to their slugs.
|
|
20
|
+
*/
|
|
21
|
+
const goalNames = async (runtime, req, scope) => {
|
|
22
|
+
try {
|
|
23
|
+
const resolved = await resolveGoalsDetailedFor(runtime, req, scope);
|
|
24
|
+
return new Map(resolved.map(({ goal }) => [goal.slug, goal.name]));
|
|
25
|
+
} catch (err) {
|
|
26
|
+
req.payload.logger?.warn(`analytics: widget goal names failed to resolve: ${String(err)}`);
|
|
27
|
+
return /* @__PURE__ */ new Map();
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* The goals table behind the goals widget: conversions per goal over the window, each with
|
|
32
|
+
* its revenue, its share of the site's visitors, and (when comparing) the same goal's
|
|
33
|
+
* conversions in the previous window. Rows come from one `goal` breakdown read and the site
|
|
34
|
+
* total from one totals read, both through the existing widget helpers so capability
|
|
35
|
+
* gating, scoping and caching stay in one place. Revenue and visitors ride along only where
|
|
36
|
+
* the source serves them; the status is the breakdown's, since a table without its rows has
|
|
37
|
+
* nothing to show.
|
|
38
|
+
*/
|
|
39
|
+
const readForWidgetGoals = async (args) => {
|
|
40
|
+
const { req, timeframe, limit, compare, adapterId, now } = args;
|
|
41
|
+
const fallback = (status, id) => ({
|
|
42
|
+
status,
|
|
43
|
+
adapterId: id,
|
|
44
|
+
dateRange: args.range ?? resolveTimeframe(timeframe, now, args.timezone),
|
|
45
|
+
timezone: args.timezone ?? "UTC",
|
|
46
|
+
rows: []
|
|
47
|
+
});
|
|
48
|
+
const runtime = getRuntime(req.payload);
|
|
49
|
+
if (!runtime) return fallback("unavailable", adapterId ?? "");
|
|
50
|
+
const ctx = await resolveReadContext({
|
|
51
|
+
runtime,
|
|
52
|
+
req,
|
|
53
|
+
adapterId,
|
|
54
|
+
scope: args.scope
|
|
55
|
+
});
|
|
56
|
+
if (!ctx.ok) return fallback("unavailable", adapterId ?? "");
|
|
57
|
+
const adapter = ctx.adapter;
|
|
58
|
+
const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
|
|
59
|
+
const dateRange = args.range ?? resolveTimeframe(timeframe, now, tz);
|
|
60
|
+
const shared = {
|
|
61
|
+
req,
|
|
62
|
+
timeframe,
|
|
63
|
+
adapterId: adapter.id,
|
|
64
|
+
scope: ctx.scope,
|
|
65
|
+
timezone: tz,
|
|
66
|
+
now
|
|
67
|
+
};
|
|
68
|
+
const comparisonRange = compare && runtime.comparison && adapter.capabilities.comparison ? previousWindow(dateRange, tz) ?? void 0 : void 0;
|
|
69
|
+
const [breakdown, totals, previous, names] = await Promise.all([
|
|
70
|
+
readForWidgetBreakdown({
|
|
71
|
+
...shared,
|
|
72
|
+
range: dateRange,
|
|
73
|
+
metric: "conversions",
|
|
74
|
+
dimension: "goal",
|
|
75
|
+
limit,
|
|
76
|
+
extraMetrics: ["revenue", "visitors"]
|
|
77
|
+
}),
|
|
78
|
+
adapter.capabilities.metrics.has("visitors") ? readForWidget({
|
|
79
|
+
...shared,
|
|
80
|
+
range: dateRange,
|
|
81
|
+
metrics: ["visitors"],
|
|
82
|
+
comparison: false
|
|
83
|
+
}) : void 0,
|
|
84
|
+
comparisonRange ? readForWidgetBreakdown({
|
|
85
|
+
...shared,
|
|
86
|
+
range: comparisonRange,
|
|
87
|
+
metric: "conversions",
|
|
88
|
+
dimension: "goal",
|
|
89
|
+
limit: previousLimit(limit)
|
|
90
|
+
}) : void 0,
|
|
91
|
+
goalNames(runtime, req, ctx.scope)
|
|
92
|
+
]);
|
|
93
|
+
if (breakdown.status !== "ok") return {
|
|
94
|
+
...fallback(breakdown.status, breakdown.adapterId),
|
|
95
|
+
dateRange,
|
|
96
|
+
timezone: tz
|
|
97
|
+
};
|
|
98
|
+
const previousBySlug = new Map((previous?.status === "ok" ? previous.rows : []).map((row) => [row.label, row.value]));
|
|
99
|
+
const siteVisitors = totals?.status === "ok" ? totals.metrics.visitors : void 0;
|
|
100
|
+
const rows = breakdown.rows.map((row) => {
|
|
101
|
+
const rate = conversionRate(row.metrics?.visitors, siteVisitors);
|
|
102
|
+
const previousConversions = previousBySlug.get(row.label);
|
|
103
|
+
return {
|
|
104
|
+
slug: row.label,
|
|
105
|
+
name: names.get(row.label) ?? row.label,
|
|
106
|
+
conversions: row.value,
|
|
107
|
+
...row.metrics?.revenue !== void 0 ? { revenue: row.metrics.revenue } : {},
|
|
108
|
+
...rate !== null ? { rate } : {},
|
|
109
|
+
...previousConversions !== void 0 ? { previousConversions } : {}
|
|
110
|
+
};
|
|
111
|
+
}).sort((a, b) => b.conversions - a.conversions).slice(0, limit);
|
|
112
|
+
return {
|
|
113
|
+
status: "ok",
|
|
114
|
+
adapterId: adapter.id,
|
|
115
|
+
dateRange,
|
|
116
|
+
timezone: tz,
|
|
117
|
+
rows,
|
|
118
|
+
...siteVisitors !== void 0 ? { siteVisitors } : {},
|
|
119
|
+
clamped: Boolean(breakdown.clamped || totals?.clamped || previous?.clamped),
|
|
120
|
+
stale: Boolean(breakdown.stale || totals?.stale || previous?.stale)
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
//#endregion
|
|
124
|
+
export { readForWidgetGoals };
|
|
125
|
+
|
|
126
|
+
//# sourceMappingURL=readForWidgetGoals.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readForWidgetGoals.js","names":[],"sources":["../../src/widgets/readForWidgetGoals.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { DateRange } from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\tresolveGoalsDetailedFor,\n\tresolveTimezoneFor,\n} from '../plugin/runtime'\nimport { MAX_QUERY_LIMIT } from '../query/limits'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { conversionRate } from '../view/conversionRate'\nimport { previousWindow } from './comparison'\nimport { readForWidget, type WidgetReadStatus } from './readForWidget'\nimport { readForWidgetBreakdown } from './readForWidgetBreakdown'\n\nexport interface GoalRow {\n\tslug: string\n\t/** The goal's admin-facing name, or its slug when no configured goal claims it. */\n\tname: string\n\tconversions: number\n\trevenue?: number\n\t/** 0..1 share of the site's visitors, absent when either side of the ratio is missing. */\n\trate?: number\n\tpreviousConversions?: number\n}\n\nexport interface WidgetGoalsResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\ttimezone: string\n\trows: GoalRow[]\n\t/** Range total the rate divides by; absent when the source does not serve visitors. */\n\tsiteVisitors?: number\n\tclamped?: boolean\n\tstale?: boolean\n}\n\nexport interface ReadForWidgetGoalsArgs {\n\treq: PayloadRequest\n\ttimeframe: TimeframePreset\n\tlimit: number\n\t/** Read the previous window too, when the source can compare. */\n\tcompare: boolean\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n}\n\n/**\n * How much wider than the table the previous window is read. Both windows rank by their own\n * conversions, so a goal in today's top rows may sit well below them in the previous window;\n * reading only as many rows as the table shows would drop exactly those deltas. Capped at\n * the bound every analytics query is held to.\n */\nconst PREVIOUS_LIMIT_FACTOR = 4\n\nconst previousLimit = (limit: number): number =>\n\tMath.min(limit * PREVIOUS_LIMIT_FACTOR, MAX_QUERY_LIMIT)\n\n/**\n * Goal names for the read's own scope. A resolver that throws must not cost the widget its\n * table, so the rows fall back to their slugs.\n */\nconst goalNames = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<Map<string, string>> => {\n\ttry {\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\treturn new Map(resolved.map(({ goal }) => [goal.slug, goal.name]))\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: widget goal names failed to resolve: ${String(err)}`)\n\t\treturn new Map()\n\t}\n}\n\n/**\n * The goals table behind the goals widget: conversions per goal over the window, each with\n * its revenue, its share of the site's visitors, and (when comparing) the same goal's\n * conversions in the previous window. Rows come from one `goal` breakdown read and the site\n * total from one totals read, both through the existing widget helpers so capability\n * gating, scoping and caching stay in one place. Revenue and visitors ride along only where\n * the source serves them; the status is the breakdown's, since a table without its rows has\n * nothing to show.\n */\nexport const readForWidgetGoals = async (\n\targs: ReadForWidgetGoalsArgs\n): Promise<WidgetGoalsResult> => {\n\tconst { req, timeframe, limit, compare, adapterId, now } = args\n\tconst fallback = (status: WidgetReadStatus, id: string): WidgetGoalsResult => ({\n\t\tstatus,\n\t\tadapterId: id,\n\t\tdateRange: args.range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\trows: [],\n\t})\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst adapter = ctx.adapter\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = args.range ?? resolveTimeframe(timeframe, now, tz)\n\t// The sub-reads resolve their own context; pinning the adapter, scope, timezone and\n\t// window keeps all three answering about exactly the same read.\n\tconst shared = { req, timeframe, adapterId: adapter.id, scope: ctx.scope, timezone: tz, now }\n\tconst comparisonRange =\n\t\tcompare && runtime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\n\tconst [breakdown, totals, previous, names] = await Promise.all([\n\t\treadForWidgetBreakdown({\n\t\t\t...shared,\n\t\t\trange: dateRange,\n\t\t\tmetric: 'conversions',\n\t\t\tdimension: 'goal',\n\t\t\tlimit,\n\t\t\textraMetrics: ['revenue', 'visitors'],\n\t\t}),\n\t\tadapter.capabilities.metrics.has('visitors')\n\t\t\t? // The site total is a denominator, never a delta: its own previous window would\n\t\t\t\t// be a second read nothing renders.\n\t\t\t\treadForWidget({ ...shared, range: dateRange, metrics: ['visitors'], comparison: false })\n\t\t\t: undefined,\n\t\tcomparisonRange\n\t\t\t? readForWidgetBreakdown({\n\t\t\t\t\t...shared,\n\t\t\t\t\trange: comparisonRange,\n\t\t\t\t\tmetric: 'conversions',\n\t\t\t\t\tdimension: 'goal',\n\t\t\t\t\tlimit: previousLimit(limit),\n\t\t\t\t})\n\t\t\t: undefined,\n\t\tgoalNames(runtime, req, ctx.scope),\n\t])\n\tif (breakdown.status !== 'ok') {\n\t\treturn { ...fallback(breakdown.status, breakdown.adapterId), dateRange, timezone: tz }\n\t}\n\n\tconst previousBySlug = new Map(\n\t\t(previous?.status === 'ok' ? previous.rows : []).map((row) => [row.label, row.value])\n\t)\n\tconst siteVisitors = totals?.status === 'ok' ? totals.metrics.visitors : undefined\n\tconst rows: GoalRow[] = breakdown.rows\n\t\t.map((row) => {\n\t\t\tconst rate = conversionRate(row.metrics?.visitors, siteVisitors)\n\t\t\tconst previousConversions = previousBySlug.get(row.label)\n\t\t\treturn {\n\t\t\t\tslug: row.label,\n\t\t\t\tname: names.get(row.label) ?? row.label,\n\t\t\t\tconversions: row.value,\n\t\t\t\t...(row.metrics?.revenue !== undefined ? { revenue: row.metrics.revenue } : {}),\n\t\t\t\t...(rate !== null ? { rate } : {}),\n\t\t\t\t...(previousConversions !== undefined ? { previousConversions } : {}),\n\t\t\t}\n\t\t})\n\t\t// The adapter ranks and caps already; re-applying both keeps one that does not from\n\t\t// spilling a long, unranked table into a dashboard card.\n\t\t.sort((a, b) => b.conversions - a.conversions)\n\t\t.slice(0, limit)\n\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\trows,\n\t\t...(siteVisitors !== undefined ? { siteVisitors } : {}),\n\t\tclamped: Boolean(breakdown.clamped || totals?.clamped || previous?.clamped),\n\t\tstale: Boolean(breakdown.stale || totals?.stale || previous?.stale),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAgEA,MAAM,wBAAwB;AAE9B,MAAM,iBAAiB,UACtB,KAAK,IAAI,QAAQ,uBAAA,GAAsC;;;;;AAMxD,MAAM,YAAY,OACjB,SACA,KACA,UACkC;CAClC,IAAI;EACH,MAAM,WAAW,MAAM,wBAAwB,SAAS,KAAK,KAAK;EAClE,OAAO,IAAI,IAAI,SAAS,KAAK,EAAE,WAAW,CAAC,KAAK,MAAM,KAAK,IAAI,CAAC,CAAC;CAClE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,mDAAmD,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Total?: number;
|
|
22
22
|
/** The previous comparable window, present only when comparison ran. */
|
|
23
23
|
comparisonRange?: DateRange;
|
|
24
|
+
/**
|
|
25
|
+
* The previous window's daily series, present only when `compare` was asked for and the
|
|
26
|
+
* adapter supports comparison. Zero-filled to the same length as `points`, so the
|
|
27
|
+
* previous window's day i overlays `points[i]`.
|
|
28
|
+
*/
|
|
29
|
+
comparisonPoints?: SeriesPoint[];
|
|
24
30
|
}
|
|
25
31
|
interface ReadForWidgetSeriesArgs {
|
|
26
32
|
req: PayloadRequest;
|
|
@@ -31,7 +37,14 @@ interface ReadForWidgetSeriesArgs {
|
|
|
31
37
|
range?: DateRange;
|
|
32
38
|
/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */
|
|
33
39
|
scope?: string | null;
|
|
40
|
+
/**
|
|
41
|
+
* Reporting timezone the caller already resolved, reused rather than resolved again so
|
|
42
|
+
* a caller-supplied `range` is read in the very timezone it was interpreted in.
|
|
43
|
+
*/
|
|
44
|
+
timezone?: string;
|
|
34
45
|
filters?: AnalyticsFilter[];
|
|
46
|
+
/** Also return the previous window's series, for the chart's comparison overlay. */
|
|
47
|
+
compare?: boolean;
|
|
35
48
|
}
|
|
36
49
|
/**
|
|
37
50
|
* Site-wide time-series read for a trend widget: resolve the timeframe, pick the
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { addDaysInTz, startOfDayInTz, zonedDayIso } from "../timeframe/tz.js";
|
|
2
2
|
import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
|
|
3
|
+
import { resolveTimeframe } from "../timeframe/presets.js";
|
|
3
4
|
import { satisfiesCapabilities } from "../core/capabilities.js";
|
|
4
5
|
import { supportsGranularity } from "../core/granularity.js";
|
|
5
6
|
import { resolveReadContext } from "../core/scopedRead.js";
|
|
6
|
-
import { resolveTimeframe } from "../timeframe/presets.js";
|
|
7
7
|
import { previousWindow } from "./comparison.js";
|
|
8
8
|
//#region src/widgets/readForWidgetSeries.ts
|
|
9
9
|
const MAX_SERIES_DAYS = 366;
|
|
@@ -37,18 +37,28 @@ const fillDailySeries = (args) => {
|
|
|
37
37
|
}));
|
|
38
38
|
};
|
|
39
39
|
/**
|
|
40
|
+
* Project a comparison series onto the primary axis: day i of the previous window overlays
|
|
41
|
+
* day i of the current one. Both windows span the same day count by construction, so this
|
|
42
|
+
* only guards a DST-shifted or clamped edge, silently truncating or zero-filling; a filled
|
|
43
|
+
* bucket borrows the axis day so every point still carries a real date.
|
|
44
|
+
*/
|
|
45
|
+
const alignSeries = (points, axis) => points.length === axis.length ? points : axis.map((day, i) => points[i] ?? {
|
|
46
|
+
date: day.date,
|
|
47
|
+
value: 0
|
|
48
|
+
});
|
|
49
|
+
/**
|
|
40
50
|
* Site-wide time-series read for a trend widget: resolve the timeframe, pick the
|
|
41
51
|
* adapter, gate on the metric and day-granularity support, read through the engine,
|
|
42
52
|
* then return a zero-filled daily series plus the headline total. Mirrors
|
|
43
53
|
* `readForWidget` but yields points instead of a single value.
|
|
44
54
|
*/
|
|
45
55
|
const readForWidgetSeries = async (args) => {
|
|
46
|
-
const { req, metric, timeframe, adapterId, now, range, filters } = args;
|
|
56
|
+
const { req, metric, timeframe, adapterId, now, range, filters, compare } = args;
|
|
47
57
|
const fallback = (status, id) => ({
|
|
48
58
|
status,
|
|
49
59
|
adapterId: id,
|
|
50
|
-
dateRange: range ?? resolveTimeframe(timeframe, now),
|
|
51
|
-
timezone: "UTC",
|
|
60
|
+
dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
|
|
61
|
+
timezone: args.timezone ?? "UTC",
|
|
52
62
|
points: [],
|
|
53
63
|
total: 0
|
|
54
64
|
});
|
|
@@ -61,7 +71,7 @@ const readForWidgetSeries = async (args) => {
|
|
|
61
71
|
scope: args.scope
|
|
62
72
|
});
|
|
63
73
|
if (!ctx.ok) return fallback("unavailable", adapterId ?? "");
|
|
64
|
-
const tz = await resolveTimezoneFor(runtime, req, ctx.scope);
|
|
74
|
+
const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
|
|
65
75
|
const dateRange = range ?? resolveTimeframe(timeframe, now, tz);
|
|
66
76
|
const base = {
|
|
67
77
|
dateRange,
|
|
@@ -100,6 +110,7 @@ const readForWidgetSeries = async (args) => {
|
|
|
100
110
|
}), comparisonRange ? runtime.engine.read(adapter, {
|
|
101
111
|
metrics: [metric],
|
|
102
112
|
dateRange: comparisonRange,
|
|
113
|
+
...compare ? { granularity: "day" } : {},
|
|
103
114
|
filters,
|
|
104
115
|
timezone: tz,
|
|
105
116
|
scope: ctx.queryScope
|
|
@@ -112,21 +123,28 @@ const readForWidgetSeries = async (args) => {
|
|
|
112
123
|
};
|
|
113
124
|
}
|
|
114
125
|
const previousTotal = previous ? previous.totals?.[metric] : void 0;
|
|
126
|
+
const points = fillDailySeries({
|
|
127
|
+
rows: result.rows,
|
|
128
|
+
dateRange,
|
|
129
|
+
metric,
|
|
130
|
+
tz
|
|
131
|
+
});
|
|
115
132
|
return {
|
|
116
133
|
status: "ok",
|
|
117
134
|
adapterId: adapter.id,
|
|
118
135
|
dateRange,
|
|
119
136
|
timezone: tz,
|
|
120
|
-
points
|
|
121
|
-
rows: result.rows,
|
|
122
|
-
dateRange,
|
|
123
|
-
metric,
|
|
124
|
-
tz
|
|
125
|
-
}),
|
|
137
|
+
points,
|
|
126
138
|
total: result.totals?.[metric] ?? 0,
|
|
127
139
|
clamped: result.meta.clamped ?? false,
|
|
128
140
|
previousTotal,
|
|
129
|
-
comparisonRange
|
|
141
|
+
comparisonRange,
|
|
142
|
+
...compare && previous && comparisonRange ? { comparisonPoints: alignSeries(fillDailySeries({
|
|
143
|
+
rows: previous.rows,
|
|
144
|
+
dateRange: comparisonRange,
|
|
145
|
+
metric,
|
|
146
|
+
tz
|
|
147
|
+
}), points) } : {}
|
|
130
148
|
};
|
|
131
149
|
};
|
|
132
150
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDateRange,\n\tMetricKey,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { addDaysInTz, DEFAULT_TIMEZONE, startOfDayInTz, zonedDayIso } from '../timeframe/tz'\nimport { previousWindow } from './comparison'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface SeriesPoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetSeriesResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tpoints: SeriesPoint[]\n\ttotal: number\n\tclamped?: boolean\n\t/** Previous-window headline total, present only when the adapter supports comparison. */\n\tpreviousTotal?: number\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n}\n\nexport interface ReadForWidgetSeriesArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\tfilters?: AnalyticsFilter[]\n}\n\nconst MAX_SERIES_DAYS = 366\n\n/**\n * Project time-series rows onto a contiguous daily axis, zero-filling gaps. Days are\n * counted in `tz` (defaulting to UTC), so a reporting-timezone read aligns each bucket\n * to that zone's midnight. The axis is capped at the most recent `MAX_SERIES_DAYS` so\n * an unbounded range (all time) stays a bounded, drawable sparkline; the headline total\n * still reflects the full range.\n */\nexport const fillDailySeries = (args: {\n\trows: AnalyticsRow[]\n\tdateRange: DateRange\n\tmetric: MetricKey\n\ttz?: string\n}): SeriesPoint[] => {\n\tconst { rows, dateRange, metric } = args\n\tconst tz = args.tz ?? DEFAULT_TIMEZONE\n\tconst lastDay = startOfDayInTz(dateRange.end, tz)\n\tconst requestedStart = startOfDayInTz(dateRange.start, tz)\n\tconst byDay = new Map<string, number>()\n\tfor (const row of rows) {\n\t\tif (!row.timestamp) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = zonedDayIso(new Date(row.timestamp), tz)\n\t\tbyDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0))\n\t}\n\t// Walk calendar days back from the last day so DST-length days never mis-step, capping\n\t// the axis at MAX_SERIES_DAYS or the requested start, whichever is more recent.\n\tconst isoDays: string[] = []\n\tlet cursor = lastDay\n\tfor (let i = 0; i < MAX_SERIES_DAYS && cursor.getTime() >= requestedStart.getTime(); i += 1) {\n\t\tisoDays.push(cursor.toISOString())\n\t\tcursor = addDaysInTz(cursor, -1, tz)\n\t}\n\treturn isoDays.reverse().map((date) => ({ date, value: byDay.get(date) ?? 0 }))\n}\n\n/**\n * Site-wide time-series read for a trend widget: resolve the timeframe, pick the\n * adapter, gate on the metric and day-granularity support, read through the engine,\n * then return a zero-filled daily series plus the headline total. Mirrors\n * `readForWidget` but yields points instead of a single value.\n */\nexport const readForWidgetSeries = async (\n\targs: ReadForWidgetSeriesArgs\n): Promise<WidgetSeriesResult> => {\n\tconst { req, metric, timeframe, adapterId, now, range, filters } = args\n\tconst fallback = (status: WidgetReadStatus, id: string): WidgetSeriesResult => ({\n\t\tstatus,\n\t\tadapterId: id,\n\t\tdateRange: range ?? resolveTimeframe(timeframe, now),\n\t\ttimezone: DEFAULT_TIMEZONE,\n\t\tpoints: [],\n\t\ttotal: 0,\n\t})\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst tz = await resolveTimezoneFor(runtime, req, ctx.scope)\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst base = { dateRange, timezone: tz, points: [] as SeriesPoint[], total: 0 }\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, {\n\t\t\tmetrics: [metric],\n\t\t\t...(filters && filters.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\tfilters: filters.map((f) => f.dimension),\n\t\t\t\t\t\tfilterOperators: filters.map((f) => f.operator),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t}) ||\n\t\t!supportsGranularity(adapter.capabilities, 'day')\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst comparisonRange =\n\t\truntime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\tlet result: AnalyticsResult\n\tlet previous: AnalyticsResult | undefined\n\ttry {\n\t\t;[result, previous] = await Promise.all([\n\t\t\truntime.engine.read(adapter, {\n\t\t\t\tmetrics: [metric],\n\t\t\t\tdateRange,\n\t\t\t\tgranularity: 'day',\n\t\t\t\tfilters,\n\t\t\t\ttimezone: tz,\n\t\t\t\tscope: ctx.queryScope,\n\t\t\t}),\n\t\t\tcomparisonRange\n\t\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t\tmetrics: [metric],\n\t\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\ttimezone: tz,\n\t\t\t\t\t\tscope: ctx.queryScope,\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\t])\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst previousTotal = previous ? previous.totals?.[metric] : undefined\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tpoints: fillDailySeries({ rows: result.rows, dateRange, metric, tz }),\n\t\ttotal: result.totals?.[metric] ?? 0,\n\t\tclamped: result.meta.clamped ?? false,\n\t\tpreviousTotal,\n\t\tcomparisonRange,\n\t}\n}\n"],"mappings":";;;;;;;;AAkDA,MAAM,kBAAkB;;;;;;;;AASxB,MAAa,mBAAmB,SAKX;CACpB,MAAM,EAAE,MAAM,WAAW,WAAW;CACpC,MAAM,KAAK,KAAK,MAAA;CAChB,MAAM,UAAU,eAAe,UAAU,KAAK,EAAE;CAChD,MAAM,iBAAiB,eAAe,UAAU,OAAO,EAAE;CACzD,MAAM,wBAAQ,IAAI,IAAoB;CACtC,KAAK,MAAM,OAAO,MAAM;EACvB,IAAI,CAAC,IAAI,WACR;EAED,MAAM,MAAM,YAAY,IAAI,KAAK,IAAI,SAAS,GAAG,EAAE;EACnD,MAAM,IAAI,MAAM,MAAM,IAAI,GAAG,KAAK,MAAM,IAAI,QAAQ,WAAW,EAAE;CAClE;CAGA,MAAM,UAAoB,CAAC;CAC3B,IAAI,SAAS;CACb,KAAK,IAAI,IAAI,GAAG,IAAI,mBAAmB,OAAO,QAAQ,KAAK,eAAe,QAAQ,GAAG,KAAK,GAAG;EAC5F,QAAQ,KAAK,OAAO,YAAY,CAAC;EACjC,SAAS,YAAY,QAAQ,IAAI,EAAE;CACpC;CACA,OAAO,QAAQ,QAAQ,EAAE,KAAK,UAAU;EAAE;EAAM,OAAO,MAAM,IAAI,IAAI,KAAK;CAAE,EAAE;AAC/E;;;;;;;AAQA,MAAa,sBAAsB,OAClC,SACiC;CACjC,MAAM,EAAE,KAAK,QAAQ,WAAW,WAAW,KAAK,OAAO,YAAY;CACnE,MAAM,YAA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ACA,UAAU;GACV,OAAO,IAAI;EACZ,CAAC,GACD,kBACG,QAAQ,OAAO,KAAK,SAAS;GAC7B,SAAS,CAAC,MAAM;GAChB,WAAW;GACX;GACA,UAAU;GACV,OAAO,IAAI;EACZ,CAAC,IACA,KAAA,CACJ,CAAC;CACF,QAAQ;EAGP,OAAO;GAAE,QAAQ;GAAe,WAAW,QAAQ;GAAI,GAAG;EAAK;CAChE;CACA,MAAM,gBAAgB,WAAW,SAAS,SAAS,UAAU,KAAA;CAC7D,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,UAAU;EACV,QAAQ,gBAAgB;GAAE,MAAM,OAAO;GAAM;GAAW;GAAQ;EAAG,CAAC;EACpE,OAAO,OAAO,SAAS,WAAW;EAClC,SAAS,OAAO,KAAK,WAAW;EAChC;EACA;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDateRange,\n\tMetricKey,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { addDaysInTz, DEFAULT_TIMEZONE, startOfDayInTz, zonedDayIso } from '../timeframe/tz'\nimport { previousWindow } from './comparison'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface SeriesPoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetSeriesResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tpoints: SeriesPoint[]\n\ttotal: number\n\tclamped?: boolean\n\t/** Previous-window headline total, present only when the adapter supports comparison. */\n\tpreviousTotal?: number\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/**\n\t * The previous window's daily series, present only when `compare` was asked for and the\n\t * adapter supports comparison. Zero-filled to the same length as `points`, so the\n\t * previous window's day i overlays `points[i]`.\n\t */\n\tcomparisonPoints?: SeriesPoint[]\n}\n\nexport interface ReadForWidgetSeriesArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\tfilters?: AnalyticsFilter[]\n\t/** Also return the previous window's series, for the chart's comparison overlay. */\n\tcompare?: boolean\n}\n\nconst MAX_SERIES_DAYS = 366\n\n/**\n * Project time-series rows onto a contiguous daily axis, zero-filling gaps. Days are\n * counted in `tz` (defaulting to UTC), so a reporting-timezone read aligns each bucket\n * to that zone's midnight. The axis is capped at the most recent `MAX_SERIES_DAYS` so\n * an unbounded range (all time) stays a bounded, drawable sparkline; the headline total\n * still reflects the full range.\n */\nexport const fillDailySeries = (args: {\n\trows: AnalyticsRow[]\n\tdateRange: DateRange\n\tmetric: MetricKey\n\ttz?: string\n}): SeriesPoint[] => {\n\tconst { rows, dateRange, metric } = args\n\tconst tz = args.tz ?? DEFAULT_TIMEZONE\n\tconst lastDay = startOfDayInTz(dateRange.end, tz)\n\tconst requestedStart = startOfDayInTz(dateRange.start, tz)\n\tconst byDay = new Map<string, number>()\n\tfor (const row of rows) {\n\t\tif (!row.timestamp) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = zonedDayIso(new Date(row.timestamp), tz)\n\t\tbyDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0))\n\t}\n\t// Walk calendar days back from the last day so DST-length days never mis-step, capping\n\t// the axis at MAX_SERIES_DAYS or the requested start, whichever is more recent.\n\tconst isoDays: string[] = []\n\tlet cursor = lastDay\n\tfor (let i = 0; i < MAX_SERIES_DAYS && cursor.getTime() >= requestedStart.getTime(); i += 1) {\n\t\tisoDays.push(cursor.toISOString())\n\t\tcursor = addDaysInTz(cursor, -1, tz)\n\t}\n\treturn isoDays.reverse().map((date) => ({ date, value: byDay.get(date) ?? 0 }))\n}\n\n/**\n * Project a comparison series onto the primary axis: day i of the previous window overlays\n * day i of the current one. Both windows span the same day count by construction, so this\n * only guards a DST-shifted or clamped edge, silently truncating or zero-filling; a filled\n * bucket borrows the axis day so every point still carries a real date.\n */\nconst alignSeries = (points: SeriesPoint[], axis: SeriesPoint[]): SeriesPoint[] =>\n\tpoints.length === axis.length\n\t\t? points\n\t\t: axis.map((day, i) => points[i] ?? { date: day.date, value: 0 })\n\n/**\n * Site-wide time-series read for a trend widget: resolve the timeframe, pick the\n * adapter, gate on the metric and day-granularity support, read through the engine,\n * then return a zero-filled daily series plus the headline total. Mirrors\n * `readForWidget` but yields points instead of a single value.\n */\nexport const readForWidgetSeries = async (\n\targs: ReadForWidgetSeriesArgs\n): Promise<WidgetSeriesResult> => {\n\tconst { req, metric, timeframe, adapterId, now, range, filters, compare } = args\n\tconst fallback = (status: WidgetReadStatus, id: string): WidgetSeriesResult => ({\n\t\tstatus,\n\t\tadapterId: id,\n\t\tdateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\tpoints: [],\n\t\ttotal: 0,\n\t})\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst base = { dateRange, timezone: tz, points: [] as SeriesPoint[], total: 0 }\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, {\n\t\t\tmetrics: [metric],\n\t\t\t...(filters && filters.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\tfilters: filters.map((f) => f.dimension),\n\t\t\t\t\t\tfilterOperators: filters.map((f) => f.operator),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t}) ||\n\t\t!supportsGranularity(adapter.capabilities, 'day')\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst comparisonRange =\n\t\truntime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\tlet result: AnalyticsResult\n\tlet previous: AnalyticsResult | undefined\n\ttry {\n\t\t;[result, previous] = await Promise.all([\n\t\t\truntime.engine.read(adapter, {\n\t\t\t\tmetrics: [metric],\n\t\t\t\tdateRange,\n\t\t\t\tgranularity: 'day',\n\t\t\t\tfilters,\n\t\t\t\ttimezone: tz,\n\t\t\t\tscope: ctx.queryScope,\n\t\t\t}),\n\t\t\tcomparisonRange\n\t\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t\tmetrics: [metric],\n\t\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t\t\t// The overlay needs the previous window bucketed like the primary; the delta\n\t\t\t\t\t\t// alone only needs its total, so the read stays as it was without `compare`.\n\t\t\t\t\t\t...(compare ? { granularity: 'day' as const } : {}),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\ttimezone: tz,\n\t\t\t\t\t\tscope: ctx.queryScope,\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\t])\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst previousTotal = previous ? previous.totals?.[metric] : undefined\n\tconst points = fillDailySeries({ rows: result.rows, dateRange, metric, tz })\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tpoints,\n\t\ttotal: result.totals?.[metric] ?? 0,\n\t\tclamped: result.meta.clamped ?? false,\n\t\tpreviousTotal,\n\t\tcomparisonRange,\n\t\t...(compare && previous && comparisonRange\n\t\t\t? {\n\t\t\t\t\tcomparisonPoints: alignSeries(\n\t\t\t\t\t\tfillDailySeries({ rows: previous.rows, dateRange: comparisonRange, metric, tz }),\n\t\t\t\t\t\tpoints\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t}\n}\n"],"mappings":";;;;;;;;AA+DA,MAAM,kBAAkB;;;;;;;;AASxB,MAAa,mBAAmB,SAKX;CACpB,MAAM,EAAE,MAAM,WAAW,WAAW;CACpC,MAAM,KAAK,KAAK,MAAA;CAChB,MAAM,UAAU,eAAe,UAAU,KAAK,EAAE;CAChD,MAAM,iBAAiB,eAAe,UAAU,OAAO,EAAE;CACzD,MAAM,wBAAQ,IAAI,IAAoB;CACtC,KAAK,MAAM,OAAO,MAAM;EACvB,IAAI,CAAC,IAAI,WACR;EAED,MAAM,MAAM,YAAY,IAAI,KAAK,IAAI,SAAS,GAAG,EAAE;EACnD,MAAM,IAAI,MAAM,MAAM,IAAI,GAAG,KAAK,MAAM,IAAI,QAAQ,WAAW,EAAE;CAClE;CAGA,MAAM,UAAoB,CAAC;CAC3B,IAAI,SAAS;CACb,KAAK,IAAI,IAAI,GAAG,IAAI,mBAAmB,OAAO,QAAQ,KAAK,eAAe,QAAQ,GAAG,KAAK,GAAG;EAC5F,QAAQ,KAAK,OAAO,YAAY,CAAC;EAC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ys.js";
|
|
2
2
|
import { labelForKey } from "../translations/server.js";
|
|
3
|
-
import { satisfiesCapabilities } from "../core/capabilities.js";
|
|
4
3
|
import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
|
|
5
4
|
import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
5
|
+
import { satisfiesCapabilities } from "../core/capabilities.js";
|
|
6
6
|
import { de } from "../translations/de.js";
|
|
7
7
|
import { en } from "../translations/en.js";
|
|
8
8
|
import { BREAKDOWN_SPECS } from "./breakdownTypes.js";
|
|
9
|
-
import { WIDGET_METRICS } from "./types.js";
|
|
9
|
+
import { GOAL_ROW_LIMITS, WIDGET_METRICS } from "./types.js";
|
|
10
10
|
import { dateRangeField } from "../fields/dateRange/field.js";
|
|
11
11
|
import { buildCustomWidgets } from "./customWidget.js";
|
|
12
12
|
//#region src/widgets/registerWidgets.ts
|
|
@@ -90,6 +90,13 @@ const timeframeSelectField = () => ({
|
|
|
90
90
|
label: labelForKey(keys.widgetTimeframeCustom)
|
|
91
91
|
}]
|
|
92
92
|
});
|
|
93
|
+
/** Reads the previous period too: the trend overlays it, the goals table deltas against it. */
|
|
94
|
+
const compareField = () => ({
|
|
95
|
+
name: "compare",
|
|
96
|
+
type: "checkbox",
|
|
97
|
+
defaultValue: false,
|
|
98
|
+
label: labelForKey(keys.widgetFieldCompare)
|
|
99
|
+
});
|
|
93
100
|
const dataSourceField = (args) => ({
|
|
94
101
|
name: "dataSource",
|
|
95
102
|
type: "select",
|
|
@@ -119,18 +126,19 @@ const customRangeField = () => dateRangeField({
|
|
|
119
126
|
});
|
|
120
127
|
/** The metric select in a widget's field list. */
|
|
121
128
|
const findMetricField = (fields) => fields.find((field) => "name" in field && field.name === "metric");
|
|
122
|
-
const metricWidgetFields = (args) => [
|
|
129
|
+
const metricWidgetFields = (args, extra = []) => [
|
|
123
130
|
titleField(args, en[keys.widgetFieldTitlePlaceholder]),
|
|
124
131
|
metricSelectField(WIDGET_METRICS, args),
|
|
125
132
|
timeframeSelectField(),
|
|
126
133
|
customRangeField(),
|
|
134
|
+
...extra,
|
|
127
135
|
...args.multiProvider ? [dataSourceField(args)] : []
|
|
128
136
|
];
|
|
129
137
|
const breakdownWidgetFields = (args, spec) => [
|
|
130
138
|
titleField(args, en[spec.label]),
|
|
131
139
|
metricSelectField(WIDGET_METRICS, args, {
|
|
132
140
|
extra: { dimensions: [spec.dimension] },
|
|
133
|
-
...spec.
|
|
141
|
+
...spec.preferredDefault ? { preferredDefault: spec.preferredDefault } : {}
|
|
134
142
|
}),
|
|
135
143
|
timeframeSelectField(),
|
|
136
144
|
customRangeField(),
|
|
@@ -144,6 +152,26 @@ const breakdownWidgetFields = (args, spec) => [
|
|
|
144
152
|
},
|
|
145
153
|
...args.multiProvider ? [dataSourceField(args)] : []
|
|
146
154
|
];
|
|
155
|
+
/** A select, not the breakdown's free number: the goals table is a summary, not a report. */
|
|
156
|
+
const goalLimitField = () => ({
|
|
157
|
+
name: "limit",
|
|
158
|
+
type: "select",
|
|
159
|
+
defaultValue: String(GOAL_ROW_LIMITS[0]),
|
|
160
|
+
label: labelForKey(keys.widgetFieldLimit),
|
|
161
|
+
admin: { isClearable: false },
|
|
162
|
+
options: GOAL_ROW_LIMITS.map((limit) => ({
|
|
163
|
+
value: String(limit),
|
|
164
|
+
label: String(limit)
|
|
165
|
+
}))
|
|
166
|
+
});
|
|
167
|
+
const goalsWidgetFields = (args) => [
|
|
168
|
+
titleField(args, en[keys.widgetGoals]),
|
|
169
|
+
timeframeSelectField(),
|
|
170
|
+
customRangeField(),
|
|
171
|
+
goalLimitField(),
|
|
172
|
+
...args.comparison === false ? [] : [compareField()],
|
|
173
|
+
...args.multiProvider ? [dataSourceField(args)] : []
|
|
174
|
+
];
|
|
147
175
|
const realtimeWidgetFields = (args) => [
|
|
148
176
|
titleField(args, en[keys.widgetFieldTitlePlaceholder]),
|
|
149
177
|
metricSelectField(["visitors", "pageviews"], args, {
|
|
@@ -193,7 +221,7 @@ const WIDGET_DEFS = [
|
|
|
193
221
|
requires: { metrics: ["pageviews"] },
|
|
194
222
|
minWidth: "small",
|
|
195
223
|
maxWidth: "full",
|
|
196
|
-
fields: metricWidgetFields
|
|
224
|
+
fields: (args) => metricWidgetFields(args, args.comparison === false ? [] : [compareField()])
|
|
197
225
|
},
|
|
198
226
|
{
|
|
199
227
|
slug: "analytics-realtime",
|
|
@@ -204,6 +232,18 @@ const WIDGET_DEFS = [
|
|
|
204
232
|
maxWidth: "medium",
|
|
205
233
|
fields: realtimeWidgetFields
|
|
206
234
|
},
|
|
235
|
+
{
|
|
236
|
+
slug: "analytics-goals",
|
|
237
|
+
component: "@10x-media/analytics/rsc#AnalyticsGoalsWidget",
|
|
238
|
+
label: keys.widgetGoals,
|
|
239
|
+
requires: {
|
|
240
|
+
metrics: ["conversions"],
|
|
241
|
+
dimensions: ["goal"]
|
|
242
|
+
},
|
|
243
|
+
minWidth: "small",
|
|
244
|
+
maxWidth: "large",
|
|
245
|
+
fields: goalsWidgetFields
|
|
246
|
+
},
|
|
207
247
|
...BREAKDOWN_SPECS.map((spec) => ({
|
|
208
248
|
slug: spec.slug,
|
|
209
249
|
component: "@10x-media/analytics/rsc#AnalyticsBreakdownWidget",
|
|
@@ -224,7 +264,10 @@ const registerWidgets = (config, args) => {
|
|
|
224
264
|
if (metricField && "options" in metricField && metricField.options.length === 0) continue;
|
|
225
265
|
built.push({
|
|
226
266
|
slug: def.slug,
|
|
227
|
-
Component:
|
|
267
|
+
Component: {
|
|
268
|
+
path: def.component,
|
|
269
|
+
serverProps: { view: args.view ?? false }
|
|
270
|
+
},
|
|
228
271
|
label: labelForKey(def.label),
|
|
229
272
|
fields,
|
|
230
273
|
minWidth: def.minWidth,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerWidgets.js","names":[],"sources":["../../src/widgets/registerWidgets.ts"],"sourcesContent":["import type {\n\tConfig,\n\tField,\n\tSelectField,\n\tSelectFieldSingleValidation,\n\tWidget,\n\tWidgetWidth,\n} from 'payload'\nimport { type CapabilityRequirement, satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { dateRangeField } from '../fields/dateRange/field'\nimport { TIMEFRAME_PRESETS } from '../timeframe/presets'\nimport { de } from '../translations/de'\nimport { en } from '../translations/en'\nimport type { TranslationKey } from '../translations/keys'\nimport { keys } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { labelForKey } from '../translations/server'\nimport { BREAKDOWN_SPECS, type BreakdownSpec } from './breakdownTypes'\nimport { buildCustomWidgets, type CustomWidgetDef } from './customWidget'\nimport { WIDGET_METRICS } from './types'\n\n/**\n * Select options must carry static labels: `filterOptions` results are serialized\n * into client form state at request time, where a label function cannot cross the\n * server/client boundary.\n */\nconst staticLabel = (key: TranslationKey): Record<string, string> => ({\n\tde: de[key],\n\ten: en[key],\n})\n\nexport interface RegisterWidgetsArgs {\n\tadapters: AnalyticsAdapter[]\n\tmultiProvider: boolean\n\t/**\n\t * True when a tenant's own runtime adapter can exist (`providers.collection` or\n\t * `providers.resolve`). Such an adapter's capabilities are unknown at config time, so\n\t * gating on the config-adapter union would impose a false ceiling: widgets and metric\n\t * options open up, and the per-request sources endpoint plus client pickers narrow per\n\t * request instead.\n\t */\n\tprovidersEnabled: boolean\n\tdisabled: string[]\n\tregister: CustomWidgetDef[]\n\tlocalizeText?: boolean\n\t/** The plugin's configured defaultAdapter, when set; falls back to the first adapter. */\n\tdefaultId?: string\n}\n\ninterface WidgetDef {\n\tslug: string\n\tcomponent: string\n\tlabel: TranslationKey\n\trequires?: CapabilityRequirement\n\tminWidth?: WidgetWidth\n\tmaxWidth?: WidgetWidth\n\tfields: (args: RegisterWidgetsArgs) => Field[]\n}\n\nexport const widgetIsSupported = (\n\trequires: CapabilityRequirement | undefined,\n\tadapters: AnalyticsAdapter[]\n): boolean => !requires || adapters.some((a) => satisfiesCapabilities(a.capabilities, requires))\n\n/**\n * The widget metric select. Options are limited to metrics at least one configured\n * adapter can serve, mirroring the OR-across-adapters gating used to hide whole widgets;\n * `extra` layers on further requirements (a breakdown widget's dimension, realtime) so\n * the picker never offers a metric the read path would report as unavailable. In\n * multi-provider installs `filterOptions` additionally narrows the picker to the selected\n * `dataSource`'s capabilities; an id not known at config time (a runtime/DB provider)\n * keeps the union. The default clamps to the first option when the preferred metric is\n * not servable, and options can come out empty for exotic adapter sets, which\n * {@link registerWidgets} treats as \"skip this widget\". When `providersEnabled`, the\n * config-adapter filter is skipped entirely: a tenant's own runtime adapter may serve\n * metrics no config adapter does, so every candidate is offered and `filterOptions` alone\n * narrows once a `dataSource` is picked.\n */\nconst metricSelectField = (\n\tcandidates: MetricKey[],\n\targs: RegisterWidgetsArgs,\n\topts: {\n\t\textra?: Omit<CapabilityRequirement, 'metrics'>\n\t\tpreferredDefault?: MetricKey\n\t} = {}\n): Field => {\n\tconst { extra, preferredDefault = 'pageviews' } = opts\n\tconst supports = (adapter: AnalyticsAdapter, metric: MetricKey): boolean =>\n\t\tsatisfiesCapabilities(adapter.capabilities, { ...extra, metrics: [metric] })\n\tconst options = (\n\t\targs.providersEnabled\n\t\t\t? candidates\n\t\t\t: candidates.filter((m) => args.adapters.some((a) => supports(a, m)))\n\t).map((m) => ({ value: m, label: staticLabel(METRIC_KEYS[m]) }))\n\tconst defaultValue = options.some((o) => o.value === preferredDefault)\n\t\t? preferredDefault\n\t\t: options[0]?.value\n\tconst filterOptions: SelectField['filterOptions'] = ({ options: opts, siblingData }) => {\n\t\tconst sourceId = (siblingData as { dataSource?: unknown } | undefined)?.dataSource\n\t\tconst adapter =\n\t\t\ttypeof sourceId === 'string' ? args.adapters.find((a) => a.id === sourceId) : undefined\n\t\tif (!adapter) {\n\t\t\treturn opts\n\t\t}\n\t\treturn opts.filter((o) => typeof o === 'object' && supports(adapter, o.value as MetricKey))\n\t}\n\treturn {\n\t\tname: 'metric',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\t...(defaultValue !== undefined ? { defaultValue } : {}),\n\t\tlabel: labelForKey(keys.widgetFieldMetric),\n\t\toptions,\n\t\tadmin: {\n\t\t\t// A required metric has no meaningful cleared state.\n\t\t\tisClearable: false,\n\t\t\tcomponents: {\n\t\t\t\tField: {\n\t\t\t\t\tpath: '@10x-media/analytics/client#MetricSelectField',\n\t\t\t\t\t...(extra ? { clientProps: { requires: extra } } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t...(args.multiProvider ? { filterOptions } : {}),\n\t}\n}\n\nconst titleField = (args: RegisterWidgetsArgs, placeholder: string): Field => ({\n\tname: 'title',\n\ttype: 'text',\n\tlabel: labelForKey(keys.widgetFieldTitle),\n\t...(args.localizeText ? { localized: true } : {}),\n\tadmin: { placeholder },\n})\n\nconst timeframeSelectField = (): Field => ({\n\tname: 'timeframe',\n\ttype: 'select',\n\trequired: true,\n\tdefaultValue: 'last30days',\n\tlabel: labelForKey(keys.widgetFieldTimeframe),\n\tadmin: { isClearable: false },\n\toptions: [\n\t\t...TIMEFRAME_PRESETS.map((p) => ({ value: p, label: labelForKey(TIMEFRAME_KEYS[p]) })),\n\t\t{ value: 'custom', label: labelForKey(keys.widgetTimeframeCustom) },\n\t],\n})\n\nconst dataSourceField = (args: RegisterWidgetsArgs): Field => ({\n\tname: 'dataSource',\n\ttype: 'select',\n\tlabel: labelForKey(keys.widgetFieldDataSource),\n\tdefaultValue: args.defaultId ?? args.adapters[0]?.id,\n\tadmin: {\n\t\t// Clearing would leave no source; the widget always reads through one.\n\t\tisClearable: false,\n\t\tcomponents: { Field: { path: '@10x-media/analytics/client#SourceSelectField' } },\n\t},\n\toptions: args.adapters.map((a) => ({ value: a.id, label: a.label })),\n\t// Payload's select validator rejects any value absent from `options`, but runtime\n\t// (DB-registered) provider ids are only known per request, not at config time.\n\tvalidate: ((value) =>\n\t\tvalue === undefined || value === null || (typeof value === 'string' && value.length > 0)\n\t\t\t? true\n\t\t\t: 'invalid data source') as SelectFieldSingleValidation,\n})\n\nconst customRangeField = (): Field =>\n\tdateRangeField({\n\t\tname: 'range',\n\t\tlabel: labelForKey(keys.widgetFieldRange),\n\t\tpickerAppearance: 'dayOnly',\n\t\toverrides: (f) => ({\n\t\t\t...f,\n\t\t\tadmin: {\n\t\t\t\t...f.admin,\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.timeframe === 'custom',\n\t\t\t},\n\t\t}),\n\t})\n\n/** The metric select in a widget's field list. */\nexport const findMetricField = (fields: Field[]): Field | undefined =>\n\tfields.find((field) => 'name' in field && field.name === 'metric')\n\nconst metricWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(WIDGET_METRICS, args),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst breakdownWidgetFields = (args: RegisterWidgetsArgs, spec: BreakdownSpec): Field[] => [\n\ttitleField(args, en[spec.label]),\n\t// A goals breakdown is a conversion table: pageviews per goal is a stranger default.\n\tmetricSelectField(WIDGET_METRICS, args, {\n\t\textra: { dimensions: [spec.dimension] },\n\t\t...(spec.dimension === 'goal' ? { preferredDefault: 'conversions' as MetricKey } : {}),\n\t}),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t{\n\t\tname: 'limit',\n\t\ttype: 'number',\n\t\tdefaultValue: 5,\n\t\tmin: 1,\n\t\tmax: 20,\n\t\tlabel: labelForKey(keys.widgetFieldLimit),\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst realtimeWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(['visitors', 'pageviews'], args, {\n\t\textra: { realtime: true },\n\t\tpreferredDefault: 'visitors',\n\t}),\n\t{\n\t\tname: 'windowMinutes',\n\t\ttype: 'select',\n\t\tdefaultValue: '30',\n\t\tlabel: labelForKey(keys.widgetFieldWindow),\n\t\tadmin: { isClearable: false },\n\t\toptions: [\n\t\t\t{ value: '5', label: '5 min' },\n\t\t\t{ value: '15', label: '15 min' },\n\t\t\t{ value: '30', label: '30 min' },\n\t\t\t{ value: '60', label: '60 min' },\n\t\t],\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst WIDGET_DEFS: WidgetDef[] = [\n\t{\n\t\tslug: 'analytics-metric',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsMetricWidget',\n\t\tlabel: keys.widgetMetricLabel,\n\t\tminWidth: 'x-small',\n\t\tmaxWidth: 'medium',\n\t\tfields: metricWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-trend',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsTrendWidget',\n\t\tlabel: keys.widgetTrendLabel,\n\t\trequires: { metrics: ['pageviews'] },\n\t\tminWidth: 'small',\n\t\tmaxWidth: 'full',\n\t\tfields: metricWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-realtime',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsRealtimeWidget',\n\t\tlabel: keys.widgetRealtimeLabel,\n\t\trequires: { realtime: true },\n\t\tminWidth: 'small' as WidgetWidth,\n\t\tmaxWidth: 'medium' as WidgetWidth,\n\t\tfields: realtimeWidgetFields,\n\t},\n\t...BREAKDOWN_SPECS.map(\n\t\t(spec): WidgetDef => ({\n\t\t\tslug: spec.slug,\n\t\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsBreakdownWidget',\n\t\t\tlabel: spec.label,\n\t\t\trequires: { dimensions: [spec.dimension] },\n\t\t\tminWidth: 'small' as WidgetWidth,\n\t\t\tmaxWidth: 'large' as WidgetWidth,\n\t\t\tfields: (args) => breakdownWidgetFields(args, spec),\n\t\t})\n\t),\n]\n\nexport const registerWidgets = (config: Config, args: RegisterWidgetsArgs): void => {\n\tconst built: Widget[] = []\n\tfor (const def of WIDGET_DEFS) {\n\t\tif (args.disabled.includes(def.slug)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!args.providersEnabled && !widgetIsSupported(def.requires, args.adapters)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst fields = def.fields(args)\n\t\t// A required metric select with no servable option would make the widget\n\t\t// impossible to configure; skip it like an unsupported widget.\n\t\tconst metricField = findMetricField(fields)\n\t\tif (metricField && 'options' in metricField && metricField.options.length === 0) {\n\t\t\tcontinue\n\t\t}\n\t\tbuilt.push({\n\t\t\tslug: def.slug,\n\t\t\tComponent: def.component,\n\t\t\tlabel: labelForKey(def.label),\n\t\t\tfields,\n\t\t\tminWidth: def.minWidth,\n\t\t\tmaxWidth: def.maxWidth,\n\t\t})\n\t}\n\tbuilt.push(...buildCustomWidgets(args.register, args.adapters, args.disabled))\n\tif (!built.length) {\n\t\treturn\n\t}\n\tconfig.admin ??= {}\n\tconfig.admin.dashboard ??= { widgets: [] }\n\tconfig.admin.dashboard.widgets ??= []\n\tconfig.admin.dashboard.widgets.push(...built)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAM,eAAe,SAAiD;CACrE,IAAI,GAAG;CACP,IAAI,GAAG;AACR;AA8BA,MAAa,qBACZ,UACA,aACa,CAAC,YAAY,SAAS,MAAM,MAAM,sBAAsB,EAAE,cAAc,QAAQ,CAAC;;;;;;;;;;;;;;;AAgB/F,MAAM,qBACL,YACA,MACA,OAGI,CAAC,MACM;CACX,MAAM,EAAE,OAAO,mBAAmB,gBAAgB;CAClD,MAAM,YAAY,SAA2B,WAC5C,sBAAsB,QAAQ,cAAc;EAAE,GAAG;EAAO,SAAS,CAAC,MAAM;CAAE,CAAC;CAC5E,MAAM,WACL,KAAK,mBACF,aACA,WAAW,QAAQ,MAAM,KAAK,SAAS,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,CAAC,GACpE,KAAK,OAAO;EAAE,OAAO;EAAG,OAAO,YAAY,YAAY,EAAE;CAAE,EAAE;CAC/D,MAAM,eAAe,QAAQ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AAM,SAAS,IAAI,OAAO,IAAI;EAG9B,MAAM,cAAc,gBAAgB,MAAM;EAC1C,IAAI,eAAe,aAAa,eAAe,YAAY,QAAQ,WAAW,GAC7E;EAED,MAAM,KAAK;GACV,MAAM,IAAI;GACV,WAAW,IAAI;GACf,OAAO,YAAY,IAAI,KAAK;GAC5B;GACA,UAAU,IAAI;GACd,UAAU,IAAI;EACf,CAAC;CACF;CACA,MAAM,KAAK,GAAG,mBAAmB,KAAK,UAAU,KAAK,UAAU,KAAK,QAAQ,CAAC;CAC7E,IAAI,CAAC,MAAM,QACV;CAED,OAAO,UAAU,CAAC;CAClB,OAAO,MAAM,cAAc,EAAE,SAAS,CAAC,EAAE;CACzC,OAAO,MAAM,UAAU,YAAY,CAAC;CACpC,OAAO,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;AAC7C"}
|
|
1
|
+
{"version":3,"file":"registerWidgets.js","names":[],"sources":["../../src/widgets/registerWidgets.ts"],"sourcesContent":["import type {\n\tConfig,\n\tField,\n\tSelectField,\n\tSelectFieldSingleValidation,\n\tWidget,\n\tWidgetWidth,\n} from 'payload'\nimport { type CapabilityRequirement, satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { dateRangeField } from '../fields/dateRange/field'\nimport { TIMEFRAME_PRESETS } from '../timeframe/presets'\nimport { de } from '../translations/de'\nimport { en } from '../translations/en'\nimport type { TranslationKey } from '../translations/keys'\nimport { keys } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { labelForKey } from '../translations/server'\nimport { BREAKDOWN_SPECS, type BreakdownSpec } from './breakdownTypes'\nimport { buildCustomWidgets, type CustomWidgetDef } from './customWidget'\nimport { GOAL_ROW_LIMITS, WIDGET_METRICS } from './types'\nimport type { WidgetView } from './viewLink'\n\n/**\n * Select options must carry static labels: `filterOptions` results are serialized\n * into client form state at request time, where a label function cannot cross the\n * server/client boundary.\n */\nconst staticLabel = (key: TranslationKey): Record<string, string> => ({\n\tde: de[key],\n\ten: en[key],\n})\n\nexport interface RegisterWidgetsArgs {\n\tadapters: AnalyticsAdapter[]\n\tmultiProvider: boolean\n\t/**\n\t * True when a tenant's own runtime adapter can exist (`providers.collection` or\n\t * `providers.resolve`). Such an adapter's capabilities are unknown at config time, so\n\t * gating on the config-adapter union would impose a false ceiling: widgets and metric\n\t * options open up, and the per-request sources endpoint plus client pickers narrow per\n\t * request instead.\n\t */\n\tprovidersEnabled: boolean\n\tdisabled: string[]\n\tregister: CustomWidgetDef[]\n\tlocalizeText?: boolean\n\t/** The plugin's configured defaultAdapter, when set; falls back to the first adapter. */\n\tdefaultId?: string\n\t/** `widgets.comparison`; false hides every compare checkbox. Defaults to on. */\n\tcomparison?: boolean\n\t/**\n\t * Where the analytics view mounts, so every built-in widget can link into it. False or\n\t * absent means no view to link to, and the widgets render without the footer link.\n\t */\n\tview?: WidgetView\n}\n\ninterface WidgetDef {\n\tslug: string\n\tcomponent: string\n\tlabel: TranslationKey\n\trequires?: CapabilityRequirement\n\tminWidth?: WidgetWidth\n\tmaxWidth?: WidgetWidth\n\tfields: (args: RegisterWidgetsArgs) => Field[]\n}\n\nexport const widgetIsSupported = (\n\trequires: CapabilityRequirement | undefined,\n\tadapters: AnalyticsAdapter[]\n): boolean => !requires || adapters.some((a) => satisfiesCapabilities(a.capabilities, requires))\n\n/**\n * The widget metric select. Options are limited to metrics at least one configured\n * adapter can serve, mirroring the OR-across-adapters gating used to hide whole widgets;\n * `extra` layers on further requirements (a breakdown widget's dimension, realtime) so\n * the picker never offers a metric the read path would report as unavailable. In\n * multi-provider installs `filterOptions` additionally narrows the picker to the selected\n * `dataSource`'s capabilities; an id not known at config time (a runtime/DB provider)\n * keeps the union. The default clamps to the first option when the preferred metric is\n * not servable, and options can come out empty for exotic adapter sets, which\n * {@link registerWidgets} treats as \"skip this widget\". When `providersEnabled`, the\n * config-adapter filter is skipped entirely: a tenant's own runtime adapter may serve\n * metrics no config adapter does, so every candidate is offered and `filterOptions` alone\n * narrows once a `dataSource` is picked.\n */\nconst metricSelectField = (\n\tcandidates: MetricKey[],\n\targs: RegisterWidgetsArgs,\n\topts: {\n\t\textra?: Omit<CapabilityRequirement, 'metrics'>\n\t\tpreferredDefault?: MetricKey\n\t} = {}\n): Field => {\n\tconst { extra, preferredDefault = 'pageviews' } = opts\n\tconst supports = (adapter: AnalyticsAdapter, metric: MetricKey): boolean =>\n\t\tsatisfiesCapabilities(adapter.capabilities, { ...extra, metrics: [metric] })\n\tconst options = (\n\t\targs.providersEnabled\n\t\t\t? candidates\n\t\t\t: candidates.filter((m) => args.adapters.some((a) => supports(a, m)))\n\t).map((m) => ({ value: m, label: staticLabel(METRIC_KEYS[m]) }))\n\tconst defaultValue = options.some((o) => o.value === preferredDefault)\n\t\t? preferredDefault\n\t\t: options[0]?.value\n\tconst filterOptions: SelectField['filterOptions'] = ({ options: opts, siblingData }) => {\n\t\tconst sourceId = (siblingData as { dataSource?: unknown } | undefined)?.dataSource\n\t\tconst adapter =\n\t\t\ttypeof sourceId === 'string' ? args.adapters.find((a) => a.id === sourceId) : undefined\n\t\tif (!adapter) {\n\t\t\treturn opts\n\t\t}\n\t\treturn opts.filter((o) => typeof o === 'object' && supports(adapter, o.value as MetricKey))\n\t}\n\treturn {\n\t\tname: 'metric',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\t...(defaultValue !== undefined ? { defaultValue } : {}),\n\t\tlabel: labelForKey(keys.widgetFieldMetric),\n\t\toptions,\n\t\tadmin: {\n\t\t\t// A required metric has no meaningful cleared state.\n\t\t\tisClearable: false,\n\t\t\tcomponents: {\n\t\t\t\tField: {\n\t\t\t\t\tpath: '@10x-media/analytics/client#MetricSelectField',\n\t\t\t\t\t...(extra ? { clientProps: { requires: extra } } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t...(args.multiProvider ? { filterOptions } : {}),\n\t}\n}\n\nconst titleField = (args: RegisterWidgetsArgs, placeholder: string): Field => ({\n\tname: 'title',\n\ttype: 'text',\n\tlabel: labelForKey(keys.widgetFieldTitle),\n\t...(args.localizeText ? { localized: true } : {}),\n\tadmin: { placeholder },\n})\n\nconst timeframeSelectField = (): Field => ({\n\tname: 'timeframe',\n\ttype: 'select',\n\trequired: true,\n\tdefaultValue: 'last30days',\n\tlabel: labelForKey(keys.widgetFieldTimeframe),\n\tadmin: { isClearable: false },\n\toptions: [\n\t\t...TIMEFRAME_PRESETS.map((p) => ({ value: p, label: labelForKey(TIMEFRAME_KEYS[p]) })),\n\t\t{ value: 'custom', label: labelForKey(keys.widgetTimeframeCustom) },\n\t],\n})\n\n/** Reads the previous period too: the trend overlays it, the goals table deltas against it. */\nconst compareField = (): Field => ({\n\tname: 'compare',\n\ttype: 'checkbox',\n\tdefaultValue: false,\n\tlabel: labelForKey(keys.widgetFieldCompare),\n})\n\nconst dataSourceField = (args: RegisterWidgetsArgs): Field => ({\n\tname: 'dataSource',\n\ttype: 'select',\n\tlabel: labelForKey(keys.widgetFieldDataSource),\n\tdefaultValue: args.defaultId ?? args.adapters[0]?.id,\n\tadmin: {\n\t\t// Clearing would leave no source; the widget always reads through one.\n\t\tisClearable: false,\n\t\tcomponents: { Field: { path: '@10x-media/analytics/client#SourceSelectField' } },\n\t},\n\toptions: args.adapters.map((a) => ({ value: a.id, label: a.label })),\n\t// Payload's select validator rejects any value absent from `options`, but runtime\n\t// (DB-registered) provider ids are only known per request, not at config time.\n\tvalidate: ((value) =>\n\t\tvalue === undefined || value === null || (typeof value === 'string' && value.length > 0)\n\t\t\t? true\n\t\t\t: 'invalid data source') as SelectFieldSingleValidation,\n})\n\nconst customRangeField = (): Field =>\n\tdateRangeField({\n\t\tname: 'range',\n\t\tlabel: labelForKey(keys.widgetFieldRange),\n\t\tpickerAppearance: 'dayOnly',\n\t\toverrides: (f) => ({\n\t\t\t...f,\n\t\t\tadmin: {\n\t\t\t\t...f.admin,\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.timeframe === 'custom',\n\t\t\t},\n\t\t}),\n\t})\n\n/** The metric select in a widget's field list. */\nexport const findMetricField = (fields: Field[]): Field | undefined =>\n\tfields.find((field) => 'name' in field && field.name === 'metric')\n\nconst metricWidgetFields = (args: RegisterWidgetsArgs, extra: Field[] = []): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(WIDGET_METRICS, args),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t...extra,\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst breakdownWidgetFields = (args: RegisterWidgetsArgs, spec: BreakdownSpec): Field[] => [\n\ttitleField(args, en[spec.label]),\n\tmetricSelectField(WIDGET_METRICS, args, {\n\t\textra: { dimensions: [spec.dimension] },\n\t\t...(spec.preferredDefault ? { preferredDefault: spec.preferredDefault } : {}),\n\t}),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t{\n\t\tname: 'limit',\n\t\ttype: 'number',\n\t\tdefaultValue: 5,\n\t\tmin: 1,\n\t\tmax: 20,\n\t\tlabel: labelForKey(keys.widgetFieldLimit),\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\n/** A select, not the breakdown's free number: the goals table is a summary, not a report. */\nconst goalLimitField = (): Field => ({\n\tname: 'limit',\n\ttype: 'select',\n\tdefaultValue: String(GOAL_ROW_LIMITS[0]),\n\tlabel: labelForKey(keys.widgetFieldLimit),\n\tadmin: { isClearable: false },\n\toptions: GOAL_ROW_LIMITS.map((limit) => ({ value: String(limit), label: String(limit) })),\n})\n\nconst goalsWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetGoals]),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\tgoalLimitField(),\n\t...(args.comparison === false ? [] : [compareField()]),\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst realtimeWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(['visitors', 'pageviews'], args, {\n\t\textra: { realtime: true },\n\t\tpreferredDefault: 'visitors',\n\t}),\n\t{\n\t\tname: 'windowMinutes',\n\t\ttype: 'select',\n\t\tdefaultValue: '30',\n\t\tlabel: labelForKey(keys.widgetFieldWindow),\n\t\tadmin: { isClearable: false },\n\t\toptions: [\n\t\t\t{ value: '5', label: '5 min' },\n\t\t\t{ value: '15', label: '15 min' },\n\t\t\t{ value: '30', label: '30 min' },\n\t\t\t{ value: '60', label: '60 min' },\n\t\t],\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst WIDGET_DEFS: WidgetDef[] = [\n\t{\n\t\tslug: 'analytics-metric',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsMetricWidget',\n\t\tlabel: keys.widgetMetricLabel,\n\t\tminWidth: 'x-small',\n\t\tmaxWidth: 'medium',\n\t\tfields: metricWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-trend',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsTrendWidget',\n\t\tlabel: keys.widgetTrendLabel,\n\t\trequires: { metrics: ['pageviews'] },\n\t\tminWidth: 'small',\n\t\tmaxWidth: 'full',\n\t\tfields: (args) => metricWidgetFields(args, args.comparison === false ? [] : [compareField()]),\n\t},\n\t{\n\t\tslug: 'analytics-realtime',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsRealtimeWidget',\n\t\tlabel: keys.widgetRealtimeLabel,\n\t\trequires: { realtime: true },\n\t\tminWidth: 'small' as WidgetWidth,\n\t\tmaxWidth: 'medium' as WidgetWidth,\n\t\tfields: realtimeWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-goals',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsGoalsWidget',\n\t\tlabel: keys.widgetGoals,\n\t\trequires: { metrics: ['conversions'], dimensions: ['goal'] },\n\t\tminWidth: 'small' as WidgetWidth,\n\t\tmaxWidth: 'large' as WidgetWidth,\n\t\tfields: goalsWidgetFields,\n\t},\n\t...BREAKDOWN_SPECS.map(\n\t\t(spec): WidgetDef => ({\n\t\t\tslug: spec.slug,\n\t\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsBreakdownWidget',\n\t\t\tlabel: spec.label,\n\t\t\trequires: { dimensions: [spec.dimension] },\n\t\t\tminWidth: 'small' as WidgetWidth,\n\t\t\tmaxWidth: 'large' as WidgetWidth,\n\t\t\tfields: (args) => breakdownWidgetFields(args, spec),\n\t\t})\n\t),\n]\n\nexport const registerWidgets = (config: Config, args: RegisterWidgetsArgs): void => {\n\tconst built: Widget[] = []\n\tfor (const def of WIDGET_DEFS) {\n\t\tif (args.disabled.includes(def.slug)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!args.providersEnabled && !widgetIsSupported(def.requires, args.adapters)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst fields = def.fields(args)\n\t\t// A required metric select with no servable option would make the widget\n\t\t// impossible to configure; skip it like an unsupported widget.\n\t\tconst metricField = findMetricField(fields)\n\t\tif (metricField && 'options' in metricField && metricField.options.length === 0) {\n\t\t\tcontinue\n\t\t}\n\t\tbuilt.push({\n\t\t\tslug: def.slug,\n\t\t\tComponent: { path: def.component, serverProps: { view: args.view ?? false } },\n\t\t\tlabel: labelForKey(def.label),\n\t\t\tfields,\n\t\t\tminWidth: def.minWidth,\n\t\t\tmaxWidth: def.maxWidth,\n\t\t})\n\t}\n\tbuilt.push(...buildCustomWidgets(args.register, args.adapters, args.disabled))\n\tif (!built.length) {\n\t\treturn\n\t}\n\tconfig.admin ??= {}\n\tconfig.admin.dashboard ??= { widgets: [] }\n\tconfig.admin.dashboard.widgets ??= []\n\tconfig.admin.dashboard.widgets.push(...built)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAM,eAAe,SAAiD;CACrE,IAAI,GAAG;CACP,IAAI,GAAG;AACR;AAqCA,MAAa,qBACZ,UACA,aACa,CAAC,YAAY,SAAS,MA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AAC,kBAAkB,IAAI,UAAU,KAAK,QAAQ,GAC3E;EAED,MAAM,SAAS,IAAI,OAAO,IAAI;EAG9B,MAAM,cAAc,gBAAgB,MAAM;EAC1C,IAAI,eAAe,aAAa,eAAe,YAAY,QAAQ,WAAW,GAC7E;EAED,MAAM,KAAK;GACV,MAAM,IAAI;GACV,WAAW;IAAE,MAAM,IAAI;IAAW,aAAa,EAAE,MAAM,KAAK,QAAQ,MAAM;GAAE;GAC5E,OAAO,YAAY,IAAI,KAAK;GAC5B;GACA,UAAU,IAAI;GACd,UAAU,IAAI;EACf,CAAC;CACF;CACA,MAAM,KAAK,GAAG,mBAAmB,KAAK,UAAU,KAAK,UAAU,KAAK,QAAQ,CAAC;CAC7E,IAAI,CAAC,MAAM,QACV;CAED,OAAO,UAAU,CAAC;CAClB,OAAO,MAAM,cAAc,EAAE,SAAS,CAAC,EAAE;CACzC,OAAO,MAAM,UAAU,YAAY,CAAC;CACpC,OAAO,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;AAC7C"}
|
package/dist/widgets/types.js
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
1
|
//#region src/widgets/types.ts
|
|
2
|
+
/** Row counts the goals widget offers; the first is its default. */
|
|
3
|
+
const GOAL_ROW_LIMITS = [
|
|
4
|
+
10,
|
|
5
|
+
25,
|
|
6
|
+
50
|
|
7
|
+
];
|
|
8
|
+
/** The stored select value as a row count, falling back to the default for anything else. */
|
|
9
|
+
const resolveGoalRowLimit = (value) => {
|
|
10
|
+
const parsed = typeof value === "string" || typeof value === "number" ? Number(value) : NaN;
|
|
11
|
+
return GOAL_ROW_LIMITS.find((limit) => limit === parsed) ?? GOAL_ROW_LIMITS[0];
|
|
12
|
+
};
|
|
2
13
|
const WIDGET_METRICS = [
|
|
3
14
|
"pageviews",
|
|
4
15
|
"visitors",
|
|
@@ -11,6 +22,6 @@ const WIDGET_METRICS = [
|
|
|
11
22
|
"scrollDepth"
|
|
12
23
|
];
|
|
13
24
|
//#endregion
|
|
14
|
-
export { WIDGET_METRICS };
|
|
25
|
+
export { GOAL_ROW_LIMITS, WIDGET_METRICS, resolveGoalRowLimit };
|
|
15
26
|
|
|
16
27
|
//# sourceMappingURL=types.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../src/widgets/types.ts"],"sourcesContent":["import type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\n\nexport interface WidgetRange {\n\tfrom?: string\n\tto?: string\n}\n\nexport interface MetricWidgetData {\n\ttitle?: string\n\tmetric?: MetricKey\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\tdataSource?: string\n}\n\nexport const WIDGET_METRICS: MetricKey[] = [\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'avgDuration',\n\t'bounceRate',\n\t'events',\n\t'conversions',\n\t'revenue',\n\t'scrollDepth',\n]\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../src/widgets/types.ts"],"sourcesContent":["import type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\n\nexport interface WidgetRange {\n\tfrom?: string\n\tto?: string\n}\n\nexport interface MetricWidgetData {\n\ttitle?: string\n\tmetric?: MetricKey\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\tdataSource?: string\n\t/** Trend widget only: overlay the previous period on the chart. */\n\tcompare?: boolean\n}\n\nexport interface GoalsWidgetData {\n\ttitle?: string\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\t/** One of {@link GOAL_ROW_LIMITS}, stored as the select's string value. */\n\tlimit?: string | number\n\tcompare?: boolean\n\tdataSource?: string\n}\n\n/** Row counts the goals widget offers; the first is its default. */\nexport const GOAL_ROW_LIMITS = [10, 25, 50] as const\n\nexport type GoalRowLimit = (typeof GOAL_ROW_LIMITS)[number]\n\n/** The stored select value as a row count, falling back to the default for anything else. */\nexport const resolveGoalRowLimit = (value: unknown): GoalRowLimit => {\n\tconst parsed = typeof value === 'string' || typeof value === 'number' ? Number(value) : Number.NaN\n\tconst match = GOAL_ROW_LIMITS.find((limit) => limit === parsed)\n\treturn match ?? GOAL_ROW_LIMITS[0]\n}\n\nexport const WIDGET_METRICS: MetricKey[] = [\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'avgDuration',\n\t'bounceRate',\n\t'events',\n\t'conversions',\n\t'revenue',\n\t'scrollDepth',\n]\n"],"mappings":";;AA6BA,MAAa,kBAAkB;CAAC;CAAI;CAAI;AAAE;;AAK1C,MAAa,uBAAuB,UAAiC;CACpE,MAAM,SAAS,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;CAExF,OADc,gBAAgB,MAAM,UAAU,UAAU,MAC7C,KAAK,gBAAgB;AACjC;AAEA,MAAa,iBAA8B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { MetricKey } from "../core/contract.js";
|
|
2
|
+
import { TimeframePreset } from "../timeframe/presets.js";
|
|
3
|
+
import { PayloadRequest } from "payload";
|
|
4
|
+
|
|
5
|
+
//#region src/widgets/viewLink.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The view as a widget sees it: where it mounts and what it opens on, or false when the
|
|
8
|
+
* app turned it off. The defaults travel with the path because a link must leave out
|
|
9
|
+
* exactly what the view would have defaulted to anyway.
|
|
10
|
+
*/
|
|
11
|
+
type WidgetView = {
|
|
12
|
+
path: string;
|
|
13
|
+
defaultRange: TimeframePreset;
|
|
14
|
+
defaultMetric: MetricKey;
|
|
15
|
+
} | false;
|
|
16
|
+
/** What `registerWidgets` adds to every built-in widget's server props. */
|
|
17
|
+
interface WidgetViewProps {
|
|
18
|
+
view?: WidgetView;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
export { WidgetViewProps };
|
|
22
|
+
//# sourceMappingURL=viewLink.d.ts.map
|