{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "open-save-dialog",
  "title": "Open / Save Dialog",
  "description": "Mac OS 9 Navigation Services Open and Save dialog with a location pop-up, Shortcuts / Favorites / Recent buttons, a browsable file list, a Name field and New Folder button.",
  "registryDependencies": [
    "https://nostalgia-ui.com/r/nostalgia-theme.json",
    "https://nostalgia-ui.com/r/retro-bevel-button.json",
    "https://nostalgia-ui.com/r/retro-button.json",
    "https://nostalgia-ui.com/r/retro-dropdown-menu.json",
    "https://nostalgia-ui.com/r/retro-icons.json",
    "https://nostalgia-ui.com/r/retro-input.json",
    "https://nostalgia-ui.com/r/retro-label.json",
    "https://nostalgia-ui.com/r/retro-select.json",
    "https://nostalgia-ui.com/r/retro-tree-view.json",
    "https://nostalgia-ui.com/r/retro-window.json"
  ],
  "files": [
    {
      "path": "registry/new-york/blocks/open-save-dialog.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { RetroBevelButton } from \"@/registry/new-york/ui/retro-bevel-button\"\nimport { RetroButton } from \"@/registry/new-york/ui/retro-button\"\nimport {\n  RetroDropdownMenu,\n  RetroDropdownMenuContent,\n  RetroDropdownMenuItem,\n  RetroDropdownMenuLabel,\n  RetroDropdownMenuSeparator,\n  RetroDropdownMenuTrigger,\n} from \"@/registry/new-york/ui/retro-dropdown-menu\"\nimport {\n  RetroIconApplication,\n  RetroIconDocument,\n  RetroIconFolder,\n  RetroIconHardDrive,\n} from \"@/registry/new-york/ui/retro-icons\"\nimport { RetroInput } from \"@/registry/new-york/ui/retro-input\"\nimport { RetroLabel } from \"@/registry/new-york/ui/retro-label\"\nimport {\n  RetroSelect,\n  RetroSelectContent,\n  RetroSelectItem,\n  RetroSelectTrigger,\n  RetroSelectValue,\n} from \"@/registry/new-york/ui/retro-select\"\nimport {\n  RetroTreeView,\n  type RetroTreeViewColumn,\n  type TreeNode,\n} from \"@/registry/new-york/ui/retro-tree-view\"\nimport { RetroWindow } from \"@/registry/new-york/ui/retro-window\"\n\n/* ------------------------------------------------------------------ */\n/*  Types                                                              */\n/* ------------------------------------------------------------------ */\n\ninterface OpenSaveFile {\n  id: string\n  name: string\n  /** Defaults to \"folder\" when `children` is set, otherwise \"document\". */\n  type?: \"folder\" | \"document\" | \"application\"\n  /** Date Modified. Use an ISO string without a zone (e.g. \"2001-10-23T14:32\"). */\n  modified?: Date | string\n  /** Folder contents. */\n  children?: OpenSaveFile[]\n}\n\ntype OpenSaveDialogMode = \"open\" | \"save\"\n\ntype OpenSaveResult =\n  | {\n      mode: \"open\"\n      /** The chosen file. */\n      file: OpenSaveFile\n      /** Folder names from the volume down to the file's folder. */\n      path: string[]\n    }\n  | {\n      mode: \"save\"\n      /** The typed file name. */\n      name: string\n      /** Folder names from the volume down to the destination folder. */\n      path: string[]\n    }\n\ninterface OpenSaveDialogBlockProps\n  extends Omit<\n    React.ComponentPropsWithoutRef<typeof RetroWindow>,\n    \"title\" | \"children\" | \"onKeyDown\"\n  > {\n  /** \"open\" (default) or \"save\". */\n  mode?: OpenSaveDialogMode\n  /** Contents of the volume (root folder). */\n  files: OpenSaveFile[]\n  /** Volume name shown at the root of the location pop-up. Defaults to \"Macintosh HD\". */\n  volumeName?: string\n  /** Initial folder, as a list of folder ids from the root. */\n  defaultPath?: string[]\n  /** Save mode: initial file name. Defaults to \"untitled\". */\n  defaultName?: string\n  /** Window title. Defaults to \"Open\" / \"Save\". */\n  title?: string\n  /** Open / Save button, Enter, or double-clicking a document. */\n  onConfirm?: (result: OpenSaveResult) => void\n  /** Cancel button, Escape or Command-period. */\n  onCancel?: () => void\n}\n\n/* ------------------------------------------------------------------ */\n/*  Helpers                                                            */\n/* ------------------------------------------------------------------ */\n\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n\n/** \"Oct 23, 1999, 2:32 PM\" — medium date used in the file list. */\nfunction formatShortDate(value: Date | string | undefined) {\n  if (!value) return null\n  const d = typeof value === \"string\" ? new Date(value) : value\n  if (Number.isNaN(d.getTime())) return null\n  const h = d.getHours()\n  return `${MONTHS[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}, ${h % 12 || 12}:${String(d.getMinutes()).padStart(2, \"0\")} ${h >= 12 ? \"PM\" : \"AM\"}`\n}\n\nfunction fileType(file: OpenSaveFile) {\n  return file.type ?? (file.children ? \"folder\" : \"document\")\n}\n\nfunction smallIcon(file: OpenSaveFile) {\n  const t = fileType(file)\n  if (t === \"folder\") return <RetroIconFolder size=\"sm\" />\n  if (t === \"application\") return <RetroIconApplication size=\"sm\" />\n  return <RetroIconDocument size=\"sm\" />\n}\n\nfunction toNode(file: OpenSaveFile): TreeNode {\n  const d = file.modified ? new Date(file.modified) : null\n  return {\n    id: file.id,\n    label: file.name,\n    icon: smallIcon(file),\n    children: file.children?.map(toNode),\n    modified: d && !Number.isNaN(d.getTime()) ? d.getTime() : undefined,\n    modifiedText: formatShortDate(file.modified),\n  }\n}\n\n/** Resolve a path of folder ids to the folder chain. Stops at the first miss. */\nfunction resolvePath(root: OpenSaveFile[], ids: string[]) {\n  const chain: OpenSaveFile[] = []\n  let level = root\n  for (const id of ids) {\n    const next = level.find((f) => f.id === id && f.children)\n    if (!next) break\n    chain.push(next)\n    level = next.children!\n  }\n  return chain\n}\n\nfunction findInTree(files: OpenSaveFile[], id: string): OpenSaveFile | undefined {\n  for (const f of files) {\n    if (f.id === id) return f\n    if (f.children) {\n      const hit = findInTree(f.children, id)\n      if (hit) return hit\n    }\n  }\n  return undefined\n}\n\n/** Path (folder ids) from the given level down to the node's parent folder. */\nfunction parentChain(files: OpenSaveFile[], id: string, trail: string[] = []): string[] | null {\n  for (const f of files) {\n    if (f.id === id) return trail\n    if (f.children) {\n      const hit = parentChain(f.children, id, [...trail, f.id])\n      if (hit) return hit\n    }\n  }\n  return null\n}\n\nfunction insertFolder(files: OpenSaveFile[], path: string[], folder: OpenSaveFile): OpenSaveFile[] {\n  if (path.length === 0) return [...files, folder]\n  return files.map((f) =>\n    f.id === path[0] && f.children\n      ? { ...f, children: insertFolder(f.children, path.slice(1), folder) }\n      : f\n  )\n}\n\n/* ------------------------------------------------------------------ */\n/*  Glyphs for the Shortcuts / Favorites / Recent bevel buttons        */\n/* ------------------------------------------------------------------ */\n\nfunction FavoritesGlyph() {\n  return (\n    <svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" aria-hidden=\"true\">\n      <path d=\"M2.5 3.5H6.5L7.5 4.5H11.5V11.5H2.5Z\" fill=\"var(--os9-gray-300)\" stroke=\"currentColor\" />\n      <path d=\"M7 6L7.7 7.6L9.4 7.7L8.1 8.8L8.5 10.4L7 9.5L5.5 10.4L5.9 8.8L4.6 7.7L6.3 7.6Z\" fill=\"currentColor\" />\n    </svg>\n  )\n}\n\nfunction RecentGlyph() {\n  return (\n    <svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" aria-hidden=\"true\">\n      <rect x=\"1.5\" y=\"1.5\" width=\"11\" height=\"11\" fill=\"var(--os9-white)\" stroke=\"currentColor\" />\n      <path d=\"M7 3.5V7H10\" fill=\"none\" stroke=\"currentColor\" />\n    </svg>\n  )\n}\n\nconst MENU_BUTTON_CLS = \"h-[22px] min-h-0 w-[34px] min-w-0 px-[4px] py-0\"\n\n/* ------------------------------------------------------------------ */\n/*  OpenSaveDialogBlock                                                */\n/* ------------------------------------------------------------------ */\n\nconst OpenSaveDialogBlock = React.forwardRef<HTMLDivElement, OpenSaveDialogBlockProps>(\n  function OpenSaveDialogBlock(\n    {\n      mode = \"open\",\n      files: filesProp,\n      volumeName = \"Macintosh HD\",\n      defaultPath = [],\n      defaultName = \"untitled\",\n      title,\n      onConfirm,\n      onCancel,\n      className,\n      contentClassName,\n      ...props\n    },\n    ref\n  ) {\n    const id = React.useId()\n    const isSave = mode === \"save\"\n    const nameRef = React.useRef<HTMLInputElement>(null)\n\n    // Local copy so New Folder can add to it.\n    const [files, setFiles] = React.useState(filesProp)\n    const [prevFilesProp, setPrevFilesProp] = React.useState(filesProp)\n    if (prevFilesProp !== filesProp) {\n      setPrevFilesProp(filesProp)\n      setFiles(filesProp)\n    }\n\n    const [pathIds, setPathIds] = React.useState<string[]>(defaultPath)\n    const chain = React.useMemo(() => resolvePath(files, pathIds), [files, pathIds])\n    const current = React.useMemo(\n      () => (chain.length ? chain[chain.length - 1].children! : files),\n      [chain, files]\n    )\n    const folderIds = chain.map((f) => f.id)\n    const pathNames = [volumeName, ...chain.map((f) => f.name)]\n\n    const [selected, setSelected] = React.useState<string[]>([])\n    const [expanded, setExpanded] = React.useState<string[]>([])\n    const [name, setName] = React.useState(defaultName)\n    const [show, setShow] = React.useState(\"known\")\n    const [favorites, setFavorites] = React.useState<string[][]>([])\n    const [recent, setRecent] = React.useState<{ file: OpenSaveFile; path: string[] }[]>([])\n\n    const nodes = React.useMemo(() => current.map(toNode), [current])\n    const selectedFile = selected[0] ? findInTree(current, selected[0]) : undefined\n\n    const columns = React.useMemo<RetroTreeViewColumn[]>(\n      () => [\n        { key: \"label\", header: \"Name\", width: \"minmax(120px,1fr)\" },\n        {\n          key: \"modified\",\n          header: \"Date Modified\",\n          width: \"minmax(0,170px)\",\n          render: (n) => (n.modifiedText as string | null) ?? \"—\",\n        },\n      ],\n      []\n    )\n\n    const navigate = (ids: string[]) => {\n      setPathIds(ids)\n      setSelected([])\n      setExpanded([])\n    }\n\n    /** Folder ids (from the root) of a node inside the current list. */\n    const idsTo = (fileId: string) => [...folderIds, ...(parentChain(current, fileId) ?? [])]\n    const namesFor = (ids: string[]) => [volumeName, ...resolvePath(files, ids).map((f) => f.name)]\n\n    const openFile = (file: OpenSaveFile) => {\n      if (fileType(file) === \"folder\") {\n        navigate([...idsTo(file.id), file.id])\n        return\n      }\n      if (isSave) {\n        setName(file.name)\n        nameRef.current?.focus()\n        return\n      }\n      const path = namesFor(idsTo(file.id))\n      setRecent((r) => [{ file, path: idsTo(file.id) }, ...r.filter((x) => x.file.id !== file.id)].slice(0, 5))\n      onConfirm?.({ mode: \"open\", file, path })\n    }\n\n    const confirm = () => {\n      if (isSave) {\n        const trimmed = name.trim()\n        if (!trimmed) return\n        // A selected folder is the save destination, as in Nav Services.\n        if (selectedFile && fileType(selectedFile) === \"folder\") {\n          onConfirm?.({ mode: \"save\", name: trimmed, path: namesFor([...idsTo(selectedFile.id), selectedFile.id]) })\n        } else {\n          onConfirm?.({ mode: \"save\", name: trimmed, path: pathNames })\n        }\n        return\n      }\n      if (selectedFile) openFile(selectedFile)\n    }\n\n    const newFolder = () => {\n      const taken = new Set(current.map((f) => f.name))\n      let n = 1\n      let folderName = \"untitled folder\"\n      while (taken.has(folderName)) folderName = `untitled folder ${++n}`\n      const folder: OpenSaveFile = {\n        id: `${id}-folder-${folderIds.join(\"/\")}-${folderName}`,\n        name: folderName,\n        children: [],\n      }\n      setFiles((f) => insertFolder(f, folderIds, folder))\n      setSelected([folder.id])\n    }\n\n    const canConfirm = isSave ? name.trim().length > 0 : !!selectedFile\n    const confirmLabel =\n      !isSave && selectedFile && fileType(selectedFile) === \"folder\" ? \"Open\" : isSave ? \"Save\" : \"Open\"\n\n    return (\n      <RetroWindow\n        ref={ref}\n        title={title ?? (isSave ? \"Save\" : \"Open\")}\n        role=\"dialog\"\n        aria-label={title ?? (isSave ? \"Save\" : \"Open\")}\n        className={cn(\"w-full max-w-[480px]\", className)}\n        contentClassName={cn(\"flex flex-col gap-[10px] p-[12px] max-[420px]:p-[8px]\", contentClassName)}\n        onKeyDown={(e) => {\n          if (e.defaultPrevented) return\n          if (e.key === \"Escape\" || (e.key === \".\" && (e.metaKey || e.ctrlKey))) {\n            e.preventDefault()\n            onCancel?.()\n          } else if (e.key === \"Enter\") {\n            const t = e.target as HTMLElement\n            // Let buttons and pop-ups handle their own Enter.\n            if (t.closest(\"button, [role=combobox], [role=menu]\")) return\n            e.preventDefault()\n            confirm()\n          }\n        }}\n        {...props}\n      >\n        {/* Save As name field */}\n        {isSave && (\n          <div className=\"flex items-center gap-2\">\n            <RetroLabel size=\"lg\" htmlFor={`${id}-name`} className=\"shrink-0\">\n              Name:\n            </RetroLabel>\n            <RetroInput\n              ref={nameRef}\n              id={`${id}-name`}\n              value={name}\n              onChange={(e) => setName(e.target.value)}\n              onFocus={(e) => e.currentTarget.select()}\n              className=\"min-w-0 flex-1\"\n              autoComplete=\"off\"\n            />\n          </div>\n        )}\n\n        {/* Location row */}\n        <div className=\"flex items-center gap-2\">\n          <RetroSelect\n            value={String(chain.length)}\n            onValueChange={(v) => navigate(folderIds.slice(0, Number(v)))}\n          >\n            <RetroSelectTrigger aria-label=\"Location\" className=\"h-[22px] min-w-0 flex-1\">\n              <span className=\"flex min-w-0 items-center gap-[6px]\">\n                {chain.length ? <RetroIconFolder size=\"sm\" /> : <RetroIconHardDrive size=\"sm\" />}\n                <span className=\"truncate\">\n                  <RetroSelectValue />\n                </span>\n              </span>\n            </RetroSelectTrigger>\n            <RetroSelectContent>\n              {pathNames\n                .map((n, i) => ({ n, i }))\n                .reverse()\n                .map(({ n, i }) => (\n                  <RetroSelectItem key={i} value={String(i)}>\n                    {n}\n                  </RetroSelectItem>\n                ))}\n            </RetroSelectContent>\n          </RetroSelect>\n\n          <div className=\"flex shrink-0\">\n            <RetroDropdownMenu modal={false}>\n              <RetroDropdownMenuTrigger\n                render={\n                  <RetroBevelButton\n                    bevel=\"small\"\n                    menu\n                    aria-label=\"Shortcuts\"\n                    title=\"Shortcuts\"\n                    icon={<RetroIconHardDrive size=\"sm\" />}\n                    className={MENU_BUTTON_CLS}\n                  />\n                }\n              />\n              <RetroDropdownMenuContent align=\"end\">\n                <RetroDropdownMenuLabel>Shortcuts</RetroDropdownMenuLabel>\n                <RetroDropdownMenuItem onSelect={() => navigate([])}>\n                  {volumeName}\n                </RetroDropdownMenuItem>\n                <RetroDropdownMenuItem\n                  disabled={chain.length === 0}\n                  onSelect={() => navigate(folderIds.slice(0, -1))}\n                >\n                  Enclosing Folder\n                </RetroDropdownMenuItem>\n              </RetroDropdownMenuContent>\n            </RetroDropdownMenu>\n\n            <RetroDropdownMenu modal={false}>\n              <RetroDropdownMenuTrigger\n                render={\n                  <RetroBevelButton\n                    bevel=\"small\"\n                    menu\n                    aria-label=\"Favorites\"\n                    title=\"Favorites\"\n                    icon={<FavoritesGlyph />}\n                    className={cn(MENU_BUTTON_CLS, \"-ml-px\")}\n                  />\n                }\n              />\n              <RetroDropdownMenuContent align=\"end\">\n                <RetroDropdownMenuItem\n                  onSelect={() =>\n                    setFavorites((f) =>\n                      f.some((p) => p.join(\"/\") === folderIds.join(\"/\")) ? f : [...f, folderIds]\n                    )\n                  }\n                >\n                  Add to Favorites\n                </RetroDropdownMenuItem>\n                <RetroDropdownMenuSeparator />\n                {favorites.length === 0 ? (\n                  <RetroDropdownMenuItem disabled>No Favorites</RetroDropdownMenuItem>\n                ) : (\n                  favorites.map((p) => (\n                    <RetroDropdownMenuItem key={p.join(\"/\") || \"root\"} onSelect={() => navigate(p)}>\n                      {namesFor(p).at(-1)}\n                    </RetroDropdownMenuItem>\n                  ))\n                )}\n              </RetroDropdownMenuContent>\n            </RetroDropdownMenu>\n\n            <RetroDropdownMenu modal={false}>\n              <RetroDropdownMenuTrigger\n                render={\n                  <RetroBevelButton\n                    bevel=\"small\"\n                    menu\n                    aria-label=\"Recent\"\n                    title=\"Recent\"\n                    icon={<RecentGlyph />}\n                    className={cn(MENU_BUTTON_CLS, \"-ml-px\")}\n                  />\n                }\n              />\n              <RetroDropdownMenuContent align=\"end\">\n                {recent.length === 0 ? (\n                  <RetroDropdownMenuItem disabled>No Recent Items</RetroDropdownMenuItem>\n                ) : (\n                  recent.map(({ file, path }) => (\n                    <RetroDropdownMenuItem\n                      key={file.id}\n                      onSelect={() => {\n                        navigate(path)\n                        setSelected([file.id])\n                      }}\n                    >\n                      {file.name}\n                    </RetroDropdownMenuItem>\n                  ))\n                )}\n              </RetroDropdownMenuContent>\n            </RetroDropdownMenu>\n          </div>\n        </div>\n\n        {/* File list */}\n        <RetroTreeView\n          aria-label={pathNames[pathNames.length - 1]}\n          items={nodes}\n          columns={columns}\n          defaultSort={{ column: \"label\", direction: \"asc\" }}\n          selected={selected}\n          onSelectedChange={(ids) => {\n            setSelected(ids)\n            const file = ids[0] ? findInTree(current, ids[0]) : undefined\n            if (isSave && file && fileType(file) !== \"folder\") setName(file.name)\n          }}\n          expanded={expanded}\n          onExpandedChange={setExpanded}\n          onActivate={(node) => {\n            const file = findInTree(current, node.id)\n            if (file) openFile(file)\n          }}\n          className=\"h-[200px]\"\n        />\n\n        {/* Show / Format pop-up */}\n        <div className=\"flex items-center gap-2\">\n          <RetroLabel size=\"lg\" id={`${id}-show`} className=\"shrink-0\">\n            {isSave ? \"Format:\" : \"Show:\"}\n          </RetroLabel>\n          <RetroSelect value={show} onValueChange={setShow}>\n            <RetroSelectTrigger aria-labelledby={`${id}-show`} className=\"h-[20px] w-[220px] max-w-full\">\n              <RetroSelectValue />\n            </RetroSelectTrigger>\n            <RetroSelectContent>\n              {isSave ? (\n                <>\n                  <RetroSelectItem value=\"known\">SimpleText Document</RetroSelectItem>\n                  <RetroSelectItem value=\"all\">Plain Text</RetroSelectItem>\n                </>\n              ) : (\n                <>\n                  <RetroSelectItem value=\"known\">All Known Documents</RetroSelectItem>\n                  <RetroSelectItem value=\"all\">All Documents</RetroSelectItem>\n                </>\n              )}\n            </RetroSelectContent>\n          </RetroSelect>\n        </div>\n\n        {/* Buttons */}\n        <div className=\"flex flex-wrap items-center gap-2 border-t border-os9-gray-500 pt-[8px] shadow-[inset_0_1px_0_var(--os9-white)]\">\n          {isSave && (\n            <RetroButton type=\"button\" onClick={newFolder}>\n              New Folder\n            </RetroButton>\n          )}\n          <div className=\"ml-auto flex items-center gap-3\">\n            <RetroButton type=\"button\" className=\"min-w-[70px]\" onClick={onCancel}>\n              Cancel\n            </RetroButton>\n            <RetroButton\n              type=\"button\"\n              isDefault\n              disabled={!canConfirm}\n              className=\"min-w-[70px]\"\n              onClick={confirm}\n            >\n              {confirmLabel}\n            </RetroButton>\n          </div>\n        </div>\n      </RetroWindow>\n    )\n  }\n)\nOpenSaveDialogBlock.displayName = \"OpenSaveDialogBlock\"\n\nexport { OpenSaveDialogBlock }\nexport type {\n  OpenSaveDialogBlockProps,\n  OpenSaveDialogMode,\n  OpenSaveFile,\n  OpenSaveResult,\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:block"
}