| 1 |
<script lang="ts"> |
| 2 |
import type { Axis } from "d3-axis"; |
| 3 |
import type { NumberValue } from "d3-scale"; |
| 4 |
import { select } from "d3-selection"; |
| 5 |
import type { Action } from "svelte/action"; |
| 6 |
|
| 7 |
type Ax = Axis<string> | Axis<NumberValue>; |
| 8 |
|
| 9 |
interface Props { |
| 10 |
/** The d3 axis to use. */ |
| 11 |
axis: Ax; |
| 12 |
/** True if this is an x axis. */ |
| 13 |
x?: boolean; |
| 14 |
/** True if this is a y axis. */ |
| 15 |
y?: boolean; |
| 16 |
/** Show a pronounced line at zero (for y axis). */ |
| 17 |
lineAtZero?: number; |
| 18 |
/** Height of the chart (needed for the correct offset of an x axis) */ |
| 19 |
innerHeight?: number; |
| 20 |
} |
| 21 |
|
| 22 |
let { |
| 23 |
axis, |
| 24 |
x = false, |
| 25 |
y = false, |
| 26 |
lineAtZero, |
| 27 |
innerHeight = 0, |
| 28 |
}: Props = $props(); |
| 29 |
|
| 30 |
let transform = $derived( |
| 31 |
x ? `translate(0,${innerHeight.toString()})` : undefined, |
| 32 |
); |
| 33 |
|
| 34 |
/** Svelte action to render the axis. */ |
| 35 |
const renderAxis: Action<SVGGElement, Ax> = (node: SVGGElement, ax) => { |
| 36 |
const selection = select(node); |
| 37 |
ax(selection); |
| 38 |
|
| 39 |
return { |
| 40 |
update(new_ax) { |
| 41 |
new_ax(selection); |
| 42 |
}, |
| 43 |
}; |
| 44 |
}; |
| 45 |
</script> |
| 46 |
|
| 47 |
<g class:y use:renderAxis={axis} {transform}> |
| 48 |
{#if y && lineAtZero != null} |
| 49 |
<g class="zero" transform={`translate(0,${lineAtZero.toString()})`}> |
| 50 |
<line x2={-axis.tickSizeInner()} /> |
| 51 |
</g> |
| 52 |
{/if} |
| 53 |
</g> |
| 54 |
|
| 55 |
<style> |
| 56 |
g :global(path), |
| 57 |
g :global(line) { |
| 58 |
fill: none; |
| 59 |
stroke: var(--chart-axis); |
| 60 |
shape-rendering: crispedges; |
| 61 |
} |
| 62 |
|
| 63 |
g.y :global(line), |
| 64 |
g.y :global(path.domain) { |
| 65 |
opacity: 0.2; |
| 66 |
} |
| 67 |
|
| 68 |
g.y .zero line { |
| 69 |
opacity: 1; |
| 70 |
stroke: #666; |
| 71 |
} |
| 72 |
</style> |