Star Citizen RSI Specturm - Auto Dark Mode

2024-07-28

// ==UserScript==
// @name        Star Citizen RSI Specturm - Auto Dark Mode
// @namespace   Kyan Violentmonkey Scripts
// @match       *://robertsspaceindustries.com/spectrum/*
// @grant       none
// @version     1.0.2
// @license     MIT
// @author      Kyan
// @description 2024-07-28
// ==/UserScript==
;(function () {
  'use strict';

  const is_dark = () => document.querySelector("#app").classList.contains("theme-dark")

  const is_light = () => document.querySelector("#app").classList.contains("theme-light")

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

  const to_light = (switch_ele) => { if (is_dark()) 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(() => {
        if (document.querySelectorAll(selector).length > 0) {
            clearInterval(timer)
            callback()
        }
    }, 1000)
    window.setTimeout(() => clearInterval(timer), 15000)
  }

  const theme_switch_selector = "label[for='toggle-button-checkbox']"
  when_element_exist(theme_switch_selector, () => {
    // Find elements that needed
    
    if (document.querySelector("#app") === null) {
      console.error("Cannot find #app element")
      return
    }

    var theme_switch = document.querySelector(theme_switch_selector)
    if (theme_switch === null) {
      console.error(`Connot find ${theme_switch_selector} element`)
      return
    }

    if (is_dark() && is_prefer_light()) {
      to_light(theme_switch)
    } else if (is_light() && is_prefer_dark()) {
      to_dark(theme_switch)
    } else {
      console.log(`[Auto Dark Mode] Prefer: ${is_prefer_light()?"✓":"✗"}Light, ${is_prefer_dark()?"✓":"✗"}Dark`)
      console.log(`[Auto Dark Mode] Current: ${is_light()?"✓":"✗"}Light, ${is_dark()?"✓":"✗"}Dark`)
    }
  })
})()