oxios-web 0.2.0

Web dashboard channel for Oxios
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
function initEditor(el) {
    if (window.editor !== undefined && el.id === 'editor-textarea' ) {
        editor.off();
        const wrapper = editor.getWrapperElement();
        if (wrapper && wrapper.parentNode) {
            wrapper.parentNode.removeChild(wrapper);
        }

        editor2.off();
        const wrapper2 = editor2.getWrapperElement();
        if (wrapper2 && wrapper2.parentNode) {
            wrapper2.parentNode.removeChild(wrapper2);
        }
    } else if (window.editor2 !== undefined && el.id === 'editor2-textarea') {
        editor2.off();
        const wrapper = editor2.getWrapperElement();
        if (wrapper && wrapper.parentNode) {
            wrapper.parentNode.removeChild(wrapper);
        }
    }

    let newEditor = HyperMD.fromTextArea(el, {
        dragDrop: false,
        viewportMargin: 10,
        mode: {
            name: 'hypermd',
            math: false, // disable $math syntax$
        },
        lineNumbers: false,
        extraKeys: {
            // 'Shift-Space': 'autocomplete',
            'Cmd-[': false, 'Cmd-]': false,
        },
        hintOptions: {
            hint: CompleteEmoji.createHintFunc(),
            closeCharacters: /$^/,
            closeOnUnfocus: false,
            completeSingle: false,
            alignWithWord: false
        },
        hmdFoldEmoji: {
            myEmoji: createAutocompleteDict
        },
        configureMouse: () => ({addNew: false}) // disable multicursor
    });
    newEditor.setSize(null, '100%');
    newEditor.on('focus', function() {
        currentEditor = newEditor; // FIXME possible RC here? If isMessingWithCurrentEditor is hold, this would overwrite
        currentEditor.refresh(); // Cursor & hide tokens conflict if we don't call it
        closeChatModal();
        log('Focused to:', newEditor.path);
    });

    newEditor.hmdResolveURL = function (path) {
        if (typeof path === 'undefined') {
            return path
        }

        path = path.replace(/%20/g, ' ');

        // TODO really dirty fix for links like:
        // ../media/image.png, remove
        if (path.startsWith('../')) {
            path = path.replace('../', '');
        }

        // Bare domain like google.com/test - window.open treats it as a relative
        // path without a protocol, which makes the PWA navigate to a sub-path.
        // Exclude local-file extensions (md, image types) so `![](img.png)`
        // isn't mistaken for a domain.
        if (/^[a-z0-9-]+(\.[a-z0-9-]+)+(\/|$)/i.test(path)
            && !/\.(md|png|jpg|jpeg|gif|webp)$/i.test(path)) {
            return 'https://' + path;
        }

        if (/^(?!http|https|\[).+\.md$/.test(path)) {
            let parts = path.split('/');
            if (parts.length === 1) {
                openFile('', path, true, 'editor2-textarea');
                return;
            }
            openFile(parts[0], parts[1], true, 'editor2-textarea');
            return path;
        }

        // Capture only the bare filename (no slashes) so the media/img
        // lookups by filename work even when path has a folder prefix.
        const match = path.match(/(?:^|\/)([^/]+\.(png|jpg|jpeg|gif|webp))$/i);

        if (match && files['media/'] && files['media/'][match[1]]) {
            return files['media/'][match[1]].imageUrl;
        }

        if (match && files['img/'] && files['img/'][match[1]]) {
            return files['img/'][match[1]].imageUrl;
        }

        // Filename fallback - look up bare filename in the global
        // image index built by loadLocalFiles. Resolves images stored in
        // any folder when the markdown link's path doesn't match.
        if (match) {
            const bareName = match[1].split('/').pop();
            if (mediaIndex[bareName] && mediaIndex[bareName].imageUrl) {
                return mediaIndex[bareName].imageUrl;
            }
        }

        return path;
    };

    newEditor.hmdReadLink = async function (path) {
        path = path.replace(/\|.*]$/, '');
        path = path.replace('[', '').replace(']', '');

        // Handle action links
        if (path === 'cmd:openDir') {
            openDir();
            return;
        }
        if (path === 'cmd:openChat') {
            openChat();
            return;
        }

        // If it is a web link open window blank
        if (/^(http|https):\/\//.test(path)) {
            window.open(path, '_blank');
            return;
        }

        path += '.md';

        if (getMemFile(path) !== null) {
            openFile(path, true, 'editor2-textarea')
            return;
        }

        // Try to find filename is any folder
        let filename = toFilename(path);
        walk(files, (path, isFile) => {
            if (!isFile) {
                return;
            }

            if (toFilename(path) === filename) {
                openFile(path, true, 'editor2-textarea');
                return false;
            }
        });
    };

    newEditor.on('inputRead', async function (cm, change) {
        if (change.text.length === 1 && change.text[0] === '[') {
            cm.showHint({
                completeSingle: false, updateOnCursorActivity: true,
            })
        }
    })

    // Auto-select/highlight title when clicking on the first line
    // TODO clear on second click
    newEditor.getWrapperElement().addEventListener('mousedown', function(e) {
        // Get the position where the mouse was clicked
        const coords = newEditor.coordsChar({left: e.clientX, top: e.clientY});

        if (coords.line === 0) {
            // Check if cursor is already on line 0
            const currentCursor = newEditor.getCursor();
            if (currentCursor.line === 0) {
                // Cursor already on line 0, don't select
                return;
            }

            // Cursor not on line 0, select the title
            setTimeout(() => {
                const lineLength = newEditor.getLine(0).length;
                newEditor.setSelection(
                    {line: 0, ch: 2},  // Start from character 2 (skip "# ")
                    {line: 0, ch: lineLength}
                );
            }, 150);
        }
    }, true);

    // Force '# ' to remain at first line.
    newEditor.on('change', function (cm, change) {
        if (change.from.line === 0) {
            const line = cm.getLine(0);
            if (!line.startsWith('# ')) {
                const content = line.replace(/^#*\s*/, '');
                cm.replaceRange('# ' + content, {line: 0, ch: 0}, {line: 0, ch: line.length});
            }
        }
    });

    // Image upload
    newEditor.on('paste', async (_, event) => {
        const items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (const item of items) {
            if (item.kind === 'file' && item.type.startsWith('image/')) {
                event.preventDefault(); // Prevent default paste behavior

                const file = item.getAsFile();
                const fileName = `${new Date().toISOString().replace(/[:.]/g, '-')}.${getImageExtension(item.type)}`;

                try {
                    const fileHandle = await writeMediaFile(fileName, file);
                    if (fileHandle) {
                        if (!files['media/']) {
                            files['media/'] = {};
                        }
                        files['media/'][fileName] = {
                            isFile: true,
                            handle: fileHandle,
                            lastModified: Date.now(),
                            imageUrl: URL.createObjectURL(file)
                        };

                        const markdownImageSyntax = `![](media/${fileName})\n`;
                        currentEditor.replaceSelection(markdownImageSyntax);
                        log(`Image saved as: ${fileName}`);
                    } else {
                        logError('Failed to save the image.');
                        alert('Failed to save the image. Please try again.');
                    }
                } catch (error) {
                    logError('Error saving image:', error);
                    alert('Error saving image: ' + error.message);
                }
            }
        }
    });

    // Editor keybindings
    newEditor.addKeyMap({
        'Enter': function (cm) { // If header is selected, enter should move cursor to next line
            const cursor = cm.getCursor();
            // If there's a selection on the header line, just move cursor
            if (cursor.line === 0) {
                if (cm.somethingSelected()) {
                    const selections = cm.listSelections();
                    const isHeaderSelection = selections.some(sel =>
                        sel.anchor.line === 0 || sel.head.line === 0
                    );

                    if (isHeaderSelection) {
                        // Clear selection and move cursor to start of line 1
                        cm.setCursor({line: 1, ch: 0});
                        return;
                    }
                } else {
                    // No selection, just move cursor to next line
                    cm.setCursor({line: 1, ch: 0});
                    return;
                }
            }

            // For all other lines, use default Enter behavior
            return CodeMirror.Pass;
        },
        'Cmd-A': function (cm) {
            const cursor = cm.getCursor();

            // If cursor is on the first line, select all text in that line
            if (cursor.line === 0) {
                const lineLength = cm.getLine(0).length;
                cm.setSelection(
                    {line: 0, ch: 0},
                    {line: 0, ch: lineLength}
                );
                return;
            }

            // Otherwise, use default Cmd-A behavior (select all except first line)
            const lastLine = cm.lastLine();
            const lastLineLength = cm.getLine(lastLine).length;

            cm.setSelection(
                {line: 1, ch: 0},
                {line: lastLine, ch: lastLineLength},
                {scroll: false}
            );
        },
        'Ctrl-A': function (cm) {
            const cursor = cm.getCursor();

            // If cursor is on the first line, select all text in that line
            if (cursor.line === 0) {
                const lineLength = cm.getLine(0).length;
                cm.setSelection(
                    {line: 0, ch: 0},
                    {line: 0, ch: lineLength}
                );
                return;
            }

            // Otherwise, use default Cmd-A behavior (select all except first line)
            const lastLine = cm.lastLine();
            const lastLineLength = cm.getLine(lastLine).length;

            cm.setSelection(
                {line: 1, ch: 0},
                {line: lastLine, ch: lastLineLength},
                {scroll: false}
            );
        },
        'Cmd-Y': function (cm) {
            var cursor = cm.getCursor();
            var lineStart = {line: cursor.line, ch: 0};
            cm.replaceRange('✅ ', lineStart);
            cm.focus();
        },
        'Ctrl-Y': function (cm) {
            var cursor = cm.getCursor();
            var lineStart = {line: cursor.line, ch: 0};
            cm.replaceRange('✅ ', lineStart);
            cm.focus();
        },
        'Cmd-B': function (cm) {
            let selection = cm.getSelection();
            let trimmedSelection = selection.trim();
            let prefix = selection.slice(0, selection.indexOf(trimmedSelection));
            let suffix = selection.slice(selection.indexOf(trimmedSelection) + trimmedSelection.length);

            const isBold = trimmedSelection.startsWith('**') && trimmedSelection.endsWith('**');

            let start = cm.getCursor('start');
            let end = cm.getCursor('end');

            if (isBold) {
                cm.replaceSelection(prefix + trimmedSelection.slice(2, -2) + suffix);
                cm.setSelection(
                    {line: start.line, ch: start.ch + prefix.length},
                    {line: end.line, ch: end.ch - suffix.length - 4}
                );
            } else {
                cm.replaceSelection(prefix + `**${trimmedSelection}**` + suffix);
                cm.setSelection(
                    {line: start.line, ch: start.ch + prefix.length},
                    {line: end.line, ch: end.ch - suffix.length + 4}
                );
            }
            cm.focus();
        },
        'Cmd-I': function (cm) {
            let selection = cm.getSelection();
            let trimmedSelection = selection.trim();
            let prefix = selection.slice(0, selection.indexOf(trimmedSelection));
            let suffix = selection.slice(selection.indexOf(trimmedSelection) + trimmedSelection.length);

            const isItalic = trimmedSelection.startsWith('*') && trimmedSelection.endsWith('*');

            let start = cm.getCursor('start');
            let end = cm.getCursor('end');

            if (isItalic) {
                cm.replaceSelection(prefix + trimmedSelection.slice(1, -1) + suffix);
                cm.setSelection(
                    {line: start.line, ch: start.ch + prefix.length},
                    {line: end.line, ch: end.ch - suffix.length - 2}
                );
            } else {
                cm.replaceSelection(prefix + `*${trimmedSelection}*` + suffix);
                cm.setSelection(
                    {line: start.line, ch: start.ch + prefix.length},
                    {line: end.line, ch: end.ch - suffix.length + 2}
                );
            }
            cm.focus();
        }
    });

    newEditor.getWrapperElement().addEventListener('mousedown', function (e) {
        if (!isMetaKey(e)) return;

        e.preventDefault();

        const code = e.target.closest('.cm-inline-code');
        if (!code) return;

        const text = code.textContent;
        navigator.clipboard.writeText(text);

        const toast = document.createElement('div');
        toast.textContent = 'Copied!';
        toast.style.cssText = `
            position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
            background: var(--col-bg-alt); color: var(--col-tx); padding: 8px 16px; border-radius: 5px;
            border: 1px solid var(--col-border);
            z-index: 9999; font-size: 14px;
        `;
        document.body.appendChild(toast);
        setTimeout(() => document.body.removeChild(toast), 1000);
    }, true);

    initAutoscroll(newEditor);

    return newEditor;
}

// Focus last line before the links.
function focusLastLine() {
    let lastLine = currentEditor.lastLine();
    let targetLine = lastLine;

    // Eat all empty lines before first links.
    while (lastLine >= 0) {
        const lineContent = currentEditor.getLine(lastLine).trim();
        if (lineContent === '') {
            lastLine--;
            continue;
        }

        lastLine = Math.min(lastLine + 1, currentEditor.lastLine());
        break;
    }
    for (let i = lastLine; i >= 0; i--) {
        const lineContent = currentEditor.getLine(i).trim();

        if (!lineContent.startsWith('[') && (!lineContent.endsWith(']') || !lineContent.endsWith(')'))) {
            targetLine = i;
            break;
        }
    }
    const targetChar = currentEditor.getLine(targetLine).length;
    currentEditor.setCursor({ line: targetLine, ch: targetChar });
    // Cursor at the end, but scroll the doc to top
    currentEditor.scrollTo(null, 0);
    // TODO only focus if there's no quick dialogue
    currentEditor.focus();
}

let savedScrollTop;
function rememberEditorPos() {
    savedScrollTop = editor.getScrollInfo().top;
}

function restoreEditorPos() {
    if (savedScrollTop === undefined) {
        return;
    }
    editor.refresh();
    editor.scrollTo(null, savedScrollTop);
}