@kubohiroya/turbowarp-plus-editor-project-folder 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,22 @@
1
1
  export declare class ExplorerFileError extends Error {
2
- readonly code: 'invalidName' | 'exists' | 'sourceChanged' | 'originalKept' | 'cleanupFailed';
3
- constructor(code: 'invalidName' | 'exists' | 'sourceChanged' | 'originalKept' | 'cleanupFailed');
2
+ readonly code: 'invalidName' | 'exists' | 'invalidDestination' | 'sourceChanged' | 'originalKept' | 'cleanupFailed';
3
+ constructor(code: 'invalidName' | 'exists' | 'invalidDestination' | 'sourceChanged' | 'originalKept' | 'cleanupFailed');
4
4
  }
5
5
  export declare function parentPath(path: string): string;
6
6
  export declare function resolveExplorerDirectory(root: FileSystemDirectoryHandle, path: string): Promise<FileSystemDirectoryHandle>;
7
+ export declare function explorerNameAvailable(directory: FileSystemDirectoryHandle, name: string): Promise<boolean>;
8
+ export declare function createExplorerDirectory(parent: FileSystemDirectoryHandle, name: string, guard: () => void): Promise<void>;
7
9
  export declare function copyExplorerFile(directory: FileSystemDirectoryHandle, file: File, guard: () => void): Promise<void>;
8
10
  export declare function renameExplorerEntry(parent: FileSystemDirectoryHandle, entry: {
9
11
  name: string;
10
12
  kind: FileSystemHandleKind;
11
13
  }, name: string, guard: () => void): Promise<void>;
14
+ export declare function canMoveExplorerEntry(path: string, destination: string): boolean;
15
+ export declare function moveExplorerEntry(root: FileSystemDirectoryHandle, entry: {
16
+ path: string;
17
+ name: string;
18
+ kind: FileSystemHandleKind;
19
+ }, destination: FileSystemDirectoryHandle, destinationPath: string, guard: () => void): Promise<void>;
12
20
  export declare function deleteExplorerEntry(parent: FileSystemDirectoryHandle, entry: {
13
21
  name: string;
14
22
  kind: FileSystemHandleKind;
@@ -5,6 +5,8 @@ export declare const actionMessages: (locale?: string) => {
5
5
  renameTitle: string;
6
6
  delete: string;
7
7
  deleteTitle: string;
8
+ createFolder: string;
9
+ folderName: string;
8
10
  newName: string;
9
11
  cancel: string;
10
12
  remove: (name: string, folder: boolean) => string;
@@ -15,6 +17,7 @@ export declare const actionMessages: (locale?: string) => {
15
17
  filesOnly: string;
16
18
  invalidName: string;
17
19
  exists: string;
20
+ invalidDestination: string;
18
21
  denied: string;
19
22
  conflict: string;
20
23
  sourceChanged: string;
@@ -28,7 +31,8 @@ export type MenuAnchor = {
28
31
  x: number;
29
32
  y: number;
30
33
  };
31
- export declare const actionCss = "\n.twpf-explorer-actions{position:fixed;z-index:2147483647;max-width:calc(100vw - 8px);padding:4px;\nborder:1px solid GrayText;border-radius:5px;background:Canvas;color:CanvasText;box-shadow:0 2px 8px #0004}\n.twpf-explorer-actions button{display:block;width:100%;border:0;padding:.35em .65em;text-align:start;background:Canvas;color:CanvasText;\nfont:inherit;cursor:pointer;border-radius:3px}\n.twpf-explorer-actions button:is(:hover,:focus-visible){background:Highlight;color:HighlightText}\n.twpf-explorer-dialog{max-width:min(28em,calc(100vw - 2em));color:CanvasText;background:Canvas;\nborder:1px solid GrayText;border-radius:6px;padding:1em;overflow-wrap:anywhere}\n.twpf-explorer-dialog::backdrop{background:#0006}\n.twpf-explorer-dialog h2{font-size:1.1em;margin:0 0 .75em}\n.twpf-explorer-dialog input{display:block;width:100%;box-sizing:border-box;margin-top:.3em}\n.twpf-explorer-dialog-footer{display:flex;justify-content:flex-end;gap:.5em;margin-top:1em}\n.twpf-explorer-drop{min-height:100%;box-sizing:border-box}\n.twpf-explorer [data-drop-active],.twpf-explorer[data-drop-active]{outline:2px solid Highlight;outline-offset:-2px}\n.twpf-explorer-feedback{white-space:pre-wrap;overflow-wrap:anywhere;padding:.25em .5em}\n";
34
+ export type FileAction = 'createFolder' | 'rename' | 'delete';
35
+ export declare const actionCss = "\n.twpf-explorer-actions{position:fixed;z-index:2147483647;max-width:calc(100vw - 8px);padding:4px;\nborder:1px solid GrayText;border-radius:5px;background:Canvas;color:CanvasText;box-shadow:0 2px 8px #0004}\n.twpf-explorer-actions button{display:block;width:100%;border:0;padding:.35em .65em;text-align:start;background:Canvas;color:CanvasText;\nfont:inherit;cursor:pointer;border-radius:3px}\n.twpf-explorer-actions button:is(:hover,:focus-visible){background:Highlight;color:HighlightText}\n.twpf-explorer-dialog{max-width:min(28em,calc(100vw - 2em));color:CanvasText;background:Canvas;\nborder:1px solid GrayText;border-radius:6px;padding:1em;overflow-wrap:anywhere}\n.twpf-explorer-dialog::backdrop{background:#0006}\n.twpf-explorer-dialog h2{font-size:1.1em;margin:0 0 .75em}\n.twpf-explorer-dialog input{display:block;width:100%;box-sizing:border-box;margin-top:.3em}\n.twpf-explorer-dialog-footer{display:flex;justify-content:flex-end;gap:.5em;margin-top:1em}\n.twpf-explorer-drop{min-height:100%;box-sizing:border-box}\n.twpf-explorer [data-drop-active],.twpf-explorer[data-drop-active]{outline:2px solid Highlight;outline-offset:-2px}\n.twpf-explorer-item[data-move-unavailable]{color:GrayText;opacity:.65;filter:grayscale(1)}\n.twpf-explorer-item[data-move-active] .twpf-explorer-name{font-weight:700}\n.twpf-explorer-drag-image{position:fixed;top:0;left:0;z-index:2147483647;pointer-events:none;\ndisplay:flex;align-items:center;gap:.4em;max-width:18em;white-space:nowrap;padding:.3em .5em;\nborder:1px solid GrayText;border-radius:4px;background:Canvas;color:CanvasText;box-shadow:0 2px 8px #0004}\n.twpf-explorer-feedback{white-space:pre-wrap;overflow-wrap:anywhere;padding:.25em .5em}\n";
32
36
  export declare function ExplorerMenu({ anchor, label, actions, close }: {
33
37
  anchor: MenuAnchor;
34
38
  label: string;
@@ -38,11 +42,11 @@ export declare function ExplorerMenu({ anchor, label, actions, close }: {
38
42
  }[];
39
43
  close(restoreFocus: boolean): void;
40
44
  }): React.ReactPortal;
41
- export declare function ExplorerFileDialog({ anchor, name, folder, rename, message, close, submit }: {
45
+ export declare function ExplorerFileDialog({ anchor, name, folder, action, message, close, submit }: {
42
46
  anchor: MenuAnchor;
43
47
  name: string;
44
48
  folder: boolean;
45
- rename: boolean;
49
+ action: FileAction;
46
50
  message: ActionMessages;
47
51
  close(): void;
48
52
  submit(name: string): void;
@@ -53,7 +53,7 @@ export declare function describeProjectFolder(project: Project, locale?: string,
53
53
  folder?: string;
54
54
  }): Map<string, string>;
55
55
  /**
56
- * A read-only tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
56
+ * A tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
57
57
  * sort before files, and `.git` is hidden. Keyboard: arrow keys, Home and End move and expand; Enter or Space opens a
58
58
  * file. Needs React 16.14–18 from the host.
59
59
  */
package/dist/explorer.js CHANGED
@@ -936,14 +936,23 @@ async function resolveExplorerDirectory(root, path) {
936
936
  if (((_await$root$resolve = await root.resolve(directory)) === null || _await$root$resolve === void 0 ? void 0 : _await$root$resolve.join("/")) !== path) throw new ExplorerFileError("sourceChanged");
937
937
  return directory;
938
938
  }
939
- async function assertUnused(directory, name) {
939
+ async function explorerNameAvailable(directory, name) {
940
940
  try {
941
941
  await directory.getFileHandle(name);
942
942
  } catch (error) {
943
- if (error instanceof DOMException && error.name === "NotFoundError") return;
943
+ if (error instanceof DOMException && error.name === "NotFoundError") return true;
944
944
  if (!(error instanceof DOMException) || error.name !== "TypeMismatchError") throw error;
945
945
  }
946
- throw new ExplorerFileError("exists");
946
+ return false;
947
+ }
948
+ async function assertUnused(directory, name) {
949
+ if (!await explorerNameAvailable(directory, name)) throw new ExplorerFileError("exists");
950
+ }
951
+ async function createExplorerDirectory(parent, name, guard) {
952
+ validateName(name);
953
+ await assertUnused(parent, name);
954
+ guard();
955
+ await parent.getDirectoryHandle(name, { create: true });
947
956
  }
948
957
  var sameVersion = (a, b) => a.size === b.size && a.lastModified === b.lastModified;
949
958
  async function writeNewFile(directory, name, file, guard) {
@@ -1068,13 +1077,26 @@ async function removeIncompleteCopy(parent, name) {
1068
1077
  }
1069
1078
  async function renameExplorerEntry(parent, entry, name, guard) {
1070
1079
  if (name === entry.name) return;
1080
+ await relocateEntry(parent, entry, parent, name, guard);
1081
+ }
1082
+ function canMoveExplorerEntry(path, destination) {
1083
+ return parentPath(path) !== destination && path !== destination && !destination.startsWith(`${path}/`);
1084
+ }
1085
+ async function moveExplorerEntry(root, entry, destination, destinationPath, guard) {
1086
+ if (!canMoveExplorerEntry(entry.path, destinationPath)) throw new ExplorerFileError("invalidDestination");
1087
+ const parent = await resolveExplorerDirectory(root, parentPath(entry.path));
1088
+ guard();
1089
+ await relocateEntry(parent, entry, destination, entry.name, guard);
1090
+ }
1091
+ async function relocateEntry(sourceParent, entry, destination, name, guard) {
1092
+ validateName(entry.name);
1071
1093
  validateName(name);
1072
- const copy = await copyEntry(parent, entry.kind === "file" ? await parent.getFileHandle(entry.name) : await parent.getDirectoryHandle(entry.name), parent, name, guard);
1094
+ const copy = await copyEntry(sourceParent, entry.kind === "file" ? await sourceParent.getFileHandle(entry.name) : await sourceParent.getDirectoryHandle(entry.name), destination, name, guard);
1073
1095
  try {
1074
1096
  await copy.verify();
1075
1097
  guard();
1076
1098
  } catch (error) {
1077
- await removeIncompleteCopy(parent, name);
1099
+ await removeIncompleteCopy(destination, name);
1078
1100
  throw error;
1079
1101
  }
1080
1102
  try {
@@ -1120,6 +1142,8 @@ var actionMessages = (locale = "en") => locale.toLowerCase().startsWith("ja") ?
1120
1142
  renameTitle: "名前を変更",
1121
1143
  delete: "削除…",
1122
1144
  deleteTitle: "削除",
1145
+ createFolder: "新規フォルダを作成",
1146
+ folderName: "フォルダ名",
1123
1147
  newName: "新しい名前",
1124
1148
  cancel: "キャンセル",
1125
1149
  remove: (name, folder) => folder ? `「${name}」とその中身を削除しますか?` : `「${name}」を削除しますか?`,
@@ -1130,6 +1154,7 @@ var actionMessages = (locale = "en") => locale.toLowerCase().startsWith("ja") ?
1130
1154
  filesOnly: "ファイルをドロップしてください。",
1131
1155
  invalidName: "この名前は使用できません。",
1132
1156
  exists: "同じ名前のファイルまたはフォルダがあります。",
1157
+ invalidDestination: "このフォルダには移動できません。",
1133
1158
  denied: "このフォルダへの書き込みが許可されていません。",
1134
1159
  conflict: "プロジェクトフォルダが変更されたか、別の操作が実行中です。",
1135
1160
  sourceChanged: "操作中に対象が変更されました。",
@@ -1142,6 +1167,8 @@ var actionMessages = (locale = "en") => locale.toLowerCase().startsWith("ja") ?
1142
1167
  renameTitle: "Rename",
1143
1168
  delete: "Delete…",
1144
1169
  deleteTitle: "Delete",
1170
+ createFolder: "Create New Folder",
1171
+ folderName: "Folder name",
1145
1172
  newName: "New name",
1146
1173
  cancel: "Cancel",
1147
1174
  remove: (name, folder) => folder ? `Delete “${name}” and its contents?` : `Delete “${name}”?`,
@@ -1152,6 +1179,7 @@ var actionMessages = (locale = "en") => locale.toLowerCase().startsWith("ja") ?
1152
1179
  filesOnly: "Drop files here.",
1153
1180
  invalidName: "This name cannot be used.",
1154
1181
  exists: "A file or folder with this name already exists.",
1182
+ invalidDestination: "This item cannot be moved to that folder.",
1155
1183
  denied: "Permission to write to this folder was not granted.",
1156
1184
  conflict: "The project folder changed or another operation is running.",
1157
1185
  sourceChanged: "The item changed during the operation.",
@@ -1173,6 +1201,11 @@ border:1px solid GrayText;border-radius:6px;padding:1em;overflow-wrap:anywhere}
1173
1201
  .twpf-explorer-dialog-footer{display:flex;justify-content:flex-end;gap:.5em;margin-top:1em}
1174
1202
  .twpf-explorer-drop{min-height:100%;box-sizing:border-box}
1175
1203
  .twpf-explorer [data-drop-active],.twpf-explorer[data-drop-active]{outline:2px solid Highlight;outline-offset:-2px}
1204
+ .twpf-explorer-item[data-move-unavailable]{color:GrayText;opacity:.65;filter:grayscale(1)}
1205
+ .twpf-explorer-item[data-move-active] .twpf-explorer-name{font-weight:700}
1206
+ .twpf-explorer-drag-image{position:fixed;top:0;left:0;z-index:2147483647;pointer-events:none;
1207
+ display:flex;align-items:center;gap:.4em;max-width:18em;white-space:nowrap;padding:.3em .5em;
1208
+ border:1px solid GrayText;border-radius:4px;background:Canvas;color:CanvasText;box-shadow:0 2px 8px #0004}
1176
1209
  .twpf-explorer-feedback{white-space:pre-wrap;overflow-wrap:anywhere;padding:.25em .5em}
1177
1210
  `;
1178
1211
  function ExplorerMenu({ anchor, label, actions, close }) {
@@ -1233,11 +1266,11 @@ function ExplorerMenu({ anchor, label, actions, close }) {
1233
1266
  onClick: action.run
1234
1267
  }, action.label))), document.body);
1235
1268
  }
1236
- function ExplorerFileDialog({ anchor, name, folder, rename, message, close, submit }) {
1269
+ function ExplorerFileDialog({ anchor, name, folder, action, message, close, submit }) {
1237
1270
  const ref = React.useRef(null);
1238
1271
  const input = React.useRef(null);
1239
1272
  const cancel = React.useRef(null);
1240
- const title = rename ? message.renameTitle : message.deleteTitle;
1273
+ const title = action === "createFolder" ? message.createFolder : action === "rename" ? message.renameTitle : message.deleteTitle;
1241
1274
  React.useLayoutEffect(() => {
1242
1275
  var _cancel$current;
1243
1276
  const dialog = ref.current;
@@ -1263,11 +1296,11 @@ function ExplorerFileDialog({ anchor, name, folder, rename, message, close, subm
1263
1296
  var _input$current$value, _input$current;
1264
1297
  event.preventDefault();
1265
1298
  submit((_input$current$value = (_input$current = input.current) === null || _input$current === void 0 ? void 0 : _input$current.value) !== null && _input$current$value !== void 0 ? _input$current$value : name);
1266
- } }, /* @__PURE__ */ React.createElement("h2", null, title), rename ? /* @__PURE__ */ React.createElement("label", null, message.newName, /* @__PURE__ */ React.createElement("input", {
1299
+ } }, /* @__PURE__ */ React.createElement("h2", null, title), action === "delete" ? /* @__PURE__ */ React.createElement("p", null, message.remove(name, folder)) : /* @__PURE__ */ React.createElement("label", null, action === "rename" ? message.newName : message.folderName, /* @__PURE__ */ React.createElement("input", {
1267
1300
  ref: input,
1268
- defaultValue: name,
1301
+ defaultValue: action === "rename" ? name : "",
1269
1302
  required: true
1270
- })) : /* @__PURE__ */ React.createElement("p", null, message.remove(name, folder)), /* @__PURE__ */ React.createElement("div", { className: "twpf-explorer-dialog-footer" }, /* @__PURE__ */ React.createElement("button", {
1303
+ })), /* @__PURE__ */ React.createElement("div", { className: "twpf-explorer-dialog-footer" }, /* @__PURE__ */ React.createElement("button", {
1271
1304
  ref: cancel,
1272
1305
  type: "button",
1273
1306
  onClick: close
@@ -1540,6 +1573,7 @@ var rootId = "/";
1540
1573
  var errorId = (parent) => `${parent}\0error`;
1541
1574
  var failure = (error, message) => error instanceof DOMException && (error.name === "NotAllowedError" || error.name === "SecurityError") ? message.denied : message.failed;
1542
1575
  var prefix = "twpf-explorer";
1576
+ var entryDragType = "application/x-twpf-explorer-entry";
1543
1577
  var css = `.${prefix}{font:inherit;color:inherit}
1544
1578
  .${prefix}-item{display:flex;align-items:center;gap:.4em;width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
1545
1579
  padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer;white-space:nowrap}
@@ -1697,6 +1731,7 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
1697
1731
  const [loadedFolders] = React.useState(() => /* @__PURE__ */ new Set());
1698
1732
  const [rootLoaded, setRootLoaded] = React.useState(false);
1699
1733
  const [drag, setDrag] = React.useState(null);
1734
+ const [move, setMove] = React.useState();
1700
1735
  const [menu, setMenu] = React.useState();
1701
1736
  const [dialog, setDialog] = React.useState();
1702
1737
  const [feedback, setFeedback] = React.useState("");
@@ -1907,8 +1942,79 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
1907
1942
  var _target$closest$getAt, _target$closest;
1908
1943
  return (_target$closest$getAt = (_target$closest = target.closest("[data-drop-directory]")) === null || _target$closest === void 0 ? void 0 : _target$closest.getAttribute("data-drop-directory")) !== null && _target$closest$getAt !== void 0 ? _target$closest$getAt : "";
1909
1944
  };
1945
+ const moveDropPath = (target) => {
1946
+ const row = target.closest(`.${prefix}-item`);
1947
+ const path = row ? row.getAttribute("data-move-directory") : "";
1948
+ return path !== null && (move === null || move === void 0 ? void 0 : move.destinations.has(path)) ? path : null;
1949
+ };
1950
+ const startMove = (event, entry) => {
1951
+ var _document$defaultView;
1952
+ if (running.current || dialog) {
1953
+ event.preventDefault();
1954
+ return;
1955
+ }
1956
+ event.stopPropagation();
1957
+ setMenu(void 0);
1958
+ setDrag(null);
1959
+ event.dataTransfer.effectAllowed = "move";
1960
+ event.dataTransfer.setData(entryDragType, entry.path);
1961
+ const row = event.currentTarget;
1962
+ const document = row.ownerDocument;
1963
+ const image = document.createElement("div");
1964
+ image.className = `${prefix}-drag-image`;
1965
+ const icon = row.querySelector(`.${prefix}-icon`);
1966
+ if (icon) image.appendChild(icon.cloneNode(true));
1967
+ const name = document.createElement("span");
1968
+ name.className = `${prefix}-name`;
1969
+ name.textContent = entry.name;
1970
+ image.appendChild(name);
1971
+ document.body.appendChild(image);
1972
+ event.dataTransfer.setDragImage(image, -12, -12);
1973
+ (_document$defaultView = document.defaultView) === null || _document$defaultView === void 0 || _document$defaultView.requestAnimationFrame(() => image.remove());
1974
+ setMove({
1975
+ entry,
1976
+ destinations: /* @__PURE__ */ new Set()
1977
+ });
1978
+ const candidates = ["", ...tree.getItems().filter((item) => item.isFolder()).map((item) => item.getId())];
1979
+ Promise.all(candidates.filter((path) => canMoveExplorerEntry(entry.path, path)).map(async (path) => {
1980
+ try {
1981
+ return await explorerNameAvailable(await directoryAt(path || rootId), entry.name) ? path : null;
1982
+ } catch (_unused3) {
1983
+ return null;
1984
+ }
1985
+ })).then((paths) => {
1986
+ if (mounted.current) setMove((current) => (current === null || current === void 0 ? void 0 : current.entry) === entry ? {
1987
+ entry,
1988
+ destinations: new Set(paths.filter((path) => path !== null))
1989
+ } : current);
1990
+ });
1991
+ };
1992
+ const endMove = () => {
1993
+ setMove(void 0);
1994
+ setDrag(null);
1995
+ };
1996
+ const dropMove = (event, entry) => {
1997
+ event.preventDefault();
1998
+ event.stopPropagation();
1999
+ const path = moveDropPath(event.target);
2000
+ endMove();
2001
+ if (path === null || event.dataTransfer.getData(entryDragType) !== entry.path) return;
2002
+ run(async () => {
2003
+ let moved = false;
2004
+ try {
2005
+ await write(path, (destination, guard) => moveExplorerEntry(directory, entry, destination, path, guard));
2006
+ moved = true;
2007
+ } finally {
2008
+ if (mounted.current) forget(entry.path);
2009
+ await reread(parentPath(entry.path));
2010
+ await reread(path, moved);
2011
+ await (git === null || git === void 0 ? void 0 : git.refresh());
2012
+ }
2013
+ });
2014
+ };
1910
2015
  const acceptsFiles = (event) => Boolean(mutate && event.dataTransfer.types.includes("Files"));
1911
2016
  const drop = (event) => {
2017
+ if (move && event.dataTransfer.types.includes(entryDragType)) return dropMove(event, move.entry);
1912
2018
  if (!acceptsFiles(event)) return;
1913
2019
  event.preventDefault();
1914
2020
  event.stopPropagation();
@@ -1969,16 +2075,22 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
1969
2075
  };
1970
2076
  const submitFileAction = (name) => {
1971
2077
  if (!dialog) return;
1972
- const { entry, rename } = dialog;
2078
+ const { entry, action } = dialog;
1973
2079
  setDialog(void 0);
1974
- if (rename && entry.name === name) return;
2080
+ if (action === "rename" && entry.name === name) return;
1975
2081
  run(async () => {
1976
- const parent = parentPath(entry.path);
2082
+ const parent = action === "createFolder" ? entry.path : parentPath(entry.path);
2083
+ let changed = false;
1977
2084
  try {
1978
- await write(parent, (handle, guard) => rename ? renameExplorerEntry(handle, entry, name, guard) : deleteExplorerEntry(handle, entry, guard));
2085
+ await write(parent, (handle, guard) => {
2086
+ if (action === "createFolder") return createExplorerDirectory(handle, name, guard);
2087
+ if (action === "rename") return renameExplorerEntry(handle, entry, name, guard);
2088
+ return deleteExplorerEntry(handle, entry, guard);
2089
+ });
2090
+ changed = true;
1979
2091
  } finally {
1980
- if (mounted.current) forget(entry.path);
1981
- await reread(parent);
2092
+ if (mounted.current && action !== "createFolder") forget(entry.path);
2093
+ await reread(parent, action === "createFolder" && changed);
1982
2094
  await (git === null || git === void 0 ? void 0 : git.refresh());
1983
2095
  }
1984
2096
  });
@@ -2009,6 +2121,8 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
2009
2121
  markLabel,
2010
2122
  description
2011
2123
  ].filter(Boolean).join(message.separator);
2124
+ const moveDestination = (entry === null || entry === void 0 ? void 0 : entry.kind) === "directory" && (move === null || move === void 0 ? void 0 : move.destinations.has(entry.path));
2125
+ const moveActive = moveDestination && drag === entry.path;
2012
2126
  const rows = [/* @__PURE__ */ React.createElement("button", _objectSpread2(_objectSpread2({}, itemProps), {}, {
2013
2127
  key: item.getId(),
2014
2128
  type: "button",
@@ -2021,6 +2135,12 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
2021
2135
  title: unsaved || (status === null || status === void 0 ? void 0 : status.staged) || (status === null || status === void 0 ? void 0 : status.revision) ? accessibleName : void 0,
2022
2136
  "data-drop-directory": (entry === null || entry === void 0 ? void 0 : entry.kind) === "directory" ? entry.path : entry ? parentPath(entry.path) : void 0,
2023
2137
  "data-drop-active": (entry === null || entry === void 0 ? void 0 : entry.kind) === "directory" && drag === entry.path ? "" : void 0,
2138
+ "data-move-directory": (entry === null || entry === void 0 ? void 0 : entry.kind) === "directory" ? entry.path : void 0,
2139
+ "data-move-unavailable": move && !moveDestination ? "" : void 0,
2140
+ "data-move-active": moveActive ? "" : void 0,
2141
+ draggable: entry && mutate ? !working : void 0,
2142
+ onDragStart: entry && mutate ? (event) => startMove(event, entry) : void 0,
2143
+ onDragEnd: entry && mutate ? endMove : void 0,
2024
2144
  "aria-haspopup": entry && (mutate || git) ? "menu" : void 0,
2025
2145
  onContextMenu: entry ? (event) => showMenu(event, entry) : void 0,
2026
2146
  onKeyDown: entry ? (event) => {
@@ -2059,6 +2179,14 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
2059
2179
  "data-drop-active": drag === "" ? "" : void 0,
2060
2180
  onDrop: drop,
2061
2181
  onDragOver: (event) => {
2182
+ if (move && event.dataTransfer.types.includes(entryDragType)) {
2183
+ const path = running.current ? null : moveDropPath(event.target);
2184
+ event.stopPropagation();
2185
+ if (path !== null) event.preventDefault();
2186
+ event.dataTransfer.dropEffect = path === null ? "none" : "move";
2187
+ setDrag(path);
2188
+ return;
2189
+ }
2062
2190
  if (!acceptsFiles(event)) return;
2063
2191
  event.preventDefault();
2064
2192
  event.stopPropagation();
@@ -2078,34 +2206,44 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
2078
2206
  anchor: menu.anchor,
2079
2207
  label: actions.actions,
2080
2208
  close: closeMenu,
2081
- actions: [...mutate ? [{
2082
- label: actions.rename,
2083
- run: () => {
2084
- closeMenu(false);
2085
- setDialog(_objectSpread2(_objectSpread2({}, menu), {}, { rename: true }));
2086
- }
2087
- }, {
2088
- label: actions.delete,
2089
- run: () => {
2090
- closeMenu(false);
2091
- setDialog(_objectSpread2(_objectSpread2({}, menu), {}, { rename: false }));
2092
- }
2093
- }] : [], ...git ? ["stage", "unstage"].map((kind) => ({
2094
- label: actions[kind],
2095
- run: () => {
2096
- closeMenu(true);
2097
- run(async () => {
2098
- var _result$error;
2099
- const result = await git.change(kind, menu.entry, isCurrent !== null && isCurrent !== void 0 ? isCurrent : (() => mounted.current));
2100
- if (!result.done) return (_result$error = result.error) !== null && _result$error !== void 0 ? _result$error : actions.conflict;
2101
- });
2102
- }
2103
- })) : []]
2209
+ actions: [
2210
+ ...mutate && menu.entry.kind === "directory" ? [{
2211
+ label: actions.createFolder,
2212
+ run: () => {
2213
+ closeMenu(false);
2214
+ setDialog(_objectSpread2(_objectSpread2({}, menu), {}, { action: "createFolder" }));
2215
+ }
2216
+ }] : [],
2217
+ ...mutate ? [{
2218
+ label: actions.rename,
2219
+ run: () => {
2220
+ closeMenu(false);
2221
+ setDialog(_objectSpread2(_objectSpread2({}, menu), {}, { action: "rename" }));
2222
+ }
2223
+ }, {
2224
+ label: actions.delete,
2225
+ run: () => {
2226
+ closeMenu(false);
2227
+ setDialog(_objectSpread2(_objectSpread2({}, menu), {}, { action: "delete" }));
2228
+ }
2229
+ }] : [],
2230
+ ...git ? ["stage", "unstage"].map((kind) => ({
2231
+ label: actions[kind],
2232
+ run: () => {
2233
+ closeMenu(true);
2234
+ run(async () => {
2235
+ var _result$error;
2236
+ const result = await git.change(kind, menu.entry, isCurrent !== null && isCurrent !== void 0 ? isCurrent : (() => mounted.current));
2237
+ if (!result.done) return (_result$error = result.error) !== null && _result$error !== void 0 ? _result$error : actions.conflict;
2238
+ });
2239
+ }
2240
+ })) : []
2241
+ ]
2104
2242
  }) : null, dialog ? /* @__PURE__ */ React.createElement(ExplorerFileDialog, {
2105
2243
  anchor: dialog.anchor,
2106
2244
  name: dialog.entry.name,
2107
2245
  folder: dialog.entry.kind === "directory",
2108
- rename: dialog.rename,
2246
+ action: dialog.action,
2109
2247
  message: actions,
2110
2248
  close: () => setDialog(void 0),
2111
2249
  submit: submitFileAction
@@ -2118,7 +2256,7 @@ var keyFor = (directory) => {
2118
2256
  return keys.get(directory);
2119
2257
  };
2120
2258
  /**
2121
- * A read-only tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
2259
+ * A tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
2122
2260
  * sort before files, and `.git` is hidden. Keyboard: arrow keys, Home and End move and expand; Enter or Space opens a
2123
2261
  * file. Needs React 16.14–18 from the host.
2124
2262
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -1,7 +1,7 @@
1
1
  type DirectoryEntries = FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>};
2
2
 
3
3
  export class ExplorerFileError extends Error {
4
- constructor(readonly code: 'invalidName' | 'exists' | 'sourceChanged' | 'originalKept' | 'cleanupFailed') {
4
+ constructor(readonly code: 'invalidName' | 'exists' | 'invalidDestination' | 'sourceChanged' | 'originalKept' | 'cleanupFailed') {
5
5
  super(code);
6
6
  }
7
7
  }
@@ -27,14 +27,25 @@ export async function resolveExplorerDirectory(root: FileSystemDirectoryHandle,
27
27
  return directory;
28
28
  }
29
29
 
30
- async function assertUnused(directory: FileSystemDirectoryHandle, name: string) {
30
+ export async function explorerNameAvailable(directory: FileSystemDirectoryHandle, name: string) {
31
31
  try {
32
32
  await directory.getFileHandle(name);
33
33
  } catch (error) {
34
- if (error instanceof DOMException && error.name === 'NotFoundError') return;
34
+ if (error instanceof DOMException && error.name === 'NotFoundError') return true;
35
35
  if (!(error instanceof DOMException) || error.name !== 'TypeMismatchError') throw error;
36
36
  }
37
- throw new ExplorerFileError('exists');
37
+ return false;
38
+ }
39
+
40
+ async function assertUnused(directory: FileSystemDirectoryHandle, name: string) {
41
+ if (!await explorerNameAvailable(directory, name)) throw new ExplorerFileError('exists');
42
+ }
43
+
44
+ export async function createExplorerDirectory(parent: FileSystemDirectoryHandle, name: string, guard: () => void) {
45
+ validateName(name);
46
+ await assertUnused(parent, name);
47
+ guard();
48
+ await parent.getDirectoryHandle(name, {create: true});
38
49
  }
39
50
 
40
51
  const sameVersion = (a: File, b: File) => a.size === b.size && a.lastModified === b.lastModified;
@@ -129,14 +140,33 @@ async function removeIncompleteCopy(parent: FileSystemDirectoryHandle, name: str
129
140
  export async function renameExplorerEntry(parent: FileSystemDirectoryHandle, entry: {name: string; kind: FileSystemHandleKind},
130
141
  name: string, guard: () => void) {
131
142
  if (name === entry.name) return;
143
+ await relocateEntry(parent, entry, parent, name, guard);
144
+ }
145
+
146
+ export function canMoveExplorerEntry(path: string, destination: string) {
147
+ return parentPath(path) !== destination && path !== destination && !destination.startsWith(`${path}/`);
148
+ }
149
+
150
+ export async function moveExplorerEntry(root: FileSystemDirectoryHandle,
151
+ entry: {path: string; name: string; kind: FileSystemHandleKind}, destination: FileSystemDirectoryHandle,
152
+ destinationPath: string, guard: () => void) {
153
+ if (!canMoveExplorerEntry(entry.path, destinationPath)) throw new ExplorerFileError('invalidDestination');
154
+ const parent = await resolveExplorerDirectory(root, parentPath(entry.path));
155
+ guard();
156
+ await relocateEntry(parent, entry, destination, entry.name, guard);
157
+ }
158
+
159
+ async function relocateEntry(sourceParent: FileSystemDirectoryHandle, entry: {name: string; kind: FileSystemHandleKind},
160
+ destination: FileSystemDirectoryHandle, name: string, guard: () => void) {
161
+ validateName(entry.name);
132
162
  validateName(name);
133
- const source = entry.kind === 'file' ? await parent.getFileHandle(entry.name) : await parent.getDirectoryHandle(entry.name);
134
- const copy = await copyEntry(parent, source, parent, name, guard);
163
+ const source = entry.kind === 'file' ? await sourceParent.getFileHandle(entry.name) : await sourceParent.getDirectoryHandle(entry.name);
164
+ const copy = await copyEntry(sourceParent, source, destination, name, guard);
135
165
  try {
136
166
  await copy.verify();
137
167
  guard();
138
168
  } catch (error) {
139
- await removeIncompleteCopy(parent, name);
169
+ await removeIncompleteCopy(destination, name);
140
170
  throw error;
141
171
  }
142
172
  try {
@@ -3,21 +3,23 @@ import {createPortal} from 'react-dom';
3
3
 
4
4
  export const actionMessages = (locale = 'en') => locale.toLowerCase().startsWith('ja') ? {
5
5
  actions: 'ファイルとフォルダの操作', rename: '名前を変更…', renameTitle: '名前を変更', delete: '削除…', deleteTitle: '削除',
6
- newName: '新しい名前', cancel: 'キャンセル',
6
+ createFolder: '新規フォルダを作成', folderName: 'フォルダ名', newName: '新しい名前', cancel: 'キャンセル',
7
7
  remove: (name: string, folder: boolean) => folder ? `「${name}」とその中身を削除しますか?` : `「${name}」を削除しますか?`,
8
8
  stage: 'Git にステージ', unstage: 'Git のステージを解除',
9
9
  working: '処理中…', copyFailed: 'コピーできませんでした', filesOnly: 'ファイルをドロップしてください。',
10
10
  invalidName: 'この名前は使用できません。', exists: '同じ名前のファイルまたはフォルダがあります。',
11
+ invalidDestination: 'このフォルダには移動できません。',
11
12
  denied: 'このフォルダへの書き込みが許可されていません。', conflict: 'プロジェクトフォルダが変更されたか、別の操作が実行中です。',
12
13
  sourceChanged: '操作中に対象が変更されました。', originalKept: '元の項目を削除できなかったため、コピーを残しました。',
13
14
  cleanupFailed: '失敗したコピーを削除できませんでした。', failed: '操作を完了できませんでした。'
14
15
  } : {
15
16
  actions: 'File and folder actions', rename: 'Rename…', renameTitle: 'Rename', delete: 'Delete…', deleteTitle: 'Delete',
16
- newName: 'New name', cancel: 'Cancel',
17
+ createFolder: 'Create New Folder', folderName: 'Folder name', newName: 'New name', cancel: 'Cancel',
17
18
  remove: (name: string, folder: boolean) => folder ? `Delete “${name}” and its contents?` : `Delete “${name}”?`,
18
19
  stage: 'Stage in Git', unstage: 'Unstage in Git',
19
20
  working: 'Working…', copyFailed: 'Could not copy', filesOnly: 'Drop files here.',
20
21
  invalidName: 'This name cannot be used.', exists: 'A file or folder with this name already exists.',
22
+ invalidDestination: 'This item cannot be moved to that folder.',
21
23
  denied: 'Permission to write to this folder was not granted.', conflict: 'The project folder changed or another operation is running.',
22
24
  sourceChanged: 'The item changed during the operation.', originalKept: 'The original could not be removed, so the copy was kept.',
23
25
  cleanupFailed: 'The incomplete copy could not be removed.', failed: 'The operation could not be completed.'
@@ -25,6 +27,7 @@ export const actionMessages = (locale = 'en') => locale.toLowerCase().startsWith
25
27
 
26
28
  export type ActionMessages = ReturnType<typeof actionMessages>;
27
29
  export type MenuAnchor = {row: HTMLButtonElement; x: number; y: number};
30
+ export type FileAction = 'createFolder' | 'rename' | 'delete';
28
31
 
29
32
  export const actionCss = `
30
33
  .twpf-explorer-actions{position:fixed;z-index:2147483647;max-width:calc(100vw - 8px);padding:4px;
@@ -40,6 +43,11 @@ border:1px solid GrayText;border-radius:6px;padding:1em;overflow-wrap:anywhere}
40
43
  .twpf-explorer-dialog-footer{display:flex;justify-content:flex-end;gap:.5em;margin-top:1em}
41
44
  .twpf-explorer-drop{min-height:100%;box-sizing:border-box}
42
45
  .twpf-explorer [data-drop-active],.twpf-explorer[data-drop-active]{outline:2px solid Highlight;outline-offset:-2px}
46
+ .twpf-explorer-item[data-move-unavailable]{color:GrayText;opacity:.65;filter:grayscale(1)}
47
+ .twpf-explorer-item[data-move-active] .twpf-explorer-name{font-weight:700}
48
+ .twpf-explorer-drag-image{position:fixed;top:0;left:0;z-index:2147483647;pointer-events:none;
49
+ display:flex;align-items:center;gap:.4em;max-width:18em;white-space:nowrap;padding:.3em .5em;
50
+ border:1px solid GrayText;border-radius:4px;background:Canvas;color:CanvasText;box-shadow:0 2px 8px #0004}
43
51
  .twpf-explorer-feedback{white-space:pre-wrap;overflow-wrap:anywhere;padding:.25em .5em}
44
52
  `;
45
53
 
@@ -87,14 +95,14 @@ export function ExplorerMenu({anchor, label, actions, close}: {
87
95
  </div>, document.body);
88
96
  }
89
97
 
90
- export function ExplorerFileDialog({anchor, name, folder, rename, message, close, submit}: {
91
- anchor: MenuAnchor; name: string; folder: boolean; rename: boolean; message: ActionMessages;
98
+ export function ExplorerFileDialog({anchor, name, folder, action, message, close, submit}: {
99
+ anchor: MenuAnchor; name: string; folder: boolean; action: FileAction; message: ActionMessages;
92
100
  close(): void; submit(name: string): void;
93
101
  }) {
94
102
  const ref = React.useRef<HTMLDialogElement>(null);
95
103
  const input = React.useRef<HTMLInputElement>(null);
96
104
  const cancel = React.useRef<HTMLButtonElement>(null);
97
- const title = rename ? message.renameTitle : message.deleteTitle;
105
+ const title = action === 'createFolder' ? message.createFolder : action === 'rename' ? message.renameTitle : message.deleteTitle;
98
106
  React.useLayoutEffect(() => {
99
107
  const dialog = ref.current!;
100
108
  dialog.showModal();
@@ -114,8 +122,10 @@ export function ExplorerFileDialog({anchor, name, folder, rename, message, close
114
122
  submit(input.current?.value ?? name);
115
123
  }}>
116
124
  <h2>{title}</h2>
117
- {rename ? <label>{message.newName}<input ref={input} defaultValue={name} required /></label> :
118
- <p>{message.remove(name, folder)}</p>}
125
+ {action === 'delete' ? <p>{message.remove(name, folder)}</p> :
126
+ <label>{action === 'rename' ? message.newName : message.folderName}
127
+ <input ref={input} defaultValue={action === 'rename' ? name : ''} required />
128
+ </label>}
119
129
  <div className="twpf-explorer-dialog-footer">
120
130
  <button ref={cancel} type="button" onClick={close}>{message.cancel}</button>
121
131
  <button type="submit">{title}</button>
package/src/explorer.tsx CHANGED
@@ -6,10 +6,10 @@ import {FolderError, isObject, manifestFile, projectFile} from './source.js';
6
6
  import {followProjectFolder} from './folder-registry.js';
7
7
  import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
8
8
  import type {Json, Project} from './source.js';
9
- import {copyExplorerFile, deleteExplorerEntry, ExplorerFileError, parentPath, renameExplorerEntry,
10
- resolveExplorerDirectory} from './explorer-files.js';
9
+ import {canMoveExplorerEntry, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
10
+ explorerNameAvailable, moveExplorerEntry, parentPath, renameExplorerEntry, resolveExplorerDirectory} from './explorer-files.js';
11
11
  import {actionCss, actionMessages, ExplorerFileDialog, ExplorerMenu} from './explorer-menu.js';
12
- import type {MenuAnchor} from './explorer-menu.js';
12
+ import type {FileAction, MenuAnchor} from './explorer-menu.js';
13
13
  import {createFilePreview} from './file-preview.js';
14
14
  import type {FilePreviewRequest, ReadFileBaseline} from './file-preview.js';
15
15
 
@@ -143,6 +143,7 @@ const failure = (error: unknown, message: Message) =>
143
143
  message.denied : message.failed;
144
144
 
145
145
  const prefix = 'twpf-explorer';
146
+ const entryDragType = 'application/x-twpf-explorer-entry';
146
147
  // Colors come from the host's text color, so the tree follows light and dark themes.
147
148
  const css = `.${prefix}{font:inherit;color:inherit}
148
149
  .${prefix}-item{display:flex;align-items:center;gap:.4em;width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
@@ -263,8 +264,9 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
263
264
  const [loadedFolders] = React.useState(() => new Set<string>());
264
265
  const [rootLoaded, setRootLoaded] = React.useState(false);
265
266
  const [drag, setDrag] = React.useState<string | null>(null);
267
+ const [move, setMove] = React.useState<{entry: ExplorerEntry; destinations: ReadonlySet<string>}>();
266
268
  const [menu, setMenu] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor}>();
267
- const [dialog, setDialog] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor; rename: boolean}>();
269
+ const [dialog, setDialog] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor; action: FileAction}>();
268
270
  const [feedback, setFeedback] = React.useState('');
269
271
  const [working, setWorking] = React.useState(false);
270
272
  const running = React.useRef(false);
@@ -405,8 +407,74 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
405
407
  };
406
408
  const dropPath = (target: EventTarget) =>
407
409
  (target as Element).closest('[data-drop-directory]')?.getAttribute('data-drop-directory') ?? '';
410
+ const moveDropPath = (target: EventTarget) => {
411
+ const row = (target as Element).closest<HTMLButtonElement>(`.${prefix}-item`);
412
+ const path = row ? row.getAttribute('data-move-directory') : '';
413
+ return path !== null && move?.destinations.has(path) ? path : null;
414
+ };
415
+ const startMove = (event: React.DragEvent<HTMLButtonElement>, entry: ExplorerEntry) => {
416
+ if (running.current || dialog) {
417
+ event.preventDefault();
418
+ return;
419
+ }
420
+ event.stopPropagation();
421
+ setMenu(undefined);
422
+ setDrag(null);
423
+ event.dataTransfer.effectAllowed = 'move';
424
+ event.dataTransfer.setData(entryDragType, entry.path);
425
+ const row = event.currentTarget;
426
+ const document = row.ownerDocument;
427
+ const image = document.createElement('div');
428
+ image.className = `${prefix}-drag-image`;
429
+ const icon = row.querySelector(`.${prefix}-icon`);
430
+ if (icon) image.appendChild(icon.cloneNode(true));
431
+ const name = document.createElement('span');
432
+ name.className = `${prefix}-name`;
433
+ name.textContent = entry.name;
434
+ image.appendChild(name);
435
+ document.body.appendChild(image);
436
+ event.dataTransfer.setDragImage(image, -12, -12);
437
+ document.defaultView?.requestAnimationFrame(() => image.remove());
438
+
439
+ setMove({entry, destinations: new Set()});
440
+ const candidates = ['', ...tree.getItems().filter(item => item.isFolder()).map(item => item.getId())];
441
+ void Promise.all(candidates.filter(path => canMoveExplorerEntry(entry.path, path)).map(async path => {
442
+ try {
443
+ return await explorerNameAvailable(await directoryAt(path || rootId), entry.name) ? path : null;
444
+ } catch {
445
+ return null;
446
+ }
447
+ })).then(paths => {
448
+ if (mounted.current) setMove(current => current?.entry === entry ?
449
+ {entry, destinations: new Set(paths.filter(path => path !== null))} : current);
450
+ });
451
+ };
452
+ const endMove = () => {
453
+ setMove(undefined);
454
+ setDrag(null);
455
+ };
456
+ const dropMove = (event: React.DragEvent<HTMLDivElement>, entry: ExplorerEntry) => {
457
+ event.preventDefault();
458
+ event.stopPropagation();
459
+ const path = moveDropPath(event.target);
460
+ endMove();
461
+ if (path === null || event.dataTransfer.getData(entryDragType) !== entry.path) return;
462
+ void run(async () => {
463
+ let moved = false;
464
+ try {
465
+ await write(path, (destination, guard) => moveExplorerEntry(directory, entry, destination, path, guard));
466
+ moved = true;
467
+ } finally {
468
+ if (mounted.current) forget(entry.path);
469
+ await reread(parentPath(entry.path));
470
+ await reread(path, moved);
471
+ await git?.refresh();
472
+ }
473
+ });
474
+ };
408
475
  const acceptsFiles = (event: React.DragEvent) => Boolean(mutate && event.dataTransfer.types.includes('Files'));
409
476
  const drop = (event: React.DragEvent<HTMLDivElement>) => {
477
+ if (move && event.dataTransfer.types.includes(entryDragType)) return dropMove(event, move.entry);
410
478
  if (!acceptsFiles(event)) return;
411
479
  event.preventDefault();
412
480
  event.stopPropagation();
@@ -456,17 +524,22 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
456
524
  };
457
525
  const submitFileAction = (name: string) => {
458
526
  if (!dialog) return;
459
- const {entry, rename} = dialog;
527
+ const {entry, action} = dialog;
460
528
  setDialog(undefined);
461
- if (rename && entry.name === name) return;
529
+ if (action === 'rename' && entry.name === name) return;
462
530
  void run(async () => {
463
- const parent = parentPath(entry.path);
531
+ const parent = action === 'createFolder' ? entry.path : parentPath(entry.path);
532
+ let changed = false;
464
533
  try {
465
- await write(parent, (handle, guard) => rename ? renameExplorerEntry(handle, entry, name, guard) :
466
- deleteExplorerEntry(handle, entry, guard));
534
+ await write(parent, (handle, guard) => {
535
+ if (action === 'createFolder') return createExplorerDirectory(handle, name, guard);
536
+ if (action === 'rename') return renameExplorerEntry(handle, entry, name, guard);
537
+ return deleteExplorerEntry(handle, entry, guard);
538
+ });
539
+ changed = true;
467
540
  } finally {
468
- if (mounted.current) forget(entry.path);
469
- await reread(parent);
541
+ if (mounted.current && action !== 'createFolder') forget(entry.path);
542
+ await reread(parent, action === 'createFolder' && changed);
470
543
  await git?.refresh();
471
544
  }
472
545
  });
@@ -488,6 +561,8 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
488
561
  folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
489
562
  const accessibleName = [item.getItemName(), unsaved && message.unsaved, status?.staged && message.staged,
490
563
  status?.revision && message.revisions[status.revision], markLabel, description].filter(Boolean).join(message.separator);
564
+ const moveDestination = entry?.kind === 'directory' && move?.destinations.has(entry.path);
565
+ const moveActive = moveDestination && drag === entry.path;
491
566
  const rows = [
492
567
  <button {...itemProps} key={item.getId()} type="button" aria-label={accessibleName}
493
568
  className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
@@ -495,6 +570,12 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
495
570
  title={unsaved || status?.staged || status?.revision ? accessibleName : undefined}
496
571
  data-drop-directory={entry?.kind === 'directory' ? entry.path : entry ? parentPath(entry.path) : undefined}
497
572
  data-drop-active={entry?.kind === 'directory' && drag === entry.path ? '' : undefined}
573
+ data-move-directory={entry?.kind === 'directory' ? entry.path : undefined}
574
+ data-move-unavailable={move && !moveDestination ? '' : undefined}
575
+ data-move-active={moveActive ? '' : undefined}
576
+ draggable={entry && mutate ? !working : undefined}
577
+ onDragStart={entry && mutate ? event => startMove(event, entry) : undefined}
578
+ onDragEnd={entry && mutate ? endMove : undefined}
498
579
  aria-haspopup={entry && (mutate || git) ? 'menu' : undefined}
499
580
  onContextMenu={entry ? event => showMenu(event, entry) : undefined}
500
581
  onKeyDown={entry ? event => {
@@ -522,6 +603,14 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
522
603
  <div className={`${prefix}${mutate ? ` ${prefix}-drop` : ''}`}
523
604
  data-drop-active={drag === '' ? '' : undefined} onDrop={drop}
524
605
  onDragOver={event => {
606
+ if (move && event.dataTransfer.types.includes(entryDragType)) {
607
+ const path = running.current ? null : moveDropPath(event.target);
608
+ event.stopPropagation();
609
+ if (path !== null) event.preventDefault();
610
+ event.dataTransfer.dropEffect = path === null ? 'none' : 'move';
611
+ setDrag(path);
612
+ return;
613
+ }
525
614
  if (!acceptsFiles(event)) return;
526
615
  event.preventDefault();
527
616
  event.stopPropagation();
@@ -542,9 +631,12 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
542
631
  {feedback || actions.working}
543
632
  </div> : null}
544
633
  {menu ? <ExplorerMenu anchor={menu.anchor} label={actions.actions} close={closeMenu} actions={[
634
+ ...(mutate && menu.entry.kind === 'directory' ? [
635
+ {label: actions.createFolder, run: () => {closeMenu(false); setDialog({...menu, action: 'createFolder'});}}
636
+ ] : []),
545
637
  ...(mutate ? [
546
- {label: actions.rename, run: () => {closeMenu(false); setDialog({...menu, rename: true});}},
547
- {label: actions.delete, run: () => {closeMenu(false); setDialog({...menu, rename: false});}}
638
+ {label: actions.rename, run: () => {closeMenu(false); setDialog({...menu, action: 'rename'});}},
639
+ {label: actions.delete, run: () => {closeMenu(false); setDialog({...menu, action: 'delete'});}}
548
640
  ] : []),
549
641
  ...(git ? (['stage', 'unstage'] as const).map(kind => ({label: actions[kind], run: () => {
550
642
  closeMenu(true);
@@ -555,7 +647,7 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
555
647
  }})) : [])
556
648
  ]} /> : null}
557
649
  {dialog ? <ExplorerFileDialog anchor={dialog.anchor} name={dialog.entry.name} folder={dialog.entry.kind === 'directory'}
558
- rename={dialog.rename} message={actions} close={() => setDialog(undefined)} submit={submitFileAction} /> : null}
650
+ action={dialog.action} message={actions} close={() => setDialog(undefined)} submit={submitFileAction} /> : null}
559
651
  </div>
560
652
  );
561
653
  }
@@ -568,7 +660,7 @@ const keyFor = (directory: FileSystemDirectoryHandle) => {
568
660
  };
569
661
 
570
662
  /**
571
- * A read-only tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
663
+ * A tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
572
664
  * sort before files, and `.git` is hidden. Keyboard: arrow keys, Home and End move and expand; Enter or Space opens a
573
665
  * file. Needs React 16.14–18 from the host.
574
666
  */