Reddit - Auto Color Scheme

Auto set dark or light mode for reddit

// ==UserScript==
// @name        Reddit - Auto Color Scheme
// @namespace   Kyan Violentmonkey Scripts
// @match       *://*.reddit.com/*
// @grant       none
// @version     1.0.1
// @license     MIT
// @author      Kyan
// @description Auto set dark or light mode for reddit
// ==/UserScript==
;(function () {
    'use strict';

    const is_dark = (ele) => ele.checked === undefined ? ele.ariaChecked === "true" : ele.checked === true

    const is_light = (ele) => is_dark(ele) === false

    const to_dark = (switch_ele) => { if (is_light(switch_ele)) switch_ele.click() }

    const to_light = (switch_ele) => { if (is_dark(switch_ele)) switch_ele.click() }

    const is_prefer_dark = () => window.matchMedia("(prefers-color-scheme: dark)").matches

    const is_prefer_light = () => window.matchMedia("(prefers-color-scheme: light)").matches

    const when_element_exist = (selector, callback)  => {
      let timer = window.setInterval(() => {
          let ele = document.querySelector(selector)
          if (ele) {
              console.log("[Auto Color Scheme] Theme Switch Element Detected.")
              clearInterval(timer)
              callback()
          }
      }, 1000)
      window.setTimeout(() => clearInterval(timer), 15000)
    }

    const theme_switch_selector = "faceplate-switch-input[name='darkmode-switch-name']"
    when_element_exist(theme_switch_selector, () => {
      // Find elements that needed
        var theme_switch = document.querySelector(theme_switch_selector)
        if (theme_switch === null) {
            console.error(`Connot find ${theme_switch_selector} element`)
            return
        }
        console.log(`[Auto Color Scheme] Prefer: ${is_prefer_light()?"[✓ Light]":"✗ Light"}, ${is_prefer_dark()?"[✓ Dark]":"✗ Dark"}`)
        console.log(`[Auto Color Scheme] Current: ${is_light(theme_switch)?"[✓ Light]":"✗ Light"}, ${is_dark(theme_switch)?"[✓ Dark]":"✗ Dark"}`)
        if (is_dark(theme_switch) && is_prefer_light()) {
            to_light(theme_switch)
            console.log("[Auto Color Scheme] Switched to Light")
        } else if (is_light(theme_switch) && is_prefer_dark()) {
            to_dark(theme_switch)
            console.log("[Auto Color Scheme] Switched to Dark")
        } else {
            console.log("[Auto Color Scheme] No need to switch")
        }
    })
})()