Skip to content

Instantly share code, notes, and snippets.

@PrintessEditor
Last active May 16, 2024 05:54
Show Gist options
  • Save PrintessEditor/eaf528a693e44b4d7c1efde7fa50d8dd to your computer and use it in GitHub Desktop.
Save PrintessEditor/eaf528a693e44b4d7c1efde7fa50d8dd to your computer and use it in GitHub Desktop.
Printess Shopify Integration
<!-- Start Printess Product Page Design Button Block -->
{%- render 'printess-add-to-basket',
product: product,
buttonLabel: "Design now",
buttonClasses: "product-form__submit button button--full-width button--primary",
shopToken: "xxxxxx",
startupLogoUrl: "",
showStartupAnimation: true,
hidePricesInEditor: false,
editorVersion: "",
legalText: ""
-%}
<!-- End Printess Product Page Design Button Block -->
{% comment %}
Renders the printess add to basket button
Version 2.01
Accepts:
- product: {Object} Product object.
- buttonLabel: {String} The button label that should be used for the design button.
- buttonClasses: {String} The add to basket classes that should be used for styling the button.
- shopToken: {String} The Printess shop token.
- startupLogoUrl: {String} The url to the logo that should be displayed at the editor startup.
- showStartupAnimation: {Boolean} The animated stars should be shown on startup.
- hidePricesInEditor: {Boolean} The editor should not display prices.
- editorVersion: {Boolean} The sub directory of the embed html in order to.
- legalText: {String} The legal text that should be displayed inside the editor together with the price.
- theme: {String} The theme the editor should be loaded with.
- showProductName: {Boolean} If set to false, the editor will not display the product name.
- showAlertOnTabClose: {Boolean} If set to true, a warning is shown in case the editor is open and someone closes the current tab.
Usage:
{% render 'printess-add-to-basket',
product: product,
buttonLabel: "",
buttonClasses: "",
shopToken: "",
startupLogoUrl: "",
showStartupAnimation: true,
hidePricesInEditor: false,
editorVersion: "/v/nightly",
legalText: "incl. tax, excl. shipping",
theme: "theme01",
showProductName: true,
showAlertOnTabClose: true
%}
{% endcomment %}
{%- liquid
if product.metafields and product.metafields.printess
if product.metafields.printess.templateName
assign printessTemplateName = product.metafields.printess.templateName
else
assign printessTemplateName = ""
endif
if product.metafields.printess.optionNameMapping
assign printessOptionNameMapping = product.metafields.printess.optionNameMapping
else
assign printessOptionNameMapping = ""
endif
if product.metafields.printess.productType
assign printessProductType = product.metafields.printess.productType
else
assign printessProductType = ""
endif
if product.metafields.printess.productDefinitionId
assign printessProductDefinitionId = product.metafields.printess.productDefinitionId
else
assign printessProductDefinitionId = -1
endif
if product.metafields.printess.mergeTemplates
assign printessMergeTemplates = product.metafields.printess.mergeTemplates
else
assign printessMergeTemplates = ""
endif
if settings.printess_outputdpi and settings.printess_outputdpi != blank
assign printessOutputDpi = settings.printess_outputdpi
else
assign printessOutputDpi = 300
endif
if product.metafields.printess.dpi
assign printessOutputDpi = product.metafields.printess.dpi
endif
if settings.printess_outputformat and settings.printess_outputformat != blank
assign printessOutputFormat = settings.printess_outputformat
else
assign printessOutputFormat = "pdf"
endif
if product.metafields.printess.outputFormat
assign printessOutputFormat = product.metafields.printess.outputFormat
endif
endif
-%}
<script id="printess_script_{{ item.key | replace: "-", "_" | replace: ":", "_" }}">
var showPrintessEditor{{ product.id | json }} = () => {
const printessButton = window.document.getElementById("printessCustomizeButton{{ product.id | json }}");
if(!printessButton || !printessButton.printessEditor) {
return;
}
const printessTemplateName = {{ printessTemplateName | json }};
const product = {{ product | json }};
const variantMetaData = {};
let metaJson = {};
{%- for variant in product.variants -%}
{%- if variant.metafields.printess -%}
{% if variant.metafields.printess.displayEditor == true or variant.metafields.printess.templateName %}
metaJson = {{ variant.metafields.printess | json }};
variantMetaData[{{ variant.id }}] = metaJson;
{%- endif -%}
{%- endif -%}
{%- endfor -%}
if(product && product.variants) {
product.variants = product.variants.filter((x) => {
if(variantMetaData[x.id]) {
if(variantMetaData[x.id].hideFromEditor === true) {
return false;
}
if(variantMetaData[x.id].templateName) {
x.templateName = variantMetaData[x.id].templateName;
} else {
x.templateName = printessTemplateName || null;
}
}
return true;
});
}
const settings = {
templateNameOrSaveToken: printessTemplateName,
mergeTemplates: {{ printessMergeTemplates | json }},
product: product,
productDefinitionId: {{ printessProductDefinitionId | json }},
outputFormat: {{ printessOutputFormat | json}},
outputDpi: {{ printessOutputDpi | json }},
optionValueMappings: {{ printessOptionNameMapping | json }},
productType: {{ printessProductType | json }},
legalText: {% if legalText != blank %}{{ legalText | json }}{% else %}""{% endif %}
// ,onAddToBasket: function(saveToken, thumbnailUrl) {
// },
// onSave: function(saveToken, thumbnailUrl) {
// }
};
{% if product.metafields.printess.theme != blank %}
settings["theme"]= {{ product.metafields.printess.theme | json }};
{% else if theme != blank %}
settings["theme"]={{ theme | json }};
{%endif%}
if(settings["theme"]) {
const themeEdit = document.getElementById("printessTheme{{ product.id | json }}");
if(themeEdit) {
themeEdit.value = settings["theme"];
}
}
printessButton.printessEditor.show(settings);
}
</script>
<span onclick='showPrintessEditor{{ product.id | json }}()' id="printessCustomizeButton{{ product.id | json }}" class="{{ buttonClasses }}" style="display:none; justify-content: center;">
{{ buttonLabel | escape }}
</span>
<script>
document.addEventListener("DOMContentLoaded", function() {
const editor = typeof initPrintessShopifyEditor !== "undefined" ? initPrintessShopifyEditor({
"shopToken": {{ shopToken | json }},
"startupLogoUrl": {{ startupLogoUrl | json }},
"showStartupAnimation": {% if showStartupAnimation == true %} true {% else %} false {% endif %},
"hidePricesInEditor": {% if hidePricesInEditor == true %} true {% else %} false {% endif %},
"editorVersion": {% if editorVersion != blank %} {{ editorVersion | json }} {% else %} "" {% endif %},
"shopMoneyFormat": "{{ shop.money_format }}",
"displayProductName": !({{showProductName | json}} === false),
"showAlertOnTabClose": {{showAlertOnTabClose | json}} === true
}) : null;
let templateName = {{ printessTemplateName | json }};
const product = {{ product | json }};
const variantMetaData = {};
let metaJson = {};
if(!editor) {
return;
}
{%- for variant in product.variants -%}
{%- if variant.metafields.printess -%}
{% if variant.metafields.printess.displayEditor == true or variant.metafields.printess.templateName %}
metaJson = {{ variant.metafields.printess | json }};
variantMetaData[{{ variant.id }}] = metaJson;
{%- endif -%}
{%- endif -%}
{%- endfor -%}
if(product && product.variants) {
product.variants = product.variants.filter((x) => {
if(variantMetaData[x.id]) {
if(variantMetaData[x.id].hideFromEditor === true) {
return false;
}
if(variantMetaData[x.id].templateName) {
x.templateName = variantMetaData[x.id].templateName;
} else {
x.templateName = templateName || null;
}
}
return true;
});
}
editor.initProductPage(templateName, product, variantMetaData, "printessCustomizeButton{{ product.id | json }}");
});
</script>
{% comment %}
Renders the printess edit button inside the cart.
Version 2.1
Accepts:
- item: {Object} cart line item.
- classes: {String} classes to use for styling.
- label: {String} the label that should be used for the edit button.
- shopToken: {String} Your printess shop token.
- startupLogoUrl: {String} Url for the startup logo of the editor that should be displayed on load (requires premium account),
- showStartupAnimation: {Boolean} The stars startup animation should be displayed.
- hidePricesInEditor: {Boolean} The editor should display product prices.
- editorVersion: {String} The editor version that should be loaded "" for release; "/v/nightly" for dev.
- legalText: {String} The legal text that should be displayed inside the editor together with the price.
- theme: {String} The theme the editor should be loaded with.
- showProductName: {Boolean} If set to false, the editor will not display the product name.
- showAlertOnTabClose: {Boolean} If set to true, a warning is shown in case the editor is open and someone closes the current tab.
Usage:
{% render 'printess-cart-edit-button',
item: item,
classes: 'button_class_1 etc',
label: 'Edit',
shopToken: "",
startupLogoUrl: "",
showStartupAnimation: true,
hidePricesInEditor: false,
editorVersion: "/v/nightly",
legalText: "incl. tax, excl. shipping",
theme: "theme01",
showProductName: true,
showAlertOnTabClose: true
%}
{% endcomment %}
{% if item.properties._printessSaveToken != blank %}
<script>
function getPrintessEditor() {
if(!getPrintessEditor.editor) {
getPrintessEditor.editor = typeof initPrintessShopifyEditor !== "undefined" ? initPrintessShopifyEditor({ displayProductName: !({{showProductName | json}} === false),
shopToken: "{{ shopToken }}",
"startupLogoUrl": "{{ startupLogoUrl }}",
"showStartupAnimation": {{ showStartupAnimation }},
"hidePricesInEditor": {{ hidePricesInEditor }},
shopMoneyFormat: "{{ shop.money_format }}",
"editorVersion": {{ editorVersion | json }},
"showAlertOnTabClose": {{showAlertOnTabClose | json}} === true
}) : null;
}
return getPrintessEditor.editor;
}
function openPrintessEditor{{ item.key | replace: "-", "_" | replace: ":", "_" }}() {
const basketItem = {{ item | json }};
const basketItemProperties = {{item.properties | json}};
if(basketItemProperties) {
basketItem.properties = {};
basketItemProperties.forEach((prop) => {
if(prop.length > 1) {
basketItem.properties[prop[0]] = prop[1];
} else {
basketItem.properties[prop[0]] = "";
}
});
}
const editor = getPrintessEditor();
if(!editor) {
return;
}
editor.getProductByHandle(basketItem.handle).then((product) => {
const selectedVariant = product.variants ? product.variants.filter((x) => x.id == basketItem.variant_id) : [];
const optionLookup = {};
if(product.options) {
product.options.forEach((option, index) => {
optionLookup[index] = option;
});
}
if(selectedVariant && selectedVariant.length > 0 && selectedVariant[0].options) {
selectedVariant[0].options.forEach((option, index) => {
if(optionLookup.hasOwnProperty(index)) {
basketItem.properties[optionLookup[index]] = option;
}
});
}
const settings = {
templateNameOrSaveToken: basketItem.properties["_printessSaveToken"] || "",
product: product,
basketItemId: {{ item.key | json }},
productDefinitionId: basketItem.properties["_printessProductDefinitionId"] || "",
outputFormat: basketItem.properties["_printessOutputType"] || "",
outputDpi: basketItem.properties["_printessDpi"] || "",
basketItemOptions: basketItem.properties,
quantity: basketItem.quantity,
optionValueMappings: basketItem.properties["_printessOptionValueMappings"] || "",
legalText: {% if legalText != blank %}{{ legalText | json }}{% else %}""{% endif %},
theme: basketItem.properties["_printessTheme"] || {% if theme != blank %}{{ theme | json }}{% else %}""{%endif%}
// ,onAddToBasket: function(saveToken, thumbnailUrl) {
// },
// onSave: function(saveToken, thumbnailUrl) {
// }
};
editor.show(settings);
});
}
</script>
<span style="margin-top: 20px;" onclick='showPrintessEditorFallback("{{ item.key | replace: "-", "_" | replace: ":", "_" }}")' id="printessCustomizeButton{{ item.key | replace: "-", "_" | replace: ":", "_" }}" class="{{ classes }}">{{ label | escape }}</span>
{% endif %}
{% comment %}
Renders the printess thumbnail to the cart
Version 2.1
Accepts:
- item: {Object} Cart line item
- width: {Number} The image width
Usage:
{% render 'printess-thumbnail',
item: item,
width: 150
%}
{% endcomment %}
<img
src="{% if item.properties._printessThumbnail != blank %}{{ item.properties._printessThumbnail }}{% else %}{{ item.image | image_url: width: 300 }}{% endif %}"
class="cart-item__image"
alt="{{ item.image.alt | escape }}"
loading="lazy"
width="{width}"
>
/*
Printess Shopify Integration
Version: 2.1
*/
html {
height: -webkit-fill-available;
}
body.hideAll>*:not(#printess-container) {
display: none !important;
}
body.hideAll {
margin: 0;
padding: 0;
height: 100vh;
height: -webkit-fill-available;
}
#printess-container>#printess {
width: 100vw;
height: 100%;
border: none;
display: block;
position: fixed;
top: 0;
left: 0;
}
/*Printess Shopify Integration Version: 2.2*/var __awaiter=this&&this.__awaiter||function(e,s,a,l){return new(a=a||Promise)(function(i,t){function o(e){try{n(l.next(e))}catch(e){t(e)}}function r(e){try{n(l.throw(e))}catch(e){t(e)}}function n(e){var t;e.done?i(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(o,r)}n((l=l.apply(e,s||[])).next())})};class PrintessEditor{constructor(e,t,i,o,r,n="",s=""){this.Context={},this.Overflow={x:"auto",y:"auto"},this.ShopToken="",this.calculateCurrentPrices=e=>{var t=this.getPriceCategories();let i=this.Context.getPriceForFormFields(this.Context.getCurrentFormFieldValues());return e.snippetPriceCategories&&e.snippetPriceCategories.forEach(e=>{e&&0<e.amount&&this.Context.snippetPrices[e.priceCategory-1]&&(i+=this.Context.snippetPrices[e.priceCategory-1].priceInCent)}),t.price=this.Context.formatMoney(i),t},this.ShopToken=e,this.EditorUrl=this.getEditorUrl(t,i);e=o||"",t={showAnimation:!0===r||"true"==r};e&&(t.imageUrl=e),s&&(t.background=s),this.EditorUrl=this.EditorUrl+"#"+encodeURIComponent(JSON.stringify(t)),this.theme=n||""}getEditorUrl(e,t){return(e=e||"https://editor.printess.com/").toLowerCase().endsWith(".html")||(e=this.sanitizeHost(e),t&&(e+=(t=this.stripEditorVersion(t))+(t?"/":"")),e+="printess-editor/embed.html"),e}stripEditorVersion(e){if(void 0!==(e=(e||"").trim())&&null!=e)if(e){for(;0==e.indexOf("/");)e=e.substring(1);for(;0<e.length&&"/"===e[e.length-1];)e=e.substring(0,e.length-1)}else e="";return e}sanitizeHost(e){return e?(e=e.trim()).endsWith("/")?e:e+"/":e||""}getPriceCategories(){return{snippetPrices:this.Context.snippetPrices.map(e=>e?e.label:null),priceCategories:{},price:this.Context.formatMoney(this.Context.getPriceForFormFields(this.Context.getCurrentFormFieldValues())),productName:this.Context.getProductName(),legalNotice:this.Context.legalText,infoUrl:this.Context.legalTextUrl}}onPriceChanged(t){try{const i=document.getElementById("printess");let e=null;try{t.snippetPriceCategories&&0<t.snippetPriceCategories.length?this.Context.stickers=t.snippetPriceCategories.filter(e=>this.Context.snippetPrices&&this.Context.snippetPrices.length>=e.priceCategory).map(e=>({productVariantId:this.Context.snippetPrices[e.priceCategory-1].variantId,quantity:e.amount})):this.Context.stickers=[],e=this.calculateCurrentPrices(t)}catch(e){console.error(e)}i&&!this.Context.hidePricesInEditor&&setTimeout(()=>{i.contentWindow.postMessage({cmd:"refreshPriceDisplay",priceDisplay:e},"*")},0)}catch(e){}}hideEditor(e=!1){try{var t=document.getElementById("printess-container");t&&(t.style.display="none"),document.body.style.overflowX=this.Overflow.x.toString(),document.body.style.overflowY=this.Overflow.y.toString(),document.body.classList.remove("hideAll"),window.removeEventListener("beforeunload",this.closeTabHandler),window.removeEventListener("unload",this.closeTabHandler)}catch(e){}"function"==typeof this.Context.editorClosed&&this.Context.editorClosed(e)}getOrCreateIframe(e){const o=this;let t=document.getElementById("printess");if(t){if("function"==typeof e)try{e(t)}catch(e){console.error(e)}}else{var i=document.createElement("div");i.setAttribute("id","printess-container"),i.setAttribute("style","display: none; position: absolute; top: 0; bottom: 0; right: 0; left: 0; width: 100%; height: 100%; z-index: 100000;"),(t=document.createElement("iframe")).setAttribute("src",this.EditorUrl),t.setAttribute("id","printess"),t.setAttribute("data-attached","false"),t.setAttribute("allow","xr-spatial-tracking; clipboard-read; clipboard-write;"),t.setAttribute("allowfullscreen","true"),i.appendChild(t),t.onload=()=>{if("function"==typeof e)try{e(t)}catch(e){console.error(e)}},window.addEventListener("message",i=>__awaiter(this,void 0,void 0,function*(){switch(i.data.cmd){case"back":o.hideEditor();break;case"basket":const t=o.Context.onAddToBasket(i.data.token,i.data.thumbnailUrl);t&&t.waitUntilClosingMS?setTimeout(function(){"function"==typeof t.executeBeforeClosing&&t.executeBeforeClosing(),o.hideEditor()},t.waitUntilClosingMS):(t&&"function"==typeof t.executeBeforeClosing&&t.executeBeforeClosing(),o.hideEditor());break;case"formFieldChanged":var e=o.reverseFormFieldMapping(i.data.n||i.data.name,i.data.v||i.data.value,this.Context.getFormFieldMappings());o.Context.onFormFieldChanged(e.name,e.value,i.data.ffCaption||"",i.data.l||i.data.label);break;case"priceChanged":o.onPriceChanged(i.data.priceInfo);break;case"renderFirstPageImage":"function"==typeof o.Context.onRenderFirstPageImage&&o.Context.onRenderFirstPageImage(i.data.result);break;case"save":"function"==typeof o.Context.onSave&&o.Context.onSave(i.data.token,i.data.thumbnailUrl)}})),window.visualViewport&&window.visualViewport.addEventListener("scroll",()=>{var e;null!=(e=t.contentWindow)&&e.postMessage({cmd:"viewportScroll",height:null==(e=window.visualViewport)?void 0:e.height,offsetTop:null==(e=window.visualViewport)?void 0:e.offsetTop},"*")},{passive:!0}),document.body.append(i)}return t}applyFormFieldMappings(t,i){var o=[];if(!i)for(const e in t)t.hasOwnProperty(e)&&o.push({name:e,value:t[e]});if(t)for(const s in t)if(t.hasOwnProperty(s)){var r=t[s],n=void 0!==i[s]&&void 0!==i[s].formField?i[s].formField:s;let e=r;void 0!==i[s]&&void 0!==i[s].values&&void 0!==i[s].values[e]&&(e=i[s].values[r]),o.push({name:n,value:e})}return o}reverseFormFieldMapping(e,t,i){let o=e||"",r=t||"";if(i)for(var n in i)if(i.hasOwnProperty(n)&&i[n].formField===e){if(i[o=n].values)for(var s in i[n].values)if(i[n].values.hasOwnProperty(s)&&i[n].values[s]===t){r=s;break}break}return{name:o,value:r}}setViewportMeta(){var i=document.getElementsByTagName("head");if(i&&0<i.length){let e=i[0].querySelector("meta[name=viewport]"),t=(e||((e=document.createElement("meta")).setAttribute("name","viewport"),i[0].appendChild(e)),e.getAttribute("content"));t?t.indexOf("interactive-widget")<0&&(t=t+(t?", ":"")+"interactive-widget=resizes-content",e.setAttribute("content",t)):e.setAttribute("content","interactive-widget=resizes-content")}}closeTabHandler(e){e.preventDefault(),e.returnValue=""}show(n){this.Context=n;let s=!(this.Context.stickers=[]);try{this.setViewportMeta()}catch(e){console.error(e)}n&&n.templateNameOrSaveToken&&(s=0===n.templateNameOrSaveToken.indexOf("st:")&&90===n.templateNameOrSaveToken.length),this.getOrCreateIframe(e=>{var t=n.getPriceInfo();let i=null,o=null;if(s||(i=this.applyFormFieldMappings(this.Context.getCurrentFormFieldValues(),n.getFormFieldMappings()),o=this.Context.getMergeTemplates()),this.showTabClosingAlert&&(window.addEventListener("beforeunload",this.closeTabHandler),window.addEventListener("unload",this.closeTabHandler)),"false"===e.getAttribute("data-attached"))try{var r={token:this.ShopToken,templateName:n.templateNameOrSaveToken,showBuyerSide:!0,templateUserId:"",basketId:"function"==typeof this.Context.getBasketId&&this.Context.getBasketId()||"Some-Unique-Basket-Or-Session-Id",shopUserId:"function"==typeof this.Context.getUserId?this.Context.getUserId()||"Some-Unique-Basket-Or-Session-Id":"Some-Unique-Shop-User-Id",formFields:i,snippetPriceCategoryLabels:t&&t.snippetPrices?t.snippetPrices:null,mergeTemplates:o};this.theme&&(r.theme=this.theme),e.contentWindow.postMessage({cmd:"attach",properties:r},"*"),e.setAttribute("data-attached","true")}catch(e){console.error(e)}else e.contentWindow.postMessage({cmd:"loadTemplateAndFormFields",parameters:[n.templateNameOrSaveToken,void 0,i,void 0]},"*")}),this.Overflow.x=document.body.style.overflowX,this.Overflow.y=document.body.style.overflowY,document.body.style.overflowX="hidden",document.body.style.overflowY="hidden",document.body.classList.add("hideAll");var e=document.getElementById("printess-container");e&&e.style.setProperty("display","block","important")}}function initPrintessEditor(e,t,i,o,r,n,s=""){let a=!1;var l;return window.printessEditor&&window.printessEditor.show||("string"!=typeof e&&(e=(l=e).shopToken||"",t=l.editorUrl||"",i=l.editorVersion||"",o=l.startupLogoUrl||"",r=void 0===l.showStartupAnimation||!0===l.showStartupAnimation,n=void 0===l.theme?"":l.theme,s=void 0===l.startupBackgroundColor?"":l.startupBackgroundColor,a=void 0!==l.showAlertOnTabClose&&!0===l.showAlertOnTabClose),l=new PrintessEditor(e||"",t||"",i||"",o||"",!0===r,n||"",s),(window.printessEditor=l).showTabClosingAlert=a),window.printessEditor};
/*Printess Shopify Integration Version: 2.2*/var __awaiter=this&&this.__awaiter||function(t,a,s,p){return new(s=s||Promise)(function(o,e){function r(t){try{i(p.next(t))}catch(t){e(t)}}function n(t){try{i(p.throw(t))}catch(t){e(t)}}function i(t){var e;t.done?o(t.value):((e=t.value)instanceof s?e:new s(function(t){t(e)})).then(r,n)}i((p=p.apply(t,a||[])).next())})};const showPrintessEditorFallback=(t,e=0)=>{var o,r,n="openPrintessEditor"+t;void 0===window[n]?(o=document.getElementById("printess_script_"+t))&&((r=document.createElement("script")).setAttribute("id","printess_script_"+t),r.type="text/javascript",r.text=o.text,o.replaceWith(r),e<10?setTimeout(function(){showPrintessEditorFallback(t,++e)},200):console.error(n+" not found.")):window[n]()},initPrintessShopifyEditor=d=>{if(void 0===window.printessShopifyEditor){const i='button[type="submit"][name="add"], button.product-form__add-button[data-action="add-to-cart"],button#AddToCart',u={productCache:{},productFormSelector:'form[data-type="add-to-cart-form"],form.product-single__form,form.shopify-product-form[id^=product-form-template],form[action="/cart/add"]',debounce:function(e,o=300){let r=void 0;return(...t)=>{clearTimeout(r),r=setTimeout(()=>{e.apply(this,t)},o)}},getCurrentProductOptionValues:o=>{function r(t){return t=0===t.indexOf("properties[")&&t.lastIndexOf("]")===t.length-1||0===t.indexOf("options[")&&t.lastIndexOf("]")===t.length-1?t.substring(11,t.length-1):t}var n={},t=u.getAddToBasketForm(u.productFormSelector);if(t){const s=t.getAttribute("name");for(const p of new FormData(t).entries()){let e=r(p[0]);!0===d.supportsOptionPositionIndex&&document.getElementsByName(p[0]).forEach(t=>{(!s||t.getAttribute("form")===s||t.form&&t.form.getAttribute("name")===s)&&(t=parseInt(t.getAttribute("data-option-position")),!isNaN(t))&&0<t&&o&&o.options&&o.options.length>=t&&(e=o.options[t-1])}),0<e.length&&"_"!==e[0]&&(n[e]=p[1])}var i,a=t.querySelectorAll('input[type="checkbox"]');if(a&&0<a.length)for(let e=0;e<a.length;++e)if(void 0!==a[e].checked&&!0===a[e].checked){let t=r(a[e].name);0<(t=!0===d.supportsOptionPositionIndex&&(i=parseInt(a[e].getAttribute("data-option-position")),!isNaN(i))&&0<i&&o&&o.options&&o.options.length>=i?o.options[i-1]:t).length&&"_"!==t[0]&&(n[t]="true")}}return n},getOptionsLookup:e=>{var o={};if(e&&e.options)for(let t=0;t<e.options.length;++t)o[e.options[t]]=t;return o},getProductOptionValuesForVariants:(t,e)=>{var o=u.getOptionsLookup(e),r={};for(const n in t)t.hasOwnProperty(n)&&0<=o[n]&&(r[n]=t[n]);return r},parseInputName:t=>{var e;return t=(t=(t||"").trim())&&"]"===t[t.length-1]&&-1<(e=(t=t.substr(0,t.length-1)).indexOf("["))?t.substr(e+1):t},addVariantChangeHandler:(e,o)=>{const r=function(t){let e="";for(const o in t)t.hasOwnProperty(o)&&(e+=o+";"+t[o]+"_");return e},n=()=>{u.debounce(()=>{var t=r(u.getProductOptionValuesForVariants(u.getCurrentProductOptionValues(e),e));u.addVariantChangeHandler.lastValue!=t&&(u.addVariantChangeHandler.lastValue=t,"function"==typeof o)&&o(u.getVariantByProductOptions(u.getCurrentProductOptionValues(e),e,!0))},100)()};var t=u.getAddToBasketForm(u.productFormSelector);if(t){const i=[];t.querySelectorAll("input,select").forEach(t=>i.push(t)),document.querySelectorAll("input[form='"+t.getAttribute("id")+"'],select[form='"+t.getAttribute("id")+"']").forEach(t=>i.push(t)),i.forEach(t=>{"select"!==t.nodeName.toLowerCase()&&"radio"!==(t.getAttribute("type")||"").toLowerCase()||t.addEventListener("change",n)})}},getVariantByProductOptions:(t,e,o=!1)=>{const r=u.getProductOptionValuesForVariants(t,e);var n=u.getOptionsLookup(e);let i=e.variants;for(const a in r)if(r.hasOwnProperty(a)){let e=void 0!==n[a]&&0<=n[a]?n[a]:-1;-1<e&&(i=i.filter(t=>{if(t.options&&t.options.length>e&&t.options[e]==r[a])return!0}))}return 0!==i.length||o?(0===i.length?e.variants:i)[0]:null},postMessage:(t,e)=>{const o=document.getElementById("printess");o&&setTimeout(function(){o.contentWindow.postMessage({cmd:t,properties:e||{}},"*")},0)},setFormFieldValue:(n,i,a,s)=>{let t=document.querySelectorAll('input[type="radio"]');t&&0<t.length&&t.forEach(t=>{var e=u.parseInputName(t.getAttribute("data-option-name")||t.getAttribute("data-name")||t.getAttribute("name")||void 0),o=t.getAttribute("value")||void 0;e!==n&&e!==a||(o===i||o===s?(t.setAttribute("checked",(!0).toString()),t.checked=!0):(t.removeAttribute("checked"),t.checked=!1))}),t&&0!=t.length||(t=document.querySelectorAll("select")).forEach(e=>{var o=u.parseInputName(e.getAttribute("data-option-name")||e.getAttribute("data-name")||e.getAttribute("name"));if(e.options)for(let t=0;t<e.options.length;++t){var r=e.options[t].getAttribute("value");o!==n&&o!==a||(r===i||r===s?(e.options[t].setAttribute("selected",(!0).toString()),e.options[t].selected=!0,e.setAttribute("value",i),e.value=i):(e.options[t].removeAttribute("selected"),e.options[t].selected=!1))}}),(t=document.querySelectorAll('input[type="text"],input[type="color"],input[type="date"],input[type="datetime-local"],input[type="email"],input[type="month"],input[type="number"],input[type="tel"],input[type="time"],input[type="url"],input[type="week"]'))&&0<t.length&&t.forEach(t=>{var e=u.parseInputName(t.getAttribute("data-option-name")||t.getAttribute("data-name")||t.getAttribute("name")),o=t.getAttribute("value");e===n?t.setAttribute("value",o):e===a&&t.setAttribute("value",s)})},setProductProperty:(t,e,o,r,n,i=!1)=>{t.basketItemOptions||(t.basketItemOptions={});var a=i?r:e;void 0!==t.basketItemOptions[a]?t.basketItemOptions[a]=i?n:o:i?t.basketItemOptions[e]=o:u.setProductProperty(t,e,o,r,n,!0)},initProductPage:(n,i,t)=>{function e(t=null,e=void 0){t=null!==t?t:u.getVariantByProductOptions(u.getCurrentProductOptionValues(i),i,!0);let o=n||"";t&&t.templateName&&(o=t.templateName);var r=window.document.getElementById("printessCustomizeButton"+i.id),t=null!==t&&!(void 0!==t.available&&!1===t.available)&&o;u.showOrHideElement({elementSelector:'button[name="add"], button.product-form__add-button[data-action="add-to-cart"],button#AddToCart'},!t,"block"),u.showOrHideElement({elementSelector:'button[type="button"].shopify-payment-button__button'},!t,"block"),r&&(r.style.display=t?"flex":"none",!0===e)&&(r.printessEditor=u)}u.addVariantChangeHandler(i,e),e(null,!0)},showOrHideElement:(e,o,r="block",n=10)=>{if(!(n<=0)){let t=void 0!==e.elementId?window.document.getElementById(e.elementId):window.document.querySelectorAll(e.elementSelector);(t=t&&void 0!==t.length?0<t.length?t[0]:null:t)?(t.originalDisplayStyle||(t.originalDisplayStyle=t.style.display||r),t.style.display=o?t.originalDisplayStyle:"none"):setTimeout(function(){u.showOrHideElement(e,o,r,n-1)},200)}},show:t=>{t=u.createShopContext(t);if("function"==typeof window.initPrintessEditor){const u=window.initPrintessEditor(d);u.show(t)}},getAddToBasketForm(t){t=document.querySelectorAll(t);if(1===t.length)return t[0];const e=document.querySelector(i);let o;return e&&t.forEach(t=>{!o&&t.contains(e)&&(o=t)}),o||t[0]},createShopContext:n=>{const r={cameFromSave:!1,lastSaveSaveToken:"",templateNameOrSaveToken:n.templateNameOrSaveToken,stickers:[],legalText:n.legalText||"",legalTextUrl:n.legalUrl||"",snippetPrices:[],chargeEachStickerUsage:!1,hidePricesInEditor:void 0!==d.hidePricesInEditor&&!0===d.hidePricesInEditor,getProductName:()=>(void 0===d.displayProductName||!1!==d.displayProductName)&&(n.product&&n.product.name)||"",getPriceInfo:()=>null,getFormFieldMappings:()=>{let t={};if(r.__ffMappings)return r.__ffMappings;if(n.optionValueMappings)try{var e=JSON.parse(n.optionValueMappings);e&&"string"!=typeof e&&"number"!=typeof e&&!Array.isArray(e)&&"boolean"!=typeof e&&"object"==typeof e&&(t=e,r.__ffMappings=t)}catch(t){}return t},getMergeTemplates:()=>n.mergeTemplates?"string"==typeof n.mergeTemplates?u.parseMergeTemplates(n.mergeTemplates):n.mergeTemplates:[],formatMoney:t=>{var e=d.shopMoneyFormat||"${{amount}}";return u.formatMoney(t,e)},onFormFieldChanged:(t,e,o,r)=>{void 0!==n.basketItemId?u.setProductProperty(n,t,e,o,r):u.setFormFieldValue(t,e,o,r)},onAddToBasket:(t,e)=>{void 0!==n.basketItemId?u.replaceBasketItem(n,t,e):u.addNewItemToBasket(n,t,e);try{"function"==typeof n.onAddToBasket&&n.onAddToBasket(t,e)}catch(t){console.error(t)}},getCurrentFormFieldValues:()=>u.getCurrentProductOptionValues(n.product),getPriceForFormFields:t=>{u.getProductOptionValuesForVariants(t,n.product);return u.getVariantByProductOptions(t,n.product,!0).price},getBasketId:()=>"Not yet implemented",onRenderFirstPageImage:t=>{if(r.cameFromSave&&r.lastSaveSaveToken){try{r.onSave(r.lastSaveSaveToken,t,!0)}catch(t){console.error(t)}r.cameFromSave=!1,r.lastSaveSaveToken=""}},onSave:(t,e,o=!1)=>{if(r.cameFromSave=!0,r.lastSaveSaveToken=t,o)try{"function"==typeof n.onSave&&n.onAddToBasket(t,e)}catch(t){console.error(t)}else u.postMessage("renderFirstPageImage",null)},editorClosed:t=>{t&&u.addOrRemoveTextField(u.productFormSelector,"",["printessSaveTokenEdit"+n.product.id,"printessThumbnailEdit"+n.product.id,"printessProductDefinitionIdEdit"+n.product.id,"printessOutputTypeEdit"+n.product.id,"printessDpiEdit"+n.product.id,"printessOptionValueMappingsEdit"+n.product.id,"printessProductTypeEdit"+n.product.id,"printessThemeEdit"+n.product.id],"")}};return r},parseMergeTemplates:e=>{let o=null;if(e){try{var t=JSON.parse(e);o="string"==typeof t?[{templateName:t,mergeMode:"layout-snippet-no-repeat"}]:Array.isArray(t)?t:[t]}catch(t){o=[{templateName:e,mergeMode:"layout-snippet-no-repeat"}]}o&&o.forEach(t=>{t.mergeMode||(t.mergeMode="layout-snippet-no-repeat")})}return o},getProductByHandle:function(o){return __awaiter(this,void 0,void 0,function*(){if(u.productCache[o])return u.productCache[o];let e=null;return yield fetch("/products/"+encodeURIComponent(o)+".js").then(function(t){return t.json()}).then(function(t){t=Object.assign(Object.assign({},t),{name:t.title,options:t.options?t.options.map(t=>t.name):[]});u.productCache[o]=t,e=t}),e})},formatMoney:(t,e)=>{"string"==typeof t&&(t=parseInt(t.replace(".","")));var o="",r=/\{\{\s*(\w+)\s*\}\}/;function n(t,e){return null==t?e:t}function i(t,e,o=null,r=null){return e=n(e,2),o=n(o,","),r=n(r,"."),isNaN(t)||null==t?"0":(t=(t/100).toFixed(e).split("."))[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+o)+(t[1]?r+t[1]:"")}switch(e.match(r)[1]){case"amount":o=i(t,2);break;case"amount_no_decimals":o=i(t,0);break;case"amount_with_comma_separator":o=i(t,2,".",",");break;case"amount_no_decimals_with_comma_separator":o=i(t,0,".",",")}return e.replace(r,o)},addOrRemoveTextField:(e,o,r,n)=>{if(Array.isArray(r))r.forEach(t=>{u.addOrRemoveTextField(e,o,t,n)});else{let t=document.getElementById(r);var i;n?(i="string"==typeof e?u.getAddToBasketForm(e):e,!t&&i&&((t=document.createElement("input")).setAttribute("id",r),t.setAttribute("name",o),t.setAttribute("type","hidden"),t.style.display="none",i.appendChild(t)),t&&t.setAttribute("value",n)):t&&t.remove()}},addNewItemToBasket:(t,e,o)=>{u.addOrRemoveTextField(u.productFormSelector,"properties[_printessSaveToken]","printessSaveTokenEdit"+t.product.id,e),u.addOrRemoveTextField(u.productFormSelector,"properties[_printessThumbnail]","printessThumbnailEdit"+t.product.id,o),u.addOrRemoveTextField(u.productFormSelector,"properties[_printessProductDefinitionId]","printessProductDefinitionIdEdit"+t.product.id,t.productDefinitionId),u.addOrRemoveTextField(u.productFormSelector,"properties[_printessOutputType]","printessOutputTypeEdit"+t.product.id,""+t.outputFormat||"pdf"),u.addOrRemoveTextField(u.productFormSelector,"properties[_printessDpi]","printessDpiEdit"+t.product.id,""+t.outputDpi||"300"),u.addOrRemoveTextField(u.productFormSelector,"properties[_printessOptionValueMappings]","printessOptionValueMappingsEdit"+t.product.id,""+t.optionValueMappings||""),u.addOrRemoveTextField(u.productFormSelector,"properties[_printessProductType]","printessProductTypeEdit"+t.product.id,t.productType||""),u.addOrRemoveTextField(u.productFormSelector,"properties[_printessTheme]","printessThemeEdit"+t.product.id,d.theme||"");e=u.getCurrentProductOptionValues(t.product),o=u.getProductOptionValuesForVariants(e,t.product);const r=u.getVariantByProductOptions(o,t.product,!0);if(r){e=document.querySelectorAll("select[name='id']");if(e&&0<e.length){var n=e[0];n.value=r.id.toString(),n.setAttribute("value",r.id.toString());for(let t=0;t<n.options.length;++t)n.options[t].selected=n.options[t].getAttribute("value")===r.id.toString()}else{o=document.querySelectorAll("input[name='id']");o&&0<o.length&&o.forEach(t=>{t.setAttribute("value",r.id.toString())})}}t=document.querySelector(i);t&&t.click()},replaceBasketItem:(n,i,a)=>{var t=u.getProductOptionValuesForVariants(n.basketItemOptions,n.product);const s=u.getVariantByProductOptions(t,n.product,!0);fetch("/cart.js",{headers:{"Content-Type":"application/json"}}).then(t=>{t.json().then(t=>{var t=t["items"],o=t.find(t=>t.properties&&t.properties._printessSaveToken?t.properties&&t.properties._printessSaveToken===n.templateNameOrSaveToken:t.id===(n&&n.product&&n.product.variants&&0<n.product.variants.length?n.product.variants[0]:n.product).id);if(o){t=o["key"];let e=Object.assign({},o.properties);if(n.basketItemOptions)for(var r in n.basketItemOptions)o.properties&&o.properties.hasOwnProperty(r)&&n.basketItemOptions.hasOwnProperty(r)&&(e[r]=n.basketItemOptions[r]);e=Object.assign(Object.assign({},e),{_printessSaveToken:i,_printessThumbnail:a,_printessProductDefinitionId:""+n.productDefinitionId,_printessOutputType:""+n.outputFormat||"pdf",_printessOptionValueMappings:n.optionValueMappings,_printessDpi:""+n.outputDpi||"300"}),fetch("/cart/change.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:t,quantity:0})}).then(t=>{fetch("/cart/add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:[{id:s.id,quantity:void 0!==n.quantity&&1<n.quantity?n.quantity:1,properties:e}]})}).then(()=>{window.location.replace("/cart")})})}})})},readBasketItemQuantityInput:t=>{"".toString();var t=document.getElementById("printessCustomizeButton"+t.toString());return(t=t&&t.closest(".cart-item"))&&(t=t.querySelector("input.quantity__input"))?parseInt(t.getAttribute("value")):null}};window.printessShopifyEditor=u}return window.printessShopifyEditor};
<!-- Start Printess theme.liquid header block -->
{% comment %} Version 2.1 {% endcomment %}
<script src="{{ 'printessEditor.js' | asset_url }}" defer="defer"></script>
<script src="{{ 'printessShopify.js' | asset_url }}" defer="defer"></script>
{{ 'printesseditor.css' | asset_url | stylesheet_tag }}
<!-- End Printess theme.liquid header block -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment