{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "carousel-composer-editing",
  "title": "Carousel Composer — Editing",
  "author": "ilinxa",
  "description": "Image editing for Carousel Composer through media-editor — the edit panel and typed readers for the edit fields. Wire in via the editing prop.",
  "dependencies": [
    "lucide-react@^1.11.0"
  ],
  "registryDependencies": [
    "@ilinxa/carousel-composer",
    "@ilinxa/media-editor",
    "button"
  ],
  "files": [
    {
      "path": "src/registry/components/media/carousel-composer/features/editing/index.ts",
      "content": "// carousel-composer editing feature — image editing through a shared\n// media-editor, shipped as its own opt-in registry item\n// (`@ilinxa/carousel-composer-editing`). It is the ONLY part of carousel-composer\n// that depends on media-editor (and so on Konva).\n//\n// Injected into the base via `editing={carouselEditing}` (CarouselComposerProps —\n// see `../../hooks/use-editing-extension.ts`). Ships with\n// `registryDependencies: [\"@ilinxa/carousel-composer\", \"@ilinxa/media-editor\"]`.\n//\n// Also exports typed readers for the two item fields the base keeps opaque\n// (`editorStateOf`, `exportMetaOf`) and the media-editor types a host needs.\n\nimport type { CarouselEditingExtension } from \"../../types\";\n// Types are re-exported through `import type` + `export type`: the shadcn path\n// rewriter rewrites `import` declarations only, never `export … from`.\nimport type {\n  ExportMetadata,\n  InitialSource,\n  MediaEditorHandle,\n  MediaEditorProps,\n  MediaEditorState,\n} from \"@/registry/components/media/media-editor/media-editor\";\nimport { CarouselEditPanel } from \"./parts/edit-panel\";\n\n/** Pass straight through: `<CarouselComposer editing={carouselEditing} />`. */\nexport const carouselEditing: CarouselEditingExtension = {\n  Panel: CarouselEditPanel,\n};\n\nexport { CarouselEditPanel } from \"./parts/edit-panel\";\nexport { editorStateOf, exportMetaOf } from \"./lib/accessors\";\n\n/** The media-editor props `CarouselComposer`'s `editorProps` forwards to the panel. */\nexport type CarouselEditorProps = Pick<\n  MediaEditorProps,\n  | \"enabledTools\"\n  | \"stickers\"\n  | \"fonts\"\n  | \"colorPresets\"\n  | \"filterPresets\"\n  | \"labels\"\n>;\n\nexport type {\n  MediaEditorState,\n  ExportMetadata,\n  InitialSource,\n  MediaEditorHandle,\n};\n\n// @ilinxa/carousel-composer-editing 0.5.0\n",
      "type": "registry:component",
      "target": "components/carousel-composer/features/editing/index.ts"
    },
    {
      "path": "src/registry/components/media/carousel-composer/features/editing/lib/accessors.ts",
      "content": "import type {\n  ExportMetadata,\n  MediaEditorState,\n} from \"@/registry/components/media/media-editor/media-editor\";\nimport type { MediaCarouselItem } from \"../../../types\";\n\n/** The item's editable layers, typed as media-editor's `MediaEditorState`. */\nexport function editorStateOf(\n  item: Pick<MediaCarouselItem, \"editorState\">,\n): MediaEditorState | undefined {\n  return item.editorState as MediaEditorState | undefined;\n}\n\n/** The item's last export metadata, typed as media-editor's `ExportMetadata`. */\nexport function exportMetaOf(\n  item: Pick<MediaCarouselItem, \"exportMeta\">,\n): ExportMetadata | undefined {\n  return item.exportMeta as ExportMetadata | undefined;\n}\n",
      "type": "registry:component",
      "target": "components/carousel-composer/features/editing/lib/accessors.ts"
    },
    {
      "path": "src/registry/components/media/carousel-composer/features/editing/parts/edit-panel.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { Loader2 } from \"lucide-react\";\nimport { Button } from \"@/components/ui/button\";\nimport { MediaEditor } from \"@/registry/components/media/media-editor/media-editor\";\nimport type {\n  InitialSource,\n  MediaEditorHandle,\n  MediaEditorProps,\n  MediaEditorState,\n} from \"@/registry/components/media/media-editor/media-editor\";\nimport type {\n  CarouselEditorPanelProps,\n  MediaCarouselItem,\n} from \"../../../types\";\nimport { centredCropRect, offsetCropRect } from \"../../../lib/aspect\";\n\n/** The only `editorProps` keys forwarded to media-editor; the rest stay the panel's. */\nconst FORWARDED_EDITOR_PROPS = [\n  \"enabledTools\",\n  \"stickers\",\n  \"fonts\",\n  \"colorPresets\",\n  \"filterPresets\",\n  \"labels\",\n] as const;\n\nfunction pickEditorProps(\n  editorProps: Readonly<Record<string, unknown>> | undefined,\n): Partial<MediaEditorProps> {\n  const picked: Record<string, unknown> = {};\n  if (!editorProps) return picked;\n  for (const key of FORWARDED_EDITOR_PROPS) {\n    if (editorProps[key] !== undefined) picked[key] = editorProps[key];\n  }\n  return picked as Partial<MediaEditorProps>;\n}\n\nfunction initialSourceFor(item: MediaCarouselItem): InitialSource {\n  const mode = item.kind === \"video\" ? \"video\" : \"photo\";\n  return item.blob\n    ? { kind: \"blob\", blob: item.blob, mode }\n    : { kind: \"url\", url: item.url, mode };\n}\n\n/** Cuts `rect` out of an encoded image; `null` when this environment cannot draw it. */\nasync function cropBlob(\n  blob: Blob,\n  rect: { x: number; y: number; width: number; height: number },\n  mimeType: string | undefined,\n): Promise<Blob | null> {\n  try {\n    const bitmap = await createImageBitmap(blob);\n    const canvas = document.createElement(\"canvas\");\n    canvas.width = rect.width;\n    canvas.height = rect.height;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return null;\n    ctx.drawImage(bitmap, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height);\n    bitmap.close?.();\n    return await new Promise<Blob | null>((resolve) =>\n      canvas.toBlob(resolve, mimeType || blob.type || \"image/jpeg\", 0.92),\n    );\n  } catch {\n    return null;\n  }\n}\n\n/**\n * The single, shared edit panel. Mounts ONE `media-editor` in edit-only mode\n * (`enabledModes={[]}` → no capture chrome / no photo-video tabs) for the\n * selected item, keyed by `item.id` so switching items remounts with a fresh\n * source.\n *\n * Re-edit contract (mirrors content-composer's media-substrate): when the item\n * already has `editorState`, we DON'T pass `initialSource` — `loadState` supplies\n * both the original image (`editorState.imageSrc`) AND the editable overlays.\n * Passing `initialSource` *as well* would composite the flattened export under\n * the re-applied overlays (double overlays). `initialSource` is only for the\n * first edit, before any `editorState` exists.\n */\nexport function CarouselEditPanel({\n  item,\n  aspect,\n  aspectRatio,\n  editorProps,\n  labels,\n  onApply,\n  onCancel,\n  onBusyChange,\n}: CarouselEditorPanelProps) {\n  const editorRef = useRef<MediaEditorHandle | null>(null);\n  const [busy, setBusy] = useState(false);\n  const [failed, setFailed] = useState(false);\n  // True until media-editor shows the source (initialSource load / loadState). Escape is\n  // swallowed by the carousel while this or the Done export is in flight.\n  const [loading, setLoading] = useState(true);\n  // ONE mount effect, in this order: a re-edit starts `loadState` first, THEN waits for the\n  // editor to settle — otherwise \"settled\" could resolve before the load began and Escape\n  // would stop being guarded while it loads. A first edit loads `initialSource` on mount.\n  // `item` is fixed for this instance (the parent keys it by `item.id`).\n  useEffect(() => {\n    const editor = editorRef.current;\n    if (item.editorState && editor) {\n      // The snapshot's imageSrc is a DEAD object URL (revoked when the previous edit's\n      // editor unmounted) — pass the persisted source blob so loadState re-mints a live\n      // one instead of opening on a black canvas (review 1.3).\n      editor.loadState(item.editorState as MediaEditorState, {\n        sourceBlob: item.sourceBlob ?? null,\n      });\n    }\n    if (!editor || typeof editor.whenSettled !== \"function\") {\n      setLoading(false);\n      return;\n    }\n    let alive = true;\n    editor\n      .whenSettled()\n      .catch(() => {})\n      .finally(() => {\n        if (alive) setLoading(false);\n      });\n    return () => {\n      alive = false;\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n  const reportedBusy = loading || busy;\n  useEffect(() => {\n    onBusyChange?.(reportedBusy);\n  }, [reportedBusy, onBusyChange]);\n\n  const seedSource = item.editorState ? undefined : initialSourceFor(item);\n\n  const isEditable = item.kind === \"image\";\n  useEffect(() => {\n    if (isEditable) return;\n    if (process.env.NODE_ENV !== \"production\") {\n      console.warn(\n        `[CarouselComposer] CarouselEditPanel refused item \"${item.id}\": it is a ${item.kind}; only image items can be edited.`,\n      );\n    }\n    onCancel();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  const handleDone = async () => {\n    const editor = editorRef.current;\n    if (!editor || !isEditable) return;\n    // Nothing changed since the source loaded: keep the item as it is instead\n    // of re-encoding it (a re-encode would bake the letterbox into the photo).\n    // `isModified` is media-editor 0.6.0+; an older vendored editor has none,\n    // so treat it as modified (the 0.3.0 behaviour: always re-export).\n    const modified =\n      typeof editor.isModified === \"function\" ? editor.isModified() : true;\n    if (!modified) {\n      onCancel();\n      return;\n    }\n    // Synchronously, before the (main-thread-heavy) export: the host's Escape guard must\n    // already be armed for a key pressed in this same task, not after the effect below.\n    onBusyChange?.(true);\n    setBusy(true);\n    setFailed(false);\n    try {\n      // Export only the photo's displayed area (no letterbox bars), at the photo's own\n      // resolution; metadata width / height are the blob's pixels. A shared aspect: an\n      // edited item must come back at it even when the crop tool was never used, so trim\n      // (centred) to the largest rect of that ratio inside the photo's own pixels, never\n      // upscaling. The photo's pixels are measured by a plain export first: an applied\n      // crop replaces the editor's photo with a smaller one, so the item's own\n      // width / height are not the pixels being exported.\n      const exportAt = (rect: { width: number; height: number }) =>\n        editor.exportImage({ region: \"media\", width: rect.width, height: rect.height });\n      let result;\n      if (aspectRatio == null) {\n        result = await editor.exportImage({ region: \"media\" });\n      } else {\n        result = await editor.exportImage({ region: \"media\" });\n        // The author's pan framing survives the trim (applyEdit then drops the offset).\n        const rect = offsetCropRect(\n          result.metadata.width,\n          result.metadata.height,\n          aspectRatio,\n          item.cropOffset,\n        );\n        if (rect.width !== result.metadata.width || rect.height !== result.metadata.height) {\n          const centred = centredCropRect(result.metadata.width, result.metadata.height, aspectRatio);\n          // The editor's export only trims centred; an off-centre window is cut from the\n          // full export. Without a canvas the centred trim is the fallback.\n          const cut =\n            rect.x !== centred.x || rect.y !== centred.y\n              ? await cropBlob(result.blob, rect, result.metadata.mimeType)\n              : null;\n          result = cut\n            ? { blob: cut, metadata: { ...result.metadata, width: rect.width, height: rect.height } }\n            : await exportAt(rect);\n        }\n      }\n      const { blob, metadata } = result;\n      const url = URL.createObjectURL(blob);\n      onApply(item.id, {\n        url,\n        blob,\n        editorState: { ...editor.getState(), videoBlob: null },\n        // The blob backing editorState.imageSrc — persisted so the NEXT\n        // re-edit can re-materialize after this editor's URLs are revoked.\n        sourceBlob: editor.getSourceBlob() ?? item.sourceBlob,\n        exportMeta: metadata,\n        width: metadata.width,\n        height: metadata.height,\n      });\n    } catch {\n      // Keep the panel open so the user can retry; nothing is committed.\n      setFailed(true);\n    } finally {\n      setBusy(false);\n    }\n  };\n\n  if (!isEditable) return null;\n\n  return (\n    <div className=\"flex flex-col gap-3\">\n      {/* No aspect-ratio or clip here: media-editor locks its own canvas to `aspect`. */}\n      <div className=\"rounded-lg border border-border\">\n        <MediaEditor\n          ref={editorRef}\n          enabledModes={[]}\n          presentation=\"inline\"\n          initialSource={seedSource}\n          aspect={aspect}\n          cropAspects={[aspect]}\n          {...pickEditorProps(editorProps)}\n        />\n      </div>\n      {failed ? (\n        <p role=\"alert\" className=\"text-sm text-destructive\">\n          {labels.editError}\n        </p>\n      ) : null}\n      <div className=\"flex items-center justify-end gap-2\">\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          onClick={onCancel}\n          disabled={busy}\n        >\n          {labels.editCancel}\n        </Button>\n        <Button\n          type=\"button\"\n          onClick={handleDone}\n          disabled={busy}\n          aria-busy={busy || undefined}\n        >\n          {busy ? (\n            <>\n              <Loader2 className=\"size-4 animate-spin\" aria-hidden />\n              {labels.editSaving}\n            </>\n          ) : (\n            labels.editDone\n          )}\n        </Button>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/carousel-composer/features/editing/parts/edit-panel.tsx"
    }
  ],
  "meta": {
    "featureOf": "carousel-composer",
    "budgetKB": 16,
    "version": "0.5.0",
    "status": "alpha"
  },
  "categories": [
    "media"
  ],
  "type": "registry:block"
}