patrick-steele-idem / morphdom

Fast and lightweight DOM diffing/patching (no virtual DOM needed)
MIT License
3.18k stars 127 forks source link

Input type change breaks value change #220

Open austenadler opened 3 years ago

austenadler commented 3 years ago

Problem

I am morphing A:

<input type="number" value="8" min="0" max="255" name="width" />

and B:

<input type="color" value="#ff00ff" />

interchangeably. This fails with either of these errors (depending on the morph direction):

The specified value "#ff00ff" cannot be parsed, or is out of range.

The specified value "8" does not conform to the required format.  The format is "#rrggbb" where rr, gg, bb are two-digit hexadecimal numbers.

At this line: https://github.com/patrick-steele-idem/morphdom/blob/348299491b43906bab940f435b655923a8f747ab/src/morphAttrs.js#L37

Cause

morphdom iterates over attrs in this line: https://github.com/patrick-steele-idem/morphdom/blob/348299491b43906bab940f435b655923a8f747ab/src/morphAttrs.js#L17 Which causes the value to be set before the type, and because the value is invalid, it is blanked out and the error is shown.

Fix

According to MDN, toNode.attributes on line 4 can be in any order. Reversing the for loop direction won't fix this in all cases because the order might not be the same. This could be fixed by setting value to blank (if it differs), setting all other attributes, then setting value at the end (if it differs).

Or if we can just move value to be the last attribute in the loop, it should work.