var PC=PC||{};
PC.fe=PC.fe||{};
!(function($, _){
'use strict';
var product_info;
wp.hooks.addAction('PC.fe.reset_product', 'mkl/product_configurator', function(){
PC.fe.saveYourDesign.resetModal();
});
wp.hooks.addAction('PC.fe.init', 'mkl/product_configurator', function(id, parent_id){
if('async'===PC.fe.config.data_mode) parent_id=id;
if(PC.productData.product_info){
product_info=PC.productData.product_info;
}else if(PC.productData['prod_' +(parent_id ? parent_id:id) ]){
product_info=PC.productData['prod_' +(parent_id ? parent_id:id) ].product_info;
}
if('variable'==product_info.product_type){
PC.fe.modal.$el.on('content-is-loaded', function(){
PC.fe.saveYourDesign.init();
PC.fe.loadYourDesign.init();
});
}else{
PC.fe.saveYourDesign.init();
PC.fe.loadYourDesign.init();
}});
$(PC.fe).on('variation_content_loaded', function(args){
if(product_info&&args.response){
product_info.user_saved_configurations=args.response.user_saved_configurations;
}});
PC.fe.loadYourDesign={
init: function(){
if(! $('body').hasClass('logged-in')) return;
if(PC_config&&PC_config.hasOwnProperty('config')&&PC_config.config.hasOwnProperty('load_config') ){
if(product_info&&product_info.user_saved_configurations&&product_info.user_saved_configurations[PC_config.load_config]){
this.setConfig(product_info.user_saved_configurations[PC_config.config.load_config].content);
}else{
PC.fe.modal.viewer.$el.append($('<div class="loading-message" />').append($('<p />').text(PC_SYD.lang.loading_config_message)) );
PC.fe.modal.viewer.$el.addClass('loading');
this.getConfig(PC_config.config.load_config);
}}
},
getConfigs: function(finished){
if(! $('body').hasClass('logged-in')){
return false;
}
wp.ajax.send({
data: {
action: 'mkl_pc_get_all_configurations',
product_id: PC.fe.active_product,
security: PC_SYD.get_config_nonce,
whatever: 'PC_SYD.get_config_nonce',
},
context: this,
success: function(d){
product_info.user_saved_configurations=d.user_saved_configurations;
product_info.user_saved_configurations_loaded=true;
if(d.nonces){
PC_SYD.save_config_nonce=d.nonces.save_config_nonce ? d.nonces.save_config_nonce:PC_SYD.save_config_nonce;
PC_SYD.save_config_image_nonce=d.nonces.save_config_image_nonce ? d.nonces.save_config_image_nonce:PC_SYD.save_config_image_nonce;
PC_SYD.delete_config_nonce=d.nonces.delete_config_nonce ? d.nonces.delete_config_nonce:PC_SYD.delete_config_nonce;
PC_SYD.get_config_nonce=d.nonces.get_config_nonce ? d.nonces.get_config_nonce:PC_SYD.get_config_nonce;
}
if(finished&&'function'==typeof finished) finished(d);
},
error: function(e){
PC.fe.modal.viewer.$el.removeClass('syd-loading');
PC.fe.modal.viewer.$el.find('.loading-message').remove();
console.log(e);
if(finished&&'function'==typeof finished) finished(e);
}});
},
getConfig: function(config_id){
$.ajax({
url: wp.ajax.settings.url,
type: 'POST',
dataType: 'json',
data:{
action: 'mkl_pc_get_configuration',
config_id: config_id,
security: PC_SYD.get_config_nonce,
},
context: this,
})
.fail(function(e){
console.log("Error getting the configuration:", e);
PC.fe.modal.viewer.$el.removeClass('loading');
PC.fe.modal.viewer.$el.find('.loading-message').remove();
})
.done(function(response){
PC.fe.modal.viewer.$el.removeClass('loading');
PC.fe.modal.viewer.$el.find('.loading-message').remove();
if(_.isObject(response) ){
if(response.length > 0){
PC.fe.loadYourDesign.setConfig(response);
}}else{
console.log("The configuration was apparently successfully fetched, but was not formated properly:", response);
}});
},
setConfig: function(config_items){
PC.fe.setConfig(config_items);
wp.hooks.doAction('pc.fe.syd.setConfig', config_items);
},
configListView: Backbone.View.extend({
tagName: 'div',
className: 'mkl-pc-modal-list',
template: wp.template('mkl-saved-designs'),
initialize: function(){
this.render();
return this;
},
render: function(){
this.$el.html(this.template());
this.$ul=this.$('ul.user-configs-list');
var that=this;
$.each(product_info.user_saved_configurations, function(index, item){
that.$ul.append(new PC.fe.loadYourDesign.configListViewItem(item).$el);
});
}}),
configListViewItem: Backbone.View.extend({
tagName: 'li',
template: wp.template('mkl-saved-designs-item'),
initialize: function(item){
this.data=item;
this.listenTo(this.model, 'change:image', this.render);
this.render();
return this;
},
events: {
'click .set-configuration': 'set_configuration',
'click .delete-configuration': 'delete_configuration',
'click .edit-configuration': 'edit_configuration',
'click .cancel-edit': 'cancel_edit',
'click .save-configuration': 'save_configuration',
},
render: function(){
this.$el.html(this.template(this.data) );
},
set_configuration: function(e){
e.preventDefault();
PC.fe.saveYourDesign.modal.maybeEdit(false);
PC.fe.loadYourDesign.setConfig(this.data.content);
console.log(this.data.content);
},
edit_configuration: function(e){
e.preventDefault();
this.$el.siblings().removeClass('editing');
this.$el.addClass('editing');
this.$('input').val(this.data.title);
PC.fe.loadYourDesign.setConfig(this.data.content);
PC.fe.saveYourDesign.modal.maybeEdit(this.data);
},
cancel_edit: function(e){
e.preventDefault();
this.$('input').val('');
this.$el.removeClass('editing');
PC.fe.saveYourDesign.modal.maybeEdit(false);
},
save_configuration: function(e){
e.preventDefault();
PC.fe.saveYourDesign.modal.$input.val(this.$('input').val());
PC.fe.saveYourDesign.modal.save();
this.cancel_edit();
},
delete_configuration: function(e){
e.preventDefault();
if(! confirm(PC_SYD.lang.confirm_deletion) ) return;
this.$el.addClass('deleting-config');
$.ajax({
url: wp.ajax.settings.url,
type: 'POST',
dataType: 'json',
data: {
action: 'mkl_pc_delete_configuration',
delete_config: this.data.ID,
security: PC_SYD.delete_config_nonce,
},
context: this,
})
.fail(function(response){
console.log("error deleting", response);
this.$el.removeClass('deleting-config');
})
.success(function(response){
this.$el.removeClass('deleting-config');
if(true==response.success){
var data=response.data;
if(data.deleted){
this.remove();
}else{
alert(data.message);
}}
});
},
}),
};
PC.fe.saveYourDesign={
init: function(){
var $btn=$('.save-your-design');
$btn.toggleClass('disabled', ! $('body').hasClass('logged-in'));
if(! $btn.data('initialized') ){
$('.save-your-design').on('click', function(e){
e.preventDefault();
PC.fe.saveYourDesign.showModal();
});
$btn.data('initialized', true);
}
if($('.save-your-design').length) PC.fe.modal.$el.addClass('syd');
$('.save-your-design--pdf').on('click', function(e){
e.preventDefault();
$(this).addClass('downloading');
PC.fe.PDF.download().then(function(){
$(this).removeClass('downloading');
}.bind(this) );
});
if($('.save-your-design--pdf').length) PC.fe.modal.$el.addClass('syd-pdf');
},
modalView: Backbone.View.extend({
tagName: 'div',
className: 'mkl-pc-syd-modal',
template: wp.template('mkl-save-the-design'),
initialize: function(){
if(! PC.fe.modal) return;
this.opened=true;
this.is_user_logged_in=$('body').hasClass('logged-in');
this.insertTarget=PC.fe.modal.$('.save-your-design-modal-container');
if(! this.insertTarget.length){
this.insertTarget=$('.save-your-design-modal-container');
}
if(! this.insertTarget.length){
console.warn('Save your design: No location was found to insert the view...');
return;
}
this.render();
this.$input=this.$('#config-name');
this.$message=this.$('.save-form--container > .message').first();
if(this.is_user_logged_in&&! product_info.user_saved_configurations&&! product_info.user_saved_configurations_loaded){
this.$('.saved-items').append($('<div class="loading-message" />').append($('<p />').text(PC_SYD.lang.loading_config_message) ));
PC.fe.loadYourDesign.getConfigs(function(){
this.$('.saved-items').empty();
this.renderListView();
}.bind(this));
}
wp.hooks.doAction('PC.fe.syd.modal.init', this);
return this;
},
events: {
'click .save-the-design': 'save_on_click',
'click .dont-save-the-design': 'close',
'click .save-my-design__login_form button': 'login',
'click .dismiss-message': 'dismiss_message',
'focus #config-name': 'check_edit',
'saved': 'saved'
},
focusable_selector: 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
render: function(){
this.$el.append(this.template());
this.insertTarget.append(this.$el);
if(product_info&&_.isObject(product_info.user_saved_configurations) ){
this.renderListView();
}
setTimeout(
this.open.bind(this), 20
);
},
renderListView: function(){
this.listView=new PC.fe.loadYourDesign.configListView();
this.$('.saved-items').append(this.listView.$el);
},
announce: function(message, assertive){
if(! message) return;
var $live=this.$('.syd-live-region').first();
if(! $live.length) return;
$live.attr('role', assertive ? 'alert':'status');
$live.text('');
setTimeout(function(){
$live.text(message);
}, 15);
},
get_focusable: function(){
return this.$('.mkl-pc-modal').find(this.focusable_selector).filter(':visible');
},
get_initial_focus_target: function(){
var $dialog=this.$('.mkl-pc-modal').first();
if(! $dialog.length) return this.$el;
var $target=this.is_user_logged_in
? this.$('#config-name:visible:not([disabled])').first()
: this.$('#mkl-syd-user:visible:not([disabled])').first();
if($target.length) return $target;
var $focusable=this.get_focusable();
if($focusable.length) return $focusable.first();
return $dialog;
},
handle_keydown: function(e){
if(! this.opened) return;
if(e.key==='Escape'){
e.preventDefault();
e.stopPropagation();
if(e.stopImmediatePropagation){
e.stopImmediatePropagation();
}
this.close();
return;
}
if(e.key!=='Tab') return;
var $focusable=this.get_focusable();
if(! $focusable.length) return;
var first=$focusable[0];
var last=$focusable[ $focusable.length - 1 ];
var activeEl=document.activeElement;
var insideDialog=this.$('.mkl-pc-modal').first().has(activeEl).length > 0||this.$('.mkl-pc-modal').first().is(activeEl);
if(! insideDialog){
e.preventDefault();
(e.shiftKey ? last:first).focus();
return;
}
if(e.shiftKey&&activeEl===first){
e.preventDefault();
last.focus();
}else if(! e.shiftKey&&activeEl===last){
e.preventDefault();
first.focus();
}},
maybeEdit: function(item){
if(item){
this.edited_item=item;
}else if(this.edited_item){
this.$input.val();
this.edited_item=false;
}},
check_edit: function(){
if(this.edited_item){
this.edited_item=false;
this.$(' .saved-items .editing').removeClass('editing');
}},
save_on_click: function(e){
if(e){
e.preventDefault();
if($(e.currentTarget).hasClass('disabled') ){
return false;
}}
this.save();
},
save: function(){
if(PC.fe.config.syd_valid_config_required){
PC.fe.save_data.save();
var errors=wp.hooks.applyFilters('PC.fe.validate_configuration', PC.fe.errors);
if(errors.length){
console.log(errors);
var messages=[];
_.each(PC.fe.errors, function(error){
if(error.choice){
error.choice.set('has_error', error.message);
}
if(error.layer){
error.layer.set('has_error', error.message);
}
messages.push(error.message);
});
this.announce(messages.join('. '), true);
return;
}}
this.$message.html('');
this.$message.removeClass('success error');
if(''==this.$input.val()){
this.$message.addClass('error');
this.$message.html('<p>' + PC_SYD.lang.name_emtpy_error +'</p>');
this.announce(PC_SYD.lang.name_emtpy_error, true);
}else{
this.$el.addClass('syd-loading');
this.$('.saved-items').attr('aria-busy', 'true');
this.announce(PC_SYD.lang.loading_config_message);
var config_id=0;
if(this.edited_item){
config_id=this.edited_item.ID;
}
PC.fe.saveYourDesign.saveDesign(this, 'default', config_id);
}},
saved: function(event, response){
if(response.saved){
if(response.save_image_async){
PC.fe.saveYourDesign.saveImage(response.save_image_async);
}
if(response.user_saved_configurations){
product_info.user_saved_configurations=response.user_saved_configurations;
if(this.listView){
this.listView.render();
}else{
this.listView=new PC.fe.loadYourDesign.configListView();
}}
this.$message.html('<p>' + response.message +'</p>');
this.$message.addClass('success');
this.announce(response.message);
this.$input.val('');
setTimeout(function(){
this.$message.fadeOut()
}.bind(this), 2000);
}else if(response.saved_image){
if(this.listView){
this.listView.render();
}else{
this.listView=new PC.fe.loadYourDesign.configListView();
}}else{
if(response.error){
this.$message.addClass('error').show();
this.$message.html('<p>' + response.error +'</p>');
this.announce(response.error, true);
}}
this.$('.saved-items').attr('aria-busy', 'false');
this.$el.removeClass('syd-loading');
},
close: function(e, options){
options=options||{};
if(e&&e.preventDefault) e.preventDefault();
this.insertTarget.removeClass('opened');
$('body').removeClass('syd-modal-opened');
var $dialog=this.$('.mkl-pc-modal').first();
$dialog.attr('aria-hidden', 'true');
$dialog.attr('inert', 'inert');
$(document).off('keydown.syd-modal-' + this.cid);
this.opened=false;
if(! options.skip_restore_focus&&this.trigger_el&&this.trigger_el.length){
this.trigger_el.trigger('focus');
}
wp.hooks.doAction('PC.fe.syd.modal.close', this);
},
open: function(){
this.opened=true;
this.trigger_el=$(document.activeElement);
if(PC.shareYourDesign&&PC.shareYourDesign.modal&&PC.shareYourDesign.modal.isOpened){
PC.shareYourDesign.modal.close(null, { skip_restore_focus: true });
}
this.insertTarget.addClass('opened');
$('body').addClass('syd-modal-opened');
var $dialog=this.$('.mkl-pc-modal').first();
$dialog.attr('aria-hidden', 'false');
$dialog.removeAttr('inert');
$(document).off('keydown.syd-modal-' + this.cid).on('keydown.syd-modal-' + this.cid, this.handle_keydown.bind(this) );
var $target=this.get_initial_focus_target();
if($target&&$target.length){
setTimeout(function(){
$target.trigger('focus');
}, 0);
}
wp.hooks.doAction('PC.fe.syd.modal.open', this);
},
dismiss_message: function(e){
if(e) e.preventDefault();
this.$message.removeClass('success error').html('');
},
login: function(e){
this.$message.removeClass('success error').hide();
$(e.currentTarget).prop('disabled', true);
var username=this.$el.find('input[name=username]').val();
var password=this.$el.find('input[name=password]').val();
if(! username||! password) return;
wp.ajax.send({
data: {
action: 'mkl_pc_maybe_login',
username: username,
password: password
},
success: _.bind(function(response){
PC_SYD.save_config_nonce=response.save_config_nonce;
PC_SYD.save_config_image_nonce=response.save_config_image_nonce;
PC_SYD.delete_config_nonce=response.delete_config_nonce;
PC_SYD.get_config_nonce=response.get_config_nonce;
$('body').addClass('logged-in');
$(e.currentTarget).prop('disabled', false);
this.announce('Logged in. Save form available.');
PC.fe.saveYourDesign.resetModal();
PC.fe.loadYourDesign.init();
}, this),
error: _.bind(function(error){
$(e.currentTarget).prop('disabled', false);
this.$message.addClass('error').show();
this.$message.html('<p>' + error + '</p>');
this.$message.find('a').prop('target', '_blank');
this.announce(error, true);
}, this),
})
},
}),
showModal: function(){
if(this.modal){
if(this.modal.opened){
this.modal.close();
}else{
this.modal.open();
}}else{
this.modal=new this.modalView();
}
if(this.modal.opened){
const side=wp.hooks.applyFilters('syd_share_modal_side', 'left');
const offset=this.modal.insertTarget.offset();
this.modal.insertTarget.css('--container-offset', Math.round(offset.left) + 'px');
this.modal.insertTarget.css('--container-width', Math.round(PC.fe.modal.$el.outerWidth()) + 'px');
}},
resetModal: function(){
if(! this.modal) return;
this.modal.opened=false;
this.modal.remove();
this.modal=null;
this.init();
},
saveDesign: function(el, config_type, ID){
if(! config_type){
config_type='default'
}
var configurator_data, product_id;
PC.fe.layers.orderBy='image_order';
PC.fe.layers.sort();
configurator_data=PC.fe.save_data.save();
PC.fe.layers.orderBy='order';
PC.fe.layers.sort();
if(''==configurator_data)
return false;
if(el&&el.$el)
var trigger_el=el.$el;
else
var trigger_el=$(el);
product_id=PC.fe.active_product;
var title=el.$input.val();
var request_data={
action: 'mkl_pc_save_configuration',
content: configurator_data,
config_type: config_type,
id: product_id,
title: title,
security: PC_SYD.save_config_nonce,
};
if(ID) request_data.configuration_id=ID;
$.ajax({
url: wp.ajax.settings.url,
type: 'POST',
dataType: 'json',
data: request_data,
context: this,
})
.fail(function(){
trigger_el.trigger('saved', false);
console.warn("error - Could not save the configuration.");
})
.done(function(response){
if(_.isObject(response)&&response.data){
trigger_el.trigger('saved', response.data);
}else{
trigger_el.trigger('saved', false);
}});
},
saveImage: function(data, config_model){
if(! data.config_id)
return false;
$.ajax({
url: wp.ajax.settings.url,
type: 'POST',
dataType: 'json',
data:{
action: 'mkl_pc_generate_configuration_image',
config_id: data.config_id,
security: PC_SYD.save_config_image_nonce,
},
context: this,
})
.fail(function(){
trigger_el.trigger('saved', false);
console.log("error");
})
.done(function(response){
if(product_info&&product_info.user_saved_configurations&&product_info.user_saved_configurations[data.config_id]&&response.success&&response.data){
if(! response.data.thumbnail) return;
product_info.user_saved_configurations[data.config_id].image=response.data.thumbnail;
}
if(config_model&&response.thumbnail){
config_model.set('image', response.thumbnail);
}
this.modal.listView.render();
});
},
OpenWindowWithPost: function(url, params){
var form=document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", url);
form.setAttribute("target", "_blank");
for(var i in params){
if(params.hasOwnProperty(i) ){
var input=document.createElement('input');
input.type='hidden';
input.name=i;
input.value=params[i];
form.appendChild(input);
}}
document.body.appendChild(form);
form.submit();
},
}
PC.fe.PDF={
download(){
const data=this.collect_PDF_data();
const items=this.get_active_items();
return this.build_image(items).then(blob=> this.send_to_PDF(blob, data) );
},
collect_PDF_data(){
const data={
mkl_pc_configuration_to_pdf: 1,
product_id: PC.fe.active_product,
base_price: PC.fe.currentProductData.product_info.price,
};
if(typeof window.pc_extra_price_get_sub_total==='function'){
data.extra_price=pc_extra_price_get_sub_total();
}
data.pc_configuration_data=PC.fe.save_data.save();
return wp.hooks.applyFilters('PC.fe.pdf_data', data);
},
get_active_items(){
const items=[];
const container=document.querySelector('.mkl_pc_layers');
[...container.children].forEach(el=> {
if(!el.classList.contains('active')||el.classList.contains('cshow-hidden')) return;
items.push(el);
});
return items;
},
get_scaled_dimensions(elements){
let height=0;
let width=0;
const maxDimension=wp.hooks.applyFilters('PC.fe.pdf.max_dimension', 1200);
elements.forEach(el=> {
const elHeight=el.naturalHeight||el.offsetHeight||0;
const elWidth=el.naturalWidth||el.offsetWidth||0;
height=Math.max(height, elHeight);
width=Math.max(width, elWidth);
});
if(height > maxDimension||width > maxDimension){
const ratio=height / width;
if(height > width){
height=maxDimension;
width=height / ratio;
}else{
width=maxDimension;
height=width * ratio;
}}
return { width, height };},
build_image(items){
return 'pixi'===PC_SYD.pdf_render_method ? this.render_with_pixi(items):this.render_with_html2Canvas(items);
},
async render_with_pixi(items){
const { width, height }=this.get_scaled_dimensions(items);
const app=new PIXI.Application();
if(typeof app.init==='function'){
await app.init({
width,
height,
backgroundAlpha: 0,
resolution: window.devicePixelRatio||1,
autoDensity: true,
});
}else if(typeof app.renderer==='undefined'){
new PIXI.Application({
width,
height,
backgroundAlpha: 0,
resolution: window.devicePixelRatio||1,
autoDensity: true,
});
}
items.forEach(el=> {
let texture=null;
if(el.tagName==='IMG'){
texture=PIXI.Texture.from(el);
}else if(el.tagName==='DIV'){
const canvas=el.querySelector('canvas');
if(canvas) texture=PIXI.Texture.from(canvas);
}
if(texture) app.stage.addChild(new PIXI.Sprite(texture));
});
return new Promise(resolve=> {
try {
app.renderer.render(app.stage);
} catch (e){
app.renderer.render({ container: app.stage });
}
const extract=app.renderer.extract||(app.renderer.plugins&&app.renderer.plugins.extract);
const canvas=extract&&typeof extract.canvas==='function' ? extract.canvas(app.stage):null;
if(!canvas||typeof canvas.toBlob!=='function'){
app.destroy(true, {
children: true,
texture: true,
baseTexture: true,
});
resolve(null);
return;
}
canvas.toBlob(blob=> {
app.destroy(true, {
children: true,
texture: true,
baseTexture: true,
});
resolve(blob);
}, 'image/png', 0.7);
});
},
render_with_html2Canvas(){
$('.pc-save-canvas-container').remove();
const container=$('<div class="pc-save-canvas-container" style="display: none;" />');
const cloned=$('.mkl_pc .mkl_pc_container .mkl_pc_viewer .mkl_pc_layers').clone();
cloned.appendTo(container);
container.appendTo($('.mkl_pc .mkl_pc_container .mkl_pc_viewer'));
const items=container.find('img.active').get();
const { width, height }=this.get_scaled_dimensions(items);
container.css({
width,
height,
left: 0,
transform: `translateX(calc(-${width}px -100vw))`,
display: 'block',
position: 'absolute',
});
container.find('.mkl_pc_layers :not(.active), .mkl_pc_layers .cshow-hidden').remove();
return html2canvas(container[0], {
onclone(doc, el){
el.querySelectorAll('*').forEach(e=> {
e.style.boxShadow='none';
e.style.filter='none';
e.style.mixBlendMode='normal';
e.style.background='none';
});
}})
.then(canvas=> fetch(canvas.toDataURL()))
.then(res=> res.blob())
.finally(()=> container.remove());
},
send_to_PDF(blob, data){
const formData=new FormData();
formData.append('file', blob, blob.name||blob.type.replace('/', '.'));
formData.append('action', 'mkl_save_to_pdf');
Object.entries(data).forEach(([key, value])=> {
formData.append(key, value);
});
return fetch(PC_config.ajaxurl, {
method: 'POST',
body: formData
})
.then(res=> res.blob())
.then(blob=> {
download(blob, PC.fe.currentProductData.product_info.title + '.pdf');
});
}};
PC.fe.get_config_code=function(replace_hiphens){
const choices=PC.fe.save_data.get_choices();
const mode=PC.fe.config.config_code_mode||'default';
const config_data=[];
_.each(choices, function(item){
const choice_id=item.choice_id;
const layer_id=item.layer_id;
const choice=PC.fe.get_choice_model(item.layer_id, item.choice_id);
const layer=PC.fe.layers.get(layer_id);
if(! layer||! choice||! item.is_choice){ return; }
if('calculation'==choice.get('text_field_type') ){ return; }
let code='';
switch(mode){
case 'sku':
if(item.sku) code=item.sku.replace('-', '__');
break;
case 'default':
default:
code=`${layer_id}C${choice_id}`;
break;
}
if('undefined'!==typeof choice.get('field_value')&&null!==choice.get('field_value') ){
if('text'!=choice.get('text_field_type')&&'textarea'!=choice.get('text_field_type') ){
var value=choice.get('field_value');
if(replace_hiphens&&'string'==typeof value){
value=value.replaceAll('-', '%2D');
}
code +=`[${value}]`;
}}
config_data.push(code);
});
return config_data.join('-');
}
PC.fe.get_config_from_code=function(code){
const mode=PC.fe.config.config_code_mode||'default';
if('sku'==mode) return decode_config_code_sku(code);
return decode_config_code(code);
}
function decode_config_code_sku(code){
const config=[];
let skus=code.split('-');
skus=skus.map(val=> val.replace('__', '-') );
_.each(skus, function(segment){
let found=false;
PC.fe.contents.content.each(( item)=> {
if(found) return;
let userInput=null;
let base=segment;
const openBracketIndex=segment.indexOf('[');
const closeBracketIndex=segment.lastIndexOf(']');
if(openBracketIndex!==-1&&closeBracketIndex > openBracketIndex){
base=segment.slice(0, openBracketIndex);
userInput=segment.slice(openBracketIndex + 1, closeBracketIndex);
if('string'==typeof userInput){
userInput=userInput.replaceAll('%2D', '-');
}}
const choices=item.get('choices');
const res=choices.findWhere({ 'sku': base });
if(res){
const config_item={ layer_id: choices.layer.id, choice_id: res.id };
if(null!==userInput) config_item.field_value=userInput;
config.push(config_item);
found=true;
}});
});
return config;
}
function decode_config_code(input){
const result=[];
const segments=input.split('-');
for(const segment of segments){
let userInput=null;
let base=segment;
const openBracketIndex=segment.indexOf('[');
const closeBracketIndex=segment.lastIndexOf(']');
if(openBracketIndex!==-1&&closeBracketIndex > openBracketIndex){
base=segment.slice(0, openBracketIndex);
userInput=segment.slice(openBracketIndex + 1, closeBracketIndex);
if('string'==typeof userInput){
userInput=userInput.replaceAll('%2D', '-');
}}
if(! base.includes('C') ){
continue;
}
const [ layerStr, choiceStr ]=base.split('C');
const layer_id=parseInt(layerStr, 10);
const choice_id=parseInt(choiceStr, 10);
if(isNaN(layer_id)||isNaN(choice_id) ){
continue;
}
let item_data={
layer_id: layer_id,
choice_id: choice_id
};
if(null!==userInput) item_data.field_value=userInput;
result.push(item_data);
}
return result;
}})(jQuery, PC._us||window._);