|
2 | 2 | import { getContext } from 'svelte';
|
3 | 3 | import type { PlotContext } from 'svelteplot/types';
|
4 | 4 | import { devicePixelRatio } from 'svelte/reactivity/window';
|
| 5 | + import { MediaQuery } from 'svelte/reactivity'; |
| 6 | + import type { Attachment } from 'svelte/attachments'; |
| 7 | +
|
| 8 | + const darkMode = new MediaQuery('prefers-color-scheme: dark'); |
| 9 | + let colorScheme = $state(); |
| 10 | +
|
| 11 | + /** |
| 12 | + * we need to repaint on dark mode changes in case the user |
| 13 | + * is using any css variables or currentColor that changes |
| 14 | + * with the color scheme |
| 15 | + */ |
| 16 | + const watchColorScheme: Attachment = (element: Element) => { |
| 17 | + const htmlElement = element.ownerDocument.documentElement; |
| 18 | + const observer = new MutationObserver(() => { |
| 19 | + colorScheme = getComputedStyle(htmlElement).colorScheme; |
| 20 | + }); |
| 21 | + observer.observe(htmlElement, { attributes: true }); |
| 22 | + return () => { |
| 23 | + observer.disconnect(); |
| 24 | + }; |
| 25 | + }; |
5 | 26 |
|
6 | 27 | let restProps: {} = $props();
|
7 | 28 |
|
|
14 | 35 | canvas element inside a foreignObject for use in a plot and takes care of
|
15 | 36 | scaling it to the device pixel ratio.
|
16 | 37 | -->
|
17 |
| - |
18 |
| -<foreignObject x="0" y="0" width={plot.width} height={plot.height}> |
19 |
| - <canvas |
20 |
| - xmlns="http://www.w3.org/1999/xhtml" |
21 |
| - {...restProps} |
22 |
| - width={plot.width * (devicePixelRatio.current ?? 1)} |
23 |
| - height={plot.height * (devicePixelRatio.current ?? 1)} |
24 |
| - style="width: {plot.width}px; height: {plot.height}px;"></canvas> |
| 38 | +<foreignObject x="0" y="0" {@attach watchColorScheme} width={plot.width} height={plot.height}> |
| 39 | + {#key [colorScheme, darkMode.current]} |
| 40 | + <canvas |
| 41 | + xmlns="http://www.w3.org/1999/xhtml" |
| 42 | + {...restProps} |
| 43 | + width={plot.width * (devicePixelRatio.current ?? 1)} |
| 44 | + height={plot.height * (devicePixelRatio.current ?? 1)} |
| 45 | + style="width: {plot.width}px; height: {plot.height}px;"></canvas> |
| 46 | + {/key} |
25 | 47 | </foreignObject>
|
26 | 48 |
|
27 | 49 | <style>
|
|
0 commit comments