File size: 5,761 Bytes
81a8217
 
affe37f
81a8217
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
 
81a8217
 
 
affe37f
 
81a8217
 
affe37f
81a8217
 
 
 
 
 
 
 
affe37f
 
81a8217
 
affe37f
 
 
 
 
 
 
 
81a8217
 
affe37f
81a8217
 
 
 
 
 
 
affe37f
81a8217
 
 
 
 
affe37f
81a8217
affe37f
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
affe37f
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
81a8217
affe37f
 
81a8217
affe37f
81a8217
affe37f
81a8217
 
 
 
affe37f
 
81a8217
affe37f
 
81a8217
 
affe37f
 
81a8217
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { TOAST_EVENT } from "../apiContract";
import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
import { MenuLabel } from "../customer-grid/icons";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import FolderNameDialog from "./FolderNameDialog";
import { deleteModuleFolder, moduleFolderChildCount, saveModuleFolder } from "./homeModel";
import type { ModuleFolder, ModuleFolderIndex } from "./homeModel";

export interface FolderTileMenuProps {
  folder: ModuleFolder;
  index: ModuleFolderIndex;
  canManage?: boolean;
  onSaveIndex?: (next: ModuleFolderIndex) => Promise<boolean>;
  onRename?: (name: string) => Promise<void>;
  onDelete?: () => Promise<void>;
  deleteBody?: ReactNode;
  children: ReactNode;
}

export class FolderPermissionError extends Error {}

/** The existing tile and its actions are siblings inside one positioning wrapper. */
export default function FolderTileMenu({
  folder, index, canManage = false, onSaveIndex, onRename, onDelete, deleteBody, children,
}: FolderTileMenuProps) {
  const trigger = useRef<HTMLButtonElement>(null);
  const writing = useRef(false);
  const [surface, setSurface] = useState<"menu" | "rename" | "delete" | null>(null);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const current = index.folders.find((candidate) => candidate.id === folder.id);
  const allowed = canManage && !!current;
  const renameAllowed = allowed && !!(onRename || onSaveIndex);
  const deleteAllowed = allowed && !!(onDelete || onSaveIndex);
  const childCount = moduleFolderChildCount(index, folder.id);
  useEffect(() => {
    if ((!renameAllowed && surface === "rename") || (!deleteAllowed && surface === "delete")
      || (!renameAllowed && !deleteAllowed)) {
      setSurface(null);
      if (surface && !writing.current) window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: {
        text: "You no longer have permission to manage this folder.", tone: "error",
      } }));
    }
  }, [renameAllowed, deleteAllowed, surface]);

  const open = (next: "rename" | "delete") => {
    if (!(next === "rename" ? renameAllowed : deleteAllowed) || writing.current) return;
    trigger.current?.focus({ preventScroll: true });
    setNotice("");
    setSurface(next);
  };
  const dismiss = () => {
    if (!writing.current) setSurface(null);
  };
  const save = async (write: () => Promise<boolean | void>) => {
    if (!allowed || writing.current) return;
    writing.current = true;
    setSaving(true);
    setNotice("");
    try {
      if (await write() !== false) setSurface(null);
      else setNotice("Folder could not be saved. Try again.");
    } catch (error) {
      if (error instanceof FolderPermissionError) {
        setSurface(null);
        window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: error.message, tone: "error" } }));
      } else setNotice(error instanceof Error ? error.message : "Folder could not be saved. Try again.");
    } finally {
      writing.current = false;
      setSaving(false);
    }
  };

  return (
    <div className="st-tilewrap home-folder-tile" data-folder-id={folder.id}>
      {children}
      {allowed && (renameAllowed || deleteAllowed) ? <>
        <button ref={trigger} type="button" className="home-folder-menu-trigger"
          aria-label={`Folder actions for ${current.name}`} title="Folder actions"
          aria-haspopup="menu" aria-expanded={surface === "menu"}
          disabled={saving}
          onClick={() => { setNotice(""); setSurface(surface === "menu" ? null : "menu"); }}>
          <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false">
            <circle cx="3" cy="8" r="1" fill="currentColor" />
            <circle cx="8" cy="8" r="1" fill="currentColor" />
            <circle cx="13" cy="8" r="1" fill="currentColor" />
          </svg>
        </button>
        {surface === "menu" ? <AnchoredOverlay anchor={trigger.current}
          className="cg-view-menu" role="menu" ariaLabel="Folder actions" onDismiss={dismiss}>
          {renameAllowed ? <button type="button" role="menuitem" onClick={() => open("rename")}>
            <MenuLabel icon="rename" text="Rename folder" />
          </button> : null}
          {deleteAllowed ? <button type="button" role="menuitem" className="is-danger" onClick={() => open("delete")}>
            <MenuLabel icon="trash" text="Delete folder" />
          </button> : null}
        </AnchoredOverlay> : null}
        {surface === "rename" && renameAllowed ? <FolderNameDialog anchor={trigger.current}
          title="Rename folder" initialName={current.name}
          siblingNames={index.folders.filter((candidate) => candidate.id !== current.id
            && (candidate.parent ?? null) === (current.parent ?? null)).map((candidate) => candidate.name)}
          disabled={saving} onDismiss={dismiss}
          onSubmit={(name) => { if (renameAllowed) void save(() => onRename
            ? onRename(name) : onSaveIndex!(saveModuleFolder(index, { ...current, name }))); }}
        /> : null}
        <ConfirmDialog open={surface === "delete" && deleteAllowed} title="Delete folder"
          body={deleteBody ?? <>{childCount} {childCount === 1 ? "item moves" : "items move"} to the top level</>}
          confirmLabel="Delete folder" tone="destructive" busy={saving}
          onCancel={dismiss}
          onConfirm={() => { if (deleteAllowed) void save(() => onDelete
            ? onDelete() : onSaveIndex!(deleteModuleFolder(index, current.id))); }} />
        {notice ? <p className="home-folder-notice" role="status">{notice}</p> : null}
      </> : null}
    </div>
  );
}