-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathtransformers.js
68 lines (60 loc) · 1.49 KB
/
transformers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* WordPress dependencies
*/
import { createBlock, parse, serialize } from '@wordpress/blocks';
import { addWidgetIdToBlock } from '@wordpress/widgets';
export function transformWidgetToBlock( widget ) {
if ( widget.id_base === 'block' ) {
const parsedBlocks = parse( widget.instance.raw.content );
if ( ! parsedBlocks.length ) {
return addWidgetIdToBlock(
createBlock( 'core/paragraph', {}, [] ),
widget.id
);
}
return addWidgetIdToBlock( parsedBlocks[ 0 ], widget.id );
}
let attributes;
if ( widget._embedded.about[ 0 ].is_multi ) {
attributes = {
idBase: widget.id_base,
instance: widget.instance,
};
} else {
attributes = {
id: widget.id,
};
}
return addWidgetIdToBlock(
createBlock( 'core/legacy-widget', attributes, [] ),
widget.id
);
}
export function transformBlockToWidget( block, relatedWidget = {} ) {
let widget;
const isValidLegacyWidgetBlock =
block.name === 'core/legacy-widget' &&
( block.attributes.id || block.attributes.instance );
if ( isValidLegacyWidgetBlock ) {
widget = {
...relatedWidget,
id: block.attributes.id ?? relatedWidget.id,
id_base: block.attributes.idBase ?? relatedWidget.id_base,
instance: block.attributes.instance ?? relatedWidget.instance,
};
} else {
widget = {
...relatedWidget,
id_base: 'block',
instance: {
raw: {
content: serialize( block ),
},
},
};
}
// Delete read-only properties.
delete widget.rendered;
delete widget.rendered_form;
return widget;
}