UNPKG

imask

Version:

vanilla javascript input mask

78 lines (61 loc) 2.23 kB
import { DIRECTION } from './utils.js'; /** Provides details of changing input */ class ActionDetails { /** Current input value */ /** Current cursor position */ /** Old input value */ /** Old selection */ constructor(opts) { Object.assign(this, opts); // double check if left part was changed (autofilling, other non-standard input triggers) while (this.value.slice(0, this.startChangePos) !== this.oldValue.slice(0, this.startChangePos)) { --this.oldSelection.start; } if (this.insertedCount) { // double check right part while (this.value.slice(this.cursorPos) !== this.oldValue.slice(this.oldSelection.end)) { if (this.value.length - this.cursorPos < this.oldValue.length - this.oldSelection.end) ++this.oldSelection.end;else ++this.cursorPos; } } } /** Start changing position */ get startChangePos() { return Math.min(this.cursorPos, this.oldSelection.start); } /** Inserted symbols count */ get insertedCount() { return this.cursorPos - this.startChangePos; } /** Inserted symbols */ get inserted() { return this.value.substr(this.startChangePos, this.insertedCount); } /** Removed symbols count */ get removedCount() { // Math.max for opposite operation return Math.max(this.oldSelection.end - this.startChangePos || // for Delete this.oldValue.length - this.value.length, 0); } /** Removed symbols */ get removed() { return this.oldValue.substr(this.startChangePos, this.removedCount); } /** Unchanged head symbols */ get head() { return this.value.substring(0, this.startChangePos); } /** Unchanged tail symbols */ get tail() { return this.value.substring(this.startChangePos + this.insertedCount); } /** Remove direction */ get removeDirection() { if (!this.removedCount || this.insertedCount) return DIRECTION.NONE; // align right if delete at right return (this.oldSelection.end === this.cursorPos || this.oldSelection.start === this.cursorPos) && // if not range removed (event with backspace) this.oldSelection.end === this.oldSelection.start ? DIRECTION.RIGHT : DIRECTION.LEFT; } } export { ActionDetails as default };