Plugin Directory

Changeset 3389052


Ignore:
Timestamp:
11/03/2025 05:38:22 PM (5 months ago)
Author:
printess
Message:
  • Added basic tracking events to dom: "printess:editor_opened_new_design", "printess:editor_opened_save_token", "printess:editor_closed_without_add_to_cart","printess:design_saved","printess:add_to_cart_clicked" are now sent to DOM via window.dispatchEvent and can be received using document.addEventListener
Location:
printess-editor/trunk/includes
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • printess-editor/trunk/includes/js/printessEditor.js

    r3383399 r3389052  
    22    constructor(settings) {
    33        this.lastSaveDate = new Date();
    4         this.visible = false;
    5         this.calculateCurrentPrices = async (priceInfo, context) => {
    6             const r = await this.getPriceCategories(context);
     4        this.calculateCurrentPrices = async (priceInfo) => {
     5            const r = await this.getPriceCategories();
    76            let basePrice = r.basePrice;
    87            if (priceInfo.snippetPriceCategories) {
    98                priceInfo.snippetPriceCategories.forEach((x) => {
    10                     if (x && x.amount > 0 && context.snippetPrices[x.priceCategory - 1]) {
    11                         basePrice += context.snippetPrices[x.priceCategory - 1].priceInCent; // * x.amount;
     9                    if (x && x.amount > 0 && PrintessEditor.currentContext.snippetPrices[x.priceCategory - 1]) {
     10                        basePrice += PrintessEditor.currentContext.snippetPrices[x.priceCategory - 1].priceInCent; // * x.amount;
    1211                    }
    1312                });
    1413            }
    15             r.price = context.formatMoney(basePrice);
     14            r.price = PrintessEditor.currentContext.formatMoney(basePrice);
    1615            return r;
    1716        };
     
    2221            ...settings
    2322        };
    24         this.visible = false;
    2523        const hasUiSettings = typeof this.Settings.uiSettings !== "undefined" && this.Settings.uiSettings !== null;
    2624        const startupSettings = {};
     
    237235        }
    238236    }
    239     async initializeIFrame(callbacks, context, settings) {
     237    async initializeIFrame(callbacks, settings) {
    240238        const that = this;
    241239        let iFrame = document.getElementById("printess");
     
    267265                    };
    268266                    try {
    269                         if (typeof context.onAllowAddToBasket === "function") {
    270                             const result = context.onAllowAddToBasket(evt.data.token, evt.data.thumbnailUrl);
     267                        if (typeof PrintessEditor.currentContext.onAllowAddToBasket === "function") {
     268                            const result = PrintessEditor.currentContext.onAllowAddToBasket(evt.data.token, evt.data.thumbnailUrl);
    271269                            if (typeof result !== "boolean" || result === true) {
    272270                                addToBasket(evt.data.token, evt.data.thumbnailUrl);
    273271                            }
    274272                        }
    275                         else if (typeof context.onAllowAddToBasketAsync === "function") {
    276                             context.onAllowAddToBasketAsync(evt.data.token, evt.data.thumbnailUrl).then((result) => {
     273                        else if (typeof PrintessEditor.currentContext.onAllowAddToBasketAsync === "function") {
     274                            PrintessEditor.currentContext.onAllowAddToBasketAsync(evt.data.token, evt.data.thumbnailUrl).then((result) => {
    277275                                if (typeof result !== "boolean" || result === true) {
    278276                                    addToBasket(evt.data.token, evt.data.thumbnailUrl);
     
    320318                    if (that.Settings.autoImportImageUrlsInFormFields === true) {
    321319                        try {
    322                             const images = await that.downloadImages(that.getImagesInFormFields(PrintessEditor.applyFormFieldMappings(context.getCurrentFormFieldValues(), context.getFormFieldMappings())));
     320                            const images = await that.downloadImages(that.getImagesInFormFields(PrintessEditor.applyFormFieldMappings(PrintessEditor.currentContext.getCurrentFormFieldValues(), PrintessEditor.currentContext.getFormFieldMappings())));
    323321                            if (!that.tempUploadImages) {
    324322                                that.tempUploadImages = images;
     
    339337                    }
    340338                    if (that.Settings.autoImportUserImages === true) {
    341                         let userId = await PrintessEditor.getUserId(context);
    342                         let basketId = await PrintessEditor.getOrGenerateBasketId(context);
     339                        let userId = await PrintessEditor.getUserId();
     340                        let basketId = await PrintessEditor.getOrGenerateBasketId();
    343341                        if (userId || basketId) {
    344342                            that.uploadUserImagesToClassicEditor(iFrame, basketId, userId);
     
    346344                    }
    347345                    if (callbacks && typeof callbacks.onLoadAsync === "function") {
    348                         callbacks.onLoadAsync(context.templateNameOrSaveToken);
     346                        callbacks.onLoadAsync(PrintessEditor.currentContext.templateNameOrSaveToken);
    349347                    }
    350348                    break;
     
    434432        return ret;
    435433    }
    436     async getPriceCategories(context, formFieldValues = null) {
     434    async getPriceCategories(formFieldValues = null) {
    437435        let price = 0;
    438436        if (!formFieldValues) {
    439             formFieldValues = context.getCurrentFormFieldValues();
    440         }
    441         if (typeof context.getPriceForFormFieldsAsync === "function") {
    442             price = await context.getPriceForFormFieldsAsync(formFieldValues);
    443         }
    444         else if (typeof context.getPriceForFormFields === "function") {
    445             price = context.getPriceForFormFields(formFieldValues);
     437            formFieldValues = PrintessEditor.currentContext.getCurrentFormFieldValues();
     438        }
     439        if (typeof PrintessEditor.currentContext.getPriceForFormFieldsAsync === "function") {
     440            price = await PrintessEditor.currentContext.getPriceForFormFieldsAsync(formFieldValues);
     441        }
     442        else if (typeof PrintessEditor.currentContext.getPriceForFormFields === "function") {
     443            price = PrintessEditor.currentContext.getPriceForFormFields(formFieldValues);
    446444        }
    447445        const r = {
    448             snippetPrices: context.snippetPrices.map((x) => x ? x.label : null),
     446            snippetPrices: PrintessEditor.currentContext.snippetPrices.map((x) => x ? x.label : null),
    449447            priceCategories: {},
    450             price: context.formatMoney(price),
     448            price: PrintessEditor.currentContext.formatMoney(price),
    451449            basePrice: price,
    452             productName: context.getProductName(),
    453             legalNotice: context.legalText,
    454             infoUrl: context.legalTextUrl
     450            productName: PrintessEditor.currentContext.getProductName(),
     451            legalNotice: PrintessEditor.currentContext.legalText,
     452            infoUrl: PrintessEditor.currentContext.legalTextUrl
    455453        };
    456454        return r;
     
    461459        return loweruiVersion === "bcui" || loweruiVersion === "panelui";
    462460    }
    463     async onPriceChanged(priceChangedInfo, context) {
     461    async onPriceChanged(priceChangedInfo) {
    464462        try {
    465463            let priceInfo = null;
    466464            try {
    467465                if (typeof priceChangedInfo.pageCount !== "undefined") {
    468                     if (context.currentPageCount !== priceChangedInfo.pageCount) {
    469                         context.currentPageCount = priceChangedInfo.pageCount;
    470                         if (context.additionalAttachParams && typeof context.additionalAttachParams["pageCountFormField"] !== "undefined") {
    471                             if (typeof context.onFormFieldChanged === "function") {
     466                    if (PrintessEditor.currentContext.currentPageCount !== priceChangedInfo.pageCount) {
     467                        PrintessEditor.currentContext.currentPageCount = priceChangedInfo.pageCount;
     468                        if (PrintessEditor.currentContext.additionalAttachParams && typeof PrintessEditor.currentContext.additionalAttachParams["pageCountFormField"] !== "undefined") {
     469                            if (typeof PrintessEditor.currentContext.onFormFieldChanged === "function") {
    472470                                try {
    473                                     context.onFormFieldChanged(context.additionalAttachParams["pageCountFormField"], context.currentPageCount.toString(), "", "");
     471                                    PrintessEditor.currentContext.onFormFieldChanged(PrintessEditor.currentContext.additionalAttachParams["pageCountFormField"], PrintessEditor.currentContext.currentPageCount.toString(), "", "");
    474472                                }
    475473                                catch (ex) {
     
    477475                                }
    478476                            }
    479                             if (typeof context.onFormFieldChangedAsync === "function") {
     477                            if (typeof PrintessEditor.currentContext.onFormFieldChangedAsync === "function") {
    480478                                try {
    481                                     await context.onFormFieldChangedAsync(context.additionalAttachParams["pageCountFormField"], context.currentPageCount.toString(), "", "");
     479                                    await PrintessEditor.currentContext.onFormFieldChangedAsync(PrintessEditor.currentContext.additionalAttachParams["pageCountFormField"], PrintessEditor.currentContext.currentPageCount.toString(), "", "");
    482480                                }
    483481                                catch (ex) {
     
    489487                }
    490488                if (priceChangedInfo.snippetPriceCategories && priceChangedInfo.snippetPriceCategories.length > 0) {
    491                     context.stickers = priceChangedInfo.snippetPriceCategories.filter((x) => context.snippetPrices && context.snippetPrices.length >= x.priceCategory).map((x) => {
     489                    PrintessEditor.currentContext.stickers = priceChangedInfo.snippetPriceCategories.filter((x) => PrintessEditor.currentContext.snippetPrices && PrintessEditor.currentContext.snippetPrices.length >= x.priceCategory).map((x) => {
    492490                        return {
    493                             productVariantId: context.snippetPrices[x.priceCategory - 1].variantId,
     491                            productVariantId: PrintessEditor.currentContext.snippetPrices[x.priceCategory - 1].variantId,
    494492                            quantity: x.amount
    495493                        };
     
    497495                }
    498496                else {
    499                     context.stickers = [];
    500                 }
    501                 if (typeof priceChangedInfo.printedRecordsCount !== "undefined" && priceChangedInfo.printedRecordsCount > 0 && typeof context.propertyChanged === "function" && priceChangedInfo.hasCirculationColumn === true) {
    502                     context.propertyChanged("circulationRecordCount", priceChangedInfo.printedRecordsCount.toString());
    503                 }
    504                 priceInfo = await this.calculateCurrentPrices(priceChangedInfo, context);
     497                    PrintessEditor.currentContext.stickers = [];
     498                }
     499                if (typeof priceChangedInfo.printedRecordsCount !== "undefined" && priceChangedInfo.printedRecordsCount > 0 && typeof PrintessEditor.currentContext.propertyChanged === "function" && priceChangedInfo.hasCirculationColumn === true) {
     500                    PrintessEditor.currentContext.propertyChanged("circulationRecordCount", priceChangedInfo.printedRecordsCount.toString());
     501                }
     502                priceInfo = await this.calculateCurrentPrices(priceChangedInfo);
    505503            }
    506504            catch (e) {
    507505                console.error(e);
    508506            }
    509             if (!context.hidePricesInEditor) {
     507            if (!PrintessEditor.currentContext.hidePricesInEditor) {
    510508                const iframe = document.getElementById("printess");
    511509                if (iframe) {
     
    528526    }
    529527    ;
    530     hideBcUiVersion(context, closeButtonClicked) {
    531         this.visible = false;
    532         const editor = this.getPrintessComponent();
    533         if (editor && editor.editor) {
    534             editor.editor.ui.hide();
    535         }
    536         if (typeof context.editorClosed === "function") {
    537             context.editorClosed(closeButtonClicked === true);
    538         }
    539         //Hide the web page scrolling
    540         document.body.classList.remove('hideAll');
     528    hideBcUiVersion(closeButtonClicked) {
     529        if (!PrintessEditor.visible) {
     530            return;
     531        }
     532        try {
     533            const editor = this.getPrintessComponent();
     534            if (editor && editor.editor) {
     535                editor.editor.ui.hide();
     536            }
     537            if (typeof PrintessEditor.currentContext.editorClosed === "function") {
     538                PrintessEditor.currentContext.editorClosed(closeButtonClicked === true);
     539            }
     540            //Hide the web page scrolling
     541            document.body.classList.remove('hideAll');
     542        }
     543        finally {
     544            PrintessEditor.visible = false;
     545        }
    541546    }
    542547    async downloadImages(images) {
     
    598603        });
    599604    }
    600     static async getOrGenerateBasketId(context) {
    601         let ret = typeof context?.getBasketId === "function" ? context.getBasketId() : "";
    602         if (!ret && typeof context?.getBasketIdAsync === "function") {
    603             ret = await context.getBasketIdAsync() || null;
     605    static async getOrGenerateBasketId() {
     606        let ret = null;
     607        if (PrintessEditor.currentContext) {
     608            ret = typeof PrintessEditor.currentContext.getBasketId === "function" ? PrintessEditor.currentContext.getBasketId() : "";
     609            if (!ret && typeof PrintessEditor.currentContext.getBasketIdAsync === "function") {
     610                ret = await PrintessEditor.currentContext.getBasketIdAsync() || null;
     611            }
    604612        }
    605613        if (!ret) {
    606             if (!ret) {
    607                 try {
    608                     ret = localStorage.getItem("printessUniqueBasketId");
    609                 }
    610                 catch (e) {
    611                     console.warn("Unable to read user id from local storage.");
    612                 }
    613             }
    614             if (!ret) {
    615                 ret = window["printessUniqueBasketId"];
    616             }
    617             if (!ret) {
    618                 ret = PrintessEditor.generateUUID() + "_" + new Date().valueOf().toString();
    619                 try {
    620                     localStorage.setItem("printessUniqueBasketId", ret);
    621                 }
    622                 catch (e) {
    623                     window["printessUniqueBasketId"] = ret;
    624                     console.warn("Unable to write user id to local storage.");
    625                 }
     614            try {
     615                ret = localStorage.getItem("printessUniqueBasketId");
     616            }
     617            catch (e) {
     618                console.warn("Unable to read user id from local storage.");
     619            }
     620        }
     621        if (!ret) {
     622            ret = window["printessUniqueBasketId"];
     623        }
     624        if (!ret) {
     625            ret = PrintessEditor.generateUUID() + "_" + new Date().valueOf().toString();
     626            try {
     627                localStorage.setItem("printessUniqueBasketId", ret);
     628            }
     629            catch (e) {
     630                window["printessUniqueBasketId"] = ret;
     631                console.warn("Unable to write user id to local storage.");
    626632            }
    627633        }
    628634        return ret || null;
    629635    }
    630     static async getUserId(context) {
    631         let ret = typeof context.getUserId === "function" ? context.getUserId() : null;
    632         if (!ret && typeof context.getUserIdAsync === "function") {
    633             ret = await context.getUserIdAsync();
     636    static async getUserId() {
     637        let ret = null;
     638        if (PrintessEditor.currentContext) {
     639            ret = typeof PrintessEditor.currentContext.getUserId === "function" ? PrintessEditor.currentContext.getUserId() : null;
     640            if (!ret && typeof PrintessEditor.currentContext.getUserIdAsync === "function") {
     641                ret = await PrintessEditor.currentContext.getUserIdAsync();
     642            }
    634643        }
    635644        return ret;
     
    660669        });
    661670    }
    662     async showBcUiVersion(context, callbacks) {
     671    async showBcUiVersion(callbacks) {
    663672        const that = this;
    664         const priceInfo = context.getPriceInfo();
    665         let isSaveToken = context && context.templateNameOrSaveToken && context.templateNameOrSaveToken.indexOf("st:") === 0;
     673        const priceInfo = PrintessEditor.currentContext.getPriceInfo();
     674        let isSaveToken = PrintessEditor.currentContext.templateNameOrSaveToken && PrintessEditor.currentContext.templateNameOrSaveToken.indexOf("st:") === 0;
    666675        let pageCount = null;
    667676        let useCustomLoader = false;
     
    670679        PrintessEditor.closeAllHtmlDialogs();
    671680        if (!isSaveToken) {
    672             formFields = PrintessEditor.applyFormFieldMappings(context.getCurrentFormFieldValues(), context.getFormFieldMappings());
    673             mergeTemplates = context.getMergeTemplates();
    674             if (context.additionalAttachParams && typeof context.additionalAttachParams["pageCountFormField"] !== "undefined") {
    675                 const pageFormField = formFields.filter(x => x.name === context.additionalAttachParams["pageCountFormField"]);
     681            formFields = PrintessEditor.applyFormFieldMappings(PrintessEditor.currentContext.getCurrentFormFieldValues(), PrintessEditor.currentContext.getFormFieldMappings());
     682            mergeTemplates = PrintessEditor.currentContext.getMergeTemplates();
     683            if (PrintessEditor.currentContext.additionalAttachParams && typeof PrintessEditor.currentContext.additionalAttachParams["pageCountFormField"] !== "undefined") {
     684                const pageFormField = formFields.filter(x => x.name === PrintessEditor.currentContext.additionalAttachParams["pageCountFormField"]);
    676685                if (pageFormField && pageFormField.length > 0) {
    677686                    let intValue = PrintessEditor.extractNumber(pageFormField[0].value);
     
    707716        if (printessComponent && printessComponent.editor) {
    708717            printessComponent.style.display = "block";
    709             await printessComponent.editor.api.loadTemplateAndFormFields(context.templateNameOrSaveToken, mergeTemplates, formFields, null, null, true);
     718            await printessComponent.editor.api.loadTemplateAndFormFields(PrintessEditor.currentContext.templateNameOrSaveToken, mergeTemplates, formFields, null, null, true);
    710719            if (!isSaveToken && pageCount !== null && pageCount > 0) {
    711720                await printessComponent.editor.api.setBookInsidePages(pageCount);
    712721            }
    713722            setTimeout(async function () {
    714                 if (context.hidePricesInEditor !== true) {
    715                     that.calculateCurrentPrices({}, context).then((priceChangedInfo) => {
     723                if (PrintessEditor.currentContext.hidePricesInEditor !== true) {
     724                    that.calculateCurrentPrices({}).then((priceChangedInfo) => {
    716725                        printessComponent.editor.ui.refreshPriceDisplay(priceChangedInfo);
    717726                    });
     
    719728                if (that.Settings.autoImportImageUrlsInFormFields === true) {
    720729                    try {
    721                         const images = await that.downloadImages(that.getImagesInFormFields(PrintessEditor.applyFormFieldMappings(context.getCurrentFormFieldValues(), context.getFormFieldMappings())));
     730                        const images = await that.downloadImages(that.getImagesInFormFields(PrintessEditor.applyFormFieldMappings(PrintessEditor.currentContext.getCurrentFormFieldValues(), PrintessEditor.currentContext.getFormFieldMappings())));
    722731                        await that.uploadImagesToBcUiEditor(images, printessComponent.editor);
    723732                    }
     
    728737                if (that.Settings.autoImportUserImages === true) {
    729738                    try {
    730                         let userId = await PrintessEditor.getUserId(context);
    731                         let basketId = await PrintessEditor.getOrGenerateBasketId(context);
     739                        let userId = await PrintessEditor.getUserId();
     740                        let basketId = await PrintessEditor.getOrGenerateBasketId();
    732741                        if (userId || basketId) {
    733742                            await that.uploadUserImagesToBcUiEditor(printessComponent.editor, basketId, userId);
     
    738747                    }
    739748                }
    740                 await callbacks.onLoadAsync(context.templateNameOrSaveToken);
     749                await callbacks.onLoadAsync(PrintessEditor.currentContext.templateNameOrSaveToken);
    741750                if (globalSettings && globalSettings.customLoader && typeof globalSettings.customLoader.onHideLoader === "function") {
    742751                    try {
     
    764773                formFields: formFields,
    765774                token: that.Settings.shopToken,
    766                 templateName: context.templateNameOrSaveToken, // "Premier Test-3",// "test Trigger Dialog",  // "price-tester", // "Premier Test", //  "Children's book", // "Label FF Test", //"test Trigger Dialog",   "test Trigger Dialog", // "Bathrobe Man", //
     775                templateName: PrintessEditor.currentContext.templateNameOrSaveToken, // "Premier Test-3",// "test Trigger Dialog",  // "price-tester", // "Premier Test", //  "Children's book", // "Label FF Test", //"test Trigger Dialog",   "test Trigger Dialog", // "Bathrobe Man", //
    767776                //templateVersion: "publish",//"draft"
    768777                translationKey: "auto", //"en"
    769                 basketId: await PrintessEditor.getOrGenerateBasketId(context),
    770                 shopUserId: await PrintessEditor.getUserId(context),
     778                basketId: await PrintessEditor.getOrGenerateBasketId(),
     779                shopUserId: await PrintessEditor.getUserId(),
    771780                // mobileMargin: {left: 20, right: 40, top: 30, bottom: 40},
    772781                // allowZoomAndPan: false,
     
    782791                        }
    783792                    };
    784                     if (typeof context.onAllowAddToBasket === "function") {
    785                         const result = context.onAllowAddToBasket(token, thumbnailUrl);
     793                    if (typeof PrintessEditor.currentContext.onAllowAddToBasket === "function") {
     794                        const result = PrintessEditor.currentContext.onAllowAddToBasket(token, thumbnailUrl);
    786795                        if (typeof result !== "boolean" || result === true) {
    787796                            addToBasket(token, thumbnailUrl);
    788797                        }
    789798                    }
    790                     else if (typeof context.onAllowAddToBasketAsync === "function") {
    791                         context.onAllowAddToBasketAsync(token, thumbnailUrl).then((result) => {
     799                    else if (typeof PrintessEditor.currentContext.onAllowAddToBasketAsync === "function") {
     800                        PrintessEditor.currentContext.onAllowAddToBasketAsync(token, thumbnailUrl).then((result) => {
    792801                            if (typeof result !== "boolean" || result === true) {
    793802                                addToBasket(token, thumbnailUrl);
     
    812821                    window.removeEventListener('beforeunload', closeTabListener);
    813822                    window.removeEventListener('unload', closeTabListener);
    814                     that.hideBcUiVersion(context, true);
     823                    that.hideBcUiVersion(true);
    815824                },
    816825                saveTemplateCallback: (saveToken, type, thumbnailUrl) => {
     
    819828                    }
    820829                    if (type && type === "close") {
    821                         that.hideBcUiVersion(context, true);
     830                        that.hideBcUiVersion(true);
    822831                    }
    823832                },
     
    833842                }
    834843            };
    835             if (typeof context.showSplitterGridSizeButton !== "undefined" && context.showSplitterGridSizeButton !== null) {
    836                 attachParams["showSplitterGridSizeButton"] = context.showSplitterGridSizeButton === true || context.showSplitterGridSizeButton === "true";
     844            if (typeof PrintessEditor.currentContext.showSplitterGridSizeButton !== "undefined" && PrintessEditor.currentContext.showSplitterGridSizeButton !== null) {
     845                attachParams["showSplitterGridSizeButton"] = PrintessEditor.currentContext.showSplitterGridSizeButton === true || PrintessEditor.currentContext.showSplitterGridSizeButton === "true";
    837846            }
    838847            if (!isSaveToken && pageCount !== null && pageCount >= 1) {
     
    851860                    return;
    852861                }
    853                 if (context.hidePricesInEditor !== true) {
    854                     const priceChangedInfo = await that.calculateCurrentPrices({}, context);
     862                if (PrintessEditor.currentContext.hidePricesInEditor !== true) {
     863                    const priceChangedInfo = await that.calculateCurrentPrices({});
    855864                    printessComponent.editor.ui.refreshPriceDisplay(priceChangedInfo);
    856865                }
    857866                if (that.Settings.autoImportImageUrlsInFormFields === true) {
    858867                    try {
    859                         const images = await that.downloadImages(that.getImagesInFormFields(PrintessEditor.applyFormFieldMappings(context.getCurrentFormFieldValues(), context.getFormFieldMappings())));
     868                        const images = await that.downloadImages(that.getImagesInFormFields(PrintessEditor.applyFormFieldMappings(PrintessEditor.currentContext.getCurrentFormFieldValues(), PrintessEditor.currentContext.getFormFieldMappings())));
    860869                        await that.uploadImagesToBcUiEditor(images, printessComponent.editor);
    861870                    }
     
    866875                if (that.Settings.autoImportUserImages === true) {
    867876                    try {
    868                         let userId = await PrintessEditor.getUserId(context);
    869                         let basketId = await PrintessEditor.getOrGenerateBasketId(context);
     877                        let userId = await PrintessEditor.getUserId();
     878                        let basketId = await PrintessEditor.getOrGenerateBasketId();
    870879                        if (userId || basketId) {
    871880                            await that.uploadUserImagesToBcUiEditor(printessComponent.editor, basketId, userId);
     
    887896        return parseInt([...inputStr].reduce((x, y) => (check(y) ? x + y : x), ""));
    888897    }
    889     async show(context) {
     898    async show(shopContext) {
     899        if (PrintessEditor.visible) {
     900            return false;
     901        }
     902        PrintessEditor.visible = true;
     903        PrintessEditor.currentContext = shopContext;
    890904        const that = this;
    891905        this.lastSaveDate = new Date();
    892         let isSaveToken = context && context.templateNameOrSaveToken && context.templateNameOrSaveToken.indexOf("st:") === 0;
    893         this.visible = true;
     906        let isSaveToken = shopContext && shopContext.templateNameOrSaveToken && shopContext.templateNameOrSaveToken.indexOf("st:") === 0;
    894907        PrintessEditor.closeAllHtmlDialogs();
    895908        const callbacks = {
    896909            onBack: () => {
    897                 that.hide(context, true);
     910                that.hide(true);
    898911            },
    899912            onAddToBasketAsync: async (saveToken, thumbnailUrl) => {
    900913                let result = null;
    901                 if (typeof context.onAddToBasketAsync === "function") {
    902                     result = await context.onAddToBasketAsync(saveToken, thumbnailUrl);
     914                if (typeof PrintessEditor.currentContext.onAddToBasketAsync === "function") {
     915                    result = await PrintessEditor.currentContext.onAddToBasketAsync(saveToken, thumbnailUrl);
    903916                }
    904917                else {
    905                     result = context.onAddToBasket(saveToken, thumbnailUrl);
     918                    result = PrintessEditor.currentContext.onAddToBasket(saveToken, thumbnailUrl);
    906919                }
    907920                if (result && result.waitUntilClosingMS) {
     
    910923                            result.executeBeforeClosing();
    911924                        }
    912                         that.hide(context, false);
     925                        that.hide(false);
    913926                    }, result.waitUntilClosingMS);
    914927                }
     
    917930                        result.executeBeforeClosing();
    918931                    }
    919                     that.hide(context, false);
     932                    that.hide(false);
    920933                }
    921934            },
    922935            onFormFieldChangedAsync: async (formFieldName, formFieldValue, formFieldLabel, formFieldValueLabel) => {
    923                 const formField = that.reverseFormFieldMapping(formFieldName, formFieldValue, context.getFormFieldMappings());
    924                 if (typeof context.onFormFieldChangedAsync === "function") {
    925                     await context.onFormFieldChanged(formField.name, formField.value, formFieldLabel, formFieldValueLabel);
    926                 }
    927                 else if (typeof context.onFormFieldChanged === "function") {
    928                     context.onFormFieldChanged(formField.name, formField.value, formFieldLabel, formFieldValueLabel);
     936                const formField = that.reverseFormFieldMapping(formFieldName, formFieldValue, PrintessEditor.currentContext.getFormFieldMappings());
     937                if (typeof PrintessEditor.currentContext.onFormFieldChangedAsync === "function") {
     938                    await PrintessEditor.currentContext.onFormFieldChanged(formField.name, formField.value, formFieldLabel, formFieldValueLabel);
     939                }
     940                else if (typeof PrintessEditor.currentContext.onFormFieldChanged === "function") {
     941                    PrintessEditor.currentContext.onFormFieldChanged(formField.name, formField.value, formFieldLabel, formFieldValueLabel);
    929942                }
    930943            },
    931944            onPriceChangedAsync: async (priceInfo) => {
    932                 await that.onPriceChanged(priceInfo, context);
     945                await that.onPriceChanged(priceInfo);
    933946            },
    934947            onGetFormField: (result) => {
    935                 if (typeof context.onGetFormField === "function") {
    936                     context.onGetFormField(result);
     948                if (typeof PrintessEditor.currentContext.onGetFormField === "function") {
     949                    PrintessEditor.currentContext.onGetFormField(result);
    937950                }
    938951            },
    939952            onSaveAsync: async (saveToken, thumbnailUrl) => {
    940953                that.lastSaveDate = new Date();
    941                 if (typeof context.onSaveAsync === "function") {
    942                     await context.onSaveAsync(saveToken, thumbnailUrl);
    943                 }
    944                 else if (typeof context.onSave === "function") {
    945                     context.onSave(saveToken, thumbnailUrl);
     954                if (typeof PrintessEditor.currentContext.onSaveAsync === "function") {
     955                    await PrintessEditor.currentContext.onSaveAsync(saveToken, thumbnailUrl);
     956                }
     957                else if (typeof PrintessEditor.currentContext.onSave === "function") {
     958                    PrintessEditor.currentContext.onSave(saveToken, thumbnailUrl);
    946959                }
    947960            },
    948961            onLoadAsync: async (currentTemplateNameOrSaveToken) => {
    949                 if (typeof context.onLoadAsync === "function") {
    950                     await context.onLoadAsync(currentTemplateNameOrSaveToken);
    951                 }
    952                 else if (typeof context.onLoad === "function") {
    953                     context.onLoad(currentTemplateNameOrSaveToken);
     962                if (typeof PrintessEditor.currentContext.onLoadAsync === "function") {
     963                    await PrintessEditor.currentContext.onLoadAsync(currentTemplateNameOrSaveToken);
     964                }
     965                else if (typeof PrintessEditor.currentContext.onLoad === "function") {
     966                    PrintessEditor.currentContext.onLoad(currentTemplateNameOrSaveToken);
    954967                }
    955968            },
     
    959972            }
    960973        };
    961         if (context) {
    962             context.save = function () {
    963                 that.save(callbacks);
    964             };
    965         }
     974        PrintessEditor.currentContext.save = function () {
     975            that.save(callbacks);
     976        };
    966977        if (this.usePanelUi()) {
    967             that.showBcUiVersion(context, callbacks);
     978            that.showBcUiVersion(callbacks);
    968979        }
    969980        else {
    970             const priceInfo = context.getPriceInfo();
     981            const priceInfo = PrintessEditor.currentContext.getPriceInfo();
    971982            let pageCount = null;
    972983            let formFields = null;
    973984            let mergeTemplates = null;
    974985            if (!isSaveToken) {
    975                 formFields = PrintessEditor.applyFormFieldMappings(context.getCurrentFormFieldValues(), context.getFormFieldMappings());
    976                 mergeTemplates = context.getMergeTemplates();
    977                 if (context.additionalAttachParams && typeof context.additionalAttachParams["pageCountFormField"] !== "undefined") {
    978                     const pageFormField = formFields.filter(x => x.name === context.additionalAttachParams["pageCountFormField"]);
     986                formFields = PrintessEditor.applyFormFieldMappings(PrintessEditor.currentContext.getCurrentFormFieldValues(), PrintessEditor.currentContext.getFormFieldMappings());
     987                mergeTemplates = PrintessEditor.currentContext.getMergeTemplates();
     988                if (PrintessEditor.currentContext.additionalAttachParams && typeof PrintessEditor.currentContext.additionalAttachParams["pageCountFormField"] !== "undefined") {
     989                    const pageFormField = formFields.filter(x => x.name === PrintessEditor.currentContext.additionalAttachParams["pageCountFormField"]);
    979990                    if (pageFormField && pageFormField.length > 0) {
    980991                        let intValue = PrintessEditor.extractNumber(pageFormField[0].value);
     
    985996                }
    986997            }
    987             const iFrame = await this.initializeIFrame(callbacks, context, this.Settings);
     998            const iFrame = await this.initializeIFrame(callbacks, this.Settings);
    988999            if (iFrame.getAttribute('data-attached') === "false") {
    9891000                try {
     
    9911002                        domain: that.Settings.apiDomain,
    9921003                        token: this.Settings.shopToken || "",
    993                         templateName: context.templateNameOrSaveToken,
     1004                        templateName: PrintessEditor.currentContext.templateNameOrSaveToken,
    9941005                        showBuyerSide: true,
    9951006                        templateUserId: '',
    996                         basketId: await PrintessEditor.getOrGenerateBasketId(context),
    997                         shopUserId: await PrintessEditor.getUserId(context),
     1007                        basketId: await PrintessEditor.getOrGenerateBasketId(),
     1008                        shopUserId: await PrintessEditor.getUserId(),
    9981009                        formFields: formFields,
    9991010                        snippetPriceCategoryLabels: priceInfo && priceInfo.snippetPrices ? priceInfo.snippetPrices : null,
     
    10011012                        skipExchangeStateApplication: true
    10021013                    };
    1003                     if (typeof context.showSplitterGridSizeButton !== "undefined" && context.showSplitterGridSizeButton !== null) {
    1004                         attachParams["showSplitterGridSizeButton"] = context.showSplitterGridSizeButton === true || context.showSplitterGridSizeButton === "true";
     1014                    if (typeof PrintessEditor.currentContext.showSplitterGridSizeButton !== "undefined" && PrintessEditor.currentContext.showSplitterGridSizeButton !== null) {
     1015                        attachParams["showSplitterGridSizeButton"] = PrintessEditor.currentContext.showSplitterGridSizeButton === true || PrintessEditor.currentContext.showSplitterGridSizeButton === "true";
    10051016                    }
    10061017                    const globalSettings = PrintessEditor.getGlobalShopSettings();
     
    10181029                        }
    10191030                    }
    1020                     if (context.additionalAttachParams) {
    1021                         for (const prop in context.additionalAttachParams) {
    1022                             if (context.additionalAttachParams.hasOwnProperty(prop)) {
    1023                                 attachParams[prop] = context.additionalAttachParams[prop];
     1031                    if (PrintessEditor.currentContext.additionalAttachParams) {
     1032                        for (const prop in PrintessEditor.currentContext.additionalAttachParams) {
     1033                            if (PrintessEditor.currentContext.additionalAttachParams.hasOwnProperty(prop)) {
     1034                                attachParams[prop] = PrintessEditor.currentContext.additionalAttachParams[prop];
    10241035                            }
    10251036                        }
     
    10421053                let undef;
    10431054                const loadParams = {
    1044                     templateNameOrToken: context.templateNameOrSaveToken,
     1055                    templateNameOrToken: PrintessEditor.currentContext.templateNameOrSaveToken,
    10451056                    mergeTemplates: mergeTemplates,
    10461057                    formFields: formFields,
     
    10571068                    }
    10581069                }
    1059                 if (context && context.additionalAttachParams) {
    1060                     if (context.additionalAttachParams.formFieldProperties) {
    1061                         loadParams.formFieldProperties = context.additionalAttachParams.formFieldProperties;
    1062                     }
    1063                     if (typeof context.additionalAttachParams.clearExchangeCaches !== "undefined") {
    1064                         loadParams.clearExchangeCaches = context.additionalAttachParams.clearExchangeCaches === false ? false : true;
     1070                if (PrintessEditor.currentContext && PrintessEditor.currentContext.additionalAttachParams) {
     1071                    if (PrintessEditor.currentContext.additionalAttachParams.formFieldProperties) {
     1072                        loadParams.formFieldProperties = PrintessEditor.currentContext.additionalAttachParams.formFieldProperties;
     1073                    }
     1074                    if (typeof PrintessEditor.currentContext.additionalAttachParams.clearExchangeCaches !== "undefined") {
     1075                        loadParams.clearExchangeCaches = PrintessEditor.currentContext.additionalAttachParams.clearExchangeCaches === false ? false : true;
    10651076                    }
    10661077                }
     
    10931104        if (!this.show.saveInterval) {
    10941105            this.show.saveInterval = setInterval(function () {
    1095                 if (that.visible && context.currentSaveTimerInMinutes !== null && context.currentSaveTimerInMinutes > 0 && typeof context.onSaveTimer === "function") {
     1106                if (PrintessEditor.visible && PrintessEditor.currentContext.currentSaveTimerInMinutes !== null && PrintessEditor.currentContext.currentSaveTimerInMinutes > 0 && typeof PrintessEditor.currentContext.onSaveTimer === "function") {
    10961107                    const timeDifferenceMs = ((new Date()).getTime() - that.lastSaveDate.getTime());
    1097                     if (timeDifferenceMs > (context.currentSaveTimerInMinutes * 60000)) {
     1108                    if (timeDifferenceMs > (PrintessEditor.currentContext.currentSaveTimerInMinutes * 60000)) {
    10981109                        that.lastSaveDate = new Date();
    1099                         context.onSaveTimer();
     1110                        PrintessEditor.currentContext.onSaveTimer();
    11001111                    }
    11011112                }
     
    11031114        }
    11041115    }
    1105     hide(context, closeButtonClicked) {
    1106         this.visible = false;
     1116    hide(closeButtonClicked) {
     1117        if (!PrintessEditor.visible) {
     1118            return;
     1119        }
     1120        PrintessEditor.visible = false;
    11071121        if (this.usePanelUi()) {
    11081122            const editor = this.getPrintessComponent();
     
    11221136            root[0].classList.remove('printess-editor-open');
    11231137        }
    1124         if (typeof context.editorClosed === "function") {
    1125             context.editorClosed(closeButtonClicked === true);
     1138        if (typeof PrintessEditor.currentContext.editorClosed === "function") {
     1139            PrintessEditor.currentContext.editorClosed(closeButtonClicked === true);
    11261140        }
    11271141    }
     
    11611175        }
    11621176    }
    1163 } function initPrintessEditor(shopToken, editorUrl, editorVersion, startupLogoUrl, showStartupAnimation, theme, startupBackgroundColor = "") {
     1177}
     1178PrintessEditor.visible = false; function initPrintessEditor(shopToken, editorUrl, editorVersion, startupLogoUrl, showStartupAnimation, theme, startupBackgroundColor = "") {
    11641179    let editorSettings;
    11651180    if (shopToken && typeof shopToken !== "string") {
  • printess-editor/trunk/includes/js/printessWoocommerce.js

    r3383399 r3389052  
    309309const initPrintessWCEditor = function (printessSettings) {
    310310    const CART_FORM_SELECTOR = "form.cart";
     311    const designNowButtonId = printessSettings.designNowButtonId || "printess-customize-button";
    311312    let itemUsage = null;
    312313    if (typeof window["printessWooEditor"] !== "undefined") {
     
    372373        }
    373374        return ret;
     375    };
     376    const readQuantityFromProductPage = () => {
     377        const form = document.querySelector(CART_FORM_SELECTOR);
     378        if (form) {
     379            const formData = new FormData(form);
     380            if (formData.has("quantity")) {
     381                const qty = parseInt(formData.get("quantity").toString());
     382                if (!isNaN(qty) && isFinite(qty) && qty > 0) {
     383                    return qty;
     384                }
     385            }
     386        }
     387        return 1;
     388    };
     389    const postTrackingEvent = (evt, context, product) => {
     390        if (!printessSettings.writeTrackingEvents) {
     391            return;
     392        }
     393        let variantOptions = "";
     394        const currentProductOptions = context.getCurrentFormFieldValues();
     395        PrintessSharedTools.forEach(currentProductOptions, (value, index, arr, key) => {
     396            if (variantOptions) {
     397                variantOptions += " | ";
     398            }
     399            variantOptions += key + ": " + value;
     400        });
     401        context.getPriceForFormFieldsAsync(currentProductOptions).then((price) => {
     402            const params = {
     403                item_id: product.id,
     404                item_name: product.name,
     405                variant: variantOptions,
     406                designId: context.templateNameOrSaveToken,
     407                price: price,
     408                quantity: readQuantityFromProductPage(),
     409                currency: printessSettings.priceFormatOptions?.currencySymbol || ""
     410            };
     411            if (typeof dataLayer !== "undefined" && typeof dataLayer.push === "function") {
     412                dataLayer.push({
     413                    event: evt,
     414                    ecommerce: {
     415                        items: [params]
     416                    }
     417                });
     418            }
     419            else {
     420                window.dispatchEvent(new CustomEvent("printess:" + evt, {
     421                    detail: params
     422                }));
     423            }
     424        });
    374425    };
    375426    const getCurrentVariant = function (productOptionValues, product) {
     
    10231074                        console.error(e);
    10241075                    }
     1076                    try {
     1077                        postTrackingEvent("add_to_cart_clicked", context, settings.product);
     1078                    }
     1079                    catch (e) {
     1080                        console.error(e);
     1081                    }
    10251082                    if (addToCartElement.type === "submit") {
    10261083                        addToCartElement.click();
     
    11721229                            console.error(e);
    11731230                        }
     1231                        try {
     1232                            postTrackingEvent("design_saved", context, settings.product);
     1233                        }
     1234                        catch (e) {
     1235                            console.error(e);
     1236                        }
    11741237                    }, (message) => {
    11751238                        hideInformationOverlay();
     
    11961259                }
    11971260                if ('buyer' === printessSettings.editorMode) { // Only buyer mode sets the token. The admin edit doesn't do anything!
     1261                    if (closeButtonClicked === true) {
     1262                        try {
     1263                            postTrackingEvent("editor_closed_without_add_to_cart", context, settings.product);
     1264                        }
     1265                        catch (e) {
     1266                            console.error(e);
     1267                        }
     1268                    }
    11981269                    //Remove saved design info
    11991270                    if (typeof URLSearchParams !== 'undefined') {
     
    12601331        designNameInput.setAttribute("name", "printess-design-name");
    12611332        designNameInput.setAttribute("type", "hidden");
    1262         customizeButton.setAttribute("id", "printess-customize-button");
     1333        customizeButton.setAttribute("id", designNowButtonId);
    12631334        customizeButton.setAttribute("name", "printess-customize-button");
    12641335        customizeButton.setAttribute("type", "button");
    12651336        customizeButton.setAttribute("onclick", "showPrintessEditor();");
    1266         customizeButton.classList.add("wp-element-button", "single_add_to_cart_button", "button", "alt");
     1337        if (printessSettings.hideCustomDesignNowButtonClasses !== true) {
     1338            customizeButton.classList.add("wp-element-button", "single_add_to_cart_button", "button", "alt");
     1339        }
    12671340        if (printessSettings.customizeButtonClasses) {
    12681341            printessSettings.customizeButtonClasses.split(" ").forEach((x) => {
     
    12921365    };
    12931366    const showCustomizeButton = function (show) {
    1294         const customizeButton = document.getElementsByName("printess-customize-button");
     1367        const customizeButton = document.getElementById(designNowButtonId);
    12951368        const addToCartButton = document.querySelector(CART_FORM_SELECTOR + " button.single_add_to_cart_button");
    1296         if (!customizeButton || customizeButton.length === 0) {
     1369        if (!customizeButton) {
    12971370            return;
    12981371        }
     
    13061379            addToCartButton.style.display = show ? "none" : "inline-block";
    13071380        }
    1308         customizeButton.forEach((x) => (x).style.display = show ? "inline-block" : "none");
     1381        customizeButton.style.display = show ? "inline-block" : "none";
    13091382    };
    13101383    const variantChangedHandler = function (product) {
     
    14181491            }
    14191492            if (typeof window["initPrintessEditor"] === "function") {
     1493                try {
     1494                    postTrackingEvent(shopContext.templateNameOrSaveToken ? (shopContext.templateNameOrSaveToken.startsWith("st:") ? "editor_opened_save_token" : "editor_opened_new_design") : "editor_opened_new_design", shopContext, settings.product);
     1495                }
     1496                catch (e) {
     1497                    console.error(e);
     1498                }
    14201499                const editor = window["initPrintessEditor"](printessSettings);
    14211500                editor.show(shopContext);
  • printess-editor/trunk/includes/printess-admin-settings.php

    r3383399 r3389052  
    128128
    129129    /**
     130     * Gets the Printess customize button id.
     131     */
     132    static function get_customize_button_id() {
     133        $ret = get_option( 'printess_customize_button_id', '' );
     134
     135        if(!isset($ret) || empty($ret)) {
     136            return "printess-customize-button";
     137        }
     138
     139        return $ret;
     140    }
     141
     142    /**
     143     * Returns true in case the internal printess customize button classes should not be rendered
     144     */
     145    static function hide_internal_customize_button_classes() {
     146        $setting = get_option( 'printess_hide_internal_customize_button_classes', '' );
     147
     148        if ( 'on' === $setting ) {
     149            return true;
     150        }
     151
     152        return false;
     153    }
     154
     155    /**
     156     * Returns true in case the plugin should send tracking events to the dom
     157     */
     158    static function write_tracking_events() {
     159        $setting = get_option( 'printess_write_tracking_events', '' );
     160
     161        if ( 'on' === $setting ) {
     162            return true;
     163        }
     164
     165        return false;
     166    }
     167
     168    /**
    130169     * Gets the Printess default editor theme.
    131170     */
     
    412451
    413452        add_settings_field(
     453            'printess_customize_button_class',
     454            __( 'Additional classes for customize button', 'printess-editor' ),
     455            function() {
     456                $setting = PrintessAdminSettings::get_customize_button_class();
     457
     458                ?><input type="text" style="min-width: 50%;" name="printess_customize_button_class" value="<?php echo esc_attr( $setting ); ?>"><?php
     459            },
     460            'printess-settings',
     461            'printess_settings_section'
     462        );
     463
     464        register_setting(
     465            'printess-settings',
     466            'printess_hide_internal_customize_button_classes',
     467            array(
     468                'type'    => 'boolean',
     469                'default' => true,
     470            )
     471        );
     472
     473        add_settings_field(
     474            'printess_hide_internal_customize_button_classes',
     475            __( 'Hide default customize button classes', 'printess-editor' ),
     476            function() {
     477                $setting = get_option( 'printess_hide_internal_customize_button_classes', 'off' );
     478                $checked = '';
     479
     480                if ( 'on' === $setting ) {
     481                    $checked = 'checked';
     482                }
     483
     484                ?>
     485
     486                <input type="checkbox" name="printess_hide_internal_customize_button_classes" <?php echo esc_html( $checked ); ?>>
     487
     488                <?php
     489            },
     490            'printess-settings',
     491            'printess_settings_section'
     492        );
     493
     494        register_setting(
     495            'printess-settings',
     496            'printess_customize_button_id',
     497            array(
     498                'type'    => 'boolean',
     499                'default' => true,
     500            )
     501        );
     502
     503        add_settings_field(
     504            'printess_customize_button_id',
     505            __( 'Customize button id', 'printess-editor' ),
     506            function() {
     507                $setting = PrintessAdminSettings::get_customize_button_id();
     508
     509                ?><input type="text" style="min-width: 50%;" name="printess_customize_button_id" value="<?php echo esc_attr( $setting ); ?>"><?php
     510            },
     511            'printess-settings',
     512            'printess_settings_section'
     513        );
     514
     515        add_settings_field(
    414516            'printess_ids_to_hide',
    415517            __( 'Ids to hide when showing editor', 'printess-editor' ),
     
    451553                'default' => 'wp-site-blocks',
    452554            )
    453         );
    454 
    455         add_settings_field(
    456             'printess_customize_button_class',
    457             __( 'Additional classes for customize button', 'printess-editor' ),
    458             function() {
    459                 $setting = PrintessAdminSettings::get_customize_button_class();
    460 
    461                 ?><input type="text" style="min-width: 50%;" name="printess_customize_button_class" value="<?php echo esc_attr( $setting ); ?>"><?php
    462             },
    463             'printess-settings',
    464             'printess_settings_section'
    465555        );
    466556
     
    13841474            'printess_settings_section'
    13851475        );
     1476
     1477        register_setting(
     1478            'printess-settings',
     1479            'printess_write_tracking_events',
     1480            array(
     1481                'type'    => 'boolean',
     1482                'default' => true,
     1483            )
     1484        );
     1485
     1486        add_settings_field(
     1487            'printess_write_tracking_events',
     1488            __( 'Write tracking events to DOM', 'printess-editor' ),
     1489            function() {
     1490                $setting = get_option( 'printess_write_tracking_events', 'off' );
     1491                $checked = '';
     1492
     1493                if ( 'on' === $setting ) {
     1494                    $checked = 'checked';
     1495                }
     1496
     1497                ?>
     1498
     1499                <input type="checkbox" name="printess_write_tracking_events" <?php echo esc_html( $checked ); ?>>
     1500
     1501                <?php
     1502            },
     1503            'printess-settings',
     1504            'printess_settings_section'
     1505        );
    13861506    }
    13871507}
Note: See TracChangeset for help on using the changeset viewer.