Skip to content

Commit

Permalink
Add Edit#move to edit caret position programmatically
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Apr 10, 2021
1 parent 8bda982 commit 15cea68
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions src/useEditable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,6 @@ const makeRange = (
return range;
};

interface Options {
disabled?: boolean;
indentation?: number;
}

interface State {
observer: MutationObserver;
disconnected: boolean;
Expand All @@ -158,11 +153,18 @@ interface State {
position: Position | null;
}

interface Edit {
export interface Options {
disabled?: boolean;
indentation?: number;
}

export interface Edit {
/** Replaces the entire content of the editable while adjusting the caret position. */
update(content: string): void;
/** Inserts new text at the caret position while deleting text in range of the offset (which accepts negative offsets). */
insert(append: string, offset?: number): void;
/** Positions the caret where specified */
move(pos: number | { row: number; column: number }): void;
}

export const useEditable = (
Expand Down Expand Up @@ -221,6 +223,22 @@ export const useEditable = (
setCurrentRange(makeRange(element, start + append.length));
}
},
move(pos: number | { row: number; column: number }) {
const { current: element } = elementRef;
if (element) {
element.focus();
let position: number;
if (typeof pos === 'number') {
position = pos;
} else {
const lines = toString(element).split('\n');
const before = lines.slice(0, pos.row).join('\n');
position = before.length + pos.column;
}

setCurrentRange(makeRange(element, position));
}
},
}),
[]
);
Expand Down

0 comments on commit 15cea68

Please sign in to comment.