@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.13
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 +67 -0
- package/dist/adapters/ga4/ga4.d.ts +6 -0
- package/dist/adapters/ga4/ga4.js +3 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.d.ts +6 -0
- package/dist/adapters/plausible/plausible.js +2 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +6 -0
- package/dist/adapters/posthog/posthog.js +21 -8
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +6 -0
- package/dist/adapters/umami/umami.js +2 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/exclusionEndpoint.js +1 -1
- package/dist/capture/exclusionEndpoint.js.map +1 -1
- package/dist/capture/slots.js +3 -3
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.js +11 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/adminOptions.js +6 -1
- package/dist/core/adminOptions.js.map +1 -1
- package/dist/core/capture.d.ts +3 -1
- package/dist/core/contract.d.ts +13 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +37 -5
- package/dist/core/options.js +6 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/registry.js.map +1 -1
- package/dist/core/scopeOptions.js +2 -0
- package/dist/core/scopeOptions.js.map +1 -1
- package/dist/core/scopedRead.js +170 -21
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceLabel.d.ts +10 -0
- package/dist/core/sourceLabel.js +63 -0
- package/dist/core/sourceLabel.js.map +1 -0
- package/dist/core/sourceOptions.js +18 -6
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +55 -0
- package/dist/core/sourcePolicy.js +51 -0
- package/dist/core/sourcePolicy.js.map +1 -0
- package/dist/exports/adapters/contract.d.ts +2 -1
- package/dist/exports/adapters/ga4.d.ts +3 -2
- package/dist/exports/adapters/native.d.ts +3 -2
- package/dist/exports/adapters/plausible.d.ts +3 -2
- package/dist/exports/adapters/posthog.d.ts +3 -2
- package/dist/exports/adapters/umami.d.ts +3 -2
- package/dist/exports/client.d.ts +7 -5
- package/dist/exports/client.js +2 -1
- package/dist/exports/next.d.ts +3 -2
- package/dist/exports/rsc.d.ts +7 -6
- package/dist/exports/testing.d.ts +3 -2
- package/dist/exports/types.d.ts +12 -8
- package/dist/fields/AnalyticsPanelClient.js.map +1 -1
- package/dist/fields/AnalyticsPanelField.d.ts +1 -1
- package/dist/fields/AnalyticsPanelField.js +3 -1
- package/dist/fields/AnalyticsPanelField.js.map +1 -1
- package/dist/fields/AnalyticsStatField.d.ts +1 -1
- package/dist/fields/AnalyticsStatField.js +1 -1
- package/dist/fields/PanelContent.js +6 -1
- package/dist/fields/PanelContent.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +3 -0
- package/dist/fields/config/fetchSources.js +5 -3
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/fields/readForDocument.d.ts +5 -4
- package/dist/fields/readForDocument.js +6 -2
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/collection.js +4 -31
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +2 -2
- package/dist/goals/trackGoalAction.js +1 -1
- package/dist/index.d.ts +14 -11
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/ingest/normalizeEvent.js +1 -1
- package/dist/native/nativeAdapter.d.ts +6 -0
- package/dist/native/nativeAdapter.js +3 -2
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/plugin/createRuntime.js +6 -3
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +1 -0
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/pluginCollections.js +11 -5
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +11 -0
- package/dist/plugin/readContextForRequest.js +25 -15
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/runtime.js +13 -5
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +8 -9
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/ProvidersListNotice.d.ts +11 -0
- package/dist/providers/ProvidersListNotice.js +36 -0
- package/dist/providers/ProvidersListNotice.js.map +1 -0
- package/dist/providers/collection.d.ts +9 -1
- package/dist/providers/collection.js +107 -42
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.d.ts +1 -1
- package/dist/providers/factory.js +8 -11
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/probe.js +5 -1
- package/dist/providers/probe.js.map +1 -1
- package/dist/providers/registry.js +49 -39
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/resolver.js +6 -3
- package/dist/providers/resolver.js.map +1 -1
- package/dist/providers/scopeUnique.js +41 -0
- package/dist/providers/scopeUnique.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/tracker/config.d.ts +5 -0
- package/dist/tracker/config.js.map +1 -1
- package/dist/tracker/sinks/createSink.js +4 -1
- package/dist/tracker/sinks/createSink.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/tracker/sinks/posthog.js +30 -2
- package/dist/tracker/sinks/posthog.js.map +1 -1
- package/dist/tracker/sinks/vendor.js +2 -2
- package/dist/tracker/sinks/vendor.js.map +1 -1
- package/dist/translations/ar.js +6 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +6 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +6 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +6 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +6 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +6 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +6 -0
- package/dist/translations/keys.js +7 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +6 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +6 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +6 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +6 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +6 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +5 -0
- package/dist/ui/components/SourcesNoticeBanner.js +20 -0
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
- package/dist/view/ViewRoot.js +2 -0
- package/dist/view/ViewRoot.js.map +1 -1
- package/dist/view/registerView.js +5 -4
- package/dist/view/registerView.js.map +1 -1
- package/dist/view/viewContext.d.ts +1 -1
- package/dist/view/viewProps.d.ts +1 -1
- package/dist/view/viewProps.js +3 -2
- package/dist/view/viewProps.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +1 -0
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +1 -0
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/defaultLayout.d.ts +26 -0
- package/dist/widgets/defaultLayout.js +51 -0
- package/dist/widgets/defaultLayout.js.map +1 -0
- package/dist/widgets/notices.js +1 -0
- package/dist/widgets/notices.js.map +1 -1
- package/dist/widgets/prepareWidgetRead.d.ts +14 -1
- package/dist/widgets/prepareWidgetRead.js +6 -2
- package/dist/widgets/prepareWidgetRead.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +4 -4
- package/dist/widgets/readForWidget.js +3 -1
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
- package/dist/widgets/readForWidgetBreakdown.js +3 -1
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +4 -4
- package/dist/widgets/readForWidgetGoals.js +3 -1
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
- package/dist/widgets/readForWidgetRealtime.js +3 -1
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +4 -4
- package/dist/widgets/readForWidgetSeries.js +3 -1
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +3 -1
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsPanelClient.js","names":["useTranslation"],"sources":["../../src/fields/AnalyticsPanelClient.tsx"],"sourcesContent":["'use client'\n\nimport { Banner, Button, useConfig, useDocumentInfo } from '@payloadcms/ui'\nimport { type ReactNode, useState } from 'react'\nimport type { ReportMode } from '../binding/report'\nimport type { SeriesGranularity, SeriesPoint } from '../charts/series'\nimport type { DimensionKey, MetricKey, MetricValues } from '../core/contract'\nimport { isRecord } from '../core/values'\nimport { apiPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { intlLocale } from '../translations/intl'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { LabeledSelect } from '../ui/components/LabeledSelect'\nimport { type RequestFailure, requestShaped } from '../ui/data/request'\nimport { useRequest } from '../ui/data/useRequest'\nimport { retryOfferFor } from '../ui/readState'\nimport { viewerNow } from '../ui/viewerClock'\nimport type { CountryFlags } from '../view/CountryFlag'\nimport type { ReadNotices } from '../widgets/readMeta'\nimport { AnalyticsEmptyState, isNewDocumentAnalytics } from './emptyState'\nimport { ITEM_PANEL_DIMENSIONS } from './itemReport'\nimport { PanelContent } from './PanelContent'\nimport { PanelLiveCounter } from './PanelLiveCounter'\nimport { PanelSkeleton } from './PanelSkeleton'\nimport type { FieldBreakdown, FieldReadStatus } from './readForDocument'\nimport { FIELD_STATE_KEYS } from './stateKeys'\nimport '../ui/analytics.css'\n\n/** JSON-safe shape of a document analytics read, as the panel endpoint returns it. */\nexport interface PanelData {\n\tstatus: FieldReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\t/** The headline answered, but a comparison, series or list did not. */\n\tincomplete?: true\n\t/** `item` for a read about the document as a content item; absent for its own page. */\n\treport?: 'item'\n\t/** An average with nothing to average over is `null`, which the cards show as a dash. */\n\tmetrics: MetricValues\n\tsupportedMetrics: MetricKey[]\n\tpreviousMetrics?: MetricValues\n\tcomparisonRange?: { start: string; end: string } | null\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone?: string\n\t/** The window the read covered, which decides whether a document with no data is new. */\n\tdateRange?: { start: string; end: string }\n\tpoints?: SeriesPoint[]\n\t/** The bucket `points` carry; a chart drawn by hour needs hourly rows to draw. */\n\tseriesGranularity?: SeriesGranularity\n\t/** The source counts live visitors, so the live counter is worth polling for. */\n\trealtime?: boolean\n\t/** One ranked list per dimension the source could narrow to this page. */\n\tbreakdowns?: FieldBreakdown[]\n\t/** What the totals' and the series' reads say about their numbers. */\n\tnotices?: ReadNotices\n}\n\n/** The parts of a panel answer the panel reads before it renders. */\nconst isPanelData = (value: unknown): value is PanelData =>\n\tisRecord(value) &&\n\ttypeof value.status === 'string' &&\n\tisRecord(value.metrics) &&\n\tArray.isArray(value.supportedMetrics) &&\n\t(value.points === undefined || Array.isArray(value.points)) &&\n\t(value.breakdowns === undefined || Array.isArray(value.breakdowns))\n\n/**\n * How far server's seed can be trusted: `fresh` needs no read, `stale` shows and is reread from\n * its source, `missing` has nothing worth showing and is read before cards appear.\n */\nexport type PanelSeed = 'fresh' | 'stale' | 'missing'\n\n/** One source the switcher may offer, and whether it can read a document as an item. */\nexport interface PanelSource {\n\tid: string\n\tlabel: string\n\tperItemQuery?: boolean\n}\n\nexport interface AnalyticsPanelClientProps {\n\tcollectionSlug: string\n\tmetrics: MetricKey[]\n\t/** Metrics the factory added speculatively, echoed so a refetch keeps them unwarned. */\n\toptionalMetrics?: MetricKey[]\n\t/** Dimensions to rank for this page; empty leaves the breakdown row out. */\n\tdimensions: DimensionKey[]\n\t/** Poll the live counter where the source counts live visitors. */\n\tliveVisitors: boolean\n\t/** The flag beside a country name: none, the plugin's own, or the host's component. */\n\tcountryFlags: CountryFlags\n\t/** The server's seed; absent when it had none, and the panel reads before showing numbers. */\n\tinitial?: PanelData\n\t/**\n\t * The instant the server rendered the panel, which the seed's counting bucket is marked by: one\n\t * clock for the server's markup and the browser's first paint, so the two never disagree.\n\t */\n\trenderedAt: string\n\t/** How far to trust `initial`; absent means `fresh` with a seed and `missing` without one. */\n\tseed?: PanelSeed\n\tinitialTimeframe: TimeframePreset\n\tadapterId?: string\n\t/**\n\t * Sources this document's scope offers, prefiltered to what reader may read and can narrow to\n\t * that scope. One entry draws no switcher; item report offers only those that read an item.\n\t */\n\tsources?: PanelSource[]\n\t/** The source the server read through, which the switcher opens on. */\n\tinitialSourceId?: string\n\t/** Metric card labels resolved to plain strings on the server. */\n\tlabels?: Partial<Record<MetricKey, string>>\n\t/** ISO 4217 code revenue renders in; absent leaves it a plain number. */\n\tcurrency?: string\n\t/** The reports the panel offers, the one it opened on first. More than one draws a switch. */\n\tmodes?: ReportMode[]\n\t/** The report the server read for the first paint. */\n\tinitialReport?: ReportMode\n\t/** Item card labels the developer set; other cards keep the item report's own names. */\n\titemLabelOverrides?: Partial<Record<MetricKey, string>>\n\t/** Creation time (ISO), absent without timestamps; see {@link isNewDocumentAnalytics}. */\n\tcreatedAt?: string\n}\n\nconst REPORT_LABELS: Record<ReportMode, TranslationKey> = {\n\titem: keys.panelReportItem,\n\tpage: keys.panelReportPage,\n}\n\n/** The window and the read that answered for it, which only ever change together. */\ninterface PanelView {\n\ttimeframe: TimeframePreset\n\tdata: PanelData\n\t/** When the numbers were read, which decides the bucket that is still counting. */\n\treadAt: string\n}\n\n/** Stands in for the numbers while the first read runs; nothing renders from it. */\nconst NOTHING_YET: PanelData = { status: 'ok', metrics: {}, supportedMetrics: [] }\n\ninterface PanelRead {\n\tpreset: TimeframePreset\n\tsource: string | undefined\n\tmode: ReportMode\n}\n\nconst readKey = (read: PanelRead): string => JSON.stringify(read)\n\n/** What the panel says for a request that failed, worded as a read's status would be. */\nconst failedState = (\n\tfailure: RequestFailure | undefined\n): Pick<PanelData, 'status' | 'retryAfterMs'> => {\n\tswitch (failure?.code) {\n\t\tcase 'forbidden':\n\t\t\treturn { status: 'no-access' }\n\t\tcase 'range_too_long':\n\t\t\treturn { status: 'range-too-long' }\n\t\tcase 'invalid_param':\n\t\t\treturn { status: 'invalid' }\n\t\tcase 'unsupported':\n\t\tcase 'not_found':\n\t\t\treturn { status: 'unavailable' }\n\t\tcase 'source_misconfigured':\n\t\t\treturn { status: failure.hostRefused ? 'host-refused' : 'misconfigured' }\n\t\tcase 'unavailable':\n\t\tcase 'rate_limited':\n\t\t\treturn {\n\t\t\t\tstatus: 'busy',\n\t\t\t\t...(failure.retryAfter === undefined ? {} : { retryAfterMs: failure.retryAfter * 1000 }),\n\t\t\t}\n\t\tdefault:\n\t\t\treturn { status: 'busy' }\n\t}\n}\n\n/** Statuses that are a failure of the read, said in an error banner, rather than a state. */\nconst FAILED: ReadonlySet<FieldReadStatus> = new Set<FieldReadStatus>([\n\t'busy',\n\t'invalid',\n\t'range-too-long',\n\t'misconfigured',\n\t'host-refused',\n])\n\n/** Cards an item report draws for most sources: views, viewers, clicks and the click rate. */\nconst ITEM_SKELETON_CARDS = 4\n\n/** The lists a report ranks: the item's own wherever the panel draws lists at all. */\nconst listsFor = (report: ReportMode, dimensions: DimensionKey[]): DimensionKey[] =>\n\treport === 'item' && dimensions.length > 0 ? ITEM_PANEL_DIMENSIONS : dimensions\n\n/** The source a report reads through: the current one where it can, else the first that can. */\nconst sourceFor = (\n\treport: ReportMode,\n\tcurrent: string | undefined,\n\tsources: PanelSource[]\n): string | undefined => {\n\tif (report === 'page' || sources.length === 0) {\n\t\treturn current\n\t}\n\tif (sources.some((source) => source.id === current && source.perItemQuery === true)) {\n\t\treturn current\n\t}\n\treturn sources.find((source) => source.perItemQuery === true)?.id ?? current\n}\n\n/**\n * Per-document analytics panel. A stale or missing server seed is reread on mount (when its tab\n * opens); on a collection bound as items it reports the document as content shown elsewhere.\n */\nexport function AnalyticsPanelClient(props: AnalyticsPanelClientProps) {\n\tconst {\n\t\tcollectionSlug,\n\t\tmetrics,\n\t\toptionalMetrics,\n\t\tdimensions,\n\t\tliveVisitors,\n\t\tcountryFlags,\n\t\tinitial,\n\t\tinitialTimeframe,\n\t\tadapterId,\n\t} = props\n\tconst modes: ReportMode[] = props.modes ?? ['page']\n\tconst sources = props.sources ?? []\n\tconst { t, i18n } = useTranslation()\n\tconst locale = intlLocale(i18n.language)\n\tconst { id } = useDocumentInfo()\n\tconst { config } = useConfig()\n\tconst documentEndpoint = apiPath(config, analyticsRoutes(config).document)\n\tconst seed: PanelSeed = props.seed ?? (initial ? 'fresh' : 'missing')\n\tconst initialSourceId = props.initialSourceId ?? adapterId\n\tconst initialReport = props.initialReport ?? modes[0] ?? 'page'\n\t// `pending` is what the picker shows; the caption and every formatter follow the window the\n\t// numbers on screen were read for, which only changes when that read lands.\n\tconst [pending, setPending] = useState<TimeframePreset>(initialTimeframe)\n\tconst [sourceId, setSourceId] = useState<string | undefined>(initialSourceId)\n\tconst [report, setReport] = useState<ReportMode>(initialReport)\n\n\tconst read: PanelRead = { preset: pending, source: sourceId, mode: report }\n\tconst documentId = id === undefined || id === null ? null : String(id)\n\t// Mounting means the tab is open, so an unvouched seed is read now, never in the document's\n\t// render. Another source or report restarts from the shimmer; another window dims old numbers.\n\tconst request = useRequest<PanelView>({\n\t\tkey: documentId === null ? null : readKey(read),\n\t\tkeep: `${sourceId ?? ''}|${report}`,\n\t\t...(initial === undefined || seed === 'missing'\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tseed: {\n\t\t\t\t\t\tkey: readKey({\n\t\t\t\t\t\t\tpreset: initialTimeframe,\n\t\t\t\t\t\t\tsource: initialSourceId,\n\t\t\t\t\t\t\tmode: initialReport,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tdata: { timeframe: initialTimeframe, data: initial, readAt: props.renderedAt },\n\t\t\t\t\t\tstale: seed === 'stale',\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\trun: async ({ signal, revalidating }) => {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tcollection: collectionSlug,\n\t\t\t\tid: documentId ?? '',\n\t\t\t\ttimeframe: read.preset,\n\t\t\t\tcompare: '1',\n\t\t\t\tseries: '1',\n\t\t\t\treport: read.mode,\n\t\t\t})\n\t\t\t// An item report reads the item's own metrics and lists, which the endpoint knows.\n\t\t\tif (read.mode === 'page') {\n\t\t\t\tparams.set('metrics', metrics.join(','))\n\t\t\t\tconst optional = optionalMetrics?.join(',') ?? ''\n\t\t\t\tif (optional !== '') {\n\t\t\t\t\tparams.set('optional', optional)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst lists = listsFor(read.mode, dimensions).join(',')\n\t\t\tif (lists !== '') {\n\t\t\t\tparams.set('dimensions', lists)\n\t\t\t}\n\t\t\tif (read.source) {\n\t\t\t\tparams.set('dataSource', read.source)\n\t\t\t}\n\t\t\t// A stale seed is read past its expired cache entry, straight from its source.\n\t\t\tif (revalidating) {\n\t\t\t\tparams.set('fresh', '1')\n\t\t\t}\n\t\t\tconst data = await requestShaped(`${documentEndpoint}?${params}`, isPanelData, { signal })\n\t\t\treturn { timeframe: read.preset, data, readAt: viewerNow().toISOString() }\n\t\t},\n\t})\n\tconst retriable = documentId !== null && request.status === 'error'\n\n\tconst onTimeframeChange = (preset: TimeframePreset) => {\n\t\t// Re-picking the window already selected is a retry after a failed read, the one way back\n\t\t// from the unavailable state without touching the picker twice.\n\t\tif (preset === pending) {\n\t\t\trequest.refetch()\n\t\t\treturn\n\t\t}\n\t\tsetPending(preset)\n\t}\n\n\tconst onReportChange = (next: ReportMode) => {\n\t\tsetReport(next)\n\t\tsetSourceId(sourceFor(next, sourceId, sources))\n\t}\n\n\tconst shownView = (): Omit<PanelView, 'data'> & { data: PanelData | undefined } => {\n\t\t// Nothing to read for a document that has no id: the seed stands, or the panel says so.\n\t\tif (documentId === null) {\n\t\t\treturn {\n\t\t\t\ttimeframe: initialTimeframe,\n\t\t\t\tdata: initial ?? { ...NOTHING_YET, status: 'unavailable' },\n\t\t\t\treadAt: props.renderedAt,\n\t\t\t}\n\t\t}\n\t\tconst timeframe = request.data?.timeframe ?? pending\n\t\tconst readAt = request.data?.readAt ?? props.renderedAt\n\t\tif (!retriable) {\n\t\t\treturn { timeframe, data: request.data?.data, readAt }\n\t\t}\n\t\treturn {\n\t\t\ttimeframe,\n\t\t\tdata: {\n\t\t\t\t...(request.data?.data ?? NOTHING_YET),\n\t\t\t\t...failedState(request.error),\n\t\t\t\t...(report === 'item' ? { report: 'item' } : {}),\n\t\t\t},\n\t\t\treadAt,\n\t\t}\n\t}\n\tconst view = shownView()\n\tconst loading = request.isRefetching\n\tconst waiting = view.data === undefined\n\tconst data = view.data ?? NOTHING_YET\n\tconst itemData = data.report === 'item'\n\tconst offered = sources.filter((source) => report === 'page' || source.perItemQuery === true)\n\tconst retryButton =\n\t\tdocumentId === null ? null : (\n\t\t\t<Button buttonStyle=\"secondary\" margin={false} onClick={() => request.refetch()} size=\"small\">\n\t\t\t\t{t(keys.viewRetry)}\n\t\t\t</Button>\n\t\t)\n\n\tconst body = (): ReactNode => {\n\t\tif (waiting) {\n\t\t\treturn (\n\t\t\t\t<PanelSkeleton\n\t\t\t\t\tcards={report === 'item' ? ITEM_SKELETON_CARDS : metrics.length}\n\t\t\t\t\tlists={listsFor(report, dimensions).length}\n\t\t\t\t/>\n\t\t\t)\n\t\t}\n\t\tif (isNewDocumentAnalytics(data, props.createdAt)) {\n\t\t\treturn (\n\t\t\t\t<div className=\"analytics-panel__empty\">\n\t\t\t\t\t<AnalyticsEmptyState isNew>{t(keys.stateNew)}</AnalyticsEmptyState>\n\t\t\t\t\t<span>{t(itemData ? keys.panelNewItem : keys.panelNewPage)}</span>\n\t\t\t\t</div>\n\t\t\t)\n\t\t}\n\t\tif (data.status !== 'ok' && FAILED.has(data.status)) {\n\t\t\tconst retry = retryOfferFor(data.status, data.retryAfterMs, { t, locale })\n\t\t\treturn (\n\t\t\t\t<div className=\"analytics-panel__state\">\n\t\t\t\t\t<Banner type=\"error\">{t(FIELD_STATE_KEYS[data.status])}</Banner>\n\t\t\t\t\t{retry?.after ? <span className=\"analytics-panel__caption\">{retry.after}</span> : null}\n\t\t\t\t\t{retry ? retryButton : null}\n\t\t\t\t</div>\n\t\t\t)\n\t\t}\n\t\tif (data.status !== 'ok') {\n\t\t\treturn (\n\t\t\t\t<AnalyticsEmptyState isNew={false}>{t(FIELD_STATE_KEYS[data.status])}</AnalyticsEmptyState>\n\t\t\t)\n\t\t}\n\t\treturn (\n\t\t\t<PanelContent\n\t\t\t\tcountryFlags={countryFlags}\n\t\t\t\tcurrency={props.currency}\n\t\t\t\tdata={data}\n\t\t\t\titemLabelOverrides={props.itemLabelOverrides}\n\t\t\t\tlabels={props.labels}\n\t\t\t\treadAt={view.readAt}\n\t\t\t\tretryButton={retryButton}\n\t\t\t\ttimeframe={view.timeframe}\n\t\t\t/>\n\t\t)\n\t}\n\n\t// The toolbar is the analytics view's in miniature: the controls on the left in the view's\n\t// order, the live indicator pushed right, and everything free to wrap on a narrow sidebar.\n\treturn (\n\t\t<div className=\"field-type analytics-panel\">\n\t\t\t<div className=\"analytics-panel__toolbar\">\n\t\t\t\t<div className=\"analytics-panel__controls\">\n\t\t\t\t\t{modes.length > 1 ? (\n\t\t\t\t\t\t<div className=\"analytics-panel__control\">\n\t\t\t\t\t\t\t<LabeledSelect\n\t\t\t\t\t\t\t\tlabel={t(keys.panelReportLabel)}\n\t\t\t\t\t\t\t\tonChange={(next) => {\n\t\t\t\t\t\t\t\t\tif (next !== report) {\n\t\t\t\t\t\t\t\t\t\tonReportChange(next)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\toptions={modes.map((mode) => ({ value: mode, label: t(REPORT_LABELS[mode]) }))}\n\t\t\t\t\t\t\t\tvalue={report}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : null}\n\t\t\t\t\t{offered.length > 1 ? (\n\t\t\t\t\t\t<div className=\"analytics-panel__control\">\n\t\t\t\t\t\t\t<LabeledSelect\n\t\t\t\t\t\t\t\tlabel={t(keys.viewSourceLabel)}\n\t\t\t\t\t\t\t\tonChange={(next) => {\n\t\t\t\t\t\t\t\t\tif (next !== sourceId) {\n\t\t\t\t\t\t\t\t\t\tsetSourceId(next)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\toptions={offered.map((s) => ({ value: s.id, label: s.label }))}\n\t\t\t\t\t\t\t\tvalue={sourceId}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : null}\n\t\t\t\t\t<div className=\"analytics-panel__control\">\n\t\t\t\t\t\t<LabeledSelect\n\t\t\t\t\t\t\tlabel={t(keys.widgetFieldRange)}\n\t\t\t\t\t\t\tonChange={(preset) => {\n\t\t\t\t\t\t\t\tif (preset !== pending || retriable) {\n\t\t\t\t\t\t\t\t\tonTimeframeChange(preset)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\toptions={TIMEFRAME_PRESETS.map((preset) => ({\n\t\t\t\t\t\t\t\tvalue: preset,\n\t\t\t\t\t\t\t\tlabel: t(TIMEFRAME_KEYS[preset]),\n\t\t\t\t\t\t\t}))}\n\t\t\t\t\t\t\tvalue={pending}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t{liveVisitors && !itemData && data.realtime && documentId !== null ? (\n\t\t\t\t\t<PanelLiveCounter\n\t\t\t\t\t\tcollectionSlug={collectionSlug}\n\t\t\t\t\t\t{...(sourceId ? { dataSource: sourceId } : {})}\n\t\t\t\t\t\tdocumentId={documentId}\n\t\t\t\t\t/>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t\t<div\n\t\t\t\taria-busy={loading || waiting}\n\t\t\t\tclassName={\n\t\t\t\t\tloading && !waiting\n\t\t\t\t\t\t? 'analytics-panel__body analytics-panel__body--dimmed'\n\t\t\t\t\t\t: 'analytics-panel__body'\n\t\t\t\t}\n\t\t\t>\n\t\t\t\t{body()}\n\t\t\t</div>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,eAAe,UACpB,SAAS,KAAK,KACd,OAAO,MAAM,WAAW,YACxB,SAAS,MAAM,OAAO,KACtB,MAAM,QAAQ,MAAM,gBAAgB,MACnC,MAAM,WAAW,KAAA,KAAa,MAAM,QAAQ,MAAM,MAAM,OACxD,MAAM,eAAe,KAAA,KAAa,MAAM,QAAQ,MAAM,UAAU;AA0DlE,MAAM,gBAAoD;CACzD,M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}
|
|
1
|
+
{"version":3,"file":"AnalyticsPanelClient.js","names":["useTranslation"],"sources":["../../src/fields/AnalyticsPanelClient.tsx"],"sourcesContent":["'use client'\n\nimport { Banner, Button, useConfig, useDocumentInfo } from '@payloadcms/ui'\nimport { type ReactNode, useState } from 'react'\nimport type { ReportMode } from '../binding/report'\nimport type { SeriesGranularity, SeriesPoint } from '../charts/series'\nimport type { DimensionKey, MetricKey, MetricValues } from '../core/contract'\nimport { isRecord } from '../core/values'\nimport { apiPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { intlLocale } from '../translations/intl'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { LabeledSelect } from '../ui/components/LabeledSelect'\nimport { type RequestFailure, requestShaped } from '../ui/data/request'\nimport { useRequest } from '../ui/data/useRequest'\nimport { retryOfferFor } from '../ui/readState'\nimport { viewerNow } from '../ui/viewerClock'\nimport type { CountryFlags } from '../view/CountryFlag'\nimport type { ReadNotices } from '../widgets/readMeta'\nimport { AnalyticsEmptyState, isNewDocumentAnalytics } from './emptyState'\nimport { ITEM_PANEL_DIMENSIONS } from './itemReport'\nimport { PanelContent } from './PanelContent'\nimport { PanelLiveCounter } from './PanelLiveCounter'\nimport { PanelSkeleton } from './PanelSkeleton'\nimport type { FieldBreakdown, FieldReadStatus } from './readForDocument'\nimport { FIELD_STATE_KEYS } from './stateKeys'\nimport '../ui/analytics.css'\n\n/** JSON-safe shape of a document analytics read, as the panel endpoint returns it. */\nexport interface PanelData {\n\tstatus: FieldReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\t/** The headline answered, but a comparison, series or list did not. */\n\tincomplete?: true\n\t/** `item` for a read about the document as a content item; absent for its own page. */\n\treport?: 'item'\n\t/** An average with nothing to average over is `null`, which the cards show as a dash. */\n\tmetrics: MetricValues\n\tsupportedMetrics: MetricKey[]\n\tpreviousMetrics?: MetricValues\n\tcomparisonRange?: { start: string; end: string } | null\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone?: string\n\t/** The window the read covered, which decides whether a document with no data is new. */\n\tdateRange?: { start: string; end: string }\n\tpoints?: SeriesPoint[]\n\t/** The bucket `points` carry; a chart drawn by hour needs hourly rows to draw. */\n\tseriesGranularity?: SeriesGranularity\n\t/** The source counts live visitors, so the live counter is worth polling for. */\n\trealtime?: boolean\n\t/** One ranked list per dimension the source could narrow to this page. */\n\tbreakdowns?: FieldBreakdown[]\n\t/** What the totals' and the series' reads say about their numbers. */\n\tnotices?: ReadNotices\n\t/** The stored source this reader cannot read; the scope's default answered instead. */\n\tsubstitutedFrom?: string\n}\n\n/** The parts of a panel answer the panel reads before it renders. */\nconst isPanelData = (value: unknown): value is PanelData =>\n\tisRecord(value) &&\n\ttypeof value.status === 'string' &&\n\tisRecord(value.metrics) &&\n\tArray.isArray(value.supportedMetrics) &&\n\t(value.points === undefined || Array.isArray(value.points)) &&\n\t(value.breakdowns === undefined || Array.isArray(value.breakdowns))\n\n/**\n * How far server's seed can be trusted: `fresh` needs no read, `stale` shows and is reread from\n * its source, `missing` has nothing worth showing and is read before cards appear.\n */\nexport type PanelSeed = 'fresh' | 'stale' | 'missing'\n\n/** One source the switcher may offer, and whether it can read a document as an item. */\nexport interface PanelSource {\n\tid: string\n\tlabel: string\n\tperItemQuery?: boolean\n}\n\nexport interface AnalyticsPanelClientProps {\n\tcollectionSlug: string\n\tmetrics: MetricKey[]\n\t/** Metrics the factory added speculatively, echoed so a refetch keeps them unwarned. */\n\toptionalMetrics?: MetricKey[]\n\t/** Dimensions to rank for this page; empty leaves the breakdown row out. */\n\tdimensions: DimensionKey[]\n\t/** Poll the live counter where the source counts live visitors. */\n\tliveVisitors: boolean\n\t/** The flag beside a country name: none, the plugin's own, or the host's component. */\n\tcountryFlags: CountryFlags\n\t/** The server's seed; absent when it had none, and the panel reads before showing numbers. */\n\tinitial?: PanelData\n\t/**\n\t * The instant the server rendered the panel, which the seed's counting bucket is marked by: one\n\t * clock for the server's markup and the browser's first paint, so the two never disagree.\n\t */\n\trenderedAt: string\n\t/** How far to trust `initial`; absent means `fresh` with a seed and `missing` without one. */\n\tseed?: PanelSeed\n\tinitialTimeframe: TimeframePreset\n\tadapterId?: string\n\t/**\n\t * Sources this document's scope offers, prefiltered to what reader may read and can narrow to\n\t * that scope. One entry draws no switcher; item report offers only those that read an item.\n\t */\n\tsources?: PanelSource[]\n\t/** The source the server read through, which the switcher opens on. */\n\tinitialSourceId?: string\n\t/** Metric card labels resolved to plain strings on the server. */\n\tlabels?: Partial<Record<MetricKey, string>>\n\t/** ISO 4217 code revenue renders in; absent leaves it a plain number. */\n\tcurrency?: string\n\t/** The reports the panel offers, the one it opened on first. More than one draws a switch. */\n\tmodes?: ReportMode[]\n\t/** The report the server read for the first paint. */\n\tinitialReport?: ReportMode\n\t/** Item card labels the developer set; other cards keep the item report's own names. */\n\titemLabelOverrides?: Partial<Record<MetricKey, string>>\n\t/** Creation time (ISO), absent without timestamps; see {@link isNewDocumentAnalytics}. */\n\tcreatedAt?: string\n}\n\nconst REPORT_LABELS: Record<ReportMode, TranslationKey> = {\n\titem: keys.panelReportItem,\n\tpage: keys.panelReportPage,\n}\n\n/** The window and the read that answered for it, which only ever change together. */\ninterface PanelView {\n\ttimeframe: TimeframePreset\n\tdata: PanelData\n\t/** When the numbers were read, which decides the bucket that is still counting. */\n\treadAt: string\n}\n\n/** Stands in for the numbers while the first read runs; nothing renders from it. */\nconst NOTHING_YET: PanelData = { status: 'ok', metrics: {}, supportedMetrics: [] }\n\ninterface PanelRead {\n\tpreset: TimeframePreset\n\tsource: string | undefined\n\tmode: ReportMode\n}\n\nconst readKey = (read: PanelRead): string => JSON.stringify(read)\n\n/** What the panel says for a request that failed, worded as a read's status would be. */\nconst failedState = (\n\tfailure: RequestFailure | undefined\n): Pick<PanelData, 'status' | 'retryAfterMs'> => {\n\tswitch (failure?.code) {\n\t\tcase 'forbidden':\n\t\t\treturn { status: 'no-access' }\n\t\tcase 'range_too_long':\n\t\t\treturn { status: 'range-too-long' }\n\t\tcase 'invalid_param':\n\t\t\treturn { status: 'invalid' }\n\t\tcase 'unsupported':\n\t\tcase 'not_found':\n\t\t\treturn { status: 'unavailable' }\n\t\tcase 'source_misconfigured':\n\t\t\treturn { status: failure.hostRefused ? 'host-refused' : 'misconfigured' }\n\t\tcase 'unavailable':\n\t\tcase 'rate_limited':\n\t\t\treturn {\n\t\t\t\tstatus: 'busy',\n\t\t\t\t...(failure.retryAfter === undefined ? {} : { retryAfterMs: failure.retryAfter * 1000 }),\n\t\t\t}\n\t\tdefault:\n\t\t\treturn { status: 'busy' }\n\t}\n}\n\n/** Statuses that are a failure of the read, said in an error banner, rather than a state. */\nconst FAILED: ReadonlySet<FieldReadStatus> = new Set<FieldReadStatus>([\n\t'busy',\n\t'invalid',\n\t'range-too-long',\n\t'misconfigured',\n\t'host-refused',\n])\n\n/** Cards an item report draws for most sources: views, viewers, clicks and the click rate. */\nconst ITEM_SKELETON_CARDS = 4\n\n/** The lists a report ranks: the item's own wherever the panel draws lists at all. */\nconst listsFor = (report: ReportMode, dimensions: DimensionKey[]): DimensionKey[] =>\n\treport === 'item' && dimensions.length > 0 ? ITEM_PANEL_DIMENSIONS : dimensions\n\n/** The source a report reads through: the current one where it can, else the first that can. */\nconst sourceFor = (\n\treport: ReportMode,\n\tcurrent: string | undefined,\n\tsources: PanelSource[]\n): string | undefined => {\n\tif (report === 'page' || sources.length === 0) {\n\t\treturn current\n\t}\n\tif (sources.some((source) => source.id === current && source.perItemQuery === true)) {\n\t\treturn current\n\t}\n\treturn sources.find((source) => source.perItemQuery === true)?.id ?? current\n}\n\n/**\n * Per-document analytics panel. A stale or missing server seed is reread on mount (when its tab\n * opens); on a collection bound as items it reports the document as content shown elsewhere.\n */\nexport function AnalyticsPanelClient(props: AnalyticsPanelClientProps) {\n\tconst {\n\t\tcollectionSlug,\n\t\tmetrics,\n\t\toptionalMetrics,\n\t\tdimensions,\n\t\tliveVisitors,\n\t\tcountryFlags,\n\t\tinitial,\n\t\tinitialTimeframe,\n\t\tadapterId,\n\t} = props\n\tconst modes: ReportMode[] = props.modes ?? ['page']\n\tconst sources = props.sources ?? []\n\tconst { t, i18n } = useTranslation()\n\tconst locale = intlLocale(i18n.language)\n\tconst { id } = useDocumentInfo()\n\tconst { config } = useConfig()\n\tconst documentEndpoint = apiPath(config, analyticsRoutes(config).document)\n\tconst seed: PanelSeed = props.seed ?? (initial ? 'fresh' : 'missing')\n\tconst initialSourceId = props.initialSourceId ?? adapterId\n\tconst initialReport = props.initialReport ?? modes[0] ?? 'page'\n\t// `pending` is what the picker shows; the caption and every formatter follow the window the\n\t// numbers on screen were read for, which only changes when that read lands.\n\tconst [pending, setPending] = useState<TimeframePreset>(initialTimeframe)\n\tconst [sourceId, setSourceId] = useState<string | undefined>(initialSourceId)\n\tconst [report, setReport] = useState<ReportMode>(initialReport)\n\n\tconst read: PanelRead = { preset: pending, source: sourceId, mode: report }\n\tconst documentId = id === undefined || id === null ? null : String(id)\n\t// Mounting means the tab is open, so an unvouched seed is read now, never in the document's\n\t// render. Another source or report restarts from the shimmer; another window dims old numbers.\n\tconst request = useRequest<PanelView>({\n\t\tkey: documentId === null ? null : readKey(read),\n\t\tkeep: `${sourceId ?? ''}|${report}`,\n\t\t...(initial === undefined || seed === 'missing'\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tseed: {\n\t\t\t\t\t\tkey: readKey({\n\t\t\t\t\t\t\tpreset: initialTimeframe,\n\t\t\t\t\t\t\tsource: initialSourceId,\n\t\t\t\t\t\t\tmode: initialReport,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tdata: { timeframe: initialTimeframe, data: initial, readAt: props.renderedAt },\n\t\t\t\t\t\tstale: seed === 'stale',\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\trun: async ({ signal, revalidating }) => {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tcollection: collectionSlug,\n\t\t\t\tid: documentId ?? '',\n\t\t\t\ttimeframe: read.preset,\n\t\t\t\tcompare: '1',\n\t\t\t\tseries: '1',\n\t\t\t\treport: read.mode,\n\t\t\t})\n\t\t\t// An item report reads the item's own metrics and lists, which the endpoint knows.\n\t\t\tif (read.mode === 'page') {\n\t\t\t\tparams.set('metrics', metrics.join(','))\n\t\t\t\tconst optional = optionalMetrics?.join(',') ?? ''\n\t\t\t\tif (optional !== '') {\n\t\t\t\t\tparams.set('optional', optional)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst lists = listsFor(read.mode, dimensions).join(',')\n\t\t\tif (lists !== '') {\n\t\t\t\tparams.set('dimensions', lists)\n\t\t\t}\n\t\t\tif (read.source) {\n\t\t\t\tparams.set('dataSource', read.source)\n\t\t\t}\n\t\t\t// A stale seed is read past its expired cache entry, straight from its source.\n\t\t\tif (revalidating) {\n\t\t\t\tparams.set('fresh', '1')\n\t\t\t}\n\t\t\tconst data = await requestShaped(`${documentEndpoint}?${params}`, isPanelData, { signal })\n\t\t\treturn { timeframe: read.preset, data, readAt: viewerNow().toISOString() }\n\t\t},\n\t})\n\tconst retriable = documentId !== null && request.status === 'error'\n\n\tconst onTimeframeChange = (preset: TimeframePreset) => {\n\t\t// Re-picking the window already selected is a retry after a failed read, the one way back\n\t\t// from the unavailable state without touching the picker twice.\n\t\tif (preset === pending) {\n\t\t\trequest.refetch()\n\t\t\treturn\n\t\t}\n\t\tsetPending(preset)\n\t}\n\n\tconst onReportChange = (next: ReportMode) => {\n\t\tsetReport(next)\n\t\tsetSourceId(sourceFor(next, sourceId, sources))\n\t}\n\n\tconst shownView = (): Omit<PanelView, 'data'> & { data: PanelData | undefined } => {\n\t\t// Nothing to read for a document that has no id: the seed stands, or the panel says so.\n\t\tif (documentId === null) {\n\t\t\treturn {\n\t\t\t\ttimeframe: initialTimeframe,\n\t\t\t\tdata: initial ?? { ...NOTHING_YET, status: 'unavailable' },\n\t\t\t\treadAt: props.renderedAt,\n\t\t\t}\n\t\t}\n\t\tconst timeframe = request.data?.timeframe ?? pending\n\t\tconst readAt = request.data?.readAt ?? props.renderedAt\n\t\tif (!retriable) {\n\t\t\treturn { timeframe, data: request.data?.data, readAt }\n\t\t}\n\t\treturn {\n\t\t\ttimeframe,\n\t\t\tdata: {\n\t\t\t\t...(request.data?.data ?? NOTHING_YET),\n\t\t\t\t...failedState(request.error),\n\t\t\t\t...(report === 'item' ? { report: 'item' } : {}),\n\t\t\t},\n\t\t\treadAt,\n\t\t}\n\t}\n\tconst view = shownView()\n\tconst loading = request.isRefetching\n\tconst waiting = view.data === undefined\n\tconst data = view.data ?? NOTHING_YET\n\tconst itemData = data.report === 'item'\n\tconst offered = sources.filter((source) => report === 'page' || source.perItemQuery === true)\n\tconst retryButton =\n\t\tdocumentId === null ? null : (\n\t\t\t<Button buttonStyle=\"secondary\" margin={false} onClick={() => request.refetch()} size=\"small\">\n\t\t\t\t{t(keys.viewRetry)}\n\t\t\t</Button>\n\t\t)\n\n\tconst body = (): ReactNode => {\n\t\tif (waiting) {\n\t\t\treturn (\n\t\t\t\t<PanelSkeleton\n\t\t\t\t\tcards={report === 'item' ? ITEM_SKELETON_CARDS : metrics.length}\n\t\t\t\t\tlists={listsFor(report, dimensions).length}\n\t\t\t\t/>\n\t\t\t)\n\t\t}\n\t\tif (isNewDocumentAnalytics(data, props.createdAt)) {\n\t\t\treturn (\n\t\t\t\t<div className=\"analytics-panel__empty\">\n\t\t\t\t\t<AnalyticsEmptyState isNew>{t(keys.stateNew)}</AnalyticsEmptyState>\n\t\t\t\t\t<span>{t(itemData ? keys.panelNewItem : keys.panelNewPage)}</span>\n\t\t\t\t</div>\n\t\t\t)\n\t\t}\n\t\tif (data.status !== 'ok' && FAILED.has(data.status)) {\n\t\t\tconst retry = retryOfferFor(data.status, data.retryAfterMs, { t, locale })\n\t\t\treturn (\n\t\t\t\t<div className=\"analytics-panel__state\">\n\t\t\t\t\t<Banner type=\"error\">{t(FIELD_STATE_KEYS[data.status])}</Banner>\n\t\t\t\t\t{retry?.after ? <span className=\"analytics-panel__caption\">{retry.after}</span> : null}\n\t\t\t\t\t{retry ? retryButton : null}\n\t\t\t\t</div>\n\t\t\t)\n\t\t}\n\t\tif (data.status !== 'ok') {\n\t\t\treturn (\n\t\t\t\t<AnalyticsEmptyState isNew={false}>{t(FIELD_STATE_KEYS[data.status])}</AnalyticsEmptyState>\n\t\t\t)\n\t\t}\n\t\treturn (\n\t\t\t<PanelContent\n\t\t\t\tcountryFlags={countryFlags}\n\t\t\t\tcurrency={props.currency}\n\t\t\t\tdata={data}\n\t\t\t\titemLabelOverrides={props.itemLabelOverrides}\n\t\t\t\tlabels={props.labels}\n\t\t\t\treadAt={view.readAt}\n\t\t\t\tretryButton={retryButton}\n\t\t\t\ttimeframe={view.timeframe}\n\t\t\t/>\n\t\t)\n\t}\n\n\t// The toolbar is the analytics view's in miniature: the controls on the left in the view's\n\t// order, the live indicator pushed right, and everything free to wrap on a narrow sidebar.\n\treturn (\n\t\t<div className=\"field-type analytics-panel\">\n\t\t\t<div className=\"analytics-panel__toolbar\">\n\t\t\t\t<div className=\"analytics-panel__controls\">\n\t\t\t\t\t{modes.length > 1 ? (\n\t\t\t\t\t\t<div className=\"analytics-panel__control\">\n\t\t\t\t\t\t\t<LabeledSelect\n\t\t\t\t\t\t\t\tlabel={t(keys.panelReportLabel)}\n\t\t\t\t\t\t\t\tonChange={(next) => {\n\t\t\t\t\t\t\t\t\tif (next !== report) {\n\t\t\t\t\t\t\t\t\t\tonReportChange(next)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\toptions={modes.map((mode) => ({ value: mode, label: t(REPORT_LABELS[mode]) }))}\n\t\t\t\t\t\t\t\tvalue={report}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : null}\n\t\t\t\t\t{offered.length > 1 ? (\n\t\t\t\t\t\t<div className=\"analytics-panel__control\">\n\t\t\t\t\t\t\t<LabeledSelect\n\t\t\t\t\t\t\t\tlabel={t(keys.viewSourceLabel)}\n\t\t\t\t\t\t\t\tonChange={(next) => {\n\t\t\t\t\t\t\t\t\tif (next !== sourceId) {\n\t\t\t\t\t\t\t\t\t\tsetSourceId(next)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\toptions={offered.map((s) => ({ value: s.id, label: s.label }))}\n\t\t\t\t\t\t\t\tvalue={sourceId}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : null}\n\t\t\t\t\t<div className=\"analytics-panel__control\">\n\t\t\t\t\t\t<LabeledSelect\n\t\t\t\t\t\t\tlabel={t(keys.widgetFieldRange)}\n\t\t\t\t\t\t\tonChange={(preset) => {\n\t\t\t\t\t\t\t\tif (preset !== pending || retriable) {\n\t\t\t\t\t\t\t\t\tonTimeframeChange(preset)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\toptions={TIMEFRAME_PRESETS.map((preset) => ({\n\t\t\t\t\t\t\t\tvalue: preset,\n\t\t\t\t\t\t\t\tlabel: t(TIMEFRAME_KEYS[preset]),\n\t\t\t\t\t\t\t}))}\n\t\t\t\t\t\t\tvalue={pending}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t{liveVisitors && !itemData && data.realtime && documentId !== null ? (\n\t\t\t\t\t<PanelLiveCounter\n\t\t\t\t\t\tcollectionSlug={collectionSlug}\n\t\t\t\t\t\t{...(sourceId ? { dataSource: sourceId } : {})}\n\t\t\t\t\t\tdocumentId={documentId}\n\t\t\t\t\t/>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t\t<div\n\t\t\t\taria-busy={loading || waiting}\n\t\t\t\tclassName={\n\t\t\t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,EAAE,KAAK,gBAAgB;OAC9B,WAAW,WAAW;QACrB,IAAI,WAAW,WAAW,WACzB,kBAAkB,MAAM;OAE1B;OACA,SAAS,kBAAkB,KAAK,YAAY;QAC3C,OAAO;QACP,OAAO,EAAE,eAAe,OAAO;OAChC,EAAE;OACF,OAAO;MACP,CAAA;KACG,CAAA;IACD;OACJ,gBAAgB,CAAC,YAAY,KAAK,YAAY,eAAe,OAC7D,oBAAC,kBAAD;IACiB;IAChB,GAAK,WAAW,EAAE,YAAY,SAAS,IAAI,CAAC;IAChC;GACZ,CAAA,IACE,IACA;MACL,oBAAC,OAAD;GACC,aAAW,WAAW;GACtB,WACC,WAAW,CAAC,UACT,wDACA;aAGH,KAAK;EACF,CAAA,CACD;;AAEP"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DimensionKey, MetricKey } from "../core/contract.js";
|
|
2
|
-
import { TimeframePreset } from "../timeframe/presets.js";
|
|
3
2
|
import { BindingDoc } from "../binding/types.js";
|
|
3
|
+
import { TimeframePreset } from "../timeframe/presets.js";
|
|
4
4
|
import { ReportOption } from "../binding/report.js";
|
|
5
5
|
import { AnalyticsMetricLabels } from "./factories.js";
|
|
6
6
|
import { StatFieldI18n } from "./AnalyticsStatField.js";
|
|
@@ -47,7 +47,8 @@ const toPanelData = (result) => ({
|
|
|
47
47
|
seriesGranularity: result.seriesGranularity,
|
|
48
48
|
realtime: result.realtime,
|
|
49
49
|
breakdowns: result.breakdowns,
|
|
50
|
-
notices: result.notices
|
|
50
|
+
notices: result.notices,
|
|
51
|
+
...result.substitutedFrom === void 0 ? {} : { substitutedFrom: result.substitutedFrom }
|
|
51
52
|
});
|
|
52
53
|
/**
|
|
53
54
|
* Without the totals there is nothing worth showing first; with them, a list nobody has read yet
|
|
@@ -103,6 +104,7 @@ const PanelFieldBody = async (props) => {
|
|
|
103
104
|
...readOptional ? { optionalMetrics: readOptional } : {},
|
|
104
105
|
timeframe,
|
|
105
106
|
adapterId,
|
|
107
|
+
fallbackWhenUnreadable: true,
|
|
106
108
|
...dimensions.length > 0 ? { dimensions: item ? ITEM_PANEL_DIMENSIONS : dimensions } : {},
|
|
107
109
|
now: renderedAt,
|
|
108
110
|
compare: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnalyticsPanelField.js","names":[],"sources":["../../src/fields/AnalyticsPanelField.tsx"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { Suspense } from 'react'\nimport { type ReportOption, reportModes } from '../binding/report'\nimport type { BindingDoc } from '../binding/types'\nimport { currentDate } from '../core/clock'\nimport type { DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { type DocumentScope, resolveDocumentScope } from '../plugin/documentScopes'\nimport { type RequestSource, resolveSourcesForRequest } from '../plugin/readContextForRequest'\nimport { getRuntime, requestCurrency } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { WithScopeToken } from '../ui/data/WithScopeToken'\nimport type { CountryFlags } from '../view/CountryFlag'\nimport { hostCountryFlag } from '../view/hostCountryFlag'\nimport { AnalyticsPanelClient, type PanelData, type PanelSeed } from './AnalyticsPanelClient'\nimport { resolveMetricLabel, type StatFieldI18n } from './AnalyticsStatField'\nimport { createdAtOf } from './emptyState'\nimport { FieldShimmer } from './FieldShimmer'\nimport type { AnalyticsMetricLabels } from './factories'\nimport {\n\tITEM_PANEL_DIMENSIONS,\n\tITEM_PANEL_METRICS,\n\tITEM_PANEL_OPTIONAL_METRICS,\n} from './itemReport'\nimport { type FieldPeek, type FieldReadResult, peekForField } from './readForDocument'\n\n/** @internal */\nexport interface AnalyticsPanelFieldProps {\n\treq: PayloadRequest\n\tdata: BindingDoc\n\tcollectionSlug: string\n\ti18n: StatFieldI18n\n\tmetrics: MetricKey[]\n\t/** Metrics the factory added speculatively; a source serving none of them warns nobody. */\n\toptionalMetrics?: MetricKey[]\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tlabels?: AnalyticsMetricLabels\n\t/** Dimensions ranked for this page, empty when the factory turned the breakdowns off. */\n\tdimensions?: DimensionKey[]\n\t/** Draw the live counter where the source counts live visitors. */\n\tliveVisitors?: boolean\n\t/** Sources the switcher offers: `'auto'` is the document scope's own, a list narrows it. */\n\tsources?: 'auto' | string[]\n\t/** What the panel reports on; `auto` follows the binding, the item first. */\n\treport?: ReportOption\n}\n\n/**\n * Server entry for the document panel. Payload renders every field as a document loads (hidden\n * tabs too), so this never waits on a source: the seed is a budgeted {@link peekForField}.\n *\n * @internal\n */\nexport const AnalyticsPanelField = (props: AnalyticsPanelFieldProps) => (\n\t<Suspense fallback={<FieldShimmer height=\"15rem\" />}>\n\t\t<WithScopeToken req={props.req}>\n\t\t\t<PanelFieldBody {...props} />\n\t\t</WithScopeToken>\n\t</Suspense>\n)\n\nconst isoRange = (range: DateRange): { start: string; end: string } => ({\n\tstart: range.start.toISOString(),\n\tend: range.end.toISOString(),\n})\n\n/** The panel's first answer as the client takes it, dates as ISO strings. */\nconst toPanelData = (result: FieldReadResult): PanelData => ({\n\tstatus: result.status,\n\t...(result.report === undefined ? {} : { report: result.report }),\n\tmetrics: result.metrics,\n\tsupportedMetrics: result.supportedMetrics,\n\tpreviousMetrics: result.previousMetrics,\n\ttimezone: result.timezone,\n\tdateRange: isoRange(result.dateRange),\n\tcomparisonRange: result.comparisonRange ? isoRange(result.comparisonRange) : undefined,\n\tpoints: result.points,\n\tseriesGranularity: result.seriesGranularity,\n\trealtime: result.realtime,\n\tbreakdowns: result.breakdowns,\n\tnotices: result.notices,\n})\n\n/**\n * Without the totals there is nothing worth showing first; with them, a list nobody has read yet\n * is filled in by the client's read like a stale answer is.\n */\nconst seedOf = ({ complete, stale, result }: FieldPeek): PanelSeed => {\n\tif (complete && !stale) {\n\t\treturn 'fresh'\n\t}\n\treturn result.status === 'ok' ? 'stale' : 'missing'\n}\n\n/**\n * Only the card labels the developer set, as plain strings: the panel names every other card\n * itself, once its read says how the numbers were counted.\n */\nconst labelOverrides = (\n\tlabels: AnalyticsMetricLabels | undefined,\n\tmetrics: MetricKey[],\n\ti18n: StatFieldI18n\n): Partial<Record<MetricKey, string>> => {\n\tconst t = asTranslate(i18n.t)\n\tconst resolved: Partial<Record<MetricKey, string>> = {}\n\tfor (const metric of metrics) {\n\t\tconst override = labels?.[metric]\n\t\tif (override !== undefined) {\n\t\t\tresolved[metric] = resolveMetricLabel(override, i18n, () => t(METRIC_KEYS[metric]))\n\t\t}\n\t}\n\treturn resolved\n}\n\nconst PanelFieldBody = async (props: AnalyticsPanelFieldProps) => {\n\tconst { req, data, collectionSlug, i18n, metrics, timeframe, adapterId, labels } = props\n\tconst dimensions = props.dimensions ?? []\n\tconst renderedAt = currentDate()\n\tconst currency = await requestCurrency(req)\n\tconst runtime = getRuntime(req.payload)\n\tconst flags = runtime?.countryFlags ?? true\n\t// The host's flag is looked up once here, for the client rows to render.\n\tconst countryFlags: CountryFlags =\n\t\ttypeof flags === 'object'\n\t\t\t? (hostCountryFlag(flags, req.payload.importMap, (message) =>\n\t\t\t\t\treq.payload.logger.warn(message)\n\t\t\t\t) ?? false)\n\t\t\t: flags\n\tconst modes = reportModes(runtime?.bindings[collectionSlug], props.report ?? 'auto')\n\tconst report = modes[0] ?? 'page'\n\tconst item = report === 'item'\n\tconst readOptional = item ? ITEM_PANEL_OPTIONAL_METRICS : props.optionalMetrics\n\t// The switcher lists the document scope's own sources, so that scope is gated first: a refusal\n\t// lists none, and the read says no-access.\n\tconst documentScope: DocumentScope = runtime\n\t\t? await resolveDocumentScope({ runtime, req, collection: collectionSlug, data })\n\t\t: { ok: true, scope: null }\n\tconst listSources = async (): Promise<RequestSource[]> => {\n\t\tif (!documentScope.ok) {\n\t\t\treturn []\n\t\t}\n\t\tconst listing = await resolveSourcesForRequest(\n\t\t\treq,\n\t\t\tdocumentScope.scope === null ? {} : { scope: documentScope.gated }\n\t\t)\n\t\treturn listing.sources\n\t}\n\tconst [peeked, sources] = await Promise.all([\n\t\tpeekForField({\n\t\t\treq,\n\t\t\tcollectionSlug,\n\t\t\tdata,\n\t\t\tmetrics: item ? ITEM_PANEL_METRICS : metrics,\n\t\t\t...(readOptional ? { optionalMetrics: readOptional } : {}),\n\t\t\ttimeframe,\n\t\t\tadapterId,\n\t\t\t...(dimensions.length > 0 ? { dimensions: item ? ITEM_PANEL_DIMENSIONS : dimensions } : {}),\n\t\t\tnow: renderedAt,\n\t\t\tcompare: true,\n\t\t\tseries: true,\n\t\t\treport,\n\t\t}),\n\t\tlistSources(),\n\t])\n\tconst offered = sources\n\t\t.filter(\n\t\t\t(source) =>\n\t\t\t\tprops.sources === undefined || props.sources === 'auto' || props.sources.includes(source.id)\n\t\t)\n\t\t.map((source) => ({\n\t\t\tid: source.id,\n\t\t\tlabel: source.label,\n\t\t\tperItemQuery: source.capabilities.perItemQuery === true,\n\t\t}))\n\n\tconst result = peeked.result\n\tconst createdAt = createdAtOf(data)\n\tconst seed = seedOf(peeked)\n\n\treturn (\n\t\t<AnalyticsPanelClient\n\t\t\tcollectionSlug={collectionSlug}\n\t\t\tcountryFlags={countryFlags}\n\t\t\tdimensions={dimensions}\n\t\t\tliveVisitors={props.liveVisitors !== false}\n\t\t\tmetrics={metrics}\n\t\t\tsources={offered}\n\t\t\tinitialSourceId={adapterId ?? result.adapterId}\n\t\t\t{...(props.optionalMetrics ? { optionalMetrics: props.optionalMetrics } : {})}\n\t\t\t{...(seed === 'missing' ? {} : { initial: toPanelData(result) })}\n\t\t\trenderedAt={renderedAt.toISOString()}\n\t\t\tseed={seed}\n\t\t\tinitialReport={report}\n\t\t\tinitialTimeframe={timeframe}\n\t\t\tadapterId={adapterId}\n\t\t\titemLabelOverrides={labelOverrides(labels, ITEM_PANEL_METRICS, i18n)}\n\t\t\tlabels={labelOverrides(labels, metrics, i18n)}\n\t\t\tmodes={modes}\n\t\t\t{...(currency ? { currency } : {})}\n\t\t\t{...(createdAt === undefined ? {} : { createdAt })}\n\t\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,aAAa,iBAAiB;CACpD,EAAE;CAEH,MAAM,SAAS,OAAO;CACtB,MAAM,YAAY,YAAY,IAAI;CAClC,MAAM,OAAO,OAAO,MAAM;CAE1B,OACC,oBAAC,sBAAD;EACiB;EACF;EACF;EACZ,cAAc,MAAM,iBAAiB;EAC5B;EACT,SAAS;EACT,iBAAiB,aAAa,OAAO;EACrC,GAAK,MAAM,kBAAkB,EAAE,iBAAiB,MAAM,gBAAgB,IAAI,CAAC;EAC3E,GAAK,SAAS,YAAY,CAAC,IAAI,EAAE,SAAS,YAAY,MAAM,EAAE;EAC9D,YAAY,WAAW,YAAY;EAC7B;EACN,eAAe;EACf,kBAAkB;EACP;EACX,oBAAoB,eAAe,QAAQ,oBAAoB,IAAI;EACnE,QAAQ,eAAe,QAAQ,SAAS,IAAI;EACrC;EACP,GAAK,WAAW,EAAE,SAAS,IAAI,CAAC;EAChC,GAAK,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CAChD,CAAA;AAEH"}
|
|
1
|
+
{"version":3,"file":"AnalyticsPanelField.js","names":[],"sources":["../../src/fields/AnalyticsPanelField.tsx"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { Suspense } from 'react'\nimport { type ReportOption, reportModes } from '../binding/report'\nimport type { BindingDoc } from '../binding/types'\nimport { currentDate } from '../core/clock'\nimport type { DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { type DocumentScope, resolveDocumentScope } from '../plugin/documentScopes'\nimport { type RequestSource, resolveSourcesForRequest } from '../plugin/readContextForRequest'\nimport { getRuntime, requestCurrency } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { WithScopeToken } from '../ui/data/WithScopeToken'\nimport type { CountryFlags } from '../view/CountryFlag'\nimport { hostCountryFlag } from '../view/hostCountryFlag'\nimport { AnalyticsPanelClient, type PanelData, type PanelSeed } from './AnalyticsPanelClient'\nimport { resolveMetricLabel, type StatFieldI18n } from './AnalyticsStatField'\nimport { createdAtOf } from './emptyState'\nimport { FieldShimmer } from './FieldShimmer'\nimport type { AnalyticsMetricLabels } from './factories'\nimport {\n\tITEM_PANEL_DIMENSIONS,\n\tITEM_PANEL_METRICS,\n\tITEM_PANEL_OPTIONAL_METRICS,\n} from './itemReport'\nimport { type FieldPeek, type FieldReadResult, peekForField } from './readForDocument'\n\n/** @internal */\nexport interface AnalyticsPanelFieldProps {\n\treq: PayloadRequest\n\tdata: BindingDoc\n\tcollectionSlug: string\n\ti18n: StatFieldI18n\n\tmetrics: MetricKey[]\n\t/** Metrics the factory added speculatively; a source serving none of them warns nobody. */\n\toptionalMetrics?: MetricKey[]\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tlabels?: AnalyticsMetricLabels\n\t/** Dimensions ranked for this page, empty when the factory turned the breakdowns off. */\n\tdimensions?: DimensionKey[]\n\t/** Draw the live counter where the source counts live visitors. */\n\tliveVisitors?: boolean\n\t/** Sources the switcher offers: `'auto'` is the document scope's own, a list narrows it. */\n\tsources?: 'auto' | string[]\n\t/** What the panel reports on; `auto` follows the binding, the item first. */\n\treport?: ReportOption\n}\n\n/**\n * Server entry for the document panel. Payload renders every field as a document loads (hidden\n * tabs too), so this never waits on a source: the seed is a budgeted {@link peekForField}.\n *\n * @internal\n */\nexport const AnalyticsPanelField = (props: AnalyticsPanelFieldProps) => (\n\t<Suspense fallback={<FieldShimmer height=\"15rem\" />}>\n\t\t<WithScopeToken req={props.req}>\n\t\t\t<PanelFieldBody {...props} />\n\t\t</WithScopeToken>\n\t</Suspense>\n)\n\nconst isoRange = (range: DateRange): { start: string; end: string } => ({\n\tstart: range.start.toISOString(),\n\tend: range.end.toISOString(),\n})\n\n/** The panel's first answer as the client takes it, dates as ISO strings. */\nconst toPanelData = (result: FieldReadResult): PanelData => ({\n\tstatus: result.status,\n\t...(result.report === undefined ? {} : { report: result.report }),\n\tmetrics: result.metrics,\n\tsupportedMetrics: result.supportedMetrics,\n\tpreviousMetrics: result.previousMetrics,\n\ttimezone: result.timezone,\n\tdateRange: isoRange(result.dateRange),\n\tcomparisonRange: result.comparisonRange ? isoRange(result.comparisonRange) : undefined,\n\tpoints: result.points,\n\tseriesGranularity: result.seriesGranularity,\n\trealtime: result.realtime,\n\tbreakdowns: result.breakdowns,\n\tnotices: result.notices,\n\t...(result.substitutedFrom === undefined ? {} : { substitutedFrom: result.substitutedFrom }),\n})\n\n/**\n * Without the totals there is nothing worth showing first; with them, a list nobody has read yet\n * is filled in by the client's read like a stale answer is.\n */\nconst seedOf = ({ complete, stale, result }: FieldPeek): PanelSeed => {\n\tif (complete && !stale) {\n\t\treturn 'fresh'\n\t}\n\treturn result.status === 'ok' ? 'stale' : 'missing'\n}\n\n/**\n * Only the card labels the developer set, as plain strings: the panel names every other card\n * itself, once its read says how the numbers were counted.\n */\nconst labelOverrides = (\n\tlabels: AnalyticsMetricLabels | undefined,\n\tmetrics: MetricKey[],\n\ti18n: StatFieldI18n\n): Partial<Record<MetricKey, string>> => {\n\tconst t = asTranslate(i18n.t)\n\tconst resolved: Partial<Record<MetricKey, string>> = {}\n\tfor (const metric of metrics) {\n\t\tconst override = labels?.[metric]\n\t\tif (override !== undefined) {\n\t\t\tresolved[metric] = resolveMetricLabel(override, i18n, () => t(METRIC_KEYS[metric]))\n\t\t}\n\t}\n\treturn resolved\n}\n\nconst PanelFieldBody = async (props: AnalyticsPanelFieldProps) => {\n\tconst { req, data, collectionSlug, i18n, metrics, timeframe, adapterId, labels } = props\n\tconst dimensions = props.dimensions ?? []\n\tconst renderedAt = currentDate()\n\tconst currency = await requestCurrency(req)\n\tconst runtime = getRuntime(req.payload)\n\tconst flags = runtime?.countryFlags ?? true\n\t// The host's flag is looked up once here, for the client rows to render.\n\tconst countryFlags: CountryFlags =\n\t\ttypeof flags === 'object'\n\t\t\t? (hostCountryFlag(flags, req.payload.importMap, (message) =>\n\t\t\t\t\treq.payload.logger.warn(message)\n\t\t\t\t) ?? false)\n\t\t\t: flags\n\tconst modes = reportModes(runtime?.bindings[collectionSlug], props.report ?? 'auto')\n\tconst report = modes[0] ?? 'page'\n\tconst item = report === 'item'\n\tconst readOptional = item ? ITEM_PANEL_OPTIONAL_METRICS : props.optionalMetrics\n\t// The switcher lists the document scope's own sources, so that scope is gated first: a refusal\n\t// lists none, and the read says no-access.\n\tconst documentScope: DocumentScope = runtime\n\t\t? await resolveDocumentScope({ runtime, req, collection: collectionSlug, data })\n\t\t: { ok: true, scope: null }\n\tconst listSources = async (): Promise<RequestSource[]> => {\n\t\tif (!documentScope.ok) {\n\t\t\treturn []\n\t\t}\n\t\tconst listing = await resolveSourcesForRequest(\n\t\t\treq,\n\t\t\tdocumentScope.scope === null ? {} : { scope: documentScope.gated }\n\t\t)\n\t\treturn listing.sources\n\t}\n\tconst [peeked, sources] = await Promise.all([\n\t\tpeekForField({\n\t\t\treq,\n\t\t\tcollectionSlug,\n\t\t\tdata,\n\t\t\tmetrics: item ? ITEM_PANEL_METRICS : metrics,\n\t\t\t...(readOptional ? { optionalMetrics: readOptional } : {}),\n\t\t\ttimeframe,\n\t\t\tadapterId,\n\t\t\tfallbackWhenUnreadable: true,\n\t\t\t...(dimensions.length > 0 ? { dimensions: item ? ITEM_PANEL_DIMENSIONS : dimensions } : {}),\n\t\t\tnow: renderedAt,\n\t\t\tcompare: true,\n\t\t\tseries: true,\n\t\t\treport,\n\t\t}),\n\t\tlistSources(),\n\t])\n\tconst offered = sources\n\t\t.filter(\n\t\t\t(source) =>\n\t\t\t\tprops.sources === undefined || props.sources === 'auto' || props.sources.includes(source.id)\n\t\t)\n\t\t.map((source) => ({\n\t\t\tid: source.id,\n\t\t\tlabel: source.label,\n\t\t\tperItemQuery: source.capabilities.perItemQuery === true,\n\t\t}))\n\n\tconst result = peeked.result\n\tconst createdAt = createdAtOf(data)\n\tconst seed = seedOf(peeked)\n\n\treturn (\n\t\t<AnalyticsPanelClient\n\t\t\tcollectionSlug={collectionSlug}\n\t\t\tcountryFlags={countryFlags}\n\t\t\tdimensions={dimensions}\n\t\t\tliveVisitors={props.liveVisitors !== false}\n\t\t\tmetrics={metrics}\n\t\t\tsources={offered}\n\t\t\tinitialSourceId={adapterId ?? result.adapterId}\n\t\t\t{...(props.optionalMetrics ? { optionalMetrics: props.optionalMetrics } : {})}\n\t\t\t{...(seed === 'missing' ? {} : { initial: toPanelData(result) })}\n\t\t\trenderedAt={renderedAt.toISOString()}\n\t\t\tseed={seed}\n\t\t\tinitialReport={report}\n\t\t\tinitialTimeframe={timeframe}\n\t\t\tadapterId={adapterId}\n\t\t\titemLabelOverrides={labelOverrides(labels, ITEM_PANEL_METRICS, i18n)}\n\t\t\tlabels={labelOverrides(labels, metrics, i18n)}\n\t\t\tmodes={modes}\n\t\t\t{...(currency ? { currency } : {})}\n\t\t\t{...(createdAt === undefined ? {} : { createdAt })}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAa,uBAAuB,UACnC,oBAAC,UAAD;CAAU,UAAU,oBAAC,cAAD,EAAc,QAAO,QAAS,CAAA;WACjD,oBAAC,gBAAD;EAAgB,KAAK,MAAM;YAC1B,oBAAC,gBAAD,EAAgB,GAAI,MAAQ,CAAA;CACb,CAAA;AACP,CAAA;AAGX,MAAM,YAAY,WAAsD;CACvE,OAAO,MAAM,MAAM,YAAY;CAC/B,KAAK,MAAM,IAAI,YAAY;AAC5B;;AAGA,MAAM,eAAe,YAAwC;CAC5D,QAAQ,OAAO;CACf,GAAI,OAAO,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,OAAO,OAAO;CAC/D,SAAS,OAAO;CAChB,kBAAkB,OAAO;CACzB,iBAAiB,OAAO;CACxB,UAAU,OAAO;CACjB,WAAW,SAAS,OAAO,SAAS;CACpC,iBAAiB,OAAO,kBAAkB,SAAS,OAAO,eAAe,IAAI,KAAA;CAC7E,QAAQ,OAAO;CACf,mBAAmB,OAAO;CAC1B,UAAU,O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E,UAAU;CAChD,CAAA;AAEH"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MetricKey } from "../core/contract.js";
|
|
2
|
-
import { TimeframePreset } from "../timeframe/presets.js";
|
|
3
2
|
import { BindingDoc } from "../binding/types.js";
|
|
3
|
+
import { TimeframePreset } from "../timeframe/presets.js";
|
|
4
4
|
import { ReportOption } from "../binding/report.js";
|
|
5
5
|
import { FallbackLanguage } from "../translations/labelMap.js";
|
|
6
6
|
import { AnalyticsMetricLabels } from "./factories.js";
|
|
@@ -3,13 +3,13 @@ import { keys } from "../translations/keys.js";
|
|
|
3
3
|
import { METRIC_KEYS, TIMEFRAME_KEYS, metricLabelKey } from "../translations/metricKeys.js";
|
|
4
4
|
import { currentDate } from "../core/clock.js";
|
|
5
5
|
import { getRuntime, requestCurrency } from "../plugin/runtime.js";
|
|
6
|
+
import { pickLabel } from "../translations/labelMap.js";
|
|
6
7
|
import { asTranslate } from "../translations/server.js";
|
|
7
8
|
import { readingOf } from "../core/metricValues.js";
|
|
8
9
|
import { OVER_BUDGET, withinBudget } from "../core/budget.js";
|
|
9
10
|
import { ITEM_STAT_METRICS, itemMetricLabel } from "./itemReport.js";
|
|
10
11
|
import { intlLocale } from "../translations/intl.js";
|
|
11
12
|
import { readForField } from "./readForDocument.js";
|
|
12
|
-
import { pickLabel } from "../translations/labelMap.js";
|
|
13
13
|
import { formatMetricValue } from "./format.js";
|
|
14
14
|
import { MetricCard } from "../ui/components/MetricCard.js";
|
|
15
15
|
import { widgetNotice } from "../widgets/notices.js";
|
|
@@ -76,9 +76,11 @@ function PanelContent(props) {
|
|
|
76
76
|
const item = data.report === "item";
|
|
77
77
|
const currency = data.notices?.currency ?? props.currency;
|
|
78
78
|
const timeZone = data.timezone ?? "UTC";
|
|
79
|
+
const substituted = { substitutedFrom: data.substitutedFrom };
|
|
79
80
|
if (isEmptyDocumentRead(data)) {
|
|
80
81
|
const emptyNotice = widgetNotice({
|
|
81
82
|
...mergeNotices(data.notices),
|
|
83
|
+
...substituted,
|
|
82
84
|
mixedCurrencies: [],
|
|
83
85
|
capped: false
|
|
84
86
|
}, {
|
|
@@ -95,7 +97,10 @@ function PanelContent(props) {
|
|
|
95
97
|
}), noticeLine(emptyNotice)]
|
|
96
98
|
});
|
|
97
99
|
}
|
|
98
|
-
const notice = widgetNotice(
|
|
100
|
+
const notice = widgetNotice({
|
|
101
|
+
...mergeNotices(data.notices, ...data.breakdowns ?? []),
|
|
102
|
+
...substituted
|
|
103
|
+
}, {
|
|
99
104
|
t,
|
|
100
105
|
locale,
|
|
101
106
|
now: viewerNow(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PanelContent.js","names":[],"sources":["../../src/fields/PanelContent.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport { labelSeries, unitForTimeframe } from '../charts/bucket'\nimport { markInProgress } from '../charts/inProgress'\nimport { TrendChart } from '../charts/TrendChart'\nimport type { MetricKey, MetricValue } from '../core/contract'\nimport { readingOf } from '../core/metricValues'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { intlLocale } from '../translations/intl'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, metricLabelKey, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { MetricCard } from '../ui/components/MetricCard'\nimport { viewerNow } from '../ui/viewerClock'\nimport type { CountryFlags } from '../view/CountryFlag'\nimport { clickRate } from '../view/conversionRate'\nimport { ComparisonDelta } from '../widgets/ComparisonDelta'\nimport { widgetNotice } from '../widgets/notices'\nimport { mergeNotices } from '../widgets/readMeta'\nimport type { PanelData } from './AnalyticsPanelClient'\nimport { AnalyticsEmptyState, isEmptyDocumentRead } from './emptyState'\nimport { formatMetricValue, formatRate } from './format'\nimport { itemMetricLabel } from './itemReport'\nimport { PanelList } from './PanelList'\n\n/**\n * Item report cards in reading order. A rate is derived from the two counts beside it rather than\n * read, so it shows whenever both are there.\n */\ntype ItemCard =\n\t| { kind: 'metric'; metric: MetricKey }\n\t| { kind: 'rate'; id: string; of: MetricKey; over: MetricKey; label: TranslationKey }\n\nconst ITEM_CARDS: ItemCard[] = [\n\t{ kind: 'metric', metric: 'impressions' },\n\t{ kind: 'metric', metric: 'visitors' },\n\t{ kind: 'metric', metric: 'interactions' },\n\t{\n\t\tkind: 'rate',\n\t\tid: 'click-rate',\n\t\tof: 'interactions',\n\t\tover: 'impressions',\n\t\tlabel: keys.metricClickRate,\n\t},\n\t{ kind: 'metric', metric: 'conversions' },\n\t{\n\t\tkind: 'rate',\n\t\tid: 'conversion-rate',\n\t\tof: 'conversions',\n\t\tover: 'impressions',\n\t\tlabel: keys.viewConversionRate,\n\t},\n\t{ kind: 'metric', metric: 'revenue' },\n]\n\n/** Lists the panel lays out under its trend; no read it makes ranks more. */\nconst MAX_PANEL_LISTS = 3\n\n/** Height the trend keeps in the panel's narrow column. */\nconst TREND_MIN_HEIGHT = 140\n\n/** \"Updated 3 minutes ago\" is worded against the clock of whichever side renders. */\nconst noticeLine = (text: string) =>\n\ttext === '' ? null : (\n\t\t<span className=\"analytics-panel__notice\" suppressHydrationWarning>\n\t\t\t{text}\n\t\t</span>\n\t)\n\ninterface ShownCard {\n\tid: string\n\tlabel: string\n\tdisplay: string\n\tcurrent: MetricValue\n\tprevious: MetricValue | undefined\n\tmetric?: MetricKey\n}\n\ninterface PanelContentProps {\n\tdata: PanelData\n\t/** The window the numbers were read for, which the caption, chart and formatters follow. */\n\ttimeframe: TimeframePreset\n\t/** When the numbers were read, which decides the bucket that is still counting. */\n\treadAt: string\n\t/** Page card labels the developer set, resolved to plain strings. */\n\tlabels: Partial<Record<MetricKey, string>> | undefined\n\t/** Item card labels the developer set; other cards keep the item report's own names. */\n\titemLabelOverrides: Partial<Record<MetricKey, string>> | undefined\n\t/** ISO 4217 code revenue renders in when the read names none; absent leaves it a plain number. */\n\tcurrency: string | undefined\n\tcountryFlags: CountryFlags\n\t/** Offered beside the note that part of the read failed. */\n\tretryButton: ReactNode\n}\n\n/**\n * An answered read: its cards, trend, lists, caption and notices, or a line saying nothing was\n * counted in the window.\n */\nexport function PanelContent(props: PanelContentProps) {\n\tconst { data, timeframe, labels, countryFlags } = props\n\tconst { t, i18n } = useTranslation()\n\tconst locale = intlLocale(i18n.language)\n\tconst item = data.report === 'item'\n\tconst currency = data.notices?.currency ?? props.currency\n\t// One line for the whole panel: the cards, the trend and every list read the same days.\n\tconst timeZone = data.timezone ?? 'UTC'\n\n\tif (isEmptyDocumentRead(data)) {\n\t\t// No cards or lists, so no revenue sum or grouped row needs explaining.\n\t\tconst emptyNotice = widgetNotice(\n\t\t\t{ ...mergeNotices(data.notices), mixedCurrencies: [], capped: false },\n\t\t\t{ t, locale, now: viewerNow(), timeZone }\n\t\t)\n\t\treturn (\n\t\t\t<div className=\"analytics-panel__content\">\n\t\t\t\t<AnalyticsEmptyState isNew={false}>\n\t\t\t\t\t{t(item ? keys.panelNoViews : keys.panelNoVisits)}\n\t\t\t\t</AnalyticsEmptyState>\n\t\t\t\t{noticeLine(emptyNotice)}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst notice = widgetNotice(mergeNotices(data.notices, ...(data.breakdowns ?? [])), {\n\t\tt,\n\t\tlocale,\n\t\tnow: viewerNow(),\n\t\ttimeZone,\n\t})\n\tconst firstMetric = data.supportedMetrics[0]\n\t// An hourly chart needs hourly rows: a source that serves none has a single value for the\n\t// window, which the metric cards already show, and a one-point line to nowhere otherwise.\n\tconst chartable = unitForTimeframe(timeframe) !== 'hour' || data.seriesGranularity === 'hour'\n\t// Every offered window runs up to when it was read, so its last bucket is still counting.\n\tconst now = new Date(props.readAt)\n\tconst bucketed =\n\t\tchartable && data.points && data.points.length > 0 && firstMetric\n\t\t\t? markInProgress(\n\t\t\t\t\tlabelSeries(data.points, {\n\t\t\t\t\t\tgranularity: data.seriesGranularity ?? 'day',\n\t\t\t\t\t\ttz: data.timezone,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\tweekday: timeframe === 'last7days',\n\t\t\t\t\t\t...(data.dateRange ? { from: new Date(data.dateRange.start) } : {}),\n\t\t\t\t\t}).map((b) => ({\n\t\t\t\t\t\t...b,\n\t\t\t\t\t\tdisplay: formatMetricValue(firstMetric, b.value, { locale, currency }),\n\t\t\t\t\t})),\n\t\t\t\t\t{ now, end: now, soFar: (period) => t(keys.chartSoFar, { period }) }\n\t\t\t\t)\n\t\t\t: null\n\t// An average with no reading on any day has nothing to draw: the card above already says so.\n\tconst buckets = bucketed?.some((b) => b.value !== null) ? bucketed : null\n\tconst served = new Set(data.supportedMetrics)\n\n\tconst card = (shown: ShownCard) => (\n\t\t<MetricCard\n\t\t\tclassName=\"analytics-panel__card\"\n\t\t\tkey={shown.id}\n\t\t\tlabel={shown.label}\n\t\t\tnoValueLabel={t(keys.stateNoValue)}\n\t\t\tvalue={shown.display}\n\t\t>\n\t\t\t{data.comparisonRange ? (\n\t\t\t\t<ComparisonDelta\n\t\t\t\t\tcurrent={shown.current}\n\t\t\t\t\tprevious={shown.previous}\n\t\t\t\t\t{...(shown.metric === undefined ? {} : { metric: shown.metric })}\n\t\t\t\t\tlocale={locale}\n\t\t\t\t\tt={t}\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t</MetricCard>\n\t)\n\n\tconst metricCard = (metric: MetricKey, label: string) => {\n\t\tconst value = readingOf(data.metrics, metric)\n\t\treturn card({\n\t\t\tid: metric,\n\t\t\tlabel,\n\t\t\tdisplay: formatMetricValue(metric, value, { locale, currency }),\n\t\t\tcurrent: value,\n\t\t\tprevious: data.previousMetrics?.[metric],\n\t\t\tmetric,\n\t\t})\n\t}\n\n\tconst pageCards = () =>\n\t\tdata.supportedMetrics.map((metric) =>\n\t\t\tmetricCard(\n\t\t\t\tmetric,\n\t\t\t\tlabels?.[metric] ?? t(metricLabelKey(metric, data.notices?.visitorsSummed))\n\t\t\t)\n\t\t)\n\n\tconst itemCards = () =>\n\t\tITEM_CARDS.flatMap((spec) => {\n\t\t\tif (spec.kind === 'metric') {\n\t\t\t\tif (!served.has(spec.metric)) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst label =\n\t\t\t\t\tprops.itemLabelOverrides?.[spec.metric] ??\n\t\t\t\t\tt(itemMetricLabel(spec.metric, METRIC_KEYS[spec.metric]))\n\t\t\t\treturn [metricCard(spec.metric, label)]\n\t\t\t}\n\t\t\tif (!served.has(spec.of) || !served.has(spec.over)) {\n\t\t\t\treturn []\n\t\t\t}\n\t\t\tconst rate = clickRate(data.metrics[spec.of], data.metrics[spec.over])\n\t\t\tconst previous = data.previousMetrics\n\t\t\t\t? clickRate(data.previousMetrics[spec.of], data.previousMetrics[spec.over])\n\t\t\t\t: undefined\n\t\t\treturn [\n\t\t\t\tcard({\n\t\t\t\t\tid: spec.id,\n\t\t\t\t\tlabel: t(spec.label),\n\t\t\t\t\tdisplay: formatRate(rate, locale),\n\t\t\t\t\tcurrent: rate,\n\t\t\t\t\tprevious,\n\t\t\t\t}),\n\t\t\t]\n\t\t})\n\n\tconst charted = item ? keys.metricImpressions : firstMetric && METRIC_KEYS[firstMetric]\n\tconst trendLabel = charted\n\t\t? t(keys.chartLabel, { metric: t(charted), window: t(TIMEFRAME_KEYS[timeframe]) })\n\t\t: ''\n\tconst lists = data.breakdowns ?? []\n\n\treturn (\n\t\t<div className=\"analytics-panel__content\">\n\t\t\t<div className=\"analytics-panel__cards\">{item ? itemCards() : pageCards()}</div>\n\t\t\t{buckets && firstMetric ? (\n\t\t\t\t<TrendChart\n\t\t\t\t\tariaLabel={trendLabel}\n\t\t\t\t\tbuckets={buckets}\n\t\t\t\t\tkeyboardHint={t(keys.chartKeyboardHint)}\n\t\t\t\t\tnoValueLabel={t(keys.stateNoValue)}\n\t\t\t\t\tlabel={\n\t\t\t\t\t\titem\n\t\t\t\t\t\t\t? t(keys.metricImpressions)\n\t\t\t\t\t\t\t: (labels?.[firstMetric] ?? t(METRIC_KEYS[firstMetric]))\n\t\t\t\t\t}\n\t\t\t\t\tminHeight={TREND_MIN_HEIGHT}\n\t\t\t\t\tperiodLabel={t(keys.viewTrendPeriod)}\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t\t{lists.length > 0 ? (\n\t\t\t\t<div className=\"analytics-panel__lists\">\n\t\t\t\t\t{lists.slice(0, MAX_PANEL_LISTS).map((block) => (\n\t\t\t\t\t\t<PanelList\n\t\t\t\t\t\t\tblock={block}\n\t\t\t\t\t\t\tcountryFlags={countryFlags}\n\t\t\t\t\t\t\tcurrency={currency}\n\t\t\t\t\t\t\titem={item}\n\t\t\t\t\t\t\tkey={block.dimension}\n\t\t\t\t\t\t/>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t\t<span className=\"analytics-panel__caption\">{t(TIMEFRAME_KEYS[timeframe])}</span>\n\t\t\t{noticeLine(notice)}\n\t\t\t{data.incomplete ? (\n\t\t\t\t<div className=\"analytics-panel__state\">\n\t\t\t\t\t{noticeLine(t(keys.statePartsFailed))}\n\t\t\t\t\t{props.retryButton}\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,aAAyB;CAC9B;EAAE,MAAM;EAAU,QAAQ;CAAc;CACxC;EAAE,MAAM;EAAU,QAAQ;CAAW;CACrC;EAAE,MAAM;EAAU,QAAQ;CAAe;CACzC;EACC,MAAM;EACN,IAAI;EACJ,IAAI;EACJ,MAAM;EACN,OAAO,KAAK;CACb;CACA;EAAE,MAAM;EAAU,QAAQ;CAAc;CACxC;EACC,MAAM;EACN,IAAI;EACJ,IAAI;EACJ,MAAM;EACN,OAAO,KAAK;CACb;CACA;EAAE,MAAM;EAAU,QAAQ;CAAU;AACrC;;AAGA,MAAM,kBAAkB;;AAGxB,MAAM,mBAAmB;;AAGzB,MAAM,cAAc,SACnB,SAAS,KAAK,OACb,oBAAC,QAAD;CAAM,WAAU;CAA0B,0BAAA;WACxC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M,WACH;QACF;EACA;;AAEP"}
|
|
1
|
+
{"version":3,"file":"PanelContent.js","names":[],"sources":["../../src/fields/PanelContent.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport { labelSeries, unitForTimeframe } from '../charts/bucket'\nimport { markInProgress } from '../charts/inProgress'\nimport { TrendChart } from '../charts/TrendChart'\nimport type { MetricKey, MetricValue } from '../core/contract'\nimport { readingOf } from '../core/metricValues'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { intlLocale } from '../translations/intl'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, metricLabelKey, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { MetricCard } from '../ui/components/MetricCard'\nimport { viewerNow } from '../ui/viewerClock'\nimport type { CountryFlags } from '../view/CountryFlag'\nimport { clickRate } from '../view/conversionRate'\nimport { ComparisonDelta } from '../widgets/ComparisonDelta'\nimport { widgetNotice } from '../widgets/notices'\nimport { mergeNotices } from '../widgets/readMeta'\nimport type { PanelData } from './AnalyticsPanelClient'\nimport { AnalyticsEmptyState, isEmptyDocumentRead } from './emptyState'\nimport { formatMetricValue, formatRate } from './format'\nimport { itemMetricLabel } from './itemReport'\nimport { PanelList } from './PanelList'\n\n/**\n * Item report cards in reading order. A rate is derived from the two counts beside it rather than\n * read, so it shows whenever both are there.\n */\ntype ItemCard =\n\t| { kind: 'metric'; metric: MetricKey }\n\t| { kind: 'rate'; id: string; of: MetricKey; over: MetricKey; label: TranslationKey }\n\nconst ITEM_CARDS: ItemCard[] = [\n\t{ kind: 'metric', metric: 'impressions' },\n\t{ kind: 'metric', metric: 'visitors' },\n\t{ kind: 'metric', metric: 'interactions' },\n\t{\n\t\tkind: 'rate',\n\t\tid: 'click-rate',\n\t\tof: 'interactions',\n\t\tover: 'impressions',\n\t\tlabel: keys.metricClickRate,\n\t},\n\t{ kind: 'metric', metric: 'conversions' },\n\t{\n\t\tkind: 'rate',\n\t\tid: 'conversion-rate',\n\t\tof: 'conversions',\n\t\tover: 'impressions',\n\t\tlabel: keys.viewConversionRate,\n\t},\n\t{ kind: 'metric', metric: 'revenue' },\n]\n\n/** Lists the panel lays out under its trend; no read it makes ranks more. */\nconst MAX_PANEL_LISTS = 3\n\n/** Height the trend keeps in the panel's narrow column. */\nconst TREND_MIN_HEIGHT = 140\n\n/** \"Updated 3 minutes ago\" is worded against the clock of whichever side renders. */\nconst noticeLine = (text: string) =>\n\ttext === '' ? null : (\n\t\t<span className=\"analytics-panel__notice\" suppressHydrationWarning>\n\t\t\t{text}\n\t\t</span>\n\t)\n\ninterface ShownCard {\n\tid: string\n\tlabel: string\n\tdisplay: string\n\tcurrent: MetricValue\n\tprevious: MetricValue | undefined\n\tmetric?: MetricKey\n}\n\ninterface PanelContentProps {\n\tdata: PanelData\n\t/** The window the numbers were read for, which the caption, chart and formatters follow. */\n\ttimeframe: TimeframePreset\n\t/** When the numbers were read, which decides the bucket that is still counting. */\n\treadAt: string\n\t/** Page card labels the developer set, resolved to plain strings. */\n\tlabels: Partial<Record<MetricKey, string>> | undefined\n\t/** Item card labels the developer set; other cards keep the item report's own names. */\n\titemLabelOverrides: Partial<Record<MetricKey, string>> | undefined\n\t/** ISO 4217 code revenue renders in when the read names none; absent leaves it a plain number. */\n\tcurrency: string | undefined\n\tcountryFlags: CountryFlags\n\t/** Offered beside the note that part of the read failed. */\n\tretryButton: ReactNode\n}\n\n/**\n * An answered read: its cards, trend, lists, caption and notices, or a line saying nothing was\n * counted in the window.\n */\nexport function PanelContent(props: PanelContentProps) {\n\tconst { data, timeframe, labels, countryFlags } = props\n\tconst { t, i18n } = useTranslation()\n\tconst locale = intlLocale(i18n.language)\n\tconst item = data.report === 'item'\n\tconst currency = data.notices?.currency ?? props.currency\n\t// One line for the whole panel: the cards, the trend and every list read the same days.\n\tconst timeZone = data.timezone ?? 'UTC'\n\tconst substituted = { substitutedFrom: data.substitutedFrom }\n\n\tif (isEmptyDocumentRead(data)) {\n\t\t// No cards or lists, so no revenue sum or grouped row needs explaining.\n\t\tconst emptyNotice = widgetNotice(\n\t\t\t{ ...mergeNotices(data.notices), ...substituted, mixedCurrencies: [], capped: false },\n\t\t\t{ t, locale, now: viewerNow(), timeZone }\n\t\t)\n\t\treturn (\n\t\t\t<div className=\"analytics-panel__content\">\n\t\t\t\t<AnalyticsEmptyState isNew={false}>\n\t\t\t\t\t{t(item ? keys.panelNoViews : keys.panelNoVisits)}\n\t\t\t\t</AnalyticsEmptyState>\n\t\t\t\t{noticeLine(emptyNotice)}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst notice = widgetNotice(\n\t\t{ ...mergeNotices(data.notices, ...(data.breakdowns ?? [])), ...substituted },\n\t\t{ t, locale, now: viewerNow(), timeZone }\n\t)\n\tconst firstMetric = data.supportedMetrics[0]\n\t// An hourly chart needs hourly rows: a source that serves none has a single value for the\n\t// window, which the metric cards already show, and a one-point line to nowhere otherwise.\n\tconst chartable = unitForTimeframe(timeframe) !== 'hour' || data.seriesGranularity === 'hour'\n\t// Every offered window runs up to when it was read, so its last bucket is still counting.\n\tconst now = new Date(props.readAt)\n\tconst bucketed =\n\t\tchartable && data.points && data.points.length > 0 && firstMetric\n\t\t\t? markInProgress(\n\t\t\t\t\tlabelSeries(data.points, {\n\t\t\t\t\t\tgranularity: data.seriesGranularity ?? 'day',\n\t\t\t\t\t\ttz: data.timezone,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\tweekday: timeframe === 'last7days',\n\t\t\t\t\t\t...(data.dateRange ? { from: new Date(data.dateRange.start) } : {}),\n\t\t\t\t\t}).map((b) => ({\n\t\t\t\t\t\t...b,\n\t\t\t\t\t\tdisplay: formatMetricValue(firstMetric, b.value, { locale, currency }),\n\t\t\t\t\t})),\n\t\t\t\t\t{ now, end: now, soFar: (period) => t(keys.chartSoFar, { period }) }\n\t\t\t\t)\n\t\t\t: null\n\t// An average with no reading on any day has nothing to draw: the card above already says so.\n\tconst buckets = bucketed?.some((b) => b.value !== null) ? bucketed : null\n\tconst served = new Set(data.supportedMetrics)\n\n\tconst card = (shown: ShownCard) => (\n\t\t<MetricCard\n\t\t\tclassName=\"analytics-panel__card\"\n\t\t\tkey={shown.id}\n\t\t\tlabel={shown.label}\n\t\t\tnoValueLabel={t(keys.stateNoValue)}\n\t\t\tvalue={shown.display}\n\t\t>\n\t\t\t{data.comparisonRange ? (\n\t\t\t\t<ComparisonDelta\n\t\t\t\t\tcurrent={shown.current}\n\t\t\t\t\tprevious={shown.previous}\n\t\t\t\t\t{...(shown.metric === undefined ? {} : { metric: shown.metric })}\n\t\t\t\t\tlocale={locale}\n\t\t\t\t\tt={t}\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t</MetricCard>\n\t)\n\n\tconst metricCard = (metric: MetricKey, label: string) => {\n\t\tconst value = readingOf(data.metrics, metric)\n\t\treturn card({\n\t\t\tid: metric,\n\t\t\tlabel,\n\t\t\tdisplay: formatMetricValue(metric, value, { locale, currency }),\n\t\t\tcurrent: value,\n\t\t\tprevious: data.previousMetrics?.[metric],\n\t\t\tmetric,\n\t\t})\n\t}\n\n\tconst pageCards = () =>\n\t\tdata.supportedMetrics.map((metric) =>\n\t\t\tmetricCard(\n\t\t\t\tmetric,\n\t\t\t\tlabels?.[metric] ?? t(metricLabelKey(metric, data.notices?.visitorsSummed))\n\t\t\t)\n\t\t)\n\n\tconst itemCards = () =>\n\t\tITEM_CARDS.flatMap((spec) => {\n\t\t\tif (spec.kind === 'metric') {\n\t\t\t\tif (!served.has(spec.metric)) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst label =\n\t\t\t\t\tprops.itemLabelOverrides?.[spec.metric] ??\n\t\t\t\t\tt(itemMetricLabel(spec.metric, METRIC_KEYS[spec.metric]))\n\t\t\t\treturn [metricCard(spec.metric, label)]\n\t\t\t}\n\t\t\tif (!served.has(spec.of) || !served.has(spec.over)) {\n\t\t\t\treturn []\n\t\t\t}\n\t\t\tconst rate = clickRate(data.metrics[spec.of], data.metrics[spec.over])\n\t\t\tconst previous = data.previousMetrics\n\t\t\t\t? clickRate(data.previousMetrics[spec.of], data.previousMetrics[spec.over])\n\t\t\t\t: undefined\n\t\t\treturn [\n\t\t\t\tcard({\n\t\t\t\t\tid: spec.id,\n\t\t\t\t\tlabel: t(spec.label),\n\t\t\t\t\tdisplay: formatRate(rate, locale),\n\t\t\t\t\tcurrent: rate,\n\t\t\t\t\tprevious,\n\t\t\t\t}),\n\t\t\t]\n\t\t})\n\n\tconst charted = item ? keys.metricImpressions : firstMetric && METRIC_KEYS[firstMetric]\n\tconst trendLabel = charted\n\t\t? t(keys.chartLabel, { metric: t(charted), window: t(TIMEFRAME_KEYS[timeframe]) })\n\t\t: ''\n\tconst lists = data.breakdowns ?? []\n\n\treturn (\n\t\t<div className=\"analytics-panel__content\">\n\t\t\t<div className=\"analytics-panel__cards\">{item ? itemCards() : pageCards()}</div>\n\t\t\t{buckets && firstMetric ? (\n\t\t\t\t<TrendChart\n\t\t\t\t\tariaLabel={trendLabel}\n\t\t\t\t\tbuckets={buckets}\n\t\t\t\t\tkeyboardHint={t(keys.chartKeyboardHint)}\n\t\t\t\t\tnoValueLabel={t(keys.stateNoValue)}\n\t\t\t\t\tlabel={\n\t\t\t\t\t\titem\n\t\t\t\t\t\t\t? t(keys.metricImpressions)\n\t\t\t\t\t\t\t: (labels?.[firstMetric] ?? t(METRIC_KEYS[firstMetric]))\n\t\t\t\t\t}\n\t\t\t\t\tminHeight={TREND_MIN_HEIGHT}\n\t\t\t\t\tperiodLabel={t(keys.viewTrendPeriod)}\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t\t{lists.length > 0 ? (\n\t\t\t\t<div className=\"analytics-panel__lists\">\n\t\t\t\t\t{lists.slice(0, MAX_PANEL_LISTS).map((block) => (\n\t\t\t\t\t\t<PanelList\n\t\t\t\t\t\t\tblock={block}\n\t\t\t\t\t\t\tcountryFlags={countryFlags}\n\t\t\t\t\t\t\tcurrency={currency}\n\t\t\t\t\t\t\titem={item}\n\t\t\t\t\t\t\tkey={block.dimension}\n\t\t\t\t\t\t/>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t\t<span className=\"analytics-panel__caption\">{t(TIMEFRAME_KEYS[timeframe])}</span>\n\t\t\t{noticeLine(notice)}\n\t\t\t{data.incomplete ? (\n\t\t\t\t<div className=\"analytics-panel__state\">\n\t\t\t\t\t{noticeLine(t(keys.statePartsFailed))}\n\t\t\t\t\t{props.retryButton}\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,aAAyB;CAC9B;EAAE,MAAM;EAAU,QAAQ;CAAc;CACxC;EAAE,MAAM;EAAU,QAAQ;CAAW;CACrC;EAAE,MAAM;EAAU,QAAQ;CAAe;CACzC;EACC,MAAM;EACN,IAAI;EACJ,IAAI;EACJ,MAAM;EACN,OAAO,KAAK;CACb;CACA;EAAE,MAAM;EAAU,QAAQ;CAAc;CACxC;EACC,MAAM;EACN,IAAI;EACJ,IAAI;EACJ,MAAM;EACN,OAAO,KAAK;CACb;CACA;EAAE,MAAM;EAAU,QAAQ;CAAU;AACrC;;AAGA,MAAM,kBAAkB;;AAGxB,MAAM,mBAAmB;;AAGzB,MAAM,cAAc,SACnB,SAAS,KAAK,OACb,oBAAC,QAAD;CAAM,WAAU;CAA0B,0BAAA;WACxC;AACI,CAAA;;;;;AAiCR,SAAgB,aAAa,OAA0B;CACtD,MAAM,EAAE,MAAM,WAAW,QAAQ,iBAAiB;CAClD,MAAM,EAAE,GAAG,SAAS,eAAe;CACnC,MAAM,SAAS,WAAW,KAAK,QAAQ;CACvC,MAAM,OAAO,KAAK,WAAW;CAC7B,MAAM,WAAW,KAAK,SAAS,YAAY,MAAM;CAEjD,MAAM,WAAW,KAAK,YAAY;CAClC,MAAM,cAAc,EAAE,iBAAiB,KAAK,gBAAgB;CAE5D,IAAI,oBA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AAK;GACnB,SAAS,WAAW,MAAM,MAAM;GAChC,SAAS;GACT;EACD,CAAC,CACF;CACD,CAAC;CAEF,MAAM,UAAU,OAAO,KAAK,oBAAoB,eAAe,YAAY;CAC3E,MAAM,aAAa,UAChB,EAAE,KAAK,YAAY;EAAE,QAAQ,EAAE,OAAO;EAAG,QAAQ,EAAE,eAAe,UAAU;CAAE,CAAC,IAC/E;CACH,MAAM,QAAQ,KAAK,cAAc,CAAC;CAElC,OACC,qBAAC,OAAD;EAAK,WAAU;YAAf;GACC,oBAAC,OAAD;IAAK,WAAU;cAA0B,OAAO,UAAU,IAAI,UAAU;GAAO,CAAA;GAC9E,WAAW,cACX,oBAAC,YAAD;IACC,WAAW;IACF;IACT,cAAc,EAAE,KAAK,iBAAiB;IACtC,cAAc,EAAE,KAAK,YAAY;IACjC,OACC,OACG,EAAE,KAAK,iBAAiB,IACvB,SAAS,gBAAgB,EAAE,YAAY,YAAY;IAExD,WAAW;IACX,aAAa,EAAE,KAAK,eAAe;GACnC,CAAA,IACE;GACH,MAAM,SAAS,IACf,oBAAC,OAAD;IAAK,WAAU;cACb,MAAM,MAAM,GAAG,eAAe,EAAE,KAAK,UACrC,oBAAC,WAAD;KACQ;KACO;KACJ;KACJ;IAEN,GADK,MAAM,SACX,CACD;GACG,CAAA,IACF;GACJ,oBAAC,QAAD;IAAM,WAAU;cAA4B,EAAE,eAAe,UAAU;GAAQ,CAAA;GAC9E,WAAW,MAAM;GACjB,KAAK,aACL,qBAAC,OAAD;IAAK,WAAU;cAAf,CACE,WAAW,EAAE,KAAK,gBAAgB,CAAC,GACnC,MAAM,WACH;QACF;EACA;;AAEP"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SerializedCapabilities } from "../../core/capabilities.js";
|
|
2
|
+
import { SourcesNotice } from "../../plugin/readContextForRequest.js";
|
|
2
3
|
|
|
3
4
|
//#region src/fields/config/fetchSources.d.ts
|
|
4
5
|
interface WireSource {
|
|
@@ -10,6 +11,8 @@ interface WireSource {
|
|
|
10
11
|
interface SourcesResponse {
|
|
11
12
|
defaultId: string | null;
|
|
12
13
|
sources: WireSource[];
|
|
14
|
+
/** What the reader should be told about the listing itself; absent, nothing. */
|
|
15
|
+
notice?: SourcesNotice;
|
|
13
16
|
}
|
|
14
17
|
//#endregion
|
|
15
18
|
export { SourcesResponse, WireSource };
|
|
@@ -5,7 +5,9 @@ import { requestShaped } from "../../ui/data/request.js";
|
|
|
5
5
|
const isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
6
6
|
/** The parts of a source the pickers read: who it is and the lists its capabilities gate on. */
|
|
7
7
|
const isWireSource = (value) => isRecord(value) && typeof value.id === "string" && typeof value.label === "string" && (value.kind === "config" || value.kind === "runtime") && isRecord(value.capabilities) && isStringList(value.capabilities.metrics) && isStringList(value.capabilities.dimensions) && isRecord(value.capabilities.filters);
|
|
8
|
-
const isSourcesResponse = (value) => isRecord(value) && (value.defaultId === null || typeof value.defaultId === "string") && Array.isArray(value.sources) && value.sources.every(isWireSource);
|
|
8
|
+
const isSourcesResponse = (value) => isRecord(value) && (value.defaultId === null || typeof value.defaultId === "string") && (value.notice === void 0 || value.notice === "platformFallback") && Array.isArray(value.sources) && value.sources.every(isWireSource);
|
|
9
|
+
/** The listing read fresh, past the shared cache, for a surface that must not show a stale one. */
|
|
10
|
+
const requestSources = (url, signal) => requestShaped(url, isSourcesResponse, { signal });
|
|
9
11
|
const cache = createSharedCache();
|
|
10
12
|
/**
|
|
11
13
|
* Source list shared by every picker on the page, keyed by scope so a login or tenant switch reads
|
|
@@ -14,8 +16,8 @@ const cache = createSharedCache();
|
|
|
14
16
|
const fetchSources = (url, scope) => cache.read({
|
|
15
17
|
route: url,
|
|
16
18
|
scope
|
|
17
|
-
}, () =>
|
|
19
|
+
}, () => requestSources(url));
|
|
18
20
|
//#endregion
|
|
19
|
-
export { fetchSources };
|
|
21
|
+
export { fetchSources, requestSources };
|
|
20
22
|
|
|
21
23
|
//# sourceMappingURL=fetchSources.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchSources.js","names":[],"sources":["../../../src/fields/config/fetchSources.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../../core/capabilities'\nimport { isRecord } from '../../core/values'\nimport { requestShaped } from '../../ui/data/request'\nimport { createSharedCache } from '../../ui/data/sharedCache'\n\nexport interface WireSource {\n\tid: string\n\tlabel: string\n\tkind: 'config' | 'runtime'\n\tcapabilities: SerializedCapabilities\n}\n\nexport interface SourcesResponse {\n\tdefaultId: string | null\n\tsources: WireSource[]\n}\n\nconst isStringList = (value: unknown): value is string[] =>\n\tArray.isArray(value) && value.every((entry) => typeof entry === 'string')\n\n/** The parts of a source the pickers read: who it is and the lists its capabilities gate on. */\nconst isWireSource = (value: unknown): value is WireSource =>\n\tisRecord(value) &&\n\ttypeof value.id === 'string' &&\n\ttypeof value.label === 'string' &&\n\t(value.kind === 'config' || value.kind === 'runtime') &&\n\tisRecord(value.capabilities) &&\n\tisStringList(value.capabilities.metrics) &&\n\tisStringList(value.capabilities.dimensions) &&\n\tisRecord(value.capabilities.filters)\n\nconst isSourcesResponse = (value: unknown): value is SourcesResponse =>\n\tisRecord(value) &&\n\t(value.defaultId === null || typeof value.defaultId === 'string') &&\n\tArray.isArray(value.sources) &&\n\tvalue.sources.every(isWireSource)\n\nconst cache = createSharedCache<SourcesResponse>()\n\n/**\n * Source list shared by every picker on the page, keyed by scope so a login or tenant switch reads\n * again. A refusal or misshapen answer rejects and drops the entry, so a later mount retries.\n */\nexport const fetchSources = (url: string, scope: string): Promise<SourcesResponse> =>\n\tcache.read({ route: url, scope }, () =>
|
|
1
|
+
{"version":3,"file":"fetchSources.js","names":[],"sources":["../../../src/fields/config/fetchSources.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../../core/capabilities'\nimport { isRecord } from '../../core/values'\nimport type { SourcesNotice } from '../../plugin/readContextForRequest'\nimport { requestShaped } from '../../ui/data/request'\nimport { createSharedCache } from '../../ui/data/sharedCache'\n\nexport interface WireSource {\n\tid: string\n\tlabel: string\n\tkind: 'config' | 'runtime'\n\tcapabilities: SerializedCapabilities\n}\n\nexport type { SourcesNotice }\n\nexport interface SourcesResponse {\n\tdefaultId: string | null\n\tsources: WireSource[]\n\t/** What the reader should be told about the listing itself; absent, nothing. */\n\tnotice?: SourcesNotice\n}\n\nconst isStringList = (value: unknown): value is string[] =>\n\tArray.isArray(value) && value.every((entry) => typeof entry === 'string')\n\n/** The parts of a source the pickers read: who it is and the lists its capabilities gate on. */\nconst isWireSource = (value: unknown): value is WireSource =>\n\tisRecord(value) &&\n\ttypeof value.id === 'string' &&\n\ttypeof value.label === 'string' &&\n\t(value.kind === 'config' || value.kind === 'runtime') &&\n\tisRecord(value.capabilities) &&\n\tisStringList(value.capabilities.metrics) &&\n\tisStringList(value.capabilities.dimensions) &&\n\tisRecord(value.capabilities.filters)\n\nconst isSourcesResponse = (value: unknown): value is SourcesResponse =>\n\tisRecord(value) &&\n\t(value.defaultId === null || typeof value.defaultId === 'string') &&\n\t(value.notice === undefined || value.notice === 'platformFallback') &&\n\tArray.isArray(value.sources) &&\n\tvalue.sources.every(isWireSource)\n\n/** The listing read fresh, past the shared cache, for a surface that must not show a stale one. */\nexport const requestSources = (url: string, signal?: AbortSignal): Promise<SourcesResponse> =>\n\trequestShaped(url, isSourcesResponse, { signal })\n\nconst cache = createSharedCache<SourcesResponse>()\n\n/**\n * Source list shared by every picker on the page, keyed by scope so a login or tenant switch reads\n * again. A refusal or misshapen answer rejects and drops the entry, so a later mount retries.\n */\nexport const fetchSources = (url: string, scope: string): Promise<SourcesResponse> =>\n\tcache.read({ route: url, scope }, () => requestSources(url))\n"],"mappings":";;;;AAsBA,MAAM,gBAAgB,UACrB,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ;;AAGzE,MAAM,gBAAgB,UACrB,SAAS,KAAK,KACd,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,UAAU,aACtB,MAAM,SAAS,YAAY,MAAM,SAAS,cAC3C,SAAS,MAAM,YAAY,KAC3B,aAAa,MAAM,aAAa,OAAO,KACvC,aAAa,MAAM,aAAa,UAAU,KAC1C,SAAS,MAAM,aAAa,OAAO;AAEpC,MAAM,qBAAqB,UAC1B,SAAS,KAAK,MACb,MAAM,cAAc,QAAQ,OAAO,MAAM,cAAc,cACvD,MAAM,WAAW,KAAA,KAAa,MAAM,WAAW,uBAChD,MAAM,QAAQ,MAAM,OAAO,KAC3B,MAAM,QAAQ,MAAM,YAAY;;AAGjC,MAAa,kBAAkB,KAAa,WAC3C,cAAc,KAAK,mBAAmB,EAAE,OAAO,CAAC;AAEjD,MAAM,QAAQ,kBAAmC;;;;;AAMjD,MAAa,gBAAgB,KAAa,UACzC,MAAM,KAAK;CAAE,OAAO;CAAK;AAAM,SAAS,eAAe,GAAG,CAAC"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { DateRange, DimensionKey, MetricKey, MetricValues } from "../core/contract.js";
|
|
2
|
-
import {
|
|
2
|
+
import { ReadPrincipal } from "../access/principal.js";
|
|
3
3
|
import { BindingDoc } from "../binding/types.js";
|
|
4
|
+
import { TimeframePreset } from "../timeframe/presets.js";
|
|
4
5
|
import { ReadNotices } from "../widgets/readMeta.js";
|
|
5
|
-
import {
|
|
6
|
+
import { StoredSourceRead, SubstitutedSource } from "../widgets/prepareWidgetRead.js";
|
|
6
7
|
import { ReportMode } from "../binding/report.js";
|
|
7
8
|
import { SeriesGranularity, SeriesPoint } from "../charts/series.js";
|
|
8
9
|
import { PayloadRequest } from "payload";
|
|
@@ -30,7 +31,7 @@ interface FieldBreakdown extends Partial<ReadNotices> {
|
|
|
30
31
|
/** The source that answered, for the value labels that read differently per provider. */
|
|
31
32
|
provider?: string;
|
|
32
33
|
}
|
|
33
|
-
interface FieldReadResult {
|
|
34
|
+
interface FieldReadResult extends SubstitutedSource {
|
|
34
35
|
status: FieldReadStatus;
|
|
35
36
|
/** How long until a `busy` read can succeed, when the source or the plugin knows. */
|
|
36
37
|
retryAfterMs?: number;
|
|
@@ -75,7 +76,7 @@ interface FieldReadResult {
|
|
|
75
76
|
* Without `scope` the read takes the document's scope (binding `scopeField`) else the request's,
|
|
76
77
|
* gated as endpoints gate it; a given `scope` is already cleared, or a job's under `SYSTEM`.
|
|
77
78
|
*/
|
|
78
|
-
type ReadForFieldArgs = ReadPrincipal & {
|
|
79
|
+
type ReadForFieldArgs = ReadPrincipal & StoredSourceRead & {
|
|
79
80
|
req: PayloadRequest;
|
|
80
81
|
collectionSlug: string;
|
|
81
82
|
data: BindingDoc;
|
|
@@ -16,7 +16,7 @@ import { readAsAsked, servedName } from "../core/metricAliases.js";
|
|
|
16
16
|
import { scopeFromDocument } from "./documentScope.js";
|
|
17
17
|
import { resolveDocumentScope } from "../plugin/documentScopes.js";
|
|
18
18
|
import { goalSlugsFor } from "../plugin/goalHint.js";
|
|
19
|
-
import { comparisonWindow } from "../widgets/prepareWidgetRead.js";
|
|
19
|
+
import { comparisonWindow, substitutionOf } from "../widgets/prepareWidgetRead.js";
|
|
20
20
|
import { mergeNotices, readMeta } from "../widgets/readMeta.js";
|
|
21
21
|
//#region src/fields/readForDocument.ts
|
|
22
22
|
/** Rows per breakdown block: a card-sized list, not a table. */
|
|
@@ -126,6 +126,7 @@ const readFieldWith = async (args, via) => {
|
|
|
126
126
|
req,
|
|
127
127
|
adapterId,
|
|
128
128
|
...principal,
|
|
129
|
+
...args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {},
|
|
129
130
|
...args.report === "item" ? { prefer: (candidate) => candidate.capabilities.perItemQuery === true } : {}
|
|
130
131
|
});
|
|
131
132
|
if (!ctx.ok) return unread(refusedStatus(ctx.reason, documentScope !== null), ctx.reason === "not-member" ? { untrustedScope: true } : {});
|
|
@@ -145,7 +146,10 @@ const readFieldWith = async (args, via) => {
|
|
|
145
146
|
locale: req.locale ?? void 0
|
|
146
147
|
}
|
|
147
148
|
};
|
|
148
|
-
return
|
|
149
|
+
return {
|
|
150
|
+
...args.report === "item" ? await readItem(resolved) : await readPage(resolved),
|
|
151
|
+
...substitutionOf(ctx)
|
|
152
|
+
};
|
|
149
153
|
};
|
|
150
154
|
/**
|
|
151
155
|
* Splits the asked metrics by what the source serves; the dropped ones the caller did not add
|