Animated String Diffing With React and D3
Do you look forward to a moving experience and interesting characters? Here's an interesting story (just follow the script... JavaScript ). You can have dynamic characters, too!
Join the DZone community and get the full member experience.
Join For Free
i turned my animated alphabet example into an animation of what you’re typing. new characters drop in from above, old characters drop down, and any white space gets squeezed out.
pretty cool, huh? try it out on my site .
maybe i’m a weirdo nerd, but i could play with that for days. well, okay, minutes. at least 30 seconds!
what i like about this demo is that it’s a great example of declarative transitions built with react. each letter handles its own animation, so all that the main component has to do is go through a list of characters in a loop and render a
letter
component for each, like this:
render() {
let { x, y } = this.props,
transition = d3.transition()
.duration(750)
.ease(d3.easecubicinout);
return (
<g transform={`translate(${x}, ${y})`}>
<reacttransitiongroup component="g">
{this.state.text.map((l, i) =>
<letter letter={l} i={i} key={i} transition={transition} />
)}
</reacttransitiongroup>
</g>
);
}
declaring a root
transition
ensures individual letter transitions are synced. rendering them in a
reacttransitiongroup
gives us some additional lifecycle methods, and each letter needs its index so that it can calculate horizontal positioning because it lacks situational awareness.
then, each
letter
component takes care of its own enter/update/exit transitions inside special lifecycle hooks.
componentwillenter
for the enter animation,
componentwillreceiveprops
for update, and
componentwillleave
for exit.
the whole component
is just 59 standard lines of code.
you can read my previous 2000-word article to learn the details about using d3 transitions with react components . i’ve cleaned up the code since then, but the gist hasn’t changed. you can see the current code in my github repository .
the
key
mystery was choosing the right key prop for each
letter
component. that part was hard. it took me two whole nights!
choosing the key prop
the key prop is how react identifies your components. for the most part, you don’t have to worry about choosing correctly. make it unique and you’re done. react can tell your components apart, which lets it do the fancy diffing stuff, and everything just works™.
sometimes, though, the type of uniqueness matters.
for example: if you use the letter itself for the key prop, this example breaks down. it won’t even display input value correctly.
you only get one chance to show each character. repeat it and react won’t care—it’s the same component as far as react is concerned. empty spaces show up because we use character index from the original string to calculate horizontal positioning.
okay then, what if we use the index? each letter has its own, so that’s good, and it’s easy to set up, so that’s great.
waaaait a minute. that’s no good! appending new characters to the end looks great, deleting characters from the end works too, but as soon as you mess around in the middle, all hell breaks loose.
react uses indexes to identify
letter
instances, so only the last character animates. the fancy-pants diffing algorithm can do the diffing, but it doesn’t understand the context.
ugh.
we have to help react out and implement our own string diffing algorithm. if you’ve ever gone to a computer science class or three, this should be a familiar problem. it’s a variation of the much researched longest subsequence problem .
a simple string diffing algorithm
the full longest common subsequence problem is a hairy beast with decades of research behind it. efficient solutions are used in everything from version control systems to bioinformatics.
a few assumptions make it easier in our case:
- changes only happen at the caret
- there is only 1 caret
- there will only ever be 1 change
a linear-complexity algorithm will do!
assuming there’s only one change at a time works even when you take copy/paste into account. users can’t copy/paste disparate chunks of text at the same time. it has to be connected. so even if the change uses the same text, it acts as a big remove followed by an insert.
our game plan is thus:
- assign a unique id to each new character
-
maintain
(char, id)
pairs for the same portion -
create or drop
(char, id)
pairs for the changed portion -
shift
(char, id)
pairs to new indexes for the shifted portion
the implementation took me 55 lines of code. you can see it in its entirety at the github repository . there are 7 steps.
step 1 – prep the vars
// fancytext.jsx -> componentwillreceiveprops()
const oldtext = this.state.textwithids;
const newtext = newprops.text.split('');
let indexofchange = 0,
sizeofchange = 0,
newlastid = this.state.lastid;
oldtext
is the current array of
(char, id)
pairs,
newtext
becomes an array of characters in the new string. we initiate
indexofchange
and
sizeofchange
to
0
.
this.state.lastid
is where we keep a running tally of new characters. think of it as an auto increment id.
step 2 – find the change
// fancytext.jsx -> componentwillreceiveprops()
// find change
for (; newtext[indexofchange] == (oldtext[indexofchange] && oldtext[indexofchange][0]); indexofchange++);
looks like old school c code, doesn’t it? we keep incrementing
indexofchange
until we find a character mismatch between the new and old text. then we know where the insertion or deletion begins.
step 3 – calculating size of change
// fancytext.jsx -> componentwillreceiveprops()
// calculate size of change
if (newtext.length > oldtext.length) {
while (newtext[indexofchange+sizeofchange] != (oldtext[indexofchange] && oldtext[indexofchange][0])
&& indexofchange+sizeofchange < newtext.length) {
sizeofchange = sizeofchange+1;
}
}else{
while (newtext[indexofchange] != (oldtext[indexofchange+sizeofchange] && oldtext[indexofchange+sizeofchange][0])
&& indexofchange+sizeofchange < oldtext.length) {
sizeofchange = sizeofchange+1;
}
}
here we have two different branches – one for insertion and one for deletion. they both use the same principle and have small differences based on which characters to compare.
we keep increasing
sizeofchange
until
indexofchange+sizeofchange
either finds a character that matches in both strings, or until it runs out of characters to check. the difference between insertion and deletion is that we’re shifting the lookup index of either
newtext
or
oldtext
.
step 4 – copying same section
// fancytext.jsx -> componentwillreceiveprops()
// use existing ids up to point of change
d3.range(0, indexofchange).foreach((i) => newtext[i] = oldtext[i]);
d3.range
creates an array of indexes from
0
to
indexofchange
. we loop through it and overwrite
newtext
with existing
(char, id)
pairs from
oldtext
.
step 5 – add new (char, id) pairs
// fancytext.jsx -> componentwillreceiveprops()
// use new ids for additions
if (newtext.length > oldtext.length) {
d3.range(indexofchange, indexofchange+sizeofchange).foreach((i) => {
let letter = newtext[i];
newtext[i] = [letter, newlastid++];
});
if the change is an insertion, we go from
indexofchange
to
indexofchange+sizeofchange
, create new
(char, id)
pairs, and override
newtext
at each index. to create each id, we take
newlastid
and increment it.
just like an auto increment index. it’s a running count of new characters that never decrements.
step 6 – shift remaining (char, id) pairs
// fancytext.jsx -> componentwillreceiveprops()
if (newtext.length > oldtext.length) {
// insertion …
// use existing ids from change to end
d3.range(indexofchange+sizeofchange, newtext.length).foreach((i) =>
newtext[i] = oldtext[i-sizeofchange]);
}else{
// use existing ids from change to end, but skip what's gone
d3.range(indexofchange, newtext.length).foreach((i) =>
newtext[i] = oldtext[i+sizeofchange]);
}
here we again have two branches: one for insertion, one for deletion. both copy
(char, id)
pairs from
oldtext
to
newtext
, but the shift happens in different directions.
when inserting, we have to shift the index by
sizeofchange
to the right. when deleting, we shift the index to the left.
// fancytext.jsx -> componentwillreceiveprops()
this.setstate({text: newprops.text,
textwithids: newtext,
lastid: newlastid});
step 7 – tell react
we have an updated list of
(char, id)
pairs in
newtext
. it reflects the updated text value while keeping all id assignments stable throughout the process. pretty neat.
we use
this.setstate
so that when react calls
render()
on our
fancytext
component, it will use the updated state.
componentwillreceiveprops
is the only lifecycle method where calling
setstate
does not trigger a re-render.
neat, huh?
step 7.5 – use the (char, id) pairs
there’s one more thing. we have to update how rendering happens. invoking the
letter
component looks like this now:
// fancytext.jsx -> render()
return (
<g transform={`translate(${x}, ${y})`}>
<reacttransitiongroup component="g">
{this.state.textwithids.map(([l, id], i) =>
<letter letter={l} i={i} key={id} transition={transition} />
)}
</reacttransitiongroup>
</g>
);
instead of iterating over
this.props.text
, we iterate over
this.state.textwithids
. for each iteration, we take the
(char, id)
pair, de-structure it, and use the
id
for our key prop.
and that’s it, our animated typing example looks like this:
wasn’t that fun?
Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments