Sha256: da995b899868ab9a752a5c65557edfa8aed02ca82efa36ec2f653bc0e8fd0778

Contents?: true

Size: 1.56 KB

Versions: 1

Compression:

Stored size: 1.56 KB

Contents

/* @preserve Dark mode Init */
/*
 * There are two color palettes on CSS for the data-theme: 'light' and 'dark'.
 * Initially the script check if a theme is set in session storage and
 * alternatively listens to a MediaQuery callback looking for "prefers-color-scheme: dark".
 */

const themeButton = {
    'light': '<i class="fas fa-adjust" aria-hidden="true"></i>',
    'dark': '<i class="fas fa-adjust fa-rotate-180" aria-hidden="true"></i>'
}

const currentTheme = () => localStorage.getItem('theme')

function setMode(theme) {
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('theme', theme)
    const toggle = document.getElementById('theme-toggle')
    if (toggle) {
        toggle.innerHTML = themeButton[theme]
    }
}

function themeToggle() {
    let sessionPrefers = currentTheme()
    if (sessionPrefers === 'light') {
        setMode('dark')
    } else {
        setMode('light')
    }
}

function bootstrapTheme() {
    if (isAutoTheme) {
        if (!currentTheme()) {
            // Load browser's preference
            let browserPrefersDark = window.matchMedia('(prefers-color-scheme: dark)');
            if (browserPrefersDark.matches) localStorage.setItem('theme', 'dark');
            browserPrefersDark.addEventListener('change', () => {
                if (browserPrefersDark.matches) localStorage.setItem('theme', 'dark')
            });
        }

        // Load theme
        let sessionPrefers = currentTheme()
        setMode(sessionPrefers ? sessionPrefers : 'light')
    }
}

// Init
(function () {
    bootstrapTheme();
})()

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
type-on-strap-2.4.7 assets/js/partials/dark-mode.js