Implement tab indentation and list continuation in the new editor (#3848, #3849) (#4072)

This overrides handling of Tab and Enter keys in the ComboMarkdownEditor, so that:

* Pressing Tab prepending 4 spaces to the line under cursor, or all the lines in the selection.
* Pressing Shift+Tab removes up to 4 spaces.
* Pressing Enter repeats any indentation and a "repeatable" prefix (list or blockquote) from the current line.

Since Tab "capture" can interfere with keyboard navigation, it's only done if there was any previous input in the textarea or if it was selected with a pointer. Additionally, presing Esc will make the textarea lose focus, resuming tab navigation. This seems adequate to me, but I might be wrong.

Had to use the "deprecated" execCommand method, since anything else I tried messes up the undo history. There's a fallback for when (if?) it's actually removed.

Only tested in desktop Firefox and Chrome so far.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/4072
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Reviewed-by: Beowulf <beowulf@noreply.codeberg.org>
Co-authored-by: Danko Aleksejevs <danko@very.lv>
Co-committed-by: Danko Aleksejevs <danko@very.lv>
This commit is contained in:
Danko Aleksejevs 2024-06-15 13:40:31 +00:00 committed by Earl Warren
parent aa20248c83
commit 221ca0c404
3 changed files with 294 additions and 0 deletions

View file

@ -84,10 +84,36 @@ class ComboMarkdownEditor {
if (el.nodeName === 'BUTTON' && !el.getAttribute('type')) el.setAttribute('type', 'button');
}
// Track whether any actual input or pointer action was made after focusing, and only intercept Tab presses after that.
this.interceptTab = false;
this.textarea.addEventListener('focus', () => {
this.interceptTab = false;
});
this.textarea.addEventListener('pointerup', () => {
// Assume if a pointer is used then Tab handling is a bit less of an issue.
this.interceptTab = true;
});
this.textarea.addEventListener('keydown', (e) => {
if (e.shiftKey) {
e.target._shiftDown = true;
}
const unmodified = !e.shiftKey && !e.ctrlKey && !e.altKey;
if (e.key === 'Escape') {
// Explicitly lose focus and reenable tab navigation.
e.target.blur();
this.interceptTab = false;
} else if (e.key === 'Tab' && this.interceptTab && !e.altKey && !e.ctrlKey) {
this.indentSelection(e.shiftKey);
this.options?.onContentChanged?.(this, e);
e.preventDefault();
} else if (e.key === 'Enter' && unmodified) {
if (this.breakLine()) {
this.options?.onContentChanged?.(this, e);
e.preventDefault();
}
} else {
this.interceptTab ||= unmodified;
}
});
this.textarea.addEventListener('keyup', (e) => {
if (!e.shiftKey) {
@ -288,6 +314,90 @@ class ComboMarkdownEditor {
}
}
indentSelection(unindent) {
// Indent with 4 spaces, unindent 4 spaces or fewer or a lost tab.
const indentPrefix = ' ';
const unindentRegex = /^( {1,4}|\t)/;
// Indent all lines that are included in the selection, partially or whole, while preserving the original selection at the end.
const lines = this.textarea.value.split('\n');
const changedLines = [];
// The current selection or cursor position.
const [start, end] = [this.textarea.selectionStart, this.textarea.selectionEnd];
// The range containing whole lines that will effectively be replaced.
let [editStart, editEnd] = [start, end];
// The range that needs to be re-selected to match previous selection.
let [newStart, newEnd] = [start, end];
// The start and end position of the current line (where end points to the newline or EOF)
let [lineStart, lineEnd] = [0, 0];
for (const line of lines) {
lineEnd = lineStart + line.length + 1;
if (lineEnd <= start) {
lineStart = lineEnd;
continue;
}
const updated = unindent ? line.replace(unindentRegex, '') : indentPrefix + line;
changedLines.push(updated);
const move = updated.length - line.length;
if (start >= lineStart && start < lineEnd) {
editStart = lineStart;
newStart = Math.max(start + move, lineStart);
}
newEnd += move;
editEnd = lineEnd - 1;
lineStart = lineEnd;
if (lineStart > end) break;
}
// Update changed lines whole.
const text = changedLines.join('\n');
this.textarea.setSelectionRange(editStart, editEnd);
if (!document.execCommand('insertText', false, text)) {
// execCommand is deprecated, but setRangeText (and any other direct value modifications) erases the native undo history.
// So only fall back to it if execCommand fails.
this.textarea.setRangeText(text);
}
// Set selection to (effectively) be the same as before.
this.textarea.setSelectionRange(newStart, Math.max(newStart, newEnd));
}
breakLine() {
const [start, end] = [this.textarea.selectionStart, this.textarea.selectionEnd];
// Do nothing if a range is selected
if (start !== end) return false;
const value = this.textarea.value;
// Find the beginning of the current line.
const lineStart = Math.max(0, value.lastIndexOf('\n', start - 1) + 1);
// Find the end and extract the line.
const lineEnd = value.indexOf('\n', start);
const line = value.slice(lineStart, lineEnd < 0 ? value.length : lineEnd);
// Match any whitespace at the start + any repeatable prefix + exactly one space after.
const prefix = line.match(/^\s*((\d+)[.)]\s|[-*+]\s+(\[[ x]\]\s?)?|(>\s+)+)?/);
// Defer to browser if we can't do anything more useful, or if the cursor is inside the prefix.
if (!prefix || !prefix[0].length || lineStart + prefix[0].length > start) return false;
// Insert newline + prefix.
let text = `\n${prefix[0]}`;
// Increment a number if present. (perhaps detecting repeating 1. and not doing that then would be a good idea)
const num = text.match(/\d+/);
if (num) text = text.replace(num[0], Number(num[0]) + 1);
text = text.replace('[x]', '[ ]');
if (!document.execCommand('insertText', false, text)) {
this.textarea.setRangeText(text);
}
return true;
}
get userPreferredEditor() {
return window.localStorage.getItem(`markdown-editor-${this.options.useScene ?? 'default'}`);
}