fix text shape contenteditable & paste handling (fixes #293)

This commit is contained in:
dwelle 2020-01-10 15:50:13 +01:00
parent f2346275ef
commit 81f23a8ccb

View File

@ -21,7 +21,7 @@ export function textWysiwyg({
// But this solution has an issue — it allows to paste // But this solution has an issue — it allows to paste
// multiline text, which is not currently supported // multiline text, which is not currently supported
const editable = document.createElement("div"); const editable = document.createElement("div");
editable.contentEditable = "plaintext-only"; editable.contentEditable = "true";
editable.tabIndex = 0; editable.tabIndex = 0;
editable.innerText = initText; editable.innerText = initText;
editable.dataset.type = "wysiwyg"; editable.dataset.type = "wysiwyg";
@ -37,7 +37,8 @@ export function textWysiwyg({
font: font, font: font,
padding: "4px", padding: "4px",
outline: "transparent", outline: "transparent",
whiteSpace: "nowrap" whiteSpace: "nowrap",
minHeight: "1em"
}); });
editable.onkeydown = ev => { editable.onkeydown = ev => {
@ -57,6 +58,14 @@ export function textWysiwyg({
} }
}; };
editable.onblur = handleSubmit; editable.onblur = handleSubmit;
// override paste to disallow non-textual data, and replace newlines
editable.onpaste = ev => {
ev.preventDefault();
try {
const text = ev.clipboardData!.getData("text").replace(/\n+/g, " ");
editable.textContent = text;
} catch {}
};
function stopEvent(ev: Event) { function stopEvent(ev: Event) {
ev.stopPropagation(); ev.stopPropagation();
@ -72,6 +81,7 @@ export function textWysiwyg({
function cleanup() { function cleanup() {
editable.onblur = null; editable.onblur = null;
editable.onkeydown = null; editable.onkeydown = null;
editable.onpaste = null;
window.removeEventListener("wheel", stopEvent, true); window.removeEventListener("wheel", stopEvent, true);
document.body.removeChild(editable); document.body.removeChild(editable);
} }