diff --git a/codetab.ts b/codetab.ts index 4d18ea5..68bbb18 100644 --- a/codetab.ts +++ b/codetab.ts @@ -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); diff --git a/mouse.ts b/mouse.ts index 77a368d..fa58888 100644 --- a/mouse.ts +++ b/mouse.ts @@ -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"); }