File size: 11,665 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import { useId, useState } from 'react'
import { SwatchIcon } from '@heroicons/react/24/outline'
import {
  CENSUS_SCALES,
  bubbleFillFromT,
  bubbleRadiusPx,
  colorFromT,
  metricToDisplayT,
  type CensusScaleId,
} from '../utils/censusMapTransforms'
import type { CensusValueMode } from '../utils/censusMapValueMode'
import type { CensusChoroLegendSemantics } from '../utils/censusDataDictionary'
import { InfoHelpTrigger } from './InfoHelpTrigger'

const CHORO_LEGEND_GRADIENT_STOPS = 17

function LabelWithInfo({
  label,
  help,
  labelClassName = 'text-xs font-semibold uppercase tracking-wide text-slate-500',
}: {
  label: string
  help: string
  labelClassName?: string
}) {
  return (
    <span className="inline-flex items-center gap-1 shrink-0">
      <span className={labelClassName}>{label}</span>
      <InfoHelpTrigger help={help} topic={label} align="left" />
    </span>
  )
}

export function ChoroplethLegend({
  min,
  max,
  scale,
  format,
  valueMode = 'raw',
  extentPoolsAllVintages = false,
  metricHelp,
  semantics,
  letterGradeLegend,
  compact = false,
}: {
  compact?: boolean
  min: number
  max: number
  scale: CensusScaleId
  format: (v: number) => string
  valueMode?: CensusValueMode
  extentPoolsAllVintages?: boolean
  metricHelp?: string
  semantics?: CensusChoroLegendSemantics | null
  letterGradeLegend?: import('react').ReactNode
}) {
  const legendHelpPanelId = useId()
  const [legendHelpOpen, setLegendHelpOpen] = useState(false)
  const n = CHORO_LEGEND_GRADIENT_STOPS
  const stops = Array.from({ length: n }, (_, i) => {
    const u = n <= 1 ? 0 : i / (n - 1)
    const v = min + u * (max - min)
    const t = metricToDisplayT(v, min, max, scale) ?? 0
    return { offset: `${u * 100}%`, color: colorFromT(t), value: v }
  })
  const tickUs = [0, 0.25, 0.5, 0.75, 1] as const
  const gradId = `census-ramp-${scale}-${Math.round(min)}-${Math.round(max)}`
  const legendInfoBody = [
    'Legend maps the displayed value to color using the selected transform. When multi-year data is loaded, low/high can be pooled across years so colors stay comparable as you change year.',
    metricHelp,
  ]
    .filter(Boolean)
    .join('\n\n')
  const legendFootnote = `Stops are evenly spaced in mapped value range; shading follows the selected transform (${CENSUS_SCALES.find((x) => x.id === scale)?.label ?? scale}). ${
    valueMode === 'raw'
      ? extentPoolsAllVintages
        ? 'Percentile band (~4th–96th pct.) is computed across all years in the slider when multi-year trend data is present, so colors stay comparable as you change year.'
        : 'Extremes use percentile clipping so outliers do not wash out the map.'
      : valueMode === 'yoy'
        ? 'Legend shows percent change vs the prior year in the slider order.'
        : 'Legend shows percent difference from the national benchmark (population-weighted state composite when available).'
  }${
    extentPoolsAllVintages && valueMode !== 'raw'
      ? ' Endpoints pool all years from trend data so the scale stays fixed while you scrub the year slider.'
      : ''
  }`
  if (compact) {
    // Phone: a slim inline gradient bar, not a card. Same stops and ticks.
    return (
      <div className="px-1" data-testid="census-legend-compact">
        <div className="flex items-center justify-between gap-2 text-[10px] font-semibold leading-tight text-slate-700">
          <span className="min-w-0 truncate">&lsaquo; {semantics?.lowEnd ?? 'Lower'}</span>
          <button
            type="button"
            className="shrink-0 rounded px-1 text-[10px] font-medium text-slate-500 underline underline-offset-2"
            aria-expanded={legendHelpOpen}
            aria-controls={legendHelpPanelId}
            onClick={() => setLegendHelpOpen((v) => !v)}
          >
            How to read
          </button>
          <span className="min-w-0 truncate text-right">{semantics?.highEnd ?? 'Higher'} &rsaquo;</span>
        </div>
        <div
          className="mt-0.5 h-2.5 w-full rounded border border-slate-300"
          style={{ background: `linear-gradient(to right, ${stops.map((x) => `${x.color} ${x.offset}`).join(', ')})` }}
          role="img"
          aria-label="Color scale from low to high"
        />
        <div className="mt-0.5 flex justify-between text-[10px] tabular-nums text-slate-600">
          {[0, 0.5, 1].map((frac) => (
            <span key={frac}>{format(min + frac * (max - min))}</span>
          ))}
        </div>
        {letterGradeLegend ? <div className="mt-1">{letterGradeLegend}</div> : null}
        {legendHelpOpen ? (
          <div
            id={legendHelpPanelId}
            className="mt-1 space-y-1.5 rounded-md border border-amber-100/90 bg-amber-50/45 px-2.5 py-2"
            role="region"
            aria-label="How to read this legend"
          >
            {semantics?.gradientHint ? (
              <p className="text-[11px] leading-snug text-slate-800">{semantics.gradientHint}</p>
            ) : null}
            <p className="whitespace-pre-wrap text-[11px] leading-snug text-slate-800">{legendInfoBody}</p>
            <p className="text-[10px] leading-snug text-slate-600">{legendFootnote}</p>
          </div>
        ) : null}
      </div>
    )
  }
  return (
    <div className="rounded-lg border border-slate-200 bg-slate-50/80 p-3 shadow-sm">
      <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-slate-600 mb-2">
        <SwatchIcon className="h-4 w-4 shrink-0" />
        {metricHelp ? (
          <LabelWithInfo label="What the colors mean" help={metricHelp} />
        ) : (
          <span>What the colors mean</span>
        )}
      </div>
      {semantics ? (
        <>
          <div className="mb-1 flex items-center justify-between gap-2 px-0.5 text-[10px] font-semibold text-slate-700">
            <span className="min-w-0 text-left leading-tight">{semantics.lowEnd}</span>
            <span className="shrink-0 text-slate-400" aria-hidden>
              ←→
            </span>
            <span className="min-w-0 text-right leading-tight">{semantics.highEnd}</span>
          </div>
          <p className="mb-2 text-[10px] leading-snug text-slate-600">{semantics.gradientHint}</p>
        </>
      ) : null}
      <svg width="100%" height="52" viewBox="0 0 260 52" preserveAspectRatio="xMidYMid meet" className="max-w-full">
        <defs>
          <linearGradient id={gradId} x1="0%" y1="0%" x2="100%" y2="0%">
            {stops.map((s, i) => (
              <stop key={i} offset={s.offset} stopColor={s.color} />
            ))}
          </linearGradient>
        </defs>
        <rect x="8" y="8" width="244" height="14" rx="3" fill={`url(#${gradId})`} stroke="#94a3b8" strokeWidth="0.5" />
        {tickUs.map((frac) => (
          <text key={frac} x={8 + frac * 244} y="44" fontSize="9" fill="#475569" textAnchor="middle">
            {format(min + frac * (max - min))}
          </text>
        ))}
      </svg>
      {letterGradeLegend ? (
        <div className="mt-2 border-t border-slate-200/90 pt-2">{letterGradeLegend}</div>
      ) : null}
      <div className="mt-2">
        <button
          type="button"
          className="inline-flex w-full items-center justify-center gap-1.5 rounded-md border border-amber-200/90 bg-amber-50/60 px-2.5 py-1.5 text-xs font-medium text-amber-950/90 shadow-sm hover:bg-amber-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#354F52] focus-visible:ring-offset-2 sm:w-auto sm:justify-start"
          aria-expanded={legendHelpOpen}
          aria-controls={legendHelpPanelId}
          onClick={() => setLegendHelpOpen((v) => !v)}
        >
          <span>How to read this legend</span>
          <span
            className={`text-[10px] text-slate-500 transition-transform ${legendHelpOpen ? 'rotate-180' : ''}`}
            aria-hidden
          >
            ▼
          </span>
        </button>
        {legendHelpOpen ? (
          <div
            id={legendHelpPanelId}
            className="mt-2 rounded-md border border-amber-100/90 bg-amber-50/45 px-2.5 py-2 space-y-2"
            role="region"
            aria-label="How to read this legend"
          >
            <p className="text-[11px] text-slate-800 leading-snug whitespace-pre-wrap">{legendInfoBody}</p>
            <p className="text-[10px] text-slate-600 leading-snug">{legendFootnote}</p>
          </div>
        ) : null}
      </div>
    </div>
  )
}

export function BubbleLegend({
  min,
  max,
  scale,
  format,
  metricHelp,
  letterGradeLegend,
}: {
  min: number
  max: number
  scale: CensusScaleId
  format: (v: number) => string
  metricHelp?: string
  letterGradeLegend?: import('react').ReactNode
}) {
  const legendHelpPanelId = useId()
  const [legendHelpOpen, setLegendHelpOpen] = useState(false)
  const refs = [0.15, 0.5, 0.88].map((u) => min + u * (max - min))
  const items = refs.map((v) => ({
    v,
    r: bubbleRadiusPx(v, min, max, scale, 4, 22),
    t: metricToDisplayT(v, min, max, scale),
    label: format(v),
  }))
  const bubbleInfoBody = [
    'Circle area encodes the mapped value; color follows the Deep Ocean ramp (steel blue → teal → deep emerald) as on the map.',
    metricHelp,
  ]
    .filter(Boolean)
    .join('\n\n')
  return (
    <div className="rounded-lg border border-slate-200 bg-slate-50/80 p-3 shadow-sm">
      <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-slate-600 mb-2">
        {metricHelp ? (
          <LabelWithInfo label="Bubble size scale" help={metricHelp} />
        ) : (
          <span>Bubble size scale</span>
        )}
      </div>
      <div className="flex items-end justify-around gap-2 px-2" style={{ height: 56 }}>
        {items.map((it, i) => (
          <div key={i} className="flex flex-col items-center gap-1">
            <div
              className="rounded-full border border-white shadow"
              style={{
                width: it.r * 2,
                height: it.r * 2,
                backgroundColor: bubbleFillFromT(it.t, 0.9),
              }}
            />
            <span className="text-[10px] text-slate-600 text-center max-w-[72px] leading-tight">{it.label}</span>
          </div>
        ))}
      </div>
      {letterGradeLegend ? (
        <div className="mt-2 border-t border-slate-200/90 pt-2">{letterGradeLegend}</div>
      ) : null}
      <div className="mt-2">
        <button
          type="button"
          className="inline-flex w-full items-center justify-center gap-1.5 rounded-md border border-amber-200/90 bg-amber-50/60 px-2.5 py-1.5 text-xs font-medium text-amber-950/90 shadow-sm hover:bg-amber-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#354F52] focus-visible:ring-offset-2 sm:w-auto sm:justify-start"
          aria-expanded={legendHelpOpen}
          aria-controls={legendHelpPanelId}
          onClick={() => setLegendHelpOpen((v) => !v)}
        >
          <span>How to read this legend</span>
          <span
            className={`text-[10px] text-slate-500 transition-transform ${legendHelpOpen ? 'rotate-180' : ''}`}
            aria-hidden
          >
            ▼
          </span>
        </button>
        {legendHelpOpen ? (
          <div
            id={legendHelpPanelId}
            className="mt-2 rounded-md border border-amber-100/90 bg-amber-50/45 px-2.5 py-2"
            role="region"
            aria-label="How to read this legend"
          >
            <p className="text-[11px] text-slate-800 leading-snug whitespace-pre-wrap">{bubbleInfoBody}</p>
          </div>
        ) : null}
      </div>
    </div>
  )
}