{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "glide",
  "title": "Glide",
  "description": "Keeps text under a slow transform off the pixel grid: the lines of text under a moving transform lean by an angle too small to see, so they travel smoothly instead of clicking along pixel by pixel.",
  "files": [
    {
      "path": "registry/remocn/glide/index.ts",
      "content": "import { useEffect, useLayoutEffect } from \"react\";\n\n// Chrome parks a glyph raster on a whole pixel vertically for as long as the\n// matrix that carries it is axis-aligned, so text under a slow transform\n// clicks along pixel by pixel. A lean too small to see takes it off that grid.\n//\n// A transform that carries text is marked, and told when it moves:\n//\n//   const glide = useGlide();\n//   transform: `scale(${s})${glide(moving)}`\n//\n// The mark changes nothing by itself. After every frame the blocks of text\n// under a marked transform get the lean: each about its own centre, and each\n// by no more than its size on the screen needs. A card, a hairline or an image\n// is fine under a transform as it is, so they stay level.\n//\n// Text leans while its transform moves, and it keeps the lean at rest when it\n// rests off the pixel grid (a scene shown smaller in a player, a camera that\n// holds at 1.03): dropping the lean there would snap it to the nearest pixel,\n// up to half a pixel in one frame, and picking it up would snap it back. Text\n// that rests on the grid loses the lean without moving, so a scene at rest at\n// full size is drawn exactly as it would be without any of this.\n\n/**\n * Returns `glide(moving)`: append it to a transform that carries text, with\n * `moving` true on the frames where that transform changes.\n *\n * Everything else lives inside this one closure: the build of Studio\n * elements pastes this file whole into the component that uses it, where a\n * second `LEAN` or `lean` at the top level would collide.\n */\nexport const useGlide = (() => {\n  /** What `glide(false)` adds to a transform: an identity matrix, to find it by. */\n  const AT_REST = \" matrix(1, 0, 0, 1, 0, 0)\";\n  /** `glide(true)` adds it twice. */\n  const MOVING = AT_REST + AT_REST;\n  const MARKED = `[style*=\"${AT_REST.trim()}\"]`;\n  // Text leaves the grid once the matrix leans x into y by half of 1/1024 in\n  // device pixels (Skia rounds the glyph matrix to 1/1024). A fifth over it.\n  const LEAN = 0.6 / 1024;\n  // Past this the text is a speck on the screen; it is left alone.\n  const STEEPEST = 5;\n  // How far from a whole pixel text may rest and still count as on the grid:\n  // the jump it makes when the lean goes is no bigger than this.\n  const ON_GRID = 0.05;\n\n  /** The linear part of a 2D matrix: x' = a·x + c·y, y' = b·x + d·y. */\n  type Lin = [a: number, b: number, c: number, d: number];\n  const LEVEL: Lin = [1, 0, 0, 1];\n  const times = (m: Lin, n: Lin): Lin => [\n    m[0] * n[0] + m[2] * n[1],\n    m[1] * n[0] + m[3] * n[1],\n    m[0] * n[2] + m[2] * n[3],\n    m[1] * n[2] + m[3] * n[3],\n  ];\n  const turned = (degrees: number): Lin => {\n    const t = (degrees * Math.PI) / 180;\n    return [Math.cos(t), Math.sin(t), -Math.sin(t), Math.cos(t)];\n  };\n  const offWhole = (n: number) => Math.abs(n - Math.round(n));\n\n  type Block = HTMLElement | SVGTextElement | SVGSVGElement;\n  let leant: Block[] = [];\n  // Fonts arrive after the first pass and change what is laid out where, with\n  // no render to follow: a block or a marked element that changes size is read\n  // again before the frame is painted.\n  let watcher: ResizeObserver | undefined;\n  const watched = new WeakSet<Element>();\n  const watch = (el: Element) => {\n    if (watched.has(el)) return;\n    watched.add(el);\n    watcher ??= new ResizeObserver(() => lean());\n    watcher.observe(el);\n  };\n\n  const depthOf = (el: Element) => {\n    let depth = 0;\n    for (let up = el.parentElement; up; up = up.parentElement) depth += 1;\n    return depth;\n  };\n\n  /** The nearest box around a text node that a transform applies to. */\n  const blockOf = (node: Node): Block | null => {\n    for (let el = node.parentElement; el; el = el.parentElement) {\n      if (el instanceof SVGElement) {\n        const text = el.closest(\"text\");\n        if (!(text instanceof SVGTextElement)) return null;\n        // Text that only shapes a mask or a clip is not drawn where it stands\n        // and cannot turn by itself: its whole drawing leans for it.\n        if (!text.closest(\"defs, mask, clipPath, pattern, symbol, marker\"))\n          return text;\n        let drawing = text.ownerSVGElement;\n        while (drawing?.ownerSVGElement) drawing = drawing.ownerSVGElement;\n        return drawing;\n      }\n      if (!(el instanceof HTMLElement)) continue;\n      const { display } = getComputedStyle(el);\n      if (display !== \"inline\" && display !== \"contents\") return el;\n    }\n    return null;\n  };\n\n  /** One pass over the page: what every element's own transforms do. */\n  function reader(given: Map<Element, number>) {\n    type Own = {\n      /** `scale` and `transform`, without the `rotate` property. */\n      lin: Lin;\n      /** `rotate`, in degrees: a lean given in this pass, or the scene's own. */\n      turn: number;\n      /** How far down it is moved, and by what whole factor it is scaled from\n       * its top left corner; null when it does anything else. */\n      carry: { dy: number; k: number } | null;\n    };\n    const lens = new Map<Element, boolean>();\n    /** Whether an element shows its children in perspective. */\n    const lensOn = (el: Element | null): boolean => {\n      if (!el) return false;\n      const seen = lens.get(el);\n      if (seen !== undefined) return seen;\n      const style = getComputedStyle(el);\n      const result =\n        style.perspective !== \"none\" ||\n        (style.transformStyle === \"preserve-3d\" && lensOn(el.parentElement));\n      lens.set(el, result);\n      return result;\n    };\n    const own = new Map<Element, Own | null>();\n    const ownOf = (el: Element): Own | null => {\n      const seen = own.get(el);\n      if (seen !== undefined) return seen;\n      const style = getComputedStyle(el);\n      const m = new DOMMatrixReadOnly(\n        style.transform === \"none\" ? \"\" : style.transform,\n      );\n      const scale = style.scale === \"none\" ? [] : style.scale.split(\" \");\n      const sx = scale.length ? Number.parseFloat(scale[0]) : 1;\n      const sy = scale.length > 1 ? Number.parseFloat(scale[1]) : sx;\n      const rotate = style.rotate === \"none\" ? [] : style.rotate.split(\" \");\n      let result: Own | null = null;\n      // Seen in perspective, text is drawn on a layer of its own: not ours. A\n      // turn out of the plane without perspective lands flat on the screen,\n      // and text under it snaps like any other.\n      // A push along z alone, or a half turn, leaves it flat even under a lens.\n      const inPerspective =\n        Math.max(Math.abs(m.m14), Math.abs(m.m24), Math.abs(m.m34)) > 1e-9 ||\n        (Math.max(\n          Math.abs(m.m13),\n          Math.abs(m.m31),\n          Math.abs(m.m23),\n          Math.abs(m.m32),\n        ) > 1e-6 &&\n          lensOn(el.parentElement));\n      if (!inPerspective && rotate.length < 2) {\n        // The `scale` property acts on what `transform` has produced.\n        const lin: Lin = [m.a * sx, m.b * sy, m.c * sx, m.d * sy];\n        const moved =\n          style.translate === \"none\"\n            ? 0\n            : (style.translate.split(\" \")[1] ?? \"0px\");\n        const k = Math.round(lin[0]);\n        const whole =\n          m.is2D &&\n          k >= 1 &&\n          Math.abs(lin[0] - k) < 1e-4 &&\n          Math.abs(lin[3] - k) < 1e-4 &&\n          Math.abs(lin[1]) < 1e-5 &&\n          Math.abs(lin[2]) < 1e-5 &&\n          rotate.length === 0 &&\n          (moved === 0 || moved.endsWith(\"px\")) &&\n          // Scaled about its corner, a box stays where layout put it.\n          (k === 1 || /^0(px)? 0(px)?/.test(style.transformOrigin));\n        result = {\n          lin,\n          turn: rotate.length ? Number.parseFloat(rotate[0]) : 0,\n          carry: whole\n            ? { dy: sy * m.f + (moved === 0 ? 0 : Number.parseFloat(moved)), k }\n            : null,\n        };\n      }\n      own.set(el, result);\n      return result;\n    };\n    const down = new Map<Element, Lin | null>();\n    /** Everything from the page down to and including this element. */\n    const linDown = (el: Element | null): Lin | null => {\n      if (!el) return LEVEL;\n      const seen = down.get(el);\n      if (seen !== undefined) return seen;\n      const above = linDown(el.parentElement);\n      const mine = above && ownOf(el);\n      const result =\n        above && mine\n          ? times(times(above, turned(given.get(el) ?? mine.turn)), mine.lin)\n          : null;\n      down.set(el, result);\n      return result;\n    };\n    const carried = new Map<Element, { dy: number; k: number } | null>();\n    const carryDown = (\n      el: Element | null,\n    ): { dy: number; k: number } | null => {\n      if (!el) return { dy: 0, k: 1 };\n      const seen = carried.get(el);\n      if (seen !== undefined) return seen;\n      const above = carryDown(el.parentElement);\n      const mine = above && !given.has(el) ? ownOf(el)?.carry : null;\n      const result =\n        above && mine\n          ? { dy: above.dy + above.k * mine.dy, k: above.k * mine.k }\n          : null;\n      carried.set(el, result);\n      return result;\n    };\n    return { ownOf, linDown, carryDown };\n  }\n\n  /**\n   * Whether text in an SVG rests on the grid: it is placed wherever it is told\n   * to, so only when it is shown one to one and its baseline happens to land on\n   * a whole pixel. `lands` is where its own space lands on the screen.\n   */\n  function restsOnGrid(text: SVGTextElement, lands: DOMMatrix | null) {\n    if (!lands) return false;\n    const dpr = window.devicePixelRatio;\n    const style = getComputedStyle(text);\n    const k = lands.d * dpr;\n    const y = text.y.baseVal.numberOfItems\n      ? text.y.baseVal.getItem(0).value\n      : 0;\n    return (\n      text.y.baseVal.numberOfItems <= 1 &&\n      text.dy.baseVal.numberOfItems === 0 &&\n      !text.querySelector(\"tspan[y], tspan[dy], textPath\") &&\n      /^(auto|alphabetic)$/.test(style.dominantBaseline) &&\n      /^(auto|baseline)$/.test(style.alignmentBaseline) &&\n      Math.abs(lands.b) < 1e-6 &&\n      Math.abs(lands.c) < 1e-6 &&\n      Math.round(k) >= 1 &&\n      offWhole(k) < 2e-3 &&\n      offWhole((lands.d * y + lands.f) * dpr) < ON_GRID\n    );\n  }\n\n  /**\n   * The angle that takes a block off the grid, given what is above it (`above`)\n   * and what its own transform does (`own`), both in device pixels: the lean is\n   * a turn between the two. 0 when the block leans enough as it is, null when\n   * no sane angle would do.\n   */\n  function angleFor(above: Lin, own: Lin): number | null {\n    // y from x of `above · turn(θ) · own` is p·sin θ + q·cos θ.\n    const p = above[3] * own[0] - above[1] * own[1];\n    const q = above[1] * own[0] + above[3] * own[1];\n    if (Math.abs(q) >= LEAN) return 0;\n    if (Math.abs(p) < 1e-9) return null;\n    // Along the turn the scene already has, so the two never cancel out.\n    const sine = ((q < 0 ? -LEAN : LEAN) - q) / p;\n    if (Math.abs(sine) > Math.sin((STEEPEST * Math.PI) / 180)) return null;\n    return (Math.asin(sine) * 180) / Math.PI;\n  }\n\n  function lean() {\n    for (const el of leant) {\n      el.style.removeProperty(\"rotate\");\n      if (el instanceof SVGElement) el.style.removeProperty(\"translate\");\n    }\n    leant = [];\n    const zones = document.querySelectorAll<HTMLElement | SVGElement>(MARKED);\n    if (zones.length === 0) return;\n    // Each block of text under a mark, and whether any transform above it moves.\n    const blocks = new Map<Block, boolean>();\n    // The texts a whole drawing leans for.\n    const standsFor = new Map<SVGSVGElement, SVGTextElement[]>();\n    for (const zone of zones) {\n      const moving = zone.style.transform.includes(MOVING.trim());\n      const walker = document.createTreeWalker(zone, NodeFilter.SHOW_TEXT);\n      for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n        if (!/\\S/.test(node.nodeValue ?? \"\")) continue;\n        const block = blockOf(node);\n        // A block that turns by a property of its own is left to the scene.\n        if (!block || block.style.rotate) continue;\n        blocks.set(block, moving || (blocks.get(block) ?? false));\n        const text = node.parentElement?.closest(\"text\");\n        if (block instanceof SVGSVGElement && text instanceof SVGTextElement)\n          standsFor.set(block, [...(standsFor.get(block) ?? []), text]);\n      }\n      watch(zone);\n    }\n    for (const block of blocks.keys()) watch(block);\n    const dpr = window.devicePixelRatio;\n    const scaled = (m: Lin): Lin => [\n      m[0] * dpr,\n      m[1] * dpr,\n      m[2] * dpr,\n      m[3] * dpr,\n    ];\n    // Outer blocks first: a block inside a leaning one takes only what it\n    // still lacks, so leans never pile up. Everything is read before anything\n    // is written; `given` stands in for the leans not yet on the page.\n    const given = new Map<Element, number>();\n    const { ownOf, linDown, carryDown } = reader(given);\n    const writes: (() => void)[] = [];\n    const ordered = [...blocks.keys()].sort((a, b) => depthOf(a) - depthOf(b));\n    for (const el of ordered) {\n      const moving = blocks.get(el) === true;\n      if (el instanceof HTMLElement) {\n        const above = linDown(el.parentElement);\n        const mine = ownOf(el);\n        if (!above || !mine) continue;\n        if (!moving) {\n          // Layout puts a baseline on a whole pixel wherever the box itself\n          // sits, so text is on the grid when the transforms around it only\n          // move it by whole pixels and show it one to one (or two, or three).\n          const carry = carryDown(el);\n          if (\n            carry &&\n            offWhole(carry.k * dpr) < 2e-3 &&\n            offWhole(carry.dy * dpr) < ON_GRID\n          )\n            continue;\n        }\n        const angle = angleFor(scaled(above), mine.lin);\n        if (!angle) continue;\n        given.set(el, angle);\n        writes.push(() => el.style.setProperty(\"rotate\", `${angle}deg`));\n        leant.push(el);\n        continue;\n      }\n      if (el instanceof SVGSVGElement) {\n        // A whole drawing: what it does itself is its own transform and the\n        // scale of its viewBox, read off where it lands on the screen.\n        const above = linDown(el.parentElement);\n        const lands = el.getScreenCTM();\n        const det = above ? above[0] * above[3] - above[1] * above[2] : 0;\n        if (!above || !lands || Math.abs(det) < 1e-12) continue;\n        if (\n          !moving &&\n          (standsFor.get(el) ?? []).every((text) =>\n            restsOnGrid(text, text.getScreenCTM()),\n          )\n        )\n          continue;\n        const mine = times(\n          [above[3] / det, -above[1] / det, -above[2] / det, above[0] / det],\n          [lands.a, lands.b, lands.c, lands.d],\n        );\n        const angle = angleFor(scaled(above), mine);\n        if (!angle) continue;\n        given.set(el, angle);\n        writes.push(() => el.style.setProperty(\"rotate\", `${angle}deg`));\n        leant.push(el);\n        continue;\n      }\n      // Its drawing leans as a whole already.\n      let drawing = el.ownerSVGElement;\n      while (drawing?.ownerSVGElement) drawing = drawing.ownerSVGElement;\n      if (drawing && given.has(drawing)) continue;\n      // Text in an SVG is placed wherever it is told to, so it is on the grid\n      // only when its baseline happens to land on a whole pixel.\n      const frame = el.parentNode;\n      if (!(frame instanceof SVGGraphicsElement) || el.style.translate)\n        continue;\n      const outer = frame.getScreenCTM();\n      const whole = el.getScreenCTM();\n      if (\n        !outer ||\n        !whole ||\n        Math.abs(outer.a * outer.d - outer.b * outer.c) < 1e-12\n      )\n        continue;\n      // What the text element itself does, in the space it is placed in.\n      const mine = outer.inverse().multiply(whole);\n      if (!moving && restsOnGrid(el, whole)) continue;\n      const angle = angleFor(scaled([outer.a, outer.b, outer.c, outer.d]), [\n        mine.a,\n        mine.b,\n        mine.c,\n        mine.d,\n      ]);\n      if (!angle) continue;\n      // An SVG element turns about the corner of its drawing. A move brings\n      // the turn to the middle of the text instead.\n      const box = el.getBBox();\n      const [cx, cy] = [box.x + box.width / 2, box.y + box.height / 2];\n      const [px, py] = [\n        mine.a * cx + mine.c * cy + mine.e,\n        mine.b * cx + mine.d * cy + mine.f,\n      ];\n      const [cos, sin] = [turned(angle)[0], turned(angle)[1]];\n      const [tx, ty] = [px - (px * cos - py * sin), py - (px * sin + py * cos)];\n      writes.push(() => {\n        el.style.setProperty(\"rotate\", `${angle}deg`);\n        el.style.setProperty(\"translate\", `${tx}px ${ty}px`);\n      });\n      leant.push(el);\n    }\n    for (const write of writes) write();\n  }\n\n  const useFrameEffect =\n    typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\n  function useGlide() {\n    // No dependencies: the lean follows whatever this frame laid out.\n    useFrameEffect(lean);\n    return glide;\n  }\n\n  const glide = (moving: boolean) => (moving ? MOVING : AT_REST);\n\n  return useGlide;\n})();\n",
      "type": "registry:lib",
      "target": "lib/remocn/glide.ts"
    }
  ],
  "type": "registry:lib"
}
