@nuxtseo/pro-search 0.0.0-stage → 0.1.10

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/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # Pro Search
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Install `@nuxtseo/pro-search` with its design system peer. Add the package to the host Nuxt config's `extends`.
4
+
5
+ - Use `SearchConsoleTrend.vue` from `@nuxtseo/pro-search/components/` for daily Search Console metrics and comparison overlays. Pass the current and previous series and the requested date range. A host can provide a connection link and a classified read failure.
6
+ - Use `RankedSearchTable.vue` and `RankedSearchRow.vue` from `@nuxtseo/pro-search/components/` for the ranked Search Console cards. Pass Top, Rising, and Falling rows. The row slot supplies the label and any host links or query variants.
7
+ - Use `BingSearchPerformance.vue` from the same path for the Bing traffic chart and ranked Pages and Keywords. Pass the traffic response and the current breakdown response. Bind `entityKind` and `page` and handle `retry` to drive the host reads. Use `BING_PERFORMANCE_PAGE_SIZE` when requesting breakdown rows.
8
+ - Import labels, icons, and Webmaster Tools tabs from `@nuxtseo/pro-search/shared/navigation`. The host owns its routes, access checks, and data reads.
@@ -0,0 +1,185 @@
1
+ <script setup lang="ts">
2
+ import type { BingDataV1 } from '@gscdump/contracts/v1/http'
3
+ import type { BingEntityKind } from '../../shared/bing-performance'
4
+ import { gscMetricColors } from '@nuxtseo/design-system/app/composables/dataVizColors'
5
+ import { computed, ref, watch } from 'vue'
6
+ import { UiAlert, UiDataTableSection, UiEmptyState, UiIcon, UiLineChart, UiMetricStat, UiMetricToggle, UiRelativeTime, UiSectionHeader, UiTableMetricCell, UiTablePathCell, UiTableShell, UiTableTd, UiTableTh, UiTogglePill } from '#components'
7
+ import { BING_PERFORMANCE_PAGE_SIZE, bingTrafficTotals, formatBingCtr, formatBingNumber, formatBingReportingDay } from '../../shared/bing-performance'
8
+
9
+ const { data, startDate, endDate, entities, pending, error } = defineProps<{
10
+ data: Extract<BingDataV1, { dataset: 'traffic' }>
11
+ startDate: string
12
+ endDate: string
13
+ entities: BingDataV1 | null
14
+ pending: boolean
15
+ error: boolean
16
+ }>()
17
+ const emit = defineEmits<{ retry: [] }>()
18
+ const entityKind = defineModel<BingEntityKind>('entityKind', { required: true })
19
+ const page = defineModel<number>('page', { required: true })
20
+
21
+ const metrics = ref(['clicks', 'impressions'])
22
+ const metricOptions = [
23
+ { key: 'clicks', label: 'Clicks', color: 'blue' },
24
+ { key: 'impressions', label: 'Impressions', color: 'purple' },
25
+ ] as const
26
+ // The chips are the chart legend, so each line draws in its chip's identity colour.
27
+ const chartSeries = computed(() => metricOptions
28
+ .filter(option => metrics.value.includes(option.key))
29
+ .map(option => ({ key: option.key, label: option.label, color: gscMetricColors[option.key].color })))
30
+ const totals = computed(() => bingTrafficTotals(data.rows))
31
+ const lastCollection = computed(() => data.sync._tag === 'missing' ? null : data.sync.observedAt)
32
+ const unavailable = computed(() => data.sync._tag === 'unavailable' || entities?.sync._tag === 'unavailable')
33
+
34
+ interface EntityRow extends Record<string, unknown> {
35
+ key: string
36
+ label: string
37
+ date: string
38
+ url: string | null
39
+ clicks: number
40
+ impressions: number
41
+ averagePosition: number | null
42
+ }
43
+
44
+ const entityOptions = [
45
+ { label: 'Pages', value: 'pages' as const },
46
+ { label: 'Keywords', value: 'keywords' as const },
47
+ ]
48
+ const visibleRows = computed<EntityRow[]>(() => {
49
+ const result = entities
50
+ if (result?.dataset !== entityKind.value)
51
+ return []
52
+ if (result.dataset === 'pages')
53
+ return result.rows.map(row => ({ key: `${row.date}:${row.page}`, date: row.date, label: row.page, url: row.page, clicks: row.clicks, impressions: row.impressions, averagePosition: row.averageImpressionPosition }))
54
+ if (result?.dataset === 'keywords')
55
+ return result.rows.map(row => ({ key: `${row.date}:${row.keyword}`, date: row.date, label: row.keyword, url: null, clicks: row.clicks, impressions: row.impressions, averagePosition: row.averageImpressionPosition }))
56
+ return []
57
+ })
58
+ const totalRows = computed(() => entities?.pagination.total ?? 0)
59
+ watch(entityKind, () => { page.value = 1 })
60
+ watch(() => entities, (result) => {
61
+ if (result && result.dataset === entityKind.value)
62
+ page.value = Math.min(page.value, Math.max(1, Math.ceil(result.pagination.total / BING_PERFORMANCE_PAGE_SIZE)))
63
+ })
64
+
65
+ function rowCtr(row: EntityRow): string {
66
+ return formatBingCtr(row.impressions === 0 ? 0 : row.clicks / row.impressions)
67
+ }
68
+ </script>
69
+
70
+ <template>
71
+ <div class="flex flex-col gap-6" data-testid="bing-search-performance">
72
+ <UiAlert
73
+ v-if="unavailable"
74
+ status="warning"
75
+ title="Some Bing data is delayed"
76
+ description="The last successful collection stays visible while the next daily sync retries."
77
+ />
78
+
79
+ <div role="group" aria-label="Bing Search Performance filters" class="flex min-w-0 flex-col gap-2">
80
+ <span class="inline-flex items-center gap-1.5 text-xs text-muted">
81
+ <UiIcon name="calendar" class="size-3.5 shrink-0 text-dimmed" aria-hidden="true" />
82
+ {{ startDate }} to {{ endDate }}
83
+ </span>
84
+ <UiMetricToggle v-if="data.rows.length" v-model="metrics" :options="[...metricOptions]" chip :colors="gscMetricColors" />
85
+ </div>
86
+
87
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
88
+ <UiSectionHeader
89
+ title="Bing Search Performance"
90
+ tooltip="Bing reports total traffic across its search surfaces. It does not provide a separate Chat source."
91
+ />
92
+ <div v-if="lastCollection" class="text-xs text-muted">
93
+ Collected <UiRelativeTime :date="lastCollection" />
94
+ </div>
95
+ </div>
96
+
97
+ <UiEmptyState v-if="!data.rows.length" icon="search" title="No Bing traffic in this date range" description="Pages and Keywords can still have data below." />
98
+
99
+ <div v-if="data.rows.length" class="flex flex-wrap gap-x-6 gap-y-3 rounded-xl border border-default bg-elevated/30 px-4 py-3">
100
+ <UiMetricStat :value="formatBingNumber(totals.clicks)" label="clicks" />
101
+ <UiMetricStat :value="formatBingNumber(totals.impressions)" label="impressions" />
102
+ <UiMetricStat :value="formatBingCtr(totals.ctr)" label="CTR" />
103
+ </div>
104
+
105
+ <div v-if="data.rows.length" class="rounded-xl border border-default bg-default p-4">
106
+ <h3 class="mb-3 text-sm font-strong text-highlighted">
107
+ Traffic over time
108
+ </h3>
109
+ <UiLineChart
110
+ :data="data.rows"
111
+ x-key="date"
112
+ :series="chartSeries"
113
+ :height="220"
114
+ :x-format="value => formatBingReportingDay(String(value))"
115
+ :y-format="value => formatBingNumber(value)"
116
+ />
117
+ </div>
118
+
119
+ <div class="flex items-center justify-between gap-3">
120
+ <UiSectionHeader
121
+ :title="entityKind === 'pages' ? 'Top Pages' : 'Top Keywords'"
122
+ tooltip="Bing updates its top Pages and Keywords data weekly."
123
+ />
124
+ <UiTogglePill v-model="entityKind" :options="entityOptions" label="Bing breakdown" />
125
+ </div>
126
+
127
+ <UiDataTableSection
128
+ v-model:page="page"
129
+ :rows="visibleRows"
130
+ :total="totalRows"
131
+ :pending="pending"
132
+ :error="error ? 'Bing data could not be loaded. Retry the request.' : undefined"
133
+ :searchable="false"
134
+ :columns="[]"
135
+ :page-size="BING_PERFORMANCE_PAGE_SIZE"
136
+ item-label="rows"
137
+ :label="entityKind === 'pages' ? 'Top Bing Pages' : 'Top Bing Keywords'"
138
+ @retry="emit('retry')"
139
+ >
140
+ <template #body>
141
+ <UiTableShell bordered row-hover size="xs" :label="entityKind === 'pages' ? 'Top Bing Pages' : 'Top Bing Keywords'">
142
+ <template #head>
143
+ <UiTableTh>
144
+ {{ entityKind === 'pages' ? 'Page' : 'Keyword' }}
145
+ </UiTableTh>
146
+ <UiTableTh>Date</UiTableTh>
147
+ <UiTableTh numeric>
148
+ Clicks
149
+ </UiTableTh>
150
+ <UiTableTh numeric>
151
+ Impressions
152
+ </UiTableTh>
153
+ <UiTableTh numeric visible-from="md">
154
+ CTR
155
+ </UiTableTh>
156
+ <UiTableTh numeric visible-from="lg">
157
+ Avg position
158
+ </UiTableTh>
159
+ </template>
160
+ <tr v-for="row in visibleRows" :key="row.key">
161
+ <UiTableTd row-header class="max-w-0 w-full">
162
+ <UiTablePathCell v-if="row.url" :url="row.url" />
163
+ <span v-else class="block truncate font-sans text-xs text-default" :title="row.label">{{ row.label }}</span>
164
+ </UiTableTd>
165
+ <UiTableTd class="whitespace-nowrap">
166
+ {{ row.date }}
167
+ </UiTableTd>
168
+ <UiTableTd numeric>
169
+ <UiTableMetricCell :value="row.clicks" :display="formatBingNumber(row.clicks)" />
170
+ </UiTableTd>
171
+ <UiTableTd numeric>
172
+ <UiTableMetricCell :value="row.impressions" :display="formatBingNumber(row.impressions)" muted />
173
+ </UiTableTd>
174
+ <UiTableTd numeric visible-from="md">
175
+ <UiTableMetricCell :value="row.impressions ? row.clicks / row.impressions : 0" :display="rowCtr(row)" muted />
176
+ </UiTableTd>
177
+ <UiTableTd numeric visible-from="lg">
178
+ <UiTableMetricCell :value="row.averagePosition" :display="row.averagePosition == null ? null : row.averagePosition.toFixed(1)" muted />
179
+ </UiTableTd>
180
+ </tr>
181
+ </UiTableShell>
182
+ </template>
183
+ </UiDataTableSection>
184
+ </div>
185
+ </template>
@@ -0,0 +1,46 @@
1
+ <script setup lang="ts">
2
+ import type { GscTrendDisplay } from './search-trend'
3
+ import { formatNumber } from '@nuxtseo/design-system/app/composables/formatting'
4
+ import { UiFavicon, UiSparkline } from '#components'
5
+
6
+ const { siteDomain, clicks, comparison, barPct, barClass, sparkColor, sparkline } = defineProps<{
7
+ siteDomain?: string
8
+ clicks: number
9
+ comparison: GscTrendDisplay
10
+ barPct: number
11
+ barClass: string
12
+ sparkColor: string
13
+ sparkline: number[]
14
+ }>()
15
+ </script>
16
+
17
+ <template>
18
+ <div class="relative flex min-w-0 items-center gap-2 py-1.5 px-1.5 rounded-md overflow-hidden cursor-default">
19
+ <div
20
+ class="absolute inset-y-0 left-0 rounded-md motion-reduce:transition-none transition-[width] duration-300"
21
+ :class="barClass"
22
+ :style="{ width: `${barPct}%` }"
23
+ />
24
+ <UiFavicon v-if="siteDomain" :domain="siteDomain" :size="14" class="relative rounded-sm shrink-0" />
25
+
26
+ <div class="relative flex min-w-0 flex-1 items-center gap-2">
27
+ <slot />
28
+ </div>
29
+
30
+ <UiSparkline
31
+ v-if="sparkline.length > 1"
32
+ :data="sparkline"
33
+ :color="sparkColor"
34
+ :width="40"
35
+ :height="14"
36
+ class="relative hidden shrink-0 @min-[19rem]:block"
37
+ />
38
+ <span class="relative shrink-0 text-xs font-medium tabular-nums text-default">{{ formatNumber(clicks) }}</span>
39
+ <span
40
+ class="relative w-16 shrink-0 truncate text-right text-mini font-medium text-muted"
41
+ :title="comparison._tag === 'none' ? undefined : comparison.title"
42
+ >
43
+ {{ comparison._tag === 'none' ? '' : comparison.label }}
44
+ </span>
45
+ </div>
46
+ </template>
@@ -0,0 +1,94 @@
1
+ <script setup lang="ts" generic="Row extends RankedSearchRow">
2
+ import type { RankedSearchRow } from '../../shared/ranked-search'
3
+ import { UiMetricLabel, UiSeverityDot, UiSkeleton } from '#components'
4
+
5
+ type EntitySort = 'top' | 'rising' | 'falling'
6
+
7
+ const { entityPlural, top = [], rising = [], falling = [], loading = false, pending = [], failed = [] } = defineProps<{
8
+ entityPlural: 'queries' | 'pages' | 'countries'
9
+ top?: Row[]
10
+ rising?: Row[]
11
+ falling?: Row[]
12
+ loading?: boolean
13
+ pending?: readonly EntitySort[]
14
+ failed?: readonly EntitySort[]
15
+ }>()
16
+
17
+ defineSlots<{
18
+ row: (props: { row: Row, barPct: number, barClass: string, sparkColor: string }) => unknown
19
+ }>()
20
+
21
+ interface SetMeta { value: EntitySort, label: string, barClass: string, sparkColor: string }
22
+ const SETS: SetMeta[] = [
23
+ { value: 'top', label: 'Top by clicks', barClass: 'bg-info/8', sparkColor: 'blue' },
24
+ { value: 'rising', label: 'Rising', barClass: 'bg-success/5', sparkColor: 'green' },
25
+ { value: 'falling', label: 'Falling', barClass: 'bg-error/8', sparkColor: 'red' },
26
+ ]
27
+
28
+ function rowsFor(s: EntitySort): Row[] {
29
+ return s === 'top' ? top : s === 'rising' ? rising : falling
30
+ }
31
+ function visibleRows(s: EntitySort): Row[] {
32
+ return rowsFor(s).slice(0, 3)
33
+ }
34
+ // Top ranks by clicks; the movers rank by |%Δ|.
35
+ function basis(s: EntitySort, row: Row): number {
36
+ return s === 'top' ? row.clicks : Math.abs(row.clicksChangePercent ?? 0)
37
+ }
38
+ function maxBasis(s: EntitySort): number {
39
+ return Math.max(...rowsFor(s).map(r => basis(s, r)), 1)
40
+ }
41
+ function barPct(s: EntitySort, row: Row): number {
42
+ return (basis(s, row) / maxBasis(s)) * 100
43
+ }
44
+ function emptyLabel(s: EntitySort): string {
45
+ return s === 'top' ? `No ${entityPlural} yet` : s === 'rising' ? `No rising ${entityPlural}` : `No declining ${entityPlural}`
46
+ }
47
+ function isPending(s: EntitySort): boolean {
48
+ return loading || pending.includes(s)
49
+ }
50
+ function rowKey(row: Row, i: number): string {
51
+ return `${row.siteDomain}:${row.keyword ?? row.label ?? ''}:${i}`
52
+ }
53
+ </script>
54
+
55
+ <template>
56
+ <div class="@container grid min-w-0 grid-cols-1 gap-3">
57
+ <template v-for="set in SETS" :key="set.value">
58
+ <div v-if="isPending(set.value)" class="min-w-0">
59
+ <!-- `block` keeps the caller's box: the self-sizing `text` type writes an
60
+ inline pixel width that beat `w-20`/`w-full`, so every placeholder came
61
+ out ~200px wide regardless of the row it stood in for. -->
62
+ <UiSkeleton type="block" class="mb-2 h-3 w-20" />
63
+ <div class="space-y-px">
64
+ <UiSkeleton v-for="j in 3" :key="j" type="block" class="h-7 w-full" />
65
+ </div>
66
+ </div>
67
+ <section v-else class="min-w-0">
68
+ <UiMetricLabel :label="set.label" class="mb-2" />
69
+ <span
70
+ v-if="failed.includes(set.value)"
71
+ class="ml-2 inline-flex items-center gap-1 text-xs text-muted"
72
+ title="Couldn't load. Reload to try again."
73
+ >
74
+ <UiSeverityDot severity="warning" />
75
+ Couldn't load
76
+ </span>
77
+ <div v-if="visibleRows(set.value).length" class="space-y-px">
78
+ <template v-for="(row, i) in visibleRows(set.value)" :key="rowKey(row, i)">
79
+ <slot
80
+ name="row"
81
+ :row="row"
82
+ :bar-pct="barPct(set.value, row)"
83
+ :bar-class="set.barClass"
84
+ :spark-color="set.sparkColor"
85
+ />
86
+ </template>
87
+ </div>
88
+ <p v-else-if="!failed.includes(set.value)" class="py-2 text-xs text-dimmed">
89
+ {{ emptyLabel(set.value) }}
90
+ </p>
91
+ </section>
92
+ </template>
93
+ </div>
94
+ </template>
@@ -0,0 +1,669 @@
1
+ <script lang="ts" setup>
2
+ import type { SearchConsoleTrendDay as DataRow, SearchConsoleTrendProps } from '../../shared/search-console-trend'
3
+ import { getGscUnstableCutoffDate } from '@gscdump/sdk/period'
4
+ import { gscMetricColors } from '@nuxtseo/design-system/app/composables/dataVizColors'
5
+ import { formatGroupedNumber } from '@nuxtseo/design-system/app/composables/formatting'
6
+ import { useChartTickPlan } from '@nuxtseo/design-system/app/composables/useChartTickPlan'
7
+ import { Scale, TextAlign } from '@unovis/ts'
8
+ import { VisArea, VisAxis, VisCrosshair, VisLine, VisScatter, VisXYContainer } from '@unovis/vue'
9
+ import { useElementSize } from '@vueuse/core'
10
+ import { computed, useTemplateRef } from 'vue'
11
+ import { ClientOnly, UiButton, UiIcon, UiSkeleton } from '#components'
12
+ import { alignPrev, anchorOffsetDays, calendarChartRows, isolatedChartValue, resolveCompareAligner, toUtcDay } from '../../shared/compare-align'
13
+
14
+ const { value, dateRange, prevValue, fullValue, fullPrevValue, compareMode, compareOffsetDays, columns, height, loading, failure, connectionTo } = defineProps<SearchConsoleTrendProps>()
15
+ const chartFailure = computed(() => value.length ? null : failure)
16
+
17
+ // The metric colour is a CSS custom property a site may override, so mix it
18
+ // rather than parse hex. Mixing with `transparent` in srgb sets only the alpha.
19
+ function metricRgba(metric: keyof typeof gscMetricColors, opacity: number) {
20
+ return `color-mix(in srgb, ${gscMetricColors[metric].color} ${Math.round(opacity * 10000) / 100}%, transparent)`
21
+ }
22
+
23
+ const gscColors = {
24
+ clicks: { line: metricRgba('clicks', 0.9), area: 'url(#gradient-clicks)', prev: metricRgba('clicks', 0.3) },
25
+ impressions: { line: metricRgba('impressions', 0.7), area: 'url(#gradient-impressions)', prev: metricRgba('impressions', 0.3) },
26
+ ctr: { line: metricRgba('ctr', 0.9), prev: metricRgba('ctr', 0.3) },
27
+ position: { line: metricRgba('position', 0.9), prev: metricRgba('position', 0.3) },
28
+ }
29
+
30
+ // Shared config for overlaid containers. No horizontal inset — the line bleeds
31
+ // edge-to-edge (and brush/hover pixel→index math maps over the full wrap width,
32
+ // so a side margin would drift the hit-testing). Edge tick labels are kept
33
+ // inside via the text-anchor overrides in <style> below.
34
+ const margin = { left: 0, right: 0, top: 0, bottom: 36 }
35
+ const plotBleed = { left: 0, right: 0 }
36
+ const chartHeight = computed(() => Number(height) || 220)
37
+ const chartInnerHeight = computed(() => chartHeight.value - margin.top - margin.bottom)
38
+
39
+ const svgDefs = `
40
+ <linearGradient id="gradient-clicks" gradientTransform="rotate(90)">
41
+ <stop offset="0%" stop-color="${metricRgba('clicks', 0.25)}" />
42
+ <stop offset="100%" stop-color="${metricRgba('clicks', 0.01)}" />
43
+ </linearGradient>
44
+ <linearGradient id="gradient-impressions" gradientTransform="rotate(90)">
45
+ <stop offset="0%" stop-color="${metricRgba('impressions', 0.2)}" />
46
+ <stop offset="100%" stop-color="${metricRgba('impressions', 0.01)}" />
47
+ </linearGradient>`
48
+
49
+ // --- Comparison data handling ---
50
+ // Unovis applies accessors against the container's data, so we merge prev rows into
51
+ // `value` by calendar-date match (prev.date + 1 year = value.date) and expose them
52
+ // via accessor functions. Using a separate `:data` prop or a shifted x-accessor
53
+ // doesn't work: the former is ignored, the latter expands the x-domain and squishes
54
+ // the current line.
55
+ type MergedRow = DataRow & { prev?: DataRow }
56
+ // The compare series is the immediately-preceding period ('previous', the
57
+ // default) as often as it is year-over-year, so the overlay can't assume a fixed
58
+ // `year - 1` key. Prefer the authoritative window-derived offset (passed by the
59
+ // dashboard; correct even when the compare window's most recent day has no rows),
60
+ // and fall back to anchoring on the most recent day of each series for callers
61
+ // without window context (chat / demo embeds). See `compare-align.ts`.
62
+ const compareAligner = computed(() => {
63
+ const offset = compareOffsetDays ?? (prevValue?.length ? anchorOffsetDays(value, prevValue) : null)
64
+ return resolveCompareAligner(compareMode, offset)
65
+ })
66
+ const calendarValue = computed(() => calendarChartRows(value, dateRange))
67
+ // Unovis Area converts missing values to zero. Fill only observed calendars.
68
+ const clicksComplete = computed(() => calendarValue.value.every(row => Number.isFinite(row.clicks)))
69
+ const impressionsComplete = computed(() => calendarValue.value.every(row => Number.isFinite(row.impressions)))
70
+ const mergedValue = computed<MergedRow[]>(() => alignPrev(calendarValue.value, prevValue, compareAligner.value))
71
+
72
+ const hasComparison = computed(() => mergedValue.value.some(r => r.prev))
73
+
74
+ // NaN y-values break the cubic curve cleanly (d3-shape's default `defined` skips them),
75
+ // so the dashed line only renders across indices where prev data is present.
76
+ const prevClicks = (d: MergedRow) => d.prev?.clicks ?? Number.NaN
77
+ const prevImpressions = (d: MergedRow) => d.prev?.impressions ?? Number.NaN
78
+ // Rate and rank values require impressions. Missing observations leave gaps.
79
+ function observedMetric(row: DataRow, metric: 'ctr' | 'position'): number | undefined {
80
+ const value = row[metric]
81
+ if (!(row.impressions > 0) || !Number.isFinite(value) || (metric === 'position' && value < 1))
82
+ return undefined
83
+ return value
84
+ }
85
+
86
+ const prevCtr = (d: MergedRow) => d.prev ? (observedMetric(d.prev, 'ctr') ?? Number.NaN) * 100 : Number.NaN
87
+ const prevPosition = (d: MergedRow) => d.prev ? observedMetric(d.prev, 'position') ?? Number.NaN : Number.NaN
88
+
89
+ // --- Calendar-aware tick planning ---
90
+ // The observed wrap width feeds the plan: at phone widths the span heuristics
91
+ // would crowd labels, so ticks that would collide are dropped reactively.
92
+ const chartEl = useTemplateRef<HTMLElement>('chartEl')
93
+ const { width: chartWidth } = useElementSize(chartEl)
94
+ const { tickPlan, tickFormat } = useChartTickPlan({ dates: () => calendarValue.value.map(v => v.date), width: chartWidth })
95
+
96
+ // With zero horizontal margin a centred label on an edge tick would half-clip
97
+ // outside the svg; anchor it inward instead — but only when the plan actually
98
+ // places a tick on the first/last data point (long spans often don't).
99
+ const firstTickAtEdge = computed(() => tickPlan.value.indices[0] === 0)
100
+ const lastTickAtEdge = computed(() => tickPlan.value.indices.at(-1) === calendarValue.value.length - 1)
101
+
102
+ // --- Unstable/estimated data detection ---
103
+ const unstableCutoffDate = computed(() => getGscUnstableCutoffDate())
104
+
105
+ const unstableCount = computed(() => {
106
+ if (!calendarValue.value.length)
107
+ return 0
108
+ const cutoff = unstableCutoffDate.value
109
+ let count = 0
110
+ for (let i = calendarValue.value.length - 1; i >= 0; i--) {
111
+ if ((calendarValue.value[i]?.date ?? '') > cutoff)
112
+ count++
113
+ else break
114
+ }
115
+ return count
116
+ })
117
+
118
+ // Width percentage for the unstable overlay (from right edge)
119
+ const unstableWidthPct = computed(() => {
120
+ if (!unstableCount.value || calendarValue.value.length < 2)
121
+ return 0
122
+ return Math.min(100, (unstableCount.value - 0.5) / (calendarValue.value.length - 1) * 100)
123
+ })
124
+
125
+ // Use the full (unzoomed) series for y-domain calcs when provided, so zooming keeps
126
+ // the value-axis scale stable. Falls back to current value/prev when not zooming.
127
+ const allData = computed(() => {
128
+ const cur = fullValue ?? value
129
+ const prev = fullPrevValue !== undefined ? fullPrevValue : prevValue
130
+ return [...cur, ...(prev || [])]
131
+ })
132
+
133
+ // Separate domain for each metric so each uses full chart height
134
+ const clicksDomain = computed<[number, number]>(() => {
135
+ if (!allData.value.length)
136
+ return [0, 1]
137
+ const max = Math.max(...allData.value.map(d => d.clicks), 1)
138
+ return [0, max * 1.1]
139
+ })
140
+
141
+ const impressionsDomain = computed<[number, number]>(() => {
142
+ if (!allData.value.length)
143
+ return [0, 1]
144
+ const max = Math.max(...allData.value.map(d => d.impressions), 1)
145
+ return [0, max * 1.1]
146
+ })
147
+
148
+ // Use Scale for CTR and Position (they need custom ranges)
149
+ const ctrScale = computed(() => {
150
+ const ctrs = allData.value.flatMap(d => observedMetric(d, 'ctr') == null ? [] : [d.ctr * 100])
151
+ const min = ctrs.length ? Math.min(...ctrs) : 0
152
+ const max = ctrs.length ? Math.max(...ctrs) : 10
153
+ const padding = (max - min) * 0.1 || 1
154
+ return Scale.scaleLinear()
155
+ .domain([Math.max(0, min - padding), max + padding])
156
+ .range([chartInnerHeight.value, 0])
157
+ })
158
+
159
+ // Position scale inverted: lower position = higher on chart
160
+ const positionScale = computed(() => {
161
+ const positions = allData.value.flatMap(d => observedMetric(d, 'position') == null ? [] : [d.position])
162
+ const min = positions.length ? Math.min(...positions) : 1
163
+ const max = positions.length ? Math.max(...positions) : 100
164
+ const padding = (max - min) * 0.1 || 1
165
+ return Scale.scaleLinear()
166
+ .domain([max + padding, Math.max(1, min - padding)])
167
+ .range([chartInnerHeight.value, 0]) // inverted: high position = low on chart
168
+ })
169
+
170
+ // Force re-mount all containers when data changes (date range switch)
171
+ // Use length + first/last date to catch same-length but different-range transitions
172
+ const chartKey = computed(() => {
173
+ const len = calendarValue.value.length
174
+ const first = calendarValue.value[0]?.date ?? ''
175
+ const last = calendarValue.value[len - 1]?.date ?? ''
176
+ return `${len}-${first}-${last}`
177
+ })
178
+
179
+ // Accessors
180
+ const calendarStart = computed(() => toUtcDay(calendarValue.value[0]?.date ?? '1970-01-01'))
181
+ const x = (d: DataRow) => (toUtcDay(d.date) - calendarStart.value) / 86_400_000
182
+ const clicks = (d: DataRow) => d.clicks
183
+ const impressions = (d: DataRow) => d.impressions
184
+ const ctr = (d: DataRow) => (observedMetric(d, 'ctr') ?? Number.NaN) * 100
185
+ const position = (d: DataRow) => observedMetric(d, 'position') ?? Number.NaN
186
+
187
+ // Keep observed provisional values distinct from the solid stable segment.
188
+ // Both segments share the cutoff point so adjacent observations connect;
189
+ // calendar NaNs still break either line instead of inventing a zero or bridge.
190
+ const stableMetric = (metric: (row: DataRow) => number) => (row: DataRow) => row.date <= unstableCutoffDate.value ? metric(row) : Number.NaN
191
+ const provisionalMetric = (metric: (row: DataRow) => number) => (row: DataRow) => row.date >= unstableCutoffDate.value ? metric(row) : Number.NaN
192
+ const stableClicks = stableMetric(clicks)
193
+ const stableImpressions = stableMetric(impressions)
194
+ const stableCtr = stableMetric(ctr)
195
+ const stablePosition = stableMetric(position)
196
+ const provisionalClicks = provisionalMetric(clicks)
197
+ const provisionalImpressions = provisionalMetric(impressions)
198
+ const provisionalCtr = provisionalMetric(ctr)
199
+ const provisionalPosition = provisionalMetric(position)
200
+
201
+ const isolatedClicks = computed(() => isolatedChartValue(mergedValue.value, clicks))
202
+ const isolatedPrevClicks = computed(() => isolatedChartValue(mergedValue.value, prevClicks))
203
+ const isolatedImpressions = computed(() => isolatedChartValue(mergedValue.value, impressions))
204
+ const isolatedPrevImpressions = computed(() => isolatedChartValue(mergedValue.value, prevImpressions))
205
+ const isolatedCtr = computed(() => isolatedChartValue(mergedValue.value, ctr))
206
+ const isolatedPrevCtr = computed(() => isolatedChartValue(mergedValue.value, prevCtr))
207
+ const isolatedPosition = computed(() => isolatedChartValue(mergedValue.value, position))
208
+ const isolatedPrevPosition = computed(() => isolatedChartValue(mergedValue.value, prevPosition))
209
+
210
+ const metricLabels = { clicks: 'Clicks', impressions: 'Impressions', ctr: 'CTR', position: 'Avg. position' }
211
+ type Metric = keyof typeof metricLabels
212
+ const visibleMetrics = computed(() => (columns ?? []).filter((metric): metric is Metric => Object.hasOwn(metricLabels, metric)))
213
+ const accessibleRows = computed(() => mergedValue.value.flatMap((row) => {
214
+ const current = { period: 'Current period', value: row }
215
+ return row.prev ? [current, { period: 'Previous period', value: row.prev }] : [current]
216
+ }))
217
+ function accessibleValue(row: DataRow, metric: Metric): string {
218
+ const value = metric === 'ctr' || metric === 'position' ? observedMetric(row, metric) : row[metric]
219
+ if (value == null || !Number.isFinite(value))
220
+ return '—'
221
+ if (metric === 'ctr')
222
+ return `${(value * 100).toFixed(2)}%`
223
+ if (metric === 'position')
224
+ return value.toFixed(1)
225
+ return formatGroupedNumber(value)
226
+ }
227
+ </script>
228
+
229
+ <template>
230
+ <div
231
+ ref="chartEl"
232
+ data-ui="ProGraphGsc"
233
+ class="gsc-chart"
234
+ :class="{ 'tick-edge-first': firstTickAtEdge, 'tick-edge-last': lastTickAtEdge }"
235
+ :aria-busy="loading || undefined"
236
+ :style="{ height: `${chartHeight}px` }"
237
+ >
238
+ <!-- Read failed. Shown ahead of the skeleton and the empty copy: a site that
239
+ errored is neither loading nor freshly connected, and saying otherwise
240
+ sends the user off waiting for a sync that already finished. -->
241
+ <div
242
+ v-if="chartFailure"
243
+ class="flex flex-col items-center justify-center h-full text-center gap-1"
244
+ role="status"
245
+ >
246
+ <UiIcon name="alert-triangle" class="size-4 text-dimmed" aria-hidden="true" />
247
+ <p class="text-sm text-muted">
248
+ {{ chartFailure._tag === 'property-unavailable' ? 'Search Console property not found.' : chartFailure.message }}
249
+ </p>
250
+ <p class="text-xs text-dimmed">
251
+ {{ chartFailure._tag === 'property-unavailable' ? 'Review the connected property for this site.' : 'Your existing data is safe. This is a read failure, not data loss.' }}
252
+ </p>
253
+ <UiButton
254
+ v-if="chartFailure._tag === 'property-unavailable' && connectionTo"
255
+ size="xs"
256
+ purpose="quiet"
257
+ :to="connectionTo"
258
+ >
259
+ Review connection
260
+ </UiButton>
261
+ </div>
262
+
263
+ <!-- Loading skeleton -->
264
+ <div v-else-if="loading" class="loading-skeleton">
265
+ <div class="flex-1 flex items-end gap-1">
266
+ <div v-for="i in 30" :key="i" class="flex-1 h-full flex">
267
+ <UiSkeleton type="bar" :index="i" />
268
+ </div>
269
+ </div>
270
+ <div class="flex justify-between mt-3">
271
+ <UiSkeleton v-for="i in 5" :key="i" class="h-3" :base="44" :range="8" />
272
+ </div>
273
+ </div>
274
+
275
+ <!-- Not enough data for chart (need >=2 points for lines) -->
276
+ <div v-else-if="value.length < 2" class="flex flex-col items-center justify-center h-full text-center gap-1">
277
+ <!-- Deliberately does NOT claim a sync is pending. The genuine
278
+ not-connected / still-syncing case is caught upstream by the page's
279
+ sample-data overlay, which actually knows the lifecycle state; this
280
+ branch only knows the window came back empty. Asserting "~5 min after
281
+ connect" here told a user with ten days of synced data to go wait. -->
282
+ <p class="text-sm text-muted">
283
+ {{ value.length === 0 ? 'No search impressions in this period.' : 'First day of GSC data is in; trend renders once we have 2+' }}
284
+ </p>
285
+ <p class="text-xs text-dimmed">
286
+ {{ value.length === 0 ? 'Try a wider date range.' : 'Check back tomorrow for the trend line.' }}
287
+ </p>
288
+ </div>
289
+
290
+ <ClientOnly v-else>
291
+ <!-- Estimated data region indicator (discovered via hover tooltip) -->
292
+ <div
293
+ v-if="unstableWidthPct > 0"
294
+ class="estimated-region"
295
+ :style="{ width: `${unstableWidthPct}%`, bottom: `${margin.bottom}px` }"
296
+ >
297
+ <div class="estimated-tint" />
298
+ <div class="estimated-separator" />
299
+ </div>
300
+
301
+ <!-- Layer 1: Impressions -->
302
+ <VisXYContainer
303
+ v-if="columns?.includes('impressions')"
304
+ :key="`impressions-${chartKey}`"
305
+ :height="chartHeight"
306
+ :data="mergedValue"
307
+ :svg-defs="svgDefs"
308
+ :margin="margin"
309
+ :auto-margin="false"
310
+ :bleed="plotBleed"
311
+ :clip-path-extend="4"
312
+ class="chart-layer"
313
+ aria-hidden="true"
314
+ :y-domain="impressionsDomain"
315
+ >
316
+ <VisLine
317
+ v-if="hasComparison"
318
+ curve-type="monotoneX"
319
+ :x="x"
320
+ :y="prevImpressions"
321
+ :color="gscColors.impressions.prev"
322
+ :line-width="1.5"
323
+ :line-dash-array="[6, 4]"
324
+ />
325
+ <VisArea
326
+ v-if="impressionsComplete"
327
+ :color="gscColors.impressions.area"
328
+ curve-type="monotoneX"
329
+ :x="x"
330
+ :y="impressions"
331
+ />
332
+ <VisLine
333
+ curve-type="monotoneX"
334
+ :x="x"
335
+ :y="stableImpressions"
336
+ :color="gscColors.impressions.line"
337
+ :line-width="2"
338
+ />
339
+ <VisLine
340
+ v-if="unstableCount > 0"
341
+ curve-type="monotoneX"
342
+ :x="x"
343
+ :y="provisionalImpressions"
344
+ :color="gscColors.impressions.line"
345
+ :line-width="2"
346
+ :line-dash-array="[2, 3]"
347
+ />
348
+ <VisScatter v-if="hasComparison" :x="x" :y="isolatedPrevImpressions" :color="gscColors.impressions.prev" :size="6" />
349
+ <VisScatter :x="x" :y="isolatedImpressions" :color="gscColors.impressions.line" :size="6" />
350
+ </VisXYContainer>
351
+
352
+ <!-- Layer 2: Clicks -->
353
+ <VisXYContainer
354
+ v-if="columns?.includes('clicks')"
355
+ :key="`clicks-${chartKey}`"
356
+ :height="chartHeight"
357
+ :data="mergedValue"
358
+ :svg-defs="svgDefs"
359
+ :margin="margin"
360
+ :auto-margin="false"
361
+ :bleed="plotBleed"
362
+ :clip-path-extend="4"
363
+ class="chart-layer"
364
+ aria-hidden="true"
365
+ :y-domain="clicksDomain"
366
+ >
367
+ <VisLine
368
+ v-if="hasComparison"
369
+ curve-type="monotoneX"
370
+ :x="x"
371
+ :y="prevClicks"
372
+ :color="gscColors.clicks.prev"
373
+ :line-width="1.5"
374
+ :line-dash-array="[6, 4]"
375
+ />
376
+ <VisArea
377
+ v-if="clicksComplete"
378
+ :color="gscColors.clicks.area"
379
+ curve-type="monotoneX"
380
+ :x="x"
381
+ :y="clicks"
382
+ />
383
+ <VisLine
384
+ curve-type="monotoneX"
385
+ :x="x"
386
+ :y="stableClicks"
387
+ :color="gscColors.clicks.line"
388
+ :line-width="2"
389
+ />
390
+ <VisLine
391
+ v-if="unstableCount > 0"
392
+ curve-type="monotoneX"
393
+ :x="x"
394
+ :y="provisionalClicks"
395
+ :color="gscColors.clicks.line"
396
+ :line-width="2"
397
+ :line-dash-array="[2, 3]"
398
+ />
399
+ <VisScatter v-if="hasComparison" :x="x" :y="isolatedPrevClicks" :color="gscColors.clicks.prev" :size="6" />
400
+ <VisScatter :x="x" :y="isolatedClicks" :color="gscColors.clicks.line" :size="6" />
401
+ </VisXYContainer>
402
+
403
+ <!-- Layer 3: CTR metric -->
404
+ <VisXYContainer
405
+ v-if="columns?.includes('ctr')"
406
+ :key="`ctr-${chartKey}`"
407
+ :height="chartHeight"
408
+ :data="mergedValue"
409
+ :margin="margin"
410
+ :auto-margin="false"
411
+ :bleed="plotBleed"
412
+ :clip-path-extend="4"
413
+ class="chart-layer"
414
+ aria-hidden="true"
415
+ >
416
+ <VisLine
417
+ v-if="hasComparison"
418
+ curve-type="monotoneX"
419
+ :x="x"
420
+ :y="prevCtr"
421
+ :y-scale="ctrScale"
422
+ :color="gscColors.ctr.prev"
423
+ :line-width="1.5"
424
+ :line-dash-array="[6, 4]"
425
+ />
426
+ <VisLine
427
+ curve-type="monotoneX"
428
+ :x="x"
429
+ :y="stableCtr"
430
+ :y-scale="ctrScale"
431
+ :color="gscColors.ctr.line"
432
+ :line-width="2"
433
+ />
434
+ <VisLine
435
+ v-if="unstableCount > 0"
436
+ curve-type="monotoneX"
437
+ :x="x"
438
+ :y="provisionalCtr"
439
+ :y-scale="ctrScale"
440
+ :color="gscColors.ctr.line"
441
+ :line-width="2"
442
+ :line-dash-array="[2, 3]"
443
+ />
444
+ <VisScatter v-if="hasComparison" :x="x" :y="isolatedPrevCtr" :y-scale="ctrScale" :color="gscColors.ctr.prev" :size="6" />
445
+ <VisScatter :x="x" :y="isolatedCtr" :y-scale="ctrScale" :color="gscColors.ctr.line" :size="6" />
446
+ </VisXYContainer>
447
+
448
+ <!-- Layer 4: Position metric (inverted scale) -->
449
+ <VisXYContainer
450
+ v-if="columns?.includes('position')"
451
+ :key="`position-${chartKey}`"
452
+ :height="chartHeight"
453
+ :data="mergedValue"
454
+ :margin="margin"
455
+ :auto-margin="false"
456
+ :bleed="plotBleed"
457
+ :clip-path-extend="4"
458
+ class="chart-layer"
459
+ aria-hidden="true"
460
+ >
461
+ <VisLine
462
+ v-if="hasComparison"
463
+ curve-type="monotoneX"
464
+ :x="x"
465
+ :y="prevPosition"
466
+ :y-scale="positionScale"
467
+ :color="gscColors.position.prev"
468
+ :line-width="1.5"
469
+ :line-dash-array="[6, 4]"
470
+ />
471
+ <VisLine
472
+ curve-type="monotoneX"
473
+ :x="x"
474
+ :y="stablePosition"
475
+ :y-scale="positionScale"
476
+ :color="gscColors.position.line"
477
+ :line-width="2"
478
+ />
479
+ <VisLine
480
+ v-if="unstableCount > 0"
481
+ curve-type="monotoneX"
482
+ :x="x"
483
+ :y="provisionalPosition"
484
+ :y-scale="positionScale"
485
+ :color="gscColors.position.line"
486
+ :line-width="2"
487
+ :line-dash-array="[2, 3]"
488
+ />
489
+ <VisScatter v-if="hasComparison" :x="x" :y="isolatedPrevPosition" :y-scale="positionScale" :color="gscColors.position.prev" :size="6" />
490
+ <VisScatter :x="x" :y="isolatedPosition" :y-scale="positionScale" :color="gscColors.position.line" :size="6" />
491
+ </VisXYContainer>
492
+
493
+ <!-- Layer 5: X-Axis + Crosshair (topmost, captures all pointer events) -->
494
+ <VisXYContainer
495
+ :key="`interactive-${chartKey}`"
496
+ :height="chartHeight"
497
+ :data="mergedValue"
498
+ :margin="margin"
499
+ :auto-margin="false"
500
+ :bleed="plotBleed"
501
+ :clip-path-extend="4"
502
+ class="chart-layer chart-layer--interactive"
503
+ aria-hidden="true"
504
+ >
505
+ <!-- Invisible line so the crosshair has data points to snap to -->
506
+ <VisLine :x="x" :y="clicks" color="transparent" :line-width="0" />
507
+ <VisAxis
508
+ type="x"
509
+ :tick-line="false"
510
+ :grid-line="false"
511
+ :domain-line="false"
512
+ :tick-values="tickPlan.indices"
513
+ :tick-format="tickFormat"
514
+ :tick-text-align="TextAlign.Center"
515
+ tick-text-font-size="11px"
516
+ tick-text-color="var(--ui-text-dimmed)"
517
+ />
518
+ <!-- VisCrosshair renders only the snap-to-point indicator line; the
519
+ tooltip is owned by the parent card (driven by pointermove against
520
+ the wrap div, not by this template callback). VisTooltip is omitted
521
+ because Unovis portals it to document.body and the empty box leaks
522
+ through as a second tooltip on top of UiChartTooltip. -->
523
+ <VisCrosshair :x="x" :y="clicks" color="none" :template="() => ''" />
524
+ </VisXYContainer>
525
+
526
+ <template #fallback>
527
+ <div class="loading-skeleton">
528
+ <div class="flex-1 flex items-end gap-1">
529
+ <div v-for="i in 30" :key="i" class="flex-1">
530
+ <UiSkeleton type="bar" :index="i" />
531
+ </div>
532
+ </div>
533
+ <div class="flex justify-between mt-3">
534
+ <UiSkeleton v-for="i in 5" :key="i" class="h-3" :base="44" :range="8" />
535
+ </div>
536
+ </div>
537
+ </template>
538
+ </ClientOnly>
539
+ <div v-if="!loading && value.length >= 2" class="sr-only">
540
+ <!-- Screen reader equivalent of the visual chart, permitted raw table exception. -->
541
+ <!-- eslint-disable-next-line vue/no-restricted-syntax -->
542
+ <table>
543
+ <caption>Search console performance chart</caption>
544
+ <thead>
545
+ <tr>
546
+ <th scope="col">
547
+ Date
548
+ </th>
549
+ <th scope="col">
550
+ Period
551
+ </th>
552
+ <th v-for="metric in visibleMetrics" :key="metric" scope="col">
553
+ {{ metricLabels[metric] }}
554
+ </th>
555
+ </tr>
556
+ </thead>
557
+ <tbody>
558
+ <tr v-for="row in accessibleRows" :key="`${row.period}-${row.value.date}`">
559
+ <th scope="row">
560
+ {{ row.value.date }}
561
+ </th>
562
+ <td>{{ row.period }}</td>
563
+ <td v-for="metric in visibleMetrics" :key="metric">
564
+ {{ accessibleValue(row.value, metric) }}
565
+ </td>
566
+ </tr>
567
+ </tbody>
568
+ </table>
569
+ </div>
570
+ </div>
571
+ </template>
572
+
573
+ <style scoped>
574
+ [data-ui="ProGraphGsc"] :deep(.unovis-area-group path) {
575
+ stroke: none;
576
+ }
577
+
578
+ .gsc-chart {
579
+ display: grid;
580
+ /* minmax(0, …): a bare 1fr track floors at the stacked SVGs' width, so the
581
+ chart grew with the window but never shrank back and pushed the page into
582
+ a horizontal scroll. */
583
+ grid-template-columns: minmax(0, 1fr);
584
+ position: relative;
585
+ }
586
+
587
+ .gsc-chart .chart-layer,
588
+ .gsc-chart .loading-skeleton {
589
+ grid-column-start: 1;
590
+ grid-row-start: 1;
591
+ }
592
+
593
+ /* Data layers are visual only — no pointer events */
594
+ .gsc-chart .chart-layer {
595
+ pointer-events: none;
596
+ }
597
+
598
+ /* Only the crosshair/axis layer captures mouse interaction */
599
+ .gsc-chart .chart-layer--interactive {
600
+ pointer-events: auto;
601
+ }
602
+
603
+ /* Subtle crosshair line, no circle markers */
604
+ .gsc-chart .chart-layer--interactive {
605
+ --vis-crosshair-line-stroke-color: var(--ui-border-accented);
606
+ --vis-crosshair-line-stroke-opacity: 0.6;
607
+ }
608
+
609
+ /* Hide the empty tooltip container (we render tooltip in the parent) */
610
+ .gsc-chart .chart-layer--interactive :deep(.unovis-tooltip) {
611
+ display: none;
612
+ }
613
+
614
+ /* Zero horizontal margin: anchor edge tick labels inward so they don't clip at
615
+ the svg boundary. Unovis sets text-anchor as an SVG attribute, which CSS
616
+ outranks; d3-axis keeps tick <g>s DOM-ordered by value, so first/last-of-type
617
+ are the leftmost/rightmost ticks. */
618
+ .gsc-chart.tick-edge-first :deep(g.tick:first-of-type > text) {
619
+ text-anchor: start;
620
+ }
621
+
622
+ .gsc-chart.tick-edge-last :deep(g.tick:last-of-type > text) {
623
+ text-anchor: end;
624
+ }
625
+
626
+ /* Estimated data region */
627
+ .estimated-region {
628
+ position: absolute;
629
+ top: 0;
630
+ right: 0;
631
+ pointer-events: none;
632
+ z-index: 5;
633
+ }
634
+
635
+ .estimated-tint {
636
+ position: absolute;
637
+ inset: 0;
638
+ background: linear-gradient(
639
+ to right,
640
+ transparent,
641
+ color-mix(in srgb, var(--ui-bg) 60%, transparent) 40%
642
+ );
643
+ }
644
+
645
+ .estimated-separator {
646
+ position: absolute;
647
+ left: 0;
648
+ top: 0;
649
+ bottom: 0;
650
+ width: 1px;
651
+ background: repeating-linear-gradient(
652
+ to bottom,
653
+ var(--ui-text-dimmed) 0,
654
+ var(--ui-text-dimmed) 3px,
655
+ transparent 3px,
656
+ transparent 7px
657
+ );
658
+ opacity: 0.35;
659
+ }
660
+
661
+ .loading-skeleton {
662
+ display: flex;
663
+ flex-direction: column;
664
+ justify-content: end;
665
+ padding-bottom: 2rem;
666
+ padding-left: 0.5rem;
667
+ padding-right: 0.5rem;
668
+ }
669
+ </style>
@@ -0,0 +1,52 @@
1
+ import { formatPercent } from '@nuxtseo/design-system/app/composables/formatting'
2
+
3
+ export type GscTrendDisplay
4
+ = | { _tag: 'none' }
5
+ | { _tag: 'from_zero', label: string, title: string }
6
+ | { _tag: 'low_volume', label: string, title: string }
7
+ | { _tag: 'percent', label: string, title: string }
8
+
9
+ interface GscTrendInput {
10
+ current: number
11
+ previous: number | null
12
+ changePercent: number | null
13
+ volumeFloor?: number
14
+ volumeLabel?: string
15
+ }
16
+
17
+ export function resolveGscTrendDisplay({
18
+ current,
19
+ previous,
20
+ changePercent,
21
+ volumeFloor = 0,
22
+ volumeLabel = 'clicks',
23
+ }: GscTrendInput): GscTrendDisplay {
24
+ if (previous == null)
25
+ return { _tag: 'none' }
26
+
27
+ if (previous === 0 && current > 0) {
28
+ return {
29
+ _tag: 'from_zero',
30
+ label: 'from 0',
31
+ title: 'No comparison value in the previous period',
32
+ }
33
+ }
34
+
35
+ if (changePercent == null || changePercent === 0)
36
+ return { _tag: 'none' }
37
+
38
+ if (volumeFloor > 0 && Math.max(Math.abs(current), Math.abs(previous)) < volumeFloor) {
39
+ return {
40
+ _tag: 'low_volume',
41
+ label: 'low volume',
42
+ title: `Percentage hidden below ${volumeFloor} ${volumeLabel}`,
43
+ }
44
+ }
45
+
46
+ const label = formatPercent(changePercent)
47
+ return {
48
+ _tag: 'percent',
49
+ label,
50
+ title: `${changePercent > 0 ? 'Up' : 'Down'} ${formatPercent(Math.abs(changePercent)).replace('+', '')} from the previous period`,
51
+ }
52
+ }
package/nuxt.config.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { defineNuxtConfig } from 'nuxt/config'
2
+
3
+ export default defineNuxtConfig({
4
+ extends: ['@nuxtseo/design-system'],
5
+ imports: { autoImport: false },
6
+ })
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@nuxtseo/pro-search",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "0.1.10",
5
+ "description": "Shared Search Console and Webmaster Tools views for Nuxt dashboards.",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./nuxt.config.ts",
9
+ "./components/*.vue": "./app/components/*.vue",
10
+ "./components/*": "./app/components/*.ts",
11
+ "./shared/*": "./shared/*.ts",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "main": "./nuxt.config.ts",
15
+ "files": [
16
+ "app",
17
+ "nuxt.config.ts",
18
+ "shared"
19
+ ],
20
+ "peerDependencies": {
21
+ "@gscdump/contracts": "^7.16.0",
22
+ "@gscdump/sdk": "^7.16.0",
23
+ "@nuxtseo/design-system": "^0.1.10",
24
+ "@vueuse/core": "^14.0.0 || ^15.0.0",
25
+ "nuxt": "^4.6.0",
26
+ "vue": "^3.5.0"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "@unovis/ts": "^1.6.7",
33
+ "@unovis/vue": "^1.6.7"
34
+ },
35
+ "devDependencies": {
36
+ "@gscdump/contracts": "7.17.0",
37
+ "@gscdump/sdk": "7.17.0",
38
+ "@nuxtseo/design-system": "0.1.10",
39
+ "@vueuse/core": "^14.4.0",
40
+ "nuxt": "4.6.1",
41
+ "site-typecheck": "0.0.0",
42
+ "vue": "^3.5.43"
43
+ },
44
+ "scripts": {
45
+ "nuxt:prepare": "nuxt prepare",
46
+ "typecheck": "nuxt prepare && site-typecheck -b --noEmit --force"
47
+ }
6
48
  }
@@ -0,0 +1,31 @@
1
+ import type { BingDataV1 } from '@gscdump/contracts/v1/http'
2
+
3
+ export type BingEntityKind = 'pages' | 'keywords'
4
+ export const BING_PERFORMANCE_PAGE_SIZE = 10
5
+
6
+ const bingNumberFormat = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 })
7
+ const bingCtrFormat = new Intl.NumberFormat('en-US', { style: 'percent', minimumFractionDigits: 1, maximumFractionDigits: 1 })
8
+ const bingReportingDayFormat = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
9
+
10
+ export function formatBingNumber(value: number): string {
11
+ return bingNumberFormat.format(value)
12
+ }
13
+
14
+ export function formatBingCtr(value: number): string {
15
+ return bingCtrFormat.format(value)
16
+ }
17
+
18
+ export function formatBingReportingDay(day: string): string {
19
+ return bingReportingDayFormat.format(new Date(`${day}T00:00:00Z`))
20
+ }
21
+
22
+ export function bingTrafficTotals(rows: Extract<BingDataV1, { dataset: 'traffic' }>['rows']) {
23
+ const totals = rows.reduce((sum, row) => ({
24
+ clicks: sum.clicks + row.clicks,
25
+ impressions: sum.impressions + row.impressions,
26
+ }), { clicks: 0, impressions: 0 })
27
+ return {
28
+ ...totals,
29
+ ctr: totals.impressions === 0 ? 0 : totals.clicks / totals.impressions,
30
+ }
31
+ }
@@ -0,0 +1,123 @@
1
+ import type { CompareMode } from '@gscdump/sdk/period'
2
+
3
+ // Aligning a comparison overlay means pairing each current-period day with its
4
+ // counterpart in the compare window. The right counterpart depends on the
5
+ // compare mode:
6
+ // - 'previous' → the SAME ordinal day of the preceding window, i.e. a fixed
7
+ // whole-day offset back (period length). Calendar-day matching is wrong here
8
+ // (the prev window is days, not a year, away).
9
+ // - 'year' → the SAME calendar day one year earlier (Feb 15 → Feb 15), which a
10
+ // fixed day offset can't express exactly across a leap boundary.
11
+ // Deriving the offset from the WINDOW DEFINITION (not the data) keeps alignment
12
+ // correct even when the compare window's most recent day has no rows.
13
+
14
+ const DAY_MS = 86_400_000
15
+
16
+ export function toUtcDay(s: string): number {
17
+ const [y = 0, m = 1, d = 1] = s.split('-').map(Number)
18
+ return Date.UTC(y, m - 1, d)
19
+ }
20
+
21
+ export function fromUtcDay(ms: number): string {
22
+ const dt = new Date(ms)
23
+ return `${dt.getUTCFullYear()}-${String(dt.getUTCMonth() + 1).padStart(2, '0')}-${String(dt.getUTCDate()).padStart(2, '0')}`
24
+ }
25
+
26
+ /** Maps a current ISO date (`YYYY-MM-DD`) to its compare-period counterpart. */
27
+ export type CompareAligner = (currentDate: string) => string
28
+
29
+ /** Same calendar day one year earlier — exact for year-over-year (no leap drift). */
30
+ export function calendarYearAligner(): CompareAligner {
31
+ return (date) => {
32
+ const [y, m, d] = date.split('-')
33
+ return `${Number(y) - 1}-${m}-${d}`
34
+ }
35
+ }
36
+
37
+ /** Fixed whole-day shift back — correct for the immediately-preceding period. */
38
+ export function offsetAligner(offsetDays: number): CompareAligner {
39
+ return date => fromUtcDay(toUtcDay(date) - offsetDays * DAY_MS)
40
+ }
41
+
42
+ /**
43
+ * Pick the aligner for a compare mode. `'year'` uses calendar matching;
44
+ * everything else uses the fixed `offsetDays`. Returns `null` when there is no
45
+ * usable strategy (no comparison, or `'previous'` with an unknown offset), in
46
+ * which case `alignPrev` leaves rows un-paired.
47
+ */
48
+ export function resolveCompareAligner(mode: CompareMode | undefined, offsetDays: number | null): CompareAligner | null {
49
+ if (mode === 'year')
50
+ return calendarYearAligner()
51
+ if (offsetDays != null)
52
+ return offsetAligner(offsetDays)
53
+ return null
54
+ }
55
+
56
+ /**
57
+ * Fallback offset when no window definition is available: anchor on the most
58
+ * recent day of each series (most likely populated; `stableData` lands the end
59
+ * on a complete day). Less robust than the window-derived offset — a compare
60
+ * window whose last day has no rows skews it — so prefer `computeCompareOffsetDays`.
61
+ */
62
+ export function anchorOffsetDays(current: { date: string }[], prev: { date: string }[]): number | null {
63
+ const lastCur = current.at(-1)
64
+ const lastPrev = prev.at(-1)
65
+ if (!lastCur || !lastPrev)
66
+ return null
67
+ return Math.round((toUtcDay(lastCur.date) - toUtcDay(lastPrev.date)) / DAY_MS)
68
+ }
69
+
70
+ /**
71
+ * Merge prev rows onto current rows by date, using `aligner` to find each
72
+ * current day's counterpart. A current day with no matching prev row is left
73
+ * un-paired (the overlay simply has no point there — correct for gaps).
74
+ */
75
+ export function alignPrev<C extends { date: string }, P extends { date: string }>(
76
+ current: C[],
77
+ prev: P[] | null | undefined,
78
+ aligner: CompareAligner | null,
79
+ ): Array<C & { prev?: P }> {
80
+ if (!current.length)
81
+ return []
82
+ if (!prev?.length || !aligner)
83
+ return current.slice()
84
+ const byDate = new Map<string, P>()
85
+ for (const row of prev) byDate.set(row.date, row)
86
+ return current.map((row) => {
87
+ const match = byDate.get(aligner(row.date))
88
+ return match ? { ...row, prev: match } : row
89
+ })
90
+ }
91
+
92
+ interface CalendarChartRow {
93
+ date: string
94
+ clicks: number
95
+ impressions: number
96
+ position: number
97
+ ctr: number
98
+ }
99
+
100
+ /** Keep elapsed reporting days without inventing observations. */
101
+ export function calendarChartRows(rows: readonly CalendarChartRow[], dateRange?: { start: string, end: string }): CalendarChartRow[] {
102
+ if (!rows.length)
103
+ return []
104
+ const byDate = new Map(rows.map(row => [row.date, row]))
105
+ const dates = [...byDate.keys()].sort()
106
+ const start = toUtcDay(dateRange?.start ?? dates[0]!)
107
+ const end = toUtcDay(dateRange?.end ?? dates.at(-1)!)
108
+ const days = Math.round((end - start) / DAY_MS) + 1
109
+ return Array.from({ length: days }, (_, index) => {
110
+ const date = fromUtcDay(start + index * DAY_MS)
111
+ return byDate.get(date) ?? { date, clicks: Number.NaN, impressions: Number.NaN, position: Number.NaN, ctr: Number.NaN }
112
+ })
113
+ }
114
+
115
+ /** Scatter accessors receive a series index, so identify isolated days by date. */
116
+ export function isolatedChartValue<T extends { date: string }>(rows: readonly T[], value: (row: T) => number): (row: T) => number {
117
+ const values = rows.map(value)
118
+ const dates = new Set(rows.flatMap((row, index) => Number.isFinite(values[index])
119
+ && !Number.isFinite(values[index - 1]) && !Number.isFinite(values[index + 1])
120
+ ? [row.date]
121
+ : []))
122
+ return row => dates.has(row.date) ? value(row) : Number.NaN
123
+ }
@@ -0,0 +1,14 @@
1
+ export const SEARCH_CONSOLE = {
2
+ label: 'Search Console',
3
+ icon: 'google',
4
+ } as const
5
+
6
+ export const WEBMASTER_TOOLS = {
7
+ label: 'Webmaster Tools',
8
+ icon: 'bing',
9
+ } as const
10
+
11
+ export const WEBMASTER_TOOLS_TABS = [
12
+ { label: 'Performance', path: '' },
13
+ { label: 'Crawl', path: '/crawl' },
14
+ ] as const
@@ -0,0 +1,7 @@
1
+ export interface RankedSearchRow {
2
+ siteDomain: string
3
+ keyword?: string
4
+ label?: string
5
+ clicks: number
6
+ clicksChangePercent: number | null
7
+ }
@@ -0,0 +1,44 @@
1
+ import type { CompareMode } from '@gscdump/sdk/period'
2
+
3
+ export interface SearchConsoleTrendDay {
4
+ date: string
5
+ clicks: number
6
+ impressions: number
7
+ position: number
8
+ ctr: number
9
+ }
10
+
11
+ export type SearchConsoleTrendFailure
12
+ = | { _tag: 'property-unavailable' }
13
+ | { _tag: 'read-failed', message: string }
14
+
15
+ export interface SearchConsoleTrendProps {
16
+ value: SearchConsoleTrendDay[]
17
+ /** Requested reporting days, including unknown days at either edge. */
18
+ dateRange?: { start: string, end: string }
19
+ prevValue: SearchConsoleTrendDay[] | null
20
+ columns?: string[]
21
+ height?: number | string
22
+ /** Show loading skeleton */
23
+ loading?: boolean
24
+ /**
25
+ * Full (unzoomed) current series. When provided, y-domains are computed against this
26
+ * so zoomed views stay anchored to the full period's scale.
27
+ */
28
+ fullValue?: SearchConsoleTrendDay[]
29
+ /** Full (unzoomed) previous series, paired with fullValue. */
30
+ fullPrevValue?: SearchConsoleTrendDay[] | null
31
+ /**
32
+ * Compare mode driving overlay alignment — `'year'` matches by calendar day,
33
+ * everything else by `compareOffsetDays`.
34
+ */
35
+ compareMode?: CompareMode
36
+ /**
37
+ * Whole-day offset between the current and compare windows (authoritative,
38
+ * window-derived). When omitted, the overlay anchors on the most recent day of
39
+ * each series instead.
40
+ */
41
+ compareOffsetDays?: number | null
42
+ failure?: SearchConsoleTrendFailure | null
43
+ connectionTo?: string
44
+ }