forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathopenFile.js
More file actions
428 lines (379 loc) · 11.1 KB
/
openFile.js
File metadata and controls
428 lines (379 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import fsOperation from "fileSystem";
import AudioPlayer from "components/audioPlayer";
import alert from "dialogs/alert";
import confirm from "dialogs/confirm";
import loader from "dialogs/loader";
import { reopenWithNewEncoding } from "palettes/changeEncoding";
import { decode, detectEncoding } from "utils/encodings";
import helpers from "utils/helpers";
import EditorFile from "./editorFile";
import fileTypeHandler from "./fileTypeHandler";
import recents from "./recents";
import appSettings from "./settings";
/**
* @typedef {object} FileOptions
* @property {string} text
* @property {{ row: number, column: number }} cursorPos
* @property {boolean} render
* @property {function} onsave
* @property {string} encoding
* @property {string} mode
* @property {string} uri
*/
/**
* Opens a editor file
* @param {String & FileOptions} file
* @param {FileOptions} options
*/
export default async function openFile(file, options = {}) {
try {
let uri = typeof file === "string" ? file : file.uri;
if (!uri) return;
/**@type {EditorFile} */
const existingFile = editorManager.getFile(uri, "uri");
const { cursorPos, render, onsave, text, mode, encoding } = options;
if (existingFile) {
// If file is already opened and new text is provided
const existingText = existingFile.session.getValue();
const existingCursorPos = existingFile.session.selection.getCursor();
// If file is already opened
existingFile.makeActive();
if (onsave) {
existingFile.onsave = onsave;
}
if (text && existingText !== text) {
// let confirmation = true;
// if (existingFile.isUnsaved) {
// const message = strings['reopen file'].replace('{file}', existingFile.filename);
// confirmation = await confirm(strings.warning, message);
// }
// if (confirmation) {
// }
existingFile.session.setValue(text);
}
if (
cursorPos &&
existingCursorPos &&
existingCursorPos.row !== cursorPos.row &&
existingCursorPos.column !== cursorPos.column
) {
existingFile.session.selection.moveCursorTo(
cursorPos.row,
cursorPos.column,
);
}
if (encoding && existingFile.encoding !== encoding) {
reopenWithNewEncoding(encoding);
}
return;
}
loader.showTitleLoader();
const settings = appSettings.value;
const fs = fsOperation(uri);
const fileInfo = await fs.stat();
const name = fileInfo.name || file.filename || uri;
const readOnly = fileInfo.canWrite ? false : true;
const createEditor = (isUnsaved, text, detectedEncoding) => {
new EditorFile(name, {
uri,
text,
cursorPos,
isUnsaved,
render,
onsave,
readOnly,
encoding: detectedEncoding || encoding,
SAFMode: mode,
});
};
// Check for registered file handlers
const customHandler = fileTypeHandler.getFileHandler(name);
if (customHandler) {
try {
await customHandler.handleFile({
name,
uri,
stats: fileInfo,
readOnly,
options: {
cursorPos,
render,
onsave,
encoding,
mode,
createEditor,
},
});
return;
} catch (error) {
console.error(`File handler '${customHandler.id}' failed:`, error);
// Continue with default handling if custom handler fails
}
}
if (text) {
// If file is not opened and has unsaved text
createEditor(true, text);
return;
}
const videoRegex = /\.(mp4|webm|ogg|mov|avi|wmv|flv|mkv|3gp)$/i;
const imageRegex = /\.(jpe?g|png|gif|webp|bmp|ico|avif|apng|tiff?)$/i;
const audioRegex = /\.(mp3|wav|ogg|m4a|aac|wma|flac|opus|3gp|mid|midi)$/i;
if (videoRegex.test(name)) {
const objectUrl = await fileToDataUrl(uri);
const videoContainer = (
<div
style={{
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
></div>
);
const videoEl = (
<video
src={objectUrl}
controls
style={{
maxWidth: "100%",
maxHeight: "100%",
}}
></video>
);
videoContainer.append(videoEl);
new EditorFile(name, {
uri,
type: "video",
tabIcon: "file file_type_video",
content: videoContainer,
render: true,
});
return;
}
if (imageRegex.test(name)) {
const objectUrl = await fileToDataUrl(uri);
const imageContainer = (
<div
className="image-container"
style={{
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
position: "relative",
}}
></div>
);
const imgEl = (
<img
src={objectUrl}
style={{
maxWidth: "100%",
maxHeight: "100%",
transformOrigin: "center",
transform: "scale(1) translate(0px, 0px)",
transition: "none",
cursor: "move",
}}
/>
);
let scale = 1;
let startX = 0;
let startY = 0;
let translateX = 0;
let translateY = 0;
let lastX = 0;
let lastY = 0;
function getBoundaries() {
const containerRect = imageContainer.getBoundingClientRect();
const imgRect = imgEl.getBoundingClientRect();
const maxX =
(imgRect.width * scale - containerRect.width) / (2 * scale);
const maxY =
(imgRect.height * scale - containerRect.height) / (2 * scale);
return {
maxX: Math.max(0, maxX),
maxY: Math.max(0, maxY),
minX: -Math.max(0, maxX),
minY: -Math.max(0, maxY),
};
}
function constrainTranslation() {
const bounds = getBoundaries();
translateX = Math.min(Math.max(translateX, bounds.minX), bounds.maxX);
translateY = Math.min(Math.max(translateY, bounds.minY), bounds.maxY);
}
// Zoom with mouse wheel
imageContainer.addEventListener("wheel", (e) => {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.1 : 0.1;
const oldScale = scale;
scale = Math.max(0.1, Math.min(5, scale + delta));
// Adjust translation to zoom toward mouse position
const rect = imgEl.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const scaleChange = scale / oldScale;
translateX = mouseX - (mouseX - translateX) * scaleChange;
translateY = mouseY - (mouseY - translateY) * scaleChange;
constrainTranslation();
imgEl.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
});
// Pan image with mouse drag or touch
imageContainer.addEventListener("mousedown", startDrag);
imageContainer.addEventListener("touchstart", (e) => {
if (e.touches.length === 1) {
startDrag(e.touches[0]);
} else if (e.touches.length === 2) {
const touch1 = e.touches[0];
const touch2 = e.touches[1];
startX = Math.abs(touch1.clientX - touch2.clientX);
startY = Math.abs(touch1.clientY - touch2.clientY);
}
});
function startDrag(e) {
lastX = e.clientX;
lastY = e.clientY;
document.addEventListener("mousemove", onDrag);
document.addEventListener("mouseup", stopDrag);
document.addEventListener("touchmove", onTouchDrag);
document.addEventListener("touchend", stopDrag);
}
function onDrag(e) {
const deltaX = e.clientX - lastX;
const deltaY = e.clientY - lastY;
translateX += deltaX / scale;
translateY += deltaY / scale;
lastX = e.clientX;
lastY = e.clientY;
constrainTranslation();
imgEl.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
}
function onTouchDrag(e) {
if (e.touches.length === 1) {
const touch = e.touches[0];
const deltaX = touch.clientX - lastX;
const deltaY = touch.clientY - lastY;
translateX += deltaX / scale;
translateY += deltaY / scale;
lastX = touch.clientX;
lastY = touch.clientY;
constrainTranslation();
imgEl.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
} else if (e.touches.length === 2) {
e.preventDefault();
const touch1 = e.touches[0];
const touch2 = e.touches[1];
const currentX = Math.abs(touch1.clientX - touch2.clientX);
const currentY = Math.abs(touch1.clientY - touch2.clientY);
const startDist = Math.sqrt(startX * startX + startY * startY);
const currentDist = Math.sqrt(
currentX * currentX + currentY * currentY,
);
const delta = (currentDist - startDist) / 100;
scale = Math.max(0.1, Math.min(5, scale + delta));
constrainTranslation();
imgEl.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
startX = currentX;
startY = currentY;
}
}
function stopDrag() {
document.removeEventListener("mousemove", onDrag);
document.removeEventListener("mouseup", stopDrag);
document.removeEventListener("touchmove", onTouchDrag);
document.removeEventListener("touchend", stopDrag);
}
imageContainer.append(imgEl);
new EditorFile(name, {
uri,
type: "image",
tabIcon: "file file_type_image",
content: imageContainer,
render: true,
});
return;
}
if (audioRegex.test(name)) {
const objectUrl = await fileToDataUrl(uri);
const audioContainer = (
<div
style={{
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
></div>
);
const audioPlayer = new AudioPlayer(audioContainer);
audioPlayer.loadTrack(objectUrl);
const audioTab = new EditorFile(name, {
uri,
type: "audio",
tabIcon: "file file_type_audio",
content: audioPlayer.container,
render: true,
});
audioTab.onclose = () => {
audioPlayer.cleanup();
};
return;
}
// Else open a new file
// Checks for valid file
if (fileInfo.length * 0.000001 > settings.maxFileSize) {
return alert(
strings.error.toUpperCase(),
strings["file too large"].replace(
"{size}",
settings.maxFileSize + "MB",
),
);
}
if (helpers.isBinary(uri)) {
const confirmation = await confirm(strings.info, strings["binary file"]);
if (!confirmation) return;
}
const binData = await fs.readFile();
// Determine encoding: if explicit provided use it, otherwise
// if settings.defaultFileEncoding === 'auto' then detect; else use the default as-is
let detectedEncoding = file.encoding || encoding;
if (!detectedEncoding) {
const defaultSetting = appSettings.value.defaultFileEncoding;
if (defaultSetting === "auto") {
try {
detectedEncoding = await detectEncoding(binData);
if (detectedEncoding === "auto") detectedEncoding = "UTF-8";
} catch (error) {
console.warn("Encoding detection failed, using UTF-8:", error);
detectedEncoding = "UTF-8";
}
} else {
detectedEncoding = defaultSetting || "UTF-8";
}
}
const fileContent = await decode(binData, detectedEncoding);
createEditor(false, fileContent, detectedEncoding);
if (mode !== "single") recents.addFile(uri);
return;
} catch (error) {
console.error(error);
} finally {
loader.removeTitleLoader();
}
}
/**
* Converts file to data url
* @param {string} file file url
*/
async function fileToDataUrl(file) {
const fs = fsOperation(file);
const fileInfo = await fs.stat();
const binData = await fs.readFile();
return URL.createObjectURL(new Blob([binData], { type: fileInfo.mime }));
}