Files
dw-sheet-data-checker/assets/admin-editor-interactions.js
2025-11-16 01:01:53 +07:00

754 lines
31 KiB
JavaScript

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
switch (operator) {
case '==':
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case '!=':
return (v1 != v2) ? options.fn(this) : options.inverse(this);
case '!==':
return (v1 !== v2) ? options.fn(this) : options.inverse(this);
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case '<=':
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
// Register the 'formatValue' helper to replace empty values with a dash
Handlebars.registerHelper('formatValue', function (value) {
return value === undefined || value === null || value.trim() === '' ? '-' : value;
});
Handlebars.registerHelper('eq', function(a, b) {
return a === b; // Return true or false
});
// Register the 'getStyle' helper for general border styles
Handlebars.registerHelper('getStyle', function (borderColor, borderWidth) {
const safeBorderColor = borderColor || 'black'; // Default fallback color
const safeBorderWidth = borderWidth || '1'; // Default fallback width
return `style="border-color: ${safeBorderColor}; border-width: ${safeBorderWidth}px;"`;
});
// Register the 'getStyleHeader' helper for header-specific styles
Handlebars.registerHelper('getStyleHeader', function (borderColor, borderWidth, headerColor) {
const safeBorderColor = borderColor || 'black'; // Default fallback color
const safeBorderWidth = borderWidth || '1'; // Default fallback width
const safeHeaderColor = headerColor || 'black'; // Default fallback text color
return `style="border-color: ${safeBorderColor}; border-width: ${safeBorderWidth}px; color: ${safeHeaderColor};"`;
});
// Register the 'getStyleValue' helper for value-specific styles
Handlebars.registerHelper('getStyleValue', function (borderColor, borderWidth, valueColor) {
const safeBorderColor = borderColor || 'black'; // Default fallback color
const safeBorderWidth = borderWidth || '1'; // Default fallback width
const safeValueColor = valueColor || 'black'; // Default fallback text color
return `style="border-color: ${safeBorderColor}; border-width: ${safeBorderWidth}px; color: ${safeValueColor};"`;
});
jQuery(document).ready(function ($) {
// Function to fetch and process Google Sheet data
function fetchAndStoreSheetData() {
const sheetUrl = $('#link').val(); // Get the URL from the input field
const isTSV = sheetUrl.includes('output=tsv'); // Detect format (TSV or CSV)
$.ajax({
url: sheetUrl,
type: 'GET',
success: function (response) {
const parsedData = parseSheetData(response, isTSV ? '\t' : ',');
const headers = parsedData.shift().map(header => header.trim()); // Clean headers
// Clean data rows and create an array of objects
const cleanedData = parsedData.map(row => {
return row.reduce((obj, value, index) => {
obj[headers[index]] = value.trim(); // Clean each value
return obj;
}, {});
});
// Store headers and full data in localStorage
localStorage.setItem('sheetHeaders', JSON.stringify(headers));
localStorage.setItem('sheetData', JSON.stringify(cleanedData));
// console.log('Headers:', headers); // For debugging
// console.log('Complete Data:', cleanedData); // For debugging
},
error: function (error) {
console.error('Error fetching data:', error);
}
});
}
// Function to parse raw data into an array using a delimiter
function parseSheetData(data, delimiter) {
return data.split('\n').map(row => row.split(delimiter));
}
$('#link').on('change', function(){
if($(this).val() !== ''){
$('tr.has-link').slideDown();
$('#checker_preview.postbox').slideDown();
$('#dummy').hide();
fetchAndStoreSheetData();
}else{
$('tr.has-link').slideUp();
$('#dummy').show();
$('#checker_preview.postbox').slideUp();
}
});
$('#link').trigger('change');
function getStoredSheetData() {
const data = JSON.parse(localStorage.getItem('sheetData'));
if (data) {
// console.log('Headers:', headers);
return data;
} else {
console.error('No stored data found.');
return null;
}
}
function getStoredSheetHeaders() {
const headers = JSON.parse(localStorage.getItem('sheetHeaders'));
if (headers) {
// console.log('Headers:', headers);
return headers;
} else {
console.error('No stored data found.');
return null;
}
}
// Example call to retrieve stored sheet data
const sheetData = getStoredSheetData();
const sheetHeaders = getStoredSheetHeaders();
$('.option-nav-menu').on('click', function(){
var table = $(this).data('table');
$('.option-nav-menu').removeClass('active');
$(this).addClass('active');
$('.table').hide();
$(table).show();
if(table == '#checker-result' && $.inArray($('.result-display-type').val(), ['standard-table', 'cards']) === -1){
$('#dw-checker-form').hide();
$('#dw-checker-result').show();
}else{
$('#dw-checker-form').show();
$('#dw-checker-result').hide();
}
});
function appendFieldsToPreview() {
var form_card = $('.repeater-card');
// Prepare data for fields
var fieldsData = [];
if (form_card.length > 0) {
$.each(form_card, function (index, card) {
var fieldType = $(card).find('.select-field-type').val();
var fieldId = $(card).find('.field-id').val();
var fieldLabel = $(card).find('.field-label').val();
var fieldPlaceholder = $(card).find('.field-placeholder').val();
var selectedKolom = $(card).find('.select-kolom').val(); // Get selected column
// Determine if it's a text or select field
if (fieldType === 'text') {
fieldsData.push({
fieldId: fieldId,
fieldLabel: fieldLabel,
fieldPlaceholder: fieldPlaceholder,
fieldLabelColor: $('.field-label-color').val(),
fieldDisplayLabel: $('.field-display-label').val(),
isTextField: true,
});
} else if (fieldType === 'select') {
let uniqueValues = [];
if (sheetHeaders.includes(selectedKolom)) { // Check if selectedKolom exists in sheetHeaders
// Extract unique values from the selected column in sheetData
$.each(sheetData, function (rowIndex, row) {
const value = row[selectedKolom]; // Access the value using the column name as the key
// Check if value exists and is not empty
if (value !== undefined && value !== null && value.trim() !== '' && value !== selectedKolom) {
const trimmedValue = value.trim(); // Trim whitespace
// Add to uniqueValues if it doesn't already exist
if (!uniqueValues.includes(trimmedValue)) {
uniqueValues.push(trimmedValue);
}
}
});
}
fieldsData.push({
fieldId: fieldId,
fieldLabel: fieldLabel,
fieldPlaceholder: fieldPlaceholder,
fieldLabelColor: $('.field-label-color').val(),
fieldDisplayLabel: $('.field-display-label').val(),
uniqueValues: uniqueValues,
isSelectField: true,
});
}
});
}
// Compile and render fields template
var fieldsTemplateSource = $('#fields-template').html();
var fieldsTemplate = Handlebars.compile(fieldsTemplateSource);
$('.dw-checker-form-fields').html(fieldsTemplate({ fields: fieldsData }));
// Handle styles and other elements
setStyles();
// Handle results display
handleResultsDisplay();
}
function setStyles() {
$('.dw-checker-wrapper').attr('style', 'background-color:' + $('.card-background').val() + $('.card-bg-opacity').val() + '; padding: ' + $('.card-padding').val() + 'em; border-radius: ' + $('.card-border-radius').val() + 'em; width: ' + $('.card-width').val() + 'px; box-shadow: ' + $('.card-box-shadow').val() + ' ' + $('.card-box-shadow-color').val() + ';');
$('.dw-checker-title')
.attr('style', 'color: ' + $('.card-title').val() + '; text-align: ' + $('.card-title-align').val() + ';')
.text($('#title').val());
$('.dw-checker-description')
.attr('style', 'color: ' + $('.card-description').val() + '; text-align: ' + $('.card-description-align').val() + ';')
.html($('#description').val());
$('.dw-checker-divider')
.attr('style', 'opacity:.25; border-color:' + $('.card-divider').val() + '; border-width:' + $('.card-divider-width').val() + ';');
// Button styles
setButtonStyles();
}
function setButtonStyles() {
$('.search-button')
.text($('.search-btn-text').val())
.attr('style', 'background-color:' + $('.search-btn-bg-color').val() + '; color:' + $('.search-btn-text-color').val() + ';');
$('.dw-checker-form-button')
.attr('style', 'justify-content:' + $('.search-btn-position').val());
$('.back-button')
.text($('.back-btn-text').val())
.attr('style', 'background-color:' + $('.back-btn-bg-color').val() + '; color:' + $('.back-btn-text-color').val() + ';');
$('.dw-checker-result-button')
.attr('style', 'justify-content:' + $('.back-btn-position').val());
}
function getColumnSettings() {
const columnSettings = {};
$('.card').each(function () {
const columnName = $(this).find('input[name*="[key]"]').val();
columnSettings[columnName] = {
hide: $(this).find('.output-value-visibility').is(':checked'),
type: $(this).find('.output-type').val(),
prefix: $(this).find('input[name*="[prefix]"]').val(),
button_text: $(this).find('input[name*="[button_text]"]').val()
};
});
return columnSettings;
}
// Preprocess sheetData based on column settings
function preprocessSheetData(sheetData, columnSettings) {
return sheetData.map(row => {
const processedRow = {};
for (const [key, value] of Object.entries(row)) {
if (!columnSettings[key]?.hide) {
processedRow[key] = value;
}
}
return processedRow;
});
}
// Handlebars helpers
Handlebars.registerHelper('getColumnSetting', function (columnName, settingKey, value) {
// Check if the value is empty
if (value === undefined || value === null || (typeof value === 'string' && value.trim() === '')) {
return ''; // Return a dash for empty values
}
// Get column settings
const columnSettings = getColumnSettings();
return columnSettings[columnName]?.[settingKey];
});
Handlebars.registerHelper('getValueWithPrefix', function (columnName) {
const columnSettings = getColumnSettings();
const prefix = columnSettings[columnName]?.prefix || '';
return `${prefix}${this[columnName]}`;
});
function handleResultsDisplay() {
if (sheetData.length > 0) {
// Extract column settings
const columnSettings = getColumnSettings();
// Preprocess sheetData based on column settings
const processedSheetData = preprocessSheetData(sheetData, columnSettings);
const displayTypeSet = $('.result-display-type').val();
const cardType = $('.result-display-card-type').val(); // Get card type
$('div#dw-checker-form > .dw-checker-wrapper').removeClass('standard-table vertical-table cards div').addClass(displayTypeSet+'-output-type');
console.log(cardType);
// Set row limits based on display type
let limitedData;
if (displayTypeSet === 'standard-table') {
limitedData = processedSheetData.slice(0, 30); // Show 30 rows for standard-table
} else {
if (displayTypeSet === 'cards' && cardType === 'row'){
limitedData = processedSheetData.slice(0, 10);
}else{
limitedData = processedSheetData.slice(0, 3); // Show 3 rows for other outputs
}
}
// Prepare data for Handlebars template
const resultsData = {
displayType: displayTypeSet,
cardType: cardType, // Pass card type to the template
columnHeaders: Object.keys(limitedData[0] || {}), // Column headers for standard table
results: limitedData,
resultDivider: $('.result-divider').val() || 'black', // Default fallback
resultDividerWidth: $('.result-divider-width').val() || '1', // Default fallback
headerColor: $('#result_header').val() || 'black', // Default fallback
valueColor: $('#result_value').val() || 'black' // Default fallback
};
// Debugging logs to verify data
console.log('Results Data:', resultsData);
// Determine which container to render into
let targetContainer;
if (['standard-table', 'cards'].includes(displayTypeSet)) {
targetContainer = $('#dw-checker-outside-results');
targetContainer.show(); // Show the outside container
$('.dw-checker-results').hide(); // Hide the standard results container
targetContainer = targetContainer.find('.dw-checker-wrapper');
// Do not hide the form
} else {
targetContainer = $('.dw-checker-results');
targetContainer.show(); // Show the standard results container
$('#dw-checker-outside-results').hide(); // Hide the outside container
// Hide the form (if needed)
}
// Compile and render the appropriate template
let renderedResults = '';
switch (displayTypeSet) {
case 'vertical-table':
const verticalTableTemplateSource = $('#vertical-table-template').html();
if (!verticalTableTemplateSource) {
console.error('Vertical table template is missing or undefined.');
return;
}
const verticalTableTemplate = Handlebars.compile(verticalTableTemplateSource);
renderedResults = verticalTableTemplate(resultsData);
break;
case 'div':
const divTemplateSource = $('#div-template').html();
if (!divTemplateSource) {
console.error('Div template is missing or undefined.');
return;
}
const divTemplate = Handlebars.compile(divTemplateSource);
renderedResults = divTemplate(resultsData);
break;
case 'standard-table':
const standardTableTemplateSource = $('#standard-table-template').html();
if (!standardTableTemplateSource) {
console.error('Standard table template is missing or undefined.');
return;
}
const standardTableTemplate = Handlebars.compile(standardTableTemplateSource);
renderedResults = standardTableTemplate(resultsData);
break;
case 'cards':
const cardsTemplateSource = $('#cards-template').html();
if (!cardsTemplateSource) {
console.error('Cards template is missing or undefined.');
return;
}
const cardsTemplate = Handlebars.compile(cardsTemplateSource);
renderedResults = cardsTemplate(resultsData);
break;
default:
console.error('Unknown display type:', displayTypeSet);
return;
}
// Insert rendered HTML into the target container
targetContainer.html(renderedResults);
// Initialize DataTables for standard table
if (displayTypeSet === 'standard-table') {
$('.dw-standard-table').DataTable({
paging: true,
pageLength: 10,
searching: false, // Hide search input
info: false, // Hide "Showing X of Y entries"
scrollX: true, // Enable horizontal scrolling
responsive: true
});
initializePagination(targetContainer);
}else if(displayTypeSet === 'cards'){
initializeCardPagination();
}
} else {
console.log('No data available in sheetData.');
}
}
// Pagination logic for cards
function initializeCardPagination() {
const pages = $('.result-page');
let currentPage = 0;
// Show the first page
$(pages[currentPage]).show();
// Update pagination controls
$('.current-page').text(`Data ${currentPage + 1}`);
// Previous button
$('.prev-page').on('click', function () {
if (currentPage > 0) {
$(pages[currentPage]).hide();
currentPage--;
$(pages[currentPage]).show();
$('.current-page').text(`Data ${currentPage + 1}`);
}
});
// Next button
$('.next-page').on('click', function () {
if (currentPage < pages.length - 1) {
$(pages[currentPage]).hide();
currentPage++;
$(pages[currentPage]).show();
$('.current-page').text(`Data ${currentPage + 1}`);
}
});
}
function initializePagination(container) {
let currentPage = 0;
const pages = container;
const totalPages = pages.length;
// Show the first page initially
pages.hide();
$(pages[currentPage]).show();
// Update pagination controls
$('.current-page').text(`Data #${currentPage + 1}`);
$('.prev-page').prop('disabled', currentPage === 0);
$('.next-page').prop('disabled', currentPage === totalPages - 1);
// Previous button click handler
$('.prev-page').on('click', () => {
if (currentPage > 0) {
currentPage--;
updatePage(pages, currentPage, totalPages);
}
});
// Next button click handler
$('.next-page').on('click', () => {
if (currentPage < totalPages - 1) {
currentPage++;
updatePage(pages, currentPage, totalPages);
}
});
}
function updatePage(pages, currentPage, totalPages) {
pages.hide();
$(pages[currentPage]).show();
$('.current-page').text(`Data ${currentPage + 1}`);
$('.prev-page').prop('disabled', currentPage === 0);
$('.next-page').prop('disabled', currentPage === totalPages - 1);
}
// Initial call to render preview
appendFieldsToPreview();
// Set an initial interval for updating the preview
// let preview_interval = setInterval(() => {
// if ($('#link').val() !== '' && $('#link_data').val() !== '') {
// appendFieldsToPreview();
// }
// }, $('#preview-interval').val() * 1000);
// Change event for updating the interval
$('#preview-interval').on('change', function () {
// clearInterval(preview_interval); // Clear the existing interval
// Set a new interval without redeclaring 'const'
// preview_interval = setInterval(() => {
// if ($('#link').val() !== '' && $('#link_data').val() !== '') {
// appendFieldsToPreview();
// }
// }, $('#preview-interval').val() * 1000);
});
// Click event for setting preview manually
$('.set-preview').on('click', function (e) {
e.preventDefault(); // Prevent default button behavior
appendFieldsToPreview(); // Call to update preview
});
$(document).on('click', '.add-form-card', function (e) {
e.preventDefault();
// Create a new card element using the Handlebars template
const cardTemplateSource = $('#repeater-template').html();
const cardTemplate = Handlebars.compile(cardTemplateSource);
// Prepare data for the new card
const newCardData = {
fields: {
newField: {
kolom: sheetHeaders, // Populate the 'kolom' select options with headers
type: 'text', // Default type
label: '', // Empty label for a fresh card
placeholder: '', // Empty placeholder for a fresh card
match: 'match' // Default match type
}
}
};
// Render the new card using Handlebars
const newCardHTML = cardTemplate(newCardData);
// Append the new card to the repeater form field container
$('.repeater-form-field').append(newCardHTML);
// Trigger change event on select elements if necessary
$('.select-kolom').trigger('change');
});
$(document).on('click', '.delete-form-card', function(e){
e.preventDefault();
$(this).parents('.card').remove();
});
$(document).on('change', '.select-kolom', function(){
$(this).parents('.card').find('.field-id').val('_'+$(this).val().replace(' ', '_').replace('.', '_').toLowerCase()).trigger('change');
$(this).parents('.card').find('.field-label').val($(this).val());
$(this).parents('.card').find('.field-placeholder').val($(this).val());
});
$(document).on('change', '.field-id', function(){
var value = $(this).val();
var card = $(this).parents('.card');
card.find('.select-kolom').attr('name', 'checker[fields]['+value+'][kolom]');
card.find('.select-field-type').attr('name', 'checker[fields]['+value+'][type]');
card.find('.field-label').attr('name', 'checker[fields]['+value+'][label]');
card.find('.field-placeholder').attr('name', 'checker[fields]['+value+'][placeholder]');
card.find('.select-match-type').attr('name', 'checker[fields]['+value+'][match]');
});
$(".repeater-form-field").sortable({
// handle: '.move-card', // Use this class as the handle for sorting
change: function(event, ui) {
ui.placeholder.css({
visibility: 'visible',
border: '2px dashed #cccccc',
borderRadius: '5px',
height: '15rem' // Placeholder height
});
},
placeholder: 'ui-state-highlight', // Optional: use a class for styling the placeholder
start: function(event, ui) {
ui.placeholder.height(ui.item.height()); // Match placeholder height to item being dragged
}
});
$('#title').on('input', function(){
$('.dw-checker-title').text($(this).val());
});
$('#description').on('input', function(){
$('.dw-checker-description').html($(this).val());
});
$(document).on('click', '.output-value-visibility', function(){
if($(this).is(':checked')){
$(this).val('yes');
}else{
$(this).val('no');
}
});
function setfields() {
// Check if sheetData is available
if (sheetData.length > 0) {
// Extract headers from sheetHeaders
const headers = sheetHeaders;
// Create options for kolom dropdown based on headers
let options = '';
$.each(headers, function (index, header) {
options += `<option value="${header}">${header}</option>`;
});
// Check if there is no post ID
if (!$('#post_id').val()) {
// Append an empty template for the repeater form field
$('.repeater-form-field').append($('#repeater-template-empty').html());
$('.select-kolom, .field-placeholder').trigger('change');
append_fields_to_preview();
} else {
// Load existing repeater field cards from post_meta
setTimeout(() => {
$.ajax({
type: 'post',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'load_repeater_field_card',
pid: $('#post_id').val(),
headers: sheetHeaders
},
success: function (response) {
const selectedColumns = Object.keys(response).map(key => {
return {
id: key, // Set the id to the key (e.g., _telegram)
kolom: response[key].label // Set kolom to the label property
};
});
// Compile Handlebars template
const source = $("#repeater-template").html();
const template = Handlebars.compile(source);
// Render template with server response data
const html = template({ fields: response });
// Insert rendered HTML into DOM
$('.repeater-form-field').html(html);
appendFieldsToPreview(); // Call additional function after rendering
$.each(selectedColumns, function(i, data){
const card_id = data.id;
$(`[name="checker[fields][${card_id}][kolom]"]`).val(data.kolom).trigger('change');
});
}
});
}, 2500);
}
$('.checker-preview > *').removeClass('d-none');
// Load output settings after a delay
setTimeout(() => {
$.ajax({
type: 'post',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'load_output_setting',
pid: $('#post_id').val(),
headers: sheetHeaders
},
success: function (response) {
if (response.success) {
// Compile output template using Handlebars
const source = $("#output-template").html();
const template = Handlebars.compile(source);
// Pass data to the output template
const html = template(response.data);
// Append rendered HTML to result value output
$('.result-value-output').html(html);
// Call additional functions after rendering
appendFieldsToPreview();
} else {
console.log('Error:', response.data);
}
}
});
}, 2500);
} else {
console.log('No sheet data available to set fields.');
}
}
setfields();
$(document).on('change', '.output-type', function(){
if($(this).val().includes('button')){
$(this).closest('.row').siblings('.type-button-link').show();
}else{
$(this).closest('.row').siblings('.type-button-link').hide();
}
});
$('.result-display-type').on('change', function(){
$('tr.setting-card-column').hide();
if($(this).val() == 'cards'){
$('tr.setting-card-column').show();
}
});
function set_card_output_style() {
var check = $('#result-card-output-grid-style');
if(check.length > 0){
$('#result-card-output-grid-style').append(`
:root {
--card-output-grid-column-desktop: repeat(${$('[name="checker[result][card_grid][desktop]"]').val()}, 1fr);
--card-output-grid-column-tablet: repeat(${$('[name="checker[result][card_grid][tablet]"]').val()}, 1fr);
--card-output-grid-column-mobile: repeat(${$('[name="checker[result][card_grid][mobile]"]').val()}, 1fr);
}
`);
}else{
$('head').append(`
<style id="result-card-output-grid-style">
:root {
--card-output-grid-column-desktop: repeat(${$('[name="checker[result][card_grid][desktop]"]').val()}, 1fr);
--card-output-grid-column-tablet: repeat(${$('[name="checker[result][card_grid][tablet]"]').val()}, 1fr);
--card-output-grid-column-mobile: repeat(${$('[name="checker[result][card_grid][mobile]"]').val()}, 1fr);
}
</style>
`);
}
}
$('.card-column-settings input').on('change blur', function(){
set_card_output_style();
});
set_card_output_style();
});