6.5 KiB · text History 59d9458
// The site-wide shader background and the /shaders controls. From
// party-slut's assets/f/js/shader_background.js (itself neiam-org's, with
// LiveView hooks replaced by delegation and htmx swap events), without its
// per-party backgrounds.
//
// The choice lives in this browser's localStorage under "app:shader",
// beside "app:theme": a pattern ("off" for none) and the effect settings,
// which the /shaders previews share. A browser that hasn't chosen gets the
// site default, which the server puts on <body data-shader-default> (see
// src/handlers/shaders.rs: Oil on glass at 7% coverage), so there is one
// place it's set.
//
// While a pattern is on, a fixed canvas sits behind the page and
// <html data-shader> puts the content column on an opaque base-100 panel
// (style.css): text never sits on the pattern. The colours follow the site
// theme. Reduced motion gets one still frame unless "Always move" is on; a
// hidden tab stops drawing; no WebGL2, no background.

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

const KEY = "app:shader"

function siteDefault() {
  try {
    return JSON.parse(document.body?.dataset.shaderDefault || "{}")
  } catch {
    return {}
  }
}

function load() {
  let saved = {}
  try {
    saved = JSON.parse(localStorage.getItem(KEY) || "{}")
  } catch {}
  return { ...DEFAULTS, pattern: "off", ...siteDefault(), ...saved }
}

let current = null
let background = null
const previews = new Map()

const on = pattern => !!pattern && pattern !== "off" && pattern !== "none"

function apply() {
  const pattern = current.pattern
  if (on(pattern) && !background) {
    const canvas = document.createElement("canvas")
    canvas.id = "site-shader"
    canvas.setAttribute("aria-hidden", "true")
    // Placed here as well as in style.css: a stylesheet older than this
    // script would otherwise leave a 300x150 inline canvas atop the page.
    Object.assign(canvas.style, {
      position: "fixed",
      inset: "0",
      width: "100vw",
      height: "100vh",
      zIndex: "-1",
      pointerEvents: "none",
    })
    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(pattern) && background) {
    background.field.destroy()
    background.canvas.remove()
    background = null
  }
  document.documentElement.toggleAttribute("data-shader", !!background)
}

// Merge `patch` into this browser's settings, save, and apply.
window.appSetShader = function (patch) {
  current = { ...current, ...patch }
  try {
    localStorage.setItem(KEY, JSON.stringify(current))
  } catch {}
  apply()
  syncControls()
  window.dispatchEvent(new CustomEvent(SETTINGS_EVENT, { detail: current }))
}

// --- previews: <canvas data-shader-preview="oil"> ---------------------------

function mountPreviews() {
  for (const [canvas, field] of previews) {
    if (!canvas.isConnected) {
      field.destroy()
      previews.delete(canvas)
    }
  }
  for (const canvas of document.querySelectorAll("canvas[data-shader-preview]")) {
    if (previews.has(canvas)) continue
    let field = null
    try {
      field = createField(canvas, () => ({ ...current, pattern: canvas.dataset.shaderPreview }))
    } catch (e) {
      console.error("shader preview:", e)
    }
    if (field) previews.set(canvas, field)
    else canvas.closest("[data-shader-card]")?.classList.add("shader-unsupported")
  }
}

// --- the /shaders controls, inside [data-shader-controls] -------------------
//   [data-use="pattern"]                        sets the background
//   input[type=checkbox][data-setting="name"]   boolean settings
//   input[type=range][data-setting="name"]      numeric settings
//   select[data-setting="name"]                 numeric settings, as options
//   [data-shader-card="pattern"]                given data-active when in use
//   [data-shader-current]                       the current pattern's name
//   [data-shader-value="name"]                  a setting's value
//   [data-shader-when="pattern"]                shown only while it is in use

function syncControls() {
  for (const root of document.querySelectorAll("[data-shader-controls]")) {
    for (const input of root.querySelectorAll("[data-setting]")) {
      const v = current[input.dataset.setting]
      if (input.type === "checkbox") input.checked = !!v
      else input.value = v
    }
    for (const card of root.querySelectorAll("[data-shader-card]")) {
      card.toggleAttribute("data-active", card.dataset.shaderCard === current.pattern)
    }
    const card = root.querySelector(`[data-shader-card="${current.pattern}"]`)
    for (const out of root.querySelectorAll("[data-shader-current]")) {
      out.textContent = card ? card.dataset.name : "Off"
    }
    for (const el of root.querySelectorAll("[data-shader-when]")) {
      el.hidden = el.dataset.shaderWhen !== current.pattern
    }
    for (const out of root.querySelectorAll("[data-shader-value]")) {
      out.textContent = current[out.dataset.shaderValue]
    }
  }
}

document.addEventListener("click", e => {
  const use = e.target.closest("[data-shader-controls] [data-use]")
  if (use) window.appSetShader({ pattern: use.dataset.use })
})

document.addEventListener("input", e => {
  const input = e.target
  if (input.dataset?.setting && input.closest("[data-shader-controls]")) {
    const value = input.type === "checkbox" ? input.checked : Number(input.value)
    window.appSetShader({ [input.dataset.setting]: value })
  }
})

function sync() {
  if (!current) current = load()
  if (background && !background.canvas.isConnected) document.body.prepend(background.canvas)
  for (const stray of document.querySelectorAll("#site-shader")) {
    if (stray !== background?.canvas) stray.remove()
  }
  apply()
  syncControls()
  mountPreviews()
}

if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", sync)
else sync()
// hx-boost swaps #content: previews and controls come and go.
document.addEventListener("htmx:afterSettle", sync)
document.addEventListener("htmx:historyRestore", sync)
// htmx snapshots <body> for the back button. Keep the canvas out of it, or
// going back would restore a blank copy beside the live one.
document.addEventListener("htmx:beforeHistorySave", () => {
  const canvas = background?.canvas
  if (!canvas) return
  canvas.remove()
  queueMicrotask(() => canvas.isConnected || document.body.prepend(canvas))
})