If I had added animation, that would be a lot more code. So let's move on to the text formatter. So this text formatter is something I built on my personal site, you can check it out if you want. It works kind of like Grammarly, where you can enter some text, and if there's any sort of error, it highlights it. I haven't added hover support in the live version, just as an FYI. But you're probably wondering how the heck does this work? Or how do things like this, like Grammarly, or even the carbon code, image exporter work? Well, they work on this concept of layers. So you'll see that in just a moment once I'm done typing in this.
So if I expand the layers, we can see that there's actually two layers. There's an input layer, and there's a highlight layer, the input layer sits on top. And that's the layer that the user is interacting with that you're typing into. But the layer below that is the highlight layer, which actually has the elements with the CSS applied for the highlighting. So if we take a look at some code, we'll notice, again, like I just mentioned, there's two layers, there's a highlight layer, and there's a text area, which is the input layer element. Now, the reason why we have to have two layers is because it's hard in this previous way, or this old way, to apply styles in the same element that the user is actively typing within without causing some weird jank behavior. So that's why you have to maintain two separate layers.
Now, since we have two layers, we have to keep them in sync. And since the user is only interacting with one of them, we have to add an event listener, at least one, probably more than this. So here we have a scroll event listener, which when the user scrolls on the text area, we have to change the scroll positioning of the highlight layer to make sure that they stay in sync. Now, if we take a look at this rather large use effects, we'll notice that we're doing quite a bit here. But importantly, is that we're reconstructing the highlight layer content every time the user inputs in text into the text area, which isn't the most optimal way of doing this. But it is the way that a lot of these implementations do it. So we dive into the code, we'll see that here we are constructing the HTML string, and any unhighlighted content we're appending to this string. And then if there is, you know, something to highlight, we are creating a span element and appending that to the HTML string. And lastly, is we're setting this inner HTML for the highlight layer. And we're creating this DOM update by doing so. So that's the text formatter. But so overly complicated code. And it has expensive, repeated mutations to DOM elements. So how can we refactor this? Let's take a look. Well, first, let's remove the duplicate layers. And let's have a single layer, a content editable layer.
Comments