-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathexport-pattern.tsx
70 lines (65 loc) · 1.56 KB
/
export-pattern.tsx
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
69
70
/**
* External dependencies
*/
import { paramCase as kebabCase } from 'change-case';
import { downloadZip } from 'client-zip';
/**
* WordPress dependencies
*/
import { downloadBlob } from '@wordpress/blob';
import { __ } from '@wordpress/i18n';
import type { Action } from '@wordpress/dataviews';
/**
* Internal dependencies
*/
import type { Pattern } from '../types';
import { getItemTitle } from './utils';
function getJsonFromItem( item: Pattern ) {
return JSON.stringify(
{
__file: item.type,
title: getItemTitle( item ),
content: item.content.raw,
syncStatus: item.wp_pattern_sync_status,
},
null,
2
);
}
const exportPattern: Action< Pattern > = {
id: 'export-pattern',
label: __( 'Export as JSON' ),
supportsBulk: true,
callback: async ( items ) => {
if ( items.length === 1 ) {
return downloadBlob(
`${ kebabCase(
getItemTitle( items[ 0 ] ) || items[ 0 ].slug
) }.json`,
getJsonFromItem( items[ 0 ] ),
'application/json'
);
}
const nameCount: Record< string, number > = {};
const filesToZip = items.map( ( item ) => {
const name = kebabCase( getItemTitle( item ) || item.slug );
nameCount[ name ] = ( nameCount[ name ] || 0 ) + 1;
return {
name: `${
name +
( nameCount[ name ] > 1
? '-' + ( nameCount[ name ] - 1 )
: '' )
}.json`,
lastModified: new Date(),
input: getJsonFromItem( item ),
};
} );
return downloadBlob(
__( 'patterns-export' ) + '.zip',
await downloadZip( filesToZip ).blob(),
'application/zip'
);
},
};
export default exportPattern;