@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,206 @@
|
|
|
1
|
+
import { DIMENSION_KEYS, FILTER_OPERATORS } from "../core/contract.js";
|
|
2
|
+
import { zonedCalendarDay } from "../timeframe/tz.js";
|
|
3
|
+
import { TIMEFRAME_PRESETS, resolveTimeframe } from "../timeframe/presets.js";
|
|
4
|
+
import { GRANULARITY_ORDER } from "../core/granularity.js";
|
|
5
|
+
import { BREAKDOWN_TABS, VIEW_METRIC_ORDER } from "./gating.js";
|
|
6
|
+
//#region src/view/state.ts
|
|
7
|
+
/**
|
|
8
|
+
* The presets the toolbar offers. `allTime` is deliberately absent: it is unbounded, and
|
|
9
|
+
* the query endpoint refuses any window longer than a year.
|
|
10
|
+
*/
|
|
11
|
+
const VIEW_RANGE_PRESETS = [
|
|
12
|
+
"today",
|
|
13
|
+
"last7days",
|
|
14
|
+
"last30days",
|
|
15
|
+
"last90days",
|
|
16
|
+
"lastYear"
|
|
17
|
+
];
|
|
18
|
+
const DEFAULT_VIEW_RANGE = "last30days";
|
|
19
|
+
const VIEW_LIMITS = [
|
|
20
|
+
10,
|
|
21
|
+
25,
|
|
22
|
+
50,
|
|
23
|
+
100
|
|
24
|
+
];
|
|
25
|
+
const DEFAULT_VIEW_TAB = "pages";
|
|
26
|
+
const KNOWN_METRICS = new Set(VIEW_METRIC_ORDER);
|
|
27
|
+
const KNOWN_DIMENSIONS = new Set(DIMENSION_KEYS);
|
|
28
|
+
const KNOWN_OPERATORS = new Set(FILTER_OPERATORS);
|
|
29
|
+
const KNOWN_GRANULARITIES = new Set(GRANULARITY_ORDER);
|
|
30
|
+
const KNOWN_PRESETS = new Set(TIMEFRAME_PRESETS);
|
|
31
|
+
const DAY_MS = 864e5;
|
|
32
|
+
const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
33
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
34
|
+
const read = (search, name) => {
|
|
35
|
+
const raw = search.get(name)?.trim();
|
|
36
|
+
return raw ? raw : null;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Epoch ms of a `YYYY-MM-DD` day, or null when it names no real calendar day. The
|
|
40
|
+
* round trip is the validation: `Date.parse` rolls February 30 forward instead of failing.
|
|
41
|
+
*/
|
|
42
|
+
const dayValue = (raw) => {
|
|
43
|
+
if (raw === null || !DAY_PATTERN.test(raw)) return null;
|
|
44
|
+
const ms = Date.parse(`${raw}T00:00:00.000Z`);
|
|
45
|
+
if (Number.isNaN(ms) || new Date(ms).toISOString().slice(0, 10) !== raw) return null;
|
|
46
|
+
return ms;
|
|
47
|
+
};
|
|
48
|
+
/** A configured default the view cannot serve falls back to the built-in range. */
|
|
49
|
+
const defaultRange = (defaults) => defaults.range === "allTime" ? DEFAULT_VIEW_RANGE : defaults.range;
|
|
50
|
+
const parseRange = (search, defaults) => {
|
|
51
|
+
const fallback = { range: defaultRange(defaults) };
|
|
52
|
+
const raw = read(search, "range");
|
|
53
|
+
if (raw === null) return fallback;
|
|
54
|
+
if (raw === "custom") {
|
|
55
|
+
const from = dayValue(read(search, "from"));
|
|
56
|
+
const to = dayValue(read(search, "to"));
|
|
57
|
+
if (from === null || to === null || to < from) return fallback;
|
|
58
|
+
if (Math.round((to - from) / DAY_MS) + 1 > 366) return fallback;
|
|
59
|
+
return {
|
|
60
|
+
range: "custom",
|
|
61
|
+
from: new Date(from).toISOString().slice(0, 10),
|
|
62
|
+
to: new Date(to).toISOString().slice(0, 10)
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
if (!KNOWN_PRESETS.has(raw) || raw === "allTime") return fallback;
|
|
66
|
+
return { range: raw };
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Filters as the endpoint's own parser would accept them, minus its errors: an entry
|
|
70
|
+
* naming a dimension, operator or value outside the contract is dropped rather than
|
|
71
|
+
* failing the whole URL, since a hand-edited link should still open a working view.
|
|
72
|
+
*/
|
|
73
|
+
const parseFilters = (search) => {
|
|
74
|
+
const raw = read(search, "filters");
|
|
75
|
+
if (raw === null) return [];
|
|
76
|
+
let decoded;
|
|
77
|
+
try {
|
|
78
|
+
decoded = JSON.parse(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
if (!Array.isArray(decoded)) return [];
|
|
83
|
+
const filters = [];
|
|
84
|
+
for (const item of decoded) {
|
|
85
|
+
if (filters.length === 10) break;
|
|
86
|
+
if (!isRecord(item)) continue;
|
|
87
|
+
const { dimension, operator, value } = item;
|
|
88
|
+
if (typeof dimension !== "string" || !KNOWN_DIMENSIONS.has(dimension)) continue;
|
|
89
|
+
if (typeof operator !== "string" || !KNOWN_OPERATORS.has(operator)) continue;
|
|
90
|
+
if (typeof value !== "string") continue;
|
|
91
|
+
const trimmed = value.trim();
|
|
92
|
+
if (trimmed.length < 1 || trimmed.length > 256) continue;
|
|
93
|
+
filters.push({
|
|
94
|
+
dimension,
|
|
95
|
+
operator,
|
|
96
|
+
value: trimmed
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return filters;
|
|
100
|
+
};
|
|
101
|
+
const parseOrder = (search) => {
|
|
102
|
+
const raw = read(search, "order");
|
|
103
|
+
if (raw === null) return;
|
|
104
|
+
const parts = raw.split(":");
|
|
105
|
+
const metric = parts[0] ?? "";
|
|
106
|
+
const direction = parts[1] ?? "";
|
|
107
|
+
if (parts.length !== 2 || !KNOWN_METRICS.has(metric)) return;
|
|
108
|
+
if (direction !== "asc" && direction !== "desc") return;
|
|
109
|
+
return {
|
|
110
|
+
metric,
|
|
111
|
+
direction
|
|
112
|
+
};
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* Total by construction: every value the URL cannot justify falls back to the install
|
|
116
|
+
* default, so a truncated, stale or hand-edited link always opens a working view.
|
|
117
|
+
*/
|
|
118
|
+
const parseViewState = (search, defaults) => {
|
|
119
|
+
const metric = read(search, "metric");
|
|
120
|
+
const granularity = read(search, "granularity");
|
|
121
|
+
const tab = read(search, "tab");
|
|
122
|
+
const source = read(search, "source");
|
|
123
|
+
const limit = Number(read(search, "limit"));
|
|
124
|
+
const compare = read(search, "compare");
|
|
125
|
+
const order = parseOrder(search);
|
|
126
|
+
return {
|
|
127
|
+
...parseRange(search, defaults),
|
|
128
|
+
compare: compare === "1" || compare === "true",
|
|
129
|
+
...source === null ? {} : { source },
|
|
130
|
+
metric: metric !== null && KNOWN_METRICS.has(metric) ? metric : defaults.metric,
|
|
131
|
+
...granularity !== null && KNOWN_GRANULARITIES.has(granularity) ? { granularity } : {},
|
|
132
|
+
tab: tab !== null && BREAKDOWN_TABS.includes(tab) ? tab : DEFAULT_VIEW_TAB,
|
|
133
|
+
filters: parseFilters(search),
|
|
134
|
+
limit: VIEW_LIMITS.includes(limit) ? limit : 10,
|
|
135
|
+
...order === void 0 ? {} : { order }
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* The shortest URL that parses back to `state`: anything equal to a default is left out,
|
|
140
|
+
* and the keys are written in one fixed order so an unchanged view never rewrites history.
|
|
141
|
+
*/
|
|
142
|
+
const serializeViewState = (state, defaults) => {
|
|
143
|
+
const params = new URLSearchParams();
|
|
144
|
+
if (state.range !== defaultRange(defaults)) params.set("range", state.range);
|
|
145
|
+
if (state.range === "custom" && state.from !== void 0 && state.to !== void 0) {
|
|
146
|
+
params.set("from", state.from);
|
|
147
|
+
params.set("to", state.to);
|
|
148
|
+
}
|
|
149
|
+
if (state.compare) params.set("compare", "1");
|
|
150
|
+
if (state.source !== void 0) params.set("source", state.source);
|
|
151
|
+
if (state.metric !== defaults.metric) params.set("metric", state.metric);
|
|
152
|
+
if (state.granularity !== void 0) params.set("granularity", state.granularity);
|
|
153
|
+
if (state.tab !== "pages") params.set("tab", state.tab);
|
|
154
|
+
if (state.filters.length > 0) params.set("filters", JSON.stringify(state.filters));
|
|
155
|
+
if (state.limit !== 10) params.set("limit", String(state.limit));
|
|
156
|
+
if (state.order !== void 0) params.set("order", `${state.order.metric}:${state.order.direction}`);
|
|
157
|
+
return params;
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* The nearest state the selected source can actually serve. The URL outlives a source
|
|
161
|
+
* switch, so a metric, tab, filter, comparison, bucket or sort the new source lacks is
|
|
162
|
+
* replaced or dropped here rather than sent to the endpoint to be rejected. Returns the
|
|
163
|
+
* same object when the gate forbids nothing, so a render can compare by identity.
|
|
164
|
+
*/
|
|
165
|
+
const coerceState = (state, gate) => {
|
|
166
|
+
const metric = gate.metrics.includes(state.metric) ? state.metric : gate.metrics[0] ?? state.metric;
|
|
167
|
+
const tab = gate.tabs.includes(state.tab) ? state.tab : gate.tabs[0] ?? state.tab;
|
|
168
|
+
const compare = state.compare && gate.canCompare;
|
|
169
|
+
const filters = state.filters.filter((filter) => gate.canFilter(filter.dimension) && gate.operators.includes(filter.operator));
|
|
170
|
+
const granularity = state.granularity !== void 0 && gate.granularities.includes(state.granularity) ? state.granularity : void 0;
|
|
171
|
+
const order = state.order !== void 0 && gate.metrics.includes(state.order.metric) ? state.order : void 0;
|
|
172
|
+
if (metric === state.metric && tab === state.tab && compare === state.compare && filters.length === state.filters.length && granularity === state.granularity && order === state.order) return state;
|
|
173
|
+
return {
|
|
174
|
+
range: state.range,
|
|
175
|
+
...state.from === void 0 ? {} : { from: state.from },
|
|
176
|
+
...state.to === void 0 ? {} : { to: state.to },
|
|
177
|
+
compare,
|
|
178
|
+
...state.source === void 0 ? {} : { source: state.source },
|
|
179
|
+
metric,
|
|
180
|
+
...granularity === void 0 ? {} : { granularity },
|
|
181
|
+
tab,
|
|
182
|
+
filters,
|
|
183
|
+
limit: state.limit,
|
|
184
|
+
...order === void 0 ? {} : { order }
|
|
185
|
+
};
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* The inclusive day window a state reads, in the reporting timezone. The endpoint reads
|
|
189
|
+
* `from`/`to` in that same timezone, so the toolbar caption and every request share one
|
|
190
|
+
* answer. `now` is injected to keep callers deterministic.
|
|
191
|
+
*/
|
|
192
|
+
const rangeFor = (state, timezone, now) => {
|
|
193
|
+
if (state.range === "custom" && state.from !== void 0 && state.to !== void 0) return {
|
|
194
|
+
from: state.from,
|
|
195
|
+
to: state.to
|
|
196
|
+
};
|
|
197
|
+
const { start, end } = resolveTimeframe(state.range === "custom" ? DEFAULT_VIEW_RANGE : state.range, now, timezone);
|
|
198
|
+
return {
|
|
199
|
+
from: zonedCalendarDay(start, timezone),
|
|
200
|
+
to: zonedCalendarDay(end, timezone)
|
|
201
|
+
};
|
|
202
|
+
};
|
|
203
|
+
//#endregion
|
|
204
|
+
export { DEFAULT_VIEW_RANGE, DEFAULT_VIEW_TAB, VIEW_LIMITS, VIEW_RANGE_PRESETS, coerceState, parseViewState, rangeFor, serializeViewState };
|
|
205
|
+
|
|
206
|
+
//# sourceMappingURL=state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state.js","names":[],"sources":["../../src/view/state.ts"],"sourcesContent":["import {\n\ttype AnalyticsFilter,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\tFILTER_OPERATORS,\n\ttype FilterOperator,\n\ttype Granularity,\n\ttype MetricKey,\n} from '../core/contract'\nimport { GRANULARITY_ORDER } from '../core/granularity'\nimport {\n\tMAX_QUERY_FILTER_VALUE_LENGTH,\n\tMAX_QUERY_FILTERS,\n\tMAX_QUERY_RANGE_DAYS,\n} from '../query/limits'\nimport { resolveTimeframe, TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { zonedCalendarDay } from '../timeframe/tz'\nimport {\n\tBREAKDOWN_TABS,\n\ttype BreakdownTab,\n\ttype DayRange,\n\tVIEW_METRIC_ORDER,\n\ttype ViewGate,\n} from './gating'\n\n/**\n * The presets the toolbar offers. `allTime` is deliberately absent: it is unbounded, and\n * the query endpoint refuses any window longer than a year.\n */\nexport const VIEW_RANGE_PRESETS: TimeframePreset[] = [\n\t'today',\n\t'last7days',\n\t'last30days',\n\t'last90days',\n\t'lastYear',\n]\n\nexport const DEFAULT_VIEW_RANGE: TimeframePreset = 'last30days'\n\nexport const VIEW_LIMITS = [10, 25, 50, 100] as const\n\nexport type ViewLimit = (typeof VIEW_LIMITS)[number]\n\nexport const DEFAULT_VIEW_LIMIT: ViewLimit = 10\n\nexport const DEFAULT_VIEW_TAB: BreakdownTab = 'pages'\n\n/** Everything the view reads from the URL. A view is its state, so a link is a view. */\nexport interface ViewState {\n\trange: TimeframePreset | 'custom'\n\t/** Set only on a custom range: an inclusive `YYYY-MM-DD` day in the reporting timezone. */\n\tfrom?: string\n\tto?: string\n\tcompare: boolean\n\tsource?: string\n\tmetric: MetricKey\n\t/** Absent means automatic; {@link autoGranularity} picks one from the range. */\n\tgranularity?: Granularity\n\ttab: BreakdownTab\n\tfilters: AnalyticsFilter[]\n\tlimit: ViewLimit\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n}\n\n/** The install's configured starting point, as `AnalyticsViewClientProps.defaults` carries it. */\nexport interface ViewDefaults {\n\trange: TimeframePreset\n\tmetric: MetricKey\n}\n\nconst KNOWN_METRICS = new Set<string>(VIEW_METRIC_ORDER)\nconst KNOWN_DIMENSIONS = new Set<string>(DIMENSION_KEYS)\nconst KNOWN_OPERATORS = new Set<string>(FILTER_OPERATORS)\nconst KNOWN_GRANULARITIES = new Set<string>(GRANULARITY_ORDER)\nconst KNOWN_PRESETS = new Set<string>(TIMEFRAME_PRESETS)\nconst DAY_MS = 86_400_000\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst read = (search: URLSearchParams, name: string): string | null => {\n\tconst raw = search.get(name)?.trim()\n\treturn raw ? raw : null\n}\n\n/**\n * Epoch ms of a `YYYY-MM-DD` day, or null when it names no real calendar day. The\n * round trip is the validation: `Date.parse` rolls February 30 forward instead of failing.\n */\nconst dayValue = (raw: string | null): number | null => {\n\tif (raw === null || !DAY_PATTERN.test(raw)) {\n\t\treturn null\n\t}\n\tconst ms = Date.parse(`${raw}T00:00:00.000Z`)\n\tif (Number.isNaN(ms) || new Date(ms).toISOString().slice(0, 10) !== raw) {\n\t\treturn null\n\t}\n\treturn ms\n}\n\n/** A configured default the view cannot serve falls back to the built-in range. */\nconst defaultRange = (defaults: ViewDefaults): TimeframePreset =>\n\tdefaults.range === 'allTime' ? DEFAULT_VIEW_RANGE : defaults.range\n\nconst parseRange = (\n\tsearch: URLSearchParams,\n\tdefaults: ViewDefaults\n): Pick<ViewState, 'range' | 'from' | 'to'> => {\n\tconst fallback = { range: defaultRange(defaults) }\n\tconst raw = read(search, 'range')\n\tif (raw === null) {\n\t\treturn fallback\n\t}\n\tif (raw === 'custom') {\n\t\tconst from = dayValue(read(search, 'from'))\n\t\tconst to = dayValue(read(search, 'to'))\n\t\tif (from === null || to === null || to < from) {\n\t\t\treturn fallback\n\t\t}\n\t\t// Beyond the endpoint's own cap the read would only ever answer `range_too_long`.\n\t\tif (Math.round((to - from) / DAY_MS) + 1 > MAX_QUERY_RANGE_DAYS) {\n\t\t\treturn fallback\n\t\t}\n\t\treturn {\n\t\t\trange: 'custom',\n\t\t\tfrom: new Date(from).toISOString().slice(0, 10),\n\t\t\tto: new Date(to).toISOString().slice(0, 10),\n\t\t}\n\t}\n\tif (!KNOWN_PRESETS.has(raw) || raw === 'allTime') {\n\t\treturn fallback\n\t}\n\treturn { range: raw as TimeframePreset }\n}\n\n/**\n * Filters as the endpoint's own parser would accept them, minus its errors: an entry\n * naming a dimension, operator or value outside the contract is dropped rather than\n * failing the whole URL, since a hand-edited link should still open a working view.\n */\nconst parseFilters = (search: URLSearchParams): AnalyticsFilter[] => {\n\tconst raw = read(search, 'filters')\n\tif (raw === null) {\n\t\treturn []\n\t}\n\tlet decoded: unknown\n\ttry {\n\t\tdecoded = JSON.parse(raw)\n\t} catch {\n\t\treturn []\n\t}\n\tif (!Array.isArray(decoded)) {\n\t\treturn []\n\t}\n\tconst filters: AnalyticsFilter[] = []\n\tfor (const item of decoded) {\n\t\tif (filters.length === MAX_QUERY_FILTERS) {\n\t\t\tbreak\n\t\t}\n\t\tif (!isRecord(item)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst { dimension, operator, value } = item\n\t\tif (typeof dimension !== 'string' || !KNOWN_DIMENSIONS.has(dimension)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof operator !== 'string' || !KNOWN_OPERATORS.has(operator)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\tcontinue\n\t\t}\n\t\tconst trimmed = value.trim()\n\t\tif (trimmed.length < 1 || trimmed.length > MAX_QUERY_FILTER_VALUE_LENGTH) {\n\t\t\tcontinue\n\t\t}\n\t\tfilters.push({\n\t\t\tdimension: dimension as DimensionKey,\n\t\t\toperator: operator as FilterOperator,\n\t\t\tvalue: trimmed,\n\t\t})\n\t}\n\treturn filters\n}\n\nconst parseOrder = (search: URLSearchParams): ViewState['order'] => {\n\tconst raw = read(search, 'order')\n\tif (raw === null) {\n\t\treturn undefined\n\t}\n\tconst parts = raw.split(':')\n\tconst metric = parts[0] ?? ''\n\tconst direction = parts[1] ?? ''\n\tif (parts.length !== 2 || !KNOWN_METRICS.has(metric)) {\n\t\treturn undefined\n\t}\n\tif (direction !== 'asc' && direction !== 'desc') {\n\t\treturn undefined\n\t}\n\treturn { metric: metric as MetricKey, direction }\n}\n\n/**\n * Total by construction: every value the URL cannot justify falls back to the install\n * default, so a truncated, stale or hand-edited link always opens a working view.\n */\nexport const parseViewState = (search: URLSearchParams, defaults: ViewDefaults): ViewState => {\n\tconst metric = read(search, 'metric')\n\tconst granularity = read(search, 'granularity')\n\tconst tab = read(search, 'tab')\n\tconst source = read(search, 'source')\n\tconst limit = Number(read(search, 'limit'))\n\tconst compare = read(search, 'compare')\n\tconst order = parseOrder(search)\n\treturn {\n\t\t...parseRange(search, defaults),\n\t\tcompare: compare === '1' || compare === 'true',\n\t\t...(source === null ? {} : { source }),\n\t\tmetric: metric !== null && KNOWN_METRICS.has(metric) ? (metric as MetricKey) : defaults.metric,\n\t\t...(granularity !== null && KNOWN_GRANULARITIES.has(granularity)\n\t\t\t? { granularity: granularity as Granularity }\n\t\t\t: {}),\n\t\ttab:\n\t\t\ttab !== null && BREAKDOWN_TABS.includes(tab as BreakdownTab)\n\t\t\t\t? (tab as BreakdownTab)\n\t\t\t\t: DEFAULT_VIEW_TAB,\n\t\tfilters: parseFilters(search),\n\t\tlimit: VIEW_LIMITS.includes(limit as ViewLimit) ? (limit as ViewLimit) : DEFAULT_VIEW_LIMIT,\n\t\t...(order === undefined ? {} : { order }),\n\t}\n}\n\n/**\n * The shortest URL that parses back to `state`: anything equal to a default is left out,\n * and the keys are written in one fixed order so an unchanged view never rewrites history.\n */\nexport const serializeViewState = (state: ViewState, defaults: ViewDefaults): URLSearchParams => {\n\tconst params = new URLSearchParams()\n\tif (state.range !== defaultRange(defaults)) {\n\t\tparams.set('range', state.range)\n\t}\n\tif (state.range === 'custom' && state.from !== undefined && state.to !== undefined) {\n\t\tparams.set('from', state.from)\n\t\tparams.set('to', state.to)\n\t}\n\tif (state.compare) {\n\t\tparams.set('compare', '1')\n\t}\n\tif (state.source !== undefined) {\n\t\tparams.set('source', state.source)\n\t}\n\tif (state.metric !== defaults.metric) {\n\t\tparams.set('metric', state.metric)\n\t}\n\tif (state.granularity !== undefined) {\n\t\tparams.set('granularity', state.granularity)\n\t}\n\tif (state.tab !== DEFAULT_VIEW_TAB) {\n\t\tparams.set('tab', state.tab)\n\t}\n\tif (state.filters.length > 0) {\n\t\tparams.set('filters', JSON.stringify(state.filters))\n\t}\n\tif (state.limit !== DEFAULT_VIEW_LIMIT) {\n\t\tparams.set('limit', String(state.limit))\n\t}\n\tif (state.order !== undefined) {\n\t\tparams.set('order', `${state.order.metric}:${state.order.direction}`)\n\t}\n\treturn params\n}\n\n/**\n * The nearest state the selected source can actually serve. The URL outlives a source\n * switch, so a metric, tab, filter, comparison, bucket or sort the new source lacks is\n * replaced or dropped here rather than sent to the endpoint to be rejected. Returns the\n * same object when the gate forbids nothing, so a render can compare by identity.\n */\nexport const coerceState = (state: ViewState, gate: ViewGate): ViewState => {\n\tconst metric = gate.metrics.includes(state.metric)\n\t\t? state.metric\n\t\t: (gate.metrics[0] ?? state.metric)\n\tconst tab = gate.tabs.includes(state.tab) ? state.tab : (gate.tabs[0] ?? state.tab)\n\tconst compare = state.compare && gate.canCompare\n\tconst filters = state.filters.filter(\n\t\t(filter) => gate.canFilter(filter.dimension) && gate.operators.includes(filter.operator)\n\t)\n\tconst granularity =\n\t\tstate.granularity !== undefined && gate.granularities.includes(state.granularity)\n\t\t\t? state.granularity\n\t\t\t: undefined\n\tconst order =\n\t\tstate.order !== undefined && gate.metrics.includes(state.order.metric) ? state.order : undefined\n\tconst unchanged =\n\t\tmetric === state.metric &&\n\t\ttab === state.tab &&\n\t\tcompare === state.compare &&\n\t\tfilters.length === state.filters.length &&\n\t\tgranularity === state.granularity &&\n\t\torder === state.order\n\tif (unchanged) {\n\t\treturn state\n\t}\n\treturn {\n\t\trange: state.range,\n\t\t...(state.from === undefined ? {} : { from: state.from }),\n\t\t...(state.to === undefined ? {} : { to: state.to }),\n\t\tcompare,\n\t\t...(state.source === undefined ? {} : { source: state.source }),\n\t\tmetric,\n\t\t...(granularity === undefined ? {} : { granularity }),\n\t\ttab,\n\t\tfilters,\n\t\tlimit: state.limit,\n\t\t...(order === undefined ? {} : { order }),\n\t}\n}\n\n/**\n * The inclusive day window a state reads, in the reporting timezone. The endpoint reads\n * `from`/`to` in that same timezone, so the toolbar caption and every request share one\n * answer. `now` is injected to keep callers deterministic.\n */\nexport const rangeFor = (state: ViewState, timezone: string, now: Date): DayRange => {\n\tif (state.range === 'custom' && state.from !== undefined && state.to !== undefined) {\n\t\treturn { from: state.from, to: state.to }\n\t}\n\tconst preset = state.range === 'custom' ? DEFAULT_VIEW_RANGE : state.range\n\tconst { start, end } = resolveTimeframe(preset, now, timezone)\n\treturn { from: zonedCalendarDay(start, timezone), to: zonedCalendarDay(end, timezone) }\n}\n"],"mappings":";;;;;;;;;;AA6BA,MAAa,qBAAwC;CACpD;CACA;CACA;CACA;CACA;AACD;AAEA,MAAa,qBAAsC;AAEnD,MAAa,cAAc;CAAC;CAAI;CAAI;CAAI;AAAG;AAM3C,MAAa,mBAAiC;AAyB9C,MAAM,gBAAgB,IAAI,IAAY,iBAAiB;AACvD,MAAM,mBAAmB,IAAI,IAAY,cAAc;AACvD,MAAM,kBAAkB,IAAI,IAAY,gBAAgB;AACxD,MAAM,sBAAsB,IAAI,IAAY,iBAAiB;AAC7D,MAAM,gBAAgB,IAAI,IAAY,iBAAiB;AACvD,MAAM,SAAS;AACf,MAAM,cAAc;AAEpB,MAAM,YAAY,UACjB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAEpE,MAAM,QAAQ,QAAyB,SAAgC;CACtE,MAAM,MAAM,OAAO,IAAI,IAAI,GAAG,KAAK;CACnC,OAAO,MAAM,MAAM;AACpB;;;;;AAMA,MAAM,YAAY,QAAsC;CACvD,IAAI,QAAQ,QAAQ,CAAC,YAAY,KAAK,GAAG,GACxC,OAAO;CAER,MAAM,KAAK,KAAK,MAAM,GAAG,IAAI,eAAe;CAC5C,IAAI,OAAO,MAAM,EAAE,KAAK,IAAI,KAAK,EAAE,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,MAAM,KACnE,OAAO;CAER,OAAO;AACR;;AAGA,MAAM,gBAAgB,aACrB,SAAS,UAAU,YAAY,qBAAqB,SAAS;AAE9D,MAAM,cACL,QACA,aAC8C;CAC9C,MAAM,WAAW,EAAE,OAAO,aAAa,QAAQ,EAAE;CACjD,MAAM,MAAM,KAAK,QAAQ,OAAO;CAChC,IAAI,QAAQ,MACX,OAAO;CAER,IAAI,QAAQ,UAAU;EACrB,MAAM,OAAO,SAAS,KAAK,QAAQ,MAAM,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M,QAAQ,KAAA;CAQxF,IANC,WAAW,MAAM,UACjB,QAAQ,MAAM,OACd,YAAY,MAAM,WAClB,QAAQ,WAAW,MAAM,QAAQ,UACjC,gBAAgB,MAAM,eACtB,UAAU,MAAM,OAEhB,OAAO;CAER,OAAO;EACN,OAAO,MAAM;EACb,GAAI,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,MAAM,KAAK;EACvD,GAAI,MAAM,OAAO,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI,MAAM,GAAG;EACjD;EACA,GAAI,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;EAC7D;EACA,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD;EACA;EACA,OAAO,MAAM;EACb,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;CACxC;AACD;;;;;;AAOA,MAAa,YAAY,OAAkB,UAAkB,QAAwB;CACpF,IAAI,MAAM,UAAU,YAAY,MAAM,SAAS,KAAA,KAAa,MAAM,OAAO,KAAA,GACxE,OAAO;EAAE,MAAM,MAAM;EAAM,IAAI,MAAM;CAAG;CAGzC,MAAM,EAAE,OAAO,QAAQ,iBADR,MAAM,UAAU,WAAW,qBAAqB,MAAM,OACrB,KAAK,QAAQ;CAC7D,OAAO;EAAE,MAAM,iBAAiB,OAAO,QAAQ;EAAG,IAAI,iBAAiB,KAAK,QAAQ;CAAE;AACvF"}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { fetchQuery } from "../query/fetchQuery.js";
|
|
3
|
+
import { autoGranularity, gate, resolveSource } from "./gating.js";
|
|
4
|
+
import { coerceState, rangeFor } from "./state.js";
|
|
5
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
6
|
+
//#region src/view/useViewQueries.ts
|
|
7
|
+
/**
|
|
8
|
+
* `QueryState.error.message` for a section with nothing to ask for: the scope has no
|
|
9
|
+
* readable source, or the source serves no metric or dimension the section needs. It is
|
|
10
|
+
* never an endpoint failure, so a caller can tell the two apart without a `QueryFetchError`.
|
|
11
|
+
*/
|
|
12
|
+
const SECTION_UNAVAILABLE = "analytics: this source serves no data for this section";
|
|
13
|
+
const NO_REQUESTS = {
|
|
14
|
+
cards: null,
|
|
15
|
+
trend: null,
|
|
16
|
+
breakdown: null,
|
|
17
|
+
goals: null
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Derives the four reads from the view state and the selected source's capabilities.
|
|
21
|
+
* Pure and total: the state is coerced to what the source serves first, so no request
|
|
22
|
+
* here can carry a metric, dimension, filter, bucket or comparison the endpoint would
|
|
23
|
+
* reject. `now` is injected to keep callers deterministic.
|
|
24
|
+
*/
|
|
25
|
+
const buildViewRequests = (props, state, now) => {
|
|
26
|
+
const source = resolveSource(props.sources, state.source);
|
|
27
|
+
if (!source) return NO_REQUESTS;
|
|
28
|
+
const served = gate(source.capabilities);
|
|
29
|
+
if (served.metrics.length === 0) return NO_REQUESTS;
|
|
30
|
+
const view = coerceState(state, served);
|
|
31
|
+
const range = rangeFor(view, props.timezone, now);
|
|
32
|
+
const shared = {
|
|
33
|
+
from: range.from,
|
|
34
|
+
to: range.to,
|
|
35
|
+
...view.filters.length > 0 ? { filters: view.filters } : {},
|
|
36
|
+
source: source.id,
|
|
37
|
+
timezone: props.timezone
|
|
38
|
+
};
|
|
39
|
+
const compare = view.compare ? { compare: "previous" } : {};
|
|
40
|
+
const breakdownMetrics = [view.metric, ...served.metrics.includes("visitors") && view.metric !== "visitors" ? ["visitors"] : []];
|
|
41
|
+
const dimension = served.dimensionsFor(view.tab)[0];
|
|
42
|
+
const order = view.order !== void 0 && breakdownMetrics.includes(view.order.metric) ? view.order : {
|
|
43
|
+
metric: view.metric,
|
|
44
|
+
direction: "desc"
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
cards: {
|
|
48
|
+
metrics: served.metrics,
|
|
49
|
+
...shared,
|
|
50
|
+
...compare
|
|
51
|
+
},
|
|
52
|
+
trend: {
|
|
53
|
+
metrics: [view.metric],
|
|
54
|
+
...shared,
|
|
55
|
+
granularity: view.granularity ?? autoGranularity(range, source.capabilities),
|
|
56
|
+
...compare
|
|
57
|
+
},
|
|
58
|
+
breakdown: dimension === void 0 ? null : {
|
|
59
|
+
metrics: breakdownMetrics,
|
|
60
|
+
dimensions: [dimension],
|
|
61
|
+
...shared,
|
|
62
|
+
limit: view.limit,
|
|
63
|
+
order
|
|
64
|
+
},
|
|
65
|
+
goals: served.goals ? {
|
|
66
|
+
metrics: [
|
|
67
|
+
"conversions",
|
|
68
|
+
...served.metrics.includes("revenue") ? ["revenue"] : [],
|
|
69
|
+
...served.metrics.includes("visitors") ? ["visitors"] : []
|
|
70
|
+
],
|
|
71
|
+
dimensions: ["goal"],
|
|
72
|
+
...shared
|
|
73
|
+
} : null
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
const asError = (err) => err instanceof Error ? err : new Error(String(err));
|
|
77
|
+
/**
|
|
78
|
+
* Runs one section's read. The request is keyed by its serialized form, so a state change
|
|
79
|
+
* that leaves a section's query identical never refetches it, and one that changes it
|
|
80
|
+
* aborts the in-flight read before issuing the new one.
|
|
81
|
+
*/
|
|
82
|
+
const useQuerySection = (apiRoute, request) => {
|
|
83
|
+
const [section, setSection] = useState({ status: "loading" });
|
|
84
|
+
const pending = useRef(null);
|
|
85
|
+
const key = request === null ? null : JSON.stringify(request);
|
|
86
|
+
const run = useCallback((serialized) => {
|
|
87
|
+
pending.current?.abort();
|
|
88
|
+
if (serialized === null) {
|
|
89
|
+
pending.current = null;
|
|
90
|
+
setSection({
|
|
91
|
+
status: "error",
|
|
92
|
+
error: /* @__PURE__ */ new Error(SECTION_UNAVAILABLE)
|
|
93
|
+
});
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const controller = new AbortController();
|
|
97
|
+
pending.current = controller;
|
|
98
|
+
setSection((prev) => prev.status === "loading" ? prev : {
|
|
99
|
+
status: "loading",
|
|
100
|
+
...prev.data === void 0 ? {} : { data: prev.data }
|
|
101
|
+
});
|
|
102
|
+
fetchQuery(apiRoute, JSON.parse(serialized), { signal: controller.signal }).then((data) => {
|
|
103
|
+
if (!controller.signal.aborted) setSection({
|
|
104
|
+
status: "ok",
|
|
105
|
+
data
|
|
106
|
+
});
|
|
107
|
+
}, (err) => {
|
|
108
|
+
if (!controller.signal.aborted) setSection((prev) => ({
|
|
109
|
+
status: "error",
|
|
110
|
+
error: asError(err),
|
|
111
|
+
...prev.data === void 0 ? {} : { data: prev.data }
|
|
112
|
+
}));
|
|
113
|
+
});
|
|
114
|
+
}, [apiRoute]);
|
|
115
|
+
const refetch = useCallback(() => {
|
|
116
|
+
run(key);
|
|
117
|
+
}, [run, key]);
|
|
118
|
+
useEffect(() => {
|
|
119
|
+
run(key);
|
|
120
|
+
return () => {
|
|
121
|
+
pending.current?.abort();
|
|
122
|
+
};
|
|
123
|
+
}, [run, key]);
|
|
124
|
+
return {
|
|
125
|
+
...section,
|
|
126
|
+
isRefetching: section.status === "loading" && section.data !== void 0,
|
|
127
|
+
refetch
|
|
128
|
+
};
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* The view's four reads for one state, each with its own lifecycle: a section refetches
|
|
132
|
+
* only when its own request changes, and an in-flight read is aborted when it does.
|
|
133
|
+
*/
|
|
134
|
+
const useViewQueries = (props, state) => {
|
|
135
|
+
const requests = buildViewRequests(props, state, /* @__PURE__ */ new Date());
|
|
136
|
+
const cards = useQuerySection(props.apiRoute, requests.cards);
|
|
137
|
+
const trend = useQuerySection(props.apiRoute, requests.trend);
|
|
138
|
+
const breakdown = useQuerySection(props.apiRoute, requests.breakdown);
|
|
139
|
+
const goals = useQuerySection(props.apiRoute, requests.goals);
|
|
140
|
+
return {
|
|
141
|
+
cards,
|
|
142
|
+
trend,
|
|
143
|
+
breakdown,
|
|
144
|
+
goals: requests.goals === null ? null : goals
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
//#endregion
|
|
148
|
+
export { SECTION_UNAVAILABLE, useViewQueries };
|
|
149
|
+
|
|
150
|
+
//# sourceMappingURL=useViewQueries.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useViewQueries.js","names":[],"sources":["../../src/view/useViewQueries.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport type { MetricKey } from '../core/contract'\nimport { fetchQuery, type QueryRequest } from '../query/fetchQuery'\nimport type { QueryResponse } from '../query/response'\nimport { autoGranularity, gate, resolveSource } from './gating'\nimport { coerceState, rangeFor, type ViewState } from './state'\nimport type { AnalyticsViewClientProps } from './viewProps'\n\n/**\n * One section's read. `error` is a `QueryFetchError` whenever the endpoint answered.\n *\n * `data` survives into the next `loading` and into an `error`, so changing the range or\n * hitting a transient failure dims or annotates the chart it already shows instead of\n * blanking it; `isRefetching` is the loading half of that, and is the flag to render a\n * subtle busy affordance on. `status === 'loading'` with no `data` is the only real empty\n * load, and the only one that earns a skeleton. A section that stops being servable at all\n * drops its data, since it belongs to a source or tab the view is no longer showing.\n */\nexport interface QueryState<T> {\n\tstatus: 'loading' | 'ok' | 'error'\n\t/** May be the previous read's answer while `status` is `loading` or `error`. */\n\tdata?: T\n\terror?: Error\n\tisRefetching: boolean\n\trefetch: () => void\n}\n\nexport interface ViewQueries {\n\tcards: QueryState<QueryResponse>\n\ttrend: QueryState<QueryResponse>\n\tbreakdown: QueryState<QueryResponse>\n\t/** Null when the source serves no goal breakdown, so the panel is not rendered at all. */\n\tgoals: QueryState<QueryResponse> | null\n}\n\n/** The four reads a view state implies; a null section is one this source cannot serve. */\nexport interface ViewRequests {\n\tcards: QueryRequest | null\n\ttrend: QueryRequest | null\n\tbreakdown: QueryRequest | null\n\tgoals: QueryRequest | null\n}\n\n/**\n * `QueryState.error.message` for a section with nothing to ask for: the scope has no\n * readable source, or the source serves no metric or dimension the section needs. It is\n * never an endpoint failure, so a caller can tell the two apart without a `QueryFetchError`.\n */\nexport const SECTION_UNAVAILABLE = 'analytics: this source serves no data for this section'\n\nconst NO_REQUESTS: ViewRequests = { cards: null, trend: null, breakdown: null, goals: null }\n\n/**\n * Derives the four reads from the view state and the selected source's capabilities.\n * Pure and total: the state is coerced to what the source serves first, so no request\n * here can carry a metric, dimension, filter, bucket or comparison the endpoint would\n * reject. `now` is injected to keep callers deterministic.\n */\nexport const buildViewRequests = (\n\tprops: AnalyticsViewClientProps,\n\tstate: ViewState,\n\tnow: Date\n): ViewRequests => {\n\tconst source = resolveSource(props.sources, state.source)\n\tif (!source) {\n\t\treturn NO_REQUESTS\n\t}\n\tconst served = gate(source.capabilities)\n\tif (served.metrics.length === 0) {\n\t\treturn NO_REQUESTS\n\t}\n\tconst view = coerceState(state, served)\n\tconst range = rangeFor(view, props.timezone, now)\n\t// The resolved id, not the state's: a stale one in the URL would otherwise ask the\n\t// endpoint for a source that is gone while the gate describes the fallback.\n\tconst shared = {\n\t\tfrom: range.from,\n\t\tto: range.to,\n\t\t...(view.filters.length > 0 ? { filters: view.filters } : {}),\n\t\tsource: source.id,\n\t\ttimezone: props.timezone,\n\t}\n\tconst compare = view.compare ? ({ compare: 'previous' } as const) : {}\n\tconst breakdownMetrics: MetricKey[] = [\n\t\tview.metric,\n\t\t...(served.metrics.includes('visitors') && view.metric !== 'visitors'\n\t\t\t? (['visitors'] as const)\n\t\t\t: []),\n\t]\n\tconst dimension = served.dimensionsFor(view.tab)[0]\n\tconst order: QueryRequest['order'] =\n\t\tview.order !== undefined && breakdownMetrics.includes(view.order.metric)\n\t\t\t? view.order\n\t\t\t: { metric: view.metric, direction: 'desc' }\n\treturn {\n\t\tcards: { metrics: served.metrics, ...shared, ...compare },\n\t\ttrend: {\n\t\t\tmetrics: [view.metric],\n\t\t\t...shared,\n\t\t\tgranularity: view.granularity ?? autoGranularity(range, source.capabilities),\n\t\t\t...compare,\n\t\t},\n\t\tbreakdown:\n\t\t\tdimension === undefined\n\t\t\t\t? null\n\t\t\t\t: {\n\t\t\t\t\t\tmetrics: breakdownMetrics,\n\t\t\t\t\t\tdimensions: [dimension],\n\t\t\t\t\t\t...shared,\n\t\t\t\t\t\tlimit: view.limit,\n\t\t\t\t\t\torder,\n\t\t\t\t\t},\n\t\tgoals: served.goals\n\t\t\t? {\n\t\t\t\t\tmetrics: [\n\t\t\t\t\t\t'conversions',\n\t\t\t\t\t\t...(served.metrics.includes('revenue') ? (['revenue'] as const) : []),\n\t\t\t\t\t\t...(served.metrics.includes('visitors') ? (['visitors'] as const) : []),\n\t\t\t\t\t],\n\t\t\t\t\tdimensions: ['goal'],\n\t\t\t\t\t...shared,\n\t\t\t\t}\n\t\t\t: null,\n\t}\n}\n\nconst asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)))\n\ntype SectionState = Omit<QueryState<QueryResponse>, 'isRefetching' | 'refetch'>\n\n/**\n * Runs one section's read. The request is keyed by its serialized form, so a state change\n * that leaves a section's query identical never refetches it, and one that changes it\n * aborts the in-flight read before issuing the new one.\n */\nconst useQuerySection = (\n\tapiRoute: string,\n\trequest: QueryRequest | null\n): QueryState<QueryResponse> => {\n\tconst [section, setSection] = useState<SectionState>({ status: 'loading' })\n\tconst pending = useRef<AbortController | null>(null)\n\tconst key = request === null ? null : JSON.stringify(request)\n\n\tconst run = useCallback(\n\t\t(serialized: string | null) => {\n\t\t\tpending.current?.abort()\n\t\t\tif (serialized === null) {\n\t\t\t\tpending.current = null\n\t\t\t\tsetSection({ status: 'error', error: new Error(SECTION_UNAVAILABLE) })\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst controller = new AbortController()\n\t\t\tpending.current = controller\n\t\t\t// Returning `prev` unchanged makes the first read a no-op update rather than a\n\t\t\t// second render; any later one keeps what is on screen until the answer lands.\n\t\t\tsetSection((prev) =>\n\t\t\t\tprev.status === 'loading'\n\t\t\t\t\t? prev\n\t\t\t\t\t: { status: 'loading', ...(prev.data === undefined ? {} : { data: prev.data }) }\n\t\t\t)\n\t\t\tfetchQuery(apiRoute, JSON.parse(serialized) as QueryRequest, {\n\t\t\t\tsignal: controller.signal,\n\t\t\t}).then(\n\t\t\t\t(data) => {\n\t\t\t\t\tif (!controller.signal.aborted) setSection({ status: 'ok', data })\n\t\t\t\t},\n\t\t\t\t(err: unknown) => {\n\t\t\t\t\t// The failure is reported beside whatever is on screen: a transient 503 on a\n\t\t\t\t\t// refetch shows a retry banner over the last good read instead of a blank panel.\n\t\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\t\tsetSection((prev) => ({\n\t\t\t\t\t\t\tstatus: 'error',\n\t\t\t\t\t\t\terror: asError(err),\n\t\t\t\t\t\t\t...(prev.data === undefined ? {} : { data: prev.data }),\n\t\t\t\t\t\t}))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t},\n\t\t[apiRoute]\n\t)\n\n\tconst refetch = useCallback(() => {\n\t\trun(key)\n\t}, [run, key])\n\n\tuseEffect(() => {\n\t\trun(key)\n\t\treturn () => {\n\t\t\tpending.current?.abort()\n\t\t}\n\t}, [run, key])\n\n\treturn {\n\t\t...section,\n\t\tisRefetching: section.status === 'loading' && section.data !== undefined,\n\t\trefetch,\n\t}\n}\n\n/**\n * The view's four reads for one state, each with its own lifecycle: a section refetches\n * only when its own request changes, and an in-flight read is aborted when it does.\n */\nexport const useViewQueries = (props: AnalyticsViewClientProps, state: ViewState): ViewQueries => {\n\tconst requests = buildViewRequests(props, state, new Date())\n\tconst cards = useQuerySection(props.apiRoute, requests.cards)\n\tconst trend = useQuerySection(props.apiRoute, requests.trend)\n\tconst breakdown = useQuerySection(props.apiRoute, requests.breakdown)\n\tconst goals = useQuerySection(props.apiRoute, requests.goals)\n\treturn { cards, trend, breakdown, goals: requests.goals === null ? null : goals }\n}\n"],"mappings":";;;;;;;;;;;AAkDA,MAAa,sBAAsB;AAEnC,MAAM,cAA4B;CAAE,OAAO;CAAM,OAAO;CAAM,WAAW;CAAM,OAAO;AAAK;;;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EACf,IAAI,GAAG;EACP,aAAa;GACZ,QAAQ,SAAS,MAAM;EACxB;CACD,GAAG,CAAC,KAAK,GAAG,CAAC;CAEb,OAAO;EACN,GAAG;EACH,cAAc,QAAQ,WAAW,aAAa,QAAQ,SAAS,KAAA;EAC/D;CACD;AACD;;;;;AAMA,MAAa,kBAAkB,OAAiC,UAAkC;CACjG,MAAM,WAAW,kBAAkB,OAAO,uBAAO,IAAI,KAAK,CAAC;CAC3D,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,MAAM,YAAY,gBAAgB,MAAM,UAAU,SAAS,SAAS;CACpE,MAAM,QAAQ,gBAAgB,MAAM,UAAU,SAAS,KAAK;CAC5D,OAAO;EAAE;EAAO;EAAO;EAAW,OAAO,SAAS,UAAU,OAAO,OAAO;CAAM;AACjF"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { MetricKey } from "../core/contract.js";
|
|
2
|
+
import { SourcesResponse } from "../fields/config/fetchSources.js";
|
|
3
|
+
import { TimeframePreset } from "../timeframe/presets.js";
|
|
4
|
+
import { PayloadRequest } from "payload";
|
|
5
|
+
|
|
6
|
+
//#region src/view/viewProps.d.ts
|
|
7
|
+
/** A goal as the view lists it: the picker needs no match or value details. */
|
|
8
|
+
interface ViewGoal {
|
|
9
|
+
slug: string;
|
|
10
|
+
name: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Everything the client shell needs to render without a second round trip. Serializable
|
|
14
|
+
* by construction: the RSC boundary drops functions, so only wire shapes appear here.
|
|
15
|
+
*/
|
|
16
|
+
interface AnalyticsViewClientProps {
|
|
17
|
+
/** Same payload the sources endpoint answers, resolved for this request's scope. */
|
|
18
|
+
sources: SourcesResponse;
|
|
19
|
+
goals: ViewGoal[];
|
|
20
|
+
defaults: {
|
|
21
|
+
range: TimeframePreset;
|
|
22
|
+
metric: MetricKey;
|
|
23
|
+
};
|
|
24
|
+
apiRoute: string;
|
|
25
|
+
adminRoute: string;
|
|
26
|
+
/** IANA reporting timezone the day boundaries align to. */
|
|
27
|
+
timezone: string;
|
|
28
|
+
/** Admin UI language (`req.i18n.language`), for number and date formatting. */
|
|
29
|
+
locale: string;
|
|
30
|
+
/**
|
|
31
|
+
* The analytics scope this render resolved to, `''` when there is none. The tenant
|
|
32
|
+
* selector sets its cookie and calls `router.refresh()`, which re-renders this shell but
|
|
33
|
+
* keeps client state, and the reads are identical strings for two tenants sharing an
|
|
34
|
+
* adapter id. Keying the client body on this remounts it instead, so a switch refetches.
|
|
35
|
+
*/
|
|
36
|
+
scopeKey: string;
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
export { AnalyticsViewClientProps, ViewGoal };
|
|
40
|
+
//# sourceMappingURL=viewProps.d.ts.map
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { getRuntime, platformReadGate, requestTimezone, resolveGoalsDetailedFor, resolveScopeFor } from "../plugin/runtime.js";
|
|
2
|
+
import { DEFAULT_VIEW } from "../core/options.js";
|
|
3
|
+
import { resolveSourcesForRequest } from "../plugin/readContextForRequest.js";
|
|
4
|
+
//#region src/view/viewProps.ts
|
|
5
|
+
/**
|
|
6
|
+
* The goals the request's scope may see, mirroring the goals endpoint exactly: no scope
|
|
7
|
+
* parameter, an unresolvable scope on a scoped install fails closed unless `platformRead`
|
|
8
|
+
* lifts it, and a failed resolution falls back to the config goals only when unscoped.
|
|
9
|
+
*/
|
|
10
|
+
const resolveGoalsList = async (runtime, req, allowed) => {
|
|
11
|
+
const configGoals = () => (runtime.goals ?? []).map((goal) => ({
|
|
12
|
+
slug: goal.slug,
|
|
13
|
+
name: goal.name
|
|
14
|
+
}));
|
|
15
|
+
try {
|
|
16
|
+
const scope = await resolveScopeFor(runtime, req);
|
|
17
|
+
if (runtime.scoped && scope === null && !await allowed()) return [];
|
|
18
|
+
return (await resolveGoalsDetailedFor(runtime, req, scope)).map(({ goal }) => ({
|
|
19
|
+
slug: goal.slug,
|
|
20
|
+
name: goal.name
|
|
21
|
+
}));
|
|
22
|
+
} catch (err) {
|
|
23
|
+
req.payload.logger?.warn(`analytics: view goals listing failed: ${String(err)}`);
|
|
24
|
+
return runtime.scoped ? [] : configGoals();
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/** The resolved scope as a render key; a resolver that throws keys as the scope-less render. */
|
|
28
|
+
const resolveScopeKey = async (runtime, req) => {
|
|
29
|
+
try {
|
|
30
|
+
return await resolveScopeFor(runtime, req) ?? "";
|
|
31
|
+
} catch {
|
|
32
|
+
return "";
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Resolves the client shell's props for one request. Split from the server component so the
|
|
37
|
+
* whole resolution (access, scope gating, sources, goals, timezone) is testable without a
|
|
38
|
+
* React render.
|
|
39
|
+
*/
|
|
40
|
+
const resolveViewProps = async (req, resolved) => {
|
|
41
|
+
if (!await resolved.access.view({ req })) return { denied: true };
|
|
42
|
+
const view = resolved.view === false ? DEFAULT_VIEW : resolved.view;
|
|
43
|
+
const runtime = getRuntime(req.payload);
|
|
44
|
+
const base = {
|
|
45
|
+
defaults: {
|
|
46
|
+
range: view.defaultRange,
|
|
47
|
+
metric: view.defaultMetric
|
|
48
|
+
},
|
|
49
|
+
apiRoute: req.payload.config.routes?.api ?? "/api",
|
|
50
|
+
adminRoute: req.payload.config.routes?.admin ?? "/admin",
|
|
51
|
+
locale: req.i18n.language
|
|
52
|
+
};
|
|
53
|
+
if (!runtime) return {
|
|
54
|
+
denied: false,
|
|
55
|
+
props: {
|
|
56
|
+
...base,
|
|
57
|
+
sources: {
|
|
58
|
+
defaultId: null,
|
|
59
|
+
sources: []
|
|
60
|
+
},
|
|
61
|
+
goals: [],
|
|
62
|
+
timezone: "UTC",
|
|
63
|
+
scopeKey: ""
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const allowed = platformReadGate(runtime, req);
|
|
67
|
+
const [sources, goals, timezone, scopeKey] = await Promise.all([
|
|
68
|
+
resolveSourcesForRequest(req, { platformRead: allowed }),
|
|
69
|
+
resolveGoalsList(runtime, req, allowed),
|
|
70
|
+
requestTimezone(req),
|
|
71
|
+
resolveScopeKey(runtime, req)
|
|
72
|
+
]);
|
|
73
|
+
return {
|
|
74
|
+
denied: false,
|
|
75
|
+
props: {
|
|
76
|
+
...base,
|
|
77
|
+
sources: {
|
|
78
|
+
defaultId: sources.defaultId,
|
|
79
|
+
sources: sources.sources
|
|
80
|
+
},
|
|
81
|
+
goals,
|
|
82
|
+
timezone,
|
|
83
|
+
scopeKey
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
//#endregion
|
|
88
|
+
export { resolveViewProps };
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=viewProps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"viewProps.js","names":[],"sources":["../../src/view/viewProps.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { DEFAULT_VIEW, type ResolvedOptions } from '../core/options'\nimport type { SourcesResponse } from '../fields/config/fetchSources'\nimport { resolveSourcesForRequest } from '../plugin/readContextForRequest'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\ttype PlatformReadGate,\n\tplatformReadGate,\n\trequestTimezone,\n\tresolveGoalsDetailedFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\n/** A goal as the view lists it: the picker needs no match or value details. */\nexport interface ViewGoal {\n\tslug: string\n\tname: string\n}\n\n/**\n * Everything the client shell needs to render without a second round trip. Serializable\n * by construction: the RSC boundary drops functions, so only wire shapes appear here.\n */\nexport interface AnalyticsViewClientProps {\n\t/** Same payload the sources endpoint answers, resolved for this request's scope. */\n\tsources: SourcesResponse\n\tgoals: ViewGoal[]\n\tdefaults: { range: TimeframePreset; metric: MetricKey }\n\tapiRoute: string\n\tadminRoute: string\n\t/** IANA reporting timezone the day boundaries align to. */\n\ttimezone: string\n\t/** Admin UI language (`req.i18n.language`), for number and date formatting. */\n\tlocale: string\n\t/**\n\t * The analytics scope this render resolved to, `''` when there is none. The tenant\n\t * selector sets its cookie and calls `router.refresh()`, which re-renders this shell but\n\t * keeps client state, and the reads are identical strings for two tenants sharing an\n\t * adapter id. Keying the client body on this remounts it instead, so a switch refetches.\n\t */\n\tscopeKey: string\n}\n\n/**\n * `denied` is a value rather than a thrown error so the view can render its own\n * no-access message inside the admin template instead of redirecting a reader who is\n * already signed in.\n */\nexport type ViewPropsResult = { denied: true } | { denied: false; props: AnalyticsViewClientProps }\n\n/**\n * The goals the request's scope may see, mirroring the goals endpoint exactly: no scope\n * parameter, an unresolvable scope on a scoped install fails closed unless `platformRead`\n * lifts it, and a failed resolution falls back to the config goals only when unscoped.\n */\nconst resolveGoalsList = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tallowed: PlatformReadGate\n): Promise<ViewGoal[]> => {\n\tconst configGoals = (): ViewGoal[] =>\n\t\t(runtime.goals ?? []).map((goal) => ({ slug: goal.slug, name: goal.name }))\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\tif (runtime.scoped && scope === null && !(await allowed())) {\n\t\t\treturn []\n\t\t}\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\treturn resolved.map(({ goal }) => ({ slug: goal.slug, name: goal.name }))\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: view goals listing failed: ${String(err)}`)\n\t\treturn runtime.scoped ? [] : configGoals()\n\t}\n}\n\n/** The resolved scope as a render key; a resolver that throws keys as the scope-less render. */\nconst resolveScopeKey = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<string> => {\n\ttry {\n\t\treturn (await resolveScopeFor(runtime, req)) ?? ''\n\t} catch {\n\t\treturn ''\n\t}\n}\n\n/**\n * Resolves the client shell's props for one request. Split from the server component so the\n * whole resolution (access, scope gating, sources, goals, timezone) is testable without a\n * React render.\n */\nexport const resolveViewProps = async (\n\treq: PayloadRequest,\n\tresolved: ResolvedOptions\n): Promise<ViewPropsResult> => {\n\tif (!(await resolved.access.view({ req }))) {\n\t\treturn { denied: true }\n\t}\n\t// `false` cannot reach a render (the view is then never registered); it defaults anyway.\n\tconst view = resolved.view === false ? DEFAULT_VIEW : resolved.view\n\tconst runtime = getRuntime(req.payload)\n\tconst base = {\n\t\tdefaults: { range: view.defaultRange, metric: view.defaultMetric },\n\t\tapiRoute: req.payload.config.routes?.api ?? '/api',\n\t\tadminRoute: req.payload.config.routes?.admin ?? '/admin',\n\t\tlocale: req.i18n.language,\n\t}\n\t// No runtime means onInit has not run (or the plugin is disabled): nothing is readable.\n\tif (!runtime) {\n\t\treturn {\n\t\t\tdenied: false,\n\t\t\tprops: {\n\t\t\t\t...base,\n\t\t\t\tsources: { defaultId: null, sources: [] },\n\t\t\t\tgoals: [],\n\t\t\t\ttimezone: DEFAULT_TIMEZONE,\n\t\t\t\tscopeKey: '',\n\t\t\t},\n\t\t}\n\t}\n\tconst allowed = platformReadGate(runtime, req)\n\tconst [sources, goals, timezone, scopeKey] = await Promise.all([\n\t\tresolveSourcesForRequest(req, { platformRead: allowed }),\n\t\tresolveGoalsList(runtime, req, allowed),\n\t\t// The same helper every read path uses, so the caption and the numbers agree: it\n\t\t// narrows the cross-scope marker to null before resolving, which resolving through\n\t\t// the runtime directly would not.\n\t\trequestTimezone(req),\n\t\tresolveScopeKey(runtime, req),\n\t])\n\treturn {\n\t\tdenied: false,\n\t\tprops: {\n\t\t\t...base,\n\t\t\tsources: { defaultId: sources.defaultId, sources: sources.sources },\n\t\t\tgoals,\n\t\t\ttimezone,\n\t\t\tscopeKey,\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;AA2DA,MAAM,mBAAmB,OACxB,SACA,KACA,YACyB;CAC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AG;CAC7C,MAAM,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,IAAI;EAC9D,yBAAyB,KAAK,EAAE,cAAc,QAAQ,CAAC;EACvD,iBAAiB,SAAS,KAAK,OAAO;EAItC,gBAAgB,GAAG;EACnB,gBAAgB,SAAS,GAAG;CAC7B,CAAC;CACD,OAAO;EACN,QAAQ;EACR,OAAO;GACN,GAAG;GACH,SAAS;IAAE,WAAW,QAAQ;IAAW,SAAS,QAAQ;GAAQ;GAClE;GACA;GACA;EACD;CACD;AACD"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { WidgetViewProps } from "./viewLink.js";
|
|
1
2
|
import { WidgetServerProps } from "payload";
|
|
2
3
|
|
|
3
4
|
//#region src/widgets/AnalyticsBreakdownWidget.d.ts
|
|
4
|
-
declare function AnalyticsBreakdownWidget(props: WidgetServerProps): Promise<import("react/jsx-runtime").JSX.Element>;
|
|
5
|
+
declare function AnalyticsBreakdownWidget(props: WidgetServerProps & WidgetViewProps): Promise<import("react/jsx-runtime").JSX.Element>;
|
|
5
6
|
//#endregion
|
|
6
7
|
export { AnalyticsBreakdownWidget };
|
|
7
8
|
//# sourceMappingURL=AnalyticsBreakdownWidget.d.ts.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { requestTimezone } from "../plugin/runtime.js";
|
|
1
2
|
import { keys } from "../translations/keys.js";
|
|
2
3
|
import { asTranslate } from "../translations/server.js";
|
|
3
4
|
import { TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
@@ -7,6 +8,8 @@ import { readForWidgetBreakdown } from "./readForWidgetBreakdown.js";
|
|
|
7
8
|
import { BarList } from "../charts/BarList.js";
|
|
8
9
|
import { formatMetricValue } from "../fields/format.js";
|
|
9
10
|
import { cardStyle, labelStyle } from "./cardChrome.js";
|
|
11
|
+
import { viewTabForDimension, widgetViewHref } from "./viewLink.js";
|
|
12
|
+
import { WidgetViewLink } from "./WidgetViewLink.js";
|
|
10
13
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
11
14
|
//#region src/widgets/AnalyticsBreakdownWidget.tsx
|
|
12
15
|
const STATE_KEY = {
|
|
@@ -19,7 +22,8 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
19
22
|
const data = props.widgetData ?? {};
|
|
20
23
|
const metric = data.metric ?? "pageviews";
|
|
21
24
|
const rawTimeframe = data.timeframe ?? "last30days";
|
|
22
|
-
const
|
|
25
|
+
const timezone = rawTimeframe === "custom" ? await requestTimezone(props.req) : void 0;
|
|
26
|
+
const customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : void 0;
|
|
23
27
|
const timeframe = rawTimeframe === "custom" ? "last30days" : rawTimeframe;
|
|
24
28
|
const limit = data.limit ?? 5;
|
|
25
29
|
const title = data.title?.trim() || (spec ? t(spec.label) : "");
|
|
@@ -31,6 +35,7 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
31
35
|
children: t(keys.stateUnavailable)
|
|
32
36
|
})
|
|
33
37
|
});
|
|
38
|
+
const tab = viewTabForDimension(spec.dimension);
|
|
34
39
|
const result = await readForWidgetBreakdown({
|
|
35
40
|
req: props.req,
|
|
36
41
|
metric,
|
|
@@ -39,10 +44,19 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
39
44
|
limit,
|
|
40
45
|
adapterId: data.dataSource,
|
|
41
46
|
now: /* @__PURE__ */ new Date(),
|
|
42
|
-
range: customRange
|
|
47
|
+
range: customRange,
|
|
48
|
+
...timezone ? { timezone } : {}
|
|
49
|
+
});
|
|
50
|
+
const href = widgetViewHref(props.view, props.req, {
|
|
51
|
+
timeframe: rawTimeframe,
|
|
52
|
+
timezone: timezone ?? "UTC",
|
|
53
|
+
...customRange ? { range: customRange } : {},
|
|
54
|
+
...result.adapterId ? { source: result.adapterId } : {},
|
|
55
|
+
...tab ? { tab } : {},
|
|
56
|
+
metric
|
|
43
57
|
});
|
|
44
58
|
const locale = props.req.i18n.language ?? "en-US";
|
|
45
|
-
const caption = customRange ? formatRangeCaption(customRange, locale) : t(TIMEFRAME_KEYS[timeframe]);
|
|
59
|
+
const caption = customRange && timezone ? formatRangeCaption(customRange, locale, timezone) : t(TIMEFRAME_KEYS[timeframe]);
|
|
46
60
|
return /* @__PURE__ */ jsxs("div", {
|
|
47
61
|
className: "analytics-breakdown-widget",
|
|
48
62
|
style: cardStyle,
|
|
@@ -75,7 +89,11 @@ async function AnalyticsBreakdownWidget(props) {
|
|
|
75
89
|
color: "var(--theme-elevation-400)"
|
|
76
90
|
},
|
|
77
91
|
children: t(keys.stateClamped)
|
|
78
|
-
}) : null
|
|
92
|
+
}) : null,
|
|
93
|
+
/* @__PURE__ */ jsx(WidgetViewLink, {
|
|
94
|
+
href,
|
|
95
|
+
label: t(keys.widgetOpenInView)
|
|
96
|
+
})
|
|
79
97
|
]
|
|
80
98
|
});
|
|
81
99
|
}
|