Brush
1980
1990
2000
2010
0
2
4
6
A line chart with a brush under it. The Brush.html.svelte component reports a min and max from 0 to 1 through bindable props, and the top chart shows only that slice of the rows. Drag on the bottom chart to try it.
This is the server-side rendered version. ssr and percentRange on <LayerCake> put the scales in percentages, so the chart renders before the browser measures it. The axes are HTML components and the marks sit in a <ScaledSvg> that stretches to fit its box. The brush is HTML, so it works the same way in both versions.
- +page.svelte
- ./_components/Line.svelte
- ./_components/Area.svelte
- ./_components/AxisX.percent-range.html.svelte
- ./_components/AxisY.percent-range.html.svelte
- ./_components/Brush.html.svelte
- ./_data/points.csv
<script>
import { LayerCake, ScaledSvg, Html } from 'layercake';
import Line from './_components/Line.svelte';
import Area from './_components/Area.svelte';
import AxisX from './_components/AxisX.percent-range.html.svelte';
import AxisY from './_components/AxisY.percent-range.html.svelte';
import Brush from './_components/Brush.html.svelte';
// The CSV rows are parsed, and their numbers typed, by @rollup/plugin-dsv. See vite.config.js
import data from './_data/points.csv';
/** @type {[number|null, number|null]} */
let brushExtents = $state([null, null]);
const xKey = 'myX';
const yKey = 'myY';
// The rows inside the brush, with at least two so the line still draws when the brush is very narrow
let brushedData = $derived.by(() => {
const start = (brushExtents[0] ?? 0) * data.length;
const end = (brushExtents[1] ?? 1) * data.length;
const selection = data.slice(start, end);
if (selection.length < 2) return data.slice(start, start + 2);
return selection;
});
</script>
<div class="brushed-chart-container">
<LayerCake
ssr
percentRange
padding={{ bottom: 20, left: 25 }}
x={xKey}
y={yKey}
yDomain={[0, null]}
data={brushedData}
>
<Html>
<AxisX
ticks={ticks => {
const filtered = ticks.filter(t => t % 1 === 0);
if (filtered.length > 7) {
return filtered.filter((t, i) => i % 2 === 0);
}
return filtered;
}}
/>
<AxisY ticks={4} />
</Html>
<ScaledSvg>
<Line stroke="#00e047" />
<Area fill="#00e04710" />
</ScaledSvg>
</LayerCake>
</div>
<div class="brush-container">
<LayerCake ssr percentRange padding={{ top: 5 }} x={xKey} y={yKey} yDomain={[0, null]} {data}>
<ScaledSvg>
<Line stroke="#00e047" />
<Area fill="#00e04710" />
</ScaledSvg>
<Html>
<Brush bind:min={brushExtents[0]} bind:max={brushExtents[1]} />
</Html>
</LayerCake>
</div>
<style>
/* Give the wrapper a width and height. LayerCake fills it. */
.brushed-chart-container {
width: 100%;
height: 80%;
}
.brush-container {
width: 100%;
height: 20%;
}
</style><!--
@component
Generates an SVG line shape.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {string} [stroke='#ab00d6'] - The line's stroke color.
*/
/** @type {Props} */
let { stroke = '#ab00d6' } = $props();
let path = $derived(
'M' +
k.data
.map(d => {
return k.xGet(d) + ',' + k.yGet(d);
})
.join('L')
);
</script>
<path class="path-line" d={path} {stroke}></path>
<style>
.path-line {
fill: none;
stroke-linejoin: round;
stroke-linecap: round;
stroke-width: 2px;
}
</style><!--
@component
Generates an SVG area shape.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {string} [fill='#ab00d610'] - The shape's fill color.
*/
/** @type {Props} */
let { fill = '#ab00d610' } = $props();
let path = $derived(
'M' +
k.data
.map(d => {
return k.xGet(d) + ',' + k.yGet(d);
})
.join('L')
);
// Close the line along the bottom of the chart to make the area
/** @type {string} */
let area = $derived.by(() => {
const yRange = k.yScale.range();
return (
path +
('L' +
k.xScale(k.extents.x ? k.extents.x[1] : 0) +
',' +
yRange[0] +
'L' +
k.xScale(k.extents.x ? k.extents.x[0] : 0) +
',' +
yRange[0] +
'Z')
);
});
</script>
<path class="path-area" d={area} {fill}></path><!--
@component
Generates an HTML x-axis along the bottom of the chart, for server-side rendered charts. If the x scale is a band scale, each tick sits in the middle of its band.
Positions are percentages when `percentRange={true}` and pixels otherwise, so this also works in a client-side chart with no setup. Set the `units` prop to `'%'` or `'px'` to override that.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {boolean} [tickMarks=false] - Show a vertical mark at each tick.
* @property {boolean} [gridlines=true] - Show gridlines extending into the chart area.
* @property {number} [tickMarkLength=6] - The length of the tick mark.
* @property {boolean} [showBaseline=false] - Show a solid line along the bottom of the chart.
* @property {boolean} [snapLabels=false] - Instead of centering the text labels on the first and the last items, align them to the edges of the chart.
* @property {(d: any) => string} [format=d => d] - Formats a tick value for display.
* @property {number|Array<any>|((ticks: Array<any>) => Array<any>)} [ticks] - If this is a number, it passes that along to the [d3Scale.ticks](https://github.com/d3/d3-scale) function. If this is an array, hardcodes the ticks to those values. If it's a function, passes along the default tick values and expects an array of tick values in return. If nothing, it uses the default ticks supplied by the D3 function.
* @property {number} [tickGutter=0] - The gap in pixels between the bottom of the chart area and the start of the tick.
* @property {number} [dx=0] - Horizontal offset of the label in pixels.
* @property {number} [dy=0] - Vertical offset of the label in pixels.
* @property {'px'|'%'} [units] - Position with pixels or percentages. Defaults to `'%'` when `percentRange={true}`, otherwise `'px'`.
*/
/** @type {Props} */
let {
tickMarks = false,
gridlines = true,
tickMarkLength = 6,
showBaseline = false,
snapLabels = false,
format = d => d,
ticks = undefined,
tickGutter = 0,
dx = 0,
dy = 0,
units = k.percentRange === true ? '%' : 'px'
} = $props();
let tickLen = $derived(tickMarks === true ? (tickMarkLength ?? 6) : 0);
let isBandwidth = $derived(typeof k.xScale.bandwidth === 'function');
/** @type {Array<any>} */
let tickVals = $derived(
Array.isArray(ticks)
? ticks
: isBandwidth
? k.xScale.domain()
: typeof ticks === 'function'
? ticks(k.xScale.ticks())
: k.xScale.ticks(ticks)
);
let halfBand = $derived(isBandwidth ? k.xScale.bandwidth() / 2 : 0);
</script>
<div class="axis x-axis" class:snapLabels>
{#if showBaseline === true}
<div class="baseline" style="top:100%; width:100%;"></div>
{/if}
{#each tickVals as tick, i (tick)}
{@const tickValUnits = k.xScale(tick)}
{#if gridlines === true}
<div
class="gridline"
style:left="{tickValUnits + halfBand}{units}"
style="top:0; bottom:0;"
></div>
{/if}
{#if tickMarks === true}
<div
class="tick-mark"
style:left="{tickValUnits + halfBand}{units}"
style:height="{tickLen}px"
style:bottom="{-tickLen - tickGutter}px"
></div>
{/if}
<div
class="tick tick-{i}"
style:left="{tickValUnits + halfBand}{units}"
style="top:calc(100% + {tickGutter}px);"
>
<div
class="text"
style:top="{tickLen}px"
style:transform="translate(calc(-50% + {dx}px), {dy}px)"
>
{format(tick)}
</div>
</div>
{/each}
</div>
<style>
.axis,
.tick,
.tick-mark,
.gridline,
.baseline {
position: absolute;
}
.axis {
width: 100%;
height: 100%;
}
.tick {
font-size: 11px;
}
.gridline {
border-left: 1px dashed #aaa;
}
.tick-mark {
border-left: 1px solid #aaa;
}
.baseline {
border-top: 1px solid #aaa;
}
.tick .text {
color: #666;
position: relative;
white-space: nowrap;
transform: translateX(-50%);
}
/* Snapped end labels sit 40% inside their edge instead of centered on it */
.axis.snapLabels .tick:last-child {
transform: translateX(-40%);
}
.axis.snapLabels .tick.tick-0 {
transform: translateX(40%);
}
</style><!--
@component
Generates an HTML y-axis along the left edge of the chart, for server-side rendered charts. If the y scale is a band scale, each tick sits in the middle of its band.
Positions are percentages when `percentRange={true}` and pixels otherwise, so this also works in a client-side chart with no setup. Set the `units` prop to `'%'` or `'px'` to override that.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {boolean} [tickMarks=false] - Show a horizontal mark at each tick.
* @property {'even'|'above'} [labelPosition='even'] - Whether the label sits level with its tick ('even') or above it ('above').
* @property {boolean} [snapBaselineLabel=false] - When labelPosition='even', adjust the lowest label so that it sits above the tick mark.
* @property {boolean} [gridlines=true] - Show gridlines extending into the chart area.
* @property {number} [tickMarkLength] - Length of the tick mark in pixels. Defaults to the width of the widest label when `labelPosition` is 'above', otherwise 6.
* @property {(d: any) => string} [format=d => d] - Formats a tick value for display.
* @property {number|Array<any>|((ticks: Array<any>) => Array<any>)} [ticks=4] - If this is a number, it passes that along to the [d3Scale.ticks](https://github.com/d3/d3-scale) function. If this is an array, hardcodes the ticks to those values. If it's a function, passes along the default tick values and expects an array of tick values in return.
* @property {number} [tickGutter=0] - The gap in pixels between the left edge of the chart area and the tick.
* @property {number} [dx=0] - Horizontal offset of the label in pixels.
* @property {number} [dy=-3] - Vertical offset of the label in pixels.
* @property {number} [charPixelWidth=7.25] - Used to calculate the widest label length to offset labels. Adjust if the automatic tick length doesn't look right because you have a bigger font (or just set `tickMarkLength` to a pixel value).
* @property {'px'|'%'} [units] - Position with pixels or percentages. Defaults to `'%'` when `percentRange={true}`, otherwise `'px'`.
*/
/** @type {Props} */
let {
tickMarks = false,
labelPosition = 'even',
snapBaselineLabel = false,
gridlines = true,
tickMarkLength = undefined,
format = d => d,
ticks = 4,
tickGutter = 0,
dx = 0,
dy = -3,
charPixelWidth = 7.25,
units = k.percentRange === true ? '%' : 'px'
} = $props();
/** @param {number} sum
* @param {string} val */
function calcStringLength(sum, val) {
if (val === ',' || val === '.') return sum + charPixelWidth * 0.5;
return sum + charPixelWidth;
}
let isBandwidth = $derived(typeof k.yScale.bandwidth === 'function');
/** @type {Array<any>} */
let tickVals = $derived(
Array.isArray(ticks)
? ticks
: isBandwidth
? k.yScale.domain()
: typeof ticks === 'function'
? ticks(k.yScale.ticks())
: k.yScale.ticks(ticks)
);
let widestTickLen = $derived(
Math.max(
10,
Math.max(...tickVals.map(d => format(d).toString().split('').reduce(calcStringLength, 0)))
)
);
let tickLen = $derived(
tickMarks === true
? labelPosition === 'above'
? (tickMarkLength ?? widestTickLen)
: (tickMarkLength ?? 6)
: 0
);
let x1 = $derived(-tickGutter - (labelPosition === 'above' ? widestTickLen : tickLen));
let halfBand = $derived(isBandwidth ? k.yScale.bandwidth() / 2 : 0);
let maxTickValUnits = $derived(Math.max(...tickVals.map(k.yScale)));
</script>
<div class="axis y-axis">
{#each tickVals as tick, i (tick)}
{@const tickValUnits = k.yScale(tick)}
<div
class="tick tick-{i}"
style="left:{k.xRange ? k.xRange[0] : 0}{units};top:{tickValUnits + halfBand}{units};"
>
{#if gridlines === true}
<div class="gridline" style="top:0;" style:left="{x1}px" style:right="0px"></div>
{/if}
{#if tickMarks === true}
<div class="tick-mark" style:top="0" style:left="{x1}px" style:width="{tickLen}px"></div>
{/if}
<div
class="text"
style:top="0"
style:text-align={labelPosition === 'even' ? 'right' : 'left'}
style:width="{widestTickLen}px"
style:left="{-widestTickLen - tickGutter - (labelPosition === 'even' ? tickLen : 0)}px"
style:transform="translate({dx + (labelPosition === 'even' ? -3 : 0)}px, calc(-50% + {dy +
(labelPosition === 'above' ||
(snapBaselineLabel === true && tickValUnits === maxTickValUnits)
? -3
: 4)}px))"
>
{format(tick)}
</div>
</div>
{/each}
</div>
<style>
.axis,
.tick,
.tick-mark,
.gridline,
.text {
position: absolute;
}
.axis {
width: 100%;
height: 100%;
}
.tick {
font-size: 11px;
width: 100%;
}
.gridline {
border-top: 1px dashed #aaa;
}
.tick-mark {
border-top: 1px solid #aaa;
}
.tick .text {
color: #666;
}
</style><!--
@component
Adds an HTML brush for picking a range from 0 to 1. Drag on the track to draw one, or focus a handle and use the arrow keys. Bind `min` and `max` to read the range elsewhere. See the [brush example](https://layercake.graphics/example/Brush).
-->
<script>
import { clamp } from 'yootils';
/**
* @typedef {Object} Props
* @property {number|null} [min=null] - Where the brush starts, from 0 to 1. Bind to it.
* @property {number|null} [max=null] - Where the brush ends, from 0 to 1. Bind to it.
*/
/** @type {Props} */
let { min = $bindable(null), max = $bindable(null) } = $props();
/** @type {HTMLDivElement|undefined} */
let brush = $state();
// A horizontal page position as a share of the brush's width, from 0 to 1
/** @param {number} clientX */
function fractionAcross(clientX) {
if (!brush) return 0;
const { left, right } = brush.getBoundingClientRect();
return clamp((clientX - left) / (right - left), 0, 1);
}
/** @typedef {{ min: number, max: number, p: number }} DragStart The range and pointer position when a drag began. */
// Wraps a drag rule so it runs on every mouse or touch move until the pointer lifts.
// It gets the range as it was when the drag began and the pointer's current position.
/** @param {(start: DragStart, p: number) => void} fn */
function handler(fn) {
/** @param {MouseEvent|TouchEvent} e */
return e => {
e.stopPropagation();
e.preventDefault();
// Only follow one finger at a time
/** @type {number|undefined} */
let touchId;
/** @type {{ clientX: number }} */
let point = /** @type {MouseEvent} */ (e);
if ('touches' in e) {
if (e.touches.length !== 1) return;
point = e.touches[0];
touchId = e.touches[0].identifier;
}
const start = { min: min ?? 0, max: max ?? 1, p: fractionAcross(point.clientX) };
/** @param {MouseEvent|TouchEvent} e */
const handleMove = e => {
e.preventDefault();
/** @type {{ clientX: number }} */
let moved = /** @type {MouseEvent} */ (e);
if ('changedTouches' in e) {
if (e.changedTouches.length !== 1) return;
if (e.changedTouches[0].identifier !== touchId) return;
moved = e.changedTouches[0];
}
fn(start, fractionAcross(moved.clientX));
};
/** @param {MouseEvent|TouchEvent} e */
const handleEnd = e => {
if ('changedTouches' in e) {
if (e.changedTouches.length !== 1) return;
if (e.changedTouches[0].identifier !== touchId) return;
} else if (e.target === brush) {
// A click on the empty track clears the range
clear();
}
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', handleEnd);
window.removeEventListener('touchmove', handleMove);
window.removeEventListener('touchend', handleEnd);
};
window.addEventListener('mousemove', handleMove);
window.addEventListener('mouseup', handleEnd);
window.addEventListener('touchmove', handleMove);
window.addEventListener('touchend', handleEnd);
};
}
function clear() {
min = null;
max = null;
}
// Drag on the track to draw a new range
const reset = handler((start, p) => {
min = clamp(Math.min(start.p, p), 0, 1);
max = clamp(Math.max(start.p, p), 0, 1);
});
// Drag the range to slide it along, keeping its width
const move = handler((start, p) => {
const d = clamp(p - start.p, -start.min, 1 - start.max);
min = start.min + d;
max = start.max + d;
});
// Drag a handle to move one end, swapping ends if it crosses the other
const adjustMin = handler((start, p) => {
min = p > start.max ? start.max : p;
max = p > start.max ? p : start.max;
});
const adjustMax = handler((start, p) => {
min = p < start.min ? p : start.min;
max = p < start.min ? start.min : p;
});
// Arrow keys nudge by a hundredth, or a tenth with shift. Home and End go to
// the edges. Escape clears the range. With no range yet, the handles sit at
// the edges, so the first key press draws one.
/** @param {KeyboardEvent} e @param {'min'|'max'|'both'} part Which part of the range the key moves. */
function handleKeydown(e, part) {
const step = e.shiftKey ? 0.1 : 0.01;
const start = { min: min ?? 0, max: max ?? 1 };
let delta;
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') delta = -step;
else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') delta = step;
else if (e.key === 'Home') delta = -1;
else if (e.key === 'End') delta = 1;
else if (e.key === 'Escape') {
clear();
return;
} else return;
e.preventDefault();
if (part === 'both') {
const d = clamp(delta, -start.min, 1 - start.max);
min = start.min + d;
max = start.max + d;
} else if (part === 'min') {
const p = clamp(start.min + delta, 0, 1);
min = Math.min(p, start.max);
max = Math.max(p, start.max);
} else {
const p = clamp(start.max + delta, 0, 1);
min = Math.min(p, start.min);
max = Math.max(p, start.min);
}
}
let left = $derived(100 * (min ?? 0));
let right = $derived(100 * (1 - (max ?? 1)));
/** @param {number} value */
const percent = value => `${Math.round(value * 100)}%`;
</script>
<!-- The track itself is mouse and touch only. Keyboard users work the range and its two handles, which are sliders. -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div bind:this={brush} class="brush-outer" onmousedown={reset} ontouchstart={reset}>
{#if min !== null && max !== null}
<div
class="brush-inner"
role="slider"
tabindex="0"
aria-label="Selected range"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={Math.round(min * 100)}
aria-valuetext="{percent(min)} to {percent(max)}"
draggable="false"
onmousedown={move}
ontouchstart={move}
onkeydown={e => handleKeydown(e, 'both')}
style="left: {left}%; right: {right}%"
></div>
{/if}
<!-- The handles stay in the DOM with no range so they can be focused, but the mouse then goes to the track -->
<div
class="brush-handle"
class:idle={min === null}
role="slider"
tabindex="0"
aria-label="Start of range"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={Math.round((min ?? 0) * 100)}
aria-valuetext={percent(min ?? 0)}
draggable="false"
onmousedown={adjustMin}
ontouchstart={adjustMin}
onkeydown={e => handleKeydown(e, 'min')}
style="left: {left}%"
></div>
<div
class="brush-handle"
class:idle={max === null}
role="slider"
tabindex="0"
aria-label="End of range"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={Math.round((max ?? 1) * 100)}
aria-valuetext={percent(max ?? 1)}
draggable="false"
onmousedown={adjustMax}
ontouchstart={adjustMax}
onkeydown={e => handleKeydown(e, 'max')}
style="right: {right}%"
></div>
</div>
<style>
.brush-outer {
position: relative;
width: 100%;
height: calc(100% + 5px);
top: -5px;
}
.brush-inner {
position: absolute;
height: 100%;
cursor: move;
background-color: #cccccc90;
}
.brush-handle {
position: absolute;
width: 0;
height: 100%;
cursor: ew-resize;
}
.brush-handle.idle {
pointer-events: none;
}
.brush-handle::before {
position: absolute;
content: '';
width: 8px;
left: -4px;
height: 100%;
background: transparent;
}
</style>myX,myY 1979,7.19 1980,7.83 1981,7.24 1982,7.44 1983,7.51 1984,7.1 1985,6.91 1986,7.53 1987,7.47 1988,7.48 1989,7.03 1990,6.23 1991,6.54 1992,7.54 1993,6.5 1994,7.18 1995,6.12 1996,7.87 1997,6.73 1998,6.55 1999,6.23 2000,6.31 2001,6.74 2002,5.95 2003,6.13 2004,6.04 2005,5.56 2006,5.91 2007,4.29 2008,4.72 2009,5.38 2010,4.92 2011,4.61 2012,3.62 2013,5.35 2014,5.28 2015,4.63 2016,4.72