From eaa8006e8d78d35d2e7c0218b7f5f9efa5454c8e Mon Sep 17 00:00:00 2001 From: Andrew Cummings Date: Sat, 23 Mar 2024 10:03:14 -0700 Subject: [PATCH 01/10] coding exercise answers --- dt-assets/js/settings.js | 566 ++++++++++++++++++++++----------------- 1 file changed, 313 insertions(+), 253 deletions(-) diff --git a/dt-assets/js/settings.js b/dt-assets/js/settings.js index 4f1e083895..eef8b48789 100644 --- a/dt-assets/js/settings.js +++ b/dt-assets/js/settings.js @@ -1,56 +1,56 @@ -jQuery(document).ready(function() { - window.current_user_lookup = window.wpApiSettingsPage.current_user_id - load_locations() +jQuery(document).ready(function () { + window.current_user_lookup = window.wpApiSettingsPage.current_user_id; + load_locations(); +}); -}) - -function app_switch (app_key = null) { - let a = jQuery('#app_link_' + app_key) - a.empty().html(``) - window.makeRequest('post', 'users/app_switch', { app_key }) - .done(function(data) { - if ('removed' === data) { - jQuery('#app_link_' + app_key).empty() +function app_switch(app_key = null) { + let a = jQuery("#app_link_" + app_key); + a.empty().html(``); + window + .makeRequest("post", "users/app_switch", { app_key }) + .done(function (data) { + if ("removed" === data) { + jQuery("#app_link_" + app_key).empty(); } else { - let u = a.data('url-base') + let u = a.data("url-base"); a.empty().html( ` ` - ) - load_user_app_copy_to_clipboard_listener() + ); + load_user_app_copy_to_clipboard_listener(); } }) .fail(function (err) { console.log("error"); console.log(err); - a.empty().html(`error`) + a.empty().html(`error`); }); } function load_user_app_copy_to_clipboard_listener() { - jQuery('.copy_to_clipboard').on('click', function(){ - let str = jQuery(this).data('value') - const el = document.createElement('textarea'); + jQuery(".copy_to_clipboard").on("click", function () { + let str = jQuery(this).data("value"); + const el = document.createElement("textarea"); el.value = str; - el.setAttribute('readonly', ''); - el.style.position = 'absolute'; - el.style.left = '-9999px'; + el.setAttribute("readonly", ""); + el.style.position = "absolute"; + el.style.left = "-9999px"; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); - document.execCommand('copy'); + document.execCommand("copy"); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } - alert('Copied') - }) + alert("Copied"); + }); } -load_user_app_copy_to_clipboard_listener() +load_user_app_copy_to_clipboard_listener(); /** * Password reset @@ -59,100 +59,119 @@ load_user_app_copy_to_clipboard_listener() * @param type * @returns {*} */ -function switch_preference (preference_key, type = null) { - return window.makeRequest('post', 'users/switch_preference', { preference_key, type}) +function switch_preference(preference_key, type = null) { + return window.makeRequest("post", "users/switch_preference", { + preference_key, + type, + }); } function change_password() { - let translation = window.wpApiSettingsPage.translations - // test matching passwords - const p1 = jQuery('#password1') - const p2 = jQuery('#password2') - const message = jQuery('#password-message') + let translation = window.wpApiSettingsPage.translations; + // test matching passwords + const p1 = jQuery("#password1"); + const p2 = jQuery("#password2"); + const message = jQuery("#password-message"); - message.empty() + message.empty(); - if (p1.val() !== p2.val()) { - message.append(translation.pass_does_not_match) - return - } + if (p1.val() !== p2.val()) { + message.append(translation.pass_does_not_match); + return; + } - window.makeRequest('post', 'users/change_password', { password: p1 }).done(data => { - console.log( data ) - message.html(translation.changed) - }).fail(window.handleAjaxError) + window + .makeRequest("post", "users/change_password", { password: p1 }) + .done((data) => { + console.log(data); + message.html(translation.changed); + }) + .fail(window.handleAjaxError); } function load_locations() { - window.makeRequest( "GET", `user/my` ) - .done(data=>{ - - - if ( typeof window.dtMapbox !== "undefined" ) { - window.dtMapbox.post_type = 'user' - window.write_results_box() - + window + .makeRequest("GET", `user/my`) + .done((data) => { + if (typeof window.dtMapbox !== "undefined") { + window.dtMapbox.post_type = "user"; + window.write_results_box(); } else { //locations - let typeahead = window.Typeahead['.js-typeahead-location_grid'] + let typeahead = window.Typeahead[".js-typeahead-location_grid"]; if (typeahead) { typeahead.items = []; - typeahead.comparedItems =[]; + typeahead.comparedItems = []; typeahead.label.container.empty(); - typeahead.adjustInputSize() + typeahead.adjustInputSize(); } - if ( typeof data.locations.location_grid !== "undefined" ) { - data.locations.location_grid.forEach(location => { - typeahead.addMultiselectItemLayout({ID: location.id.toString(), name: location.label}) - }) + if (typeof data.locations.location_grid !== "undefined") { + data.locations.location_grid.forEach((location) => { + typeahead.addMultiselectItemLayout({ + ID: location.id.toString(), + name: location.label, + }); + }); } - } - }).catch((e)=>{ - console.log( 'error in locations') - console.log( e) - }) + }) + .catch((e) => { + console.log("error in locations"); + console.log(e); + }); } -if ( typeof window.dtMapbox === "undefined" ) { - let typeaheadTotals = {} - if (!window.Typeahead['.js-typeahead-location_grid'] ){ +if (typeof window.dtMapbox === "undefined") { + let typeaheadTotals = {}; + if (!window.Typeahead[".js-typeahead-location_grid"]) { jQuery.typeahead({ - input: '.js-typeahead-location_grid', + input: ".js-typeahead-location_grid", minLength: 0, accent: true, searchOnFocus: true, maxItem: 20, - dropdownFilter: [{ - key: 'group', - value: 'focus', - template: window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.regions_of_focus), - all: window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.all_locations), - }], + dropdownFilter: [ + { + key: "group", + value: "focus", + template: window.SHAREDFUNCTIONS.escapeHTML( + window.wpApiShare.translations.regions_of_focus + ), + all: window.SHAREDFUNCTIONS.escapeHTML( + window.wpApiShare.translations.all_locations + ), + }, + ], source: { focus: { display: "name", ajax: { - url: window.wpApiShare.root + 'dt/v1/mapping_module/search_location_grid_by_name', + url: + window.wpApiShare.root + + "dt/v1/mapping_module/search_location_grid_by_name", data: { s: "{{query}}", filter: function () { - return window.lodash.get(window.Typeahead['.js-typeahead-location_grid'].filters.dropdown, 'value', 'all') - } + // return window.lodash.get(window.Typeahead['.js-typeahead-location_grid'].filters.dropdown, 'value', 'all') + const { dropdown } = + window.Typeahead[".js-typeahead-location_grid"].filters; + const value = dropdown?.value ?? "all"; + return value; + }, }, beforeSend: function (xhr) { - xhr.setRequestHeader('X-WP-Nonce', window.wpApiShare.nonce); + xhr.setRequestHeader("X-WP-Nonce", window.wpApiShare.nonce); }, callback: { done: function (data) { if (typeof window.typeaheadTotals !== "undefined") { - window.typeaheadTotals.field = data.total + window.typeaheadTotals.field = data.total; } - return data.location_grid - } - } - } - } + return data.location_grid; + }, + }, + }, + }, }, display: "name", templateValue: "{{name}}", @@ -161,197 +180,234 @@ if ( typeof window.dtMapbox === "undefined" ) { matchOn: ["ID"], data: function () { return []; - }, callback: { + }, + callback: { onCancel: function (node, item) { - delete_location_grid( item.ID) - } - } + delete_location_grid(item.ID); + }, + }, }, callback: { - onClick: function(node, a, item, event){ - add_location_grid( item.ID) + onClick: function (node, a, item, event) { + add_location_grid(item.ID); }, - onReady(){ - this.filters.dropdown = {key: "group", value: "focus", template: window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.regions_of_focus)} + onReady() { + this.filters.dropdown = { + key: "group", + value: "focus", + template: window.SHAREDFUNCTIONS.escapeHTML( + window.wpApiShare.translations.regions_of_focus + ), + }; this.container .removeClass("filter") .find("." + this.options.selector.filterButton) - .html(window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.regions_of_focus)); + .html( + window.SHAREDFUNCTIONS.escapeHTML( + window.wpApiShare.translations.regions_of_focus + ) + ); }, onResult: function (node, query, result, resultCount) { - resultCount = typeaheadTotals.location_grid - let text = window.TYPEAHEADS.typeaheadHelpText(resultCount, query, result) - jQuery('#location_grid-result-container').html(text); + resultCount = typeaheadTotals.location_grid; + let text = window.TYPEAHEADS.typeaheadHelpText( + resultCount, + query, + result + ); + jQuery("#location_grid-result-container").html(text); }, onHideLayout: function () { - jQuery('#location_grid-result-container').html(""); - } - } + jQuery("#location_grid-result-container").html(""); + }, + }, }); } } -let add_location_grid = ( value )=>{ - let data = { - grid_id: value - } - return window.makeRequest( "POST", `users/user_location`, data ) -} -let delete_location_grid = ( value )=>{ - let data = { - grid_id: value - } - return window.makeRequest( "DELETE", `users/user_location`, data ) -} +let add_location_grid = (value) => { + let data = { + grid_id: value, + }; + return window.makeRequest("POST", `users/user_location`, data); +}; +let delete_location_grid = (value) => { + let data = { + grid_id: value, + }; + return window.makeRequest("DELETE", `users/user_location`, data); +}; - -let update_user = ( key, value )=>{ - let data = { - [key]: value - } - return window.makeRequest( "POST", `user/update`, data , 'dt/v1/' ) -} +let update_user = (key, value) => { + let data = { + [key]: value, + }; + return window.makeRequest("POST", `user/update`, data, "dt/v1/"); +}; /** * Set availability dates */ -let dateFields = [ "start_date", "end_date" ] - dateFields.forEach(key=>{ - let datePicker = jQuery(`#${key}.date-picker`) - datePicker.datepicker({ - onSelect: function (date) { - let start_date = jQuery('#start_date').val() - let end_date = jQuery('#end_date').val() - if ( start_date && end_date && ( window.moment(start_date) < window.moment(end_date) )){ - jQuery('#add_unavailable_dates').removeAttr("disabled"); - } else { - jQuery('#add_unavailable_dates').attr("disabled", true); - } - }, - dateFormat: 'yy-mm-dd', - changeMonth: true, - changeYear: true, - yearRange: "-20:+10", - }) - }) +let dateFields = ["start_date", "end_date"]; +dateFields.forEach((key) => { + let datePicker = jQuery(`#${key}.date-picker`); + datePicker.datepicker({ + onSelect: function (date) { + let start_date = jQuery("#start_date").val(); + let end_date = jQuery("#end_date").val(); + if ( + start_date && + end_date && + window.moment(start_date) < window.moment(end_date) + ) { + jQuery("#add_unavailable_dates").removeAttr("disabled"); + } else { + jQuery("#add_unavailable_dates").attr("disabled", true); + } + }, + dateFormat: "yy-mm-dd", + changeMonth: true, + changeYear: true, + yearRange: "-20:+10", + }); +}); -jQuery('#add_unavailable_dates').on('click', function () { - let start_date = jQuery('#start_date').val() - let end_date = jQuery('#end_date').val() - jQuery('#add_unavailable_dates_spinner').addClass('active') - update_user( 'add_unavailability', {start_date, end_date}).then((resp)=>{ - jQuery('#add_unavailable_dates_spinner').removeClass('active') - jQuery('#start_date').val('') - jQuery('#end_date').val('') - display_dates_unavailable(resp) - }) -}) -let display_dates_unavailable = (list = [], first_run )=>{ - let date_unavailable_table = jQuery('#unavailable-list') - let rows = `` - list = window.lodash.orderBy( list, [ "start_date" ], "desc") - list.forEach(range=>{ +jQuery("#add_unavailable_dates").on("click", function () { + let start_date = jQuery("#start_date").val(); + let end_date = jQuery("#end_date").val(); + jQuery("#add_unavailable_dates_spinner").addClass("active"); + update_user("add_unavailability", { start_date, end_date }).then((resp) => { + jQuery("#add_unavailable_dates_spinner").removeClass("active"); + jQuery("#start_date").val(""); + jQuery("#end_date").val(""); + display_dates_unavailable(resp); + }); +}); +let display_dates_unavailable = (list = [], first_run) => { + let date_unavailable_table = jQuery("#unavailable-list"); + let rows = ``; + // list = window.lodash.orderBy( list, [ "start_date" ], "desc") + list.sort((a, b) => new Date(b.start_date) - new Date(a.start_date)); + list.forEach((range) => { rows += ` ${window.SHAREDFUNCTIONS.escapeHTML(range.start_date)} ${window.SHAREDFUNCTIONS.escapeHTML(range.end_date)} - + - ` - }) - if ( rows || ( !rows && !first_run ) ){ - date_unavailable_table.html(rows) + `; + }); + if (rows || (!rows && !first_run)) { + date_unavailable_table.html(rows); } -} -display_dates_unavailable( window.wpApiSettingsPage.custom_data.availability, true ) -jQuery( document).on( 'click', '.remove_dates_unavailable', function () { - let id = jQuery(this).data('id'); - update_user( 'remove_unavailability', id).then((resp)=>{ - display_dates_unavailable(resp) - }) -}) +}; +display_dates_unavailable( + window.wpApiSettingsPage.custom_data.availability, + true +); +jQuery(document).on("click", ".remove_dates_unavailable", function () { + let id = jQuery(this).data("id"); + update_user("remove_unavailability", id).then((resp) => { + display_dates_unavailable(resp); + }); +}); -let status_buttons = jQuery('.status-button') -let color_workload_buttons = (name) =>{ - status_buttons.css('background-color', "") - status_buttons.addClass("hollow") - if ( name ){ - let selected = jQuery(`.status-button[name=${name}]`) - selected.removeClass("hollow") - selected.css('background-color', window.lodash.get(window.wpApiSettingsPage, `workload_status_options.${name}.color`)) - selected.blur() +let status_buttons = jQuery(".status-button"); +let color_workload_buttons = (name) => { + status_buttons.css("background-color", ""); + status_buttons.addClass("hollow"); + if (name) { + let selected = jQuery(`.status-button[name=${name}]`); + selected.removeClass("hollow"); + const color = + window.wpApiSettingsPage?.workload_status_options?.[name]?.color; + selected.css("background-color", color); + // selected.css('background-color', window.lodash.get(window.wpApiSettingsPage, `workload_status_options.${name}.color`)) + selected.blur(); } -} -color_workload_buttons(window.wpApiSettingsPage.workload_status ) -status_buttons.on( 'click', function () { - jQuery("#workload-spinner").addClass("active") - let name = jQuery(this).attr('name') - color_workload_buttons(name) - update_user( 'workload_status', name ) - .then(()=>{ - jQuery("#workload-spinner").removeClass("active") - }).fail(()=>{ - status_buttons.css('background-color', "") - jQuery("#workload-spinner").removeClass("active") - status_buttons.addClass("hollow") - }) -}) - +}; +color_workload_buttons(window.wpApiSettingsPage.workload_status); +status_buttons.on("click", function () { + jQuery("#workload-spinner").addClass("active"); + let name = jQuery(this).attr("name"); + color_workload_buttons(name); + update_user("workload_status", name) + .then(() => { + jQuery("#workload-spinner").removeClass("active"); + }) + .fail(() => { + status_buttons.css("background-color", ""); + jQuery("#workload-spinner").removeClass("active"); + status_buttons.addClass("hollow"); + }); +}); -jQuery('button.dt_multi_select').on('click',function () { - let fieldKey = jQuery(this).data("field-key") - let optionKey = jQuery(this).attr('id') - jQuery(`#${fieldKey}-spinner`).addClass("active") - let field = jQuery(`[data-field-key="${fieldKey}"]#${optionKey}`) - field.addClass("submitting-select-button") - let action = "add" - let update_request = null - if (field.hasClass("selected-select-button")){ - action = "delete" - update_request = update_user( 'remove_' + fieldKey, optionKey ) +jQuery("button.dt_multi_select").on("click", function () { + let fieldKey = jQuery(this).data("field-key"); + let optionKey = jQuery(this).attr("id"); + jQuery(`#${fieldKey}-spinner`).addClass("active"); + let field = jQuery(`[data-field-key="${fieldKey}"]#${optionKey}`); + field.addClass("submitting-select-button"); + let action = "add"; + let update_request = null; + if (field.hasClass("selected-select-button")) { + action = "delete"; + update_request = update_user("remove_" + fieldKey, optionKey); } else { - field.removeClass("empty-select-button") - field.addClass("selected-select-button") - update_request = update_user( 'add_' + fieldKey, optionKey ) + field.removeClass("empty-select-button"); + field.addClass("selected-select-button"); + update_request = update_user("add_" + fieldKey, optionKey); } - update_request.then(()=>{ - field.removeClass("submitting-select-button selected-select-button") - field.blur(); - field.addClass( action === "delete" ? "empty-select-button" : "selected-select-button"); - jQuery(`#${fieldKey}-spinner`).removeClass("active") - }).catch(err=>{ - field.removeClass("submitting-select-button selected-select-button") - field.addClass( action === "add" ? "empty-select-button" : "selected-select-button") - window.handleAjaxError(err) - }) -}) -jQuery('select.select-field').change(e => { - const id = jQuery(e.currentTarget).attr('id') - const val = jQuery(e.currentTarget).val() - jQuery(`#${id}-spinner`).addClass("active") - update_user(id, val).then(()=>{ - jQuery(`#${id}-spinner`).removeClass("active") - }).catch(window.handleAjaxError) -}) -jQuery('input[name="email-preference"]').on('change', (e) => { - const optionId = e.target.id.replace('-preference', '') - const loadingSpinner = jQuery('#email-preference-spinner') - loadingSpinner.addClass('active') - update_user('email-preference', optionId) - .then(() => { - loadingSpinner.removeClass('active') - }) - .fail(() => { - loadingSpinner.removeClass('active') - }) -}) + update_request + .then(() => { + field.removeClass("submitting-select-button selected-select-button"); + field.blur(); + field.addClass( + action === "delete" ? "empty-select-button" : "selected-select-button" + ); + jQuery(`#${fieldKey}-spinner`).removeClass("active"); + }) + .catch((err) => { + field.removeClass("submitting-select-button selected-select-button"); + field.addClass( + action === "add" ? "empty-select-button" : "selected-select-button" + ); + window.handleAjaxError(err); + }); +}); +jQuery("select.select-field").change((e) => { + const id = jQuery(e.currentTarget).attr("id"); + const val = jQuery(e.currentTarget).val(); + jQuery(`#${id}-spinner`).addClass("active"); + update_user(id, val) + .then(() => { + jQuery(`#${id}-spinner`).removeClass("active"); + }) + .catch(window.handleAjaxError); +}); +jQuery('input[name="email-preference"]').on("change", (e) => { + const optionId = e.target.id.replace("-preference", ""); + const loadingSpinner = jQuery("#email-preference-spinner"); + loadingSpinner.addClass("active"); + update_user("email-preference", optionId) + .then(() => { + loadingSpinner.removeClass("active"); + }) + .fail(() => { + loadingSpinner.removeClass("active"); + }); +}); /** * People groups */ -if ( jQuery('.js-typeahead-people_groups').length) { +if (jQuery(".js-typeahead-people_groups").length) { jQuery.typeahead({ - input: '.js-typeahead-people_groups', + input: ".js-typeahead-people_groups", minLength: 0, accent: true, searchOnFocus: true, @@ -361,40 +417,44 @@ if ( jQuery('.js-typeahead-people_groups').length) { display: ["name", "label"], templateValue: function () { if (this.items[this.items.length - 1].label) { - return "{{label}}" + return "{{label}}"; } else { - return "{{name}}" + return "{{name}}"; } }, dynamic: true, multiselect: { matchOn: ["ID"], data: function () { - return window.wpApiSettingsPage.user_people_groups.map(g => { - return {ID: g.ID, name: g.post_title}; - }) + return window.wpApiSettingsPage.user_people_groups.map((g) => { + return { ID: g.ID, name: g.post_title }; + }); }, callback: { onCancel: function (node, item) { - update_user('remove_people_groups', item.ID) - } + update_user("remove_people_groups", item.ID); + }, }, }, callback: { onClick: function (node, a, item, event) { - update_user('add_people_groups', item.ID) - this.addMultiselectItemLayout(item) - event.preventDefault() + update_user("add_people_groups", item.ID); + this.addMultiselectItemLayout(item); + event.preventDefault(); this.hideLayout(); this.resetInput(); }, onResult: function (node, query, result, resultCount) { - let text = window.TYPEAHEADS.typeaheadHelpText(resultCount, query, result) - jQuery('#people_groups-result-container').html(text); + let text = window.TYPEAHEADS.typeaheadHelpText( + resultCount, + query, + result + ); + jQuery("#people_groups-result-container").html(text); }, onHideLayout: function () { - jQuery('#people_groups-result-container').html(""); - } - } - }) + jQuery("#people_groups-result-container").html(""); + }, + }, + }); } From 112a29928519474b26696b1f10e43a93545eea3c Mon Sep 17 00:00:00 2001 From: Andrew Cummings Date: Wed, 27 Mar 2024 16:20:51 -0700 Subject: [PATCH 02/10] coding exercise remove linting --- dt-assets/js/settings.js | 554 ++++++++++++++++++--------------------- 1 file changed, 251 insertions(+), 303 deletions(-) diff --git a/dt-assets/js/settings.js b/dt-assets/js/settings.js index eef8b48789..81874efb17 100644 --- a/dt-assets/js/settings.js +++ b/dt-assets/js/settings.js @@ -1,56 +1,56 @@ -jQuery(document).ready(function () { - window.current_user_lookup = window.wpApiSettingsPage.current_user_id; - load_locations(); -}); +jQuery(document).ready(function() { + window.current_user_lookup = window.wpApiSettingsPage.current_user_id + load_locations() -function app_switch(app_key = null) { - let a = jQuery("#app_link_" + app_key); - a.empty().html(``); - window - .makeRequest("post", "users/app_switch", { app_key }) - .done(function (data) { - if ("removed" === data) { - jQuery("#app_link_" + app_key).empty(); +}) + +function app_switch (app_key = null) { + let a = jQuery('#app_link_' + app_key) + a.empty().html(``) + window.makeRequest('post', 'users/app_switch', { app_key }) + .done(function(data) { + if ('removed' === data) { + jQuery('#app_link_' + app_key).empty() } else { - let u = a.data("url-base"); + let u = a.data('url-base') a.empty().html( ` ` - ); - load_user_app_copy_to_clipboard_listener(); + ) + load_user_app_copy_to_clipboard_listener() } }) .fail(function (err) { console.log("error"); console.log(err); - a.empty().html(`error`); + a.empty().html(`error`) }); } function load_user_app_copy_to_clipboard_listener() { - jQuery(".copy_to_clipboard").on("click", function () { - let str = jQuery(this).data("value"); - const el = document.createElement("textarea"); + jQuery('.copy_to_clipboard').on('click', function(){ + let str = jQuery(this).data('value') + const el = document.createElement('textarea'); el.value = str; - el.setAttribute("readonly", ""); - el.style.position = "absolute"; - el.style.left = "-9999px"; + el.setAttribute('readonly', ''); + el.style.position = 'absolute'; + el.style.left = '-9999px'; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); - document.execCommand("copy"); + document.execCommand('copy'); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } - alert("Copied"); - }); + alert('Copied') + }) } -load_user_app_copy_to_clipboard_listener(); +load_user_app_copy_to_clipboard_listener() /** * Password reset @@ -59,96 +59,81 @@ load_user_app_copy_to_clipboard_listener(); * @param type * @returns {*} */ -function switch_preference(preference_key, type = null) { - return window.makeRequest("post", "users/switch_preference", { - preference_key, - type, - }); +function switch_preference (preference_key, type = null) { + return window.makeRequest('post', 'users/switch_preference', { preference_key, type}) } function change_password() { - let translation = window.wpApiSettingsPage.translations; - // test matching passwords - const p1 = jQuery("#password1"); - const p2 = jQuery("#password2"); - const message = jQuery("#password-message"); + let translation = window.wpApiSettingsPage.translations + // test matching passwords + const p1 = jQuery('#password1') + const p2 = jQuery('#password2') + const message = jQuery('#password-message') - message.empty(); + message.empty() - if (p1.val() !== p2.val()) { - message.append(translation.pass_does_not_match); - return; - } + if (p1.val() !== p2.val()) { + message.append(translation.pass_does_not_match) + return + } - window - .makeRequest("post", "users/change_password", { password: p1 }) - .done((data) => { - console.log(data); - message.html(translation.changed); - }) - .fail(window.handleAjaxError); + window.makeRequest('post', 'users/change_password', { password: p1 }).done(data => { + console.log( data ) + message.html(translation.changed) + }).fail(window.handleAjaxError) } function load_locations() { - window - .makeRequest("GET", `user/my`) - .done((data) => { - if (typeof window.dtMapbox !== "undefined") { - window.dtMapbox.post_type = "user"; - window.write_results_box(); + window.makeRequest( "GET", `user/my` ) + .done(data=>{ + + + if ( typeof window.dtMapbox !== "undefined" ) { + window.dtMapbox.post_type = 'user' + window.write_results_box() + } else { //locations - let typeahead = window.Typeahead[".js-typeahead-location_grid"]; + let typeahead = window.Typeahead['.js-typeahead-location_grid'] if (typeahead) { typeahead.items = []; - typeahead.comparedItems = []; + typeahead.comparedItems =[]; typeahead.label.container.empty(); - typeahead.adjustInputSize(); + typeahead.adjustInputSize() } - if (typeof data.locations.location_grid !== "undefined") { - data.locations.location_grid.forEach((location) => { - typeahead.addMultiselectItemLayout({ - ID: location.id.toString(), - name: location.label, - }); - }); + if ( typeof data.locations.location_grid !== "undefined" ) { + data.locations.location_grid.forEach(location => { + typeahead.addMultiselectItemLayout({ID: location.id.toString(), name: location.label}) + }) } + } - }) - .catch((e) => { - console.log("error in locations"); - console.log(e); - }); + }).catch((e)=>{ + console.log( 'error in locations') + console.log( e) + }) } -if (typeof window.dtMapbox === "undefined") { - let typeaheadTotals = {}; - if (!window.Typeahead[".js-typeahead-location_grid"]) { +if ( typeof window.dtMapbox === "undefined" ) { + let typeaheadTotals = {} + if (!window.Typeahead['.js-typeahead-location_grid'] ){ jQuery.typeahead({ - input: ".js-typeahead-location_grid", + input: '.js-typeahead-location_grid', minLength: 0, accent: true, searchOnFocus: true, maxItem: 20, - dropdownFilter: [ - { - key: "group", - value: "focus", - template: window.SHAREDFUNCTIONS.escapeHTML( - window.wpApiShare.translations.regions_of_focus - ), - all: window.SHAREDFUNCTIONS.escapeHTML( - window.wpApiShare.translations.all_locations - ), - }, - ], + dropdownFilter: [{ + key: 'group', + value: 'focus', + template: window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.regions_of_focus), + all: window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.all_locations), + }], source: { focus: { display: "name", ajax: { - url: - window.wpApiShare.root + - "dt/v1/mapping_module/search_location_grid_by_name", + url: window.wpApiShare.root + 'dt/v1/mapping_module/search_location_grid_by_name', data: { s: "{{query}}", filter: function () { @@ -157,21 +142,21 @@ if (typeof window.dtMapbox === "undefined") { window.Typeahead[".js-typeahead-location_grid"].filters; const value = dropdown?.value ?? "all"; return value; - }, + } }, beforeSend: function (xhr) { - xhr.setRequestHeader("X-WP-Nonce", window.wpApiShare.nonce); + xhr.setRequestHeader('X-WP-Nonce', window.wpApiShare.nonce); }, callback: { done: function (data) { if (typeof window.typeaheadTotals !== "undefined") { - window.typeaheadTotals.field = data.total; + window.typeaheadTotals.field = data.total } - return data.location_grid; - }, - }, - }, - }, + return data.location_grid + } + } + } + } }, display: "name", templateValue: "{{name}}", @@ -180,234 +165,201 @@ if (typeof window.dtMapbox === "undefined") { matchOn: ["ID"], data: function () { return []; - }, - callback: { + }, callback: { onCancel: function (node, item) { - delete_location_grid(item.ID); - }, - }, + delete_location_grid( item.ID) + } + } }, callback: { - onClick: function (node, a, item, event) { - add_location_grid(item.ID); + onClick: function(node, a, item, event){ + add_location_grid( item.ID) }, - onReady() { - this.filters.dropdown = { - key: "group", - value: "focus", - template: window.SHAREDFUNCTIONS.escapeHTML( - window.wpApiShare.translations.regions_of_focus - ), - }; + onReady(){ + this.filters.dropdown = {key: "group", value: "focus", template: window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.regions_of_focus)} this.container .removeClass("filter") .find("." + this.options.selector.filterButton) - .html( - window.SHAREDFUNCTIONS.escapeHTML( - window.wpApiShare.translations.regions_of_focus - ) - ); + .html(window.SHAREDFUNCTIONS.escapeHTML(window.wpApiShare.translations.regions_of_focus)); }, onResult: function (node, query, result, resultCount) { - resultCount = typeaheadTotals.location_grid; - let text = window.TYPEAHEADS.typeaheadHelpText( - resultCount, - query, - result - ); - jQuery("#location_grid-result-container").html(text); + resultCount = typeaheadTotals.location_grid + let text = window.TYPEAHEADS.typeaheadHelpText(resultCount, query, result) + jQuery('#location_grid-result-container').html(text); }, onHideLayout: function () { - jQuery("#location_grid-result-container").html(""); - }, - }, + jQuery('#location_grid-result-container').html(""); + } + } }); } } -let add_location_grid = (value) => { - let data = { - grid_id: value, - }; - return window.makeRequest("POST", `users/user_location`, data); -}; -let delete_location_grid = (value) => { - let data = { - grid_id: value, - }; - return window.makeRequest("DELETE", `users/user_location`, data); -}; +let add_location_grid = ( value )=>{ + let data = { + grid_id: value + } + return window.makeRequest( "POST", `users/user_location`, data ) +} +let delete_location_grid = ( value )=>{ + let data = { + grid_id: value + } + return window.makeRequest( "DELETE", `users/user_location`, data ) +} + -let update_user = (key, value) => { - let data = { - [key]: value, - }; - return window.makeRequest("POST", `user/update`, data, "dt/v1/"); -}; +let update_user = ( key, value )=>{ + let data = { + [key]: value + } + return window.makeRequest( "POST", `user/update`, data , 'dt/v1/' ) +} /** * Set availability dates */ -let dateFields = ["start_date", "end_date"]; -dateFields.forEach((key) => { - let datePicker = jQuery(`#${key}.date-picker`); - datePicker.datepicker({ - onSelect: function (date) { - let start_date = jQuery("#start_date").val(); - let end_date = jQuery("#end_date").val(); - if ( - start_date && - end_date && - window.moment(start_date) < window.moment(end_date) - ) { - jQuery("#add_unavailable_dates").removeAttr("disabled"); - } else { - jQuery("#add_unavailable_dates").attr("disabled", true); - } - }, - dateFormat: "yy-mm-dd", - changeMonth: true, - changeYear: true, - yearRange: "-20:+10", - }); -}); +let dateFields = [ "start_date", "end_date" ] + dateFields.forEach(key=>{ + let datePicker = jQuery(`#${key}.date-picker`) + datePicker.datepicker({ + onSelect: function (date) { + let start_date = jQuery('#start_date').val() + let end_date = jQuery('#end_date').val() + if ( start_date && end_date && ( window.moment(start_date) < window.moment(end_date) )){ + jQuery('#add_unavailable_dates').removeAttr("disabled"); + } else { + jQuery('#add_unavailable_dates').attr("disabled", true); + } + }, + dateFormat: 'yy-mm-dd', + changeMonth: true, + changeYear: true, + yearRange: "-20:+10", + }) + }) -jQuery("#add_unavailable_dates").on("click", function () { - let start_date = jQuery("#start_date").val(); - let end_date = jQuery("#end_date").val(); - jQuery("#add_unavailable_dates_spinner").addClass("active"); - update_user("add_unavailability", { start_date, end_date }).then((resp) => { - jQuery("#add_unavailable_dates_spinner").removeClass("active"); - jQuery("#start_date").val(""); - jQuery("#end_date").val(""); - display_dates_unavailable(resp); - }); -}); -let display_dates_unavailable = (list = [], first_run) => { - let date_unavailable_table = jQuery("#unavailable-list"); - let rows = ``; +jQuery('#add_unavailable_dates').on('click', function () { + let start_date = jQuery('#start_date').val() + let end_date = jQuery('#end_date').val() + jQuery('#add_unavailable_dates_spinner').addClass('active') + update_user( 'add_unavailability', {start_date, end_date}).then((resp)=>{ + jQuery('#add_unavailable_dates_spinner').removeClass('active') + jQuery('#start_date').val('') + jQuery('#end_date').val('') + display_dates_unavailable(resp) + }) +}) +let display_dates_unavailable = (list = [], first_run )=>{ + let date_unavailable_table = jQuery('#unavailable-list') + let rows = `` // list = window.lodash.orderBy( list, [ "start_date" ], "desc") list.sort((a, b) => new Date(b.start_date) - new Date(a.start_date)); - list.forEach((range) => { + list.forEach(range=>{ rows += ` ${window.SHAREDFUNCTIONS.escapeHTML(range.start_date)} ${window.SHAREDFUNCTIONS.escapeHTML(range.end_date)} - + - `; - }); - if (rows || (!rows && !first_run)) { - date_unavailable_table.html(rows); + ` + }) + if ( rows || ( !rows && !first_run ) ){ + date_unavailable_table.html(rows) } -}; -display_dates_unavailable( - window.wpApiSettingsPage.custom_data.availability, - true -); -jQuery(document).on("click", ".remove_dates_unavailable", function () { - let id = jQuery(this).data("id"); - update_user("remove_unavailability", id).then((resp) => { - display_dates_unavailable(resp); - }); -}); +} +display_dates_unavailable( window.wpApiSettingsPage.custom_data.availability, true ) +jQuery( document).on( 'click', '.remove_dates_unavailable', function () { + let id = jQuery(this).data('id'); + update_user( 'remove_unavailability', id).then((resp)=>{ + display_dates_unavailable(resp) + }) +}) -let status_buttons = jQuery(".status-button"); -let color_workload_buttons = (name) => { - status_buttons.css("background-color", ""); - status_buttons.addClass("hollow"); - if (name) { - let selected = jQuery(`.status-button[name=${name}]`); - selected.removeClass("hollow"); +let status_buttons = jQuery('.status-button') +let color_workload_buttons = (name) =>{ + status_buttons.css('background-color', "") + status_buttons.addClass("hollow") + if ( name ){ + let selected = jQuery(`.status-button[name=${name}]`) + selected.removeClass("hollow") + // selected.css('background-color', window.lodash.get(window.wpApiSettingsPage, `workload_status_options.${name}.color`)) const color = window.wpApiSettingsPage?.workload_status_options?.[name]?.color; selected.css("background-color", color); - // selected.css('background-color', window.lodash.get(window.wpApiSettingsPage, `workload_status_options.${name}.color`)) - selected.blur(); + selected.blur() } -}; -color_workload_buttons(window.wpApiSettingsPage.workload_status); -status_buttons.on("click", function () { - jQuery("#workload-spinner").addClass("active"); - let name = jQuery(this).attr("name"); - color_workload_buttons(name); - update_user("workload_status", name) - .then(() => { - jQuery("#workload-spinner").removeClass("active"); - }) - .fail(() => { - status_buttons.css("background-color", ""); - jQuery("#workload-spinner").removeClass("active"); - status_buttons.addClass("hollow"); - }); -}); +} +color_workload_buttons(window.wpApiSettingsPage.workload_status ) +status_buttons.on( 'click', function () { + jQuery("#workload-spinner").addClass("active") + let name = jQuery(this).attr('name') + color_workload_buttons(name) + update_user( 'workload_status', name ) + .then(()=>{ + jQuery("#workload-spinner").removeClass("active") + }).fail(()=>{ + status_buttons.css('background-color', "") + jQuery("#workload-spinner").removeClass("active") + status_buttons.addClass("hollow") + }) +}) + -jQuery("button.dt_multi_select").on("click", function () { - let fieldKey = jQuery(this).data("field-key"); - let optionKey = jQuery(this).attr("id"); - jQuery(`#${fieldKey}-spinner`).addClass("active"); - let field = jQuery(`[data-field-key="${fieldKey}"]#${optionKey}`); - field.addClass("submitting-select-button"); - let action = "add"; - let update_request = null; - if (field.hasClass("selected-select-button")) { - action = "delete"; - update_request = update_user("remove_" + fieldKey, optionKey); +jQuery('button.dt_multi_select').on('click',function () { + let fieldKey = jQuery(this).data("field-key") + let optionKey = jQuery(this).attr('id') + jQuery(`#${fieldKey}-spinner`).addClass("active") + let field = jQuery(`[data-field-key="${fieldKey}"]#${optionKey}`) + field.addClass("submitting-select-button") + let action = "add" + let update_request = null + if (field.hasClass("selected-select-button")){ + action = "delete" + update_request = update_user( 'remove_' + fieldKey, optionKey ) } else { - field.removeClass("empty-select-button"); - field.addClass("selected-select-button"); - update_request = update_user("add_" + fieldKey, optionKey); + field.removeClass("empty-select-button") + field.addClass("selected-select-button") + update_request = update_user( 'add_' + fieldKey, optionKey ) } - update_request - .then(() => { - field.removeClass("submitting-select-button selected-select-button"); - field.blur(); - field.addClass( - action === "delete" ? "empty-select-button" : "selected-select-button" - ); - jQuery(`#${fieldKey}-spinner`).removeClass("active"); - }) - .catch((err) => { - field.removeClass("submitting-select-button selected-select-button"); - field.addClass( - action === "add" ? "empty-select-button" : "selected-select-button" - ); - window.handleAjaxError(err); - }); -}); -jQuery("select.select-field").change((e) => { - const id = jQuery(e.currentTarget).attr("id"); - const val = jQuery(e.currentTarget).val(); - jQuery(`#${id}-spinner`).addClass("active"); - update_user(id, val) - .then(() => { - jQuery(`#${id}-spinner`).removeClass("active"); - }) - .catch(window.handleAjaxError); -}); -jQuery('input[name="email-preference"]').on("change", (e) => { - const optionId = e.target.id.replace("-preference", ""); - const loadingSpinner = jQuery("#email-preference-spinner"); - loadingSpinner.addClass("active"); - update_user("email-preference", optionId) - .then(() => { - loadingSpinner.removeClass("active"); - }) - .fail(() => { - loadingSpinner.removeClass("active"); - }); -}); + update_request.then(()=>{ + field.removeClass("submitting-select-button selected-select-button") + field.blur(); + field.addClass( action === "delete" ? "empty-select-button" : "selected-select-button"); + jQuery(`#${fieldKey}-spinner`).removeClass("active") + }).catch(err=>{ + field.removeClass("submitting-select-button selected-select-button") + field.addClass( action === "add" ? "empty-select-button" : "selected-select-button") + window.handleAjaxError(err) + }) +}) +jQuery('select.select-field').change(e => { + const id = jQuery(e.currentTarget).attr('id') + const val = jQuery(e.currentTarget).val() + jQuery(`#${id}-spinner`).addClass("active") + update_user(id, val).then(()=>{ + jQuery(`#${id}-spinner`).removeClass("active") + }).catch(window.handleAjaxError) +}) +jQuery('input[name="email-preference"]').on('change', (e) => { + const optionId = e.target.id.replace('-preference', '') + const loadingSpinner = jQuery('#email-preference-spinner') + loadingSpinner.addClass('active') + update_user('email-preference', optionId) + .then(() => { + loadingSpinner.removeClass('active') + }) + .fail(() => { + loadingSpinner.removeClass('active') + }) +}) /** * People groups */ -if (jQuery(".js-typeahead-people_groups").length) { +if ( jQuery('.js-typeahead-people_groups').length) { jQuery.typeahead({ - input: ".js-typeahead-people_groups", + input: '.js-typeahead-people_groups', minLength: 0, accent: true, searchOnFocus: true, @@ -417,44 +369,40 @@ if (jQuery(".js-typeahead-people_groups").length) { display: ["name", "label"], templateValue: function () { if (this.items[this.items.length - 1].label) { - return "{{label}}"; + return "{{label}}" } else { - return "{{name}}"; + return "{{name}}" } }, dynamic: true, multiselect: { matchOn: ["ID"], data: function () { - return window.wpApiSettingsPage.user_people_groups.map((g) => { - return { ID: g.ID, name: g.post_title }; - }); + return window.wpApiSettingsPage.user_people_groups.map(g => { + return {ID: g.ID, name: g.post_title}; + }) }, callback: { onCancel: function (node, item) { - update_user("remove_people_groups", item.ID); - }, + update_user('remove_people_groups', item.ID) + } }, }, callback: { onClick: function (node, a, item, event) { - update_user("add_people_groups", item.ID); - this.addMultiselectItemLayout(item); - event.preventDefault(); + update_user('add_people_groups', item.ID) + this.addMultiselectItemLayout(item) + event.preventDefault() this.hideLayout(); this.resetInput(); }, onResult: function (node, query, result, resultCount) { - let text = window.TYPEAHEADS.typeaheadHelpText( - resultCount, - query, - result - ); - jQuery("#people_groups-result-container").html(text); + let text = window.TYPEAHEADS.typeaheadHelpText(resultCount, query, result) + jQuery('#people_groups-result-container').html(text); }, onHideLayout: function () { - jQuery("#people_groups-result-container").html(""); - }, - }, - }); + jQuery('#people_groups-result-container').html(""); + } + } + }) } From 89031935be5d9551de0535b989ff7e1df9a658a0 Mon Sep 17 00:00:00 2001 From: corsac Date: Thu, 28 Mar 2024 13:33:52 +0100 Subject: [PATCH 03/10] remove lodash comments --- dt-assets/js/settings.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/dt-assets/js/settings.js b/dt-assets/js/settings.js index 81874efb17..2dafcb0620 100644 --- a/dt-assets/js/settings.js +++ b/dt-assets/js/settings.js @@ -137,7 +137,6 @@ if ( typeof window.dtMapbox === "undefined" ) { data: { s: "{{query}}", filter: function () { - // return window.lodash.get(window.Typeahead['.js-typeahead-location_grid'].filters.dropdown, 'value', 'all') const { dropdown } = window.Typeahead[".js-typeahead-location_grid"].filters; const value = dropdown?.value ?? "all"; @@ -252,7 +251,6 @@ jQuery('#add_unavailable_dates').on('click', function () { let display_dates_unavailable = (list = [], first_run )=>{ let date_unavailable_table = jQuery('#unavailable-list') let rows = `` - // list = window.lodash.orderBy( list, [ "start_date" ], "desc") list.sort((a, b) => new Date(b.start_date) - new Date(a.start_date)); list.forEach(range=>{ rows += ` @@ -283,7 +281,6 @@ let color_workload_buttons = (name) =>{ if ( name ){ let selected = jQuery(`.status-button[name=${name}]`) selected.removeClass("hollow") - // selected.css('background-color', window.lodash.get(window.wpApiSettingsPage, `workload_status_options.${name}.color`)) const color = window.wpApiSettingsPage?.workload_status_options?.[name]?.color; selected.css("background-color", color); From 4a72a593bf9ecbae200dd196d51263722691ee22 Mon Sep 17 00:00:00 2001 From: Andrew Cummings Date: Mon, 1 Apr 2024 15:00:59 -0700 Subject: [PATCH 04/10] initial push for first issue --- dt-assets/js/comments.js | 54 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/dt-assets/js/comments.js b/dt-assets/js/comments.js index e8005c0abd..41b8fab514 100644 --- a/dt-assets/js/comments.js +++ b/dt-assets/js/comments.js @@ -12,10 +12,63 @@ jQuery(document).ready(function($) { let activity = [] // not guaranteed to be in any particular order let langcode = document.querySelector('html').getAttribute('lang') ? document.querySelector('html').getAttribute('lang').replace('_', '-') : "en";// get the language attribute from the HTML or default to english if it doesn't exists. + function convertComment(text) { + //**text** becomes text */ + text = text.replace(/\*\*(.*?)\*\*/g, '$1'); + //__text__ becomes text */ + text = text.replace(/\_\_(.*?)\_\_/g, '$1'); + //*text* becomes text */ + text = text.replace(/\*(.*?)\*/g, '$1'); + //- text or * text or + text becomes text */ + text = text.replace(/^\s*[*+-]\s+(.*)$/gm, '
  • $1
  • '); + // also, #. becomes a numbered list + text = text.replace(/^\s*\d+\.\s+(.*)$/gm, '
  • $1
  • '); + //creates lists with the help of line 23 and 25 + if (text.includes('
  • ')) { + text = '
      ' + text + '
    '; + } + //![image](imageUrl) becomes image */ + text = text.replace(/!\[(.*?)\]\((.*?)\)/g, '$1'); + //return modified comment + return text; + } + //pre-simplification +// //**text** becomes text */ +// function convertToBold(text) { +// return text.replace(/\*\*(.*?)\*\*/g, '$1'); +// } +// //__text__ becomes text */ +// function convertToBoldPartTwo(text) { +// return text.replace(/\_\_(.*?)\_\_/g, '$1'); +// } +// //*text* becomes text */ +// function convertToItalics(text) { +// return text.replace(/\*(.*?)\*/g, '$1'); +// } +// //- text or * text or + text becomes text */ +// // also, #. becomes a numbered list +// function convertToList(text) { +// text = text.replace(/^\s*[*+-]\s+(.*)$/gm, '
  • $1
  • '); +// text = text.replace(/^\s*\d+\.\s+(.*)$/gm, '
  • $1
  • '); + +// if (text.includes('
  • ')) { +// text = '
      ' + text + '
    '; +// } + +// return text; +// } +// //![image](imageUrl) becomes image */ +// function convertImage(text) { +// return text.replace(/!\[(.*?)\]\((.*?)\)/g, '$1'); +// } + function post_comment(postId) { let commentInput = jQuery("#comment-input") let commentButton = jQuery("#add-comment-button") let commentType = $('#comment_type_selector').val() + let commentText = commentInput.val(); + commentText = convertComment(commentText); + getCommentWithMentions(comment_plain_text=>{ if (comment_plain_text) { commentButton.toggleClass('loading') @@ -602,6 +655,7 @@ jQuery(document).ready(function($) { }) }).catch(err => { console.error(err) }) }, + //probably here templates : { mentionItemSyntax : function (data) { return `[${data.value}](${data.id})` From 6af1b82eb54fbdfabde8a4ca1ae249cef93ad9e2 Mon Sep 17 00:00:00 2001 From: Andrew Cummings Date: Sun, 14 Apr 2024 07:00:12 -0700 Subject: [PATCH 05/10] markdown sans images working --- dt-assets/js/comments.js | 905 ++++++++++++++++--------------- dt-assets/js/shared-functions.js | 38 ++ 2 files changed, 513 insertions(+), 430 deletions(-) diff --git a/dt-assets/js/comments.js b/dt-assets/js/comments.js index 41b8fab514..3b6d8715ed 100644 --- a/dt-assets/js/comments.js +++ b/dt-assets/js/comments.js @@ -1,156 +1,119 @@ /* global moment:false, _:false, commentsSettings:false */ -jQuery(document).ready(function($) { +jQuery(document).ready(function ($) { let commentPostedEvent = document.createEvent('Event'); commentPostedEvent.initEvent('comment_posted', true, true); - let postId = window.detailsSettings.post_id - let postType = window.detailsSettings.post_type - let rest_api = window.API - let { formatComment } = window.SHAREDFUNCTIONS - - let comments = [] - let activity = [] // not guaranteed to be in any particular order - let langcode = document.querySelector('html').getAttribute('lang') ? document.querySelector('html').getAttribute('lang').replace('_', '-') : "en";// get the language attribute from the HTML or default to english if it doesn't exists. - - function convertComment(text) { - //**text** becomes text */ - text = text.replace(/\*\*(.*?)\*\*/g, '$1'); - //__text__ becomes text */ - text = text.replace(/\_\_(.*?)\_\_/g, '$1'); - //*text* becomes text */ - text = text.replace(/\*(.*?)\*/g, '$1'); - //- text or * text or + text becomes text */ - text = text.replace(/^\s*[*+-]\s+(.*)$/gm, '
  • $1
  • '); - // also, #. becomes a numbered list - text = text.replace(/^\s*\d+\.\s+(.*)$/gm, '
  • $1
  • '); - //creates lists with the help of line 23 and 25 - if (text.includes('
  • ')) { - text = '
      ' + text + '
    '; - } - //![image](imageUrl) becomes image */ - text = text.replace(/!\[(.*?)\]\((.*?)\)/g, '$1'); - //return modified comment - return text; - } - //pre-simplification -// //**text** becomes text */ -// function convertToBold(text) { -// return text.replace(/\*\*(.*?)\*\*/g, '$1'); -// } -// //__text__ becomes text */ -// function convertToBoldPartTwo(text) { -// return text.replace(/\_\_(.*?)\_\_/g, '$1'); -// } -// //*text* becomes text */ -// function convertToItalics(text) { -// return text.replace(/\*(.*?)\*/g, '$1'); -// } -// //- text or * text or + text becomes text */ -// // also, #. becomes a numbered list -// function convertToList(text) { -// text = text.replace(/^\s*[*+-]\s+(.*)$/gm, '
  • $1
  • '); -// text = text.replace(/^\s*\d+\.\s+(.*)$/gm, '
  • $1
  • '); - -// if (text.includes('
  • ')) { -// text = '
      ' + text + '
    '; -// } - -// return text; -// } -// //![image](imageUrl) becomes image */ -// function convertImage(text) { -// return text.replace(/!\[(.*?)\]\((.*?)\)/g, '$1'); -// } + let postId = window.detailsSettings.post_id; + let postType = window.detailsSettings.post_type; + let rest_api = window.API; + let { formatComment } = window.SHAREDFUNCTIONS; + + let comments = []; + let activity = []; // not guaranteed to be in any particular order + let langcode = document.querySelector('html').getAttribute('lang') + ? document.querySelector('html').getAttribute('lang').replace('_', '-') + : 'en'; // get the language attribute from the HTML or default to english if it doesn't exists. function post_comment(postId) { - let commentInput = jQuery("#comment-input") - let commentButton = jQuery("#add-comment-button") - let commentType = $('#comment_type_selector').val() - let commentText = commentInput.val(); - commentText = convertComment(commentText); - - getCommentWithMentions(comment_plain_text=>{ + let commentInput = jQuery('#comment-input'); + let commentButton = jQuery('#add-comment-button'); + let commentType = $('#comment_type_selector').val(); + getCommentWithMentions((comment_plain_text) => { if (comment_plain_text) { - commentButton.toggleClass('loading') - commentInput.attr("disabled", true) - commentButton.attr("disabled", true) - rest_api.post_comment(postType, postId, comment_plain_text, commentType ).then(data => { - let updated_comment = data.comment || data - commentInput.val("").trigger( "change" ) - commentButton.toggleClass('loading') - updated_comment.date = window.moment(updated_comment.comment_date_gmt + "Z") - comments.push(updated_comment) - display_activity_comment() - // fire comment posted event - $('#content')[0].dispatchEvent(commentPostedEvent); - commentInput.attr("disabled", false) - commentButton.attr("disabled", false) - $('textarea.mention').mentionsInput('reset') - }).catch(err => { - console.log("error") - console.log(err) - jQuery("#errors").append(err.responseText) - }) + commentButton.toggleClass('loading'); + commentInput.attr('disabled', true); + commentButton.attr('disabled', true); + rest_api + .post_comment(postType, postId, comment_plain_text, commentType) + .then((data) => { + let updated_comment = data.comment || data; + commentInput.val('').trigger('change'); + commentButton.toggleClass('loading'); + updated_comment.date = window.moment( + updated_comment.comment_date_gmt + 'Z', + ); + comments.push(updated_comment); + display_activity_comment(); + // fire comment posted event + $('#content')[0].dispatchEvent(commentPostedEvent); + commentInput.attr('disabled', false); + commentButton.attr('disabled', false); + $('textarea.mention').mentionsInput('reset'); + }) + .catch((err) => { + console.log('error'); + console.log(err); + jQuery('#errors').append(err.responseText); + }); } }); } - function prepareActivityData(activityData) { /* Insert a "created contact" item in the activity, even though it is not * stored in the database. It is not stored as an activity in the database, * to avoid duplicating data with the post's metadata. */ - let settings = commentsSettings - const currentContact = settings.post - let createdDate = window.moment.utc(currentContact.post_date_gmt, "YYYY-MM-DD HH:mm:ss", true) + let settings = commentsSettings; + const currentContact = settings.post; + let createdDate = window.moment.utc( + currentContact.post_date_gmt, + 'YYYY-MM-DD HH:mm:ss', + true, + ); const createdContactActivityItem = { hist_time: createdDate.unix(), - object_note: window.detailsSettings.translations.created_on.replace('%s', window.SHAREDFUNCTIONS.formatDate(createdDate.unix(), true)), + object_note: window.detailsSettings.translations.created_on.replace( + '%s', + window.SHAREDFUNCTIONS.formatDate(createdDate.unix(), true), + ), name: settings.contact_author_name, user_id: currentContact.post_author, - } - activityData.push(createdContactActivityItem) - if (window.lodash.get(settings, "post_with_fields.initial_comments")){ + }; + activityData.push(createdContactActivityItem); + if (window.lodash.get(settings, 'post_with_fields.initial_comments')) { const initialComments = { - hist_time: createdDate.unix()+1, + hist_time: createdDate.unix() + 1, object_note: settings.post_with_fields.initial_comments, name: settings.contact_author_name, user_id: currentContact.post_author, - } - activityData.push(initialComments) + }; + activityData.push(initialComments); } - activityData.forEach(item => { - item.date = window.moment.unix(item.hist_time) - let field = item.meta_key + activityData.forEach((item) => { + item.date = window.moment.unix(item.hist_time); + let field = item.meta_key; - if (field && field.includes("quick_button_")){ - if (window.detailsSettings){ - field = window.lodash.get(window.detailsSettings,`post_settings.fields[${item.meta_key}].name`) + if (field && field.includes('quick_button_')) { + if (window.detailsSettings) { + field = window.lodash.get( + window.detailsSettings, + `post_settings.fields[${item.meta_key}].name`, + ); } - item.action = ` + item.action = ` - ${window.SHAREDFUNCTIONS.escapeHTML( field || item.meta_key )} - ` + ${window.SHAREDFUNCTIONS.escapeHTML(field || item.meta_key)} + `; } else { - item.action = '' + item.action = ''; } - }) - - let tab = $(`[data-id="activity"].tab-button-label`) - let text = tab.text() - text = text.substring(0, text.indexOf('(')) || text - text += ` (${formatNumber(activityData.length, langcode)})` - tab.text(text) - tab.parent().parent('.hide').removeClass('hide') + }); + + let tab = $(`[data-id="activity"].tab-button-label`); + let text = tab.text(); + text = text.substring(0, text.indexOf('(')) || text; + text += ` (${formatNumber(activityData.length, langcode)})`; + tab.text(text); + tab.parent().parent('.hide').removeClass('hide'); } - $(".show-tabs").on("click", function () { - let id = $(this).attr("id") - $('input.tabs-section').prop('checked', id === 'show-all-tabs') - saveTabs() - }) + $('.show-tabs').on('click', function () { + let id = $(this).attr('id'); + $('input.tabs-section').prop('checked', id === 'show-all-tabs'); + saveTabs(); + }); - /* We use the CSS 'white-space:pre-wrap' and '
    ' HTML elements + /* We use the CSS 'white-space:pre-wrap' and '
    ' HTML elements * to match the behaviour that the user sees when editing the comment in an * input with dir=auto set, especially when using a right-to-left language * with multiple paragraphs. */ @@ -173,12 +136,25 @@ jQuery(document).ready(function($) { if (a.comment){ %> <% is_Comment = true; %>
    -
    <%= a.text.replace(/\\n/g, '
    ') /* not escaped on purpose */ %>
    +
    + <% + if (a.text.indexOf('
  • ') === -1) { + %> + <%= a.text.replace(/\\n/g, '
    ') /* not escaped on purpose */ %> + <% } else { %> + <%= a.text %> + <% } %> +
    <% if ( commentsSettings.google_translate_key !== "" && is_Comment && !has_Comment_ID && activity[0].comment_type !== 'duplicate' ) { %>
    <% } %>
    + <% if ( a.meta && a.meta.audio_url ) { %> + <% window.lodash.forEach(a.meta.audio_url, function(meta){ %> + + <% }) %> + <% } %>
    ` ) - $(document).on("click", '.translate-button.showTranslation', function() { + $(document).on('click', '.translate-button.showTranslation', function () { let combinedArray = []; - jQuery(this).siblings('.comment-bubble').each(function(index, comment) { - let sourceText = $(comment).text(); - sourceText = sourceText.replace(/\s+/g, ' ').trim(); - combinedArray[index] = sourceText; - }) + jQuery(this) + .siblings('.comment-bubble') + .each(function (index, comment) { + let sourceText = $(comment).text(); + sourceText = sourceText.replace(/\s+/g, ' ').trim(); + combinedArray[index] = sourceText; + }); let translation_bubble = $(this).siblings('.translation-bubble'); - let translation_hide = $(this).siblings('.translate-button.hideTranslation'); + let translation_hide = $(this).siblings( + '.translate-button.hideTranslation', + ); - let url = `https://translation.googleapis.com/language/translate/v2?key=${window.SHAREDFUNCTIONS.escapeHTML(commentsSettings.google_translate_key)}` + let url = `https://translation.googleapis.com/language/translate/v2?key=${window.SHAREDFUNCTIONS.escapeHTML(commentsSettings.google_translate_key)}`; let targetLang; - if (langcode !== "zh-TW") { - targetLang = langcode.substr(0,2); + if (langcode !== 'zh-TW') { + targetLang = langcode.substr(0, 2); } else { targetLang = langcode; } - function google_translate_fetch(postData, translate_button, arrayStartPos = 0) { + function google_translate_fetch( + postData, + translate_button, + arrayStartPos = 0, + ) { fetch(url, { - method: 'POST', - body: JSON.stringify(postData), - }) - .then(response => response.json()) + method: 'POST', + body: JSON.stringify(postData), + }) + .then((response) => response.json()) .then((result) => { - - $.each(result.data.translations, function( index, translation ) { - $(translation_bubble[index + arrayStartPos]).append(translation.translatedText); + $.each(result.data.translations, function (index, translation) { + $(translation_bubble[index + arrayStartPos]).append( + translation.translatedText, + ); }); translation_hide.removeClass('hide'); $(translate_button).addClass('hide'); - }) + }); } - if( combinedArray.length <= 128) { + if (combinedArray.length <= 128) { let postData = { - "q": combinedArray, - "target": targetLang - } + q: combinedArray, + target: targetLang, + }; google_translate_fetch(postData, this); } else { - var i,j,temparray,chunk = 128; - for (i=0,j=combinedArray.length; i{ - $(this).toggleClass('loading') - if (response){ - $('#delete-comment-modal').foundation('close') - } else { - $('.delete-comment.callout').show() - } - }).catch(err=>{ - $(this).toggleClass('loading') - if (window.lodash.get(err, "responseJSON.message")){ - $('.delete-comment.callout').show() - $('#delete-comment-error').html(err.responseJSON.message) - } - }) - }) + }); - $(document).on("click", ".open-edit-comment", function () { - let id = $(this).data("id") - let comment_type = $(this).data("type"); - let comment = window.lodash.find(comments, {comment_ID:id.toString()}) + $(document).on('click', '.open-delete-comment', function () { + let id = $(this).data('id'); + $('#comment-to-delete').html($(`.comment-bubble.${id}`).html()); + $('.delete-comment.callout').hide(); + $('#delete-comment-modal').foundation('open'); + $('#confirm-comment-delete').data('id', id); + }); + $('#confirm-comment-delete').on('click', function () { + let id = $(this).data('id'); + $(this).toggleClass('loading'); + rest_api + .delete_comment(postType, postId, id) + .then((response) => { + $(this).toggleClass('loading'); + if (response) { + $('#delete-comment-modal').foundation('close'); + } else { + $('.delete-comment.callout').show(); + } + }) + .catch((err) => { + $(this).toggleClass('loading'); + if (window.lodash.get(err, 'responseJSON.message')) { + $('.delete-comment.callout').show(); + $('#delete-comment-error').html(err.responseJSON.message); + } + }); + }); - let comment_html = comment.comment_content // eg: "Tom & Jerry" + $(document).on('click', '.open-edit-comment', function () { + let id = $(this).data('id'); + let comment_type = $(this).data('type'); + let comment = window.lodash.find(comments, { comment_ID: id.toString() }); + let comment_html = comment.comment_content; // eg: "Tom & Jerry" /** * .DT - while previewing submitted comments, enhance the presentation of special characters with a helper function below */ function unescapeHtml(safe) { - return safe.replace(/&/g, '&') + return ( + safe + .replace(/&/g, '&') //.replace(/</g, '<') //.replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, "'") - .replace(/'/g, "'"); + .replace(/'/g, "'") + ); } // textarea deos not render HTML, so using window.lodash.unescape is safe. Note that @@ -357,30 +351,33 @@ jQuery(document).ready(function($) { $('#edit_comment_type_selector').val(comment_type); - $('.edit-comment.callout').hide() - $('#edit-comment-modal').foundation('open') - $('#confirm-comment-edit').data("id", id) - }) - $('#confirm-comment-edit').on("click", function () { - $(this).toggleClass('loading') - let id = $(this).data("id") - let updated_comment = $('#comment-to-edit').val() + $('.edit-comment.callout').hide(); + $('#edit-comment-modal').foundation('open'); + $('#confirm-comment-edit').data('id', id); + }); + $('#confirm-comment-edit').on('click', function () { + $(this).toggleClass('loading'); + let id = $(this).data('id'); + let updated_comment = $('#comment-to-edit').val(); let commentType = $('#edit_comment_type_selector').val(); - rest_api.update_comment( postType, postId, id, updated_comment, commentType).then((response)=>{ - $(this).toggleClass('loading') - if (response === 1 || response === 0 || response.comment_ID){ - $('#edit-comment-modal').foundation('close') - } else { - $('.edit-comment.callout').show() - } - }).catch(err=>{ - $(this).toggleClass('loading') - if (window.lodash.get(err, "responseJSON.message")){ - $('.edit-comment.callout').show() - $('#edit-comment-error').html(err.responseJSON.message) - } - }) - }) + rest_api + .update_comment(postType, postId, id, updated_comment, commentType) + .then((response) => { + $(this).toggleClass('loading'); + if (response === 1 || response === 0 || response.comment_ID) { + $('#edit-comment-modal').foundation('close'); + } else { + $('.edit-comment.callout').show(); + } + }) + .catch((err) => { + $(this).toggleClass('loading'); + if (window.lodash.get(err, 'responseJSON.message')) { + $('.edit-comment.callout').show(); + $('#edit-comment-error').html(err.responseJSON.message); + } + }); + }); function formatNumber(num, lang) { return num.toLocaleString(lang); @@ -389,202 +386,226 @@ jQuery(document).ready(function($) { function display_activity_comment() { let hiddenTabs = []; try { - hiddenTabs = JSON.parse( window.SHAREDFUNCTIONS.getCookie("dt_activity_comments_hidden_tabs") ) + hiddenTabs = JSON.parse( + window.SHAREDFUNCTIONS.getCookie('dt_activity_comments_hidden_tabs'), + ); } catch (e) {} - hiddenTabs.forEach(tab=>{ - $(`#tab-button-${tab}`).prop('checked', false) - }) - let commentsWrapper = $("#comments-wrapper") - commentsWrapper.empty() - let displayed = [] - if ( !hiddenTabs.includes("activity")){ - displayed = window.lodash.union(displayed, activity) + hiddenTabs.forEach((tab) => { + $(`#tab-button-${tab}`).prop('checked', false); + }); + let commentsWrapper = $('#comments-wrapper'); + commentsWrapper.empty(); + let displayed = []; + if (!hiddenTabs.includes('activity')) { + displayed = window.lodash.union(displayed, activity); } - comments.forEach(comment=>{ - if (!hiddenTabs.includes(comment.comment_type)){ - displayed.push(comment) + comments.forEach((comment) => { + if (!hiddenTabs.includes(comment.comment_type)) { + displayed.push(comment); } - }) - displayed = displayed.sort((a,b)=>{ - return (a.sort_date || a.date) < (b.sort_date || b.date) ? 1 : -1 - }) - let array = [] + }); + displayed = displayed.sort((a, b) => { + return (a.sort_date || a.date) < (b.sort_date || b.date) ? 1 : -1; + }); + let array = []; - displayed.forEach(d=>{ + displayed.forEach((d) => { let baptismDateRegex = /\{(\d+)\}+/; if (baptismDateRegex.test(d.object_note)) { if (d.field_type === 'datetime') { - d.object_note = d.object_note.replace(baptismDateRegex, formatTimestampToDateTime); + d.object_note = d.object_note.replace( + baptismDateRegex, + formatTimestampToDateTime, + ); } else { - d.object_note = d.object_note.replace(baptismDateRegex, formatTimestampToDate); + d.object_note = d.object_note.replace( + baptismDateRegex, + formatTimestampToDate, + ); } } - if ( d.object_note ){ - d.object_note = formatComment(d.object_note) + if (d.object_note) { + d.object_note = formatComment(d.object_note); } - let first = window.lodash.first(array) - let name = d.comment_author || d.name - let gravatar = d.gravatar || "" + let first = window.lodash.first(array); + let name = d.comment_author || d.name; + let gravatar = d.gravatar || ''; let obj = { name: name, date: d.date, - date_formatted: window.SHAREDFUNCTIONS.formatDate(moment(d.date).unix(), true), + date_formatted: window.SHAREDFUNCTIONS.formatDate( + moment(d.date).unix(), + true, + ), gravatar, - text:d.object_note || formatComment(d.comment_content), + text: d.object_note || formatComment(d.comment_content), comment: !!d.comment_content, - comment_ID : d.comment_ID, + comment_ID: d.comment_ID, is_own_comment: d.user_id === commentsSettings.current_user_id, - comment_type : d.comment_type, + comment_type: d.comment_type, action: d.action, reactions: d.comment_reactions || {}, - } + meta: d.comment_meta || {}, + }; - let diff = first ? first.date.diff(obj.date, "hours") : 0 - if (!first || (first.name === name && diff < 1) ){ - array.push(obj) + let diff = first ? first.date.diff(obj.date, 'hours') : 0; + if (!first || (first.name === name && diff < 1)) { + array.push(obj); } else { - commentsWrapper.append(commentTemplate({ - name: array[0].name, + commentsWrapper.append( + commentTemplate({ + name: array[0].name, + gravatar: array[0].gravatar, + date: array[0].date_formatted, + activity: array, + }), + ); + array = [obj]; + } + }); + if (array.length > 0) { + commentsWrapper.append( + commentTemplate({ gravatar: array[0].gravatar, + name: array[0].name, date: array[0].date_formatted, - activity: array - })) - array = [obj] - } - }) - if (array.length > 0){ - commentsWrapper.append(commentTemplate({ - gravatar: array[0].gravatar, - name: array[0].name, - date: array[0].date_formatted, - activity: array - })) + activity: array, + }), + ); } document.querySelectorAll('.reactions__dropdown').forEach((element) => { - const commentId = element.dataset.commentId - const emojis = emojiButtons() - const reactionForm = document.createElement('form') - reactionForm.classList.add('pick-reaction-form') + const commentId = element.dataset.commentId; + const emojis = emojiButtons(); + const reactionForm = document.createElement('form'); + reactionForm.classList.add('pick-reaction-form'); reactionForm.innerHTML = ` ${emojis} - ` + `; reactionForm.addEventListener('submit', (e) => { e.preventDefault(); const formDataEntries = new FormData(e.target).entries(); const entries = Array.from(formDataEntries); //event submitter data is not available in Safari/Webkit browsers only in Chrome/Blink browsers. This checks if that data exists and falls back to the formDataEntries data if it doesn't exists. const reaction = e.submitter ? e.submitter.value : entries[0][1]; - rest_api.toggle_comment_reaction(postType, postId, commentId, reaction) - }) - element.appendChild(reactionForm) - }) - document.querySelectorAll('#comments-wrapper [data-toggle]').forEach((element) => { - const dropdownId = $(element).data('toggle') - const dropdownElement = document.querySelector(`#${dropdownId}`) - element.addEventListener('click', (e) => { - const style = getComputedStyle(dropdownElement) - element.toggleAttribute('open') - if (style.visibility === 'hidden') { - dropdownElement.style.visibility = 'visible' - dropdownElement.style.display = 'block' - } else { - dropdownElement.style.visibility = 'hidden' - dropdownElement.style.display = 'none' - } - }) - }) + rest_api.toggle_comment_reaction(postType, postId, commentId, reaction); + }); + element.appendChild(reactionForm); + }); + document + .querySelectorAll('#comments-wrapper [data-toggle]') + .forEach((element) => { + const dropdownId = $(element).data('toggle'); + const dropdownElement = document.querySelector(`#${dropdownId}`); + element.addEventListener('click', (e) => { + const style = getComputedStyle(dropdownElement); + element.toggleAttribute('open'); + if (style.visibility === 'hidden') { + dropdownElement.style.visibility = 'visible'; + dropdownElement.style.display = 'block'; + } else { + dropdownElement.style.visibility = 'hidden'; + dropdownElement.style.display = 'none'; + } + }); + }); document.querySelectorAll('.comment-reaction').forEach((element) => { element.addEventListener('click', (e) => { - const commentId = e.target.dataset.commentId - const reaction = e.target.dataset.reactionValue - rest_api.toggle_comment_reaction(postType, postId, commentId, reaction) - }) - }) + const commentId = e.target.dataset.commentId; + const reaction = e.target.dataset.reactionValue; + rest_api.toggle_comment_reaction(postType, postId, commentId, reaction); + }); + }); } function emojiButtons() { - const reactions = commentsSettings.reaction_options - const emojiContainer = document.createElement('div') - emojiContainer.classList.add('reactions-emoji-container') - let emojis = '' + const reactions = commentsSettings.reaction_options; + const emojiContainer = document.createElement('div'); + emojiContainer.classList.add('reactions-emoji-container'); + let emojis = ''; Object.entries(reactions).forEach(([alias, reaction]) => { - const reactionValue = `reaction_${alias}` + const reactionValue = `reaction_${alias}`; emojis += ` - ` - }) - emojiContainer.innerHTML = emojis - return emojiContainer.outerHTML + `; + }); + emojiContainer.innerHTML = emojis; + return emojiContainer.outerHTML; } function formatTimestampToDate(match, timestamp) { - return window.SHAREDFUNCTIONS.formatDate(timestamp) + return window.SHAREDFUNCTIONS.formatDate(timestamp); } function formatTimestampToDateTime(match, timestamp) { - return window.SHAREDFUNCTIONS.formatDate(timestamp, true) + return window.SHAREDFUNCTIONS.formatDate(timestamp, true); } /** * Comments and activity */ - $( document ).ajaxComplete(function(event, xhr, settings) { - if (settings && settings.type && (settings.type === "POST" || settings.type === "DELETE")){ - if (!settings.url.includes("notifications")){ - refreshActivity() + $(document).ajaxComplete(function (event, xhr, settings) { + if ( + settings && + settings.type && + (settings.type === 'POST' || settings.type === 'DELETE') + ) { + if (!settings.url.includes('notifications')) { + refreshActivity(); } } }); - $( document ).ajaxSend(function(event, xhr, settings) { - if (settings && settings.type && (settings.type === "POST" || settings.type === "DELETE")){ - if (!settings.url.includes("notifications")){ - $("#comments-activity-spinner.loading-spinner").addClass("active") + $(document).ajaxSend(function (event, xhr, settings) { + if ( + settings && + settings.type && + (settings.type === 'POST' || settings.type === 'DELETE') + ) { + if (!settings.url.includes('notifications')) { + $('#comments-activity-spinner.loading-spinner').addClass('active'); } } }); - let refreshActivity = ()=>{ + let refreshActivity = () => { get_all(); - } - - + }; - let getAllPromise = null - let getCommentsPromise = null - let getActivityPromise = null + let getAllPromise = null; + let getCommentsPromise = null; + let getActivityPromise = null; function get_all() { //abort previous promise if it is not finished. - if (getAllPromise && window.lodash.get(getAllPromise, "readyState") !== 4){ - getActivityPromise.abort() - getCommentsPromise.abort() + if (getAllPromise && window.lodash.get(getAllPromise, 'readyState') !== 4) { + getActivityPromise.abort(); + getCommentsPromise.abort(); } - getCommentsPromise = rest_api.get_comments(postType, postId) - getActivityPromise = rest_api.get_activity(postType, postId) - getAllPromise = $.when( - getCommentsPromise, - getActivityPromise - ) - getAllPromise.then(function(commentDataStatusJQXHR, activityDataStatusJQXHR) { - $("#comments-activity-spinner.loading-spinner").removeClass("active") - const commentData = commentDataStatusJQXHR[0].comments; - const activityData = activityDataStatusJQXHR[0].activity; - - prepareData(commentData, activityData) - }).catch(err => { - if ( !window.lodash.get( err, "statusText" ) === "abort" ) { - console.error(err); - jQuery("#errors").append(err.responseText) - } - }) + getCommentsPromise = rest_api.get_comments(postType, postId); + getActivityPromise = rest_api.get_activity(postType, postId); + getAllPromise = $.when(getCommentsPromise, getActivityPromise); + getAllPromise + .then(function (commentDataStatusJQXHR, activityDataStatusJQXHR) { + $('#comments-activity-spinner.loading-spinner').removeClass('active'); + const commentData = commentDataStatusJQXHR[0].comments; + const activityData = activityDataStatusJQXHR[0].activity; + + prepareData(commentData, activityData); + }) + .catch((err) => { + if (!window.lodash.get(err, 'statusText') === 'abort') { + console.error(err); + jQuery('#errors').append(err.responseText); + } + }); } - - let prepareData = function(commentData, activityData){ + let prepareData = function (commentData, activityData) { let typesCount = {}; - commentData.forEach(comment => { - comment.date = window.moment(comment.comment_date_gmt + "Z") - comment.sort_date = window.moment(comment.comment_date_gmt + "Z").add(5, 'seconds') + commentData.forEach((comment) => { + comment.date = window.moment(comment.comment_date_gmt + 'Z'); + comment.sort_date = window + .moment(comment.comment_date_gmt + 'Z') + .add(5, 'seconds'); /* comment_content should be HTML. However, we want to make sure that * HTML like "
    Hello" gets transformed to "
    Hello
    ", that @@ -594,122 +615,146 @@ jQuery(document).ready(function($) { * can trust the contents of the database to have been sanitized * thanks to wp_new_comment . */ - // .DT lets strip out the tags provided from the submited comment and treat it as pure text. - comment.comment_content = $("
    ").text(comment.comment_content).text() + // .DT lets strip out the tags provided from the submited comment and treat it as pure text. + comment.comment_content = $('
    ').text(comment.comment_content).text(); - if (!typesCount[comment.comment_type]){ + if (!typesCount[comment.comment_type]) { typesCount[comment.comment_type] = 0; } typesCount[comment.comment_type]++; - }) - $('#comment-activity-tabs .tabs-title[data-always-show!="true"]').addClass('hide') - window.lodash.forOwn(typesCount, (val, key)=>{ - let tab = $(`[data-id="${key}"].tab-button-label`) - let text = tab.text() - text = text.substring(0, text.indexOf('(')) || text - text += ` (${formatNumber(val, langcode)})` - tab.text(text) - tab.parent().parent('.hide').removeClass('hide') - }) - comments = commentData - activity = activityData - prepareActivityData(activity) - display_activity_comment("all") - } - prepareData( commentsSettings.comments.comments, commentsSettings.activity.activity ) - + }); + $('#comment-activity-tabs .tabs-title[data-always-show!="true"]').addClass( + 'hide', + ); + window.lodash.forOwn(typesCount, (val, key) => { + let tab = $(`[data-id="${key}"].tab-button-label`); + let text = tab.text(); + text = text.substring(0, text.indexOf('(')) || text; + text += ` (${formatNumber(val, langcode)})`; + tab.text(text); + tab.parent().parent('.hide').removeClass('hide'); + }); + comments = commentData; + activity = activityData; + prepareActivityData(activity); + display_activity_comment('all'); + }; + prepareData( + commentsSettings.comments.comments, + commentsSettings.activity.activity, + ); jQuery('#add-comment-button').on('click', function () { - post_comment(postId) - }) - - $('#comment-activity-tabs .tabs-section').on("change", function () { - saveTabs() - }) - let saveTabs = ()=>{ - let hiddenTabs = $('#comment-activity-tabs .tabs-section:not(:checked)') - let hiddenTabIds = []; - hiddenTabs.each((i, e)=>{ - hiddenTabIds.push($(e).data("id")) - }) - document.cookie = `dt_activity_comments_hidden_tabs=${JSON.stringify(hiddenTabIds)};path=/;expires=Fri, 31 Dec 9999 23:59:59 GMT"` - display_activity_comment() - } + post_comment(postId); + }); + $('#comment-activity-tabs .tabs-section').on('change', function () { + saveTabs(); + }); + let saveTabs = () => { + let hiddenTabs = $('#comment-activity-tabs .tabs-section:not(:checked)'); + let hiddenTabIds = []; + hiddenTabs.each((i, e) => { + hiddenTabIds.push($(e).data('id')); + }); + document.cookie = `dt_activity_comments_hidden_tabs=${JSON.stringify(hiddenTabIds)};path=/;expires=Fri, 31 Dec 9999 23:59:59 GMT"`; + display_activity_comment(); + }; - let searchUsersPromise = null + let searchUsersPromise = null; $('textarea.mention').mentionsInput({ - onDataRequest:function (mode, query, callback) { - $('#comment-input').addClass('loading-gif') - if ( searchUsersPromise && window.lodash.get(searchUsersPromise, 'readyState') !== 4 ){ - searchUsersPromise.abort("abortPromise") + onDataRequest: function (mode, query, callback) { + $('#comment-input').addClass('loading-gif'); + if ( + searchUsersPromise && + window.lodash.get(searchUsersPromise, 'readyState') !== 4 + ) { + searchUsersPromise.abort('abortPromise'); } - searchUsersPromise = window.API.search_users(query) - searchUsersPromise.then(responseData=>{ - $('#comment-input').removeClass('loading-gif') - let data = [] - responseData.forEach(user=>{ - data.push({id:user.ID, name:user.name, type:postType, avatar:user.avatar}) - callback.call(this, data); + searchUsersPromise = window.API.search_users(query); + searchUsersPromise + .then((responseData) => { + $('#comment-input').removeClass('loading-gif'); + let data = []; + responseData.forEach((user) => { + data.push({ + id: user.ID, + name: user.name, + type: postType, + avatar: user.avatar, + }); + callback.call(this, data); + }); }) - }).catch(err => { console.error(err) }) + .catch((err) => { + console.error(err); + }); }, - //probably here - templates : { - mentionItemSyntax : function (data) { - return `[${data.value}](${data.id})` - } + templates: { + mentionItemSyntax: function (data) { + return `[${data.value}](${data.id})`; + }, }, showAvatars: true, - minChars: 0 + minChars: 0, }); - let getMentionedUsers = (callback)=>{ - $('textarea.mention').mentionsInput('getMentions', function(data) { + let getMentionedUsers = (callback) => { + $('textarea.mention').mentionsInput('getMentions', function (data) { callback(data); }); - } + }; - let getCommentWithMentions = (callback)=>{ - $('textarea.mention').mentionsInput('val', function(text) { + let getCommentWithMentions = (callback) => { + $('textarea.mention').mentionsInput('val', function (text) { callback(text); }); - } + }; // $(document).on('click', '.revert-activity', function () { - let id = $(this).data('id') - $("#revert-modal").foundation('open') - $("#confirm-revert").data("id", id) - window.API.get_single_activity(postType, postId, id).then(a => { - let field = a.meta_key - if (window.detailsSettings.post_settings){ - field = window.lodash.get(window.detailsSettings, `post_settings.fields[${a.meta_key}].name`) - } + let id = $(this).data('id'); + $('#revert-modal').foundation('open'); + $('#confirm-revert').data('id', id); + window.API.get_single_activity(postType, postId, id) + .then((a) => { + let field = a.meta_key; + if (window.detailsSettings.post_settings) { + field = window.lodash.get( + window.detailsSettings, + `post_settings.fields[${a.meta_key}].name`, + ); + } - $(".revert-field").html(field || a.meta_key) - $(".revert-current-value").html(a.meta_value) - $(".revert-old-value").html(a.old_value || 0) - }).catch(err => { console.error(err) }) - }) + $('.revert-field').html(field || a.meta_key); + $('.revert-current-value').html(a.meta_value); + $('.revert-old-value').html(a.old_value || 0); + }) + .catch((err) => { + console.error(err); + }); + }); // confirm going back to the old version on the activity - $('#confirm-revert').on("click", function () { - let id = $(this).data('id') - window.API.revert_activity(postType, postId, id).then(contactResponse => { - refreshActivity() - $("#revert-modal").foundation('close') - if (typeof refresh_quick_action_buttons === 'function'){ - window.refresh_quick_action_buttons(contactResponse) - } - }).catch(err => { console.error(err) }) - }) + $('#confirm-revert').on('click', function () { + let id = $(this).data('id'); + window.API.revert_activity(postType, postId, id) + .then((contactResponse) => { + refreshActivity(); + $('#revert-modal').foundation('close'); + if (typeof refresh_quick_action_buttons === 'function') { + window.refresh_quick_action_buttons(contactResponse); + } + }) + .catch((err) => { + console.error(err); + }); + }); - window.onbeforeunload = function() { - if ( $('textarea.mention').val() ){ + window.onbeforeunload = function () { + if ($('textarea.mention').val()) { return true; } }; - -}); +}); \ No newline at end of file diff --git a/dt-assets/js/shared-functions.js b/dt-assets/js/shared-functions.js index a307ff6e50..d78bcc60b2 100644 --- a/dt-assets/js/shared-functions.js +++ b/dt-assets/js/shared-functions.js @@ -733,7 +733,45 @@ window.SHAREDFUNCTIONS = { return `${text}` }) + //**comment** becomes comment */ + comment = comment.replace(/\*\*(.*?)\*\*/g, '$1'); + //__comment__ becomes comment */ + comment = comment.replace(/\_\_(.*?)\_\_/g, '$1'); + //*comment* becomes comment */ + comment = comment.replace(/\*(.*?)\*/g, '$1'); + //- comment or * comment or + comment becomes comment */ + comment = comment.replace(/^\s*[*+-]\s+(.*)$/gm, '
  • $1
  • '); + // also, #. becomes a numbered list + comment = comment.replace(/^\s*(\d+\.)\s+(.*)$/gm, '
  • $1 $2
  • '); + //creates lists with the help of line 23 and 25 + + if (comment.includes('
  • ')) { + const firstLi = /
  • /; + const lastLi = /<\/li>/g; + const firstLiIndex = comment.search(firstLi); + if (firstLiIndex === -1) { + return comment; } + + const lastLiIndex = comment.lastIndexOf("
  • "); + const digits = /\d\./; + let listItemContent = comment.slice(firstLiIndex + 4, lastLiIndex); // Extract comment content between
  • and
  • + + let nonlistItemContent = comment.slice(lastLiIndex + 5); + + if (digits.test(listItemContent) == true) { + comment = comment.slice(0, firstLiIndex) + '
      ' + '
    1. ' + listItemContent + '
    2. ' + comment.slice(lastLiIndex, lastLiIndex + 5) + '
    \n' + nonlistItemContent; // Add newline character + } else { + comment = comment.slice(0, firstLiIndex) + '
      ' + '
    • ' + listItemContent + '
    • ' + comment.slice(lastLiIndex, lastLiIndex + 5) + '
    \n' + nonlistItemContent; // Add newline character + } +} + //![image](imageUrl) becomes image */ + comment = comment.replace(/!\[(.*?)\]\((.*?)\)/g, '$1'); + //return modified comment + return comment; + + } + return comment }, convertArabicToEnglishNumbers(string) { From 258cb803f76e7eb67b9df7e2f4adb4c4d862e9cc Mon Sep 17 00:00:00 2001 From: Andrew Cummings Date: Wed, 15 May 2024 08:15:51 -0700 Subject: [PATCH 06/10] pushing changes for troubleshooting --- dt-core/admin/admin-settings-endpoints.php | 23 + dt-core/admin/js/dt-options.js | 1082 +++++++++++------- dt-core/admin/menu/tabs/tab-custom-lists.php | 40 +- 3 files changed, 709 insertions(+), 436 deletions(-) diff --git a/dt-core/admin/admin-settings-endpoints.php b/dt-core/admin/admin-settings-endpoints.php index 45d399ef76..81838a86b4 100644 --- a/dt-core/admin/admin-settings-endpoints.php +++ b/dt-core/admin/admin-settings-endpoints.php @@ -215,6 +215,29 @@ public function add_api_routes() { 'permission_callback' => [ $this, 'default_permission_check' ], ] ); + + register_rest_route( + $this->namespace, '/languages', [ + 'methods' => 'POST', + 'callback' => [ $this, 'update_languages' ], + 'permission_callback' => [ $this, 'default_permission_check' ], + ] + ); + } + + public function update_languages( WP_REST_REQUEST $request ) { + $params = $request->get_params(); + // var_dump( $params ); + // $languages = dt_get_option( 'dt_working_languages' ) ?: []; + $languages = $params; + // $dt_global_languages_list = dt_get_global_languages_list(); + // $langs = dt_get_available_languages(); + // // $languages = $params['tableLangs']; + // $test = $params['tableLangs']; + + // //need to build $languages + update_option( 'dt_working_languages', $languages, false ); + } public static function get_post_fields() { diff --git a/dt-core/admin/js/dt-options.js b/dt-core/admin/js/dt-options.js index d72fbb1190..4dc9a92222 100644 --- a/dt-core/admin/js/dt-options.js +++ b/dt-core/admin/js/dt-options.js @@ -1,82 +1,212 @@ jQuery(document).ready(function ($) { - $('.expand_translations').click(function (e) { + $(".expand_translations").click(function (e) { e.preventDefault(); - display_translation_dialog($(this).siblings(), $(this).data('form_name'), $(this).data('source')); + display_translation_dialog( + $(this).siblings(), + $(this).data("form_name"), + $(this).data("source"), + ); }); - $('.change-icon-button').click(function (e) { + $("#add_lang_button").click(function (e) { + e.preventDefault(); + let selectedLangCode = $("#new_lang_select").val(); + let selectedLang = $("#new_lang_select option:selected").text(); + + let langkey = $(".lang_key"); + let defaultlabel = $(".default_label"); + let customlabel = $(".custom_label"); + let isocode = $(".iso_code"); + let enabledkey = $(".enabled"); + let tableLangs = {}; + for (let i = 0; i < langkey.length; i++) { + console.log(langkey.length); + let currentLangKey = $(langkey[i]); + let currentDefaultLabel = $(defaultlabel[i]); + let currentCustomLabel = $(customlabel[i]); + let currentIsoCode = $(isocode[i]); + let currentEnabledKey = $(enabledkey[i]); + let langKeyText = currentLangKey.text(); + if (!tableLangs[langKeyText]) { + tableLangs[langKeyText] = []; + tableLangs[langKeyText].push(langKeyText); + tableLangs[langKeyText].push(currentDefaultLabel.text()); + // tableLangs[langKeyText].push( + // currentCustomLabel.children("input").val() + // ); + tableLangs[langKeyText].push(currentIsoCode.children("input").val()); + tableLangs[langKeyText].push( + currentEnabledKey.children("input").prop("checked"), + ); + } + } + + let lang_exists = ""; + for (var key in tableLangs) { + if (Object.prototype.hasOwnProperty.call(tableLangs, "key")) { + if (tableLangs[key].indexOf(selectedLangCode) !== -1) { + console.log("you shall not pass"); + lang_exists = "true"; + window.alert("This language has already been added"); + break; + } else { + console.log("in here"); + lang_exists = "false"; + } + } + } + // language_label[][default]" value="").append( + $("").text(selectedLangCode), + $("").text(selectedLang), + $( + "", + ), + $( + "", + ), + $(""), + $( + "", + ), + ); + + $("#language_table tbody").append(newRow); + } else { + console.log("here"); + } + langkey = ""; + }); + + $("#save_lang_button").click(function (e) { + let button = $(e.currentTarget); + e.preventDefault(); + let langkey = $(".lang_key"); + let defaultlabel = $(".default_label"); + let customlabel = $(".custom_label"); + let isocode = $(".iso_code"); + let enabledkey = $(".enabled"); + let translationkey = $(".translation_key"); + let tableLangs = {}; + let i = 0; + + while (i < langkey.length) { + // console.log(customlabel, "customlabel"); + if (!tableLangs[langkey[i].textContent]) { + tableLangs[langkey[i].textContent] = {}; + } + tableLangs[langkey[i].textContent]["label"] = langkey[i].textContent; + tableLangs[langkey[i].textContent]["native_name"] = + defaultlabel[i].textContent; + // tableLangs[langkey[i].textContent]["flag"] = customlabel; + tableLangs[langkey[i].textContent]["flag"] = + customlabel[i].children[0].value; + // tableLangs[langkey[i].textContent]["flag"] = ""; + tableLangs[langkey[i].textContent]["rtl"] = isocode[i].textContent; + // tableLangs[langkey[i].textContent].push( + // enabledkey[i].children[0].checked + // ); + + i++; + } + console.log(tableLangs, "line 134"); + + $.ajax({ + type: "POST", + dataType: "json", + data: JSON.stringify(tableLangs), + contentType: "application/json; charset=utf-8", + url: `${window.dt_admin_scripts.rest_root}dt-admin-settings/languages/`, + beforeSend: (xhr) => { + xhr.setRequestHeader("X-WP-Nonce", window.dt_admin_scripts.nonce); + }, + success: function (response) { + var languages = JSON.parse(response); + console.log(languages, "success"); + }, + error: function (xhr, status, error) { + console.log(error, "error line 82"); + console.log(status, "status line 83"); + console.error(xhr.responseText, "responsetext line 84"); + }, + }); + }); + + $(".change-icon-button").click(function (e) { e.preventDefault(); // Fetch handle to key workflow elements - let parent_form = $("form[name='" + $(e.currentTarget).data('form') + "']"); - let icon_input = $("input[name='" + $(e.currentTarget).data('icon-input') + "']"); + let parent_form = $("form[name='" + $(e.currentTarget).data("form") + "']"); + let icon_input = $( + "input[name='" + $(e.currentTarget).data("icon-input") + "']", + ); // Display icon selector dialog display_icon_selector_dialog(parent_form, icon_input); }); // Support DT customization icon picker requests. - $('.dt-admin-modal-box').on('click', '.change-icon-button', function (e) { - let icon_input = $("input[name='" + $(e.currentTarget).data('icon-input') + "']"); - let dialog = $('#dt_icon_selector_dialog'); + $(".dt-admin-modal-box").on("click", ".change-icon-button", function (e) { + let icon_input = $( + "input[name='" + $(e.currentTarget).data("icon-input") + "']", + ); + let dialog = $("#dt_icon_selector_dialog"); if (dialog) { - dialog.dialog({ modal: false, autoOpen: false, hide: 0, show: 0, - height: 'auto', - width: 'auto', + height: "auto", + width: "auto", resizable: false, - title: 'Icon Selector Dialog', + title: "Icon Selector Dialog", buttons: [ { - text: 'Cancel', - icon: 'ui-icon-close', + text: "Cancel", + icon: "ui-icon-close", click: function () { - $(this).dialog('close'); - } + $(this).dialog("close"); + }, }, { - text: 'Save', - icon: 'ui-icon-copy', - click: function () { - } + text: "Save", + icon: "ui-icon-copy", + click: function () {}, }, { - text: 'Upload Custom Icon', - icon: 'ui-icon-circle-zoomout', - click: function () { - } - } + text: "Upload Custom Icon", + icon: "ui-icon-circle-zoomout", + click: function () {}, + }, ], open: function (event, ui) { - let ui_dialog = $(document).find('.ui-dialog')[0]; + let ui_dialog = $(document).find(".ui-dialog")[0]; // Fetch and set font icon picker dialog contents. if (ui_dialog) { - let cloned = $(ui_dialog).clone(); let html = ` @@ -84,102 +214,102 @@ jQuery(document).ready(function ($) { `; // Set some initial defaults to aid downstream processing. - let content = $('.dt-admin-modal-icon-picker-box-content'); + let content = $(".dt-admin-modal-icon-picker-box-content"); content.html(html); - content.find('button.ui-dialog-titlebar-close').hide(); - content.find('span.ui-dialog-title').css('font-weight', 'bold'); - content.find('button.ui-button').data('icon-input', icon_input.attr('name')); - + content.find("button.ui-dialog-titlebar-close").hide(); + content.find("span.ui-dialog-title").css("font-weight", "bold"); + content + .find("button.ui-button") + .data("icon-input", icon_input.attr("name")); } // Force an immediate close, to draw attention to flipped content! - $(this).dialog('close'); + $(this).dialog("close"); // Display some initial icons execute_icon_selection_filter_query(false); }, - close: function (event, ui) { - } + close: function (event, ui) {}, }); // Insert selection area div, within dialog button footer - let ui_dialog_buttonset = $('.ui-dialog-buttonset'); - ui_dialog_buttonset.css('margin', '1.5em'); - ui_dialog_buttonset.prepend($('') - .attr('id', 'dialog_icon_selector_icon_selection_div') - .css('display', 'inline-block') - .css('vertical-align', 'middle') - .css('padding', '0') - .css('margin-right', '175px') + let ui_dialog_buttonset = $(".ui-dialog-buttonset"); + ui_dialog_buttonset.css("margin", "1.5em"); + ui_dialog_buttonset.prepend( + $("") + .attr("id", "dialog_icon_selector_icon_selection_div") + .css("display", "inline-block") + .css("vertical-align", "middle") + .css("padding", "0") + .css("margin-right", "175px"), ); // Display updated dialog - dialog.dialog('open'); - + dialog.dialog("open"); } }); - $('.dt-admin-modal-box').on('click', '.ui-button', function (e) { - + $(".dt-admin-modal-box").on("click", ".ui-button", function (e) { // Determine action to be taken. let button = $(e.currentTarget); - let icon_input = $("input[name='" + $(button).data('icon-input') + "']"); - let close_button = button.find('span.ui-icon-close'); - let save_button = button.find('span.ui-icon-copy'); - let upload_button = button.find('span.ui-icon-circle-zoomout'); + let icon_input = $("input[name='" + $(button).data("icon-input") + "']"); + let close_button = button.find("span.ui-icon-close"); + let save_button = button.find("span.ui-icon-copy"); + let upload_button = button.find("span.ui-icon-circle-zoomout"); if (close_button && close_button.length > 0) { - $('.dt-admin-modal-icon-picker-box-close-button').click(); - + $(".dt-admin-modal-icon-picker-box-close-button").click(); } else if (save_button && save_button.length > 0) { handle_icon_save(null, null, icon_input, function (source) { - // Refresh icon image accordingly, to capture any changes. - let icon_img_wrapper = $(icon_input).parent().find('.field-icon-wrapper'); + let icon_img_wrapper = $(icon_input) + .parent() + .find(".field-icon-wrapper"); if (icon_img_wrapper) { let icon = $(icon_input).val(); - $(icon_img_wrapper).html((icon && icon.trim().toLowerCase().startsWith('mdi') ? ``:``)); + $(icon_img_wrapper).html( + icon && icon.trim().toLowerCase().startsWith("mdi") + ? `` + : ``, + ); } - $('.dt-admin-modal-icon-picker-box-close-button').click(); - + $(".dt-admin-modal-icon-picker-box-close-button").click(); }); - } else if (upload_button && upload_button.length > 0) { handle_icon_upload(null, null, icon_input, function (source) { - // Refresh icon image accordingly, to capture any changes. - let icon_img_wrapper = $(icon_input).parent().find('.field-icon-wrapper'); + let icon_img_wrapper = $(icon_input) + .parent() + .find(".field-icon-wrapper"); if (icon_img_wrapper) { let icon = $(icon_input).val(); - $(icon_img_wrapper).html((icon && icon.trim().toLowerCase().startsWith('mdi') ? ``:``)); + $(icon_img_wrapper).html( + icon && icon.trim().toLowerCase().startsWith("mdi") + ? `` + : ``, + ); } - $('.dt-admin-modal-icon-picker-box-close-button').click(); - + $(".dt-admin-modal-icon-picker-box-close-button").click(); }); - } - }); /** * Icon selector modal dialog - Process icon selection filter queries & selections */ - $(document).on('keyup', '#dialog_icon_selector_filter_input', function (e) { - let code = (e.keyCode || e.which); + $(document).on("keyup", "#dialog_icon_selector_filter_input", function (e) { + let code = e.keyCode || e.which; // Only get excited over specific key codes. - if ((code===8) || - (code===13) || - ((code >= 48) && (code <= 90))) { - + if (code === 8 || code === 13 || (code >= 48 && code <= 90)) { execute_icon_selection_filter_query(); } }); - $(document).on('click', '.dialog-icon-selector-icon', function (e) { + $(document).on("click", ".dialog-icon-selector-icon", function (e) { handle_icon_selection($(e.currentTarget)); }); @@ -190,48 +320,52 @@ jQuery(document).ready(function ($) { * Translation modal dialog */ - function display_translation_dialog(container, form_name, source = '') { - let dialog = $('#dt_translation_dialog'); + function display_translation_dialog(container, form_name, source = "") { + let dialog = $("#dt_translation_dialog"); if (container && form_name && dialog) { - // Update dialog div - $(dialog).empty().append($($(container).find('table')[0]).clone()); + $(dialog) + .empty() + .append($($(container).find("table")[0]).clone()); // Refresh dialog config dialog.dialog({ modal: true, autoOpen: false, - hide: 'fade', - show: 'fade', - height: 'auto', - width: 'auto', + hide: "fade", + show: "fade", + height: "auto", + width: "auto", resizable: true, - title: 'Translation Dialog', + title: "Translation Dialog", buttons: { Update: function () { - // Update source translation container $(container).empty().append($(this).children()); // Close dialog - $(this).dialog('close'); + $(this).dialog("close"); // Finally, auto save changes, accordingly, based on source. - if (window.lodash.includes(['fields'], source)) { - handle_custom_field_save_request(null, $('.dt-custom-fields-save-button')[0], true); + if (window.lodash.includes(["fields"], source)) { + handle_custom_field_save_request( + null, + $(".dt-custom-fields-save-button")[0], + true, + ); } else { $('form[name="' + form_name + '"]').submit(); } - - } - } + }, + }, }); // Display updated dialog - dialog.dialog('open'); - + dialog.dialog("open"); } else { - console.log('Unable to reference a valid: [container, form-name, dialog]'); + console.log( + "Unable to reference a valid: [container, form-name, dialog]", + ); } } @@ -239,69 +373,70 @@ jQuery(document).ready(function ($) { * Icon selector modal dialog */ - function display_icon_selector_dialog(parent_form, icon_input, callback = function (source) { - }) { - let dialog = $('#dt_icon_selector_dialog'); + function display_icon_selector_dialog( + parent_form, + icon_input, + callback = function (source) {}, + ) { + let dialog = $("#dt_icon_selector_dialog"); if (dialog) { - // Refresh dialog config dialog.dialog({ modal: true, autoOpen: false, - hide: 'fade', - show: 'fade', - height: 'auto', - width: 'auto', + hide: "fade", + show: "fade", + height: "auto", + width: "auto", resizable: false, - title: 'Icon Selector Dialog', + title: "Icon Selector Dialog", buttons: [ { - text: 'Cancel', - icon: 'ui-icon-close', + text: "Cancel", + icon: "ui-icon-close", click: function () { - $(this).dialog('close'); - callback('cancel'); - } + $(this).dialog("close"); + callback("cancel"); + }, }, { - text: 'Save', - icon: 'ui-icon-copy', + text: "Save", + icon: "ui-icon-copy", click: function () { handle_icon_save(this, parent_form, icon_input, callback); - } + }, }, { - text: 'Upload Custom Icon', - icon: 'ui-icon-circle-zoomout', + text: "Upload Custom Icon", + icon: "ui-icon-circle-zoomout", click: function () { handle_icon_upload(this, parent_form, icon_input, callback); - } - } + }, + }, ], open: function (event, ui) { - // Display some initial icons execute_icon_selection_filter_query(); }, close: function (event, ui) { - callback('dialogclose'); - } + callback("dialogclose"); + }, }); // Insert selection area div, within dialog button footer - $('.ui-dialog-buttonset').prepend($('') - .attr('id', 'dialog_icon_selector_icon_selection_div') - .css('display', 'inline-block') - .css('vertical-align', 'middle') - .css('padding', '0') - .css('margin-right', '175px') + $(".ui-dialog-buttonset").prepend( + $("") + .attr("id", "dialog_icon_selector_icon_selection_div") + .css("display", "inline-block") + .css("vertical-align", "middle") + .css("padding", "0") + .css("margin-right", "175px"), ); // Display updated dialog - dialog.dialog('open'); - + dialog.dialog("open"); } else { - console.log('Unable to reference a valid: [dialog]'); + console.log("Unable to reference a valid: [dialog]"); } } @@ -312,11 +447,19 @@ jQuery(document).ready(function ($) { function build_icon_class_name_list() { let icon_class_names = []; $.each(document.styleSheets, function (idx, style_sheet) { - if (window.lodash.includes(style_sheet.href, 'dt-core/dependencies/mdi/css/materialdesignicons.min.css')) { + if ( + window.lodash.includes( + style_sheet.href, + "dt-core/dependencies/mdi/css/materialdesignicons.min.css", + ) + ) { $.each(style_sheet.cssRules, function (key, rule) { - if (rule.constructor.name === 'CSSStyleRule') { + if (rule.constructor.name === "CSSStyleRule") { icon_class_names.push({ - class: rule.selectorText.substring(1, rule.selectorText.indexOf(':')) + class: rule.selectorText.substring( + 1, + rule.selectorText.indexOf(":"), + ), }); } }); @@ -347,68 +490,82 @@ jQuery(document).ready(function ($) { */ function execute_icon_selection_filter_query(enable_tooltips = true) { - // Always default to a somewhat wildcard search if input text is blank - let query = $('#dialog_icon_selector_filter_input').val().trim(); - query = window.lodash.isEmpty(query) ? 'a' : query; + let query = $("#dialog_icon_selector_filter_input").val().trim(); + query = window.lodash.isEmpty(query) ? "a" : query; // Proceed with icon display refresh - $('#dialog_icon_selector_icons_div').fadeOut('fast', function () { - $('#dialog_icon_selector_icons_search_msg').text('').fadeOut('fast'); - $('#dialog_icon_selector_icons_search_spinner').addClass('active').fadeIn('fast', function () { - - // Clear currently displayed icons - $('#dialog_icon_selector_icons_table > tbody > tr').remove(); - - // Obtain filtered icon list - let filtered_icons = window.lodash.filter(icons, function (icon) { - return icon['class'] && window.lodash.includes(icon['class'], query); - }); - - // Truncate filtered list for performance purposes - filtered_icons = filtered_icons.slice(0, 200); - - // Populate icons table - let loop_counter = 0; - let icon_counter = 0; - let tds = ''; - - $.each(filtered_icons, function (idx, filtered_icon) { - loop_counter++; - - let icon_class_name = filtered_icon['class']; - if (icon_class_name && is_icon_valid(icon_class_name)) { - tds += '' + $("#dialog_icon_selector_icons_div").fadeOut("fast", function () { + $("#dialog_icon_selector_icons_search_msg").text("").fadeOut("fast"); + $("#dialog_icon_selector_icons_search_spinner") + .addClass("active") + .fadeIn("fast", function () { + // Clear currently displayed icons + $("#dialog_icon_selector_icons_table > tbody > tr").remove(); + + // Obtain filtered icon list + let filtered_icons = window.lodash.filter(icons, function (icon) { + return ( + icon["class"] && window.lodash.includes(icon["class"], query) + ); + }); - if ((++icon_counter > 5) || (loop_counter >= filtered_icons.length)) { - $('#dialog_icon_selector_icons_table > tbody').append('' + tds + ''); - icon_counter = 0; - tds = ''; + // Truncate filtered list for performance purposes + filtered_icons = filtered_icons.slice(0, 200); + + // Populate icons table + let loop_counter = 0; + let icon_counter = 0; + let tds = ""; + + $.each(filtered_icons, function (idx, filtered_icon) { + loop_counter++; + + let icon_class_name = filtered_icon["class"]; + if (icon_class_name && is_icon_valid(icon_class_name)) { + tds += + ''; + + if (++icon_counter > 5 || loop_counter >= filtered_icons.length) { + $("#dialog_icon_selector_icons_table > tbody").append( + "" + tds + "", + ); + icon_counter = 0; + tds = ""; + } } - } - }); - - // If requested, activate icon tooltips - if (enable_tooltips) { - $('#dialog_icon_selector_icons_table > tbody').find('.mdi').each(function (idx, icon) { - $(icon).tooltip({ - show: {effect: 'fade', duration: 100} - }); }); - } - $('#dialog_icon_selector_icons_search_spinner').removeClass('active').fadeOut('fast', function () { - - // Display results or no icons found message - if (filtered_icons.length > 0) { - $('#dialog_icon_selector_icons_div').fadeIn('fast'); - - } else { - $('#dialog_icon_selector_icons_search_msg').text('No Icons Found').fadeIn('fast'); + // If requested, activate icon tooltips + if (enable_tooltips) { + $("#dialog_icon_selector_icons_table > tbody") + .find(".mdi") + .each(function (idx, icon) { + $(icon).tooltip({ + show: { effect: "fade", duration: 100 }, + }); + }); } + $("#dialog_icon_selector_icons_search_spinner") + .removeClass("active") + .fadeOut("fast", function () { + // Display results or no icons found message + if (filtered_icons.length > 0) { + $("#dialog_icon_selector_icons_div").fadeIn("fast"); + } else { + $("#dialog_icon_selector_icons_search_msg") + .text("No Icons Found") + .fadeIn("fast"); + } + }); }); - }); }); } @@ -417,20 +574,20 @@ jQuery(document).ready(function ($) { */ function is_icon_valid(icon_class_name) { - // Firstly, empty sandbox... - $('#dialog_icon_selector_icons_sandbox_div').empty(); + $("#dialog_icon_selector_icons_sandbox_div").empty(); // Add corresponding icon - let icon = $('') - .addClass('mdi ' + icon_class_name) - .appendTo('#dialog_icon_selector_icons_sandbox_div'); + let icon = $("") + .addClass("mdi " + icon_class_name) + .appendTo("#dialog_icon_selector_icons_sandbox_div"); // Determine icon validity - let valid = window.getComputedStyle(icon[0], ':before')['content'] !== 'none'; + let valid = + window.getComputedStyle(icon[0], ":before")["content"] !== "none"; // Clear down sandbox and return findings - $('#dialog_icon_selector_icons_sandbox_div').empty(); + $("#dialog_icon_selector_icons_sandbox_div").empty(); return valid; } @@ -441,26 +598,26 @@ jQuery(document).ready(function ($) { function handle_icon_selection(icon) { if (icon) { - // Create a clone element, to be assigned to dialog footer let cloned_icon = $(icon).clone(true); // Using some fancy transitions, assign new cloned selection - $('#dialog_icon_selector_icon_selection_div').fadeOut('fast', function () { - - // Clear out previous selections - $('#dialog_icon_selector_icon_selection_div').empty(); - - // Make use of selection css class - $(cloned_icon).removeClass('dialog-icon-selector-icon'); - $(cloned_icon).addClass('dialog-icon-selector-icon-selected'); - $(cloned_icon).attr('title', $(icon).data('icon_class')); - - // Append and display selection - $('#dialog_icon_selector_icon_selection_div').append($(cloned_icon)); - $('#dialog_icon_selector_icon_selection_div').fadeIn('fast'); - - }); + $("#dialog_icon_selector_icon_selection_div").fadeOut( + "fast", + function () { + // Clear out previous selections + $("#dialog_icon_selector_icon_selection_div").empty(); + + // Make use of selection css class + $(cloned_icon).removeClass("dialog-icon-selector-icon"); + $(cloned_icon).addClass("dialog-icon-selector-icon-selected"); + $(cloned_icon).attr("title", $(icon).data("icon_class")); + + // Append and display selection + $("#dialog_icon_selector_icon_selection_div").append($(cloned_icon)); + $("#dialog_icon_selector_icon_selection_div").fadeIn("fast"); + }, + ); } } @@ -468,19 +625,23 @@ jQuery(document).ready(function ($) { * Icon selector modal dialog - Handle Icon Save */ - function handle_icon_save(dialog, parent_form, icon_input, callback = function (source) { - }) { - + function handle_icon_save( + dialog, + parent_form, + icon_input, + callback = function (source) {}, + ) { // Determine if there is a valid selection - let selected_icon = $('#dialog_icon_selector_icon_selection_div').find('.dialog-icon-selector-icon-selected'); + let selected_icon = $("#dialog_icon_selector_icon_selection_div").find( + ".dialog-icon-selector-icon-selected", + ); if ($(selected_icon).length) { - // Update form icon class input - icon_input.val('mdi ' + $(selected_icon).data('icon_class')); + icon_input.val("mdi " + $(selected_icon).data("icon_class")); // If present, close dialog if (dialog) { - $(dialog).dialog('close'); + $(dialog).dialog("close"); } // If present, auto-submit; to refresh changes @@ -489,7 +650,7 @@ jQuery(document).ready(function ($) { } // Execute callback with relevant source flag. - callback('save'); + callback("save"); } } @@ -497,57 +658,61 @@ jQuery(document).ready(function ($) { * Icon selector modal dialog - Handle Icon Uploads */ - function handle_icon_upload(dialog, parent_form, icon_input, callback = function (source) { - }) { - + function handle_icon_upload( + dialog, + parent_form, + icon_input, + callback = function (source) {}, + ) { // Build media uploader modal let mediaFrame = window.wp.media({ - // Accepts [ 'select', 'post', 'image', 'audio', 'video' ] // Determines what kind of library should be rendered. - frame: 'select', + frame: "select", // Modal title. - title: window.dt_admin_shared.escape(window.dt_admin_scripts.upload.title), + title: window.dt_admin_shared.escape( + window.dt_admin_scripts.upload.title, + ), // Enable/disable multiple select multiple: false, // Library wordpress query arguments. library: { - order: 'DESC', + order: "DESC", // [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ] - orderby: 'date', + orderby: "date", // mime type. e.g. 'image', 'image/jpeg' - type: ['image'], + type: ["image"], // Searches the attachment title. search: null, // Includes media only uploaded to the specified post (ID) - uploadedTo: null // wp.media.view.settings.post.id (for current post ID) + uploadedTo: null, // wp.media.view.settings.post.id (for current post ID) }, button: { - text: window.dt_admin_shared.escape(window.dt_admin_scripts.upload.button_txt) - } - + text: window.dt_admin_shared.escape( + window.dt_admin_scripts.upload.button_txt, + ), + }, }); // Handle selected files - mediaFrame.on('select', function () { - + mediaFrame.on("select", function () { // Fetch and convert selected into json object - let selected = mediaFrame.state().get('selection').first().toJSON(); + let selected = mediaFrame.state().get("selection").first().toJSON(); // Update form icon link icon_input.val(selected.url); // If present, close dialog if (dialog) { - $(dialog).dialog('close'); + $(dialog).dialog("close"); } // If present, auto-submit; to refresh changes @@ -556,8 +721,7 @@ jQuery(document).ready(function ($) { } // Execute callback with relevant source flag. - callback('upload'); - + callback("upload"); }); // Open the media uploader. @@ -567,104 +731,114 @@ jQuery(document).ready(function ($) { /** * Sorting code for tiles */ - $( ".connectedSortable" ).sortable({ - connectWith: ".connectedSortable", - placeholder: "ui-state-highlight" - }).disableSelection(); - - $( "#sort-tiles" ).sortable({ - items: "div.sort-tile:not(.disabled-drag)", - placeholder: "ui-state-highlight", - cancel: ".connectedSortable", - }).disableSelection(); - - $(".save-drag-changes").on( "click", function (){ + $(".connectedSortable") + .sortable({ + connectWith: ".connectedSortable", + placeholder: "ui-state-highlight", + }) + .disableSelection(); + + $("#sort-tiles") + .sortable({ + items: "div.sort-tile:not(.disabled-drag)", + placeholder: "ui-state-highlight", + cancel: ".connectedSortable", + }) + .disableSelection(); + + $(".save-drag-changes").on("click", function () { let order = []; - $(".sort-tile").each((a, b)=>{ - let tile_key = $(b).attr("id") + $(".sort-tile").each((a, b) => { + let tile_key = $(b).attr("id"); let tile = { key: tile_key, - fields: [] - } - $(`#${tile_key} .connectedSortable li`).each((field_index, field)=>{ - tile.fields.push($(field).attr('id')) - }) - order.push(tile) - }) + fields: [], + }; + $(`#${tile_key} .connectedSortable li`).each((field_index, field) => { + tile.fields.push($(field).attr("id")); + }); + order.push(tile); + }); let input = $("") - .attr("type", "hidden") - .attr("name", "order").val(JSON.stringify(order)); - $('#tile-order-form').append(input).submit(); - - }) - + .attr("type", "hidden") + .attr("name", "order") + .val(JSON.stringify(order)); + $("#tile-order-form").append(input).submit(); + }); /** * new fields */ //show more fields when connection option selected - $('#new_field_type_select').on('change', function (){ - if ( this.value === "connection" ){ - $('.connection_field_target_row').show() - $('#private_field_row').hide() - $('#connection_field_target').prop('required', true); + $("#new_field_type_select").on("change", function () { + if (this.value === "connection") { + $(".connection_field_target_row").show(); + $("#private_field_row").hide(); + $("#connection_field_target").prop("required", true); } else { - $('.connection_field_reverse_row').hide() - $('.connection_field_target_row').hide() - $('#private_field_row').show() - $('#connection_field_target').prop('required', false); + $(".connection_field_reverse_row").hide(); + $(".connection_field_target_row").hide(); + $("#private_field_row").show(); + $("#connection_field_target").prop("required", false); } - }) + }); //show the reverse connection field name row if the post type is not "self" - $('#connection_field_target').on("change", function (){ - let post_type_label = $( "#connection_field_target option:selected" ).text(); - $('.connected_post_type').html(post_type_label) - if ( this.value === $('#current_post_type').val()){ - $('.same_post_type_other_field_name').toggle(!$('#multidirectional_checkbox').is(':checked')) - $('.connection_field_reverse_row').hide() - $('.same_post_type_row').show() + $("#connection_field_target").on("change", function () { + let post_type_label = $("#connection_field_target option:selected").text(); + $(".connected_post_type").html(post_type_label); + if (this.value === $("#current_post_type").val()) { + $(".same_post_type_other_field_name").toggle( + !$("#multidirectional_checkbox").is(":checked"), + ); + $(".connection_field_reverse_row").hide(); + $(".same_post_type_row").show(); } else { - $('.same_post_type_other_field_name').hide() - $('.connection_field_reverse_row').show() - $('.same_post_type_row').hide() + $(".same_post_type_other_field_name").hide(); + $(".connection_field_reverse_row").show(); + $(".same_post_type_row").hide(); } - }) - + }); - $('#multidirectional_checkbox').on("change", function (){ - $('.same_post_type_other_field_name').toggle(!this.checked) - }) + $("#multidirectional_checkbox").on("change", function () { + $(".same_post_type_other_field_name").toggle(!this.checked); + }); /** * Sorting code for field options */ - $('.sortable-field-options').sortable({ - connectWith: '.sortable-field-options', - placeholder: 'ui-state-highlight', - update: function (evt, ui) { - - let updated_field_options_ordering = []; - - // Snapshot updated field options ordering by key. - $('.sortable-field-options').find('.sortable-field-options-key').each(function (idx, key_div) { - let key = $(key_div).text().trim(); - if (key) { - updated_field_options_ordering.push(encode_field_key_special_characters(key)); - } - }); - - // Persist updated field options ordering. - $('#sortable_field_options_ordering').val(JSON.stringify(updated_field_options_ordering)); + $(".sortable-field-options") + .sortable({ + connectWith: ".sortable-field-options", + placeholder: "ui-state-highlight", + update: function (evt, ui) { + let updated_field_options_ordering = []; + + // Snapshot updated field options ordering by key. + $(".sortable-field-options") + .find(".sortable-field-options-key") + .each(function (idx, key_div) { + let key = $(key_div).text().trim(); + if (key) { + updated_field_options_ordering.push( + encode_field_key_special_characters(key), + ); + } + }); - } - }).disableSelection(); + // Persist updated field options ordering. + $("#sortable_field_options_ordering").val( + JSON.stringify(updated_field_options_ordering), + ); + }, + }) + .disableSelection(); function encode_field_key_special_characters(key) { - key = window.lodash.replace(key, '<', '_less_than_'); - key = window.lodash.replace(key, '>', '_more_than_'); + key = window.lodash.replace(key, "<", "_less_than_"); + key = window.lodash.replace(key, ">", "_more_than_"); return key; } @@ -673,14 +847,21 @@ jQuery(document).ready(function ($) { * Tile Display Conditions - [START] */ - $(document).on('click', 'input:radio[name="tile_display_option"]', function (e) { - handle_tile_display_condition_selection($(e.currentTarget)); - }); + $(document).on( + "click", + 'input:radio[name="tile_display_option"]', + function (e) { + handle_tile_display_condition_selection($(e.currentTarget)); + }, + ); function handle_tile_display_condition_selection(display_condition) { - let show_custom = display_condition && $(display_condition).val() == 'custom'; - let custom_elements = $('#tile_display_custom_elements'); - show_custom ? $(custom_elements).slideDown('slow') : $(custom_elements).slideUp('slow'); + let show_custom = + display_condition && $(display_condition).val() == "custom"; + let custom_elements = $("#tile_display_custom_elements"); + show_custom + ? $(custom_elements).slideDown("slow") + : $(custom_elements).slideUp("slow"); } /** @@ -691,42 +872,39 @@ jQuery(document).ready(function ($) { * Tile Display Help Modal - [START] */ - $(document).on('click', '.help-button', function (e) { + $(document).on("click", ".help-button", function (e) { handle_tile_display_help_modal($(e.currentTarget)); }); function handle_tile_display_help_modal(help_button) { - let dialog = $('#' + $(help_button).data('dialog_id')); + let dialog = $("#" + $(help_button).data("dialog_id")); if (dialog) { - // Refresh help dialog config dialog.dialog({ modal: true, autoOpen: false, - hide: 'fade', - show: 'fade', + hide: "fade", + show: "fade", height: 600, width: 450, resizable: true, - title: 'Help Dialog', + title: "Help Dialog", buttons: [ { - text: 'OK', - icon: 'ui-icon-check', + text: "OK", + icon: "ui-icon-check", click: function () { - $(this).dialog('close'); - } - } + $(this).dialog("close"); + }, + }, ], - open: function (event, ui) { - } + open: function (event, ui) {}, }); // Display help dialog - dialog.dialog('open'); - + dialog.dialog("open"); } else { - console.log('Unable to reference a valid: [dialog]'); + console.log("Unable to reference a valid: [dialog]"); } } @@ -738,12 +916,15 @@ jQuery(document).ready(function ($) { * Alternative Save Flow - [START] */ - $(document).on('click', '.dt-custom-fields-save-button', function (e) { + $(document).on("click", ".dt-custom-fields-save-button", function (e) { handle_custom_field_save_request(e, $(e.currentTarget), false); }); - function handle_custom_field_save_request(event, save_button, translate_update_only) { - + function handle_custom_field_save_request( + event, + save_button, + translate_update_only, + ) { // If defined, short-circuit default save flow and adopt ajax approach if needed. if (event) { event.preventDefault(); @@ -751,79 +932,130 @@ jQuery(document).ready(function ($) { // Determine which save path is to be taken. if (!translate_update_only) { - $('form[name="' + $(save_button).data('form_id') + '"]').submit(); + $('form[name="' + $(save_button).data("form_id") + '"]').submit(); } else { - // Always capture field parent level name & description translations; which is present across all fields. let payload = { - 'post_type': $(save_button).data('post_type'), - 'field_id': $(save_button).data('field_id'), - 'field_type': $(save_button).data('field_type'), - 'translations': package_custom_field_translations($(save_button).data('field_id')), - 'option_translations': window.lodash.includes(['key_select', 'multi_select', 'link'], $(save_button).data('field_type')) ? package_custom_field_option_translations():[] + post_type: $(save_button).data("post_type"), + field_id: $(save_button).data("field_id"), + field_type: $(save_button).data("field_type"), + translations: package_custom_field_translations( + $(save_button).data("field_id"), + ), + option_translations: window.lodash.includes( + ["key_select", "multi_select", "link"], + $(save_button).data("field_type"), + ) + ? package_custom_field_option_translations() + : [], }; // Have core endpoint process field translations accordingly. $.ajax({ - type: 'POST', - contentType: 'application/json; charset=utf-8', - dataType: 'json', + type: "POST", + contentType: "application/json; charset=utf-8", + dataType: "json", data: JSON.stringify(payload), url: `${window.dt_admin_scripts.rest_root}dt-admin/scripts/update_custom_field_translations`, beforeSend: (xhr) => { - xhr.setRequestHeader('X-WP-Nonce', window.dt_admin_scripts.nonce); - } - }).done(function (response) { - - // Update translation counts. - $('#custom_name_translation_count').html((response['translations']) ? Object.keys(response['translations']).length:0); - $('#custom_description_translation_count').html((response['description_translations']) ? Object.keys(response['description_translations']).length:0); - if ((response['defaults']) && window.lodash.includes(['key_select', 'multi_select', 'link'], $(save_button).data('field_type'))) { - $('.sortable-field-options').find('tr.ui-sortable-handle').each(function (idx, tr) { - let option_key = $(tr).find('.sortable-field-options-key').text().trim(); - $(tr).find('#option_name_translation_count').html((response['defaults'] && response['defaults'][option_key] && response['defaults'][option_key]['translations']) ? Object.keys(response['defaults'][option_key]['translations']).length:0); - $(tr).find('#option_description_translation_count').html((response['defaults'] && response['defaults'][option_key] && response['defaults'][option_key]['description_translations']) ? Object.keys(response['defaults'][option_key]['description_translations']).length:0); - }); - } - - }).fail(function (error) { - console.log("error"); - console.log(error); - }); + xhr.setRequestHeader("X-WP-Nonce", window.dt_admin_scripts.nonce); + }, + }) + .done(function (response) { + // Update translation counts. + $("#custom_name_translation_count").html( + response["translations"] + ? Object.keys(response["translations"]).length + : 0, + ); + $("#custom_description_translation_count").html( + response["description_translations"] + ? Object.keys(response["description_translations"]).length + : 0, + ); + if ( + response["defaults"] && + window.lodash.includes( + ["key_select", "multi_select", "link"], + $(save_button).data("field_type"), + ) + ) { + $(".sortable-field-options") + .find("tr.ui-sortable-handle") + .each(function (idx, tr) { + let option_key = $(tr) + .find(".sortable-field-options-key") + .text() + .trim(); + $(tr) + .find("#option_name_translation_count") + .html( + response["defaults"] && + response["defaults"][option_key] && + response["defaults"][option_key]["translations"] + ? Object.keys( + response["defaults"][option_key]["translations"], + ).length + : 0, + ); + $(tr) + .find("#option_description_translation_count") + .html( + response["defaults"] && + response["defaults"][option_key] && + response["defaults"][option_key][ + "description_translations" + ] + ? Object.keys( + response["defaults"][option_key][ + "description_translations" + ], + ).length + : 0, + ); + }); + } + }) + .fail(function (error) { + console.log("error"); + console.log(error); + }); } } function package_custom_field_translations(field_id) { let packaged_translations = { - 'translations': [], - 'description_translations': [] + translations: [], + description_translations: [], }; // Locate field name translations. - let field_name_prefix = 'field_key_' + field_id + '_translation-'; + let field_name_prefix = "field_key_" + field_id + "_translation-"; $("input[id^='" + field_name_prefix + "']").each(function (idx, input) { - let locale = window.lodash.split($(input).attr('id'), '-')[1]; + let locale = window.lodash.split($(input).attr("id"), "-")[1]; let value = $(input).val(); if (locale && value) { - packaged_translations['translations'].push({ - 'locale': locale, - 'value': value + packaged_translations["translations"].push({ + locale: locale, + value: value, }); } }); // Locate field description translations. - let field_description_prefix = 'field_description_translation-'; - $("input[id^='" + field_description_prefix + "']").each(function (idx, input) { - let locale = window.lodash.split($(input).attr('id'), '-')[1]; - let value = $(input).val(); - if (locale && value) { - packaged_translations['description_translations'].push({ - 'locale': locale, - 'value': value - }); - } - }); + let field_description_prefix = "field_description_translation-"; + $("input[id^='" + field_description_prefix + "']").each( + function (idx, input) { + let locale = window.lodash.split($(input).attr("id"), "-")[1]; + let value = $(input).val(); + if (locale && value) { + packaged_translations["description_translations"].push({ + locale: locale, + value: value, + }); + } + }, + ); return packaged_translations; } @@ -831,48 +1063,62 @@ jQuery(document).ready(function ($) { function package_custom_field_option_translations() { let packaged_translations = []; - $('.sortable-field-options').find('tr.ui-sortable-handle').each(function (idx, tr) { - let translations = { - 'option_key': '', - 'option_translations': [], - 'option_description_translations': [] - }; - - // Determine option key. - let option_key = $(tr).find('.sortable-field-options-key').text().trim(); - if (option_key) { - translations['option_key'] = option_key; - - // Locate option key translations. - let option_key_prefix = 'field_option_' + option_key + '_translation-'; - $(tr).find("input[id^='" + option_key_prefix + "']").each(function (okt_idx, okt_input) { - let locale = window.lodash.split($(okt_input).attr('id'), '-')[1]; - let value = $(okt_input).val(); - if (locale && value) { - translations['option_translations'].push({ - 'locale': locale, - 'value': $(okt_input).val() + $(".sortable-field-options") + .find("tr.ui-sortable-handle") + .each(function (idx, tr) { + let translations = { + option_key: "", + option_translations: [], + option_description_translations: [], + }; + + // Determine option key. + let option_key = $(tr) + .find(".sortable-field-options-key") + .text() + .trim(); + if (option_key) { + translations["option_key"] = option_key; + + // Locate option key translations. + let option_key_prefix = + "field_option_" + option_key + "_translation-"; + $(tr) + .find("input[id^='" + option_key_prefix + "']") + .each(function (okt_idx, okt_input) { + let locale = window.lodash.split($(okt_input).attr("id"), "-")[1]; + let value = $(okt_input).val(); + if (locale && value) { + translations["option_translations"].push({ + locale: locale, + value: $(okt_input).val(), + }); + } }); - } - }); - // Locate option key description translations. - let option_key_description_prefix = 'option_description_' + option_key + '_translation-'; - $(tr).find("input[id^='" + option_key_description_prefix + "']").each(function (okdt_idx, okdt_input) { - let locale = window.lodash.split($(okdt_input).attr('id'), '-')[1]; - let value = $(okdt_input).val(); - if (locale && value) { - translations['option_description_translations'].push({ - 'locale': locale, - 'value': $(okdt_input).val() + // Locate option key description translations. + let option_key_description_prefix = + "option_description_" + option_key + "_translation-"; + $(tr) + .find("input[id^='" + option_key_description_prefix + "']") + .each(function (okdt_idx, okdt_input) { + let locale = window.lodash.split( + $(okdt_input).attr("id"), + "-", + )[1]; + let value = $(okdt_input).val(); + if (locale && value) { + translations["option_description_translations"].push({ + locale: locale, + value: $(okdt_input).val(), + }); + } }); - } - }); - // Package recent translations. - packaged_translations.push(translations); - } - }); + // Package recent translations. + packaged_translations.push(translations); + } + }); return packaged_translations; } @@ -880,6 +1126,4 @@ jQuery(document).ready(function ($) { /** * Alternative Save Flow - [END] */ - - -}) +}); diff --git a/dt-core/admin/menu/tabs/tab-custom-lists.php b/dt-core/admin/menu/tabs/tab-custom-lists.php index baee73025d..9170a65654 100644 --- a/dt-core/admin/menu/tabs/tab-custom-lists.php +++ b/dt-core/admin/menu/tabs/tab-custom-lists.php @@ -617,6 +617,8 @@ public static function admin_notice( string $notice, string $type ) { * UI for picking languages */ private function languages_box(){ + // $languages = array("en"=> array("label" => "English", "native_name" => "English", "flag" => '', "rtl" => false)); + $languages = dt_get_option( 'dt_working_languages' ) ?: []; $dt_global_languages_list = dt_get_global_languages_list(); uasort($dt_global_languages_list, function( $a, $b ) { @@ -624,9 +626,9 @@ private function languages_box(){ }); $form_name = 'languages_box'; ?> -
    - -
    - ${$(cloned).find('.ui-dialog-titlebar').html()} + ${$(cloned).find(".ui-dialog-titlebar").html()}

    - ${$(cloned).find('.ui-dialog-content').html()} + ${$(cloned).find(".ui-dialog-content").html()}

    - ${$(cloned).find('.ui-dialog-buttonpane').html()} + ${$(cloned).find(".ui-dialog-buttonpane").html()}
    + +
    @@ -641,18 +643,18 @@ private function languages_box(){ $language_option ) : $enabled = !isset( $language_option['deleted'] ) || $language_option['deleted'] == false; ?> - + - - - - - + + + + -
    + /> +
    -
    - + + +