add babycode button controls
This commit is contained in:
@@ -23,3 +23,58 @@ export function setTab(_, sender, el) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function insertBabycode(_, sender, el) {
|
||||
if (!el.parentNode.contains(sender)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const tagStart = sender.dataset.babycodeTag;
|
||||
const breakLine = 'breakLine' in sender.dataset;
|
||||
const prefill = 'prefill' in sender.dataset ? sender.dataset.prefill : '';
|
||||
|
||||
const hasAttr = tagStart[tagStart.length - 1] === '=';
|
||||
|
||||
let tagEnd = tagStart;
|
||||
let tagInsertStart = `[${tagStart}]${breakLine ? '\n' : ''}`;
|
||||
if (hasAttr) {
|
||||
tagEnd = tagEnd.slice(0, -1);
|
||||
}
|
||||
const tagInsertEnd = `${breakLine ? '\n' : ''}[/${tagEnd}]`;
|
||||
const hasSelection = el.selectionStart !== el.selectionEnd;
|
||||
const text = el.value;
|
||||
|
||||
if (hasSelection) {
|
||||
const realStart = Math.min(el.selectionStart, el.selectionEnd);
|
||||
const realEnd = Math.max(el.selectionStart, el.selectionEnd);
|
||||
const selectionLength = realEnd - realStart;
|
||||
|
||||
const strStart = text.slice(0, realStart);
|
||||
const strEnd = text.substring(realEnd);
|
||||
const frag = `${tagInsertStart}${text.slice(realStart, realEnd)}${tagInsertEnd}`;
|
||||
const reconst = `${strStart}${frag}${strEnd}`;
|
||||
el.value = reconst;
|
||||
if (!hasAttr) {
|
||||
el.setSelectionRange(realStart + tagInsertStart.length, realStart + tagInsertEnd.length + selectionLength - 1);
|
||||
} else {
|
||||
const attrCursor = realStart + tagInsertEnd.length - (1 + (breakLine ? 1 : 0))
|
||||
el.setSelectionRange(attrCursor, attrCursor); // cursor on attr
|
||||
}
|
||||
} else {
|
||||
if (hasAttr) {
|
||||
tagInsertStart += prefill;
|
||||
}
|
||||
const cursor = el.selectionStart;
|
||||
const strStart = text.slice(0, cursor);
|
||||
const strEnd = text.substring(cursor);
|
||||
|
||||
let newCursor = strStart.length + tagInsertStart.length;
|
||||
if (hasAttr) {
|
||||
newCursor = cursor + tagInsertStart.length - prefill.length - (1 + (breakLine ? 1 : 0)); //cursor on attr
|
||||
}
|
||||
const reconst = `${strStart}${tagInsertStart}${tagInsertEnd}${strEnd}`;
|
||||
el.value = reconst;
|
||||
el.setSelectionRange(newCursor, newCursor);
|
||||
}
|
||||
el.focus();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user