{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "column-resize",
  "title": "Column resize",
  "description": "The edge of a table's column that resizes it, on ui-sdk's createResize: a drag, the arrow keys, Home and End, Enter or a double press to put it back, and a width an agent can set. The Table's.",
  "dependencies": [
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/number-format.json"
  ],
  "files": [
    {
      "path": "registry/lib/column-resize.ts",
      "content": "import { numberFormatter } from '@/registry/lib/number-format'\nimport {\n  announce,\n  type ChangeDetails,\n  createChange,\n  createResize,\n  definePrimitive,\n  isRTL,\n  live,\n  type ResizeDraft,\n} from '@ui-sdk/core'\n\n/*\n * The edge of a table's column that resizes it, built on ui-sdk's\n * `createResize` with one box, the column, and its end edge as the handle:\n * a pointer drags it, the arrows move it a step (Shift for a large one),\n * Home and End take it to its bounds, and Enter or a double press puts the\n * width back. While a pointer drags, the column takes each width at once;\n * the table owns how a width that lands at once or eases looks. An agent\n * sets a width with `resizeTo`.\n */\n\n/** Why a width changed: a drag, a key, a double press that put it back, or code and agents. */\ntype ColumnResizeReason = 'drag' | 'resize-key' | 'reset' | 'imperative'\n\ninterface ColumnResizeOptions {\n  /** The column's width in px, once resized: null while it keeps the width it was laid out at. */\n  width?: number | null\n  /** A width was asked for, or null to put it back. */\n  onWidthChange?: (\n    width: number | null,\n    details: ChangeDetails<ColumnResizeReason>,\n  ) => void\n  /** The column's name, as its announcements say it. */\n  name?: string\n  /** The narrowest it goes, in px. */\n  min?: number\n  /** The widest it goes, in px. */\n  max?: number\n  /** How far an arrow moves the edge, in px: 16 by default. */\n  step?: number\n  /** How far Shift with an arrow moves the edge, in px: 64 by default. */\n  largeStep?: number\n}\n\n/** The one box this resizes. */\nconst COLUMN = 'column'\n\n/** The column's head, which holds its width. */\nconst headOf = (el: HTMLElement | undefined) => el?.closest('th') ?? undefined\n\n/** The width the head has now: the one it is going to, not one partway through an ease. */\nfunction headWidth(head: HTMLElement) {\n  const kept = Number.parseFloat(head.style.getPropertyValue('--column-width'))\n  return Number.isNaN(kept) ? head.getBoundingClientRect().width : kept\n}\n\n/**\n * Lets the table's columns take a width at once, with no ease, while `run`\n * changes one and for the frame after, so the render that follows lands too.\n */\nfunction atOnce(table: HTMLElement | null | undefined, run: () => void) {\n  if (!table) return run()\n  table.dataset.resizing = ''\n  run()\n  requestAnimationFrame(() =>\n    requestAnimationFrame(() => {\n      if (!table.querySelector('[data-slot=column-resize][data-dragging]'))\n        delete table.dataset.resizing\n    }),\n  )\n}\n\n/** What a screen reader hears once a column's width is put back. */\nfunction columnResetMessage(name: string) {\n  return `${name} is back to the width it was laid out at.`\n}\n\n/** What a screen reader hears once a column's width changes. */\nfunction columnResizeMessage(name: string, width: number, locale?: string) {\n  return `${name} is ${numberFormatter(locale).format(width)} px wide.`\n}\n\nconst columnResize = definePrimitive({\n  name: 'column-resize',\n  options: {\n    width: 'number',\n    onWidthChange: 'callback',\n    name: 'string',\n    min: 'number',\n    max: 'number',\n    step: 'number',\n    largeStep: 'number',\n  },\n  controlled: ['width'],\n  state: (options: ColumnResizeOptions) => ({\n    width: options.width ?? null,\n    draft: null as ResizeDraft | null,\n  }),\n  sync: (options) => ({ width: options.width ?? null }),\n  api: (context) => {\n    const { options, store } = context\n    const change = createChange(context)\n    const handleEl = () => context.element('root')\n    const bounds = () => {\n      const { min = 64, max = 800 } = options()\n      return { min, max: Math.max(min, max) }\n    }\n    const clamp = (width: number) =>\n      Math.round(Math.min(Math.max(width, bounds().min), bounds().max))\n    // The laid-out width a drag started from, while the drag writes the head's.\n    let laidOut: number | null = null\n    // The width it shows: its own once resized, else the one it was laid out at.\n    const widthOf = (width: number | null) => {\n      if (width !== null) return width\n      if (laidOut !== null) return laidOut\n      const head = headOf(handleEl())\n      return head ? clamp(headWidth(head)) : bounds().min\n    }\n    // Whether the drag that just ended set a width.\n    let dropped = false\n    const commit = (\n      width: number | null,\n      details: { reason: ColumnResizeReason; event?: Event },\n    ) => {\n      const run = () => change('width', width, details)\n      // Every resize lands at once, as the table's own width does.\n      let done = false\n      atOnce(headOf(handleEl())?.closest('table'), () => {\n        done = run()\n      })\n      // A drop that went through keeps its width on the head until the render brings it.\n      if (details.reason === 'drag') dropped = done\n      return done\n    }\n    const resize = createResize(context, {\n      boxes: (state) => ({\n        [COLUMN]: { x: 0, y: 0, width: widthOf(state.width), height: 0 },\n      }),\n      draft: 'draft',\n      set: (value, details) => commit(value[COLUMN].width, details),\n      min: () => ({ width: bounds().min, height: 0 }),\n      max: () => ({ width: bounds().max, height: 0 }),\n      // A drop lands where it was let go; the arrows take their own steps below.\n      label: () => options().name ?? 'Column',\n      message: ({ box }) =>\n        columnResizeMessage(\n          options().name ?? 'Column',\n          box.width,\n          document.documentElement.lang || undefined,\n        ),\n    })\n    // The end edge: on the right, or the left in right to left.\n    const edge = (el: HTMLElement) => (isRTL(el) ? 'w' : 'e')\n    /** Sets the column's width in px, within its bounds, or puts it back with null: an agent's resize. */\n    const resizeTo = (width: number | null) => {\n      if (width !== null && !Number.isFinite(width)) {\n        throw new Error(\n          `A width is a number of px, or null to put it back; got ${width}.`,\n        )\n      }\n      const next = width === null ? null : clamp(width)\n      if (next === store.get().width) return false\n      return commit(next, { reason: 'imperative' })\n    }\n    /** Puts the width back to the one it was laid out at, and says so. */\n    const reset = (event: Event) => {\n      if (store.get().width === null) return\n      if (commit(null, { reason: 'reset', event }))\n        announce(columnResetMessage(options().name ?? 'Column'), {\n          priority: 'assertive',\n        })\n    }\n    return {\n      resize,\n      resizeTo,\n      bounds,\n      edge,\n      keydown(event: KeyboardEvent, el: HTMLElement) {\n        if (event.altKey || event.ctrlKey || event.metaKey) return\n        // Enter puts it back, as a double press does; Home and End take it to its bounds.\n        const to =\n          event.key === 'Enter'\n            ? { width: null, reason: 'reset' as const }\n            : event.key === 'Home'\n              ? { width: bounds().min, reason: 'resize-key' as const }\n              : event.key === 'End'\n                ? { width: bounds().max, reason: 'resize-key' as const }\n                : undefined\n        if (!to) {\n          // The arrows move the end edge a step, Shift a large one, across the screen.\n          const way = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0\n          if (way === 0) return\n          event.preventDefault()\n          const by = event.shiftKey ? (options().largeStep ?? 64) : (options().step ?? 16)\n          resize.resizeBy(COLUMN, edge(el), way * by, 0, { reason: 'resize-key', event })\n          return\n        }\n        event.preventDefault()\n        if (to.width === null) {\n          reset(event)\n          return\n        }\n        // Through the resize, so it is said as an arrow's is.\n        resize.resizeTo(\n          COLUMN,\n          { x: 0, y: 0, width: to.width, height: 0 },\n          { reason: to.reason, event },\n          edge(el),\n        )\n      },\n      reset,\n      /** Follows a drag on the head: each width the pointer gives, at once. */\n      follow(el: HTMLElement) {\n        const head = headOf(el)\n        const table = head?.closest('table')\n        if (!head) return\n        let dragging = false\n        return store.subscribe(() => {\n          const draft = store.get().draft\n          if (draft) {\n            if (!dragging) {\n              table?.setAttribute('data-resizing', '')\n              laidOut = store.get().width === null ? widthOf(null) : null\n            }\n            dragging = true\n            head.style.setProperty('--column-width', `${draft.box.width}px`)\n            return\n          }\n          if (!dragging) return\n          dragging = false\n          // The drop's change runs right after the draft ends: unless it set a\n          // width, as Escape or a refused change don't, the head goes back.\n          queueMicrotask(() => {\n            if (!dropped)\n              head.style.setProperty('--column-width', `${widthOf(store.get().width)}px`)\n            dropped = false\n            laidOut = null\n            atOnce(table, () => {})\n          })\n        })\n      },\n    }\n  },\n  slots: (slot) => ({\n    // A focusable separator, as ui-sdk's Resizable draws its handles.\n    root: slot({\n      role: 'separator',\n      focus: 'tab-stop',\n      keys: [\n        'ArrowLeft',\n        'ArrowRight',\n        'shift+ArrowLeft',\n        'shift+ArrowRight',\n        'Home',\n        'End',\n        'Enter',\n      ],\n      attrs: (state, { api }) => ({\n        tabindex: '0',\n        'aria-orientation': 'vertical',\n        'aria-valuemin': String(api.bounds().min),\n        'aria-valuemax': String(api.bounds().max),\n        // While it keeps the width it was laid out at, the table reads that out.\n        'aria-valuenow':\n          state.width === null ? undefined : String(Math.round(state.width)),\n      }),\n      live: live((state) => ({ 'data-dragging': state.draft ? '' : undefined })),\n      on: {\n        pointerdown: (event, { api, el }) => {\n          if (el) api.resize.pointerdown(event as PointerEvent, COLUMN, api.edge(el), el)\n        },\n        keydown: (event, { api, el }) => {\n          if (el) api.keydown(event as KeyboardEvent, el)\n        },\n        dblclick: (event, { api }) => api.reset(event),\n      },\n      bind: (el, { api }) => api.follow(el),\n    }),\n  }),\n  agent: { actions: ['resizeTo'] },\n})\n\nexport { columnResetMessage, columnResize, columnResizeMessage }\nexport type { ColumnResizeOptions, ColumnResizeReason }\n",
      "type": "registry:lib",
      "target": "@lib/column-resize.ts"
    }
  ],
  "type": "registry:lib"
}