= {
"codeHtml": "'use client' ; \n \nimport { useRef, useState, type ComponentPropsWithRef } from 'react' ; \nimport { useGSAP } from '@gsap/react' ; \nimport gsap from 'gsap' ; \nimport { cn } from '@/lib/utils' ; \n \ngsap. registerPlugin (useGSAP); \n \ntype Rgb = [ number , number , number ]; \nconst TEAL : Rgb = [ 4 / 255 , 95 / 255 , 100 / 255 ]; \nconst LIME : Rgb = [ 198 / 255 , 245 / 255 , 111 / 255 ]; \n \n// Brush: the ink that trails the cursor. \nconst RADIUS = 0.52 ; // dab size, in button heights \nconst FOLLOW = 0.08 ; // seconds the brush lags the pointer; the lag is the glide \nconst INK_PER_PX = 0.06 ; // ink per pixel moved, so circling builds up more \nconst INK_MAX = 1.6 ; \nconst INK_FADE = 1.6 ; // ink lost per second \nconst PUSH = 0.15 ; // share of the pointer's speed handed to the fluid \nconst FLOW_FADE = 2.5 ; // motion lost per second \n \n// Pool: the ink that floods in when the cursor crosses an edge. \nconst POOL_X = 0.28 ; // from a side: reach in, in widths \nconst POOL_Y = 1 ; // from a side: height, in heights; 1 fills top to bottom \nconst POOL_SPAN = 0.22 ; // from top or bottom: half its width, in widths \nconst POOL_DEPTH = 0.8 ; // from top or bottom: reach in, in heights \nconst POOL_INK = 1.6 ; \nconst POOL_FADE = 2.4 ; // lost per second, apart from the brush's ink \nconst POOL_GROW = 0.88 ; // seconds to spread in \nconst POOL_GAP = 0.35 ; // shortest time between two pools \n \n// Solver. \nconst CELL = 3 ; // simulation cell size, in CSS pixels \nconst PRESSURE_STEPS = 12 ; \nconst PRESSURE_KEEP = 0.8 ; // last frame's pressure, reused as a head start \nconst IDLE_AFTER = 3.5 ; // seconds without new ink before the loop sleeps \n \nconst VERTEX = `#version 300 es \nin vec2 aPos; \nout vec2 vUv; \nvoid main() { \n vUv = aPos * 0.5 + 0.5; \n gl_Position = vec4(aPos, 0.0, 1.0); \n}` ; \n \nconst head = `#version 300 es \nprecision highp float; \nin vec2 vUv; \nout vec4 outColor; \n` ; \n \n// Adds a soft dab. Ink has two layers: x is the brush, which builds up to a \n// cap, and y the pools, which keep the highest dab so their edge stays soft. \nconst SPLAT = `${ head } \nuniform sampler2D uTarget; \nuniform vec2 uPoint; \nuniform vec2 uValue; \nuniform float uRadius; \nuniform float uAspect; \nuniform float uShape; \nuniform float uMax; \nuniform float uInk; \nvoid main() { \n vec2 d = vUv - uPoint; \n d.x *= uAspect; \n float dab = exp(-pow(dot(d, d) / uRadius, uShape)); \n vec4 base = texture(uTarget, vUv); \n outColor = uInk > 0.5 \n ? vec4(min(base.x + dab * uValue.x, uMax), max(base.y, dab * uValue.y), 0.0, 1.0) \n : vec4(base.xy + dab * uValue, 0.0, 1.0); \n}` ; \n \n// Moves a field along the velocity and fades it: ink by a fixed amount a \n// second, motion in proportion. \nconst ADVECT = `${ head } \nuniform sampler2D uVelocity; \nuniform sampler2D uSource; \nuniform vec2 uCell; \nuniform float uDt; \nuniform vec4 uFade; \nuniform float uInk; \nvoid main() { \n vec2 from = vUv - uDt * texture(uVelocity, vUv).xy * uCell; \n vec4 value = texture(uSource, from); \n // Nothing flows in from outside, so teal washes back in behind the ink. \n vec2 edge = min(from, 1.0 - from) / (uCell * 0.75); \n vec4 carried = value * clamp(min(edge.x, edge.y), 0.0, 1.0); \n if (uInk > 0.5) { \n carried.y = value.y; // pools sit against the edge, so they keep it \n outColor = max(carried - uFade * uDt, 0.0); \n } else { \n outColor = carried / (1.0 + uFade * uDt); \n } \n}` ; \n \n// The cell to the left, right, below and above, for the three passes below. \nconst neighbours = `${ head } \nuniform vec2 uCell; \nvec4 L(sampler2D s) { return texture(s, vUv - vec2(uCell.x, 0.0)); } \nvec4 R(sampler2D s) { return texture(s, vUv + vec2(uCell.x, 0.0)); } \nvec4 B(sampler2D s) { return texture(s, vUv - vec2(0.0, uCell.y)); } \nvec4 T(sampler2D s) { return texture(s, vUv + vec2(0.0, uCell.y)); } \n` ; \n \nconst DIVERGENCE = `${ neighbours } \nuniform sampler2D uVelocity; \nvoid main() { \n float div = R(uVelocity).x - L(uVelocity).x + T(uVelocity).y - B(uVelocity).y; \n outColor = vec4(0.5 * div, 0.0, 0.0, 1.0); \n}` ; \n \n// One relaxation pass. uKeep scales the neighbours: PRESSURE_KEEP on the first \n// pass, so it starts from most of last frame's pressure, then 1. \nconst PRESSURE = `${ neighbours } \nuniform sampler2D uPressure; \nuniform sampler2D uDivergence; \nuniform float uKeep; \nvoid main() { \n float sum = L(uPressure).x + R(uPressure).x + B(uPressure).x + T(uPressure).x; \n outColor = vec4((sum * uKeep - texture(uDivergence, vUv).x) * 0.25, 0.0, 0.0, 1.0); \n}` ; \n \nconst GRADIENT = `${ neighbours } \nuniform sampler2D uPressure; \nuniform sampler2D uVelocity; \nvoid main() { \n vec2 grad = vec2(R(uPressure).x - L(uPressure).x, T(uPressure).x - B(uPressure).x); \n outColor = vec4(texture(uVelocity, vUv).xy - 0.5 * grad, 0.0, 1.0); \n}` ; \n \n// Shows the ink as a soft threshold, so the lime has an edge, and flips the \n// label's colours under it. \nconst DISPLAY = `${ head } \nuniform sampler2D uInk; \nuniform sampler2D uLabel; \nuniform vec3 uBase; \nuniform vec3 uFill; \nvoid main() { \n vec2 ink = texture(uInk, vUv).xy; \n float k = smoothstep(0.3, 0.72, ink.x + ink.y); \n vec3 surface = mix(uBase, uFill, k); \n vec3 text = mix(uFill, uBase, k); \n outColor = vec4(mix(surface, text, texture(uLabel, vUv).a), 1.0); \n}` ; \n \nconst prefersReducedMotion = () => \n typeof window !== 'undefined' && window. matchMedia ( '(prefers-reduced-motion: reduce)' ).matches; \n \n// Where a move from a (outside) to b (inside) crossed into a w×h box, and \n// whether it came in through a side rather than the top or bottom. \nconst entryPoint = ( ax : number , ay : number , bx : number , by : number , w : number , h : number ) => { \n const tx = ax < 0 ? - ax / (bx - ax) : ax > w ? (ax - w) / (ax - bx) : - 1 ; \n const ty = ay < 0 ? - ay / (by - ay) : ay > h ? (ay - h) / (ay - by) : - 1 ; \n const t = Math. max (tx, ty); \n return { x: ax + (bx - ax) * t, y: ay + (by - ay) * t, side: tx >= ty }; \n}; \n \nconst isFocusVisible = ( el : Element ) => { \n try { \n return el. matches ( ':focus-visible' ); \n } catch { \n return true ; \n } \n}; \n \ntype Gl = WebGL2RenderingContext ; \ntype Target = { tex : WebGLTexture ; fbo : WebGLFramebuffer ; w : number ; h : number }; \ntype Pair = { read : Target ; write : Target ; swap : () => void }; \ntype Program = { use : () => void ; set : Record < string , WebGLUniformLocation | null > }; \n \nconst program = ( gl : Gl , fragment : string ) : Program | null => { \n const prog = gl. createProgram (); \n if ( ! prog) return null ; \n for ( const [ type , source ] of [ \n [gl. VERTEX_SHADER , VERTEX ], \n [gl. FRAGMENT_SHADER , fragment], \n ] as const ) { \n const shader = gl. createShader (type); \n if ( ! shader) return null ; \n gl. shaderSource (shader, source); \n gl. compileShader (shader); \n gl. attachShader (prog, shader); \n gl. deleteShader (shader); // freed with the program \n } \n gl. bindAttribLocation (prog, 0 , 'aPos' ); \n gl. linkProgram (prog); \n if ( ! gl. getProgramParameter (prog, gl. LINK_STATUS )) return null ; \n const set : Program [ 'set' ] = {}; \n const count = gl. getProgramParameter (prog, gl. ACTIVE_UNIFORMS ) as number ; \n for ( let i = 0 ; i < count; i += 1 ) { \n const name = gl. getActiveUniform (prog, i)?.name; \n if (name) set[name] = gl. getUniformLocation (prog, name); \n } \n return { use : () => gl. useProgram (prog), set }; \n}; \n \nconst free = ( gl : Gl , ... items : ( Target | Pair | null )[]) => { \n for ( const item of items) { \n if ( ! item) continue ; \n for ( const t of 'read' in item ? [item.read, item.write] : [item]) { \n gl. deleteTexture (t.tex); \n gl. deleteFramebuffer (t.fbo); \n } \n } \n}; \n \n// A half-float texture to draw into. Null if the device can't render to one. \nconst target = ( gl : Gl , w : number , h : number ) : Target | null => { \n const tex = gl. createTexture (); \n const fbo = gl. createFramebuffer (); \n if ( ! tex || ! fbo) return null ; \n gl. bindTexture (gl. TEXTURE_2D , tex); \n gl. texParameteri (gl. TEXTURE_2D , gl. TEXTURE_MIN_FILTER , gl. LINEAR ); \n gl. texParameteri (gl. TEXTURE_2D , gl. TEXTURE_MAG_FILTER , gl. LINEAR ); \n gl. texParameteri (gl. TEXTURE_2D , gl. TEXTURE_WRAP_S , gl. CLAMP_TO_EDGE ); \n gl. texParameteri (gl. TEXTURE_2D , gl. TEXTURE_WRAP_T , gl. CLAMP_TO_EDGE ); \n gl. texImage2D (gl. TEXTURE_2D , 0 , gl. RGBA16F , w, h, 0 , gl. RGBA , gl. HALF_FLOAT , null ); \n gl. bindFramebuffer (gl. FRAMEBUFFER , fbo); \n gl. framebufferTexture2D (gl. FRAMEBUFFER , gl. COLOR_ATTACHMENT0 , gl. TEXTURE_2D , tex, 0 ); \n const t = { tex, fbo, w, h }; \n if (gl. checkFramebufferStatus (gl. FRAMEBUFFER ) !== gl. FRAMEBUFFER_COMPLETE ) { \n free (gl, t); \n return null ; \n } \n gl. clearColor ( 0 , 0 , 0 , 1 ); \n gl. clear (gl. COLOR_BUFFER_BIT ); \n return t; \n}; \n \n// Two targets to read from one while writing the other, then swap. \nconst pair = ( gl : Gl , w : number , h : number ) : Pair | null => { \n const a = target (gl, w, h); \n const b = target (gl, w, h); \n if ( ! a || ! b) { \n free (gl, a, b); \n return null ; \n } \n const p : Pair = { \n read: a, \n write: b, \n swap : () => { \n [p.read, p.write] = [p.write, p.read]; \n }, \n }; \n return p; \n}; \n \ntype Stroke = { x : number ; y : number ; vx : number ; vy : number ; moved : number }; \n \ntype Renderer = { \n /** Fits the canvas to the button. False if the device can't run it. */ \n resize : () => boolean ; \n step : ( dt : number , stroke : Stroke | null ) => void ; \n /** A pool at (x, y) reaching rx widths across and ry heights up and down. */ \n pool : ( x : number , y : number , rx : number , ry : number , size : number ) => void ; \n dispose : () => void ; \n}; \n \n// A small stable-fluids solver. The pointer pushes motion and drops ink, a few \n// pressure passes keep the motion swirling rather than piling up, and both are \n// carried along and fade. \nconst createRenderer = ( \n canvas : HTMLCanvasElement , \n button : HTMLElement , \n label : HTMLElement \n) : Renderer | null => { \n const gl = canvas. getContext ( 'webgl2' , { \n alpha: false , \n antialias: false , \n depth: false , \n stencil: false , \n // A button never needs the discrete GPU; don't wake it on dual-GPU laptops. \n powerPreference: 'low-power' , \n }); \n if ( ! gl) return null ; \n gl. getExtension ( 'EXT_color_buffer_float' ); \n gl. getExtension ( 'EXT_color_buffer_half_float' ); \n const dispose = () => gl. getExtension ( 'WEBGL_lose_context' )?. loseContext (); \n \n const sources = [ SPLAT , ADVECT , DIVERGENCE , PRESSURE , GRADIENT , DISPLAY ]; \n const programs = sources. map (( source ) => program (gl, source)); \n if (programs. some (( p ) => ! p)) { \n dispose (); \n return null ; \n } \n const [ splatP , advectP , divergenceP , pressureP , gradientP , displayP ] = programs as Program []; \n \n // One quad covering the target; every pass draws it. \n gl. bindBuffer (gl. ARRAY_BUFFER , gl. createBuffer ()); \n gl. bufferData (gl. ARRAY_BUFFER , new Float32Array ([ - 1 , - 1 , 1 , - 1 , - 1 , 1 , 1 , 1 ]), gl. STATIC_DRAW ); \n gl. enableVertexAttribArray ( 0 ); \n gl. vertexAttribPointer ( 0 , 2 , gl. FLOAT , false , 0 , 0 ); \n \n const labelTex = gl. createTexture (); \n gl. bindTexture (gl. TEXTURE_2D , labelTex); \n gl. texParameteri (gl. TEXTURE_2D , gl. TEXTURE_MIN_FILTER , gl. LINEAR ); \n gl. texParameteri (gl. TEXTURE_2D , gl. TEXTURE_WRAP_S , gl. CLAMP_TO_EDGE ); \n gl. texParameteri (gl. TEXTURE_2D , gl. TEXTURE_WRAP_T , gl. CLAMP_TO_EDGE ); \n const text = document. createElement ( 'canvas' ); \n \n let velocity : Pair | null = null ; \n let pressure : Pair | null = null ; \n let divergence : Target | null = null ; \n let ink : Pair | null = null ; \n // Button size in CSS pixels, and canvas size in device pixels. \n let cssW = 1 ; \n let cssH = 1 ; \n let width = 1 ; \n let height = 1 ; \n let dpr = 1 ; \n \n const draw = ( to : Target | null ) => { \n gl. bindFramebuffer (gl. FRAMEBUFFER , to ? to.fbo : null ); \n gl. viewport ( 0 , 0 , to ? to.w : width, to ? to.h : height); \n gl. drawArrays (gl. TRIANGLE_STRIP , 0 , 4 ); \n }; \n \n const bind = ( unit : number , tex : WebGLTexture | null ) => { \n gl. activeTexture (gl. TEXTURE0 + unit); \n gl. bindTexture (gl. TEXTURE_2D , tex); \n return unit; \n }; \n \n // Adds a dab to a field at (x, y) in button pixels. The radius is in button \n // heights; aspect stretches it across. \n const splat = ( \n field : Pair , \n x : number , \n y : number , \n value : [ number , number ], \n { \n radius , \n aspect , \n shape , \n isInk , \n } : { radius : number ; aspect : number ; shape : number ; isInk : boolean } \n ) => { \n splatP. use (); \n gl. uniform1i (splatP.set.uTarget, bind ( 0 , field.read.tex)); \n gl. uniform2f (splatP.set.uPoint, x / cssW, 1 - y / cssH); \n gl. uniform2f (splatP.set.uValue, ... value); \n gl. uniform1f (splatP.set.uRadius, radius * radius); \n gl. uniform1f (splatP.set.uAspect, aspect); \n gl. uniform1f (splatP.set.uShape, shape); \n gl. uniform1f (splatP.set.uMax, INK_MAX ); \n gl. uniform1f (splatP.set.uInk, isInk ? 1 : 0 ); \n draw (field.write); \n field. swap (); \n }; \n \n const advect = ( field : Pair , cell : readonly [ number , number ], dt : number , fade : Rgb ) => { \n if ( ! velocity) return ; \n const isInk = field === ink; \n advectP. use (); \n gl. uniform1i (advectP.set.uVelocity, bind ( 0 , velocity.read.tex)); \n gl. uniform1i (advectP.set.uSource, bind ( 1 , field.read.tex)); \n gl. uniform2f (advectP.set.uCell, ... cell); \n gl. uniform1f (advectP.set.uDt, dt); \n gl. uniform4f (advectP.set.uFade, ... fade, 0 ); \n gl. uniform1f (advectP.set.uInk, isInk ? 1 : 0 ); \n draw (field.write); \n field. swap (); \n }; \n \n // The DOM label stays for assistive tech; its pixels are drawn here so the \n // shader can recolour them under the ink. \n const drawLabel = () => { \n const ctx = text. getContext ( '2d' ); \n if ( ! ctx) return ; \n text.width = width; \n text.height = height; \n const style = getComputedStyle (label); \n ctx.font = `${ style . fontStyle } ${ style . fontWeight } ${ parseFloat ( style . fontSize ) * dpr }px ${ style . fontFamily }` ; \n if ( 'letterSpacing' in ctx) { \n ctx.letterSpacing = `${ ( parseFloat ( style . letterSpacing ) || 0 ) * dpr }px` ; \n } \n const words = label.textContent ?? '' ; \n const metrics = ctx. measureText (words); \n // Font box metrics arrived in Firefox 116; the glyph box is close enough. \n const ascent = metrics.fontBoundingBoxAscent ?? metrics.actualBoundingBoxAscent; \n const descent = metrics.fontBoundingBoxDescent ?? metrics.actualBoundingBoxDescent; \n const gap = (label.offsetHeight * dpr - (ascent + descent)) / 2 ; \n ctx.fillStyle = '#fff' ; \n ctx. fillText (words, label.offsetLeft * dpr, label.offsetTop * dpr + gap + ascent); \n gl. bindTexture (gl. TEXTURE_2D , labelTex); \n gl. pixelStorei (gl. UNPACK_FLIP_Y_WEBGL , true ); \n gl. texImage2D (gl. TEXTURE_2D , 0 , gl. RGBA , gl. RGBA , gl. UNSIGNED_BYTE , text); \n gl. pixelStorei (gl. UNPACK_FLIP_Y_WEBGL , false ); \n }; \n \n const show = () => { \n if ( ! ink) return ; \n displayP. use (); \n gl. uniform1i (displayP.set.uInk, bind ( 0 , ink.read.tex)); \n gl. uniform1i (displayP.set.uLabel, bind ( 1 , labelTex)); \n gl. uniform3fv (displayP.set.uBase, TEAL ); \n gl. uniform3fv (displayP.set.uFill, LIME ); \n draw ( null ); \n }; \n \n return { \n resize : () => { \n cssW = Math. max ( 1 , button.offsetWidth); \n cssH = Math. max ( 1 , button.offsetHeight); \n dpr = Math. min (window.devicePixelRatio || 1 , 2 ); \n width = Math. round (cssW * dpr); \n height = Math. round (cssH * dpr); \n canvas.width = width; \n canvas.height = height; \n \n free (gl, velocity, pressure, divergence, ink); \n const simW = Math. max ( 8 , Math. round (cssW / CELL )); \n const simH = Math. max ( 8 , Math. round (cssH / CELL )); \n velocity = pair (gl, simW, simH); \n pressure = pair (gl, simW, simH); \n divergence = target (gl, simW, simH); \n ink = pair (gl, Math. max ( 8 , cssW), Math. max ( 8 , cssH)); \n if ( ! velocity || ! pressure || ! divergence || ! ink) return false ; \n \n drawLabel (); \n show (); \n return true ; \n }, \n \n step : ( dt , stroke ) => { \n if ( ! velocity || ! pressure || ! divergence || ! ink) return ; \n const cell = [ 1 / velocity.read.w, 1 / velocity.read.h] as const ; \n \n if (stroke) { \n const brush = { radius: RADIUS , aspect: cssW / cssH, shape: 1 }; \n const push : [ number , number ] = [(stroke.vx / CELL ) * PUSH , ( - stroke.vy / CELL ) * PUSH ]; \n splat (velocity, stroke.x, stroke.y, push, { ... brush, isInk: false }); \n splat (ink, stroke.x, stroke.y, [stroke.moved * INK_PER_PX , 0 ], { ... brush, isInk: true }); \n } \n \n // Pressure: start from most of last frame's, then relax it. \n divergenceP. use (); \n gl. uniform2f (divergenceP.set.uCell, ... cell); \n gl. uniform1i (divergenceP.set.uVelocity, bind ( 0 , velocity.read.tex)); \n draw (divergence); \n \n pressureP. use (); \n gl. uniform2f (pressureP.set.uCell, ... cell); \n gl. uniform1i (pressureP.set.uDivergence, bind ( 1 , divergence.tex)); \n for ( let i = 0 ; i < PRESSURE_STEPS ; i += 1 ) { \n gl. uniform1f (pressureP.set.uKeep, i === 0 ? PRESSURE_KEEP : 1 ); \n gl. uniform1i (pressureP.set.uPressure, bind ( 0 , pressure.read.tex)); \n draw (pressure.write); \n pressure. swap (); \n } \n \n gradientP. use (); \n gl. uniform2f (gradientP.set.uCell, ... cell); \n gl. uniform1i (gradientP.set.uPressure, bind ( 0 , pressure.read.tex)); \n gl. uniform1i (gradientP.set.uVelocity, bind ( 1 , velocity.read.tex)); \n draw (velocity.write); \n velocity. swap (); \n \n advect (velocity, cell, dt, [ FLOW_FADE , FLOW_FADE , 0 ]); \n advect (ink, cell, dt, [ INK_FADE , POOL_FADE , 0 ]); \n show (); \n }, \n \n pool : ( x , y , rx , ry , size ) => { \n if ( ! ink) return ; \n // Measured in heights, so squeeze x to reach rx of the width. \n splat (ink, x, y, [ 0 , POOL_INK ], { \n radius: ry * size, \n aspect: ry / rx, \n shape: 2 , \n isInk: true , \n }); \n }, \n \n dispose, \n }; \n}; \n \nexport interface InkStrokeButtonProps extends ComponentPropsWithRef < 'button' > { \n children : string ; \n} \n \nconst InkStrokeButton = ({ \n children, \n className, \n type = 'button' , \n ref, \n ... props \n} : InkStrokeButtonProps ) => { \n const btnRef = useRef < HTMLButtonElement >( null ); \n const canvasRef = useRef < HTMLCanvasElement >( null ); \n const labelRef = useRef < HTMLSpanElement >( null ); \n const [ live , setLive ] = useState ( false ); \n \n const setRef = ( node : HTMLButtonElement | null ) => { \n btnRef.current = node; \n if ( typeof ref === 'function' ) ref (node); \n else if (ref) ref.current = node; \n }; \n \n useGSAP ( \n () => { \n const btn = btnRef.current; \n const canvas = canvasRef.current; \n const label = labelRef.current; \n if ( ! btn || ! canvas || ! label) return ; \n \n let renderer : Renderer | null = null ; \n let ticking = false ; \n let lastInk = - Infinity ; \n let sweep : gsap . core . Tween | null = null ; \n // All positions are in the button's own pixels. The pointer is tracked \n // across the page, so the ink is ready as the cursor arrives. \n const pointer = { x: 0 , y: 0 , known: false }; \n const brush = { x: 0 , y: 0 }; \n const pool = { x: 0 , y: 0 , rx: POOL_X , ry: POOL_Y , at: - Infinity }; \n \n const near = ( x : number , y : number , margin : number ) => \n x > - margin && y > - margin && x < btn.offsetWidth + margin && y < btn.offsetHeight + margin; \n \n const stop = () => { \n gsap.ticker. remove (tick); \n ticking = false ; \n }; \n \n function tick ( time : number , deltaTime : number ) { \n if ( ! renderer || ! btn) return stop (); \n const dt = Math. min (deltaTime / 1000 , 1 / 30 ); \n \n // The brush eases after the pointer, which is what makes the ink glide. \n const ease = 1 - Math. exp ( - dt / FOLLOW ); \n const x = brush.x + (pointer.x - brush.x) * ease; \n const y = brush.y + (pointer.y - brush.y) * ease; \n const dx = x - brush.x; \n const dy = y - brush.y; \n const moved = Math. hypot (dx, dy); \n const painting = \n pointer.known && moved > 0.2 && near (x, y, btn.offsetHeight * RADIUS * 0.6 ); \n brush.x = x; \n brush.y = y; \n \n // A new pool eases out from 15% to full size. \n const grown = (time - pool.at) / POOL_GROW ; \n if (grown < 1 ) \n renderer. pool (pool.x, pool.y, pool.rx, pool.ry, 0.15 + 0.85 * ( 1 - ( 1 - grown) ** 3 )); \n \n renderer. step (dt, painting ? { x, y, vx: dx / dt, vy: dy / dt, moved } : null ); \n if (painting || grown < 1 ) lastInk = time; \n // Sleep once the ink has faded; the next move wakes it. \n if ( ! sweep?. isActive () && time - lastInk > IDLE_AFTER ) stop (); \n } \n \n const wake = () => { \n if (ticking || ! renderer) return ; \n ticking = true ; \n gsap.ticker. add (tick); \n }; \n \n const onMove = ( event : PointerEvent ) => { \n if (event.pointerType === 'touch' || ! renderer || btn.disabled) return ; \n const box = btn. getBoundingClientRect (); \n const scale = box.width / btn.offsetWidth || 1 ; \n const x = (event.clientX - box.left) / scale; \n const y = (event.clientY - box.top) / scale; \n \n // Coming in over an edge floods a pool in from that edge. Through a \n // side it fills a full-height band; through the top or bottom it \n // spreads from where the cursor crossed. \n const now = gsap.ticker.time; \n const entered = pointer.known && near (x, y, 0 ) && ! near (pointer.x, pointer.y, 0 ); \n if (entered && now - pool.at > POOL_GAP ) { \n const w = btn.offsetWidth; \n const h = btn.offsetHeight; \n const at = entryPoint (pointer.x, pointer.y, x, y, w, h); \n Object. assign ( \n pool, \n at.side \n ? { x: at.x < w / 2 ? 0 : w, y: h / 2 , rx: POOL_X , ry: POOL_Y } \n : { \n x: Math. min (Math. max (at.x, 0 ), w), \n y: at.y < h / 2 ? 0 : h, \n rx: POOL_SPAN , \n ry: POOL_DEPTH , \n }, \n { at: now } \n ); \n } \n \n // A sleeping brush starts where the pointer was, not where it rested. \n if ( ! pointer.known || ! ticking) { \n brush.x = pointer.known ? pointer.x : x; \n brush.y = pointer.known ? pointer.y : y; \n } \n Object. assign (pointer, { x, y, known: true }); \n if ( near (x, y, btn.offsetHeight * RADIUS * 2 )) wake (); \n }; \n \n // Chrome sends pointer events to disabled buttons, so skip those. \n const onHover = ( event : PointerEvent ) => { \n btn.dataset.active = String (event.type === 'pointerenter' && ! btn.disabled); \n }; \n \n // A keyboard user has no cursor, so focus sweeps one across for them. \n const onFocus = () => { \n if ( ! isFocusVisible (btn)) return ; \n btn.dataset.active = 'true' ; \n if ( ! renderer) return ; \n sweep?. kill (); \n const y = btn.offsetHeight / 2 ; \n Object. assign (pointer, { x: - btn.offsetHeight * 0.4 , y, known: true }); \n Object. assign (brush, { x: pointer.x, y }); \n wake (); \n sweep = gsap. to (pointer, { x: btn.offsetWidth * 0.75 , duration: 0.6 , ease: 'power2.out' }); \n }; \n const onBlur = () => { \n if ( ! btn. matches ( ':hover' )) btn.dataset.active = 'false' ; \n }; \n \n // Without WebGL the CSS colour swap takes over (data-live=false). \n const fallBack = () => { \n stop (); \n renderer?. dispose (); \n renderer = null ; \n setLive ( false ); \n }; \n const fit = () => { \n if (renderer && ! renderer. resize ()) fallBack (); \n }; \n const resize = new ResizeObserver (fit); \n \n const start = () => { \n if (renderer || prefersReducedMotion ()) return ; \n renderer = createRenderer (canvas, btn, label); \n if ( ! renderer) return ; \n if ( ! renderer. resize ()) return fallBack (); \n setLive ( true ); \n resize. observe (btn); \n // The label too: new text in a fixed-width button must be redrawn. \n resize. observe (label); \n document.fonts?.ready. then (fit); \n }; \n \n // Not restored: the CSS fallback takes over for the rest of the visit. \n const onLost = () => { \n stop (); \n renderer = null ; \n setLive ( false ); \n }; \n \n // Contexts are limited per page, so one is only made once on screen. \n const visible = \n typeof IntersectionObserver === 'undefined' \n ? null \n : new IntersectionObserver (( entries ) => { \n if (entries. some (( entry ) => entry.isIntersecting)) { \n visible?. disconnect (); \n start (); \n } \n }); \n if (visible) visible. observe (btn); \n else start (); \n \n window. addEventListener ( 'pointermove' , onMove, { passive: true }); \n btn. addEventListener ( 'pointerenter' , onHover); \n btn. addEventListener ( 'pointerleave' , onHover); \n btn. addEventListener ( 'focus' , onFocus); \n btn. addEventListener ( 'blur' , onBlur); \n canvas. addEventListener ( 'webglcontextlost' , onLost); \n return () => { \n window. removeEventListener ( 'pointermove' , onMove); \n btn. removeEventListener ( 'pointerenter' , onHover); \n btn. removeEventListener ( 'pointerleave' , onHover); \n btn. removeEventListener ( 'focus' , onFocus); \n btn. removeEventListener ( 'blur' , onBlur); \n canvas. removeEventListener ( 'webglcontextlost' , onLost); \n visible?. disconnect (); \n resize. disconnect (); \n sweep?. kill (); \n stop (); \n renderer?. dispose (); \n renderer = null ; // so a late fonts.ready finds nothing to resize \n }; \n }, \n { scope: btnRef } \n ); \n \n return ( \n < button \n ref = {setRef} \n type = {type} \n data-active = \"false\" \n data-live = {live} \n className = { cn ( \n 'relative inline-flex h-12 cursor-pointer items-center justify-center overflow-hidden rounded-[14px] bg-[#045f64] px-6 text-base font-medium text-[#c6f56f] transition-[background-color,color,scale] duration-200 ease-[cubic-bezier(0.32,0.72,0,1)] outline-none select-none focus-visible:ring-2 focus-visible:ring-[#045f64] focus-visible:ring-offset-2 not-disabled:active:scale-[0.97] disabled:cursor-not-allowed disabled:opacity-50 data-[active=true]:data-[live=false]:bg-[#c6f56f] data-[active=true]:data-[live=false]:text-[#045f64] motion-reduce:transition-none motion-reduce:active:scale-100' , \n className \n )} \n { ... props} \n > \n < canvas \n ref = {canvasRef} \n aria-hidden = \"true\" \n className = { cn ( \n // High-contrast mode forces the label visible, so hide the copy. \n 'pointer-events-none absolute inset-0 size-full forced-colors:hidden' , \n live ? 'opacity-100' : 'opacity-0' \n )} \n /> \n < span ref = {labelRef} className = { cn ( 'relative whitespace-nowrap' , live && 'text-transparent' )}> \n {children} \n </ span > \n </ button > \n ); \n}; \n \nexport default InkStrokeButton; \n "
}
},
+ "password-strength": {
+ "react": {
+ "code": "'use client';\n\nimport { useId, useRef, useState, type ComponentPropsWithoutRef, type RefObject } from 'react';\nimport { useGSAP } from '@gsap/react';\nimport gsap from 'gsap';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(useGSAP);\n\nexport interface PasswordRule {\n label: string;\n test: (value: string) => boolean;\n}\n\nexport const defaultRules: readonly PasswordRule[] = [\n { label: 'At least 10 characters', test: (value) => value.length >= 10 },\n {\n label: 'Upper and lower case letters',\n test: (value) => /[a-z]/.test(value) && /[A-Z]/.test(value),\n },\n { label: 'At least one number', test: (value) => /\\d/.test(value) },\n { label: 'At least one symbol', test: (value) => /[^A-Za-z0-9]/.test(value) },\n];\n\nconst LEVELS = [\n { word: 'Weak', color: '#e5484d' },\n { word: 'Fair', color: '#f5a524' },\n { word: 'Good', color: '#8bc34a' },\n { word: 'Strong', color: '#14b8a6' },\n] as const;\n\nconst BARS = LEVELS.length;\nconst MASK_FONT = 'tween-password-mask';\n\nconst MASK_FONT_FACE = `@font-face{font-family:${MASK_FONT};src:url(data:font/woff2;base64,d09GMgABAAAAAAFkAAoAAAAAArgAAAEdAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAPAo4UAE2AiQDBgsGAAQgBYEEByYbFQIAngfZuXAl09NfFYuG5CSC5+9HP+e+u50UyUkJUmmRgm27aEsLsh79C6TC3NYwWgzVmEU1ytDDoCg4nqUv4Wv/nIGBrDp3sx3v/iaDxMNo7FHXLpA4AAgwCiwOJA0ww3SH6mliRErkr1cU6TpWIoMcc11oekhXT/9t+r8UKr8AdIUJBZotzM+GUFpDmtL+/0e6z893w4JInA9UowWQAUXOedcWVRu5JYo75ds9+o9eLmxefbR56fsIAsHWa1LdxNfyKL7A56HhZV179TSdQiGBYEt9jV9xI8CiehOBpFoBEgAAsnEBQhMCJGWaFCJXCAM680lSa2ZFgX3wnWZR5oOpX6BIAWzeAiaEOq7Om8XEFMDwWNhlhNiTawA=) format('woff2');unicode-range:U+2022,U+25CF;font-display:block}`;\n\nconst prefersReducedMotion = () =>\n typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nconst scoreOf = (value: string, met: number, total: number) =>\n value ? Math.max(1, Math.round((met / (total || 1)) * BARS)) : 0;\n\nconst EyeIcon = ({ slashRef }: { slashRef: RefObject }) => (\n \n \n \n \n \n);\n\nexport interface PasswordStrengthProps extends Omit<\n ComponentPropsWithoutRef<'div'>,\n 'defaultValue' | 'onChange'\n> {\n label?: string;\n placeholder?: string;\n name?: string;\n autoComplete?: string;\n rules?: readonly PasswordRule[];\n value?: string;\n defaultValue?: string;\n onValueChange?: (value: string, met: number) => void;\n}\n\nconst PasswordStrength = ({\n label = 'Password',\n placeholder = 'Choose a password',\n name = 'password',\n autoComplete = 'new-password',\n rules = defaultRules,\n value: controlledValue,\n defaultValue = '',\n onValueChange,\n className,\n ...props\n}: PasswordStrengthProps) => {\n const id = useId();\n const inputId = `${id}-input`;\n const strengthId = `${id}-strength`;\n const rulesId = `${id}-rules`;\n\n const rootRef = useRef(null);\n const slashRef = useRef(null);\n const wordRef = useRef(null);\n const fillRefs = useRef<(HTMLSpanElement | null)[]>([]);\n const discRefs = useRef<(HTMLSpanElement | null)[]>([]);\n const checkRefs = useRef<(SVGPathElement | null)[]>([]);\n const eyeRef = useRef(null);\n const previousScore = useRef(0);\n const settled = useRef(false);\n\n const [innerValue, setInnerValue] = useState(defaultValue);\n const [visible, setVisible] = useState(false);\n const [inheritedFont, setInheritedFont] = useState();\n\n const value = controlledValue ?? innerValue;\n const results = rules.map((rule) => rule.test(value));\n const met = results.filter(Boolean).length;\n const score = scoreOf(value, met, rules.length);\n const level = score > 0 ? LEVELS[score - 1] : undefined;\n const metKey = results.map(Number).join('');\n\n useGSAP(\n () => {\n const instant = !settled.current || prefersReducedMotion();\n const from = previousScore.current;\n const rising = score >= from;\n const low = Math.min(from, score);\n const high = Math.max(from, score);\n\n fillRefs.current.forEach((fill, index) => {\n if (!fill) return;\n const changed = index >= low && index < high;\n const order = rising ? index - low : high - 1 - index;\n gsap.to(fill, {\n scaleX: index < score ? 1 : 0,\n duration: instant ? 0 : 0.45,\n delay: instant || !changed ? 0 : order * 0.06,\n ease: 'power3.out',\n overwrite: 'auto',\n });\n });\n\n if (!instant && level && score !== from) {\n gsap.fromTo(\n wordRef.current,\n { yPercent: rising ? 60 : -60, opacity: 0 },\n { yPercent: 0, opacity: 1, duration: 0.35, ease: 'power3.out', overwrite: true }\n );\n }\n\n previousScore.current = score;\n },\n { scope: rootRef, dependencies: [score] }\n );\n\n useGSAP(\n () => {\n const instant = !settled.current || prefersReducedMotion();\n results.forEach((ok, index) => {\n const disc = discRefs.current[index];\n const check = checkRefs.current[index];\n if (!disc || !check) return;\n gsap.to(disc, {\n scale: ok ? 1 : 0,\n duration: instant ? 0 : 0.3,\n ease: 'power3.out',\n overwrite: 'auto',\n });\n gsap.to(check, {\n attr: { 'stroke-dashoffset': ok ? 0 : 1 },\n duration: instant ? 0 : ok ? 0.3 : 0.15,\n delay: instant || !ok ? 0 : 0.1,\n ease: 'power2.out',\n overwrite: 'auto',\n });\n });\n settled.current = true;\n },\n { scope: rootRef, dependencies: [metKey] }\n );\n\n useGSAP(\n () => {\n gsap.to(slashRef.current, {\n attr: { 'stroke-dashoffset': visible ? 0 : 1 },\n duration: prefersReducedMotion() ? 0 : 0.25,\n ease: 'power2.out',\n overwrite: 'auto',\n });\n },\n { scope: rootRef, dependencies: [visible] }\n );\n\n useGSAP(\n () => {\n if (rootRef.current) setInheritedFont(getComputedStyle(rootRef.current).fontFamily);\n },\n { scope: rootRef }\n );\n\n const toggleVisible = () => {\n const next = !visible;\n setVisible(next);\n if (prefersReducedMotion()) return;\n gsap\n .timeline()\n .to(eyeRef.current, { scaleY: 0.1, duration: 0.1, ease: 'power2.in' })\n .to(eyeRef.current, { scaleY: 1, duration: 0.2, ease: 'power2.out' });\n };\n\n const handleChange = (next: string) => {\n if (controlledValue === undefined) setInnerValue(next);\n onValueChange?.(next, rules.filter((rule) => rule.test(next)).length);\n };\n\n return (\n \n \n
\n {label}\n \n\n
\n handleChange(event.target.value)}\n style={{ fontFamily: inheritedFont ? `${MASK_FONT}, ${inheritedFont}` : MASK_FONT }}\n className=\"w-full rounded-xl border border-current/15 bg-transparent py-3 pr-12 pl-4 text-sm transition-[border-color] duration-200 placeholder:text-current/40 focus:border-(--password-accent) focus:outline-none motion-reduce:transition-none\"\n />\n \n \n \n \n \n
\n\n
\n {LEVELS.map(({ word }, index) => (\n \n {\n fillRefs.current[index] = node;\n }}\n className=\"block size-full origin-left [transform:scaleX(0)] rounded-full transition-colors duration-300 will-change-transform\"\n style={{ backgroundColor: level?.color ?? LEVELS[0].color }}\n />\n \n ))}\n
\n\n
\n {level && (\n <>\n Strength: \n \n {level.word}\n \n >\n )}\n
\n\n
\n {rules.map((rule, index) => (\n \n \n {\n discRefs.current[index] = node;\n }}\n className=\"absolute -inset-px [transform:scale(0)] rounded-full bg-(--password-accent)\"\n />\n \n {\n checkRefs.current[index] = node;\n }}\n d=\"M3.5 8.5l3 3 6-7\"\n pathLength={1}\n strokeDasharray=\"1\"\n stroke=\"var(--password-on-accent)\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeDashoffset=\"1\"\n />\n \n \n {rule.label}\n {results[index] ? '(met)' : '(not met)'} \n \n ))}\n \n
\n );\n};\n\nexport default PasswordStrength;\n",
+ "codeHtml": "'use client' ; \n \nimport { useId, useRef, useState, type ComponentPropsWithoutRef, type RefObject } from 'react' ; \nimport { useGSAP } from '@gsap/react' ; \nimport gsap from 'gsap' ; \nimport { cn } from '@/lib/utils' ; \n \ngsap. registerPlugin (useGSAP); \n \nexport interface PasswordRule { \n label : string ; \n test : ( value : string ) => boolean ; \n} \n \nexport const defaultRules : readonly PasswordRule [] = [ \n { label: 'At least 10 characters' , test : ( value ) => value. length >= 10 }, \n { \n label: 'Upper and lower case letters' , \n test : ( value ) => / [a-z] / . test (value) && / [A-Z] / . test (value), \n }, \n { label: 'At least one number' , test : ( value ) => / \\d / . test (value) }, \n { label: 'At least one symbol' , test : ( value ) => / [ ^ A-Za-z0-9] / . test (value) }, \n]; \n \nconst LEVELS = [ \n { word: 'Weak' , color: '#e5484d' }, \n { word: 'Fair' , color: '#f5a524' }, \n { word: 'Good' , color: '#8bc34a' }, \n { word: 'Strong' , color: '#14b8a6' }, \n] as const ; \n \nconst BARS = LEVELS . length ; \nconst MASK_FONT = 'tween-password-mask' ; \n \nconst MASK_FONT_FACE = `@font-face{font-family:${ MASK_FONT };src:url(data:font/woff2;base64,d09GMgABAAAAAAFkAAoAAAAAArgAAAEdAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAPAo4UAE2AiQDBgsGAAQgBYEEByYbFQIAngfZuXAl09NfFYuG5CSC5+9HP+e+u50UyUkJUmmRgm27aEsLsh79C6TC3NYwWgzVmEU1ytDDoCg4nqUv4Wv/nIGBrDp3sx3v/iaDxMNo7FHXLpA4AAgwCiwOJA0ww3SH6mliRErkr1cU6TpWIoMcc11oekhXT/9t+r8UKr8AdIUJBZotzM+GUFpDmtL+/0e6z893w4JInA9UowWQAUXOedcWVRu5JYo75ds9+o9eLmxefbR56fsIAsHWa1LdxNfyKL7A56HhZV179TSdQiGBYEt9jV9xI8CiehOBpFoBEgAAsnEBQhMCJGWaFCJXCAM680lSa2ZFgX3wnWZR5oOpX6BIAWzeAiaEOq7Om8XEFMDwWNhlhNiTawA=) format('woff2');unicode-range:U+2022,U+25CF;font-display:block}` ; \n \nconst prefersReducedMotion = () => \n typeof window !== 'undefined' && window. matchMedia ( '(prefers-reduced-motion: reduce)' ).matches; \n \nconst scoreOf = ( value : string , met : number , total : number ) => \n value ? Math. max ( 1 , Math. round ((met / (total || 1 )) * BARS )) : 0 ; \n \nconst EyeIcon = ({ slashRef } : { slashRef : RefObject < SVGPathElement | null > }) => ( \n < svg \n viewBox = \"0 0 24 24\" \n className = \"size-4\" \n fill = \"none\" \n stroke = \"currentColor\" \n strokeWidth = \"2\" \n strokeLinecap = \"round\" \n strokeLinejoin = \"round\" \n aria-hidden = \"true\" \n > \n < path d = \"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z\" /> \n < circle cx = \"12\" cy = \"12\" r = \"3\" /> \n < path ref = {slashRef} d = \"M4 4l16 16\" pathLength = { 1 } strokeDasharray = \"1\" strokeDashoffset = \"1\" /> \n </ svg > \n); \n \nexport interface PasswordStrengthProps extends Omit < \n ComponentPropsWithoutRef < 'div' >, \n 'defaultValue' | 'onChange' \n> { \n label ?: string ; \n placeholder ?: string ; \n name ?: string ; \n autoComplete ?: string ; \n rules ?: readonly PasswordRule []; \n value ?: string ; \n defaultValue ?: string ; \n onValueChange ?: ( value : string , met : number ) => void ; \n} \n \nconst PasswordStrength = ({ \n label = 'Password' , \n placeholder = 'Choose a password' , \n name = 'password' , \n autoComplete = 'new-password' , \n rules = defaultRules, \n value: controlledValue, \n defaultValue = '' , \n onValueChange, \n className, \n ... props \n} : PasswordStrengthProps ) => { \n const id = useId (); \n const inputId = `${ id }-input` ; \n const strengthId = `${ id }-strength` ; \n const rulesId = `${ id }-rules` ; \n \n const rootRef = useRef < HTMLDivElement >( null ); \n const slashRef = useRef < SVGPathElement >( null ); \n const wordRef = useRef < HTMLSpanElement >( null ); \n const fillRefs = useRef <( HTMLSpanElement | null )[]>([]); \n const discRefs = useRef <( HTMLSpanElement | null )[]>([]); \n const checkRefs = useRef <( SVGPathElement | null )[]>([]); \n const eyeRef = useRef < HTMLSpanElement >( null ); \n const previousScore = useRef ( 0 ); \n const settled = useRef ( false ); \n \n const [ innerValue , setInnerValue ] = useState (defaultValue); \n const [ visible , setVisible ] = useState ( false ); \n const [ inheritedFont , setInheritedFont ] = useState < string >(); \n \n const value = controlledValue ?? innerValue; \n const results = rules. map (( rule ) => rule. test (value)); \n const met = results. filter (Boolean). length ; \n const score = scoreOf (value, met, rules. length ); \n const level = score > 0 ? LEVELS [score - 1 ] : undefined ; \n const metKey = results. map (Number). join ( '' ); \n \n useGSAP ( \n () => { \n const instant = ! settled.current || prefersReducedMotion (); \n const from = previousScore.current; \n const rising = score >= from; \n const low = Math. min (from, score); \n const high = Math. max (from, score); \n \n fillRefs.current. forEach (( fill , index ) => { \n if ( ! fill) return ; \n const changed = index >= low && index < high; \n const order = rising ? index - low : high - 1 - index; \n gsap. to (fill, { \n scaleX: index < score ? 1 : 0 , \n duration: instant ? 0 : 0.45 , \n delay: instant || ! changed ? 0 : order * 0.06 , \n ease: 'power3.out' , \n overwrite: 'auto' , \n }); \n }); \n \n if ( ! instant && level && score !== from) { \n gsap. fromTo ( \n wordRef.current, \n { yPercent: rising ? 60 : - 60 , opacity: 0 }, \n { yPercent: 0 , opacity: 1 , duration: 0.35 , ease: 'power3.out' , overwrite: true } \n ); \n } \n \n previousScore.current = score; \n }, \n { scope: rootRef, dependencies: [score] } \n ); \n \n useGSAP ( \n () => { \n const instant = ! settled.current || prefersReducedMotion (); \n results. forEach (( ok , index ) => { \n const disc = discRefs.current[index]; \n const check = checkRefs.current[index]; \n if ( ! disc || ! check) return ; \n gsap. to (disc, { \n scale: ok ? 1 : 0 , \n duration: instant ? 0 : 0.3 , \n ease: 'power3.out' , \n overwrite: 'auto' , \n }); \n gsap. to (check, { \n attr: { 'stroke-dashoffset' : ok ? 0 : 1 }, \n duration: instant ? 0 : ok ? 0.3 : 0.15 , \n delay: instant || ! ok ? 0 : 0.1 , \n ease: 'power2.out' , \n overwrite: 'auto' , \n }); \n }); \n settled.current = true ; \n }, \n { scope: rootRef, dependencies: [metKey] } \n ); \n \n useGSAP ( \n () => { \n gsap. to (slashRef.current, { \n attr: { 'stroke-dashoffset' : visible ? 0 : 1 }, \n duration: prefersReducedMotion () ? 0 : 0.25 , \n ease: 'power2.out' , \n overwrite: 'auto' , \n }); \n }, \n { scope: rootRef, dependencies: [visible] } \n ); \n \n useGSAP ( \n () => { \n if (rootRef.current) setInheritedFont ( getComputedStyle (rootRef.current).fontFamily); \n }, \n { scope: rootRef } \n ); \n \n const toggleVisible = () => { \n const next = ! visible; \n setVisible (next); \n if ( prefersReducedMotion ()) return ; \n gsap \n . timeline () \n . to (eyeRef.current, { scaleY: 0.1 , duration: 0.1 , ease: 'power2.in' }) \n . to (eyeRef.current, { scaleY: 1 , duration: 0.2 , ease: 'power2.out' }); \n }; \n \n const handleChange = ( next : string ) => { \n if (controlledValue === undefined ) setInnerValue (next); \n onValueChange ?.(next, rules. filter (( rule ) => rule. test (next)). length ); \n }; \n \n return ( \n < div \n ref = {rootRef} \n data-password-strength \n className = { cn ( \n 'w-full max-w-sm [--password-accent:#045f64] [--password-on-accent:#ffffff] dark:[--password-accent:#c6f56f] dark:[--password-on-accent:#12161f]' , \n className \n )} \n { ... props} \n > \n < style href = { MASK_FONT } precedence = \"default\" > \n { MASK_FONT_FACE } \n </ style > \n < label htmlFor = {inputId} className = \"block text-sm font-medium\" > \n {label} \n </ label > \n \n < div className = \"relative mt-2\" > \n < input \n id = {inputId} \n name = {name} \n type = {visible ? 'text' : 'password' } \n value = {value} \n placeholder = {placeholder} \n autoComplete = {autoComplete} \n spellCheck = { false } \n aria-describedby = { `${ strengthId } ${ rulesId }` } \n onChange = {( event ) => handleChange (event.target.value)} \n style = {{ fontFamily: inheritedFont ? `${ MASK_FONT }, ${ inheritedFont }` : MASK_FONT }} \n className = \"w-full rounded-xl border border-current/15 bg-transparent py-3 pr-12 pl-4 text-sm transition-[border-color] duration-200 placeholder:text-current/40 focus:border-(--password-accent) focus:outline-none motion-reduce:transition-none\" \n /> \n < button \n type = \"button\" \n aria-label = {visible ? 'Hide password' : 'Show password' } \n aria-pressed = {visible} \n aria-controls = {inputId} \n onClick = {toggleVisible} \n className = \"absolute top-1/2 right-2 grid size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-lg opacity-60 transition-opacity duration-200 hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-current\" \n > \n < span ref = {eyeRef} className = \"flex\" > \n < EyeIcon slashRef = {slashRef} /> \n </ span > \n </ button > \n </ div > \n \n < div aria-hidden = \"true\" className = \"mt-3 grid grid-cols-4 gap-1.5\" > \n { LEVELS . map (({ word }, index ) => ( \n < span key = {word} className = \"h-1.5 overflow-hidden rounded-full bg-current/10\" > \n < span \n ref = {( node ) => { \n fillRefs.current[index] = node; \n }} \n className = \"block size-full origin-left [transform:scaleX(0)] rounded-full transition-colors duration-300 will-change-transform\" \n style = {{ backgroundColor: level?.color ?? LEVELS [ 0 ].color }} \n /> \n </ span > \n ))} \n </ div > \n \n < p id = {strengthId} aria-live = \"polite\" className = \"mt-2 h-4 overflow-hidden text-xs\" > \n {level && ( \n <> \n < span className = \"opacity-60\" >Strength: </ span > \n < span ref = {wordRef} className = \"inline-block font-medium\" > \n {level.word} \n </ span > \n </> \n )} \n </ p > \n \n < ul id = {rulesId} className = \"mt-4 space-y-2 text-sm\" > \n {rules. map (( rule , index ) => ( \n < li \n key = {rule.label} \n data-met = {results[index] || undefined } \n className = \"flex items-center gap-2.5 opacity-60 transition-opacity duration-200 data-met:opacity-100 motion-reduce:transition-none\" \n > \n < span \n aria-hidden = \"true\" \n className = \"relative grid size-4 shrink-0 place-items-center rounded-full border border-current/25\" \n > \n < span \n ref = {( node ) => { \n discRefs.current[index] = node; \n }} \n className = \"absolute -inset-px [transform:scale(0)] rounded-full bg-(--password-accent)\" \n /> \n < svg viewBox = \"0 0 16 16\" className = \"relative size-3\" fill = \"none\" > \n < path \n ref = {( node ) => { \n checkRefs.current[index] = node; \n }} \n d = \"M3.5 8.5l3 3 6-7\" \n pathLength = { 1 } \n strokeDasharray = \"1\" \n stroke = \"var(--password-on-accent)\" \n strokeWidth = \"2\" \n strokeLinecap = \"round\" \n strokeLinejoin = \"round\" \n strokeDashoffset = \"1\" \n /> \n </ svg > \n </ span > \n {rule.label} \n < span className = \"sr-only\" >{results[index] ? '(met)' : '(not met)' }</ span > \n </ li > \n ))} \n </ ul > \n </ div > \n ); \n}; \n \nexport default PasswordStrength; \n "
+ }
+ },
"pricing-plan-switch": {
"react": {
"code": "'use client';\n\nimport { useRef, useState, type ComponentPropsWithoutRef } from 'react';\nimport { useGSAP } from '@gsap/react';\nimport NumberFlow from '@number-flow/react';\nimport gsap from 'gsap';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(useGSAP);\n\nconst prefersReducedMotion = () =>\n typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nexport interface PricingPlan {\n /** Stable id used as the animation key. */\n id: string;\n /** Plan name, shown in the left selector and the morphing card badge. */\n name: string;\n /** Supporting line under the name in the selector. */\n subtitle: string;\n /** Body copy that crossfades in when the plan is selected. */\n description: string;\n /** Price billed monthly. */\n monthly: number;\n /** Price billed yearly. */\n yearly: number;\n /** How many of `features` are included (the rest render dimmed). */\n includedCount: number;\n}\n\nexport interface PricingPlanSwitchProps extends Omit, 'title'> {\n /** Plans shown in the selector. Defaults to a 3-tier sample. */\n plans?: PricingPlan[];\n /** Feature checklist; each plan lights up its first `includedCount` rows. */\n features?: string[];\n /** Eyebrow badge above the heading. */\n eyebrow?: string;\n /** Section heading. */\n heading?: string;\n /** Section sub-heading. */\n description?: string;\n /** Currency symbol shown before the price. */\n currency?: string;\n /** Primary CTA label. */\n ctaText?: string;\n /** Primary CTA link. */\n ctaHref?: string;\n}\n\nconst DEFAULT_PLANS: PricingPlan[] = [\n {\n id: 'starter',\n name: 'Starter',\n subtitle: 'For early-stage teams',\n description:\n 'Everything you need to get moving — core automation, a shared workspace, and email support to keep momentum.',\n monthly: 2500,\n yearly: 25000,\n includedCount: 5,\n },\n {\n id: 'pro',\n name: 'Pro',\n subtitle: 'For growing teams',\n description:\n 'Built for growing teams with advanced automation, priority workflows, and deeper analytics to keep everything moving.',\n monthly: 4190,\n yearly: 41900,\n includedCount: 7,\n },\n {\n id: 'business',\n name: 'Business',\n subtitle: 'For established businesses',\n description:\n 'Enterprise-grade controls with custom workflows, team-wide governance, and dedicated support for large-scale operations.',\n monthly: 8290,\n yearly: 82900,\n includedCount: 9,\n },\n];\n\nconst DEFAULT_FEATURES: string[] = [\n 'Unlimited workflows',\n 'Team workspace',\n 'Email support',\n 'Advanced automation',\n 'Priority queue',\n 'Usage analytics',\n 'Role-based access',\n 'Custom integrations',\n 'Dedicated success manager',\n];\n\nconst ArrowIcon = ({ className }: { className?: string }) => {\n return (\n \n \n \n );\n};\n\nconst CheckIcon = ({ className }: { className?: string }) => {\n return (\n \n \n \n );\n};\n\nconst DotIcon = ({ className }: { className?: string }) => {\n return (\n \n \n \n );\n};\n\nconst PricingPlanSwitch = ({\n plans = DEFAULT_PLANS,\n features = DEFAULT_FEATURES,\n eyebrow = 'Pricing',\n heading = 'Simple pricing that scales with you',\n description = 'Upgrade anytime as your needs evolve, and stay focused on building and expanding your product with confidence.',\n currency = '$',\n ctaText = 'Get started',\n ctaHref = '#',\n className,\n ...props\n}: PricingPlanSwitchProps) => {\n const firstId = plans[0]?.id ?? '';\n const [selectedId, setSelectedId] = useState(firstId);\n const [isYearly, setIsYearly] = useState(false);\n\n const cardRef = useRef(null);\n const badgeWrapperRef = useRef(null);\n const prevIdRef = useRef(firstId);\n const badgeRefs = useRef>({});\n const descriptionRefs = useRef>({});\n\n const currentPlan = plans.find((p) => p.id === selectedId) ?? plans[0];\n const price = isYearly ? (currentPlan?.yearly ?? 0) : (currentPlan?.monthly ?? 0);\n\n // Establish the starting state: only the first badge/description is visible,\n // and the wrapper is sized to that badge so its width can morph later.\n useGSAP(\n () => {\n const wrapper = badgeWrapperRef.current;\n if (!wrapper) return;\n\n plans.forEach((plan, index) => {\n const badge = badgeRefs.current[plan.id];\n if (badge) gsap.set(badge, { opacity: index === 0 ? 1 : 0, y: 0 });\n });\n\n const first = badgeRefs.current[firstId];\n if (first) wrapper.style.width = `${first.offsetWidth}px`;\n },\n { scope: cardRef }\n );\n\n // Crossfade the badge + description and morph the badge width on selection.\n useGSAP(\n () => {\n const prev = prevIdRef.current;\n const next = selectedId;\n if (prev === next) return;\n\n const fromBadge = badgeRefs.current[prev];\n const toBadge = badgeRefs.current[next];\n const fromDescription = descriptionRefs.current[prev];\n const toDescription = descriptionRefs.current[next];\n const wrapper = badgeWrapperRef.current;\n\n if (prefersReducedMotion()) {\n plans.forEach((plan) => {\n const badge = badgeRefs.current[plan.id];\n const desc = descriptionRefs.current[plan.id];\n if (badge) gsap.set(badge, { opacity: plan.id === next ? 1 : 0, y: 0 });\n if (desc) gsap.set(desc, { opacity: plan.id === next ? 1 : 0, y: 0 });\n });\n if (wrapper && toBadge) wrapper.style.width = `${toBadge.offsetWidth}px`;\n prevIdRef.current = next;\n return;\n }\n\n const tl = gsap.timeline({ defaults: { ease: 'power3.out' } });\n\n if (fromBadge && toBadge) {\n const fromWidth = wrapper?.offsetWidth ?? fromBadge.offsetWidth;\n const toWidth = toBadge.offsetWidth;\n\n tl.set(toBadge, { y: 12, opacity: 0 }, 0);\n tl.to(fromBadge, { y: -12, opacity: 0, duration: 0.22 }, 0);\n tl.to(toBadge, { y: 0, opacity: 1, duration: 0.28 }, 0.12);\n tl.set(fromBadge, { y: 0 }, 0.3);\n\n if (wrapper) {\n tl.to(wrapper, { width: toWidth, duration: 0.28 }, toWidth > fromWidth ? 0 : 0.12);\n }\n }\n\n if (fromDescription && toDescription) {\n tl.set(toDescription, { y: 12, opacity: 0 }, 0);\n tl.to(fromDescription, { y: -12, opacity: 0, duration: 0.22 }, 0);\n tl.to(toDescription, { y: 0, opacity: 1, duration: 0.28 }, 0.12);\n tl.set(fromDescription, { y: 0 }, 0.3);\n }\n\n prevIdRef.current = next;\n },\n { scope: cardRef, dependencies: [selectedId] }\n );\n\n return (\n \n \n {/* Header */}\n
\n
\n
\n {eyebrow}\n \n
\n
\n {heading}\n \n
\n {description}\n
\n
\n
\n\n {/* Billing toggle */}\n
\n \n \n Monthly\n \n setIsYearly(e.target.checked)}\n className=\"peer sr-only\"\n aria-label=\"Toggle yearly billing\"\n />\n \n \n Yearly\n \n \n
\n
\n\n
\n {/* Plan selector */}\n
\n
\n {plans.map((plan) => {\n const isActive = selectedId === plan.id;\n return (\n
setSelectedId(plan.id)}\n data-active={isActive ? 'true' : 'false'}\n className=\"group flex w-full cursor-pointer items-center justify-between gap-x-6 rounded-xl px-5 py-3 text-left transition-colors hover:bg-white data-[active=true]:bg-white data-[active=true]:shadow-sm dark:hover:bg-white/10 dark:data-[active=true]:bg-white/10\"\n >\n \n \n {plan.name}\n \n \n {plan.subtitle}\n \n \n \n \n \n \n );\n })}\n
\n\n
\n \n \n Free trial\n \n \n \n Cancel anytime\n \n
\n
\n\n {/* Card */}\n
\n
\n
\n {plans.map((plan) => (\n {\n badgeRefs.current[plan.id] = el ?? undefined;\n }}\n className=\"absolute inset-y-0 left-0 flex w-max items-center px-3 text-xs font-medium whitespace-nowrap text-[#045f64] dark:text-[#9fd4d6]\"\n >\n {plan.name}\n \n ))}\n \n\n
\n
\n
\n Subscription\n \n
\n {currency}\n \n \n {isYearly ? '/year' : '/month'}\n \n
\n
\n\n
\n {plans.map((plan, index) => (\n {\n descriptionRefs.current[plan.id] = el ?? undefined;\n }}\n className={cn(\n 'col-start-1 row-start-1 text-sm text-[#045f64]/70 dark:text-[#9fd4d6]/80',\n index !== 0 && 'opacity-0'\n )}\n >\n {plan.description}\n
\n ))}\n \n
\n\n
\n {ctaText}\n \n \n
\n\n
\n
\n What's included:\n \n
\n {features.map((feature, index) => {\n const isActive = index < (currentPlan?.includedCount ?? 0);\n return (\n \n \n \n \n \n {feature}\n \n \n );\n })}\n \n
\n
\n
\n
\n \n );\n};\n\nexport default PricingPlanSwitch;\n",
diff --git a/apps/docs/registry/demos/password-strength.tsx b/apps/docs/registry/demos/password-strength.tsx
new file mode 100644
index 0000000..dcbfe43
--- /dev/null
+++ b/apps/docs/registry/demos/password-strength.tsx
@@ -0,0 +1,13 @@
+'use client';
+
+import PasswordStrength from '@/registry/tweenui/password-strength';
+
+const PasswordStrengthDemo = () => {
+ return (
+
+ );
+};
+
+export default PasswordStrengthDemo;
diff --git a/apps/docs/registry/registry-ui.ts b/apps/docs/registry/registry-ui.ts
index 28eaca9..106b168 100644
--- a/apps/docs/registry/registry-ui.ts
+++ b/apps/docs/registry/registry-ui.ts
@@ -1215,6 +1215,43 @@ export default function Example() {
export default function Example() {
return {}}>Start a project ;
+}`,
+ },
+ },
+ {
+ name: 'password-strength',
+ type: 'component',
+ addedAt: '2026-11-22',
+ title: 'Password Strength',
+ description:
+ 'A password field with a four-bar strength meter. The bars fill one after another and shift from red to teal as the password gets stronger, the strength word rolls in, and each requirement draws a check when it is met. The eye blinks and draws a slash across itself to show or hide the password.',
+ media: {},
+ dependencies: ['gsap', '@gsap/react'],
+ registryDependencies: [],
+ cssVars: {},
+ files: [
+ {
+ path: 'registry/tweenui/password-strength.tsx',
+ target: 'components/tweenui/password-strength.tsx',
+ kind: 'react',
+ },
+ ],
+ variants: [
+ {
+ id: 'default',
+ label: 'Default',
+ reactSource: 'registry/tweenui/password-strength.tsx',
+ },
+ ],
+ usage: {
+ react: `import PasswordStrength from '@/components/tweenui/password-strength';
+
+export default function Example() {
+ return (
+
+ );
}`,
},
},
diff --git a/apps/docs/registry/tweenui/password-strength.tsx b/apps/docs/registry/tweenui/password-strength.tsx
new file mode 100644
index 0000000..5d30cfc
--- /dev/null
+++ b/apps/docs/registry/tweenui/password-strength.tsx
@@ -0,0 +1,318 @@
+'use client';
+
+import { useId, useRef, useState, type ComponentPropsWithoutRef, type RefObject } from 'react';
+import { useGSAP } from '@gsap/react';
+import gsap from 'gsap';
+import { cn } from '@/lib/utils';
+
+gsap.registerPlugin(useGSAP);
+
+export interface PasswordRule {
+ label: string;
+ test: (value: string) => boolean;
+}
+
+export const defaultRules: readonly PasswordRule[] = [
+ { label: 'At least 10 characters', test: (value) => value.length >= 10 },
+ {
+ label: 'Upper and lower case letters',
+ test: (value) => /[a-z]/.test(value) && /[A-Z]/.test(value),
+ },
+ { label: 'At least one number', test: (value) => /\d/.test(value) },
+ { label: 'At least one symbol', test: (value) => /[^A-Za-z0-9]/.test(value) },
+];
+
+const LEVELS = [
+ { word: 'Weak', color: '#e5484d' },
+ { word: 'Fair', color: '#f5a524' },
+ { word: 'Good', color: '#8bc34a' },
+ { word: 'Strong', color: '#14b8a6' },
+] as const;
+
+const BARS = LEVELS.length;
+const MASK_FONT = 'tween-password-mask';
+
+const MASK_FONT_FACE = `@font-face{font-family:${MASK_FONT};src:url(data:font/woff2;base64,d09GMgABAAAAAAFkAAoAAAAAArgAAAEdAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAPAo4UAE2AiQDBgsGAAQgBYEEByYbFQIAngfZuXAl09NfFYuG5CSC5+9HP+e+u50UyUkJUmmRgm27aEsLsh79C6TC3NYwWgzVmEU1ytDDoCg4nqUv4Wv/nIGBrDp3sx3v/iaDxMNo7FHXLpA4AAgwCiwOJA0ww3SH6mliRErkr1cU6TpWIoMcc11oekhXT/9t+r8UKr8AdIUJBZotzM+GUFpDmtL+/0e6z893w4JInA9UowWQAUXOedcWVRu5JYo75ds9+o9eLmxefbR56fsIAsHWa1LdxNfyKL7A56HhZV179TSdQiGBYEt9jV9xI8CiehOBpFoBEgAAsnEBQhMCJGWaFCJXCAM680lSa2ZFgX3wnWZR5oOpX6BIAWzeAiaEOq7Om8XEFMDwWNhlhNiTawA=) format('woff2');unicode-range:U+2022,U+25CF;font-display:block}`;
+
+const prefersReducedMotion = () =>
+ typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const scoreOf = (value: string, met: number, total: number) =>
+ value ? Math.max(1, Math.round((met / (total || 1)) * BARS)) : 0;
+
+const EyeIcon = ({ slashRef }: { slashRef: RefObject }) => (
+
+
+
+
+
+);
+
+export interface PasswordStrengthProps extends Omit<
+ ComponentPropsWithoutRef<'div'>,
+ 'defaultValue' | 'onChange'
+> {
+ label?: string;
+ placeholder?: string;
+ name?: string;
+ autoComplete?: string;
+ rules?: readonly PasswordRule[];
+ value?: string;
+ defaultValue?: string;
+ onValueChange?: (value: string, met: number) => void;
+}
+
+const PasswordStrength = ({
+ label = 'Password',
+ placeholder = 'Choose a password',
+ name = 'password',
+ autoComplete = 'new-password',
+ rules = defaultRules,
+ value: controlledValue,
+ defaultValue = '',
+ onValueChange,
+ className,
+ ...props
+}: PasswordStrengthProps) => {
+ const id = useId();
+ const inputId = `${id}-input`;
+ const strengthId = `${id}-strength`;
+ const rulesId = `${id}-rules`;
+
+ const rootRef = useRef(null);
+ const slashRef = useRef(null);
+ const wordRef = useRef(null);
+ const fillRefs = useRef<(HTMLSpanElement | null)[]>([]);
+ const discRefs = useRef<(HTMLSpanElement | null)[]>([]);
+ const checkRefs = useRef<(SVGPathElement | null)[]>([]);
+ const eyeRef = useRef(null);
+ const previousScore = useRef(0);
+ const settled = useRef(false);
+
+ const [innerValue, setInnerValue] = useState(defaultValue);
+ const [visible, setVisible] = useState(false);
+ const [inheritedFont, setInheritedFont] = useState();
+
+ const value = controlledValue ?? innerValue;
+ const results = rules.map((rule) => rule.test(value));
+ const met = results.filter(Boolean).length;
+ const score = scoreOf(value, met, rules.length);
+ const level = score > 0 ? LEVELS[score - 1] : undefined;
+ const metKey = results.map(Number).join('');
+
+ useGSAP(
+ () => {
+ const instant = !settled.current || prefersReducedMotion();
+ const from = previousScore.current;
+ const rising = score >= from;
+ const low = Math.min(from, score);
+ const high = Math.max(from, score);
+
+ fillRefs.current.forEach((fill, index) => {
+ if (!fill) return;
+ const changed = index >= low && index < high;
+ const order = rising ? index - low : high - 1 - index;
+ gsap.to(fill, {
+ scaleX: index < score ? 1 : 0,
+ duration: instant ? 0 : 0.45,
+ delay: instant || !changed ? 0 : order * 0.06,
+ ease: 'power3.out',
+ overwrite: 'auto',
+ });
+ });
+
+ if (!instant && level && score !== from) {
+ gsap.fromTo(
+ wordRef.current,
+ { yPercent: rising ? 60 : -60, opacity: 0 },
+ { yPercent: 0, opacity: 1, duration: 0.35, ease: 'power3.out', overwrite: true }
+ );
+ }
+
+ previousScore.current = score;
+ },
+ { scope: rootRef, dependencies: [score] }
+ );
+
+ useGSAP(
+ () => {
+ const instant = !settled.current || prefersReducedMotion();
+ results.forEach((ok, index) => {
+ const disc = discRefs.current[index];
+ const check = checkRefs.current[index];
+ if (!disc || !check) return;
+ gsap.to(disc, {
+ scale: ok ? 1 : 0,
+ duration: instant ? 0 : 0.3,
+ ease: 'power3.out',
+ overwrite: 'auto',
+ });
+ gsap.to(check, {
+ attr: { 'stroke-dashoffset': ok ? 0 : 1 },
+ duration: instant ? 0 : ok ? 0.3 : 0.15,
+ delay: instant || !ok ? 0 : 0.1,
+ ease: 'power2.out',
+ overwrite: 'auto',
+ });
+ });
+ settled.current = true;
+ },
+ { scope: rootRef, dependencies: [metKey] }
+ );
+
+ useGSAP(
+ () => {
+ gsap.to(slashRef.current, {
+ attr: { 'stroke-dashoffset': visible ? 0 : 1 },
+ duration: prefersReducedMotion() ? 0 : 0.25,
+ ease: 'power2.out',
+ overwrite: 'auto',
+ });
+ },
+ { scope: rootRef, dependencies: [visible] }
+ );
+
+ useGSAP(
+ () => {
+ if (rootRef.current) setInheritedFont(getComputedStyle(rootRef.current).fontFamily);
+ },
+ { scope: rootRef }
+ );
+
+ const toggleVisible = () => {
+ const next = !visible;
+ setVisible(next);
+ if (prefersReducedMotion()) return;
+ gsap
+ .timeline()
+ .to(eyeRef.current, { scaleY: 0.1, duration: 0.1, ease: 'power2.in' })
+ .to(eyeRef.current, { scaleY: 1, duration: 0.2, ease: 'power2.out' });
+ };
+
+ const handleChange = (next: string) => {
+ if (controlledValue === undefined) setInnerValue(next);
+ onValueChange?.(next, rules.filter((rule) => rule.test(next)).length);
+ };
+
+ return (
+
+
+
+ {label}
+
+
+
+ handleChange(event.target.value)}
+ style={{ fontFamily: inheritedFont ? `${MASK_FONT}, ${inheritedFont}` : MASK_FONT }}
+ className="w-full rounded-xl border border-current/15 bg-transparent py-3 pr-12 pl-4 text-sm transition-[border-color] duration-200 placeholder:text-current/40 focus:border-(--password-accent) focus:outline-none motion-reduce:transition-none"
+ />
+
+
+
+
+
+
+
+
+ {LEVELS.map(({ word }, index) => (
+
+ {
+ fillRefs.current[index] = node;
+ }}
+ className="block size-full origin-left [transform:scaleX(0)] rounded-full transition-colors duration-300 will-change-transform"
+ style={{ backgroundColor: level?.color ?? LEVELS[0].color }}
+ />
+
+ ))}
+
+
+
+ {level && (
+ <>
+ Strength:
+
+ {level.word}
+
+ >
+ )}
+
+
+
+ {rules.map((rule, index) => (
+
+
+ {
+ discRefs.current[index] = node;
+ }}
+ className="absolute -inset-px [transform:scale(0)] rounded-full bg-(--password-accent)"
+ />
+
+ {
+ checkRefs.current[index] = node;
+ }}
+ d="M3.5 8.5l3 3 6-7"
+ pathLength={1}
+ strokeDasharray="1"
+ stroke="var(--password-on-accent)"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeDashoffset="1"
+ />
+
+
+ {rule.label}
+ {results[index] ? '(met)' : '(not met)'}
+
+ ))}
+
+
+ );
+};
+
+export default PasswordStrength;
diff --git a/apps/docs/tests/password-strength.test.tsx b/apps/docs/tests/password-strength.test.tsx
new file mode 100644
index 0000000..39ed4d4
--- /dev/null
+++ b/apps/docs/tests/password-strength.test.tsx
@@ -0,0 +1,102 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import PasswordStrength, { defaultRules } from '@/registry/tweenui/password-strength';
+
+const setReducedMotion = (reduce: boolean) => {
+ window.matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: query.includes('reduce') ? reduce : false,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })) as unknown as typeof window.matchMedia;
+};
+
+const type = (value: string) =>
+ fireEvent.change(screen.getByLabelText('Password'), { target: { value } });
+
+describe('Password Strength', () => {
+ beforeEach(() => setReducedMotion(false));
+
+ it('renders a labelled password input with the default rules', () => {
+ render( );
+ const input = screen.getByLabelText('Password');
+ expect(input).toHaveAttribute('type', 'password');
+ expect(input).toHaveAttribute('name', 'password');
+ expect(input).toHaveAttribute('autocomplete', 'new-password');
+ expect(screen.getAllByRole('listitem')).toHaveLength(defaultRules.length);
+ expect(screen.getAllByText('(not met)')).toHaveLength(4);
+ });
+
+ it('shows no strength while empty', () => {
+ render( );
+ expect(screen.queryByText(/Strength/)).toBeNull();
+ });
+
+ it('rates the password as rules are met', () => {
+ render( );
+ type('abc');
+ expect(screen.getByText('Weak')).toBeInTheDocument();
+ type('abcDEF');
+ expect(screen.getByText('Weak')).toBeInTheDocument();
+ type('abcDEF1');
+ expect(screen.getByText('Fair')).toBeInTheDocument();
+ type('abcDEF1!');
+ expect(screen.getByText('Good')).toBeInTheDocument();
+ type('abcDEF12!@');
+ expect(screen.getByText('Strong')).toBeInTheDocument();
+ expect(screen.getAllByText('(met)')).toHaveLength(4);
+ });
+
+ it('reports the value and met count', () => {
+ const onValueChange = vi.fn();
+ render( );
+ type('abcDEF1');
+ expect(onValueChange).toHaveBeenLastCalledWith('abcDEF1', 2);
+ });
+
+ it('toggles visibility with the eye button', () => {
+ render( );
+ fireEvent.click(screen.getByRole('button', { name: 'Show password' }));
+ expect(screen.getByLabelText('Password')).toHaveAttribute('type', 'text');
+ const hide = screen.getByRole('button', { name: 'Hide password' });
+ expect(hide).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(hide);
+ expect(screen.getByLabelText('Password')).toHaveAttribute('type', 'password');
+ });
+
+ it('draws the password mask with the asterisk font', () => {
+ render( );
+ const input = screen.getByLabelText('Password');
+ expect(input.style.fontFamily).toMatch(/^tween-password-mask/);
+ expect(document.head.innerHTML + document.body.innerHTML).toContain(
+ 'unicode-range:U+2022,U+25CF'
+ );
+ });
+
+ it('accepts custom rules', () => {
+ render(
+ value.includes('-') }]} />
+ );
+ type('a-b');
+ expect(screen.getByText('Has a dash').closest('li')).toHaveAttribute('data-met', 'true');
+ expect(screen.getByText('Strong')).toBeInTheDocument();
+ });
+
+ it('follows the controlled value', () => {
+ const { rerender } = render( );
+ rerender( );
+ expect(screen.getByLabelText('Password')).toHaveValue('abcDEF12!@');
+ expect(screen.getByText('Strong')).toBeInTheDocument();
+ });
+
+ it('works under reduced motion', () => {
+ setReducedMotion(true);
+ render( );
+ type('abcDEF1');
+ expect(screen.getByText('Fair')).toBeInTheDocument();
+ });
+});