Files
dw-sheet-data-checker/assets/admin-editor.js

786 lines
25 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);
}
});
Handlebars.registerHelper("eq", function (a, b) {
return a === b;
});
const safeStyle = (styleString) =>
new Handlebars.SafeString(`style="${styleString}"`);
const normalizeKeyToId = (key) =>
String(key || "")
.toLowerCase()
.replace(/\s+/g, "_")
.replace(/\./g, "_");
Handlebars.registerHelper("getStyle", function (divider, dividerWidth) {
return safeStyle(
`border-color: ${divider}; border-width: ${dividerWidth}px;`,
);
});
Handlebars.registerHelper(
"getStyleHeader",
function (divider, dividerWidth, headerColor) {
return safeStyle(
`border-color: ${divider}; border-width: ${dividerWidth}px; color: ${headerColor};`,
);
},
);
Handlebars.registerHelper(
"getStyleValue",
function (divider, dividerWidth, valueColor) {
return safeStyle(
`border-color: ${divider}; border-width: ${dividerWidth}px; color: ${valueColor};`,
);
},
);
Handlebars.registerHelper("formatValue", function (value) {
if (value === null || value === undefined) {
return "";
}
return value;
});
Handlebars.registerHelper("getColumnSetting", function (key, prop) {
const id = normalizeKeyToId(key);
switch (prop) {
case "hide":
return jQuery(`#output-visibility-${id}`).is(":checked") ? "yes" : "no";
case "type":
return jQuery(`#output-type-${id}`).val() || "text";
case "button_text":
return jQuery(`#output-buttontext-${id}`).val() || "";
case "prefix":
return jQuery(`#output-prefix-${id}`).val() || "";
case "bg_color":
return jQuery(`#output-bg_color-${id}`).val() || "#cccccc";
case "text_color":
return jQuery(`#output-text_color-${id}`).val() || "#000000";
default:
return "";
}
});
Handlebars.registerHelper("getValueWithPrefix", function (key, options) {
const prefix = Handlebars.helpers.getColumnSetting(key, "prefix");
const value =
options && options.data && options.data.root && options.data.root.value
? options.data.root.value
: this;
return `${prefix}${value || ""}`;
});
jQuery(document).ready(function ($) {
function get_the_header(data) {
var link_format = $(".sheet-url").val();
if (link_format === "") {
console.error("Error: No sheet URL found");
return false;
}
// Determine the format by checking the last few characters
var the_format = link_format.slice(-3);
var lines = data.split("\n");
var result = [];
var delimiter = ",";
// Set the correct delimiter based on the format
if (the_format === "csv") {
delimiter = ",";
} else if (the_format === "tsv") {
delimiter = "\t";
}
// Read headers
var headers = lines[0].split(delimiter).map((header) => header.trim()); // Trim any whitespace
if (!headers || headers.length === 0) {
console.error("Error: No headers found in data");
return false;
}
console.log("Headers found:", headers);
// Process each line and create objects
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentLine = lines[i].split(delimiter);
// Only process if the line has data
if (currentLine.length > 1 || currentLine[0] !== "") {
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] =
currentLine[j] !== undefined ? currentLine[j].trim() : null; // Handle missing values
}
result.push(obj);
}
}
setfields(result);
// Append the result as a JSON string in a textarea
$(".checker-preview").append(`
<textarea id="link_data" class="form-control w-100 d-none">${JSON.stringify(result)}</textarea>
`);
append_fields_to_preview();
}
function setfields(data) {
$.each(data, function (i, j) {
if (i == 0) {
var headers = Object.keys(j);
var existingCards = $(".repeater-card");
if (!$("#post_id").val()) {
var defaultKey = headers[0]
? "_" + headers[0].replace(" ", "_").replace(".", "_").toLowerCase()
: "field_1";
var defaultFields = {};
defaultFields[defaultKey] = {
type: "text",
label: headers[0] || "",
placeholder: headers[0] || "",
match: "match",
kolom: headers,
selected_kolom: headers[0] || "",
};
var sourceEmpty = $("#repeater-template").html();
if (!sourceEmpty) {
console.error("Template #repeater-template not found!");
return;
}
var templateEmpty = Handlebars.compile(sourceEmpty);
var htmlEmpty = templateEmpty({ fields: defaultFields });
$(".repeater-form-field").html(htmlEmpty);
$(".select-kolom, .field-placeholder").trigger("change");
append_fields_to_preview();
} else {
console.log("[FLOW] Existing post detected, will call load_repeater_field_card");
setTimeout(() => {
// Check if checkerAdminSecurity is available
if (typeof checkerAdminSecurity === 'undefined') {
console.error("checkerAdminSecurity is not defined!");
return;
}
// Extract headers from the first data item
var jsonData = JSON.parse($("#link_data").val());
var headers = [];
if (jsonData && jsonData.length > 0) {
headers = Object.keys(jsonData[0]);
}
console.log("[FLOW] About to call AJAX load_repeater_field_card");
console.log("[FLOW] Headers to send:", headers);
console.log("[FLOW] Post ID:", $("#post_id").val());
$.ajax({
type: "post",
url: checkerAdminSecurity.ajaxurl,
data: {
action: "load_repeater_field_card",
pid: $("#post_id").val(),
headers: headers,
security: checkerAdminSecurity.nonce,
},
success: function (response) {
console.log("[FLOW] ✅ AJAX success callback reached!");
console.log("[DEBUG] Response from PHP:", response);
console.log("[DEBUG] Response type:", typeof response);
console.log("[DEBUG] Response is empty?", Object.keys(response).length === 0);
if (response && response.success === false) {
console.error("Failed to load repeater fields:", response.data);
return;
}
// Check if template exists
var source = $("#repeater-template").html();
if (!source) {
console.error("Template #repeater-template not found!");
return;
}
console.log("[DEBUG] Template source length:", source.length);
// Compile template
var template = Handlebars.compile(source);
// Handle both raw object and wp_send_json_success payloads
var fieldData =
response && response.success && response.data
? response.data.fields || response.data
: response;
// Render template with response data
var html = template({ fields: fieldData });
console.log("[DEBUG] Rendered HTML length:", html.length);
console.log("[DEBUG] First 200 chars:", html.substring(0, 200));
// Insert into DOM
$(".repeater-form-field").html(html);
append_fields_to_preview();
},
error: function(xhr, status, error) {
console.error("[FLOW] ❌ AJAX ERROR!");
console.error("[FLOW] Status:", status);
console.error("[FLOW] Error:", error);
console.error("[FLOW] Response:", xhr.responseText);
}
});
}, 2500);
}
$(".checker-preview > *").removeClass("d-none");
setTimeout(() => {
// Extract headers for load_output_setting
var jsonData = JSON.parse($("#link_data").val());
var headers = [];
if (jsonData && jsonData.length > 0) {
headers = Object.keys(jsonData[0]);
}
$.ajax({
type: "post",
url: checkerAdminSecurity.ajaxurl,
data: {
action: "load_output_setting",
pid: $("#post_id").val(),
headers: headers,
security: checkerAdminSecurity.nonce,
},
success: function (response) {
if (!response || response.success === false) {
console.error("Failed to load output settings:", response && response.data);
return;
}
var payload = response.data;
// Support both {data: [...]} and direct array responses
if (payload && Array.isArray(payload.data)) {
payload = { data: payload.data };
} else if (Array.isArray(payload)) {
payload = { data: payload };
}
if (!payload || !Array.isArray(payload.data)) {
console.error("Output payload missing data array");
return;
}
// Compile the Handlebars template
var source = $("#output-template").html();
if (!source) {
console.error("Template #output-template not found!");
return;
}
var template = Handlebars.compile(source);
// Pass data to the template
var html = template(payload);
// Append the rendered HTML
$(".result-value-output").html(html);
// You can call other functions after the template is rendered
append_fields_to_preview();
},
});
}, 2500);
}
});
}
$(".sheet-url").on("change", function () {
if ($(this).is(":valid") && $(this).val() !== "") {
$("tr.has-link").slideDown();
$("#dw_checker_preview.postbox").slideDown();
$("#dummy").hide();
$.ajax({
type: "GET",
url: $(this).val(),
dataType: "text",
beforeSend: function () {
$(".checker-preview").append(`
<textarea id="link_data" class="form-control w-100">Loading Data....</textarea>
`);
},
success: function (data) {
$(".checker-preview textarea").remove();
get_the_header(data);
},
});
} else {
$("tr.has-link").slideUp();
$("#dummy").show();
$("#dw_checker_preview.postbox").slideUp();
}
});
$(".sheet-url").trigger("change");
function append_fields_to_preview() {
var form_card = $(".repeater-card");
$(".dw-checker-form-fields").html("");
if (form_card.length > 0) {
$.each(form_card, function (o, p) {
if ($(p).find(".select-field-type").val() == "text") {
$(".dw-checker-form-fields").append(
`
<div class="dw-checker-field">
<label for="` +
$(p).find(".field-id").val() +
`" style="color: ` +
$(".field-label-color").val() +
`;display: ` +
$(".field-display-label").val() +
`;">` +
$(p).find(".field-label").val() +
`</label>
<input name="` +
$(p).find("field-id").val() +
`" placeholder="` +
$(p).find(".field-placeholder").val() +
`"/>
</div>
`,
);
} else if ($(p).find(".select-field-type").val() == "select") {
var jsonData = JSON.parse($("#link_data").val());
var uniqueValues = [];
$.each(jsonData, function (index, item) {
var skema = item[$(p).find(".select-kolom").val()];
if ($.inArray(skema, uniqueValues) === -1) {
uniqueValues.push(skema);
}
});
// console.log(uniqueValues);
var options = "";
$.each(uniqueValues, function (q, r) {
options += '<option value="' + r + '">' + r + "</option>";
});
var exist = $(".dw-checker-field");
$(".dw-checker-form-fields").append(
`
<div class="dw-checker-field">
<label for="` +
$(p).find("field-id").val() +
`" style="color: ` +
$(".field-label-color").val() +
`;display: ` +
$(".field-display-label").val() +
`;">` +
$(p).find(".field-label").val() +
`</label>
<select name="` +
$(p).find("field-id").val() +
`" placeholder="` +
$(p).find(".field-placeholder").val() +
`">
<option value="">` +
$(p).find(".field-placeholder").val() +
`</option>
` +
options +
`
</select>
</div>
`,
);
}
});
}
$(".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() +
";",
);
$(".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(),
);
if ($("#link_data").val()) {
var linkDataValue = $("#link_data").val();
// Skip if it's a loading message
if (linkDataValue === "Loading Data....") {
return;
}
try {
var jsonData = JSON.parse(linkDataValue);
} catch (e) {
console.error("Error parsing JSON:", e);
return;
}
var resultData = [];
var resultDiv = "";
if ($(".result-display-type").val() == "table") {
$.each(jsonData, function (index, item) {
if (index == 0) {
resultData = item;
resultDiv +=
'<table class="dw-checker-result-table" style="border-color: ' +
$(".result-divider").val() +
"; border-width: " +
$(".result-divider-width").val() +
'px;"><tbody>';
var header_color = $("#result_header").val();
var value_color = $("#result_value").val();
$.each(item, function (q, r) {
var id = q.replace(" ", "_").replace(".", "_").toLowerCase();
var prefix = "";
if ($("#output-prefix-" + id).val()) {
prefix = $("#output-prefix-" + id).val();
}
if ($("#output-visibility-" + id).val() == "yes") {
return;
}
if ($("#output-type-" + id).val() == "link_button") {
r =
'<button href="' +
r +
'" class="dw-checker-value-button">' +
$("#output-buttontext-" + id).val() +
"</button>";
}
resultDiv += "<tr>";
resultDiv +=
'<th style="border-color: ' +
$(".result-divider").val() +
"; border-width: " +
$(".result-divider-width").val() +
'px;"><span class="dw-checker-result-header" style="color:' +
header_color +
'">' +
q +
"</span></th>";
resultDiv +=
'<td style="border-color: ' +
$(".result-divider").val() +
"; border-width: " +
$(".result-divider-width").val() +
'px;"><span class="dw-checker-result-value" style="color:' +
value_color +
'">' +
prefix +
r +
"</span></td>";
resultDiv += "</tr>";
});
resultDiv += "</tbody></table>";
}
});
} else if ($(".result-display-type").val() == "div") {
$.each(jsonData, function (index, item) {
if (index == 0) {
resultData = item;
var header_color = $("#result_header").val();
var value_color = $("#result_value").val();
$.each(item, function (q, r) {
var id = q.replace(" ", "_").replace(".", "_").toLowerCase();
var prefix = "";
if ($("#output-prefix-" + id).val()) {
prefix = $("#output-prefix-" + id).val();
}
if ($("#output-visibility-" + id).val() == "yes") {
return;
}
if ($("#output-type-" + id).val() == "link_button") {
r =
'<a href="' +
r +
'" class="dw-checker-value-button">' +
$("#output-buttontext-" + id).val() +
"</a>";
}
resultDiv +=
'<div class="dw-checker-result-div" style="border-bottom-color: ' +
$(".result-divider").val() +
"; border-bottom-width: " +
$(".result-divider-width").val() +
'px;">';
resultDiv +=
'<div class="result-header"><span class="dw-checker-result-header" style="color:' +
header_color +
';">' +
q +
"</span></div>";
resultDiv +=
'<div class="result-value"><span class="dw-checker-result-value" style="color:' +
value_color +
';">' +
prefix +
r +
"</span></div>";
resultDiv += "</div>";
});
}
});
}
$(".dw-checker-results").html(resultDiv);
}
$(".dw-checker-value-button").attr(
"style",
"background-color: " +
$(".search-btn-bg-color").val() +
"; color: " +
$(".search-btn-text-color").val() +
";",
);
}
setInterval(
() => {
if ($("#link").val() !== "" && $("#link_data").val() !== "") {
append_fields_to_preview();
}
},
$("#preview-interval").val() * 1000,
);
$(".set-preview").on("click", function (e) {
e.preventDefault();
append_fields_to_preview();
});
$(document).on("click", ".add-form-card", function (e) {
e.preventDefault();
var source = $("#repeater-template").html();
if (!source) {
console.error("Template #repeater-template not found!");
return;
}
var headers = [];
if ($(".select-kolom").length) {
$(".select-kolom")
.first()
.find("option")
.each(function (_, opt) {
headers.push($(opt).val());
});
}
if (!headers.length && $("#link_data").val()) {
try {
var jsonData = JSON.parse($("#link_data").val());
if (jsonData && jsonData.length > 0) {
headers = Object.keys(jsonData[0]);
}
} catch (err) {
console.error("Unable to parse headers for new field card", err);
}
}
var newKey =
"field_" +
(Date.now().toString(36) + Math.random().toString(36).slice(2, 6));
var fieldConfig = {};
fieldConfig[newKey] = {
type: "text",
label: headers[0] || "",
placeholder: headers[0] || "",
match: "match",
kolom: headers,
selected_kolom: headers[0] || "",
};
var template = Handlebars.compile(source);
var html = template({ fields: fieldConfig });
$(".repeater-form-field").append(html);
$(".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({
change: function (event, ui) {
ui.placeholder.css({
visibility: "visible",
border: "2px dashed #cccccc",
borderRadius: "5px",
height: "15rem",
});
},
});
$("#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");
}
});
$(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();
}
});
$(".option-nav-menu").on("click", function () {
var table = $(this).data("table");
$(".option-nav-menu").removeClass("active");
$(this).addClass("active");
$(".checker-setting").hide();
if (table == "#checker-card") {
$("#checker-card").show();
} else if (table == "#checker-result") {
$("#checker-result").show();
} else if (table == "#checker-security") {
$("#checker-security").show();
} else if (table == "#checker-form") {
$("#checker-form").show();
}
});
$(".result-display-type").on("change", function () {
$("tr.setting-card-column").hide();
if ($(this).val() == "card") {
$("tr.setting-card-column").show();
}
});
});