-
Notifications
You must be signed in to change notification settings - Fork 49
/
shopifyFD.js
3806 lines (3005 loc) · 130 KB
/
shopifyFD.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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
#############
## *##
# % **#
# %%% ***#
# %%F%D%% ****#
# %%% *****#
# ### % ###***#
# # #### #### #**#
# # # # #**#
# ##### # # #####***#
# # # *******#
### # **# ###
# - - - - - - #
| | | | | | |
freakdesign.com
*/
(function(){
"use strict";
/* Sanity checks */
if(document.URL.indexOf("myshopify.com/admin")<0){ return alert('Error: Shopify Admin not found') }
if(typeof Shopify === 'undefined'){ return alert('Error: Shopify object not found') }
if(typeof jQuery === 'undefined'){ return alert('Error: jQuery not found') }
if(!!document.getElementById("shopifyfd-css")){
var errorMessage = 'Error: ShopifyFD already loaded';
"object" === typeof Shopify && Shopify.Flash && Shopify.Flash.error ? Shopify.Flash.error(errorMessage) : alert(errorMessage) ;
return
};
if (!("classList" in document.createElement("_")) || document.createElementNS && !("classList" in document.createElementNS("http://www.w3.org/2000/svg","g"))) {
notice("Browser unsupported (classList)"); /* if you want to add support for classList, do so here */
return;
};
var settings = {
enableDragDrop:true,
wait: 1000,
apiLimit:250
};
/* Translations */
var translation = window.shopifyfdTranslation || {
save:'Save',
edit:'Edit',
delete:'Delete',
about_shopifyfd:'About ShopifyFD',
select_or_create_metafield:'Select or create a metafield',
reload_page:'Reload page to check results.',
add_new_metafield:'Add New Metafield',
edit_metafield:'Edit Metafield',
metafield_deleted:'Metafield deleted',
hide_from_sitemap:'Hide from Sitemap'
};
var app = {
alpha:false,
omega:false,
metafields:{},
data:{},
cache:{}
};
/* File paths */
var paths = {
css:'//freakdesign-us.s3.amazonaws.com/shopify/shopifyFD/s/shopifyFD.min.css?20160718',
help:'//freakdesign-us.s3.amazonaws.com/shopify/shopifyFD/freakdesign-shopifyfd-for-shopify-guide.pdf'
}
var loadCss = function(){
var shopifyCSS = document.createElement("link");
shopifyCSS.type = "text/css";
shopifyCSS.rel = "stylesheet";
shopifyCSS.id = "shopifyfd-css";
shopifyCSS.href = paths.css;
document.getElementsByTagName('head')[0].appendChild(shopifyCSS);
}
loadCss();
var shopifyfd_nav = '<ul id="shopifyfdnav" class="fadein ui-nav__group ui-nav__group--parent"><li class="ui-nav__item ui-nav__item--parent"><a href="https://freakdesign.com.au/pages/shopifyfd" target="_blank" class="ui-nav__link ui-nav__link--parent" style="color: #21c2a8;"><svg class="next-icon next-icon--size-20 next-icon--no-nudge" style="fill:#27c3aa"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#next-settings"></use> </svg><span class="ui-nav__label ui-nav__label--parent">ShopifyFD</span></a></li></ul>';
var metafieldform = '<label class="metafield-next-label next-label">'+translation.add_new_metafield+'</label><input class="ssb" maxlength="20" type="text" id="metafield_namespace" placeholder="namespace" list="fd-dl-namespace"><datalist id="fd-dl-namespace"></datalist><input class="ssb" maxlength="30" type="text" id="metafield_key" placeholder="key" list="fd-dl-key"><datalist id="fd-dl-key"></datalist><textarea class="ssb" id="metafield_value" placeholder="value"></textarea><input type="hidden" id="metafield_id"><a class="btn btn-slim fd-btn savemymeta" id="shopifyjs_savemetafield">'+translation.save+'</a> <a class="int btn btn-slim fd-btn savemymeta" id="shopifyjs_savemetafield_int">Save as Integer</a> <a id="shopifyjs_copymetafield" class="btn btn-slim hide btn-primary tooltip tooltip-bottom"><span class="tooltip-container"><span class="tooltip-label">Copy Metafield to Virtual Clipboard</span></span>Copy</a> <a class="btn btn-slim hide delete tooltip tooltip-bottom" id="shopifyjs_deletemetafield"><span class="tooltip-container"><span class="tooltip-label">There is no undo. Be careful...</span></span>'+translation.delete+'</a><p style="margin:1em 0;line-height:1"><small><span class="metafield-save-note">Please note: Using the save button top right will NOT save these metafields. Be sure to click '+translation.save+' above.<br><br></span><a id="advanced_meta_features" href="#">Toggle helper buttons</a></small></p><div id="advanced_meta" class="hide"><p style="border-bottom: 1px solid #ccc;margin-bottom:.5em">Handle Helper <a id="adv_clear_cache" style="float:right" href="#">Clear cache</a></p><p><a id="adv_get_collections" class="btn fd-btn" href="">Get collections</a></p><p><a id="adv_get_products" class="btn fd-btn" href="">Get '+settings.apiLimit+' products</a></p></div>';
var metafieldloader = '<div class="next-card-metafield next-card next-card--aside fadein"><section class="next-card__section"><h3 class="next-heading">Metafields <svg class="next-icon next-icon--size-16 metafield-fullscreen-btn"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#next-website"></use></svg><span id="metacount" class="hide">0</span></h3><div class="metafield-content content"><i class="ico ico-20 ico-20-loading"></i></div></section></div>';
var metafieldloaderSection = '<div class="section metafields"><div class="next-grid"><div class="next-grid__cell next-grid__cell--quarter"><div class="section-summary"><h1>Metafields</h1><p>Manage the metafields that belong to this collection.</p></div></div><div class="next-grid__cell"><div class="next-card"><div class="section-content" id="collection-metafields"><div class="next-card__section">'+metafieldloader+'</div></div></div></div></div></div>';
var metafield_default = '<option value="">'+translation.select_or_create_metafield+'</option>';
var metafield_copybox = '<div class="metafield-copy-paste sst"><a class="fd-btn btn btn-slim" id="fd_copymetafields">Copy All Metafields</a> <a class="fd-btn btn btn-slim" id="fd_pastemetafields">Paste Metafields</a> <a class="btn btn-slim tooltip tooltip-bottom" href="#" id="fd_whatmetafields"><span class="tooltip-container"><span class="tooltip-label">View what is in the clipboard</span></span>?</a></div>';
var rte_menu_html = '<div class="sst" id="rte_extra"><a class="btn btn-slim fd-btn tooltip btn-destroy tooltip-bottom" id="clearformatting" href="#"><span class="tooltip-container"><span class="tooltip-label">Will remove all HTML on click</span></span>Purge HTML</a> <a class="btn btn-slim fd-btn tooltip tooltip-bottom" id="clear-html-attributes" href="#"><span class="tooltip-container"><span class="tooltip-label">Removes HTML attributes except for <br>target,class,href & src</span></span>Clean HTML</a> <a class="btn btn-slim fd-btn tooltip tooltip-bottom" id="createbackup" href="#"><span class="tooltip-container"><span class="tooltip-label">Save contents as metafield</span></span>Backup</a> <a class="btn btn-slim fd-btn" style="display:none;" id="restorebackup" href="#">Restore Backup</a> <a class="btn btn-slim fd-btn" id="save_images_to_meta" href="#">Images to Metafields</a></div>';
var vbox = '<div class="vbox fadein"><fieldset><select>'+metafield_default+'</select><input id="mv_namespace" placeholder="namespace" /><input id="mv_key" placeholder="key" /><input id="mv_value" placeholder="value" /></fieldset><span class="mybuttons"><a class="save btn btn-slim" href="#">'+translation.save+'</a> <a class="btn btn-slim saveinteger" href="#">'+translation.save+' as Integer</a> <a title="'+translation.delete+'" class="btn-slim delete hidden" href="#">'+translation.delete+'</a></span></div>';
var vbox_single_html = '<div class="vbox-single-card next-card"><div class="next-card__section"><h2 class="next-heading--quarter-margin">Variant Metafields</h2><div id="vrow" class="single-variant">'+vbox+'</div></div></div>'
var bulk_html_box = '<p class="warning">This section makes bulk changes to your product metafields. If something goes wrong it may adversely effect all product metafields. There is no undo.</p><table><tr><td>Namespace</td><td><input id="bulk_namespace" placeholder="Namespace" type="text" /></td></tr><tr><td>Key</td><td><input id="bulk_key" placeholder="Key" type="text" /></td></tr><tr><td>Value</td><td><input id="bulk_value" type="text" placeholder="value" /></td></tr><tr><td colspan="2"><p><strong>Note:</strong> Any existing metafield with the same namespace and key will be overwritten.</p></td></tr><tr><td><a class="btn create">'+translation.save+'</a> <a class="btn createint">Save Integer</a></td><td><span style="display:none"><a class="btn delete">Delete</a> <input type="text" style="width:50%" placeholder="Type delete" /></span></td></tr><tr><td colspan="2"><textarea class="debug" placeholder="Data Output (future use only)"></textarea></td></tr></table>';
var autosave_html = ' <a id="autosave" tabindex="-1" class="btn btn-slim has-loading" href="#">Autosave</a>';
var html_about = '<p>ShopifyFD is "honor-ware", which means that we trust each other to be nice. As the developer of it, I\'m committed to keep the tool something that\'s actually useful. By releasing new features and correcting possible bugs on a constant basis I can do just that, but I need your support. If you use it and intend to keep it, please sponsor its development by making a small <a target="_blank" href="http://shopifyfd.com/">contribution</a>.</p><p>You can track changes by keeping an eye on the project page or following me on <a target="_blank" href="https://twitter.com/freakdesign">twitter</a>.</p><p><h4 style="margin-top:1em">Resources and links</h4><ul><li><a href="http://freakdesign.com.au/pages/shopifyfd" target="_blank">Project home page</a></li><li><a href="http://goo.gl/OsFK2d" target="_blank">Feature Request</a></li><li><a href="http://bit.ly/shopifyFD_forum" target="_blank">Shopify forum post</a></li></ul></p>';
var bubble_html = '<div class="bubble hide fadein"><div class="bubble-content p"><div class="pr"><ul class="unstyled"></ul></div></div></div>';
var bulk_tags = '<div><div class="clearfix em"><div class="half">Choose a collection</div><div class="half"><select data-action="collection"><option value="">Loading, please wait...</option></select></div></div><div class="clearfix em"><div class="half">Choose an action</div><div class="half"><select data-action="action"><option value="add">Add</option><option value="set">Set</option><option value="remove">Remove</option><option disabled value="toggle">Toggle</option><option value="purge" style="background:red;color:#fff">DELETE ALL</option></select></div></div><div class="clearfix em"><div class="half">Set the tag</div><div class="half"><input /></div></div><div class="half"><a class="btn" data-action="update_tags">Update tags</a></div><div class="half"><small>Add: Adds tags to the existing ones<br>Set: Replaces tags with new ones<br>Remove: Removes matching tags<br>Toggle: Future Use, disabled...</small></div></div>';
var next_item_HTML = '<div class="ui-layout__item"><div class="next-card"></div></div>';
var selector_next_secondary = '.ui-layout__section--secondary .ui-layout__item:last';
var selector_next_primary = '.ui-layout__section--primary .ui-layout__item:last';
var selector_sidebar = '.next-layout__sidebar:first';
var selector_sidebar_child = '.next-layout__sidebar > div:first';
var variant_edit_card = '#variant-edit-card';
var selector_sidebar_cell = '.next-grid__cell--third:first';
var selector_sidebar_cell_alt = '.ui-layout__section--secondary .ui-layout__item:first';
var selector_mf_content = 'div.metafield-content';
var selector_general_settings = '#settings-general section:first';
var header_primary_action = '.header .header__primary-actions:first';
var header_secondary_action = '.header .header__secondary-actions:first';
var header_ui_title_bar = '.ui-title-bar';
var header_ui_title = '.ui-title-bar .ui-title-bar__heading-group'; /* header_ui_action_bar_links */
var header_ui_buttons = 'ui-title-bar__actions:first';
var header_ui_buttons_secondary = '.ui-title-bar__actions.ui-title-bar__actions--secondary:first';
var header_ui_action_bar_links = '.action-bar__top-links';
var alphaOmega = function(url){
/* return url parts for location / object detection */
if(typeof url === 'undefined'){
var url = [location.protocol, '//', location.host, location.pathname].join('');
}
var urlArray = url.split('/');
var alpha = urlArray[urlArray.length - 2];
var omega = urlArray.pop();
return [alpha,omega,location.search.substring(1)];
};
var escape = function (str) {
/* Escapes a string */
return str
.replace(/[\\]/g, '\\\\')
.replace(/[\"]/g, '\\\"')
.replace(/[\/]/g, '\\/')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t');
};
function escapeHtml(str) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
var windowResize = function(){
window.dispatchEvent(new Event('resize'));
};
var redirect = function(url) {
/* Redirects the page */
if(typeof url !== 'undefined' && typeof Turbolinks === 'function'){
try {
Turbolinks.visit(url);
} catch (e) {
return false;
}
}
};
var selectSort = function(a,b){
/* simple sorting */
if(!a.getAttribute('value')){
return -1;
}else if(!b.getAttribute('value')){
return 1;
}
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
var stripHTML = function(dirtyString) {
/* removes html from a string */
var container = document.createElement('div');
container.innerHTML = dirtyString;
return container.textContent || container.innerText;
};
var supportsHTML5Storage = function(){
/* Simple check for Storage support */
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
};
var notice = function(m,err){
/* Show message at bottom of the screen using the inbult messaging system */
if(typeof Shopify.Flash.error !== 'function' || typeof Shopify.Flash.notice !== 'function'){ return }
err ? Shopify.Flash.error(m) : Shopify.Flash.notice(m);
};
var _data = function(a,b){
/* setter and getter */
if("undefined"===typeof b)return app[a];app[a]=b
};
var about_app = function(){
/* About this tool. */
fd_modal(true,html_about,translation.about_shopifyfd,true);
return false;
};
var get_theme_data = function(){
/* Get the main theme ID and store response (one time) */
if(typeof app.data.themeId !== 'undefined'){ return }
$.ajax({
type: 'GET',
url: '/admin/themes.json',
success: function(d){
if(d){
app.data.themes = d.themes;
for (var i = 0, len = d.themes.length; i < len; i++) {
if(d.themes[i].role ==='main'){
app.data.themeId = d.themes[i].id
//_data('themeID',d["themes"][i].id);
}
}
}
}
})
};
var add_ui = function(){
/* option to increase working area */
addNavClose();
if(document.getElementById('shopifyfdnav')){ return false }
/* get the first nav group */
var navGroup = document.querySelectorAll('.ui-nav .ui-nav__group')[0];
if(!navGroup){ return }
/* create the wrapper and insert */
var el = document.createElement('div');
el.innerHTML = shopifyfd_nav;
navGroup.parentNode.insertBefore(el, navGroup.nextSibling);
}
var createbackup = function(id,autosave){
/* Create a backup of the current RTE html */
if(typeof id === 'undefined' || !id){ return false }
var rtePanel = $("iframe:first").contents().find("#tinymce:first");
if(!rtePanel.length){ return false }
var myhtml = rtePanel.html();
var metafield = {
"metafield": {
"namespace": 'backups',
"key": id,
"value": myhtml,
"value_type": "string"
}
};
if(typeof autosave !== 'undefined'){
/* sanity checks */
if(window.location.href.indexOf('/admin/products/')<0){ return false }
if(!$('#autosave').hasClass('active')){ return false }
$('#autosave').addClass('is-loading').removeClass('active');
metafield.metafield.namespace = 'autosave';
metafield.metafield.key = 'html';
}
var url = [location.protocol, '//', location.host, location.pathname,'/metafields.json'].join('');
if(_data('alpha') === 'articles'){ url = '/admin/articles/' + id + '/metafields.json' }
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: metafield,
success: function(d){
updatedropdown();
if (typeof autosave === 'undefined'){
notice('Backup saved');
}else{
$('#autosave').removeClass('is-loading').addClass('active');
}
},
error: function(d){
var err = JSON.parse(d.responseText);
notice(err.errors.value[0],true);
}
});
return true;
};
var bulk_save_metafield_queue = function(m,i,debug_box){
/* Bulk metafield queue handler */
/* Sanity check */
if(typeof m === 'undefined'){ return false }
if(typeof i === 'undefined'){ return false }
$.ajax({
type: "POST",
url: '/admin/products/'+_data('products')[i].id+'/metafields.json',
dataType: 'json',
data: m,
success: function(d){
if(debug_box){
var fdmv = debug_box.val();
debug_box.val(fdmv+i+': '+_data('products')[i].id+': ok\n');
}
if(i+1 < _data('products').length){
bulk_save_metafield_queue(m,i+1,debug_box)
}else{
if(_data('alpha') == 'products'){ updatedropdown() }
notice("Bulk changes done!");
}
}
})
};
var getMetafieldUrl = function(id,url){
/* Return the correct metafield url */
if(typeof url === 'undefined'){
var url = [location.protocol, '//', location.host, location.pathname].join('');
}
var pathEnd = '/metafields.json';
var ao = alphaOmega(url);
var alpha = ao[0];
var omega = ao[1];
if(typeof id !== 'undefined' && !isNaN(id)){
pathEnd = '/metafields/'+id+'.json';
}
if(omega === 'general'){ return '/admin' + pathEnd }
url = [location.protocol, '//', location.host, '/admin/', alpha, '/', omega, pathEnd].join('');
return url;
}
var loadmeta = function(loadinto,v){
/*
_ _ _
| | ___ __ _ __| |_ __ ___ ___| |_ __ _
| |/ _ \ / _` |/ _` | '_ ` _ \ / _ \ __/ _` |
| | (_) | (_| | (_| | | | | | | __/ || (_| |
|_|\___/ \__,_|\__,_|_| |_| |_|\___|\__\__,_|
Loads the metafields for the current view
*/
var url = getMetafieldUrl() + '?limit='+settings.apiLimit;
var body = $('body');
app.cache.fullscreenMetafield = $('.metafield-fullscreen-btn');
if(app.cache.fullscreenMetafield.length){
app.cache.fullscreenMetafield.on('click',function(){
if(body.hasClass('fullscreen-metafield')){
body.removeClass('fullscreen-metafield');
}else{
body.addClass('fullscreen-metafield');
}
});
}
$.getJSON(url, function(data) {
var h = '';
var namespaceArray = _data('datalistNamespace') || ['global','test','theme'];
var keyArray = _data('datalistKey') || [];
var m = data.metafields;
if(m){
_data('m',m);
_data('hasbackup',false); /* reset to default */
$('#restorebackup').hide();
if(_data('alpha')==='products' || _data('alpha')==='collections' || _data('alpha')==='pages'){
setup_copypaste();
}
var metacount = $('#metacount');
metacount.text(m.length).removeClass('hide');
if(m.length === 0){
metacount.addClass('hide');
}
for (var i = 0, len = m.length; i < len; i++) {
h+= '<option data-type="' +m[i].value_type + '" data-id="' +m[i].id + '">' +m[i].namespace + '.' + m[i].key + '</option>';
app.metafields[m[i].id] = { namespace: m[i].namespace, value: m[i].value, key: m[i].key };
if (m[i].namespace == "backups"){
if(_data('hasbackup') === false){
$('#restorebackup').show();
_data('hasbackup',true);
setupRteBackupBtn();
}
}
if(m[i].namespace === 'seo' && m[i].key === 'hidden' && m[i].value === 1){
hiddenObject(m[i].id)
}
namespaceArray.push(m[i].namespace);
keyArray.push(m[i].key);
}
namespaceArray = array_unique(namespaceArray);
keyArray = array_unique(keyArray);
_data('datalistNamespace',namespaceArray);
_data('datalistKey',keyArray);
h = '<select id="metafieldselect" class="ssb">' + metafield_default + h +'</select>';
}else{
h ='<select id="metafieldselect" class="ssb">' + metafield_default + '</select>';
}
loadinto.html(h).append(metafieldform);
for (var i = 0; i < namespaceArray.length; i++) {
var dlOption = $('<option />',{
value:namespaceArray[i]
});
$('#fd-dl-namespace').append(dlOption)
};
for (var i = 0; i < keyArray.length; i++) {
var dlOption = $('<option />',{
value:keyArray[i]
});
$('#fd-dl-key').append(dlOption)
};
$('#advanced_meta_features').off('click').on('click',function(){
var adv_meta = $('#advanced_meta').eq(0);
adv_meta.toggleClass('hide');
return false;
});
$('#adv_clear_cache').off('click').on('click',function(){
$('#advanced_meta').find('select').remove().end().find('a').show();
_data('products',false);
_data('collections',false);
return false;
});
$('#adv_get_products').off('click').on('click',function(){
var t = $(this);
var add_select = function(d){
var toappend='';
var select=$('<select />').change(function(){
var t=$(this);
$('#metafield_value').val(t.val());
}).html('<option value="">Add product handle as value</option>');
for (var i = 0, len = d.products.length; i < len; i++) {
toappend+='<option value="'+d.products[i].handle+'">'+d.products[i].title+'</option>';
}
select.append(toappend);
t.after(select).hide();
};
if(!_data('products')){
$.ajax({
type: 'GET',
url: '/admin/products.json?limit='+settings.apiLimit,
dataType: 'json',
success: function(d){
if(d.products.length){
_data('products',d);
add_select(d);
}
},
fail: function(){
notice('Failed to load products',true);
}
});
}else{
var d = _data('products');
add_select(d);
}
return false;
});
$('#adv_get_collections').off('click').on('click',function(){
var t = $(this);
var add_select = function(d){
var toappend='';
var select=$('<select />',{}).change(function(){
var t=$(this);
$('#metafield_value').val(t.val());
}).html('<option value="">Add collection handle as value</option>');
for (var i = 0, len = d.collections.length; i < len; i++) {
toappend+='<option value="'+d.collections[i].handle+'">'+d.collections[i].title+'</option>';
}
select.append(toappend);
t.after(select).hide();
};
if(!_data('collections')){
$.ajax({
type: 'GET',
url: '/admin/collections.json?limit='+settings.apiLimit,
dataType: 'json',
success: function(d){
if(d.collections.length){
_data('collections',d);
add_select(d);
}
},
error: function(){
notice('Failed to load collections',true);
}
});
}else{
var d = _data('collections');
add_select(d);
}
return false;
});
$('#metafieldselect').change(function(){
var t = $(this).find(':selected');
if(t.attr('data-id')){
var m = app.metafields[t.attr('data-id')];
$('.metafield-next-label').text(translation.edit_metafield);
$('#metafield_namespace').val(m.namespace).prop("disabled", true);
$('#metafield_key').val(m.key).prop("disabled", true);
$('#metafield_value').val(m.value);
$('#metafield_id').val(t.attr('data-id'));
$('#shopifyjs_deletemetafield').removeClass('hide');
}else{
clearmetaform();
}
});
$('#shopifyjs_deletemetafield').on('click',function(e){
e.preventDefault();
var id = $('#metafield_id').val() || false;
if(!id){
notice('Object ID Missing',true);
return false;
}
var url = getMetafieldUrl(id);
/* sanity check */
if(url.indexOf('?show_all_images')>-1){ return }
if(url.indexOf('products.json')>-1){ return }
$.ajax({
type: "DELETE",
url: url,
success: function(d){
notice(translation.metafield_deleted);
updatedropdown();
},
error:function(d){
notice('Failed to delete',true);
}
});
});
$('.metafield-content a.savemymeta').off('click').on('click',function(){
var thistype = 'string';
if($(this).hasClass('int')){thistype = 'integer'}
var metafield_namespace = $('#metafield_namespace').val(),
metafield_key = $('#metafield_key').val(),
metafield_value = $('#metafield_value').val(),
metafield_id = $('#metafield_id').val();
var metaJSON = {
"metafield": {
"namespace": metafield_namespace,
"key": metafield_key,
"value": metafield_value,
"value_type": thistype
}
};
var metaupdateJSON = {
"metafield": {
"id": metafield_id,
"value": metafield_value,
"value_type": thistype
}
};
if(metafield_id.length>5){
var url = getMetafieldUrl(metafield_id);
$.ajax({
type: "PUT",
url: url,
dataType: 'json',
data: metaupdateJSON,
success: function(d){
updatedropdown();
flog(d);
notice('Metafield updated');
}
});
}else{
var url = getMetafieldUrl();
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: metaJSON,
success: function(d){
updatedropdown();
notice('Metafield saved');
},
error: function(d){
var r = JSON.parse(d.responseText),
e = '';
if (r.errors.namespace){e+='Namespace '+escape(r.errors.namespace[0])+'. '}
if (r.errors.key){e+='Key '+escape(r.errors.key[0])+'. '}
if (r.errors.value){e+='Value '+escape(r.errors.value[0])+'. '}
notice('Metafield failed to save: ' + e,true);
}
});
}
return false;
});
});
}
var clearformatting = function(){
var mycontent = $("iframe:first").contents().find("#tinymce:first");
if(!mycontent.length){ return false }
var div = document.createElement("div");
div.innerHTML = mycontent.html();
var text = div.textContent || div.innerText || "";
mycontent.text(text);
};
var removeAttributes = function(){
var mycontent = $("iframe:first").contents().find("#tinymce:first");
if(!mycontent.length){ return false }
var selector = mycontent.find('*');
var whitelist = ['href','target','class','src'];
selector.each(function(i,elem) {
for (var i = elem.attributes.length -1; i >= 0 ; i--) {
if(whitelist.indexOf(elem.attributes[i].name)<0){
elem.removeAttribute(elem.attributes[i].name);
}
}
});
};
var clearmetaform = function(){
$('.metafield-next-label').text(translation.add_new_metafield);
$('#metafield_namespace').val('').prop("disabled", false);
$('#metafield_key').val('').prop("disabled", false);
$('#metafield_value').val('');
$('#metafield_id').val('');
$('#shopifyjs_deletemetafield').addClass('hide');
};
var jsonEndpointShow = function(a){
var target = document.getElementsByClassName(header_ui_action_bar_links.replace('.',''));
if(!target.length){ return }
if(document.getElementsByClassName('view-json-endpoint-link').length){ return }
var button = document.createElement("a");
button.innerHTML = 'View JSON';
button.target = '_blank';
button.classList.add('btn','action-bar__link','btn--link');
button.href =['//', location.host, location.pathname].join('')+'.json';
target[0].appendChild(button);
};
var set_drag_drop = function(){
if(!settings.enableDragDrop){ return false }
var dndSupported = function () {
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};
if(dndSupported()){
flog('has dnd');
var doc = document.documentElement;
doc.ondragover = function () { this.className = 'dragit'; return false; };
doc.ondragleave = function () { this.className = ''; return false; };
doc.ondragend = function () { this.className = '';return false; };
doc.ondrop = function (event) {
event.preventDefault && event.preventDefault();
var files = event.dataTransfer.files;
var files_count = files.length;
var files_index = 0;
var reader = new FileReader();
var file_array = {};
reader.onload = function (event) {
flog('load');
var fdata = event.target.result;
var justdata = fdata.split(',')[1];
file_array[files_index] = { "name": files[files_index].name, "data": justdata };
files_index++;
if(files_index < files_count){
notice("Reading file ["+ (files_index+1 )+"] contents...");
reader.readAsDataURL(files[files_index]);
}else{
do_upload(file_array);
}
};
if(files_count){
document.documentElement.className = 'dragit';
notice("Reading file ["+ (files_index+1 )+"] contents...");
reader.readAsDataURL(files[files_index]);
}
return false;
}
}
};
var do_upload = function(d){
/* grab the dropped files and upload them to the theme */
if(!settings.enableDragDrop){ return false }
var tid = app.data.themeId; //_data('themeID');
if(!tid || isNaN(tid)){ notice('Theme ID not found',true); return false; }
var files = d;
var files_count = Object.keys(d).length;
var files_index = 0;
if(_data('alpha') == 'themes'){tid = _data('omega');}
if(_data('omega') == 'settings' && !isNaN(_data('alpha'))){tid = _data('alpha');}
var doajax = function(){
var myfile = {
"asset": {"key": 'assets/'+files[files_index].name,"attachment": files[files_index].data}
};
$.ajax({
type: "PUT",
url: '/admin/themes/'+tid+'/assets.json',
data: myfile,
success: function(){
notice(files[files_index].name + ' uploaded ('+(files_index+1)+'/'+files_count+')');
files_index++;
if(files_index < files_count){ doajax() } else {
document.documentElement.className = '';
}
},
error:function(){
notice('File upload failed',true);
}
});
}
doajax();
};
var updateVariant = function(data,count,callback){
if(typeof data === 'undefined'){ return false }
notice('Updating Variant '+(count+1)+'/'+data.length+'...');
if(typeof count === 'undefined'){ var count = 0 }
if(typeof callback === 'undefined'){ var callback = false }
$.ajax({
type: "PUT",
url: '/admin/variants/'+data[count].variant.id,
dataType: 'json',
data: data[count],
success: function(d){
++count;
if(count<data.length){
updateVariant(data,count,callback);
}else{
notice('Variants updated');
if(typeof callback === 'function'){
callback();
}
}
},
error:function(){
notice('Update failed',true);
}
});
};
var save_variant_metafield = function(id,namespace,key,value,vid,type){
/* save a metafield attached to a variant */
var thistype='undefined' !== typeof type ? 'integer' : 'string';
var ajaxType = 'post';
var url = '/admin/variants/'+id+'/metafields.json';
var meta = {"metafield": {"namespace": namespace,"key": key,"value": value,"value_type": thistype}};
if(vid.length){
if(isNaN(vid)){ return false }
meta = {"metafield": {"id": vid,"value": value,"value_type": thistype}};
url = '/admin/variants/'+id+'/metafields/'+vid+'.json';
ajaxType = 'put';
}
$.ajax({
type: ajaxType,
url: url,
data: meta,
success: function(d){
flog(d);
setup_vrow(id);
notice('Metafield saved');
},
error:function(d){
setup_vrow(id);
notice('Error Saving',true);
}
});
};
var delete_variant_metafield = function(id,vid){
/* delete a metafield attached to a variant */
var url = '/admin/variants/'+id+'/metafields/'+vid+'.json';
if(url.indexOf('?')>-1){ return false }
if(url.indexOf('products.json')>-1){ return false }
$.ajax({
type: "DELETE",
url: url,
success: function(d){
flog(d);
setup_vrow(id);
notice(translation.metafield_deleted);
},
error:function(d){
setup_vrow(id);
notice('Failed to delete',true);
}
});
};
var variant_fillfields = function(id){
var o;
for (var i = 0, len = _data('vm').length; i < len; i++) {
o = _data('vm')[i];
if(parseInt(o.id) == parseInt(id)){
return o;
}
};
return false;
}
var setup_vrow = function(v){
if(typeof v === 'undefined' || isNaN(v) || !v ){ notice("Could not find ID",true); return false }
$('#mv_namespace').val('').prop("disabled", false);
$('#mv_key').val('').prop("disabled", false);
$('#mv_value').val('');
_data('current_vid','');
var option = function(o){
return '<option class="meta" value="'+o.id+'">'+o.namespace+'.'+o.key+'</option>';
}
$.ajax({
type: 'GET',
url: '/admin/variants/'+v+'/metafields.json',
success: function(d){
$('#vrow option.meta').remove();
var m = d.metafields;
if(m){
_data('vm',m);
if(m.length){
$('#vrow select').addClass('active');
}else{
$('#vrow select').removeClass('active');
}
}
for (var i = 0, len = m.length; i < len; i++) {
$('#vrow select').append(option(m[i]));
}
$('#vrow .save').off('click').on('click',function(){
if(!_data('current_vid')){
_data('current_vid','');
}
save_variant_metafield(v,$('#mv_namespace').val(),$('#mv_key').val(),$('#mv_value').val(),_data('current_vid'));
return false;
});
$('#vrow .saveinteger').off('click').on('click',function(){
/*$('#vrow .mybuttons').hide();*/
if(!_data('current_vid')){
_data('current_vid','');
}
save_variant_metafield(v,$('#mv_namespace').val(),$('#mv_key').val(),$('#mv_value').val(),_data('current_vid'),true);
return false;
});
$('#vrow .delete').addClass('hidden').off('click').on('click',function(){
/*$('#vrow .mybuttons').hide();*/
delete_variant_metafield(v,_data('current_vid'));
return false;
});
$('#vrow select').eq(0).off('change').change(function(){
var v_val = $(this).val();
_data('current_vid',v_val);
flog(_data('vm'));
if(v_val.length){