Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions src/web/EditMenu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import type { Rect } from '../types';

export type MenuActions = {
canCut(): boolean;
canCopy(): boolean;
canPaste(): boolean;
cut(): void;
copy(): void;
paste(): void;
selectAll(): void;
};

export type MenuTheme = { background: string; foreground: string; border: string };

type Item = { label: string; enabled(): boolean; run(): void; keepsMenu: boolean };

// The space between the menu and what it points at.
const GAP = 8;

// One menu shows on the page at a time.
let active: EditMenu | null = null;

// The floating Cut, Copy, Paste and Select all bar, fixed on the page so it can leave the editor's box.
export class EditMenu {
private readonly el = document.createElement('div');
private readonly items: Item[];
private isShown = false;
private labels = '';
private size = { width: 0, height: 0 };
private themed = '';

constructor(actions: MenuActions) {
this.items = [
{ label: 'Cut', enabled: () => actions.canCut(), run: () => actions.cut(), keepsMenu: false },
{
label: 'Copy',
enabled: () => actions.canCopy(),
run: () => actions.copy(),
keepsMenu: false,
},
{
label: 'Paste',
enabled: () => actions.canPaste(),
run: () => actions.paste(),
keepsMenu: false,
},
{ label: 'Select all', enabled: () => true, run: () => actions.selectAll(), keepsMenu: true },
];
this.el.dataset.codepadMenu = '';
this.el.style.cssText =
'position:fixed;left:0;top:0;display:none;z-index:2147483647;border-radius:8px;overflow:hidden;' +
'box-shadow:0 2px 8px rgba(0,0,0,0.25);font:14px system-ui;user-select:none;-webkit-user-select:none;' +
'-webkit-touch-callout:none;white-space:nowrap;';
// The textarea keeps the focus, so Copy and Cut act on the editor's selection.
for (const type of ['pointerdown', 'mousedown'])
this.el.addEventListener(type, (e) => e.preventDefault());
this.el.addEventListener('click', (e) => {
const button = (e.target as Element).closest('button');
const item = this.items.find((i) => i.label === button?.textContent);
if (!item) return;
if (!item.keepsMenu) this.hide();
item.run();
});
document.body.append(this.el);
}

get shown(): boolean {
return this.isShown;
}

show(): void {
if (active && active !== this) active.hide();
active = this;
this.isShown = true;
}

hide(): void {
this.isShown = false;
if (active === this) active = null;
this.el.style.display = 'none';
}

// Places the menu above the anchor, or below when the visible area has no room above. Both in page coordinates.
place(anchor: Rect | null, visible: Rect, theme: MenuTheme): void {
const out =
!anchor ||
anchor.y + anchor.height < visible.y ||
anchor.y > visible.y + visible.height ||
anchor.x + anchor.width < visible.x ||
anchor.x > visible.x + visible.width;
if (!this.isShown || out) {
this.el.style.display = 'none';
return;
}
this.theme(theme);
this.build();
const { width, height } = this.size;
let top = anchor.y - GAP - height;
if (top < visible.y) top = anchor.y + anchor.height + GAP;
const centre = anchor.x + anchor.width / 2;
const left = Math.max(
visible.x,
Math.min(centre - width / 2, visible.x + visible.width - width),
);
this.el.style.left = `${Math.round(left)}px`;
this.el.style.top = `${Math.round(top)}px`;
}

destroy(): void {
this.hide();
this.el.remove();
}

// The buttons of the actions that apply now, measured again only when that set changes.
private build(): void {
const items = this.items.filter((i) => i.enabled());
const labels = items.map((i) => i.label).join('\n');
this.el.style.display = 'flex';
if (labels === this.labels) return;
this.labels = labels;
this.el.replaceChildren(
...items.map((item) => {
const button = document.createElement('button');
button.type = 'button';
button.textContent = item.label;
button.style.cssText =
'height:44px;padding:0 16px;border:0;margin:0;background:transparent;color:inherit;font:inherit;cursor:pointer;';
return button;
}),
);
this.size = { width: this.el.offsetWidth, height: this.el.offsetHeight };
}

private theme(t: MenuTheme): void {
const key = `${t.background} ${t.foreground} ${t.border}`;
if (key === this.themed) return;
this.themed = key;
this.el.style.background = t.background;
this.el.style.color = t.foreground;
this.el.style.border = `1px solid ${t.border}`;
this.labels = '';
}
}
107 changes: 101 additions & 6 deletions src/web/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ import { EditorCore, type MoveUnit, type WebChange } from './core/EditorCore';
import { Layout } from './core/Layout';
import type { CoreModule } from './core/module';
import { measureBaseline, solidTop, waveAmplitude, wavePath } from './decorations';
import { EditMenu } from './EditMenu';
import { type DecodedFrame, decodeFrame } from './frame';
import { type HandleEnds, Handles } from './Handles';
import { HANDLE_HEIGHT, type HandleEnds, Handles } from './Handles';
import { CaretMover, type LineGeometry } from './input/CaretMover';
import type { HandleKind } from './input/GestureMachine';
import { InputHost } from './input/InputHost';
Expand Down Expand Up @@ -256,6 +257,9 @@ export class EditorView {
};
private readonly pointer: PointerHost;
private readonly handles: Handles;
private readonly menu: EditMenu;
// Where a right click opened the menu, which then stays at the pointer.
private menuAt: { x: number; y: number } | null = null;
// True while the last pointer down on the editor was touch or pen: only then do handles show.
private touchMode = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches;
private insertionShown = false;
Expand All @@ -271,7 +275,7 @@ export class EditorView {
const beside =
target === s && e.clientX < r.left + s.clientWidth && e.clientY < r.top + s.clientHeight;
const inside = this.textLayer.contains(target) || this.gutter.contains(target) || beside;
if (e.button !== 0 || !inside) return;
if ((e.button !== 0 && e.button !== 2) || !inside) return;
e.preventDefault();
this.pointer.press(e);
};
Expand Down Expand Up @@ -310,6 +314,8 @@ export class EditorView {
keyDown: (e) => this.keyDown(e),
clipboard: (cut) => this.clipboard(cut),
focusChanged: (focused) => {
// Chrome blurs the textarea during a long press, and the release focuses it again.
if (!focused && !this.pointer.holdsTouch) this.hideMenu();
this.safely(() => (focused ? this.o.onFocus?.() : this.o.onBlur?.()));
this.invalidate();
},
Expand Down Expand Up @@ -342,8 +348,26 @@ export class EditorView {
endHandleDrag: () => {
this.handleDrag = null;
this.handles.dragging = false;
this.invalidate();
this.showMenu();
},
showMenu: (at) => this.showMenu(at),
hideMenu: () => this.hideMenu(),
});
this.menu = new EditMenu({
canCut: () => !this.o.readOnly && this.selectedText() !== '',
canCopy: () => this.selectedText() !== '',
canPaste: () =>
!this.o.readOnly &&
typeof navigator !== 'undefined' &&
typeof navigator.clipboard?.readText === 'function',
cut: () => {
if (!this.input.execute('cut')) this.clipboardFailed(this.cutSelection());
},
copy: () => {
if (!this.input.execute('copy')) this.clipboardFailed(this.copySelection());
},
paste: () => this.clipboardFailed(this.pasteClipboard()),
selectAll: () => this.apply(() => this.core.selectAll()),
});
this.handles = new Handles(this.textLayer);
// The browser keeps panning and pinch zoom, the editor takes taps and long presses.
Expand Down Expand Up @@ -436,7 +460,10 @@ export class EditorView {
if (outside) this.session.external();
edit();
const changes = this.core.takeChanges();
if (changes.length) this.hideInsertion();
if (changes.length) {
this.hideInsertion();
this.hideMenu();
}
for (const change of changes) {
this.search.onChange(change);
this.changed(change, changes.length);
Expand Down Expand Up @@ -534,6 +561,7 @@ export class EditorView {
const { anchor, head } = this.core.selection;
const fixed = kind === 'start' ? Math.max(anchor, head) : Math.min(anchor, head);
this.handleDrag = { dy: y - this.handles.top(kind), fixed };
this.hideMenu();
this.handles.dragging = true;
return kind;
}
Expand All @@ -552,6 +580,59 @@ export class EditorView {
this.showInsertion();
}

private showMenu(at?: { x: number; y: number }): void {
this.menuAt = at ?? null;
this.menu.show();
this.invalidate();
}

private hideMenu(): void {
if (!this.menu.shown) return;
this.menu.hide();
this.menuAt = null;
}

// The menu's anchor in page coordinates: a right click's pointer, else the ends in view and, as Android, the handles under them.
private menuAnchor(from: number, to: number, rootBox: DOMRect, handles: boolean): Rect | null {
if (this.menuAt) return { ...this.menuAt, width: 0, height: 0 };
const view = this.visibleBox();
let out: Rect | null = null;
for (const offset of from === to ? [from] : [from, to]) {
const r = this.caretRect(offset, rootBox);
if (!r) continue;
const x = r.x + rootBox.left;
const y = r.y + rootBox.top;
if (y + r.height <= view.top || y >= view.bottom || x < view.left - 1 || x > view.right + 1)
continue;
if (!out) {
out = { x, y, width: 1, height: r.height };
continue;
}
const left = Math.min(out.x, x);
const top = Math.min(out.y, y);
const right = Math.max(out.x + out.width, x + 1);
const bottom = Math.max(out.y + out.height, y + r.height);
out = { x: left, y: top, width: right - left, height: bottom - top };
}
if (out && handles) out.height += HANDLE_HEIGHT;
return out;
}

// The editor's box where it meets the visual viewport, which the keyboard can shrink and pan.
private menuArea(rootBox: DOMRect): Rect {
const vv = typeof visualViewport === 'undefined' ? null : visualViewport;
const top = Math.max(rootBox.top, vv ? vv.offsetTop : 0);
const bottom = Math.min(rootBox.bottom, vv ? vv.offsetTop + vv.height : innerHeight);
const left = Math.max(rootBox.left, vv ? vv.offsetLeft : 0);
const right = Math.min(rootBox.right, vv ? vv.offsetLeft + vv.width : innerWidth);
return { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) };
}

// A menu action the clipboard refused, reported without failing the page.
private clipboardFailed(action: Promise<void>): void {
action.catch((e) => console.warn('[codepad]', e));
}

// The handles a touch shows, each at its end's row in the text layer, read before the draw writes.
private handleEnds(from: number, to: number, rootBox: DOMRect, layer: DOMRect): HandleEnds {
if (!this.touchMode || !(this.input.focused || this.pointer.holdsTouch)) return {};
Expand Down Expand Up @@ -684,6 +765,7 @@ export class EditorView {

// Runs an edit or a move from a key or the ref, then shows the caret.
private perform(edit: () => void): void {
this.hideMenu();
this.revealing = true;
this.apply(edit);
}
Expand Down Expand Up @@ -829,6 +911,9 @@ export class EditorView {
const writeMatches = this.planMatches(rootBox, from, to);
const writeBrackets = this.planBrackets();
const ends = this.handleEnds(from, to, rootBox, box);
const shownHandles = Object.values(ends).some(Boolean);
const menuAnchor = this.menu.shown ? this.menuAnchor(from, to, rootBox, shownHandles) : null;
const menuArea = this.menu.shown ? this.menuArea(rootBox) : null;
const layout = this.layout;
const handleArea = {
width: Math.max(
Expand Down Expand Up @@ -874,6 +959,15 @@ export class EditorView {
writeMatches();
writeBrackets();
this.handles.place(ends, this.css.cursor, handleArea);
if (menuArea) {
const css = this.css;
const theme = {
background: css.background,
foreground: css.foreground,
border: css.gutterForeground,
};
this.menu.place(menuAnchor, menuArea, theme);
}
}

// The page boxes of the document range on the lines that are drawn.
Expand Down Expand Up @@ -1316,8 +1410,8 @@ export class EditorView {
}
}
}
// A clipped long line follows the window, so a page scroll draws again.
this.listenToPage(!this.o.scrollEnabled || clipped);
// A clipped long line and the menu follow the window, so a page scroll draws again.
this.listenToPage(!this.o.scrollEnabled || clipped || this.menu.shown);
const css = this.css;
const wanted = new Map<number, string>();
for (const [line, list] of parts) {
Expand Down Expand Up @@ -1527,6 +1621,7 @@ export class EditorView {
this.offRegistered();
this.input.destroy();
this.pointer.destroy();
this.menu.destroy();
this.scroller.removeEventListener('mousedown', this.onMouseDownEvent);
this.listenToPage(false);
this.offViewport();
Expand Down
5 changes: 3 additions & 2 deletions src/web/Handles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import type { HandleKind } from './input/GestureMachine';
export type HandleEnds = { insertion?: Rect; start?: Rect; end?: Rect };

const SIZE = 22;
// A finger-sized hit area under the row, centered on the shape.
const HIT = 44;
// A finger-sized hit area under the row, centered on the shape, and how far handles reach below it.
export const HANDLE_HEIGHT = 44;
const HIT = HANDLE_HEIGHT;
// Where each shape's tip sits along its width.
const TIP: Record<HandleKind, number> = { insertion: 0.5, start: 1, end: 0 };
const SHAPES: Record<HandleKind, { path: string; height: number }> = {
Expand Down
10 changes: 10 additions & 0 deletions src/web/input/InputHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,16 @@ export class InputHost {
this.textarea.remove();
}

// Runs the browser's copy or cut on the textarea, whose events put the editor's selection on the clipboard. False when the browser refuses.
execute(command: 'copy' | 'cut'): boolean {
if (!this.focused) this.focus();
try {
return document.execCommand(command);
} catch {
return false;
}
}

// The textarea holds only a window, so the clipboard takes the editor's whole selection.
private clip(e: ClipboardEvent, cut: boolean): void {
const text = this.hooks.clipboard(cut);
Expand Down
Loading