基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-03 5852890ac7c6925af4edd70398790d96f8b44284
samples/plugins/sample.audio-visualizer/index.html
@@ -1,5 +1,6 @@
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -15,180 +16,390 @@
      user-select: none;
    }
    body {
      /* background:
        radial-gradient(circle at 68% 66%, rgba(0, 210, 255, 0.18), transparent 18%),
        radial-gradient(circle at 50% 66%, rgba(255, 0, 200, 0.16), transparent 32%),
        linear-gradient(90deg, rgba(0, 12, 22, 0.45), rgba(20, 0, 35, 0.45)); */
      background: transparent;
    }
    #stage {
      position: fixed;
      inset: 0;
      width: 100vw;
      height: 100vh;
      position: relative;
      box-sizing: border-box;
      overflow: hidden;
      background: transparent;
      --base-y: 58%;
      --glow: rgba(255, 47, 179, 0.42);
      --cool: #29d8ff;
      --hot: #ff2fb3;
      --accent: #f8fbff;
    }
    #stage::before {
      content: "";
    #visualizer {
      position: absolute;
      left: 0;
      right: 0;
      top: var(--base-y);
      height: 1px;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.72), transparent);
      box-shadow:
        0 0 8px rgba(255, 255, 255, 0.7),
        0 0 22px var(--glow);
      opacity: 0.86;
    }
    .bars {
      position: absolute;
      inset: 0 10px;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 2px;
    }
    .bar {
      --level: 0.16;
      --bar-height: 7%;
      --bar-top: 51%;
      --bar-opacity: 0.43;
      --reflection-height: 4vh;
      --reflection-opacity: 0.06;
      position: relative;
      flex: 1 1 auto;
      min-width: 1px;
      max-width: 4px;
      height: var(--bar-height);
      margin-top: var(--bar-top);
      border-radius: 999px;
      transform-origin: bottom center;
      background:
        linear-gradient(180deg, var(--accent), var(--hot) 36%, var(--cool));
      box-shadow:
        0 0 5px rgba(255, 255, 255, 0.72),
        0 0 12px var(--glow);
      opacity: var(--bar-opacity);
      transition:
        height 64ms linear,
        margin-top 64ms linear,
        opacity 64ms linear;
    }
    .bar::after {
      content: "";
      position: absolute;
      width: inherit;
      min-width: inherit;
      max-width: inherit;
      height: var(--reflection-height);
      transform: translateY(100%) scaleY(0.72);
      transform-origin: top center;
      border-radius: inherit;
      background: linear-gradient(180deg, rgba(255, 47, 179, 0.26), rgba(41, 216, 255, 0.02));
      filter: blur(1px);
      opacity: var(--reflection-opacity);
      inset: 0;
      width: 100%;
      height: 100%;
      display: block;
    }
  </style>
</head>
<body>
  <main id="stage" aria-hidden="true">
    <div id="bars" class="bars"></div>
    <canvas id="visualizer"></canvas>
  </main>
  <script>
    const stage = document.getElementById("stage");
    const barRoot = document.getElementById("bars");
    const DISPLAY_BAR_COUNT = 256;
    const FALLBACK_LEVEL_COUNT = 128;
    const canvas = document.getElementById("visualizer");
    const ctx = canvas.getContext("2d", { alpha: true });
    const settings = {
      barCount: 192,
      primaryColor: "#ff2fb3",
      secondaryColor: "#29d8ff",
      accentColor: "#f8fbff",
      sensitivity: 1.42
      sensitivity: 5.5,
      centerYRatio: 0.66,
      maxHeightRatio: 3.5,
      smooth: 0.3,
      decay: 0.5,
      compressionPower: 0.7
    };
    let hostLevels = null;
    let width = 1;
    let height = 1;
    let ratio = 1;
    let sourceLevels = new Array(FALLBACK_LEVEL_COUNT).fill(0);
    let displayLevels = new Array(DISPLAY_BAR_COUNT).fill(0.01);
    let smoothedLevels = new Array(DISPLAY_BAR_COUNT).fill(0.01);
    let lastHostSampleAt = 0;
    let fallbackPhase = 0;
    let bars = [];
    let lastEnergy = 0;
    let beat = 0;
    let phase = 0;
    function safeNumber(value, fallback = 0) {
      const number = Number(value);
      return Number.isFinite(number) ? number : fallback;
    }
    function clamp(value, min, max) {
      return Math.max(min, Math.min(max, safeNumber(value, min)));
    }
    function lerp(a, b, t) {
      return a + (b - a) * t;
    }
    function smoothstep(edge0, edge1, x) {
      const span = edge1 - edge0 || 1;
      x = clamp((x - edge0) / span, 0, 1);
      return x * x * (3 - 2 * x);
    }
    function resize() {
      ratio = window.devicePixelRatio || 1;
      width = Math.max(1, window.innerWidth);
      height = Math.max(1, window.innerHeight);
      canvas.width = Math.floor(width * ratio);
      canvas.height = Math.floor(height * ratio);
      canvas.style.width = `${width}px`;
      canvas.style.height = `${height}px`;
      ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
    }
    function applyConfig(config) {
      Object.assign(settings, config || {});
      stage.style.setProperty("--hot", settings.primaryColor);
      stage.style.setProperty("--cool", settings.secondaryColor);
      stage.style.setProperty("--accent", settings.accentColor);
      stage.style.setProperty("--glow", `${hexToRgb(settings.primaryColor, "255, 47, 179")}, 0.42)`.replace(/^/, "rgba("));
      const count = Math.max(96, Math.min(320, Number(settings.barCount) || 192));
      if (bars.length === count) {
      settings.sensitivity = clamp(settings.sensitivity, 0.2, 6);
      settings.centerYRatio = clamp(settings.centerYRatio, 0.2, 0.9);
      settings.maxHeightRatio = clamp(settings.maxHeightRatio, 0.06, 0.48);
    }
    async function loadHostConfig() {
      if (!window.moliDesktop?.getConfig) {
        return;
      }
      barRoot.textContent = "";
      bars = Array.from({ length: count }, () => {
        const node = document.createElement("i");
        node.className = "bar";
        barRoot.appendChild(node);
        return node;
      try {
        applyConfig(await window.moliDesktop.getConfig());
        await window.moliDesktop.notify?.({
          level: "info",
          message: "Audio visualizer loaded through moliDesktop bridge."
        });
      } catch {
        // The visualizer should keep rendering even if a host bridge call fails.
      }
    }
    function acceptLevels(levels) {
      if (!Array.isArray(levels) || levels.length === 0) {
        return;
      }
      sourceLevels = levels.map(value => clamp(value, 0, 1));
      displayLevels = buildBars(sourceLevels, DISPLAY_BAR_COUNT);
      lastHostSampleAt = performance.now();
    }
    function sampleLevel(levels, index) {
      if (!Array.isArray(levels) || levels.length === 0) {
        return 0;
      }
      const last = levels.length - 1;
      const safeIndex = clamp(index, 0, last);
      const i0 = Math.floor(safeIndex);
      const i1 = Math.min(last, i0 + 1);
      const t = safeIndex - i0;
      return lerp(safeNumber(levels[i0]), safeNumber(levels[i1]), t);
    }
    function calcMidBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = t / 0.35;
      const mid = sampleLevel(levels, lerp(bassEnd, midEnd, Math.pow(p, 0.9)));
      const high = sampleLevel(levels, lerp(midEnd, highEnd, Math.pow(p, 0.7)));
      return {
        value: mid * 0.72 + high * 0.28,
        shape: 0.06 + p * 0.1 + (0.18 + Math.pow(p, 0.9) * 0.48) * smoothstep(0, 0.42, p),
        band: "mid"
      };
    }
    function calcTrebleBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = (t - 0.35) / 0.23;
      const high = sampleLevel(levels, lerp(midEnd, highEnd, Math.pow(p, 0.8)));
      const mid = sampleLevel(levels, lerp(midEnd * 0.75, midEnd, p));
      return {
        value: high * 0.82 + mid * 0.18,
        shape: 0.22 + Math.sin(p * Math.PI) * 0.28,
        band: "treble"
      };
    }
    function calcBassBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = (t - 0.58) / 0.24;
      const bass = sampleLevel(levels, lerp(0, bassEnd, Math.pow(p, 0.55)));
      const midBass = sampleLevel(levels, lerp(bassEnd, Math.floor(count * 0.32), p));
      const high = sampleLevel(levels, lerp(midEnd, highEnd, p));
      const peak = Math.exp(-Math.pow((p - 0.58) / 0.36, 2));
      return {
        value: bass * 0.58 + midBass * 0.24 + high * 0.18,
        shape: 0.16 + smoothstep(0, 0.38, p) * (0.08 + peak * 0.72),
        band: "bass"
      };
    }
    function calcTailBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = (t - 0.82) / 0.18;
      const high = sampleLevel(levels, lerp(midEnd, highEnd, p));
      const bass = sampleLevel(levels, bassEnd * 0.45);
      const mid = sampleLevel(levels, lerp(bassEnd, midEnd * 0.7, 1 - p));
      return {
        value: high * 0.62 + bass * 0.16 + mid * 0.1,
        shape: Math.pow(1 - p, 1.65) * 0.38 + 0.06,
        band: "tail"
      };
    }
    function mixBar(a, b, k) {
      const ratio = smoothstep(0, 1, k);
      return {
        value: lerp(a.value, b.value, ratio),
        shape: lerp(a.shape, b.shape, ratio),
        band: ratio < 0.5 ? a.band : b.band
      };
    }
    function getBarByPosition(levels, t, count, bassEnd, midEnd, highEnd) {
      const blend58 = 0.07;
      const blend82 = 0.035;
      if (t < 0.35) {
        return calcMidBar(levels, t, count, bassEnd, midEnd, highEnd);
      }
      if (t < 0.58 - blend58) {
        return calcTrebleBar(levels, t, count, bassEnd, midEnd, highEnd);
      }
      if (t < 0.58 + blend58) {
        const k = (t - (0.58 - blend58)) / (blend58 * 2);
        return mixBar(
          calcTrebleBar(levels, t, count, bassEnd, midEnd, highEnd),
          calcBassBar(levels, t, count, bassEnd, midEnd, highEnd),
          k);
      }
      if (t < 0.82 - blend82) {
        return calcBassBar(levels, t, count, bassEnd, midEnd, highEnd);
      }
      if (t < 0.82 + blend82) {
        const k = (t - (0.82 - blend82)) / (blend82 * 2);
        return mixBar(
          calcBassBar(levels, t, count, bassEnd, midEnd, highEnd),
          calcTailBar(levels, t, count, bassEnd, midEnd, highEnd),
          k);
      }
      return calcTailBar(levels, t, count, bassEnd, midEnd, highEnd);
    }
    function applyBandGain(value, band) {
      if (band === "bass") return value * 2.15;
      if (band === "mid") return value * 1.75;
      if (band === "treble") return value * 2.35;
      if (band === "tail") return value * 1.95;
      return value;
    }
    function applyCompression(value) {
      const compressed = Math.pow(value * settings.sensitivity, settings.compressionPower);
      return compressed / (1 + compressed);
    }
    function buildBars(levels, count) {
      const inputCount = levels.length || FALLBACK_LEVEL_COUNT;
      const bassEnd = Math.floor(inputCount * 0.16);
      const midEnd = Math.floor(inputCount * 0.55);
      const highEnd = inputCount - 1;
      return Array.from({ length: count }, (_, index) => {
        const t = index / Math.max(1, count - 1);
        const item = getBarByPosition(levels, t, inputCount, bassEnd, midEnd, highEnd);
        let value = applyCompression(applyBandGain(item.value, item.band));
        const grain = 0.92 + 0.06 * Math.sin(index * 0.47) + 0.04 * Math.sin(index * 1.13);
        const sparkle = item.band === "treble" || item.band === "tail"
          ? 0.92 + 0.12 * Math.sin(performance.now() * 0.018 + index * 0.9)
          : 1;
        return clamp(value * item.shape * grain * sparkle, 0.01, 1);
      });
    }
    function sample(index) {
      if (hostLevels && performance.now() - lastHostSampleAt < 420) {
        const bin = Math.min(hostLevels.length - 1, Math.floor(index / Math.max(1, bars.length) * hostLevels.length));
        const value = Number(hostLevels[bin]) || 0;
        const neighbor = (Number(hostLevels[Math.max(0, bin - 1)]) || 0) * 0.16
          + (Number(hostLevels[Math.min(hostLevels.length - 1, bin + 1)]) || 0) * 0.16;
        return Math.min(1, Math.pow(value, 0.72) * settings.sensitivity + neighbor);
    function buildFallbackLevels() {
      phase += 0.018;
      const levels = new Array(FALLBACK_LEVEL_COUNT);
      for (let index = 0; index < levels.length; index++) {
        const t = index / Math.max(1, levels.length - 1);
        const bass = Math.exp(-Math.pow((t - 0.12) / 0.12, 2)) * (0.35 + Math.sin(phase * 1.7) * 0.25);
        const mid = Math.exp(-Math.pow((t - 0.48) / 0.18, 2)) * (0.22 + Math.sin(phase * 2.8 + index * 0.08) * 0.16);
        const high = Math.exp(-Math.pow((t - 0.78) / 0.22, 2)) * (0.16 + Math.sin(phase * 5.2 + index * 0.3) * 0.12);
        levels[index] = clamp(0.02 + bass + mid + high, 0, 1);
      }
      return levels;
      }
      fallbackPhase += 0.0025;
      const main = Math.sin(index * 0.18 + fallbackPhase * 54) * 0.5 + 0.5;
      const ripple = Math.sin(index * 0.047 - fallbackPhase * 22) * 0.5 + 0.5;
      const burst = Math.pow(Math.sin(index * 0.022 + fallbackPhase * 13) * 0.5 + 0.5, 7);
      return 0.08 + main * 0.18 + ripple * 0.12 + burst * 0.58;
    function colorByPosition(t) {
      // const hue = lerp(330, 292, smoothstep(0, 1, t));
      // return `hsl(${hue}, 100%, ${lerp(62, 70, t)}%)`;
      const hue = lerp(330, 292, smoothstep(0, 1, t));
      return `hsla(${hue}, 100%, ${lerp(62, 70, t)}%, 0.35)`;
    }
    function roundedBar(x, y, barWidth, barHeight, radius) {
      const safeRadius = Math.min(radius, barWidth / 2, barHeight / 2);
      ctx.beginPath();
      ctx.moveTo(x + safeRadius, y);
      ctx.lineTo(x + barWidth - safeRadius, y);
      ctx.quadraticCurveTo(x + barWidth, y, x + barWidth, y + safeRadius);
      ctx.lineTo(x + barWidth, y + barHeight - safeRadius);
      ctx.quadraticCurveTo(x + barWidth, y + barHeight, x + barWidth - safeRadius, y + barHeight);
      ctx.lineTo(x + safeRadius, y + barHeight);
      ctx.quadraticCurveTo(x, y + barHeight, x, y + barHeight - safeRadius);
      ctx.lineTo(x, y + safeRadius);
      ctx.quadraticCurveTo(x, y, x + safeRadius, y);
      ctx.closePath();
    }
    function drawBackground(centerY) {
      // const cyan = ctx.createRadialGradient(width * 0.68, centerY, 0, width * 0.68, centerY, width * 0.22);
      // cyan.addColorStop(0, "rgba(0, 220, 255, 0.18)");
      // cyan.addColorStop(0.45, "rgba(0, 120, 255, 0.08)");
      // cyan.addColorStop(1, "rgba(0, 0, 0, 0)");
      // ctx.fillStyle = cyan;
      // ctx.fillRect(0, 0, width, height);
      // const magenta = ctx.createRadialGradient(width * 0.5, centerY, 0, width * 0.5, centerY, width * 0.42);
      // magenta.addColorStop(0, "rgba(255, 0, 220, 0.12)");
      // magenta.addColorStop(0.55, "rgba(110, 0, 255, 0.07)");
      // magenta.addColorStop(1, "rgba(0, 0, 0, 0)");
      // ctx.fillStyle = magenta;
      // ctx.fillRect(0, 0, width, height);
    }
    function draw() {
      bars.forEach((bar, index) => {
        const centerBias = Math.sin((index / Math.max(1, bars.length - 1)) * Math.PI);
        const value = Math.min(1, sample(index) * (0.72 + centerBias * 0.36));
        const height = value * 44;
        const top = Math.max(0, 58 - height);
        bar.style.setProperty("--level", value.toFixed(3));
        bar.style.setProperty("--bar-height", `${height.toFixed(2)}%`);
        bar.style.setProperty("--bar-top", `${top.toFixed(2)}%`);
        bar.style.setProperty("--bar-opacity", (0.32 + value * 0.68).toFixed(3));
        bar.style.setProperty("--reflection-height", `${(value * 26).toFixed(2)}vh`);
        bar.style.setProperty("--reflection-opacity", (value * 0.36).toFixed(3));
      });
      resize();
      if (performance.now() - lastHostSampleAt > 900) {
        acceptLevels(buildFallbackLevels());
      }
      ctx.clearRect(0, 0, width, height);
      const centerY = height * settings.centerYRatio;
      // const maxHalfHeight = height * settings.maxHeightRatio;
      const maxHalfHeight = height / 2;
      drawBackground(centerY);
      const energy = sourceLevels.reduce((sum, value) => sum + value, 0);
      beat = energy > lastEnergy * 1.12 ? 1 : beat * 0.9;
      lastEnergy = energy;
      const SILENCE_THRESHOLD = 0.001;
      const isSilent = energy < SILENCE_THRESHOLD;
      const line = ctx.createLinearGradient(0, 0, width, 0);
      line.addColorStop(0, "rgba(255,255,255,0)");
      line.addColorStop(0.5, "rgba(255,255,255,0.72)");
      line.addColorStop(1, "rgba(255,255,255,0)");
      ctx.save();
      ctx.fillStyle = line;
      ctx.shadowBlur = 10;
      ctx.shadowColor = "rgba(255,255,255,0.65)";
      ctx.fillRect(0, centerY - 0.5, width, 1);
      ctx.restore();
      const gap = width < 900 ? 2 : 3;
      const barWidth = Math.max(1.2, Math.min(5, (width - gap * (DISPLAY_BAR_COUNT - 1)) / DISPLAY_BAR_COUNT));
      const totalWidth = DISPLAY_BAR_COUNT * barWidth + (DISPLAY_BAR_COUNT - 1) * gap;
      let x = (width - totalWidth) / 2;
      if (isSilent) {
        requestAnimationFrame(draw);
        return;
      }
      for (let index = 0; index < DISPLAY_BAR_COUNT; index++) {
        const t = index / Math.max(1, DISPLAY_BAR_COUNT - 1);
        const target = displayLevels[index] * (t > 0.58 && t < 0.82 ? 1 + beat * 0.34 : t >= 0.35 && t < 0.58 ? 1 + beat * 0.1 : 1);
        smoothedLevels[index] = Math.max(
          target * settings.smooth + smoothedLevels[index] * (1 - settings.smooth),
          smoothedLevels[index] * settings.decay);
        const value = clamp(smoothedLevels[index], 0.01, 1);
        const barHeight = Math.max(1.2, value * maxHalfHeight);
        const color = colorByPosition(t);
        const gradient = ctx.createLinearGradient(0, centerY - barHeight, 0, centerY + barHeight);
        // gradient.addColorStop(0, "rgba(255,255,255,0.95)");
        // gradient.addColorStop(0.28, color);
        // gradient.addColorStop(0.72, color);
        // gradient.addColorStop(1, "rgba(0,230,255,0.85)");
        gradient.addColorStop(0, "rgba(255,255,255,0.35)");
        gradient.addColorStop(0.28, color);
        gradient.addColorStop(0.72, color);
        gradient.addColorStop(1, "rgba(0,230,255,0.35)");
        ctx.save();
        ctx.fillStyle = gradient;
        ctx.shadowBlur = 8;
        ctx.shadowColor = color;
        roundedBar(x, centerY - barHeight, barWidth, barHeight * 2, Math.min(3, barWidth / 2));
        ctx.fill();
        ctx.restore();
        x += barWidth + gap;
      }
      requestAnimationFrame(draw);
    }
    function hexToRgb(hex, fallback) {
      const match = String(hex || "").trim().match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
      if (!match) {
        return fallback;
      }
      return `${parseInt(match[1], 16)}, ${parseInt(match[2], 16)}, ${parseInt(match[3], 16)}`;
    }
    window.addEventListener("moli:widget-loaded", async () => {
      if (window.moliDesktop?.getConfig) {
        applyConfig(await window.moliDesktop.getConfig());
      }
    });
    window.addEventListener("moli:audio-spectrum", event => {
      const levels = event.detail?.levels;
      if (Array.isArray(levels) && levels.length > 0) {
        hostLevels = levels;
        lastHostSampleAt = performance.now();
      }
    });
    window.addEventListener("resize", resize);
    window.addEventListener("moli:widget-loaded", loadHostConfig);
    window.addEventListener("moli:config-changed", event => applyConfig(event.detail));
    window.addEventListener("moli:audio-spectrum", event => acceptLevels(event.detail?.levels || event.detail?.Levels));
    applyConfig();
    loadHostConfig();
    resize();
    draw();
  </script>
</body>
</html>