rob-revisited/ide/ui/js/ssh.js

621 lines
32 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The SSH window (desktop IDE): the servers you work on, with the computer's own ssh / scp (your ~/.ssh/config, keys,
// agent, known_hosts; no password is ever kept: ssh asks for it itself, in a terminal).
// - Servers: add / edit / remove, import the hosts of ~/.ssh/config, test the connection (without any question).
// - A session: a tab of the IDE's Terminal running ssh (prompts, passwords, colours, vim...); Windows: a console window.
// - Files: browse a remote folder, new folder, rename / move, copy, delete (asked first), upload (a file, a folder, or a file
// dragged from the Project view), download (scp, its progress shown), a remote file opened in the editor (saved back with ssh).
// - Drag and drop with the system's file manager, both ways (desktop): files / folders dropped from it on the list or on a remote
// folder are uploaded there (the runtime tells the page their real paths: jumphp.on('native:drag')); remote items dragged out of
// the window are downloaded to a folder of their own first (ssh.stage), then a native drag carries them (native.dragFiles). Dropped
// on the Project view instead, they are downloaded into that folder. A name already there: overwrite / skip / rename, asked.
// Linux / macOS: a terminal session is shared (ControlMaster): once you typed its password, the file panel uses it too.
// The PHP side: ide/src/Ssh/SshCommands.php.
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, confirm, prompt, dialog, menu, progressBar } from './ui.js';
import { zoom } from './zoom.js';
const bytes = (n) => (n >= 1073741824 ? (n / 1073741824).toFixed(1) + ' GB' : n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? (n / 1024).toFixed(0) + ' KB' : n + ' B');
const join = (dir, name) => (dir.endsWith('/') ? dir : dir + '/') + name;
const parent = (path) => { const p = path.replace(/\/+$/, ''); const i = p.lastIndexOf('/'); return i <= 0 ? '/' : p.slice(0, i); };
export class SshPanel {
constructor(app) {
this.app = app;
this.node = el('div.ssh-view');
this.servers = null;
this.info = null; // ssh.probe: {ssh, scp, version, os, sharing}
this.browse = null; // {server, path, entries, selected: Set, busy, error}
this.jobs = new Map(); // job -> {label, percent, file, speed, done, error, onEnd}
this.tests = {}; // server id -> {ok, message} | 'busy'
backend.on('ssh.transfer', (p) => { const j = this.jobs.get(p.job); if (j) { Object.assign(j, p); this.renderJobs(); } });
backend.on('ssh.transfer.end', (p) => this.jobEnded(p));
// drag and drop with the file manager: files dragged over / dropped on the window (their real paths), the remote rows' drags
this.native = backend.kind === 'native';
this.press = null; // a mouse press on a remote row: {x, y, entry}
this.drag = null; // a drag of remote rows going on (beginDrag)
this.outPaths = new Set(); // the local copies dragged out last: dropped back on the window, they are not uploaded again
this.lastOver = null; // the page's own last dragover of files: {x, y, at}, CSS pixels
if (this.native) backend.on('native:drag', (d) => this.osDrag(d || {}));
document.addEventListener('dragover', (e) => {
if ([...(e.dataTransfer?.types || [])].includes('Files')) this.lastOver = { x: e.clientX, y: e.clientY, at: performance.now() };
}, true);
document.addEventListener('mousemove', (e) => this.dragMove(e), true);
document.addEventListener('mouseup', (e) => this.dragUp(e), true);
document.documentElement.addEventListener('mouseleave', () => { if (this.drag) this.leaveWindow(); });
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && this.drag && !this.drag.out) { this.stopStaging(this.drag); this.endDrag(); } }, true);
this.render();
}
title() { return 'SSH'; }
actions() {
return [
el('button', { title: t('Add a server'), onclick: () => this.edit() }, icon('plus')),
el('button', { title: t('Import from ~/.ssh/config'), onclick: () => this.importConfig() }, icon('download')),
el('button', { title: t('Refresh'), onclick: () => this.refresh() }, icon('refresh')),
];
}
shown() { this.refresh(); }
async refresh() {
if (!this.info) this.info = await backend.invoke('ssh.probe', {}).catch(() => ({ ssh: null }));
const r = await backend.invoke('ssh.servers', {}).catch((e) => { notify(e.message, 'error', { title: 'SSH' }); return null; });
this.servers = r?.servers || [];
if (this.browse) {
const s = this.servers.find((x) => x.id === this.browse.server.id);
if (!s) this.browse = null; else { this.browse.server = s; return this.list(this.browse.path); }
}
this.render();
return null;
}
render() {
clear(this.node);
this.body = el('div.ssh-body');
this.jobsNode = el('div.ssh-jobs');
this.node.append(this.body, this.jobsNode);
if (this.browse) this.renderFiles(); else this.renderServers();
this.renderJobs();
}
// servers -------------------------------------------------------------------------------------------------
renderServers() {
const b = this.body;
if (this.info && !this.info.ssh) {
b.append(el('div.ssh-error', {}, t('ssh was not found on this computer: install the OpenSSH client (Windows: Settings › Optional features › OpenSSH Client).')));
}
if (!this.servers) { b.append(el('div.ssh-hint', {}, t('Loading…'))); return; }
if (!this.servers.length) {
b.append(el('div.ssh-hint', {}, t('No server yet. Add one, or import the hosts of your ~/.ssh/config.')),
el('div.ssh-toolbar', {},
el('button.btn.primary', { onclick: () => this.edit() }, t('Add a server')),
el('button.btn', { onclick: () => this.importConfig() }, t('Import from ~/.ssh/config'))));
}
for (const s of this.servers) {
const test = this.tests[s.id];
const where = `${s.user ? s.user + '@' : ''}${s.host}${s.port ? ':' + s.port : ''}${s.jump ? ' via ' + s.jump : ''}`;
b.append(el('div.ssh-row', { ondblclick: () => this.open(s) },
el('span.ssh-dot' + (test === 'busy' ? '.busy' : test?.ok ? '.on' : test ? '.off' : ''), { title: test && test !== 'busy' ? (test.ok ? t('Connected') : test.message) : '' }),
el('div.ssh-main', {},
el('div.ssh-name', {}, s.name),
el('div.ssh-sub', { title: where }, where + (s.folder ? ' ' + s.folder : '')),
test && test !== 'busy' && !test.ok ? el('div.ssh-error', {}, test.message) : null),
el('div.ssh-actions', {},
this.btn(t('Open a terminal (ssh)'), 'terminal', () => this.session(s)),
this.btn(t('Browse the files'), 'folder', () => this.open(s)),
this.btn(t('Test the connection'), 'check', () => this.test(s)),
this.btn(t('Edit'), 'edit', () => this.edit(s)),
this.btn(t('Remove'), 'trash', () => this.remove(s)))));
}
if (this.info?.version) b.append(el('div.ssh-hint.small', {}, this.info.version + (this.info.sharing ? ' · ' + t('a terminal\'s session is shared with the file panel') : '')));
}
btn(title, ico, fn, disabled = false) {
return el('button.icon-btn', { title, disabled, onclick: (e) => { e.stopPropagation(); fn(); } }, icon(ico));
}
edit(s = null) {
const v = s || { name: '', host: '', port: '', user: '', identity: '', jump: '', folder: '' };
const field = (key, label, placeholder = '') => {
const input = el('input.input', { value: v[key] ? String(v[key]) : '', placeholder });
// the key file: also chosen in the system's file chooser, opened in ~/.ssh
const browse = key === 'identity' ? el('button.btn.small', { type: 'button', title: t('Choose the key file'), onclick: async (e) => {
e.preventDefault();
const f = await backend.invoke('native.open', { title: t('Choose the key file'), directory: '~/.ssh' }).catch(() => null);
if (typeof f === 'string' && f) input.value = f;
} }, '…') : null;
return [key, input, el('label.ssh-field', {}, el('span', {}, t(label)), browse ? el('div.ssh-row', { style: { display: 'flex', gap: '6px' } }, input, browse) : input)];
};
const fields = [field('name', 'Name', 'Production'), field('host', 'Host (or an alias of ~/.ssh/config)', 'example.org'), field('port', 'Port', '22'),
field('user', 'User', 'deploy'), field('identity', 'Key file (empty: your agent and default keys)', '~/.ssh/id_ed25519'),
field('jump', 'Jump host (ProxyJump)', 'user@bastion'), field('folder', 'Start folder on the server', '/var/www')];
dialog({
title: s ? 'Edit the server' : 'Add a server',
body: el('div.ssh-form', {}, ...fields.map((f) => f[2]), el('p.ssh-hint.small', {}, t('No password is kept: ssh asks for it in the terminal. Keys stay your files.'))),
buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
const server = { id: s?.id || '' };
for (const [key, input] of fields) server[key] = input.value.trim();
server.port = Number(server.port) || 0;
try { await backend.invoke('ssh.server.save', { server }); } catch (e) { notify(e.message, 'error', { title: 'SSH' }); return false; }
this.refresh();
return true;
} }],
});
}
async remove(s) {
if (!await confirm(t('Remove the server {name}?', { name: s.name }), t('Only the IDE forgets it: nothing changes on the server or in your ~/.ssh.'), { ok: t('Remove'), danger: true })) return;
await backend.invoke('ssh.server.remove', { id: s.id }).catch((e) => notify(e.message, 'error'));
this.refresh();
}
async importConfig() {
const r = await backend.invoke('ssh.config.hosts', {}).catch((e) => { notify(e.message, 'error', { title: 'SSH' }); return null; });
if (!r) return;
if (!r.hosts.length) { notify(t('No named host in ~/.ssh/config.'), 'info', { title: 'SSH' }); return; }
const known = new Set((this.servers || []).map((s) => s.host));
const boxes = r.hosts.map((h) => {
const box = el('input', { type: 'checkbox', checked: !known.has(h.alias), disabled: known.has(h.alias) });
const detail = [h.user && h.user + '@', h.hostname || '', h.port ? ':' + h.port : '', h.jump ? ' via ' + h.jump : ''].join('');
return [h.alias, box, el('label.ssh-check', {}, box, el('b', {}, h.alias), el('span.ssh-sub', {}, ' ' + detail + (known.has(h.alias) ? ' · ' + t('already there') : '')))];
});
dialog({
title: 'Import from ~/.ssh/config',
body: el('div.ssh-form', {}, el('p.ssh-hint.small', {}, t('Each host keeps its alias: ssh applies your whole config (keys, ports, jump hosts).')), ...boxes.map((b) => b[2])),
buttons: [{ label: 'Cancel' }, { label: 'Import', primary: true, action: async () => {
const aliases = boxes.filter((b) => b[1].checked && !b[1].disabled).map((b) => b[0]);
const res = await backend.invoke('ssh.config.import', { aliases });
notify(t('{n} server(s) imported.', { n: res.added }), 'success', { title: 'SSH' });
this.refresh();
} }],
});
}
async test(s) {
this.tests[s.id] = 'busy';
this.render();
this.tests[s.id] = await backend.invoke('ssh.server.test', { id: s.id }).catch((e) => ({ ok: false, message: e.message }));
if (!this.tests[s.id].ok && /verification failed|Permission denied|password|passphrase/i.test(this.tests[s.id].message)) {
this.tests[s.id].message += '\n' + t('Open a terminal once: ssh asks there (host key, password); its session then serves the file panel too.');
}
this.render();
}
/** A session: a tab of the IDE's terminal running ssh (Windows: a console window, the IDE's terminal there has no pseudo-terminal). */
async session(s, folder = '') {
try {
if (this.info?.os === 'Windows' || !this.app.terminal) {
await backend.invoke('ssh.external', { id: s.id, folder });
return;
}
const r = await backend.invoke('ssh.session', { id: s.id, folder });
this.app.showTool?.('terminal', true);
await this.app.terminal.run(r.line, 'SSH ' + r.label);
} catch (e) { notify(e.message, 'error', { title: 'SSH' }); }
}
// files ---------------------------------------------------------------------------------------------------
open(s) {
const path = prefs.get('sshPath:' + s.id, s.folder || ''); // where it was left
this.browse = { server: s, path, entries: [], selected: new Set(), busy: true, error: null };
this.render();
this.list(path);
}
async list(path) {
const b = this.browse;
b.busy = true;
b.error = null;
if (this.listNode) this.renderList();
try {
const r = await backend.invoke('ssh.list', { id: b.server.id, path });
if (this.browse !== b) return;
b.path = r.path || path;
b.entries = r.entries;
b.selected = new Set();
prefs.set('sshPath:' + b.server.id, b.path);
} catch (e) {
b.error = e.message;
} finally { b.busy = false; }
if (this.browse === b) this.render();
}
renderFiles() {
const b = this.browse;
const pathInput = el('input.input.ssh-path', { value: b.path, title: t('A folder of the server (Enter)'),
onkeydown: (e) => { if (e.key === 'Enter') this.list(e.target.value.trim()); } });
this.body.append(
el('div.ssh-toolbar', {},
this.btn(t('Servers'), 'collapse', () => { this.browse = null; this.render(); }),
el('b.ssh-server', { title: b.server.host }, b.server.name),
pathInput,
this.btn(t('Up'), 'pull', () => this.list(parent(b.path)), b.path === '/' || !b.path),
this.btn(t('Refresh'), 'refresh', () => this.list(b.path))),
el('div.ssh-toolbar', {},
this.btn(t('New folder'), 'plus', () => this.mkdir()),
this.btn(t('Upload a file'), 'upload', () => this.uploadPick(false)),
this.btn(t('Upload a folder'), 'folder', () => this.uploadPick(true)),
this.btn(t('Download the selection'), 'download', () => this.download(this.picked()), !b.selected.size),
this.btn(t('Copy the selection to…'), 'copy', () => this.copyMove('copy', this.picked()), !b.selected.size),
this.btn(t('Move the selection to…'), 'diff', () => this.copyMove('move', this.picked()), !b.selected.size),
this.btn(t('Delete the selection'), 'trash', () => this.deleteFiles(this.picked()), !b.selected.size),
el('span.ssh-spacer'),
this.btn(t('Open a terminal in this folder'), 'terminal', () => this.session(b.server, b.path))));
this.listNode = el('div.ssh-list', {
// the Project view's files (text/x-jumphp-path), and the file manager's (Files: the drop itself comes as native:drag, with paths)
ondragover: (e) => {
const types = [...e.dataTransfer.types];
if (!types.includes('text/x-jumphp-path') && !(this.native && types.includes('Files'))) return;
e.preventDefault();
if (!types.includes('Files')) this.dropMark(this.targetOf(e.target));
},
ondragleave: (e) => { if (!this.listNode.contains(e.relatedTarget)) this.dropMark(null); },
ondrop: (e) => {
const target = this.targetOf(e.target);
this.dropMark(null);
const path = e.dataTransfer.getData('text/x-jumphp-path');
if (!path) { if ([...e.dataTransfer.types].includes('Files')) e.preventDefault(); return; }
e.preventDefault();
this.uploadTo([path], target?.dir);
},
});
this.body.append(this.listNode, el('div.ssh-hint.small', {}, t(this.native
? 'Drop files here from the Project view or your file manager to upload them, drag files out to download them. Double click a file to edit it.'
: 'Drag files from the Project view here to upload them. Double click a file to edit it.')));
this.renderList();
}
picked() { return [...this.browse.selected].map((name) => join(this.browse.path, name)); }
renderList() {
const b = this.browse;
const list = this.listNode;
clear(list);
if (b.busy) list.append(el('div.ssh-hint', {}, t('Loading…')));
if (b.error) list.append(el('pre.ssh-error', {}, b.error));
if (b.busy || b.error) return;
if (!b.entries.length) list.append(el('div.ssh-hint', {}, t('This folder is empty.')));
for (const e of b.entries) {
const sel = b.selected.has(e.name);
const path = join(b.path, e.name);
list.append(el('div.ssh-file' + (sel ? '.sel' : ''), {
title: `${e.mode} ${e.owner}:${e.group}${e.target ? ' → ' + e.target : ''}`,
dataset: e.type === 'dir' ? { dir: path } : {},
onmousedown: (ev) => { if (ev.button === 0 && !ev.ctrlKey && !ev.metaKey && !ev.shiftKey) { ev.preventDefault(); this.press = { x: ev.clientX, y: ev.clientY, entry: e }; } },
onclick: (ev) => {
if (!(ev.ctrlKey || ev.metaKey)) b.selected.clear();
if (sel && (ev.ctrlKey || ev.metaKey)) b.selected.delete(e.name); else b.selected.add(e.name);
this.render();
},
ondblclick: () => this.activate(e, path),
oncontextmenu: (ev) => { ev.preventDefault(); if (!b.selected.has(e.name)) { b.selected = new Set([e.name]); this.render(); } this.fileMenu(e, path, ev); },
},
icon(e.type === 'dir' ? 'folder' : e.type === 'link' ? 'fork' : 'file'),
el('span.ssh-fname', {}, e.name),
el('span.ssh-fsize', {}, e.type === 'dir' ? '' : bytes(e.size)),
el('span.ssh-fdate', {}, e.date)));
}
}
/** Double click: a folder opens, a file goes to the editor; a link is tried as a folder first. */
async activate(e, path) {
if (e.type === 'dir') return this.list(path);
if (e.type === 'link') {
try {
await backend.invoke('ssh.list', { id: this.browse.server.id, path });
return this.list(path);
} catch { /* not a folder: a file */ }
}
return this.editFile(path);
}
editFile(path) { return this.app.editors.open(`ssh://${this.browse.server.id}${path}`); }
fileMenu(e, path, ev) {
const items = [
e.type !== 'dir' ? { label: t('Open in the editor'), icon: 'edit', action: () => this.editFile(path) } : { label: t('Open'), icon: 'folder', action: () => this.list(path) },
{ label: t('Download…'), icon: 'download', action: () => this.download(this.picked()) },
'-',
{ label: t('Rename…'), icon: 'edit', action: () => this.rename(e, path) },
{ label: t('Copy to…'), icon: 'copy', action: () => this.copyMove('copy', this.picked()) },
{ label: t('Move to…'), icon: 'diff', action: () => this.copyMove('move', this.picked()) },
'-',
{ label: t('Copy the path'), icon: 'copy', action: () => navigator.clipboard?.writeText(path).catch(() => {}) },
{ label: t('Delete'), icon: 'trash', action: () => this.deleteFiles(this.picked()) },
];
menu(items, { x: ev.clientX, y: ev.clientY });
}
async op(action, paths, to = '') {
try {
await backend.invoke('ssh.op', { id: this.browse.server.id, action, paths, to });
} catch (e) { notify(e.message, 'error', { title: 'SSH' }); }
this.list(this.browse.path);
}
async mkdir() {
const name = await prompt(t('New folder'), { label: t('Its name, in {path}', { path: this.browse.path }) });
if (name?.trim()) this.op('mkdir', [join(this.browse.path, name.trim())]);
}
async rename(e, path) {
const name = await prompt(t('Rename {name}', { name: e.name }), { value: e.name, select: [0, e.name.lastIndexOf('.') > 0 ? e.name.lastIndexOf('.') : e.name.length] });
if (name?.trim() && name.trim() !== e.name) this.op('move', [path], name.includes('/') ? name.trim() : join(this.browse.path, name.trim()));
}
async copyMove(action, paths) {
if (!paths.length) return;
const to = await prompt(action === 'copy' ? t('Copy {n} item(s) to', { n: paths.length }) : t('Move {n} item(s) to', { n: paths.length }),
{ value: this.browse.path.replace(/\/?$/, '/'), label: t('A folder of the server') });
if (to?.trim()) this.op(action, paths, to.trim().replace(/\/?$/, '/'));
}
async deleteFiles(paths) {
if (!paths.length) return;
const names = paths.map((p) => p.split('/').pop()).join(', ');
if (!await confirm(t('Delete {n} item(s) on {server}?', { n: paths.length, server: this.browse.server.name }),
t('{names}: deleted on the server, folders with everything in them. This cannot be undone.', { names }), { ok: t('Delete'), danger: true })) return;
this.op('delete', paths);
}
// transfers -----------------------------------------------------------------------------------------------
async uploadPick(folder) {
const f = await backend.invoke('native.open', folder ? { folder: true, title: t('A folder to upload') } : { title: t('A file to upload') }).catch(() => null);
if (f) this.upload([f]);
}
upload(from) { return this.uploadTo(from); }
/** Local files / folders (the project's, or absolute: the file manager's) uploaded into a remote folder (default: the one shown). */
async uploadTo(from, dir = null) {
const b = this.browse;
if (!b || !from.length) return;
const to = dir || b.path;
const conflict = await this.askConflicts('upload', from, to);
if (!conflict) return;
await this.startJob(t('Upload to {server}', { server: b.server.name }), { id: b.server.id, direction: 'upload', from, to, conflict },
() => { if (this.browse === b) this.list(b.path); });
}
async download(paths) {
if (!paths.length) return;
const to = await backend.invoke('native.open', { folder: true, title: t('Download into this folder') }).catch(() => null);
if (to) this.downloadTo(paths, to);
}
/** Remote paths downloaded into a local folder (absolute, or the project's: the Project view's drops). */
async downloadTo(paths, to) {
const b = this.browse;
if (!b || !paths.length) return;
const conflict = await this.askConflicts('download', paths, to);
if (!conflict) return;
await this.startJob(t('Download from {server}', { server: b.server.name }), { id: b.server.id, direction: 'download', from: paths, to, conflict },
() => notify(t('Downloaded into {path}.', { path: to === '.' ? (this.app.project?.name || to) : to }), 'success', { title: 'SSH' }));
}
/** 'overwrite' when nothing is in the way, else what the user picks (skip / rename / overwrite); null: cancelled. */
async askConflicts(direction, from, to) {
let existing;
try {
existing = (await backend.invoke('ssh.conflicts', { id: this.browse.server.id, direction, from, to })).existing || [];
} catch (e) { notify(e.message, 'error', { title: 'SSH' }); return null; }
if (!existing.length) return 'overwrite';
return new Promise((resolve) => {
let answered = false;
const pick = (policy) => () => { answered = true; resolve(policy); };
dialog({
title: 'Already there',
body: el('div.ssh-form', {},
el('p', {}, t('{n} item(s) already exist in {path}:', { n: existing.length, path: to === '.' ? (this.app.project?.name || to) : to })),
el('pre.ssh-conflicts', {}, existing.join('\n')),
el('p.ssh-hint.small', {}, t('Overwrite replaces them (folders are merged), Skip keeps them, Rename copies under a new name: "name (2)".'))),
buttons: [{ label: 'Cancel' }, { label: 'Skip', action: pick('skip') }, { label: 'Rename', action: pick('rename') },
{ label: 'Overwrite', primary: true, action: pick('overwrite') }],
onClose: () => { if (!answered) resolve(null); },
});
});
}
// drag and drop -------------------------------------------------------------------------------------------
/** Where a drop on the list goes: a remote folder row, else the folder shown. */
targetOf(node) {
if (!this.browse || !node || !this.listNode?.contains(node)) return null;
const row = node.closest?.('.ssh-file[data-dir]');
return { dir: row ? row.dataset.dir : this.browse.path, row };
}
dropMark(target) {
if (!this.listNode) return;
this.listNode.classList.toggle('drop', !!target && !target.row);
for (const r of this.listNode.querySelectorAll('.ssh-file.drop')) if (r !== target?.row) r.classList.remove('drop');
target?.row?.classList.add('drop');
}
/** Files of the system dragged over the window / dropped (the runtime's native:drag; x / y: the window's logical pixels). */
osDrag(d) {
if (!this.browse || !this.listNode?.isConnected) return;
if (d.phase === 'leave') { this.dropMark(null); return; }
// the page's own dragover says where the pointer is in CSS pixels; else the runtime's position, through the IDE's zoom
const recent = this.lastOver && performance.now() - this.lastOver.at < 500;
const scale = zoom.uiMode === 'native' ? zoom.get('ui') / 100 : 1;
const x = recent ? this.lastOver.x : (d.x || 0) / scale;
const y = recent ? this.lastOver.y : (d.y || 0) / scale;
const target = this.targetOf(document.elementFromPoint(x, y));
if (d.phase !== 'drop') { this.dropMark(target); return; }
this.dropMark(null);
const paths = (d.paths || []).filter((p) => !this.outPaths.has(p));
if (target && paths.length) this.uploadTo(paths, target.dir);
}
/** The mouse moves with a remote row pressed: past a few pixels, a drag begins (a ghost follows; out of the window: native). */
dragMove(ev) {
const p = this.press;
if (!p) return;
if (!(ev.buttons & 1)) { this.press = null; if (this.drag && !this.drag.out) { this.stopStaging(this.drag); this.endDrag(); } return; }
if (!this.drag) {
if (Math.hypot(ev.clientX - p.x, ev.clientY - p.y) < 6 || !this.browse) return;
this.beginDrag(p.entry);
}
const d = this.drag;
if (d.out) return;
if (ev.clientX < 0 || ev.clientY < 0 || ev.clientX >= innerWidth || ev.clientY >= innerHeight) { this.leaveWindow(); return; }
d.ghost.style.left = ev.clientX + 14 + 'px';
d.ghost.style.top = ev.clientY + 10 + 'px';
this.markTree(this.treeTargetAt(ev.clientX, ev.clientY));
}
beginDrag(entry) {
const b = this.browse;
if (!b.selected.has(entry.name)) { b.selected = new Set([entry.name]); this.renderList(); }
const items = b.entries.filter((x) => b.selected.has(x.name)).map((x) => ({ path: join(b.path, x.name), size: x.size, date: x.date, type: x.type }));
const hint = el('div.ssh-drag-hint', {}, t(this.native ? 'Release outside the IDE: into your file manager' : 'Drop on a folder of the Project view'));
const ghost = el('div.ssh-drag-ghost', {}, el('div', {}, icon(items.length === 1 && items[0].type === 'dir' ? 'folder' : 'file'), ' ',
items.length === 1 ? items[0].path.split('/').pop() : t('{n} item(s)', { n: items.length })), hint);
document.body.append(ghost);
document.body.classList.add('ssh-dragging');
this.drag = { server: b.server, items, ghost, hint, target: null, staged: null, job: null, out: false, held: true };
// the copies the file manager will take are downloaded at once (often ready before the pointer leaves the window)
if (this.native) this.stage(this.drag);
}
async stage(d) {
try {
const r = await backend.invoke('ssh.stage', { id: d.server.id, items: d.items });
if (r.job === null || r.job === undefined) { this.staged(d, r.paths); return; }
d.job = r.job;
const names = d.items.map((i) => i.path.split('/').pop()).join(', ');
this.jobs.set(r.job, { job: r.job, label: t('Preparing the drag') + ': ' + names, percent: null, file: '', speed: '', quiet: true, onEnd: () => this.staged(d, r.paths) });
this.renderJobs();
} catch (e) {
d.error = e.message;
if (d.out) notify(e.message, 'error', { title: 'SSH' });
}
}
staged(d, paths) {
d.staged = paths;
d.job = null;
if (!d.out) return;
if (d.held && this.drag === d) this.dragOut(d);
else notify(t('Downloaded: drag the files out of the IDE again.'), 'info', { title: 'SSH' });
}
/** The pointer left the window during a drag: the native drag takes over once the copies are there. */
leaveWindow() {
const d = this.drag;
if (!d || d.out) return;
d.out = true;
this.markTree(null);
d.ghost.remove();
if (!this.native) { this.endDrag(); return; }
if (d.staged) this.dragOut(d);
else if (d.error) { notify(d.error, 'error', { title: 'SSH' }); this.endDrag(); }
}
dragOut(d) {
if (d.started) return;
d.started = true;
const paths = d.staged;
this.outPaths = new Set(paths);
const label = globalThis.__TAURI_INTERNALS__?.metadata?.currentWindow?.label || 'main';
backend.invoke('native.dragFiles', { paths, window: label }).catch((e) => {
notify(t('The drag out could not start: {error}', { error: e.message }) + '\n' + t('Use Download… instead.'), 'warning', { title: 'SSH' });
});
this.endDrag();
}
dragUp() {
const d = this.drag;
this.press = null;
if (!d) return;
d.held = false;
if (d.out) {
// released out of the window before the copies were there: they stay ready for the next drag
this.endDrag();
return;
}
const target = d.target;
this.stopStaging(d);
this.endDrag();
if (target) this.downloadTo(d.items.map((i) => i.path), target);
}
/** The staging download of a drag dropped inside the window (or cancelled) is not needed any more. */
stopStaging(d) {
if (d.job === null || d.job === undefined) return;
backend.invoke('ssh.transfer.stop', { job: d.job }).catch(() => {});
this.jobs.delete(d.job);
this.renderJobs();
}
endDrag() {
const d = this.drag;
if (!d) return;
d.ghost.remove();
this.markTree(null);
document.body.classList.remove('ssh-dragging');
this.drag = null;
}
/** A folder of the Project view under the pointer: a folder row, or a file's folder; the root row: the project ('.'). */
treeTargetAt(x, y) {
const row = document.elementFromPoint(x, y)?.closest?.('.tree .row[data-path]');
if (!row) return null;
const path = row.dataset.path || '';
const dir = row.querySelector('.twisty.leaf') ? path.split('/').slice(0, -1).join('/') : path;
return { row, dir: dir || '.' };
}
markTree(target) {
for (const r of document.querySelectorAll('.tree .row.ssh-drop')) if (r !== target?.row) r.classList.remove('ssh-drop');
target?.row?.classList.add('ssh-drop');
const d = this.drag;
if (!d) return;
d.target = target ? target.dir : null;
d.hint.textContent = target ? t('Download into {path}', { path: target.dir === '.' ? (this.app.project?.name || '.') : target.dir })
: t(this.native ? 'Release outside the IDE: into your file manager' : 'Drop on a folder of the Project view');
}
async startJob(label, payload, onEnd) {
try {
const r = await backend.invoke('ssh.transfer', payload);
this.jobs.set(r.job, { job: r.job, label: label + ': ' + payload.from.map((p) => p.split(/[\\/]/).pop()).join(', '), percent: null, file: '', speed: '', onEnd });
this.renderJobs();
} catch (e) { notify(e.message, 'error', { title: 'SSH' }); }
}
jobEnded(p) {
const j = this.jobs.get(p.job);
if (!j) return;
if (p.code === 0) {
this.jobs.delete(p.job);
j.onEnd?.();
} else if (j.quiet && p.error === 'stopped') {
this.jobs.delete(p.job);
} else {
j.error = p.error || t('stopped');
j.done = true;
}
this.renderJobs();
}
renderJobs() {
const node = this.jobsNode;
if (!node) return;
clear(node);
node.hidden = !this.jobs.size;
for (const j of this.jobs.values()) {
node.append(el('div.ssh-job', {},
el('div.ssh-job-head', {}, el('span.ssh-job-label', { title: j.label }, j.label),
el('span.ssh-muted', {}, j.done ? '' : [j.file, j.percent !== null && j.percent !== undefined ? j.percent + '%' : '', j.speed].filter(Boolean).join(' ')),
j.done ? this.btn(t('Close'), 'close', () => { this.jobs.delete(j.job); this.renderJobs(); })
: this.btn(t('Stop'), 'stop', () => backend.invoke('ssh.transfer.stop', { job: j.job }).catch(() => {}))),
j.done ? el('pre.ssh-error', {}, j.error) : progressBar(j.percent === null || j.percent === undefined ? null : j.percent / 100)));
}
}
}