I am trying to implement a way to add a TAB character (or even multiple spacebar characters) when the TAB key is pressed while editing a Textbox.
Unfortunately, I have two solutions and neither seems to work. They result in the same unintended behavior: Hitting TAB initially seems to work, until you add any other character during the edit, at which point all of the characters added by the TAB key have been reverted.
I’m not sure why this is happening or what a fix could be. I tried digging into the internal private methods and have not found anything that seems to cause this yet.
While I’m here, a bonus would be if someone could help me get the TAB character to actually appear with a character width of 4. Currently, the tab character looks identical to a regular space when inside the Textbox.
ctx = canvasEl.getContext('2d');
canvas = new fabric.Canvas('c');
var textbox_options = {
editable: true,
hasBorders: false,
hasControls: false,
lockMovementX: true,
lockMovementY: true,
};
var text = new fabric.Textbox('some text', textbox_options);
canvas.add(text);
canvas.requestRenderAll();
function addTab(textbox) {
var t = textbox.text;
var selStart = textbox.selectionStart;
textbox.set('text', t.substring(0, selStart) + 't' + t.substring(selStart, t.length));
textbox.setSelectionStart(selStart+1);
textbox.setSelectionEnd(selStart);
}
// solution 1
fabric.Textbox.prototype["insertTabChar"] = function (e) {
addTab(this);
}
text.keysMap[9] = "insertTabChar";
// solution 2
this.addEventListener('keydown', event => {
if (event.code == "Tab") {
event.preventDefault();
}
})
fabric.IText.prototype.onKeyDown = (function(onKeyDown) {
return function(e) {
if (e.keyCode == 9) {
addTab(this);
canvas.requestRenderAll();
}
onKeyDown.call(this, e);
}
})(fabric.IText.prototype.onKeyDown);