Skip to content

Commit

Permalink
refactor(imgui): update textField() key/cursor handling
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Sep 19, 2020
1 parent ff2b318 commit 27889d3
Showing 1 changed file with 16 additions and 68 deletions.
84 changes: 16 additions & 68 deletions packages/imgui/src/components/textfield.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ import { IMGUI } from "../gui";
import { textLabelRaw } from "./textlabel";
import { tooltipRaw } from "./tooltip";

interface TextfieldState {
cursor: number;
offset: number;
}

export const textField = (
gui: IMGUI,
layout: IGridLayout | LayoutBox,
Expand Down Expand Up @@ -104,6 +99,16 @@ export const textFieldRaw = (
[xx, y + h - 4],
]);
}

const move = (next: number, delta: number) => {
state.cursor = next;
if (drawCursor + delta < 0) {
state.offset = Math.max(offset + delta, 0);
} else if (drawCursor + delta > maxLen) {
state.offset = Math.min(offset + delta, maxOffset);
}
};

const k = gui.key;
switch (k) {
case "":
Expand All @@ -118,15 +123,7 @@ export const textFieldRaw = (
const next = gui.isAltDown()
? prevNonAlpha(txt, cursor - 1)
: cursor - 1;
move(
state,
next,
next - cursor,
drawCursor,
offset,
maxLen,
maxOffset
);
move(next, next - cursor);
return txt.substr(0, next) + txt.substr(cursor);
}
break;
Expand All @@ -143,58 +140,26 @@ export const textFieldRaw = (
const next = gui.isAltDown()
? prevNonAlpha(txt, cursor - 1)
: cursor - 1;
move(
state,
next,
next - cursor,
drawCursor,
offset,
maxLen,
maxOffset
);
move(next, next - cursor);
}
break;
case Key.RIGHT:
if (cursor < txtLen) {
const next = gui.isAltDown()
? nextNonAlpha(txt, cursor + 1)
: cursor + 1;
move(
state,
next,
next - cursor,
drawCursor,
offset,
maxLen,
maxOffset
);
move(next, next - cursor);
}
break;
case Key.HOME:
move(state, 0, -cursor, drawCursor, offset, maxLen, maxOffset);
move(0, -cursor);
break;
case Key.END:
move(
state,
txtLen,
txtLen - cursor,
drawCursor,
offset,
maxLen,
maxOffset
);
move(txtLen, txtLen - cursor);
break;
default: {
if (k.length === 1 && filter(k)) {
move(
state,
cursor + 1,
1,
drawCursor,
offset,
maxLen,
maxOffset
);
move(cursor + 1, 1);
return txt.substr(0, cursor) + k + txt.substr(cursor);
}
}
Expand All @@ -217,20 +182,3 @@ const prevNonAlpha = (src: string, i: number) => {
for (; i > 0 && !WS.test(src[i]); i--) {}
return i;
};

const move = (
state: TextfieldState,
next: number,
delta: number,
drawCursor: number,
offset: number,
maxLen: number,
maxOffset: number
) => {
state.cursor = next;
if (drawCursor + delta < 0) {
state.offset = Math.max(offset + delta, 0);
} else if (drawCursor + delta > maxLen) {
state.offset = Math.min(offset + delta, maxOffset);
}
};

0 comments on commit 27889d3

Please sign in to comment.