@kubohiroya/turbowarp-plus-editor-project-folder 0.9.0 → 0.9.2
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.
- package/dist/create-folder.d.ts +4 -1
- package/dist/explorer-files.d.ts +10 -2
- package/dist/explorer-menu.d.ts +7 -3
- package/dist/explorer.d.ts +6 -3
- package/dist/explorer.js +222 -63
- package/dist/index.d.ts +3 -2
- package/dist/index.js +22 -102
- package/dist/session.d.ts +4 -1
- package/dist/{shared-kI7qYraF.js → shared-Dco5rGKE.js} +1 -1
- package/dist/{shared-JdaDvk2R.js → shared-Dz9dzxQF.js} +186 -1
- package/package.json +1 -1
- package/src/create-folder.ts +118 -46
- package/src/explorer-files.ts +37 -7
- package/src/explorer-menu.tsx +17 -7
- package/src/explorer.tsx +155 -28
- package/src/index.ts +13 -4
- package/src/session.ts +8 -3
package/src/explorer-files.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
|
134
|
-
const copy = await copyEntry(
|
|
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(
|
|
169
|
+
await removeIncompleteCopy(destination, name);
|
|
140
170
|
throw error;
|
|
141
171
|
}
|
|
142
172
|
try {
|
package/src/explorer-menu.tsx
CHANGED
|
@@ -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,
|
|
91
|
-
anchor: MenuAnchor; name: string; folder: boolean;
|
|
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
|
-
{
|
|
118
|
-
<
|
|
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
|
@@ -3,13 +3,14 @@ import {asyncDataLoaderFeature, hotkeysCoreFeature, selectionFeature} from '@hea
|
|
|
3
3
|
import type {ItemInstance} from '@headless-tree/core';
|
|
4
4
|
import {useTree} from '@headless-tree/react/react17';
|
|
5
5
|
import {FolderError, isObject, manifestFile, projectFile} from './source.js';
|
|
6
|
+
import {projectFolderOverwriteWarning} from './create-folder.js';
|
|
6
7
|
import {followProjectFolder} from './folder-registry.js';
|
|
7
8
|
import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
|
|
8
9
|
import type {Json, Project} from './source.js';
|
|
9
|
-
import {
|
|
10
|
-
resolveExplorerDirectory} from './explorer-files.js';
|
|
10
|
+
import {canMoveExplorerEntry, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
|
|
11
|
+
explorerNameAvailable, moveExplorerEntry, parentPath, renameExplorerEntry, resolveExplorerDirectory} from './explorer-files.js';
|
|
11
12
|
import {actionCss, actionMessages, ExplorerFileDialog, ExplorerMenu} from './explorer-menu.js';
|
|
12
|
-
import type {MenuAnchor} from './explorer-menu.js';
|
|
13
|
+
import type {FileAction, MenuAnchor} from './explorer-menu.js';
|
|
13
14
|
import {createFilePreview} from './file-preview.js';
|
|
14
15
|
import type {FilePreviewRequest, ReadFileBaseline} from './file-preview.js';
|
|
15
16
|
|
|
@@ -52,6 +53,8 @@ const messages = {
|
|
|
52
53
|
en: {
|
|
53
54
|
label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.',
|
|
54
55
|
noFolder: 'Open a project folder to show its files here.', open: 'Open Project Folder…',
|
|
56
|
+
create: 'Create Project Folder', creating: 'Creating project folder…',
|
|
57
|
+
createFailed: 'Could not create the project folder.',
|
|
55
58
|
unavailable: 'File tabs are unavailable in this editor layout.',
|
|
56
59
|
failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
|
|
57
60
|
separator: ', ',
|
|
@@ -68,6 +71,8 @@ const messages = {
|
|
|
68
71
|
ja: {
|
|
69
72
|
label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。',
|
|
70
73
|
noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
|
|
74
|
+
create: 'プロジェクトフォルダを作成', creating: 'プロジェクトフォルダを作成しています…',
|
|
75
|
+
createFailed: 'プロジェクトフォルダを作成できませんでした。',
|
|
71
76
|
unavailable: 'このエディターのレイアウトではファイルをタブで開けません。',
|
|
72
77
|
failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
|
|
73
78
|
separator: '、',
|
|
@@ -143,9 +148,11 @@ const failure = (error: unknown, message: Message) =>
|
|
|
143
148
|
message.denied : message.failed;
|
|
144
149
|
|
|
145
150
|
const prefix = 'twpf-explorer';
|
|
151
|
+
const entryDragType = 'application/x-twpf-explorer-entry';
|
|
146
152
|
// Colors come from the host's text color, so the tree follows light and dark themes.
|
|
147
153
|
const css = `.${prefix}{font:inherit;color:inherit}
|
|
148
|
-
.${prefix}-item{display:
|
|
154
|
+
.${prefix}-item{display:grid;grid-template-columns:1em 20px minmax(0,1fr);align-items:center;gap:.2em .4em;
|
|
155
|
+
width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
|
|
149
156
|
padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer;white-space:nowrap}
|
|
150
157
|
.${prefix}-item:hover{background:rgba(128,128,128,.12)}
|
|
151
158
|
.${prefix}-item[aria-selected="true"]{background:rgba(128,128,128,.24)}
|
|
@@ -155,6 +162,7 @@ padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:i
|
|
|
155
162
|
.${prefix}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
|
|
156
163
|
background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50%) 0 0/8px 8px}
|
|
157
164
|
.${prefix}-icon img[hidden]{display:none}
|
|
165
|
+
.${prefix}-label{grid-column:3;display:flex;align-items:center;gap:.4em;min-width:0}
|
|
158
166
|
.${prefix}-filename{display:inline-flex;min-width:0}
|
|
159
167
|
.${prefix}-name{overflow:hidden;text-overflow:ellipsis}
|
|
160
168
|
.${prefix}-item[data-staged] .${prefix}-filename{font-weight:700}
|
|
@@ -163,7 +171,9 @@ background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50
|
|
|
163
171
|
.${prefix}-item[data-revision="merged"] .${prefix}-filename{color:#17603e;color:light-dark(#17603e,#85e3ad)}
|
|
164
172
|
.${prefix}-unsaved{flex:none}
|
|
165
173
|
.${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
|
|
166
|
-
.${prefix}-description{
|
|
174
|
+
.${prefix}-description{grid-column:3;min-width:0;padding:.2em .4em;border-radius:3px;background:rgba(128,128,128,.12);
|
|
175
|
+
color:inherit;color:color-mix(in srgb,currentColor 78%,transparent);font-size:.75em;line-height:1.4;
|
|
176
|
+
white-space:normal;overflow-wrap:anywhere}
|
|
167
177
|
.${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
|
|
168
178
|
.${prefix}-empty{padding:.5em}
|
|
169
179
|
.${prefix}-empty p{margin:0 0 .6em}
|
|
@@ -263,8 +273,9 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
263
273
|
const [loadedFolders] = React.useState(() => new Set<string>());
|
|
264
274
|
const [rootLoaded, setRootLoaded] = React.useState(false);
|
|
265
275
|
const [drag, setDrag] = React.useState<string | null>(null);
|
|
276
|
+
const [move, setMove] = React.useState<{entry: ExplorerEntry; destinations: ReadonlySet<string>}>();
|
|
266
277
|
const [menu, setMenu] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor}>();
|
|
267
|
-
const [dialog, setDialog] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor;
|
|
278
|
+
const [dialog, setDialog] = React.useState<{entry: ExplorerEntry; anchor: MenuAnchor; action: FileAction}>();
|
|
268
279
|
const [feedback, setFeedback] = React.useState('');
|
|
269
280
|
const [working, setWorking] = React.useState(false);
|
|
270
281
|
const running = React.useRef(false);
|
|
@@ -405,8 +416,74 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
405
416
|
};
|
|
406
417
|
const dropPath = (target: EventTarget) =>
|
|
407
418
|
(target as Element).closest('[data-drop-directory]')?.getAttribute('data-drop-directory') ?? '';
|
|
419
|
+
const moveDropPath = (target: EventTarget) => {
|
|
420
|
+
const row = (target as Element).closest<HTMLButtonElement>(`.${prefix}-item`);
|
|
421
|
+
const path = row ? row.getAttribute('data-move-directory') : '';
|
|
422
|
+
return path !== null && move?.destinations.has(path) ? path : null;
|
|
423
|
+
};
|
|
424
|
+
const startMove = (event: React.DragEvent<HTMLButtonElement>, entry: ExplorerEntry) => {
|
|
425
|
+
if (running.current || dialog) {
|
|
426
|
+
event.preventDefault();
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
event.stopPropagation();
|
|
430
|
+
setMenu(undefined);
|
|
431
|
+
setDrag(null);
|
|
432
|
+
event.dataTransfer.effectAllowed = 'move';
|
|
433
|
+
event.dataTransfer.setData(entryDragType, entry.path);
|
|
434
|
+
const row = event.currentTarget;
|
|
435
|
+
const document = row.ownerDocument;
|
|
436
|
+
const image = document.createElement('div');
|
|
437
|
+
image.className = `${prefix}-drag-image`;
|
|
438
|
+
const icon = row.querySelector(`.${prefix}-icon`);
|
|
439
|
+
if (icon) image.appendChild(icon.cloneNode(true));
|
|
440
|
+
const name = document.createElement('span');
|
|
441
|
+
name.className = `${prefix}-name`;
|
|
442
|
+
name.textContent = entry.name;
|
|
443
|
+
image.appendChild(name);
|
|
444
|
+
document.body.appendChild(image);
|
|
445
|
+
event.dataTransfer.setDragImage(image, -12, -12);
|
|
446
|
+
document.defaultView?.requestAnimationFrame(() => image.remove());
|
|
447
|
+
|
|
448
|
+
setMove({entry, destinations: new Set()});
|
|
449
|
+
const candidates = ['', ...tree.getItems().filter(item => item.isFolder()).map(item => item.getId())];
|
|
450
|
+
void Promise.all(candidates.filter(path => canMoveExplorerEntry(entry.path, path)).map(async path => {
|
|
451
|
+
try {
|
|
452
|
+
return await explorerNameAvailable(await directoryAt(path || rootId), entry.name) ? path : null;
|
|
453
|
+
} catch {
|
|
454
|
+
return null;
|
|
455
|
+
}
|
|
456
|
+
})).then(paths => {
|
|
457
|
+
if (mounted.current) setMove(current => current?.entry === entry ?
|
|
458
|
+
{entry, destinations: new Set(paths.filter(path => path !== null))} : current);
|
|
459
|
+
});
|
|
460
|
+
};
|
|
461
|
+
const endMove = () => {
|
|
462
|
+
setMove(undefined);
|
|
463
|
+
setDrag(null);
|
|
464
|
+
};
|
|
465
|
+
const dropMove = (event: React.DragEvent<HTMLDivElement>, entry: ExplorerEntry) => {
|
|
466
|
+
event.preventDefault();
|
|
467
|
+
event.stopPropagation();
|
|
468
|
+
const path = moveDropPath(event.target);
|
|
469
|
+
endMove();
|
|
470
|
+
if (path === null || event.dataTransfer.getData(entryDragType) !== entry.path) return;
|
|
471
|
+
void run(async () => {
|
|
472
|
+
let moved = false;
|
|
473
|
+
try {
|
|
474
|
+
await write(path, (destination, guard) => moveExplorerEntry(directory, entry, destination, path, guard));
|
|
475
|
+
moved = true;
|
|
476
|
+
} finally {
|
|
477
|
+
if (mounted.current) forget(entry.path);
|
|
478
|
+
await reread(parentPath(entry.path));
|
|
479
|
+
await reread(path, moved);
|
|
480
|
+
await git?.refresh();
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
};
|
|
408
484
|
const acceptsFiles = (event: React.DragEvent) => Boolean(mutate && event.dataTransfer.types.includes('Files'));
|
|
409
485
|
const drop = (event: React.DragEvent<HTMLDivElement>) => {
|
|
486
|
+
if (move && event.dataTransfer.types.includes(entryDragType)) return dropMove(event, move.entry);
|
|
410
487
|
if (!acceptsFiles(event)) return;
|
|
411
488
|
event.preventDefault();
|
|
412
489
|
event.stopPropagation();
|
|
@@ -456,17 +533,22 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
456
533
|
};
|
|
457
534
|
const submitFileAction = (name: string) => {
|
|
458
535
|
if (!dialog) return;
|
|
459
|
-
const {entry,
|
|
536
|
+
const {entry, action} = dialog;
|
|
460
537
|
setDialog(undefined);
|
|
461
|
-
if (rename && entry.name === name) return;
|
|
538
|
+
if (action === 'rename' && entry.name === name) return;
|
|
462
539
|
void run(async () => {
|
|
463
|
-
const parent = parentPath(entry.path);
|
|
540
|
+
const parent = action === 'createFolder' ? entry.path : parentPath(entry.path);
|
|
541
|
+
let changed = false;
|
|
464
542
|
try {
|
|
465
|
-
await write(parent, (handle, guard) =>
|
|
466
|
-
|
|
543
|
+
await write(parent, (handle, guard) => {
|
|
544
|
+
if (action === 'createFolder') return createExplorerDirectory(handle, name, guard);
|
|
545
|
+
if (action === 'rename') return renameExplorerEntry(handle, entry, name, guard);
|
|
546
|
+
return deleteExplorerEntry(handle, entry, guard);
|
|
547
|
+
});
|
|
548
|
+
changed = true;
|
|
467
549
|
} finally {
|
|
468
|
-
if (mounted.current) forget(entry.path);
|
|
469
|
-
await reread(parent);
|
|
550
|
+
if (mounted.current && action !== 'createFolder') forget(entry.path);
|
|
551
|
+
await reread(parent, action === 'createFolder' && changed);
|
|
470
552
|
await git?.refresh();
|
|
471
553
|
}
|
|
472
554
|
});
|
|
@@ -488,13 +570,21 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
488
570
|
folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
|
|
489
571
|
const accessibleName = [item.getItemName(), unsaved && message.unsaved, status?.staged && message.staged,
|
|
490
572
|
status?.revision && message.revisions[status.revision], markLabel, description].filter(Boolean).join(message.separator);
|
|
573
|
+
const moveDestination = entry?.kind === 'directory' && move?.destinations.has(entry.path);
|
|
574
|
+
const moveActive = moveDestination && drag === entry.path;
|
|
491
575
|
const rows = [
|
|
492
576
|
<button {...itemProps} key={item.getId()} type="button" aria-label={accessibleName}
|
|
493
577
|
className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
|
|
494
578
|
data-path={data?.path} data-staged={status?.staged ? '' : undefined} data-revision={status?.revision}
|
|
495
|
-
title={
|
|
579
|
+
title={accessibleName || undefined}
|
|
496
580
|
data-drop-directory={entry?.kind === 'directory' ? entry.path : entry ? parentPath(entry.path) : undefined}
|
|
497
581
|
data-drop-active={entry?.kind === 'directory' && drag === entry.path ? '' : undefined}
|
|
582
|
+
data-move-directory={entry?.kind === 'directory' ? entry.path : undefined}
|
|
583
|
+
data-move-unavailable={move && !moveDestination ? '' : undefined}
|
|
584
|
+
data-move-active={moveActive ? '' : undefined}
|
|
585
|
+
draggable={entry && mutate ? !working : undefined}
|
|
586
|
+
onDragStart={entry && mutate ? event => startMove(event, entry) : undefined}
|
|
587
|
+
onDragEnd={entry && mutate ? endMove : undefined}
|
|
498
588
|
aria-haspopup={entry && (mutate || git) ? 'menu' : undefined}
|
|
499
589
|
onContextMenu={entry ? event => showMenu(event, entry) : undefined}
|
|
500
590
|
onKeyDown={entry ? event => {
|
|
@@ -503,11 +593,13 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
503
593
|
} : itemProps.onKeyDown}>
|
|
504
594
|
<span className={`${prefix}-caret`} aria-hidden="true">{folder ? (expanded ? '▾' : '▸') : ''}</span>
|
|
505
595
|
{icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' ? readFile : undefined} /> : null}
|
|
506
|
-
<span className={`${prefix}-
|
|
507
|
-
<span className={`${prefix}-
|
|
508
|
-
|
|
596
|
+
<span className={`${prefix}-label`}>
|
|
597
|
+
<span className={`${prefix}-filename`}>
|
|
598
|
+
<span className={`${prefix}-name`}>{item.getItemName()}</span>
|
|
599
|
+
{unsaved ? <span className={`${prefix}-unsaved`} aria-hidden="true">*</span> : null}
|
|
600
|
+
</span>
|
|
601
|
+
{markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
|
|
509
602
|
</span>
|
|
510
|
-
{markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
|
|
511
603
|
{description ? <span className={`${prefix}-description`} aria-hidden="true">{description}</span> : null}
|
|
512
604
|
</button>
|
|
513
605
|
];
|
|
@@ -522,6 +614,14 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
522
614
|
<div className={`${prefix}${mutate ? ` ${prefix}-drop` : ''}`}
|
|
523
615
|
data-drop-active={drag === '' ? '' : undefined} onDrop={drop}
|
|
524
616
|
onDragOver={event => {
|
|
617
|
+
if (move && event.dataTransfer.types.includes(entryDragType)) {
|
|
618
|
+
const path = running.current ? null : moveDropPath(event.target);
|
|
619
|
+
event.stopPropagation();
|
|
620
|
+
if (path !== null) event.preventDefault();
|
|
621
|
+
event.dataTransfer.dropEffect = path === null ? 'none' : 'move';
|
|
622
|
+
setDrag(path);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
525
625
|
if (!acceptsFiles(event)) return;
|
|
526
626
|
event.preventDefault();
|
|
527
627
|
event.stopPropagation();
|
|
@@ -542,9 +642,12 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
542
642
|
{feedback || actions.working}
|
|
543
643
|
</div> : null}
|
|
544
644
|
{menu ? <ExplorerMenu anchor={menu.anchor} label={actions.actions} close={closeMenu} actions={[
|
|
645
|
+
...(mutate && menu.entry.kind === 'directory' ? [
|
|
646
|
+
{label: actions.createFolder, run: () => {closeMenu(false); setDialog({...menu, action: 'createFolder'});}}
|
|
647
|
+
] : []),
|
|
545
648
|
...(mutate ? [
|
|
546
|
-
{label: actions.rename, run: () => {closeMenu(false); setDialog({...menu,
|
|
547
|
-
{label: actions.delete, run: () => {closeMenu(false); setDialog({...menu,
|
|
649
|
+
{label: actions.rename, run: () => {closeMenu(false); setDialog({...menu, action: 'rename'});}},
|
|
650
|
+
{label: actions.delete, run: () => {closeMenu(false); setDialog({...menu, action: 'delete'});}}
|
|
548
651
|
] : []),
|
|
549
652
|
...(git ? (['stage', 'unstage'] as const).map(kind => ({label: actions[kind], run: () => {
|
|
550
653
|
closeMenu(true);
|
|
@@ -555,7 +658,7 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
555
658
|
}})) : [])
|
|
556
659
|
]} /> : null}
|
|
557
660
|
{dialog ? <ExplorerFileDialog anchor={dialog.anchor} name={dialog.entry.name} folder={dialog.entry.kind === 'directory'}
|
|
558
|
-
|
|
661
|
+
action={dialog.action} message={actions} close={() => setDialog(undefined)} submit={submitFileAction} /> : null}
|
|
559
662
|
</div>
|
|
560
663
|
);
|
|
561
664
|
}
|
|
@@ -568,7 +671,7 @@ const keyFor = (directory: FileSystemDirectoryHandle) => {
|
|
|
568
671
|
};
|
|
569
672
|
|
|
570
673
|
/**
|
|
571
|
-
* A
|
|
674
|
+
* A tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
|
|
572
675
|
* sort before files, and `.git` is hidden. Keyboard: arrow keys, Home and End move and expand; Enter or Space opens a
|
|
573
676
|
* file. Needs React 16.14–18 from the host.
|
|
574
677
|
*/
|
|
@@ -585,6 +688,8 @@ export type FollowFileStatuses = (directory: FileSystemDirectoryHandle,
|
|
|
585
688
|
type FolderViewProps = {
|
|
586
689
|
vm: object;
|
|
587
690
|
locale?: string;
|
|
691
|
+
/** Saves the current project to a local folder. */
|
|
692
|
+
createFolder?(): Promise<unknown>;
|
|
588
693
|
marks?: FollowMarks;
|
|
589
694
|
fileStatuses?: FollowFileStatuses;
|
|
590
695
|
git?: FollowExplorerGit;
|
|
@@ -599,8 +704,22 @@ const readJson = async (directory: FileSystemDirectoryHandle, name: string): Pro
|
|
|
599
704
|
JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
|
|
600
705
|
|
|
601
706
|
function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: followStatuses, git: followGit,
|
|
602
|
-
openFile, readBaseline}: FolderViewProps) {
|
|
707
|
+
openFile, readBaseline, createFolder}: FolderViewProps) {
|
|
603
708
|
const message = messagesFor(locale);
|
|
709
|
+
const [creating, setCreating] = React.useState(false);
|
|
710
|
+
const [createError, setCreateError] = React.useState('');
|
|
711
|
+
const create = async () => {
|
|
712
|
+
if (!createFolder || creating) return;
|
|
713
|
+
setCreating(true);
|
|
714
|
+
setCreateError('');
|
|
715
|
+
try {
|
|
716
|
+
await createFolder();
|
|
717
|
+
} catch {
|
|
718
|
+
setCreateError(message.createFailed);
|
|
719
|
+
} finally {
|
|
720
|
+
setCreating(false);
|
|
721
|
+
}
|
|
722
|
+
};
|
|
604
723
|
const [{folder, directory, version}, setFollowed] = React.useState<{
|
|
605
724
|
folder?: FollowedFolder; directory: FileSystemDirectoryHandle | null; version: number;
|
|
606
725
|
}>({directory: null, version: 0});
|
|
@@ -654,8 +773,15 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
|
|
|
654
773
|
if (!directory) {
|
|
655
774
|
return <div className={`${prefix}-empty`}>
|
|
656
775
|
<style>{css}</style>
|
|
657
|
-
|
|
658
|
-
|
|
776
|
+
{createFolder ? <>
|
|
777
|
+
<p>{projectFolderOverwriteWarning(locale)}</p>
|
|
778
|
+
<button type="button" disabled={creating} onClick={() => void create()}>{message.create}</button>
|
|
779
|
+
{creating && <p role="status">{message.creating}</p>}
|
|
780
|
+
{createError && <p role="alert">{createError}</p>}
|
|
781
|
+
</> : <>
|
|
782
|
+
<p>{message.noFolder}</p>
|
|
783
|
+
<button type="button" onClick={() => folder.open(locale)}>{message.open}</button>
|
|
784
|
+
</>}
|
|
659
785
|
</div>;
|
|
660
786
|
}
|
|
661
787
|
return <>
|
|
@@ -675,10 +801,11 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
|
|
|
675
801
|
/**
|
|
676
802
|
* Renders the explorer of the project folder open for `vm`, for a side panel of the host: its files with what each is
|
|
677
803
|
* for, and `marks` (such as the Git status) when given. It follows the folder as it opens, closes and saves; with no
|
|
678
|
-
* folder open it offers
|
|
804
|
+
* folder open it offers to create one when the host supplies a command, or to open an existing one.
|
|
805
|
+
* It renders nothing while no project folder is mounted for `vm`.
|
|
679
806
|
* Pass the same `marks` function across renders, or the marks are followed again.
|
|
680
807
|
*/
|
|
681
808
|
export function renderProjectFolderExplorer(createElement: (component: any, props: any, ...children: any[]) => any,
|
|
682
|
-
|
|
683
|
-
return createElement(FolderView,
|
|
809
|
+
props: FolderViewProps) {
|
|
810
|
+
return createElement(FolderView, props);
|
|
684
811
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {FolderError} from './source.js';
|
|
2
2
|
import {createFolderSession} from './session.js';
|
|
3
|
+
import {isProjectFolderEmpty} from './create-folder.js';
|
|
3
4
|
import {registerFolder} from './folder-registry.js';
|
|
4
5
|
import type {FolderHost, FolderVM, PickerWindow} from './session.js';
|
|
5
6
|
|
|
@@ -8,7 +9,7 @@ export type {ReloadTarget} from './block-reload.js';
|
|
|
8
9
|
export {followProjectFolder} from './folder-registry.js';
|
|
9
10
|
export type {FollowedFolder} from './folder-registry.js';
|
|
10
11
|
export type {DeserializeBlocks} from './script-reload.js';
|
|
11
|
-
export {createProjectFolder} from './create-folder.js';
|
|
12
|
+
export {createProjectFolder, projectFolderOverwriteWarning} from './create-folder.js';
|
|
12
13
|
|
|
13
14
|
const messages = {
|
|
14
15
|
en: {
|
|
@@ -262,15 +263,23 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
|
|
|
262
263
|
openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
|
|
263
264
|
session.openDirectory(...args).finally(renderReload),
|
|
264
265
|
save: () => session.save().finally(renderReload),
|
|
265
|
-
createFromSnapshot({prepareFiles, directory, current = () => true}: {
|
|
266
|
+
createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true}: {
|
|
266
267
|
prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
|
|
268
|
+
collectEdits?: () => Promise<void>;
|
|
267
269
|
directory?: FileSystemDirectoryHandle;
|
|
268
270
|
current?: () => boolean;
|
|
269
271
|
}) {
|
|
272
|
+
const message = locale.startsWith('ja') ?
|
|
273
|
+
'指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?' :
|
|
274
|
+
'The selected folder is not empty. Contents in the folder may be overwritten. Continue?';
|
|
270
275
|
return session.createFromSnapshot(async () => {
|
|
271
|
-
if (directory) return directory;
|
|
272
276
|
try {
|
|
273
|
-
|
|
277
|
+
const selected = directory ?? await pickDirectory.call(view, {id: 'turbowarp-plus-project-folder', mode: 'readwrite'});
|
|
278
|
+
if (!current()) return null;
|
|
279
|
+
const overwrite = !await isProjectFolderEmpty(selected);
|
|
280
|
+
if (!current() || (overwrite && !view.confirm(message))) return null;
|
|
281
|
+
await collectEdits?.();
|
|
282
|
+
return current() ? {directory: selected, overwrite} : null;
|
|
274
283
|
} catch (error) {
|
|
275
284
|
if (error instanceof DOMException && error.name === 'AbortError') return null;
|
|
276
285
|
throw error;
|
package/src/session.ts
CHANGED
|
@@ -417,18 +417,23 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
417
417
|
openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean): Promise<OpenResult> {
|
|
418
418
|
return openFrom(() => Promise.resolve(directory), confirmReplace);
|
|
419
419
|
},
|
|
420
|
-
createFromSnapshot(
|
|
420
|
+
createFromSnapshot(selectDestination: () => Promise<{directory: FileSystemDirectoryHandle; overwrite: boolean} | null>,
|
|
421
421
|
prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>, isCurrent: () => boolean): Promise<OpenResult> {
|
|
422
422
|
const stage = vm.runtime.getTargetForStage();
|
|
423
423
|
let savedRevision: number | undefined;
|
|
424
424
|
const currentProject = () => !disposed && vm.runtime.getTargetForStage() === stage &&
|
|
425
425
|
(savedRevision === undefined || revision === savedRevision) && isCurrent();
|
|
426
|
-
|
|
426
|
+
let overwrite = false;
|
|
427
|
+
return openFrom(async () => {
|
|
428
|
+
const destination = await selectDestination();
|
|
429
|
+
overwrite = destination?.overwrite ?? false;
|
|
430
|
+
return destination?.directory ?? null;
|
|
431
|
+
}, currentProject, async directory => {
|
|
427
432
|
if (!currentProject()) return null;
|
|
428
433
|
savedRevision = revision;
|
|
429
434
|
const files = await prepareFiles();
|
|
430
435
|
if (!currentProject()) return null;
|
|
431
|
-
return createProjectFolder({directory, files, storage: vm.runtime.storage, current: currentProject});
|
|
436
|
+
return createProjectFolder({directory, files, storage: vm.runtime.storage, overwrite, current: currentProject});
|
|
432
437
|
}, currentProject);
|
|
433
438
|
},
|
|
434
439
|
async save(): Promise<SaveResult> {
|