UNPKG

@uiw/react-textarea-code-editor

Version:
91 lines 2.62 kB
export class SelectionText { constructor(elm) { this.elm = void 0; this.start = void 0; this.end = void 0; this.value = void 0; var { selectionStart, selectionEnd } = elm; this.elm = elm; this.start = selectionStart; this.end = selectionEnd; this.value = this.elm.value; } position(start, end) { var { selectionStart, selectionEnd } = this.elm; this.start = typeof start === 'number' && !isNaN(start) ? start : selectionStart; this.end = typeof end === 'number' && !isNaN(end) ? end : selectionEnd; this.elm.selectionStart = this.start; this.elm.selectionEnd = this.end; return this; } insertText(text) { // Most of the used APIs only work with the field selected this.elm.focus(); this.elm.setRangeText(text); this.value = this.elm.value; this.position(); return this; } getSelectedValue(start, end) { var { selectionStart, selectionEnd } = this.elm; return this.value.slice(typeof start === 'number' && !isNaN(start) ? start : selectionStart, typeof end === 'number' && !isNaN(end) ? start : selectionEnd); } getLineStartNumber() { var start = this.start; while (start > 0) { start--; if (this.value.charAt(start) === '\n') { start++; break; } } return start; } /** Indent on new lines */ getIndentText() { var start = this.getLineStartNumber(); var str = this.getSelectedValue(start); var indent = ''; str.replace(/(^(\s)+)/, (str, old) => indent = old); return indent; } lineStarInstert(text) { if (text) { var oldStart = this.start; var start = this.getLineStartNumber(); var str = this.getSelectedValue(start); this.position(start, this.end).insertText(str.split('\n').map(txt => text + txt).join('\n')).position(oldStart + text.length, this.end); } return this; } lineStarRemove(text) { if (text) { var oldStart = this.start; var start = this.getLineStartNumber(); var str = this.getSelectedValue(start); var reg = new RegExp("^" + text, 'g'); var newStart = oldStart - text.length; if (!reg.test(str)) { newStart = oldStart; } this.position(start, this.end).insertText(str.split('\n').map(txt => txt.replace(reg, '')).join('\n')).position(newStart, this.end); } } /** Notify any possible listeners of the change */ notifyChange() { var event = new Event('input', { bubbles: true, cancelable: false }); this.elm.dispatchEvent(event); } }