imask
Version:
vanilla javascript input mask
55 lines (49 loc) • 1.83 kB
JavaScript
import HTMLMaskElement from './html-mask-element.js';
import IMask from '../core/holder.js';
import './mask-element.js';
class HTMLContenteditableMaskElement extends HTMLMaskElement {
/** Returns HTMLElement selection start */
get _unsafeSelectionStart() {
const root = this.rootElement;
const selection = root.getSelection && root.getSelection();
const anchorOffset = selection && selection.anchorOffset;
const focusOffset = selection && selection.focusOffset;
if (focusOffset == null || anchorOffset == null || anchorOffset < focusOffset) {
return anchorOffset;
}
return focusOffset;
}
/** Returns HTMLElement selection end */
get _unsafeSelectionEnd() {
const root = this.rootElement;
const selection = root.getSelection && root.getSelection();
const anchorOffset = selection && selection.anchorOffset;
const focusOffset = selection && selection.focusOffset;
if (focusOffset == null || anchorOffset == null || anchorOffset > focusOffset) {
return anchorOffset;
}
return focusOffset;
}
/** Sets HTMLElement selection */
_unsafeSelect(start, end) {
if (!this.rootElement.createRange) return;
const range = this.rootElement.createRange();
range.setStart(this.input.firstChild || this.input, start);
range.setEnd(this.input.lastChild || this.input, end);
const root = this.rootElement;
const selection = root.getSelection && root.getSelection();
if (selection) {
selection.removeAllRanges();
selection.addRange(range);
}
}
/** HTMLElement value */
get value() {
return this.input.textContent || '';
}
set value(value) {
this.input.textContent = value;
}
}
IMask.HTMLContenteditableMaskElement = HTMLContenteditableMaskElement;
export { HTMLContenteditableMaskElement as default };