4.5 KiB · text History 3208487
// The site-wide shader background, and the hooks behind /shaders.
//
// The choice lives in localStorage under "shader", like the theme: a
// pattern ("off" for none) and the effect settings, which the /shaders
// previews share. Until a visitor chooses, the background is eyes, with
// neiam-org's eye defaults. While a pattern is on, a fixed canvas sits
// behind the page and <html data-shader> makes the page clear over it
// and its cards glass (see app.css). The colours follow the site theme.

import { createField, DEFAULTS } from "./shader_field"

const KEY = "shader"
const EVENT = "vigil:shader-settings"

const DEFAULT_PATTERN = "eyes"
let current = load()
let background = null

function load() {
  try {
    return { ...DEFAULTS, pattern: DEFAULT_PATTERN, ...JSON.parse(localStorage.getItem(KEY) || "{}") }
  } catch {
    return { ...DEFAULTS, pattern: DEFAULT_PATTERN }
  }
}

export const shaderSettings = () => current

function apply() {
  const on = current.pattern && current.pattern !== "off"
  if (on && !background) {
    const canvas = document.createElement("canvas")
    canvas.id = "site-shader"
    canvas.setAttribute("aria-hidden", "true")
    document.body.prepend(canvas)
    let field = null
    try {
      field = createField(canvas, () => current, { fps: 30, maxScale: 1 })
    } catch (e) {
      console.error("shader background:", e)
    }
    if (!field) {
      canvas.remove()
      return
    }
    background = { canvas, field }
  } else if (!on && background) {
    background.field.destroy()
    background.canvas.remove()
    background = null
  }
  document.documentElement.toggleAttribute("data-shader", !!background)
}

// Merge `patch` into the settings, save, and apply. Global, like
// setTheme, so plain onclick handlers can use it.
window.setShader = function (patch) {
  current = { ...current, ...patch }
  try {
    localStorage.setItem(KEY, JSON.stringify(current))
  } catch {}
  apply()
  window.dispatchEvent(new CustomEvent(EVENT, { detail: current }))
}

document.addEventListener("DOMContentLoaded", apply)

// <canvas phx-hook="ShaderPreview" data-pattern="bokeh">: that pattern,
// with the shared effect settings, in the site theme.
export const ShaderPreview = {
  mounted() {
    try {
      this.field = createField(this.el, () => ({ ...current, pattern: this.el.dataset.pattern }))
    } catch (e) {
      console.error("shader preview:", e)
    }
    if (!this.field) this.el.closest("[data-shader-card]")?.classList.add("shader-unsupported")
  },
  destroyed() {
    this.field && this.field.destroy()
  },
}

// The /shaders controls. Inside the hook's element:
//   [data-use="pattern"]          buttons that set the background
//   input[type=checkbox][data-setting="name"]  boolean settings
//   input[type=range][data-setting="name"]     numeric settings
//   [data-shader-card="pattern"]  cards, given data-active when in use
//   [data-shader-current]         filled with the current pattern's name
//   [data-shader-when="pattern"]  shown only while that pattern is in use
export const ShaderControls = {
  mounted() {
    this.el.addEventListener("click", e => {
      const use = e.target.closest("[data-use]")
      if (use) window.setShader({ pattern: use.dataset.use })
    })
    this.el.addEventListener("input", e => {
      const name = e.target.dataset.setting
      if (!name) return
      const value = e.target.type === "checkbox" ? e.target.checked : Number(e.target.value)
      window.setShader({ [name]: value })
    })
    this.sync = () => {
      for (const input of this.el.querySelectorAll("[data-setting]")) {
        const v = current[input.dataset.setting]
        if (input.type === "checkbox") input.checked = !!v
        else input.value = v
      }
      for (const card of this.el.querySelectorAll("[data-shader-card]")) {
        card.toggleAttribute("data-active", card.dataset.shaderCard === current.pattern)
      }
      for (const out of this.el.querySelectorAll("[data-shader-current]")) {
        const card = this.el.querySelector(`[data-shader-card="${current.pattern}"]`)
        out.textContent = card ? card.dataset.name : "Off"
      }
      for (const el of this.el.querySelectorAll("[data-shader-when]")) {
        el.hidden = el.dataset.shaderWhen !== current.pattern
      }
      for (const out of this.el.querySelectorAll("[data-shader-value]")) {
        out.textContent = current[out.dataset.shaderValue]
      }
    }
    window.addEventListener(EVENT, this.sync)
    this.sync()
  },
  destroyed() {
    window.removeEventListener(EVENT, this.sync)
  },
}