性能
需注意帧率: 平均 60 fps,p5 59.9 · 长任务: 0 个,共 0 毫秒,最长 0 毫秒 · 源码 gzip 11 KB · 运行时 287 KB
Liquid toggleMIT开关Bencho
由 Lorenzo Cabra 制作的开关 React 组件。依据 MIT 许可从 Bencho 原样收录,此处为实时预览。
质量报告
等级和分数来自构建或测试时跑过的自动检查。没跑过的项目会标成「未检测」,不会填假数据。
帧率: 平均 60 fps,p5 59.9 · 长任务: 0 个,共 0 毫秒,最长 0 毫秒 · 源码 gzip 11 KB · 运行时 287 KB
问题 0 · 读屏: 通过
没有持续动效
无溢出
帧率和长任务是在无界面的 Chromium 里用软件 WebGL 测的,只适合在本站组件之间比较,不代表真机表现。
不适用:静止时没有可见动画;由悬停触发的动画没有测试。
没有 axe-core 违规。

检测于 2026年11月15日 · 数据来自自动脚本,不是手工填写。
按实际尺寸显示。
复制内容以许可声明开头,使用代码时请保留。
<div id="root"></div>:root{--bg:#f6f4f0;--ink:#17181a;--background:40 20% 96%;--foreground:24 10% 8%;--card:0 0% 100%}html,body{min-height:100%;margin:0;background:var(--bg);color:var(--ink)}html,body{height:100%;overflow:hidden}body{display:grid;place-items:center}#root{display:grid;place-items:center;max-width:100%;max-height:100%;box-sizing:border-box;padding:16px;color:hsl(var(--foreground))}#root.full{width:100%;height:100%;padding:0}@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-play-state:paused!important;transition-duration:0s!important}}
/*
MIT License
Copyright (c) 2026 Lorenzo Cabra
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Not covered by this licence: the Bencho name and the goat mark, and the
photographs shown on bencho.dev (none are included here). Third-party
material keeps its own licence; see THIRD_PARTY.md.
Icon substitution (this copy only): lucide-react (ISC) was replaced with @tabler/icons-react (MIT).
Sample photographs were replaced with Incidental AI assets. The Bencho name and goat mark are not licensed for marketing use.
*/
/* ── Bencho tokens ─────────────────────────────────────────
The custom properties the free blocks read, at the values
bencho.dev draws them with. Light by default; dark under
[data-theme="dark"] on any ancestor, or automatically with
the system setting unless [data-theme="light"] says otherwise.
Map these to your own theme rather than keeping two: a block
only ever reads the names, never the values. */
:root {
--font-ui: "Inter", "Helvetica Neue", Helvetica, Arial, sans-serif;
--bg: #ffffff;
--board: #ffffff;
--card: #f7f7f6;
--surface: #f7f7f6;
--surface-2: #f1f1f0;
--surface-3: #ecebe7;
--ink: #17181a;
--ink-rgb: 23, 24, 26;
--ink-2: #3c3b37;
--ink-3: #5c5b56;
--ink-4: #6f6e68;
--ink-5: #85847e;
--on-ink: #ffffff;
--on-ink-rgb: 255, 255, 255;
--slab: #17181a;
--on-slab: #ffffff;
--slab-dark: #0e0f11;
--fill-slab: #ffffff;
--fill-on: #17181a;
--fill-on-rgb: 23, 24, 26;
--pane: var(--fill-slab);
--pane-edge: rgba(23, 24, 26, 0.08);
--pane-thumb: rgba(23, 24, 26, 0.07);
--inlay: rgba(255, 255, 255, 0.55);
--inlay-hi: rgba(23, 24, 26, 0.09);
--elev-rgb: 255, 255, 255;
--glass-rgb: 255, 255, 255;
--shadow-rgb: 23, 24, 26;
--wash: 0.06;
--pick: #0d99ff;
--signal: #2231dd;
--focus: #2231dd;
--ok: #15803d;
--ember: #b8431c;
color-scheme: light;
}
[data-theme="dark"] {
--bg: #000000;
--board: #1a1a1a;
--card: #0a0a0a;
--surface: #0f0f0f;
--surface-2: #181818;
--surface-3: #202020;
--ink: #ffffff;
--ink-rgb: 255, 255, 255;
--ink-2: #b4b4b4;
--ink-3: #9a9a9a;
--ink-4: #828282;
--ink-5: #6b6b6b;
--on-ink: #000000;
--on-ink-rgb: 0, 0, 0;
--slab: #1a1a1a;
--on-slab: #ffffff;
--slab-dark: #262626;
--fill-slab: #262626;
--fill-on: #ffffff;
--fill-on-rgb: 255, 255, 255;
--pane-edge: rgba(255, 255, 255, 0.08);
--pane-thumb: rgba(255, 255, 255, 0.07);
--inlay: rgba(255, 255, 255, 0.1);
--inlay-hi: rgba(255, 255, 255, 0.09);
--elev-rgb: 32, 32, 32;
--shadow-rgb: 0, 0, 0;
--wash: 0.09;
--pick: #3aa9ff;
--ok: #34d17a;
color-scheme: dark;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #000000;
--board: #1a1a1a;
--card: #0a0a0a;
--surface: #0f0f0f;
--surface-2: #181818;
--surface-3: #202020;
--ink: #ffffff;
--ink-rgb: 255, 255, 255;
--ink-2: #b4b4b4;
--ink-3: #9a9a9a;
--ink-4: #828282;
--ink-5: #6b6b6b;
--on-ink: #000000;
--on-ink-rgb: 0, 0, 0;
--slab: #1a1a1a;
--on-slab: #ffffff;
--slab-dark: #262626;
--fill-slab: #262626;
--fill-on: #ffffff;
--fill-on-rgb: 255, 255, 255;
--pane-edge: rgba(255, 255, 255, 0.08);
--pane-thumb: rgba(255, 255, 255, 0.07);
--inlay: rgba(255, 255, 255, 0.1);
--inlay-hi: rgba(255, 255, 255, 0.09);
--elev-rgb: 32, 32, 32;
--shadow-rgb: 0, 0, 0;
--wash: 0.09;
--pick: #3aa9ff;
--ok: #34d17a;
color-scheme: dark;
}
}
/* Toggle.css */
/*
MIT License
Copyright (c) 2026 Lorenzo Cabra
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Not covered by this licence: the Bencho name and the goat mark, and the
photographs shown on bencho.dev (none are included here). Third-party
material keeps its own licence; see THIRD_PARTY.md.
Icon substitution (this copy only): lucide-react (ISC) was replaced with @tabler/icons-react (MIT).
Sample photographs were replaced with Incidental AI assets. The Bencho name and goat mark are not licensed for marketing use.
*/
/* ── the rest of them ────────────────────────────────────────
Not every block has a ::before to hang a border on, and
giving each one a pseudo-element it does not otherwise need
is a lot of stylesheet for a hairline. A 1px spread shadow
is the same mark by another means — the create menu has
used exactly this since it was written, for exactly this
reason — and it composites without touching layout.
This is what makes Stroke honest on every entry rather than
on the dozen that happened to be built on a glass pane. */
[data-stroke="on"] .bal,
[data-stroke="on"] .bar-rail,
[data-stroke="on"] .fan-core,
[data-stroke="on"] .step-pill,
[data-stroke="on"] .liq-sw,
[data-stroke="on"] .deck-card,
[data-stroke="on"] .tick-row,
/* NOT the rows. Stroke is a question about the block's own
edge, and hanging it on every row inside drew four
hairlines in the middle of a panel that still had none
round it. `.lab` already carries the ::before this control
was built for, and the roster's box is a .lab. */
/* ── a ring on a metaball ────────────────────────────────────
The reorder list's rows are blobs on a filtered layer, and a
spread shadow drawn there does not survive: the blur smears
it and the alpha row then crushes what is left to nothing,
so Stroke appeared to do nothing on this block in either
theme.
The ring goes on the UNFILTERED twin instead. Every row is
drawn twice — a blob that merges and an ink layer above it
that carries the avatar and the name — and the two share
their geometry exactly, so an outline on the top one traces
the shape of the bottom one for free. */
/* ── and the node card ─────────────────────────────────────
It drew its hairline unconditionally for a revision, which
is the one thing a block with a Stroke control must not do:
the control then reads as broken in the Off position,
because the edge it promises to remove is still there. The
ring follows the card's own corner, which is a knob. */
[data-stroke="on"] .nod-card {
box-shadow: 0 0 0 1px var(--pane-edge);
border-radius: var(--nod-r, 20px);}
/* ════ liquid ═══════════════════════════════════════════════
Three studies in one filter. Prefix liq-.
Every one of these is two layers in register: opaque shapes
on a layer carrying url(#liq-goo), and anything that needs
a crisp edge — text, a hit area — riding above on a layer
that carries no filter at all. The goo eats translucency
and mangles glyphs, so nothing else can share the layer. */
/* ── 1 · liquid toggle ───────────────────────────────────── */
.liq-well {
width: 240px; height: 130px;
display: grid; place-items: center;}
/* ── BLACK AND WHITE, AND NO EDGE OF ITS OWN ────────────────
The on state was a green wash with a green ring, which made
this the only block on the bench asserting a colour nothing
else uses — and a switch does not need a hue to say it is
on. It inverts instead: a light track with a dark thumb
becomes a dark track with a light one, which is the strongest
thing two colours can say and the only thing this component
has to say.
`--fill-on` / `--fill-slab` rather than --ink / --board, so
the pair follows the Fill control the entry declares instead
of naming a colour twice.
And no inset ring. It carried one unconditionally, which is
an edge the Stroke switch cannot take away — the same bug
the sleep pill, the command bar and the Notify pill all had.
Stroke's own rule is a few hundred lines up. */
.liq-sw {
position: relative;
width: 92px; height: 46px;
padding: 0; border: 0;
/* ── ALWAYS A PILL ────────────────────────────────────────
It took a Corner knob for a while and does not any more.
A switch is a pill: that is the shape the gesture is named
after, and squaring it turns a thing you slide into a
thing you click. The droplet inside followed the knob too,
concentrically, and the same argument applies twice over —
one number that could only ever make the component less
like itself. */
border-radius: 999px;
/* ── OFF IS THE SLAB, NOT A GREY ─────────────────────────
The two states are the two ends of the fill's own ramp,
and OFF is the light end of it: the track is the slab —
white on a light fill, near-black on a dark one — and the
dot is a grey mixed toward it. ON is the inversion, ink
track and slab dot, which is what it always was.
Read across the pair, the TRACK carries the state and the
dot is along for the ride. It was the other way round:
the off track was a 12% wash and the dot was full ink, so
the loud half of the switch was the part that only moves.
It reads because the card behind is not white — the stage
is the board's own grey, so a white pill on it is an
object. Stroke's hairline is there for anywhere it is
not. */
background: var(--fill-slab, var(--card));
cursor: pointer;
/* it is a rail you can push along, not only a button */
touch-action: none;
transition: background 420ms ease;}
.liq-sw[data-on="true"] { background: var(--fill-on, var(--ink)); }
.liq-sw-blobs {
position: absolute; inset: 0;}
/* opaque on purpose: a goo filter over a translucent fill
thresholds the alpha away and the shape disappears */
/* left: 0 is not optional. These are inline elements, so with
left: auto the static position is wherever the line box put
them — and the button they sit in centres its text, which
pushed both blobs to the middle of the track and the thumb
clean off the end of it. */
/* ── the droplet, and it is the ONLY body ───────────────────
There was a second, smaller blob running behind it on a
lagging spring; the goo between them necked into a thread,
which is what a trail is and what it looks like. It is one
body that stretches now — see the note in Liquid.tsx, and
the dragging ball's, which lost the same thing first.
`left: 0` is not optional. It is an inline element, so with
`left: auto` the static position is wherever the line box
put it — and the button it sits in centres its text, which
pushed the thumb to the middle of the track.
OPAQUE on purpose: a goo filter over a translucent fill
thresholds the alpha away and the shape disappears. Which
is why the grey is a `color-mix` and not an alpha — see the
note where the off colour is chosen. */
.liq-thumb {
position: absolute;
left: 0; top: 50%;
/* the size comes from Liquid.tsx, which also needs it for the
travel — one number, so the circle and the distance it
crosses cannot disagree */
width: var(--liq-thumb, 36px); height: var(--liq-thumb, 36px);
margin-top: calc(var(--liq-thumb, 36px) / -2);
border-radius: 999px;
background: color-mix(in srgb, var(--fill-on, var(--ink)) 19%, var(--fill-slab, var(--card)));
/* transform is Framer's — a CSS transition on the same
property re-interpolates every frame the spring writes,
and what you see is the easing, not the spring. The colour
is the only thing here that eases, and it is the only one
that can: everything else about this element is written
into one transform by Framer. */
transition: background 420ms ease;}
/* ON inverts the pair: ink track, slab droplet. The two states
are the two ends of the fill's ramp and never two values of
the same one. */
.liq-sw[data-on="true"] .liq-thumb { background: var(--fill-slab, var(--board)); }
@media (prefers-reduced-motion: reduce) {
.liq-thumb, .liq-pill, .liq-bead { transition-duration: 160ms; }
}
// bencho source (MIT). npm i motion react · Tailwind CSS v4
// ── blocks/liq-toggle/Toggle.tsx (https://github.com/cabralorenzo/bencho/blob/c65992417427bb09e661674ffa800bef29adef49/blocks/liq-toggle/Toggle.tsx)
/*
MIT License
Copyright (c) 2026 Lorenzo Cabra
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Not covered by this licence: the Bencho name and the goat mark, and the
photographs shown on bencho.dev (none are included here). Third-party
material keeps its own licence; see THIRD_PARTY.md.
Icon substitution (this copy only): lucide-react (ISC) was replaced with @tabler/icons-react (MIT).
Sample photographs were replaced with Incidental AI assets. The Bencho name and goat mark are not licensed for marketing use.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { animate, motion, useMotionValue, useSpring, useTransform, useVelocity } from "motion/react";
/* ── what this block expects the page to provide ───────
#liq-goo — an SVG filter the stylesheet points at. Mount it once,
anywhere in the page, inside an <svg width="0" height="0"
style={{ position: "absolute" }}><defs>…</defs></svg>:
<filter id="liq-goo" x="-50%" y="-50%" width="200%" height="200%"
colorInterpolationFilters="sRGB">
<feGaussianBlur in="SourceGraphic" stdDeviation={7} result="smear" />
<feColorMatrix
in="smear"
type="matrix"
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -10"
/>
</filter>
*/
/* ══ Liquid ═══════════════════════════════════════════════
Three metaball studies: a toggle, a reorderable list, and
a create menu.
RECONSTRUCTED. The original file was destroyed; this is
rebuilt against the surviving stylesheet, which specifies
the geometry, the layering and the timing exactly. The
behaviour matches what index.css and the catalog demos
require. The original's internal reasoning is not
recoverable and is not reproduced here.
── the shared constraint ───────────────────────────────
Everything on a filtered layer must be OPAQUE. The goo
filter thresholds alpha, so a translucent fill under it
disappears. That is why each of these has two layers: an
opaque blob layer that carries the filter, and an unfiltered
layer above it carrying the text — antialiased type would
be eaten by the same threshold. */
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
/* ══ 1 · Toggle ═══════════════════════════════════════════
Two blobs, not one. The thumb crosses at once and a smaller
drop follows it late, so for most of the crossing the pair
is stretched into a single waisted capsule. They must stay
OVERLAPPED — a goo bridge across a real gap comes out thin
and reads as two blobs and a thread. */
const TRACK = 92;
/* ── the droplet, and the air round it ─────────────────────
36 in a 46 track, so five pixels of track show all the way
round. It was 40 with three, which is a thumb pressed into
its slot; five is a droplet sitting in one.
PAD is the same five, and it has to be: the inset at the
ends and the inset above and below are the same gap seen
twice, and at 40/4 they were 3 and 4 — near enough to look
like a mistake rather than a decision.
The size is handed to the stylesheet as `--liq-thumb`
rather than written there as well. The travel maths needs
it and so does the circle, and two copies of a number that
must agree is one copy too many. */
const THUMB = 36;
const PAD = (46 - THUMB) / 2;
/* the two ends of the thumb's travel, and the line between */
const SHUT_X = PAD;
const OPEN_X = TRACK - THUMB - PAD;
const MID_X = (SHUT_X + OPEN_X) / 2;
/* 23 is half of the 46px track — the pill it already is. The
thumb stays round whatever this says: it is a droplet, and
the whole component is about liquid. */
export function Toggle({
/* how much the droplet lengthens into its own travel,
0..100 — the dragging ball's knob, and the same idea */
stretch = 36,
/* how fast it crosses, 0..100 */
speed = 50,
}: {
stretch?: number;
speed?: number;
} = {}) {
const [on, setOn] = useState(false);
/* held, so the settling spring knows to keep out of the way
while a finger owns the thumb */
const [held, setHeld] = useState(false);
/* the pointer is over the switch. State and not `:hover`,
because what it drives is a spring in the same transform
the position lives in — see the note on `swell`. */
const [hot, setHot] = useState(false);
/* ── NO GOO. There is nothing left for it to merge. ──────
The filter existed to fuse the thumb with the straggler
running behind it: blur everything, then threshold the
alpha, and two overlapping circles come out as one waisted
capsule. With the straggler gone it had one circle to
work on, and a blur-then-threshold pass over a single
round shape cannot improve it — it can only soften the
edge, which is exactly what it was doing. That is the
answer to "why does the dot look low definition": it was
being rasterised, blurred nine pixels and re-cut at a
contrast of 19, every frame, for no gain.
A plain DOM circle with a border-radius is drawn by the
browser at device resolution and stays crisp at any zoom
the wall or the canvas asks for. The stretch is a CSS
transform now rather than a deformation the filter had to
carry, so nothing here needs the pass. */
const rail = useRef<HTMLButtonElement | null>(null);
const grip = useRef<{ id: number; grab: number | null; moved: boolean } | null>(null);
/* ── ONE POSITION, WRITTEN TWO WAYS ──────────────────────
The thumb's x is a motion value rather than a prop, which
is what lets a finger and a spring both drive it without
one of them having to know about the other: a drag writes
it directly, a release animates it, and nothing re-renders
either way.
The straggler is a SPRING FOLLOWING that value. It used to
be the same target with a delay on it, which is a good
description of a click and a poor one of a drag — a delay
means the drop sets off late and arrives at a place the
thumb left; a spring means it is always chasing wherever
the thumb is now, and it stretches by exactly as much as
you are moving. Drag slowly and the pair stays one shape;
flick and the goo necks out behind it. */
const x = useMotionValue<number>(SHUT_X);
/* ── ONE BODY. STRETCH, NOT A TRAIL. ─────────────────────
There was a second, smaller blob running behind this one
on a lagging spring, and the goo between them necked into
a thread — which is what a trail IS, and what it looks
like: a droplet dragging a tail, or at speed two separate
circles. The dragging ball had the same thing and lost it
for the same reason; its note is the long version.
What replaces it is the ball's own answer. The ONE body
lengthens along its direction of travel and thins across
it, so the elasticity is in the shape of the thing moving
rather than in something left behind — and there is
nothing to leave behind, because there is nothing behind
it.
Area is kept: scaleY is 1/scaleX, so the thumb is the same
amount of droplet whatever it is doing. */
const vel = useVelocity(x);
const eased = useSpring(vel, { stiffness: 380, damping: 34, mass: 0.6 });
/* ── the divisor is the whole tuning ─────────────────────
The thumb's peak speed on a 44px crossing is about 150px
a second, so dividing by 1400 asked it to reach 1400 to
mean anything: measured, the stretch peaked at 1.039 —
arithmetically present and invisible. 600 puts the peak at
about 1.09 at the default, which is the ball's own kind of
give, and the cap at 0.4 leaves the top of the knob
somewhere to go. */
const lengthen = (v: number) =>
1 + Math.min(0.4, Math.abs(v) / 600) * (clamp(stretch, 0, 100) / 100);
/* ── the hover swell goes in the SAME transform ──────────
It was the CSS `scale` property, on the reasoning that
`scale` is its own property and would compose with
whatever the transform was doing. It composes, but not
independently: the individual transform properties apply
BEFORE `transform`, so `scale: 1.035` scaled the
coordinate system that `translateX(51px)` then moved
through — 51 became 52.8, and the droplet drifted toward
the end of the track it was already sitting at.
It only showed on the ON state, and the arithmetic says
why: the error is the translate times 3.5%, and the
translate is 5 when the switch is off and 51 when it is
on. Measured at 51 — the right margin should have gone
5 to 4.37 and went to 2.58 instead.
Multiplied into scaleX and scaleY here, it is a swell
about the droplet's own centre and the position is
untouched. The stretch stays area-preserving inside it. */
const swell = useSpring(hot ? 1.035 : 1, {
stiffness: 380,
damping: 34,
mass: 0.6,
});
const wide = useTransform([eased, swell], ([v, s]: number[]) => lengthen(v) * s);
const tall = useTransform([eased, swell], ([v, s]: number[]) => s / lengthen(v));
/* ── how the thumb lands when it is let go ───────────────
Bounce is the damping and Speed is the stiffness, so both
knobs are properties of one spring rather than of a curve.
SOFTER THAN IT WAS. At 220/20 the default zeta was 0.71
and the crossing was quick with a visible snap at the end
— a switch throwing itself to the other side. 170/21.5 is
zeta 0.87: it still arrives with a hint of give, and the
hint is the whole of it. The dragging ball is the
reference, and what makes that one feel gentle is not a
slow spring but the absence of a hard stop; the same
applies here, and the goo doing the necking is the other
half of it.
Damping is a constant now. It was the Bounce knob, and a
switch is not a thing anybody wants a bounce dial on: the
whole range from dead to lively is the difference between
a control that works and one that is showing off, and 21.5
is the answer. Speed still moves, because how fast a
switch crosses is a real question. */
const settle = useMemo(
() => ({
type: "spring" as const,
stiffness: 170 - (50 - speed) * 1.1,
damping: 21.5,
mass: 0.9,
}),
[speed],
);
/* Rest is wherever `on` says, and it is only ever applied
when nothing is holding the thumb. The cleanup stopping
the animation is what makes grabbing it mid-flight work:
`held` turning true tears down the settle and leaves the
value exactly where the spring had got to. */
useEffect(() => {
if (held) return;
const run = animate(x, on ? OPEN_X : SHUT_X, settle);
return () => run.stop();
}, [on, held, x, settle]);
/* the component is drawn at whatever fraction the card
allows, so a client delta has to be divided back out
before it means anything in the track's own units */
const local = (clientX: number) => {
const el = rail.current;
if (!el) return 0;
const b = el.getBoundingClientRect();
const k = b.width / (el.offsetWidth || b.width) || 1;
return (clientX - b.left) / k;
};
const down = (e: React.PointerEvent) => {
/* ── NO OFFSET YET. It is taken at the first MOVE. ──────
This used to decide here: grabbed on the thumb it kept
the offset you took hold of, and grabbed anywhere else
it set the offset to half a thumb so the droplet "came
to the finger and centred under it". It did not come —
it TELEPORTED. `x.set()` is a hard write with no spring
behind it, so the first pointermove after an off-thumb
press moved the droplet the whole way in a single frame.
Measured: pressed at 80 with the droplet at 5, it went
46px between two frames.
Taking the offset at the first move instead means that
move produces no displacement at all and every one after
it tracks the delta — so a drag always starts from where
the droplet actually is. There is no press anywhere on
this control that can make it jump.
What it costs: an off-thumb press-and-drag no longer
brings the droplet under your finger, it moves it by how
far you dragged. On a 92px track you are never far from
the thumb, and a 46px teleport is the worse of the
two. */
grip.current = { id: e.pointerId, grab: null, moved: false };
setHeld(true);
/* it throws if the id is not a live pointer — a synthetic
event from a test or a rehearsal is exactly that — and
the drag is perfectly usable without it, so it must not
take the grab down with it */
try { rail.current?.setPointerCapture(e.pointerId); } catch { /* not live */ }
};
const move = (e: React.PointerEvent) => {
const g = grip.current;
if (!g || g.id !== e.pointerId) return;
const at = local(e.clientX);
/* the offset, taken from where the droplet IS — see the
note in `down`. The first move therefore asks for
exactly the position it already has. */
if (g.grab === null) g.grab = at - x.get();
const next = clamp(at - g.grab, SHUT_X, OPEN_X);
if (Math.abs(next - x.get()) > 0.4) g.moved = true;
x.set(next);
/* the continuous voice, pitched to where it has got to and
floored so a fast sweep is a rise and not a rattle */
/* it flips as it passes the middle rather than on release,
so the track answers under your finger */
const past = next > MID_X;
if (past !== on) { setOn(past); }
};
const up = (e: React.PointerEvent) => {
const g = grip.current;
if (!g) return;
grip.current = null;
/* ── AND THE RELEASE IS GUARDED TOO ────────────────────
`releasePointerCapture` throws if the pointer was never
captured — which is now possible, because the capture in
`down` is itself guarded and can quietly fail. Unguarded
it threw before `setHeld(false)`, and a switch left
`held` never settles: the rest spring is torn down while
held, so the droplet stopped wherever the drag ended and
stayed there. Caught in a test, where the synthetic
pointer made the capture fail every time — but a real
pointer that is gone by the time the handler runs does
the same thing. */
try { rail.current?.releasePointerCapture?.(e.pointerId); } catch { /* never captured */ }
/* A press that never travelled is a CLICK, and a click
toggles — the switch has to keep working as a switch. */
if (!g.moved) { setOn((v) => { return !v; }); }
setHeld(false);
};
return (
<div className="liq-well" style={{ "--liq-thumb": `${THUMB}px` } as React.CSSProperties}>
<button
ref={rail}
className="liq-sw"
data-on={on}
role="switch"
aria-checked={on}
aria-label="Liquid toggle"
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
onPointerEnter={() => setHot(true)}
onPointerLeave={() => setHot(false)}
/* the keyboard still gets a plain switch */
onKeyDown={(e) => {
if (e.key !== " " && e.key !== "Enter") return;
e.preventDefault();
setOn((v) => { return !v; });
}}
>
<span className="liq-sw-blobs" aria-hidden="true">
<motion.span className="liq-thumb" style={{ x, scaleX: wide, scaleY: tall }} />
</span>
</button>
</div>
);
}控件 · HTML · CSS · JS
直接改代码,再用控件微调,预览会随输入实时更新。

在线编辑每个组件,用控件微调,下载完整源码,复制进阶提示词。
一次性 $49占位价格
测试模式:不会真实扣款。
免费:预览、复制按钮和课程说明。
会移动并变色的旋钮,一眼看出状态。
设置、筛选和开关类偏好。
调轨道宽度、旋钮大小和缓动曲线。
把 Bencho (github.com/cabralorenzo/bencho)(MIT)中的「液体开关」组件加入我的 React + Tailwind CSS 应用。源文件:https://github.com/cabralorenzo/bencho/blob/c65992417427bb09e661674ffa800bef29adef49/blocks/liq-toggle/Toggle.tsx。会移动并变色的旋钮,一眼看出状态。 适用场景:设置、筛选和开关类偏好。 可调参数:调轨道宽度、旋钮大小和缓动曲线。 支持浅色与深色主题,遵循 prefers-reduced-motion。保留 MIT 许可声明。
更完整的提示词,包含调参、无障碍和接入步骤。