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

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/explorer.js CHANGED
@@ -1,474 +1,634 @@
1
- import { C as e, S as t, d as n, g as r, t as i, u as a } from "./shared-DlmcdO1_.js";
2
- import * as o from "react";
3
- import { useEffect as s, useState as c } from "react";
1
+ import { C as _asyncIterator, S as _objectSpread2, d as manifestFile, g as projectFile, r as FolderError, t as followProjectFolder, u as isObject } from "./shared-JdaDvk2R.js";
2
+ import * as React from "react";
3
+ import { useEffect, useState } from "react";
4
+ import { createPortal } from "react-dom";
4
5
  // node_modules/@headless-tree/core/dist/index.mjs
5
- var l = Object.defineProperty, u = Object.defineProperties, d = Object.getOwnPropertyDescriptors, f = Object.getOwnPropertySymbols, p = Object.prototype.hasOwnProperty, m = Object.prototype.propertyIsEnumerable, h = (e, t, n) => t in e ? l(e, t, {
6
- enumerable: !0,
7
- configurable: !0,
8
- writable: !0,
9
- value: n
10
- }) : e[t] = n, g = (e, t) => {
11
- for (var n in t || (t = {})) p.call(t, n) && h(e, n, t[n]);
12
- if (f) for (var n of f(t)) m.call(t, n) && h(e, n, t[n]);
13
- return e;
14
- }, _ = (e, t) => u(e, d(t)), v = (e, t, n) => new Promise((r, i) => {
15
- var a = (e) => {
16
- try {
17
- s(n.next(e));
18
- } catch (e) {
19
- i(e);
20
- }
21
- }, o = (e) => {
22
- try {
23
- s(n.throw(e));
24
- } catch (e) {
25
- i(e);
26
- }
27
- }, s = (e) => e.done ? r(e.value) : Promise.resolve(e.value).then(a, o);
28
- s((n = n.apply(e, t)).next());
29
- });
30
- function y(e, t) {
31
- return typeof e == "function" ? e(t) : e;
6
+ var __defProp$1 = Object.defineProperty;
7
+ var __defProps$1 = Object.defineProperties;
8
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
9
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
10
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
13
+ enumerable: true,
14
+ configurable: true,
15
+ writable: true,
16
+ value
17
+ }) : obj[key] = value;
18
+ var __spreadValues$1 = (a, b) => {
19
+ for (var prop in b || (b = {})) if (__hasOwnProp$1.call(b, prop)) __defNormalProp$1(a, prop, b[prop]);
20
+ if (__getOwnPropSymbols$1) {
21
+ for (var prop of __getOwnPropSymbols$1(b)) if (__propIsEnum$1.call(b, prop)) __defNormalProp$1(a, prop, b[prop]);
22
+ }
23
+ return a;
24
+ };
25
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
26
+ var __async = (__this, __arguments, generator) => {
27
+ return new Promise((resolve, reject) => {
28
+ var fulfilled = (value) => {
29
+ try {
30
+ step(generator.next(value));
31
+ } catch (e) {
32
+ reject(e);
33
+ }
34
+ };
35
+ var rejected = (value) => {
36
+ try {
37
+ step(generator.throw(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
43
+ step((generator = generator.apply(__this, __arguments)).next());
44
+ });
45
+ };
46
+ function functionalUpdate(updater, input) {
47
+ return typeof updater === "function" ? updater(input) : updater;
32
48
  }
33
- function b(e, t) {
34
- return (n) => {
35
- t.setState((t) => _(g({}, t), { [e]: y(n, t[e]) }));
49
+ function makeStateUpdater(key, instance) {
50
+ return (updater) => {
51
+ instance.setState((old) => {
52
+ return __spreadProps$1(__spreadValues$1({}, old), { [key]: functionalUpdate(updater, old[key]) });
53
+ });
36
54
  };
37
55
  }
38
- var x = (e, t = 100, n = 1e3) => new Promise((r) => {
39
- let i, a = setInterval(() => {
40
- e() && (r(), clearInterval(a), clearTimeout(i));
41
- }, t);
42
- i = setTimeout(() => {
43
- clearInterval(a), r();
44
- }, n);
45
- }), S = "Headless Tree: ", C = (e) => Error(S + e), w = (e) => console.warn(S + e), T = {
56
+ var poll = (fn, interval = 100, timeout = 1e3) => new Promise((resolve) => {
57
+ let clear;
58
+ const i = setInterval(() => {
59
+ if (fn()) {
60
+ resolve();
61
+ clearInterval(i);
62
+ clearTimeout(clear);
63
+ }
64
+ }, interval);
65
+ clear = setTimeout(() => {
66
+ clearInterval(i);
67
+ resolve();
68
+ }, timeout);
69
+ });
70
+ var prefix$1 = "Headless Tree: ";
71
+ var throwError = (message) => Error(prefix$1 + message);
72
+ var logWarning = (message) => console.warn(prefix$1 + message);
73
+ var treeFeature = {
46
74
  key: "tree",
47
- getInitialState: (e) => g({
75
+ getInitialState: (initialState) => __spreadValues$1({
48
76
  expandedItems: [],
49
77
  focusedItem: null
50
- }, e),
51
- getDefaultConfig: (e, t) => g({
52
- setExpandedItems: b("expandedItems", t),
53
- setFocusedItem: b("focusedItem", t)
54
- }, e),
78
+ }, initialState),
79
+ getDefaultConfig: (defaultConfig, tree) => __spreadValues$1({
80
+ setExpandedItems: makeStateUpdater("expandedItems", tree),
81
+ setFocusedItem: makeStateUpdater("focusedItem", tree)
82
+ }, defaultConfig),
55
83
  stateHandlerNames: {
56
84
  expandedItems: "setExpandedItems",
57
85
  focusedItem: "setFocusedItem"
58
86
  },
59
87
  treeInstance: {
60
- getItemsMeta: ({ tree: e }) => {
61
- let { rootItemId: t } = e.getConfig(), { expandedItems: n } = e.getState(), r = [], i = new Set(n), a = (t, n, o, s, c) => {
62
- var l;
63
- if (n.includes(t)) w(`Circular reference for ${n.join(".")}`);
64
- else if (r.push({
65
- itemId: t,
66
- level: o,
67
- index: r.length,
68
- parentId: n.at(-1),
69
- setSize: s,
70
- posInSet: c
71
- }), i.has(t)) {
72
- let r = (l = e.retrieveChildrenIds(t)) == null ? [] : l, i = 0;
73
- for (let e of r) a(e, n.concat(t), o + 1, r.length, i++);
88
+ getItemsMeta: ({ tree }) => {
89
+ const { rootItemId } = tree.getConfig();
90
+ const { expandedItems } = tree.getState();
91
+ const flatItems = [];
92
+ const expandedItemsSet = new Set(expandedItems);
93
+ const recursiveAdd = (itemId, path, level, setSize, posInSet) => {
94
+ var _a;
95
+ if (path.includes(itemId)) {
96
+ logWarning(`Circular reference for ${path.join(".")}`);
97
+ return;
98
+ }
99
+ flatItems.push({
100
+ itemId,
101
+ level,
102
+ index: flatItems.length,
103
+ parentId: path.at(-1),
104
+ setSize,
105
+ posInSet
106
+ });
107
+ if (expandedItemsSet.has(itemId)) {
108
+ const children2 = (_a = tree.retrieveChildrenIds(itemId)) != null ? _a : [];
109
+ let i2 = 0;
110
+ for (const childId of children2) recursiveAdd(childId, path.concat(itemId), level + 1, children2.length, i2++);
74
111
  }
75
- }, o = e.retrieveChildrenIds(t), s = 0;
76
- for (let e of o) a(e, [t], 0, o.length, s++);
77
- return r;
112
+ };
113
+ const children = tree.retrieveChildrenIds(rootItemId);
114
+ let i = 0;
115
+ for (const itemId of children) recursiveAdd(itemId, [rootItemId], 0, children.length, i++);
116
+ return flatItems;
78
117
  },
79
- getFocusedItem: ({ tree: e }) => {
80
- var t;
81
- let n = e.getState().focusedItem;
82
- return (t = n === null ? null : e.getItemInstance(n)) == null ? e.getItems()[0] : t;
118
+ getFocusedItem: ({ tree }) => {
119
+ var _a;
120
+ const focusedItemId = tree.getState().focusedItem;
121
+ return (_a = focusedItemId !== null ? tree.getItemInstance(focusedItemId) : null) != null ? _a : tree.getItems()[0];
83
122
  },
84
- getRootItem: ({ tree: e }) => {
85
- let { rootItemId: t } = e.getConfig();
86
- return e.getItemInstance(t);
123
+ getRootItem: ({ tree }) => {
124
+ const { rootItemId } = tree.getConfig();
125
+ return tree.getItemInstance(rootItemId);
87
126
  },
88
- focusNextItem: ({ tree: e }) => {
89
- var t;
90
- let n = e.getFocusedItem().getItemMeta();
91
- if (!n) return;
92
- let r = Math.min(n.index + 1, e.getItems().length - 1);
93
- (t = e.getItems()[r]) == null || t.setFocused();
127
+ focusNextItem: ({ tree }) => {
128
+ var _a;
129
+ const focused = tree.getFocusedItem().getItemMeta();
130
+ if (!focused) return;
131
+ const nextIndex = Math.min(focused.index + 1, tree.getItems().length - 1);
132
+ (_a = tree.getItems()[nextIndex]) == null || _a.setFocused();
94
133
  },
95
- focusPreviousItem: ({ tree: e }) => {
96
- var t;
97
- let n = e.getFocusedItem().getItemMeta();
98
- if (!n) return;
99
- let r = Math.max(n.index - 1, 0);
100
- (t = e.getItems()[r]) == null || t.setFocused();
134
+ focusPreviousItem: ({ tree }) => {
135
+ var _a;
136
+ const focused = tree.getFocusedItem().getItemMeta();
137
+ if (!focused) return;
138
+ const nextIndex = Math.max(focused.index - 1, 0);
139
+ (_a = tree.getItems()[nextIndex]) == null || _a.setFocused();
101
140
  },
102
- updateDomFocus: ({ tree: e }) => {
103
- setTimeout(() => v(null, null, function* () {
104
- var t, n, r, i, a;
105
- let o = e.getFocusedItem();
106
- (n = (t = e.getConfig()).scrollToItem) == null || n.call(t, o), yield x(() => o.getElement() !== null, 20, 500);
107
- let s = o.getElement();
108
- s ? s.focus() : ((r = e.getItems()[0]) == null || r.setFocused(), (a = (i = e.getItems()[0]) == null ? void 0 : i.getElement()) == null || a.focus());
141
+ updateDomFocus: ({ tree }) => {
142
+ setTimeout(() => __async(null, null, function* () {
143
+ var _a, _b, _c, _d, _e;
144
+ const focusedItem = tree.getFocusedItem();
145
+ (_b = (_a = tree.getConfig()).scrollToItem) == null || _b.call(_a, focusedItem);
146
+ yield poll(() => focusedItem.getElement() !== null, 20, 500);
147
+ const focusedElement = focusedItem.getElement();
148
+ if (!focusedElement) {
149
+ (_c = tree.getItems()[0]) == null || _c.setFocused();
150
+ (_e = (_d = tree.getItems()[0]) == null ? void 0 : _d.getElement()) == null || _e.focus();
151
+ return;
152
+ }
153
+ focusedElement.focus();
109
154
  }));
110
155
  },
111
- getContainerProps: ({ prev: e, tree: t }, n) => _(g({}, e == null ? void 0 : e()), {
156
+ getContainerProps: ({ prev, tree }, treeLabel) => __spreadProps$1(__spreadValues$1({}, prev == null ? void 0 : prev()), {
112
157
  role: "tree",
113
- "aria-label": n == null ? "" : n,
114
- ref: t.registerElement
158
+ "aria-label": treeLabel != null ? treeLabel : "",
159
+ ref: tree.registerElement
115
160
  }),
116
- isSearchOpen: () => !1
161
+ isSearchOpen: () => false
117
162
  },
118
163
  itemInstance: {
119
- scrollTo: (e, t) => v(null, [e, t], function* ({ tree: e, item: t }, n) {
120
- var r, i, a;
121
- (i = (r = e.getConfig()).scrollToItem) == null || i.call(r, t), yield x(() => t.getElement() !== null, 20), (a = t.getElement()) == null || a.scrollIntoView(n);
164
+ scrollTo: (_0, _1) => __async(null, [_0, _1], function* ({ tree, item }, scrollIntoViewArg) {
165
+ var _a, _b, _c;
166
+ (_b = (_a = tree.getConfig()).scrollToItem) == null || _b.call(_a, item);
167
+ yield poll(() => item.getElement() !== null, 20);
168
+ (_c = item.getElement()) == null || _c.scrollIntoView(scrollIntoViewArg);
122
169
  }),
123
- getId: ({ itemId: e }) => e,
124
- getKey: ({ itemId: e }) => e,
125
- getProps: ({ item: e, prev: t }) => {
126
- let n = e.getItemMeta();
127
- return _(g({}, t == null ? void 0 : t()), {
128
- ref: e.registerElement,
170
+ getId: ({ itemId }) => itemId,
171
+ getKey: ({ itemId }) => itemId,
172
+ getProps: ({ item, prev }) => {
173
+ const itemMeta = item.getItemMeta();
174
+ return __spreadProps$1(__spreadValues$1({}, prev == null ? void 0 : prev()), {
175
+ ref: item.registerElement,
129
176
  role: "treeitem",
130
- "aria-setsize": n.setSize,
131
- "aria-posinset": n.posInSet + 1,
177
+ "aria-setsize": itemMeta.setSize,
178
+ "aria-posinset": itemMeta.posInSet + 1,
132
179
  "aria-selected": "false",
133
- "aria-label": e.getItemName(),
134
- "aria-level": n.level + 1,
135
- "aria-expanded": e.isFolder() ? e.isExpanded() : void 0,
136
- tabIndex: e.isFocused() ? 0 : -1,
137
- onClick: (t) => {
138
- e.setFocused(), e.primaryAction(), t.ctrlKey || t.shiftKey || t.metaKey || e.isFolder() && (e.isExpanded() ? e.collapse() : e.expand());
180
+ "aria-label": item.getItemName(),
181
+ "aria-level": itemMeta.level + 1,
182
+ "aria-expanded": item.isFolder() ? item.isExpanded() : void 0,
183
+ tabIndex: item.isFocused() ? 0 : -1,
184
+ onClick: (e) => {
185
+ item.setFocused();
186
+ item.primaryAction();
187
+ if (e.ctrlKey || e.shiftKey || e.metaKey) return;
188
+ if (!item.isFolder()) return;
189
+ if (item.isExpanded()) item.collapse();
190
+ else item.expand();
139
191
  }
140
192
  });
141
193
  },
142
- expand: ({ tree: e, item: t, itemId: n }) => {
143
- var r;
144
- t.isFolder() && ((r = e.getState().loadingItemChildrens) != null && r.includes(n) || (e.applySubStateUpdate("expandedItems", (e) => [...e, n]), e.rebuildTree()));
194
+ expand: ({ tree, item, itemId }) => {
195
+ var _a;
196
+ if (!item.isFolder()) return;
197
+ if ((_a = tree.getState().loadingItemChildrens) == null ? void 0 : _a.includes(itemId)) return;
198
+ tree.applySubStateUpdate("expandedItems", (expandedItems) => [...expandedItems, itemId]);
199
+ tree.rebuildTree();
200
+ },
201
+ collapse: ({ tree, item, itemId }) => {
202
+ if (!item.isFolder()) return;
203
+ tree.applySubStateUpdate("expandedItems", (expandedItems) => expandedItems.filter((id) => id !== itemId));
204
+ tree.rebuildTree();
145
205
  },
146
- collapse: ({ tree: e, item: t, itemId: n }) => {
147
- t.isFolder() && (e.applySubStateUpdate("expandedItems", (e) => e.filter((e) => e !== n)), e.rebuildTree());
206
+ getItemData: ({ tree, itemId }) => tree.retrieveItemData(itemId),
207
+ equals: ({ item }, other) => item.getId() === (other == null ? void 0 : other.getId()),
208
+ isExpanded: ({ tree, itemId }) => tree.getState().expandedItems.includes(itemId),
209
+ isDescendentOf: ({ item }, parentId) => {
210
+ const parent = item.getParent();
211
+ return Boolean((parent == null ? void 0 : parent.getId()) === parentId || (parent == null ? void 0 : parent.isDescendentOf(parentId)));
148
212
  },
149
- getItemData: ({ tree: e, itemId: t }) => e.retrieveItemData(t),
150
- equals: ({ item: e }, t) => e.getId() === (t == null ? void 0 : t.getId()),
151
- isExpanded: ({ tree: e, itemId: t }) => e.getState().expandedItems.includes(t),
152
- isDescendentOf: ({ item: e }, t) => {
153
- let n = e.getParent();
154
- return !!((n == null ? void 0 : n.getId()) === t || n != null && n.isDescendentOf(t));
213
+ isFocused: ({ tree, item, itemId }) => tree.getState().focusedItem === itemId || tree.getState().focusedItem === null && item.getItemMeta().index === 0,
214
+ isFolder: ({ tree, item, itemId }) => itemId === tree.getConfig().rootItemId || tree.getConfig().isItemFolder(item),
215
+ getItemName: ({ tree, item }) => {
216
+ return tree.getConfig().getItemName(item);
155
217
  },
156
- isFocused: ({ tree: e, item: t, itemId: n }) => e.getState().focusedItem === n || e.getState().focusedItem === null && t.getItemMeta().index === 0,
157
- isFolder: ({ tree: e, item: t, itemId: n }) => n === e.getConfig().rootItemId || e.getConfig().isItemFolder(t),
158
- getItemName: ({ tree: e, item: t }) => e.getConfig().getItemName(t),
159
- setFocused: ({ tree: e, itemId: t }) => {
160
- e.applySubStateUpdate("focusedItem", t);
218
+ setFocused: ({ tree, itemId }) => {
219
+ tree.applySubStateUpdate("focusedItem", itemId);
161
220
  },
162
- primaryAction: ({ tree: e, item: t }) => {
163
- var n, r;
164
- return (r = (n = e.getConfig()).onPrimaryAction) == null ? void 0 : r.call(n, t);
221
+ primaryAction: ({ tree, item }) => {
222
+ var _a, _b;
223
+ return (_b = (_a = tree.getConfig()).onPrimaryAction) == null ? void 0 : _b.call(_a, item);
165
224
  },
166
- getParent: ({ tree: e, item: t }) => t.getItemMeta().parentId ? e.getItemInstance(t.getItemMeta().parentId) : void 0,
167
- getIndexInParent: ({ item: e }) => e.getItemMeta().posInSet,
168
- getChildren: ({ tree: e, itemId: t }) => e.retrieveChildrenIds(t).map((t) => e.getItemInstance(t)),
169
- getTree: ({ tree: e }) => e,
170
- getItemAbove: ({ tree: e, item: t }) => e.getItems()[t.getItemMeta().index - 1],
171
- getItemBelow: ({ tree: e, item: t }) => e.getItems()[t.getItemMeta().index + 1]
225
+ getParent: ({ tree, item }) => item.getItemMeta().parentId ? tree.getItemInstance(item.getItemMeta().parentId) : void 0,
226
+ getIndexInParent: ({ item }) => item.getItemMeta().posInSet,
227
+ getChildren: ({ tree, itemId }) => tree.retrieveChildrenIds(itemId).map((id) => tree.getItemInstance(id)),
228
+ getTree: ({ tree }) => tree,
229
+ getItemAbove: ({ tree, item }) => tree.getItems()[item.getItemMeta().index - 1],
230
+ getItemBelow: ({ tree, item }) => tree.getItems()[item.getItemMeta().index + 1]
172
231
  },
173
232
  hotkeys: {
174
233
  focusNextItem: {
175
234
  hotkey: "ArrowDown",
176
- canRepeat: !0,
177
- preventDefault: !0,
178
- isEnabled: (e) => {
179
- var t, n;
180
- return !((n = (t = e.isSearchOpen) == null ? void 0 : t.call(e)) != null && n) && !e.getState().dnd;
235
+ canRepeat: true,
236
+ preventDefault: true,
237
+ isEnabled: (tree) => {
238
+ var _a, _b;
239
+ return !((_b = (_a = tree.isSearchOpen) == null ? void 0 : _a.call(tree)) != null ? _b : false) && !tree.getState().dnd;
181
240
  },
182
- handler: (e, t) => {
183
- t.focusNextItem(), t.updateDomFocus();
241
+ handler: (e, tree) => {
242
+ tree.focusNextItem();
243
+ tree.updateDomFocus();
184
244
  }
185
245
  },
186
246
  focusPreviousItem: {
187
247
  hotkey: "ArrowUp",
188
- canRepeat: !0,
189
- preventDefault: !0,
190
- isEnabled: (e) => {
191
- var t, n;
192
- return !((n = (t = e.isSearchOpen) == null ? void 0 : t.call(e)) != null && n) && !e.getState().dnd;
248
+ canRepeat: true,
249
+ preventDefault: true,
250
+ isEnabled: (tree) => {
251
+ var _a, _b;
252
+ return !((_b = (_a = tree.isSearchOpen) == null ? void 0 : _a.call(tree)) != null ? _b : false) && !tree.getState().dnd;
193
253
  },
194
- handler: (e, t) => {
195
- t.focusPreviousItem(), t.updateDomFocus();
254
+ handler: (e, tree) => {
255
+ tree.focusPreviousItem();
256
+ tree.updateDomFocus();
196
257
  }
197
258
  },
198
259
  expandOrDown: {
199
260
  hotkey: "ArrowRight",
200
- canRepeat: !0,
201
- handler: (e, t) => {
202
- let n = t.getFocusedItem();
203
- n.isExpanded() || !n.isFolder() ? (t.focusNextItem(), t.updateDomFocus()) : n.expand();
261
+ canRepeat: true,
262
+ handler: (e, tree) => {
263
+ const item = tree.getFocusedItem();
264
+ if (item.isExpanded() || !item.isFolder()) {
265
+ tree.focusNextItem();
266
+ tree.updateDomFocus();
267
+ } else item.expand();
204
268
  }
205
269
  },
206
270
  collapseOrUp: {
207
271
  hotkey: "ArrowLeft",
208
- canRepeat: !0,
209
- handler: (e, t) => {
210
- var n;
211
- let r = t.getFocusedItem();
212
- (!r.isExpanded() || !r.isFolder()) && r.getItemMeta().level !== 0 ? ((n = r.getParent()) == null || n.setFocused(), t.updateDomFocus()) : r.collapse();
272
+ canRepeat: true,
273
+ handler: (e, tree) => {
274
+ var _a;
275
+ const item = tree.getFocusedItem();
276
+ if ((!item.isExpanded() || !item.isFolder()) && item.getItemMeta().level !== 0) {
277
+ (_a = item.getParent()) == null || _a.setFocused();
278
+ tree.updateDomFocus();
279
+ } else item.collapse();
213
280
  }
214
281
  },
215
282
  focusFirstItem: {
216
283
  hotkey: "Home",
217
- handler: (e, t) => {
218
- var n;
219
- (n = t.getItems()[0]) == null || n.setFocused(), t.updateDomFocus();
284
+ handler: (e, tree) => {
285
+ var _a;
286
+ (_a = tree.getItems()[0]) == null || _a.setFocused();
287
+ tree.updateDomFocus();
220
288
  }
221
289
  },
222
290
  focusLastItem: {
223
291
  hotkey: "End",
224
- handler: (e, t) => {
225
- var n;
226
- (n = t.getItems()[t.getItems().length - 1]) == null || n.setFocused(), t.updateDomFocus();
292
+ handler: (e, tree) => {
293
+ var _a;
294
+ (_a = tree.getItems()[tree.getItems().length - 1]) == null || _a.setFocused();
295
+ tree.updateDomFocus();
227
296
  }
228
297
  }
229
298
  }
230
- }, E = (e, t, n) => {
231
- let r = {};
232
- return [r, () => {
233
- let i = n(r);
234
- featureLoop: for (let n = 0; n < e.length; n++) {
235
- let a = e[n][t];
236
- if (!a) continue featureLoop;
237
- methodLoop: for (let [e, t] of Object.entries(a)) {
238
- if (!t) continue methodLoop;
239
- let n = r[e];
240
- r[e] = (...e) => t(_(g({}, i), { prev: n }), ...e);
299
+ };
300
+ var buildStaticInstance = (features, instanceType, buildOpts) => {
301
+ const instance = {};
302
+ const finalize = () => {
303
+ const opts = buildOpts(instance);
304
+ featureLoop: for (let i = 0; i < features.length; i++) {
305
+ const definition = features[i][instanceType];
306
+ if (!definition) continue featureLoop;
307
+ methodLoop: for (const [key, method] of Object.entries(definition)) {
308
+ if (!method) continue methodLoop;
309
+ const prev = instance[key];
310
+ instance[key] = (...args) => {
311
+ return method(__spreadProps$1(__spreadValues$1({}, opts), { prev }), ...args);
312
+ };
241
313
  }
242
314
  }
243
- }];
244
- }, ee = (e) => {
245
- var t;
246
- let n = e == null ? void 0 : e.map((e) => e.key);
247
- for (let r of e == null ? [] : e) {
248
- let e = (t = r.deps) == null ? void 0 : t.find((e) => !(n != null && n.includes(e)));
249
- if (e) throw C(`${r.key} needs ${e}`);
315
+ };
316
+ return [instance, finalize];
317
+ };
318
+ var verifyFeatures = (features) => {
319
+ var _a;
320
+ const loadedFeatures = features == null ? void 0 : features.map((feature) => feature.key);
321
+ for (const feature of features != null ? features : []) {
322
+ const missingDependency = (_a = feature.deps) == null ? void 0 : _a.find((dep) => !(loadedFeatures == null ? void 0 : loadedFeatures.includes(dep)));
323
+ if (missingDependency) throw throwError(`${feature.key} needs ${missingDependency}`);
250
324
  }
251
- }, te = (e, t) => {
252
- let n = e.length;
253
- for (let r = 0; r < n; r++) for (let i = r + 1; i < n; i++) t(e[i], e[r]) < 0 && ([e[r], e[i]] = [e[i], e[r]]);
254
- return e;
255
- }, ne = (e) => (t, n) => {
256
- var r, i;
257
- return n.key && (r = t.overwrites) != null && r.includes(n.key) ? 1 : t.key && (i = n.overwrites) != null && i.includes(t.key) ? -1 : e.indexOf(t) - e.indexOf(n);
258
- }, re = (e = []) => te(e, ne(e)), ie = (e) => {
259
- var t, n, r, i;
260
- let a = (t = e.instanceBuilder) == null ? E : t, o = [T, ...re(e.features)];
261
- ee(o);
262
- let s = [...o], [c, l] = a(s, "treeInstance", (e) => ({ tree: e })), u = o.reduce((e, t) => {
263
- var n, r;
264
- return (r = (n = t.getInitialState) == null ? void 0 : n.call(t, e, c)) == null ? e : r;
265
- }, (r = (n = e.initialState) == null ? e.state : n) == null ? {} : r), d = o.reduce((e, t) => {
266
- var n, r;
267
- return (r = (n = t.getDefaultConfig) == null ? void 0 : n.call(t, e, c)) == null ? e : r;
268
- }, e), f = o.reduce((e, t) => g(g({}, e), t.stateHandlerNames), {}), p, m = { current: {} }, h = !1, _ = {}, v = [], y = {}, b = {}, x = {}, S = {}, C = () => {
269
- v = [], x = {};
270
- let [e, t] = a(s, "itemInstance", (e) => ({
271
- item: e,
272
- tree: c,
273
- itemId: d.rootItemId
325
+ };
326
+ var exhaustiveSort = (arr, compareFn) => {
327
+ const n = arr.length;
328
+ for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (compareFn(arr[j], arr[i]) < 0) [arr[i], arr[j]] = [arr[j], arr[i]];
329
+ return arr;
330
+ };
331
+ var compareFeatures = (originalOrder) => (feature1, feature2) => {
332
+ var _a, _b;
333
+ if (feature2.key && ((_a = feature1.overwrites) == null ? void 0 : _a.includes(feature2.key))) return 1;
334
+ if (feature1.key && ((_b = feature2.overwrites) == null ? void 0 : _b.includes(feature1.key))) return -1;
335
+ return originalOrder.indexOf(feature1) - originalOrder.indexOf(feature2);
336
+ };
337
+ var sortFeatures = (features = []) => exhaustiveSort(features, compareFeatures(features));
338
+ var createTree = (initialConfig) => {
339
+ var _a, _b, _c, _d;
340
+ const buildInstance = (_a = initialConfig.instanceBuilder) != null ? _a : buildStaticInstance;
341
+ const additionalFeatures = [treeFeature, ...sortFeatures(initialConfig.features)];
342
+ verifyFeatures(additionalFeatures);
343
+ const features = [...additionalFeatures];
344
+ const [treeInstance, finalizeTree] = buildInstance(features, "treeInstance", (tree) => ({ tree }));
345
+ let state = additionalFeatures.reduce((acc, feature) => {
346
+ var _a2, _b2;
347
+ return (_b2 = (_a2 = feature.getInitialState) == null ? void 0 : _a2.call(feature, acc, treeInstance)) != null ? _b2 : acc;
348
+ }, (_c = (_b = initialConfig.initialState) != null ? _b : initialConfig.state) != null ? _c : {});
349
+ let config = additionalFeatures.reduce((acc, feature) => {
350
+ var _a2, _b2;
351
+ return (_b2 = (_a2 = feature.getDefaultConfig) == null ? void 0 : _a2.call(feature, acc, treeInstance)) != null ? _b2 : acc;
352
+ }, initialConfig);
353
+ const stateHandlerNames = additionalFeatures.reduce((acc, feature) => __spreadValues$1(__spreadValues$1({}, acc), feature.stateHandlerNames), {});
354
+ let treeElement;
355
+ const treeDataRef = { current: {} };
356
+ let rebuildScheduled = false;
357
+ const itemInstancesMap = {};
358
+ let itemInstances = [];
359
+ const itemElementsMap = {};
360
+ const itemDataRefs = {};
361
+ let itemMetaMap = {};
362
+ const hotkeyPresets = {};
363
+ const rebuildItemMeta = () => {
364
+ itemInstances = [];
365
+ itemMetaMap = {};
366
+ const [rootInstance, finalizeRootInstance] = buildInstance(features, "itemInstance", (item) => ({
367
+ item,
368
+ tree: treeInstance,
369
+ itemId: config.rootItemId
274
370
  }));
275
- t(), _[d.rootItemId] = e, x[d.rootItemId] = {
276
- itemId: d.rootItemId,
371
+ finalizeRootInstance();
372
+ itemInstancesMap[config.rootItemId] = rootInstance;
373
+ itemMetaMap[config.rootItemId] = {
374
+ itemId: config.rootItemId,
277
375
  index: -1,
278
376
  parentId: null,
279
377
  level: -1,
280
378
  posInSet: 0,
281
379
  setSize: 1
282
380
  };
283
- for (let e of c.getItemsMeta()) if (x[e.itemId] = e, _[e.itemId]) v.push(_[e.itemId]);
284
- else {
285
- let [t, n] = a(s, "itemInstance", (t) => ({
286
- item: t,
287
- tree: c,
288
- itemId: e.itemId
289
- }));
290
- n(), _[e.itemId] = t, v.push(t);
381
+ for (const item of treeInstance.getItemsMeta()) {
382
+ itemMetaMap[item.itemId] = item;
383
+ if (!itemInstancesMap[item.itemId]) {
384
+ const [instance, finalizeInstance] = buildInstance(features, "itemInstance", (instance2) => ({
385
+ item: instance2,
386
+ tree: treeInstance,
387
+ itemId: item.itemId
388
+ }));
389
+ finalizeInstance();
390
+ itemInstancesMap[item.itemId] = instance;
391
+ itemInstances.push(instance);
392
+ } else itemInstances.push(itemInstancesMap[item.itemId]);
291
393
  }
292
- h = !1;
293
- }, w = (e) => {
294
- for (let t of o) e(t);
394
+ rebuildScheduled = false;
395
+ };
396
+ const eachFeature = (fn) => {
397
+ for (const feature of additionalFeatures) fn(feature);
295
398
  };
296
- s.unshift({
399
+ features.unshift({
297
400
  key: "main",
298
401
  treeInstance: {
299
- getState: () => u,
300
- setState: ({}, e) => {
301
- var t;
302
- (t = d.setState) == null || t.call(d, u);
402
+ getState: () => state,
403
+ setState: ({}, updater) => {
404
+ var _a2;
405
+ (_a2 = config.setState) == null || _a2.call(config, state);
303
406
  },
304
- setMounted: ({}, e) => {
305
- var t;
306
- let n = m.current;
307
- n.isMounted = e, e && ((t = n.waitingForMount) == null || t.forEach((e) => e()), n.waitingForMount = []);
407
+ setMounted: ({}, isMounted) => {
408
+ var _a2;
409
+ const ref = treeDataRef.current;
410
+ ref.isMounted = isMounted;
411
+ if (isMounted) {
412
+ (_a2 = ref.waitingForMount) == null || _a2.forEach((cb) => cb());
413
+ ref.waitingForMount = [];
414
+ }
308
415
  },
309
- applySubStateUpdate: ({}, e, t) => {
310
- let n = () => {
311
- u[e] = typeof t == "function" ? t(u[e]) : t;
312
- let n = d[f[e]];
313
- n == null || n(u[e]);
314
- }, r = m.current;
315
- r.isMounted ? n() : (r.waitingForMount != null || (r.waitingForMount = []), r.waitingForMount.push(n));
416
+ applySubStateUpdate: ({}, stateName, updater) => {
417
+ const apply = () => {
418
+ state[stateName] = typeof updater === "function" ? updater(state[stateName]) : updater;
419
+ const externalStateSetter = config[stateHandlerNames[stateName]];
420
+ externalStateSetter == null || externalStateSetter(state[stateName]);
421
+ };
422
+ const ref = treeDataRef.current;
423
+ if (ref.isMounted) apply();
424
+ else {
425
+ ref.waitingForMount != null || (ref.waitingForMount = []);
426
+ ref.waitingForMount.push(apply);
427
+ }
316
428
  },
317
429
  rebuildTree: () => {
318
- var e;
319
- let t = m.current;
320
- t.isMounted ? (C(), (e = d.setState) == null || e.call(d, u)) : (t.waitingForMount != null || (t.waitingForMount = []), t.waitingForMount.push(() => {
321
- var e;
322
- C(), (e = d.setState) == null || e.call(d, u);
323
- }));
430
+ var _a2;
431
+ const ref = treeDataRef.current;
432
+ if (ref.isMounted) {
433
+ rebuildItemMeta();
434
+ (_a2 = config.setState) == null || _a2.call(config, state);
435
+ } else {
436
+ ref.waitingForMount != null || (ref.waitingForMount = []);
437
+ ref.waitingForMount.push(() => {
438
+ var _a3;
439
+ rebuildItemMeta();
440
+ (_a3 = config.setState) == null || _a3.call(config, state);
441
+ });
442
+ }
324
443
  },
325
444
  scheduleRebuildTree: () => {
326
- h = !0;
445
+ rebuildScheduled = true;
327
446
  },
328
- getConfig: () => d,
329
- setConfig: (e, t) => {
330
- var n, r, i;
331
- let a = typeof t == "function" ? t(d) : t, o = ((n = a.state) == null ? void 0 : n.expandedItems) && ((r = a.state) == null ? void 0 : r.expandedItems) !== u.expandedItems;
332
- d = a, a.state && (u = g(g({}, u), a.state)), o && (C(), (i = d.setState) == null || i.call(d, u));
447
+ getConfig: () => config,
448
+ setConfig: (_, updater) => {
449
+ var _a2, _b2, _c2;
450
+ const newConfig = typeof updater === "function" ? updater(config) : updater;
451
+ const hasChangedExpandedItems = ((_a2 = newConfig.state) == null ? void 0 : _a2.expandedItems) && ((_b2 = newConfig.state) == null ? void 0 : _b2.expandedItems) !== state.expandedItems;
452
+ config = newConfig;
453
+ if (newConfig.state) state = __spreadValues$1(__spreadValues$1({}, state), newConfig.state);
454
+ if (hasChangedExpandedItems) {
455
+ rebuildItemMeta();
456
+ (_c2 = config.setState) == null || _c2.call(config, state);
457
+ }
333
458
  },
334
- getItemInstance: ({}, e) => {
335
- let t = _[e];
336
- if (!t) {
337
- let [t, n] = a(s, "itemInstance", (t) => ({
338
- item: t,
339
- tree: c,
340
- itemId: e
459
+ getItemInstance: ({}, itemId) => {
460
+ const existingInstance = itemInstancesMap[itemId];
461
+ if (!existingInstance) {
462
+ const [instance, finalizeInstance] = buildInstance(features, "itemInstance", (instance2) => ({
463
+ item: instance2,
464
+ tree: treeInstance,
465
+ itemId
341
466
  }));
342
- return n(), t;
467
+ finalizeInstance();
468
+ return instance;
343
469
  }
344
- return t;
470
+ return existingInstance;
471
+ },
472
+ getItems: () => {
473
+ if (rebuildScheduled) rebuildItemMeta();
474
+ return itemInstances;
345
475
  },
346
- getItems: () => (h && C(), v),
347
- registerElement: ({}, e) => {
348
- p !== e && (p && !e ? w((e) => {
349
- var t;
350
- return (t = e.onTreeUnmount) == null ? void 0 : t.call(e, c, p);
351
- }) : !p && e && w((t) => {
352
- var n;
353
- return (n = t.onTreeMount) == null ? void 0 : n.call(t, c, e);
354
- }), p = e);
476
+ registerElement: ({}, element) => {
477
+ if (treeElement === element) return;
478
+ if (treeElement && !element) eachFeature((feature) => {
479
+ var _a2;
480
+ return (_a2 = feature.onTreeUnmount) == null ? void 0 : _a2.call(feature, treeInstance, treeElement);
481
+ });
482
+ else if (!treeElement && element) eachFeature((feature) => {
483
+ var _a2;
484
+ return (_a2 = feature.onTreeMount) == null ? void 0 : _a2.call(feature, treeInstance, element);
485
+ });
486
+ treeElement = element;
355
487
  },
356
- getElement: () => p,
357
- getDataRef: () => m,
358
- getHotkeyPresets: () => S
488
+ getElement: () => treeElement,
489
+ getDataRef: () => treeDataRef,
490
+ getHotkeyPresets: () => hotkeyPresets
359
491
  },
360
492
  itemInstance: {
361
- registerElement: ({ itemId: e, item: t }, n) => {
362
- if (y[e] === n) return;
363
- let r = y[e];
364
- r && !n ? w((e) => {
365
- var n;
366
- return (n = e.onItemUnmount) == null ? void 0 : n.call(e, t, r, c);
367
- }) : !r && n && w((e) => {
368
- var r;
369
- return (r = e.onItemMount) == null ? void 0 : r.call(e, t, n, c);
370
- }), y[e] = n;
493
+ registerElement: ({ itemId, item }, element) => {
494
+ if (itemElementsMap[itemId] === element) return;
495
+ const oldElement = itemElementsMap[itemId];
496
+ if (oldElement && !element) eachFeature((feature) => {
497
+ var _a2;
498
+ return (_a2 = feature.onItemUnmount) == null ? void 0 : _a2.call(feature, item, oldElement, treeInstance);
499
+ });
500
+ else if (!oldElement && element) eachFeature((feature) => {
501
+ var _a2;
502
+ return (_a2 = feature.onItemMount) == null ? void 0 : _a2.call(feature, item, element, treeInstance);
503
+ });
504
+ itemElementsMap[itemId] = element;
371
505
  },
372
- getElement: ({ itemId: e }) => y[e],
373
- getDataRef: ({ itemId: e }) => {
374
- var t;
375
- return (t = b[e]) == null ? b[e] = { current: {} } : t;
506
+ getElement: ({ itemId }) => itemElementsMap[itemId],
507
+ getDataRef: ({ itemId }) => {
508
+ var _a2;
509
+ return (_a2 = itemDataRefs[itemId]) != null ? _a2 : itemDataRefs[itemId] = { current: {} };
376
510
  },
377
- getItemMeta: ({ itemId: e }) => {
378
- var t;
379
- return (t = x[e]) == null ? {
380
- itemId: e,
511
+ getItemMeta: ({ itemId }) => {
512
+ var _a2;
513
+ return (_a2 = itemMetaMap[itemId]) != null ? _a2 : {
514
+ itemId,
381
515
  parentId: null,
382
516
  level: -1,
383
517
  index: -1,
384
518
  posInSet: 0,
385
519
  setSize: 1
386
- } : t;
520
+ };
387
521
  }
388
522
  }
389
523
  });
390
- for (let e of s) Object.assign(S, (i = e.hotkeys) == null ? {} : i);
391
- return l(), c;
392
- }, ae = {
524
+ for (const feature of features) Object.assign(hotkeyPresets, (_d = feature.hotkeys) != null ? _d : {});
525
+ finalizeTree();
526
+ return treeInstance;
527
+ };
528
+ var selectionFeature = {
393
529
  key: "selection",
394
- getInitialState: (e) => g({ selectedItems: [] }, e),
395
- getDefaultConfig: (e, t) => g({ setSelectedItems: b("selectedItems", t) }, e),
530
+ getInitialState: (initialState) => __spreadValues$1({ selectedItems: [] }, initialState),
531
+ getDefaultConfig: (defaultConfig, tree) => __spreadValues$1({ setSelectedItems: makeStateUpdater("selectedItems", tree) }, defaultConfig),
396
532
  stateHandlerNames: { selectedItems: "setSelectedItems" },
397
533
  treeInstance: {
398
- setSelectedItems: ({ tree: e }, t) => {
399
- e.applySubStateUpdate("selectedItems", t);
534
+ setSelectedItems: ({ tree }, selectedItems) => {
535
+ tree.applySubStateUpdate("selectedItems", selectedItems);
400
536
  },
401
- getSelectedItems: ({ tree: e }) => e.getState().selectedItems.map(e.getItemInstance)
537
+ getSelectedItems: ({ tree }) => {
538
+ return tree.getState().selectedItems.map(tree.getItemInstance);
539
+ }
402
540
  },
403
541
  itemInstance: {
404
- select: ({ tree: e, itemId: t }) => {
405
- let { selectedItems: n } = e.getState();
406
- e.setSelectedItems(n.includes(t) ? n : [...n, t]);
542
+ select: ({ tree, itemId }) => {
543
+ const { selectedItems } = tree.getState();
544
+ tree.setSelectedItems(selectedItems.includes(itemId) ? selectedItems : [...selectedItems, itemId]);
407
545
  },
408
- deselect: ({ tree: e, itemId: t }) => {
409
- let { selectedItems: n } = e.getState();
410
- e.setSelectedItems(n.filter((e) => e !== t));
546
+ deselect: ({ tree, itemId }) => {
547
+ const { selectedItems } = tree.getState();
548
+ tree.setSelectedItems(selectedItems.filter((id) => id !== itemId));
411
549
  },
412
- isSelected: ({ tree: e, itemId: t }) => {
413
- let { selectedItems: n } = e.getState();
414
- return n.includes(t);
550
+ isSelected: ({ tree, itemId }) => {
551
+ const { selectedItems } = tree.getState();
552
+ return selectedItems.includes(itemId);
415
553
  },
416
- selectUpTo: ({ tree: e, item: t, itemId: n }, r) => {
417
- let i = t.getItemMeta().index, a = e.getDataRef();
418
- if (!a.current.selectUpToAnchorId) {
419
- a.current.selectUpToAnchorId = n, e.setSelectedItems([n]);
554
+ selectUpTo: ({ tree, item, itemId }, ctrl) => {
555
+ const indexA = item.getItemMeta().index;
556
+ const dataRef = tree.getDataRef();
557
+ if (!dataRef.current.selectUpToAnchorId) {
558
+ dataRef.current.selectUpToAnchorId = itemId;
559
+ tree.setSelectedItems([itemId]);
420
560
  return;
421
561
  }
422
- let o = e.getItemInstance(a.current.selectUpToAnchorId).getItemMeta().index, [s, c] = i < o ? [i, o] : [o, i], l = e.getItems().slice(s, c + 1).map((e) => e.getItemMeta().itemId);
423
- if (!r) {
424
- e.setSelectedItems(l);
562
+ const indexB = tree.getItemInstance(dataRef.current.selectUpToAnchorId).getItemMeta().index;
563
+ const [a, b] = indexA < indexB ? [indexA, indexB] : [indexB, indexA];
564
+ const newSelectedItems = tree.getItems().slice(a, b + 1).map((treeItem) => treeItem.getItemMeta().itemId);
565
+ if (!ctrl) {
566
+ tree.setSelectedItems(newSelectedItems);
425
567
  return;
426
568
  }
427
- let { selectedItems: u } = e.getState(), d = [.../* @__PURE__ */ new Set([...u, ...l])];
428
- e.setSelectedItems(d);
569
+ const { selectedItems } = tree.getState();
570
+ const uniqueSelectedItems = [.../* @__PURE__ */ new Set([...selectedItems, ...newSelectedItems])];
571
+ tree.setSelectedItems(uniqueSelectedItems);
429
572
  },
430
- toggleSelect: ({ item: e }) => {
431
- e.isSelected() ? e.deselect() : e.select();
573
+ toggleSelect: ({ item }) => {
574
+ if (item.isSelected()) item.deselect();
575
+ else item.select();
432
576
  },
433
- getProps: ({ tree: e, item: t, itemId: n, prev: r }) => _(g({}, r == null ? void 0 : r()), {
434
- "aria-selected": t.isSelected() ? "true" : "false",
435
- onClick: (i) => {
436
- var a, o;
437
- i.shiftKey ? t.selectUpTo(i.ctrlKey || i.metaKey) : i.ctrlKey || i.metaKey ? t.toggleSelect() : e.setSelectedItems([n]), i.shiftKey || (e.getDataRef().current.selectUpToAnchorId = n), (o = (a = r == null ? void 0 : r()) == null ? void 0 : a.onClick) == null || o.call(a, i);
577
+ getProps: ({ tree, item, itemId, prev }) => __spreadProps$1(__spreadValues$1({}, prev == null ? void 0 : prev()), {
578
+ "aria-selected": item.isSelected() ? "true" : "false",
579
+ onClick: (e) => {
580
+ var _a, _b;
581
+ if (e.shiftKey) item.selectUpTo(e.ctrlKey || e.metaKey);
582
+ else if (e.ctrlKey || e.metaKey) item.toggleSelect();
583
+ else tree.setSelectedItems([itemId]);
584
+ if (!e.shiftKey) tree.getDataRef().current.selectUpToAnchorId = itemId;
585
+ (_b = (_a = prev == null ? void 0 : prev()) == null ? void 0 : _a.onClick) == null || _b.call(_a, e);
438
586
  }
439
587
  })
440
588
  },
441
589
  hotkeys: {
442
590
  toggleSelectedItem: {
443
591
  hotkey: "Control+Space",
444
- preventDefault: !0,
445
- handler: (e, t) => {
446
- t.getFocusedItem().toggleSelect();
592
+ preventDefault: true,
593
+ handler: (_, tree) => {
594
+ tree.getFocusedItem().toggleSelect();
447
595
  }
448
596
  },
449
597
  selectUpwards: {
450
598
  hotkey: "Shift+ArrowUp",
451
- handler: (e, t) => {
452
- let n = t.getFocusedItem(), r = n.getItemAbove();
453
- r && (n.isSelected() && r.isSelected() ? n.deselect() : r.select(), r.setFocused(), t.updateDomFocus());
599
+ handler: (e, tree) => {
600
+ const focused = tree.getFocusedItem();
601
+ const above = focused.getItemAbove();
602
+ if (!above) return;
603
+ if (focused.isSelected() && above.isSelected()) focused.deselect();
604
+ else above.select();
605
+ above.setFocused();
606
+ tree.updateDomFocus();
454
607
  }
455
608
  },
456
609
  selectDownwards: {
457
610
  hotkey: "Shift+ArrowDown",
458
- handler: (e, t) => {
459
- let n = t.getFocusedItem(), r = n.getItemBelow();
460
- r && (n.isSelected() && r.isSelected() ? n.deselect() : r.select(), r.setFocused(), t.updateDomFocus());
611
+ handler: (e, tree) => {
612
+ const focused = tree.getFocusedItem();
613
+ const below = focused.getItemBelow();
614
+ if (!below) return;
615
+ if (focused.isSelected() && below.isSelected()) focused.deselect();
616
+ else below.select();
617
+ below.setFocused();
618
+ tree.updateDomFocus();
461
619
  }
462
620
  },
463
621
  selectAll: {
464
622
  hotkey: "Control+KeyA",
465
- preventDefault: !0,
466
- handler: (e, t) => {
467
- t.setSelectedItems(t.getItems().map((e) => e.getId()));
623
+ preventDefault: true,
624
+ handler: (e, tree) => {
625
+ tree.setSelectedItems(tree.getItems().map((item) => item.getId()));
468
626
  }
469
627
  }
470
628
  }
471
- }, D = (e) => e.code !== "" && e.code !== "Unidentified" ? e.code : e.key, O = {
629
+ };
630
+ var resolveKeyCode = (event) => event.code !== "" && event.code !== "Unidentified" ? event.code : event.key;
631
+ var specialKeys = {
472
632
  letter: /^Key[A-Z]$/,
473
633
  letterornumber: /^(Key[A-Z]|Digit[0-9])$/,
474
634
  plus: /^(NumpadAdd|Plus)$/,
@@ -477,7 +637,8 @@ var x = (e, t = 100, n = 1e3) => new Promise((r) => {
477
637
  shift: /^(ShiftLeft|ShiftRight)$/,
478
638
  metaorcontrol: /^(MetaLeft|MetaRight|ControlLeft|ControlRight)$/,
479
639
  enter: /^(Enter|NumpadEnter)$/
480
- }, k = /* @__PURE__ */ new Set([
640
+ };
641
+ var modifierKeyCodes = /* @__PURE__ */ new Set([
481
642
  "MetaLeft",
482
643
  "MetaRight",
483
644
  "Meta",
@@ -490,177 +651,789 @@ var x = (e, t = 100, n = 1e3) => new Promise((r) => {
490
651
  "ShiftLeft",
491
652
  "ShiftRight",
492
653
  "Shift"
493
- ]), oe = (e, t, n) => {
494
- let r = n.hotkey.toLowerCase().split("+"), i = r.every((t) => {
495
- if (t in O) return [...e].some((e) => O[t].test(e));
496
- let n = [...e].map((e) => e.toLowerCase());
497
- return n.includes(t.toLowerCase()) || n.includes(`key${t.toLowerCase()}`);
498
- }), a = !n.isEnabled || n.isEnabled(t);
499
- return i && a && e.size === r.length;
500
- }, se = (e, t, n, r) => {
501
- var i;
502
- return (i = Object.entries(g(g({}, n), r)).find(([, n]) => oe(e, t, n))) == null ? void 0 : i[0];
503
- }, A = {
504
- clearPressedKeys: (e) => {
505
- e.current.pressedKeys = /* @__PURE__ */ new Set();
654
+ ]);
655
+ var testHotkeyMatch = (pressedKeys, tree, hotkey) => {
656
+ const supposedKeys = hotkey.hotkey.toLowerCase().split("+");
657
+ const doKeysMatch = supposedKeys.every((key) => {
658
+ if (key in specialKeys) return [...pressedKeys].some((pressedKey) => specialKeys[key].test(pressedKey));
659
+ const pressedKeysLowerCase = [...pressedKeys].map((pressedKey) => pressedKey.toLowerCase());
660
+ return pressedKeysLowerCase.includes(key.toLowerCase()) || pressedKeysLowerCase.includes(`key${key.toLowerCase()}`);
661
+ });
662
+ const isEnabled = !hotkey.isEnabled || hotkey.isEnabled(tree);
663
+ return doKeysMatch && isEnabled && pressedKeys.size === supposedKeys.length;
664
+ };
665
+ var findHotkeyMatch = (pressedKeys, tree, config1, config2) => {
666
+ var _a;
667
+ return (_a = Object.entries(__spreadValues$1(__spreadValues$1({}, config1), config2)).find(([, hotkey]) => testHotkeyMatch(pressedKeys, tree, hotkey))) == null ? void 0 : _a[0];
668
+ };
669
+ var hotkeysCoreController = {
670
+ clearPressedKeys: (dataRef) => {
671
+ dataRef.current.pressedKeys = /* @__PURE__ */ new Set();
506
672
  },
507
- dispatchKeyDown: (e, t, n, r = {}) => {
508
- var i, a, o, s;
509
- let { isInputFocused: c = !1, releaseAfterDispatch: l = !1 } = r, { ignoreHotkeysOnInputs: u, onTreeHotkey: d, hotkeys: f } = e.getConfig();
510
- if (c && u) return;
511
- let p = D({
512
- code: (i = n.code) == null ? "" : i,
513
- key: (a = n.key) == null ? "" : a
673
+ dispatchKeyDown: (tree, dataRef, eventLike, options = {}) => {
674
+ var _a, _b, _c, _e;
675
+ const { isInputFocused = false, releaseAfterDispatch = false } = options;
676
+ const { ignoreHotkeysOnInputs, onTreeHotkey, hotkeys } = tree.getConfig();
677
+ if (isInputFocused && ignoreHotkeysOnInputs) return;
678
+ const resolvedCode = resolveKeyCode({
679
+ code: (_a = eventLike.code) != null ? _a : "",
680
+ key: (_b = eventLike.key) != null ? _b : ""
514
681
  });
515
- (o = t.current).pressedKeys != null || (o.pressedKeys = /* @__PURE__ */ new Set());
516
- let m = !t.current.pressedKeys.has(p);
517
- p && t.current.pressedKeys.add(p);
518
- let h = se(t.current.pressedKeys, e, e.getHotkeyPresets(), f);
519
- if (l && p && t.current.pressedKeys.delete(p), !h) return;
520
- let _ = g(g({}, e.getHotkeyPresets()[h]), f == null ? void 0 : f[h]);
521
- _ && (_.allowWhenInputFocused || !c) && (_.canRepeat || m) && (_.preventDefault && ((s = n.preventDefault) == null || s.call(n)), _.handler(n, e), d == null || d(h, n));
682
+ (_c = dataRef.current).pressedKeys != null || (_c.pressedKeys = /* @__PURE__ */ new Set());
683
+ const isNewKey = !dataRef.current.pressedKeys.has(resolvedCode);
684
+ if (resolvedCode) dataRef.current.pressedKeys.add(resolvedCode);
685
+ const hotkeyName = findHotkeyMatch(dataRef.current.pressedKeys, tree, tree.getHotkeyPresets(), hotkeys);
686
+ if (releaseAfterDispatch && resolvedCode) dataRef.current.pressedKeys.delete(resolvedCode);
687
+ if (!hotkeyName) return;
688
+ const hotkeyConfig = __spreadValues$1(__spreadValues$1({}, tree.getHotkeyPresets()[hotkeyName]), hotkeys == null ? void 0 : hotkeys[hotkeyName]);
689
+ if (!hotkeyConfig) return;
690
+ if (!hotkeyConfig.allowWhenInputFocused && isInputFocused) return;
691
+ if (!hotkeyConfig.canRepeat && !isNewKey) return;
692
+ if (hotkeyConfig.preventDefault) (_e = eventLike.preventDefault) == null || _e.call(eventLike);
693
+ hotkeyConfig.handler(eventLike, tree);
694
+ onTreeHotkey == null || onTreeHotkey(hotkeyName, eventLike);
522
695
  },
523
- dispatchKeyUp: (e, t) => {
524
- var n, r, i;
525
- let a = D({
526
- code: (n = t.code) == null ? "" : n,
527
- key: (r = t.key) == null ? "" : r
696
+ dispatchKeyUp: (dataRef, eventLike) => {
697
+ var _a, _b, _c;
698
+ const resolvedCode = resolveKeyCode({
699
+ code: (_a = eventLike.code) != null ? _a : "",
700
+ key: (_b = eventLike.key) != null ? _b : ""
528
701
  });
529
- a && ((i = e.current).pressedKeys != null || (i.pressedKeys = /* @__PURE__ */ new Set()), k.has(a) && (e.current.pressedKeys = new Set([...e.current.pressedKeys].filter((e) => k.has(e)))), e.current.pressedKeys.delete(a));
702
+ if (!resolvedCode) return;
703
+ (_c = dataRef.current).pressedKeys != null || (_c.pressedKeys = /* @__PURE__ */ new Set());
704
+ if (modifierKeyCodes.has(resolvedCode)) dataRef.current.pressedKeys = new Set([...dataRef.current.pressedKeys].filter((pressedKey) => modifierKeyCodes.has(pressedKey)));
705
+ dataRef.current.pressedKeys.delete(resolvedCode);
530
706
  }
531
- }, ce = {
707
+ };
708
+ var hotkeysCoreFeature = {
532
709
  key: "hotkeys-core",
533
- onTreeMount: (e, t) => {
534
- let n = e.getDataRef(), r = (t) => {
535
- let r = t.target instanceof HTMLInputElement;
536
- A.dispatchKeyDown(e, n, t, {
537
- isInputFocused: r,
538
- releaseAfterDispatch: r
710
+ onTreeMount: (tree, element) => {
711
+ const data = tree.getDataRef();
712
+ const keydown = (e) => {
713
+ const isInputFocused = e.target instanceof HTMLInputElement;
714
+ hotkeysCoreController.dispatchKeyDown(tree, data, e, {
715
+ isInputFocused,
716
+ releaseAfterDispatch: isInputFocused
539
717
  });
540
- }, i = (e) => {
541
- A.dispatchKeyUp(n, e);
542
- }, a = () => {
543
- A.clearPressedKeys(n);
544
718
  };
545
- t.addEventListener("keydown", r), document.addEventListener("keyup", i), window.addEventListener("focus", a), n.current.keydownHandler = r, n.current.keyupHandler = i, n.current.resetHandler = a;
719
+ const keyup = (e) => {
720
+ hotkeysCoreController.dispatchKeyUp(data, e);
721
+ };
722
+ const reset = () => {
723
+ hotkeysCoreController.clearPressedKeys(data);
724
+ };
725
+ element.addEventListener("keydown", keydown);
726
+ document.addEventListener("keyup", keyup);
727
+ window.addEventListener("focus", reset);
728
+ data.current.keydownHandler = keydown;
729
+ data.current.keyupHandler = keyup;
730
+ data.current.resetHandler = reset;
546
731
  },
547
- onTreeUnmount: (e, t) => {
548
- let n = e.getDataRef();
549
- n.current.keyupHandler && (document.removeEventListener("keyup", n.current.keyupHandler), delete n.current.keyupHandler), n.current.keydownHandler && (t.removeEventListener("keydown", n.current.keydownHandler), delete n.current.keydownHandler), n.current.resetHandler && (window.removeEventListener("focus", n.current.resetHandler), delete n.current.resetHandler);
732
+ onTreeUnmount: (tree, element) => {
733
+ const data = tree.getDataRef();
734
+ if (data.current.keyupHandler) {
735
+ document.removeEventListener("keyup", data.current.keyupHandler);
736
+ delete data.current.keyupHandler;
737
+ }
738
+ if (data.current.keydownHandler) {
739
+ element.removeEventListener("keydown", data.current.keydownHandler);
740
+ delete data.current.keydownHandler;
741
+ }
742
+ if (data.current.resetHandler) {
743
+ window.removeEventListener("focus", data.current.resetHandler);
744
+ delete data.current.resetHandler;
745
+ }
550
746
  }
551
- }, j = (e) => {
552
- var t, n, r, i;
553
- let a = e.getDataRef();
554
- return (t = a.current).itemData != null || (t.itemData = {}), (n = a.current).childrenIds != null || (n.childrenIds = {}), (r = a.current).loadingDataSubs != null || (r.loadingDataSubs = {}), (i = a.current).loadingChildrenSubs != null || (i.loadingChildrenSubs = {}), a;
555
- }, M = (e, t) => v(null, null, function* () {
556
- var n, r;
557
- let i = e.getConfig(), a = j(e);
558
- if (e.getState().loadingItemData.includes(t)) return new Promise((e) => {
559
- var n;
560
- (n = a.current.loadingDataSubs)[t] != null || (n[t] = []), a.current.loadingDataSubs[t].push(() => {
561
- e(a.current.itemData[t]);
747
+ };
748
+ var getDataRef = (tree) => {
749
+ var _a, _c, _e, _g;
750
+ const dataRef = tree.getDataRef();
751
+ (_a = dataRef.current).itemData != null || (_a.itemData = {});
752
+ (_c = dataRef.current).childrenIds != null || (_c.childrenIds = {});
753
+ (_e = dataRef.current).loadingDataSubs != null || (_e.loadingDataSubs = {});
754
+ (_g = dataRef.current).loadingChildrenSubs != null || (_g.loadingChildrenSubs = {});
755
+ return dataRef;
756
+ };
757
+ var loadItemData = (tree, itemId) => __async(null, null, function* () {
758
+ var _a, _b;
759
+ const config = tree.getConfig();
760
+ const dataRef = getDataRef(tree);
761
+ if (tree.getState().loadingItemData.includes(itemId)) return new Promise((resolve) => {
762
+ var _a2;
763
+ (_a2 = dataRef.current.loadingDataSubs)[itemId] != null || (_a2[itemId] = []);
764
+ dataRef.current.loadingDataSubs[itemId].push(() => {
765
+ resolve(dataRef.current.itemData[itemId]);
562
766
  });
563
767
  });
564
- a.current.itemData[t] || e.applySubStateUpdate("loadingItemData", (e) => [...e, t]);
565
- let o = yield i.dataLoader.getItem(t);
566
- return a.current.itemData[t] = o, (n = i.onLoadedItem) == null || n.call(i, t, o), e.applySubStateUpdate("loadingItemData", (e) => e.filter((e) => e !== t)), (r = a.current.loadingDataSubs[t]) == null || r.forEach((e) => e()), o;
567
- }), N = (e, t) => v(null, null, function* () {
568
- var n, r, i;
569
- let a = e.getConfig(), o = j(e), s;
570
- if (e.getState().loadingItemChildrens.includes(t)) return new Promise((e) => {
571
- var n;
572
- (n = o.current.loadingChildrenSubs)[t] != null || (n[t] = []), o.current.loadingChildrenSubs[t].push(() => {
573
- e(o.current.childrenIds[t]);
768
+ if (!dataRef.current.itemData[itemId]) tree.applySubStateUpdate("loadingItemData", (loadingItemData) => [...loadingItemData, itemId]);
769
+ const item = yield config.dataLoader.getItem(itemId);
770
+ dataRef.current.itemData[itemId] = item;
771
+ (_a = config.onLoadedItem) == null || _a.call(config, itemId, item);
772
+ tree.applySubStateUpdate("loadingItemData", (loadingItemData) => loadingItemData.filter((id) => id !== itemId));
773
+ (_b = dataRef.current.loadingDataSubs[itemId]) == null || _b.forEach((cb) => cb());
774
+ return item;
775
+ });
776
+ var loadChildrenIds = (tree, itemId) => __async(null, null, function* () {
777
+ var _a, _b, _c;
778
+ const config = tree.getConfig();
779
+ const dataRef = getDataRef(tree);
780
+ let childrenIds;
781
+ if (tree.getState().loadingItemChildrens.includes(itemId)) return new Promise((resolve) => {
782
+ var _a2;
783
+ (_a2 = dataRef.current.loadingChildrenSubs)[itemId] != null || (_a2[itemId] = []);
784
+ dataRef.current.loadingChildrenSubs[itemId].push(() => {
785
+ resolve(dataRef.current.childrenIds[itemId]);
574
786
  });
575
787
  });
576
- if (o.current.childrenIds[t] || e.applySubStateUpdate("loadingItemChildrens", (e) => [...e, t]), "getChildrenWithData" in a.dataLoader) {
577
- let r = yield a.dataLoader.getChildrenWithData(t);
578
- s = r.map((e) => e.id), o.current.childrenIds[t] = s, r.forEach(({ id: e, data: t }) => {
579
- var n;
580
- o.current.itemData[e] = t, (n = a.onLoadedItem) == null || n.call(a, e, t);
581
- }), (n = a.onLoadedChildren) == null || n.call(a, t, s), e.rebuildTree(), e.applySubStateUpdate("loadingItemData", (e) => e.filter((e) => !s.includes(e)));
582
- } else s = yield a.dataLoader.getChildren(t), o.current.childrenIds[t] = s, (r = a.onLoadedChildren) == null || r.call(a, t, s), e.rebuildTree();
583
- return e.applySubStateUpdate("loadingItemChildrens", (e) => e.filter((e) => e !== t)), (i = o.current.loadingChildrenSubs[t]) == null || i.forEach((e) => e()), s;
584
- }), le = {
788
+ if (!dataRef.current.childrenIds[itemId]) tree.applySubStateUpdate("loadingItemChildrens", (loadingItemChildrens) => [...loadingItemChildrens, itemId]);
789
+ if ("getChildrenWithData" in config.dataLoader) {
790
+ const children = yield config.dataLoader.getChildrenWithData(itemId);
791
+ childrenIds = children.map((c) => c.id);
792
+ dataRef.current.childrenIds[itemId] = childrenIds;
793
+ children.forEach(({ id, data }) => {
794
+ var _a2;
795
+ dataRef.current.itemData[id] = data;
796
+ (_a2 = config.onLoadedItem) == null || _a2.call(config, id, data);
797
+ });
798
+ (_a = config.onLoadedChildren) == null || _a.call(config, itemId, childrenIds);
799
+ tree.rebuildTree();
800
+ tree.applySubStateUpdate("loadingItemData", (loadingItemData) => loadingItemData.filter((id) => !childrenIds.includes(id)));
801
+ } else {
802
+ childrenIds = yield config.dataLoader.getChildren(itemId);
803
+ dataRef.current.childrenIds[itemId] = childrenIds;
804
+ (_b = config.onLoadedChildren) == null || _b.call(config, itemId, childrenIds);
805
+ tree.rebuildTree();
806
+ }
807
+ tree.applySubStateUpdate("loadingItemChildrens", (loadingItemChildrens) => loadingItemChildrens.filter((id) => id !== itemId));
808
+ (_c = dataRef.current.loadingChildrenSubs[itemId]) == null || _c.forEach((cb) => cb());
809
+ return childrenIds;
810
+ });
811
+ var asyncDataLoaderFeature = {
585
812
  key: "async-data-loader",
586
- getInitialState: (e) => g({
813
+ getInitialState: (initialState) => __spreadValues$1({
587
814
  loadingItemData: [],
588
815
  loadingItemChildrens: []
589
- }, e),
590
- getDefaultConfig: (e, t) => g({
591
- setLoadingItemData: b("loadingItemData", t),
592
- setLoadingItemChildrens: b("loadingItemChildrens", t)
593
- }, e),
816
+ }, initialState),
817
+ getDefaultConfig: (defaultConfig, tree) => __spreadValues$1({
818
+ setLoadingItemData: makeStateUpdater("loadingItemData", tree),
819
+ setLoadingItemChildrens: makeStateUpdater("loadingItemChildrens", tree)
820
+ }, defaultConfig),
594
821
  stateHandlerNames: {
595
822
  loadingItemData: "setLoadingItemData",
596
823
  loadingItemChildrens: "setLoadingItemChildrens"
597
824
  },
598
825
  treeInstance: {
599
- waitForItemDataLoaded: ({ tree: e }, t) => e.loadItemData(t),
600
- waitForItemChildrenLoaded: ({ tree: e }, t) => e.loadChildrenIds(t),
601
- loadItemData: (e, t) => v(null, [e, t], function* ({ tree: e }, t) {
602
- var n;
603
- return (n = j(e).current.itemData[t]) == null ? yield M(e, t) : n;
826
+ waitForItemDataLoaded: ({ tree }, itemId) => tree.loadItemData(itemId),
827
+ waitForItemChildrenLoaded: ({ tree }, itemId) => tree.loadChildrenIds(itemId),
828
+ loadItemData: (_0, _1) => __async(null, [_0, _1], function* ({ tree }, itemId) {
829
+ var _a;
830
+ return (_a = getDataRef(tree).current.itemData[itemId]) != null ? _a : yield loadItemData(tree, itemId);
604
831
  }),
605
- loadChildrenIds: (e, t) => v(null, [e, t], function* ({ tree: e }, t) {
606
- var n;
607
- return (n = j(e).current.childrenIds[t]) == null ? yield N(e, t) : n;
832
+ loadChildrenIds: (_0, _1) => __async(null, [_0, _1], function* ({ tree }, itemId) {
833
+ var _a;
834
+ return (_a = getDataRef(tree).current.childrenIds[itemId]) != null ? _a : yield loadChildrenIds(tree, itemId);
608
835
  }),
609
- retrieveItemData: ({ tree: e }, t, n = !1) => {
610
- var r, i;
611
- let a = e.getConfig(), o = j(e);
612
- return o.current.itemData[t] ? o.current.itemData[t] : (!e.getState().loadingItemData.includes(t) && !n && setTimeout(() => M(e, t)), (i = (r = a.createLoadingItemData) == null ? void 0 : r.call(a)) == null ? null : i);
836
+ retrieveItemData: ({ tree }, itemId, skipFetch = false) => {
837
+ var _a, _b;
838
+ const config = tree.getConfig();
839
+ const dataRef = getDataRef(tree);
840
+ if (dataRef.current.itemData[itemId]) return dataRef.current.itemData[itemId];
841
+ if (!tree.getState().loadingItemData.includes(itemId) && !skipFetch) setTimeout(() => loadItemData(tree, itemId));
842
+ return (_b = (_a = config.createLoadingItemData) == null ? void 0 : _a.call(config)) != null ? _b : null;
613
843
  },
614
- retrieveChildrenIds: ({ tree: e }, t, n = !1) => {
615
- let r = j(e);
616
- return r.current.childrenIds[t] ? r.current.childrenIds[t] : (e.getState().loadingItemChildrens.includes(t) || n || setTimeout(() => N(e, t)), []);
844
+ retrieveChildrenIds: ({ tree }, itemId, skipFetch = false) => {
845
+ const dataRef = getDataRef(tree);
846
+ if (dataRef.current.childrenIds[itemId]) return dataRef.current.childrenIds[itemId];
847
+ if (tree.getState().loadingItemChildrens.includes(itemId) || skipFetch) return [];
848
+ setTimeout(() => loadChildrenIds(tree, itemId));
849
+ return [];
617
850
  }
618
851
  },
619
852
  itemInstance: {
620
- isLoading: ({ tree: e, item: t }) => e.getState().loadingItemData.includes(t.getItemMeta().itemId) || e.getState().loadingItemChildrens.includes(t.getItemMeta().itemId),
621
- invalidateItemData: (e, t) => v(null, [e, t], function* ({ tree: e, itemId: t }, n) {
622
- var r;
623
- n || (r = j(e).current.itemData) == null || delete r[t], yield M(e, t);
853
+ isLoading: ({ tree, item }) => tree.getState().loadingItemData.includes(item.getItemMeta().itemId) || tree.getState().loadingItemChildrens.includes(item.getItemMeta().itemId),
854
+ invalidateItemData: (_0, _1) => __async(null, [_0, _1], function* ({ tree, itemId }, optimistic) {
855
+ var _a;
856
+ if (!optimistic) (_a = getDataRef(tree).current.itemData) == null || delete _a[itemId];
857
+ yield loadItemData(tree, itemId);
624
858
  }),
625
- invalidateChildrenIds: (e, t) => v(null, [e, t], function* ({ tree: e, itemId: t }, n) {
626
- var r;
627
- n || (r = j(e).current.childrenIds) == null || delete r[t], yield N(e, t);
859
+ invalidateChildrenIds: (_0, _1) => __async(null, [_0, _1], function* ({ tree, itemId }, optimistic) {
860
+ var _a;
861
+ if (!optimistic) (_a = getDataRef(tree).current.childrenIds) == null || delete _a[itemId];
862
+ yield loadChildrenIds(tree, itemId);
628
863
  }),
629
- updateCachedChildrenIds: ({ tree: e, itemId: t }, n, r) => {
630
- j(e).current.childrenIds[t] = n, r || e.rebuildTree();
864
+ updateCachedChildrenIds: ({ tree, itemId }, childrenIds, skipUpdateTree) => {
865
+ getDataRef(tree).current.childrenIds[itemId] = childrenIds;
866
+ if (!skipUpdateTree) tree.rebuildTree();
631
867
  },
632
- updateCachedData: ({ tree: e, itemId: t }, n, r) => {
633
- j(e).current.itemData[t] = n, r || e.rebuildTree();
868
+ updateCachedData: ({ tree, itemId }, data, skipUpdateTree) => {
869
+ getDataRef(tree).current.itemData[itemId] = data;
870
+ if (!skipUpdateTree) tree.rebuildTree();
634
871
  },
635
- hasLoadedData: ({ tree: e, itemId: t }) => e.getDataRef().current.itemData[t] !== void 0
872
+ hasLoadedData: ({ tree, itemId }) => {
873
+ return tree.getDataRef().current.itemData[itemId] !== void 0;
874
+ }
875
+ }
876
+ };
877
+ // node_modules/@headless-tree/react/dist/chunk-FWCSY2DS.mjs
878
+ var __defProp = Object.defineProperty;
879
+ var __defProps = Object.defineProperties;
880
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
881
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
882
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
883
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
884
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
885
+ enumerable: true,
886
+ configurable: true,
887
+ writable: true,
888
+ value
889
+ }) : obj[key] = value;
890
+ var __spreadValues = (a, b) => {
891
+ for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]);
892
+ if (__getOwnPropSymbols) {
893
+ for (var prop of __getOwnPropSymbols(b)) if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]);
894
+ }
895
+ return a;
896
+ };
897
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
898
+ // node_modules/@headless-tree/react/dist/react17/index.mjs
899
+ var useTree = (config) => {
900
+ const [tree] = useState(() => ({ current: createTree(config) }));
901
+ const [state, setState] = useState(() => tree.current.getState());
902
+ useEffect(() => {
903
+ tree.current.rebuildTree();
904
+ }, [tree]);
905
+ tree.current.setConfig((prev) => __spreadProps(__spreadValues(__spreadValues({}, prev), config), {
906
+ state: __spreadValues(__spreadValues({}, state), config.state),
907
+ setState: (state2) => {
908
+ var _a;
909
+ setState(state2);
910
+ (_a = config.setState) == null || _a.call(config, state2);
911
+ }
912
+ }));
913
+ return tree.current;
914
+ };
915
+ // src/explorer-files.ts
916
+ var ExplorerFileError = class extends Error {
917
+ constructor(code) {
918
+ super(code);
919
+ this.code = code;
920
+ }
921
+ };
922
+ function parentPath(path) {
923
+ return path.slice(0, Math.max(0, path.lastIndexOf("/")));
924
+ }
925
+ function validateName(name) {
926
+ if (!name.trim() || name === "." || name === ".." || name.toLowerCase() === ".git" || /[\\/\u0000]/u.test(name)) throw new ExplorerFileError("invalidName");
927
+ }
928
+ async function resolveExplorerDirectory(root, path) {
929
+ var _await$root$resolve;
930
+ let directory = root;
931
+ const parts = path ? path.split("/") : [];
932
+ for (const part of parts) {
933
+ validateName(part);
934
+ directory = await directory.getDirectoryHandle(part);
935
+ }
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
+ return directory;
938
+ }
939
+ async function assertUnused(directory, name) {
940
+ try {
941
+ await directory.getFileHandle(name);
942
+ } catch (error) {
943
+ if (error instanceof DOMException && error.name === "NotFoundError") return;
944
+ if (!(error instanceof DOMException) || error.name !== "TypeMismatchError") throw error;
945
+ }
946
+ throw new ExplorerFileError("exists");
947
+ }
948
+ var sameVersion = (a, b) => a.size === b.size && a.lastModified === b.lastModified;
949
+ async function writeNewFile(directory, name, file, guard) {
950
+ await assertUnused(directory, name);
951
+ guard();
952
+ const handle = await directory.getFileHandle(name, { create: true });
953
+ const empty = await handle.getFile();
954
+ if (empty.size) throw new ExplorerFileError("exists");
955
+ const options = { mode: "exclusive" };
956
+ let stream;
957
+ try {
958
+ stream = await handle.createWritable(options);
959
+ await stream.write(file);
960
+ if (!sameVersion(empty, await handle.getFile())) throw new ExplorerFileError("exists");
961
+ guard();
962
+ await stream.close();
963
+ } catch (error) {
964
+ await (stream === null || stream === void 0 ? void 0 : stream.abort().catch(() => {}));
965
+ try {
966
+ if (sameVersion(empty, await handle.getFile())) await directory.removeEntry(name);
967
+ } catch (_unused) {
968
+ throw new ExplorerFileError("cleanupFailed");
969
+ }
970
+ throw error;
971
+ }
972
+ }
973
+ async function copyExplorerFile(directory, file, guard) {
974
+ validateName(file.name);
975
+ await writeNewFile(directory, file.name, file, guard);
976
+ }
977
+ async function copyEntry(sourceParent, source, parent, name, guard) {
978
+ validateName(source.name);
979
+ if (source.kind === "file") {
980
+ const handle = source;
981
+ const file = await handle.getFile();
982
+ await writeNewFile(parent, name, file, guard);
983
+ const verify = async () => {
984
+ if (!sameVersion(file, await handle.getFile())) throw new ExplorerFileError("sourceChanged");
985
+ };
986
+ return {
987
+ verify,
988
+ async removeSource() {
989
+ await verify();
990
+ guard();
991
+ await sourceParent.removeEntry(source.name);
992
+ }
993
+ };
994
+ }
995
+ await assertUnused(parent, name);
996
+ guard();
997
+ const destination = await parent.getDirectoryHandle(name, { create: true });
998
+ const directory = source;
999
+ const children = /* @__PURE__ */ new Map();
1000
+ try {
1001
+ var _iteratorAbruptCompletion = false;
1002
+ var _didIteratorError = false;
1003
+ var _iteratorError;
1004
+ try {
1005
+ for (var _iterator = _asyncIterator(directory.values()), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
1006
+ const handle = _step.value;
1007
+ children.set(handle.name, {
1008
+ handle,
1009
+ copy: await copyEntry(directory, handle, destination, handle.name, guard)
1010
+ });
1011
+ }
1012
+ } catch (err) {
1013
+ _didIteratorError = true;
1014
+ _iteratorError = err;
1015
+ } finally {
1016
+ try {
1017
+ if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
1018
+ } finally {
1019
+ if (_didIteratorError) throw _iteratorError;
1020
+ }
1021
+ }
1022
+ } catch (error) {
1023
+ await removeIncompleteCopy(parent, name);
1024
+ throw error;
1025
+ }
1026
+ const verify = async () => {
1027
+ let count = 0;
1028
+ var _iteratorAbruptCompletion2 = false;
1029
+ var _didIteratorError2 = false;
1030
+ var _iteratorError2;
1031
+ try {
1032
+ for (var _iterator2 = _asyncIterator(directory.values()), _step2; _iteratorAbruptCompletion2 = !(_step2 = await _iterator2.next()).done; _iteratorAbruptCompletion2 = false) {
1033
+ const handle = _step2.value;
1034
+ {
1035
+ const child = children.get(handle.name);
1036
+ if (!child || !await handle.isSameEntry(child.handle)) throw new ExplorerFileError("sourceChanged");
1037
+ await child.copy.verify();
1038
+ count++;
1039
+ }
1040
+ }
1041
+ } catch (err) {
1042
+ _didIteratorError2 = true;
1043
+ _iteratorError2 = err;
1044
+ } finally {
1045
+ try {
1046
+ if (_iteratorAbruptCompletion2 && _iterator2.return != null) await _iterator2.return();
1047
+ } finally {
1048
+ if (_didIteratorError2) throw _iteratorError2;
1049
+ }
1050
+ }
1051
+ if (count !== children.size) throw new ExplorerFileError("sourceChanged");
1052
+ };
1053
+ return {
1054
+ verify,
1055
+ async removeSource() {
1056
+ for (const { copy } of children.values()) await copy.removeSource();
1057
+ guard();
1058
+ await sourceParent.removeEntry(source.name);
1059
+ }
1060
+ };
1061
+ }
1062
+ async function removeIncompleteCopy(parent, name) {
1063
+ try {
1064
+ await parent.removeEntry(name, { recursive: true });
1065
+ } catch (_unused2) {
1066
+ throw new ExplorerFileError("cleanupFailed");
1067
+ }
1068
+ }
1069
+ async function renameExplorerEntry(parent, entry, name, guard) {
1070
+ if (name === entry.name) return;
1071
+ validateName(name);
1072
+ const copy = await copyEntry(parent, entry.kind === "file" ? await parent.getFileHandle(entry.name) : await parent.getDirectoryHandle(entry.name), parent, name, guard);
1073
+ try {
1074
+ await copy.verify();
1075
+ guard();
1076
+ } catch (error) {
1077
+ await removeIncompleteCopy(parent, name);
1078
+ throw error;
1079
+ }
1080
+ try {
1081
+ await copy.removeSource();
1082
+ } catch (_unused3) {
1083
+ throw new ExplorerFileError("originalKept");
1084
+ }
1085
+ }
1086
+ async function deleteExplorerEntry(parent, entry, guard) {
1087
+ validateName(entry.name);
1088
+ if (entry.kind === "directory") {
1089
+ const check = async (directory) => {
1090
+ var _iteratorAbruptCompletion3 = false;
1091
+ var _didIteratorError3 = false;
1092
+ var _iteratorError3;
1093
+ try {
1094
+ for (var _iterator3 = _asyncIterator(directory.values()), _step3; _iteratorAbruptCompletion3 = !(_step3 = await _iterator3.next()).done; _iteratorAbruptCompletion3 = false) {
1095
+ const child = _step3.value;
1096
+ guard();
1097
+ validateName(child.name);
1098
+ if (child.kind === "directory") await check(child);
1099
+ }
1100
+ } catch (err) {
1101
+ _didIteratorError3 = true;
1102
+ _iteratorError3 = err;
1103
+ } finally {
1104
+ try {
1105
+ if (_iteratorAbruptCompletion3 && _iterator3.return != null) await _iterator3.return();
1106
+ } finally {
1107
+ if (_didIteratorError3) throw _iteratorError3;
1108
+ }
1109
+ }
1110
+ };
1111
+ await check(await parent.getDirectoryHandle(entry.name));
1112
+ } else await parent.getFileHandle(entry.name);
1113
+ guard();
1114
+ await parent.removeEntry(entry.name, { recursive: entry.kind === "directory" });
1115
+ }
1116
+ // src/explorer-menu.tsx
1117
+ var actionMessages = (locale = "en") => locale.toLowerCase().startsWith("ja") ? {
1118
+ actions: "ファイルとフォルダの操作",
1119
+ rename: "名前を変更…",
1120
+ renameTitle: "名前を変更",
1121
+ delete: "削除…",
1122
+ deleteTitle: "削除",
1123
+ newName: "新しい名前",
1124
+ cancel: "キャンセル",
1125
+ remove: (name, folder) => folder ? `「${name}」とその中身を削除しますか?` : `「${name}」を削除しますか?`,
1126
+ stage: "Git にステージ",
1127
+ unstage: "Git のステージを解除",
1128
+ working: "処理中…",
1129
+ copyFailed: "コピーできませんでした",
1130
+ filesOnly: "ファイルをドロップしてください。",
1131
+ invalidName: "この名前は使用できません。",
1132
+ exists: "同じ名前のファイルまたはフォルダがあります。",
1133
+ denied: "このフォルダへの書き込みが許可されていません。",
1134
+ conflict: "プロジェクトフォルダが変更されたか、別の操作が実行中です。",
1135
+ sourceChanged: "操作中に対象が変更されました。",
1136
+ originalKept: "元の項目を削除できなかったため、コピーを残しました。",
1137
+ cleanupFailed: "失敗したコピーを削除できませんでした。",
1138
+ failed: "操作を完了できませんでした。"
1139
+ } : {
1140
+ actions: "File and folder actions",
1141
+ rename: "Rename…",
1142
+ renameTitle: "Rename",
1143
+ delete: "Delete…",
1144
+ deleteTitle: "Delete",
1145
+ newName: "New name",
1146
+ cancel: "Cancel",
1147
+ remove: (name, folder) => folder ? `Delete “${name}” and its contents?` : `Delete “${name}”?`,
1148
+ stage: "Stage in Git",
1149
+ unstage: "Unstage in Git",
1150
+ working: "Working…",
1151
+ copyFailed: "Could not copy",
1152
+ filesOnly: "Drop files here.",
1153
+ invalidName: "This name cannot be used.",
1154
+ exists: "A file or folder with this name already exists.",
1155
+ denied: "Permission to write to this folder was not granted.",
1156
+ conflict: "The project folder changed or another operation is running.",
1157
+ sourceChanged: "The item changed during the operation.",
1158
+ originalKept: "The original could not be removed, so the copy was kept.",
1159
+ cleanupFailed: "The incomplete copy could not be removed.",
1160
+ failed: "The operation could not be completed."
1161
+ };
1162
+ var actionCss = `
1163
+ .twpf-explorer-actions{position:fixed;z-index:2147483647;max-width:calc(100vw - 8px);padding:4px;
1164
+ border:1px solid GrayText;border-radius:5px;background:Canvas;color:CanvasText;box-shadow:0 2px 8px #0004}
1165
+ .twpf-explorer-actions button{display:block;width:100%;border:0;padding:.35em .65em;text-align:start;background:Canvas;color:CanvasText;
1166
+ font:inherit;cursor:pointer;border-radius:3px}
1167
+ .twpf-explorer-actions button:is(:hover,:focus-visible){background:Highlight;color:HighlightText}
1168
+ .twpf-explorer-dialog{max-width:min(28em,calc(100vw - 2em));color:CanvasText;background:Canvas;
1169
+ border:1px solid GrayText;border-radius:6px;padding:1em;overflow-wrap:anywhere}
1170
+ .twpf-explorer-dialog::backdrop{background:#0006}
1171
+ .twpf-explorer-dialog h2{font-size:1.1em;margin:0 0 .75em}
1172
+ .twpf-explorer-dialog input{display:block;width:100%;box-sizing:border-box;margin-top:.3em}
1173
+ .twpf-explorer-dialog-footer{display:flex;justify-content:flex-end;gap:.5em;margin-top:1em}
1174
+ .twpf-explorer-drop{min-height:100%;box-sizing:border-box}
1175
+ .twpf-explorer [data-drop-active],.twpf-explorer[data-drop-active]{outline:2px solid Highlight;outline-offset:-2px}
1176
+ .twpf-explorer-feedback{white-space:pre-wrap;overflow-wrap:anywhere;padding:.25em .5em}
1177
+ `;
1178
+ function ExplorerMenu({ anchor, label, actions, close }) {
1179
+ const ref = React.useRef(null);
1180
+ const document = anchor.row.ownerDocument;
1181
+ React.useLayoutEffect(() => {
1182
+ var _menu$querySelector;
1183
+ const menu = ref.current;
1184
+ const { width, height } = menu.getBoundingClientRect();
1185
+ menu.style.left = `${Math.max(4, Math.min(anchor.x, document.documentElement.clientWidth - width - 4))}px`;
1186
+ menu.style.top = `${Math.max(4, Math.min(anchor.y, document.documentElement.clientHeight - height - 4))}px`;
1187
+ (_menu$querySelector = menu.querySelector("button")) === null || _menu$querySelector === void 0 || _menu$querySelector.focus();
1188
+ const outside = (event) => {
1189
+ if (!menu.contains(event.target)) close(false);
1190
+ };
1191
+ document.addEventListener("pointerdown", outside, true);
1192
+ document.addEventListener("focusin", outside, true);
1193
+ return () => {
1194
+ document.removeEventListener("pointerdown", outside, true);
1195
+ document.removeEventListener("focusin", outside, true);
1196
+ };
1197
+ }, [anchor]);
1198
+ return createPortal(/* @__PURE__ */ React.createElement("div", {
1199
+ ref,
1200
+ role: "menu",
1201
+ "aria-label": label,
1202
+ className: "twpf-explorer-actions",
1203
+ onKeyDown: (event) => {
1204
+ var _buttons$next;
1205
+ if (event.key === "Tab") {
1206
+ close(true);
1207
+ return;
1208
+ }
1209
+ if (event.key === "Escape") {
1210
+ event.preventDefault();
1211
+ event.stopPropagation();
1212
+ close(true);
1213
+ return;
1214
+ }
1215
+ const buttons = Array.from(event.currentTarget.querySelectorAll("button"));
1216
+ const index = buttons.indexOf(document.activeElement);
1217
+ const next = {
1218
+ ArrowDown: (index + 1) % buttons.length,
1219
+ ArrowUp: (index + buttons.length - 1) % buttons.length,
1220
+ Home: 0,
1221
+ End: buttons.length - 1
1222
+ }[event.key];
1223
+ if (next === void 0) return;
1224
+ event.preventDefault();
1225
+ event.stopPropagation();
1226
+ (_buttons$next = buttons[next]) === null || _buttons$next === void 0 || _buttons$next.focus();
1227
+ }
1228
+ }, actions.map((action) => /* @__PURE__ */ React.createElement("button", {
1229
+ key: action.label,
1230
+ type: "button",
1231
+ role: "menuitem",
1232
+ tabIndex: -1,
1233
+ onClick: action.run
1234
+ }, action.label))), document.body);
1235
+ }
1236
+ function ExplorerFileDialog({ anchor, name, folder, rename, message, close, submit }) {
1237
+ const ref = React.useRef(null);
1238
+ const input = React.useRef(null);
1239
+ const cancel = React.useRef(null);
1240
+ const title = rename ? message.renameTitle : message.deleteTitle;
1241
+ React.useLayoutEffect(() => {
1242
+ var _cancel$current;
1243
+ const dialog = ref.current;
1244
+ dialog.showModal();
1245
+ if (input.current) {
1246
+ input.current.focus();
1247
+ input.current.select();
1248
+ } else (_cancel$current = cancel.current) === null || _cancel$current === void 0 || _cancel$current.focus();
1249
+ return () => {
1250
+ dialog.close();
1251
+ if (anchor.row.isConnected) anchor.row.focus({ preventScroll: true });
1252
+ };
1253
+ }, []);
1254
+ return createPortal(/* @__PURE__ */ React.createElement("dialog", {
1255
+ ref,
1256
+ "aria-label": title,
1257
+ className: "twpf-explorer-dialog",
1258
+ onCancel: (event) => {
1259
+ event.preventDefault();
1260
+ close();
1261
+ }
1262
+ }, /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
1263
+ var _input$current$value, _input$current;
1264
+ event.preventDefault();
1265
+ 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", {
1267
+ ref: input,
1268
+ defaultValue: name,
1269
+ 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", {
1271
+ ref: cancel,
1272
+ type: "button",
1273
+ onClick: close
1274
+ }, message.cancel), /* @__PURE__ */ React.createElement("button", { type: "submit" }, title)))), anchor.row.ownerDocument.body);
1275
+ }
1276
+ // src/file-preview.ts
1277
+ var mimeTypes = new Map(Object.entries({
1278
+ apng: "image/apng",
1279
+ avif: "image/avif",
1280
+ bmp: "image/bmp",
1281
+ gif: "image/gif",
1282
+ ico: "image/x-icon",
1283
+ jpg: "image/jpeg",
1284
+ jpeg: "image/jpeg",
1285
+ png: "image/png",
1286
+ svg: "image/svg+xml",
1287
+ webp: "image/webp",
1288
+ aac: "audio/aac",
1289
+ aif: "audio/aiff",
1290
+ aiff: "audio/aiff",
1291
+ flac: "audio/flac",
1292
+ m4a: "audio/mp4",
1293
+ mp3: "audio/mpeg",
1294
+ oga: "audio/ogg",
1295
+ ogg: "audio/ogg",
1296
+ opus: "audio/ogg",
1297
+ wav: "audio/wav",
1298
+ m4v: "video/mp4",
1299
+ mov: "video/quicktime",
1300
+ mp4: "video/mp4",
1301
+ ogv: "video/ogg",
1302
+ webm: "video/webm"
1303
+ }));
1304
+ var textLimit = 4194304;
1305
+ var styles = `
1306
+ .twpf-preview{box-sizing:border-box;height:100%;overflow:auto;padding:1rem;color:var(--text-primary,inherit);
1307
+ background:var(--ui-primary,transparent)}
1308
+ .twpf-preview:has(.twpf-text-file){padding:0;overflow:hidden}
1309
+ .twpf-preview img,.twpf-preview video{display:block;max-width:100%;max-height:100%;margin:auto;object-fit:contain}
1310
+ .twpf-preview audio{width:min(100%,32rem)}
1311
+ `;
1312
+ var messages$1 = {
1313
+ en: {
1314
+ loading: "Loading file…",
1315
+ failed: "This file could not be read.",
1316
+ unsupported: "This file cannot be previewed.",
1317
+ mediaError: "This media could not be opened.",
1318
+ large: "This text file is too large to open (4 MiB limit)."
1319
+ },
1320
+ ja: {
1321
+ loading: "ファイルを読み込んでいます…",
1322
+ failed: "このファイルを読み込めません。",
1323
+ unsupported: "このファイルはプレビューできません。",
1324
+ mediaError: "このメディアを開けません。",
1325
+ large: "このテキストファイルは開けるサイズの上限(4 MiB)を超えています。"
636
1326
  }
637
- }, ue = Object.defineProperty, de = Object.defineProperties, fe = Object.getOwnPropertyDescriptors, P = Object.getOwnPropertySymbols, F = Object.prototype.hasOwnProperty, I = Object.prototype.propertyIsEnumerable, L = (e, t, n) => t in e ? ue(e, t, {
638
- enumerable: !0,
639
- configurable: !0,
640
- writable: !0,
641
- value: n
642
- }) : e[t] = n, R = (e, t) => {
643
- for (var n in t || (t = {})) F.call(t, n) && L(e, n, t[n]);
644
- if (P) for (var n of P(t)) I.call(t, n) && L(e, n, t[n]);
645
- return e;
646
- }, z = (e, t) => de(e, fe(t)), B = (e) => {
647
- let [t] = c(() => ({ current: ie(e) })), [n, r] = c(() => t.current.getState());
648
- return s(() => {
649
- t.current.rebuildTree();
650
- }, [t]), t.current.setConfig((t) => z(R(R({}, t), e), {
651
- state: R(R({}, n), e.state),
652
- setState: (t) => {
653
- var n;
654
- r(t), (n = e.setState) == null || n.call(e, t);
1327
+ };
1328
+ async function fileAt(directory, path) {
1329
+ const parts = path.split("/");
1330
+ const name = parts.pop();
1331
+ for (const part of parts) directory = await directory.getDirectoryHandle(part);
1332
+ return directory.getFileHandle(name);
1333
+ }
1334
+ function createFilePreview(directory, documentId, { name, path }, locale, readBaseline) {
1335
+ return {
1336
+ reference: {
1337
+ providerId: "turbowarp-plus-project-folder",
1338
+ documentId
1339
+ },
1340
+ filename: name,
1341
+ title: name,
1342
+ transient: true,
1343
+ mount(element, close) {
1344
+ const message = locale.toLowerCase().startsWith("ja") ? messages$1.ja : messages$1.en;
1345
+ const { ownerDocument: document } = element;
1346
+ const panel = document.createElement("div");
1347
+ panel.className = "twpf-preview";
1348
+ const style = document.createElement("style");
1349
+ style.textContent = styles;
1350
+ const status = document.createElement("p");
1351
+ status.setAttribute("role", "status");
1352
+ status.textContent = message.loading;
1353
+ panel.append(style, status);
1354
+ element.append(panel);
1355
+ let disposed = false;
1356
+ let url;
1357
+ let media;
1358
+ let textSession;
1359
+ const readHandle = () => fileAt(directory, path);
1360
+ const show = (node) => status.replaceWith(node);
1361
+ const load = async () => {
1362
+ var _mimeTypes$get;
1363
+ const file = await (await readHandle()).getFile();
1364
+ if (disposed) return;
1365
+ const extension = name.includes(".") ? name.split(".").pop().toLowerCase() : "";
1366
+ const mime = (_mimeTypes$get = mimeTypes.get(extension)) !== null && _mimeTypes$get !== void 0 ? _mimeTypes$get : file.type;
1367
+ const kind = mime.split("/")[0];
1368
+ if (kind === "image" || kind === "audio" || kind === "video") {
1369
+ url = URL.createObjectURL(mime === file.type ? file : file.slice(0, file.size, mime));
1370
+ const view = document.createElement(kind === "image" ? "img" : kind);
1371
+ view.addEventListener("error", () => {
1372
+ status.textContent = message.mediaError;
1373
+ view.replaceWith(status);
1374
+ }, { once: true });
1375
+ if (view.tagName === "IMG") view.alt = name;
1376
+ else {
1377
+ media = view;
1378
+ media.controls = true;
1379
+ media.preload = "metadata";
1380
+ media.setAttribute("aria-label", name);
1381
+ }
1382
+ view.src = url;
1383
+ show(view);
1384
+ return;
1385
+ }
1386
+ if (file.size > 4194304) {
1387
+ status.textContent = message.large;
1388
+ return;
1389
+ }
1390
+ const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-kI7qYraF.js")]);
1391
+ if (disposed) return;
1392
+ const content = decodeText(bytes);
1393
+ if (content === null) {
1394
+ status.textContent = message.unsupported;
1395
+ return;
1396
+ }
1397
+ textSession = mountTextFile(panel, {
1398
+ path,
1399
+ extension,
1400
+ content,
1401
+ locale,
1402
+ limit: textLimit,
1403
+ readHandle,
1404
+ close,
1405
+ readBaseline: readBaseline && (() => readBaseline(directory, path, 4194304))
1406
+ });
1407
+ status.remove();
1408
+ };
1409
+ load().catch(() => {
1410
+ if (!disposed) status.textContent = message.failed;
1411
+ });
1412
+ return {
1413
+ requestClose() {
1414
+ if (textSession) textSession.requestClose();
1415
+ else close();
1416
+ },
1417
+ dispose() {
1418
+ disposed = true;
1419
+ textSession === null || textSession === void 0 || textSession.dispose();
1420
+ media === null || media === void 0 || media.pause();
1421
+ if (url) URL.revokeObjectURL(url);
1422
+ panel.remove();
1423
+ }
1424
+ };
655
1425
  }
656
- })), t.current;
657
- }, V = {
1426
+ };
1427
+ }
1428
+ // src/explorer.tsx
1429
+ var messages = {
658
1430
  en: {
659
1431
  label: "Project folder",
660
1432
  loading: "Loading…",
661
1433
  empty: "This folder is empty.",
662
1434
  noFolder: "Open a project folder to show its files here.",
663
1435
  open: "Open Project Folder…",
1436
+ unavailable: "File tabs are unavailable in this editor layout.",
664
1437
  failed: "This folder could not be read.",
665
1438
  denied: "Permission to read this folder was not granted.",
666
1439
  separator: ", ",
@@ -670,15 +1443,22 @@ var x = (e, t = 100, n = 1e3) => new Promise((r) => {
670
1443
  deleted: "Deleted",
671
1444
  untracked: "Untracked"
672
1445
  },
1446
+ unsaved: "Unsaved changes",
1447
+ staged: "Staged",
1448
+ revisions: {
1449
+ committed: "Committed",
1450
+ pushed: "Pushed",
1451
+ merged: "Pull request merged"
1452
+ },
673
1453
  project: "Project data",
674
1454
  manifest: "Folder manifest",
675
1455
  extensions: "Embedded extensions",
676
1456
  assetsDirectory: "Costume and sound files",
677
1457
  extensionsDirectory: "Extension files",
678
- costume: (e, t) => `${e} · costume ${t}`,
679
- backdrop: (e) => `Stage · backdrop ${e}`,
680
- sound: (e, t) => `${e} · sound ${t}`,
681
- stageSound: (e) => `Stage · sound ${e}`
1458
+ costume: (sprite, name) => `${sprite} · costume ${name}`,
1459
+ backdrop: (name) => `Stage · backdrop ${name}`,
1460
+ sound: (sprite, name) => `${sprite} · sound ${name}`,
1461
+ stageSound: (name) => `Stage · sound ${name}`
682
1462
  },
683
1463
  ja: {
684
1464
  label: "作品フォルダ",
@@ -686,6 +1466,7 @@ var x = (e, t = 100, n = 1e3) => new Promise((r) => {
686
1466
  empty: "このフォルダは空です。",
687
1467
  noFolder: "プロジェクトフォルダを開くと、ここにファイルを表示します。",
688
1468
  open: "プロジェクトフォルダを開く…",
1469
+ unavailable: "このエディターのレイアウトではファイルをタブで開けません。",
689
1470
  failed: "このフォルダを読み込めません。",
690
1471
  denied: "このフォルダを読む許可がありません。",
691
1472
  separator: "、",
@@ -695,94 +1476,134 @@ var x = (e, t = 100, n = 1e3) => new Promise((r) => {
695
1476
  deleted: "削除",
696
1477
  untracked: "未追跡"
697
1478
  },
1479
+ unsaved: "未保存の変更あり",
1480
+ staged: "ステージ済み",
1481
+ revisions: {
1482
+ committed: "コミット済み",
1483
+ pushed: "プッシュ済み",
1484
+ merged: "PR マージ済み"
1485
+ },
698
1486
  project: "作品データ",
699
1487
  manifest: "作品フォルダの目録",
700
1488
  extensions: "埋め込み拡張の一覧",
701
1489
  assetsDirectory: "コスチュームと音のファイル",
702
1490
  extensionsDirectory: "拡張のファイル",
703
- costume: (e, t) => `${e} のコスチューム ${t}`,
704
- backdrop: (e) => `ステージの背景 ${e}`,
705
- sound: (e, t) => `${e} の音 ${t}`,
706
- stageSound: (e) => `ステージの音 ${e}`
1491
+ costume: (sprite, name) => `${sprite} のコスチューム ${name}`,
1492
+ backdrop: (name) => `ステージの背景 ${name}`,
1493
+ sound: (sprite, name) => `${sprite} の音 ${name}`,
1494
+ stageSound: (name) => `ステージの音 ${name}`
707
1495
  }
708
- }, H = (e = "en") => e.toLowerCase().startsWith("ja") ? V.ja : V.en;
709
- function U(e, t, { manifest: i, folder: o = "" } = {}) {
710
- let s = H(t), c = o.replace(/^\/+|\/+$/gu, ""), l = (e) => c ? `${c}/${e}` : e, u = a(i) && typeof i.assetsDirectory == "string" && i.assetsDirectory ? i.assetsDirectory.replace(/^\/+|\/+$/gu, "") : "assets", d = a(i) && typeof i.embeddedExtensions == "string" ? i.embeddedExtensions : "embedded-extensions.json", f = /* @__PURE__ */ new Map([
711
- [l(r), s.project],
712
- [l(n), s.manifest],
713
- [l(d), s.extensions],
714
- [l(u), s.assetsDirectory],
715
- [l("extensions"), s.extensionsDirectory]
716
- ]), p = /* @__PURE__ */ new Map();
717
- for (let t of Array.isArray(e.targets) ? e.targets : []) {
718
- if (!a(t)) continue;
719
- let e = typeof t.name == "string" ? t.name : "";
720
- for (let n of ["costumes", "sounds"]) {
721
- let r = t[n];
722
- if (Array.isArray(r)) for (let i of r) {
723
- var m;
724
- if (!a(i) || typeof i.assetId != "string" || typeof i.dataFormat != "string") continue;
725
- let r = typeof i.md5ext == "string" ? i.md5ext : `${i.assetId}.${i.dataFormat}`, o = typeof i.name == "string" ? i.name : "", c = n === "costumes" ? t.isStage ? s.backdrop(o) : s.costume(e, o) : t.isStage ? s.stageSound(o) : s.sound(e, o), d = l(`${u}/${r}`), f = (m = p.get(d)) == null ? [] : m;
726
- f.includes(c) || f.push(c), p.set(d, f);
1496
+ };
1497
+ var messagesFor = (locale = "en") => locale.toLowerCase().startsWith("ja") ? messages.ja : messages.en;
1498
+ /**
1499
+ * Describes the files of a project folder for `ProjectFolderExplorer`'s `descriptions`: the project, manifest and
1500
+ * extension files, and each asset file with the costumes and sounds that use it. `folder` is the project folder's
1501
+ * path inside the explorer's root ('' when the root is the project folder). Malformed entries are skipped.
1502
+ */
1503
+ function describeProjectFolder(project, locale, { manifest, folder = "" } = {}) {
1504
+ const message = messagesFor(locale);
1505
+ const prefix = folder.replace(/^\/+|\/+$/gu, "");
1506
+ const at = (name) => prefix ? `${prefix}/${name}` : name;
1507
+ const assetsDirectory = isObject(manifest) && typeof manifest.assetsDirectory === "string" && manifest.assetsDirectory ? manifest.assetsDirectory.replace(/^\/+|\/+$/gu, "") : "assets";
1508
+ const extensions = isObject(manifest) && typeof manifest.embeddedExtensions === "string" ? manifest.embeddedExtensions : "embedded-extensions.json";
1509
+ const descriptions = /* @__PURE__ */ new Map([
1510
+ [at(projectFile), message.project],
1511
+ [at(manifestFile), message.manifest],
1512
+ [at(extensions), message.extensions],
1513
+ [at(assetsDirectory), message.assetsDirectory],
1514
+ [at("extensions"), message.extensionsDirectory]
1515
+ ]);
1516
+ const users = /* @__PURE__ */ new Map();
1517
+ for (const target of Array.isArray(project.targets) ? project.targets : []) {
1518
+ if (!isObject(target)) continue;
1519
+ const sprite = typeof target.name === "string" ? target.name : "";
1520
+ for (const kind of ["costumes", "sounds"]) {
1521
+ const entries = target[kind];
1522
+ if (!Array.isArray(entries)) continue;
1523
+ for (const entry of entries) {
1524
+ var _users$get;
1525
+ if (!isObject(entry) || typeof entry.assetId !== "string" || typeof entry.dataFormat !== "string") continue;
1526
+ const file = typeof entry.md5ext === "string" ? entry.md5ext : `${entry.assetId}.${entry.dataFormat}`;
1527
+ const name = typeof entry.name === "string" ? entry.name : "";
1528
+ const text = kind === "costumes" ? target.isStage ? message.backdrop(name) : message.costume(sprite, name) : target.isStage ? message.stageSound(name) : message.sound(sprite, name);
1529
+ const path = at(`${assetsDirectory}/${file}`);
1530
+ const list = (_users$get = users.get(path)) !== null && _users$get !== void 0 ? _users$get : [];
1531
+ if (!list.includes(text)) list.push(text);
1532
+ users.set(path, list);
727
1533
  }
728
1534
  }
729
1535
  }
730
- for (let [e, t] of p) f.set(e, t.join(s.separator));
731
- return f;
1536
+ for (const [path, list] of users) descriptions.set(path, list.join(message.separator));
1537
+ return descriptions;
732
1538
  }
733
- var W = "/", pe = (e) => `${e}\0error`, me = (e, t) => e instanceof DOMException && (e.name === "NotAllowedError" || e.name === "SecurityError") ? t.denied : t.failed, G = "twpf-explorer", K = `.${G}{font:inherit;color:inherit}
734
- .${G}-item{display:flex;align-items:center;gap:.4em;width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
1539
+ var rootId = "/";
1540
+ var errorId = (parent) => `${parent}\0error`;
1541
+ var failure = (error, message) => error instanceof DOMException && (error.name === "NotAllowedError" || error.name === "SecurityError") ? message.denied : message.failed;
1542
+ var prefix = "twpf-explorer";
1543
+ var css = `.${prefix}{font:inherit;color:inherit}
1544
+ .${prefix}-item{display:flex;align-items:center;gap:.4em;width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
735
1545
  padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer;white-space:nowrap}
736
- .${G}-item:hover{background:rgba(128,128,128,.12)}
737
- .${G}-item[aria-selected="true"]{background:rgba(128,128,128,.24)}
738
- .${G}-item:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
739
- .${G}-caret{display:inline-block;width:1em;flex:none;text-align:center}
740
- .${G}-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:none}
741
- .${G}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
1546
+ .${prefix}-item:hover{background:rgba(128,128,128,.12)}
1547
+ .${prefix}-item[aria-selected="true"]{background:rgba(128,128,128,.24)}
1548
+ .${prefix}-item:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
1549
+ .${prefix}-caret{display:inline-block;width:1em;flex:none;text-align:center}
1550
+ .${prefix}-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:none}
1551
+ .${prefix}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
742
1552
  background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50%) 0 0/8px 8px}
743
- .${G}-icon img[hidden]{display:none}
744
- .${G}-name{overflow:hidden;text-overflow:ellipsis}
745
- .${G}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
746
- .${G}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
747
- .${G}-status{opacity:.7;font-style:italic;padding-block:.15em}
748
- .${G}-empty{padding:.5em}
749
- .${G}-empty p{margin:0 0 .6em}
750
- .${G}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.2em .6em;font:inherit;cursor:pointer}`, q = (e) => ({ paddingInlineStart: `${.25 + e * 1.1}em` }), J = "M3.5 1.5h6l3 3v10h-9z", Y = "M9.5 1.5v3h3", he = {
751
- folder: ["M1.5 3.5h4l1.5 1.5h7.5v8h-13z"],
1553
+ .${prefix}-icon img[hidden]{display:none}
1554
+ .${prefix}-filename{display:inline-flex;min-width:0}
1555
+ .${prefix}-name{overflow:hidden;text-overflow:ellipsis}
1556
+ .${prefix}-item[data-staged] .${prefix}-filename{font-weight:700}
1557
+ .${prefix}-item[data-revision="committed"] .${prefix}-filename{color:#174b9d;color:light-dark(#174b9d,#91c1ff)}
1558
+ .${prefix}-item[data-revision="pushed"] .${prefix}-filename{color:#67369a;color:light-dark(#67369a,#dfafff)}
1559
+ .${prefix}-item[data-revision="merged"] .${prefix}-filename{color:#17603e;color:light-dark(#17603e,#85e3ad)}
1560
+ .${prefix}-unsaved{flex:none}
1561
+ .${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
1562
+ .${prefix}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
1563
+ .${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
1564
+ .${prefix}-empty{padding:.5em}
1565
+ .${prefix}-empty p{margin:0 0 .6em}
1566
+ .${prefix}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.2em .6em;font:inherit;cursor:pointer}`;
1567
+ var indent = (level) => ({ paddingInlineStart: `${.25 + level * 1.1}em` });
1568
+ var page = "M3.5 1.5h6l3 3v10h-9z";
1569
+ var corner = "M9.5 1.5v3h3";
1570
+ var icons = {
1571
+ "folder": ["M1.5 3.5h4l1.5 1.5h7.5v8h-13z"],
752
1572
  "folder-open": ["M1.5 13V3.5h4l1.5 1.5h6v2", "M1.5 13l2-6h11l-2 6z"],
753
- project: [
1573
+ "project": [
754
1574
  "M8 1.5l6 3v7l-6 3-6-3v-7z",
755
1575
  "M2 4.5l6 3 6-3",
756
1576
  "M8 7.5v7"
757
1577
  ],
758
- json: [
759
- J,
760
- Y,
1578
+ "json": [
1579
+ page,
1580
+ corner,
761
1581
  "M7 7c-1 0-1 .6-1 1.4s-.3 1.1-.8 1.1c.5 0 .8.4.8 1.1S6 12 7 12",
762
1582
  "M9 7c1 0 1 .6 1 1.4s.3 1.1.8 1.1c-.5 0-.8.4-.8 1.1S10 12 9 12"
763
1583
  ],
764
- image: [
1584
+ "image": [
765
1585
  "M1.5 2.5h13v11h-13z",
766
1586
  "M1.5 11l4-4 3 3 2-2 4 4",
767
1587
  "M12.2 5.5a1.2 1.2 0 1 1-2.4 0a1.2 1.2 0 1 1 2.4 0"
768
1588
  ],
769
- sound: [
1589
+ "sound": [
770
1590
  "M2 6h3l3.5-3v10L5 10H2z",
771
1591
  "M10.5 5.5a3.5 3.5 0 0 1 0 5",
772
1592
  "M12.5 3.5a6.5 6.5 0 0 1 0 9"
773
1593
  ],
774
- code: [
1594
+ "code": [
775
1595
  "M5.5 4.5L2 8l3.5 3.5",
776
1596
  "M10.5 4.5L14 8l-3.5 3.5",
777
1597
  "M9 3l-2 10"
778
1598
  ],
779
- text: [
780
- J,
781
- Y,
1599
+ "text": [
1600
+ page,
1601
+ corner,
782
1602
  "M5.5 7.5h5M5.5 9.5h5M5.5 11.5h3"
783
1603
  ],
784
- file: [J, Y]
785
- }, ge = {
1604
+ "file": [page, corner]
1605
+ };
1606
+ var extensionIcons = {
786
1607
  json: "json",
787
1608
  svg: "image",
788
1609
  png: "image",
@@ -799,37 +1620,54 @@ background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50
799
1620
  ts: "code",
800
1621
  md: "text",
801
1622
  txt: "text"
802
- }, _e = (e) => {
803
- var t;
804
- return e === "project.source.json" || e === "sb3-source.json" ? "project" : (t = ge[e.slice(e.lastIndexOf(".") + 1).toLowerCase()]) == null ? "file" : t;
805
- }, ve = 2097152;
806
- function ye({ kind: e, path: t, readFile: n }) {
807
- let r = o.useRef(null), [i, a] = o.useState("waiting"), [s, c] = o.useState();
808
- return o.useEffect(() => {
809
- if (!n) return;
810
- let e = !0, i, o = async () => {
811
- a("loading");
1623
+ };
1624
+ var iconFor = (name) => {
1625
+ var _extensionIcons$name$;
1626
+ return name === "project.source.json" || name === "sb3-source.json" ? "project" : (_extensionIcons$name$ = extensionIcons[name.slice(name.lastIndexOf(".") + 1).toLowerCase()]) !== null && _extensionIcons$name$ !== void 0 ? _extensionIcons$name$ : "file";
1627
+ };
1628
+ var thumbnailLimit = 2097152;
1629
+ function Icon({ kind, path, readFile }) {
1630
+ const ref = React.useRef(null);
1631
+ const [state, setState] = React.useState("waiting");
1632
+ const [url, setUrl] = React.useState();
1633
+ React.useEffect(() => {
1634
+ if (!readFile) return void 0;
1635
+ let live = true;
1636
+ let created;
1637
+ const load = async () => {
1638
+ setState("loading");
812
1639
  try {
813
- let r = await n(t);
814
- if (!e) return;
815
- if (r.size > ve) return a("skipped");
816
- i = URL.createObjectURL(r), c(i);
817
- } catch (t) {
818
- e && a("failed");
1640
+ const file = await readFile(path);
1641
+ if (!live) return;
1642
+ if (file.size > thumbnailLimit) return setState("skipped");
1643
+ created = URL.createObjectURL(file);
1644
+ setUrl(created);
1645
+ } catch (_unused) {
1646
+ if (live) setState("failed");
819
1647
  }
820
- }, s;
821
- return typeof IntersectionObserver == "function" && r.current ? (s = new IntersectionObserver((e) => {
822
- e.some((e) => e.isIntersecting) && (s == null || s.disconnect(), o());
823
- }), s.observe(r.current)) : o(), () => {
824
- e = !1, s == null || s.disconnect(), i && URL.revokeObjectURL(i);
825
1648
  };
826
- }, [t]), /* @__PURE__ */ o.createElement("span", {
827
- ref: r,
828
- className: `${G}-icon`,
1649
+ let observer;
1650
+ if (typeof IntersectionObserver === "function" && ref.current) {
1651
+ observer = new IntersectionObserver((entries) => {
1652
+ if (!entries.some((entry) => entry.isIntersecting)) return;
1653
+ observer === null || observer === void 0 || observer.disconnect();
1654
+ load();
1655
+ });
1656
+ observer.observe(ref.current);
1657
+ } else load();
1658
+ return () => {
1659
+ live = false;
1660
+ observer === null || observer === void 0 || observer.disconnect();
1661
+ if (created) URL.revokeObjectURL(created);
1662
+ };
1663
+ }, [path]);
1664
+ return /* @__PURE__ */ React.createElement("span", {
1665
+ ref,
1666
+ className: `${prefix}-icon`,
829
1667
  "aria-hidden": "true",
830
- "data-icon": e,
831
- "data-thumbnail": n ? i : void 0
832
- }, i === "loaded" ? null : /* @__PURE__ */ o.createElement("svg", {
1668
+ "data-icon": kind,
1669
+ "data-thumbnail": readFile ? state : void 0
1670
+ }, state === "loaded" ? null : /* @__PURE__ */ React.createElement("svg", {
833
1671
  viewBox: "0 0 16 16",
834
1672
  width: "16",
835
1673
  height: "16",
@@ -839,123 +1677,160 @@ function ye({ kind: e, path: t, readFile: n }) {
839
1677
  strokeLinecap: "round",
840
1678
  strokeLinejoin: "round",
841
1679
  focusable: "false"
842
- }, he[e].map((e) => /* @__PURE__ */ o.createElement("path", {
843
- key: e,
844
- d: e
845
- }))), s && i !== "failed" ? /* @__PURE__ */ o.createElement("img", {
846
- src: s,
1680
+ }, icons[kind].map((d) => /* @__PURE__ */ React.createElement("path", {
1681
+ key: d,
1682
+ d
1683
+ }))), url && state !== "failed" ? /* @__PURE__ */ React.createElement("img", {
1684
+ src: url,
847
1685
  alt: "",
848
1686
  decoding: "async",
849
- hidden: i !== "loaded",
850
- onLoad: () => a("loaded"),
851
- onError: () => a("failed")
1687
+ hidden: state !== "loaded",
1688
+ onLoad: () => setState("loaded"),
1689
+ onError: () => setState("failed")
852
1690
  }) : null);
853
1691
  }
854
- function X({ directory: n, locale: r, descriptions: i, marks: a, onOpen: s, label: c }) {
855
- let l = H(r), [u] = o.useState(() => /* @__PURE__ */ new Map([[W, n]])), [d] = o.useState(() => /* @__PURE__ */ new Map()), [f, p] = o.useState(!1), m = o.useMemo(() => new Intl.Collator(r, {
856
- numeric: !0,
1692
+ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsavedPaths, refreshKey, onOpen, label, mutate, git, isCurrent }) {
1693
+ const message = messagesFor(locale);
1694
+ const actions = actionMessages(locale);
1695
+ const [handles] = React.useState(() => /* @__PURE__ */ new Map([[rootId, directory]]));
1696
+ const [files] = React.useState(() => /* @__PURE__ */ new Map());
1697
+ const [loadedFolders] = React.useState(() => /* @__PURE__ */ new Set());
1698
+ const [rootLoaded, setRootLoaded] = React.useState(false);
1699
+ const [drag, setDrag] = React.useState(null);
1700
+ const [menu, setMenu] = React.useState();
1701
+ const [dialog, setDialog] = React.useState();
1702
+ const [feedback, setFeedback] = React.useState("");
1703
+ const [working, setWorking] = React.useState(false);
1704
+ const running = React.useRef(false);
1705
+ const mounted = React.useRef(true);
1706
+ React.useEffect(() => {
1707
+ mounted.current = true;
1708
+ return () => {
1709
+ mounted.current = false;
1710
+ };
1711
+ }, []);
1712
+ const collator = React.useMemo(() => new Intl.Collator(locale, {
1713
+ numeric: true,
857
1714
  sensitivity: "base"
858
- }), [r]), h = async (e) => {
859
- let t = u.get(e);
860
- if (t) return t;
861
- t = n;
862
- for (let n of e.split("/")) t = await t.getDirectoryHandle(n);
863
- return u.set(e, t), t;
864
- }, g = async (e) => {
865
- let t = d.get(e);
866
- if (!t) {
867
- let r = e.split("/"), i = r.pop();
868
- t = await (r.length ? await h(r.join("/")) : n).getFileHandle(i);
1715
+ }), [locale]);
1716
+ const directoryAt = async (id) => {
1717
+ let handle = handles.get(id);
1718
+ if (handle) return handle;
1719
+ handle = directory;
1720
+ for (const name of id.split("/")) handle = await handle.getDirectoryHandle(name);
1721
+ handles.set(id, handle);
1722
+ return handle;
1723
+ };
1724
+ const readFile = async (path) => {
1725
+ let handle = files.get(path);
1726
+ if (!handle) {
1727
+ const parts = path.split("/");
1728
+ const name = parts.pop();
1729
+ handle = await (parts.length ? await directoryAt(parts.join("/")) : directory).getFileHandle(name);
869
1730
  }
870
- return t.getFile();
871
- }, _ = B({
872
- rootItemId: W,
1731
+ return handle.getFile();
1732
+ };
1733
+ const tree = useTree({
1734
+ rootItemId: rootId,
873
1735
  initialState: {
874
1736
  expandedItems: [],
875
1737
  selectedItems: [],
876
1738
  focusedItem: null
877
1739
  },
878
- getItemName: (e) => {
879
- var t, n;
880
- return (t = (n = e.getItemData()) == null ? void 0 : n.name) == null ? "" : t;
1740
+ getItemName: (item) => {
1741
+ var _item$getItemData$nam, _item$getItemData;
1742
+ return (_item$getItemData$nam = (_item$getItemData = item.getItemData()) === null || _item$getItemData === void 0 ? void 0 : _item$getItemData.name) !== null && _item$getItemData$nam !== void 0 ? _item$getItemData$nam : "";
881
1743
  },
882
- isItemFolder: (e) => {
883
- var t;
884
- return ((t = e.getItemData()) == null ? void 0 : t.kind) === "directory";
1744
+ isItemFolder: (item) => {
1745
+ var _item$getItemData2;
1746
+ return ((_item$getItemData2 = item.getItemData()) === null || _item$getItemData2 === void 0 ? void 0 : _item$getItemData2.kind) === "directory";
885
1747
  },
886
1748
  createLoadingItemData: () => ({
887
1749
  name: "",
888
1750
  path: "",
889
1751
  kind: "file"
890
1752
  }),
891
- onPrimaryAction: (e) => {
892
- let t = e.getItemData();
893
- (t == null ? void 0 : t.kind) === "file" && (s == null || s({
894
- path: t.path,
895
- name: t.name,
1753
+ onPrimaryAction: (item) => {
1754
+ const data = item.getItemData();
1755
+ if ((data === null || data === void 0 ? void 0 : data.kind) === "file") onOpen === null || onOpen === void 0 || onOpen({
1756
+ path: data.path,
1757
+ name: data.name,
896
1758
  kind: "file"
897
- }));
1759
+ });
898
1760
  },
899
- onLoadedChildren: (e) => {
900
- e === W && p(!0);
1761
+ onLoadedChildren: (id) => {
1762
+ if (id === rootId) setRootLoaded(true);
901
1763
  },
902
1764
  dataLoader: {
903
- getItem: async (e) => {
904
- if (e === W) return {
905
- name: n.name,
1765
+ getItem: async (id) => {
1766
+ if (id === rootId) return {
1767
+ name: directory.name,
906
1768
  path: "",
907
1769
  kind: "directory"
908
1770
  };
909
- let t = e.split("/"), r = t.pop(), i = t.length ? await h(t.join("/")) : n;
1771
+ const parts = id.split("/");
1772
+ const name = parts.pop();
1773
+ const parent = parts.length ? await directoryAt(parts.join("/")) : directory;
910
1774
  try {
911
- return await i.getDirectoryHandle(r), {
912
- name: r,
913
- path: e,
1775
+ await parent.getDirectoryHandle(name);
1776
+ return {
1777
+ name,
1778
+ path: id,
914
1779
  kind: "directory"
915
1780
  };
916
- } catch (t) {
917
- return await i.getFileHandle(r), {
918
- name: r,
919
- path: e,
1781
+ } catch (_unused2) {
1782
+ await parent.getFileHandle(name);
1783
+ return {
1784
+ name,
1785
+ path: id,
920
1786
  kind: "file"
921
1787
  };
922
1788
  }
923
1789
  },
924
- getChildrenWithData: async (t) => {
1790
+ getChildrenWithData: async (id) => {
925
1791
  try {
926
- let s = await h(t), c = t === W ? "" : `${t}/`, l = [];
927
- var n = !1, r = !1, i;
1792
+ const handle = await directoryAt(id);
1793
+ const base = id === rootId ? "" : `${id}/`;
1794
+ const nodes = [];
1795
+ var _iteratorAbruptCompletion = false;
1796
+ var _didIteratorError = false;
1797
+ var _iteratorError;
928
1798
  try {
929
- for (var a = e(s.values()), o; n = !(o = await a.next()).done; n = !1) {
930
- let e = o.value;
1799
+ for (var _iterator = _asyncIterator(handle.values()), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
1800
+ const entry = _step.value;
931
1801
  {
932
- if (e.kind === "directory" && e.name === ".git") continue;
933
- let t = c + e.name;
934
- e.kind === "directory" ? u.set(t, e) : d.set(t, e), l.push({
935
- name: e.name,
936
- path: t,
937
- kind: e.kind
1802
+ if (entry.name.toLowerCase() === ".git") continue;
1803
+ const path = base + entry.name;
1804
+ if (entry.kind === "directory") handles.set(path, entry);
1805
+ else files.set(path, entry);
1806
+ nodes.push({
1807
+ name: entry.name,
1808
+ path,
1809
+ kind: entry.kind
938
1810
  });
939
1811
  }
940
1812
  }
941
- } catch (e) {
942
- r = !0, i = e;
1813
+ } catch (err) {
1814
+ _didIteratorError = true;
1815
+ _iteratorError = err;
943
1816
  } finally {
944
1817
  try {
945
- n && a.return != null && await a.return();
1818
+ if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
946
1819
  } finally {
947
- if (r) throw i;
1820
+ if (_didIteratorError) throw _iteratorError;
948
1821
  }
949
1822
  }
950
- return l.sort((e, t) => (e.kind === "directory" ? 0 : 1) - (t.kind === "directory" ? 0 : 1) || m.compare(e.name, t.name) || (e.name < t.name ? -1 : +(e.name > t.name))), l.map((e) => ({
951
- id: e.path,
952
- data: e
1823
+ loadedFolders.add(id);
1824
+ nodes.sort((a, b) => (a.kind === "directory" ? 0 : 1) - (b.kind === "directory" ? 0 : 1) || collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1825
+ return nodes.map((data) => ({
1826
+ id: data.path,
1827
+ data
953
1828
  }));
954
- } catch (e) {
1829
+ } catch (error) {
955
1830
  return [{
956
- id: pe(t),
1831
+ id: errorId(id),
957
1832
  data: {
958
- name: me(e, l),
1833
+ name: failure(error, message),
959
1834
  path: "",
960
1835
  kind: "error"
961
1836
  }
@@ -964,96 +1839,409 @@ function X({ directory: n, locale: r, descriptions: i, marks: a, onOpen: s, labe
964
1839
  }
965
1840
  },
966
1841
  features: [
967
- le,
968
- ae,
969
- ce
1842
+ asyncDataLoaderFeature,
1843
+ selectionFeature,
1844
+ hotkeysCoreFeature
970
1845
  ]
971
1846
  });
972
- o.useEffect(() => (_.setMounted(!0), () => _.setMounted(!1)), [_]);
973
- let v = (e) => {
974
- let n = e.getItemData(), r = e.getItemMeta().level, s = e.isFolder(), c = s && e.isExpanded(), u = n && n.kind !== "error" ? a == null ? void 0 : a.get(n.path) : void 0, d = u ? l.marks[u] : "", f = n && n.kind !== "error" ? i == null ? void 0 : i.get(n.path) : void 0, p = !n || n.kind === "error" ? void 0 : s ? c ? "folder-open" : "folder" : _e(n.name), m = [
975
- e.getItemName(),
976
- d,
977
- f
978
- ].filter(Boolean).join(l.separator), h = [/* @__PURE__ */ o.createElement("button", t(t({}, e.getProps()), {}, {
979
- key: e.getId(),
1847
+ React.useEffect(() => {
1848
+ tree.setMounted(true);
1849
+ return () => tree.setMounted(false);
1850
+ }, [tree]);
1851
+ const lastRefresh = React.useRef(refreshKey);
1852
+ React.useEffect(() => {
1853
+ if (lastRefresh.current === refreshKey) return;
1854
+ lastRefresh.current = refreshKey;
1855
+ Promise.all([...loadedFolders].map((id) => tree.getItemInstance(id).invalidateChildrenIds(true)));
1856
+ }, [
1857
+ tree,
1858
+ loadedFolders,
1859
+ refreshKey
1860
+ ]);
1861
+ const errorText = (error) => {
1862
+ if (error instanceof ExplorerFileError) return actions[error.code];
1863
+ if (error instanceof DOMException && ["NotAllowedError", "SecurityError"].includes(error.name)) return actions.denied;
1864
+ if (error instanceof FolderError && error.code === "conflict") return actions.conflict;
1865
+ return actions.failed;
1866
+ };
1867
+ const run = async (operation) => {
1868
+ if (running.current) return;
1869
+ running.current = true;
1870
+ setWorking(true);
1871
+ setFeedback("");
1872
+ try {
1873
+ const result = await operation();
1874
+ if (mounted.current) setFeedback(result !== null && result !== void 0 ? result : "");
1875
+ } catch (error) {
1876
+ if (mounted.current) setFeedback(errorText(error));
1877
+ } finally {
1878
+ running.current = false;
1879
+ if (mounted.current) setWorking(false);
1880
+ }
1881
+ };
1882
+ const write = (path, operation) => mutate(async (guard) => {
1883
+ const permission = directory.requestPermission;
1884
+ if (permission && await permission.call(directory, { mode: "readwrite" }) !== "granted") throw new DOMException("Write permission denied", "NotAllowedError");
1885
+ guard();
1886
+ const parent = await resolveExplorerDirectory(directory, path);
1887
+ guard();
1888
+ await operation(parent, guard);
1889
+ });
1890
+ const reread = async (path, expand = false) => {
1891
+ if (!mounted.current) return;
1892
+ const parent = path ? tree.getItemInstance(path) : tree.getRootItem();
1893
+ if (expand && path && !parent.isExpanded()) parent.expand();
1894
+ await parent.invalidateChildrenIds(true);
1895
+ };
1896
+ const forget = (path) => {
1897
+ const cache = tree.getDataRef();
1898
+ for (const id of handles.keys()) {
1899
+ if (id !== path && !id.startsWith(`${path}/`)) continue;
1900
+ delete cache.current.childrenIds[id];
1901
+ loadedFolders.delete(id);
1902
+ handles.delete(id);
1903
+ }
1904
+ for (const id of files.keys()) if (id === path || id.startsWith(`${path}/`)) files.delete(id);
1905
+ };
1906
+ const dropPath = (target) => {
1907
+ var _target$closest$getAt, _target$closest;
1908
+ 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
+ };
1910
+ const acceptsFiles = (event) => Boolean(mutate && event.dataTransfer.types.includes("Files"));
1911
+ const drop = (event) => {
1912
+ if (!acceptsFiles(event)) return;
1913
+ event.preventDefault();
1914
+ event.stopPropagation();
1915
+ setDrag(null);
1916
+ const path = dropPath(event.target);
1917
+ const items = Array.from(event.dataTransfer.items);
1918
+ const problems = [];
1919
+ const dropped = items.length ? items.flatMap((item) => {
1920
+ var _item$webkitGetAsEntr;
1921
+ if (item.kind !== "file") return [];
1922
+ const entry = (_item$webkitGetAsEntr = item.webkitGetAsEntry) === null || _item$webkitGetAsEntr === void 0 ? void 0 : _item$webkitGetAsEntr.call(item);
1923
+ if (entry === null || entry === void 0 ? void 0 : entry.isDirectory) {
1924
+ problems.push(`${entry.name} — ${actions.filesOnly}`);
1925
+ return [];
1926
+ }
1927
+ const file = item.getAsFile();
1928
+ return file ? [file] : [];
1929
+ }) : Array.from(event.dataTransfer.files);
1930
+ run(async () => {
1931
+ if (!dropped.length) return problems.join("\n") || actions.filesOnly;
1932
+ try {
1933
+ await write(path, async (parent, guard) => {
1934
+ for (const file of dropped) {
1935
+ guard();
1936
+ try {
1937
+ await copyExplorerFile(parent, file, guard);
1938
+ } catch (error) {
1939
+ problems.push(`${actions.copyFailed} ${file.name} — ${errorText(error)}`);
1940
+ }
1941
+ }
1942
+ });
1943
+ } finally {
1944
+ await reread(path, true);
1945
+ await (git === null || git === void 0 ? void 0 : git.refresh());
1946
+ }
1947
+ return problems.join("\n");
1948
+ });
1949
+ };
1950
+ const closeMenu = (restoreFocus) => {
1951
+ setMenu(void 0);
1952
+ if (restoreFocus && (menu === null || menu === void 0 ? void 0 : menu.anchor.row.isConnected)) menu.anchor.row.focus({ preventScroll: true });
1953
+ };
1954
+ const showMenu = (event, entry) => {
1955
+ if (running.current || !mutate && !git) return;
1956
+ event.preventDefault();
1957
+ event.stopPropagation();
1958
+ const row = event.currentTarget;
1959
+ const rect = row.getBoundingClientRect();
1960
+ const pointer = "clientX" in event && (event.clientX || event.clientY);
1961
+ setMenu({
1962
+ entry,
1963
+ anchor: {
1964
+ row,
1965
+ x: pointer ? event.clientX : rect.left,
1966
+ y: pointer ? event.clientY : rect.bottom
1967
+ }
1968
+ });
1969
+ };
1970
+ const submitFileAction = (name) => {
1971
+ if (!dialog) return;
1972
+ const { entry, rename } = dialog;
1973
+ setDialog(void 0);
1974
+ if (rename && entry.name === name) return;
1975
+ run(async () => {
1976
+ const parent = parentPath(entry.path);
1977
+ try {
1978
+ await write(parent, (handle, guard) => rename ? renameExplorerEntry(handle, entry, name, guard) : deleteExplorerEntry(handle, entry, guard));
1979
+ } finally {
1980
+ if (mounted.current) forget(entry.path);
1981
+ await reread(parent);
1982
+ await (git === null || git === void 0 ? void 0 : git.refresh());
1983
+ }
1984
+ });
1985
+ };
1986
+ const renderItem = (item) => {
1987
+ var _status$change;
1988
+ const data = item.getItemData();
1989
+ const entry = (data === null || data === void 0 ? void 0 : data.path) && data.kind !== "error" ? {
1990
+ path: data.path,
1991
+ name: data.name,
1992
+ kind: data.kind
1993
+ } : void 0;
1994
+ const itemProps = item.getProps();
1995
+ const level = item.getItemMeta().level;
1996
+ const folder = item.isFolder();
1997
+ const expanded = folder && item.isExpanded();
1998
+ const status = (data === null || data === void 0 ? void 0 : data.kind) === "file" ? fileStatuses === null || fileStatuses === void 0 ? void 0 : fileStatuses.get(data.path) : void 0;
1999
+ const unsaved = (data === null || data === void 0 ? void 0 : data.kind) === "file" && (unsavedPaths === null || unsavedPaths === void 0 ? void 0 : unsavedPaths.has(data.path));
2000
+ const mark = (_status$change = status === null || status === void 0 ? void 0 : status.change) !== null && _status$change !== void 0 ? _status$change : data && data.kind !== "error" ? marks === null || marks === void 0 ? void 0 : marks.get(data.path) : void 0;
2001
+ const markLabel = mark ? message.marks[mark] : "";
2002
+ const description = data && data.kind !== "error" ? descriptions === null || descriptions === void 0 ? void 0 : descriptions.get(data.path) : void 0;
2003
+ const icon = !data || data.kind === "error" ? void 0 : folder ? expanded ? "folder-open" : "folder" : iconFor(data.name);
2004
+ const accessibleName = [
2005
+ item.getItemName(),
2006
+ unsaved && message.unsaved,
2007
+ (status === null || status === void 0 ? void 0 : status.staged) && message.staged,
2008
+ (status === null || status === void 0 ? void 0 : status.revision) && message.revisions[status.revision],
2009
+ markLabel,
2010
+ description
2011
+ ].filter(Boolean).join(message.separator);
2012
+ const rows = [/* @__PURE__ */ React.createElement("button", _objectSpread2(_objectSpread2({}, itemProps), {}, {
2013
+ key: item.getId(),
980
2014
  type: "button",
981
- "aria-label": m,
982
- className: `${G}-item${(n == null ? void 0 : n.kind) === "error" ? ` ${G}-error` : ""}`,
983
- style: q(r),
984
- "data-path": n == null ? void 0 : n.path
985
- }), /* @__PURE__ */ o.createElement("span", {
986
- className: `${G}-caret`,
2015
+ "aria-label": accessibleName,
2016
+ className: `${prefix}-item${(data === null || data === void 0 ? void 0 : data.kind) === "error" ? ` ${prefix}-error` : ""}`,
2017
+ style: indent(level),
2018
+ "data-path": data === null || data === void 0 ? void 0 : data.path,
2019
+ "data-staged": (status === null || status === void 0 ? void 0 : status.staged) ? "" : void 0,
2020
+ "data-revision": status === null || status === void 0 ? void 0 : status.revision,
2021
+ title: unsaved || (status === null || status === void 0 ? void 0 : status.staged) || (status === null || status === void 0 ? void 0 : status.revision) ? accessibleName : void 0,
2022
+ "data-drop-directory": (entry === null || entry === void 0 ? void 0 : entry.kind) === "directory" ? entry.path : entry ? parentPath(entry.path) : void 0,
2023
+ "data-drop-active": (entry === null || entry === void 0 ? void 0 : entry.kind) === "directory" && drag === entry.path ? "" : void 0,
2024
+ "aria-haspopup": entry && (mutate || git) ? "menu" : void 0,
2025
+ onContextMenu: entry ? (event) => showMenu(event, entry) : void 0,
2026
+ onKeyDown: entry ? (event) => {
2027
+ var _itemProps$onKeyDown;
2028
+ if ((mutate || git) && (event.key === "ContextMenu" || event.shiftKey && event.key === "F10")) showMenu(event, entry);
2029
+ else (_itemProps$onKeyDown = itemProps.onKeyDown) === null || _itemProps$onKeyDown === void 0 || _itemProps$onKeyDown.call(itemProps, event);
2030
+ } : itemProps.onKeyDown
2031
+ }), /* @__PURE__ */ React.createElement("span", {
2032
+ className: `${prefix}-caret`,
987
2033
  "aria-hidden": "true"
988
- }, s ? c ? "▾" : "▸" : ""), p ? /* @__PURE__ */ o.createElement(ye, {
989
- kind: p,
990
- path: n.path,
991
- readFile: p === "image" ? g : void 0
992
- }) : null, /* @__PURE__ */ o.createElement("span", { className: `${G}-name` }, e.getItemName()), d ? /* @__PURE__ */ o.createElement("span", {
993
- className: `${G}-mark`,
2034
+ }, folder ? expanded ? "▾" : "▸" : ""), icon ? /* @__PURE__ */ React.createElement(Icon, {
2035
+ kind: icon,
2036
+ path: data.path,
2037
+ readFile: icon === "image" ? readFile : void 0
2038
+ }) : null, /* @__PURE__ */ React.createElement("span", { className: `${prefix}-filename` }, /* @__PURE__ */ React.createElement("span", { className: `${prefix}-name` }, item.getItemName()), unsaved ? /* @__PURE__ */ React.createElement("span", {
2039
+ className: `${prefix}-unsaved`,
994
2040
  "aria-hidden": "true"
995
- }, d) : null, f ? /* @__PURE__ */ o.createElement("span", {
996
- className: `${G}-description`,
2041
+ }, "*") : null), markLabel ? /* @__PURE__ */ React.createElement("span", {
2042
+ className: `${prefix}-mark`,
997
2043
  "aria-hidden": "true"
998
- }, f) : null)];
999
- return c && e.isLoading() && h.push(/* @__PURE__ */ o.createElement("div", {
1000
- key: `${e.getId()}\0loading`,
1001
- className: `${G}-status`,
2044
+ }, markLabel) : null, description ? /* @__PURE__ */ React.createElement("span", {
2045
+ className: `${prefix}-description`,
2046
+ "aria-hidden": "true"
2047
+ }, description) : null)];
2048
+ if (expanded && item.isLoading()) rows.push(/* @__PURE__ */ React.createElement("div", {
2049
+ key: `${item.getId()}\0loading`,
2050
+ className: `${prefix}-status`,
1002
2051
  role: "status",
1003
- style: q(r + 1)
1004
- }, l.loading)), h;
1005
- }, y = _.getItems();
1006
- return /* @__PURE__ */ o.createElement("div", { className: G }, /* @__PURE__ */ o.createElement("style", null, K), /* @__PURE__ */ o.createElement("div", _.getContainerProps(c == null ? l.label : c), y.map(v)), y.length ? null : /* @__PURE__ */ o.createElement("div", {
1007
- className: `${G}-status`,
2052
+ style: indent(level + 1)
2053
+ }, message.loading));
2054
+ return rows;
2055
+ };
2056
+ const items = tree.getItems();
2057
+ return /* @__PURE__ */ React.createElement("div", {
2058
+ className: `${prefix}${mutate ? ` ${prefix}-drop` : ""}`,
2059
+ "data-drop-active": drag === "" ? "" : void 0,
2060
+ onDrop: drop,
2061
+ onDragOver: (event) => {
2062
+ if (!acceptsFiles(event)) return;
2063
+ event.preventDefault();
2064
+ event.stopPropagation();
2065
+ event.dataTransfer.dropEffect = running.current ? "none" : "copy";
2066
+ if (!running.current) setDrag(dropPath(event.target));
2067
+ },
2068
+ onDragLeave: (event) => {
2069
+ if (!event.currentTarget.contains(event.relatedTarget)) setDrag(null);
2070
+ }
2071
+ }, /* @__PURE__ */ React.createElement("style", null, css + actionCss), /* @__PURE__ */ React.createElement("div", tree.getContainerProps(label !== null && label !== void 0 ? label : message.label), items.map(renderItem)), items.length ? null : /* @__PURE__ */ React.createElement("div", {
2072
+ className: `${prefix}-status`,
1008
2073
  role: "status"
1009
- }, f ? l.empty : l.loading));
2074
+ }, rootLoaded ? message.empty : message.loading), working || feedback ? /* @__PURE__ */ React.createElement("div", {
2075
+ className: `${prefix}-feedback`,
2076
+ role: feedback ? "alert" : "status"
2077
+ }, feedback || actions.working) : null, menu ? /* @__PURE__ */ React.createElement(ExplorerMenu, {
2078
+ anchor: menu.anchor,
2079
+ label: actions.actions,
2080
+ 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
+ })) : []]
2104
+ }) : null, dialog ? /* @__PURE__ */ React.createElement(ExplorerFileDialog, {
2105
+ anchor: dialog.anchor,
2106
+ name: dialog.entry.name,
2107
+ folder: dialog.entry.kind === "directory",
2108
+ rename: dialog.rename,
2109
+ message: actions,
2110
+ close: () => setDialog(void 0),
2111
+ submit: submitFileAction
2112
+ }) : null);
1010
2113
  }
1011
- var be = 0, Z = /* @__PURE__ */ new WeakMap(), xe = (e) => (Z.has(e) || Z.set(e, be++), Z.get(e));
1012
- function Q(e) {
1013
- return /* @__PURE__ */ o.createElement(X, t({ key: xe(e.directory) }, e));
2114
+ var nextKey = 0;
2115
+ var keys = /* @__PURE__ */ new WeakMap();
2116
+ var keyFor = (directory) => {
2117
+ if (!keys.has(directory)) keys.set(directory, nextKey++);
2118
+ return keys.get(directory);
2119
+ };
2120
+ /**
2121
+ * A read-only tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
2122
+ * sort before files, and `.git` is hidden. Keyboard: arrow keys, Home and End move and expand; Enter or Space opens a
2123
+ * file. Needs React 16.14–18 from the host.
2124
+ */
2125
+ function ProjectFolderExplorer(props) {
2126
+ return /* @__PURE__ */ React.createElement(Explorer, _objectSpread2({ key: keyFor(props.directory) }, props));
1014
2127
  }
1015
- var $ = async (e, t) => JSON.parse(await (await (await e.getFileHandle(t)).getFile()).text());
1016
- function Se({ vm: e, locale: t, marks: s }) {
1017
- let c = H(t), [{ folder: l, directory: u, version: d }, f] = o.useState({
2128
+ var readJson = async (directory, name) => JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
2129
+ function FolderView({ vm, locale = "en", marks: followMarks, fileStatuses: followStatuses, git: followGit, openFile, readBaseline }) {
2130
+ const message = messagesFor(locale);
2131
+ const [{ folder, directory, version }, setFollowed] = React.useState({
1018
2132
  directory: null,
1019
2133
  version: 0
1020
2134
  });
1021
- o.useEffect(() => i(e, (e, t) => f((n) => ({
1022
- folder: e,
1023
- directory: t,
1024
- version: n.version + 1
1025
- }))), [e]);
1026
- let [p, m] = o.useState();
1027
- o.useEffect(() => {
1028
- let e = !0;
1029
- if (m(void 0), u) return Promise.all([$(u, r), $(u, n).catch(() => void 0)]).then(([n, r]) => {
1030
- e && a(n) && m(U(n, t, { manifest: r }));
1031
- }, () => {}), () => {
1032
- e = !1;
2135
+ React.useEffect(() => followProjectFolder(vm, (folder, directory) => setFollowed((previous) => ({
2136
+ folder,
2137
+ directory,
2138
+ version: previous.version + 1
2139
+ }))), [vm]);
2140
+ const [descriptions, setDescriptions] = React.useState();
2141
+ React.useEffect(() => {
2142
+ let current = true;
2143
+ setDescriptions(void 0);
2144
+ if (!directory) return;
2145
+ Promise.all([readJson(directory, projectFile), readJson(directory, manifestFile).catch(() => void 0)]).then(([project, manifest]) => {
2146
+ if (current && isObject(project)) setDescriptions(describeProjectFolder(project, locale, { manifest }));
2147
+ }, () => {});
2148
+ return () => {
2149
+ current = false;
1033
2150
  };
1034
2151
  }, [
1035
- u,
1036
- d,
1037
- t
2152
+ directory,
2153
+ version,
2154
+ locale
1038
2155
  ]);
1039
- let [h, g] = o.useState();
1040
- return o.useEffect(() => {
1041
- if (g(void 0), u && s) return s(u, g);
1042
- }, [u, s]), l ? u ? /* @__PURE__ */ o.createElement(Q, {
1043
- directory: u,
1044
- locale: t,
1045
- descriptions: p,
1046
- marks: h
1047
- }) : /* @__PURE__ */ o.createElement("div", { className: `${G}-empty` }, /* @__PURE__ */ o.createElement("style", null, K), /* @__PURE__ */ o.createElement("p", null, c.noFolder), /* @__PURE__ */ o.createElement("button", {
2156
+ const [marks, setMarks] = React.useState();
2157
+ const [unavailable, setUnavailable] = React.useState();
2158
+ React.useEffect(() => {
2159
+ setMarks(void 0);
2160
+ if (!directory || !followMarks) return;
2161
+ return followMarks(directory, setMarks);
2162
+ }, [directory, followMarks]);
2163
+ const [statuses, setStatuses] = React.useState();
2164
+ React.useEffect(() => {
2165
+ if (!directory || !followStatuses) return;
2166
+ return followStatuses(directory, (paths) => setStatuses({
2167
+ directory,
2168
+ paths
2169
+ }));
2170
+ }, [directory, followStatuses]);
2171
+ const [unsaved, setUnsaved] = React.useState();
2172
+ React.useEffect(() => {
2173
+ if (!folder || !directory) return;
2174
+ const update = () => {
2175
+ const paths = folder.unsavedPaths();
2176
+ if (paths) setUnsaved({
2177
+ directory,
2178
+ paths
2179
+ });
2180
+ };
2181
+ let timer;
2182
+ const schedule = () => {
2183
+ clearTimeout(timer);
2184
+ timer = setTimeout(update, 100);
2185
+ };
2186
+ update();
2187
+ const stop = folder.subscribeEdits(schedule);
2188
+ return () => {
2189
+ stop();
2190
+ clearTimeout(timer);
2191
+ };
2192
+ }, [
2193
+ folder,
2194
+ directory,
2195
+ version
2196
+ ]);
2197
+ const [git, setGit] = React.useState();
2198
+ React.useEffect(() => {
2199
+ if (!directory || !followGit) return;
2200
+ return followGit(directory, (actions) => setGit({
2201
+ directory,
2202
+ actions
2203
+ }));
2204
+ }, [directory, followGit]);
2205
+ if (!folder) return null;
2206
+ if (!directory) return /* @__PURE__ */ React.createElement("div", { className: `${prefix}-empty` }, /* @__PURE__ */ React.createElement("style", null, css), /* @__PURE__ */ React.createElement("p", null, message.noFolder), /* @__PURE__ */ React.createElement("button", {
1048
2207
  type: "button",
1049
- onClick: () => l.open(t == null ? "en" : t)
1050
- }, c.open)) : null;
2208
+ onClick: () => folder.open(locale !== null && locale !== void 0 ? locale : "en")
2209
+ }, message.open));
2210
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ProjectFolderExplorer, {
2211
+ directory,
2212
+ locale,
2213
+ descriptions,
2214
+ marks,
2215
+ refreshKey: version,
2216
+ fileStatuses: (statuses === null || statuses === void 0 ? void 0 : statuses.directory) === directory ? statuses.paths : void 0,
2217
+ unsavedPaths: (unsaved === null || unsaved === void 0 ? void 0 : unsaved.directory) === directory ? unsaved.paths : void 0,
2218
+ mutate: (operation) => folder.mutate(directory, operation),
2219
+ isCurrent: () => folder.directory === directory,
2220
+ git: (git === null || git === void 0 ? void 0 : git.directory) === directory ? git.actions : void 0,
2221
+ onOpen: openFile && ((entry) => {
2222
+ const request = createFilePreview(directory, `${keyFor(directory)}/${entry.path}`, entry, locale, readBaseline);
2223
+ setUnavailable(openFile(request) ? void 0 : directory);
2224
+ })
2225
+ }), unavailable === directory && /* @__PURE__ */ React.createElement("p", {
2226
+ className: `${prefix}-status`,
2227
+ role: "status"
2228
+ }, message.unavailable));
1051
2229
  }
1052
- function Ce(e, { vm: t, locale: n = "en", marks: r }) {
1053
- return e(Se, {
1054
- vm: t,
1055
- locale: n,
1056
- marks: r
2230
+ /**
2231
+ * Renders the explorer of the project folder open for `vm`, for a side panel of the host: its files with what each is
2232
+ * for, and `marks` (such as the Git status) when given. It follows the folder as it opens, closes and saves; with no
2233
+ * folder open it offers Open Project Folder…, and it renders nothing while no project folder is mounted for `vm`.
2234
+ * Pass the same `marks` function across renders, or the marks are followed again.
2235
+ */
2236
+ function renderProjectFolderExplorer(createElement, { vm, locale = "en", marks, fileStatuses, git, openFile, readBaseline }) {
2237
+ return createElement(FolderView, {
2238
+ vm,
2239
+ locale,
2240
+ marks,
2241
+ fileStatuses,
2242
+ git,
2243
+ openFile,
2244
+ readBaseline
1057
2245
  });
1058
2246
  }
1059
- export { Q as ProjectFolderExplorer, U as describeProjectFolder, Ce as renderProjectFolderExplorer };
2247
+ export { ProjectFolderExplorer, describeProjectFolder, renderProjectFolderExplorer };