townmouse 0.0.0-stage → 0.2.1
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/CHANGELOG.md +126 -0
- package/DESIGN.md +169 -0
- package/LICENSE +661 -0
- package/README.md +368 -2
- package/SECURITY.md +57 -0
- package/TOWNMOUSE.md +91 -0
- package/assets/brand/mascot/README.md +23 -0
- package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
- package/assets/brand/mascot/townmouse-icon.svg +1 -0
- package/assets/brand/mascot/townmouse-monocled.png +0 -0
- package/bin/townmouse +68 -0
- package/docs/PACKAGING.md +275 -0
- package/docs/browser-workspace.md +184 -0
- package/docs/panes.md +252 -0
- package/native/TownmouseApp.swift +108 -0
- package/package.json +89 -4
- package/public/apple-touch-icon.png +0 -0
- package/public/brand/floydslabs-credit.png +0 -0
- package/public/brand/floydslabs-credit.webp +0 -0
- package/public/brand/townmouse-aristocrat.webp +0 -0
- package/public/brand/townmouse-monocled.webp +0 -0
- package/public/clipboard-text.mjs +5 -0
- package/public/favicon-16x16.png +0 -0
- package/public/favicon-32x32.png +0 -0
- package/public/favicon.ico +0 -0
- package/public/favicon.svg +1 -0
- package/public/features/autosave.mjs +76 -0
- package/public/features/clipboard.mjs +69 -0
- package/public/features/command-palette.mjs +181 -0
- package/public/features/desktop-palette.mjs +19 -0
- package/public/features/export.mjs +37 -0
- package/public/features/file-drop.mjs +77 -0
- package/public/features/floating-palette.mjs +113 -0
- package/public/features/fontsize.mjs +72 -0
- package/public/features/haptic-keys.mjs +42 -0
- package/public/features/history-undo.mjs +102 -0
- package/public/features/keepalive.mjs +36 -0
- package/public/features/keybar-config.mjs +70 -0
- package/public/features/keyboard-shortcuts.mjs +74 -0
- package/public/features/links.mjs +139 -0
- package/public/features/multi-window-sync.mjs +74 -0
- package/public/features/osc-bridge.mjs +59 -0
- package/public/features/phone-landscape-focus.mjs +157 -0
- package/public/features/recent-commands.mjs +100 -0
- package/public/features/search.mjs +134 -0
- package/public/features/session-lock.mjs +96 -0
- package/public/features/session-manager.mjs +149 -0
- package/public/features/settings-sync.mjs +77 -0
- package/public/features/shortcut-help.mjs +85 -0
- package/public/features/smart-completions.mjs +101 -0
- package/public/features/smart-suggest.mjs +124 -0
- package/public/features/snippets.mjs +85 -0
- package/public/features/split-view.mjs +102 -0
- package/public/features/status-metrics.mjs +114 -0
- package/public/features/stylus-support.mjs +124 -0
- package/public/features/swipe-history.mjs +141 -0
- package/public/features/swipe-sessions.mjs +85 -0
- package/public/features/tab-reorder.mjs +62 -0
- package/public/features/theme-system.mjs +51 -0
- package/public/features/toast-status.mjs +118 -0
- package/public/features/two-finger-menu.mjs +87 -0
- package/public/features/voice-input.mjs +244 -0
- package/public/features/wake-fullscreen.mjs +67 -0
- package/public/features/window-title.mjs +40 -0
- package/public/features/zoom.mjs +80 -0
- package/public/icon-128.png +0 -0
- package/public/icon-180.png +0 -0
- package/public/icon-192.png +0 -0
- package/public/icon-48.png +0 -0
- package/public/icon-512-maskable.png +0 -0
- package/public/icon-512.png +0 -0
- package/public/icon.svg +1 -0
- package/public/index.html +1765 -0
- package/public/input-chunks.mjs +22 -0
- package/public/input-guard.mjs +210 -0
- package/public/manifest.json +56 -0
- package/public/panes.css +1257 -0
- package/public/panes.html +208 -0
- package/public/panes.mjs +2625 -0
- package/public/service-worker.js +67 -0
- package/public/workspace.css +1447 -0
- package/public/workspace.mjs +1475 -0
- package/scripts/install-service.sh +269 -0
- package/scripts/node-runtime.sh +138 -0
- package/scripts/panes +439 -0
- package/scripts/prepare-native.sh +35 -0
- package/scripts/run-hooks +69 -0
- package/scripts/t1.sh +113 -0
- package/scripts/uninstall-service.sh +49 -0
- package/src/agent-guide.js +260 -0
- package/src/attachments.js +128 -0
- package/src/browser-dom.js +545 -0
- package/src/browser-workspace.js +1246 -0
- package/src/chrome-resolve.js +80 -0
- package/src/pty-permissions.js +99 -0
- package/src/regex-worker.js +13 -0
- package/src/replay-text.js +189 -0
- package/src/request-boundary.js +58 -0
- package/src/safe-regex.js +87 -0
- package/src/server.js +1122 -0
- package/src/shell-resolve.js +42 -0
- package/src/static-deps.js +61 -0
- package/src/workspace-panes.js +1099 -0
package/public/panes.mjs
ADDED
|
@@ -0,0 +1,2625 @@
|
|
|
1
|
+
import { Terminal } from '/node_modules/@xterm/xterm/lib/xterm.mjs';
|
|
2
|
+
import { FitAddon } from '/node_modules/@xterm/addon-fit/lib/addon-fit.mjs';
|
|
3
|
+
import { WebLinksAddon } from '/node_modules/@xterm/addon-web-links/lib/addon-web-links.mjs';
|
|
4
|
+
import { chunkInput } from '/input-chunks.mjs';
|
|
5
|
+
import { decodeClipboardText } from '/clipboard-text.mjs';
|
|
6
|
+
|
|
7
|
+
const API_ROOT = '/api/panes';
|
|
8
|
+
const STATE_POLL_MS = 1200;
|
|
9
|
+
const READ_POLL_MS = 180;
|
|
10
|
+
const SNAPSHOT_POLL_MS = 1000;
|
|
11
|
+
const MAX_HISTORY = 120000;
|
|
12
|
+
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
|
|
13
|
+
|
|
14
|
+
const byId = (id) => document.getElementById(id);
|
|
15
|
+
const els = {
|
|
16
|
+
app: byId('panes-app'),
|
|
17
|
+
grid: byId('pane-grid'),
|
|
18
|
+
tabStrip: byId('tabstrip'),
|
|
19
|
+
workspace: byId('workspace'),
|
|
20
|
+
emptyState: byId('empty-state'),
|
|
21
|
+
emptyTitle: byId('empty-title'),
|
|
22
|
+
emptyCopy: byId('empty-copy'),
|
|
23
|
+
emptyActions: byId('empty-actions'),
|
|
24
|
+
emptyAddTerminal: byId('empty-add-terminal'),
|
|
25
|
+
emptyAddBrowser: byId('empty-add-browser'),
|
|
26
|
+
emptyNewTab: byId('empty-new-tab'),
|
|
27
|
+
backButton: byId('back-button'),
|
|
28
|
+
hostPill: byId('host-pill'),
|
|
29
|
+
hostName: byId('host-name'),
|
|
30
|
+
tabsButton: byId('tabs-button'),
|
|
31
|
+
tabCount: byId('tab-count'),
|
|
32
|
+
keyboardButton: byId('keyboard-button'),
|
|
33
|
+
menuButton: byId('menu-button'),
|
|
34
|
+
tabsDialog: byId('tabs-dialog'),
|
|
35
|
+
tabsList: byId('tabs-list'),
|
|
36
|
+
tabsEmpty: byId('tabs-empty'),
|
|
37
|
+
tabsLimits: byId('tabs-limits'),
|
|
38
|
+
tabsNewTab: byId('tabs-new-tab'),
|
|
39
|
+
tabsAddTerminal: byId('tabs-add-terminal'),
|
|
40
|
+
tabsAddBrowser: byId('tabs-add-browser'),
|
|
41
|
+
menuDialog: byId('menu-dialog'),
|
|
42
|
+
menuAddTerminal: byId('menu-add-terminal'),
|
|
43
|
+
menuAddBrowser: byId('menu-add-browser'),
|
|
44
|
+
menuNewTab: byId('menu-new-tab'),
|
|
45
|
+
menuAttach: byId('menu-attach'),
|
|
46
|
+
menuReader: byId('menu-reader'),
|
|
47
|
+
menuShortcuts: byId('menu-shortcuts'),
|
|
48
|
+
menuFontUp: byId('menu-font-up'),
|
|
49
|
+
menuFontDown: byId('menu-font-down'),
|
|
50
|
+
shortcutsDialog: byId('shortcuts-dialog'),
|
|
51
|
+
attachInput: byId('attach-input'),
|
|
52
|
+
readerView: byId('reader-view'),
|
|
53
|
+
readerText: byId('reader-text'),
|
|
54
|
+
readerRefresh: byId('reader-refresh'),
|
|
55
|
+
readerClose: byId('reader-close'),
|
|
56
|
+
closeConfirm: byId('close-confirm'),
|
|
57
|
+
closeConfirmTitle: byId('close-confirm-title'),
|
|
58
|
+
closeConfirmCopy: byId('close-confirm-copy'),
|
|
59
|
+
closeCancel: byId('close-cancel'),
|
|
60
|
+
closeApprove: byId('close-approve'),
|
|
61
|
+
keybar: byId('pane-keybar'),
|
|
62
|
+
contextMenu: byId('pane-context-menu'),
|
|
63
|
+
browserContextMenu: byId('browser-context-menu'),
|
|
64
|
+
browserControl: byId('browser-control'),
|
|
65
|
+
browserControlLabel: byId('browser-control-label'),
|
|
66
|
+
browserControlSelect: byId('browser-control-select'),
|
|
67
|
+
browserControlValue: byId('browser-control-value'),
|
|
68
|
+
browserControlCancel: byId('browser-control-cancel'),
|
|
69
|
+
browserControlApply: byId('browser-control-apply'),
|
|
70
|
+
pageDialog: byId('page-dialog'),
|
|
71
|
+
pageDialogMessage: byId('page-dialog-message'),
|
|
72
|
+
pageDialogField: byId('page-dialog-field'),
|
|
73
|
+
pageDialogInput: byId('page-dialog-input'),
|
|
74
|
+
pageDialogDismiss: byId('page-dialog-dismiss'),
|
|
75
|
+
pageDialogAccept: byId('page-dialog-accept'),
|
|
76
|
+
notice: byId('notice'),
|
|
77
|
+
srStatus: byId('sr-status')
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const TERMINAL_THEME = {
|
|
81
|
+
background: '#0a0d12',
|
|
82
|
+
foreground: '#e8eef6',
|
|
83
|
+
cursor: '#8ab4ff',
|
|
84
|
+
cursorAccent: '#0a0d12',
|
|
85
|
+
selectionBackground: 'rgba(138, 180, 255, 0.24)',
|
|
86
|
+
black: '#11161d',
|
|
87
|
+
red: '#ff8f8f',
|
|
88
|
+
green: '#7fe3c0',
|
|
89
|
+
yellow: '#e9d6a1',
|
|
90
|
+
blue: '#8ab4ff',
|
|
91
|
+
magenta: '#d9b1cf',
|
|
92
|
+
cyan: '#8fe6d4',
|
|
93
|
+
white: '#e8eef6',
|
|
94
|
+
brightBlack: '#5f6f88',
|
|
95
|
+
brightRed: '#ffb3b3',
|
|
96
|
+
brightGreen: '#a5f2d8',
|
|
97
|
+
brightYellow: '#f3e5bd',
|
|
98
|
+
brightBlue: '#a9c8ff',
|
|
99
|
+
brightMagenta: '#e8cae1',
|
|
100
|
+
brightCyan: '#b6f4e6',
|
|
101
|
+
brightWhite: '#f4f8ff'
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const CLOSE_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>';
|
|
105
|
+
const BACK_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M15 18l-6-6 6-6"/></svg>';
|
|
106
|
+
const RELOAD_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5"/></svg>';
|
|
107
|
+
const MAXIMIZE_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 4H4v5M15 4h5v5M4 15v5h5M20 15v5h-5"/></svg>';
|
|
108
|
+
const RESTORE_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 4v5H4M15 4v5h5M4 15h5v5M20 15h-5v5M9 9h6v6H9z"/></svg>';
|
|
109
|
+
const LOCK_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>';
|
|
110
|
+
|
|
111
|
+
let token = '';
|
|
112
|
+
let currentState = null;
|
|
113
|
+
let lastSignature = '';
|
|
114
|
+
let currentTabId = null;
|
|
115
|
+
let refreshInFlight = null;
|
|
116
|
+
let noticeTimer = 0;
|
|
117
|
+
let noticeText = '';
|
|
118
|
+
let noticeAt = 0;
|
|
119
|
+
let tabsDialogSignature = '';
|
|
120
|
+
let booting = false;
|
|
121
|
+
let pendingClose = null;
|
|
122
|
+
let pageDialogRecordId = null;
|
|
123
|
+
let pageDialogId = null;
|
|
124
|
+
let pageDialogType = '';
|
|
125
|
+
let contextRecordId = null;
|
|
126
|
+
let browserContextRecordId = null;
|
|
127
|
+
let browserControlRecordId = null;
|
|
128
|
+
let browserControlPoint = null;
|
|
129
|
+
let browserControlKind = '';
|
|
130
|
+
|
|
131
|
+
const cursors = new Map();
|
|
132
|
+
const histories = new Map();
|
|
133
|
+
const records = new Map();
|
|
134
|
+
// Input queues are keyed by pane id, not by the view record. A tab switch can
|
|
135
|
+
// dispose and recreate a record while a paste is still being delivered; both
|
|
136
|
+
// views must feed the same ordered queue.
|
|
137
|
+
const inputPumps = new Map();
|
|
138
|
+
|
|
139
|
+
const PANE_FONT_KEY = 'townmouse.paneFontSize';
|
|
140
|
+
|
|
141
|
+
function paneFontOverride() {
|
|
142
|
+
const value = Number(window.localStorage.getItem(PANE_FONT_KEY));
|
|
143
|
+
return value >= 8 && value <= 24 ? value : 0;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function adjustPaneFont(delta) {
|
|
147
|
+
const record = activeTerminalRecord();
|
|
148
|
+
const current = paneFontOverride() || (record?.term?.options.fontSize) || 11;
|
|
149
|
+
const next = Math.max(8, Math.min(24, current + delta));
|
|
150
|
+
try { window.localStorage.setItem(PANE_FONT_KEY, String(next)); } catch (_) { /* storage disabled */ }
|
|
151
|
+
for (const candidate of records.values()) {
|
|
152
|
+
if (candidate.kind !== 'terminal' || !candidate.term) continue;
|
|
153
|
+
candidate.term.options.fontSize = next;
|
|
154
|
+
safeFit(candidate);
|
|
155
|
+
}
|
|
156
|
+
showNotice(`Terminal text ${next}px`, 'info', 1800);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function inputPumpFor(paneId) {
|
|
160
|
+
let pump = inputPumps.get(paneId);
|
|
161
|
+
if (!pump) {
|
|
162
|
+
pump = { paneId, pendingInput: '', inputTimer: 0, inputBusy: false, inputStopped: false };
|
|
163
|
+
inputPumps.set(paneId, pump);
|
|
164
|
+
}
|
|
165
|
+
return pump;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function shellQuote(value) {
|
|
169
|
+
return `'${String(value).replace(/'/g, `'\\''`)}'`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function uploadAttachment(file) {
|
|
173
|
+
const response = await fetch('/api/attachments', {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
headers: {
|
|
176
|
+
'Content-Type': file.type || 'application/octet-stream',
|
|
177
|
+
'X-Filename': encodeURIComponent(file.name || 'attachment')
|
|
178
|
+
},
|
|
179
|
+
body: file
|
|
180
|
+
});
|
|
181
|
+
let payload = null;
|
|
182
|
+
try { payload = await response.json(); } catch (_) { payload = null; }
|
|
183
|
+
if (!response.ok) throw new Error((payload && payload.error) || `Upload failed (${response.status}).`);
|
|
184
|
+
return payload;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function attachFiles(record, files) {
|
|
188
|
+
if (!record || !files || !files.length) return;
|
|
189
|
+
for (const file of files) {
|
|
190
|
+
try {
|
|
191
|
+
const attachment = await uploadAttachment(file);
|
|
192
|
+
if (record.kind === 'terminal' && record.term) {
|
|
193
|
+
record.term.paste(`${shellQuote(attachment.path)} `);
|
|
194
|
+
showAttachmentNotice(attachment, file);
|
|
195
|
+
} else if (record.kind === 'browser') {
|
|
196
|
+
// Navigate the local browser straight at loopback; a forwarded host is
|
|
197
|
+
// for human-facing links, not the pane's own Chromium.
|
|
198
|
+
await api(`/panes/${record.id}/url`, { method: 'POST', body: { url: attachment.localUrl || attachment.url } });
|
|
199
|
+
record.lastViewport = '';
|
|
200
|
+
requestSnapshot(record, 120);
|
|
201
|
+
showNotice(`Opened ${file.name} in the browser pane`, 'info', 2600);
|
|
202
|
+
}
|
|
203
|
+
} catch (error) {
|
|
204
|
+
showNotice(error.message || `Could not attach ${file.name}.`, 'error');
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function reorderActivePane(direction) {
|
|
210
|
+
const tab = activeTab();
|
|
211
|
+
if (!tab || tab.panes.length < 2) return;
|
|
212
|
+
const from = tab.panes.findIndex((pane) => pane.id === effectiveActivePaneId(tab));
|
|
213
|
+
const to = Math.max(0, Math.min(tab.panes.length - 1, from + direction));
|
|
214
|
+
if (from < 0 || to === from) return;
|
|
215
|
+
void (async () => {
|
|
216
|
+
try {
|
|
217
|
+
const next = await api(`/tabs/${tab.id}/reorder`, { method: 'POST', body: { paneId: tab.panes[from].id, index: to } });
|
|
218
|
+
if (next && next.tabs) applyState(next, { force: true });
|
|
219
|
+
else await refresh();
|
|
220
|
+
logStatus('Pane reordered.');
|
|
221
|
+
} catch (error) {
|
|
222
|
+
showNotice(error.message || 'Could not reorder the pane.', 'error');
|
|
223
|
+
}
|
|
224
|
+
})();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function wirePaneReorder(root, paneId) {
|
|
228
|
+
const header = root.querySelector('.pane-header');
|
|
229
|
+
if (!header) return;
|
|
230
|
+
header.addEventListener('pointerdown', (event) => {
|
|
231
|
+
if (event.target.closest('button, input')) return;
|
|
232
|
+
const startX = event.clientX;
|
|
233
|
+
const startY = event.clientY;
|
|
234
|
+
let dragging = false;
|
|
235
|
+
let target = null;
|
|
236
|
+
const clearTarget = () => {
|
|
237
|
+
if (target) target.classList.remove('drop-target');
|
|
238
|
+
target = null;
|
|
239
|
+
};
|
|
240
|
+
const move = (moveEvent) => {
|
|
241
|
+
if (!dragging && Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY) > 8) {
|
|
242
|
+
dragging = true;
|
|
243
|
+
root.classList.add('reordering');
|
|
244
|
+
}
|
|
245
|
+
if (!dragging) return;
|
|
246
|
+
const under = document.elementFromPoint(moveEvent.clientX, moveEvent.clientY)?.closest?.('.pane');
|
|
247
|
+
if (under === target) return;
|
|
248
|
+
clearTarget();
|
|
249
|
+
if (under && under !== root) {
|
|
250
|
+
target = under;
|
|
251
|
+
target.classList.add('drop-target');
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
const end = (upEvent) => {
|
|
255
|
+
document.removeEventListener('pointermove', move);
|
|
256
|
+
document.removeEventListener('pointerup', end);
|
|
257
|
+
document.removeEventListener('pointercancel', end);
|
|
258
|
+
root.classList.remove('reordering');
|
|
259
|
+
const drop = target;
|
|
260
|
+
clearTarget();
|
|
261
|
+
if (!dragging || !drop || !currentState) return;
|
|
262
|
+
const tab = activeTab();
|
|
263
|
+
if (!tab) return;
|
|
264
|
+
const from = tab.panes.findIndex((pane) => pane.id === paneId);
|
|
265
|
+
const dropId = drop.dataset.paneId;
|
|
266
|
+
const over = tab.panes.findIndex((pane) => pane.id === dropId);
|
|
267
|
+
if (from < 0 || over < 0 || from === over) return;
|
|
268
|
+
const rect = drop.getBoundingClientRect();
|
|
269
|
+
const after = upEvent.clientX > rect.left + rect.width / 2;
|
|
270
|
+
const index = Math.max(0, Math.min(tab.panes.length - 1, over + (after ? 1 : 0) - (from < over ? 1 : 0)));
|
|
271
|
+
void (async () => {
|
|
272
|
+
try {
|
|
273
|
+
const next = await api(`/tabs/${tab.id}/reorder`, { method: 'POST', body: { paneId, index } });
|
|
274
|
+
if (next && next.tabs) applyState(next, { force: true });
|
|
275
|
+
else await refresh();
|
|
276
|
+
} catch (error) {
|
|
277
|
+
showNotice(error.message || 'Could not reorder the pane.', 'error');
|
|
278
|
+
}
|
|
279
|
+
})();
|
|
280
|
+
};
|
|
281
|
+
document.addEventListener('pointermove', move);
|
|
282
|
+
document.addEventListener('pointerup', end);
|
|
283
|
+
document.addEventListener('pointercancel', end);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function wireDrop(root, paneId) {
|
|
288
|
+
const recordFor = () => records.get(paneId);
|
|
289
|
+
const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes('Files');
|
|
290
|
+
root.addEventListener('dragover', (event) => {
|
|
291
|
+
if (!hasFiles(event)) return;
|
|
292
|
+
event.preventDefault();
|
|
293
|
+
event.stopPropagation();
|
|
294
|
+
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
|
|
295
|
+
root.classList.add('drop-target');
|
|
296
|
+
});
|
|
297
|
+
root.addEventListener('dragleave', (event) => {
|
|
298
|
+
if (!root.contains(event.relatedTarget)) root.classList.remove('drop-target');
|
|
299
|
+
});
|
|
300
|
+
root.addEventListener('drop', (event) => {
|
|
301
|
+
if (!event.dataTransfer?.files?.length) return;
|
|
302
|
+
event.preventDefault();
|
|
303
|
+
event.stopPropagation();
|
|
304
|
+
root.classList.remove('drop-target');
|
|
305
|
+
void attachFiles(recordFor(), Array.from(event.dataTransfer.files));
|
|
306
|
+
});
|
|
307
|
+
root.addEventListener('paste', (event) => {
|
|
308
|
+
const files = Array.from(event.clipboardData?.items || [])
|
|
309
|
+
.filter((item) => item.kind === 'file')
|
|
310
|
+
.map((item) => item.getAsFile())
|
|
311
|
+
.filter(Boolean);
|
|
312
|
+
if (!files.length) return;
|
|
313
|
+
event.preventDefault();
|
|
314
|
+
event.stopImmediatePropagation();
|
|
315
|
+
void attachFiles(recordFor(), files);
|
|
316
|
+
}, true);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function logStatus(message) {
|
|
320
|
+
els.srStatus.textContent = message;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function showNotice(message, kind = 'error', duration = 4200, copyUrl = '') {
|
|
324
|
+
if (!message) return;
|
|
325
|
+
const now = Date.now();
|
|
326
|
+
if (kind === 'error' && message === noticeText && now - noticeAt < 1200) return;
|
|
327
|
+
noticeText = message;
|
|
328
|
+
noticeAt = now;
|
|
329
|
+
els.notice.textContent = message;
|
|
330
|
+
els.notice.dataset.kind = kind;
|
|
331
|
+
if (copyUrl) {
|
|
332
|
+
els.notice.dataset.copyUrl = copyUrl;
|
|
333
|
+
els.notice.title = 'Tap to copy the attachment URL';
|
|
334
|
+
} else {
|
|
335
|
+
delete els.notice.dataset.copyUrl;
|
|
336
|
+
els.notice.removeAttribute('title');
|
|
337
|
+
}
|
|
338
|
+
els.notice.hidden = false;
|
|
339
|
+
clearTimeout(noticeTimer);
|
|
340
|
+
if (duration > 0) {
|
|
341
|
+
noticeTimer = window.setTimeout(() => { els.notice.hidden = true; }, duration);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function showAttachmentNotice(attachment, file) {
|
|
346
|
+
// The URL is part of the message, not a filename that disappears. Tapping
|
|
347
|
+
// the notice copies it; agents can get the same URL from `panes attach`.
|
|
348
|
+
showNotice(`Attached ${file.name} · ${attachment.url}`, 'info', 8000, attachment.url);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function syncMenuState() {
|
|
352
|
+
const anyOpen = [els.contextMenu, els.browserContextMenu]
|
|
353
|
+
.some((menu) => menu && !menu.hidden);
|
|
354
|
+
els.app?.classList.toggle('menu-open', anyOpen);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function syncDialogState() {
|
|
358
|
+
const anyOpen = [els.browserControl, els.pageDialog]
|
|
359
|
+
.some((dialog) => dialog && !dialog.hidden);
|
|
360
|
+
els.app?.classList.toggle('dialog-open', anyOpen);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function hideContextMenu() {
|
|
364
|
+
contextRecordId = null;
|
|
365
|
+
browserContextRecordId = null;
|
|
366
|
+
if (els.contextMenu) els.contextMenu.hidden = true;
|
|
367
|
+
if (els.browserContextMenu) els.browserContextMenu.hidden = true;
|
|
368
|
+
syncMenuState();
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function showBrowserContextMenu(record, _clientX, _clientY) {
|
|
372
|
+
if (!els.browserContextMenu || !record || record.kind !== 'browser') return;
|
|
373
|
+
// A blocking page prompt owns the bottom strip; the rail would be hidden
|
|
374
|
+
// behind it and the action would look broken.
|
|
375
|
+
if (els.app?.classList.contains('dialog-open')) return;
|
|
376
|
+
hideContextMenu();
|
|
377
|
+
closeSheets();
|
|
378
|
+
browserContextRecordId = record.id;
|
|
379
|
+
record.suppressClickUntil = Date.now() + 700;
|
|
380
|
+
els.browserContextMenu.hidden = false;
|
|
381
|
+
syncMenuState();
|
|
382
|
+
els.browserContextMenu.querySelector('[role="menuitem"]')?.focus();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function wireBrowserContext(record) {
|
|
386
|
+
record.image.addEventListener('contextmenu', (event) => {
|
|
387
|
+
event.preventDefault();
|
|
388
|
+
void setActivePane(record.id);
|
|
389
|
+
showBrowserContextMenu(record, event.clientX, event.clientY);
|
|
390
|
+
});
|
|
391
|
+
let timer = 0;
|
|
392
|
+
let startX = 0;
|
|
393
|
+
let startY = 0;
|
|
394
|
+
record.view.addEventListener('pointerdown', (event) => {
|
|
395
|
+
if (event.pointerType === 'mouse') return;
|
|
396
|
+
startX = event.clientX;
|
|
397
|
+
startY = event.clientY;
|
|
398
|
+
clearTimeout(timer);
|
|
399
|
+
timer = window.setTimeout(() => showBrowserContextMenu(record, startX, startY), 550);
|
|
400
|
+
});
|
|
401
|
+
record.view.addEventListener('pointermove', (event) => {
|
|
402
|
+
if (Math.hypot(event.clientX - startX, event.clientY - startY) > 10) clearTimeout(timer);
|
|
403
|
+
});
|
|
404
|
+
for (const type of ['pointerup', 'pointercancel', 'pointerleave']) {
|
|
405
|
+
record.view.addEventListener(type, () => clearTimeout(timer));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function showContextMenu(record, _clientX, _clientY) {
|
|
410
|
+
if (!els.contextMenu || !record || record.kind !== 'terminal') return;
|
|
411
|
+
if (els.app?.classList.contains('dialog-open')) return;
|
|
412
|
+
hideContextMenu();
|
|
413
|
+
closeSheets();
|
|
414
|
+
contextRecordId = record.id;
|
|
415
|
+
els.contextMenu.hidden = false;
|
|
416
|
+
syncMenuState();
|
|
417
|
+
els.contextMenu.querySelector('[role="menuitem"]')?.focus();
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function wirePaneContext(root, record) {
|
|
421
|
+
root.addEventListener('contextmenu', (event) => {
|
|
422
|
+
if (event.target.closest('input, button')) return;
|
|
423
|
+
event.preventDefault();
|
|
424
|
+
void setActivePane(record.id);
|
|
425
|
+
showContextMenu(record, event.clientX, event.clientY);
|
|
426
|
+
});
|
|
427
|
+
const body = root.querySelector('.pane-body');
|
|
428
|
+
if (!body) return;
|
|
429
|
+
let timer = 0;
|
|
430
|
+
let startX = 0;
|
|
431
|
+
let startY = 0;
|
|
432
|
+
body.addEventListener('pointerdown', (event) => {
|
|
433
|
+
if (event.pointerType === 'mouse') return;
|
|
434
|
+
startX = event.clientX;
|
|
435
|
+
startY = event.clientY;
|
|
436
|
+
clearTimeout(timer);
|
|
437
|
+
timer = window.setTimeout(() => showContextMenu(record, startX, startY), 550);
|
|
438
|
+
});
|
|
439
|
+
body.addEventListener('pointermove', (event) => {
|
|
440
|
+
if (Math.hypot(event.clientX - startX, event.clientY - startY) > 10) clearTimeout(timer);
|
|
441
|
+
});
|
|
442
|
+
for (const type of ['pointerup', 'pointercancel', 'pointerleave']) {
|
|
443
|
+
body.addEventListener(type, () => clearTimeout(timer));
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function hideBrowserControl() {
|
|
448
|
+
browserControlRecordId = null;
|
|
449
|
+
browserControlPoint = null;
|
|
450
|
+
browserControlKind = '';
|
|
451
|
+
if (els.browserControl) els.browserControl.hidden = true;
|
|
452
|
+
syncDialogState();
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function showBrowserControl(record, control, point) {
|
|
456
|
+
if (!els.browserControl || !record || !control) return;
|
|
457
|
+
// Only dismiss soft docks when the control is first revealed; later updates
|
|
458
|
+
// of an already-visible control must not close a sheet the user opened.
|
|
459
|
+
if (els.browserControl.hidden) {
|
|
460
|
+
closeSheets();
|
|
461
|
+
hideContextMenu();
|
|
462
|
+
}
|
|
463
|
+
browserControlRecordId = record.id;
|
|
464
|
+
browserControlPoint = point;
|
|
465
|
+
browserControlKind = control.kind;
|
|
466
|
+
els.browserControl.hidden = false;
|
|
467
|
+
syncDialogState();
|
|
468
|
+
if (control.kind === 'select') {
|
|
469
|
+
els.browserControlLabel.textContent = 'Choose an option';
|
|
470
|
+
els.browserControlSelect.hidden = false;
|
|
471
|
+
els.browserControlValue.hidden = true;
|
|
472
|
+
els.browserControlSelect.replaceChildren(...(control.options || []).map((option) => {
|
|
473
|
+
const el = document.createElement('option');
|
|
474
|
+
el.value = option.value;
|
|
475
|
+
el.textContent = option.label;
|
|
476
|
+
if (option.value === control.value) el.selected = true;
|
|
477
|
+
return el;
|
|
478
|
+
}));
|
|
479
|
+
} else {
|
|
480
|
+
els.browserControlLabel.textContent = `Choose a ${control.kind} value`;
|
|
481
|
+
els.browserControlSelect.hidden = true;
|
|
482
|
+
els.browserControlValue.hidden = false;
|
|
483
|
+
els.browserControlValue.type = control.kind;
|
|
484
|
+
els.browserControlValue.value = control.value || '';
|
|
485
|
+
}
|
|
486
|
+
(control.kind === 'select' ? els.browserControlSelect : els.browserControlValue).focus();
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async function applyBrowserControl() {
|
|
490
|
+
const record = records.get(browserControlRecordId);
|
|
491
|
+
if (!record || !browserControlPoint) { hideBrowserControl(); return; }
|
|
492
|
+
const value = browserControlKind === 'select'
|
|
493
|
+
? els.browserControlSelect.value
|
|
494
|
+
: els.browserControlValue.value;
|
|
495
|
+
const action = browserControlKind === 'select' ? 'selectAt' : 'setValueAt';
|
|
496
|
+
const point = browserControlPoint;
|
|
497
|
+
hideBrowserControl();
|
|
498
|
+
await browserAction(record, action, { ...point, value });
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function hidePageDialog() {
|
|
502
|
+
pageDialogRecordId = null;
|
|
503
|
+
pageDialogId = null;
|
|
504
|
+
pageDialogType = '';
|
|
505
|
+
if (els.pageDialog) els.pageDialog.hidden = true;
|
|
506
|
+
syncDialogState();
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function showPageDialog(record, dialog) {
|
|
510
|
+
if (!els.pageDialog || !record || !dialog || !dialog.id) return;
|
|
511
|
+
if (pageDialogId !== dialog.id) {
|
|
512
|
+
// A blocking page dialog outranks the soft docks. Close them on arrival;
|
|
513
|
+
// the next snapshot reuses this id, so a sheet the user reopens later is
|
|
514
|
+
// not closed again. The browser control shares the bottom strip, so it
|
|
515
|
+
// must not be left underneath the prompt.
|
|
516
|
+
closeSheets();
|
|
517
|
+
hideContextMenu();
|
|
518
|
+
hideBrowserControl();
|
|
519
|
+
pageDialogRecordId = record.id;
|
|
520
|
+
pageDialogId = dialog.id;
|
|
521
|
+
pageDialogType = dialog.type || 'alert';
|
|
522
|
+
els.pageDialogMessage.textContent = `Page ${pageDialogType}: ${dialog.message || ''}`;
|
|
523
|
+
els.pageDialogField.hidden = pageDialogType !== 'prompt';
|
|
524
|
+
els.pageDialogInput.value = dialog.defaultValue || '';
|
|
525
|
+
els.pageDialogAccept.textContent = pageDialogType === 'alert' ? 'OK' : 'Accept';
|
|
526
|
+
}
|
|
527
|
+
els.pageDialog.hidden = false;
|
|
528
|
+
syncDialogState();
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function answerPageDialog(action) {
|
|
532
|
+
const record = records.get(pageDialogRecordId);
|
|
533
|
+
if (!record) { hidePageDialog(); return; }
|
|
534
|
+
const body = { action };
|
|
535
|
+
if (action === 'accept' && pageDialogType === 'prompt') body.text = els.pageDialogInput.value;
|
|
536
|
+
try {
|
|
537
|
+
await api(`/panes/${record.id}/browser/dialog`, { method: 'POST', body });
|
|
538
|
+
hidePageDialog();
|
|
539
|
+
requestSnapshot(record, 120);
|
|
540
|
+
logStatus(action === 'accept' ? 'Page dialog accepted.' : 'Page dialog dismissed.');
|
|
541
|
+
} catch (error) {
|
|
542
|
+
showNotice(error.message || 'Could not answer the page dialog.', 'error');
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
async function api(path, { method = 'GET', body } = {}) {
|
|
547
|
+
const headers = { 'X-Townmouse-Token': token };
|
|
548
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
549
|
+
const response = await fetch(API_ROOT + path, {
|
|
550
|
+
method,
|
|
551
|
+
headers,
|
|
552
|
+
cache: 'no-store',
|
|
553
|
+
body: body === undefined ? undefined : JSON.stringify(body)
|
|
554
|
+
});
|
|
555
|
+
let payload = null;
|
|
556
|
+
try { payload = await response.json(); } catch (_) { payload = null; }
|
|
557
|
+
if (!response.ok) {
|
|
558
|
+
throw new Error((payload && payload.error) || `Request failed (${response.status}).`);
|
|
559
|
+
}
|
|
560
|
+
return payload;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function activeTab(state = currentState) {
|
|
564
|
+
if (!state || !Array.isArray(state.tabs)) return null;
|
|
565
|
+
return state.tabs.find((tab) => tab.id === state.activeTabId) || state.tabs[0] || null;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function effectiveActivePaneId(tab = activeTab()) {
|
|
569
|
+
if (!tab || !tab.panes.length) return null;
|
|
570
|
+
const candidate = currentState && currentState.activePaneId;
|
|
571
|
+
return tab.panes.some((pane) => pane.id === candidate) ? candidate : tab.panes[0].id;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function paneTitle(pane, index) {
|
|
575
|
+
const title = String(pane.title || '').trim();
|
|
576
|
+
if (title) return title;
|
|
577
|
+
if (pane.kind === 'browser') {
|
|
578
|
+
if (pane.url && pane.url !== 'about:blank') return pane.url;
|
|
579
|
+
return 'Browser';
|
|
580
|
+
}
|
|
581
|
+
return `Terminal ${index + 1}`;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ─── Terminal key bar ──────────────────────────────────────────────────────
|
|
585
|
+
// Phones have no Esc/Tab/Ctrl/arrow keys. Emit the same xterm sequences as the
|
|
586
|
+
// main terminal directly through the pane input queue, independent of focus.
|
|
587
|
+
|
|
588
|
+
const PANE_SEQ = {
|
|
589
|
+
esc: '\x1b', tab: '\t',
|
|
590
|
+
up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D',
|
|
591
|
+
home: '\x1b[H', end: '\x1b[F', pgup: '\x1b[5~', pgdn: '\x1b[6~'
|
|
592
|
+
};
|
|
593
|
+
const paneMods = { ctrl: false, alt: false };
|
|
594
|
+
|
|
595
|
+
function activeTerminalRecord() {
|
|
596
|
+
const record = records.get(effectiveActivePaneId());
|
|
597
|
+
return record && record.kind === 'terminal' && !record.disposed ? record : null;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
async function refreshReaderView() {
|
|
601
|
+
const paneId = effectiveActivePaneId();
|
|
602
|
+
const record = records.get(paneId);
|
|
603
|
+
if (!els.readerText) return;
|
|
604
|
+
if (!record) {
|
|
605
|
+
els.readerText.textContent = 'No active pane.';
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
if (record.kind === 'browser') {
|
|
609
|
+
els.readerText.textContent = 'Reading page text…';
|
|
610
|
+
try {
|
|
611
|
+
const page = await api(`/panes/${paneId}/browser/content`);
|
|
612
|
+
els.readerText.textContent = String(page.text || '').trim() || 'This page has no readable text.';
|
|
613
|
+
} catch (error) {
|
|
614
|
+
els.readerText.textContent = error.message || 'Could not read the page.';
|
|
615
|
+
}
|
|
616
|
+
els.readerText.scrollTop = 0;
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
if (!record.term) {
|
|
620
|
+
els.readerText.textContent = 'No active terminal.';
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const buffer = record.term.buffer.active;
|
|
624
|
+
const lines = [];
|
|
625
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
626
|
+
const line = buffer.getLine(i);
|
|
627
|
+
lines.push(line ? line.translateToString(true) : '');
|
|
628
|
+
}
|
|
629
|
+
while (lines.length && !lines[0].trim()) lines.shift();
|
|
630
|
+
while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
|
|
631
|
+
els.readerText.textContent = lines.join('\n') || 'No terminal text yet.';
|
|
632
|
+
els.readerText.scrollTop = 0;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function openReaderView() {
|
|
636
|
+
if (!els.readerView) return;
|
|
637
|
+
closeSheets();
|
|
638
|
+
els.readerView.hidden = false;
|
|
639
|
+
void refreshReaderView();
|
|
640
|
+
els.readerClose.focus();
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function closeReaderView() {
|
|
644
|
+
if (!els.readerView) return;
|
|
645
|
+
els.readerView.hidden = true;
|
|
646
|
+
const record = activeTerminalRecord();
|
|
647
|
+
if (record && record.term) record.term.focus();
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function syncPaneMods() {
|
|
651
|
+
if (!els.keybar) return;
|
|
652
|
+
els.keybar.querySelectorAll('.pane-key.toggle[data-mod]').forEach((button) => {
|
|
653
|
+
const active = Boolean(paneMods[button.dataset.mod]);
|
|
654
|
+
button.classList.toggle('active', active);
|
|
655
|
+
button.setAttribute('aria-pressed', active ? 'true' : 'false');
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function clearPaneMods() {
|
|
660
|
+
paneMods.ctrl = false;
|
|
661
|
+
paneMods.alt = false;
|
|
662
|
+
syncPaneMods();
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function emitPaneSequence(sequence) {
|
|
666
|
+
const record = activeTerminalRecord();
|
|
667
|
+
if (!record) return;
|
|
668
|
+
sendTerminalInput(record, sequence);
|
|
669
|
+
clearPaneMods();
|
|
670
|
+
if (record.term) record.term.focus();
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function emitPaneLiteral(character) {
|
|
674
|
+
const record = activeTerminalRecord();
|
|
675
|
+
if (!record) return;
|
|
676
|
+
let output = character;
|
|
677
|
+
if (paneMods.ctrl && output.length === 1) output = String.fromCharCode(output.charCodeAt(0) & 0x1f);
|
|
678
|
+
if (paneMods.alt && output.length === 1) output = '\x1b' + output;
|
|
679
|
+
sendTerminalInput(record, output);
|
|
680
|
+
clearPaneMods();
|
|
681
|
+
if (record.term) record.term.focus();
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function makePaneKey(label, options = {}) {
|
|
685
|
+
const button = document.createElement('button');
|
|
686
|
+
button.type = 'button';
|
|
687
|
+
button.className = 'pane-key';
|
|
688
|
+
button.textContent = label;
|
|
689
|
+
if (options.title) button.title = options.title;
|
|
690
|
+
if (options.key) button.dataset.key = options.key;
|
|
691
|
+
if (options.toggle) {
|
|
692
|
+
button.classList.add('toggle');
|
|
693
|
+
button.dataset.mod = options.toggle;
|
|
694
|
+
button.setAttribute('aria-pressed', 'false');
|
|
695
|
+
button.addEventListener('click', () => {
|
|
696
|
+
paneMods[options.toggle] = !paneMods[options.toggle];
|
|
697
|
+
Object.keys(paneMods).forEach((name) => {
|
|
698
|
+
if (name !== options.toggle) paneMods[name] = false;
|
|
699
|
+
});
|
|
700
|
+
syncPaneMods();
|
|
701
|
+
});
|
|
702
|
+
} else if (options.sequence) {
|
|
703
|
+
button.addEventListener('click', () => emitPaneSequence(options.sequence));
|
|
704
|
+
} else if (options.literal) {
|
|
705
|
+
button.addEventListener('click', () => emitPaneLiteral(options.literal));
|
|
706
|
+
}
|
|
707
|
+
return button;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
let keybarKind = '';
|
|
711
|
+
|
|
712
|
+
function makeBrowserKey(label, key, title) {
|
|
713
|
+
const button = makePaneKey(label, { title });
|
|
714
|
+
button.addEventListener('click', () => {
|
|
715
|
+
const record = records.get(effectiveActivePaneId());
|
|
716
|
+
if (record && record.kind === 'browser') void browserAction(record, 'key', { key });
|
|
717
|
+
});
|
|
718
|
+
return button;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function buildPaneKeybar(kind = 'terminal') {
|
|
722
|
+
if (!els.keybar || keybarKind === kind) return;
|
|
723
|
+
keybarKind = kind;
|
|
724
|
+
const keys = kind === 'browser'
|
|
725
|
+
? [
|
|
726
|
+
makeBrowserKey('ENTER', 'Enter', 'Enter'),
|
|
727
|
+
makeBrowserKey('TAB', 'Tab', 'Tab'),
|
|
728
|
+
makeBrowserKey('ESC', 'Escape', 'Escape'),
|
|
729
|
+
makeBrowserKey('←', 'ArrowLeft', 'Left'),
|
|
730
|
+
makeBrowserKey('↑', 'ArrowUp', 'Up'),
|
|
731
|
+
makeBrowserKey('↓', 'ArrowDown', 'Down'),
|
|
732
|
+
makeBrowserKey('→', 'ArrowRight', 'Right'),
|
|
733
|
+
makeBrowserKey('⌫', 'Backspace', 'Backspace')
|
|
734
|
+
]
|
|
735
|
+
: [
|
|
736
|
+
makePaneKey('ESC', { sequence: PANE_SEQ.esc, title: 'Escape' }),
|
|
737
|
+
makePaneKey('TAB', { sequence: PANE_SEQ.tab, title: 'Tab' }),
|
|
738
|
+
makePaneKey('CTRL', { toggle: 'ctrl', title: 'Ctrl (sticky)' }),
|
|
739
|
+
makePaneKey('ALT', { toggle: 'alt', title: 'Alt (sticky)' }),
|
|
740
|
+
makePaneKey('C', { literal: 'c', key: 'c', title: 'C; with CTRL active sends Ctrl+C' }),
|
|
741
|
+
makePaneKey('←', { sequence: PANE_SEQ.left, title: 'Left' }),
|
|
742
|
+
makePaneKey('↑', { sequence: PANE_SEQ.up, title: 'Up' }),
|
|
743
|
+
makePaneKey('↓', { sequence: PANE_SEQ.down, title: 'Down' }),
|
|
744
|
+
makePaneKey('→', { sequence: PANE_SEQ.right, title: 'Right' }),
|
|
745
|
+
makePaneKey('HOME', { sequence: PANE_SEQ.home, title: 'Home' }),
|
|
746
|
+
makePaneKey('END', { sequence: PANE_SEQ.end, title: 'End' }),
|
|
747
|
+
makePaneKey('PGUP', { sequence: PANE_SEQ.pgup, title: 'Page Up' }),
|
|
748
|
+
makePaneKey('PGDN', { sequence: PANE_SEQ.pgdn, title: 'Page Down' })
|
|
749
|
+
];
|
|
750
|
+
els.keybar.replaceChildren(...keys);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
function updateKeybar() {
|
|
754
|
+
if (!els.keybar) return;
|
|
755
|
+
const record = activeTerminalRecord();
|
|
756
|
+
const active = records.get(effectiveActivePaneId());
|
|
757
|
+
if (active && active.kind === 'browser') {
|
|
758
|
+
buildPaneKeybar('browser');
|
|
759
|
+
els.keybar.hidden = false;
|
|
760
|
+
} else if (record) {
|
|
761
|
+
buildPaneKeybar('terminal');
|
|
762
|
+
els.keybar.hidden = false;
|
|
763
|
+
} else {
|
|
764
|
+
els.keybar.hidden = true;
|
|
765
|
+
}
|
|
766
|
+
if (els.menuReader) els.menuReader.disabled = !active;
|
|
767
|
+
if (els.menuFontUp) els.menuFontUp.disabled = !record;
|
|
768
|
+
if (els.menuFontDown) els.menuFontDown.disabled = !record;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function paneCountLabel(count) {
|
|
772
|
+
return `${count} ${count === 1 ? 'pane' : 'panes'}`;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
async function refresh() {
|
|
776
|
+
if (!token) return currentState;
|
|
777
|
+
if (refreshInFlight) {
|
|
778
|
+
try { await refreshInFlight; } catch (_) { /* previous refresh already reported */ }
|
|
779
|
+
}
|
|
780
|
+
const work = (async () => {
|
|
781
|
+
try {
|
|
782
|
+
const next = await api('/state');
|
|
783
|
+
applyState(next);
|
|
784
|
+
return next;
|
|
785
|
+
} catch (error) {
|
|
786
|
+
showNotice(error.message || 'Workspace refresh failed.', 'error');
|
|
787
|
+
return currentState;
|
|
788
|
+
}
|
|
789
|
+
})();
|
|
790
|
+
refreshInFlight = work;
|
|
791
|
+
try {
|
|
792
|
+
return await work;
|
|
793
|
+
} finally {
|
|
794
|
+
if (refreshInFlight === work) refreshInFlight = null;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
function applyState(next, { force = false } = {}) {
|
|
799
|
+
if (!next || !Array.isArray(next.tabs)) return;
|
|
800
|
+
const previousTabId = currentState && currentState.activeTabId;
|
|
801
|
+
currentState = next;
|
|
802
|
+
updateChrome();
|
|
803
|
+
const tab = activeTab();
|
|
804
|
+
const signature = tab
|
|
805
|
+
? `${tab.id}|${tab.panes.map((pane) => `${pane.id}:${pane.kind}`).join(',')}`
|
|
806
|
+
: 'none';
|
|
807
|
+
if (force || signature !== lastSignature) {
|
|
808
|
+
lastSignature = signature;
|
|
809
|
+
rebuild(tab);
|
|
810
|
+
if (!navigator.maxTouchPoints && tab) {
|
|
811
|
+
requestAnimationFrame(() => focusPaneById(effectiveActivePaneId(tab), 'terminal'));
|
|
812
|
+
}
|
|
813
|
+
} else {
|
|
814
|
+
updatePaneChrome(tab);
|
|
815
|
+
}
|
|
816
|
+
// rebuild() returns before updatePaneChrome() when the active tab is empty.
|
|
817
|
+
discardStaleOverlays();
|
|
818
|
+
prunePaneMemory();
|
|
819
|
+
if (els.tabsDialog.open) renderTabsDialog();
|
|
820
|
+
if (tab) document.title = `${tab.title} — Panes`;
|
|
821
|
+
else document.title = 'Panes — Townmouse';
|
|
822
|
+
if (previousTabId && tab && previousTabId !== tab.id) logStatus(`Switched to ${tab.title}.`);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
function updateChrome() {
|
|
826
|
+
const tabs = (currentState && currentState.tabs) || [];
|
|
827
|
+
els.tabCount.textContent = String(tabs.length);
|
|
828
|
+
els.tabsButton.setAttribute('aria-label', tabs.length === 1 ? 'Workspace tabs, 1 tab' : `Workspace tabs, ${tabs.length} tabs`);
|
|
829
|
+
updateHostContext();
|
|
830
|
+
const limits = currentState && currentState.limits;
|
|
831
|
+
if (limits) {
|
|
832
|
+
els.tabsLimits.textContent = `Up to ${limits.maxTabs} tabs, ${limits.maxPanesPerTab} panes per tab.`;
|
|
833
|
+
}
|
|
834
|
+
updateAddLimits();
|
|
835
|
+
renderTabStrip();
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function renderTabStrip() {
|
|
839
|
+
if (!els.tabStrip) return;
|
|
840
|
+
const tabs = (currentState && currentState.tabs) || [];
|
|
841
|
+
els.tabStrip.hidden = tabs.length < 2;
|
|
842
|
+
if (tabs.length < 2) { els.tabStrip.replaceChildren(); return; }
|
|
843
|
+
const list = document.createElement('div');
|
|
844
|
+
list.className = 'tabstrip-tabs';
|
|
845
|
+
list.setAttribute('role', 'tablist');
|
|
846
|
+
list.setAttribute('aria-label', 'Workspace tabs');
|
|
847
|
+
for (const tab of tabs) {
|
|
848
|
+
const active = tab.id === currentState.activeTabId;
|
|
849
|
+
const item = document.createElement('div');
|
|
850
|
+
item.className = 'tabstrip-item' + (active ? ' is-active' : '');
|
|
851
|
+
item.dataset.createdBy = tab.createdBy || 'human';
|
|
852
|
+
const button = document.createElement('button');
|
|
853
|
+
button.type = 'button';
|
|
854
|
+
button.className = 'tabstrip-tab' + (active ? ' is-active' : '') + (tab.createdBy === 'agent' ? ' agent-tab' : '');
|
|
855
|
+
button.textContent = tab.title;
|
|
856
|
+
if (tab.createdBy === 'agent') button.title = `${tab.title} — created by an agent`;
|
|
857
|
+
button.setAttribute('role', 'tab');
|
|
858
|
+
button.setAttribute('aria-selected', active ? 'true' : 'false');
|
|
859
|
+
button.setAttribute('aria-controls', 'pane-grid');
|
|
860
|
+
button.tabIndex = active ? 0 : -1;
|
|
861
|
+
button.addEventListener('click', () => { void activateTab(tab.id); });
|
|
862
|
+
const close = document.createElement('button');
|
|
863
|
+
close.type = 'button';
|
|
864
|
+
close.className = 'tabstrip-close';
|
|
865
|
+
close.textContent = '×';
|
|
866
|
+
close.setAttribute('aria-label', `Close tab ${tab.title}`);
|
|
867
|
+
close.addEventListener('click', (event) => {
|
|
868
|
+
event.stopPropagation();
|
|
869
|
+
requestClose('tab', tab.id, tab.title);
|
|
870
|
+
});
|
|
871
|
+
item.append(button, close);
|
|
872
|
+
list.append(item);
|
|
873
|
+
}
|
|
874
|
+
list.addEventListener('keydown', (event) => {
|
|
875
|
+
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
|
876
|
+
const buttons = [...list.querySelectorAll('[role="tab"]')];
|
|
877
|
+
const index = buttons.indexOf(document.activeElement);
|
|
878
|
+
if (index < 0) return;
|
|
879
|
+
event.preventDefault();
|
|
880
|
+
const next = event.key === 'Home' ? 0
|
|
881
|
+
: event.key === 'End' ? buttons.length - 1
|
|
882
|
+
: (index + (event.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length;
|
|
883
|
+
buttons[next].focus();
|
|
884
|
+
const tab = tabs[next];
|
|
885
|
+
if (tab) void activateTab(tab.id);
|
|
886
|
+
});
|
|
887
|
+
const add = document.createElement('button');
|
|
888
|
+
add.type = 'button';
|
|
889
|
+
add.className = 'tabstrip-add';
|
|
890
|
+
add.textContent = '+ Tab';
|
|
891
|
+
add.setAttribute('aria-label', 'New workspace tab');
|
|
892
|
+
add.addEventListener('click', () => { void newTab(); });
|
|
893
|
+
els.tabStrip.replaceChildren(list, add);
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
const LAYOUT_PREFIX = 'townmouse.pane-layout.';
|
|
897
|
+
|
|
898
|
+
function readPaneLayout(tabId) {
|
|
899
|
+
try {
|
|
900
|
+
const saved = JSON.parse(window.localStorage.getItem(LAYOUT_PREFIX + tabId) || '{}');
|
|
901
|
+
return {
|
|
902
|
+
x: Math.max(0.2, Math.min(0.8, Number(saved.x) || 0.5)),
|
|
903
|
+
y: Math.max(0.2, Math.min(0.8, Number(saved.y) || 0.5))
|
|
904
|
+
};
|
|
905
|
+
} catch (_) {
|
|
906
|
+
return { x: 0.5, y: 0.5 };
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function savePaneLayout(tabId, layout) {
|
|
911
|
+
try {
|
|
912
|
+
window.localStorage.setItem(LAYOUT_PREFIX + tabId, JSON.stringify(layout));
|
|
913
|
+
} catch (_) { /* storage may be disabled */ }
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
function applyPaneLayout(tab) {
|
|
917
|
+
if (!els.grid || !currentState) return;
|
|
918
|
+
const panes = tab ? tab.panes : [];
|
|
919
|
+
els.grid.querySelectorAll('.pane-splitter').forEach((splitter) => splitter.remove());
|
|
920
|
+
els.grid.style.gridTemplateColumns = '';
|
|
921
|
+
els.grid.style.gridTemplateRows = '';
|
|
922
|
+
els.grid.style.gap = '';
|
|
923
|
+
for (const record of records.values()) record.root.style.gridArea = '';
|
|
924
|
+
if (!tab || panes.length < 2 || window.matchMedia('(max-width: 600px)').matches) return;
|
|
925
|
+
|
|
926
|
+
const count = panes.length;
|
|
927
|
+
const layout = readPaneLayout(tab.id);
|
|
928
|
+
const setTemplates = () => {
|
|
929
|
+
els.grid.style.gridTemplateColumns = `calc((100% - 6px) * ${layout.x}) 6px minmax(0, 1fr)`;
|
|
930
|
+
els.grid.style.gridTemplateRows = count === 2
|
|
931
|
+
? 'minmax(0, 1fr)'
|
|
932
|
+
: `calc((100% - 6px) * ${layout.y}) 6px minmax(0, 1fr)`;
|
|
933
|
+
els.grid.style.gap = '0';
|
|
934
|
+
els.grid.querySelectorAll('.pane-splitter').forEach((splitter) => {
|
|
935
|
+
splitter.setAttribute('aria-valuenow', String(Math.round((splitter.classList.contains('vertical') ? layout.x : layout.y) * 100)));
|
|
936
|
+
});
|
|
937
|
+
};
|
|
938
|
+
const areas = count === 2
|
|
939
|
+
? ['1 / 1 / 2 / 2', '1 / 3 / 2 / 4']
|
|
940
|
+
: count === 3
|
|
941
|
+
? ['1 / 1 / 2 / 4', '3 / 1 / 4 / 2', '3 / 3 / 4 / 4']
|
|
942
|
+
: ['1 / 1 / 2 / 2', '1 / 3 / 2 / 4', '3 / 1 / 4 / 2', '3 / 3 / 4 / 4'];
|
|
943
|
+
panes.forEach((pane, index) => {
|
|
944
|
+
const record = records.get(pane.id);
|
|
945
|
+
if (record && areas[index]) record.root.style.gridArea = areas[index];
|
|
946
|
+
});
|
|
947
|
+
|
|
948
|
+
function makeSplitter(orientation, area) {
|
|
949
|
+
const splitter = document.createElement('div');
|
|
950
|
+
splitter.className = `pane-splitter ${orientation}`;
|
|
951
|
+
splitter.style.gridArea = area;
|
|
952
|
+
splitter.tabIndex = 0;
|
|
953
|
+
splitter.setAttribute('role', 'separator');
|
|
954
|
+
splitter.setAttribute('aria-orientation', orientation === 'vertical' ? 'vertical' : 'horizontal');
|
|
955
|
+
splitter.setAttribute('aria-label', orientation === 'vertical' ? 'Resize pane columns' : 'Resize pane rows');
|
|
956
|
+
splitter.setAttribute('aria-valuemin', '20');
|
|
957
|
+
splitter.setAttribute('aria-valuemax', '80');
|
|
958
|
+
splitter.setAttribute('aria-valuenow', String(Math.round((orientation === 'vertical' ? layout.x : layout.y) * 100)));
|
|
959
|
+
const value = () => orientation === 'vertical' ? layout.x : layout.y;
|
|
960
|
+
const apply = (clientX, clientY) => {
|
|
961
|
+
const rect = els.grid.getBoundingClientRect();
|
|
962
|
+
const ratio = orientation === 'vertical'
|
|
963
|
+
? (clientX - rect.left) / rect.width
|
|
964
|
+
: (clientY - rect.top) / rect.height;
|
|
965
|
+
const clamped = Math.max(0.2, Math.min(0.8, ratio));
|
|
966
|
+
if (orientation === 'vertical') layout.x = clamped;
|
|
967
|
+
else layout.y = clamped;
|
|
968
|
+
setTemplates();
|
|
969
|
+
savePaneLayout(tab.id, layout);
|
|
970
|
+
};
|
|
971
|
+
splitter.addEventListener('pointerdown', (event) => {
|
|
972
|
+
event.preventDefault();
|
|
973
|
+
splitter.setPointerCapture?.(event.pointerId);
|
|
974
|
+
splitter.classList.add('dragging');
|
|
975
|
+
const move = (moveEvent) => apply(moveEvent.clientX, moveEvent.clientY);
|
|
976
|
+
const end = () => {
|
|
977
|
+
splitter.classList.remove('dragging');
|
|
978
|
+
splitter.removeEventListener('pointermove', move);
|
|
979
|
+
};
|
|
980
|
+
splitter.addEventListener('pointermove', move);
|
|
981
|
+
splitter.addEventListener('pointerup', end, { once: true });
|
|
982
|
+
splitter.addEventListener('pointercancel', end, { once: true });
|
|
983
|
+
});
|
|
984
|
+
splitter.addEventListener('dblclick', () => {
|
|
985
|
+
layout.x = 0.5;
|
|
986
|
+
layout.y = 0.5;
|
|
987
|
+
setTemplates();
|
|
988
|
+
savePaneLayout(tab.id, layout);
|
|
989
|
+
});
|
|
990
|
+
splitter.addEventListener('keydown', (event) => {
|
|
991
|
+
const step = event.shiftKey ? 0.1 : 0.02;
|
|
992
|
+
let next = value();
|
|
993
|
+
if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') next -= step;
|
|
994
|
+
else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') next += step;
|
|
995
|
+
else if (event.key === 'Home') next = 0.2;
|
|
996
|
+
else if (event.key === 'End') next = 0.8;
|
|
997
|
+
else return;
|
|
998
|
+
event.preventDefault();
|
|
999
|
+
next = Math.max(0.2, Math.min(0.8, next));
|
|
1000
|
+
if (orientation === 'vertical') layout.x = next;
|
|
1001
|
+
else layout.y = next;
|
|
1002
|
+
setTemplates();
|
|
1003
|
+
savePaneLayout(tab.id, layout);
|
|
1004
|
+
});
|
|
1005
|
+
return splitter;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
const splitters = [];
|
|
1009
|
+
if (count === 2) {
|
|
1010
|
+
splitters.push(makeSplitter('vertical', '1 / 2 / 2 / 3'));
|
|
1011
|
+
} else if (count === 3) {
|
|
1012
|
+
splitters.push(makeSplitter('horizontal', '2 / 1 / 3 / 4'));
|
|
1013
|
+
splitters.push(makeSplitter('vertical', '3 / 2 / 4 / 3'));
|
|
1014
|
+
} else {
|
|
1015
|
+
splitters.push(makeSplitter('vertical', '1 / 2 / 2 / 3'));
|
|
1016
|
+
splitters.push(makeSplitter('horizontal', '2 / 1 / 3 / 4'));
|
|
1017
|
+
splitters.push(makeSplitter('vertical', '3 / 2 / 4 / 3'));
|
|
1018
|
+
}
|
|
1019
|
+
els.grid.append(...splitters);
|
|
1020
|
+
setTemplates();
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function rebuild(tab) {
|
|
1024
|
+
const nextTabId = tab ? tab.id : null;
|
|
1025
|
+
const panes = tab ? tab.panes : [];
|
|
1026
|
+
const nextIds = new Set(panes.map((pane) => pane.id));
|
|
1027
|
+
|
|
1028
|
+
if (nextTabId !== currentTabId) {
|
|
1029
|
+
// A tab switch is the one time terminals are discarded outright; their
|
|
1030
|
+
// cursors and local scrollback survive in the maps below.
|
|
1031
|
+
els.grid.classList.remove('is-maximized');
|
|
1032
|
+
teardownPanes();
|
|
1033
|
+
els.grid.replaceChildren();
|
|
1034
|
+
currentTabId = nextTabId;
|
|
1035
|
+
} else {
|
|
1036
|
+
for (const [id, record] of [...records]) {
|
|
1037
|
+
const pane = panes.find((candidate) => candidate.id === id);
|
|
1038
|
+
if (!pane || pane.kind !== record.kind) {
|
|
1039
|
+
if (record.root.classList.contains('is-maximized')) {
|
|
1040
|
+
els.grid.classList.remove('is-maximized');
|
|
1041
|
+
}
|
|
1042
|
+
disposeRecord(record);
|
|
1043
|
+
records.delete(id);
|
|
1044
|
+
record.root.remove();
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const count = panes.length;
|
|
1050
|
+
els.grid.dataset.count = String(count);
|
|
1051
|
+
if (!tab || count === 0) {
|
|
1052
|
+
els.grid.hidden = true;
|
|
1053
|
+
els.emptyState.hidden = false;
|
|
1054
|
+
updateEmptyState(tab);
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
els.grid.hidden = false;
|
|
1058
|
+
els.emptyState.hidden = true;
|
|
1059
|
+
for (const pane of panes) {
|
|
1060
|
+
const existing = records.get(pane.id);
|
|
1061
|
+
const node = existing
|
|
1062
|
+
? existing.root
|
|
1063
|
+
: (pane.kind === 'browser' ? createBrowserPane(pane) : createTerminalPane(pane));
|
|
1064
|
+
// Appending an existing node only reorders it; its xterm DOM lives on.
|
|
1065
|
+
els.grid.append(node);
|
|
1066
|
+
}
|
|
1067
|
+
updatePaneChrome(tab);
|
|
1068
|
+
applyPaneLayout(tab);
|
|
1069
|
+
syncMaximizeButtons();
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// Maximize/restore is available both from Alt+M and from a visible control in
|
|
1073
|
+
// the pane header, so the feature is discoverable without knowing the shortcut.
|
|
1074
|
+
function togglePaneMaximized(paneId) {
|
|
1075
|
+
const id = paneId || effectiveActivePaneId();
|
|
1076
|
+
const record = records.get(id);
|
|
1077
|
+
if (!record) return;
|
|
1078
|
+
const maximize = !(els.grid.classList.contains('is-maximized') && record.root.classList.contains('is-maximized'));
|
|
1079
|
+
els.grid.classList.toggle('is-maximized', maximize);
|
|
1080
|
+
for (const [candidateId, candidate] of records) {
|
|
1081
|
+
candidate.root.classList.toggle('is-maximized', maximize && candidateId === id);
|
|
1082
|
+
}
|
|
1083
|
+
syncMaximizeButtons();
|
|
1084
|
+
logStatus(maximize ? 'Pane maximized.' : 'Pane restored.');
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
function syncMaximizeButtons() {
|
|
1088
|
+
const gridMaximized = els.grid.classList.contains('is-maximized');
|
|
1089
|
+
for (const record of records.values()) {
|
|
1090
|
+
const button = record.maximizeButton;
|
|
1091
|
+
if (!button) continue;
|
|
1092
|
+
const active = gridMaximized && record.root.classList.contains('is-maximized');
|
|
1093
|
+
button.innerHTML = active ? RESTORE_ICON : MAXIMIZE_ICON;
|
|
1094
|
+
button.setAttribute('aria-label', active ? 'Restore pane' : 'Maximize pane');
|
|
1095
|
+
button.setAttribute('aria-pressed', active ? 'true' : 'false');
|
|
1096
|
+
button.title = active ? 'Restore split view (Alt+M)' : 'Maximize pane (Alt+M)';
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function updateEmptyState(tab) {
|
|
1101
|
+
if (!tab) {
|
|
1102
|
+
els.emptyTitle.textContent = 'No workspace tabs';
|
|
1103
|
+
els.emptyCopy.textContent = 'Create a tab to open terminals and browsers.';
|
|
1104
|
+
} else if (!tab.panes.length) {
|
|
1105
|
+
els.emptyTitle.textContent = 'This tab is empty';
|
|
1106
|
+
els.emptyCopy.textContent = `${tab.title} has no panes yet. Add a terminal or a browser.`;
|
|
1107
|
+
}
|
|
1108
|
+
els.emptyActions.hidden = false;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// Compact age for agent-reported status, so an old report does not read as a
|
|
1112
|
+
// fresh one. Program status and agent status are shown as separate facts.
|
|
1113
|
+
function formatAge(ms) {
|
|
1114
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
1115
|
+
if (seconds < 45) return 'just now';
|
|
1116
|
+
const minutes = Math.round(seconds / 60);
|
|
1117
|
+
if (minutes < 60) return `${minutes}m`;
|
|
1118
|
+
const hours = Math.round(minutes / 60);
|
|
1119
|
+
if (hours < 24) return `${hours}h`;
|
|
1120
|
+
return `${Math.round(hours / 24)}d`;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
function updatePaneChrome(tab) {
|
|
1124
|
+
if (!tab) { updateBackButton(); updateKeybar(); updateHostContext(); return; }
|
|
1125
|
+
const activeId = effectiveActivePaneId(tab);
|
|
1126
|
+
tab.panes.forEach((pane, index) => {
|
|
1127
|
+
const record = records.get(pane.id);
|
|
1128
|
+
if (!record) return;
|
|
1129
|
+
record.root.classList.toggle('is-active', pane.id === activeId);
|
|
1130
|
+
const title = paneTitle(pane, index);
|
|
1131
|
+
if (record.titleEl.textContent !== title) record.titleEl.textContent = title;
|
|
1132
|
+
record.titleEl.title = title;
|
|
1133
|
+
record.closeButton.setAttribute('aria-label', `Close ${pane.kind} pane ${title}`);
|
|
1134
|
+
if (record.kind === 'terminal') {
|
|
1135
|
+
const status = pane.status === 'exited' ? 'exited' : 'running';
|
|
1136
|
+
if (record.root.dataset.status !== status) record.root.dataset.status = status;
|
|
1137
|
+
const agentState = pane.agentState || '';
|
|
1138
|
+
record.root.dataset.agentState = agentState;
|
|
1139
|
+
record.root.dataset.programStatus = status;
|
|
1140
|
+
const ageMs = Number(pane.agentStateAgeMs);
|
|
1141
|
+
const agentText = agentState
|
|
1142
|
+
? `${agentState}${Number.isFinite(ageMs) ? ` · ${formatAge(ageMs)}` : ''}`
|
|
1143
|
+
: '';
|
|
1144
|
+
const kindText = status === 'exited'
|
|
1145
|
+
? (agentText ? `Terminal · exited · ${agentText}` : 'Terminal · exited')
|
|
1146
|
+
: agentText ? `Terminal · ${agentText}` : 'Terminal';
|
|
1147
|
+
if (record.kindEl.textContent !== kindText) record.kindEl.textContent = kindText;
|
|
1148
|
+
const command = pane.command;
|
|
1149
|
+
const commandText = command
|
|
1150
|
+
? ` Last command: ${command.status}${Number.isFinite(command.exitCode) ? ` (exit ${command.exitCode})` : ''}.`
|
|
1151
|
+
: '';
|
|
1152
|
+
record.kindEl.title = (agentState
|
|
1153
|
+
? `Program: ${status}. Agent last reported "${agentState}" ${Number.isFinite(ageMs) ? formatAge(ageMs) : 'recently'} ago.`
|
|
1154
|
+
: `Program: ${status}. The agent has not reported a status.`) + commandText;
|
|
1155
|
+
} else {
|
|
1156
|
+
if (record.kindEl.textContent !== 'Browser') record.kindEl.textContent = 'Browser';
|
|
1157
|
+
if (pane.url && !record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== pane.url) {
|
|
1158
|
+
record.addressInput.value = pane.url;
|
|
1159
|
+
}
|
|
1160
|
+
record.currentUrl = pane.url || record.currentUrl;
|
|
1161
|
+
}
|
|
1162
|
+
});
|
|
1163
|
+
discardStaleOverlays();
|
|
1164
|
+
updateKeybar();
|
|
1165
|
+
updateBackButton();
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
// Overlay ids can outlive their pane when a tab is switched or a pane closes.
|
|
1169
|
+
// Reconcile them with the rebuilt records so a stale menu/control/dialog does
|
|
1170
|
+
// not keep the reserved strip (and its .dialog-open/.menu-open class) latched.
|
|
1171
|
+
function discardStaleOverlays() {
|
|
1172
|
+
if (browserControlRecordId && !records.has(browserControlRecordId)) hideBrowserControl();
|
|
1173
|
+
if (contextRecordId && !records.has(contextRecordId)) hideContextMenu();
|
|
1174
|
+
if (browserContextRecordId && !records.has(browserContextRecordId)) hideContextMenu();
|
|
1175
|
+
if (pageDialogRecordId && !records.has(pageDialogRecordId)) hidePageDialog();
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
function updateActiveClasses() {
|
|
1179
|
+
const tab = activeTab();
|
|
1180
|
+
const activeId = effectiveActivePaneId(tab);
|
|
1181
|
+
for (const [id, record] of records) {
|
|
1182
|
+
record.root.classList.toggle('is-active', id === activeId);
|
|
1183
|
+
}
|
|
1184
|
+
const active = records.get(activeId);
|
|
1185
|
+
if (active && active.kind === 'browser') {
|
|
1186
|
+
requestAnimationFrame(() => {
|
|
1187
|
+
if (!active.disposed) active.resizeBrowser?.();
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
updateKeybar();
|
|
1191
|
+
updateHostContext();
|
|
1192
|
+
updateBackButton();
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function updateHostContext() {
|
|
1196
|
+
if (!els.hostName) return;
|
|
1197
|
+
const tab = activeTab();
|
|
1198
|
+
const host = currentState?.host || 'localhost';
|
|
1199
|
+
const narrow = window.matchMedia('(max-width: 699px)').matches;
|
|
1200
|
+
els.hostName.textContent = narrow && tab ? tab.title : host;
|
|
1201
|
+
if (els.hostPill) els.hostPill.title = narrow ? `Active tab: ${tab ? tab.title : 'none'} · ${host}` : host;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
function updateBackButton() {
|
|
1205
|
+
const record = records.get(effectiveActivePaneId());
|
|
1206
|
+
const enabled = Boolean(record && record.kind === 'browser' && record.canGoBack);
|
|
1207
|
+
els.backButton.disabled = !enabled;
|
|
1208
|
+
els.backButton.setAttribute('aria-label', enabled ? `Back in ${record.titleEl.textContent || 'browser'}` : 'Back');
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
function prunePaneMemory() {
|
|
1212
|
+
if (!currentState) return;
|
|
1213
|
+
const live = new Set();
|
|
1214
|
+
for (const tab of currentState.tabs) for (const pane of tab.panes) live.add(pane.id);
|
|
1215
|
+
for (const id of cursors.keys()) {
|
|
1216
|
+
if (!live.has(id)) { cursors.delete(id); histories.delete(id); }
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
async function setActivePane(paneId) {
|
|
1221
|
+
if (!paneId || !currentState) return;
|
|
1222
|
+
if (currentState.activePaneId === paneId) { updateActiveClasses(); return; }
|
|
1223
|
+
currentState = { ...currentState, activePaneId: paneId };
|
|
1224
|
+
updateActiveClasses();
|
|
1225
|
+
try {
|
|
1226
|
+
const next = await api('/active', { method: 'POST', body: { paneId } });
|
|
1227
|
+
applyState(next);
|
|
1228
|
+
} catch (error) {
|
|
1229
|
+
showNotice(error.message || 'Could not select the pane.', 'error');
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
function onPanePointerDown(event) {
|
|
1234
|
+
if (event.target.closest('button')) return;
|
|
1235
|
+
const paneId = event.currentTarget.dataset.paneId;
|
|
1236
|
+
if (paneId) void setActivePane(paneId);
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
function teardownPanes() {
|
|
1240
|
+
// Switching tabs disposes the terminal view but not the server-side shell.
|
|
1241
|
+
// Let already-queued input (an editor paste, a command plus Enter) finish
|
|
1242
|
+
// instead of silently truncating it when the user changes views.
|
|
1243
|
+
for (const record of records.values()) disposeRecord(record, { keepInput: true });
|
|
1244
|
+
records.clear();
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function disposeRecord(record, { keepInput = false } = {}) {
|
|
1248
|
+
if (!record || record.disposed) return;
|
|
1249
|
+
record.disposed = true;
|
|
1250
|
+
if (record.readTimer) { clearTimeout(record.readTimer); record.readTimer = 0; }
|
|
1251
|
+
if (record.streamController) {
|
|
1252
|
+
try { record.streamController.abort(); } catch (_) { /* already ended */ }
|
|
1253
|
+
record.streamController = null;
|
|
1254
|
+
}
|
|
1255
|
+
const pump = record.kind === 'terminal' ? inputPumpFor(record.id) : null;
|
|
1256
|
+
if (keepInput && pump) {
|
|
1257
|
+
// No timer and no request in flight means nothing would deliver what is
|
|
1258
|
+
// already queued; restart the flush before dropping the view.
|
|
1259
|
+
if (pump.pendingInput && !pump.inputBusy && !pump.inputTimer) {
|
|
1260
|
+
pump.inputTimer = window.setTimeout(() => {
|
|
1261
|
+
pump.inputTimer = 0;
|
|
1262
|
+
void flushTerminalInput(pump);
|
|
1263
|
+
}, 12);
|
|
1264
|
+
}
|
|
1265
|
+
} else if (pump) {
|
|
1266
|
+
pump.inputStopped = true;
|
|
1267
|
+
pump.pendingInput = '';
|
|
1268
|
+
if (pump.inputTimer) { clearTimeout(pump.inputTimer); pump.inputTimer = 0; }
|
|
1269
|
+
inputPumps.delete(record.id);
|
|
1270
|
+
}
|
|
1271
|
+
if (record.snapshotTimer) { clearTimeout(record.snapshotTimer); record.snapshotTimer = 0; }
|
|
1272
|
+
if (record.wheelTimer) { clearTimeout(record.wheelTimer); record.wheelTimer = 0; }
|
|
1273
|
+
if (record.fitFrame) { cancelAnimationFrame(record.fitFrame); record.fitFrame = 0; }
|
|
1274
|
+
if (record.resizeObserver) {
|
|
1275
|
+
try { record.resizeObserver.disconnect(); } catch (_) { /* already detached */ }
|
|
1276
|
+
record.resizeObserver = null;
|
|
1277
|
+
}
|
|
1278
|
+
if (record.resizeTimer) { clearTimeout(record.resizeTimer); record.resizeTimer = 0; }
|
|
1279
|
+
if (record.term) {
|
|
1280
|
+
try { record.term.dispose(); } catch (_) { /* already disposed */ }
|
|
1281
|
+
record.term = null;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
function createTerminalPane(pane) {
|
|
1286
|
+
const root = document.createElement('section');
|
|
1287
|
+
root.className = 'pane pane-terminal';
|
|
1288
|
+
root.dataset.paneId = pane.id;
|
|
1289
|
+
root.dataset.kind = 'terminal';
|
|
1290
|
+
root.dataset.createdBy = pane.createdBy || 'human';
|
|
1291
|
+
root.dataset.status = pane.status === 'exited' ? 'exited' : 'running';
|
|
1292
|
+
root.innerHTML =
|
|
1293
|
+
'<header class="pane-header">' +
|
|
1294
|
+
'<span class="pane-title"></span>' +
|
|
1295
|
+
'<span class="pane-kind">Terminal</span>' +
|
|
1296
|
+
`<button type="button" class="pane-maximize" aria-label="Maximize pane" title="Maximize (Alt+M)">${MAXIMIZE_ICON}</button>` +
|
|
1297
|
+
`<button type="button" class="pane-close" aria-label="Close terminal pane">${CLOSE_ICON}</button>` +
|
|
1298
|
+
'</header>' +
|
|
1299
|
+
'<div class="pane-body"><div class="terminal-host"></div></div>';
|
|
1300
|
+
|
|
1301
|
+
const record = {
|
|
1302
|
+
id: pane.id,
|
|
1303
|
+
kind: 'terminal',
|
|
1304
|
+
root,
|
|
1305
|
+
titleEl: root.querySelector('.pane-title'),
|
|
1306
|
+
kindEl: root.querySelector('.pane-kind'),
|
|
1307
|
+
closeButton: root.querySelector('.pane-close'),
|
|
1308
|
+
host: root.querySelector('.terminal-host'),
|
|
1309
|
+
term: null,
|
|
1310
|
+
fit: null,
|
|
1311
|
+
resizeObserver: null,
|
|
1312
|
+
fitFrame: 0,
|
|
1313
|
+
readTimer: 0,
|
|
1314
|
+
pendingInput: '',
|
|
1315
|
+
inputTimer: 0,
|
|
1316
|
+
inputBusy: false,
|
|
1317
|
+
inputStopped: false,
|
|
1318
|
+
streamController: null,
|
|
1319
|
+
offset: cursors.get(pane.id) || 0,
|
|
1320
|
+
lastResize: '',
|
|
1321
|
+
exited: false,
|
|
1322
|
+
pendingStart: pane.status === 'starting',
|
|
1323
|
+
starting: false,
|
|
1324
|
+
disposed: false
|
|
1325
|
+
};
|
|
1326
|
+
record.titleEl.textContent = pane.title || 'Terminal';
|
|
1327
|
+
record.closeButton.setAttribute('aria-label', `Close terminal pane ${pane.title || 'Terminal'}`);
|
|
1328
|
+
record.maximizeButton = root.querySelector('.pane-maximize');
|
|
1329
|
+
record.maximizeButton.addEventListener('click', () => { togglePaneMaximized(pane.id); });
|
|
1330
|
+
root.addEventListener('pointerdown', onPanePointerDown);
|
|
1331
|
+
root.addEventListener('focusin', () => { void setActivePane(pane.id); });
|
|
1332
|
+
record.closeButton.addEventListener('click', () => { requestClose('pane', pane.id, record.titleEl.textContent); });
|
|
1333
|
+
records.set(pane.id, record);
|
|
1334
|
+
wireDrop(root, pane.id);
|
|
1335
|
+
wirePaneReorder(root, pane.id);
|
|
1336
|
+
wirePaneContext(root, record);
|
|
1337
|
+
requestAnimationFrame(() => {
|
|
1338
|
+
if (!record.disposed && root.isConnected) mountTerminal(record);
|
|
1339
|
+
});
|
|
1340
|
+
return root;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
function mountTerminal(record) {
|
|
1344
|
+
if (record.term || record.disposed || !record.host.isConnected) return;
|
|
1345
|
+
const term = new Terminal({
|
|
1346
|
+
cursorBlink: !reducedMotion.matches,
|
|
1347
|
+
cursorStyle: 'bar',
|
|
1348
|
+
cursorWidth: 2,
|
|
1349
|
+
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',
|
|
1350
|
+
fontSize: 13,
|
|
1351
|
+
lineHeight: 1.15,
|
|
1352
|
+
letterSpacing: 0,
|
|
1353
|
+
scrollback: 5000,
|
|
1354
|
+
convertEol: false,
|
|
1355
|
+
allowTransparency: false,
|
|
1356
|
+
theme: TERMINAL_THEME
|
|
1357
|
+
});
|
|
1358
|
+
const fit = new FitAddon();
|
|
1359
|
+
term.loadAddon(fit);
|
|
1360
|
+
term.loadAddon(new WebLinksAddon());
|
|
1361
|
+
try {
|
|
1362
|
+
term.open(record.host);
|
|
1363
|
+
// OSC 52 clipboard writes: agents and shell tools can copy without a
|
|
1364
|
+
// synthetic keystroke. Reads are deliberately not supported.
|
|
1365
|
+
term.parser.registerOscHandler(52, (data) => {
|
|
1366
|
+
const payload = String(data).split(';')[1] || '';
|
|
1367
|
+
if (payload && payload !== '?') {
|
|
1368
|
+
try {
|
|
1369
|
+
const text = decodeClipboardText(payload);
|
|
1370
|
+
if (text) navigator.clipboard?.writeText(text).catch(() => {});
|
|
1371
|
+
} catch (_) { /* malformed clipboard payload */ }
|
|
1372
|
+
}
|
|
1373
|
+
return true;
|
|
1374
|
+
});
|
|
1375
|
+
} catch (error) {
|
|
1376
|
+
showNotice('The terminal could not be opened.', 'error');
|
|
1377
|
+
try { term.dispose(); } catch (_) { /* nothing to release */ }
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
record.term = term;
|
|
1381
|
+
record.fit = fit;
|
|
1382
|
+
// Terminal copy: Cmd/Ctrl+C with a selection copies; with no selection it
|
|
1383
|
+
// still reaches the PTY as SIGINT, matching terminal expectations.
|
|
1384
|
+
term.attachCustomKeyEventHandler((event) => {
|
|
1385
|
+
const platform = navigator.userAgentData?.platform || navigator.platform || '';
|
|
1386
|
+
const copyChord = /mac|iphone|ipad/i.test(platform)
|
|
1387
|
+
? event.metaKey && !event.ctrlKey
|
|
1388
|
+
: event.ctrlKey && event.shiftKey;
|
|
1389
|
+
// Bare Ctrl+C must always interrupt the foreground process, even when
|
|
1390
|
+
// text is selected. Swallowing it for copy is a terminal cardinal sin.
|
|
1391
|
+
if (!copyChord || event.key.toLowerCase() !== 'c' || !term.hasSelection()) return true;
|
|
1392
|
+
try { navigator.clipboard?.writeText(term.getSelection()); } catch (_) { /* clipboard denied */ }
|
|
1393
|
+
return false;
|
|
1394
|
+
});
|
|
1395
|
+
term.onData((data) => {
|
|
1396
|
+
if (!record.disposed && data) sendTerminalInput(record, data);
|
|
1397
|
+
});
|
|
1398
|
+
term.onResize(({ cols, rows }) => {
|
|
1399
|
+
if (!record.disposed) sendTerminalResize(record, cols, rows);
|
|
1400
|
+
});
|
|
1401
|
+
const history = histories.get(record.id);
|
|
1402
|
+
requestAnimationFrame(() => {
|
|
1403
|
+
if (record.disposed || !record.term) return;
|
|
1404
|
+
// Fit before replaying or spawning: the first prompt and the local history
|
|
1405
|
+
// must be laid out at the pane's real width, not xterm's default grid.
|
|
1406
|
+
safeFit(record);
|
|
1407
|
+
if (history) term.write(history);
|
|
1408
|
+
if (record.pendingStart) {
|
|
1409
|
+
void startPendingTerminal(record);
|
|
1410
|
+
} else {
|
|
1411
|
+
void startTerminalStream(record);
|
|
1412
|
+
sendTerminalResize(record, record.term.cols, record.term.rows);
|
|
1413
|
+
}
|
|
1414
|
+
});
|
|
1415
|
+
const applyFontSize = () => {
|
|
1416
|
+
if (record.disposed || !record.term) return;
|
|
1417
|
+
const width = record.host.getBoundingClientRect().width;
|
|
1418
|
+
const override = paneFontOverride();
|
|
1419
|
+
const size = override || (width >= 560 ? 13 : width >= 430 ? 12 : width >= 320 ? 11 : 10);
|
|
1420
|
+
if (record.term.options.fontSize !== size) {
|
|
1421
|
+
record.term.options.fontSize = size;
|
|
1422
|
+
safeFit(record);
|
|
1423
|
+
}
|
|
1424
|
+
};
|
|
1425
|
+
applyFontSize();
|
|
1426
|
+
record.resizeObserver = new ResizeObserver(() => {
|
|
1427
|
+
if (record.disposed) return;
|
|
1428
|
+
if (record.fitFrame) cancelAnimationFrame(record.fitFrame);
|
|
1429
|
+
record.fitFrame = requestAnimationFrame(() => {
|
|
1430
|
+
record.fitFrame = 0;
|
|
1431
|
+
applyFontSize();
|
|
1432
|
+
safeFit(record);
|
|
1433
|
+
});
|
|
1434
|
+
});
|
|
1435
|
+
record.resizeObserver.observe(record.host);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
async function startPendingTerminal(record) {
|
|
1439
|
+
if (!record || record.disposed || record.starting || !record.term) return;
|
|
1440
|
+
record.starting = true;
|
|
1441
|
+
try {
|
|
1442
|
+
await api(`/panes/${record.id}/start`, {
|
|
1443
|
+
method: 'POST',
|
|
1444
|
+
body: { cols: record.term.cols, rows: record.term.rows }
|
|
1445
|
+
});
|
|
1446
|
+
if (record.disposed) return;
|
|
1447
|
+
record.pendingStart = false;
|
|
1448
|
+
void startTerminalStream(record);
|
|
1449
|
+
} catch (error) {
|
|
1450
|
+
if (!record.disposed) {
|
|
1451
|
+
showNotice(error.message || 'The terminal could not start.', 'error');
|
|
1452
|
+
void startTerminalStream(record);
|
|
1453
|
+
}
|
|
1454
|
+
} finally {
|
|
1455
|
+
record.starting = false;
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
function safeFit(record) {
|
|
1460
|
+
if (record.disposed || !record.fit || !record.term) return;
|
|
1461
|
+
const rect = record.host.getBoundingClientRect();
|
|
1462
|
+
if (rect.width < 24 || rect.height < 24) return;
|
|
1463
|
+
try { record.fit.fit(); } catch (_) { /* layout not ready yet */ }
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
function sendTerminalResize(record, cols, rows) {
|
|
1467
|
+
const next = `${cols}x${rows}`;
|
|
1468
|
+
if (record.lastResize === next) return;
|
|
1469
|
+
record.lastResize = next;
|
|
1470
|
+
api(`/panes/${record.id}/resize`, { method: 'POST', body: { cols, rows } }).catch(() => {
|
|
1471
|
+
record.lastResize = '';
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
function sendTerminalInput(record, data) {
|
|
1476
|
+
const pump = inputPumpFor(record.id);
|
|
1477
|
+
if (pump.inputStopped || !data) return;
|
|
1478
|
+
// Coalesce fast typing and pastes into one ordered request instead of one
|
|
1479
|
+
// HTTP round-trip per keystroke. This is the difference between smooth and
|
|
1480
|
+
// jittery input when the agent or a build is also producing output.
|
|
1481
|
+
pump.pendingInput += data;
|
|
1482
|
+
if (pump.inputTimer || pump.inputBusy) return;
|
|
1483
|
+
pump.inputTimer = window.setTimeout(() => {
|
|
1484
|
+
pump.inputTimer = 0;
|
|
1485
|
+
void flushTerminalInput(pump);
|
|
1486
|
+
}, 12);
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
async function flushTerminalInput(pump) {
|
|
1490
|
+
if (pump.inputStopped || pump.inputBusy || !pump.pendingInput) return;
|
|
1491
|
+
const payload = pump.pendingInput;
|
|
1492
|
+
pump.pendingInput = '';
|
|
1493
|
+
pump.inputBusy = true;
|
|
1494
|
+
try {
|
|
1495
|
+
// Keep each request below the global JSON body limit so large pastes work.
|
|
1496
|
+
for (const chunk of chunkInput(payload)) {
|
|
1497
|
+
if (pump.inputStopped) break;
|
|
1498
|
+
await api(`/panes/${pump.paneId}/input`, { method: 'POST', body: { data: chunk } });
|
|
1499
|
+
}
|
|
1500
|
+
} catch (error) {
|
|
1501
|
+
if (!pump.inputStopped) logStatus('Terminal input could not be sent.');
|
|
1502
|
+
} finally {
|
|
1503
|
+
pump.inputBusy = false;
|
|
1504
|
+
if (!pump.inputStopped && pump.pendingInput) {
|
|
1505
|
+
pump.inputTimer = window.setTimeout(() => {
|
|
1506
|
+
pump.inputTimer = 0;
|
|
1507
|
+
void flushTerminalInput(pump);
|
|
1508
|
+
}, 12);
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
async function startTerminalStream(record) {
|
|
1514
|
+
if (record.disposed || !record.term) return;
|
|
1515
|
+
if (record.streamController) {
|
|
1516
|
+
try { record.streamController.abort(); } catch (_) { /* already ended */ }
|
|
1517
|
+
}
|
|
1518
|
+
const controller = new AbortController();
|
|
1519
|
+
record.streamController = controller;
|
|
1520
|
+
try {
|
|
1521
|
+
const response = await fetch(`/api/panes/panes/${record.id}/stream?since=${record.offset || 0}`, {
|
|
1522
|
+
headers: { 'X-Townmouse-Token': token },
|
|
1523
|
+
signal: controller.signal,
|
|
1524
|
+
cache: 'no-store'
|
|
1525
|
+
});
|
|
1526
|
+
if (!response.ok || !response.body) throw new Error(`Output stream failed (${response.status}).`);
|
|
1527
|
+
const reader = response.body.getReader();
|
|
1528
|
+
const decoder = new TextDecoder();
|
|
1529
|
+
let buffer = '';
|
|
1530
|
+
while (!record.disposed) {
|
|
1531
|
+
const { value, done } = await reader.read();
|
|
1532
|
+
if (done) break;
|
|
1533
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1534
|
+
let boundary;
|
|
1535
|
+
while ((boundary = buffer.indexOf('\n\n')) >= 0) {
|
|
1536
|
+
const event = buffer.slice(0, boundary);
|
|
1537
|
+
buffer = buffer.slice(boundary + 2);
|
|
1538
|
+
const line = event.split('\n').find((entry) => entry.startsWith('data: '));
|
|
1539
|
+
if (!line) continue;
|
|
1540
|
+
let payload = null;
|
|
1541
|
+
try { payload = JSON.parse(line.slice(6)); } catch (_) { continue; }
|
|
1542
|
+
if (!record.term || record.disposed) continue;
|
|
1543
|
+
if (payload.data) {
|
|
1544
|
+
record.term.write(payload.data);
|
|
1545
|
+
rememberOutput(record.id, payload.data);
|
|
1546
|
+
}
|
|
1547
|
+
if (Number.isFinite(Number(payload.offset))) {
|
|
1548
|
+
record.offset = Number(payload.offset);
|
|
1549
|
+
cursors.set(record.id, record.offset);
|
|
1550
|
+
}
|
|
1551
|
+
if (payload.exited && !record.exited) markTerminalExited(record);
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
} catch (error) {
|
|
1555
|
+
if (record.disposed || controller.signal.aborted) return;
|
|
1556
|
+
}
|
|
1557
|
+
// A dropped stream is not a dead terminal: fall back to polling.
|
|
1558
|
+
if (!record.disposed) startTerminalRead(record);
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
function startTerminalRead(record) {
|
|
1562
|
+
if (record.readTimer) { clearTimeout(record.readTimer); record.readTimer = 0; }
|
|
1563
|
+
const poll = async () => {
|
|
1564
|
+
if (record.disposed) return;
|
|
1565
|
+
try {
|
|
1566
|
+
const payload = await api(`/panes/${record.id}/read?since=${record.offset || 0}`);
|
|
1567
|
+
if (record.disposed || !record.term) return;
|
|
1568
|
+
if (payload && payload.data) {
|
|
1569
|
+
record.term.write(payload.data);
|
|
1570
|
+
rememberOutput(record.id, payload.data);
|
|
1571
|
+
}
|
|
1572
|
+
const nextOffset = Number(payload && payload.offset);
|
|
1573
|
+
if (Number.isFinite(nextOffset)) {
|
|
1574
|
+
record.offset = nextOffset;
|
|
1575
|
+
cursors.set(record.id, nextOffset);
|
|
1576
|
+
}
|
|
1577
|
+
if (payload && payload.exited && !record.exited) markTerminalExited(record);
|
|
1578
|
+
} catch (error) {
|
|
1579
|
+
// A missed read is retried; the workspace poll reports connection loss.
|
|
1580
|
+
} finally {
|
|
1581
|
+
if (!record.disposed && !record.exited) {
|
|
1582
|
+
record.readTimer = window.setTimeout(poll, READ_POLL_MS);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
};
|
|
1586
|
+
poll();
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
function markTerminalExited(record) {
|
|
1590
|
+
if (record.exited) return;
|
|
1591
|
+
record.exited = true;
|
|
1592
|
+
record.root.dataset.status = 'exited';
|
|
1593
|
+
record.kindEl.textContent = 'Terminal · exited';
|
|
1594
|
+
const marker = '\r\n\x1b[38;5;244m[process exited]\x1b[0m\r\n';
|
|
1595
|
+
if (record.term) record.term.write(marker);
|
|
1596
|
+
rememberOutput(record.id, '\r\n[process exited]\r\n');
|
|
1597
|
+
logStatus(`${record.titleEl.textContent} exited.`);
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
function rememberOutput(paneId, data) {
|
|
1601
|
+
const value = (histories.get(paneId) || '') + data;
|
|
1602
|
+
histories.set(paneId, value.length > MAX_HISTORY ? value.slice(-MAX_HISTORY) : value);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
function createBrowserPane(pane) {
|
|
1606
|
+
const root = document.createElement('section');
|
|
1607
|
+
root.className = 'pane pane-browser';
|
|
1608
|
+
root.dataset.paneId = pane.id;
|
|
1609
|
+
root.dataset.kind = 'browser';
|
|
1610
|
+
root.dataset.createdBy = pane.createdBy || 'human';
|
|
1611
|
+
root.innerHTML =
|
|
1612
|
+
'<header class="pane-header">' +
|
|
1613
|
+
'<span class="pane-title"></span>' +
|
|
1614
|
+
'<span class="pane-kind">Browser</span>' +
|
|
1615
|
+
`<button type="button" class="pane-maximize" aria-label="Maximize pane" title="Maximize (Alt+M)">${MAXIMIZE_ICON}</button>` +
|
|
1616
|
+
`<button type="button" class="pane-close" aria-label="Close browser pane">${CLOSE_ICON}</button>` +
|
|
1617
|
+
'</header>' +
|
|
1618
|
+
'<div class="pane-body">' +
|
|
1619
|
+
'<div class="browser-toolbar">' +
|
|
1620
|
+
`<button type="button" class="browser-icon-button browser-back" aria-label="Back">${BACK_ICON}</button>` +
|
|
1621
|
+
'<button type="button" class="browser-icon-button browser-forward" aria-label="Forward"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg></button>' +
|
|
1622
|
+
`<button type="button" class="browser-icon-button browser-reload" aria-label="Reload">${RELOAD_ICON}</button>` +
|
|
1623
|
+
`<button type="button" class="browser-icon-button browser-size" aria-label="Lock browser size" aria-pressed="false" title="Fixed size: keep the page from resizing with your viewer">${LOCK_ICON}</button>` +
|
|
1624
|
+
'<form class="address-form" novalidate>' +
|
|
1625
|
+
'<input class="address-input" type="text" inputmode="url" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Enter an address" aria-label="Address">' +
|
|
1626
|
+
'<button type="submit" class="address-go">Go</button>' +
|
|
1627
|
+
'</form>' +
|
|
1628
|
+
'</div>' +
|
|
1629
|
+
'<div class="browser-view">' +
|
|
1630
|
+
'<img class="browser-image" alt="" draggable="false" tabindex="0">' +
|
|
1631
|
+
'<button type="button" class="pane-reopen" hidden>Reopen browser</button>' +
|
|
1632
|
+
'</div>' +
|
|
1633
|
+
'<form class="browser-type-row" novalidate>' +
|
|
1634
|
+
'<input class="browser-type-input" type="text" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Type into the page" aria-label="Type into the page">' +
|
|
1635
|
+
'<button type="submit" class="address-go">Send</button>' +
|
|
1636
|
+
'</form>' +
|
|
1637
|
+
'</div>';
|
|
1638
|
+
|
|
1639
|
+
const record = {
|
|
1640
|
+
id: pane.id,
|
|
1641
|
+
kind: 'browser',
|
|
1642
|
+
root,
|
|
1643
|
+
titleEl: root.querySelector('.pane-title'),
|
|
1644
|
+
kindEl: root.querySelector('.pane-kind'),
|
|
1645
|
+
closeButton: root.querySelector('.pane-close'),
|
|
1646
|
+
addressForm: root.querySelector('.address-form'),
|
|
1647
|
+
addressInput: root.querySelector('.address-input'),
|
|
1648
|
+
typeForm: root.querySelector('.browser-type-row'),
|
|
1649
|
+
typeInput: root.querySelector('.browser-type-input'),
|
|
1650
|
+
view: root.querySelector('.browser-view'),
|
|
1651
|
+
image: root.querySelector('.browser-image'),
|
|
1652
|
+
reopenButton: root.querySelector('.pane-reopen'),
|
|
1653
|
+
backButton: root.querySelector('.browser-back'),
|
|
1654
|
+
forwardButton: root.querySelector('.browser-forward'),
|
|
1655
|
+
reloadButton: root.querySelector('.browser-reload'),
|
|
1656
|
+
sizeButton: root.querySelector('.browser-size'),
|
|
1657
|
+
sizing: pane.sizing === 'fixed' ? 'fixed' : 'fit',
|
|
1658
|
+
width: 1280,
|
|
1659
|
+
height: 800,
|
|
1660
|
+
currentUrl: pane.url || '',
|
|
1661
|
+
addressDirty: false,
|
|
1662
|
+
lastImage: '',
|
|
1663
|
+
snapshotBusy: false,
|
|
1664
|
+
snapshotWanted: false,
|
|
1665
|
+
snapshotTimer: 0,
|
|
1666
|
+
wheelDelta: 0,
|
|
1667
|
+
wheelDeltaX: 0,
|
|
1668
|
+
wheelTimer: 0,
|
|
1669
|
+
lastDialogAt: '',
|
|
1670
|
+
resizeObserver: null,
|
|
1671
|
+
resizeTimer: 0,
|
|
1672
|
+
lastViewport: '',
|
|
1673
|
+
canGoBack: false,
|
|
1674
|
+
canGoForward: false,
|
|
1675
|
+
disposed: false
|
|
1676
|
+
};
|
|
1677
|
+
record.titleEl.textContent = pane.title || 'Browser';
|
|
1678
|
+
record.closeButton.setAttribute('aria-label', `Close browser pane ${pane.title || 'Browser'}`);
|
|
1679
|
+
record.maximizeButton = root.querySelector('.pane-maximize');
|
|
1680
|
+
record.maximizeButton.addEventListener('click', () => { togglePaneMaximized(pane.id); });
|
|
1681
|
+
record.addressInput.value = pane.url && pane.url !== 'about:blank' ? pane.url : '';
|
|
1682
|
+
record.backButton.disabled = true;
|
|
1683
|
+
record.forwardButton.disabled = true;
|
|
1684
|
+
|
|
1685
|
+
root.addEventListener('pointerdown', onPanePointerDown);
|
|
1686
|
+
root.addEventListener('focusin', () => { void setActivePane(pane.id); });
|
|
1687
|
+
record.closeButton.addEventListener('click', () => { requestClose('pane', pane.id, record.titleEl.textContent); });
|
|
1688
|
+
record.backButton.addEventListener('click', () => { void browserAction(record, 'back'); });
|
|
1689
|
+
record.forwardButton.addEventListener('click', () => { void browserAction(record, 'forward'); });
|
|
1690
|
+
record.reloadButton.addEventListener('click', () => { void browserAction(record, 'reload'); });
|
|
1691
|
+
record.sizeButton.addEventListener('click', () => { void toggleBrowserSizing(record); });
|
|
1692
|
+
record.addressForm.addEventListener('submit', (event) => {
|
|
1693
|
+
event.preventDefault();
|
|
1694
|
+
void navigateBrowser(record);
|
|
1695
|
+
});
|
|
1696
|
+
record.addressInput.addEventListener('input', () => { record.addressDirty = true; });
|
|
1697
|
+
record.addressInput.addEventListener('blur', () => {
|
|
1698
|
+
window.setTimeout(() => {
|
|
1699
|
+
if (record.disposed || !record.addressDirty || document.activeElement === record.addressInput) return;
|
|
1700
|
+
record.addressDirty = false;
|
|
1701
|
+
record.addressInput.value = record.currentUrl || '';
|
|
1702
|
+
}, 250);
|
|
1703
|
+
});
|
|
1704
|
+
record.typeForm.addEventListener('submit', (event) => {
|
|
1705
|
+
event.preventDefault();
|
|
1706
|
+
submitBrowserType(record);
|
|
1707
|
+
});
|
|
1708
|
+
record.image.addEventListener('click', (event) => {
|
|
1709
|
+
record.image.focus({ preventScroll: true });
|
|
1710
|
+
void onBrowserImageClick(record, event);
|
|
1711
|
+
});
|
|
1712
|
+
record.reopenButton.addEventListener('click', async () => {
|
|
1713
|
+
try {
|
|
1714
|
+
await api(`/panes/${record.id}/browser/reopen`, { method: 'POST' });
|
|
1715
|
+
record.lastViewport = '';
|
|
1716
|
+
record.reopenButton.hidden = true;
|
|
1717
|
+
record.root.classList.remove('is-offline');
|
|
1718
|
+
requestSnapshot(record, 120);
|
|
1719
|
+
} catch (error) {
|
|
1720
|
+
showNotice(error.message || 'Could not reopen the browser.', 'error');
|
|
1721
|
+
}
|
|
1722
|
+
});
|
|
1723
|
+
record.image.addEventListener('keydown', (event) => {
|
|
1724
|
+
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
|
1725
|
+
if (event.key.length === 1) {
|
|
1726
|
+
event.preventDefault();
|
|
1727
|
+
void browserAction(record, 'type', { text: event.key });
|
|
1728
|
+
return;
|
|
1729
|
+
}
|
|
1730
|
+
const named = ['Enter', 'Backspace', 'Escape', 'Tab', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown'];
|
|
1731
|
+
if (!named.includes(event.key)) return;
|
|
1732
|
+
event.preventDefault();
|
|
1733
|
+
void browserAction(record, 'key', { key: event.key });
|
|
1734
|
+
});
|
|
1735
|
+
record.view.addEventListener('wheel', (event) => onBrowserWheel(record, event), { passive: false });
|
|
1736
|
+
let touchY = 0;
|
|
1737
|
+
let touchX = 0;
|
|
1738
|
+
let touchActive = false;
|
|
1739
|
+
record.view.addEventListener('touchstart', (event) => {
|
|
1740
|
+
if (event.touches.length !== 1) return;
|
|
1741
|
+
touchActive = true;
|
|
1742
|
+
touchY = event.touches[0].clientY;
|
|
1743
|
+
touchX = event.touches[0].clientX;
|
|
1744
|
+
}, { passive: true });
|
|
1745
|
+
record.view.addEventListener('touchmove', (event) => {
|
|
1746
|
+
if (!touchActive || event.touches.length !== 1) return;
|
|
1747
|
+
event.preventDefault();
|
|
1748
|
+
const nextY = event.touches[0].clientY;
|
|
1749
|
+
const nextX = event.touches[0].clientX;
|
|
1750
|
+
const deltaY = touchY - nextY;
|
|
1751
|
+
const deltaX = touchX - nextX;
|
|
1752
|
+
touchY = nextY;
|
|
1753
|
+
touchX = nextX;
|
|
1754
|
+
if (deltaY || deltaX) queueBrowserScroll(record, deltaY, deltaX);
|
|
1755
|
+
}, { passive: false });
|
|
1756
|
+
record.view.addEventListener('touchend', () => { touchActive = false; }, { passive: true });
|
|
1757
|
+
|
|
1758
|
+
records.set(pane.id, record);
|
|
1759
|
+
wireDrop(root, pane.id);
|
|
1760
|
+
wirePaneReorder(root, pane.id);
|
|
1761
|
+
wireBrowserContext(record);
|
|
1762
|
+
const resizeBrowser = () => {
|
|
1763
|
+
if (record.disposed || !record.root.isConnected) return;
|
|
1764
|
+
// Fixed-size mode: the human's viewer never rearranges the page. The image
|
|
1765
|
+
// is scaled with object-fit instead.
|
|
1766
|
+
if (record.sizing === 'fixed') return;
|
|
1767
|
+
const rect = record.view.getBoundingClientRect();
|
|
1768
|
+
const width = Math.round(rect.width);
|
|
1769
|
+
const height = Math.round(rect.height);
|
|
1770
|
+
if (width < 50 || height < 50) return;
|
|
1771
|
+
const key = `${width}x${height}`;
|
|
1772
|
+
if (record.lastViewport === key) return;
|
|
1773
|
+
record.lastViewport = key;
|
|
1774
|
+
api(`/panes/${record.id}/resize`, { method: 'POST', body: { width, height } })
|
|
1775
|
+
.then((size) => {
|
|
1776
|
+
if (record.disposed) return;
|
|
1777
|
+
if (size && Number.isFinite(size.width)) record.width = size.width;
|
|
1778
|
+
if (size && Number.isFinite(size.height)) record.height = size.height;
|
|
1779
|
+
requestSnapshot(record, 120);
|
|
1780
|
+
})
|
|
1781
|
+
.catch(() => { record.lastViewport = ''; });
|
|
1782
|
+
};
|
|
1783
|
+
record.resizeObserver = new ResizeObserver(() => {
|
|
1784
|
+
if (record.disposed) return;
|
|
1785
|
+
if (record.resizeTimer) clearTimeout(record.resizeTimer);
|
|
1786
|
+
record.resizeTimer = window.setTimeout(() => {
|
|
1787
|
+
record.resizeTimer = 0;
|
|
1788
|
+
resizeBrowser();
|
|
1789
|
+
}, 180);
|
|
1790
|
+
});
|
|
1791
|
+
record.resizeBrowser = resizeBrowser;
|
|
1792
|
+
record.resizeObserver.observe(record.view);
|
|
1793
|
+
requestAnimationFrame(() => {
|
|
1794
|
+
if (!record.disposed && root.isConnected) {
|
|
1795
|
+
resizeBrowser();
|
|
1796
|
+
requestSnapshot(record, 0);
|
|
1797
|
+
}
|
|
1798
|
+
});
|
|
1799
|
+
return root;
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
function updateBrowserSizingChrome(record) {
|
|
1803
|
+
if (!record.sizeButton) return;
|
|
1804
|
+
const fixed = record.sizing === 'fixed';
|
|
1805
|
+
record.sizeButton.setAttribute('aria-pressed', fixed ? 'true' : 'false');
|
|
1806
|
+
record.sizeButton.setAttribute('aria-label', fixed ? 'Unlock browser size' : 'Lock browser size');
|
|
1807
|
+
record.sizeButton.title = fixed
|
|
1808
|
+
? `Fixed at ${record.width}×${record.height} — your viewer scales the picture, not the page. Click to fit the pane again.`
|
|
1809
|
+
: 'Fixed size: keep the page from resizing when you open menus, resize the viewer, or switch tabs.';
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
async function toggleBrowserSizing(record) {
|
|
1813
|
+
if (record.disposed) return;
|
|
1814
|
+
const next = record.sizing === 'fixed' ? 'fit' : 'fixed';
|
|
1815
|
+
try {
|
|
1816
|
+
const size = await api(`/panes/${record.id}/browser/sizing`, {
|
|
1817
|
+
method: 'POST',
|
|
1818
|
+
body: { mode: next, width: record.width, height: record.height }
|
|
1819
|
+
});
|
|
1820
|
+
if (record.disposed) return;
|
|
1821
|
+
record.sizing = size && size.sizing === 'fixed' ? 'fixed' : 'fit';
|
|
1822
|
+
if (size && Number.isFinite(size.width)) record.width = size.width;
|
|
1823
|
+
if (size && Number.isFinite(size.height)) record.height = size.height;
|
|
1824
|
+
updateBrowserSizingChrome(record);
|
|
1825
|
+
if (record.sizing === 'fit') {
|
|
1826
|
+
record.lastViewport = '';
|
|
1827
|
+
record.resizeBrowser?.();
|
|
1828
|
+
}
|
|
1829
|
+
requestSnapshot(record, 100);
|
|
1830
|
+
showNotice(
|
|
1831
|
+
record.sizing === 'fixed'
|
|
1832
|
+
? `Browser size locked at ${record.width}×${record.height}.`
|
|
1833
|
+
: 'Browser fits the pane again.',
|
|
1834
|
+
'info'
|
|
1835
|
+
);
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
if (!record.disposed) showNotice(error.message || 'Could not change browser sizing.', 'error');
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
function requestSnapshot(record, delay = 0) {
|
|
1842
|
+
if (record.disposed) return;
|
|
1843
|
+
if (record.snapshotBusy) {
|
|
1844
|
+
record.snapshotWanted = true;
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
if (record.snapshotTimer) clearTimeout(record.snapshotTimer);
|
|
1848
|
+
record.snapshotTimer = window.setTimeout(() => {
|
|
1849
|
+
record.snapshotTimer = 0;
|
|
1850
|
+
void pollSnapshot(record);
|
|
1851
|
+
}, Math.max(0, delay));
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
async function pollSnapshot(record) {
|
|
1855
|
+
if (record.disposed || !record.root.isConnected) return;
|
|
1856
|
+
if (record.snapshotBusy) {
|
|
1857
|
+
record.snapshotWanted = true;
|
|
1858
|
+
return;
|
|
1859
|
+
}
|
|
1860
|
+
record.snapshotBusy = true;
|
|
1861
|
+
record.snapshotWanted = false;
|
|
1862
|
+
try {
|
|
1863
|
+
const snapshot = await api(`/panes/${record.id}/browser/snapshot`);
|
|
1864
|
+
if (record.disposed) return;
|
|
1865
|
+
applySnapshot(record, snapshot);
|
|
1866
|
+
} catch (error) {
|
|
1867
|
+
if (!record.disposed) {
|
|
1868
|
+
record.root.classList.add('is-offline');
|
|
1869
|
+
record.reopenButton.hidden = false;
|
|
1870
|
+
}
|
|
1871
|
+
} finally {
|
|
1872
|
+
record.snapshotBusy = false;
|
|
1873
|
+
if (!record.disposed) requestSnapshot(record, record.snapshotWanted ? 120 : SNAPSHOT_POLL_MS);
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
function applySnapshot(record, snapshot) {
|
|
1878
|
+
if (!snapshot) return;
|
|
1879
|
+
const width = Number(snapshot.width);
|
|
1880
|
+
const height = Number(snapshot.height);
|
|
1881
|
+
if (Number.isFinite(width) && width > 0) record.width = width;
|
|
1882
|
+
if (Number.isFinite(height) && height > 0) record.height = height;
|
|
1883
|
+
if (snapshot.url) {
|
|
1884
|
+
record.currentUrl = snapshot.url;
|
|
1885
|
+
if (!record.addressDirty && document.activeElement !== record.addressInput && record.addressInput.value !== snapshot.url) {
|
|
1886
|
+
record.addressInput.value = snapshot.url;
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
if (snapshot.title) {
|
|
1890
|
+
record.titleEl.textContent = snapshot.title;
|
|
1891
|
+
record.titleEl.title = snapshot.title;
|
|
1892
|
+
record.closeButton.setAttribute('aria-label', `Close browser pane ${snapshot.title}`);
|
|
1893
|
+
}
|
|
1894
|
+
if (snapshot.image && snapshot.image !== record.lastImage) {
|
|
1895
|
+
record.lastImage = snapshot.image;
|
|
1896
|
+
record.image.src = `data:image/jpeg;base64,${snapshot.image}`;
|
|
1897
|
+
record.image.alt = snapshot.title ? `Snapshot of ${snapshot.title}` : 'Browser page snapshot';
|
|
1898
|
+
}
|
|
1899
|
+
if (snapshot.sizing) record.sizing = snapshot.sizing === 'fixed' ? 'fixed' : 'fit';
|
|
1900
|
+
updateBrowserSizingChrome(record);
|
|
1901
|
+
if (typeof snapshot.canGoBack === 'boolean') {
|
|
1902
|
+
record.canGoBack = snapshot.canGoBack;
|
|
1903
|
+
record.backButton.disabled = !snapshot.canGoBack;
|
|
1904
|
+
}
|
|
1905
|
+
if (typeof snapshot.canGoForward === 'boolean') {
|
|
1906
|
+
record.canGoForward = snapshot.canGoForward;
|
|
1907
|
+
record.forwardButton.disabled = !snapshot.canGoForward;
|
|
1908
|
+
}
|
|
1909
|
+
if (snapshot.dialog && snapshot.dialog.id) {
|
|
1910
|
+
showPageDialog(record, snapshot.dialog);
|
|
1911
|
+
} else if (pageDialogRecordId === record.id) {
|
|
1912
|
+
hidePageDialog();
|
|
1913
|
+
}
|
|
1914
|
+
record.root.classList.remove('is-offline');
|
|
1915
|
+
record.reopenButton.hidden = true;
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
async function onBrowserImageClick(record, event) {
|
|
1919
|
+
if (event.button !== undefined && event.button !== 0) return;
|
|
1920
|
+
if (record.suppressClickUntil && Date.now() < record.suppressClickUntil) return;
|
|
1921
|
+
const rect = record.image.getBoundingClientRect();
|
|
1922
|
+
if (rect.width <= 0 || rect.height <= 0) return;
|
|
1923
|
+
const width = record.width || record.image.naturalWidth;
|
|
1924
|
+
const height = record.height || record.image.naturalHeight;
|
|
1925
|
+
if (!width || !height) return;
|
|
1926
|
+
const scale = Math.min(rect.width / width, rect.height / height);
|
|
1927
|
+
if (!Number.isFinite(scale) || scale <= 0) return;
|
|
1928
|
+
const contentWidth = width * scale;
|
|
1929
|
+
const contentHeight = height * scale;
|
|
1930
|
+
const left = rect.left + (rect.width - contentWidth) / 2;
|
|
1931
|
+
const top = rect.top + (rect.height - contentHeight) / 2;
|
|
1932
|
+
const localX = event.clientX - left;
|
|
1933
|
+
const localY = event.clientY - top;
|
|
1934
|
+
if (localX < 0 || localY < 0 || localX > contentWidth || localY > contentHeight) return;
|
|
1935
|
+
const x = Math.max(0, Math.min(width, Math.round(localX / scale)));
|
|
1936
|
+
const y = Math.max(0, Math.min(height, Math.round(localY / scale)));
|
|
1937
|
+
const updated = await browserAction(record, 'click', { x, y });
|
|
1938
|
+
if (updated && updated.control) showBrowserControl(record, updated.control, { x, y });
|
|
1939
|
+
else if (browserControlRecordId === record.id) hideBrowserControl();
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
function queueBrowserScroll(record, deltaY, deltaX = 0) {
|
|
1943
|
+
const dy = Math.max(-1500, Math.min(1500, Number(deltaY) || 0));
|
|
1944
|
+
const dx = Math.max(-1500, Math.min(1500, Number(deltaX) || 0));
|
|
1945
|
+
if (!dy && !dx) return;
|
|
1946
|
+
record.wheelDelta += dy;
|
|
1947
|
+
record.wheelDeltaX = (record.wheelDeltaX || 0) + dx;
|
|
1948
|
+
if (record.wheelTimer) return;
|
|
1949
|
+
record.wheelTimer = window.setTimeout(() => {
|
|
1950
|
+
record.wheelTimer = 0;
|
|
1951
|
+
const totalY = Math.max(-1500, Math.min(1500, record.wheelDelta));
|
|
1952
|
+
const totalX = Math.max(-1500, Math.min(1500, record.wheelDeltaX || 0));
|
|
1953
|
+
record.wheelDelta = 0;
|
|
1954
|
+
record.wheelDeltaX = 0;
|
|
1955
|
+
if ((totalY || totalX) && !record.disposed) {
|
|
1956
|
+
void browserAction(record, 'scroll', { deltaY: totalY, deltaX: totalX, pointer: true });
|
|
1957
|
+
}
|
|
1958
|
+
}, 70);
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
function onBrowserWheel(record, event) {
|
|
1962
|
+
event.preventDefault();
|
|
1963
|
+
queueBrowserScroll(record, event.deltaY, event.deltaX);
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
async function browserAction(record, action, extra = {}) {
|
|
1967
|
+
if (record.disposed) return;
|
|
1968
|
+
try {
|
|
1969
|
+
const updated = await api(`/panes/${record.id}/browser/action`, {
|
|
1970
|
+
method: 'POST',
|
|
1971
|
+
body: { action, ...extra }
|
|
1972
|
+
});
|
|
1973
|
+
if (record.disposed) return;
|
|
1974
|
+
if (updated) {
|
|
1975
|
+
if (updated.url) {
|
|
1976
|
+
record.currentUrl = updated.url;
|
|
1977
|
+
if (!record.addressDirty && document.activeElement !== record.addressInput) record.addressInput.value = updated.url;
|
|
1978
|
+
}
|
|
1979
|
+
if (updated.title) {
|
|
1980
|
+
record.titleEl.textContent = updated.title;
|
|
1981
|
+
record.titleEl.title = updated.title;
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
requestSnapshot(record, 220);
|
|
1985
|
+
return updated;
|
|
1986
|
+
} catch (error) {
|
|
1987
|
+
if (!record.disposed) showNotice(error.message || 'Browser action failed.', 'error');
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
function normalizeAddress(value) {
|
|
1992
|
+
const raw = String(value || '').trim();
|
|
1993
|
+
if (!raw) return '';
|
|
1994
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) return raw;
|
|
1995
|
+
if (/^(about|data|view-source):/i.test(raw)) return raw;
|
|
1996
|
+
if (/^(localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i.test(raw)) return `http://${raw}`;
|
|
1997
|
+
return `https://${raw.replace(/^\/+/, '')}`;
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
async function navigateBrowser(record) {
|
|
2001
|
+
const url = normalizeAddress(record.addressInput.value);
|
|
2002
|
+
if (!url) return;
|
|
2003
|
+
record.addressDirty = false;
|
|
2004
|
+
record.addressInput.value = url;
|
|
2005
|
+
try {
|
|
2006
|
+
const updated = await api(`/panes/${record.id}/url`, { method: 'POST', body: { url } });
|
|
2007
|
+
if (record.disposed) return;
|
|
2008
|
+
if (updated) {
|
|
2009
|
+
record.currentUrl = updated.url || url;
|
|
2010
|
+
if (updated.title) {
|
|
2011
|
+
record.titleEl.textContent = updated.title;
|
|
2012
|
+
record.titleEl.title = updated.title;
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
record.addressInput.blur();
|
|
2016
|
+
requestSnapshot(record, 180);
|
|
2017
|
+
} catch (error) {
|
|
2018
|
+
if (!record.disposed) showNotice(error.message || 'Could not open that address.', 'error');
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
function submitBrowserType(record) {
|
|
2023
|
+
const text = record.typeInput.value;
|
|
2024
|
+
if (!text) return;
|
|
2025
|
+
record.typeInput.value = '';
|
|
2026
|
+
void browserAction(record, 'type', { text });
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
async function addPane(kind) {
|
|
2030
|
+
closeSheets();
|
|
2031
|
+
try {
|
|
2032
|
+
let tabId = currentState && currentState.activeTabId;
|
|
2033
|
+
if (!tabId || !currentState.tabs.some((tab) => tab.id === tabId)) {
|
|
2034
|
+
const created = await api('/tabs', { method: 'POST', body: {} });
|
|
2035
|
+
tabId = created.id;
|
|
2036
|
+
}
|
|
2037
|
+
const body = kind === 'terminal' ? { kind, start: false } : { kind };
|
|
2038
|
+
const pane = await api(`/tabs/${tabId}/panes`, { method: 'POST', body });
|
|
2039
|
+
await refresh();
|
|
2040
|
+
if (pane && pane.id) {
|
|
2041
|
+
window.setTimeout(() => {
|
|
2042
|
+
if (kind === 'browser') focusPaneById(pane.id, 'address');
|
|
2043
|
+
else focusPaneById(pane.id, 'terminal');
|
|
2044
|
+
}, 80);
|
|
2045
|
+
}
|
|
2046
|
+
logStatus(kind === 'browser' ? 'Browser pane added.' : 'Terminal pane added.');
|
|
2047
|
+
} catch (error) {
|
|
2048
|
+
showNotice(error.message || 'Could not add the pane.', 'error');
|
|
2049
|
+
await refresh();
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
async function newTab() {
|
|
2054
|
+
closeSheets();
|
|
2055
|
+
try {
|
|
2056
|
+
await api('/tabs', { method: 'POST', body: {} });
|
|
2057
|
+
await refresh();
|
|
2058
|
+
logStatus('New workspace tab created.');
|
|
2059
|
+
} catch (error) {
|
|
2060
|
+
showNotice(error.message || 'Could not create a tab.', 'error');
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
function requestClose(kind, id, title) {
|
|
2065
|
+
pendingClose = { kind, id, title };
|
|
2066
|
+
els.closeConfirmTitle.textContent = `Close ${title}?`;
|
|
2067
|
+
if (kind === 'tab') {
|
|
2068
|
+
const tab = currentState && currentState.tabs.find((candidate) => candidate.id === id);
|
|
2069
|
+
const count = tab ? tab.panes.length : 0;
|
|
2070
|
+
els.closeConfirmCopy.textContent = count
|
|
2071
|
+
? `Closing this tab ends ${count === 1 ? 'its pane' : `all ${count} panes`} and any running jobs. This cannot be undone.`
|
|
2072
|
+
: 'Closing this tab cannot be undone.';
|
|
2073
|
+
} else {
|
|
2074
|
+
els.closeConfirmCopy.textContent = 'Closing this pane ends its shell and any running job. This cannot be undone.';
|
|
2075
|
+
}
|
|
2076
|
+
els.closeApprove.textContent = kind === 'tab' ? 'Close tab' : 'Close pane';
|
|
2077
|
+
closeSheets();
|
|
2078
|
+
hideContextMenu();
|
|
2079
|
+
els.closeConfirm.show();
|
|
2080
|
+
syncPanelState();
|
|
2081
|
+
els.closeCancel.focus();
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
async function closeTab(tabId, title) {
|
|
2085
|
+
try {
|
|
2086
|
+
const payload = await api(`/tabs/${tabId}`, { method: 'DELETE' });
|
|
2087
|
+
if (payload && payload.state) applyState(payload.state);
|
|
2088
|
+
else await refresh();
|
|
2089
|
+
tabsDialogSignature = '';
|
|
2090
|
+
if (els.tabsDialog.open) renderTabsDialog();
|
|
2091
|
+
logStatus(`Closed tab ${title}.`);
|
|
2092
|
+
} catch (error) {
|
|
2093
|
+
showNotice(error.message || 'Could not close the tab.', 'error');
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
async function closePane(paneId, title) {
|
|
2098
|
+
try {
|
|
2099
|
+
const payload = await api(`/panes/${paneId}`, { method: 'DELETE' });
|
|
2100
|
+
if (payload && payload.state) applyState(payload.state);
|
|
2101
|
+
else await refresh();
|
|
2102
|
+
logStatus(`Closed ${title}.`);
|
|
2103
|
+
} catch (error) {
|
|
2104
|
+
showNotice(error.message || 'Could not close the pane.', 'error');
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
|
|
2108
|
+
async function activateTab(tabId) {
|
|
2109
|
+
try {
|
|
2110
|
+
const tab = currentState && currentState.tabs.find((candidate) => candidate.id === tabId);
|
|
2111
|
+
const body = { tabId };
|
|
2112
|
+
if (tab && tab.panes[0]) body.paneId = tab.panes[0].id;
|
|
2113
|
+
const next = await api('/active', { method: 'POST', body });
|
|
2114
|
+
closeSheets();
|
|
2115
|
+
applyState(next);
|
|
2116
|
+
logStatus(`Switched to ${tab ? tab.title : 'tab'}.`);
|
|
2117
|
+
} catch (error) {
|
|
2118
|
+
showNotice(error.message || 'Could not switch tabs.', 'error');
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
function tabsDialogSignatureValue() {
|
|
2123
|
+
if (!currentState) return '';
|
|
2124
|
+
const tabs = currentState.tabs.map((tab) => {
|
|
2125
|
+
const active = tab.id === currentState.activeTabId ? '1' : '0';
|
|
2126
|
+
return `${tab.id}:${tab.title}:${tab.panes.length}:${active}`;
|
|
2127
|
+
});
|
|
2128
|
+
return `${tabs.join('|')}|${currentState.activePaneId || ''}|${JSON.stringify(currentState.limits || null)}`;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
function renderTabsDialog() {
|
|
2132
|
+
if (!currentState) return;
|
|
2133
|
+
const signature = tabsDialogSignatureValue();
|
|
2134
|
+
if (signature === tabsDialogSignature && els.tabsList.childElementCount) return;
|
|
2135
|
+
tabsDialogSignature = signature;
|
|
2136
|
+
const tabs = currentState.tabs;
|
|
2137
|
+
els.tabsList.replaceChildren();
|
|
2138
|
+
els.tabsEmpty.hidden = tabs.length > 0;
|
|
2139
|
+
const activeId = currentState.activeTabId;
|
|
2140
|
+
const fragment = document.createDocumentFragment();
|
|
2141
|
+
for (const tab of tabs) {
|
|
2142
|
+
const row = document.createElement('li');
|
|
2143
|
+
row.className = `tab-row${tab.id === activeId ? ' is-active' : ''}`;
|
|
2144
|
+
|
|
2145
|
+
const select = document.createElement('button');
|
|
2146
|
+
select.type = 'button';
|
|
2147
|
+
select.className = 'tab-select';
|
|
2148
|
+
select.dataset.tabId = tab.id;
|
|
2149
|
+
select.setAttribute('aria-label', `Switch to ${tab.title}, ${paneCountLabel(tab.panes.length)}`);
|
|
2150
|
+
if (tab.id === activeId) select.setAttribute('aria-current', 'true');
|
|
2151
|
+
const name = document.createElement('span');
|
|
2152
|
+
name.className = 'tab-name';
|
|
2153
|
+
name.textContent = tab.title;
|
|
2154
|
+
select.append(name);
|
|
2155
|
+
if (tab.id === activeId) {
|
|
2156
|
+
const current = document.createElement('span');
|
|
2157
|
+
current.className = 'tab-current';
|
|
2158
|
+
current.textContent = 'Current';
|
|
2159
|
+
select.append(current);
|
|
2160
|
+
}
|
|
2161
|
+
const meta = document.createElement('span');
|
|
2162
|
+
meta.className = 'tab-meta';
|
|
2163
|
+
meta.textContent = paneCountLabel(tab.panes.length);
|
|
2164
|
+
select.append(meta);
|
|
2165
|
+
select.addEventListener('click', () => { void activateTab(tab.id); });
|
|
2166
|
+
|
|
2167
|
+
const close = document.createElement('button');
|
|
2168
|
+
close.type = 'button';
|
|
2169
|
+
close.className = 'tab-close';
|
|
2170
|
+
close.innerHTML = CLOSE_ICON;
|
|
2171
|
+
close.setAttribute('aria-label', `Close tab ${tab.title}`);
|
|
2172
|
+
close.addEventListener('click', () => { requestClose('tab', tab.id, tab.title); });
|
|
2173
|
+
|
|
2174
|
+
row.append(select, close);
|
|
2175
|
+
fragment.append(row);
|
|
2176
|
+
}
|
|
2177
|
+
els.tabsList.append(fragment);
|
|
2178
|
+
updateAddLimits();
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
function updateAddLimits() {
|
|
2182
|
+
if (!currentState) return;
|
|
2183
|
+
const tab = activeTab();
|
|
2184
|
+
const limits = currentState.limits || {};
|
|
2185
|
+
const maxPanes = limits.maxPanesPerTab || 4;
|
|
2186
|
+
const maxTabs = limits.maxTabs || 24;
|
|
2187
|
+
const atPaneLimit = Boolean(tab && tab.panes.length >= maxPanes);
|
|
2188
|
+
const atTabLimit = currentState.tabs.length >= maxTabs;
|
|
2189
|
+
els.tabsAddTerminal.disabled = atPaneLimit;
|
|
2190
|
+
els.tabsAddBrowser.disabled = atPaneLimit;
|
|
2191
|
+
els.menuAddTerminal.disabled = atPaneLimit;
|
|
2192
|
+
els.menuAddBrowser.disabled = atPaneLimit;
|
|
2193
|
+
els.emptyAddTerminal.disabled = atPaneLimit;
|
|
2194
|
+
els.emptyAddBrowser.disabled = atPaneLimit;
|
|
2195
|
+
els.tabsNewTab.disabled = atTabLimit;
|
|
2196
|
+
els.menuNewTab.disabled = atTabLimit;
|
|
2197
|
+
els.emptyNewTab.disabled = atTabLimit;
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
function syncPanelState() {
|
|
2201
|
+
const anyOpen = [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]
|
|
2202
|
+
.some((dialog) => dialog && dialog.open);
|
|
2203
|
+
els.app?.classList.toggle('panel-open', anyOpen);
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
function openSheets(dialog) {
|
|
2207
|
+
if (dialog.open) return;
|
|
2208
|
+
closeSheets();
|
|
2209
|
+
hideContextMenu();
|
|
2210
|
+
dialog.show();
|
|
2211
|
+
syncPanelState();
|
|
2212
|
+
dialog.querySelector('button, input, select')?.focus();
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
function closeSheets() {
|
|
2216
|
+
for (const dialog of [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]) {
|
|
2217
|
+
if (dialog?.open) dialog.close();
|
|
2218
|
+
}
|
|
2219
|
+
syncPanelState();
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
function openTabsDialog() {
|
|
2223
|
+
tabsDialogSignature = '';
|
|
2224
|
+
if (!currentState) {
|
|
2225
|
+
void refresh();
|
|
2226
|
+
return;
|
|
2227
|
+
}
|
|
2228
|
+
renderTabsDialog();
|
|
2229
|
+
openSheets(els.tabsDialog);
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
function openMenuDialog() {
|
|
2233
|
+
updateAddLimits();
|
|
2234
|
+
openSheets(els.menuDialog);
|
|
2235
|
+
}
|
|
2236
|
+
|
|
2237
|
+
function focusPaneById(paneId, mode = 'type') {
|
|
2238
|
+
const record = records.get(paneId);
|
|
2239
|
+
if (!record) return false;
|
|
2240
|
+
if (record.kind === 'terminal') {
|
|
2241
|
+
if (record.term) {
|
|
2242
|
+
record.term.focus();
|
|
2243
|
+
return true;
|
|
2244
|
+
}
|
|
2245
|
+
requestAnimationFrame(() => {
|
|
2246
|
+
if (!record.disposed && record.term) record.term.focus();
|
|
2247
|
+
});
|
|
2248
|
+
return true;
|
|
2249
|
+
}
|
|
2250
|
+
if (record.kind === 'browser') {
|
|
2251
|
+
const input = mode === 'address' ? record.addressInput : record.typeInput;
|
|
2252
|
+
input.focus();
|
|
2253
|
+
return true;
|
|
2254
|
+
}
|
|
2255
|
+
return false;
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
function focusActive() {
|
|
2259
|
+
const tab = activeTab();
|
|
2260
|
+
if (!tab || !tab.panes.length) {
|
|
2261
|
+
if (!els.emptyState.hidden) els.emptyAddTerminal.focus();
|
|
2262
|
+
else showNotice('Add a terminal or browser to type.', 'info', 2600);
|
|
2263
|
+
return;
|
|
2264
|
+
}
|
|
2265
|
+
const paneId = effectiveActivePaneId(tab);
|
|
2266
|
+
const record = records.get(paneId);
|
|
2267
|
+
if (!record) {
|
|
2268
|
+
requestAnimationFrame(() => { focusPaneById(paneId); });
|
|
2269
|
+
return;
|
|
2270
|
+
}
|
|
2271
|
+
void setActivePane(paneId);
|
|
2272
|
+
focusPaneById(paneId, record.kind === 'browser' ? 'type' : 'terminal');
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
function triggerBack() {
|
|
2276
|
+
const record = records.get(effectiveActivePaneId());
|
|
2277
|
+
if (record && record.kind === 'browser') void browserAction(record, 'back');
|
|
2278
|
+
}
|
|
2279
|
+
|
|
2280
|
+
function bindEvents() {
|
|
2281
|
+
document.addEventListener('keydown', (event) => {
|
|
2282
|
+
if (!event.altKey || event.ctrlKey || event.metaKey) return;
|
|
2283
|
+
if (document.querySelector('dialog[open]')) return;
|
|
2284
|
+
const target = event.target;
|
|
2285
|
+
if (target && target.closest && target.closest('input:not(.xterm-helper-textarea), textarea:not(.xterm-helper-textarea), [contenteditable="true"]')) return;
|
|
2286
|
+
const tabs = (currentState && currentState.tabs) || [];
|
|
2287
|
+
if (event.key.toLowerCase() === 't') {
|
|
2288
|
+
event.preventDefault();
|
|
2289
|
+
void newTab();
|
|
2290
|
+
return;
|
|
2291
|
+
}
|
|
2292
|
+
if (event.key.toLowerCase() === 'w') {
|
|
2293
|
+
const tab = activeTab();
|
|
2294
|
+
const paneId = effectiveActivePaneId(tab);
|
|
2295
|
+
const record = records.get(paneId);
|
|
2296
|
+
if (record) {
|
|
2297
|
+
event.preventDefault();
|
|
2298
|
+
requestClose('pane', paneId, record.titleEl.textContent || 'pane');
|
|
2299
|
+
}
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
if (event.key === '[' || event.key === ']') {
|
|
2303
|
+
if (!tabs.length) return;
|
|
2304
|
+
const index = Math.max(0, tabs.findIndex((tab) => tab.id === currentState.activeTabId));
|
|
2305
|
+
const next = tabs[(index + (event.key === ']' ? 1 : -1) + tabs.length) % tabs.length];
|
|
2306
|
+
if (next) { event.preventDefault(); void activateTab(next.id); }
|
|
2307
|
+
return;
|
|
2308
|
+
}
|
|
2309
|
+
if (event.key.toLowerCase() === 'm') {
|
|
2310
|
+
const paneId = effectiveActivePaneId();
|
|
2311
|
+
if (!records.get(paneId)) return;
|
|
2312
|
+
event.preventDefault();
|
|
2313
|
+
togglePaneMaximized(paneId);
|
|
2314
|
+
return;
|
|
2315
|
+
}
|
|
2316
|
+
if (/^[1-9]$/.test(event.key) && tabs.length) {
|
|
2317
|
+
const index = event.key === '9' ? tabs.length - 1 : Number(event.key) - 1;
|
|
2318
|
+
if (tabs[index]) { event.preventDefault(); void activateTab(tabs[index].id); }
|
|
2319
|
+
return;
|
|
2320
|
+
}
|
|
2321
|
+
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight' || event.key === 'ArrowUp' || event.key === 'ArrowDown') {
|
|
2322
|
+
const tab = activeTab();
|
|
2323
|
+
if (!tab || !tab.panes.length) return;
|
|
2324
|
+
const step = event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? -1 : 1;
|
|
2325
|
+
if (event.shiftKey) {
|
|
2326
|
+
event.preventDefault();
|
|
2327
|
+
reorderActivePane(step);
|
|
2328
|
+
return;
|
|
2329
|
+
}
|
|
2330
|
+
const at = tab.panes.findIndex((pane) => pane.id === effectiveActivePaneId(tab));
|
|
2331
|
+
const next = tab.panes[(at + step + tab.panes.length) % tab.panes.length];
|
|
2332
|
+
if (next) {
|
|
2333
|
+
event.preventDefault();
|
|
2334
|
+
void setActivePane(next.id);
|
|
2335
|
+
focusPaneById(next.id, next.kind === 'browser' ? 'type' : 'terminal');
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
});
|
|
2339
|
+
window.addEventListener('dragover', (event) => {
|
|
2340
|
+
if (Array.from(event.dataTransfer?.types || []).includes('Files')) event.preventDefault();
|
|
2341
|
+
});
|
|
2342
|
+
window.addEventListener('drop', (event) => {
|
|
2343
|
+
if (!event.dataTransfer?.files?.length) return;
|
|
2344
|
+
if (event.target.closest?.('.pane')) return;
|
|
2345
|
+
event.preventDefault();
|
|
2346
|
+
const record = records.get(effectiveActivePaneId());
|
|
2347
|
+
void attachFiles(record, Array.from(event.dataTransfer.files));
|
|
2348
|
+
});
|
|
2349
|
+
els.emptyAddTerminal.addEventListener('click', () => { void addPane('terminal'); });
|
|
2350
|
+
els.emptyAddBrowser.addEventListener('click', () => { void addPane('browser'); });
|
|
2351
|
+
els.emptyNewTab.addEventListener('click', () => { void newTab(); });
|
|
2352
|
+
|
|
2353
|
+
els.contextMenu.addEventListener('click', async (event) => {
|
|
2354
|
+
const action = event.target.closest('[data-context]')?.dataset.context;
|
|
2355
|
+
const record = records.get(contextRecordId);
|
|
2356
|
+
hideContextMenu();
|
|
2357
|
+
if (!action || !record || !record.term) return;
|
|
2358
|
+
try {
|
|
2359
|
+
if (action === 'copy') {
|
|
2360
|
+
if (!record.term.hasSelection()) { showNotice('Select terminal text first.', 'info', 2200); return; }
|
|
2361
|
+
await navigator.clipboard.writeText(record.term.getSelection());
|
|
2362
|
+
showNotice('Selection copied.', 'info', 2200);
|
|
2363
|
+
} else if (action === 'paste') {
|
|
2364
|
+
const text = await navigator.clipboard.readText();
|
|
2365
|
+
if (text) sendTerminalInput(record, text);
|
|
2366
|
+
} else if (action === 'select-all') {
|
|
2367
|
+
record.term.selectAll();
|
|
2368
|
+
} else if (action === 'clear') {
|
|
2369
|
+
record.term.clear();
|
|
2370
|
+
} else if (action === 'reader') {
|
|
2371
|
+
openReaderView();
|
|
2372
|
+
}
|
|
2373
|
+
} catch (error) {
|
|
2374
|
+
showNotice(error.message || 'Clipboard is unavailable in this browser.', 'error');
|
|
2375
|
+
}
|
|
2376
|
+
});
|
|
2377
|
+
els.browserContextMenu.addEventListener('click', async (event) => {
|
|
2378
|
+
const action = event.target.closest('[data-browser-context]')?.dataset.browserContext;
|
|
2379
|
+
const record = records.get(browserContextRecordId);
|
|
2380
|
+
hideContextMenu();
|
|
2381
|
+
if (!action || !record) return;
|
|
2382
|
+
if (action === 'copy-url') {
|
|
2383
|
+
try {
|
|
2384
|
+
await navigator.clipboard.writeText(record.currentUrl || '');
|
|
2385
|
+
showNotice('Page URL copied.', 'info', 2200);
|
|
2386
|
+
} catch (_) {
|
|
2387
|
+
showNotice('Copy blocked by the browser.', 'error');
|
|
2388
|
+
}
|
|
2389
|
+
return;
|
|
2390
|
+
}
|
|
2391
|
+
if (action === 'open') {
|
|
2392
|
+
if (record.currentUrl) window.open(record.currentUrl, '_blank');
|
|
2393
|
+
return;
|
|
2394
|
+
}
|
|
2395
|
+
if (['back', 'forward', 'reload'].includes(action)) void browserAction(record, action);
|
|
2396
|
+
});
|
|
2397
|
+
document.addEventListener('pointerdown', (event) => {
|
|
2398
|
+
if (!els.contextMenu.hidden && !els.contextMenu.contains(event.target)) hideContextMenu();
|
|
2399
|
+
if (!els.browserContextMenu.hidden && !els.browserContextMenu.contains(event.target)) hideContextMenu();
|
|
2400
|
+
}, true);
|
|
2401
|
+
document.addEventListener('keydown', (event) => {
|
|
2402
|
+
if (event.key === 'Escape' && !els.contextMenu.hidden) { event.preventDefault(); hideContextMenu(); }
|
|
2403
|
+
}, true);
|
|
2404
|
+
els.browserControlCancel.addEventListener('click', hideBrowserControl);
|
|
2405
|
+
els.browserControlApply.addEventListener('click', () => { void applyBrowserControl(); });
|
|
2406
|
+
els.browserControlValue.addEventListener('keydown', (event) => {
|
|
2407
|
+
if (event.key === 'Enter') { event.preventDefault(); void applyBrowserControl(); }
|
|
2408
|
+
});
|
|
2409
|
+
els.pageDialogDismiss.addEventListener('click', () => { void answerPageDialog('dismiss'); });
|
|
2410
|
+
els.pageDialogAccept.addEventListener('click', () => { void answerPageDialog('accept'); });
|
|
2411
|
+
els.pageDialogInput.addEventListener('keydown', (event) => {
|
|
2412
|
+
if (event.key === 'Enter') { event.preventDefault(); void answerPageDialog('accept'); }
|
|
2413
|
+
});
|
|
2414
|
+
els.closeCancel.addEventListener('click', () => {
|
|
2415
|
+
pendingClose = null;
|
|
2416
|
+
els.closeConfirm.close();
|
|
2417
|
+
});
|
|
2418
|
+
els.closeConfirm.addEventListener('cancel', () => { pendingClose = null; });
|
|
2419
|
+
els.closeApprove.addEventListener('click', () => {
|
|
2420
|
+
const target = pendingClose;
|
|
2421
|
+
pendingClose = null;
|
|
2422
|
+
els.closeConfirm.close();
|
|
2423
|
+
if (!target) return;
|
|
2424
|
+
if (target.kind === 'tab') void closeTab(target.id, target.title);
|
|
2425
|
+
else void closePane(target.id, target.title);
|
|
2426
|
+
});
|
|
2427
|
+
els.notice.addEventListener('click', async () => {
|
|
2428
|
+
const url = els.notice.dataset.copyUrl;
|
|
2429
|
+
if (!url) return;
|
|
2430
|
+
try {
|
|
2431
|
+
await navigator.clipboard.writeText(url);
|
|
2432
|
+
showNotice('Attachment URL copied', 'info', 2200);
|
|
2433
|
+
} catch (_) {
|
|
2434
|
+
showNotice('Copy blocked by the browser; select the URL instead.', 'error', 3200);
|
|
2435
|
+
}
|
|
2436
|
+
});
|
|
2437
|
+
els.backButton.addEventListener('click', triggerBack);
|
|
2438
|
+
els.tabsButton.addEventListener('click', openTabsDialog);
|
|
2439
|
+
els.keyboardButton.addEventListener('click', focusActive);
|
|
2440
|
+
els.menuButton.addEventListener('click', openMenuDialog);
|
|
2441
|
+
|
|
2442
|
+
els.tabsNewTab.addEventListener('click', () => { void newTab(); });
|
|
2443
|
+
els.tabsAddTerminal.addEventListener('click', () => { void addPane('terminal'); });
|
|
2444
|
+
els.tabsAddBrowser.addEventListener('click', () => { void addPane('browser'); });
|
|
2445
|
+
els.menuNewTab.addEventListener('click', () => { void newTab(); });
|
|
2446
|
+
els.menuAddTerminal.addEventListener('click', () => { void addPane('terminal'); });
|
|
2447
|
+
els.menuAddBrowser.addEventListener('click', () => { void addPane('browser'); });
|
|
2448
|
+
els.menuAttach.addEventListener('click', () => { closeSheets(); els.attachInput.click(); });
|
|
2449
|
+
els.menuReader.addEventListener('click', openReaderView);
|
|
2450
|
+
els.menuFontUp.addEventListener('click', () => adjustPaneFont(1));
|
|
2451
|
+
els.menuFontDown.addEventListener('click', () => adjustPaneFont(-1));
|
|
2452
|
+
els.menuShortcuts.addEventListener('click', () => {
|
|
2453
|
+
openSheets(els.shortcutsDialog);
|
|
2454
|
+
});
|
|
2455
|
+
els.readerRefresh.addEventListener('click', refreshReaderView);
|
|
2456
|
+
els.readerClose.addEventListener('click', closeReaderView);
|
|
2457
|
+
els.readerView.addEventListener('keydown', (event) => {
|
|
2458
|
+
if (event.key === 'Escape') { event.preventDefault(); closeReaderView(); }
|
|
2459
|
+
});
|
|
2460
|
+
els.attachInput.addEventListener('change', () => {
|
|
2461
|
+
const files = Array.from(els.attachInput.files || []);
|
|
2462
|
+
els.attachInput.value = '';
|
|
2463
|
+
void attachFiles(records.get(effectiveActivePaneId()), files);
|
|
2464
|
+
});
|
|
2465
|
+
|
|
2466
|
+
document.querySelectorAll('[data-close]').forEach((button) => {
|
|
2467
|
+
button.addEventListener('click', () => {
|
|
2468
|
+
const dialog = button.closest('dialog');
|
|
2469
|
+
if (dialog) dialog.close();
|
|
2470
|
+
});
|
|
2471
|
+
});
|
|
2472
|
+
|
|
2473
|
+
for (const dialog of [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]) {
|
|
2474
|
+
dialog?.addEventListener('close', syncPanelState);
|
|
2475
|
+
}
|
|
2476
|
+
// closeSheets() can dismiss the confirmation programmatically (for example
|
|
2477
|
+
// when a page dialog arrives); clear the pending target on every close.
|
|
2478
|
+
// The close event is queued, so requestClose may have already reopened the
|
|
2479
|
+
// dialog with a new target by the time it fires.
|
|
2480
|
+
els.closeConfirm?.addEventListener('close', () => {
|
|
2481
|
+
if (!els.closeConfirm.open) pendingClose = null;
|
|
2482
|
+
});
|
|
2483
|
+
// Capture-phase: the docks are non-modal, so focus can sit in an xterm that
|
|
2484
|
+
// consumes Escape before a bubble listener would ever see it.
|
|
2485
|
+
document.addEventListener('keydown', (event) => {
|
|
2486
|
+
if (event.key !== 'Escape') return;
|
|
2487
|
+
// Check the sheet list directly: this runs on every Escape in a TUI, and a
|
|
2488
|
+
// document-wide dialog query would also match non-sheet overlays.
|
|
2489
|
+
const anySheet = [els.tabsDialog, els.menuDialog, els.shortcutsDialog, els.closeConfirm]
|
|
2490
|
+
.some((dialog) => dialog && dialog.open);
|
|
2491
|
+
if (!anySheet) return;
|
|
2492
|
+
// A pane owns its keys. Escape goes to vim/less/the page; the dock has a
|
|
2493
|
+
// visible close control because it is not modal.
|
|
2494
|
+
if (event.target instanceof Element && event.target.closest('.pane')) return;
|
|
2495
|
+
event.preventDefault();
|
|
2496
|
+
event.stopPropagation();
|
|
2497
|
+
closeSheets();
|
|
2498
|
+
}, true);
|
|
2499
|
+
|
|
2500
|
+
for (const dialog of [els.tabsDialog, els.menuDialog]) {
|
|
2501
|
+
dialog.addEventListener('click', (event) => {
|
|
2502
|
+
if (event.target === dialog) dialog.close();
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
|
|
2506
|
+
const onMotionPreference = () => {
|
|
2507
|
+
for (const record of records.values()) {
|
|
2508
|
+
if (record.term) record.term.options.cursorBlink = !reducedMotion.matches;
|
|
2509
|
+
}
|
|
2510
|
+
};
|
|
2511
|
+
if (typeof reducedMotion.addEventListener === 'function') {
|
|
2512
|
+
reducedMotion.addEventListener('change', onMotionPreference);
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
|
|
2516
|
+
let statePollTimer = 0;
|
|
2517
|
+
|
|
2518
|
+
function startStatePolling() {
|
|
2519
|
+
if (statePollTimer) clearInterval(statePollTimer);
|
|
2520
|
+
statePollTimer = window.setInterval(() => {
|
|
2521
|
+
if (!document.hidden) void refresh();
|
|
2522
|
+
}, STATE_POLL_MS);
|
|
2523
|
+
document.addEventListener('visibilitychange', () => {
|
|
2524
|
+
if (!document.hidden) void refresh();
|
|
2525
|
+
});
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2528
|
+
async function bootstrap() {
|
|
2529
|
+
if (booting) return;
|
|
2530
|
+
booting = true;
|
|
2531
|
+
els.emptyTitle.textContent = 'Connecting to the workspace';
|
|
2532
|
+
els.emptyCopy.textContent = 'Reading tabs and panes.';
|
|
2533
|
+
els.emptyActions.hidden = true;
|
|
2534
|
+
try {
|
|
2535
|
+
const response = await fetch(`${API_ROOT}/bootstrap`, { cache: 'no-store' });
|
|
2536
|
+
let payload = null;
|
|
2537
|
+
try { payload = await response.json(); } catch (_) { payload = null; }
|
|
2538
|
+
if (!response.ok) throw new Error((payload && payload.error) || `Workspace bootstrap failed (${response.status}).`);
|
|
2539
|
+
if (!payload || !payload.token) throw new Error('Workspace bootstrap did not return a token.');
|
|
2540
|
+
token = payload.token;
|
|
2541
|
+
const previousEpoch = window.sessionStorage.getItem('townmouse.workspaceEpoch');
|
|
2542
|
+
const epoch = payload.state && payload.state.epoch;
|
|
2543
|
+
applyState(payload.state, { force: true });
|
|
2544
|
+
clearTimeout(noticeTimer);
|
|
2545
|
+
els.notice.hidden = true;
|
|
2546
|
+
if (previousEpoch && epoch && previousEpoch !== epoch) {
|
|
2547
|
+
showNotice('Workspace restarted. Layout restored; terminal scrollback and running jobs are gone.', 'info', 9000);
|
|
2548
|
+
}
|
|
2549
|
+
if (epoch) {
|
|
2550
|
+
try { window.sessionStorage.setItem('townmouse.workspaceEpoch', epoch); } catch (_) { /* storage disabled */ }
|
|
2551
|
+
}
|
|
2552
|
+
logStatus('Workspace ready.');
|
|
2553
|
+
} catch (error) {
|
|
2554
|
+
token = '';
|
|
2555
|
+
booting = false;
|
|
2556
|
+
els.emptyTitle.textContent = 'Workspace unavailable';
|
|
2557
|
+
els.emptyCopy.textContent = 'Waiting for the local server. Retrying.';
|
|
2558
|
+
els.emptyActions.hidden = true;
|
|
2559
|
+
showNotice(error.message || 'Could not reach the workspace. Retrying.', 'error', 0);
|
|
2560
|
+
window.setTimeout(() => { void bootstrap(); }, 1800);
|
|
2561
|
+
return;
|
|
2562
|
+
}
|
|
2563
|
+
booting = false;
|
|
2564
|
+
startStatePolling();
|
|
2565
|
+
}
|
|
2566
|
+
|
|
2567
|
+
window.__panes = {
|
|
2568
|
+
refresh: () => refresh(),
|
|
2569
|
+
state: () => currentState,
|
|
2570
|
+
dimensions: (paneId) => {
|
|
2571
|
+
const record = records.get(paneId || effectiveActivePaneId());
|
|
2572
|
+
return record && record.term ? { cols: record.term.cols, rows: record.term.rows } : null;
|
|
2573
|
+
},
|
|
2574
|
+
selectAll: (paneId) => {
|
|
2575
|
+
const record = records.get(paneId || effectiveActivePaneId());
|
|
2576
|
+
if (record && record.term) record.term.selectAll();
|
|
2577
|
+
},
|
|
2578
|
+
selection: (paneId) => {
|
|
2579
|
+
const record = records.get(paneId || effectiveActivePaneId());
|
|
2580
|
+
return record && record.term ? record.term.getSelection() : '';
|
|
2581
|
+
},
|
|
2582
|
+
fontSize: (paneId) => {
|
|
2583
|
+
const record = records.get(paneId || effectiveActivePaneId());
|
|
2584
|
+
return record && record.term ? record.term.options.fontSize : null;
|
|
2585
|
+
},
|
|
2586
|
+
render: (next) => {
|
|
2587
|
+
if (next && Array.isArray(next.tabs)) {
|
|
2588
|
+
applyState(next, { force: true });
|
|
2589
|
+
} else if (currentState) {
|
|
2590
|
+
applyState(currentState, { force: true });
|
|
2591
|
+
}
|
|
2592
|
+
return currentState;
|
|
2593
|
+
}
|
|
2594
|
+
};
|
|
2595
|
+
|
|
2596
|
+
Object.defineProperty(window.__panes, '__debug', {
|
|
2597
|
+
value: { histories, cursors, records },
|
|
2598
|
+
enumerable: false
|
|
2599
|
+
});
|
|
2600
|
+
|
|
2601
|
+
const syncKeyboardInset = () => {
|
|
2602
|
+
const viewport = window.visualViewport;
|
|
2603
|
+
const inset = viewport ? Math.max(0, window.innerHeight - viewport.height - viewport.offsetTop) : 0;
|
|
2604
|
+
document.documentElement.style.setProperty('--keyboard-inset', `${Math.round(inset)}px`);
|
|
2605
|
+
document.body.classList.toggle('keyboard-open', inset > 80);
|
|
2606
|
+
};
|
|
2607
|
+
window.visualViewport?.addEventListener('resize', syncKeyboardInset);
|
|
2608
|
+
window.visualViewport?.addEventListener('scroll', syncKeyboardInset);
|
|
2609
|
+
syncKeyboardInset();
|
|
2610
|
+
|
|
2611
|
+
let layoutResizeFrame = 0;
|
|
2612
|
+
window.addEventListener('resize', () => {
|
|
2613
|
+
if (layoutResizeFrame) cancelAnimationFrame(layoutResizeFrame);
|
|
2614
|
+
layoutResizeFrame = requestAnimationFrame(() => {
|
|
2615
|
+
layoutResizeFrame = 0;
|
|
2616
|
+
applyPaneLayout(activeTab());
|
|
2617
|
+
updateHostContext();
|
|
2618
|
+
});
|
|
2619
|
+
});
|
|
2620
|
+
|
|
2621
|
+
buildPaneKeybar();
|
|
2622
|
+
bindEvents();
|
|
2623
|
+
void bootstrap();
|
|
2624
|
+
|
|
2625
|
+
|