Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Is this the only way to get DaisyUI colors based on the theme in Svelte?

$
0
0

I'm using Svelte with DaisyUI and need to retrieve the current theme colors dynamically. I rely on these colors in chroma-js, so it’s crucial to get them correctly. The code below works for me, but it feels like there might be a more efficient or idiomatic way to achieve this. Is this the only/best approach to get the current theme colors from DaisyUI?

Here’s the relevant code snippet:

<script lang="ts">    import { onMount } from 'svelte';    import { theme } from '$stores/global';    import type { ThemeColor, ThemeColorMap } from "$type/shared";    type ColorElement = {        [key in ThemeColor]?: HTMLDivElement | undefined;    };    export let colors: ThemeColorMap;    const colorKeys: ThemeColor[] = ['accent', 'info', 'neutral'];    let colorElements: ColorElement = {} as ColorElement; // This will store references to the div elements    function getColors(): ThemeColorMap {        if (typeof window === 'undefined') {            return {};        }        let newColors: ThemeColorMap = {};        Object.entries(colorElements).forEach(([key, element]) => {            if (element) {                newColors[key as ThemeColor] = getComputedStyle(element).backgroundColor;            }        });        return newColors;    }    onMount(() => {        colors = getColors();    });    theme.subscribe(() => {        colors = getColors();    });</script><div class="hidden">    {#each colorKeys as key}<div class="bg-{key}" bind:this={colorElements[key]}></div>    {/each}</div>

This approach creates hidden div elements with DaisyUI color classes, and then I use getComputedStyle to extract the background color from these elements.

While this works, it feels a bit hacky, especially with the hidden elements. Is there a more direct or efficient way to access the current DaisyUI theme colors in Svelte, particularly for use with chroma-js?

Any suggestions would be appreciated!


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>