162 lines
8.9 KiB
JavaScript
162 lines
8.9 KiB
JavaScript
// The window layout of one project, kept as ONE versioned record (`layout.v1:<project>`) and put back after a reload:
|
|
// tool windows (side, active one, sizes), editor tabs with cursor / scroll / selection and split groups, the Project tree
|
|
// (folders opened, selection), the Claude panel (active conversation, scroll, unsent text, log view, conversations in windows,
|
|
// Remote Control in a Terminal) and the Terminal tabs.
|
|
//
|
|
// Everything here is pure (no DOM, no backend): app.js collects a snapshot and gives a `host` to restore(), tests/layout.test.mjs
|
|
// plays serialize / migrate / prune / restore with a fake host. It works the same in the web IDE (nothing desktop-only here:
|
|
// what a target lacks is simply not in the snapshot, or not known by the host, and is skipped).
|
|
export const LAYOUT_VERSION = 1;
|
|
export const SIDES = ['left', 'bottom', 'right'];
|
|
const SIZE_VARS = ['--left-width', '--bottom-height', '--right-width'];
|
|
const MAX_TABS = 60;
|
|
const MAX_DRAFT = 20000;
|
|
const MAX_TREE = 400;
|
|
|
|
/** The prefs key of a project's record. */
|
|
export const layoutKey = (projectKey) => 'layout.v1:' + projectKey;
|
|
|
|
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
const str = (v, max = 4096) => (typeof v === 'string' ? v.slice(0, max) : null);
|
|
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
|
const arr = (v) => (Array.isArray(v) ? v : []);
|
|
|
|
/** A cleaned view state of a text editor: {line, col, top, left, sel: [startLine, startCol, endLine, endCol]}. */
|
|
function cleanView(v) {
|
|
if (!isObj(v)) return null;
|
|
const out = {};
|
|
for (const k of ['line', 'col', 'top', 'left']) { const n = num(v[k]); if (n !== null && n >= 0) out[k] = Math.round(n); }
|
|
if (Array.isArray(v.sel) && v.sel.length === 4 && v.sel.every((n) => num(n) !== null && n >= 1)) out.sel = v.sel.map(Math.round);
|
|
return Object.keys(out).length ? out : null;
|
|
}
|
|
|
|
/** The font zoom per panel, {id: number} (px 8..40 for `editor` / `terminal`, % 50..300 for the others; see zoom.js). Older records have none. */
|
|
const PX_PANELS = new Set(['editor', 'terminal']);
|
|
function cleanZoom(v) {
|
|
const out = {};
|
|
if (!isObj(v)) return out;
|
|
for (const [id, n] of Object.entries(v).slice(0, 60)) {
|
|
const [min, max] = PX_PANELS.has(id) ? [8, 40] : [50, 300];
|
|
if (/^[\w.-]{1,64}$/.test(id) && num(n) !== null) out[id] = Math.round(Math.min(max, Math.max(min, n)) * 100) / 100;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** The record for a snapshot taken from the live IDE (anything odd is dropped: it is read back from storage later). */
|
|
export function serialize(snap = {}, now = Date.now()) {
|
|
const tools = isObj(snap.tools) ? snap.tools : {};
|
|
const open = {};
|
|
for (const side of SIDES) open[side] = str(tools.open?.[side], 64);
|
|
const sizes = {};
|
|
for (const v of SIZE_VARS) { const s = str(tools.sizes?.[v], 32); if (s) sizes[v] = s; }
|
|
const sides = {};
|
|
for (const [id, side] of Object.entries(isObj(tools.sides) ? tools.sides : {})) if (SIDES.includes(side)) sides[id.slice(0, 64)] = side;
|
|
const groups = arr(snap.editors?.groups).slice(0, 6).map((g) => ({
|
|
active: str(g?.active),
|
|
tabs: arr(g?.tabs).slice(0, MAX_TABS).map((tab) => ({ path: str(tab?.path), view: cleanView(tab?.view) })).filter((tab) => tab.path),
|
|
}));
|
|
const convs = {};
|
|
for (const [key, c] of Object.entries(isObj(snap.claude?.convs) ? snap.claude.convs : {}).slice(0, 30)) {
|
|
convs[key.slice(0, 64)] = { draft: str(c?.draft, MAX_DRAFT) || '', scroll: Math.max(0, num(c?.scroll) ?? 0), stick: c?.stick !== false, log: !!c?.log };
|
|
}
|
|
const terms = arr(snap.terminals?.tabs).slice(0, 12).map((x) => ({
|
|
id: num(x?.id), label: str(x?.label, 80) || 'Local', rc: isObj(x?.rc) && str(x.rc.conv, 64) ? { conv: str(x.rc.conv, 64), mark: isObj(x.rc.mark) ? x.rc.mark : null } : null,
|
|
}));
|
|
return {
|
|
v: LAYOUT_VERSION,
|
|
savedAt: now,
|
|
tools: { open, sizes, sides },
|
|
editors: { activeGroup: Math.max(0, num(snap.editors?.activeGroup) ?? 0), groups },
|
|
tree: { expanded: arr(snap.tree?.expanded).map((p) => str(p)).filter((p) => p !== null).slice(0, MAX_TREE), selected: str(snap.tree?.selected) },
|
|
claude: {
|
|
active: str(snap.claude?.active, 64), convs,
|
|
detached: arr(snap.claude?.detached).map((k) => str(k, 64)).filter(Boolean).slice(0, 10),
|
|
},
|
|
terminals: { boot: str(snap.terminals?.boot, 64), active: Math.max(0, num(snap.terminals?.active) ?? 0), tabs: terms },
|
|
share: { active: !!snap.share?.active },
|
|
zoom: cleanZoom(snap.zoom),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Any stored value -> a record of the current version, or null (nothing usable). Newer versions are not guessed at; the older
|
|
* pieces of prefs (`tool:*`, `size--*`, `tabs:`, `tree:`) are read by legacy() when there is no record at all.
|
|
*/
|
|
export function migrate(raw) {
|
|
if (!isObj(raw)) return null;
|
|
if (raw.v === LAYOUT_VERSION) return serialize(raw, num(raw.savedAt) ?? 0);
|
|
return null;
|
|
}
|
|
|
|
/** A record from the layout pieces the IDE kept before there was one (prefs read through `get`). */
|
|
export function legacy(get, projectKey) {
|
|
const open = { left: get('tool:left', null), bottom: get('tool:bottom', null), right: null };
|
|
const sizes = {};
|
|
for (const v of SIZE_VARS) { const s = get('size' + v, null); if (s) sizes[v] = s; }
|
|
const groups = arr(get('tabs:' + projectKey, null)).map((g) => ({ active: g?.active, tabs: arr(g?.tabs).map((path) => ({ path })) }));
|
|
return serialize({ tools: { open, sizes }, editors: { groups }, tree: { expanded: arr(get('tree:' + projectKey, [])) } }, 0);
|
|
}
|
|
|
|
/** The record without what no longer exists (a tool that was renamed or is not offered here, a deleted file): silently. */
|
|
export function prune(layout, { tools = [], files = null } = {}) {
|
|
const known = new Set(tools);
|
|
const has = (p) => files === null || files.has(p);
|
|
const l = structuredClone(layout);
|
|
for (const side of SIDES) if (l.tools.open[side] && !known.has(l.tools.open[side])) l.tools.open[side] = null;
|
|
for (const id of Object.keys(l.tools.sides)) if (!known.has(id)) delete l.tools.sides[id];
|
|
l.editors.groups = l.editors.groups.map((g) => {
|
|
const tabs = g.tabs.filter((tab) => has(tab.path));
|
|
return { active: tabs.some((tab) => tab.path === g.active) ? g.active : (tabs[tabs.length - 1]?.path ?? null), tabs };
|
|
}).filter((g) => g.tabs.length);
|
|
l.editors.activeGroup = Math.min(l.editors.activeGroup, Math.max(0, l.editors.groups.length - 1));
|
|
if (files !== null) {
|
|
const dirs = new Set(['']);
|
|
for (const f of files) for (let i = f.indexOf('/'); i !== -1; i = f.indexOf('/', i + 1)) dirs.add(f.slice(0, i));
|
|
l.tree.expanded = l.tree.expanded.filter((p) => p.startsWith('lib:') || dirs.has(p.replace(/\/+$/, '')));
|
|
}
|
|
if (l.tree.selected !== null && l.tree.selected !== '' && !has(l.tree.selected) && !l.tree.expanded.includes(l.tree.selected)) l.tree.selected = null;
|
|
return l;
|
|
}
|
|
|
|
/**
|
|
* Puts a record back, in order: tools -> tree -> editors -> Terminal -> Claude. A step that fails is skipped (the rest still
|
|
* comes back). `host` is what the page gives:
|
|
* toolIds(), files() (Set or null), setSizes(sizes), moveTool(id, side), showTool(id), closeSide(side),
|
|
* tree(treeRecord), editors(editorsRecord), terminals(terminalsRecord), claude(claudeRecord) (the last four optional).
|
|
* Returns the names of the steps that failed (for logs / tests).
|
|
*/
|
|
export async function restore(layout, host) {
|
|
const failed = [];
|
|
const l = prune(layout, { tools: host.toolIds(), files: host.files?.() ?? null });
|
|
const step = async (name, fn) => { try { await fn(); } catch (e) { failed.push(name + ': ' + (e?.message || e)); } };
|
|
await step('tools', async () => {
|
|
host.setSizes?.(l.tools.sizes);
|
|
for (const [id, side] of Object.entries(l.tools.sides)) host.moveTool?.(id, side);
|
|
for (const side of SIDES) { if (l.tools.open[side]) host.showTool(l.tools.open[side]); else host.closeSide(side); }
|
|
});
|
|
if (host.zoom && Object.keys(l.zoom || {}).length) await step('zoom', () => host.zoom(l.zoom));
|
|
if (host.tree) await step('tree', () => host.tree(l.tree));
|
|
if (host.editors) await step('editors', () => host.editors(l.editors));
|
|
// the Terminal first: a conversation that was in Remote Control finds its Terminal tab again
|
|
if (host.terminals) await step('terminals', () => host.terminals(l.terminals));
|
|
if (host.claude) await step('claude', () => host.claude(l.claude));
|
|
return { layout: l, failed };
|
|
}
|
|
|
|
/** A saver: `save()` writes the snapshot when it differs from the last one written (cheap to call often); `flush()` at once. */
|
|
export function createSaver(collect, write, same = (a, b) => JSON.stringify(a) === JSON.stringify(b)) {
|
|
let last = null;
|
|
let timer = null;
|
|
const flush = () => {
|
|
clearTimeout(timer); timer = null;
|
|
let rec;
|
|
try { rec = collect(); } catch { return false; }
|
|
if (!rec) return false;
|
|
const cmp = { ...rec, savedAt: 0 };
|
|
if (last && same(last, cmp)) return false;
|
|
last = cmp;
|
|
write(rec);
|
|
return true;
|
|
};
|
|
return { flush, save(ms = 600) { if (timer === null) timer = setTimeout(flush, ms); }, forget() { last = null; } };
|
|
}
|