Anki/ts/domlib/location/location.ts
Henrik Giesel 610ef8f043
Save and restore location on ContentEditable (#1481)
* Add utility functions for saving and restoring the caret location

* Implement cross-browser.getSelection

* Save and restore location on ContentEditable

* Fix refocus by clicking on a field that had a non-collapsed selection
2021-11-09 12:53:39 +10:00

40 lines
1.3 KiB
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
export interface CaretLocation {
coordinates: number[];
offset: number;
}
export enum Order {
LessThan,
Equal,
GreaterThan,
}
export function compareLocations(first: CaretLocation, second: CaretLocation): Order {
const smallerLength = Math.min(first.coordinates.length, second.coordinates.length);
for (let i = 0; i <= smallerLength; i++) {
if (first.coordinates.length === i) {
if (second.coordinates.length === i) {
if (first.offset < second.offset) {
return Order.LessThan;
} else if (first.offset > second.offset) {
return Order.GreaterThan;
} else {
return Order.Equal;
}
}
return Order.LessThan;
} else if (second.coordinates.length === i) {
return Order.GreaterThan;
} else if (first.coordinates[i] < second.coordinates[i]) {
return Order.LessThan;
} else if (first.coordinates[i] > second.coordinates[i]) {
return Order.GreaterThan;
}
}
throw new Error("compareLocations: Should never happen");
}