fixed
This commit is contained in:
1 parent
4194cef934
commit
363127fe9e
3350 files changed
+1284220
-1
No files matched your search
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* Generic create/edit form engine.
|
||||
*
|
||||
* Builds the form from the resource schema in resources.js, handles
|
||||
* multilingual (TM/RU/EN) tabbed inputs, Quill rich text, image uploads
|
||||
* with preview, client-side required validation with inline errors and submit.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const LANGS = [
|
||||
{ code: "tm", label: "TM" },
|
||||
{ code: "ru", label: "RU" },
|
||||
{ code: "en", label: "EN" },
|
||||
];
|
||||
|
||||
const QUILL_TOOLBAR = [
|
||||
[{ header: [1, 2, 3, false] }],
|
||||
["bold", "italic", "underline", "strike"],
|
||||
[{ list: "ordered" }, { list: "bullet" }],
|
||||
["link"],
|
||||
["clean"],
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const body = document.body;
|
||||
if (body.dataset.page !== "form") return;
|
||||
if (!Auth.requireAuth()) return;
|
||||
|
||||
const slug = body.dataset.resource;
|
||||
const mode = body.dataset.mode; // create | edit
|
||||
const recordId = body.dataset.id || "";
|
||||
const schema = Resources[slug];
|
||||
if (!schema) return;
|
||||
|
||||
const form = document.getElementById("resource-form");
|
||||
const fieldsContainer = document.getElementById("form-fields");
|
||||
const submitButton = document.getElementById("form-submit");
|
||||
let record = null;
|
||||
const richEditors = {};
|
||||
|
||||
// ----- field builders ----------------------------------------------------
|
||||
|
||||
function fieldWrapper(field, inner) {
|
||||
return `
|
||||
<div class="form-control w-full" data-field="${field.name}">
|
||||
<label class="label" for="field-${field.name}">
|
||||
<span class="label-text font-medium">${UI.escapeHtml(field.label)}${field.required ? ' <span class="text-error" aria-hidden="true">*</span>' : ""}</span>
|
||||
</label>
|
||||
${inner}
|
||||
${field.help ? `<p class="label-text-alt mt-1 text-base-content/60">${UI.escapeHtml(field.help)}</p>` : ""}
|
||||
<p class="mt-1 hidden text-sm text-error" data-error role="alert"></p>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function langTabsHtml(field, isTextarea) {
|
||||
const tabs = LANGS.map(
|
||||
(lang, index) =>
|
||||
`<button type="button" role="tab" aria-selected="${index === 0}" ` +
|
||||
`class="tab ${index === 0 ? "tab-active" : ""}" data-lang-tab="${lang.code}">${lang.label}</button>`
|
||||
).join("");
|
||||
const inputs = LANGS.map((lang, index) => {
|
||||
const shared = `id="field-${field.name}-${lang.code}" data-lang-input="${lang.code}" ` +
|
||||
`class="${isTextarea ? "textarea textarea-bordered w-full" : "input input-bordered w-full"} ${index === 0 ? "" : "hidden"}" ` +
|
||||
`placeholder="${UI.escapeHtml(field.label)} (${lang.label})" aria-label="${UI.escapeHtml(field.label)} in ${lang.label}"`;
|
||||
return isTextarea
|
||||
? `<textarea ${shared} rows="${field.rows || 5}"></textarea>`
|
||||
: `<input type="text" ${shared}>`;
|
||||
}).join("");
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<div role="tablist" class="tabs tabs-boxed mb-2 w-fit">${tabs}</div>${inputs}`
|
||||
);
|
||||
}
|
||||
|
||||
function langRichHtml(field) {
|
||||
const tabs = LANGS.map(
|
||||
(lang, index) =>
|
||||
`<button type="button" role="tab" aria-selected="${index === 0}" ` +
|
||||
`class="tab ${index === 0 ? "tab-active" : ""}" data-lang-tab="${lang.code}">${lang.label}</button>`
|
||||
).join("");
|
||||
const panels = LANGS.map(
|
||||
(lang, index) =>
|
||||
`<div data-lang-panel="${lang.code}" class="${index === 0 ? "" : "hidden"} rounded-lg border border-base-300 bg-base-100">` +
|
||||
`<div id="field-${field.name}-${lang.code}" class="min-h-[12rem]" aria-label="${UI.escapeHtml(field.label)} in ${lang.label}"></div>` +
|
||||
`</div>`
|
||||
).join("");
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<div role="tablist" class="tabs tabs-boxed mb-2 w-fit">${tabs}</div>${panels}`
|
||||
);
|
||||
}
|
||||
|
||||
function inputHtml(field) {
|
||||
const type = field.type === "date" ? "date" : "text";
|
||||
const pattern = field.numeric ? 'inputmode="decimal" pattern="[0-9]*[.,]?[0-9]*"' : "";
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<input type="${type}" id="field-${field.name}" class="input input-bordered w-full" ` +
|
||||
`placeholder="${UI.escapeHtml(field.placeholder || "")}" value="${UI.escapeHtml(field.defaultValue || "")}" ${pattern}>`
|
||||
);
|
||||
}
|
||||
|
||||
function textareaHtml(field) {
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<textarea id="field-${field.name}" class="textarea textarea-bordered w-full" rows="${field.rows || 5}"></textarea>`
|
||||
);
|
||||
}
|
||||
|
||||
function selectHtml(field) {
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<select id="field-${field.name}" class="select select-bordered w-full">
|
||||
<option value="" disabled selected>Loading…</option>
|
||||
</select>`
|
||||
);
|
||||
}
|
||||
|
||||
function imageHtml(field) {
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<div class="flex flex-col gap-3">
|
||||
<img data-image-preview alt="Preview" class="hidden h-32 w-fit max-w-xs rounded-lg border border-base-300 object-contain">
|
||||
<input type="hidden" data-image-path>
|
||||
<div class="flex items-center gap-3">
|
||||
<input type="file" id="field-${field.name}" accept="image/*" class="file-input file-input-bordered w-full max-w-xs">
|
||||
<span data-upload-spinner class="loading loading-spinner loading-sm hidden" aria-label="Uploading"></span>
|
||||
</div>
|
||||
</div>`
|
||||
);
|
||||
}
|
||||
|
||||
function quillHtml(quill) {
|
||||
if (!quill) return "";
|
||||
const text = quill.getText().replace(/\n/g, "").trim();
|
||||
if (!text) return "";
|
||||
return quill.root.innerHTML;
|
||||
}
|
||||
|
||||
function initRichEditors() {
|
||||
if (typeof Quill === "undefined") return;
|
||||
schema.fields
|
||||
.filter((field) => field.type === "lang-richtext")
|
||||
.forEach((field) => {
|
||||
richEditors[field.name] = {};
|
||||
LANGS.forEach((lang) => {
|
||||
const el = document.getElementById("field-" + field.name + "-" + lang.code);
|
||||
if (!el) return;
|
||||
richEditors[field.name][lang.code] = new Quill(el, {
|
||||
theme: "snow",
|
||||
modules: { toolbar: QUILL_TOOLBAR },
|
||||
placeholder: field.label + " (" + lang.label + ")",
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function buildFields() {
|
||||
fieldsContainer.innerHTML = schema.fields
|
||||
.map((field) => {
|
||||
switch (field.type) {
|
||||
case "lang":
|
||||
return langTabsHtml(field, false);
|
||||
case "lang-textarea":
|
||||
return langTabsHtml(field, true);
|
||||
case "lang-richtext":
|
||||
return langRichHtml(field);
|
||||
case "textarea":
|
||||
return textareaHtml(field);
|
||||
case "select":
|
||||
return selectHtml(field);
|
||||
case "image":
|
||||
return imageHtml(field);
|
||||
default:
|
||||
return inputHtml(field);
|
||||
}
|
||||
})
|
||||
.join("");
|
||||
|
||||
// Language tab switching.
|
||||
fieldsContainer.querySelectorAll("[data-field]").forEach((wrapper) => {
|
||||
const tabs = wrapper.querySelectorAll("[data-lang-tab]");
|
||||
if (!tabs.length) return;
|
||||
tabs.forEach((tab) => {
|
||||
tab.addEventListener("click", () => {
|
||||
tabs.forEach((t) => {
|
||||
t.classList.toggle("tab-active", t === tab);
|
||||
t.setAttribute("aria-selected", String(t === tab));
|
||||
});
|
||||
const code = tab.dataset.langTab;
|
||||
wrapper.querySelectorAll("[data-lang-input]").forEach((input) => {
|
||||
input.classList.toggle("hidden", input.dataset.langInput !== code);
|
||||
});
|
||||
wrapper.querySelectorAll("[data-lang-panel]").forEach((panel) => {
|
||||
panel.classList.toggle("hidden", panel.dataset.langPanel !== code);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
initRichEditors();
|
||||
|
||||
// Image upload handling.
|
||||
schema.fields
|
||||
.filter((field) => field.type === "image")
|
||||
.forEach((field) => {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${field.name}"]`);
|
||||
const fileInput = wrapper.querySelector('input[type="file"]');
|
||||
const pathInput = wrapper.querySelector("[data-image-path]");
|
||||
const preview = wrapper.querySelector("[data-image-preview]");
|
||||
const spinner = wrapper.querySelector("[data-upload-spinner]");
|
||||
|
||||
fileInput.addEventListener("change", async () => {
|
||||
const file = fileInput.files && fileInput.files[0];
|
||||
if (!file) return;
|
||||
spinner.classList.remove("hidden");
|
||||
fileInput.disabled = true;
|
||||
try {
|
||||
const path = await Api.upload(file);
|
||||
pathInput.value = path;
|
||||
preview.src = path;
|
||||
preview.classList.remove("hidden");
|
||||
clearError(field.name);
|
||||
UI.toast("Image uploaded", "success");
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
} finally {
|
||||
spinner.classList.add("hidden");
|
||||
fileInput.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function loadSelectOptions() {
|
||||
const selectFields = schema.fields.filter((field) => field.type === "select");
|
||||
await Promise.all(
|
||||
selectFields.map(async (field) => {
|
||||
const select = document.getElementById("field-" + field.name);
|
||||
try {
|
||||
const data = await Api.get(field.options.endpoint, { limit: 0, page: 0 });
|
||||
const items = (data && data[field.options.listKey]) || [];
|
||||
select.innerHTML =
|
||||
'<option value="" disabled selected>Select…</option>' +
|
||||
items
|
||||
.map(
|
||||
(item) =>
|
||||
`<option value="${item[field.options.valueField]}">${UI.escapeHtml(langText(item[field.options.labelField]))}</option>`
|
||||
)
|
||||
.join("");
|
||||
} catch (error) {
|
||||
select.innerHTML = '<option value="" disabled selected>Failed to load</option>';
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ----- values ------------------------------------------------------------
|
||||
|
||||
function setError(name, message) {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${name}"]`);
|
||||
if (!wrapper) return;
|
||||
const errorEl = wrapper.querySelector("[data-error]");
|
||||
errorEl.textContent = message;
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function clearError(name) {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${name}"]`);
|
||||
if (!wrapper) return;
|
||||
const errorEl = wrapper.querySelector("[data-error]");
|
||||
errorEl.textContent = "";
|
||||
errorEl.classList.add("hidden");
|
||||
}
|
||||
|
||||
function isLangField(type) {
|
||||
return type === "lang" || type === "lang-textarea" || type === "lang-richtext";
|
||||
}
|
||||
|
||||
function collectValues() {
|
||||
const values = {};
|
||||
schema.fields.forEach((field) => {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${field.name}"]`);
|
||||
if (field.type === "lang-richtext") {
|
||||
const value = {};
|
||||
LANGS.forEach((lang) => {
|
||||
value[lang.code] = quillHtml(richEditors[field.name] && richEditors[field.name][lang.code]);
|
||||
});
|
||||
values[field.name] = value;
|
||||
} else if (field.type === "lang" || field.type === "lang-textarea") {
|
||||
const value = {};
|
||||
wrapper.querySelectorAll("[data-lang-input]").forEach((input) => {
|
||||
value[input.dataset.langInput] = input.value.trim();
|
||||
});
|
||||
values[field.name] = value;
|
||||
} else if (field.type === "image") {
|
||||
values[field.name] = wrapper.querySelector("[data-image-path]").value;
|
||||
} else if (field.type === "date") {
|
||||
const raw = document.getElementById("field-" + field.name).value;
|
||||
values[field.name] = raw ? raw + "T00:00:00Z" : "";
|
||||
} else {
|
||||
values[field.name] = document.getElementById("field-" + field.name).value.trim();
|
||||
}
|
||||
});
|
||||
return values;
|
||||
}
|
||||
|
||||
function validate(values) {
|
||||
let valid = true;
|
||||
schema.fields.forEach((field) => {
|
||||
clearError(field.name);
|
||||
if (!field.required) return;
|
||||
const value = values[field.name];
|
||||
if (isLangField(field.type)) {
|
||||
if (!value.tm && !value.ru && !value.en) {
|
||||
setError(field.name, "Fill in at least one language.");
|
||||
valid = false;
|
||||
}
|
||||
} else if (!value) {
|
||||
setError(
|
||||
field.name,
|
||||
field.type === "image" ? "Please upload an image." : "This field is required."
|
||||
);
|
||||
valid = false;
|
||||
}
|
||||
});
|
||||
return valid;
|
||||
}
|
||||
|
||||
function populate(values) {
|
||||
schema.fields.forEach((field) => {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${field.name}"]`);
|
||||
const value = values[field.name];
|
||||
if (value === undefined || value === null) return;
|
||||
if (field.type === "lang-richtext") {
|
||||
LANGS.forEach((lang) => {
|
||||
const quill = richEditors[field.name] && richEditors[field.name][lang.code];
|
||||
if (!quill) return;
|
||||
const html = (value && value[lang.code]) || "";
|
||||
quill.setContents([]);
|
||||
if (html) {
|
||||
quill.clipboard.dangerouslyPasteHTML(html);
|
||||
}
|
||||
});
|
||||
} else if (field.type === "lang" || field.type === "lang-textarea") {
|
||||
wrapper.querySelectorAll("[data-lang-input]").forEach((input) => {
|
||||
input.value = (value && value[input.dataset.langInput]) || "";
|
||||
});
|
||||
} else if (field.type === "image") {
|
||||
const pathInput = wrapper.querySelector("[data-image-path]");
|
||||
const preview = wrapper.querySelector("[data-image-preview]");
|
||||
pathInput.value = value || "";
|
||||
if (value) {
|
||||
preview.src = value;
|
||||
preview.classList.remove("hidden");
|
||||
}
|
||||
} else if (field.type === "date") {
|
||||
const input = document.getElementById("field-" + field.name);
|
||||
input.value = value ? String(value).slice(0, 10) : "";
|
||||
} else {
|
||||
document.getElementById("field-" + field.name).value = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ----- load & submit -------------------------------------------------------
|
||||
|
||||
async function loadRecord() {
|
||||
if (mode !== "edit") return;
|
||||
const url = schema.getOneUrl
|
||||
? schema.getOneUrl(recordId)
|
||||
: `${schema.endpoint}/${recordId}`;
|
||||
try {
|
||||
record = await Api.get(url);
|
||||
const values = schema.recordToValues ? schema.recordToValues(record) : record;
|
||||
populate(values);
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const values = collectValues();
|
||||
if (!validate(values)) {
|
||||
UI.toast("Please fix the highlighted fields.", "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = schema.buildPayload(values, mode, record);
|
||||
UI.setLoading(submitButton, true);
|
||||
try {
|
||||
if (mode === "edit") {
|
||||
await Api.put(`${schema.endpoint}/${recordId}`, payload);
|
||||
} else {
|
||||
await Api.post(schema.endpoint, payload);
|
||||
}
|
||||
UI.toast(mode === "edit" ? "Saved successfully" : "Created successfully", "success");
|
||||
setTimeout(() => {
|
||||
window.location.href = "/admin/" + slug;
|
||||
}, 600);
|
||||
} catch (error) {
|
||||
UI.setLoading(submitButton, false);
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
});
|
||||
|
||||
// ----- init ----------------------------------------------------------------
|
||||
|
||||
buildFields();
|
||||
Auth.loadProfile();
|
||||
Auth.bindLogoutButtons();
|
||||
loadSelectOptions().then(loadRecord);
|
||||
});
|
||||
})();
|
||||
Reference in new issue
Block a user