frappe-ui 1.0.2 → 1.1.0

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.
Files changed (96) hide show
  1. package/experimental/Calendar/calendarUtils.ts +33 -21
  2. package/experimental/MultiEmailInput/MultiEmailInput.vue +64 -12
  3. package/experimental/MultiEmailInput/types.ts +12 -3
  4. package/experimental/Stepper/StepIndicator.vue +129 -0
  5. package/experimental/Stepper/Stepper.api.md +117 -0
  6. package/experimental/Stepper/Stepper.md +95 -0
  7. package/experimental/Stepper/Stepper.vue +82 -0
  8. package/experimental/Stepper/StepperHorizontal.vue +93 -0
  9. package/experimental/Stepper/StepperVertical.vue +291 -0
  10. package/experimental/Stepper/index.ts +11 -0
  11. package/experimental/Stepper/resolve.ts +87 -0
  12. package/experimental/Stepper/types.ts +89 -0
  13. package/experimental.ts +2 -0
  14. package/package.json +1 -1
  15. package/src/charts/CalendarHeatmapChart.vue +353 -0
  16. package/src/charts/DonutChart.vue +34 -58
  17. package/src/charts/HeatmapChart.vue +26 -64
  18. package/src/charts/NumberCard.vue +62 -7
  19. package/src/charts/PercentageBarChart.vue +243 -0
  20. package/src/charts/SankeyChart.vue +14 -11
  21. package/src/charts/ScatterChart.vue +24 -20
  22. package/src/charts/axisChartCommon.ts +182 -18
  23. package/src/charts/axisFormat.ts +8 -3
  24. package/src/charts/calendarHeatmapOptions.ts +604 -0
  25. package/src/charts/colorMath.ts +26 -0
  26. package/src/charts/components/ChartContainer.vue +63 -53
  27. package/src/charts/components/ChartLegend.vue +216 -24
  28. package/src/charts/components/ChartScale.vue +85 -0
  29. package/src/charts/core/dataLabelFit.ts +45 -6
  30. package/src/charts/core/useAxisChart.ts +36 -19
  31. package/src/charts/core/useChart.ts +6 -1
  32. package/src/charts/core/usePlotKeyboard.ts +13 -2
  33. package/src/charts/docs/BarChart.md +11 -3
  34. package/src/charts/docs/CalendarHeatmapChart.api.md +165 -0
  35. package/src/charts/docs/CalendarHeatmapChart.md +33 -0
  36. package/src/charts/docs/ChartContainer.api.md +6 -0
  37. package/src/charts/docs/ChartLegend.api.md +1 -1
  38. package/src/charts/docs/ChartLegend.md +25 -3
  39. package/src/charts/docs/DonutChart.api.md +12 -0
  40. package/src/charts/docs/DonutChart.md +17 -0
  41. package/src/charts/docs/HeatmapChart.api.md +1 -1
  42. package/src/charts/docs/LineChart.md +5 -3
  43. package/src/charts/docs/NumberCard.api.md +6 -0
  44. package/src/charts/docs/NumberCard.md +6 -0
  45. package/src/charts/docs/Overview.md +13 -6
  46. package/src/charts/docs/PercentageBarChart.api.md +148 -0
  47. package/src/charts/docs/PercentageBarChart.md +42 -0
  48. package/src/charts/docs/ScatterChart.md +2 -3
  49. package/src/charts/donutChartOptions.ts +22 -130
  50. package/src/charts/format.ts +4 -1
  51. package/src/charts/heatmapOptions.ts +17 -12
  52. package/src/charts/hiddenSeries.ts +8 -3
  53. package/src/charts/index.ts +12 -0
  54. package/src/charts/legendOverflow.ts +40 -0
  55. package/src/charts/numberCardFormat.ts +19 -13
  56. package/src/charts/referenceLines.ts +2 -1
  57. package/src/charts/scatterOptions.ts +16 -3
  58. package/src/charts/seriesData.ts +8 -3
  59. package/src/charts/slices.ts +228 -0
  60. package/src/charts/tokens.ts +99 -0
  61. package/src/charts/types.ts +318 -9
  62. package/src/components/Avatar/Avatar.md +27 -2
  63. package/src/components/Avatar/Avatar.vue +29 -12
  64. package/src/components/Combobox/Combobox.vue +9 -2
  65. package/src/components/Combobox/ComboboxResults.vue +6 -1
  66. package/src/components/Combobox/utils.ts +2 -1
  67. package/src/components/Dialog/Dialog.md +3 -1
  68. package/src/components/Duration/Duration.api.md +16 -3
  69. package/src/components/Duration/Duration.md +21 -0
  70. package/src/components/Duration/Duration.vue +29 -8
  71. package/src/components/Duration/duration.ts +105 -44
  72. package/src/components/Duration/index.ts +1 -0
  73. package/src/components/Duration/types.ts +30 -1
  74. package/src/components/Menu/utils.ts +3 -2
  75. package/src/components/MultiSelect/MultiSelect.api.md +5 -0
  76. package/src/components/MultiSelect/MultiSelect.vue +34 -0
  77. package/src/components/MultiSelect/MultiSelectResults.vue +3 -4
  78. package/src/components/MultiSelect/types.ts +6 -0
  79. package/src/components/Select/Select.vue +4 -4
  80. package/src/components/Select/utils.ts +1 -0
  81. package/src/components/Switch/Switch.vue +3 -3
  82. package/src/components/shared/selection/utils.ts +8 -1
  83. package/src/data-fetching/useCall/useCall.ts +25 -26
  84. package/src/data-fetching/useFrappeFetch.ts +48 -2
  85. package/src/data-fetching/useList/useList.ts +11 -3
  86. package/src/data-fetching/utils.ts +15 -1
  87. package/src/molecules/editor/components/MediaNodeView.vue +10 -1
  88. package/src/molecules/editor/components/MediaResizeGuide.vue +71 -0
  89. package/src/molecules/editor/components/media-node-view-utils.ts +7 -0
  90. package/src/molecules/editor/composables/useNodeViewResize.ts +142 -10
  91. package/src/molecules/editor/extensions/iframe/IframeNodeView.vue +3 -1
  92. package/src/molecules/editor/useEditor.ts +12 -6
  93. package/src/utils/dialog.ts +37 -14
  94. package/tailwind/content.js +1 -0
  95. package/vite/README.md +5 -3
  96. package/vite/codeLanguages.js +41 -17
@@ -0,0 +1,604 @@
1
+ import type { EChartsCoreOption } from 'echarts/core'
2
+ import {
3
+ AXIS_LABEL_FONT_SIZE,
4
+ AXIS_LABEL_MARGIN,
5
+ CATEGORY_LABEL_GAP,
6
+ toNumber,
7
+ } from './axisChartCommon'
8
+ import { dayjs } from '#utils/dayjs'
9
+ import { estimateTextWidth } from './format'
10
+ import { interpolateRamp } from './colorMath'
11
+ import {
12
+ CELL_BORDER_WIDTH,
13
+ CELL_RADIUS,
14
+ HEATMAP_RAMP_SAMPLES,
15
+ heatmapRampStops,
16
+ hoverCellColor,
17
+ rampColor,
18
+ resolveScale,
19
+ sampleRamp,
20
+ visualMapMin,
21
+ } from './heatmapOptions'
22
+ import { CHART_FONT_FAMILY } from './measureText'
23
+ import type { ChartTokens } from './tokens'
24
+ import { mergeDeep } from './utils'
25
+ import type {
26
+ CalendarHeatmapBand,
27
+ CalendarHeatmapCell,
28
+ CalendarHeatmapChartConfig,
29
+ CalendarHeatmapDay,
30
+ CalendarHeatmapGrid,
31
+ CalendarHeatmapWeekStart,
32
+ } from './types'
33
+
34
+ export type CalendarHeatmapOptionContext = {
35
+ tokens: ChartTokens
36
+ /** Plot size in px the square cells fit into. Unset, they take a default. */
37
+ width?: number
38
+ height?: number
39
+ }
40
+
41
+ /** Where `layoutCalendar` puts the bands and the scale, in px from the plot's corner. */
42
+ export type CalendarHeatmapLayout = {
43
+ cellSize: number
44
+ /** Left edge of the bands, past the weekday and year labels. */
45
+ left: number
46
+ /** Width of the weekday labels and their margin; 0 when rows are too short for them. */
47
+ dayGutter: number
48
+ /** Top of each band's first row of cells. */
49
+ tops: number[]
50
+ /** Right edge of the widest band. */
51
+ right: number
52
+ /** Top of the scale under the last band. */
53
+ scaleTop: number
54
+ }
55
+
56
+ const DAY_MS = 24 * 60 * 60 * 1000
57
+
58
+ /** Up to this many days is one band; longer, bands of twelve months. */
59
+ const ONE_BAND_MAX_DAYS = 366
60
+
61
+ /**
62
+ * Where on the ramp the lowest day lands. The pale end is as light as the grey
63
+ * of an empty day, so a day with data, 0 included, starts past it.
64
+ */
65
+ const RAMP_FLOOR = 0.15
66
+
67
+ /** echarts' own default: past it a day reads as a tile. */
68
+ const MAX_CELL_SIZE = 20
69
+ const DEFAULT_CELL_SIZE = 12
70
+
71
+ /** Room above a band for its month labels. */
72
+ export const MONTH_LABEL_ROW = AXIS_LABEL_FONT_SIZE + AXIS_LABEL_MARGIN
73
+ const BAND_GAP = 12
74
+ const PLOT_RIGHT_PAD = 4
75
+ /** Room under the last band for the HTML scale, and the gap above it. */
76
+ const SCALE_ROW = 24
77
+ const SCALE_GAP = 8
78
+
79
+ const FIRST_DAY: Record<CalendarHeatmapWeekStart, number> = {
80
+ sunday: 0,
81
+ monday: 1,
82
+ tuesday: 2,
83
+ wednesday: 3,
84
+ thursday: 4,
85
+ friday: 5,
86
+ saturday: 6,
87
+ }
88
+
89
+ /** Rows that carry a weekday label: seven at cell height crowd into each other. */
90
+ const LABELLED_ROWS = [1, 3, 5]
91
+
92
+ /** Short month names in the dayjs locale, as the tooltip and time axes print them. */
93
+ function monthNames() {
94
+ return Array.from({ length: 12 }, (_, month) =>
95
+ dayjs(new Date(2024, month, 1)).format('MMM'),
96
+ )
97
+ }
98
+
99
+ /**
100
+ * Indexed by weekday, Sunday first, as echarts reads `dayLabel.nameMap`. Labels
101
+ * go by row, so any week start gets evenly spaced ones.
102
+ */
103
+ function dayNames(firstDay: number) {
104
+ const names = Array<string>(7).fill('')
105
+ for (const row of LABELLED_ROWS) {
106
+ const weekday = (firstDay + row) % 7
107
+ names[weekday] = dayjs(new Date(2024, 0, 7 + weekday)).format('ddd')
108
+ }
109
+ return names
110
+ }
111
+
112
+ function weekStartDay(config: Pick<CalendarHeatmapChartConfig, 'weekStart'>) {
113
+ if (config.weekStart) return FIRST_DAY[config.weekStart]
114
+ return dayjs.Ls[dayjs.locale()]?.weekStart ?? FIRST_DAY.sunday
115
+ }
116
+
117
+ const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})/
118
+
119
+ /**
120
+ * The calendar day a value names, as `YYYY-MM-DD`, or null when it names none.
121
+ *
122
+ * A string is read for the date it spells, not as an instant: `2024-03-01`
123
+ * through `new Date` is UTC midnight, which west of Greenwich is the day before.
124
+ * A `Date` is read in local time, the day it prints as.
125
+ */
126
+ export function calendarDay(value: any): string | null {
127
+ if (value instanceof Date) {
128
+ if (isNaN(value.getTime())) return null
129
+ return dayKey(value.getFullYear(), value.getMonth() + 1, value.getDate())
130
+ }
131
+ if (typeof value !== 'string') return null
132
+ const match = ISO_DAY.exec(value)
133
+ if (!match) return null
134
+ const [, year, month, day] = match.map(Number)
135
+ const parsed = new Date(Date.UTC(year, month - 1, day))
136
+ // `2024-02-30` matches the pattern and rolls over into March.
137
+ if (parsed.getUTCMonth() !== month - 1) return null
138
+ return toKey(parsed.getTime())
139
+ }
140
+
141
+ function dayKey(year: number, month: number, day: number) {
142
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
143
+ }
144
+
145
+ /** Day arithmetic runs on UTC midnights, so no daylight saving shift moves a day. */
146
+ function toTime(key: string) {
147
+ const [year, month, day] = key.split('-').map(Number)
148
+ return Date.UTC(year, month - 1, day)
149
+ }
150
+
151
+ function toKey(time: number) {
152
+ const date = new Date(time)
153
+ return dayKey(
154
+ date.getUTCFullYear(),
155
+ date.getUTCMonth() + 1,
156
+ date.getUTCDate(),
157
+ )
158
+ }
159
+
160
+ function addDays(key: string, days: number) {
161
+ return toKey(toTime(key) + days * DAY_MS)
162
+ }
163
+
164
+ function daysBetween(from: string, to: string) {
165
+ return Math.round((toTime(to) - toTime(from)) / DAY_MS)
166
+ }
167
+
168
+ /** The first day of the month `months` after the one `key` falls in. */
169
+ function monthStart(key: string, months = 0) {
170
+ const [year, month] = key.split('-').map(Number)
171
+ const index = year * 12 + month - 1 + months
172
+ return dayKey(Math.floor(index / 12), (index % 12) + 1, 1)
173
+ }
174
+
175
+ function monthEnd(key: string) {
176
+ return addDays(monthStart(key, 1), -1)
177
+ }
178
+
179
+ function configDay(value: string | Date | undefined, name: string) {
180
+ if (value === undefined || value === null || value === '') return undefined
181
+ const day = calendarDay(value)
182
+ if (!day) throw new Error(`\`${name}\` is not a date: ${String(value)}`)
183
+ return day
184
+ }
185
+
186
+ /**
187
+ * The days drawn, or none. A range the config names in full is drawn even with
188
+ * no data in it, because an empty year is a reading too. An end it leaves out
189
+ * comes from the data inside the end it names, rounded out to the whole month,
190
+ * and with no such data there is nothing to draw. Only a range the caller
191
+ * wrote backwards is an error.
192
+ */
193
+ function resolveRange(
194
+ config: CalendarHeatmapChartConfig,
195
+ days: string[],
196
+ ): { start: string; end: string } | undefined {
197
+ const start = configDay(config.start, 'start')
198
+ const end = configDay(config.end, 'end')
199
+ if (start && end) {
200
+ if (start > end) {
201
+ throw new Error(`\`start\` (${start}) is after \`end\` (${end})`)
202
+ }
203
+ return { start, end }
204
+ }
205
+
206
+ const inside = days.filter(
207
+ (day) => (!start || day >= start) && (!end || day <= end),
208
+ )
209
+ if (!inside.length) return undefined
210
+ return {
211
+ start: start ?? monthStart(inside[0]),
212
+ end: end ?? monthEnd(inside[inside.length - 1]),
213
+ }
214
+ }
215
+
216
+ /**
217
+ * A year or less is one band. Longer, bands of twelve months from the range's
218
+ * first month, so a fiscal or a rolling year is one band, not two halves. Each
219
+ * band is the days drawn in it, and the span its calendar lays out: a whole
220
+ * twelve months, so its months line up with the other bands.
221
+ */
222
+ function bandRanges(start: string, end: string) {
223
+ if (daysBetween(start, end) < ONE_BAND_MAX_DAYS) {
224
+ return [{ start, end, span: [start, end] as [string, string] }]
225
+ }
226
+ const ranges = []
227
+ for (
228
+ let first = monthStart(start);
229
+ first <= end;
230
+ first = monthStart(first, 12)
231
+ ) {
232
+ const last = addDays(monthStart(first, 12), -1)
233
+ ranges.push({
234
+ start: first < start ? start : first,
235
+ end: last > end ? end : last,
236
+ span: [first, last] as [string, string],
237
+ })
238
+ }
239
+ return ranges
240
+ }
241
+
242
+ /** A band's years: `2024` for a calendar year, `2023–24` across two. */
243
+ function bandLabel([first, last]: [string, string]) {
244
+ const [from, to] = [first.slice(0, 4), last.slice(0, 4)]
245
+ return from === to ? from : `${from}–${to.slice(2)}`
246
+ }
247
+
248
+ /** The months a band draws days in, as `YYYY-MM`. */
249
+ function bandMonths(band: CalendarHeatmapBand) {
250
+ const months = []
251
+ for (
252
+ let first = monthStart(band.start);
253
+ first <= band.end;
254
+ first = monthStart(first, 1)
255
+ ) {
256
+ months.push(first.slice(0, 7))
257
+ }
258
+ return months
259
+ }
260
+
261
+ /** A day's row in its column, 0 at the top. */
262
+ function weekRow(day: string, firstDay: number) {
263
+ return (new Date(toTime(day)).getUTCDay() - firstDay + 7) % 7
264
+ }
265
+
266
+ /** Week columns from the column `start` falls in to the one `end` falls in. */
267
+ function weekCount(start: string, end: string, firstDay: number) {
268
+ return Math.ceil((weekRow(start, firstDay) + daysBetween(start, end) + 1) / 7)
269
+ }
270
+
271
+ /**
272
+ * Days, bands and the resolved color scale. Of two rows on the same day the
273
+ * later one is drawn, as on the category heatmap: the chart does not choose how
274
+ * a caller's numbers combine.
275
+ */
276
+ export function buildCalendarHeatmapGrid(
277
+ config: CalendarHeatmapChartConfig,
278
+ { tokens }: CalendarHeatmapOptionContext,
279
+ ): CalendarHeatmapGrid {
280
+ const firstDay = weekStartDay(config)
281
+ const placed = new Map<string, { value: number; row: Record<string, any> }>()
282
+
283
+ for (const row of config.data ?? []) {
284
+ const date = calendarDay(row[config.dateColumn])
285
+ const value = toNumber(row[config.valueColumn])
286
+ if (date === null || value === null) continue
287
+ if (import.meta.env.DEV && placed.has(date)) {
288
+ console.warn(
289
+ `[frappe-ui] Two rows land on the calendar heatmap day ${date}. The last one is drawn; pre-aggregate the data to choose yourself.`,
290
+ )
291
+ }
292
+ placed.set(date, { value, row })
293
+ }
294
+
295
+ const range = resolveRange(config, [...placed.keys()].sort())
296
+ const inRange = [...placed.entries()]
297
+ .filter(([date]) => range && date >= range.start && date <= range.end)
298
+ .sort(([a], [b]) => (a < b ? -1 : 1))
299
+
300
+ const { min, max } = resolveScale(
301
+ config,
302
+ inRange.map(([, day]) => day),
303
+ )
304
+ const stops = dataRamp(config, tokens)
305
+ const span = max - min
306
+
307
+ const ranges = range ? bandRanges(range.start, range.end) : []
308
+ const bands: CalendarHeatmapBand[] = []
309
+ const cells: CalendarHeatmapCell[] = []
310
+ const days: CalendarHeatmapDay[] = []
311
+
312
+ ranges.forEach(({ start, end, span: bandSpan }, band) => {
313
+ const entry: CalendarHeatmapBand = {
314
+ start,
315
+ end,
316
+ span: bandSpan,
317
+ weeks: weekCount(bandSpan[0], bandSpan[1], firstDay),
318
+ cells: [],
319
+ }
320
+ bands.push(entry)
321
+ let empty = 0
322
+ for (let date = start; date <= end; date = addDays(date, 1)) {
323
+ const day = placed.get(date)
324
+ if (!day) {
325
+ // The empty days' series follow the data series, one per band.
326
+ days.push({
327
+ date,
328
+ band,
329
+ seriesIndex: ranges.length + band,
330
+ dataIndex: empty++,
331
+ })
332
+ continue
333
+ }
334
+ const cell = {
335
+ date,
336
+ value: day.value,
337
+ row: day.row,
338
+ // As on the category heatmap: a flat calendar reads as present, not empty.
339
+ color: rampColor(stops, span > 0 ? (day.value - min) / span : 1),
340
+ }
341
+ days.push({
342
+ date,
343
+ band,
344
+ cell,
345
+ seriesIndex: band,
346
+ dataIndex: entry.cells.length,
347
+ })
348
+ entry.cells.push(cell)
349
+ cells.push(cell)
350
+ }
351
+ })
352
+
353
+ return { bands, cells, days, min, max, stops }
354
+ }
355
+
356
+ /**
357
+ * The ramp from its floor up, which the days and the scale both draw from. A
358
+ * diverging ramp keeps its pale middle for zero, so it is drawn whole.
359
+ */
360
+ function dataRamp(config: CalendarHeatmapChartConfig, tokens: ChartTokens) {
361
+ const stops = heatmapRampStops(config, tokens)
362
+ if (config.palette === 'diverging') return stops
363
+ try {
364
+ return Array.from({ length: HEATMAP_RAMP_SAMPLES }, (_, i) =>
365
+ interpolateRamp(
366
+ stops,
367
+ RAMP_FLOOR + ((1 - RAMP_FLOOR) * i) / (HEATMAP_RAMP_SAMPLES - 1),
368
+ ),
369
+ )
370
+ } catch {
371
+ return stops
372
+ }
373
+ }
374
+
375
+ /** Gutter left of the bands: the weekday labels, and the year beside them. */
376
+ function gutters(grid: CalendarHeatmapGrid, firstDay: number) {
377
+ const dayLabelWidth = Math.max(
378
+ ...dayNames(firstDay).map((name) =>
379
+ estimateTextWidth(name, AXIS_LABEL_FONT_SIZE),
380
+ ),
381
+ )
382
+ const day = Math.ceil(dayLabelWidth) + AXIS_LABEL_MARGIN
383
+ // The year runs up the side of its band, outside the day labels.
384
+ const year =
385
+ grid.bands.length > 1 ? AXIS_LABEL_FONT_SIZE + AXIS_LABEL_MARGIN : 0
386
+ return { day, total: day + year }
387
+ }
388
+
389
+ /**
390
+ * Where the bands and the scale under them sit in the plot. Cells are square,
391
+ * as large as both the width and the height allow: the width holds the widest
392
+ * band's weeks beside the gutter, the height every band, its month labels and
393
+ * the scale. The calendar sits at the top left, as the sibling charts do, and
394
+ * the room it does not need is left under it and to its right.
395
+ */
396
+ export function layoutCalendar(
397
+ grid: CalendarHeatmapGrid,
398
+ config: Pick<CalendarHeatmapChartConfig, 'weekStart'>,
399
+ {
400
+ width = 0,
401
+ height = 0,
402
+ }: Pick<CalendarHeatmapOptionContext, 'width' | 'height'>,
403
+ ): CalendarHeatmapLayout {
404
+ const count = grid.bands.length
405
+ const weeks = Math.max(...grid.bands.map((band) => band.weeks))
406
+ const chrome = count * MONTH_LABEL_ROW + (count - 1) * BAND_GAP + SCALE_ROW
407
+
408
+ function fit(gutter: number) {
409
+ const fits = [MAX_CELL_SIZE]
410
+ if (width > 0) fits.push((width - gutter - PLOT_RIGHT_PAD) / weeks)
411
+ if (height > 0) fits.push((height - chrome) / (7 * count))
412
+ return fits.length === 1
413
+ ? DEFAULT_CELL_SIZE
414
+ : Math.max(1, Math.floor(Math.min(...fits)))
415
+ }
416
+
417
+ let gutter = gutters(grid, weekStartDay(config))
418
+ let cellSize = fit(gutter.total)
419
+ // A row shorter than the label font cannot carry a weekday, so the labels
420
+ // go and the cells take their room.
421
+ if (cellSize < AXIS_LABEL_FONT_SIZE) {
422
+ gutter = { day: 0, total: gutter.total - gutter.day }
423
+ cellSize = fit(gutter.total)
424
+ }
425
+
426
+ const bandHeight = MONTH_LABEL_ROW + 7 * cellSize + BAND_GAP
427
+ return {
428
+ cellSize,
429
+ left: gutter.total,
430
+ dayGutter: gutter.day,
431
+ tops: grid.bands.map((_, index) => MONTH_LABEL_ROW + index * bandHeight),
432
+ right: gutter.total + weeks * cellSize,
433
+ scaleTop: count * bandHeight - BAND_GAP + SCALE_GAP,
434
+ }
435
+ }
436
+
437
+ /**
438
+ * The months a band names, as `YYYY-MM`: those it draws days in, less any whose
439
+ * label would run into the one before it. A month's label stands over the
440
+ * first column its top row falls in, which is where echarts draws it.
441
+ */
442
+ export function bandMonthLabels(
443
+ band: CalendarHeatmapBand,
444
+ firstDay: number,
445
+ cellSize: number,
446
+ ) {
447
+ const [spanStart] = band.span
448
+ const names = monthNames()
449
+ const shown: string[] = []
450
+ let free = -Infinity
451
+ for (const month of bandMonths(band)) {
452
+ const first = `${month}-01` < spanStart ? spanStart : `${month}-01`
453
+ const top = addDays(first, (7 - weekRow(first, firstDay)) % 7)
454
+ const column = Math.floor(
455
+ (weekRow(spanStart, firstDay) + daysBetween(spanStart, top)) / 7,
456
+ )
457
+ const x = column * cellSize
458
+ if (x < free) continue
459
+ shown.push(month)
460
+ const name = names[Number(month.slice(5)) - 1]
461
+ free =
462
+ x + estimateTextWidth(name, AXIS_LABEL_FONT_SIZE) + CATEGORY_LABEL_GAP
463
+ }
464
+ return shown
465
+ }
466
+
467
+ /** Prints the months in `shown`, as `YYYY-MM`, and leaves the rest blank. */
468
+ function monthLabelFormatter(shown: Set<string>) {
469
+ return (params: { yyyy: string; MM: string; nameMap: string }) =>
470
+ shown.has(`${params.yyyy}-${params.MM}`) ? params.nameMap : ''
471
+ }
472
+
473
+ export function buildCalendarHeatmapOption(
474
+ config: CalendarHeatmapChartConfig,
475
+ context: CalendarHeatmapOptionContext,
476
+ grid = buildCalendarHeatmapGrid(config, context),
477
+ ): EChartsCoreOption {
478
+ const { tokens } = context
479
+ const isMultiBand = grid.bands.length > 1
480
+ const layout = layoutCalendar(grid, config, context)
481
+ const size = layout.cellSize
482
+
483
+ const labelStyle = {
484
+ color: tokens.axisLabel,
485
+ fontSize: AXIS_LABEL_FONT_SIZE,
486
+ fontFamily: CHART_FONT_FAMILY,
487
+ }
488
+
489
+ const firstDay = weekStartDay(config)
490
+ const calendar = grid.bands.map((band, index) => ({
491
+ // A band lays out its whole span; the days outside the range stay
492
+ // transparent, as the calendar's own day rects are.
493
+ range: band.span,
494
+ orient: 'horizontal',
495
+ left: layout.left,
496
+ top: layout.tops[index],
497
+ cellSize: [size, size],
498
+ // The series draw every day, empty ones included, so the calendar's own
499
+ // rects and month rules would only draw under and across them.
500
+ splitLine: { show: false },
501
+ itemStyle: { color: 'transparent', borderWidth: 0 },
502
+ dayLabel: {
503
+ show: layout.dayGutter > 0,
504
+ ...labelStyle,
505
+ firstDay,
506
+ nameMap: dayNames(firstDay),
507
+ margin: AXIS_LABEL_MARGIN,
508
+ },
509
+ monthLabel: {
510
+ ...labelStyle,
511
+ nameMap: monthNames(),
512
+ align: 'left',
513
+ margin: AXIS_LABEL_MARGIN / 2,
514
+ formatter: monthLabelFormatter(
515
+ new Set(bandMonthLabels(band, firstDay, size)),
516
+ ),
517
+ },
518
+ yearLabel: {
519
+ show: isMultiBand,
520
+ ...labelStyle,
521
+ color: tokens.axisTitle,
522
+ fontWeight: 'normal',
523
+ position: 'left',
524
+ margin: layout.dayGutter + AXIS_LABEL_MARGIN / 2,
525
+ formatter: bandLabel(band.span),
526
+ },
527
+ }))
528
+
529
+ const cellStyle = {
530
+ borderRadius: CELL_RADIUS,
531
+ borderWidth: CELL_BORDER_WIDTH,
532
+ borderColor: tokens.backdrop,
533
+ }
534
+
535
+ // The data series come first, one per band, so a series index is a band index.
536
+ const dataSeries = grid.bands.map((band, index) => ({
537
+ type: 'heatmap',
538
+ coordinateSystem: 'calendar',
539
+ calendarIndex: index,
540
+ name: config.valueColumn,
541
+ itemStyle: cellStyle,
542
+ // As on the category heatmap: hover lightens the fill and nothing else.
543
+ emphasis: {
544
+ focus: 'none',
545
+ itemStyle: { ...cellStyle, shadowBlur: 0, shadowColor: 'transparent' },
546
+ },
547
+ data: band.cells.map((cell) => ({
548
+ value: [cell.date, cell.value],
549
+ emphasis: { itemStyle: { color: hoverCellColor(cell.color) } },
550
+ })),
551
+ }))
552
+
553
+ // Days with no data. A series of their own rather than the calendar's day
554
+ // rects, which take no corner radius and answer no pointer.
555
+ const emptyStyle = { ...cellStyle, color: tokens.gridline }
556
+ const emptySeries = grid.bands.map((_, index) => ({
557
+ type: 'heatmap',
558
+ coordinateSystem: 'calendar',
559
+ calendarIndex: index,
560
+ itemStyle: emptyStyle,
561
+ emphasis: {
562
+ focus: 'none',
563
+ itemStyle: { ...emptyStyle, shadowBlur: 0, shadowColor: 'transparent' },
564
+ },
565
+ data: grid.days
566
+ .filter((day) => day.band === index && !day.cell)
567
+ .map((day) => [day.date, 0]),
568
+ }))
569
+
570
+ const option = {
571
+ animation: true,
572
+ animationDuration: 500,
573
+ animationDurationUpdate: 300,
574
+ textStyle: { fontFamily: CHART_FONT_FAMILY },
575
+ calendar,
576
+ // Hidden: the ramp is explained by an HTML scale under the plot. The empty
577
+ // days take a second map only because echarts' development build throws for
578
+ // a heatmap without one. It maps opacity: a color mapping would overwrite
579
+ // their `itemStyle.color`, and cannot parse the oklch gridline token.
580
+ visualMap: [
581
+ {
582
+ type: 'continuous',
583
+ show: false,
584
+ calculable: false,
585
+ min: visualMapMin(grid),
586
+ max: grid.max,
587
+ inRange: { color: sampleRamp(grid.stops) },
588
+ seriesIndex: dataSeries.map((_, index) => index),
589
+ },
590
+ {
591
+ type: 'continuous',
592
+ show: false,
593
+ calculable: false,
594
+ min: 0,
595
+ max: 1,
596
+ inRange: { opacity: [1, 1] },
597
+ seriesIndex: emptySeries.map((_, index) => dataSeries.length + index),
598
+ },
599
+ ],
600
+ series: [...dataSeries, ...emptySeries],
601
+ }
602
+
603
+ return mergeDeep(option, config.echartOptions)
604
+ }
@@ -127,6 +127,32 @@ export function oklchToHex(color: Oklch): string {
127
127
  return toHex(oklchToRgb(clampToGamut(color)))
128
128
  }
129
129
 
130
+ const CSS_OKLCH =
131
+ /^oklch\(\s*([\d.]+%?)\s+([\d.]+%?)\s+([\d.]+|none)(?:deg)?\s*(?:\/\s*([\d.]+%?)\s*)?\)$/i
132
+
133
+ /**
134
+ * A CSS `oklch()` color as hex, or as `rgba()` when it carries an alpha below
135
+ * 1, clamped into sRGB. Null for anything else.
136
+ */
137
+ export function oklchCssToSrgb(text: string): string | null {
138
+ const match = CSS_OKLCH.exec(text.trim())
139
+ if (!match) return null
140
+ const [, lightness, chroma, hue, alpha] = match
141
+ const number = (value: string, percentOf: number) =>
142
+ value.endsWith('%')
143
+ ? (parseFloat(value) / 100) * percentOf
144
+ : parseFloat(value)
145
+ const hex = oklchToHex({
146
+ l: number(lightness, 1),
147
+ c: number(chroma, 0.4),
148
+ h: hue === 'none' ? 0 : parseFloat(hue),
149
+ })
150
+ const opacity = alpha === undefined ? 1 : number(alpha, 1)
151
+ if (opacity >= 1) return hex
152
+ const { r, g, b } = parseHex(hex)
153
+ return `rgba(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)}, ${opacity})`
154
+ }
155
+
130
156
  export function hexToOklch(hex: string): Oklch {
131
157
  return rgbToOklch(parseHex(hex))
132
158
  }