Add basic mouse support in code editor

This commit is contained in:
dylan 2023-05-08 22:20:58 -07:00
parent a7ed7b87f2
commit e5276de775
2 changed files with 18 additions and 2 deletions

View File

@ -7,6 +7,7 @@ import { K, ctrlKeyDown, getKeyboardString, keyPressed, shiftKeyDown } from "./k
import { clipboard, tokenize } from "./deps.ts";
import { getBuiltins } from "./runcode.ts";
import { page } from "./viewsheets.ts";
import { mouseDown, mouseHeld, mousePos } from "./mouse.ts";
const historyDebounceFrames = 20;
@ -433,10 +434,13 @@ const pixelToIndex = (str: string, x: number, y: number) => {
const prefix = lines.slice(0, yy).join("\n").length+(yy === 0 ? 0 : 1);
const line = lines[yy];
let j = 0;
while (measureText(line.slice(0, j))+1 < x && j < line.length) {
while (measureText(line.slice(0, j)) < x && j < line.length) {
j+=1;
}
return prefix + j;
if (measureText(line) < x) {
j+=1;
}
return prefix + Math.max(0, j-1);
}
const update = async () => {
@ -451,6 +455,14 @@ const update = async () => {
}
}
if (mouseDown()) {
const {x, y} = mousePos();
state.setSelection(pixelToIndex(state.code, x, y-8));
} else if (mouseHeld()) {
const {x, y} = mousePos();
state.setFocus(pixelToIndex(state.code, x, y-8));
}
const keyboardString = getKeyboardString();
if (keyboardString) {
state.insertText(keyboardString);

View File

@ -79,6 +79,10 @@ export const refreshMouse = () => {
mouseEvents.length = 0;
}
export const mouseDown = (button: number = M.LEFT) => {
return mouseEvents.some(ev => ev.button === button && ev.type === "down");
}
export const mouseClick = (button: number = M.LEFT) => {
return mouseEvents.some(ev => ev.button === button && ev.type === "click");
}