release: WRNexusJS 0.5.0
This commit is contained in:
@@ -10,7 +10,7 @@ import type { SchemaDescriptor } from "./index.ts";
|
||||
|
||||
/** `window.__wireSchemas = { name: descriptor, ... }` for the client validator. */
|
||||
export function renderSchemasScript(descriptors: Record<string, SchemaDescriptor>): string {
|
||||
return `window.__wireSchemas=${JSON.stringify(descriptors)};`;
|
||||
return `window.__wireSchemas=Object.assign(window.__wireSchemas||{},${JSON.stringify(descriptors)});`;
|
||||
}
|
||||
|
||||
export const VALIDATE_RUNTIME = String.raw`
|
||||
@@ -40,6 +40,10 @@ export const VALIDATE_RUNTIME = String.raw`
|
||||
}
|
||||
|
||||
function checkField(desc, raw) {
|
||||
if (desc.type === "unknown") {
|
||||
var missing = raw === undefined || raw === null || raw === "";
|
||||
return (missing && !desc.optional) ? (desc.requiredMessage || "Required") : null;
|
||||
}
|
||||
if (desc.type === "boolean") {
|
||||
var b = raw === true || raw === "true" || raw === "on";
|
||||
return (!desc.optional && !b) ? (desc.requiredMessage || "Required") : null;
|
||||
@@ -70,9 +74,32 @@ export const VALIDATE_RUNTIME = String.raw`
|
||||
if (el && el.setAttribute) {
|
||||
if (err) { el.setAttribute("aria-invalid", "true"); if (el.classList) el.classList.add("wire-invalid"); }
|
||||
else { el.removeAttribute("aria-invalid"); if (el.classList) el.classList.remove("wire-invalid"); }
|
||||
var field = el.closest && el.closest(".wire-next--field, .wire-next--choice-field");
|
||||
if (field) field.setAttribute("data-invalid", err ? "true" : "false");
|
||||
}
|
||||
}
|
||||
|
||||
function showFormError(form, message) {
|
||||
var box = form.querySelector('[data-error="_form"]');
|
||||
if (!box) return;
|
||||
box.textContent = message || "";
|
||||
box.hidden = !message;
|
||||
if (box.classList) box.classList.toggle("hidden", !message);
|
||||
}
|
||||
|
||||
|
||||
function hideSuccess(form) {
|
||||
var box = form.querySelector("[data-success]");
|
||||
if (!box) return;
|
||||
box.hidden = true;
|
||||
if (box.classList) box.classList.add("hidden");
|
||||
}
|
||||
|
||||
function clearErrors(form, schema) {
|
||||
Object.keys(schema.fields).forEach(function (name) { showError(form, name, ""); });
|
||||
showFormError(form, "");
|
||||
}
|
||||
|
||||
function validateForm(form, schema) {
|
||||
var errors = 0;
|
||||
Object.keys(schema.fields).forEach(function (name) {
|
||||
@@ -95,18 +122,29 @@ export const VALIDATE_RUNTIME = String.raw`
|
||||
return out;
|
||||
}
|
||||
|
||||
function onSuccess(form, data) {
|
||||
var redirect = form.getAttribute("data-redirect") || (data && data.redirect);
|
||||
function onSuccess(form, data, responseRedirect) {
|
||||
showFormError(form, "");
|
||||
form.dispatchEvent(new CustomEvent("wire:success", { detail: data, bubbles: true }));
|
||||
var redirect = responseRedirect || form.getAttribute("data-redirect") || (data && data.redirect);
|
||||
if (redirect) {
|
||||
// Prefer client-side navigation (no full reload) when it is available.
|
||||
if (window.__wrnexusNavigate) window.__wrnexusNavigate(redirect);
|
||||
else location.assign(redirect);
|
||||
// Prefer client-side navigation for same-origin application redirects.
|
||||
try {
|
||||
var target = new URL(redirect, location.href);
|
||||
if (target.origin === location.origin && window.__wrnexusNavigate) {
|
||||
window.__wrnexusNavigate(target.pathname + target.search + target.hash);
|
||||
} else location.assign(target.href);
|
||||
} catch (e) {
|
||||
location.assign(redirect);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var box = form.querySelector("[data-success]");
|
||||
if (box) { box.textContent = box.getAttribute("data-success") || "Success"; box.hidden = false; }
|
||||
if (box) {
|
||||
box.textContent = box.getAttribute("data-success") || "Success";
|
||||
box.hidden = false;
|
||||
if (box.classList) box.classList.remove("hidden");
|
||||
}
|
||||
form.reset();
|
||||
form.dispatchEvent(new CustomEvent("wire:success", { detail: data, bubbles: true }));
|
||||
}
|
||||
|
||||
function csrfHeader() {
|
||||
@@ -118,6 +156,8 @@ export const VALIDATE_RUNTIME = String.raw`
|
||||
var method = (form.getAttribute("method") || "post").toUpperCase();
|
||||
var action = form.getAttribute("action") || location.pathname;
|
||||
var btns = form.querySelectorAll("[type=submit]");
|
||||
clearErrors(form, schema);
|
||||
hideSuccess(form);
|
||||
btns.forEach(function (b) { b.disabled = true; });
|
||||
var headers = { "content-type": "application/json", accept: "application/json" };
|
||||
var csrf = csrfHeader();
|
||||
@@ -129,50 +169,145 @@ export const VALIDATE_RUNTIME = String.raw`
|
||||
body: JSON.stringify(collect(form)),
|
||||
})
|
||||
.then(function (res) {
|
||||
return res.json().catch(function () { return {}; }).then(function (data) { return { res: res, data: data }; });
|
||||
var responseRedirect = res.redirected && res.url ? res.url : "";
|
||||
return res.json().catch(function () { return {}; }).then(function (data) {
|
||||
return { res: res, data: data, responseRedirect: responseRedirect };
|
||||
});
|
||||
})
|
||||
.then(function (r) {
|
||||
if (r.res.ok) { onSuccess(form, r.data); return; }
|
||||
// Surface server-side field errors (e.g. "email already taken").
|
||||
if (r.res.ok && (!r.data || r.data.ok !== false)) {
|
||||
onSuccess(form, r.data, r.responseRedirect);
|
||||
return;
|
||||
}
|
||||
// Surface server-side field errors and a form-level API message.
|
||||
var errors = r.data && r.data.errors;
|
||||
if (errors) Object.keys(errors).forEach(function (f) { showError(form, f, errors[f]); });
|
||||
var message = r.data && (r.data.message || r.data.error);
|
||||
showFormError(form, message || (errors ? "" : ("Request failed (" + r.res.status + ")")));
|
||||
form.dispatchEvent(new CustomEvent("wire:error", { detail: r.data, bubbles: true }));
|
||||
})
|
||||
.catch(function () {
|
||||
form.dispatchEvent(new CustomEvent("wire:error", { detail: { network: true }, bubbles: true }));
|
||||
.catch(function (error) {
|
||||
var detail = { network: true, message: error && error.message ? error.message : "Network request failed" };
|
||||
showFormError(form, detail.message);
|
||||
form.dispatchEvent(new CustomEvent("wire:error", { detail: detail, bubbles: true }));
|
||||
})
|
||||
.then(function () { btns.forEach(function (b) { b.disabled = false; }); });
|
||||
}
|
||||
|
||||
function bind(form) {
|
||||
if (form.__wireValidateBound) return;
|
||||
form.__wireValidateBound = 1;
|
||||
var name = form.getAttribute("data-schema");
|
||||
var schema = (window.__wireSchemas || {})[name];
|
||||
if (!schema) return;
|
||||
|
||||
// Package runtimes may register schemas later in the same page load.
|
||||
// Do not report an error during the first scan.
|
||||
if (!schema) {
|
||||
form.__wireValidatePending = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
form.__wireValidatePending = 0;
|
||||
form.__wireValidateMissingWarned = 0;
|
||||
form.__wireValidateBound = 1;
|
||||
form.__wireValidateMissingWarned = 0;
|
||||
// Schema-backed forms use WRNexus messages instead of the browser's
|
||||
// non-themeable native validation bubbles.
|
||||
form.noValidate = true;
|
||||
form.setAttribute("novalidate", "");
|
||||
form.addEventListener("submit", function (e) {
|
||||
e.preventDefault();
|
||||
clearErrors(form, schema);
|
||||
hideSuccess(form);
|
||||
if (validateForm(form, schema) > 0) return; // client-invalid: stay put, errors shown
|
||||
submitForm(form, schema);
|
||||
});
|
||||
form.addEventListener("blur", function (e) {
|
||||
function validateTarget(e) {
|
||||
var t = e.target;
|
||||
if (t && t.name && schema.fields[t.name]) {
|
||||
showError(form, t.name, checkField(schema.fields[t.name], t.type === "checkbox" ? t.checked : t.value));
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
form.addEventListener("input", validateTarget, true);
|
||||
form.addEventListener("change", validateTarget, true);
|
||||
form.addEventListener("blur", validateTarget, true);
|
||||
}
|
||||
|
||||
function registerSchemas(descriptors, root) {
|
||||
window.__wireSchemas =
|
||||
window.__wireSchemas || {};
|
||||
|
||||
Object.keys(descriptors || {}).forEach(
|
||||
function (name) {
|
||||
window.__wireSchemas[name] =
|
||||
descriptors[name];
|
||||
}
|
||||
);
|
||||
|
||||
init(root || document);
|
||||
}
|
||||
|
||||
function init(root) {
|
||||
(root || document).querySelectorAll("form[data-schema]").forEach(bind);
|
||||
}
|
||||
|
||||
window.__wireValidate = { init: init };
|
||||
window.__wireValidate = {
|
||||
init: init,
|
||||
registerSchemas: registerSchemas
|
||||
};
|
||||
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", function () { init(document); });
|
||||
else init(document);
|
||||
|
||||
document.addEventListener(
|
||||
"submit",
|
||||
function (event) {
|
||||
var form = event.target;
|
||||
|
||||
if (
|
||||
!form ||
|
||||
!form.matches ||
|
||||
!form.matches("form[data-schema]")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (form.__wireValidateBound) {
|
||||
return;
|
||||
}
|
||||
|
||||
var name =
|
||||
form.getAttribute("data-schema");
|
||||
|
||||
var schema =
|
||||
(window.__wireSchemas || {})[name];
|
||||
|
||||
if (schema) {
|
||||
bind(form);
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
showFormError(
|
||||
form,
|
||||
"Validation could not be loaded. Please refresh and try again."
|
||||
);
|
||||
|
||||
if (
|
||||
!form.__wireValidateMissingWarned &&
|
||||
window.console &&
|
||||
console.error
|
||||
) {
|
||||
form.__wireValidateMissingWarned = 1;
|
||||
|
||||
console.error(
|
||||
"[wrnexus:validation] Schema '" +
|
||||
name +
|
||||
"' is unavailable:",
|
||||
form
|
||||
);
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
})();
|
||||
`.trim();
|
||||
|
||||
Reference in New Issue
Block a user