219 lines
11 KiB
JavaScript
219 lines
11 KiB
JavaScript
// The hexadecimal view of any file (the editor's View as Hexadecimal, the quick editor's Hexadecimal): offset | 16 bytes |
|
|
// their characters, one line each. Only the lines on the screen are drawn and only their bytes are read (ranges of 64 KB
|
|
// asked to the PHP side: file.bytes / quick.bytes), so a 100 MB file scrolls as fast as a small one. Read only.
|
|
import { t } from './ui.js';
|
|
|
|
const ROW = 18; // px per line
|
|
const PER = 16; // bytes per line
|
|
const CHUNK = 64 * 1024; // bytes per read
|
|
const KEEP = 48; // chunks kept in memory
|
|
const MAX_SPACE = 8_000_000; // px: browsers cap an element's height, a bigger file maps its scroll onto this
|
|
|
|
const STYLE = `
|
|
.hexv { position: absolute; inset: 0; display: flex; flex-direction: column; background: var(--bg, #1e1f22); color: var(--text, #dfe1e5); font-size: 12px; }
|
|
.hexv-bar { display: flex; align-items: center; gap: 8px; padding: 5px 10px; border-bottom: 1px solid var(--border-2, var(--line, #393b40)); flex: none; flex-wrap: wrap; }
|
|
.hexv-bar input { width: 120px; font: 12px ui-monospace, monospace; background: transparent; color: inherit; border: 1px solid var(--border-2, var(--line, #393b40)); border-radius: 4px; padding: 3px 6px; }
|
|
.hexv-bar button { font: inherit; color: inherit; background: transparent; border: 1px solid var(--border-2, var(--line, #393b40)); border-radius: 4px; padding: 3px 9px; cursor: pointer; }
|
|
.hexv-info { font-family: ui-monospace, monospace; color: var(--text-2, var(--muted, #8c8f96)); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; min-width: 0; }
|
|
.hexv-note { color: var(--warn, #e0a030); }
|
|
.hexv-scroll { flex: 1; min-height: 0; overflow: auto; position: relative; outline: none; }
|
|
.hexv-rows { position: absolute; left: 0; top: 0; padding: 0 12px; font: 12.5px/${ROW}px ui-monospace, 'JetBrains Mono', monospace; white-space: pre; user-select: none; }
|
|
.hexv-row { height: ${ROW}px; }
|
|
.hexv-off { color: var(--text-3, var(--muted, #6f737a)); margin-right: 16px; }
|
|
.hexv-row b { font-weight: normal; cursor: pointer; display: inline-block; }
|
|
.hexv-hex b { width: 2ch; margin-right: 1ch; }
|
|
.hexv-hex b.gap { margin-right: 2ch; }
|
|
.hexv-asc { margin-left: 14px; border-left: 1px solid var(--border-2, var(--line, #393b40)); padding-left: 10px; }
|
|
.hexv-asc b { width: 1ch; }
|
|
.hexv-row b.z { opacity: .45; }
|
|
.hexv-row b.sel { background: var(--accent, #3574f0); color: #fff; border-radius: 2px; opacity: 1; }
|
|
.hexv-row b.wait { opacity: .3; }
|
|
`;
|
|
|
|
function addStyle() {
|
|
if (document.getElementById('hexv-style')) return;
|
|
const style = document.createElement('style');
|
|
style.id = 'hexv-style';
|
|
style.textContent = STYLE;
|
|
document.head.append(style);
|
|
}
|
|
|
|
const make = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; };
|
|
const hex = (n, width) => n.toString(16).padStart(width, '0');
|
|
const shown = (b) => (b >= 0x20 && b < 0x7f ? String.fromCharCode(b) : '.');
|
|
|
|
/** "0x1f", "1fh", "$1f", "1F" (letters: hexadecimal) or "31" (decimal) -> 31; null when it is not a number */
|
|
export function parseOffset(text) {
|
|
const s = String(text).trim().toLowerCase().replace(/_/g, '');
|
|
if (/^(0x|\$)[0-9a-f]+$/.test(s)) return parseInt(s.replace(/^(0x|\$)/, ''), 16);
|
|
if (/^[0-9a-f]+h$/.test(s)) return parseInt(s.slice(0, -1), 16);
|
|
if (/^\d+$/.test(s)) return parseInt(s, 10);
|
|
if (/^[0-9a-f]+$/.test(s)) return parseInt(s, 16);
|
|
return null;
|
|
}
|
|
|
|
export class HexView {
|
|
/**
|
|
* @param {HTMLElement} host
|
|
* @param {{read: (offset: number, length: number) => Promise<{size: number, base64: string}>, note?: string}} options
|
|
*/
|
|
constructor(host, { read, note = '' }) {
|
|
addStyle();
|
|
this.read = read;
|
|
this.size = 0;
|
|
this.chunks = new Map(); // index -> Uint8Array | Promise
|
|
this.selected = -1;
|
|
this.node = make('div', 'hexv');
|
|
this.goto = make('input');
|
|
this.goto.placeholder = t('Go to offset');
|
|
this.goto.title = t('An offset: 0x1F00 or 1F00h (hexadecimal), 7936 (decimal)');
|
|
this.goto.onkeydown = (e) => { if (e.key === 'Enter') this.jump(); };
|
|
const go = make('button', '', t('Go'));
|
|
go.onclick = () => this.jump();
|
|
this.info = make('span', 'hexv-info');
|
|
const bar = make('div', 'hexv-bar');
|
|
bar.append(this.goto, go, this.info);
|
|
if (note) bar.append(make('span', 'hexv-note', note));
|
|
this.scroller = make('div', 'hexv-scroll');
|
|
this.scroller.tabIndex = 0;
|
|
this.space = make('div');
|
|
this.rows = make('div', 'hexv-rows');
|
|
this.scroller.append(this.space, this.rows);
|
|
this.node.append(bar, this.scroller);
|
|
host.append(this.node);
|
|
this.scroller.addEventListener('scroll', () => this.draw());
|
|
this.scroller.addEventListener('keydown', (e) => this.key(e));
|
|
this.rows.addEventListener('click', (e) => {
|
|
const b = e.target.closest('b[data-o]');
|
|
if (b) this.select(Number(b.dataset.o), false);
|
|
});
|
|
this.resize = new ResizeObserver(() => this.draw());
|
|
this.resize.observe(this.scroller);
|
|
this.info.textContent = t('Reading…');
|
|
this.chunk(0).then(() => { this.layout(); this.draw(); this.describe(); }).catch((e) => { this.info.textContent = String(e.message || e); });
|
|
}
|
|
|
|
destroy() { this.resize.disconnect(); this.node.remove(); this.chunks.clear(); }
|
|
|
|
get lines() { return Math.max(1, Math.ceil(this.size / PER)); }
|
|
|
|
layout() { this.space.style.height = Math.min(this.lines * ROW, MAX_SPACE) + 'px'; }
|
|
|
|
/** the first line on the screen, from the scroll (a big file: the scroll is a ratio of its lines) */
|
|
firstLine() {
|
|
const view = this.scroller.clientHeight;
|
|
const total = this.lines * ROW;
|
|
if (total <= MAX_SPACE) return Math.floor(this.scroller.scrollTop / ROW);
|
|
const max = Math.max(1, MAX_SPACE - view);
|
|
return Math.round(this.scroller.scrollTop / max * Math.max(0, this.lines - Math.floor(view / ROW)));
|
|
}
|
|
|
|
scrollToLine(line) {
|
|
const view = this.scroller.clientHeight;
|
|
const total = this.lines * ROW;
|
|
if (total <= MAX_SPACE) this.scroller.scrollTop = line * ROW;
|
|
else this.scroller.scrollTop = line / Math.max(1, this.lines - Math.floor(view / ROW)) * Math.max(1, MAX_SPACE - view);
|
|
this.draw();
|
|
}
|
|
|
|
chunk(index) {
|
|
const have = this.chunks.get(index);
|
|
if (have) return have instanceof Promise ? have : Promise.resolve(have);
|
|
const p = this.read(index * CHUNK, CHUNK).then((r) => {
|
|
this.size = r.size;
|
|
const bin = atob(r.base64 || '');
|
|
const bytes = new Uint8Array(bin.length);
|
|
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
this.chunks.set(index, bytes);
|
|
if (this.chunks.size > KEEP) this.chunks.delete(this.chunks.keys().next().value);
|
|
return bytes;
|
|
}, (e) => { this.chunks.delete(index); throw e; });
|
|
this.chunks.set(index, p);
|
|
return p;
|
|
}
|
|
|
|
/** the byte at an offset, or undefined while its chunk is being read (it asks for it) */
|
|
byte(offset) {
|
|
const index = Math.floor(offset / CHUNK);
|
|
const c = this.chunks.get(index);
|
|
if (c && !(c instanceof Promise)) { this.chunks.delete(index); this.chunks.set(index, c); return c[offset - index * CHUNK]; }
|
|
if (!c) this.chunk(index).then(() => this.draw()).catch(() => null);
|
|
return undefined;
|
|
}
|
|
|
|
draw() {
|
|
if (!this.size && !this.chunks.size) return;
|
|
const view = this.scroller.clientHeight;
|
|
const count = Math.ceil(view / ROW) + 1;
|
|
const first = Math.max(0, Math.min(this.firstLine(), this.lines - 1));
|
|
const space = Math.min(this.lines * ROW, MAX_SPACE);
|
|
const top = this.lines * ROW <= MAX_SPACE ? first * ROW : this.scroller.scrollTop;
|
|
this.rows.style.top = top + 'px';
|
|
// never taller than the room left: the lines drawn must not make the scroll longer
|
|
this.rows.style.height = Math.max(ROW, Math.min(count * ROW, space - top)) + 'px';
|
|
this.rows.style.overflow = 'hidden';
|
|
const width = Math.max(8, hex(Math.max(0, this.size - 1), 1).length);
|
|
const out = document.createDocumentFragment();
|
|
for (let line = first; line < Math.min(this.lines, first + count); line++) {
|
|
const row = make('div', 'hexv-row');
|
|
const hexes = make('span', 'hexv-hex');
|
|
const chars = make('span', 'hexv-asc');
|
|
row.append(make('span', 'hexv-off', hex(line * PER, width)), hexes, chars);
|
|
for (let i = 0; i < PER; i++) {
|
|
const o = line * PER + i;
|
|
if (o >= this.size) { hexes.append(make('b', i === 7 ? 'gap' : '', ' ')); continue; }
|
|
const b = this.byte(o);
|
|
const cls = (b === undefined ? 'wait' : b === 0 ? 'z' : '') + (o === this.selected ? ' sel' : '');
|
|
const h = make('b', cls + (i === 7 ? ' gap' : ''), b === undefined ? '··' : hex(b, 2));
|
|
const c = make('b', cls, b === undefined ? '·' : shown(b));
|
|
h.dataset.o = c.dataset.o = o;
|
|
hexes.append(h);
|
|
chars.append(c);
|
|
}
|
|
out.append(row);
|
|
}
|
|
this.rows.replaceChildren(out);
|
|
}
|
|
|
|
select(offset, reveal = true) {
|
|
if (!this.size) return;
|
|
this.selected = Math.max(0, Math.min(this.size - 1, offset));
|
|
if (reveal) {
|
|
const line = Math.floor(this.selected / PER);
|
|
const first = this.firstLine();
|
|
const visible = Math.max(1, Math.floor(this.scroller.clientHeight / ROW) - 1);
|
|
if (line < first || line >= first + visible) this.scrollToLine(Math.max(0, line - Math.floor(visible / 3)));
|
|
}
|
|
this.draw();
|
|
this.describe();
|
|
this.scroller.focus({ preventScroll: true });
|
|
}
|
|
|
|
/** the selected byte: its offset, its value in decimal / hexadecimal / binary, its character */
|
|
describe() {
|
|
const size = `${this.size.toLocaleString()} ${t('bytes')}`;
|
|
if (this.selected < 0) { this.info.textContent = size; return; }
|
|
const o = this.selected;
|
|
const b = this.byte(o);
|
|
if (b === undefined) { this.chunk(Math.floor(o / CHUNK)).then(() => this.describe()).catch(() => null); return; }
|
|
const char = b >= 0x20 && b < 0x7f ? `'${String.fromCharCode(b)}'` : b < 0x20 ? `^${String.fromCharCode(b + 64)}` : '—';
|
|
this.info.textContent = `${t('Offset')} 0x${hex(o, 1)} (${o}) · ${t('Value')} 0x${hex(b, 2)} = ${b} = 0b${b.toString(2).padStart(8, '0')} = ${char} · ${size}`;
|
|
}
|
|
|
|
jump() {
|
|
const o = parseOffset(this.goto.value);
|
|
if (o === null) { this.info.textContent = t('Not an offset: {text}', { text: this.goto.value }); return; }
|
|
this.select(o);
|
|
}
|
|
|
|
key(e) {
|
|
const moves = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -PER, ArrowDown: PER, PageUp: -PER * 32, PageDown: PER * 32 };
|
|
if (e.key in moves) { e.preventDefault(); this.select(Math.max(0, this.selected) + moves[e.key]); }
|
|
else if (e.key === 'Home' && e.ctrlKey) { e.preventDefault(); this.select(0); }
|
|
else if (e.key === 'End' && e.ctrlKey) { e.preventDefault(); this.select(this.size - 1); }
|
|
else if (e.key === 'g' && e.ctrlKey) { e.preventDefault(); this.goto.focus(); this.goto.select(); }
|
|
}
|
|
}
|
|
|
|
/** base64 of a file's bytes from the IDE's backend (file.bytes, a project path) or the quick editor's (quick.bytes, a path of the disk) */
|
|
export const bytesReader = (backend, command, path) => (offset, length) => backend.invoke(command, { path, offset, length });
|