{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "measure",
  "title": "Measure",
  "description": "A paragraph whose measure you set by dragging its right edge, with the number of characters a line and a verdict on it.",
  "dependencies": [
    "@chenglou/pretext"
  ],
  "registryDependencies": [
    "https://thedirectors.agency/ui/r/0nlytype.json"
  ],
  "files": [
    {
      "path": "registry/0nlytype/ui/measure.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/** The <html> switches that change the face; smooth scrolling toggles a class there on every scroll, which must not re-lay the text. */\nconst FACE = [\"data-pair\", \"data-scheme\", \"data-mode\", \"data-key\"]\n\ntype MeasureProps = Omit<React.ComponentProps<\"div\">, \"children\" | \"defaultValue\"> & {\n  /** The paragraph. Plain text: pretext measures it. */\n  children: string\n  /** Characters a line, to begin with. */\n  defaultMeasure?: number\n  /** The shortest measure the handle allows, in characters. */\n  min?: number\n  /** The longest measure the handle allows, in characters. */\n  max?: number\n  /** track: the handle rides a hairline. alphabets: a ruler of lowercase alphabets, the measure read in alphabets. columns: the page takes as many columns of that measure as it holds. */\n  variant?: \"track\" | \"alphabets\" | \"columns\"\n}\n\n/** Below this a line is too short to read in; above COMFORT_TO the eye loses the next line. */\nconst COMFORT_FROM = 45\nconst COMFORT_TO = 75\n\nconst verdict = (n: number) => (n < COMFORT_FROM ? \"too short to read in\" : n <= COMFORT_TO ? \"comfortable\" : \"the eye loses the next line\")\n\ntype Engine = { lay: (px: number) => string[]; ch: number; lh: number; room: number; width: number; em: number; abc: number[] }\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyz\"\nconst SAY = [\"no\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n\n/** A length in lowercase alphabets, to the quarter: \"2½ alphabets\", \"¾ of an alphabet\". */\nfunction inAlphabets(x: number) {\n  const q = Math.round(x * 4)\n  const [whole, part] = [Math.floor(q / 4), [\"\", \"¼\", \"½\", \"¾\"][q % 4]]\n  if (!whole) return part ? `${part} of an alphabet` : \"no alphabet\"\n  return `${whole}${part} alphabet${whole === 1 && !part ? \"\" : \"s\"}`\n}\n\n/**\n * A paragraph whose measure you set by dragging its right edge. The edge is a hairline with a ring\n * on a track above it, and the range where a line reads well is marked on that track in the accent.\n * Pretext lays the lines again whenever the width changes, so they follow the hand. The handle is a\n * slider (arrows step a character, Page steps ten), the measure is the italic, and the verdict is\n * pencil. The lines are aria-hidden; the text is there once for a reader.\n * `alphabets` makes the track a ruler of lowercase alphabets, as a type specimen gives a face's\n * alphabet length, and reads the measure in alphabets; `columns` sets as many columns of the\n * measure as the page holds, so narrowing the line brings another column in.\n */\nfunction Measure({ children: text, defaultMeasure = 62, min = 20, max = 110, variant = \"track\", className, style, ...props }: MeasureProps) {\n  const stage = React.useRef<HTMLDivElement>(null)\n  const body = React.useRef<HTMLParagraphElement>(null)\n  const [measure, setMeasure] = React.useState(defaultMeasure)\n  const [engine, setEngine] = React.useState<Engine | null>(null)\n\n  // The most characters the container can hold: the handle stops at the edge of the page.\n  const room = engine ? Math.max(min, Math.min(max, engine.room)) : max\n  const n = Math.min(Math.max(measure, min), room)\n  const lines = React.useMemo(() => engine?.lay(n * engine.ch) ?? null, [engine, n])\n  // columns: as many columns of this measure as the page holds, two ems apart, never more than there are lines.\n  const gap = engine ? 2 * engine.em : 0\n  const cols = variant === \"columns\" && engine && lines ? Math.max(1, Math.min(lines.length, Math.floor((engine.width + gap) / (n * engine.ch + gap)))) : 1\n  // alphabets: how many lowercase alphabets the line is, and the ruler's letter the edge falls on.\n  const px = engine ? n * engine.ch : 0\n  const abcs = engine && engine.abc[26] ? px / engine.abc[26] : 0\n  const edge = engine ? engine.abc.findIndex((w, i) => i > 0 && w > px) - 1 : -1\n  const said = variant === \"alphabets\" ? `${inAlphabets(abcs)} a line` : `${n} characters a line`\n  const judged = variant === \"columns\" && cols > 1 ? `${verdict(n)}, in ${SAY[cols] ?? cols} columns` : verdict(n)\n\n  React.useEffect(() => {\n    const el = body.current, box = stage.current\n    if (!el || !box) return\n    let cancelled = false\n    const off: (() => void)[] = []\n\n    ;(async () => {\n      let lib: typeof import(\"@chenglou/pretext\")\n      try {\n        lib = await import(\"@chenglou/pretext\")\n      } catch {\n        return // the plain paragraph stays\n      }\n      let font = \"\", prepared: ReturnType<typeof lib.prepareWithSegments> | undefined, ch = 8\n\n      async function measureFace() {\n        if (cancelled || !el!.isConnected) return\n        const style = getComputedStyle(el!)\n        const next = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`\n        if (next !== font || !prepared) {\n          font = next\n          await document.fonts.load(font, text)\n          if (cancelled || !el!.isConnected) return\n          prepared = lib.prepareWithSegments(text, font)\n          // A character is the average one in this text, so \"62 characters a line\" is what the lines really hold.\n          ch = lib.layoutNextLine(prepared, { segmentIndex: 0, graphemeIndex: 0 }, 1e6)!.width / text.length\n        }\n        const size = parseFloat(style.fontSize)\n        const p = prepared\n        // The ruler of alphabets: where each of its letters ends, kerning and all, as far as the handle can go.\n        const ctx = document.createElement(\"canvas\").getContext(\"2d\")!\n        ctx.font = font\n        const ruler = ALPHABET.repeat(Math.ceil((max * ch) / ctx.measureText(ALPHABET).width) + 1)\n        const abc = Array.from({ length: ruler.length + 1 }, (_, i) => ctx.measureText(ruler.slice(0, i)).width)\n        if (cancelled) return\n        setEngine({\n          width: box!.clientWidth,\n          em: size,\n          abc,\n          ch,\n          lh: parseFloat(style.lineHeight) || size * 1.6,\n          room: Math.floor(box!.clientWidth / ch),\n          lay(px) {\n            const out: string[] = []\n            let cursor = { segmentIndex: 0, graphemeIndex: 0 }\n            for (let guard = 0; guard < 2000; guard++) {\n              const line = lib.layoutNextLine(p, cursor, px)\n              if (!line) break\n              out.push(line.text.trimEnd())\n              cursor = line.end\n            }\n            return out\n          },\n        })\n      }\n\n      await measureFace()\n      if (cancelled) return\n      let width = box.clientWidth\n      const resized = new ResizeObserver(() => {\n        if (box.clientWidth !== width) { width = box.clientWidth; measureFace() }\n      })\n      resized.observe(box)\n      // A change of pair or scheme on <html> can change the face: measure again.\n      const restyled = new MutationObserver(() => measureFace())\n      restyled.observe(document.documentElement, { attributeFilter: FACE })\n      off.push(() => { resized.disconnect(); restyled.disconnect() })\n    })()\n\n    return () => {\n      cancelled = true\n      off.forEach((f) => f())\n    }\n  }, [text, max])\n\n  const set = (v: number) => setMeasure(Math.min(Math.max(Math.round(v), min), room))\n  // Dragging: the pointer's distance from the paragraph's left edge, in characters.\n  const drag = (e: React.PointerEvent) => {\n    if (!engine || !(e.buttons & 1) || !stage.current) return\n    const box = stage.current.getBoundingClientRect()\n    // The edge is the line's end: the right in left-to-right, the left in right-to-left.\n    set((getComputedStyle(stage.current).direction === \"rtl\" ? box.right - e.clientX : e.clientX - box.left) / engine.ch)\n  }\n  const press = (e: React.PointerEvent) => {\n    e.currentTarget.setPointerCapture(e.pointerId)\n    drag(e)\n  }\n  const keys = (e: React.KeyboardEvent) => {\n    // Right to left, the line grows leftward, so the arrows follow the edge.\n    const out = stage.current && getComputedStyle(stage.current).direction === \"rtl\" ? -1 : 1\n    const to: Record<string, number> = { ArrowRight: n + out, ArrowUp: n + 1, ArrowLeft: n - out, ArrowDown: n - 1, PageUp: n + 10, PageDown: n - 10, Home: min, End: room }\n    if (!(e.key in to)) return\n    e.preventDefault()\n    set(to[e.key])\n  }\n  const handlers = { onPointerDown: press, onPointerMove: drag }\n\n  return (\n    <div\n      data-slot=\"measure\"\n      data-variant={variant}\n      className={cn(\"ot-measure\", className)}\n      style={{ \"--n\": n, \"--ch\": engine ? `${engine.ch}px` : undefined, \"--cols\": cols, \"--gap\": `${gap}px`, ...style } as React.CSSProperties}\n      {...props}\n    >\n      <p className=\"ot-measure-read\" aria-hidden=\"true\">\n        {/* The readout is the library's English: each part is its own left-to-right run, so a right-to-left page keeps \"30 characters a line\" in order. */}\n        <span className=\"ot-measure-count\" dir=\"ltr\">\n          <span className=\"ot-measure-n\">{said.split(\" \")[0]}</span> {said.split(\" \").slice(1).join(\" \")}\n        </span>\n        <span className=\"ot-measure-verdict\" dir=\"ltr\">{judged}</span>\n      </p>\n      <div ref={stage} className=\"ot-measure-stage\">\n        <div className=\"ot-measure-track\" aria-hidden=\"true\" {...handlers}>\n          {variant === \"alphabets\" ? (\n            <span className=\"ot-measure-abc\">\n              {ALPHABET.repeat(engine ? (engine.abc.length - 1) / 26 : Math.ceil(max / 26) + 1)\n                .split(\"\")\n                .map((c, i) => (\n                  <span key={i} data-in={i < edge || undefined} data-edge={i === edge || undefined}>\n                    {c}\n                  </span>\n                ))}\n            </span>\n          ) : null}\n          <span className=\"ot-measure-good\" />\n          {/* The comfortable range's ends, as figures under the track, where the page is wide enough to hold them. */}\n          {[COMFORT_FROM, COMFORT_TO].map((at) =>\n            engine && at <= room ? (\n              <span key={at} className=\"ot-measure-at\" style={{ \"--at\": at } as React.CSSProperties}>\n                {at}\n              </span>\n            ) : null,\n          )}\n        </div>\n        <div\n          role=\"slider\"\n          tabIndex={0}\n          aria-label=\"Measure\"\n          aria-orientation=\"horizontal\"\n          aria-valuemin={min}\n          aria-valuemax={room}\n          aria-valuenow={n}\n          aria-valuetext={`${n} characters a line${variant === \"alphabets\" ? `, ${inAlphabets(abcs)}` : \"\"}, ${judged}`}\n          className=\"ot-measure-handle\"\n          onKeyDown={keys}\n          {...handlers}\n        >\n          <span className=\"ot-measure-ring\" />\n        </div>\n        <p ref={body} className=\"ot-measure-body\">\n          <span className=\"ot-sr\">{text}</span>\n          {lines ? (\n            <span aria-hidden=\"true\" className=\"ot-measure-lines\">\n              {lines.map((line, i) => (\n                <span key={i}>{line}</span>\n              ))}\n            </span>\n          ) : (\n            <span aria-hidden=\"true\">{text}</span>\n          )}\n        </p>\n      </div>\n    </div>\n  )\n}\n\nexport { Measure, type MeasureProps }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/0nlytype/styles/measure.css",
      "content": "@layer components {\n  /* ── ot-measure ── a paragraph whose width you set by its right edge. Everything is drawn in\n     characters (--ch: the average one in this text, measured by pretext; 1ch until then), so the handle, the track and the text agree.\n     The track runs the whole width; the range where a line reads well is the accent on it. */\n  .ot-measure { max-width: 100%; --track: 2.25rem; --from: 45; --to: 75; /* the comfortable range, in characters */ margin: 0; font-size: var(--ot-p); line-height: var(--ot-p-lh); }\n  /* A phone can't hold a comfortable measure at reading size, so it sets the paragraph a size down. */\n  @media (max-width: 30rem) { .ot-measure { font-size: var(--ot-pp); line-height: var(--ot-pp-lh); } }\n  .ot-measure-read { display: flex; flex-direction: column; align-items: start; gap: var(--ot-space-1); margin: 0 0 var(--ot-space-4); }\n  /* The count: the number large, its words a dynamic down beside it, on one baseline (scale contrast, as \"It has to be design.\" sets it). */\n  .ot-measure-count { font-family: var(--ot-expression); font-style: italic; font-size: calc(var(--ot-mp) * var(--ot-expression-scale)); line-height: 1; letter-spacing: 0; color: var(--ot-ink); font-variant-numeric: lining-nums; }\n  .ot-measure-n { font-size: calc(var(--ot-mf) * var(--ot-expression-scale)); }\n  .ot-measure-verdict { font-size: var(--ot-pp); line-height: var(--ot-pp-lh); letter-spacing: var(--ot-pp-tr); color: var(--ot-pencil); }\n\n  .ot-measure-stage { position: relative; padding-top: var(--track); }\n  .ot-measure-track {\n    position: absolute; inset: 0 0 auto; height: var(--track); cursor: ew-resize; touch-action: none;\n    background: linear-gradient(var(--ot-rule-strong), var(--ot-rule-strong)) 0 50% / 100% var(--ot-hairline) no-repeat;\n  }\n  .ot-measure-good {\n    position: absolute; top: calc(50% - var(--ot-stroke) / 2); height: var(--ot-stroke); background: var(--ot-accent);\n    inset-inline-start: calc(var(--from) * var(--ch, 1ch)); width: calc((var(--to) - var(--from)) * var(--ch, 1ch)); max-width: calc(100% - var(--from) * var(--ch, 1ch));\n  }\n  /* The comfortable range's ends as figures over the track, small and in pencil, as SPECTRA sets its data. */\n  .ot-measure-at {\n    position: absolute; bottom: calc(50% + 0.5rem); inset-inline-start: calc(var(--at) * var(--ch, 1ch)); translate: calc(var(--ot-measure-dir, 1) * -50%) 0; pointer-events: none;\n    font-size: var(--ot-pp); line-height: 1; letter-spacing: var(--ot-pp-tr); color: var(--ot-pencil); font-variant-numeric: tabular-nums lining-nums;\n  }\n  /* The handle is the paragraph's right edge, a hairline from the track down through the lines; its\n     ring sits on the track. The hit area is wider than what's drawn. */\n  .ot-measure-handle {\n    position: absolute; top: 0; bottom: 0; inset-inline-start: calc(var(--n) * var(--ch, 1ch)); width: 2.25rem; translate: calc(var(--ot-measure-dir, 1) * -50%) 0;\n    cursor: ew-resize; touch-action: none; outline: 0;\n    background: linear-gradient(var(--ot-ink), var(--ot-ink)) 50% var(--track) / var(--ot-hairline) calc(100% - var(--track)) no-repeat;\n  }\n  .ot-measure-ring {\n    position: absolute; top: calc(var(--track) / 2); left: 50%; width: 0.75rem; height: 0.75rem; translate: -50% -50%;\n    border: var(--ot-stroke) solid var(--ot-ink); border-radius: 50%; background: var(--ot-paper);\n    transition: scale var(--ot-allegro) var(--ot-exhale);\n  }\n  .ot-measure-handle:is(:hover, :active) .ot-measure-ring { scale: 1.25; }\n  :is(.ot-measure-handle:focus-visible, .ot-measure[data-force~=\"focus\"] .ot-measure-handle) .ot-measure-ring { outline: var(--ot-stroke) solid var(--ot-accent); outline-offset: 4px; }\n\n  /* Right to left the edge is the line's end on the left: the handle and the figures centre the other way. */\n  .ot-measure:is([dir=\"rtl\"], [dir=\"rtl\"] *) { --ot-measure-dir: -1; }\n  .ot-measure-body { margin: 0; width: calc(var(--n) * var(--ch, 1ch)); max-width: 100%; color: var(--ot-graphite); }\n  .ot-measure-lines { display: block; }\n  .ot-measure-lines > span { display: block; white-space: pre; }\n\n  /* alphabets: the track is a ruler of lowercase alphabets in the paragraph's own face and size, as a\n     type specimen gives a face's alphabet length. The letters inside the measure are graphite, the\n     rest a rule's grey, and the letter the edge cuts is the accent; the hairline runs down through it. The\n     comfortable range is a hairline under the ruler. */\n  .ot-measure[data-variant=\"alphabets\"] { --track: 3rem; }\n  .ot-measure[data-variant=\"alphabets\"] .ot-measure-track { background: none; overflow: clip; }\n  .ot-measure-abc {\n    position: absolute; inset-inline: 0; top: 50%; translate: 0 -50%; display: block; overflow: clip;\n    line-height: 1; white-space: pre; color: var(--ot-rule-strong); /* the ruler beyond the measure: drawn, not read */\n  }\n  .ot-measure-abc > [data-in] { color: var(--ot-graphite); }\n  .ot-measure-abc > [data-edge] { color: var(--ot-accent); }\n  .ot-measure[data-variant=\"alphabets\"] .ot-measure-good { top: calc(50% + 0.75em); height: var(--ot-hairline); background: var(--ot-rule-strong); }\n  .ot-measure[data-variant=\"alphabets\"] .ot-measure-at, .ot-measure[data-variant=\"alphabets\"] .ot-measure-ring { display: none; }\n  .ot-measure[data-variant=\"alphabets\"] .ot-measure-handle { background-position: 50% 0; background-size: var(--ot-hairline) 100%; }\n  .ot-measure[data-variant=\"alphabets\"] :is(.ot-measure-handle:focus-visible, [data-force~=\"focus\"] .ot-measure-handle) { background-image: linear-gradient(var(--ot-accent), var(--ot-accent)); background-size: var(--ot-stroke) 100%; }\n\n  /* columns: the page takes as many columns of the measure as it holds, two ems apart, balanced;\n     the handle is the first column's edge, and narrowing the line brings another column in. */\n  .ot-measure[data-variant=\"columns\"] .ot-measure-body {\n    width: calc(var(--cols) * var(--n) * var(--ch, 1ch) + (var(--cols) - 1) * var(--gap)); column-count: var(--cols); column-gap: var(--gap);\n  }\n\n  /* Forced colours: the hairlines in CanvasText, the comfortable range and the edge letter in Highlight. */\n  @media (forced-colors: active) {\n    .ot-measure-track, .ot-measure-handle, .ot-measure-good, .ot-measure-abc { forced-color-adjust: none; }\n    .ot-measure-track { background-image: linear-gradient(CanvasText, CanvasText); }\n    .ot-measure-handle { background-image: linear-gradient(CanvasText, CanvasText); }\n    .ot-measure-good { background: Highlight; }\n    .ot-measure-ring { border-color: CanvasText; background: Canvas; }\n    .ot-measure-abc { color: GrayText; }\n    .ot-measure-abc > [data-in] { color: CanvasText; }\n    .ot-measure-abc > [data-edge] { color: Highlight; }\n  }\n}\n",
      "type": "registry:file",
      "target": "styles/0nlytype/measure.css"
    }
  ],
  "css": {
    "@import \"../styles/0nlytype/measure.css\"": {}
  },
  "meta": {
    "movement": "II",
    "underneath": "hook",
    "contract": "ot-measure"
  },
  "type": "registry:ui"
}
