@d3plus/core 4.6.0 → 4.7.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.
- package/README.md +728 -1454
- package/es/index.js.map +1 -1
- package/es/internal.js +5 -0
- package/es/internal.js.map +1 -1
- package/es/src/charts/Chord/index.js +2 -0
- package/es/src/charts/Chord/index.js.map +1 -1
- package/es/src/charts/Geomap/applyLayout.js +3 -1
- package/es/src/charts/Geomap/applyLayout.js.map +1 -1
- package/es/src/charts/Geomap/index.js +3 -1
- package/es/src/charts/Geomap/index.js.map +1 -1
- package/es/src/charts/Matrix/emit.js +5 -4
- package/es/src/charts/Matrix/emit.js.map +1 -1
- package/es/src/charts/Network/index.js +4 -0
- package/es/src/charts/Network/index.js.map +1 -1
- package/es/src/charts/Pack/emit.js +6 -6
- package/es/src/charts/Pack/emit.js.map +1 -1
- package/es/src/charts/Pack/index.js +2 -0
- package/es/src/charts/Pack/index.js.map +1 -1
- package/es/src/charts/Pie/emit.js +5 -6
- package/es/src/charts/Pie/emit.js.map +1 -1
- package/es/src/charts/Pie/index.js +2 -0
- package/es/src/charts/Pie/index.js.map +1 -1
- package/es/src/charts/Plot/index.js +15 -1
- package/es/src/charts/Plot/index.js.map +1 -1
- package/es/src/charts/Plot/insetRegion.js +21 -0
- package/es/src/charts/Plot/insetRegion.js.map +1 -0
- package/es/src/charts/Plot/sharedHover.js +117 -16
- package/es/src/charts/Plot/sharedHover.js.map +1 -1
- package/es/src/charts/Plot/sharedTooltip.js +35 -15
- package/es/src/charts/Plot/sharedTooltip.js.map +1 -1
- package/es/src/charts/Plot/trendLines.js +140 -38
- package/es/src/charts/Plot/trendLines.js.map +1 -1
- package/es/src/charts/Plot/trendProjection.js +120 -0
- package/es/src/charts/Plot/trendProjection.js.map +1 -0
- package/es/src/charts/Plot/trendScene.js +33 -19
- package/es/src/charts/Plot/trendScene.js.map +1 -1
- package/es/src/charts/Plot/trendTooltip.js +79 -17
- package/es/src/charts/Plot/trendTooltip.js.map +1 -1
- package/es/src/charts/Priestley/emit.js +3 -4
- package/es/src/charts/Priestley/emit.js.map +1 -1
- package/es/src/charts/RadialMatrix/emit.js +4 -4
- package/es/src/charts/RadialMatrix/emit.js.map +1 -1
- package/es/src/charts/Rings/index.js +5 -1
- package/es/src/charts/Rings/index.js.map +1 -1
- package/es/src/charts/Sankey/index.js +2 -0
- package/es/src/charts/Sankey/index.js.map +1 -1
- package/es/src/charts/Tree/index.js +2 -0
- package/es/src/charts/Tree/index.js.map +1 -1
- package/es/src/charts/Treemap/emit.js +3 -4
- package/es/src/charts/Treemap/emit.js.map +1 -1
- package/es/src/charts/definition/ChartDefinition.js.map +1 -1
- package/es/src/charts/definition/makeChart.js +8 -2
- package/es/src/charts/definition/makeChart.js.map +1 -1
- package/es/src/charts/drawSteps/bottomRightControls.js +3 -0
- package/es/src/charts/drawSteps/bottomRightControls.js.map +1 -1
- package/es/src/charts/drawSteps/bottomRightControlsMarkup.js +135 -4
- package/es/src/charts/drawSteps/bottomRightControlsMarkup.js.map +1 -1
- package/es/src/charts/drawSteps/searchControlsMarkup.js +15 -38
- package/es/src/charts/drawSteps/searchControlsMarkup.js.map +1 -1
- package/es/src/charts/events/click.legend.js +10 -5
- package/es/src/charts/events/click.legend.js.map +1 -1
- package/es/src/charts/events/mousemove.shape.js +8 -1
- package/es/src/charts/events/mousemove.shape.js.map +1 -1
- package/es/src/charts/features/emitHelpers.js +19 -5
- package/es/src/charts/features/emitHelpers.js.map +1 -1
- package/es/src/charts/features/features.js +3 -108
- package/es/src/charts/features/features.js.map +1 -1
- package/es/src/charts/features/featuresColorScale.js +161 -0
- package/es/src/charts/features/featuresColorScale.js.map +1 -0
- package/es/src/charts/features/featuresLegend.js +145 -32
- package/es/src/charts/features/featuresLegend.js.map +1 -1
- package/es/src/charts/features/insetState.js +174 -0
- package/es/src/charts/features/insetState.js.map +1 -0
- package/es/src/charts/features/sceneBounds.js +271 -0
- package/es/src/charts/features/sceneBounds.js.map +1 -0
- package/es/src/charts/features/tooltipSwatch.js +73 -0
- package/es/src/charts/features/tooltipSwatch.js.map +1 -0
- package/es/src/charts/pipeline/insetPlacement.js +406 -0
- package/es/src/charts/pipeline/insetPlacement.js.map +1 -0
- package/es/src/charts/pipeline/runVizPipeline.js +6 -2
- package/es/src/charts/pipeline/runVizPipeline.js.map +1 -1
- package/es/src/charts/viz/Viz.js +18 -3
- package/es/src/charts/viz/Viz.js.map +1 -1
- package/es/src/charts/viz/VizBaseConfig.js +20 -24
- package/es/src/charts/viz/VizBaseConfig.js.map +1 -1
- package/es/src/charts/viz/interactionOpacity.js +21 -13
- package/es/src/charts/viz/interactionOpacity.js.map +1 -1
- package/es/src/charts/viz/linkGroup.js +386 -0
- package/es/src/charts/viz/linkGroup.js.map +1 -0
- package/es/src/charts/viz/sceneRows.js +33 -0
- package/es/src/charts/viz/sceneRows.js.map +1 -0
- package/es/src/charts/viz/vizDefaults.js +13 -8
- package/es/src/charts/viz/vizDefaults.js.map +1 -1
- package/es/src/charts/viz/vizTypes.js.map +1 -1
- package/es/src/components/Axis/AxisBottom.js +1 -1
- package/es/src/components/Axis/AxisBottom.js.map +1 -1
- package/es/src/components/Axis/AxisLeft.js +1 -1
- package/es/src/components/Axis/AxisLeft.js.map +1 -1
- package/es/src/components/Axis/AxisRight.js +1 -1
- package/es/src/components/Axis/AxisRight.js.map +1 -1
- package/es/src/components/Axis/AxisTop.js +1 -1
- package/es/src/components/Axis/AxisTop.js.map +1 -1
- package/es/src/components/Axis/axisLayoutLabels.js +13 -1
- package/es/src/components/Axis/axisLayoutLabels.js.map +1 -1
- package/es/src/components/ColorScale/ColorScale.js.map +1 -1
- package/es/src/components/Legend/legendConfig.js +2 -1
- package/es/src/components/Legend/legendConfig.js.map +1 -1
- package/es/src/components/Legend/legendRender.js +42 -5
- package/es/src/components/Legend/legendRender.js.map +1 -1
- package/es/src/components/TextBox.js +1 -1
- package/es/src/components/TextBox.js.map +1 -1
- package/es/src/shapes/Bar.js +1 -1
- package/es/src/shapes/Bar.js.map +1 -1
- package/es/src/shapes/Box.js +1 -1
- package/es/src/shapes/Box.js.map +1 -1
- package/es/src/shapes/Rect.js +1 -1
- package/es/src/shapes/Rect.js.map +1 -1
- package/es/src/shapes/Shape.js +9 -36
- package/es/src/shapes/Shape.js.map +1 -1
- package/es/src/shapes/Whisker.js +1 -1
- package/es/src/shapes/Whisker.js.map +1 -1
- package/es/src/shapes/textureKey.js +104 -0
- package/es/src/shapes/textureKey.js.map +1 -0
- package/es/src/utils/D3plusConfig.js.map +1 -1
- package/package.json +10 -9
- package/types/index.d.ts +1 -0
- package/types/internal.d.ts +7 -0
- package/types/src/charts/Plot/index.d.ts +8 -0
- package/types/src/charts/Plot/insetRegion.d.ts +4 -0
- package/types/src/charts/Plot/sharedHover.d.ts +5 -0
- package/types/src/charts/Plot/sharedTooltip.d.ts +10 -0
- package/types/src/charts/Plot/trendLines.d.ts +23 -3
- package/types/src/charts/Plot/trendProjection.d.ts +28 -0
- package/types/src/charts/Plot/trendScene.d.ts +2 -1
- package/types/src/charts/Plot/trendTooltip.d.ts +16 -5
- package/types/src/charts/definition/ChartDefinition.d.ts +9 -0
- package/types/src/charts/definition/makeChart.d.ts +2 -2
- package/types/src/charts/drawSteps/bottomRightControlsMarkup.d.ts +2 -0
- package/types/src/charts/drawSteps/searchControlsMarkup.d.ts +7 -5
- package/types/src/charts/features/emitHelpers.d.ts +10 -4
- package/types/src/charts/features/features.d.ts +1 -8
- package/types/src/charts/features/featuresColorScale.d.ts +24 -0
- package/types/src/charts/features/featuresLegend.d.ts +15 -0
- package/types/src/charts/features/insetState.d.ts +95 -0
- package/types/src/charts/features/sceneBounds.d.ts +18 -0
- package/types/src/charts/features/tooltipSwatch.d.ts +31 -0
- package/types/src/charts/pipeline/insetPlacement.d.ts +45 -0
- package/types/src/charts/pipeline/runVizPipeline.d.ts +2 -1
- package/types/src/charts/viz/Viz.d.ts +9 -1
- package/types/src/charts/viz/VizBaseConfig.d.ts +8 -12
- package/types/src/charts/viz/linkGroup.d.ts +96 -0
- package/types/src/charts/viz/sceneRows.d.ts +13 -0
- package/types/src/charts/viz/vizTypes.d.ts +17 -0
- package/types/src/components/Axis/AxisBottom.d.ts +1 -1
- package/types/src/components/Axis/AxisLeft.d.ts +1 -1
- package/types/src/components/Axis/AxisRight.d.ts +1 -1
- package/types/src/components/Axis/AxisTop.d.ts +1 -1
- package/types/src/components/ColorScale/ColorScale.d.ts +4 -4
- package/types/src/components/Legend/legendRender.d.ts +1 -1
- package/types/src/components/TextBox.d.ts +1 -1
- package/types/src/shapes/Bar.d.ts +1 -1
- package/types/src/shapes/Box.d.ts +1 -1
- package/types/src/shapes/Rect.d.ts +1 -1
- package/types/src/shapes/Whisker.d.ts +1 -1
- package/types/src/shapes/textureKey.d.ts +9 -0
- package/types/src/utils/D3plusConfig.d.ts +42 -1
- package/umd/d3plus-core.full.js +2393 -594
- package/umd/d3plus-core.full.js.map +1 -1
- package/umd/d3plus-core.full.min.js +1945 -1601
- package/umd/d3plus-core.js +1744 -404
- package/umd/d3plus-core.js.map +1 -1
- package/umd/d3plus-core.min.js +1401 -1087
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/charts/Plot/trendLines.ts"],"sourcesContent":["/**\n Automatic trend lines: fits a regression per series (or across all data)\n from the formatted Plot rows, samples it along the independent axis, and\n widens the dependent axis's values so the fitted line and its confidence\n band stay inside the plot. Painted by `trendScene.ts`.\n*/\nimport {groups} from \"d3-array\";\n\nimport type {DataPoint} from \"@d3plus/data\";\nimport {linearConfidence, regression} from \"@d3plus/math\";\nimport type {RegressionResult, RegressionType} from \"@d3plus/math\";\n\nimport type {TransformStage} from \"../pipeline/stages.js\";\nimport type {VizInstance} from \"../viz/vizTypes.js\";\nimport {isSpanAxis} from \"./discreteSpan.js\";\n\ntype Row = Record<string, unknown>;\ntype Axis = \"x\" | \"y\";\n\n/** The regression types `trendLine` accepts. */\nexport const trendTypes: RegressionType[] = [\n \"linear\",\n \"exponential\",\n \"logarithmic\",\n \"power\",\n \"polynomial\",\n];\n\n/** Number of points sampled along a continuous independent axis. */\nconst SAMPLES = 50;\n\n/** One point along a fitted trend line, in plot data space. */\nexport interface TrendSample {\n x: unknown;\n y: unknown;\n /** Lower confidence bound on the dependent axis. */\n lci?: number;\n /** Upper confidence bound on the dependent axis. */\n hci?: number;\n}\n\n/** A fitted trend line, ready to paint. */\nexport interface TrendFit {\n /** Stable key: the series id, or \"all\". */\n id: string;\n /** Tooltip title: the series label, or the translated \"Trend Line\". */\n label: string;\n /** Line stroke (and band fill). */\n color: string;\n /** The independent axis the fit runs along. */\n axis: Axis;\n fit: RegressionResult;\n samples: TrendSample[];\n /** A source row of the series, so hover dimming treats the line as part of it. */\n row?: DataPoint;\n}\n\n/** The values `trendLine` accepts: a regression type, `true` (linear), or `false` (off). */\nexport type TrendLineType = boolean | RegressionType;\n\n/** The default `trendLineConfig`. */\nexport function trendLineDefaults(): Record<string, unknown> {\n return {\n confidence: false,\n confidenceConfig: {fillOpacity: 0.15},\n confidenceLevel: 0.95,\n group: \"series\",\n order: 2,\n strokeDasharray: \"6 4\",\n strokeWidth: 2,\n tooltip: true,\n };\n}\n\n/** Resolves the `trendLine` setting to a regression type, or null when off. */\nexport function resolveTrendType(value: unknown): RegressionType | null {\n if (value === true) return \"linear\";\n return trendTypes.includes(value as RegressionType) ? (value as RegressionType) : null;\n}\n\n/**\n The axis a trend line runs along: the discrete axis when one is set (so a\n horizontal bar chart fits along y), otherwise x.\n*/\nexport function trendAxis(discrete: unknown): Axis {\n return discrete === \"y\" ? \"y\" : \"x\";\n}\n\n/**\n Maps independent-axis values to numbers for fitting, and back again for\n plotting: Dates by timestamp, numbers as-is, and anything else (category\n names) by its position in the axis's ordered values.\n*/\nexport function trendNumberScale(order: unknown[]): {\n toNumber: (v: unknown) => number;\n fromNumber: (n: number) => unknown;\n} {\n const keys = order.map(v => `${v}`);\n const categorical = order.some(v => !(v instanceof Date) && typeof v !== \"number\");\n const time = order.some(v => v instanceof Date);\n return {\n toNumber: v => {\n if (v instanceof Date) return +v;\n if (!categorical && typeof v === \"number\") return v;\n const index = keys.indexOf(`${v}`);\n return index < 0 ? NaN : index;\n },\n fromNumber: n => (categorical ? order[Math.round(n)] : time ? new Date(n) : n),\n };\n}\n\n/**\n The independent-axis positions to sample a fit at, within its extent: one\n per category on a point scale (in-between positions can't be placed), or\n evenly spaced points on a continuous axis.\n*/\nexport function trendSamplePositions(\n extent: [number, number],\n categories: number[] | null,\n count = SAMPLES,\n): number[] {\n const [lo, hi] = extent;\n if (categories) return categories.filter(n => n >= lo && n <= hi);\n if (lo === hi) return [lo];\n return Array.from({length: count}, (_, i) => lo + (hi - lo) * i / (count - 1));\n}\n\n/** Whether an axis plots on a point (category) scale, matching `computePlotScales`. */\nfunction isPointAxis(viz: VizInstance, axis: Axis): boolean {\n if (viz[`_${axis}Time`]) return false;\n return (viz.schema.discrete === axis && !isSpanAxis(viz, axis)) || !!viz.schema[`${axis}Sort`];\n}\n\n/** The id of the series a row belongs to at a `groupBy` depth. */\nfunction seriesKey(viz: VizInstance, row: Row, depth: number): string {\n return viz._ids(row.data as DataPoint, row.i as number)\n .slice(0, depth + 1)\n .join(\"_\");\n}\n\n/** A set of points to fit: its key, `[x, y]` points, a source row, and the depth labeling it. */\ntype FitGroup = [string, [number, number][], Row | undefined, number];\n\n/**\n Groups rows into the sets to fit. A series is the drawn id when it spans\n several points (a line, or a series of bars); when every drawn id is a\n single point (a scatter plot), series come from the parent `groupBy`\n level, or all points fit together at the top level.\n*/\nfunction fitGroups(\n viz: VizInstance,\n rows: Row[],\n axis: Axis,\n toNumber: (v: unknown) => number,\n): FitGroup[] {\n const dep = axis === \"x\" ? \"y\" : \"x\";\n const point = (r: Row): [number, number] => [toNumber(r[axis]), +(r[dep] as number)];\n // A stacked chart fits the stack totals, so the line follows the stack tops.\n if (viz.schema.stacked) {\n const totals = groups(rows, r => toNumber(r[axis]))\n .map(([n, rs]): [number, number] => [n, rs.reduce((s, r) => s + (+(r[dep] as number) || 0), 0)]);\n return [[\"all\", totals, undefined, -1]];\n }\n const all: FitGroup[] = [[\"all\", rows.map(point), undefined, -1]];\n if (viz._trendLineConfig?.group === \"all\") return all;\n const bySeries = (depth: number): FitGroup[] =>\n groups(rows, r => seriesKey(viz, r, depth)).map(([key, rs]) => [key, rs.map(point), rs[0], depth]);\n const depth = viz._drawDepth;\n const drawn = bySeries(depth);\n if (drawn.some(([, points]) => points.length > 1)) return drawn;\n return depth > 0 ? bySeries(depth - 1) : all;\n}\n\n/** Fits the trend lines for the current data; empty when `trendLine` is off. */\nexport function computeTrendFits(viz: VizInstance, rows: Row[], order: unknown[]): TrendFit[] {\n const type = resolveTrendType(viz._trendLine);\n if (!type || !rows.length) return [];\n const config = viz._trendLineConfig || {};\n const axis = trendAxis(viz.schema.discrete);\n const dep = axis === \"x\" ? \"y\" : \"x\";\n const {toNumber, fromNumber} = trendNumberScale(order);\n const categories = isPointAxis(viz, axis)\n ? order.map(toNumber).filter(Number.isFinite)\n : null;\n const logDep = `${viz[`_${dep}Config`]?.scale}`.toLowerCase() === \"log\";\n const fill = viz.schema.shapeConfig.fill;\n\n const fits: TrendFit[] = [];\n for (const [id, points, source, depth] of fitGroups(viz, rows, axis, toNumber)) {\n const fit = regression(points, type, {order: config.order as number | undefined});\n if (!fit) continue;\n const band = config.confidence && type === \"linear\"\n ? linearConfidence(points, config.confidenceLevel as number | undefined)\n : null;\n const samples: TrendSample[] = [];\n for (const n of trendSamplePositions(fit.extent, categories)) {\n const value = fit.predict(n);\n if (!Number.isFinite(value) || (logDep && value <= 0)) continue;\n const sample = {[axis]: fromNumber(n), [dep]: value} as unknown as TrendSample;\n if (band) [sample.lci, sample.hci] = band(n);\n samples.push(sample);\n }\n if (samples.length < 2) continue;\n const row = source ? (source.data as DataPoint) : undefined;\n const color = config.stroke\n ? config.stroke\n : row\n ? typeof fill === \"function\" ? fill(row, source!.i) : fill\n : \"#444\";\n const label = row\n ? viz._drawLabel(row, source!.i as number, depth)\n : viz.schema.translate(\"Trend Line\");\n fits.push({id, label, color, axis, fit, samples, row});\n }\n return fits;\n}\n\n/** The dependent-axis values a set of fits plots, including band bounds. */\nexport function trendDomainValues(fits: TrendFit[]): number[] {\n const values: number[] = [];\n for (const {axis, samples} of fits) {\n const dep = axis === \"x\" ? \"y\" : \"x\";\n for (const s of samples) {\n values.push(s[dep] as number);\n if (s.lci !== undefined) values.push(s.lci, s.hci!);\n }\n }\n return values.filter(Number.isFinite);\n}\n\n/**\n `computePlotTrendFits` — runs after `computePlotAxisValues`: fits the\n trend lines onto `viz._trendFits` and appends their values to the\n dependent axis's values, so the non-stacked domain covers them (the\n stacked domain reads `viz._trendFits` directly).\n*/\nexport const computePlotTrendFits: TransformStage = ({viz, plotFormattedData, xData, yData}) => {\n const axis = trendAxis(viz.schema.discrete);\n const fits = (viz._trendFits = computeTrendFits(\n viz,\n plotFormattedData || [],\n (axis === \"x\" ? xData : yData) || [],\n ));\n if (!fits.length) return {};\n const extra = trendDomainValues(fits);\n return axis === \"x\"\n ? {yData: (yData || []).concat(extra)}\n : {xData: (xData || []).concat(extra)};\n};\n"],"names":["groups","linearConfidence","regression","isSpanAxis","trendTypes","SAMPLES","trendLineDefaults","confidence","confidenceConfig","fillOpacity","confidenceLevel","group","order","strokeDasharray","strokeWidth","tooltip","resolveTrendType","value","includes","trendAxis","discrete","trendNumberScale","keys","map","v","categorical","some","Date","time","toNumber","index","indexOf","NaN","fromNumber","n","Math","round","trendSamplePositions","extent","categories","count","lo","hi","filter","Array","from","length","_","i","isPointAxis","viz","axis","schema","seriesKey","row","depth","_ids","data","slice","join","fitGroups","rows","dep","point","r","stacked","totals","rs","reduce","s","undefined","all","_trendLineConfig","bySeries","key","_drawDepth","drawn","points","computeTrendFits","type","_trendLine","config","Number","isFinite","logDep","scale","toLowerCase","fill","shapeConfig","fits","id","source","fit","band","samples","predict","sample","lci","hci","push","color","stroke","label","_drawLabel","translate","trendDomainValues","values","computePlotTrendFits","plotFormattedData","xData","yData","_trendFits","extra","concat"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;AAKA,GACA,SAAQA,MAAM,QAAO,WAAW;AAGhC,SAAQC,gBAAgB,EAAEC,UAAU,QAAO,eAAe;AAK1D,SAAQC,UAAU,QAAO,oBAAoB;AAK7C,8CAA8C,GAC9C,OAAO,IAAMC,aAA+B;IAC1C;IACA;IACA;IACA;IACA;CACD,CAAC;AAEF,kEAAkE,GAClE,IAAMC,UAAU;AA+BhB,mCAAmC,GACnC,OAAO,SAASC;IACd,OAAO;QACLC,YAAY;QACZC,kBAAkB;YAACC,aAAa;QAAI;QACpCC,iBAAiB;QACjBC,OAAO;QACPC,OAAO;QACPC,iBAAiB;QACjBC,aAAa;QACbC,SAAS;IACX;AACF;AAEA,6EAA6E,GAC7E,OAAO,SAASC,iBAAiBC,KAAc;IAC7C,IAAIA,UAAU,MAAM,OAAO;IAC3B,OAAOb,WAAWc,QAAQ,CAACD,SAA4BA,QAA2B;AACpF;AAEA;;;AAGA,GACA,OAAO,SAASE,UAAUC,QAAiB;IACzC,OAAOA,aAAa,MAAM,MAAM;AAClC;AAEA;;;;AAIA,GACA,OAAO,SAASC,iBAAiBT,KAAgB;IAI/C,IAAMU,OAAOV,MAAMW,GAAG,CAACC,SAAAA;eAAK,AAAC,GAAI,OAAFA;;IAC/B,IAAMC,cAAcb,MAAMc,IAAI,CAACF,SAAAA;eAAK,CAAEA,AAAC,YAADA,GAAaG,SAAS,OAAOH,MAAM;;IACzE,IAAMI,OAAOhB,MAAMc,IAAI,CAACF,SAAAA;eAAKA,AAAC,YAADA,GAAaG;;IAC1C,OAAO;QACLE,UAAUL,SAAVK,SAAUL;YACR,IAAIA,AAAC,YAADA,GAAaG,OAAM,OAAO,CAACH;YAC/B,IAAI,CAACC,eAAe,OAAOD,MAAM,UAAU,OAAOA;YAClD,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AA;;gBAAL,QAAK,aAAW2C,4BAAX,UAAA,8BAAA,SAAA,0BAAA,kCAAoB;oBAApB,IAAMzB,IAAN;oBACHqC,OAAOP,IAAI,CAAC9B,CAAC,CAACP,IAAI;oBAClB,IAAIO,EAAE4B,GAAG,KAAK3B,WAAWoC,OAAOP,IAAI,CAAC9B,EAAE4B,GAAG,EAAE5B,EAAE6B,GAAG;gBACnD;;gBAHK;gBAAA;;;yBAAA,8BAAA;wBAAA;;;wBAAA;8BAAA;;;;QAIP;;QANK;QAAA;;;iBAAA,6BAAA;gBAAA;;;gBAAA;sBAAA;;;;IAOL,OAAOQ,OAAO/D,MAAM,CAACuC,OAAOC,QAAQ;AACtC;AAEA;;;;;AAKA,GACA,OAAO,IAAMwB,uBAAuC;QAAEzD,YAAAA,KAAK0D,0BAAAA,mBAAmBC,cAAAA,OAAOC,cAAAA;IACnF,IAAM3D,OAAOhC,UAAU+B,IAAIE,MAAM,CAAChC,QAAQ;IAC1C,IAAMqE,OAAQvC,IAAI6D,UAAU,GAAGjC,iBAC7B5B,KACA0D,qBAAqB,EAAE,EACvB,AAACzD,CAAAA,SAAS,MAAM0D,QAAQC,KAAI,KAAM,EAAE;IAEtC,IAAI,CAACrB,KAAK3C,MAAM,EAAE,OAAO,CAAC;IAC1B,IAAMkE,QAAQP,kBAAkBhB;IAChC,OAAOtC,SAAS,MACZ;QAAC2D,OAAO,AAACA,CAAAA,SAAS,EAAE,AAAD,EAAGG,MAAM,CAACD;IAAM,IACnC;QAACH,OAAO,AAACA,CAAAA,SAAS,EAAE,AAAD,EAAGI,MAAM,CAACD;IAAM;AACzC,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/charts/Plot/trendLines.ts"],"sourcesContent":["/**\n Automatic trend lines: fits a regression per series (or across all data)\n from the formatted Plot rows, samples it along the independent axis, and\n widens the dependent axis's values so the fitted line and its confidence\n band stay inside the plot. Painted by `trendScene.ts`.\n*/\nimport {groups} from \"d3-array\";\n\nimport type {DataPoint} from \"@d3plus/data\";\nimport {linearConfidence, linearPrediction, regression} from \"@d3plus/math\";\nimport type {RegressionResult, RegressionType} from \"@d3plus/math\";\n\nimport type {TransformStage} from \"../pipeline/stages.js\";\nimport type {VizInstance} from \"../viz/vizTypes.js\";\nimport {isSpanAxis} from \"./discreteSpan.js\";\nimport {projectionPositions} from \"./trendProjection.js\";\n\ntype Row = Record<string, unknown>;\ntype Axis = \"x\" | \"y\";\n\n/** The regression types `trendLine` accepts. */\nexport const trendTypes: RegressionType[] = [\n \"linear\",\n \"exponential\",\n \"logarithmic\",\n \"power\",\n \"polynomial\",\n];\n\n/** Number of points sampled along a continuous independent axis. */\nconst SAMPLES = 50;\n\n/** One point along a fitted trend line, in plot data space. */\nexport interface TrendSample {\n x: unknown;\n y: unknown;\n /** Lower confidence bound on the dependent axis. */\n lci?: number;\n /** Upper confidence bound on the dependent axis. */\n hci?: number;\n /** Whether the point lies in the projection past the fitted data. */\n projected?: boolean;\n /** Whether the point sits on one of the projection's axis positions (the ones hover snaps to). */\n step?: boolean;\n}\n\n/** A fitted trend line, ready to paint. */\nexport interface TrendFit {\n /** Stable key: the series id, or \"all\". */\n id: string;\n /** Tooltip title: the series label, or the translated \"Trend Line\". */\n label: string;\n /** Line stroke (and band fill). */\n color: string;\n /** The independent axis the fit runs along. */\n axis: Axis;\n fit: RegressionResult;\n samples: TrendSample[];\n /** A source row of the series, so hover dimming treats the line as part of it. */\n row?: DataPoint;\n}\n\n/** The values `trendLine` accepts: a regression type, `true` (linear), or `false` (off). */\nexport type TrendLineType = boolean | RegressionType;\n\n/** The default `trendLineConfig`. */\nexport function trendLineDefaults(): Record<string, unknown> {\n return {\n confidence: false,\n confidenceConfig: {fillOpacity: 0.15},\n confidenceLevel: 0.95,\n group: \"series\",\n order: 2,\n projection: 0,\n projectionConfig: {strokeDasharray: \"2 4\"},\n strokeDasharray: \"6 4\",\n strokeWidth: 2,\n tooltip: true,\n };\n}\n\n/** Resolves the `trendLine` setting to a regression type, or null when off. */\nexport function resolveTrendType(value: unknown): RegressionType | null {\n if (value === true) return \"linear\";\n return trendTypes.includes(value as RegressionType) ? (value as RegressionType) : null;\n}\n\n/**\n The axis a trend line runs along: the discrete axis when one is set (so a\n horizontal bar chart fits along y), otherwise x.\n*/\nexport function trendAxis(discrete: unknown): Axis {\n return discrete === \"y\" ? \"y\" : \"x\";\n}\n\n/**\n Maps independent-axis values to numbers for fitting, and back again for\n plotting: Dates by timestamp, numbers as-is, and anything else (category\n names) by its position in the axis's ordered values.\n*/\nexport function trendNumberScale(order: unknown[]): {\n toNumber: (v: unknown) => number;\n fromNumber: (n: number) => unknown;\n} {\n const keys = order.map(v => `${v}`);\n const categorical = order.some(v => !(v instanceof Date) && typeof v !== \"number\");\n const time = order.some(v => v instanceof Date);\n return {\n toNumber: v => {\n if (v instanceof Date) return +v;\n if (!categorical && typeof v === \"number\") return v;\n const index = keys.indexOf(`${v}`);\n return index < 0 ? NaN : index;\n },\n fromNumber: n => (categorical ? order[Math.round(n)] : time ? new Date(n) : n),\n };\n}\n\n/**\n The independent-axis positions to sample a fit at, within its extent: one\n per category on a point scale (in-between positions can't be placed), or\n evenly spaced points on a continuous axis.\n*/\nexport function trendSamplePositions(\n extent: [number, number],\n categories: number[] | null,\n count = SAMPLES,\n): number[] {\n const [lo, hi] = extent;\n if (categories) return categories.filter(n => n >= lo && n <= hi);\n if (lo === hi) return [lo];\n return Array.from({length: count}, (_, i) => lo + (hi - lo) * i / (count - 1));\n}\n\n/**\n The independent-axis positions to sample a fit's projection at, past the\n end of its data: each projected category on a point scale, or on a\n continuous axis evenly spaced points (as dense as the fitted stretch)\n together with every projected step. The first position is the fit's last\n value, where the projection starts.\n @param extent The fit's `[min, max]` independent values.\n @param steps The axis positions the projection passes through, as numbers.\n @param categories The point scale's positions, or null on a continuous axis.\n*/\nexport function trendProjectionPositions(\n extent: [number, number],\n steps: number[],\n categories: number[] | null,\n): number[] {\n const [lo, hi] = extent;\n const end = Math.max(...steps);\n if (!(end > hi)) return [];\n if (categories) return [hi, ...categories.filter(n => n > hi && n <= end)];\n const count = hi > lo ? Math.round(SAMPLES * (end - hi) / (hi - lo)) : SAMPLES;\n const even = trendSamplePositions([hi, end], null, Math.min(Math.max(count, 2), SAMPLES) + 1);\n return Array.from(new Set([...even, ...steps.filter(n => n > hi)])).sort((a, b) => a - b);\n}\n\n/** Whether an axis plots on a point (category) scale, matching `computePlotScales`. */\nfunction isPointAxis(viz: VizInstance, axis: Axis): boolean {\n if (viz[`_${axis}Time`]) return false;\n return (viz.schema.discrete === axis && !isSpanAxis(viz, axis)) || !!viz.schema[`${axis}Sort`];\n}\n\n/** The id of the series a row belongs to at a `groupBy` depth. */\nfunction seriesKey(viz: VizInstance, row: Row, depth: number): string {\n return viz._ids(row.data as DataPoint, row.i as number)\n .slice(0, depth + 1)\n .join(\"_\");\n}\n\n/** A set of points to fit: its key, `[x, y]` points, a source row, and the depth labeling it. */\ntype FitGroup = [string, [number, number][], Row | undefined, number];\n\n/**\n Groups rows into the sets to fit. A series is the drawn id when it spans\n several points (a line, or a series of bars); when every drawn id is a\n single point (a scatter plot), series come from the parent `groupBy`\n level, or all points fit together at the top level.\n*/\nfunction fitGroups(\n viz: VizInstance,\n rows: Row[],\n axis: Axis,\n toNumber: (v: unknown) => number,\n): FitGroup[] {\n const dep = axis === \"x\" ? \"y\" : \"x\";\n const point = (r: Row): [number, number] => [toNumber(r[axis]), +(r[dep] as number)];\n // A stacked chart fits the stack totals, so the line follows the stack tops.\n if (viz.schema.stacked) {\n const totals = groups(rows, r => toNumber(r[axis]))\n .map(([n, rs]): [number, number] => [n, rs.reduce((s, r) => s + (+(r[dep] as number) || 0), 0)]);\n return [[\"all\", totals, undefined, -1]];\n }\n const all: FitGroup[] = [[\"all\", rows.map(point), undefined, -1]];\n if (viz._trendLineConfig?.group === \"all\") return all;\n const bySeries = (depth: number): FitGroup[] =>\n groups(rows, r => seriesKey(viz, r, depth)).map(([key, rs]) => [key, rs.map(point), rs[0], depth]);\n const depth = viz._drawDepth;\n const drawn = bySeries(depth);\n if (drawn.some(([, points]) => points.length > 1)) return drawn;\n return depth > 0 ? bySeries(depth - 1) : all;\n}\n\n/**\n Fits the trend lines for the current data; empty when `trendLine` is off.\n `projected` lists future independent-axis positions (from\n `projectionPositions`) each line extends to, past the end of its data.\n*/\nexport function computeTrendFits(\n viz: VizInstance,\n rows: Row[],\n order: unknown[],\n projected: unknown[] = [],\n): TrendFit[] {\n const type = resolveTrendType(viz._trendLine);\n if (!type || !rows.length) return [];\n const config = viz._trendLineConfig || {};\n const axis = trendAxis(viz.schema.discrete);\n const dep = axis === \"x\" ? \"y\" : \"x\";\n const {toNumber, fromNumber} = trendNumberScale(order.concat(projected));\n const categories = isPointAxis(viz, axis)\n ? order.concat(projected).map(toNumber).filter(Number.isFinite)\n : null;\n // With a projection on, a line projects through every axis position past\n // its data: the projected ones, and those other series still plot.\n const steps = projected.length\n ? order.concat(projected).map(toNumber).filter(Number.isFinite)\n : [];\n const logDep = `${viz[`_${dep}Config`]?.scale}`.toLowerCase() === \"log\";\n const fill = viz.schema.shapeConfig.fill;\n\n const fits: TrendFit[] = [];\n for (const [id, points, source, depth] of fitGroups(viz, rows, axis, toNumber)) {\n const fit = regression(points, type, {order: config.order as number | undefined});\n if (!fit) continue;\n const banded = config.confidence && type === \"linear\";\n const level = config.confidenceLevel as number | undefined;\n // The fitted stretch bands the mean response; the projection widens to\n // where a new observation could fall.\n const band = banded ? linearConfidence(points, level) : null;\n const fan = banded ? linearPrediction(points, level) : null;\n const samples: TrendSample[] = [];\n const sampleAt = (n: number, projectedRun: boolean) => {\n const value = fit.predict(n);\n if (!Number.isFinite(value) || (logDep && value <= 0)) return;\n const sample = {[axis]: fromNumber(n), [dep]: value} as unknown as TrendSample;\n const bounds = projectedRun ? fan : band;\n if (bounds) [sample.lci, sample.hci] = bounds(n);\n if (projectedRun) sample.projected = true;\n if (projectedRun && n > fit.extent[1] && steps.includes(n)) sample.step = true;\n samples.push(sample);\n };\n trendSamplePositions(fit.extent, categories).forEach(n => sampleAt(n, false));\n trendProjectionPositions(fit.extent, steps, categories).forEach(n => sampleAt(n, true));\n if (samples.length < 2) continue;\n const row = source ? (source.data as DataPoint) : undefined;\n const color = config.stroke\n ? config.stroke\n : row\n ? typeof fill === \"function\" ? fill(row, source!.i) : fill\n : \"#444\";\n const label = row\n ? viz._drawLabel(row, source!.i as number, depth)\n : viz.schema.translate(\"Trend Line\");\n fits.push({id, label, color, axis, fit, samples, row});\n }\n return fits;\n}\n\n/** The dependent-axis values a set of fits plots, including band bounds. */\nexport function trendDomainValues(fits: TrendFit[]): number[] {\n const values: number[] = [];\n for (const {axis, samples} of fits) {\n const dep = axis === \"x\" ? \"y\" : \"x\";\n for (const s of samples) {\n values.push(s[dep] as number);\n if (s.lci !== undefined) values.push(s.lci, s.hci!);\n }\n }\n return values.filter(Number.isFinite);\n}\n\n/**\n `computePlotTrendFits` — runs after `computePlotAxisValues`: fits the\n trend lines onto `viz._trendFits` and appends their values to the\n dependent axis's values, so the non-stacked domain covers them (the\n stacked domain reads `viz._trendFits` directly). A projection's future\n positions join the independent axis's values, widening it to fit.\n*/\nexport const computePlotTrendFits: TransformStage = ({viz, plotFormattedData, xData, yData}) => {\n const axis = trendAxis(viz.schema.discrete);\n const order = (axis === \"x\" ? xData : yData) || [];\n const projected = resolveTrendType(viz._trendLine)\n ? projectionPositions(order, viz._trendLineConfig?.projection)\n : [];\n const fits = (viz._trendFits = computeTrendFits(viz, plotFormattedData || [], order, projected));\n if (!fits.length) return {};\n const extra = trendDomainValues(fits);\n const out = axis === \"x\"\n ? {yData: (yData || []).concat(extra)}\n : {xData: (xData || []).concat(extra)};\n if (!fits.some(f => f.samples.some(s => s.projected))) return out;\n return {...out, [`${axis}Data`]: order.concat(projected)};\n};\n"],"names":["groups","linearConfidence","linearPrediction","regression","isSpanAxis","projectionPositions","trendTypes","SAMPLES","trendLineDefaults","confidence","confidenceConfig","fillOpacity","confidenceLevel","group","order","projection","projectionConfig","strokeDasharray","strokeWidth","tooltip","resolveTrendType","value","includes","trendAxis","discrete","trendNumberScale","keys","map","v","categorical","some","Date","time","toNumber","index","indexOf","NaN","fromNumber","n","Math","round","trendSamplePositions","extent","categories","count","lo","hi","filter","Array","from","length","_","i","trendProjectionPositions","steps","end","max","even","min","Set","sort","a","b","isPointAxis","viz","axis","schema","seriesKey","row","depth","_ids","data","slice","join","fitGroups","rows","dep","point","r","stacked","totals","rs","reduce","s","undefined","all","_trendLineConfig","bySeries","key","_drawDepth","drawn","points","computeTrendFits","projected","type","_trendLine","config","concat","Number","isFinite","logDep","scale","toLowerCase","fill","shapeConfig","fits","id","source","fit","banded","level","band","fan","samples","sampleAt","projectedRun","predict","sample","bounds","lci","hci","step","push","forEach","color","stroke","label","_drawLabel","translate","trendDomainValues","values","computePlotTrendFits","plotFormattedData","xData","yData","_trendFits","extra","out","f"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;AAKA,GACA,SAAQA,MAAM,QAAO,WAAW;AAGhC,SAAQC,gBAAgB,EAAEC,gBAAgB,EAAEC,UAAU,QAAO,eAAe;AAK5E,SAAQC,UAAU,QAAO,oBAAoB;AAC7C,SAAQC,mBAAmB,QAAO,uBAAuB;AAKzD,8CAA8C,GAC9C,OAAO,IAAMC,aAA+B;IAC1C;IACA;IACA;IACA;IACA;CACD,CAAC;AAEF,kEAAkE,GAClE,IAAMC,UAAU;AAmChB,mCAAmC,GACnC,OAAO,SAASC;IACd,OAAO;QACLC,YAAY;QACZC,kBAAkB;YAACC,aAAa;QAAI;QACpCC,iBAAiB;QACjBC,OAAO;QACPC,OAAO;QACPC,YAAY;QACZC,kBAAkB;YAACC,iBAAiB;QAAK;QACzCA,iBAAiB;QACjBC,aAAa;QACbC,SAAS;IACX;AACF;AAEA,6EAA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;;IAOL,OAAOU,OAAOnF,MAAM,CAACmD,OAAOC,QAAQ;AACtC;AAEA;;;;;;AAMA,GACA,OAAO,IAAMgC,uBAAuC;QAAEnE,YAAAA,KAAKoE,0BAAAA,mBAAmBC,cAAAA,OAAOC,cAAAA;QAIpDtE;IAH/B,IAAMC,OAAO1C,UAAUyC,IAAIE,MAAM,CAAC1C,QAAQ;IAC1C,IAAMV,QAAQ,AAACmD,CAAAA,SAAS,MAAMoE,QAAQC,KAAI,KAAM,EAAE;IAClD,IAAMzC,YAAYzE,iBAAiB4C,IAAI+B,UAAU,IAC7C1F,oBAAoBS,QAAOkD,wBAAAA,IAAIsB,gBAAgB,cAApBtB,4CAAAA,sBAAsBjD,UAAU,IAC3D,EAAE;IACN,IAAM0F,OAAQzC,IAAIuE,UAAU,GAAG3C,iBAAiB5B,KAAKoE,qBAAqB,EAAE,EAAEtH,OAAO+E;IACrF,IAAI,CAACY,KAAKvD,MAAM,EAAE,OAAO,CAAC;IAC1B,IAAMsF,QAAQP,kBAAkBxB;IAChC,IAAMgC,MAAMxE,SAAS,MACjB;QAACqE,OAAO,AAACA,CAAAA,SAAS,EAAE,AAAD,EAAGrC,MAAM,CAACuC;IAAM,IACnC;QAACH,OAAO,AAACA,CAAAA,SAAS,EAAE,AAAD,EAAGpC,MAAM,CAACuC;IAAM;IACvC,IAAI,CAAC/B,KAAK3E,IAAI,CAAC4G,SAAAA;eAAKA,EAAEzB,OAAO,CAACnF,IAAI,CAACqD,SAAAA;mBAAKA,EAAEU,SAAS;;QAAI,OAAO4C;IAC9D,OAAO,wCAAIA,MAAK,qBAAC,AAAC,GAAO,OAALxE,MAAK,SAAQnD,MAAMmF,MAAM,CAACJ;AAChD,EAAE"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
function _instanceof(left, right) {
|
|
2
|
+
"@swc/helpers - instanceof";
|
|
3
|
+
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
4
|
+
return !!right[Symbol.hasInstance](left);
|
|
5
|
+
} else {
|
|
6
|
+
return left instanceof right;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
Trend line projections: the future independent-axis positions a fitted
|
|
11
|
+
trend line extends to (`trendLineConfig.projection`), stepping past the
|
|
12
|
+
last plotted value at the data's own spacing.
|
|
13
|
+
*/ import { timeDay, timeHour, timeMinute, timeMonth, timeSecond, timeYear } from "d3-time";
|
|
14
|
+
import { date } from "@d3plus/dom";
|
|
15
|
+
/** The calendar intervals a time axis is checked against, coarsest first. */ var intervals = [
|
|
16
|
+
timeYear,
|
|
17
|
+
timeMonth,
|
|
18
|
+
timeDay,
|
|
19
|
+
timeHour,
|
|
20
|
+
timeMinute,
|
|
21
|
+
timeSecond
|
|
22
|
+
];
|
|
23
|
+
/** The median of a non-empty list of numbers. */ function median(values) {
|
|
24
|
+
var sorted = values.slice().sort(function(a, b) {
|
|
25
|
+
return a - b;
|
|
26
|
+
});
|
|
27
|
+
var mid = sorted.length >> 1;
|
|
28
|
+
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
|
|
29
|
+
}
|
|
30
|
+
/** Drops floating point noise from a stepped number (0.1 + 0.2 → 0.3). */ var clean = function clean(n) {
|
|
31
|
+
return +n.toPrecision(12);
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
How to step along an independent axis: numbers by the median gap between
|
|
35
|
+
distinct values; dates by the coarsest calendar interval every date lands
|
|
36
|
+
on (years, months, days, …) times the median number of those intervals
|
|
37
|
+
between dates, falling back to the median gap in milliseconds. Null for a
|
|
38
|
+
category axis or fewer than two distinct values.
|
|
39
|
+
@param order The independent axis's values.
|
|
40
|
+
*/ export function trendStep(order) {
|
|
41
|
+
var time = order.some(function(v) {
|
|
42
|
+
return _instanceof(v, Date);
|
|
43
|
+
});
|
|
44
|
+
if (order.some(function(v) {
|
|
45
|
+
return !_instanceof(v, Date) && typeof v !== "number";
|
|
46
|
+
})) return null;
|
|
47
|
+
var values = Array.from(new Set(order.map(Number).filter(Number.isFinite))).sort(function(a, b) {
|
|
48
|
+
return a - b;
|
|
49
|
+
});
|
|
50
|
+
if (values.length < 2) return null;
|
|
51
|
+
var gaps = values.slice(1).map(function(v, i) {
|
|
52
|
+
return v - values[i];
|
|
53
|
+
});
|
|
54
|
+
if (!time) {
|
|
55
|
+
var step = median(gaps);
|
|
56
|
+
return function(v, k) {
|
|
57
|
+
return clean(v + step * k);
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
var dates = values.map(function(v) {
|
|
61
|
+
return new Date(v);
|
|
62
|
+
});
|
|
63
|
+
var interval = intervals.find(function(t) {
|
|
64
|
+
return dates.every(function(d) {
|
|
65
|
+
return +t.floor(d) === +d;
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
if (interval) {
|
|
69
|
+
var step1 = Math.round(median(dates.slice(1).map(function(d, i) {
|
|
70
|
+
return interval.count(dates[i], d);
|
|
71
|
+
})));
|
|
72
|
+
if (step1 > 0) return function(v, k) {
|
|
73
|
+
return interval.offset(v, step1 * k);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
var step2 = median(gaps);
|
|
77
|
+
return function(v, k) {
|
|
78
|
+
return new Date(+v + step2 * k);
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Most steps a `{to}` projection will add, so a far-off end can't run away. */ var MAX_STEPS = 1000;
|
|
82
|
+
/**
|
|
83
|
+
The future independent-axis positions a projection adds after the last
|
|
84
|
+
value of `order`: `projection` steps, or every step up to and including
|
|
85
|
+
`projection.to`. Empty when off, on a category axis, or when the end
|
|
86
|
+
isn't past the last value.
|
|
87
|
+
@param order The independent axis's values.
|
|
88
|
+
@param projection The `trendLineConfig.projection` setting.
|
|
89
|
+
*/ export function projectionPositions(order, projection) {
|
|
90
|
+
if (!projection) return [];
|
|
91
|
+
var offset = trendStep(order);
|
|
92
|
+
if (!offset) return [];
|
|
93
|
+
var time = order.some(function(v) {
|
|
94
|
+
return _instanceof(v, Date);
|
|
95
|
+
});
|
|
96
|
+
var last = order.reduce(function(a, b) {
|
|
97
|
+
return +b > +a ? b : a;
|
|
98
|
+
}, order[0]);
|
|
99
|
+
if (typeof projection === "number") {
|
|
100
|
+
var count = Math.min(Math.floor(projection), MAX_STEPS);
|
|
101
|
+
return Array.from({
|
|
102
|
+
length: Math.max(count, 0)
|
|
103
|
+
}, function(_, i) {
|
|
104
|
+
return offset(last, i + 1);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
var to = projection.to;
|
|
108
|
+
if (to === undefined || to === null) return [];
|
|
109
|
+
var end = time ? date(to) : +to;
|
|
110
|
+
if (!Number.isFinite(+end)) return [];
|
|
111
|
+
var out = [];
|
|
112
|
+
for(var k = 1; k <= MAX_STEPS; k++){
|
|
113
|
+
var next = offset(last, k);
|
|
114
|
+
if (+next > +end) break;
|
|
115
|
+
out.push(next);
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=trendProjection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/charts/Plot/trendProjection.ts"],"sourcesContent":["/**\n Trend line projections: the future independent-axis positions a fitted\n trend line extends to (`trendLineConfig.projection`), stepping past the\n last plotted value at the data's own spacing.\n*/\nimport {timeDay, timeHour, timeMinute, timeMonth, timeSecond, timeYear} from \"d3-time\";\nimport type {CountableTimeInterval} from \"d3-time\";\n\nimport {date} from \"@d3plus/dom\";\n\n/**\n The `projection` setting: a number of steps past the last value, or an\n end value to step up to (a number, or on a time axis a Date or anything\n `date` parses, such as a year).\n*/\nexport type TrendProjection = number | {to: number | string | Date};\n\n/** Steps `k` intervals past a value along the independent axis. */\nexport type TrendOffset = (value: unknown, k: number) => unknown;\n\n/** The calendar intervals a time axis is checked against, coarsest first. */\nconst intervals: CountableTimeInterval[] = [timeYear, timeMonth, timeDay, timeHour, timeMinute, timeSecond];\n\n/** The median of a non-empty list of numbers. */\nfunction median(values: number[]): number {\n const sorted = values.slice().sort((a, b) => a - b);\n const mid = sorted.length >> 1;\n return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\n/** Drops floating point noise from a stepped number (0.1 + 0.2 → 0.3). */\nconst clean = (n: number): number => +n.toPrecision(12);\n\n/**\n How to step along an independent axis: numbers by the median gap between\n distinct values; dates by the coarsest calendar interval every date lands\n on (years, months, days, …) times the median number of those intervals\n between dates, falling back to the median gap in milliseconds. Null for a\n category axis or fewer than two distinct values.\n @param order The independent axis's values.\n*/\nexport function trendStep(order: unknown[]): TrendOffset | null {\n const time = order.some(v => v instanceof Date);\n if (order.some(v => !(v instanceof Date) && typeof v !== \"number\")) return null;\n const values = Array.from(new Set(order.map(Number).filter(Number.isFinite))).sort((a, b) => a - b);\n if (values.length < 2) return null;\n const gaps = values.slice(1).map((v, i) => v - values[i]);\n\n if (!time) {\n const step = median(gaps);\n return (v, k) => clean((v as number) + step * k);\n }\n\n const dates = values.map(v => new Date(v));\n const interval = intervals.find(t => dates.every(d => +t.floor(d) === +d));\n if (interval) {\n const step = Math.round(median(dates.slice(1).map((d, i) => interval.count(dates[i], d))));\n if (step > 0) return (v, k) => interval.offset(v as Date, step * k);\n }\n const step = median(gaps);\n return (v, k) => new Date(+(v as Date) + step * k);\n}\n\n/** Most steps a `{to}` projection will add, so a far-off end can't run away. */\nconst MAX_STEPS = 1000;\n\n/**\n The future independent-axis positions a projection adds after the last\n value of `order`: `projection` steps, or every step up to and including\n `projection.to`. Empty when off, on a category axis, or when the end\n isn't past the last value.\n @param order The independent axis's values.\n @param projection The `trendLineConfig.projection` setting.\n*/\nexport function projectionPositions(order: unknown[], projection: unknown): unknown[] {\n if (!projection) return [];\n const offset = trendStep(order);\n if (!offset) return [];\n const time = order.some(v => v instanceof Date);\n const last = order.reduce<unknown>((a, b) => (+(b as number) > +(a as number) ? b : a), order[0]);\n\n if (typeof projection === \"number\") {\n const count = Math.min(Math.floor(projection), MAX_STEPS);\n return Array.from({length: Math.max(count, 0)}, (_, i) => offset(last, i + 1));\n }\n\n const to = (projection as {to?: unknown}).to;\n if (to === undefined || to === null) return [];\n const end = time ? date(to as string | number) : +(to as number);\n if (!Number.isFinite(+(end as number))) return [];\n const out: unknown[] = [];\n for (let k = 1; k <= MAX_STEPS; k++) {\n const next = offset(last, k);\n if (+(next as number) > +(end as number)) break;\n out.push(next);\n }\n return out;\n}\n"],"names":["timeDay","timeHour","timeMinute","timeMonth","timeSecond","timeYear","date","intervals","median","values","sorted","slice","sort","a","b","mid","length","clean","n","toPrecision","trendStep","order","time","some","v","Date","Array","from","Set","map","Number","filter","isFinite","gaps","i","step","k","dates","interval","find","t","every","d","floor","Math","round","count","offset","MAX_STEPS","projectionPositions","projection","last","reduce","min","max","_","to","undefined","end","out","next","push"],"mappings":";;;;;;;;AAAA;;;;AAIA,GACA,SAAQA,OAAO,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,SAAS,EAAEC,UAAU,EAAEC,QAAQ,QAAO,UAAU;AAGvF,SAAQC,IAAI,QAAO,cAAc;AAYjC,2EAA2E,GAC3E,IAAMC,YAAqC;IAACF;IAAUF;IAAWH;IAASC;IAAUC;IAAYE;CAAW;AAE3G,+CAA+C,GAC/C,SAASI,OAAOC,MAAgB;IAC9B,IAAMC,SAASD,OAAOE,KAAK,GAAGC,IAAI,CAAC,SAACC,GAAGC;eAAMD,IAAIC;;IACjD,IAAMC,MAAML,OAAOM,MAAM,IAAI;IAC7B,OAAON,OAAOM,MAAM,GAAG,IAAIN,MAAM,CAACK,IAAI,GAAG,AAACL,CAAAA,MAAM,CAACK,MAAM,EAAE,GAAGL,MAAM,CAACK,IAAI,AAAD,IAAK;AAC7E;AAEA,wEAAwE,GACxE,IAAME,QAAQ,eAACC;WAAsB,CAACA,EAAEC,WAAW,CAAC;;AAEpD;;;;;;;AAOA,GACA,OAAO,SAASC,UAAUC,KAAgB;IACxC,IAAM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A,GACA,OAAO,SAASC,oBAAoB5B,KAAgB,EAAE6B,UAAmB;IACvE,IAAI,CAACA,YAAY,OAAO,EAAE;IAC1B,IAAMH,SAAS3B,UAAUC;IACzB,IAAI,CAAC0B,QAAQ,OAAO,EAAE;IACtB,IAAMzB,OAAOD,MAAME,IAAI,CAACC,SAAAA;eAAKA,AAAC,YAADA,GAAaC;;IAC1C,IAAM0B,OAAO9B,MAAM+B,MAAM,CAAU,SAACvC,GAAGC;eAAO,CAAEA,IAAe,CAAED,IAAeC,IAAID;OAAIQ,KAAK,CAAC,EAAE;IAEhG,IAAI,OAAO6B,eAAe,UAAU;QAClC,IAAMJ,QAAQF,KAAKS,GAAG,CAACT,KAAKD,KAAK,CAACO,aAAaF;QAC/C,OAAOtB,MAAMC,IAAI,CAAC;YAACX,QAAQ4B,KAAKU,GAAG,CAACR,OAAO;QAAE,GAAG,SAACS,GAAGrB;mBAAMa,OAAOI,MAAMjB,IAAI;;IAC7E;IAEA,IAAMsB,KAAK,AAACN,WAA8BM,EAAE;IAC5C,IAAIA,OAAOC,aAAaD,OAAO,MAAM,OAAO,EAAE;IAC9C,IAAME,MAAMpC,OAAOhB,KAAKkD,MAAyB,CAAEA;IACnD,IAAI,CAAC1B,OAAOE,QAAQ,CAAC,CAAE0B,MAAiB,OAAO,EAAE;IACjD,IAAMC,MAAiB,EAAE;IACzB,IAAK,IAAIvB,IAAI,GAAGA,KAAKY,WAAWZ,IAAK;QACnC,IAAMwB,OAAOb,OAAOI,MAAMf;QAC1B,IAAI,CAAEwB,OAAkB,CAAEF,KAAgB;QAC1CC,IAAIE,IAAI,CAACD;IACX;IACA,OAAOD;AACT"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
Paints the fitted trend lines (`viz._trendFits`) behind the plot's marks:
|
|
3
|
-
per fit, an optional confidence band and the line itself
|
|
3
|
+
per fit, an optional confidence band and the line itself (plus its
|
|
4
|
+
projection past the data, styled by `projectionConfig`), in one
|
|
4
5
|
stably-keyed group so frames tween rather than re-enter.
|
|
5
6
|
*/ function _array_like_to_array(arr, len) {
|
|
6
7
|
if (len == null || len > arr.length) len = arr.length;
|
|
@@ -119,6 +120,8 @@ import { collectComputed, makeShape } from "../features/emitHelpers.js";
|
|
|
119
120
|
"confidence",
|
|
120
121
|
"confidenceLevel",
|
|
121
122
|
"confidenceConfig",
|
|
123
|
+
"projection",
|
|
124
|
+
"projectionConfig",
|
|
122
125
|
"tooltip",
|
|
123
126
|
"stroke"
|
|
124
127
|
];
|
|
@@ -163,14 +166,13 @@ import { collectComputed, makeShape } from "../features/emitHelpers.js";
|
|
|
163
166
|
};
|
|
164
167
|
}
|
|
165
168
|
/** Renders one fit's band (when computed) and line as a keyed group. */ function trendGroup(viz, fit, x, y) {
|
|
166
|
-
var _children;
|
|
167
169
|
var config = viz._trendLineConfig || {};
|
|
168
170
|
var children = [];
|
|
169
171
|
var id = function id() {
|
|
170
172
|
return "trend-".concat(fit.id);
|
|
171
173
|
};
|
|
172
174
|
if (fit.samples[0].lci !== undefined) {
|
|
173
|
-
var
|
|
175
|
+
var _children;
|
|
174
176
|
var band = makeShape("Area").renderMode("compute").duration(viz.schema.duration).data(fit.samples).config({
|
|
175
177
|
id: id,
|
|
176
178
|
label: false,
|
|
@@ -178,7 +180,7 @@ import { collectComputed, makeShape } from "../features/emitHelpers.js";
|
|
|
178
180
|
stroke: "none",
|
|
179
181
|
strokeWidth: 0
|
|
180
182
|
}).config(config.confidenceConfig || {}).config(bandAccessors(fit, x, y));
|
|
181
|
-
(
|
|
183
|
+
(_children = children).push.apply(_children, _to_consumable_array(collectComputed(band).map(function(n) {
|
|
182
184
|
return stamp(n, fit, false);
|
|
183
185
|
})));
|
|
184
186
|
}
|
|
@@ -186,21 +188,33 @@ import { collectComputed, makeShape } from "../features/emitHelpers.js";
|
|
|
186
188
|
var _param = _sliced_to_array(param, 1), key = _param[0];
|
|
187
189
|
return !FIT_KEYS.includes(key);
|
|
188
190
|
}));
|
|
189
|
-
var line =
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
191
|
+
var line = function line(samples, key, style) {
|
|
192
|
+
var _children;
|
|
193
|
+
if (samples.length < 2) return;
|
|
194
|
+
var shape = makeShape("Line").renderMode("compute").duration(viz.schema.duration).data(samples).config(_object_spread_props(_object_spread({}, paint), {
|
|
195
|
+
id: key,
|
|
196
|
+
label: false,
|
|
197
|
+
stroke: fit.color
|
|
198
|
+
})).config(style).config({
|
|
199
|
+
x: function x1(d) {
|
|
200
|
+
return x(d.x);
|
|
201
|
+
},
|
|
202
|
+
y: function y1(d) {
|
|
203
|
+
return y(d.y);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
(_children = children).push.apply(_children, _to_consumable_array(collectComputed(shape).map(function(n) {
|
|
207
|
+
return stamp(n, fit, config.tooltip !== false);
|
|
208
|
+
})));
|
|
209
|
+
};
|
|
210
|
+
line(fit.samples.filter(function(d) {
|
|
211
|
+
return !d.projected;
|
|
212
|
+
}), id, {});
|
|
213
|
+
line(fit.samples.filter(function(d) {
|
|
214
|
+
return d.projected;
|
|
215
|
+
}), function() {
|
|
216
|
+
return "trend-".concat(fit.id, "-projection");
|
|
217
|
+
}, config.projectionConfig || {});
|
|
204
218
|
if (!children.length) return null;
|
|
205
219
|
return {
|
|
206
220
|
type: "group",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/charts/Plot/trendScene.ts"],"sourcesContent":["/**\n Paints the fitted trend lines (`viz._trendFits`) behind the plot's marks:\n per fit, an optional confidence band and the line itself, in one\n stably-keyed group so frames tween rather than re-enter.\n*/\nimport type {SceneNode} from \"@d3plus/render\";\n\nimport {collectComputed, makeShape} from \"../features/emitHelpers.js\";\nimport type {PlotAxisFn} from \"../features/plotPaint.js\";\nimport type {VizInstance} from \"../viz/vizTypes.js\";\nimport type {TrendFit, TrendSample} from \"./trendLines.js\";\n\n/** Scene-node fields the trend line stamps for hover routing. */\nexport type TrendNode = SceneNode & {\n interactive?: boolean;\n interactionGroup?: string;\n trendFit?: TrendFit;\n children?: SceneNode[];\n};\n\n/** `trendLineConfig` keys that drive the fit or band; the rest style the Line. */\nconst FIT_KEYS = [\"group\", \"order\", \"confidence\", \"confidenceLevel\", \"confidenceConfig\", \"tooltip\", \"stroke\"];\n\n/**\n Stamps a subtree as trend chrome: pickable only when it carries a tooltip\n (`trendFit`), and dimmed with its series on hover via the series' row.\n*/\nfunction stamp(node: SceneNode, fit: TrendFit, pickable: boolean): SceneNode {\n const n = node as TrendNode;\n n.interactive = pickable;\n n.interactionGroup = \"trend\";\n if (pickable) n.trendFit = fit;\n n.datum = fit.row;\n if (n.children) n.children.forEach(c => stamp(c, fit, pickable));\n return node;\n}\n\n/** The band's Area accessors: independent axis along the samples, bounds across. */\nfunction bandAccessors(fit: TrendFit, x: PlotAxisFn, y: PlotAxisFn) {\n const along = (d: TrendSample) => (fit.axis === \"x\" ? x(d.x) : y(d.y));\n const lo = (d: TrendSample) => (fit.axis === \"x\" ? y(d.lci) : x(d.lci));\n const hi = (d: TrendSample) => (fit.axis === \"x\" ? y(d.hci) : x(d.hci));\n return fit.axis === \"x\"\n ? {x: along, x0: along, x1: null, y: lo, y0: lo, y1: hi}\n : {y: along, y0: along, y1: null, x: lo, x0: lo, x1: hi};\n}\n\n/** Renders one fit's band (when computed) and line as a keyed group. */\nfunction trendGroup(viz: VizInstance, fit: TrendFit, x: PlotAxisFn, y: PlotAxisFn): SceneNode | null {\n const config = viz._trendLineConfig || {};\n const children: SceneNode[] = [];\n const id = () => `trend-${fit.id}`;\n if (fit.samples[0].lci !== undefined) {\n const band = makeShape(\"Area\")\n .renderMode(\"compute\")\n .duration(viz.schema.duration)\n .data(fit.samples)\n .config({id, label: false, fill: fit.color, stroke: \"none\", strokeWidth: 0})\n .config((config.confidenceConfig || {}) as Record<string, unknown>)\n .config(bandAccessors(fit, x, y));\n children.push(...collectComputed(band).map(n => stamp(n, fit, false)));\n }\n const paint = Object.fromEntries(\n Object.entries(config).filter(([key]) => !FIT_KEYS.includes(key)),\n );\n const line = makeShape(\"Line\")\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/charts/Plot/trendScene.ts"],"sourcesContent":["/**\n Paints the fitted trend lines (`viz._trendFits`) behind the plot's marks:\n per fit, an optional confidence band and the line itself (plus its\n projection past the data, styled by `projectionConfig`), in one\n stably-keyed group so frames tween rather than re-enter.\n*/\nimport type {SceneNode} from \"@d3plus/render\";\n\nimport {collectComputed, makeShape} from \"../features/emitHelpers.js\";\nimport type {PlotAxisFn} from \"../features/plotPaint.js\";\nimport type {VizInstance} from \"../viz/vizTypes.js\";\nimport type {TrendFit, TrendSample} from \"./trendLines.js\";\n\n/** Scene-node fields the trend line stamps for hover routing. */\nexport type TrendNode = SceneNode & {\n interactive?: boolean;\n interactionGroup?: string;\n trendFit?: TrendFit;\n children?: SceneNode[];\n};\n\n/** `trendLineConfig` keys that drive the fit or band; the rest style the Line. */\nconst FIT_KEYS = [\n \"group\", \"order\", \"confidence\", \"confidenceLevel\", \"confidenceConfig\",\n \"projection\", \"projectionConfig\", \"tooltip\", \"stroke\",\n];\n\n/**\n Stamps a subtree as trend chrome: pickable only when it carries a tooltip\n (`trendFit`), and dimmed with its series on hover via the series' row.\n*/\nfunction stamp(node: SceneNode, fit: TrendFit, pickable: boolean): SceneNode {\n const n = node as TrendNode;\n n.interactive = pickable;\n n.interactionGroup = \"trend\";\n if (pickable) n.trendFit = fit;\n n.datum = fit.row;\n if (n.children) n.children.forEach(c => stamp(c, fit, pickable));\n return node;\n}\n\n/** The band's Area accessors: independent axis along the samples, bounds across. */\nfunction bandAccessors(fit: TrendFit, x: PlotAxisFn, y: PlotAxisFn) {\n const along = (d: TrendSample) => (fit.axis === \"x\" ? x(d.x) : y(d.y));\n const lo = (d: TrendSample) => (fit.axis === \"x\" ? y(d.lci) : x(d.lci));\n const hi = (d: TrendSample) => (fit.axis === \"x\" ? y(d.hci) : x(d.hci));\n return fit.axis === \"x\"\n ? {x: along, x0: along, x1: null, y: lo, y0: lo, y1: hi}\n : {y: along, y0: along, y1: null, x: lo, x0: lo, x1: hi};\n}\n\n/** Renders one fit's band (when computed) and line as a keyed group. */\nfunction trendGroup(viz: VizInstance, fit: TrendFit, x: PlotAxisFn, y: PlotAxisFn): SceneNode | null {\n const config = viz._trendLineConfig || {};\n const children: SceneNode[] = [];\n const id = () => `trend-${fit.id}`;\n if (fit.samples[0].lci !== undefined) {\n const band = makeShape(\"Area\")\n .renderMode(\"compute\")\n .duration(viz.schema.duration)\n .data(fit.samples)\n .config({id, label: false, fill: fit.color, stroke: \"none\", strokeWidth: 0})\n .config((config.confidenceConfig || {}) as Record<string, unknown>)\n .config(bandAccessors(fit, x, y));\n children.push(...collectComputed(band).map(n => stamp(n, fit, false)));\n }\n const paint = Object.fromEntries(\n Object.entries(config).filter(([key]) => !FIT_KEYS.includes(key)),\n );\n const line = (samples: TrendSample[], key: () => string, style: Record<string, unknown>) => {\n if (samples.length < 2) return;\n const shape = makeShape(\"Line\")\n .renderMode(\"compute\")\n .duration(viz.schema.duration)\n .data(samples)\n .config({...paint, id: key, label: false, stroke: fit.color})\n .config(style)\n .config({x: (d: TrendSample) => x(d.x), y: (d: TrendSample) => y(d.y)});\n children.push(...collectComputed(shape).map(n => stamp(n, fit, config.tooltip !== false)));\n };\n line(fit.samples.filter(d => !d.projected), id, {});\n line(\n fit.samples.filter(d => d.projected),\n () => `trend-${fit.id}-projection`,\n (config.projectionConfig || {}) as Record<string, unknown>,\n );\n if (!children.length) return null;\n return {type: \"group\", key: `plot-trend-${fit.id}`, children} as SceneNode;\n}\n\n/** The scene groups for every fitted trend line, painted behind the marks. */\nexport function emitTrendLines(viz: VizInstance, x: PlotAxisFn, y: PlotAxisFn): SceneNode[] {\n const fits = viz._trendFits || [];\n return fits\n .map(fit => trendGroup(viz, fit, x, y))\n .filter((g): g is SceneNode => g !== null);\n}\n"],"names":["collectComputed","makeShape","FIT_KEYS","stamp","node","fit","pickable","n","interactive","interactionGroup","trendFit","datum","row","children","forEach","c","bandAccessors","x","y","along","d","axis","lo","lci","hi","hci","x0","x1","y0","y1","trendGroup","viz","config","_trendLineConfig","id","samples","undefined","band","renderMode","duration","schema","data","label","fill","color","stroke","strokeWidth","confidenceConfig","push","map","paint","Object","fromEntries","entries","filter","key","includes","line","style","length","shape","tooltip","projected","projectionConfig","type","emitTrendLines","fits","_trendFits","g"],"mappings":"AAAA;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAQA,eAAe,EAAEC,SAAS,QAAO,6BAA6B;AAatE,gFAAgF,GAChF,IAAMC,WAAW;IACf;IAAS;IAAS;IAAc;IAAmB;IACnD;IAAc;IAAoB;IAAW;CAC9C;AAED;;;AAGA,GACA,SAASC,MAAMC,IAAe,EAAEC,GAAa,EAAEC,QAAiB;IAC9D,IAAMC,IAAIH;IACVG,EAAEC,WAAW,GAAGF;IAChBC,EAAEE,gBAAgB,GAAG;IACrB,IAAIH,UAAUC,EAAEG,QAAQ,GAAGL;IAC3BE,EAAEI,KAAK,GAAGN,IAAIO,GAAG;IACjB,IAAIL,EAAEM,QAAQ,EAAEN,EAAEM,QAAQ,CAACC,OAAO,CAACC,SAAAA;eAAKZ,MAAMY,GAAGV,KAAKC;;IACtD,OAAOF;AACT;AAEA,kFAAkF,GAClF,SAASY,cAAcX,GAAa,EAAEY,CAAa,EAAEC,CAAa;IAChE,IAAMC,QAAQ,eAACC;eAAoBf,IAAIgB,IAAI,KAAK,MAAMJ,EAAEG,EAAEH,CAAC,IAAIC,EAAEE,EAAEF,CAAC;;IACpE,IAAMI,K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AAMgD,OAAOnC,IAAIoC,UAAU,IAAI,EAAE;IACjC,OAAOD,KACJjB,GAAG,CAAC5C,SAAAA;eAAOyB,WAAWC,KAAK1B,KAAKY,GAAGC;OACnCoC,MAAM,CAAC,SAACc;eAAsBA,MAAM;;AACzC"}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
The tooltip shown when hovering a trend line: the series (or "Trend
|
|
3
|
+
Line"), the regression type, its fitted equation, R², and the number of
|
|
4
|
+
observations it was fit to.
|
|
5
|
+
*/ function _array_like_to_array(arr, len) {
|
|
2
6
|
if (len == null || len > arr.length) len = arr.length;
|
|
3
7
|
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
|
|
4
8
|
return arr2;
|
|
@@ -44,13 +48,10 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
44
48
|
if (n === "Map" || n === "Set") return Array.from(n);
|
|
45
49
|
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
46
50
|
}
|
|
47
|
-
|
|
48
|
-
The tooltip shown when hovering a trend line: the series (or "Trend
|
|
49
|
-
Line"), the regression type, its fitted equation, R², and the number of
|
|
50
|
-
observations it was fit to.
|
|
51
|
-
*/ import { formatAbbreviate } from "@d3plus/format";
|
|
51
|
+
import { formatAbbreviate } from "@d3plus/format";
|
|
52
52
|
import { configPrep } from "../../utils/index.js";
|
|
53
|
-
import {
|
|
53
|
+
import { tooltipSwatch, withSwatch } from "../features/tooltipSwatch.js";
|
|
54
|
+
import { axisName, axisValue, prepareTooltip } from "./sharedTooltip.js";
|
|
54
55
|
var SUPERSCRIPTS = {
|
|
55
56
|
2: "²",
|
|
56
57
|
3: "³"
|
|
@@ -116,17 +117,35 @@ var SUPERSCRIPTS = {
|
|
|
116
117
|
return n !== 0 && Math.abs(n) < 1e-3 ? n.toPrecision(3) : formatAbbreviate(n, locale);
|
|
117
118
|
};
|
|
118
119
|
}
|
|
119
|
-
/**
|
|
120
|
+
/**
|
|
121
|
+
The tooltip rows for a fit: type, equation, R², and observations. Given a
|
|
122
|
+
projected sample, it leads with that projection: its independent-axis
|
|
123
|
+
value (marked "Projected") and its predicted value, with the band's
|
|
124
|
+
bounds when drawn.
|
|
125
|
+
*/ export function trendTooltipRows(viz, trend, sample) {
|
|
120
126
|
var fit = trend.fit, axis = trend.axis;
|
|
121
127
|
var t = function t(s) {
|
|
122
128
|
return viz.schema.translate(s);
|
|
123
129
|
};
|
|
124
|
-
var rows = [
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
+
var rows = [];
|
|
131
|
+
if (sample && sample.projected) {
|
|
132
|
+
var dep = axis === "x" ? "y" : "x";
|
|
133
|
+
var value = function value(n) {
|
|
134
|
+
return axisValue(viz, dep, n);
|
|
135
|
+
};
|
|
136
|
+
var bounds = sample.lci !== undefined ? " (".concat(value(sample.lci), " – ").concat(value(sample.hci), ")") : "";
|
|
137
|
+
rows.push([
|
|
138
|
+
axisName(viz, axis),
|
|
139
|
+
"".concat(axisValue(viz, axis, sample[axis]), " (").concat(t("Projected"), ")")
|
|
140
|
+
], [
|
|
141
|
+
axisName(viz, dep),
|
|
142
|
+
"".concat(value(sample[dep])).concat(bounds)
|
|
143
|
+
]);
|
|
144
|
+
}
|
|
145
|
+
rows.push([
|
|
146
|
+
t("Trend Line"),
|
|
147
|
+
t(trendTypeNames[fit.type])
|
|
148
|
+
]);
|
|
130
149
|
// An equation in milliseconds since 1970 says nothing a reader can use.
|
|
131
150
|
if (!viz["_".concat(axis, "Time")]) rows.push([
|
|
132
151
|
t("Equation"),
|
|
@@ -141,7 +160,50 @@ var SUPERSCRIPTS = {
|
|
|
141
160
|
]);
|
|
142
161
|
return rows;
|
|
143
162
|
}
|
|
144
|
-
/**
|
|
163
|
+
/**
|
|
164
|
+
The projected step nearest a content-space pointer along the fit's
|
|
165
|
+
independent axis, when the pointer is over the projection; undefined over
|
|
166
|
+
the fitted stretch (or for a fit with no projection).
|
|
167
|
+
*/ export function nearestProjectedSample(viz, trend, cursor) {
|
|
168
|
+
var position = trend.axis === "x" ? viz._xFunc : viz._yFunc;
|
|
169
|
+
if (!position) return undefined;
|
|
170
|
+
var target = trend.axis === "x" ? cursor[0] : cursor[1];
|
|
171
|
+
var nearest = function nearest(samples) {
|
|
172
|
+
var best;
|
|
173
|
+
var gap = Infinity;
|
|
174
|
+
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
175
|
+
try {
|
|
176
|
+
for(var _iterator = samples[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
|
|
177
|
+
var sample = _step.value;
|
|
178
|
+
var d = Math.abs(position(sample[trend.axis]) - target);
|
|
179
|
+
var ref;
|
|
180
|
+
if (d < gap) ref = [
|
|
181
|
+
sample,
|
|
182
|
+
d
|
|
183
|
+
], best = ref[0], gap = ref[1], ref;
|
|
184
|
+
}
|
|
185
|
+
} catch (err) {
|
|
186
|
+
_didIteratorError = true;
|
|
187
|
+
_iteratorError = err;
|
|
188
|
+
} finally{
|
|
189
|
+
try {
|
|
190
|
+
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
|
191
|
+
_iterator.return();
|
|
192
|
+
}
|
|
193
|
+
} finally{
|
|
194
|
+
if (_didIteratorError) {
|
|
195
|
+
throw _iteratorError;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return best;
|
|
200
|
+
};
|
|
201
|
+
var best = nearest(trend.samples);
|
|
202
|
+
return best && best.projected ? nearest(trend.samples.filter(function(s) {
|
|
203
|
+
return s.step;
|
|
204
|
+
})) : undefined;
|
|
205
|
+
}
|
|
206
|
+
/** Renders the trend tooltip at the pointer, leading with the nearest projected value when over the projection. */ export function renderTrendTooltip(viz, trend, event, cursor) {
|
|
145
207
|
var native = event.nativeEvent;
|
|
146
208
|
var position = native && native.touches && native.touches.length ? [
|
|
147
209
|
native.touches[0].clientX,
|
|
@@ -153,8 +215,8 @@ var SUPERSCRIPTS = {
|
|
|
153
215
|
prepareTooltip(viz).data([
|
|
154
216
|
trend.row || {}
|
|
155
217
|
]).config(configPrep.bind(viz)(viz.schema.tooltipConfig)).title(function() {
|
|
156
|
-
return trend.label;
|
|
157
|
-
}).thead([]).tbody(trendTooltipRows(viz, trend)).footer(false).position(position).render();
|
|
218
|
+
return withSwatch(tooltipSwatch(trend.color, "Line"), trend.label);
|
|
219
|
+
}).thead([]).tbody(trendTooltipRows(viz, trend, cursor ? nearestProjectedSample(viz, trend, cursor) : undefined)).footer(false).position(position).render();
|
|
158
220
|
}
|
|
159
221
|
|
|
160
222
|
//# sourceMappingURL=trendTooltip.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/charts/Plot/trendTooltip.ts"],"sourcesContent":["/**\n The tooltip shown when hovering a trend line: the series (or \"Trend\n Line\"), the regression type, its fitted equation, R², and the number of\n observations it was fit to.\n*/\nimport {formatAbbreviate} from \"@d3plus/format\";\nimport type {RegressionResult} from \"@d3plus/math\";\nimport type {SceneEvent} from \"@d3plus/render\";\n\nimport {configPrep} from \"../../utils/index.js\";\nimport type {VizContext} from \"../../utils/configPrep.js\";\nimport type {VizInstance} from \"../viz/vizTypes.js\";\nimport {prepareTooltip} from \"./sharedTooltip.js\";\nimport type {TrendFit} from \"./trendLines.js\";\n\nconst SUPERSCRIPTS: Record<string, string> = {2: \"²\", 3: \"³\"};\n\n/** Display names for each regression type, as translation keys. */\nexport const trendTypeNames: Record<string, string> = {\n exponential: \"Exponential\",\n linear: \"Linear\",\n logarithmic: \"Logarithmic\",\n polynomial: \"Polynomial\",\n power: \"Power\",\n};\n\n/** Joins signed terms into \"a + b − c\", dropping zero terms. */\nfunction joinTerms(terms: [number, string][], format: (n: number) => string): string {\n const kept = terms.filter(([c]) => c !== 0);\n if (!kept.length) return format(0);\n return kept\n .map(([c, unit], i) => {\n const body = `${format(Math.abs(c))}${unit}`;\n if (i === 0) return c < 0 ? `−${body}` : body;\n return c < 0 ? ` − ${body}` : ` + ${body}`;\n })\n .join(\"\");\n}\n\n/**\n The fitted equation as display text, e.g. `y = 1.24x + 3.41k` or\n `y = 2e^(0.3x)`. `x` and `y` name the independent and dependent axes, and\n swap for a fit along the y axis (a horizontal chart).\n @param fit The regression result.\n @param format Formats each coefficient.\n @param axis The independent axis the fit runs along.\n*/\nexport function trendEquation(\n fit: Pick<RegressionResult, \"type\" | \"coefficients\">,\n format: (n: number) => string = String,\n axis: \"x\" | \"y\" = \"x\",\n): string {\n const x = axis;\n const y = axis === \"x\" ? \"y\" : \"x\";\n const c = fit.coefficients;\n let rhs: string;\n if (fit.type === \"exponential\") rhs = `${format(c[0])}e^(${format(c[1])}${x})`;\n else if (fit.type === \"power\") rhs = `${format(c[0])}${x}^${format(c[1])}`;\n else if (fit.type === \"logarithmic\") rhs = joinTerms([[c[1], `ln(${x})`], [c[0], \"\"]], format);\n else {\n const terms = c\n .map((coef, k): [number, string] => [coef, k === 0 ? \"\" : k === 1 ? x : `${x}${SUPERSCRIPTS[k] || `^${k}`}`])\n .reverse();\n rhs = joinTerms(terms, format);\n }\n return `${y} = ${rhs}`;\n}\n\n/** Abbreviates a coefficient, keeping three significant digits on tiny values. */\nfunction coefficientFormat(locale: string): (n: number) => string {\n return n => (n !== 0 && Math.abs(n) < 1e-3 ? n.toPrecision(3) : formatAbbreviate(n, locale));\n}\n\n/** The tooltip rows for a fit: type, equation, R², and observations. */\nexport function trendTooltipRows(viz: VizInstance, trend: TrendFit): string[][] {\n const {fit, axis} = trend;\n const t = (s: string) => viz.schema.translate(s);\n const rows = [[t(\"Trend Line\"), t(trendTypeNames[fit.type])]];\n // An equation in milliseconds since 1970 says nothing a reader can use.\n if (!viz[`_${axis}Time`])\n rows.push([t(\"Equation\"), trendEquation(fit, coefficientFormat(viz.schema.locale), axis)]);\n rows.push([\"R²\", fit.r2.toFixed(3)], [t(\"Observations\"), `${fit.n}`]);\n return rows;\n}\n\n/** Renders the trend tooltip at the pointer. */\nexport function renderTrendTooltip(viz: VizInstance, trend: TrendFit, event: SceneEvent): void {\n const native = event.nativeEvent as MouseEvent & TouchEvent;\n const position =\n native && native.touches && native.touches.length\n ? [native.touches[0].clientX, native.touches[0].clientY]\n : native\n ? [native.clientX, native.clientY]\n : event.point;\n prepareTooltip(viz)\n .data([trend.row || {}])\n .config(configPrep.bind(viz as unknown as VizContext)(viz.schema.tooltipConfig))\n .title(() => trend.label)\n .thead([])\n .tbody(trendTooltipRows(viz, trend))\n .footer(false)\n .position(position)\n .render();\n}\n"],"names":["formatAbbreviate","configPrep","prepareTooltip","SUPERSCRIPTS","trendTypeNames","exponential","linear","logarithmic","polynomial","power","joinTerms","terms","format","kept","filter","c","length","map","i","unit","body","Math","abs","join","trendEquation","fit","String","axis","x","y","coefficients","rhs","type","coef","k","reverse","coefficientFormat","locale","n","toPrecision","trendTooltipRows","viz","trend","t","s","schema","translate","rows","push","r2","toFixed","renderTrendTooltip","event","native","nativeEvent","position","touches","clientX","clientY","point","data","row","config","bind","tooltipConfig","title","label","thead","tbody","footer","render"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;AAIA,GACA,SAAQA,gBAAgB,QAAO,iBAAiB;AAIhD,SAAQC,UAAU,QAAO,uBAAuB;AAGhD,SAAQC,cAAc,QAAO,qBAAqB;AAGlD,IAAMC,eAAuC;IAAC,GAAG;IAAK,GAAG;AAAG;AAE5D,iEAAiE,GACjE,OAAO,IAAMC,iBAAyC;IACpDC,aAAa;IACbC,QAAQ;IACRC,aAAa;IACbC,YAAY;IACZC,OAAO;AACT,EAAE;AAEF,8DAA8D,GAC9D,SAASC,UAAUC,KAAyB,EAAEC,MAA6B;IACzE,IAAMC,OAAOF,MAAMG,MAAM,CAAC;iDAAEC;eAAOA,MAAM;;IACzC,IAAI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J,OAAOK,OAAO;KAAC,GAChCN,MAAMO,KAAK;IACnBzD,eAAeuC,KACZmB,IAAI,CAAC;QAAClB,MAAMmB,GAAG,IAAI,CAAC;KAAE,EACtBC,MAAM,CAAC7D,WAAW8D,IAAI,CAACtB,KAA8BA,IAAII,MAAM,CAACmB,aAAa,GAC7EC,KAAK,CAAC;eAAMvB,MAAMwB,KAAK;OACvBC,KAAK,CAAC,EAAE,EACRC,KAAK,CAAC5B,iBAAiBC,KAAKC,QAC5B2B,MAAM,CAAC,OACPd,QAAQ,CAACA,UACTe,MAAM;AACX"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/charts/Plot/trendTooltip.ts"],"sourcesContent":["/**\n The tooltip shown when hovering a trend line: the series (or \"Trend\n Line\"), the regression type, its fitted equation, R², and the number of\n observations it was fit to.\n*/\nimport type {DataPoint} from \"@d3plus/data\";\nimport {formatAbbreviate} from \"@d3plus/format\";\nimport type {RegressionResult} from \"@d3plus/math\";\nimport type {SceneEvent} from \"@d3plus/render\";\n\nimport {configPrep} from \"../../utils/index.js\";\nimport type {VizContext} from \"../../utils/configPrep.js\";\nimport {tooltipSwatch, withSwatch} from \"../features/tooltipSwatch.js\";\nimport type {VizInstance} from \"../viz/vizTypes.js\";\nimport {axisName, axisValue, prepareTooltip} from \"./sharedTooltip.js\";\nimport type {TrendFit, TrendSample} from \"./trendLines.js\";\n\nconst SUPERSCRIPTS: Record<string, string> = {2: \"²\", 3: \"³\"};\n\n/** Display names for each regression type, as translation keys. */\nexport const trendTypeNames: Record<string, string> = {\n exponential: \"Exponential\",\n linear: \"Linear\",\n logarithmic: \"Logarithmic\",\n polynomial: \"Polynomial\",\n power: \"Power\",\n};\n\n/** Joins signed terms into \"a + b − c\", dropping zero terms. */\nfunction joinTerms(terms: [number, string][], format: (n: number) => string): string {\n const kept = terms.filter(([c]) => c !== 0);\n if (!kept.length) return format(0);\n return kept\n .map(([c, unit], i) => {\n const body = `${format(Math.abs(c))}${unit}`;\n if (i === 0) return c < 0 ? `−${body}` : body;\n return c < 0 ? ` − ${body}` : ` + ${body}`;\n })\n .join(\"\");\n}\n\n/**\n The fitted equation as display text, e.g. `y = 1.24x + 3.41k` or\n `y = 2e^(0.3x)`. `x` and `y` name the independent and dependent axes, and\n swap for a fit along the y axis (a horizontal chart).\n @param fit The regression result.\n @param format Formats each coefficient.\n @param axis The independent axis the fit runs along.\n*/\nexport function trendEquation(\n fit: Pick<RegressionResult, \"type\" | \"coefficients\">,\n format: (n: number) => string = String,\n axis: \"x\" | \"y\" = \"x\",\n): string {\n const x = axis;\n const y = axis === \"x\" ? \"y\" : \"x\";\n const c = fit.coefficients;\n let rhs: string;\n if (fit.type === \"exponential\") rhs = `${format(c[0])}e^(${format(c[1])}${x})`;\n else if (fit.type === \"power\") rhs = `${format(c[0])}${x}^${format(c[1])}`;\n else if (fit.type === \"logarithmic\") rhs = joinTerms([[c[1], `ln(${x})`], [c[0], \"\"]], format);\n else {\n const terms = c\n .map((coef, k): [number, string] => [coef, k === 0 ? \"\" : k === 1 ? x : `${x}${SUPERSCRIPTS[k] || `^${k}`}`])\n .reverse();\n rhs = joinTerms(terms, format);\n }\n return `${y} = ${rhs}`;\n}\n\n/** Abbreviates a coefficient, keeping three significant digits on tiny values. */\nfunction coefficientFormat(locale: string): (n: number) => string {\n return n => (n !== 0 && Math.abs(n) < 1e-3 ? n.toPrecision(3) : formatAbbreviate(n, locale));\n}\n\n/**\n The tooltip rows for a fit: type, equation, R², and observations. Given a\n projected sample, it leads with that projection: its independent-axis\n value (marked \"Projected\") and its predicted value, with the band's\n bounds when drawn.\n*/\nexport function trendTooltipRows(viz: VizInstance, trend: TrendFit, sample?: TrendSample): string[][] {\n const {fit, axis} = trend;\n const t = (s: string) => viz.schema.translate(s);\n const rows: string[][] = [];\n if (sample && sample.projected) {\n const dep = axis === \"x\" ? \"y\" : \"x\";\n const value = (n: unknown) => axisValue(viz, dep, n);\n const bounds = sample.lci !== undefined ? ` (${value(sample.lci)} – ${value(sample.hci)})` : \"\";\n rows.push(\n [axisName(viz, axis), `${axisValue(viz, axis, sample[axis])} (${t(\"Projected\")})`],\n [axisName(viz, dep), `${value(sample[dep])}${bounds}`],\n );\n }\n rows.push([t(\"Trend Line\"), t(trendTypeNames[fit.type])]);\n // An equation in milliseconds since 1970 says nothing a reader can use.\n if (!viz[`_${axis}Time`])\n rows.push([t(\"Equation\"), trendEquation(fit, coefficientFormat(viz.schema.locale), axis)]);\n rows.push([\"R²\", fit.r2.toFixed(3)], [t(\"Observations\"), `${fit.n}`]);\n return rows;\n}\n\n/**\n The projected step nearest a content-space pointer along the fit's\n independent axis, when the pointer is over the projection; undefined over\n the fitted stretch (or for a fit with no projection).\n*/\nexport function nearestProjectedSample(\n viz: VizInstance,\n trend: TrendFit,\n cursor: [number, number],\n): TrendSample | undefined {\n const position = trend.axis === \"x\" ? viz._xFunc : viz._yFunc;\n if (!position) return undefined;\n const target = trend.axis === \"x\" ? cursor[0] : cursor[1];\n const nearest = (samples: TrendSample[]): TrendSample | undefined => {\n let best: TrendSample | undefined;\n let gap = Infinity;\n for (const sample of samples) {\n const d = Math.abs(position(sample[trend.axis] as DataPoint) - target);\n if (d < gap) [best, gap] = [sample, d];\n }\n return best;\n };\n const best = nearest(trend.samples);\n return best && best.projected ? nearest(trend.samples.filter(s => s.step)) : undefined;\n}\n\n/** Renders the trend tooltip at the pointer, leading with the nearest projected value when over the projection. */\nexport function renderTrendTooltip(\n viz: VizInstance,\n trend: TrendFit,\n event: SceneEvent,\n cursor?: [number, number],\n): void {\n const native = event.nativeEvent as MouseEvent & TouchEvent;\n const position =\n native && native.touches && native.touches.length\n ? [native.touches[0].clientX, native.touches[0].clientY]\n : native\n ? [native.clientX, native.clientY]\n : event.point;\n prepareTooltip(viz)\n .data([trend.row || {}])\n .config(configPrep.bind(viz as unknown as VizContext)(viz.schema.tooltipConfig))\n .title(() => withSwatch(tooltipSwatch(trend.color, \"Line\"), trend.label))\n .thead([])\n .tbody(trendTooltipRows(viz, trend, cursor ? nearestProjectedSample(viz, trend, cursor) : undefined))\n .footer(false)\n .position(position)\n .render();\n}\n"],"names":["formatAbbreviate","configPrep","tooltipSwatch","withSwatch","axisName","axisValue","prepareTooltip","SUPERSCRIPTS","trendTypeNames","exponential","linear","logarithmic","polynomial","power","joinTerms","terms","format","kept","filter","c","length","map","i","unit","body","Math","abs","join","trendEquation","fit","String","axis","x","y","coefficients","rhs","type","coef","k","reverse","coefficientFormat","locale","n","toPrecision","trendTooltipRows","viz","trend","sample","t","s","schema","translate","rows","projected","dep","value","bounds","lci","undefined","hci","push","r2","toFixed","nearestProjectedSample","cursor","position","_xFunc","_yFunc","target","nearest","samples","best","gap","Infinity","d","step","renderTrendTooltip","event","native","nativeEvent","touches","clientX","clientY","point","data","row","config","bind","tooltipConfig","title","color","label","thead","tbody","footer","render"],"mappings":"AAAA;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAQA,gBAAgB,QAAO,iBAAiB;AAIhD,SAAQC,UAAU,QAAO,uBAAuB;AAEhD,SAAQC,aAAa,EAAEC,UAAU,QAAO,+BAA+B;AAEvE,SAAQC,QAAQ,EAAEC,SAAS,EAAEC,cAAc,QAAO,qBAAqB;AAGvE,IAAMC,eAAuC;IAAC,GAAG;IAAK,GAAG;AAAG;AAE5D,iEAAiE,GACjE,OAAO,IAAMC,iBAAyC;IACpDC,aAAa;IACbC,QAAQ;IACRC,aAAa;IACbC,YAAY;IACZC,OAAO;AACT,EAAE;AAEF,8DAA8D,GAC9D,SAASC,UAAUC,KAAyB,EAAEC,MAA6B;IACzE,IAAMC,OAAOF,MAAMG,MAAM,CAAC;iDAAEC;eAAOA,MAAM;;IACzC,IAAI,CAACF,KAAKG,MAAM,EAAE,OAAOJ,OAAO;IAChC,OAAOC,KACJI,GAAG,CAAC,gBAAYC;iDAAVH,eAAGI;QACR,IAAMC,OAAO,AAAC,GAAwBD,OAAtBP,OAAOS,KAAKC,GAAG,CA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QAAEH,OAAOE,OAAO,CAAC,EAAE,CAACE,OAAO;KAAC,GACtDJ,SACE;QAACA,OAAOG,OAAO;QAAEH,OAAOI,OAAO;KAAC,GAChCL,MAAMM,KAAK;IACnB7E,eAAeuC,KACZuC,IAAI,CAAC;QAACtC,MAAMuC,GAAG,IAAI,CAAC;KAAE,EACtBC,MAAM,CAACrF,WAAWsF,IAAI,CAAC1C,KAA8BA,IAAIK,MAAM,CAACsC,aAAa,GAC7EC,KAAK,CAAC;eAAMtF,WAAWD,cAAc4C,MAAM4C,KAAK,EAAE,SAAS5C,MAAM6C,KAAK;OACtEC,KAAK,CAAC,EAAE,EACRC,KAAK,CAACjD,iBAAiBC,KAAKC,OAAOkB,SAASD,uBAAuBlB,KAAKC,OAAOkB,UAAUN,YACzFoC,MAAM,CAAC,OACP7B,QAAQ,CAACA,UACT8B,MAAM;AACX"}
|
|
@@ -57,7 +57,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
57
57
|
*/ import { colorContrast } from "@d3plus/color";
|
|
58
58
|
import constant from "../../utils/constant.js";
|
|
59
59
|
import { emitLabels } from "../../shapes/emitLabels.js";
|
|
60
|
-
import { userLabelConfig } from "../features/emitHelpers.js";
|
|
60
|
+
import { userLabelConfig, textureFill, shapeConfigFor } from "../features/emitHelpers.js";
|
|
61
61
|
function resolveAccessor(val, d, i) {
|
|
62
62
|
if (typeof val === "function") {
|
|
63
63
|
return val(d, i);
|
|
@@ -66,13 +66,12 @@ function resolveAccessor(val, d, i) {
|
|
|
66
66
|
}
|
|
67
67
|
export var priestleyEmit = function priestleyEmit(param) {
|
|
68
68
|
var viz = param.viz, shapeData = param.shapeData;
|
|
69
|
-
var _viz_schema_shapeConfig;
|
|
70
69
|
var data = shapeData !== null && shapeData !== void 0 ? shapeData : [];
|
|
71
70
|
if (!data.length) return [];
|
|
72
71
|
var xScale = viz.ctx.xScale;
|
|
73
72
|
var yScale = viz.ctx.yScale;
|
|
74
73
|
var bandWidth = viz.ctx.bandWidth;
|
|
75
|
-
var sc = (
|
|
74
|
+
var sc = shapeConfigFor(viz, "Rect");
|
|
76
75
|
var rectNodes = data.map(function(d, i) {
|
|
77
76
|
var _yScale;
|
|
78
77
|
var fill = resolveAccessor(sc.fill, d.data, i);
|
|
@@ -101,7 +100,7 @@ export var priestleyEmit = function priestleyEmit(param) {
|
|
|
101
100
|
height: bandWidth,
|
|
102
101
|
datum: d.data,
|
|
103
102
|
paint: {
|
|
104
|
-
fill:
|
|
103
|
+
fill: textureFill(sc, d.data, i, fill),
|
|
105
104
|
stroke: stroke,
|
|
106
105
|
strokeWidth: strokeWidth
|
|
107
106
|
},
|