{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "patch-bay",
  "title": "Patch bay",
  "author": "superzero11 <https://github.com/superzero11/uiset>",
  "description": "Jacks and cables built on UI SDK createConnect: patch by drag, keyboard or agent.",
  "dependencies": [
    "@ui-sdk/core@0.1.0-beta.5",
    "@ui-sdk/react@0.1.0-beta.5"
  ],
  "registryDependencies": [
    "https://uiset.dev/r/uiset.json"
  ],
  "files": [
    {
      "path": "registry/uiset/ui/patch-bay.tsx",
      "content": "\"use client\"\n\nimport type { ConnectDraft } from \"@ui-sdk/core\"\nimport { createParts, type PartProps } from \"@ui-sdk/react/primitive\"\nimport {\n  useLayoutEffect,\n  useRef,\n  useState,\n  type CSSProperties,\n  type ReactNode,\n} from \"react\"\nimport { cablePath as sag, localPoint, type Point } from \"./studio/cables\"\nimport { patchBay, type Cable, type PatchBayOptions } from \"./studio/patch-bay\"\nimport \"./studio/patch-bay.css\"\n\nconst parts = createParts(patchBay, { root: \"div\", jack: \"button\" })\n\n\nfunction Cables({ cables, draft }: { cables: Cable[]; draft: ConnectDraft | null }) {\n  const svg = useRef<SVGSVGElement>(null)\n  const [centers, setCenters] = useState<Record<string, Point>>({})\n\n  useLayoutEffect(() => {\n    const root = svg.current?.parentElement\n    if (!root) return\n    const measure = () => {\n      const next: Record<string, Point> = {}\n      for (const jack of root.querySelectorAll<HTMLElement>(\"[data-port]\")) {\n        const rect = jack.getBoundingClientRect()\n        next[jack.dataset.port!] = localPoint(root, rect.left + rect.width / 2, rect.top + rect.height / 2)\n      }\n      setCenters(next)\n    }\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(root)\n    for (const jack of root.querySelectorAll(\"[data-port]\")) observer.observe(jack)\n    void document.fonts?.ready.then(measure)\n    return () => observer.disconnect()\n  }, [])\n\n  const loose = draft && centers[draft.from]\n  const end = draft && (draft.to ? centers[draft.to] : { x: draft.x, y: draft.y })\n\n  return (\n    <svg ref={svg} className=\"patch-bay-cables\" aria-hidden=\"true\" focusable=\"false\">\n      {cables.map((cable, index) => {\n        const a = centers[cable.from]\n        const b = centers[cable.to]\n        if (!a || !b) return null\n        return (\n          <g\n            key={`${cable.from}>${cable.to}`}\n            className=\"patch-bay-cable\"\n            style={\n              {\n                \"--cable-color\": `var(--uiset-cable-${(index % 5) + 1})`,\n              } as CSSProperties\n            }\n          >\n            <path d={sag(a, b)} />\n            <circle cx={a.x} cy={a.y} r=\"5.5\" />\n            <circle cx={b.x} cy={b.y} r=\"5.5\" />\n          </g>\n        )\n      })}\n      {loose && end && (\n        <g\n          className=\"patch-bay-cable\"\n          data-draft=\"\"\n          style={\n            {\n              \"--cable-color\": `var(--uiset-cable-${(cables.length % 5) + 1})`,\n            } as CSSProperties\n          }\n        >\n          <path d={sag(loose, end)} />\n          <circle cx={loose.x} cy={loose.y} r=\"5.5\" />\n          <circle cx={end.x} cy={end.y} r=\"5.5\" />\n        </g>\n      )}\n    </svg>\n  )\n}\n\ntype PatchBayProps = PatchBayOptions &\n  Omit<PartProps<\"div\">, \"defaultValue\" | \"onChange\" | \"children\"> & {\n    children: ReactNode\n  }\n\nfunction PatchBay({ children, className, ...props }: PatchBayProps) {\n  return (\n    <parts.Root className={[\"patch-bay\", className].filter(Boolean).join(\" \")} {...props}>\n      {({ cables, connecting }) => (\n        <>\n          {children}\n          <Cables cables={cables} draft={connecting} />\n        </>\n      )}\n    </parts.Root>\n  )\n}\n\ntype PatchBayJackProps = Omit<PartProps<\"button\">, \"value\"> & {\n  port: string\n  label: string\n}\n\nfunction PatchBayJack({ port, label, ...props }: PatchBayJackProps) {\n  return <parts.Jack value={port} aria-label={label} {...props} />\n}\n\nexport { PatchBay, PatchBayJack }\nexport type { Cable, PatchBayJackProps, PatchBayProps }\n",
      "type": "registry:ui",
      "target": "@ui/patch-bay.tsx"
    },
    {
      "path": "registry/uiset/ui/studio/patch-bay.ts",
      "content": "import {\n  createChange,\n  createConnect,\n  definePrimitive,\n  live,\n  type ChangeDetails,\n  type ConnectDraft,\n} from \"@ui-sdk/core\"\nimport { localPoint } from \"./cables\"\n\ntype Cable = { from: string; to: string }\ntype PatchReason = \"drag\" | \"connect-key\" | \"imperative\"\n\ntype PatchBayOptions = {\n  value?: Cable[]\n  defaultValue?: Cable[]\n  labels?: Record<string, string>\n  onValueChange?: (cables: Cable[], details: ChangeDetails<PatchReason>) => void\n}\n\nconst isOut = (key: string) => key.endsWith(\":out\")\nconst isIn = (key: string) => key.endsWith(\":in\")\n\nfunction describe(cables: Cable[], key: string, labels: Record<string, string>) {\n  const name = (port: string) => labels[port] ?? port\n  const peers = cables\n    .filter((cable) => cable.from === key || cable.to === key)\n    .map((cable) => name(cable.from === key ? cable.to : cable.from))\n  return peers.length ? `Patched to ${peers.join(\", \")}` : \"Not patched\"\n}\n\n/** @internal Left out of @uiset/web's declarations: its type names UI SDK internals. */\nconst patchBay = definePrimitive({\n  name: \"patch-bay\",\n  options: {\n    value: \"value\",\n    defaultValue: \"value\",\n    labels: \"value\",\n    onValueChange: \"callback\",\n  },\n  controlled: [\"value\"],\n  live: [\"connecting\"],\n  state: (options: PatchBayOptions) => ({\n    value: options.value ?? options.defaultValue ?? ([] as Cable[]),\n    labels: options.labels ?? ({} as Record<string, string>),\n    connecting: null as ConnectDraft | null,\n  }),\n  sync: (options) => ({\n    ...(options.value === undefined ? {} : { value: options.value }),\n    labels: options.labels ?? {},\n  }),\n  api: (context) => {\n    const change = createChange(context)\n    let surface: HTMLElement | null = null\n\n    const label = (key: string) => context.store.get().labels[key] ?? key\n    const resolve = (name: string) => {\n      const { labels } = context.store.get()\n      if (name in labels) return name\n      const wanted = name.trim().toLowerCase()\n      return (\n        Object.keys(labels).find((key) => labels[key]!.toLowerCase() === wanted) ?? name\n      )\n    }\n    // An input takes one cable, so patching into a used input replaces its cable.\n    // Patching a pair that's already connected pulls that cable out.\n    const toggle = (\n      from: string,\n      to: string,\n      details: ChangeDetails<PatchReason>[\"reason\"],\n      event?: Event,\n    ) => {\n      const cables = context.store.get().value\n      const exists = cables.some((cable) => cable.from === from && cable.to === to)\n      const next = exists\n        ? cables.filter((cable) => !(cable.from === from && cable.to === to))\n        : [...cables.filter((cable) => cable.to !== to), { from, to }]\n      return change(\"value\", next, { reason: details, event })\n    }\n\n    const wiring = createConnect(context, {\n      slot: \"jack\",\n      draft: \"connecting\",\n      canConnect: (from, to) => isOut(from) && isIn(to),\n      point: (x, y) => (surface ? localPoint(surface, x, y) : { x, y }),\n      label,\n      connect: (from, to, details) => toggle(from, to, details.reason, details.event),\n    })\n\n    return {\n      wiring,\n      label,\n      surface: (el: HTMLElement | null) => {\n        surface = el\n      },\n      ports: () =>\n        Object.entries(context.store.get().labels).map(([value, text]) => ({\n          value,\n          label: text,\n        })),\n      plug(from: string, to: string) {\n        const source = resolve(from)\n        const target = resolve(to)\n        if (!isOut(source) || !isIn(target)) return false\n        const exists = context.store\n          .get()\n          .value.some((cable) => cable.from === source && cable.to === target)\n        return exists || toggle(source, target, \"imperative\")\n      },\n      unplug(from: string, to: string) {\n        const source = resolve(from)\n        const target = resolve(to)\n        const exists = context.store\n          .get()\n          .value.some((cable) => cable.from === source && cable.to === target)\n        return exists && toggle(source, target, \"imperative\")\n      },\n      clear: () => change(\"value\", [], { reason: \"imperative\" }),\n      /** The cables now, and a way to set them from code (web elements' live `value`). */\n      cables: () => context.store.get().value,\n      setCables: (next: Cable[]) => change(\"value\", next, { reason: \"imperative\" }),\n    }\n  },\n  slots: (slot) => ({\n    root: slot<{}, { cables: Cable[]; connecting: ConnectDraft | null }>({\n      role: \"group\",\n      state: (state) => ({ cables: state.value, connecting: state.connecting }),\n      bind: (el, part) => {\n        part.api.surface(el)\n        return () => part.api.surface(null)\n      },\n    }),\n    jack: slot<{ value: string }>({\n      props: { value: \"string\" },\n      role: \"button\",\n      focus: \"native\",\n      // A mouse click ends a drag; only keys and screen readers start a keyboard patch.\n      press: ({ api, key }, event) => {\n        if (event instanceof MouseEvent && event.detail > 0) return\n        api.wiring.start(key)\n      },\n      attrs: (state, { key }) => ({\n        type: \"button\",\n        \"data-port\": key,\n        \"data-kind\": isOut(key) ? \"out\" : \"in\",\n        \"data-patched\": state.value.some(\n          (cable) => cable.from === key || cable.to === key,\n        )\n          ? \"\"\n          : undefined,\n        \"aria-description\": describe(state.value, key, state.labels),\n      }),\n      live: live((state, { api, key }) => ({\n        \"data-connect\": api.wiring.role(state, key),\n      })),\n      on: {\n        pointerdown: (event, { el, api, key }) => {\n          if (el && isOut(key)) api.wiring.pointerdown(event as PointerEvent, key, el)\n        },\n        keydown: (event, { api }) => {\n          if (api.wiring.active()) api.wiring.keydown(event as KeyboardEvent)\n        },\n      },\n    }),\n  }),\n  agent: { actions: [\"plug\", \"unplug\", \"clear\"], items: (api) => api.ports() },\n})\n\nexport { patchBay }\nexport type { Cable, PatchBayOptions, PatchReason }\n",
      "type": "registry:file",
      "target": "@ui/studio/patch-bay.ts"
    },
    {
      "path": "registry/uiset/ui/studio/cables.ts",
      "content": "// A patch cable's path between two jacks: it sags under its own weight, more the longer it\n// is, like a real one. Shared by the React patch bay and the web element.\n\ntype Point = { x: number; y: number }\n\nfunction cablePath(a: Point, b: Point) {\n  const drop = Math.min(150, 28 + Math.hypot(b.x - a.x, b.y - a.y) * 0.35)\n  return `M ${a.x} ${a.y} C ${a.x} ${a.y + drop}, ${b.x} ${b.y + drop}, ${b.x} ${b.y}`\n}\n\n/**\n * A point on the screen, in an element's own pixels. Screen distances stop being layout\n * distances when an ancestor scales the element (a zoomed canvas, a CSS transform), and a\n * cable drawn from them would miss its jacks: this divides the scale back out.\n */\nfunction localPoint(surface: HTMLElement, x: number, y: number): Point {\n  const box = surface.getBoundingClientRect()\n  const scaleX = (surface.offsetWidth && box.width / surface.offsetWidth) || 1\n  const scaleY = (surface.offsetHeight && box.height / surface.offsetHeight) || 1\n  return { x: (x - box.left) / scaleX, y: (y - box.top) / scaleY }\n}\n\nexport { cablePath, localPoint }\nexport type { Point }\n",
      "type": "registry:file",
      "target": "@ui/studio/cables.ts"
    },
    {
      "path": "registry/uiset/ui/studio/patch-bay.css",
      "content": "@layer ui-sdk, uiset.tokens, uiset.base, uiset.skin;\n\n@layer uiset.base {\n  .patch-bay {\n    position: relative;\n  }\n\n  .patch-bay-cables {\n    position: absolute;\n    inset: 0;\n    z-index: 2;\n    width: 100%;\n    height: 100%;\n    overflow: visible;\n    pointer-events: none;\n  }\n\n  .patch-bay-cable {\n    path {\n      fill: none;\n      stroke: var(--cable-color);\n      stroke-width: 5;\n      stroke-linecap: round;\n      filter: drop-shadow(0 3px 2px oklch(0 0 0 / 0.35));\n    }\n\n    circle {\n      fill: var(--cable-color);\n      stroke: oklch(0 0 0 / 0.35);\n      stroke-width: 1.5;\n    }\n\n    &[data-draft] path {\n      stroke-dasharray: 2 7;\n    }\n  }\n\n  [data-slot=\"patch-bay-jack\"] {\n    --jack-size: 1.625rem;\n    position: relative;\n    display: inline-grid;\n    place-items: center;\n    width: var(--jack-size);\n    height: var(--jack-size);\n    padding: 0;\n    border: 2px solid var(--ui-input);\n    border-radius: 50%;\n    background: var(--ui-muted);\n    cursor: grab;\n    touch-action: none;\n\n    /* ::before, since on touch screens UI SDK turns a button's ::after into its hit area. */\n    &::before {\n      content: \"\";\n      width: 42%;\n      aspect-ratio: 1;\n      border-radius: 50%;\n      background: var(--ui-foreground);\n      opacity: 0.85;\n    }\n\n    &[data-kind=\"in\"] {\n      cursor: default;\n    }\n\n    &[data-connect=\"source\"],\n    &[data-connect=\"target\"] {\n      outline: 3px solid var(--ui-ring-border);\n      outline-offset: 2px;\n    }\n\n    &[data-connect=\"candidate\"] {\n      border-color: var(--ui-primary);\n    }\n  }\n\n  @media (forced-colors: active) {\n    .patch-bay-cable path,\n    .patch-bay-cable circle {\n      stroke: CanvasText;\n      fill: none;\n    }\n\n    [data-slot=\"patch-bay-jack\"][data-connect] {\n      outline-color: Highlight;\n    }\n  }\n}\n",
      "type": "registry:file",
      "target": "@ui/studio/patch-bay.css"
    }
  ],
  "type": "registry:ui"
}