Components Forms

Spring Toggle

Pull and release a hanging light switch to change the light and let the cord spring back.

Live previewGo + JavaScript

Pull the cord to change the light.

Usage

Set Label to give the switch an accessible name and Hint to show a short instruction. In your own app, set Checked to true for light mode or Disabled to prevent changes. Pull down at least 40 pixels and release to switch modes, or set Threshold to a distance from 8 to 160 pixels. A shorter drag returns the handle to rest. A click, tap, or press of Space also toggles the native checkbox, even without JavaScript. Reduced motion turns off the spring rebound. On the Mono site, both the preview and the header switch set the theme for every page. Mono follows your device until you choose a theme, then remembers your choice in this browser. To update another part of your application, listen for the input’s change event and read its checked property. Set Name and Value to include the checked switch in a form submission.

Register spring-toggle with Head and pass its properties to Render. Go setup guide

Set --spring-height for the height of the panel, --spring-length for the resting cord length, and --spring-handle-size for the square handle. For a compact settings row, see the Switch.

Go usage
Go usage
err := mono.UI.Render(w, "spring-toggle", mono.Props{
	"Hint":  "Pull the cord to change the light.",
	"Label": "Light mode",
	"Name":  "studio_lighting",
	"Value": "light",
})
Rendered HTML
Rendered HTML
<div class="mu-spring-toggle" data-mono="spring-toggle">
  <span class="mu-spring-cord" data-spring-cord aria-hidden="true"></span>
  <label class="mu-spring-handle" data-spring-handle for="demo-spring-toggle">
    <input class="mu-sr-only mu-spring-input" data-spring-input type="checkbox" role="switch" id="demo-spring-toggle"
      name="studio_lighting" aria-label="Light mode" value="light"
      aria-describedby="demo-spring-toggle-hint"  >
    <svg class="mu-spring-sun" width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true" focusable="false">
      <circle cx="16" cy="16" r="5.8"/>
      <path d="M16 1v3M16 28v3M1 16h3M28 16h3M5.4 5.4l2.1 2.1M24.5 24.5l2.1 2.1M5.4 26.6l2.1-2.1M24.5 7.5l2.1-2.1"/>
    </svg>
    <svg class="mu-spring-cloud" width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
      <path d="M15.5 11.3a6 6 0 0 1 10.3 5.3M20 2v3M27.7 5.2l-2 2M30.5 13h-3M12.2 5.2l2 2"/>
      <path d="M9 27a7 7 0 1 1 6.8-8.8 4.7 4.7 0 0 1 5 1.9A3.5 3.5 0 1 1 21 27Z"/>
    </svg>
  </label>
  <p class="mu-spring-hint" id="demo-spring-toggle-hint">Pull the cord to change the light.</p>
</div>
Apply the switch to a reading pane
Apply the switch to a reading pane
// Render the switch inside <article class="reading-pane">.
err := mono.UI.Render(w, "spring-toggle", mono.Props{
	"ID": "reading-light", "Label": "Light mode", "Name": "reading_light",
	"Checked": true, "Threshold": 56,
})
Reading pane CSS
Reading pane CSS
.reading-pane {
  background: #111;
  color: #fff;
}
.reading-pane:has(#reading-light:checked) {
  background: #fff;
  color: #111;
}
.reading-pane [data-mono="spring-toggle"] {
  --spring-height: 20rem;
  --spring-length: 7rem;
}
Go template
Go template
<div class="mu-spring-toggle" data-mono="spring-toggle"{{if ne .Threshold nil}} data-threshold="{{.Threshold}}"{{end}}>
  <span class="mu-spring-cord" data-spring-cord aria-hidden="true"></span>
  <label class="mu-spring-handle" data-spring-handle for="{{.ID}}">
    <input class="mu-sr-only mu-spring-input" data-spring-input type="checkbox" role="switch" id="{{.ID}}"
      name="{{or .Name .ID}}" aria-label="{{or .Label "Light mode"}}"{{if ne .Value nil}} value="{{.Value}}"{{end}}
      {{if .Hint}}aria-describedby="{{.ID}}-hint"{{end}} {{if .Checked}}checked{{end}} {{if .Disabled}}disabled{{end}}>
    <svg class="mu-spring-sun" width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true" focusable="false">
      <circle cx="16" cy="16" r="5.8"/>
      <path d="M16 1v3M16 28v3M1 16h3M28 16h3M5.4 5.4l2.1 2.1M24.5 24.5l2.1 2.1M5.4 26.6l2.1-2.1M24.5 7.5l2.1-2.1"/>
    </svg>
    <svg class="mu-spring-cloud" width="34" height="34" viewBox="0 0 32 32" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
      <path d="M15.5 11.3a6 6 0 0 1 10.3 5.3M20 2v3M27.7 5.2l-2 2M30.5 13h-3M12.2 5.2l2 2"/>
      <path d="M9 27a7 7 0 1 1 6.8-8.8 4.7 4.7 0 0 1 5 1.9A3.5 3.5 0 1 1 21 27Z"/>
    </svg>
  </label>
  {{with .Hint}}<p class="mu-spring-hint" id="{{$.ID}}-hint">{{.}}</p>{{end}}
</div>
Component CSS
Component CSS
.mu-spring-toggle[data-mono] {
  --spring-paper: #000;
  --spring-ink: #fff;
  --spring-rest: min(var(--spring-length, 12.5rem), 45%);
  position: relative;
  isolation: isolate;
  width: 100%;
  height: var(--spring-height, clamp(22rem, 64svh, 36rem));
  overflow: hidden;
  color: var(--spring-ink);
  background: var(--spring-paper);
}
.mu-spring-toggle:has(.mu-spring-input:checked) {
  --spring-paper: #fff;
  --spring-ink: #000;
}
.mu-spring-cord {
  position: absolute;
  top: 0;
  left: 50%;
  width: 2.5px;
  height: var(--spring-rest);
  background: var(--spring-ink);
  pointer-events: none;
  transform-origin: 50% 0;
  transform: translateX(-50%) rotate(var(--spring-angle, 0rad)) scaleY(var(--spring-stretch, 1));
}
.mu-spring-toggle .mu-spring-handle {
  position: absolute;
  top: var(--spring-rest);
  left: 50%;
  display: grid;
  place-items: center;
  width: clamp(2.75rem, var(--spring-handle-size, 4rem), 100%);
  aspect-ratio: 1;
  margin: 0;
  padding: 0;
  background: var(--spring-ink);
  color: var(--spring-paper);
  transform: translate(calc(-50% + var(--spring-x, 0px)), var(--spring-y, 0px));
  cursor: grab;
  touch-action: none;
  user-select: none;
  -webkit-user-select: none;
  -webkit-tap-highlight-color: transparent;
}
.mu-spring-handle .mu-spring-input { margin: 0; padding: 0; pointer-events: none; }
.mu-spring-handle svg { display: block; width: 55%; height: auto; pointer-events: none; }
.mu-spring-handle .mu-spring-cloud, .mu-spring-input:checked ~ .mu-spring-sun { display: none; }
.mu-spring-input:checked ~ .mu-spring-cloud { display: block; }
.mu-spring-toggle .mu-spring-handle:active { cursor: grabbing; }
.mu-spring-toggle .mu-spring-handle:has(.mu-spring-input:disabled) { opacity: .55; cursor: not-allowed; }
.mu-spring-handle:has(.mu-spring-input:focus-visible) { outline: 2px solid var(--spring-ink); outline-offset: 5px; }
.mu-spring-toggle .mu-spring-hint {
  position: absolute;
  inset-inline: 1rem;
  bottom: 1.25rem;
  margin: 0;
  opacity: .76;
  font-size: .85rem;
  line-height: 1.45;
  text-align: center;
  overflow-wrap: anywhere;
  pointer-events: none;
}
@media (prefers-reduced-motion: reduce) {
  .mu-spring-cord, .mu-spring-toggle .mu-spring-handle { transform: translateX(-50%); }
}
@media (forced-colors: active) {
  .mu-spring-toggle[data-mono] { border: 1px solid CanvasText; }
  .mu-spring-cord { forced-color-adjust: none; background: CanvasText; }
  .mu-spring-toggle .mu-spring-handle { forced-color-adjust: none; color: ButtonText; background: ButtonFace; border: 1px solid ButtonText; }
  .mu-spring-handle:has(.mu-spring-input:checked) { background: Highlight; color: HighlightText; }
  .mu-spring-handle:has(.mu-spring-input:focus-visible) { outline-color: Highlight; }
}
JavaScript module
JavaScript module
export function mount(root) {
  const handle = root.querySelector('[data-spring-handle]');
  const input = root.querySelector('[data-spring-input]');
  const cord = root.querySelector('[data-spring-cord]');
  if (!handle || !input || !cord) return;
  const reduced = window.matchMedia('(prefers-reduced-motion: reduce)');
  const limit = (value, min, max) => Math.max(min, Math.min(max, value));
  let pull, frame = 0, rest = 1, x = 0, y = 0, skipPointerClick = false;

  function paint(dx, dy) {
    x = dx;
    y = dy;
    root.style.setProperty('--spring-x', x.toFixed(2) + 'px');
    root.style.setProperty('--spring-y', y.toFixed(2) + 'px');
    root.style.setProperty('--spring-angle', -Math.atan2(x, rest + y) + 'rad');
    root.style.setProperty('--spring-stretch', Math.hypot(x, rest + y) / rest);
  }

  function center() {
    cancelAnimationFrame(frame);
    frame = x = y = 0;
    for (const prop of ['--spring-x', '--spring-y', '--spring-angle', '--spring-stretch']) {
      root.style.removeProperty(prop);
    }
  }

  function recoil() {
    cancelAnimationFrame(frame);
    if (reduced.matches || (!x && !y)) return center();
    const fromX = x, fromY = y, start = performance.now();
    function step(now) {
      const t = Math.max(0, now - start) / 1000;
      const decay = Math.exp(-8 * t);
      if (reduced.matches || !root.isConnected || decay * Math.max(Math.abs(fromX), Math.abs(fromY)) < .08) {
        center();
        return;
      }
      // Damped spring released from rest. Its response is independent of frame rate.
      const offset = decay * (Math.cos(19 * t) + (8 / 19) * Math.sin(19 * t));
      paint(fromX * offset, fromY * offset);
      frame = requestAnimationFrame(step);
    }
    frame = requestAnimationFrame(step);
  }

  function drawPull() {
    frame = 0;
    if (!pull || reduced.matches) return;
    const dx = limit(pull.fromX + pull.dx * .55, -pull.side, pull.side);
    const dy = limit(pull.fromY + pull.dy, -Math.min(16, rest * .3), pull.depth);
    paint(dx, dy);
  }

  function sample(event) {
    pull.dx = event.clientX - pull.startX;
    pull.dy = event.clientY - pull.startY;
    if (Math.hypot(pull.dx, pull.dy) > 5) pull.moved = true;
  }

  function finish(event, cancelled) {
    if (!pull || (event.pointerId != null && event.pointerId !== pull.id)) return;
    cancelAnimationFrame(frame);
    frame = 0;
    if (!cancelled) sample(event);
    if (pull.moved) drawPull();
    const gesture = pull;
    skipPointerClick = cancelled || gesture.moved;
    // The native checkbox remains the source of truth and emits input/change.
    if (!cancelled && gesture.moved && gesture.dy >= gesture.threshold && !input.matches(':disabled')) input.click();
    pull = null;
    gesture.events.abort();
    if (handle.hasPointerCapture(gesture.id)) handle.releasePointerCapture(gesture.id);
    root.removeAttribute('data-spring-dragging');
    recoil();
  }

  handle.addEventListener('pointerdown', event => {
    if (pull || !event.isPrimary || event.button !== 0 || input.matches(':disabled') || !handle.setPointerCapture) return;
    skipPointerClick = false;
    cancelAnimationFrame(frame);
    frame = 0;
    rest = Math.max(1, cord.offsetHeight);
    const raw = Number(root.dataset.threshold);
    const threshold = limit(root.dataset.threshold?.trim() && Number.isFinite(raw) ? raw : 40, 8, 160);
    const available = root.getBoundingClientRect();
    const box = handle.getBoundingClientRect();
    const events = new AbortController();
    pull = {
      id: event.pointerId, startX: event.clientX, startY: event.clientY,
      fromX: x, fromY: y, dx: 0, dy: 0, moved: false, events, threshold,
      side: Math.max(0, Math.min(64, (available.width - box.width) / 2)),
      depth: Math.max(0, Math.min(available.bottom - box.bottom + y, threshold + 80)),
    };
    handle.setPointerCapture(event.pointerId);
    root.setAttribute('data-spring-dragging', '');
    const options = { signal: events.signal };
    window.addEventListener('blur', event => finish(event, true), options);
    document.addEventListener('visibilitychange', event => { if (document.hidden) finish(event, true); }, options);
    input.form?.addEventListener('reset', event => finish(event, true), options);
  });
  handle.addEventListener('pointermove', event => {
    if (!pull || event.pointerId !== pull.id) return;
    sample(event);
    if (pull.moved && !frame && !reduced.matches) frame = requestAnimationFrame(drawPull);
  });
  handle.addEventListener('pointerup', event => finish(event, false));
  handle.addEventListener('pointercancel', event => finish(event, true));
  handle.addEventListener('lostpointercapture', event => finish(event, true));
  handle.addEventListener('click', event => {
    // A captured release may also synthesize a label click after a drag.
    // Keyboard and programmatic activations have detail 0 and stay native.
    if (skipPointerClick && event.detail > 0) {
      skipPointerClick = false;
      event.preventDefault();
    }
  }, true);
  input.addEventListener('change', () => {
    if (pull || reduced.matches || input.matches(':disabled')) return;
    rest = Math.max(1, cord.offsetHeight);
    paint(x, Math.max(y, 12));
    recoil();
  });
}
Use the HTML in a static site

Copy the rendered HTML above. Download these assets into the same folder as your page, then add the tags below to its head.

Shared CSS Component CSS Ready-to-use module

HTML head
<link rel="stylesheet" href="./base.css">
<link rel="stylesheet" href="./spring-toggle.css">
<script type="module" src="./spring-toggle.js"></script>

Copy into your project

Run this command from the Mono checkout. Set -out to the component directory in your application.

Terminal
go run ./cmd/mono-ui add -out ./components spring-toggle
Example properties (JSON)
example.json
{
  "Hint": "Pull the cord to change the light.",
  "Label": "Light mode",
  "Name": "studio_lighting",
  "Value": "light"
}