This repository has been archived by the owner on Sep 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
jurassicninja.js
532 lines (477 loc) · 15.7 KB
/
jurassicninja.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
const CREATE_PAGE_SLUG = '/create';
const SPECIALOPS_CREATE_PAGE_SLUG = '/specialops';
const originalProgressText = jQuery( '#progress' ).text();
const originalProgressImage = jQuery( '#img1' ).attr( 'src' );
let availableJetpackBetaPlugins = [];
let availableJetpackBetaBranches = []; // Deprecated.
init();
function init() {
if ( isCreatePage() ) {
features = collectFeaturesFromQueryString();
setTimeout( () => {
launchSite( jQuery, features );
}, 1000 );
}
if ( isSpecialOpsPage() ) {
hookJetpackBranches();
hookWooCommerceBetaBranches();
hookAvailableLanguages();
jQuery( '[data-is-create-button]' ).click( function () {
const $this = jQuery( this );
const features = collectFeaturesFromFormInputs();
// Buttons can declare a feature too
if ( $this.data( 'feature' ) ) {
features[ $this.data( 'feature' ) ] = true;
}
launchSite( jQuery, features, true );
return false;
} )
}
}
function launchSite( $, features, resetSpinner = false ) {
$( function() {
startSpinner();
if ( resetSpinner ) {
$( '#progress' ).text( originalProgressText );
jQuery( '#img1' ).attr( 'src', originalProgressImage );
$( '#progress' ).show();
}
jurassicNinjaApi().create( features )
.then( response => {
var successMessage = $( '#progress' ).data().successMessage;
$( '#progress' ).html( `<a href="${ response.data.url }">${ successMessage }</a>` );
stopSpinner();
favicon_update_colour( 'green' );
} )
.catch( err => {
var errorMessage = $( '#progress' ).data().errorMessage;
$( '#progress' ).text( `${ errorMessage } (${ err.message }).` );
stopSpinner( true );
favicon_update_colour( 'red' );
} );
} );
}
function collectFeaturesFromFormInputs() {
const features = {};
const assign = ( el, v ) => {
let n = features;
const keys = jQuery( el ).data( 'feature' ).split( '.' );
while ( keys.length > 1 ) {
const k = keys.shift();
if ( typeof( n[k] ) !== 'object' ) {
n[k] = {};
}
n = n[k];
}
n[keys.shift()] = v;
};
const forEach = Array.prototype.forEach;
const els = jQuery( 'input[type=checkbox][data-feature]' );
forEach.call( els, function( el ) {
assign( el, jQuery( el ).is( ':checked' ) );
} );
const selects = jQuery( 'select[data-feature]' );
forEach.call( selects, function( el ) {
assign( el, jQuery( el ).val() );
} );
const text_inputs = jQuery( 'input[type=text][data-feature]' );
forEach.call( text_inputs, function( el ) {
assign( el, jQuery( el ).val() );
} );
features['jetpack-products'] = Array.prototype.reduce.call(
jQuery( 'input[data-feature="jetpack-products"]' ),
function( acc, el ) {
const $this = jQuery(el);
const value = !$this.is( '[type="checkbox"]' ) || $this.is( ':checked' )
? $this.val()
: '';
return acc.concat( value.split( ',' ).filter( Boolean ) );
},
[]
);
// get selected JPCRM option and value
selected_jpcrm_option = document.querySelector( "input[type='radio'][name='jpcrm-options']:checked" );
if ( selected_jpcrm_option.dataset.feature ) {
features[selected_jpcrm_option.dataset.feature] = selected_jpcrm_option.nextElementSibling.value;
}
return features;
}
function collectFeaturesFromQueryString() {
if ( ! location.search ) {
return {};
}
let params = location.search.substr( 1 ).replace( /\+/g, '%20' ).split( '&' );
let features = {};
const assign = ( key, v ) => {
let n = features;
const keys = key.split( '.' );
while ( keys.length > 1 ) {
const k = keys.shift();
if ( typeof( n[k] ) !== 'object' ) {
n[k] = {};
}
n = n[k];
}
n[keys.shift()] = v;
};
for ( var p of params ) {
if ( p.includes( '=' ) ) {
const splitParam = p.split( '=', 2 ).map( c => decodeURIComponent( c ) );
assign( splitParam[0], splitParam[1] );
} else {
p = decodeURIComponent( p );
if ( p.startsWith( 'no' ) ) {
assign( p.slice( 2 ), false );
} else {
assign( p, true );
}
}
}
return features;
}
function isSpecialOpsPage() {
return window.location.pathname.startsWith( SPECIALOPS_CREATE_PAGE_SLUG );
}
function isCreatePage() {
return window.location.pathname.startsWith( CREATE_PAGE_SLUG )
}
function startSpinner() {
jQuery( '#img1' ).show();
jQuery( '#img2' ).hide();
favicon_update_colour( 'orange' );
}
function stopSpinner( error = false ) {
if ( error ) {
jQuery( '#img2' ).hide();
jQuery( '#img1' ).attr( 'src', jQuery( '#img1' ).data().failureImgSrc );
} else {
jQuery( '#img1' ).hide();
jQuery( '#img2' ).show();
}
}
function param( name ) {
let params;
if ( location.search ) {
let params = location.search.split( '?' )[1].split( '&' );
// branch option is only valid when jetpack-beta is used.
if ( name == 'branch' && params.includes( 'jetpack-beta' ) ) {
let branch = params.filter( param => param.startsWith( 'branch' ) )
return branch.length ? branch[0].split( '=' )[1] : 'master'
}
if ( params.includes( name ) ) {
return true;
}
if ( params.includes( 'no' + name ) ) {
return false;
}
return null;
}
return null;
}
function jurassicNinjaApi() {
if ( ! ( this instanceof jurassicNinjaApi ) ) {
return new jurassicNinjaApi();
}
function create( features ) {
const url = restApiSettings.root;
const nonce = restApiSettings.nonce;
return fetch( url + 'jurassic.ninja/create', {
method: 'post',
credentials: 'same-origin',
body: Object.keys( features ).length ? JSON.stringify( features ) : null,
headers: {
'X-WP-Nonce': nonce,
'content-type': 'application/json',
}
} )
.then( checkStatusAndErrors ).then( parseJson )
}
function checkStatusAndErrors( response ) {
if ( response.status === 503 ) {
throw new Error( 'Site launching is turned off right now' );
}
if ( response.status === 401 ) {
throw new Error( 'Launching sites is currently restricted to authenticated users' );
}
// 400 status are custom WP_Error when features are requested in a bad way
// so we still parse the json there.
if ( response.status !== 200 && response.status !== 400 ) {
throw new Error( 'The API responded in a weird way' );
}
return response;
}
function parseJson( response ) {
let message = 'There was en error with the response from the API';
return response.json()
.then( data => {
// 400 status are custom WP_Error when features are requested in a bad way
if ( response.status === 400 ) {
message = data.message;
throw new Error();
}
return data;
} )
.catch( () => {
throw new Error ( message )
} );
}
this.create = create;
}
/**
* Adds a dot to the favicon so that you know the status of a build
*/
function favicon_update_colour( colour ) {
function getLocation( href ) {
var l = document.createElement( 'a' );
l.href = href;
return l;
}
function remove_all_favicons() {
var links = document.getElementsByTagName( 'head' )[0].getElementsByTagName( 'link' );
for ( var i = 0; i < links.length; i++ ) {
if ( (/(^|\s)icon(\s|$)/i).test( links[i].getAttribute( 'rel' ) ) ) {
var element = links[i];
element.parentNode.removeChild(element);
}
}
}
function get_current_favicon() {
//get link element
function getLinks() {
var icons = [];
var links = document.getElementsByTagName('head')[0].getElementsByTagName('link');
for (var i = 0; i < links.length; i++) {
if ((/(^|\s)icon(\s|$)/i).test(links[i].getAttribute('rel'))) {
icons.push(links[i]);
}
}
return icons;
};
//if link element
var elms = getLinks();
if (elms.length === 0) {
elms = [document.createElement('link')];
elms[0].setAttribute('rel', 'icon');
document.getElementsByTagName('head')[0].appendChild(elms[0]);
}
elms.forEach( function(item) {
item.setAttribute( 'type', 'image/png' );
} );
return elms[ elms.length -1 ];
}
var favicon = get_current_favicon();
var canvas = document.createElement( 'canvas' );
canvas.width = 32;canvas.height = 32;
var ctx = canvas.getContext( '2d' );
var img = new Image();
if ( favicon.href ) {
var location = getLocation( favicon.href );
if ( ['i1.wp.com', 'i2.wp.com','i3.wp.com', 'i4.wp.com'].indexOf( location.host ) >= 0 ) {
var pathSplit = location.pathname.split( '/' );
pathSplit.splice( 0, 2); // removes the domain part
img.src = '/' + pathSplit.join( '/' );
} else {
img.src = favicon.href;
}
}
img.onload = function() {
ctx.drawImage( img, 0, 0, 32, 32 );
ctx.arc(20, 20, 6, 0, 2 * Math.PI, false);
ctx.fillStyle = colour;
ctx.fill();
var link = favicon;
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = canvas.toDataURL( 'image/x-icon' );
remove_all_favicons(); // Remove all the favicons so that Chrome works as expeceted.
document.getElementsByTagName( 'head' )[0].appendChild( link );
}
}
function getAvailableWooCommerceBetaBranches() {
return fetch( '/wp-json/jurassic.ninja/woocommerce-beta-tester/branches' )
.then( response => response.json() )
.then( body => {
if ( !body.data ) {
return [];
}
let branches = [];
if ( body.data.pr ) {
branches = Object.values(body.data.pr);
}
if ( body.data.master ) {
branches.push( body.data.master );
}
return branches.sort((a, b) => a.branch.localeCompare(b.branch));
} );
}
function getAvailableJetpackBetaPlugins() {
return fetch( '/wp-json/jurassic.ninja/jetpack-beta/plugins')
.then( response => response.json() )
.then( body => {
let plugins = Object.keys( body.data ).map( slug => {
return Object.assign( { slug: slug }, body.data[slug] );
} );
plugins.sort( ( a, b ) => a.name.localeCompare( b.name ) );
return plugins;
} );
}
function getAvailableJetpackBetaBranches( plugin_slug ) {
return fetch( '/wp-json/jurassic.ninja/jetpack-beta/plugins/' + ( plugin_slug || 'jetpack' ) + '/branches' )
.then( response => response.json() )
.then( body => {
let branches = [];
if ( body.data.master ) {
branches.push( body.data.master );
}
if ( body.data.rc ) {
branches.push( body.data.rc );
}
branches = branches.concat( Object.keys( body.data.pr ).map( title => {
return body.data.pr[title];
} ) );
return branches;
} );
}
function hookAvailableLanguages() {
const $language_list = jQuery( '[data-feature=language]' );
Object.keys( availableLanguages ).forEach( l => {
jQuery( '#language' ).append( new Option( availableLanguages[ l ].native_name, l ) );
} );
}
function toggleJetpackProducts() {
const $jetpack_toggle = jQuery( '[data-feature=jetpack]' );
const $jetpack_products = jQuery( '.jn-jetpack-products-list' );
$jetpack_products.toggle( $jetpack_toggle.is( ':checked' ) );
}
function toggleJPCRMOptions() {
const $jpcrm_toggle = jQuery( '[data-feature=jpcrm]' );
const $jpcrm_options = jQuery( '.jn-jpcrm-options' );
$jpcrm_options.toggle( $jpcrm_toggle.is( ':checked' ) );
}
function hookJetpackBranches() {
const $jetpack_toggle = jQuery( '[data-feature=jetpack]' );
const $jetpack_beta_toggle = jQuery( '[data-feature=jetpack-beta]' );
const $jpcrm_toggle = jQuery( '[data-feature=jpcrm]' );
const $branches_list = jQuery('#jetpack_beta_branches_group');
const $search_input = jQuery('#jetpack_branch');
const search_results = document.getElementById('jetpack_branches');
$jetpack_toggle.change( toggleJetpackProducts );
toggleJetpackProducts();
$jpcrm_toggle.change( toggleJPCRMOptions );
let onchange;
if ( $branches_list.length ) {
onchange = () => {
// New style.
if ( $jetpack_beta_toggle.is( ':checked' ) ) {
$branches_list.show();
} else {
$branches_list.hide();
}
};
} else {
onchange = () => {
// Old style.
if ( $jetpack_beta_toggle.is( ':checked' ) ) {
$search_input.attr( 'disabled', false );
} else {
$search_input.attr( 'disabled', true );
}
};
}
$jetpack_beta_toggle.change( onchange );
onchange();
getAvailableJetpackBetaPlugins()
.then( list => {
availableJetpackBetaPlugins = list;
if ( $branches_list.length ) {
$branches_list.empty();
}
availableJetpackBetaPlugins.forEach( plugin => {
if ( $branches_list.length ) {
const $div = jQuery( '<div>' );
const $label = jQuery( '<label>' );
$label.attr( 'for', `jetpack_beta_plugin_${ plugin.slug }` );
$label.text( `${ plugin.name } Branch:` );
$div.append( $label );
$div.append( jQuery( '<br>' ) );
const $input = jQuery( '<input class="form-control" role="search" type="text" value="" aria-hidden="false">' );
$input.attr( 'id', `jetpack_beta_plugin_${ plugin.slug }` );
$input.attr( 'list', `jetpack_beta_plugin_list_${ plugin.slug }` );
$input.attr( 'placeholder', `${ plugin.name } branch to enable` );
$input.attr( 'data-feature', `branches.${ plugin.slug }` );
$div.append( $input );
plugin.$search_input = $input;
$div.append( jQuery( '<br>' ) );
const datalist = document.createElement( 'datalist' );
datalist.id = `jetpack_beta_plugin_list_${ plugin.slug }`;
plugin.search_results = datalist;
$div.append( datalist );
$branches_list.append( $div );
} else if ( plugin.slug === 'jetpack' ) {
plugin.$search_input = $search_input;
plugin.search_results = search_results;
} else {
return;
}
getAvailableJetpackBetaBranches( plugin.slug )
.then( list => {
plugin.branches = list;
if ( plugin.slug === 'jetpack' ) {
availableJetpackBetaBranches = list;
}
plugin.branches.forEach( branch => {
// Create a new <option> element.
const option = document.createElement('option');
if ( branch.pr ) {
option.innerHTML = 'PR #' + branch.pr;
option.value = branch.branch;
} else if ( branch.branch === 'master' ) {
option.innerHTML = 'Bleeding Edge';
option.value = 'master';
} else {
option.innerHTML = 'Release Candidate';
option.value = 'rc';
}
// attach the option to the datalist element
plugin.search_results.appendChild(option);
} );
} );
} );
} );
}
function hookWooCommerceBetaBranches() {
getAvailableWooCommerceBetaBranches().then( branches => {
const wooBetaCheckBox = document.querySelector('[data-feature=woocommerce-beta-tester]');
if (branches.length && wooBetaCheckBox) {
const checkboxContainer = wooBetaCheckBox.closest('.checkbox');
const wooBetaSelect = document.createElement('input');
wooBetaSelect.id = 'woocommerce_beta_branch';
wooBetaSelect.name = 'woocommerce_beta_branch';
wooBetaSelect.className = 'form-control';
wooBetaSelect.setAttribute('role' , 'search') ;
wooBetaSelect.setAttribute('list', 'woocommerce_branches');
wooBetaSelect.setAttribute('type', 'text');
wooBetaSelect.setAttribute('Placeholder', 'Select a branch to enable');
wooBetaSelect.setAttribute('data-feature', 'woocommerce-beta-tester-live-branch');
wooBetaSelect.style.display = "none";
const datalist = document.createElement('datalist');
datalist.id = 'woocommerce_branches';
branches.forEach( branch => {
const option = document.createElement('option');
option.innerHTML = branch.branch;
option.value = branch.branch;
datalist.appendChild(option);
} );
checkboxContainer.appendChild(wooBetaSelect);
checkboxContainer.appendChild(datalist);
// Toggle display of the select list
wooBetaCheckBox.addEventListener('change', function() {
if (this.checked) {
wooBetaSelect.style.display = "block";
} else {
wooBetaSelect.style.display = "none";
}
});
}
});
}