Compare commits

..
3 Commits
Author SHA1 Message Date
deepDiverPaul ed8ae3200b refresh theme-one starter blocks and layout
Redesign the master layout and content blocks with responsive styling, accessible navigation, and configurable CTA and quote sections. Add about-me, embedded-code, and FAQ blocks, and update the generated theme assets. Replace Alpine-based locale handling with vanilla JavaScript for locale flags and gallery lightboxes, and remove Alpine and DaisyUI dependencies.
2026-11-25 17:50:12 +01:00
deepDiverPaul 102fbc9464 improve form submission handling and frontend assets
Replace Alpine form bindings with accessible vanilla JavaScript submission states and unique field IDs. Add the bundled frontend script and Rolldown build configuration, update the generated stylesheet, and extend submission handler tests.
2026-11-25 15:56:26 +01:00
deepDiverPaul a07e3ad8d9 fix localized page management and builder synchronization
Validate locales and route uniqueness, report page deletion failures, and keep translation CRUD and route caches consistent. Show translation completeness in page settings and listings, and preserve locale-specific block data while synchronizing shared structure. Add translation service and page builder synchronization tests.
2026-11-25 14:53:35 +01:00
75 changed files with 2880 additions and 2555 deletions
+133 -35
View File
@@ -9,6 +9,7 @@
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
"Courier New", monospace; "Courier New", monospace;
--spacing: 0.25rem; --spacing: 0.25rem;
--container-md: 28rem;
--container-2xl: 42rem; --container-2xl: 42rem;
--text-xs: 0.75rem; --text-xs: 0.75rem;
--text-xs--line-height: calc(1 / 0.75); --text-xs--line-height: calc(1 / 0.75);
@@ -24,12 +25,14 @@
--text-3xl--line-height: calc(2.25 / 1.875); --text-3xl--line-height: calc(2.25 / 1.875);
--text-4xl: 2.25rem; --text-4xl: 2.25rem;
--text-4xl--line-height: calc(2.5 / 2.25); --text-4xl--line-height: calc(2.5 / 2.25);
--text-6xl: 3.75rem;
--text-6xl--line-height: 1;
--font-weight-medium: 500; --font-weight-medium: 500;
--font-weight-semibold: 600;
--font-weight-bold: 700; --font-weight-bold: 700;
--tracking-tight: -0.025em;
--tracking-wide: 0.025em; --tracking-wide: 0.025em;
--radius-lg: 0.5rem; --leading-relaxed: 1.625;
--radius-xl: 0.75rem;
--radius-2xl: 1rem;
--default-transition-duration: 150ms; --default-transition-duration: 150ms;
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
--default-font-family: var(--font-sans); --default-font-family: var(--font-sans);
@@ -223,8 +226,8 @@
.mb-2 { .mb-2 {
margin-bottom: calc(var(--spacing) * 2); margin-bottom: calc(var(--spacing) * 2);
} }
.mb-4 { .mb-3 {
margin-bottom: calc(var(--spacing) * 4); margin-bottom: calc(var(--spacing) * 3);
} }
.mb-5 { .mb-5 {
margin-bottom: calc(var(--spacing) * 5); margin-bottom: calc(var(--spacing) * 5);
@@ -235,15 +238,36 @@
.ml-1 { .ml-1 {
margin-left: var(--spacing); margin-left: var(--spacing);
} }
.line-clamp-3 {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
}
.flex { .flex {
display: flex; display: flex;
} }
.grid {
display: grid;
}
.hidden { .hidden {
display: none; display: none;
} }
.table { .table {
display: table; display: table;
} }
.size-10 {
width: calc(var(--spacing) * 10);
height: calc(var(--spacing) * 10);
}
.size-11 {
width: calc(var(--spacing) * 11);
height: calc(var(--spacing) * 11);
}
.size-14 {
width: calc(var(--spacing) * 14);
height: calc(var(--spacing) * 14);
}
.h-16 { .h-16 {
height: calc(var(--spacing) * 16); height: calc(var(--spacing) * 16);
} }
@@ -268,15 +292,30 @@
.max-w-2xl { .max-w-2xl {
max-width: var(--container-2xl); max-width: var(--container-2xl);
} }
.max-w-72 {
max-width: calc(var(--spacing) * 72);
}
.max-w-md {
max-width: var(--container-md);
}
.min-w-40 { .min-w-40 {
min-width: calc(var(--spacing) * 40); min-width: calc(var(--spacing) * 40);
} }
.min-w-\[36rem\] {
min-width: 36rem;
}
.min-w-\[48rem\] {
min-width: 48rem;
}
.min-w-full { .min-w-full {
min-width: 100%; min-width: 100%;
} }
.flex-1 { .flex-1 {
flex: 1; flex: 1;
} }
.shrink-0 {
flex-shrink: 0;
}
.cursor-grab { .cursor-grab {
cursor: grab; cursor: grab;
} }
@@ -292,6 +331,9 @@
.flex-wrap { .flex-wrap {
flex-wrap: wrap; flex-wrap: wrap;
} }
.place-items-center {
place-items: center;
}
.items-center { .items-center {
align-items: center; align-items: center;
} }
@@ -319,6 +361,9 @@
.gap-4 { .gap-4 {
gap: calc(var(--spacing) * 4); gap: calc(var(--spacing) * 4);
} }
.gap-5 {
gap: calc(var(--spacing) * 5);
}
:where(.space-y-1 > :not(:last-child)) { :where(.space-y-1 > :not(:last-child)) {
--tw-space-y-reverse: 0; --tw-space-y-reverse: 0;
margin-block-start: calc(var(--spacing) * var(--tw-space-y-reverse)); margin-block-start: calc(var(--spacing) * var(--tw-space-y-reverse));
@@ -329,11 +374,6 @@
margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse)); margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse))); margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)));
} }
:where(.space-y-3 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)));
}
:where(.space-y-4 > :not(:last-child)) { :where(.space-y-4 > :not(:last-child)) {
--tw-space-y-reverse: 0; --tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse)); margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));
@@ -344,17 +384,25 @@
margin-block-start: calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse)); margin-block-start: calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse))); margin-block-end: calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)));
} }
:where(.space-y-6 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)));
}
.self-start {
align-self: flex-start;
}
.overflow-x-auto { .overflow-x-auto {
overflow-x: auto; overflow-x: auto;
} }
.rounded { .rounded-2xl {
border-radius: 0.25rem; border-radius: var(--radius-2xl);
} }
.rounded-full { .rounded-full {
border-radius: calc(infinity * 1px); border-radius: calc(infinity * 1px);
} }
.rounded-lg { .rounded-xl {
border-radius: var(--radius-lg); border-radius: var(--radius-xl);
} }
.border { .border {
border-style: var(--tw-border-style); border-style: var(--tw-border-style);
@@ -364,6 +412,10 @@
border-style: var(--tw-border-style); border-style: var(--tw-border-style);
border-width: 2px; border-width: 2px;
} }
.border-t {
border-top-style: var(--tw-border-style);
border-top-width: 1px;
}
.border-b { .border-b {
border-bottom-style: var(--tw-border-style); border-bottom-style: var(--tw-border-style);
border-bottom-width: 1px; border-bottom-width: 1px;
@@ -376,15 +428,12 @@
--tw-border-style: dashed; --tw-border-style: dashed;
border-style: dashed; border-style: dashed;
} }
.p-0 {
padding: 0px;
}
.p-2 {
padding: calc(var(--spacing) * 2);
}
.p-3 { .p-3 {
padding: calc(var(--spacing) * 3); padding: calc(var(--spacing) * 3);
} }
.p-4 {
padding: calc(var(--spacing) * 4);
}
.px-0 { .px-0 {
padding-inline: 0px; padding-inline: 0px;
} }
@@ -394,26 +443,32 @@
.px-4 { .px-4 {
padding-inline: calc(var(--spacing) * 4); padding-inline: calc(var(--spacing) * 4);
} }
.px-5 {
padding-inline: calc(var(--spacing) * 5);
}
.py-2 { .py-2 {
padding-block: calc(var(--spacing) * 2); padding-block: calc(var(--spacing) * 2);
} }
.py-8 { .py-8 {
padding-block: calc(var(--spacing) * 8); padding-block: calc(var(--spacing) * 8);
} }
.py-16 { .py-10 {
padding-block: calc(var(--spacing) * 16); padding-block: calc(var(--spacing) * 10);
} }
.pt-2 { .py-12 {
padding-top: calc(var(--spacing) * 2); padding-block: calc(var(--spacing) * 12);
}
.pt-4 {
padding-top: calc(var(--spacing) * 4);
}
.pt-5 {
padding-top: calc(var(--spacing) * 5);
} }
.pb-4 { .pb-4 {
padding-bottom: calc(var(--spacing) * 4); padding-bottom: calc(var(--spacing) * 4);
} }
.pl-3 { .pb-5 {
padding-left: calc(var(--spacing) * 3); padding-bottom: calc(var(--spacing) * 5);
}
.pl-8 {
padding-left: calc(var(--spacing) * 8);
} }
.text-center { .text-center {
text-align: center; text-align: center;
@@ -436,10 +491,6 @@
font-size: var(--text-4xl); font-size: var(--text-4xl);
line-height: var(--tw-leading, var(--text-4xl--line-height)); line-height: var(--tw-leading, var(--text-4xl--line-height));
} }
.text-6xl {
font-size: var(--text-6xl);
line-height: var(--tw-leading, var(--text-6xl--line-height));
}
.text-lg { .text-lg {
font-size: var(--text-lg); font-size: var(--text-lg);
line-height: var(--tw-leading, var(--text-lg--line-height)); line-height: var(--tw-leading, var(--text-lg--line-height));
@@ -456,6 +507,10 @@
font-size: var(--text-xs); font-size: var(--text-xs);
line-height: var(--tw-leading, var(--text-xs--line-height)); line-height: var(--tw-leading, var(--text-xs--line-height));
} }
.leading-relaxed {
--tw-leading: var(--leading-relaxed);
line-height: var(--leading-relaxed);
}
.font-bold { .font-bold {
--tw-font-weight: var(--font-weight-bold); --tw-font-weight: var(--font-weight-bold);
font-weight: var(--font-weight-bold); font-weight: var(--font-weight-bold);
@@ -464,10 +519,25 @@
--tw-font-weight: var(--font-weight-medium); --tw-font-weight: var(--font-weight-medium);
font-weight: var(--font-weight-medium); font-weight: var(--font-weight-medium);
} }
.font-semibold {
--tw-font-weight: var(--font-weight-semibold);
font-weight: var(--font-weight-semibold);
}
.tracking-\[0\.18em\] {
--tw-tracking: 0.18em;
letter-spacing: 0.18em;
}
.tracking-tight {
--tw-tracking: var(--tracking-tight);
letter-spacing: var(--tracking-tight);
}
.tracking-wide { .tracking-wide {
--tw-tracking: var(--tracking-wide); --tw-tracking: var(--tracking-wide);
letter-spacing: var(--tracking-wide); letter-spacing: var(--tracking-wide);
} }
.break-words {
overflow-wrap: break-word;
}
.uppercase { .uppercase {
text-transform: uppercase; text-transform: uppercase;
} }
@@ -496,14 +566,37 @@
.sm\:items-center { .sm\:items-center {
align-items: center; align-items: center;
} }
.sm\:items-end {
align-items: flex-end;
}
.sm\:justify-between { .sm\:justify-between {
justify-content: space-between; justify-content: space-between;
} }
.sm\:justify-end { .sm\:justify-end {
justify-content: flex-end; justify-content: flex-end;
} }
.sm\:pl-4 { .sm\:self-center {
padding-left: calc(var(--spacing) * 4); align-self: center;
}
.sm\:p-4 {
padding: calc(var(--spacing) * 4);
}
.sm\:p-5 {
padding: calc(var(--spacing) * 5);
}
.sm\:p-6 {
padding: calc(var(--spacing) * 6);
}
.sm\:py-16 {
padding-block: calc(var(--spacing) * 16);
}
.sm\:pl-9 {
padding-left: calc(var(--spacing) * 9);
}
}
@media (width >= 64rem) {
.lg\:p-8 {
padding: calc(var(--spacing) * 8);
} }
} }
} }
@@ -668,6 +761,10 @@
inherits: false; inherits: false;
initial-value: solid; initial-value: solid;
} }
@property --tw-leading {
syntax: "*";
inherits: false;
}
@property --tw-font-weight { @property --tw-font-weight {
syntax: "*"; syntax: "*";
inherits: false; inherits: false;
@@ -746,6 +843,7 @@
*, ::before, ::after, ::backdrop { *, ::before, ::after, ::backdrop {
--tw-space-y-reverse: 0; --tw-space-y-reverse: 0;
--tw-border-style: solid; --tw-border-style: solid;
--tw-leading: initial;
--tw-font-weight: initial; --tw-font-weight: initial;
--tw-tracking: initial; --tw-tracking: initial;
--tw-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000;
+1
View File
@@ -0,0 +1 @@
(()=>{let e=`Your submission could not be completed. Please try again.`;function t(e,t){e&&(e.hidden=!t,e.classList.toggle(`hidden`,!t))}function n(e){let t=Array.from(e.querySelectorAll(`input[type="checkbox"]`));t.length!==0&&(t[0].required=!t.some(e=>e.checked))}function r(e){let t={},n=Array.from(e.querySelectorAll(`input[name], select[name], textarea[name]`)).filter(e=>!e.matches(`:disabled`)),r=/* @__PURE__ */ new Map;return n.forEach(e=>{e instanceof HTMLInputElement&&[`button`,`submit`,`reset`,`image`].includes(e.type)||(r.has(e.name)||r.set(e.name,[]),r.get(e.name).push(e))}),r.forEach((e,n)=>{let r=e[0];if(r instanceof HTMLInputElement&&r.type===`checkbox`)t[n]=e.filter(e=>e.checked).map(e=>e.value);else if(r instanceof HTMLInputElement&&r.type===`radio`){let r=e.find(e=>e.checked);t[n]=r?r.value:``}else t[n]=r.value}),{fields:t}}function i(e,n){let r=e.querySelector(`[data-form-submit]`),i=e.querySelector(`[data-form-submit-idle]`),a=e.querySelector(`[data-form-submit-busy]`);e.setAttribute(`aria-busy`,String(n)),r&&(r.disabled=n,r.setAttribute(`aria-busy`,String(n))),t(i,!n),t(a,n)}function a(){document.querySelectorAll(`[data-field-type="checkbox"][data-field-required="true"]`).forEach(n)}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,a,{once:!0}):a(),document.addEventListener(`change`,e=>{if(!(e.target instanceof HTMLInputElement)||e.target.type!==`checkbox`)return;let t=e.target.closest(`[data-field-type="checkbox"][data-field-required="true"]`);t&&n(t)}),document.addEventListener(`submit`,async n=>{let a=n.target;if(!(a instanceof HTMLFormElement)||!a.matches(`[data-form-wrapper]`)||(n.preventDefault(),a.dataset.submitting===`true`))return;a.dataset.submitting=`true`;let o=a.parentElement,s=o.querySelector(`[data-form-error]`),c=o.querySelector(`[data-form-success]`);t(s,!1),s&&(s.textContent=``),i(a,!0);try{let n=await fetch(`/ext--form/submit?id=${encodeURIComponent(a.dataset.formId)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r(a))}),i=await n.json();if(!n.ok||!i||!i.success){let t=i&&Array.isArray(i.errors)?i.errors.join(` `):``;throw Error(t||e)}a.hidden=!0,a.classList.add(`hidden`),t(c,!0)}catch(n){s&&(s.textContent=n instanceof Error&&n.message?n.message:e,t(s,!0))}finally{i(a,!1),delete a.dataset.submitting}})})();
+145
View File
@@ -0,0 +1,145 @@
(() => {
const defaultErrorMessage = 'Your submission could not be completed. Please try again.';
function setVisible(element, visible) {
if (!element) {
return;
}
element.hidden = !visible;
element.classList.toggle('hidden', !visible);
}
function updateCheckboxGroupRequired(group) {
const checkboxes = Array.from(group.querySelectorAll('input[type="checkbox"]'));
if (checkboxes.length === 0) {
return;
}
checkboxes[0].required = !checkboxes.some(checkbox => checkbox.checked);
}
function collectFields(form) {
const fields = {};
const controls = Array.from(form.querySelectorAll('input[name], select[name], textarea[name]'))
.filter(control => !control.matches(':disabled'));
const groups = new Map();
controls.forEach(control => {
if (control instanceof HTMLInputElement && ['button', 'submit', 'reset', 'image'].includes(control.type)) {
return;
}
if (!groups.has(control.name)) {
groups.set(control.name, []);
}
groups.get(control.name).push(control);
});
groups.forEach((groupControls, name) => {
const firstControl = groupControls[0];
if (firstControl instanceof HTMLInputElement && firstControl.type === 'checkbox') {
fields[name] = groupControls
.filter(control => control.checked)
.map(control => control.value);
return;
}
if (firstControl instanceof HTMLInputElement && firstControl.type === 'radio') {
const selectedControl = groupControls.find(control => control.checked);
fields[name] = selectedControl ? selectedControl.value : '';
return;
}
fields[name] = firstControl.value;
});
return { fields };
}
function setBusy(form, busy) {
const submitButton = form.querySelector('[data-form-submit]');
const idleContent = form.querySelector('[data-form-submit-idle]');
const busyContent = form.querySelector('[data-form-submit-busy]');
form.setAttribute('aria-busy', String(busy));
if (submitButton) {
submitButton.disabled = busy;
submitButton.setAttribute('aria-busy', String(busy));
}
setVisible(idleContent, !busy);
setVisible(busyContent, busy);
}
function initializeCheckboxGroups() {
document.querySelectorAll('[data-field-type="checkbox"][data-field-required="true"]')
.forEach(updateCheckboxGroupRequired);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeCheckboxGroups, { once: true });
} else {
initializeCheckboxGroups();
}
document.addEventListener('change', event => {
if (!(event.target instanceof HTMLInputElement) || event.target.type !== 'checkbox') {
return;
}
const group = event.target.closest('[data-field-type="checkbox"][data-field-required="true"]');
if (group) {
updateCheckboxGroupRequired(group);
}
});
document.addEventListener('submit', async event => {
const form = event.target;
if (!(form instanceof HTMLFormElement) || !form.matches('[data-form-wrapper]')) {
return;
}
event.preventDefault();
if (form.dataset.submitting === 'true') {
return;
}
form.dataset.submitting = 'true';
const formContainer = form.parentElement;
const errorMessage = formContainer.querySelector('[data-form-error]');
const successMessage = formContainer.querySelector('[data-form-success]');
setVisible(errorMessage, false);
if (errorMessage) {
errorMessage.textContent = '';
}
setBusy(form, true);
try {
const response = await fetch(`/ext--form/submit?id=${encodeURIComponent(form.dataset.formId)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(collectFields(form))
});
const result = await response.json();
if (!response.ok || !result || !result.success) {
const errors = result && Array.isArray(result.errors) ? result.errors.join(' ') : '';
throw new Error(errors || defaultErrorMessage);
}
form.hidden = true;
form.classList.add('hidden');
setVisible(successMessage, true);
} catch (error) {
if (errorMessage) {
errorMessage.textContent = error instanceof Error && error.message
? error.message
: defaultErrorMessage;
setVisible(errorMessage, true);
}
} finally {
setBusy(form, false);
delete form.dataset.submitting;
}
});
})();
@@ -5,35 +5,18 @@ if ($id > 0):
$form = $formRepository->findWithId($id); $form = $formRepository->findWithId($id);
$fields = json_decode($form["fields"], true); $fields = json_decode($form["fields"], true);
$formInstanceId = uniqid("form-$id-");
?> ?>
<div class="mx-auto w-full max-w-2xl"> <div class="mx-auto w-full max-w-2xl">
<div x-data="{data: {fields : {}}, status: 'idle', submitted: false, errorMessage: ''}" class="space-y-4"> <div class="space-y-4">
<form x-show="!submitted" x-transition:leave x-transition:leave-opacity-0 x-on:submit.prevent=" <form data-form-wrapper data-form-id="<?= phpb_e($id) ?>" aria-busy="false">
status = 'busy'; <?php foreach ($fields as $fieldIndex => $field):
errorMessage = '';
try {
const response = await fetch('/ext--form/submit?id=<?= $id ?>', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
const result = await response.json();
if (!response.ok || !result.success) {
throw new Error((result.errors || []).join(' ') || 'Your submission could not be completed. Please try again.');
}
submitted = true;
} catch (error) {
errorMessage = error.message || 'Your submission could not be completed. Please try again.';
} finally {
status = 'idle';
}
">
<?php foreach ($fields as $field):
$fieldName = $field["name"]; $fieldName = $field["name"];
$fieldLabel = $field["label"]; $fieldLabel = $field["label"];
$fieldType = $field["type"]; $fieldType = $field["type"];
$fieldId = $formInstanceId . "-field-" . (int) $fieldIndex;
$fieldRequired = $fieldRequired =
isset($field["required"]) && $field["required"]; isset($field["required"]) && $field["required"];
$fieldOptions = isset($field["options"]) $fieldOptions = isset($field["options"])
@@ -42,7 +25,7 @@ if ($id > 0):
?> ?>
<div class="form-control mb-5"> <div class="form-control mb-5">
<?php if ($fieldType === "checkbox" || $fieldType === "radio"): ?> <?php if ($fieldType === "checkbox" || $fieldType === "radio"): ?>
<fieldset class="space-y-2"> <fieldset class="space-y-2" data-field-type="<?= phpb_e($fieldType) ?>" data-field-required="<?= $fieldRequired ? "true" : "false" ?>">
<legend class="label mb-1 px-0"> <legend class="label mb-1 px-0">
<span class="label-text font-medium"> <span class="label-text font-medium">
<?= phpb_e($fieldLabel) ?> <?= phpb_e($fieldLabel) ?>
@@ -53,7 +36,7 @@ if ($id > 0):
</span> </span>
</legend> </legend>
<?php else: ?> <?php else: ?>
<label for="form-field-<?= phpb_e($fieldName) ?>" class="label mb-1 px-0"> <label for="<?= phpb_e($fieldId) ?>" class="label mb-1 px-0">
<span class="label-text font-medium"> <span class="label-text font-medium">
<?= phpb_e($fieldLabel) ?> <?= phpb_e($fieldLabel) ?>
<?php if ($fieldRequired): ?> <?php if ($fieldRequired): ?>
@@ -64,7 +47,7 @@ if ($id > 0):
</label> </label>
<?php endif; ?> <?php endif; ?>
<?php if ($fieldType === "select"): ?> <?php if ($fieldType === "select"): ?>
<select id="form-field-<?= phpb_e($fieldName) ?>" x-model="data.fields.<?= $fieldName ?>" class="select select-bordered w-full" <?= $fieldRequired <select id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" class="select select-bordered w-full" <?= $fieldRequired
? "required" ? "required"
: "" ?>> : "" ?>>
<option value="" disabled selected>Please select</option> <option value="" disabled selected>Please select</option>
@@ -76,11 +59,11 @@ if ($id > 0):
</select> </select>
<?php elseif ($fieldType === "checkbox"): ?> <?php elseif ($fieldType === "checkbox"): ?>
<div class="space-y-2"> <div class="space-y-2">
<?php foreach ($fieldOptions as $option): ?> <?php foreach ($fieldOptions as $optionIndex => $option): ?>
<label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2"> <label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2">
<input type="checkbox" value="<?= phpb_e($option[ <input type="checkbox" name="<?= phpb_e($fieldName) ?>" value="<?= phpb_e($option[
"value" "value"
]) ?>" x-model="data.fields.<?= $fieldName ?>" class="checkbox checkbox-sm checkbox-primary" /> ]) ?>" <?= $fieldRequired && $optionIndex === 0 ? "required" : "" ?> class="checkbox checkbox-sm checkbox-primary" />
<span class="label-text"><?= phpb_e($option[ <span class="label-text"><?= phpb_e($option[
"label" "label"
]) ?></span> ]) ?></span>
@@ -89,11 +72,11 @@ if ($id > 0):
</div> </div>
<?php elseif ($fieldType === "radio"): ?> <?php elseif ($fieldType === "radio"): ?>
<div class="space-y-2"> <div class="space-y-2">
<?php foreach ($fieldOptions as $option): ?> <?php foreach ($fieldOptions as $optionIndex => $option): ?>
<label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2"> <label class="label cursor-pointer justify-start gap-3 rounded-box border border-base-300 px-3 py-2">
<input type="radio" name="<?= phpb_e($fieldName) ?>" value="<?= phpb_e($option[ <input type="radio" id="<?= phpb_e($fieldId) ?>-<?= (int) $optionIndex ?>" name="<?= phpb_e($fieldName) ?>" value="<?= phpb_e($option[
"value" "value"
]) ?>" x-model="data.fields.<?= $fieldName ?>" class="radio radio-sm radio-primary" /> ]) ?>" <?= $fieldRequired && $optionIndex === 0 ? "required" : "" ?> class="radio radio-sm radio-primary" />
<span class="label-text"><?= phpb_e($option[ <span class="label-text"><?= phpb_e($option[
"label" "label"
]) ?></span> ]) ?></span>
@@ -101,11 +84,11 @@ if ($id > 0):
<?php endforeach; ?> <?php endforeach; ?>
</div> </div>
<?php elseif ($fieldType === "textarea"): ?> <?php elseif ($fieldType === "textarea"): ?>
<textarea id="form-field-<?= phpb_e($fieldName) ?>" x-model="data.fields.<?= $fieldName ?>" class="textarea textarea-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired <textarea id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" class="textarea textarea-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired
? "required" ? "required"
: "" ?> rows="4"></textarea> : "" ?> rows="4"></textarea>
<?php else: ?> <?php else: ?>
<input id="form-field-<?= phpb_e($fieldName) ?>" type="<?= phpb_e($fieldType) ?>" x-model="data.fields.<?= $fieldName ?>" class="input input-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired <input id="<?= phpb_e($fieldId) ?>" name="<?= phpb_e($fieldName) ?>" type="<?= phpb_e($fieldType) ?>" class="input input-bordered w-full" placeholder="<?= phpb_e($fieldLabel) ?>" <?= $fieldRequired
? "required" ? "required"
: "" ?>> : "" ?>>
<?php endif; ?> <?php endif; ?>
@@ -116,20 +99,20 @@ if ($id > 0):
<?php <?php
endforeach; ?> endforeach; ?>
<div class="mt-6"> <div class="mt-6">
<button type="submit" class="btn btn-primary w-full" :disabled="status === 'busy'" :aria-busy="status === 'busy'"> <button type="submit" class="btn btn-primary w-full" data-form-submit aria-busy="false">
<span x-show="status === 'idle'" aria-live="polite"> <span data-form-submit-idle aria-live="polite">
<i class="ph-duotone ph-paper-plane-tilt" aria-hidden="true"></i> <i class="ph-duotone ph-paper-plane-tilt" aria-hidden="true"></i>
Submit Submit
</span> </span>
<span x-show="status === 'busy'" role="status" aria-live="polite"> <span data-form-submit-busy class="hidden" hidden role="status" aria-live="polite">
<span class="loading loading-spinner loading-sm" aria-hidden="true"></span> <span class="loading loading-spinner loading-sm" aria-hidden="true"></span>
Sending... Sending...
</span> </span>
</button> </button>
</div> </div>
</form> </form>
<div x-show="errorMessage" x-text="errorMessage" class="alert alert-error mt-4 shadow-sm" role="alert" aria-live="assertive" aria-atomic="true"></div> <div data-form-error class="alert alert-error mt-4 shadow-sm hidden" hidden role="alert" aria-live="assertive" aria-atomic="true"></div>
<div x-show="submitted" x-transition:enter x-transition:enter-opacity-0 x-transition:enter-delay-100 class="card mt-4 border border-success/30 bg-base-100 shadow-sm" role="status" aria-live="polite"> <div data-form-success class="card mt-4 border border-success/30 bg-base-100 shadow-sm hidden" hidden role="status" aria-live="polite">
<div class="card-body items-center text-center"> <div class="card-body items-center text-center">
<div class="mb-2 flex h-16 w-16 items-center justify-center rounded-full bg-success/20"> <div class="mb-2 flex h-16 w-16 items-center justify-center rounded-full bg-success/20">
<i class="ph-duotone ph-check text-3xl text-success" aria-hidden="true"></i> <i class="ph-duotone ph-check text-3xl text-success" aria-hidden="true"></i>
+5
View File
@@ -20,6 +20,11 @@ return [
"type" => "style", "type" => "style",
"location" => "header", "location" => "header",
], ],
[
"src" => "/assets/dist.js",
"type" => "script",
"location" => "footer",
],
], ],
"tables" => [ "tables" => [
"entries" => [ "entries" => [
+405 -1
View File
@@ -1,5 +1,5 @@
{ {
"name": "dev_plugi-ext-form", "name": "plugi-ext-form",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
@@ -7,6 +7,43 @@
"dependencies": { "dependencies": {
"@tailwindcss/cli": "^4.3.5", "@tailwindcss/cli": "^4.3.5",
"tailwindcss": "^4.3.5" "tailwindcss": "^4.3.5"
},
"devDependencies": {
"rolldown": "^1.3.3"
}
},
"node_modules/@emnapi/core": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
"integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "2.2.0",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
"integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
} }
}, },
"node_modules/@jridgewell/gen-mapping": { "node_modules/@jridgewell/gen-mapping": {
@@ -54,6 +91,38 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
"integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
"@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
}
},
"node_modules/@oxc-project/types": {
"version": "0.159.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.159.0.tgz",
"integrity": "sha512-QWjWhxheluOJ82kDHNyps00UvRpQCtI34B5A/SzpgQycUD/79FuvT4I0aQIfE/bdPwKmX4QPftnywFBH6FxJhQ==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/oxc-project"
}
},
"node_modules/@parcel/watcher": { "node_modules/@parcel/watcher": {
"version": "2.6.0", "version": "2.6.0",
"resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz",
@@ -328,6 +397,287 @@
"url": "https://opencollective.com/parcel" "url": "https://opencollective.com/parcel"
} }
}, },
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.3.tgz",
"integrity": "sha512-K1itOg1Xl50XyjLDa4qQZqaYsfiQbFbFRWXOEOupOsGr3whhm5ed4lgySd6Inohv2TB0+sdU4AxORKuS/TGang==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.3.tgz",
"integrity": "sha512-re+E0E3YSJXjEFzdOvBgkVUev1Gg49ileia04qy+Djn0lIMBr7pnwVOYQ+4vc9XbLClCmMziasqXHM7KTmKNKQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.3.tgz",
"integrity": "sha512-6pMLYsUiQJXPkUj/CG447hOBKtbe+hjWw/wbxe/mucoPKgnLSVRTzey7s0kXfqrjxhDd3gQ2hj6lgUKRumsIzw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-darwin-x64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.3.tgz",
"integrity": "sha512-Lz+TskwvhceQgwnP+0ox5ZeL7HDDXHKWVRpOqC1Eo05y6rYyfvvep0msGqC95kQTykXrmGgP6qwJB1NdgNZVhg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.3.tgz",
"integrity": "sha512-sIzqNDbA7GFDXU8k9/vcJyV1p45mCe+xHOLo9qD7gdbTbMlwB+SpnFoP7WSpC2iYdGfOX9pjBxCfViRn/Nu3Jw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.3.tgz",
"integrity": "sha512-HYysnZZ7HD3FM5RIBN6wDMoxtOjw4LS9HhRuQ57MsZt5XGpGRPxVpplvr7vUXRN+9MD8zb6vn1JRP06PXIuMYQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.3.tgz",
"integrity": "sha512-XAyLqWSoEKVc8wsDbCIz5o2sBY6ye+0YByK9ib5QxFReoM1KHyThSHsdUODa1DKNzlEfae+p9QwK62LsVwo6Nw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.3.tgz",
"integrity": "sha512-oVyicDPj6vUVFRnuoQS7M2Ab8EkGWoq3a5ntyQqjtZoXfgVykIJqN2IAJSi9q9UyNoQUW0vbBLQSgGtlPJ40Kg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.3.tgz",
"integrity": "sha512-k7aFSWgUoi/X7jCst7UEof7pS5jc5ymD8mT/pdFE+pO1IBBI2+JU5Os4HEDqS/tYhetRggwM7MOiLP3cg1bSBQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.3.tgz",
"integrity": "sha512-D5mxHpr1qIb1Pt5UT+Bm2p6vJ7+VxcxWcxZCYVDFzZwWRq9iLiEg4/ROsaXFQl1O8sDQZZJ55UoRWWMK64uH5w==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.3.tgz",
"integrity": "sha512-nmW1O4BbNEmQI9+KTHbJgbDv0EuyZy64oBnRlMCtLJ8lQMIJ/H/iziQ0g2IUlHEhNrSebGvs9cRrlRj8oEfP+g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.3.tgz",
"integrity": "sha512-ivU4JFHK5nFzrRbzp3+vwYdLj8mFckH4oz3hEl5LH/YeThr9/m2N2vF3NvLevtHq6e0COimgrEVyYTwQhh4ODg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.3.tgz",
"integrity": "sha512-XxZoRIkNZ/7pFgvOA8QJmx3uFjMyVz7zS2/urzlaFffoOGclDvpUAMu3AHKT551E8JBKXLxIjpYxYMdF6Mz9vQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-wasm32-wasi": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.3.tgz",
"integrity": "sha512-bBl1MB2gF26PSPy3CiDLiv+A6JGI546WbsDR34LfKAywSGeBeQXaDanoDG6QdZDJs53M1QyJir5MTKTu1n4ptA==",
"cpu": [
"wasm32"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "2.0.0-beta.2",
"@emnapi/runtime": "2.0.0-beta.2",
"@napi-rs/wasm-runtime": "1.2.6"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.3.tgz",
"integrity": "sha512-6rZur0hyen4LPhOxWIg7az1YX+Eo8Vvauc0D6lFYGK/QCvN+1XpnB8aFe3jQc/PBUGIReJJnLX3sS8h33/5v7A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.3.tgz",
"integrity": "sha512-Ggzyuq1mN7claruAZH10aiiM1N3LRCoMP5xDXPdU514ulL0D2bksCWgFqEmEM2/pDzEP7Dq+dcv7IH452jtr1w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/pluginutils": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
"integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
"dev": true,
"license": "MIT"
},
"node_modules/@tailwindcss/cli": { "node_modules/@tailwindcss/cli": {
"version": "4.3.5", "version": "4.3.5",
"resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz", "resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz",
@@ -649,6 +999,17 @@
"node": ">= 20" "node": ">= 20"
} }
}, },
"node_modules/@tybys/wasm-util": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
"integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/detect-libc": { "node_modules/detect-libc": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -998,6 +1359,41 @@
"url": "https://github.com/sponsors/jonschlinkert" "url": "https://github.com/sponsors/jonschlinkert"
} }
}, },
"node_modules/rolldown": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.3.tgz",
"integrity": "sha512-ksB1g74e7haRy02OYm4lOQAlr6sK6hBpAY5R+YC30Gkv4L1COwF6M9umBAYAPxWpGow6Vr+IXtyDjH9fq7A+Zg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.159.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
"rolldown": "bin/cli.mjs"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@rolldown/binding-android-arm-eabi": "1.3.3",
"@rolldown/binding-android-arm64": "1.3.3",
"@rolldown/binding-darwin-arm64": "1.3.3",
"@rolldown/binding-darwin-x64": "1.3.3",
"@rolldown/binding-freebsd-x64": "1.3.3",
"@rolldown/binding-linux-arm-gnueabihf": "1.3.3",
"@rolldown/binding-linux-arm64-gnu": "1.3.3",
"@rolldown/binding-linux-arm64-musl": "1.3.3",
"@rolldown/binding-linux-ppc64-gnu": "1.3.3",
"@rolldown/binding-linux-s390x-gnu": "1.3.3",
"@rolldown/binding-linux-x64-gnu": "1.3.3",
"@rolldown/binding-linux-x64-musl": "1.3.3",
"@rolldown/binding-openharmony-arm64": "1.3.3",
"@rolldown/binding-wasm32-wasi": "1.3.3",
"@rolldown/binding-win32-arm64-msvc": "1.3.3",
"@rolldown/binding-win32-x64-msvc": "1.3.3"
}
},
"node_modules/source-map-js": { "node_modules/source-map-js": {
"version": "1.2.4", "version": "1.2.4",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz",
@@ -1025,6 +1421,14 @@
"type": "opencollective", "type": "opencollective",
"url": "https://opencollective.com/webpack" "url": "https://opencollective.com/webpack"
} }
},
"node_modules/tslib": {
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
"dev": true,
"license": "0BSD",
"optional": true
} }
} }
} }
+7 -1
View File
@@ -1,10 +1,16 @@
{ {
"type": "module",
"dependencies": { "dependencies": {
"@tailwindcss/cli": "^4.3.5", "@tailwindcss/cli": "^4.3.5",
"tailwindcss": "^4.3.5" "tailwindcss": "^4.3.5"
}, },
"devDependencies": {
"rolldown": "^1.3.3"
},
"scripts": { "scripts": {
"dev": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css --watch", "dev": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css --watch",
"build": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css" "build": "npm run build:js && npm run build:css",
"build:css": "npx -y @tailwindcss/cli -i ./assets/main.css -o ./assets/dist.css",
"build:js": "rolldown assets/main.js --file assets/dist.js -m"
} }
} }
@@ -256,12 +256,21 @@ namespace {
assertSameValue(422, $result['status'], 'Malformed action options must be rejected'); assertSameValue(422, $result['status'], 'Malformed action options must be rejected');
$view = file_get_contents(dirname(__DIR__) . '/blocks/form-wrapper/view.php'); $view = file_get_contents(dirname(__DIR__) . '/blocks/form-wrapper/view.php');
if (strpos($view, '!response.ok || !result.success') === false || strpos($view, 'x-show="errorMessage"') === false) { $frontendScript = file_get_contents(dirname(__DIR__) . '/assets/main.js');
if (strpos($view, 'data-form-wrapper') === false || preg_match('/\bx-(?:data|model|show|on|transition|text)\b/', $view) === 1) {
throw new \RuntimeException('The public form wrapper must use vanilla JavaScript hooks without Alpine directives.');
}
if (strpos($frontendScript, 'if (!response.ok || !result || !result.success)') === false || strpos($frontendScript, 'setVisible(errorMessage, true)') === false) {
throw new \RuntimeException('The frontend must check the response and expose a retryable error state.'); throw new \RuntimeException('The frontend must check the response and expose a retryable error state.');
} }
if (preg_match('/if \(!response\.ok \|\| !result\.success\).*?submitted = true;/s', $view) !== 1) { $responseCheck = strpos($frontendScript, 'if (!response.ok || !result || !result.success)');
$successState = strpos($frontendScript, 'setVisible(successMessage, true)');
if ($successState === false || $responseCheck === false || $responseCheck > $successState) {
throw new \RuntimeException('The frontend may only show its success state after a successful response.'); throw new \RuntimeException('The frontend may only show its success state after a successful response.');
} }
if (strpos($frontendScript, 'finally') === false || strpos($frontendScript, 'setBusy(form, false)') === false) {
throw new \RuntimeException('The frontend must restore its busy state after a submission attempt.');
}
$editor = file_get_contents(dirname(__DIR__) . '/admin/Views/EditForm.php'); $editor = file_get_contents(dirname(__DIR__) . '/admin/Views/EditForm.php');
foreach (['finisherDefinitions', 'getFinisherSettings', 'finisher.options[setting.name]', 'setting.type'] as $setting) { foreach (['finisherDefinitions', 'getFinisherSettings', 'finisher.options[setting.name]', 'setting.type'] as $setting) {
+1
View File
@@ -33,6 +33,7 @@ return [
'page-create-failed' => 'Die Seite konnte nicht erstellt werden. Prüfen Sie Pflichtfelder, übersetzte Werte, Routen und die Datenbankverbindung und versuchen Sie es erneut.', 'page-create-failed' => 'Die Seite konnte nicht erstellt werden. Prüfen Sie Pflichtfelder, übersetzte Werte, Routen und die Datenbankverbindung und versuchen Sie es erneut.',
'page-updated' => 'Seite aktualisiert', 'page-updated' => 'Seite aktualisiert',
'page-deleted' => 'Seite gelöscht', 'page-deleted' => 'Seite gelöscht',
'page-delete-failed' => 'Die Seite konnte nicht gelöscht werden. Versuchen Sie es erneut oder prüfen Sie die Datenbankverbindung.',
'page-type' => 'Seitentyp', 'page-type' => 'Seitentyp',
'page-types' => [ 'page-types' => [
'static' => 'Statische Seite', 'static' => 'Statische Seite',
+1
View File
@@ -33,6 +33,7 @@ return [
'page-create-failed' => 'Page could not be created. Check required fields, localized values, routes, and the database connection, then try again.', 'page-create-failed' => 'Page could not be created. Check required fields, localized values, routes, and the database connection, then try again.',
'page-updated' => 'Page successfully updated', 'page-updated' => 'Page successfully updated',
'page-deleted' => 'Page removed', 'page-deleted' => 'Page removed',
'page-delete-failed' => 'Page could not be deleted. Try again or check the database connection.',
'page-type' => 'Page type', 'page-type' => 'Page type',
'page-types' => [ 'page-types' => [
'static' => 'Static page', 'static' => 'Static page',
+1
View File
@@ -32,6 +32,7 @@ return [
'page-created' => 'Sidan har skapats', 'page-created' => 'Sidan har skapats',
'page-updated' => 'Sidan har uppdaterats', 'page-updated' => 'Sidan har uppdaterats',
'page-deleted' => 'Sidan har tagits bort', 'page-deleted' => 'Sidan har tagits bort',
'page-delete-failed' => 'Sidan kunde inte tas bort. Försök igen eller kontrollera databasanslutningen.',
'page-type' => 'Sidtyp', 'page-type' => 'Sidtyp',
'page-types' => [ 'page-types' => [
'static' => 'Statisk sida', 'static' => 'Statisk sida',
@@ -4,4 +4,20 @@ namespace Plugi\Contracts;
interface PageTranslationRepositoryContract interface PageTranslationRepositoryContract
{ {
/**
* Determine whether a route is already used by another page translation.
*
* @param string $route
* @param mixed|null $excludedPageId
* @return bool
*/
public function routeExists(string $route, $excludedPageId = null): bool;
/**
* Return translations belonging to the given page IDs.
*
* @param array $pageIds
* @return array
*/
public function getForPages(array $pageIds): array;
} }
@@ -8,6 +8,7 @@ use Plugi\Contracts\ThemeContract;
use Plugi\Modules\GrapesJS\Block\BlockAdapter; use Plugi\Modules\GrapesJS\Block\BlockAdapter;
use Plugi\Modules\GrapesJS\Thumb\ThumbGenerator; use Plugi\Modules\GrapesJS\Thumb\ThumbGenerator;
use Plugi\Modules\GrapesJS\Upload\Uploader; use Plugi\Modules\GrapesJS\Upload\Uploader;
use Plugi\PageTranslationService;
use Plugi\Repositories\PageRepository; use Plugi\Repositories\PageRepository;
use Plugi\Repositories\UploadRepository; use Plugi\Repositories\UploadRepository;
use Exception; use Exception;
@@ -101,14 +102,22 @@ class PageBuilder implements PageBuilderContract
} }
break; break;
case 'renderBlock': case 'renderBlock':
if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) { $language = $this->getValidPostedLanguage();
$this->renderPageBuilderBlock($page, $_POST['language'], json_decode($_POST['data'], true)); if ($language === null) {
$this->respondToInvalidLanguageRequest();
}
if (isset($_POST['data'])) {
$this->renderPageBuilderBlock($page, $language, json_decode($_POST['data'], true));
exit(); exit();
} }
break; break;
case 'renderLanguageVariant': case 'renderLanguageVariant':
if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) { $language = $this->getValidPostedLanguage();
$this->renderLanguageVariant($page, $_POST['language'], json_decode($_POST['data'], true)); if ($language === null) {
$this->respondToInvalidLanguageRequest();
}
if (isset($_POST['data'])) {
$this->renderLanguageVariant($page, $language, json_decode($_POST['data'], true));
exit(); exit();
} }
break; break;
@@ -204,8 +213,13 @@ class PageBuilder implements PageBuilderContract
// init variables that should be accessible in the view // init variables that should be accessible in the view
$pageBuilder = $this; $pageBuilder = $this;
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]); $pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]);
if (! empty($_SESSION['plugi_language'])) { $activeLanguages = array_keys(phpb_active_languages());
$pageRenderer->setLanguage($_SESSION['plugi_language']); $currentLanguage = (new PageTranslationService())->resolveLocale($_SESSION['plugi_language'] ?? null, $activeLanguages);
if ($currentLanguage !== null) {
$_SESSION['plugi_language'] = $currentLanguage;
$pageRenderer->setLanguage($currentLanguage);
} else {
unset($_SESSION['plugi_language']);
} }
// create an array of theme blocks and theme block settings for in the page builder sidebar // create an array of theme blocks and theme block settings for in the page builder sidebar
@@ -279,6 +293,9 @@ class PageBuilder implements PageBuilderContract
public function renderLanguageVariant(PageContract $page, string $language, $blockData = []) public function renderLanguageVariant(PageContract $page, string $language, $blockData = [])
{ {
phpb_set_in_editmode(); phpb_set_in_editmode();
if (! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
$this->respondToInvalidLanguageRequest();
}
$_SESSION['plugi_language'] = $language; $_SESSION['plugi_language'] = $language;
$blockData = is_array($blockData) ? $blockData : []; $blockData = is_array($blockData) ? $blockData : [];
@@ -291,6 +308,32 @@ class PageBuilder implements PageBuilderContract
]); ]);
} }
/**
* Return the requested language only when it is an active locale.
*
* @return string|null
*/
protected function getValidPostedLanguage(): ?string
{
$language = $_POST['language'] ?? null;
if (! is_string($language) || ! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
return null;
}
return $language;
}
/**
* Return a clear client error for an unsupported language request.
*/
protected function respondToInvalidLanguageRequest(): void
{
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['message' => 'Unsupported language.']);
exit();
}
/** /**
* Update the given page with the given data (an array of html blocks). * Update the given page with the given data (an array of html blocks).
* *
@@ -5,6 +5,7 @@ namespace Plugi\Modules\GrapesJS;
use Plugi\Contracts\PageContract; use Plugi\Contracts\PageContract;
use Plugi\Contracts\ThemeContract; use Plugi\Contracts\ThemeContract;
use Plugi\Modules\GrapesJS\Block\BlockRenderer; use Plugi\Modules\GrapesJS\Block\BlockRenderer;
use Plugi\PageTranslationService;
use Plugi\ThemeBlock; use Plugi\ThemeBlock;
use Exception; use Exception;
use Plugi\Extensions; use Plugi\Extensions;
@@ -93,9 +94,7 @@ class PageRenderer
} }
} }
if ($blockKeysAreLanguages) { if ($blockKeysAreLanguages) {
if (! in_array($language, $supportedLanguages)) { $language = (new PageTranslationService())->resolveLocale($language, $supportedLanguages) ?? $language;
$language = $supportedLanguages[0] ?? $language;
}
} }
$this->language = $language; $this->language = $language;
@@ -78,8 +78,12 @@
if (!select) return; if (!select) return;
let selectedLanguage = select.value; let selectedLanguage = select.value;
window.switchLanguage(selectedLanguage, function() { window.switchLanguage(selectedLanguage, function(success) {
if (success) {
activateLanguage(selectedLanguage); activateLanguage(selectedLanguage);
} else {
select.value = window.currentLanguage;
}
}); });
}); });
@@ -74,7 +74,7 @@
errorMessage = errData.message ? (errorMessage + ': "' + errData.message + '"') : errorMessage; errorMessage = errData.message ? (errorMessage + ': "' + errData.message + '"') : errorMessage;
window.toastr.error(errorMessage); window.toastr.error(errorMessage);
window.toastr.error(window.translations['toastr-switching-language-failed']); window.toastr.error(window.translations['toastr-switching-language-failed']);
callback(); callback(false);
window.setWaiting(false); window.setWaiting(false);
return; return;
} }
@@ -82,10 +82,10 @@
const responseText = await response.text(); const responseText = await response.text();
let parsed = JSON.parse(responseText); let parsed = JSON.parse(responseText);
window.pageBlocks[newLanguage] = parsed.dynamicBlocks ? parsed.dynamicBlocks : {}; window.pageBlocks[newLanguage] = parsed.dynamicBlocks ? parsed.dynamicBlocks : {};
callback(); callback(true);
window.setWaiting(false); window.setWaiting(false);
} catch (error) { } catch (error) {
callback(); callback(false);
console.error(error); console.error(error);
window.toastr.error(error.message || 'Error'); window.toastr.error(error.message || 'Error');
window.toastr.error(window.translations['toastr-switching-language-failed']); window.toastr.error(window.translations['toastr-switching-language-failed']);
@@ -95,81 +95,70 @@
}; };
/** /**
* Copy new blocks of the current language to the new language or remove old blocks from the new language. * Copy new shared blocks of the current language to the new language.
* *
* @param newLanguage * @param newLanguage
*/ */
function applyChangesFromCurrentLanguageToNewLanguage(newLanguage) { function applyChangesFromCurrentLanguageToNewLanguage(newLanguage) {
let newLanguageBlocks = window.pageBlocks[newLanguage]; const currentLanguageBlocks = window.pageBlocks[window.currentLanguage] || {};
let currentLanguageBlocks = window.pageBlocks[window.currentLanguage]; window.pageBlocks[newLanguage] = window.synchronizePageBlockVariants(
currentLanguageBlocks,
if (newLanguageBlocks === undefined) { window.pageBlocks[newLanguage] || {}
newLanguageBlocks = currentLanguageBlocks; );
} else {
updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks);
// copy missing blocks from the current language to the target language
for (let blockId in currentLanguageBlocks) {
if (newLanguageBlocks[blockId] === undefined) {
newLanguageBlocks[blockId] = currentLanguageBlocks[blockId];
}
}
}
// copy the content of blocks containers of the current language to the blocks containers of the new language
for (let blockId in currentLanguageBlocks) {
let currentBlockHtml = (currentLanguageBlocks[blockId] && currentLanguageBlocks[blockId]['html']) || '';
let newBlockHtml = (newLanguageBlocks[blockId] && newLanguageBlocks[blockId]['html']) || '';
let currDiv = document.createElement("div");
currDiv.innerHTML = currentBlockHtml;
let newDiv = document.createElement("div");
newDiv.innerHTML = newBlockHtml;
let currContainers = currDiv.querySelectorAll("[phpb-blocks-container]");
let newContainers = newDiv.querySelectorAll("[phpb-blocks-container]");
currContainers.forEach((cont, index) => {
if (newContainers[index]) {
newContainers[index].innerHTML = cont.innerHTML;
}
});
newLanguageBlocks[blockId]['html'] = newDiv.innerHTML;
}
window.pageBlocks[newLanguage] = newLanguageBlocks;
} }
/** /**
* Replace phpb-blocks-container html snippets if a block of the current language already exists in the target language. * Synchronize shared block structure without replacing existing locale-specific block data.
* This ensures all child blocks are present for all languages and they remain in the same order
*/ */
function updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks) { window.synchronizePageBlockVariants = function(sourceBlocks, targetBlocks) {
for (let blockId in currentLanguageBlocks) { sourceBlocks = sourceBlocks && typeof sourceBlocks === 'object' ? sourceBlocks : {};
// skip if the parent block does not yet exist in the target language targetBlocks = targetBlocks && typeof targetBlocks === 'object' && !Array.isArray(targetBlocks) ? targetBlocks : {};
if (newLanguageBlocks[blockId] === undefined) {
continue; Object.keys(sourceBlocks).forEach(blockId => {
const sourceBlock = sourceBlocks[blockId];
const targetBlock = targetBlocks[blockId];
if (! targetBlock || typeof targetBlock !== 'object') {
targetBlocks[blockId] = JSON.parse(JSON.stringify(sourceBlock));
return;
} }
for (let subBlockId in currentLanguageBlocks[blockId].blocks) { if (typeof sourceBlock?.html === 'string' && typeof targetBlock.html === 'string') {
let updatedSubBlock = currentLanguageBlocks[blockId].blocks[subBlockId]; targetBlock.html = synchronizeBlockContainers(sourceBlock.html, targetBlock.html);
let oldSubBlock = newLanguageBlocks[blockId].blocks[subBlockId];
if (! updatedSubBlock || ! oldSubBlock) {
continue;
} }
let updatedSubBlockMatches = updatedSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g); if (sourceBlock?.blocks && typeof sourceBlock.blocks === 'object') {
let oldSubBlockMatches = oldSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g); targetBlock.blocks = window.synchronizePageBlockVariants(sourceBlock.blocks, targetBlock.blocks || {});
if (! updatedSubBlockMatches || ! oldSubBlockMatches) { }
continue; });
return targetBlocks;
};
/**
* Copy only shared child structure from the source language into existing block containers.
*/
function synchronizeBlockContainers(sourceHtml, targetHtml) {
if (! sourceHtml.includes('phpb-blocks-container')) {
return targetHtml;
} }
for (let i = 0; i < updatedSubBlockMatches.length; i++) { const sourceElement = document.createElement('div');
newLanguageBlocks[blockId].blocks[subBlockId].html = sourceElement.innerHTML = sourceHtml;
newLanguageBlocks[blockId].blocks[subBlockId].html.replace(oldSubBlockMatches[i], updatedSubBlockMatches[i]); const targetElement = document.createElement('div');
} targetElement.innerHTML = targetHtml;
} const sourceContainers = sourceElement.querySelectorAll('[phpb-blocks-container]');
const targetContainers = targetElement.querySelectorAll('[phpb-blocks-container]');
sourceContainers.forEach((sourceContainer, index) => {
if (targetContainers[index]) {
targetContainers[index].innerHTML = sourceContainer.innerHTML;
} else {
targetElement.appendChild(sourceContainer.cloneNode(true));
} }
});
return targetElement.innerHTML;
} }
/** /**
@@ -18,13 +18,6 @@
<script type="text/javascript" src="<?= phpb_asset('pagebuilder/grapesjs-touch-v0.1.1.min.js') ?>"></script> <script type="text/javascript" src="<?= phpb_asset('pagebuilder/grapesjs-touch-v0.1.1.min.js') ?>"></script>
<script type="text/javascript"> <script type="text/javascript">
<?php
$currentLanguage = in_array(phpb_config('general.language'), phpb_active_languages()) ?
phpb_config('general.language') : array_keys(phpb_active_languages())[0];
if (! empty($_SESSION['plugi_language'])) {
$currentLanguage = $_SESSION['plugi_language'];
}
?>
window.languages = <?= json_encode(phpb_active_languages()) ?>; window.languages = <?= json_encode(phpb_active_languages()) ?>;
window.currentLanguage = <?= json_encode($currentLanguage) ?>; window.currentLanguage = <?= json_encode($currentLanguage) ?>;
window.translations = <?= json_encode(phpb_trans('pagebuilder')) ?>; window.translations = <?= json_encode(phpb_trans('pagebuilder')) ?>;
@@ -5,9 +5,9 @@ namespace Plugi\Modules\WebsiteManager;
use Plugi\Contracts\PageContract; use Plugi\Contracts\PageContract;
use Plugi\Contracts\WebsiteManagerContract; use Plugi\Contracts\WebsiteManagerContract;
use Plugi\Extensions; use Plugi\Extensions;
use Plugi\PageTranslationService;
use Plugi\Repositories\MenuRepository; use Plugi\Repositories\MenuRepository;
use Plugi\Repositories\PageRepository; use Plugi\Repositories\PageRepository;
use Plugi\Repositories\PageTranslationRepository;
use Plugi\Repositories\SettingRepository; use Plugi\Repositories\SettingRepository;
use Plugi\Repositories\UploadRepository; use Plugi\Repositories\UploadRepository;
@@ -127,7 +127,12 @@ class WebsiteManager implements WebsiteManagerContract
public function handleDestroy(PageContract $page) public function handleDestroy(PageContract $page)
{ {
$pageRepository = new PageRepository; $pageRepository = new PageRepository;
$pageRepository->destroy($page->getId()); if (! $pageRepository->destroy($page->getId())) {
phpb_redirect(phpb_url('website_manager'), [
'message-type' => 'error',
'message' => phpb_trans('website-manager.page-delete-failed')
]);
}
phpb_redirect(phpb_url('website_manager'), [ phpb_redirect(phpb_url('website_manager'), [
'message-type' => 'success', 'message-type' => 'success',
'message' => phpb_trans('website-manager.page-deleted') 'message' => phpb_trans('website-manager.page-deleted')
@@ -194,8 +199,8 @@ class WebsiteManager implements WebsiteManagerContract
return ($a->getRoute() < $b->getRoute()) ? -1 : 1; return ($a->getRoute() < $b->getRoute()) ? -1 : 1;
}); });
$pageTranslationRepository = new PageTranslationRepository; $activeLanguages = phpb_active_languages();
$pageTranslations = $pageTranslationRepository->getAll(); $pageTranslationCoverage = (new PageTranslationService())->getPageCoverage($pages, $activeLanguages);
$filesRepository = new UploadRepository; $filesRepository = new UploadRepository;
$files = $filesRepository->getAll(); $files = $filesRepository->getAll();
@@ -104,7 +104,7 @@ $javascriptValue = static function (string $value): string {
<div class="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between"> <div class="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
<div> <div>
<h2 class="text-lg font-semibold text-base-content">Localized page details</h2> <h2 class="text-lg font-semibold text-base-content">Localized page details</h2>
<p class="text-sm text-base-content/60">Titles, routes, and metadata can vary by language.</p> <p class="text-sm text-base-content/60">Each language shows its own saved values; missing translations are left blank instead of using fallback text.</p>
</div> </div>
<span class="badge badge-outline"><?= count($activeLanguages) ?> languages</span> <span class="badge badge-outline"><?= count($activeLanguages) ?> languages</span>
</div> </div>
@@ -112,13 +112,41 @@ $javascriptValue = static function (string $value): string {
<?php <?php
$firstLang = true; $firstLang = true;
foreach ($activeLanguages as $languageCode => $languageTranslation): foreach ($activeLanguages as $languageCode => $languageTranslation):
$savedTranslation = $pageTranslations[$languageCode] ?? null;
$hasSavedTranslation = is_array($savedTranslation);
$translationType = $fieldValue('type') !== '' ? $fieldValue('type') : ($page?->get('type') ?? 'static');
$hasRequiredTranslationValues = $hasSavedTranslation
&& trim((string) ($savedTranslation['route'] ?? '')) !== ''
&& ($translationType === 'redirect'
? trim((string) ($savedTranslation['target'] ?? '')) !== ''
: trim((string) ($savedTranslation['title'] ?? '')) !== '');
$localeStatus = $action === 'create'
? 'New translation'
: (! $hasSavedTranslation ? 'Missing' : ($hasRequiredTranslationValues ? 'Complete' : 'Needs attention'));
$localeStatusClass = $action === 'create'
? 'badge-outline'
: (! $hasSavedTranslation ? 'badge-error' : ($hasRequiredTranslationValues ? 'badge-success' : 'badge-warning'));
?> ?>
<details class="collapse collapse-arrow border border-base-300 bg-base-100" <?= phpb_e($firstLang ? 'open' : '') ?>> <details class="collapse collapse-arrow border border-base-300 bg-base-100" <?= phpb_e($firstLang ? 'open' : '') ?>>
<summary class="collapse-title flex min-h-14 items-center text-base font-semibold sm:text-lg"> <summary class="collapse-title flex min-h-14 flex-wrap items-center gap-2 text-base font-semibold sm:text-lg">
<span><?= phpb_trans('languages.' . $languageCode) ?></span> <span><?= phpb_trans('languages.' . $languageCode) ?></span>
<span class="badge badge-ghost ml-3"><?= phpb_e($languageCode) ?></span> <span class="badge badge-ghost ml-3"><?= phpb_e($languageCode) ?></span>
<span class="badge badge-sm <?= $localeStatusClass ?>"><?= $localeStatus ?></span>
</summary> </summary>
<div class="collapse-content space-y-5"> <div class="collapse-content space-y-5">
<?php if ($action === 'create' || ! $hasSavedTranslation || ! $hasRequiredTranslationValues): ?>
<div class="alert <?= $hasSavedTranslation ? 'alert-warning' : 'alert-info' ?>" role="status">
<span>
<?php if ($action === 'create'): ?>
Enter the actual values for this language; other locales will not be used to fill these fields.
<?php elseif (! $hasSavedTranslation): ?>
No saved translation exists for this language. Enter its actual values; fields are not filled from another locale.
<?php else: ?>
This saved translation is missing a required title, route, or redirect target. Complete these fields before saving.
<?php endif; ?>
</span>
</div>
<?php endif; ?>
<div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0"> <div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0">
<div class="form-control w-full"> <div class="form-control w-full">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title"> <label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
@@ -148,7 +176,7 @@ $javascriptValue = static function (string $value): string {
<label class="label" for="<?= phpb_e($languageCode) ?>-page-target-redirect"> <label class="label" for="<?= phpb_e($languageCode) ?>-page-target-redirect">
<span class="label-text"><?= phpb_trans('website-manager.target-redirect') ?></span> <span class="label-text"><?= phpb_trans('website-manager.target-redirect') ?></span>
</label> </label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('target', $languageCode)) ?>" /> <input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('target', $languageCode)) ?>" :required="type==='redirect'" />
</div> </div>
<div class="form-control w-full"> <div class="form-control w-full">
@@ -10,19 +10,20 @@
</a> </a>
</header> </header>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100"> <div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[48rem]"> <table class="table table-zebra w-full min-w-[64rem]">
<thead> <thead>
<tr> <tr>
<th class="w-16">ID</th> <th class="w-16">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th> <th><?= phpb_trans('website-manager.name') ?></th>
<th><?= phpb_trans('website-manager.route') ?></th> <th>Localized titles and routes</th>
<th>Coverage</th>
<th class="w-44"><?= phpb_trans('website-manager.actions') ?></th> <th class="w-44"><?= phpb_trans('website-manager.actions') ?></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php if (empty($pages)): ?> <?php if (empty($pages)): ?>
<tr> <tr>
<td colspan="4" class="py-12 text-center"> <td colspan="5" class="py-12 text-center">
<span class="mx-auto mb-3 grid size-11 place-items-center rounded-2xl bg-info/10 text-info"> <span class="mx-auto mb-3 grid size-11 place-items-center rounded-2xl bg-info/10 text-info">
<i class="text-2xl ph-duotone ph-files" aria-hidden="true"></i> <i class="text-2xl ph-duotone ph-files" aria-hidden="true"></i>
</span> </span>
@@ -32,18 +33,60 @@
</tr> </tr>
<?php endif; ?> <?php endif; ?>
<?php foreach ($pages as $page): ?> <?php foreach ($pages as $page): ?>
<?php
$pageRoute = $page->getRoute();
$canViewPage = $page->get('type') !== 'redirect' && is_string($pageRoute) && $pageRoute !== '';
?>
<tr> <tr>
<td><?= phpb_e($page->getId()) ?></td> <td><?= phpb_e($page->getId()) ?></td>
<td class="font-medium"><?= phpb_e($page->getName()) ?></td> <td class="font-medium"><?= phpb_e($page->getName()) ?></td>
<td> <td>
<div class="hidden pl-4 pl-8"></div> <div class="grid gap-2 sm:grid-cols-2">
<div class="pl-<?= phpb_e((count(explode('/', $page->getRoute()))-2)*4) ?>"> <?php foreach ($activeLanguages as $languageCode => $languageTranslation): ?>
<?= phpb_e($page->getRoute()) ?> <?php
$localeCoverage = $pageTranslationCoverage[$page->getId()]['locales'][$languageCode] ?? null;
$localeExists = $localeCoverage['exists'] ?? false;
$localeComplete = $localeCoverage['complete'] ?? false;
$localeStatus = $localeComplete ? 'Complete' : ($localeExists ? 'Needs attention' : 'Missing');
$localeBadgeClass = $localeComplete ? 'badge-success' : ($localeExists ? 'badge-warning' : 'badge-error');
$localeTitle = $localeCoverage['title'] ?? null;
$localeRoute = $localeCoverage['route'] ?? null;
$localeTitleLabel = is_string($localeTitle) && trim($localeTitle) !== ''
? phpb_e($localeTitle)
: ($page->get('type') === 'redirect' ? 'Redirect page' : 'Title not set');
?>
<div class="min-w-0 rounded-box border border-base-300 p-3">
<div class="mb-1 flex flex-wrap items-center justify-between gap-2">
<span class="text-xs font-semibold text-base-content/70">
<?= phpb_trans('languages.' . $languageCode) ?>
<span class="font-mono">(<?= phpb_e($languageCode) ?>)</span>
</span>
<span class="badge badge-sm <?= $localeBadgeClass ?>"><?= $localeStatus ?></span>
</div>
<p class="truncate text-sm font-medium" title="<?= phpb_e($localeTitle) ?>">
<?= $localeTitleLabel ?>
</p>
<p class="break-all font-mono text-xs text-base-content/60" title="<?= phpb_e($localeRoute) ?>">
<?= is_string($localeRoute) && trim($localeRoute) !== '' ? phpb_e($localeRoute) : 'Route not set' ?>
</p>
</div>
<?php endforeach; ?>
</div> </div>
</td> </td>
<td>
<?php
$pageCoverage = $pageTranslationCoverage[$page->getId()] ?? ['completeCount' => 0, 'localeCount' => count($activeLanguages)];
$coverageClass = $pageCoverage['localeCount'] > 0 && $pageCoverage['completeCount'] === $pageCoverage['localeCount']
? 'badge-success'
: ($pageCoverage['completeCount'] > 0 ? 'badge-warning' : 'badge-error');
?>
<span class="badge <?= $coverageClass ?>">
<?= phpb_e($pageCoverage['completeCount']) ?> / <?= phpb_e($pageCoverage['localeCount']) ?> complete
</span>
</td>
<td> <td>
<div class="flex items-center gap-1"> <div class="flex items-center gap-1">
<a href="<?= phpb_e(phpb_full_url($page->getRoute())) ?>" title="<?= phpb_trans('website-manager.view') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.view')) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-square btn-sm <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" <?= $page->get('type') === 'redirect' ? 'tabindex="-1" aria-disabled="true"' : '' ?>> <a href="<?= phpb_e($canViewPage ? phpb_full_url($pageRoute) : '#') ?>" title="<?= phpb_trans('website-manager.view') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.view')) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-square btn-sm <?= $canViewPage ? '' : 'btn-disabled' ?>" <?= $canViewPage ? '' : 'tabindex="-1" aria-disabled="true"' ?>>
<i class="text-xl ph-duotone ph-eye" aria-hidden="true"></i> <i class="text-xl ph-duotone ph-eye" aria-hidden="true"></i>
</a> </a>
<a href="<?= phpb_url('pagebuilder', ['page' => $page->getId()]) ?>" class="btn btn-primary btn-square btn-sm <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.edit')) ?>" <?= $page->get('type') === 'redirect' ? 'tabindex="-1" aria-disabled="true"' : '' ?>> <a href="<?= phpb_url('pagebuilder', ['page' => $page->getId()]) ?>" class="btn btn-primary btn-square btn-sm <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.edit')) ?>" <?= $page->get('type') === 'redirect' ? 'tabindex="-1" aria-disabled="true"' : '' ?>>
+5 -13
View File
@@ -129,14 +129,7 @@ class Page implements PageContract
public function getTranslation(string $setting, ?string $locale = null) public function getTranslation(string $setting, ?string $locale = null)
{ {
$translations = $this->getTranslations(); $translations = $this->getTranslations();
if (empty($translations)) { return (new PageTranslationService())->resolveTranslation($translations, $setting, $locale);
return null;
}
$locale = $locale ?? phpb_config('general.language');
return $translations[$locale][$setting] ??
$translations['en'][$setting] ??
$translations[array_keys($translations)[0]][$setting] ??
null;
} }
/** /**
@@ -178,11 +171,10 @@ class Page implements PageContract
*/ */
public function invalidateCache() public function invalidateCache()
{ {
$cache = phpb_instance('cache'); $routes = array_map(function ($translation) {
return $translation['route'] ?? null;
}, $this->getTranslations());
foreach ($this->getTranslations() as $locale => $translationData) { (new PageTranslationService())->invalidateRoutes($routes);
$languageRoute = $this->getRoute($locale);
$cache->invalidate($languageRoute);
}
} }
} }
+206
View File
@@ -0,0 +1,206 @@
<?php
namespace Plugi;
use Plugi\Repositories\PageTranslationRepository;
class PageTranslationService
{
/**
* Return the requested locale, configured default, or first available locale, in that order.
*
* @param string|null $locale
* @param array $availableLocales
* @return string[]
*/
public function getLocaleFallbackOrder(?string $locale, array $availableLocales): array
{
$availableLocales = $this->getAvailableLocales($availableLocales);
$fallbackLocales = [];
foreach ([$locale, phpb_config('general.language')] as $preferredLocale) {
if (is_string($preferredLocale) && in_array($preferredLocale, $availableLocales, true)) {
$fallbackLocales[] = $preferredLocale;
}
}
foreach ($availableLocales as $availableLocale) {
$fallbackLocales[] = $availableLocale;
}
return array_values(array_unique($fallbackLocales));
}
/**
* Resolve a locale using the shared fallback order.
*
* @param string|null $locale
* @param array $availableLocales
* @return string|null
*/
public function resolveLocale(?string $locale, array $availableLocales): ?string
{
return $this->getLocaleFallbackOrder($locale, $availableLocales)[0] ?? null;
}
/**
* Determine whether a locale is active without applying fallback.
*
* @param string|null $locale
* @param array $availableLocales
* @return bool
*/
public function isAvailableLocale(?string $locale, array $availableLocales): bool
{
return $locale !== null && in_array($locale, $this->getAvailableLocales($availableLocales), true);
}
/**
* Return the setting from the first translation containing a non-null value.
*
* @param array $translations
* @param string $setting
* @param string|null $locale
* @return mixed|null
*/
public function resolveTranslation(array $translations, string $setting, ?string $locale = null)
{
foreach ($this->getLocaleFallbackOrder($locale, array_keys($translations)) as $fallbackLocale) {
if (array_key_exists($setting, $translations[$fallbackLocale]) && $translations[$fallbackLocale][$setting] !== null) {
return $translations[$fallbackLocale][$setting];
}
}
return null;
}
/**
* Return every stored route for a page, including inactive locales.
*
* @param mixed $pageId
* @return string[]
*/
public function getPageRoutes($pageId): array
{
$translations = (new PageTranslationRepository())->getForPages([$pageId]);
$routes = [];
foreach ($translations as $translation) {
$route = $translation->route ?? null;
if (is_string($route) && $route !== '') {
$routes[] = $route;
}
}
$routes = array_values(array_unique($routes));
sort($routes, SORT_STRING);
return $routes;
}
/**
* Invalidate routes after their corresponding persistence operation succeeds.
*
* @param array $routes
*/
public function invalidateRoutes(array $routes): void
{
$routes = array_values(array_unique(array_filter($routes, function ($route) {
return is_string($route) && $route !== '';
})));
sort($routes, SORT_STRING);
if (empty($routes)) {
return;
}
$cache = phpb_instance('cache');
if (! $cache) {
return;
}
foreach ($routes as $route) {
$cache->invalidate($route);
}
}
/**
* Return actual saved translation coverage for the given pages and active locales.
*
* @param array $pages
* @param array $activeLanguages
* @return array
*/
public function getPageCoverage(array $pages, array $activeLanguages): array
{
$coverage = [];
$pageTypes = [];
$pageIds = [];
foreach ($pages as $page) {
$pageId = (string) $page->getId();
$pageIds[] = $page->getId();
$pageTypes[$pageId] = $page->get('type');
$coverage[$pageId] = [
'completeCount' => 0,
'localeCount' => count($activeLanguages),
'locales' => [],
];
foreach ($activeLanguages as $locale => $language) {
$coverage[$pageId]['locales'][$locale] = [
'exists' => false,
'complete' => false,
'title' => null,
'route' => null,
];
}
}
if (empty($pageIds)) {
return $coverage;
}
$foreignKey = phpb_config('page.translation.foreign_key');
$translations = (new PageTranslationRepository())->getForPages($pageIds);
foreach ($translations as $translation) {
$pageId = (string) ($translation->$foreignKey ?? '');
$locale = $translation->locale ?? null;
if (! isset($coverage[$pageId]) || ! is_string($locale) || ! array_key_exists($locale, $activeLanguages)) {
continue;
}
$title = $translation->title ?? null;
$route = $translation->route ?? null;
$target = $translation->target ?? null;
$hasRequiredValue = $pageTypes[$pageId] === 'redirect'
? trim((string) $target) !== ''
: trim((string) $title) !== '';
$isComplete = trim((string) $route) !== '' && $hasRequiredValue;
$coverage[$pageId]['locales'][$locale] = [
'exists' => true,
'complete' => $isComplete,
'title' => $title,
'route' => $route,
];
if ($isComplete) {
$coverage[$pageId]['completeCount']++;
}
}
return $coverage;
}
/**
* Normalize a list or locale-keyed language map to locale codes.
*
* @param array $availableLocales
* @return string[]
*/
private function getAvailableLocales(array $availableLocales): array
{
if ($availableLocales === [] || array_keys($availableLocales) !== range(0, count($availableLocales) - 1)) {
$availableLocales = array_keys($availableLocales);
}
return array_values(array_filter($availableLocales, function ($availableLocale) {
return is_string($availableLocale) && $availableLocale !== '';
}));
}
}
+25 -9
View File
@@ -5,6 +5,7 @@ namespace Plugi\Repositories;
use Plugi\Contracts\PageContract; use Plugi\Contracts\PageContract;
use Plugi\Contracts\PageRepositoryContract; use Plugi\Contracts\PageRepositoryContract;
use Plugi\Contracts\PageTranslationContract; use Plugi\Contracts\PageTranslationContract;
use Plugi\PageTranslationService;
class PageRepository extends BaseRepository implements PageRepositoryContract class PageRepository extends BaseRepository implements PageRepositoryContract
{ {
@@ -90,7 +91,10 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
return false; return false;
} }
$updateResult = $this->db->transaction(function () use ($page, $data) { $translationService = new PageTranslationService();
$oldRoutes = [];
$updateResult = $this->db->transaction(function () use ($page, $data, $translationService, &$oldRoutes) {
$oldRoutes = $translationService->getPageRoutes($page->getId());
if (! $this->replaceTranslations($page, $data)) { if (! $this->replaceTranslations($page, $data)) {
return false; return false;
} }
@@ -102,7 +106,7 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
]); ]);
}); });
if ($updateResult) { if ($updateResult) {
$page->invalidateCache(); $translationService->invalidateRoutes(array_merge($oldRoutes, array_values($data['route'])));
} }
return $updateResult; return $updateResult;
} }
@@ -185,13 +189,9 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
$routes[$route] = true; $routes[$route] = true;
} }
$foreignKey = phpb_config('page.translation.foreign_key');
$pageTranslationRepository = new PageTranslationRepository; $pageTranslationRepository = new PageTranslationRepository;
foreach ($pageTranslationRepository->getAll(['route', $foreignKey]) as $translation) { foreach (array_keys($routes) as $route) {
if ($pageId !== null && (string) $translation->$foreignKey === (string) $pageId) { if ($pageTranslationRepository->routeExists($route, $pageId)) {
continue;
}
if (array_key_exists($translation->route, $routes)) {
return true; return true;
} }
} }
@@ -211,7 +211,9 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
$updateResult = parent::update($page, [ $updateResult = parent::update($page, [
'data' => json_encode($data), 'data' => json_encode($data),
]); ]);
if ($updateResult) {
$page->invalidateCache(); $page->invalidateCache();
}
return $updateResult; return $updateResult;
} }
@@ -223,8 +225,22 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
*/ */
public function destroy($id) public function destroy($id)
{ {
$this->findWithId($id)->invalidateCache(); $translationService = new PageTranslationService();
$routes = [];
$destroyResult = $this->db->transaction(function () use ($id, $translationService, &$routes) {
$routes = $translationService->getPageRoutes($id);
$pageTranslationRepository = new PageTranslationRepository();
if (! $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $id)) {
return false;
}
return parent::destroy($id); return parent::destroy($id);
});
if ($destroyResult) {
$translationService->invalidateRoutes($routes);
}
return $destroyResult;
} }
} }
@@ -29,4 +29,47 @@ class PageTranslationRepository extends BaseRepository implements PageTranslatio
parent::__construct(); parent::__construct();
$this->class = phpb_instance('page.translation'); $this->class = phpb_instance('page.translation');
} }
/**
* Determine whether a route is already used by another page translation.
*
* @param string $route
* @param mixed|null $excludedPageId
* @return bool
*/
public function routeExists(string $route, $excludedPageId = null): bool
{
$query = "SELECT 1 FROM {$this->table} WHERE route = ?";
$parameters = [$route];
if ($excludedPageId !== null) {
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
$query .= " AND {$foreignKey} != ?";
$parameters[] = $excludedPageId;
}
$query .= ' LIMIT 1';
return ! empty($this->db->select($query, $parameters));
}
/**
* Return translations belonging to the given page IDs.
*
* @param array $pageIds
* @return array
*/
public function getForPages(array $pageIds): array
{
if (empty($pageIds)) {
return [];
}
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
$placeholders = implode(', ', array_fill(0, count($pageIds), '?'));
$records = $this->db->select(
"SELECT * FROM {$this->table} WHERE {$foreignKey} IN ({$placeholders})",
array_values($pageIds)
);
return $this->createInstances($records);
}
} }
@@ -0,0 +1,110 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const sourcePath = new URL('../src/Modules/GrapesJS/resources/assets/js/save-page.js', import.meta.url);
const source = fs.readFileSync(sourcePath, 'utf8');
class TestElement {
constructor() {
this._innerHTML = '';
}
set innerHTML(value) {
this._innerHTML = value;
}
get innerHTML() {
return this._innerHTML;
}
querySelectorAll() {
const pattern = /<div([^>]*\bphpb-blocks-container\b[^>]*)>([\s\S]*?)<\/div>/g;
return [...this._innerHTML.matchAll(pattern)].map((match, index) => {
return new TestContainer(this, index, `<div${match[1]}>`, match[2]);
});
}
replaceContainer(index, containerHtml) {
const pattern = /<div([^>]*\bphpb-blocks-container\b[^>]*)>([\s\S]*?)<\/div>/g;
let currentIndex = 0;
this._innerHTML = this._innerHTML.replace(pattern, match => {
return currentIndex++ === index ? containerHtml : match;
});
}
appendChild(container) {
this._innerHTML += container.outerHTML;
}
}
class TestContainer {
constructor(parent, index, openingTag, innerHTML) {
this.parent = parent;
this.index = index;
this.openingTag = openingTag;
this._innerHTML = innerHTML;
}
set innerHTML(value) {
this._innerHTML = value;
this.parent.replaceContainer(this.index, `${this.openingTag}${value}</div>`);
}
get innerHTML() {
return this._innerHTML;
}
get outerHTML() {
return `${this.openingTag}${this._innerHTML}</div>`;
}
cloneNode() {
return new TestContainer(null, 0, this.openingTag, this._innerHTML);
}
}
const window = {};
const document = {
getElementById: () => null,
addEventListener: () => {},
createElement: () => new TestElement(),
};
vm.runInNewContext(source, { window, document, console, setTimeout, URLSearchParams });
const sourceBlocks = {
parent: {
html: '<p>Source locale text</p><div phpb-blocks-container>[block slug="child" id="new-child"]</div>',
settings: {label: 'Source setting'},
blocks: {
existingChild: {html: '<p>Source child text</p>', settings: {label: 'Source child setting'}},
newChild: {html: '<p>New shared block</p>', settings: {label: 'New setting'}},
},
},
newParent: {html: '<p>New shared parent</p>', settings: {label: 'New parent setting'}},
};
const targetBlocks = {
parent: {
html: '<p>Translated parent text</p><div phpb-blocks-container>[block slug="child" id="existing-child"]</div>',
settings: {label: 'Translated parent setting'},
blocks: {
existingChild: {html: '<p>Existing translated child</p>', settings: {label: 'Translated child setting'}},
},
},
localeOnlyParent: {html: '<p>Existing locale-only content</p>'},
};
const synchronizedBlocks = window.synchronizePageBlockVariants(sourceBlocks, targetBlocks);
assert.match(synchronizedBlocks.parent.html, /Translated parent text/);
assert.match(synchronizedBlocks.parent.html, /id="new-child"/);
assert.equal(synchronizedBlocks.parent.settings.label, 'Translated parent setting');
assert.equal(synchronizedBlocks.parent.blocks.existingChild.html, '<p>Existing translated child</p>');
assert.equal(synchronizedBlocks.parent.blocks.existingChild.settings.label, 'Translated child setting');
assert.equal(synchronizedBlocks.parent.blocks.newChild.html, '<p>New shared block</p>');
assert.equal(synchronizedBlocks.newParent.html, '<p>New shared parent</p>');
assert.equal(synchronizedBlocks.localeOnlyParent.html, '<p>Existing locale-only content</p>');
sourceBlocks.parent.blocks.newChild.html = '<p>Source changed after synchronization</p>';
assert.equal(synchronizedBlocks.parent.blocks.newChild.html, '<p>New shared block</p>');
console.log('PASS: shared block structure synchronizes without overwriting existing locale content.');
@@ -21,6 +21,7 @@ require_once __DIR__ . '/../src/Contracts/ThemeContract.php';
require_once __DIR__ . '/../src/Core/DB.php'; require_once __DIR__ . '/../src/Core/DB.php';
require_once __DIR__ . '/../src/Repositories/BaseRepository.php'; require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php'; require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php';
require_once __DIR__ . '/../src/PageTranslationService.php';
require_once __DIR__ . '/../src/Page.php'; require_once __DIR__ . '/../src/Page.php';
require_once __DIR__ . '/../src/PageTranslation.php'; require_once __DIR__ . '/../src/PageTranslation.php';
require_once __DIR__ . '/../src/Repositories/PageRepository.php'; require_once __DIR__ . '/../src/Repositories/PageRepository.php';
@@ -31,8 +32,13 @@ require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.php';
class PageCreationTestDatabase extends DB class PageCreationTestDatabase extends DB
{ {
public int $translationInsertCount = 0; public int $translationInsertCount = 0;
public int $pageTranslationAllCallCount = 0;
public int $pageTranslationBatchSelectCount = 0;
public ?int $failOnTranslationInsert = null; public ?int $failOnTranslationInsert = null;
public bool $throwOnTranslationFailure = false; public bool $throwOnTranslationFailure = false;
public ?string $failOnDeleteTable = null;
public bool $throwOnDeleteFailure = false;
public bool $failOnPageUpdate = false;
public function __construct() public function __construct()
{ {
@@ -43,6 +49,16 @@ class PageCreationTestDatabase extends DB
public function query(string $query, array $parameters = []) public function query(string $query, array $parameters = [])
{ {
if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) {
if ($this->throwOnDeleteFailure) {
throw new PDOException('Simulated page deletion failure.');
}
return false;
}
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
return false;
}
if (str_starts_with($query, 'INSERT INTO page_translations')) { if (str_starts_with($query, 'INSERT INTO page_translations')) {
$this->translationInsertCount++; $this->translationInsertCount++;
if ($this->translationInsertCount === $this->failOnTranslationInsert) { if ($this->translationInsertCount === $this->failOnTranslationInsert) {
@@ -56,6 +72,24 @@ class PageCreationTestDatabase extends DB
return parent::query($query, $parameters); return parent::query($query, $parameters);
} }
public function all(string $table, array|string $columns = '*'): array
{
if ($table === 'page_translations') {
$this->pageTranslationAllCallCount++;
}
return parent::all($table, $columns);
}
public function select(string $query, array $parameters): array
{
if (str_starts_with($query, 'SELECT * FROM page_translations WHERE page_id IN (')) {
$this->pageTranslationBatchSelectCount++;
}
return parent::select($query, $parameters);
}
public function createSchema(): void public function createSchema(): void
{ {
$this->pdo->exec('CREATE TABLE pages ( $this->pdo->exec('CREATE TABLE pages (
@@ -102,8 +136,11 @@ class PageCreationTestWebsiteManager extends WebsiteManager
class PageCreationTestCache class PageCreationTestCache
{ {
public static array $invalidatedRoutes = [];
public function invalidate(string $route): void public function invalidate(string $route): void
{ {
self::$invalidatedRoutes[] = $route;
} }
} }
@@ -165,6 +202,11 @@ function phpb_url(string $module, array $parameters = []): string
return '/' . $module; return '/' . $module;
} }
function phpb_full_url(string $route): string
{
return 'https://example.test' . $route;
}
function phpb_csrf_field(): void function phpb_csrf_field(): void
{ {
} }
@@ -175,6 +217,9 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
$_ENV['DATABASE_PREFIX'] = ''; $_ENV['DATABASE_PREFIX'] = '';
$pageCreationConfig = [ $pageCreationConfig = [
'general' => [
'language' => 'en',
],
'page' => [ 'page' => [
'table' => 'pages', 'table' => 'pages',
'translation' => [ 'translation' => [
@@ -184,6 +229,7 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
], ],
]; ];
$pageCreationLanguages = $languages; $pageCreationLanguages = $languages;
PageCreationTestCache::$invalidatedRoutes = [];
$phpb_db = new PageCreationTestDatabase(); $phpb_db = new PageCreationTestDatabase();
$phpb_db->createSchema(); $phpb_db->createSchema();
} }
@@ -222,6 +268,21 @@ function runPageCreationCase(string $name, callable $case): bool
} }
$cases = [ $cases = [
'configured locale is preferred over the first available translation' => function (): void {
resetPageCreationDatabase(['de' => [], 'fr' => []]);
global $pageCreationConfig;
$pageCreationConfig['general']['language'] = 'fr';
$page = new Page();
$page->setTranslations([
'de' => ['title' => 'Deutscher Titel'],
'fr' => ['title' => 'Titre français'],
]);
assertPageCreation(
$page->getTranslation('title', 'it') === 'Titre français',
'Missing requested locale should fall back to the configured default, not the first saved locale.'
);
},
'locked generated routes do not leave a base page without translations' => function (): void { 'locked generated routes do not leave a base page without translations' => function (): void {
resetPageCreationDatabase(); resetPageCreationDatabase();
$payload = pageCreationPayload(); $payload = pageCreationPayload();
@@ -321,6 +382,54 @@ $cases = [
assertPageCreation(str_contains($malformedHtml, '\\u0027\\u003C/script\\u003E'), 'Submitted route was not safely encoded for Alpine.'); assertPageCreation(str_contains($malformedHtml, '\\u0027\\u003C/script\\u003E'), 'Submitted route was not safely encoded for Alpine.');
$_POST = []; $_POST = [];
}, },
'page settings leave missing locale values blank and explain the missing translation' => function (): void {
resetPageCreationDatabase();
$page = new Page();
$page->setData([
'id' => 42,
'name' => 'English page',
'layout' => 'default',
'type' => 'static',
]);
$page->setTranslations([
'en' => [
'title' => 'English title',
'route' => '/english-page',
'meta_title' => '',
'meta_description' => '',
'target' => '',
],
]);
$_POST = [];
$action = 'edit';
$errorMessage = null;
$theme = new class {
public function getThemeLayouts(): array
{
return [new class {
public function getSlug(): string
{
return 'default';
}
public function getTitle(): string
{
return 'Default';
}
}];
}
};
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/page-settings.php';
$html = ob_get_clean();
preg_match('/name="title\[de\]" value="([^"]*)"/', $html, $germanTitle);
assertPageCreation(($germanTitle[1] ?? null) === '', 'Missing German title was filled from the English translation.');
assertPageCreation(str_contains($html, 'No saved translation exists for this language.'), 'The missing locale was not explained.');
assertPageCreation(str_contains($html, 'Each language shows its own saved values; missing translations are left blank instead of using fallback text.'), 'Locale-specific editing guidance was not shown.');
$_POST = [];
},
'generated routes persist for every active locale' => function (): void { 'generated routes persist for every active locale' => function (): void {
resetPageCreationDatabase(); resetPageCreationDatabase();
@@ -403,6 +512,156 @@ $cases = [
assertPageCreation($secondPage === false, 'Duplicate route was not rejected.'); assertPageCreation($secondPage === false, 'Duplicate route was not rejected.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Duplicate create left an extra base page.'); assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Duplicate create left an extra base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Duplicate create changed translations.'); assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Duplicate create changed translations.');
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
},
'route collision checks allow an unchanged page route and reject another locale collision' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
assertPageCreation($repository->update($page, pageCreationPayload()) === true, 'An unchanged route should not collide with its own page.');
assertPageCreation(
$repository->create(pageCreationPayload([
'name' => 'German route collision',
'route' => ['en' => '/unique-route', 'de' => '/de/new-page'],
])) === false,
'A route collision in a non-default locale was not rejected.'
);
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
},
'page locale coverage summarizes complete partial and absent translations in one batch' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'route' => ['en' => '/complete-en', 'de' => '/complete-de'],
]));
$repository->create(pageCreationPayload([
'name' => 'Partial page',
'route' => ['en' => '/partial-en', 'de' => '/partial-de'],
]));
$repository->create(pageCreationPayload([
'name' => 'Missing locale page',
'route' => ['en' => '/missing-en', 'de' => '/missing-de'],
]));
$pages = $repository->getAll();
$pageRows = [];
foreach ($pages as $page) {
$pageRows[$page->getId()] = $page;
}
global $phpb_db;
$pageIds = array_keys($pageRows);
$phpb_db->query('UPDATE page_translations SET title = ? WHERE page_id = ? AND locale = ?', ['', $pageIds[1], 'de']);
$phpb_db->query('DELETE FROM page_translations WHERE page_id = ? AND locale = ?', [$pageIds[2], 'de']);
$missingPage = new Page();
$missingPage->setData(['id' => 999, 'type' => 'static']);
$pages[] = $missingPage;
$phpb_db->pageTranslationBatchSelectCount = 0;
$coverage = (new Plugi\PageTranslationService())->getPageCoverage($pages, phpb_active_languages());
assertPageCreation($coverage[$pageIds[0]]['completeCount'] === 2, 'A complete page did not report all active locales complete.');
assertPageCreation($coverage[$pageIds[1]]['completeCount'] === 1, 'A partially complete page reported the wrong coverage count.');
assertPageCreation($coverage[$pageIds[1]]['locales']['de']['exists'] === true, 'An incomplete saved locale was reported as missing.');
assertPageCreation($coverage[$pageIds[1]]['locales']['de']['complete'] === false, 'An incomplete saved locale was reported as complete.');
assertPageCreation($coverage[$pageIds[2]]['locales']['de']['exists'] === false, 'An absent locale was reported as saved.');
assertPageCreation($coverage[999]['completeCount'] === 0, 'A page without translation records reported complete locales.');
assertPageCreation($phpb_db->pageTranslationBatchSelectCount === 1, 'Translation coverage used more than one batched repository query.');
$activeLanguages = phpb_active_languages();
$pageTranslationCoverage = $coverage;
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/pages.php';
$html = ob_get_clean();
assertPageCreation(str_contains($html, '/complete-en'), 'The page overview did not render the saved English route.');
assertPageCreation(str_contains($html, '/complete-de'), 'The page overview did not render the saved German route.');
assertPageCreation(str_contains($html, 'New page'), 'The page overview did not render a saved localized title.');
assertPageCreation(str_contains($html, '2 / 2 complete'), 'The page overview did not render the translation coverage summary.');
},
'successful route updates invalidate old and new localized routes' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$result = $repository->update($page, pageCreationPayload([
'route' => ['en' => '/changed-en', 'de' => '/changed-de'],
]));
assertPageCreation($result === true, 'A valid route update failed.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/changed-de', '/changed-en', '/de/new-page', '/new-page'],
'A successful route update did not invalidate both old and new localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'page deletion removes translations and invalidates routes after commit' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'route' => ['en' => '/delete-en', 'de' => '/delete-de'],
]));
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
assertPageCreation($repository->destroy($pageId) === true, 'Page deletion failed.');
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Page deletion left the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Page deletion left translation rows.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/delete-de', '/delete-en'],
'Successful deletion did not invalidate every stored localized route: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'failed page deletion rolls back translation cleanup without invalidating caches' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
$phpb_db->failOnDeleteTable = 'pages';
assertPageCreation($repository->destroy($pageId) === false, 'A failed base-row deletion was reported as successful.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Failed deletion removed the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Failed deletion did not roll back translation cleanup.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Failed deletion invalidated route caches.');
},
'exception during page deletion rolls back rows and leaves caches intact' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
$phpb_db->failOnDeleteTable = 'pages';
$phpb_db->throwOnDeleteFailure = true;
try {
$repository->destroy($pageId);
} catch (PDOException) {
}
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Deletion exception removed the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Deletion exception did not roll back translation cleanup.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Deletion exception invalidated route caches.');
},
'page content cache invalidation occurs only after successful writes' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$phpb_db->failOnPageUpdate = true;
assertPageCreation($repository->updatePageData($page, ['html' => []]) === false, 'A failed page-data update was reported as successful.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'A failed page-data update invalidated route caches.');
$phpb_db->failOnPageUpdate = false;
assertPageCreation($repository->updatePageData($page, ['html' => []]) === true, 'A valid page-data update failed.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/de/new-page', '/new-page'],
'A successful page-data update did not invalidate localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
}, },
'translation write failures roll back the base page and translations' => function (): void { 'translation write failures roll back the base page and translations' => function (): void {
resetPageCreationDatabase(); resetPageCreationDatabase();
@@ -449,6 +708,7 @@ $cases = [
assertPageCreation(count($translations) === 2, 'Failed update changed the translation count.'); assertPageCreation(count($translations) === 2, 'Failed update changed the translation count.');
assertPageCreation($translations[0]['route'] === '/new-page', 'Failed update did not restore the English route.'); assertPageCreation($translations[0]['route'] === '/new-page', 'Failed update did not restore the English route.');
assertPageCreation($translations[1]['route'] === '/de/new-page', 'Failed update did not restore the German route.'); assertPageCreation($translations[1]['route'] === '/de/new-page', 'Failed update did not restore the German route.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Failed metadata update invalidated route caches.');
}, },
]; ];
@@ -0,0 +1,111 @@
<?php
require_once __DIR__ . '/../src/PageTranslationService.php';
$pageTranslationServiceConfig = [
'general' => [
'language' => 'en',
],
];
function phpb_config(?string $key = null): mixed
{
global $pageTranslationServiceConfig;
if ($key === null) {
return $pageTranslationServiceConfig;
}
$value = $pageTranslationServiceConfig;
foreach (explode('.', $key) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return '';
}
$value = $value[$segment];
}
return $value;
}
function assertPageTranslationService(bool $condition, string $message): void
{
if (! $condition) {
throw new RuntimeException($message);
}
}
function runPageTranslationServiceCase(string $name, callable $case): bool
{
try {
$case();
fwrite(STDOUT, "PASS: {$name}\n");
return true;
} catch (Throwable $exception) {
fwrite(STDERR, "FAIL: {$name}: {$exception->getMessage()}\n");
return false;
}
}
$service = new Plugi\PageTranslationService();
$cases = [
'requested locale wins when available' => function () use ($service): void {
assertPageTranslationService(
$service->resolveLocale('fr', ['de', 'fr']) === 'fr',
'An available requested locale should be selected before the configured default.'
);
},
'configured locale wins when requested locale is absent' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'fr';
assertPageTranslationService(
$service->resolveLocale('it', ['de', 'fr']) === 'fr',
'The configured default should be used when the requested locale is unavailable.'
);
},
'first available locale is used when configured locale is unavailable' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'en';
assertPageTranslationService(
$service->resolveLocale('it', ['de', 'fr']) === 'de',
'The first available locale should be used without assuming an English translation exists.'
);
},
'no available locale resolves to null' => function () use ($service): void {
assertPageTranslationService($service->resolveLocale('en', []) === null, 'An empty locale list should resolve to null.');
},
'unsupported locales are rejected instead of receiving fallback' => function () use ($service): void {
assertPageTranslationService(
$service->isAvailableLocale('en', ['en' => 'English'])
&& ! $service->isAvailableLocale('it', ['en' => 'English']),
'Locale validation should accept active languages only and must not apply fallback.'
);
},
'translation values follow the same fallback order and preserve empty strings' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'fr';
$translations = [
'de' => ['title' => 'Deutscher Titel', 'meta_title' => ''],
'fr' => ['title' => 'Titre français', 'meta_title' => 'Titre de métadonnées'],
];
assertPageTranslationService(
$service->resolveTranslation($translations, 'title', 'it') === 'Titre français',
'Translation metadata did not use the configured locale fallback.'
);
assertPageTranslationService(
$service->resolveTranslation($translations, 'meta_title', 'de') === '',
'An intentionally empty translation should not be replaced by fallback text.'
);
},
];
$passed = 0;
foreach ($cases as $name => $case) {
if (runPageTranslationServiceCase($name, $case)) {
$passed++;
}
}
fwrite(STDOUT, sprintf("%d/%d page translation service cases passed.\n", $passed, count($cases)));
exit($passed === count($cases) ? 0 : 1);
@@ -0,0 +1,39 @@
<?php
return [
'title' => 'About Me',
'category' => 'Sections',
'icon' => 'ph ph-user-circle',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'A little about me'
],
'name' => [
'label' => 'Name',
'type' => 'text',
'value' => 'Your name'
],
'role' => [
'label' => 'Role or profession',
'type' => 'text',
'value' => 'Designer and maker'
],
'biography' => [
'label' => 'Biography',
'type' => 'text',
'value' => 'I help people turn good ideas into thoughtful, useful experiences. I believe the best work comes from listening carefully, staying curious, and paying attention to the details.'
],
'image_src' => [
'label' => 'Portrait image URL',
'type' => 'text',
'value' => 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=900&q=80'
],
'image_alt' => [
'label' => 'Image alternative text',
'type' => 'text',
'value' => 'Portrait of a creative professional'
],
]
];
+15
View File
@@ -0,0 +1,15 @@
<section class="bg-slate-50 px-4 py-12 sm:py-16">
<div class="mx-auto grid max-w-6xl gap-10 md:grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] md:items-center">
<?php if (strlen($block->setting('image_src')) > 0) : ?>
<div class="overflow-hidden rounded-2xl bg-slate-200">
<img class="aspect-square h-full w-full object-cover" src="<?= $block->setting('image_src') ?>" alt="<?= $block->setting('image_alt') ?>" loading="lazy" decoding="async">
</div>
<?php endif; ?>
<div>
<h2 class="mb-6 text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<h3 class="text-xl font-semibold text-slate-900"><?= $block->setting('name') ?></h3>
<p class="mt-1 text-sm font-medium text-slate-500"><?= $block->setting('role') ?></p>
<p class="mt-5 text-base leading-7 text-slate-600"><?= $block->setting('biography') ?></p>
</div>
</div>
</section>
+2 -19
View File
@@ -2,24 +2,7 @@
return [ return [
'title' => 'Button', 'title' => 'Button',
'category' => 'Layout', 'category' => 'Content',
'hidden' => true, 'hidden' => true,
'icon' => 'fa fa-hand-peace-o', 'icon' => 'ph ph-cursor-click',
'settings' => [
"order" => [
"type" => "select",
"label" => "Image Position",
"value" => "md:flex-row",
"options" => [
[
"id" => "md:flex-row",
"name" => "Right"
],
[
"id" => "md:flex-row-reverse",
"name" => "Left"
]
]
],
]
]; ];
+2 -2
View File
@@ -1,3 +1,3 @@
<a class="p-4 rounded bg-primary-300" href="#"> <a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900" href="/contact">
button Get in touch
</a> </a>
+1 -15
View File
@@ -4,19 +4,5 @@ return [
'title' => 'Column', 'title' => 'Column',
'category' => 'Layout', 'category' => 'Layout',
'hidden' => true, 'hidden' => true,
'icon' => 'fa fa-hand-peace-o', 'icon' => 'ph ph-columns',
'settings' => [
'text' => [
'label'=> 'Text',
'type' => 'text',
'placeholder' =>'auto',
'value' => 'Micheal Gough'
],
'texti' => [
'label'=> 'Text',
'type' => 'text',
'placeholder' =>'auto',
'value' => 'Micheal Gough'
],
]
]; ];
+1 -1
View File
@@ -1,3 +1,3 @@
<div class="col p-8 border rounded" phpb-blocks-container> <div class="min-w-0 rounded-xl border border-slate-200 bg-white p-6 sm:p-8" phpb-blocks-container>
[block slug="paragraph"] [block slug="paragraph"]
</div> </div>
+22 -6
View File
@@ -3,13 +3,29 @@
return [ return [
'title' => 'CTA', 'title' => 'CTA',
'category' => 'General', 'category' => 'General',
'icon' => 'fa fa-hand-peace-o', 'icon' => 'ph ph-megaphone',
'settings' => [ 'settings' => [
'person' => [ 'heading' => [
'label'=> 'Height', 'label' => 'Heading',
'type' => 'text', 'type' => 'text',
'placeholder' =>'auto', 'placeholder' => 'Add a short call to action',
'value' => 'Micheal Gough' 'value' => 'Ready to take the next step?'
] ],
'message' => [
'label' => 'Supporting text',
'type' => 'text',
'placeholder' => 'Explain what visitors can do next',
'value' => 'Get in touch to talk about how we can help.'
],
'button_label' => [
'label' => 'Button label',
'type' => 'text',
'value' => 'Contact us'
],
'button_url' => [
'label' => 'Button URL',
'type' => 'text',
'value' => '/contact'
],
] ]
]; ];
+7 -7
View File
@@ -1,9 +1,9 @@
<section class="bg-gray-50 dark:bg-gray-800"> <section class="bg-slate-100 px-4 py-12 sm:py-16">
<div class="max-w-screen-xl px-4 py-8 mx-auto lg:py-16 lg:px-6"> <div class="mx-auto max-w-3xl text-center">
<div class="max-w-screen-sm mx-auto text-center"> <h2 class="mb-4 text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<h2 class="mb-4 text-3xl font-extrabold leading-tight tracking-tight text-gray-900 dark:text-white">Start your free trial today</h2> <p class="mb-8 text-lg leading-7 text-slate-600"><?= $block->setting('message') ?></p>
<p class="mb-6 font-light text-gray-500 dark:text-gray-400 md:text-lg">Try Landwind Platform for 30 days. No credit card required.</p> <a href="<?= $block->setting('button_url') ?>" class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900">
<a href="#" class="text-white bg-purple-700 hover:bg-purple-800 focus:ring-4 focus:ring-purple-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-purple-600 dark:hover:bg-purple-700 focus:outline-none dark:focus:ring-purple-800">Free trial for 30 days</a> <?= $block->setting('button_label') ?>
</div> </a>
</div> </div>
</section> </section>
@@ -0,0 +1,7 @@
<?php
return [
'title' => 'Embedded Code',
'category' => 'Content',
'icon' => 'ph ph-code-block',
];
@@ -0,0 +1,5 @@
<section class="px-4 py-8">
<div class="mx-auto max-w-5xl rounded-xl border border-dashed border-slate-300 bg-slate-50 p-6 text-slate-500 sm:p-8" data-raw-content phpb-editable>
<p>Place approved embed content here using the existing trusted page-editor workflow.</p>
</div>
</section>
@@ -0,0 +1,20 @@
<?php
return [
'title' => 'FAQ Item',
'category' => 'Content',
'hidden' => true,
'icon' => 'ph ph-question',
'settings' => [
'question' => [
'label' => 'Question',
'type' => 'text',
'value' => 'How does the process begin?'
],
'answer' => [
'label' => 'Answer',
'type' => 'text',
'value' => 'We start with a conversation about your goals, audience, and the outcome you want to achieve.'
],
]
];
@@ -0,0 +1,9 @@
<details class="group rounded-xl border border-slate-200 bg-white">
<summary class="flex cursor-pointer list-none items-center justify-between gap-4 px-5 py-4 font-semibold text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-700">
<span><?= $block->setting('question') ?></span>
<span class="text-xl font-normal text-slate-500 transition group-open:rotate-45" aria-hidden="true">+</span>
</summary>
<div class="px-5 pb-5 text-slate-600">
<p class="leading-7"><?= $block->setting('answer') ?></p>
</div>
</details>
+25
View File
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'FAQ Section',
'category' => 'Sections',
'icon' => 'ph ph-question',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Frequently asked questions'
],
'intro' => [
'label' => 'Supporting text',
'type' => 'text',
'value' => 'Find quick answers to common questions about our services and process.'
],
'item_count' => [
'label' => 'Number of questions (1–10)',
'type' => 'number',
'value' => '5',
'placeholder' => '5'
],
]
];
+16
View File
@@ -0,0 +1,16 @@
<?php
$itemCount = max(1, min(10, intval($block->setting('item_count'))));
?>
<section class="px-4 py-12 sm:py-16">
<div class="mx-auto max-w-4xl">
<div class="mb-8 max-w-3xl">
<h2 class="text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<p class="mt-4 text-lg leading-7 text-slate-600"><?= $block->setting('intro') ?></p>
</div>
<div class="space-y-3">
<?php for ($i = 0; $i < $itemCount; $i++): ?>
[block slug="faq-item" id="faq-item-<?= $i ?>"]
<?php endfor; ?>
</div>
</div>
</section>
@@ -0,0 +1,35 @@
<?php
return [
'title' => 'Feature Card',
'category' => 'Content',
'hidden' => true,
'icon' => 'ph ph-cardholder',
'settings' => [
'symbol' => [
'label' => 'Icon or symbol',
'type' => 'text',
'value' => '✦'
],
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Clear direction'
],
'description' => [
'label' => 'Description',
'type' => 'text',
'value' => 'Start with a clear plan shaped around your goals and the people you want to reach.'
],
'link_label' => [
'label' => 'Link label',
'type' => 'text',
'value' => 'Learn more'
],
'link_url' => [
'label' => 'Link URL',
'type' => 'text',
'value' => '/services'
],
]
];
@@ -0,0 +1,10 @@
<article class="h-full rounded-xl border border-slate-200 bg-white p-6 shadow-sm transition hover:shadow-md">
<span class="mb-5 inline-flex h-11 w-11 items-center justify-center rounded-lg bg-slate-100 text-xl text-slate-900" aria-hidden="true"><?= $block->setting('symbol') ?></span>
<h3 class="text-xl font-semibold text-slate-900"><?= $block->setting('heading') ?></h3>
<p class="mt-3 leading-7 text-slate-600"><?= $block->setting('description') ?></p>
<?php if (strlen($block->setting('link_url')) > 0) : ?>
<a class="mt-5 inline-flex items-center gap-2 text-sm font-semibold text-slate-900 underline decoration-slate-300 underline-offset-4 hover:decoration-slate-900" href="<?= $block->setting('link_url') ?>">
<?= $block->setting('link_label') ?>
</a>
<?php endif; ?>
</article>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Feature Cards',
'category' => 'Sections',
'icon' => 'ph ph-cards',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Thoughtful solutions for every stage'
],
'intro' => [
'label' => 'Supporting text',
'type' => 'text',
'value' => 'Highlight the services, strengths, or benefits that matter most to your visitors.'
],
'card_count' => [
'label' => 'Number of cards (1–6)',
'type' => 'number',
'value' => '3',
'placeholder' => '3'
],
]
];
@@ -0,0 +1,16 @@
<?php
$cardCount = max(1, min(6, intval($block->setting('card_count'))));
?>
<section class="px-4 py-12 sm:py-16">
<div class="mx-auto max-w-7xl">
<div class="mb-10 max-w-3xl">
<h2 class="text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<p class="mt-4 text-lg leading-7 text-slate-600"><?= $block->setting('intro') ?></p>
</div>
<div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
<?php for ($i = 0; $i < $cardCount; $i++): ?>
[block slug="feature-card" id="feature-card-<?= $i ?>"]
<?php endfor; ?>
</div>
</div>
</section>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Gallery Image',
'category' => 'Content',
'hidden' => true,
'icon' => 'ph ph-image',
'settings' => [
'image_src' => [
'label' => 'Image source URL',
'type' => 'text',
'value' => 'https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?auto=format&fit=crop&w=1200&q=80'
],
'image_alt' => [
'label' => 'Image alternative text',
'type' => 'text',
'value' => 'Rolling hills beneath a cloudy sky'
],
'caption' => [
'label' => 'Caption',
'type' => 'text',
'value' => 'A quiet moment in the landscape'
],
]
];
@@ -0,0 +1,10 @@
<figure class="overflow-hidden rounded-xl bg-slate-100">
<?php if (strlen($block->setting('image_src')) > 0) : ?>
<a class="group block focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-700" href="<?= $block->setting('image_src') ?>" target="_blank" rel="noopener noreferrer" data-gallery-trigger>
<img class="aspect-square w-full object-cover transition duration-300 group-hover:scale-105" src="<?= $block->setting('image_src') ?>" alt="<?= $block->setting('image_alt') ?>" loading="lazy" decoding="async">
</a>
<?php endif; ?>
<?php if (strlen($block->setting('caption')) > 0) : ?>
<figcaption class="px-3 py-2 text-sm text-slate-600"><?= $block->setting('caption') ?></figcaption>
<?php endif; ?>
</figure>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Gallery',
'category' => 'Sections',
'icon' => 'ph ph-images',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'A selection of our work'
],
'item_count' => [
'label' => 'Number of images (1–12)',
'type' => 'number',
'value' => '6',
'placeholder' => '6'
],
'lightbox_enabled' => [
'label' => 'Enable image lightbox',
'type' => 'yes_no',
'value' => 1
],
]
];
+24
View File
@@ -0,0 +1,24 @@
<?php
$itemCount = max(1, min(12, intval($block->setting('item_count'))));
$lightboxEnabled = (int) $block->setting('lightbox_enabled') === 1;
?>
<section class="px-4 py-12 sm:py-16" data-gallery data-gallery-lightbox="<?= $lightboxEnabled ? 'true' : 'false' ?>">
<div class="mx-auto max-w-7xl">
<h2 class="mb-8 text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
<?php for ($i = 0; $i < $itemCount; $i++): ?>
[block slug="gallery-item" id="gallery-item-<?= $i ?>"]
<?php endfor; ?>
</div>
<?php if ($lightboxEnabled) : ?>
<dialog class="m-auto max-h-[90vh] max-w-[90vw] overflow-visible border-0 bg-transparent p-0 text-white backdrop:bg-slate-950/80" data-gallery-dialog aria-label="Gallery image preview">
<form method="dialog" class="absolute right-2 top-2 z-10">
<button class="rounded-full bg-white/90 p-2 text-slate-900 shadow hover:bg-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white" aria-label="Close image preview">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 6l12 12M18 6L6 18" /></svg>
</button>
</form>
<img class="max-h-[90vh] max-w-[90vw] rounded-lg object-contain" data-gallery-lightbox-image alt="">
</dialog>
<?php endif; ?>
</div>
</section>
@@ -3,7 +3,8 @@
return [ return [
'title' => 'Hello World', 'title' => 'Hello World',
'category' => 'General', 'category' => 'General',
'icon' => 'fa fa-hand-peace-o', 'hidden' => true,
'icon' => 'ph ph-hand-wave',
'settings' => [ 'settings' => [
'height' => [ 'height' => [
'label'=> 'Height', 'label'=> 'Height',
+44
View File
@@ -0,0 +1,44 @@
<?php
return [
'title' => 'Hero',
'category' => 'Sections',
'icon' => 'ph ph-panorama',
'settings' => [
'eyebrow' => [
'label' => 'Eyebrow',
'type' => 'text',
'value' => 'A better way to build your website'
],
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'Make your next idea a reality'
],
'message' => [
'label' => 'Supporting text',
'type' => 'text',
'value' => 'Introduce your business, explain what makes it different, and help visitors find their next step.'
],
'button_label' => [
'label' => 'Button label',
'type' => 'text',
'value' => 'Explore our services'
],
'button_url' => [
'label' => 'Button URL',
'type' => 'text',
'value' => '/services'
],
'image_src' => [
'label' => 'Image source URL',
'type' => 'text',
'value' => 'https://images.unsplash.com/photo-1497366216548-37526070297c?auto=format&fit=crop&w=1200&q=80'
],
'image_alt' => [
'label' => 'Image alternative text',
'type' => 'text',
'value' => 'A bright, welcoming workspace'
],
]
];
+17
View File
@@ -0,0 +1,17 @@
<section class="bg-white px-4 py-16 sm:py-20 lg:py-24">
<div class="mx-auto grid max-w-7xl gap-12 lg:grid-cols-2 lg:items-center">
<div>
<p class="mb-4 text-sm font-semibold uppercase tracking-wide text-slate-600"><?= $block->setting('eyebrow') ?></p>
<h1 class="text-4xl font-semibold tracking-tight text-slate-950 sm:text-5xl lg:text-6xl"><?= $block->setting('heading') ?></h1>
<p class="mt-6 max-w-2xl text-lg leading-8 text-slate-600"><?= $block->setting('message') ?></p>
<a href="<?= $block->setting('button_url') ?>" class="mt-8 inline-flex items-center justify-center rounded-lg bg-slate-900 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900">
<?= $block->setting('button_label') ?>
</a>
</div>
<?php if (strlen($block->setting('image_src')) > 0) : ?>
<div class="overflow-hidden rounded-2xl bg-slate-100">
<img class="aspect-[4/3] h-full w-full object-cover" src="<?= $block->setting('image_src') ?>" alt="<?= $block->setting('image_alt') ?>" fetchpriority="high">
</div>
<?php endif; ?>
</div>
</section>
+3 -2
View File
@@ -1,7 +1,8 @@
<?php <?php
return [ return [
'title' => 'image', 'title' => 'Image',
'category' => 'Content',
'hidden' => true, 'hidden' => true,
'icon' => 'fa fa-hand-peace-o' 'icon' => 'ph ph-image'
]; ];
+1 -1
View File
@@ -1 +1 @@
<img src="" alt="" data-blubb="foo"> <img class="h-auto w-full rounded-xl object-cover" src="https://images.unsplash.com/photo-1497366216548-37526070297c?auto=format&amp;fit=crop&amp;w=1200&amp;q=80" alt="A bright, welcoming workspace" loading="lazy" decoding="async">
+7
View File
@@ -0,0 +1,7 @@
<?php
return [
'title' => 'List',
'category' => 'Content',
'icon' => 'ph ph-list-bullets',
];
+10
View File
@@ -0,0 +1,10 @@
<section class="px-4 py-12 sm:py-16">
<div class="mx-auto max-w-3xl">
<h2 class="mb-6 text-2xl font-semibold tracking-tight text-slate-900 sm:text-3xl" phpb-editable>What you can expect</h2>
<ul class="list-disc space-y-3 pl-6 text-base leading-7 text-slate-600 marker:text-slate-400">
<li phpb-editable>Clear communication from the first conversation to the final delivery</li>
<li phpb-editable>Practical recommendations tailored to your goals</li>
<li phpb-editable>Thoughtful, reliable support at every stage</li>
</ul>
</div>
</section>
+2 -2
View File
@@ -2,7 +2,7 @@
return [ return [
'title' => 'Paragraph', 'title' => 'Paragraph',
'category' => 'Layout', 'category' => 'Content',
'hidden' => true, 'hidden' => true,
'icon' => 'fa fa-hand-peace-o', 'icon' => 'ph ph-text-align-left',
]; ];
+3 -3
View File
@@ -1,3 +1,3 @@
<div class="" phpb-editable> <p class="text-base leading-7 text-slate-600" phpb-editable>
Dolore cillum et tempor. Nulla mollit quis sunt duis aliqua ad consectetur minim Lorem irure non duis. Et est elit cillum magna non. Culpa nisi aute occaecat aliqua eiusmod. Sunt tempor eu dolore duis ad mollit enim elit commodo labore aute quis dolor. Consequat consectetur elit officia non anim cillum reprehenderit nulla duis deserunt ex id. Veniam ex in reprehenderit in ut id tempor occaecat. Nisi ea velit adipisicing minim voluptate. Add a paragraph that explains your service, shares useful information, or gives visitors the context they need.
</div> </p>
+15 -6
View File
@@ -3,13 +3,22 @@
return [ return [
'title' => 'Quote', 'title' => 'Quote',
'category' => 'General', 'category' => 'General',
'icon' => 'fa fa-hand-peace-o', 'icon' => 'ph ph-quotes',
'settings' => [ 'settings' => [
'person' => [ 'quote' => [
'label'=> 'Height', 'label' => 'Quote',
'type' => 'text', 'type' => 'text',
'placeholder' =>'auto', 'value' => 'Clear communication and thoughtful planning make every project better.'
'value' => 'Micheal Gough' ],
] 'person' => [
'label' => 'Name',
'type' => 'text',
'value' => 'Jordan Lee'
],
'role' => [
'label' => 'Role or attribution',
'type' => 'text',
'value' => 'Customer'
],
] ]
]; ];
+8 -13
View File
@@ -1,19 +1,14 @@
<section class="bg-gray-50 dark:bg-gray-800"> <section class="bg-slate-50 px-4 py-12 sm:py-16">
<div class="max-w-screen-xl px-4 py-8 mx-auto text-center lg:py-24 lg:px-6"> <figure class="mx-auto max-w-3xl text-center">
<figure class="max-w-screen-md mx-auto"> <svg class="mx-auto mb-5 h-10 w-10 text-slate-300" viewBox="0 0 24 27" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<svg class="h-12 mx-auto mb-3 text-gray-400 dark:text-gray-600" viewBox="0 0 24 27" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M14.017 18L14.017 10.609C14.017 4.905 17.748 1.039 23 0L23.995 2.151C21.563 3.068 20 5.789 20 8H24V18H14.017ZM0 18V10.609C0 4.905 3.748 1.038 9 0L9.996 2.151C7.563 3.068 6 5.789 6 8H9.983L9.983 18L0 18Z" />
<path d="M14.017 18L14.017 10.609C14.017 4.905 17.748 1.039 23 0L23.995 2.151C21.563 3.068 20 5.789 20 8H24V18H14.017ZM0 18V10.609C0 4.905 3.748 1.038 9 0L9.996 2.151C7.563 3.068 6 5.789 6 8H9.983L9.983 18L0 18Z" fill="currentColor"></path>
</svg> </svg>
<blockquote> <blockquote>
<p class="text-xl font-medium text-gray-900 md:text-2xl dark:text-white">"Landwind is just awesome. It contains tons of predesigned components and pages starting from login screen to complex dashboard. Perfect choice for your next SaaS application."</p> <p class="text-xl font-medium leading-8 text-slate-900 sm:text-2xl">“<?= $block->setting('quote') ?>”</p>
</blockquote> </blockquote>
<figcaption class="flex items-center justify-center mt-6 space-x-3"> <figcaption class="mt-6 text-sm text-slate-600">
<img class="w-6 h-6 rounded-full" src="https://flowbite.s3.amazonaws.com/blocks/marketing-ui/avatars/michael-gouch.png" alt="profile picture"> <span class="font-semibold text-slate-900"><?= $block->setting('person') ?></span>
<div class="flex items-center divide-x-2 divide-gray-500 dark:divide-gray-700"> <span> · <?= $block->setting('role') ?></span>
<div class="pr-3 font-medium text-gray-900 dark:text-white"><?php echo $block->setting('person'); ?></div>
<div class="pl-3 text-sm font-light text-gray-500 dark:text-gray-400">CEO at Google</div>
</div>
</figcaption> </figcaption>
</figure> </figure>
</div>
</section> </section>
+4 -3
View File
@@ -3,12 +3,13 @@
return [ return [
'title' => 'Row', 'title' => 'Row',
'category' => 'Layout', 'category' => 'Layout',
'icon' => 'fa fa-hand-peace-o', 'icon' => 'ph ph-columns',
'settings' => [ 'settings' => [
"column_count" => [ "column_count" => [
"type" => "number", "type" => "number",
"label" => "Number of columns", "label" => "Number of columns (1–4)",
"value" => "3" "value" => "3",
"placeholder" => "3"
], ],
] ]
]; ];
+10 -6
View File
@@ -1,10 +1,14 @@
<div class="row p-3 flex flex-nowrap gap-3">
<?php <?php
$columnCount = intval($block->setting('column_count')); $columnCount = max(1, min(4, intval($block->setting('column_count'))));
for ($i = 0; $i < $columnCount; $i++): $columnClasses = [
1 => 'md:grid-cols-1',
2 => 'md:grid-cols-2',
3 => 'md:grid-cols-3',
4 => 'md:grid-cols-4',
];
?> ?>
<div class="grid grid-cols-1 gap-6 <?= $columnClasses[$columnCount] ?>">
<?php for ($i = 0; $i < $columnCount; $i++): ?>
[block slug="col" id="col<?= $i ?>"] [block slug="col" id="col<?= $i ?>"]
<?php <?php endfor; ?>
endfor;
?>
</div> </div>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Testimonial',
'category' => 'Content',
'hidden' => true,
'icon' => 'ph ph-quotes',
'settings' => [
'quote' => [
'label' => 'Quote',
'type' => 'text',
'value' => 'The process was clear from the start, and the final result made a real difference to our business.'
],
'name' => [
'label' => 'Name',
'type' => 'text',
'value' => 'Taylor Morgan'
],
'role' => [
'label' => 'Role or attribution',
'type' => 'text',
'value' => 'Business owner'
],
]
];
@@ -0,0 +1,7 @@
<figure class="flex h-full flex-col rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<blockquote class="flex-1 text-base leading-7 text-slate-700">“<?= $block->setting('quote') ?>”</blockquote>
<figcaption class="mt-6 border-t border-slate-100 pt-4">
<p class="font-semibold text-slate-900"><?= $block->setting('name') ?></p>
<p class="mt-1 text-sm text-slate-500"><?= $block->setting('role') ?></p>
</figcaption>
</figure>
@@ -0,0 +1,25 @@
<?php
return [
'title' => 'Testimonials',
'category' => 'Sections',
'icon' => 'ph ph-chat-centered-quote',
'settings' => [
'heading' => [
'label' => 'Heading',
'type' => 'text',
'value' => 'What our clients say'
],
'intro' => [
'label' => 'Supporting text',
'type' => 'text',
'value' => 'A few words from people we have had the pleasure of working with.'
],
'item_count' => [
'label' => 'Number of testimonials (1–6)',
'type' => 'number',
'value' => '3',
'placeholder' => '3'
],
]
];
@@ -0,0 +1,16 @@
<?php
$itemCount = max(1, min(6, intval($block->setting('item_count'))));
?>
<section class="bg-slate-50 px-4 py-12 sm:py-16">
<div class="mx-auto max-w-7xl">
<div class="mb-10 max-w-3xl">
<h2 class="text-3xl font-semibold tracking-tight text-slate-900 sm:text-4xl"><?= $block->setting('heading') ?></h2>
<p class="mt-4 text-lg leading-7 text-slate-600"><?= $block->setting('intro') ?></p>
</div>
<div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
<?php for ($i = 0; $i < $itemCount; $i++): ?>
[block slug="testimonial-item" id="testimonial-item-<?= $i ?>"]
<?php endfor; ?>
</div>
</div>
</section>
@@ -2,7 +2,7 @@
return [ return [
'title' => 'Text + Image', 'title' => 'Text + Image',
'category' => 'General', 'category' => 'Content',
'icon' => 'ph ph-square-half', 'icon' => 'ph ph-square-half',
'settings' => [ 'settings' => [
"order" => [ "order" => [
@@ -23,18 +23,18 @@ return [
"width" => [ "width" => [
"type" => "select", "type" => "select",
"label" => "Image Width", "label" => "Image Width",
"value" => "md:w-6/12", "value" => "md:w-1/2",
"options" => [ "options" => [
[ [
"id" => "md:w-4/12", "id" => "md:w-1/3",
"name" => "1/3" "name" => "1/3"
], ],
[ [
"id" => "md:w-6/12", "id" => "md:w-1/2",
"name" => "1/2" "name" => "1/2"
], ],
[ [
"id" => "md:w-full", "id" => "md:w-2/3",
"name" => "2/3" "name" => "2/3"
], ],
] ]
@@ -43,7 +43,7 @@ return [
'label'=> 'Headline', 'label'=> 'Headline',
'type' => 'text', 'type' => 'text',
'placeholder' =>'Headline', 'placeholder' =>'Headline',
'value' => 'Lorem Ipsum dolor' 'value' => 'A flexible section for your story'
], ],
] ]
]; ];
+9 -9
View File
@@ -1,17 +1,17 @@
<section class=""> <section class="py-12 sm:py-16">
<div class="container container-md mx-auto p-4 flex flex-row gap-4 flex-col-reverse <?= phpb_e($block->setting('order')) ?>"> <div class="mx-auto flex max-w-6xl flex-col gap-8 px-4 sm:px-6 lg:px-8 md:flex-row <?= $block->setting('order') ?>">
<div class="md:w-6/12 grow"> <div class="min-w-0 flex-1">
<?php if (strlen($block->setting('headline')) > 0) : ?> <?php if (strlen($block->setting('headline')) > 0) : ?>
<div class=" text-2xl"> <h2 class="mb-4 text-3xl font-semibold tracking-tight text-slate-900">
<?= phpb_e($block->setting('headline')) ?> <?= $block->setting('headline') ?>
</div> </h2>
<?php endif; ?> <?php endif; ?>
<div class="space-y-5">
[block slug="paragraph"] [block slug="paragraph"]
<br>
<br>
[block slug="button"] [block slug="button"]
</div> </div>
<div class="<?= phpb_e($block->setting('width')) ?>"> </div>
<div class="w-full <?= $block->setting('width') ?>">
[block slug="image"] [block slug="image"]
</div> </div>
</div> </div>
+1 -5
View File
File diff suppressed because one or more lines are too long
+486 -2003
View File
File diff suppressed because it is too large Load Diff
+36 -63
View File
@@ -29,117 +29,90 @@ use Plugi\Repositories\MenuRepository;
<body> <body>
<?= Extensions::getHtmlBlocks("body-start") ?> <?= Extensions::getHtmlBlocks("body-start") ?>
<div class="navbar bg-base-100">
<div class="navbar-start">
<div class="dropdown">
<label tabindex="0" class="btn btn-ghost lg:hidden">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16" /></svg>
</label>
<ul tabindex="0" class="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52">
<?php <?php
$menuRepo = new MenuRepository(); $menuRepo = new MenuRepository();
$mainMenu = $menuRepo->getHydratedMenu("Main"); $mainMenu = $menuRepo->getHydratedMenu("Main");
?> ?>
<header class="border-b border-slate-200 bg-white">
<div class="mx-auto flex max-w-7xl items-center justify-between px-4 py-4 sm:px-6 lg:px-8">
<a href="/" class="text-xl font-semibold tracking-tight text-slate-900">
<?= phpb_e($page->getTranslation("meta_title") ?: "Home") ?>
</a>
<nav aria-label="Main navigation">
<details class="relative lg:hidden">
<summary class="flex cursor-pointer list-none items-center rounded-md p-2 text-slate-700 hover:bg-slate-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-700">
<span class="sr-only">Main menu</span>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" /></svg>
</summary>
<ul class="absolute right-0 z-10 mt-2 w-56 rounded-lg border border-slate-200 bg-white p-2 shadow-lg">
<?php if ($mainMenu): ?> <?php if ($mainMenu): ?>
<?php foreach ($mainMenu["pages"] as $menuPage): ?> <?php foreach ($mainMenu["pages"] as $menuPage): ?>
<li> <li>
<a href="<?= phpb_e($menuPage["route"]) ?>"><?= phpb_e( <a class="block rounded-md px-3 py-2 text-slate-700 hover:bg-slate-100" href="<?= phpb_e($menuPage["route"]) ?>"><?= phpb_e($menuPage["title"]) ?></a>
$menuPage["title"],
) ?></a>
</li> </li>
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
<!-- <li>-->
<!-- <a>Parent</a>-->
<!-- <ul class="p-2">-->
<!-- <li><a>Submenu 1</a></li>-->
<!-- <li><a>Submenu 2</a></li>-->
<!-- </ul>-->
<!-- </li>-->
</ul> </ul>
</div> </details>
<a class="btn btn-ghost normal-case text-xl">daisyUI</a> <ul class="hidden items-center gap-6 lg:flex">
</div>
<div class="navbar-center hidden lg:flex">
<ul class="menu menu-horizontal px-1">
<?php
$menuRepo = new MenuRepository();
$mainMenu = $menuRepo->getHydratedMenu("Main");
?>
<?php if ($mainMenu): ?> <?php if ($mainMenu): ?>
<?php foreach ($mainMenu["pages"] as $menuPage): ?> <?php foreach ($mainMenu["pages"] as $menuPage): ?>
<li> <li>
<a href="<?= phpb_e($menuPage["route"]) ?>"><?= phpb_e( <a class="text-sm font-medium text-slate-700 hover:text-slate-950" href="<?= phpb_e($menuPage["route"]) ?>"><?= phpb_e($menuPage["title"]) ?></a>
$menuPage["title"],
) ?></a>
</li> </li>
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
<!-- <li tabindex="0">-->
<!-- <details>-->
<!-- <summary>Parent</summary>-->
<!-- <ul class="p-2">-->
<!-- <li><a>Submenu 1</a></li>-->
<!-- <li><a>Submenu 2</a></li>-->
<!-- </ul>-->
<!-- </details>-->
<!-- </li>-->
</ul> </ul>
</nav>
</div> </div>
<div class="navbar-end"> </header>
<a class="btn">Button</a>
</div>
</div>
<main class="#main-content"> <main id="main-content" class="min-h-screen">
<?= $body ?> <?= $body ?>
</main> </main>
<footer class="footer footer-center p-4 bg-base-300 text-base-content"> <footer class="border-t border-slate-200 bg-slate-50 text-slate-700">
<div> <div class="mx-auto flex max-w-7xl flex-col items-center gap-4 px-4 py-8 sm:px-6 lg:px-8">
<ul class="flex flex-wrap justify-center items-center mb-6 text-gray-900 dark:text-white"> <nav aria-label="Footer navigation">
<ul class="flex flex-wrap items-center justify-center gap-x-6 gap-y-3">
<?php <?php
$menuRepo = new MenuRepository();
$footerMenu = $menuRepo->getHydratedMenu("Footer"); $footerMenu = $menuRepo->getHydratedMenu("Footer");
?> ?>
<?php if ($footerMenu): ?> <?php if ($footerMenu): ?>
<?php foreach ($footerMenu["pages"] as $menuPage): ?> <?php foreach ($footerMenu["pages"] as $menuPage): ?>
<li> <li>
<a href="<?= phpb_e( <a href="<?= phpb_e($menuPage["route"]) ?>" class="text-sm hover:underline"><?= phpb_e($menuPage["title"]) ?></a>
$menuPage["route"],
) ?>" class="mr-4 hover:underline md:mr-6 "><?= phpb_e(
$menuPage["title"],
) ?></a>
</li> </li>
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
<li> <li>
<div class="dropdown dropdown-hover dropdown-top"> <details class="relative">
<label tabindex="0" class="btn m-1 btn-xs"><i class="ph ph-translate"></i></label> <summary class="flex cursor-pointer list-none items-center rounded-md p-2 hover:bg-slate-200 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-700">
<ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-52"> <span class="sr-only">Choose language</span>
<i class="ph ph-translate" aria-hidden="true"></i>
</summary>
<ul class="absolute bottom-full right-0 z-10 mb-2 w-52 rounded-lg border border-slate-200 bg-white p-2 shadow-lg">
<?php <?php
$menuRepo = new MenuRepository();
$languageMenu = $menuRepo->getLanguageMenu( $languageMenu = $menuRepo->getLanguageMenu(
$page->getTranslation("page_id"), $page->getTranslation("page_id"),
); );
?> ?>
<?php if ($languageMenu): ?> <?php if ($languageMenu): ?>
<?php foreach ($languageMenu as $lang): ?> <?php foreach ($languageMenu as $lang): ?>
<li x-data="{emoji: ''}" x-init="emoji = plugi.getFlagEmoji('<?= phpb_e( <li>
$lang["locale"], <a class="flex items-center gap-2 rounded-md px-3 py-2 hover:bg-slate-100" href="<?= phpb_e($lang["route"]) ?>">
) ?>')"> <span data-locale-flag data-locale="<?= phpb_e($lang["locale"]) ?>" aria-hidden="true"></span>
<a href="<?= phpb_e($lang["route"]) ?>">
<span x-text="emoji"></span>
<?= phpb_e($lang["title"]) ?> <?= phpb_e($lang["title"]) ?>
</a> </a>
</li> </li>
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
</ul> </ul>
</div> </details>
</li> </li>
</ul> </ul>
<p>Copyright © <?= phpb_e(date("Y")) ?></p> </nav>
<p class="text-sm">Copyright © <?= phpb_e(date("Y")) ?></p>
</div> </div>
</footer> </footer>
-107
View File
@@ -7,13 +7,8 @@
"": { "": {
"name": "phpb-demo-template", "name": "phpb-demo-template",
"version": "0.0.0", "version": "0.0.0",
"dependencies": {
"@types/alpinejs": "^3.7.2",
"alpinejs": "^3.12.2"
},
"devDependencies": { "devDependencies": {
"@tailwindcss/cli": "^4.3.5", "@tailwindcss/cli": "^4.3.5",
"daisyui": "^5.8.2",
"npm-watch": "^0.11.0", "npm-watch": "^0.11.0",
"rolldown": "^1.3.3", "rolldown": "^1.3.3",
"tailwindcss": "^4.3.5", "tailwindcss": "^4.3.5",
@@ -1069,54 +1064,12 @@
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@types/alpinejs": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/@types/alpinejs/-/alpinejs-3.7.2.tgz",
"integrity": "sha512-M/PAVysvGxOlhifP/6XmO8bj5HW9w+Ygr03PdryM3tCb1KuQEaAAvVcyeZc5T75PbjH3dCzy/M/w/nJEE0FTSg==",
"dependencies": {
"@vue/reactivity": "^3.2.26"
}
},
"node_modules/@types/alpinejs/node_modules/@vue/reactivity": {
"version": "3.3.4",
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.3.4.tgz",
"integrity": "sha512-kLTDLwd0B1jG08NBF3R5rqULtv/f8x3rOFByTDz4J53ttIQEDmALqKqXY0J+XQeN0aV2FBxY8nJDf88yvOPAqQ==",
"dependencies": {
"@vue/shared": "3.3.4"
}
},
"node_modules/@types/alpinejs/node_modules/@vue/shared": {
"version": "3.3.4",
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.3.4.tgz",
"integrity": "sha512-7OjdcV8vQ74eiz1TZLzZP4JwqM5fA94K6yntPS5Z25r9HDuGNzaGdgvwKYq6S+MxwF0TFRwe50fIR/MYnakdkQ=="
},
"node_modules/@vue/reactivity": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.1.5.tgz",
"integrity": "sha512-1tdfLmNjWG6t/CsPldh+foumYFo3cpyCHgBYQ34ylaMsJ+SNHQ1kApMIa8jN+i593zQuaw3AdWH0nJTARzCFhg==",
"dependencies": {
"@vue/shared": "3.1.5"
}
},
"node_modules/@vue/shared": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.1.5.tgz",
"integrity": "sha512-oJ4F3TnvpXaQwZJNF3ZK+kLPHKarDmJjJ6jyzVNDKH9md1dptjC7lWR//jrGuLdek/U6iltWxqAnYOu8gCiOvA=="
},
"node_modules/abbrev": { "node_modules/abbrev": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
"integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
"dev": true "dev": true
}, },
"node_modules/alpinejs": {
"version": "3.12.3",
"resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.12.3.tgz",
"integrity": "sha512-fLz2dfYQ3xCk7Ip8LiIpV2W+9brUyex2TAE7Z0BCvZdUDklJE+n+a8gCgLWzfZ0GzZNZu7HUP8Z0z6Xbm6fsSA==",
"dependencies": {
"@vue/reactivity": "~3.1.1"
}
},
"node_modules/anymatch": { "node_modules/anymatch": {
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
@@ -1214,16 +1167,6 @@
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true "dev": true
}, },
"node_modules/daisyui": {
"version": "5.8.2",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.8.2.tgz",
"integrity": "sha512-InScsDXX0pbfgvWyPQ8iTHV4rNMZdfbMo85KqlQUn62/PCIjwczViw5lbotzoXy/nPrn4qjDMmx/fspuUnjBtA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/saadeghi/daisyui?sponsor=1"
}
},
"node_modules/debug": { "node_modules/debug": {
"version": "3.2.7", "version": "3.2.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
@@ -2531,56 +2474,12 @@
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"@types/alpinejs": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/@types/alpinejs/-/alpinejs-3.7.2.tgz",
"integrity": "sha512-M/PAVysvGxOlhifP/6XmO8bj5HW9w+Ygr03PdryM3tCb1KuQEaAAvVcyeZc5T75PbjH3dCzy/M/w/nJEE0FTSg==",
"requires": {
"@vue/reactivity": "^3.2.26"
},
"dependencies": {
"@vue/reactivity": {
"version": "3.3.4",
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.3.4.tgz",
"integrity": "sha512-kLTDLwd0B1jG08NBF3R5rqULtv/f8x3rOFByTDz4J53ttIQEDmALqKqXY0J+XQeN0aV2FBxY8nJDf88yvOPAqQ==",
"requires": {
"@vue/shared": "3.3.4"
}
},
"@vue/shared": {
"version": "3.3.4",
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.3.4.tgz",
"integrity": "sha512-7OjdcV8vQ74eiz1TZLzZP4JwqM5fA94K6yntPS5Z25r9HDuGNzaGdgvwKYq6S+MxwF0TFRwe50fIR/MYnakdkQ=="
}
}
},
"@vue/reactivity": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.1.5.tgz",
"integrity": "sha512-1tdfLmNjWG6t/CsPldh+foumYFo3cpyCHgBYQ34ylaMsJ+SNHQ1kApMIa8jN+i593zQuaw3AdWH0nJTARzCFhg==",
"requires": {
"@vue/shared": "3.1.5"
}
},
"@vue/shared": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.1.5.tgz",
"integrity": "sha512-oJ4F3TnvpXaQwZJNF3ZK+kLPHKarDmJjJ6jyzVNDKH9md1dptjC7lWR//jrGuLdek/U6iltWxqAnYOu8gCiOvA=="
},
"abbrev": { "abbrev": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
"integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
"dev": true "dev": true
}, },
"alpinejs": {
"version": "3.12.3",
"resolved": "https://registry.npmjs.org/alpinejs/-/alpinejs-3.12.3.tgz",
"integrity": "sha512-fLz2dfYQ3xCk7Ip8LiIpV2W+9brUyex2TAE7Z0BCvZdUDklJE+n+a8gCgLWzfZ0GzZNZu7HUP8Z0z6Xbm6fsSA==",
"requires": {
"@vue/reactivity": "~3.1.1"
}
},
"anymatch": { "anymatch": {
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
@@ -2655,12 +2554,6 @@
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true "dev": true
}, },
"daisyui": {
"version": "5.8.2",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.8.2.tgz",
"integrity": "sha512-InScsDXX0pbfgvWyPQ8iTHV4rNMZdfbMo85KqlQUn62/PCIjwczViw5lbotzoXy/nPrn4qjDMmx/fspuUnjBtA==",
"dev": true
},
"debug": { "debug": {
"version": "3.2.7", "version": "3.2.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
-5
View File
@@ -21,14 +21,9 @@
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/cli": "^4.3.5", "@tailwindcss/cli": "^4.3.5",
"daisyui": "^5.8.2",
"npm-watch": "^0.11.0", "npm-watch": "^0.11.0",
"rolldown": "^1.3.3", "rolldown": "^1.3.3",
"tailwindcss": "^4.3.5", "tailwindcss": "^4.3.5",
"typescript": "^6.0.3" "typescript": "^6.0.3"
},
"dependencies": {
"@types/alpinejs": "^3.7.2",
"alpinejs": "^3.12.2"
} }
} }
+26 -5
View File
@@ -1,13 +1,34 @@
import Alpine from 'alpinejs'
import {localeMapper} from "./helpers/localemapper.ts"; import {localeMapper} from "./helpers/localemapper.ts";
const getFlagEmoji = (locale: string) => { const getFlagEmoji = (locale: string) => {
const countryCode = localeMapper(locale) const countryCode = localeMapper(locale)
return String.fromCodePoint(...[...countryCode.toUpperCase()].map(x => 0x1f1a5 + x.charCodeAt(0))) return String.fromCodePoint(...[...countryCode.toUpperCase()].map(x => 0x1f1a5 + x.charCodeAt(0)))
} }
window.plugi = {} document.querySelectorAll<HTMLElement>("[data-locale-flag]").forEach((flag) => {
window.plugi.getFlagEmoji = getFlagEmoji const locale = flag.dataset.locale
if (locale) {
flag.textContent = getFlagEmoji(locale)
}
})
Alpine.start() document.querySelectorAll<HTMLElement>("[data-gallery]").forEach((gallery) => {
if (gallery.dataset.galleryLightbox !== "true") {
return
}
const dialog = gallery.querySelector<HTMLDialogElement>("[data-gallery-dialog]")
const lightboxImage = dialog?.querySelector<HTMLImageElement>("[data-gallery-lightbox-image]")
if (!dialog || !lightboxImage || typeof dialog.showModal !== "function") {
return
}
gallery.querySelectorAll<HTMLAnchorElement>("[data-gallery-trigger]").forEach((trigger) => {
trigger.addEventListener("click", (event) => {
event.preventDefault()
lightboxImage.src = trigger.href
lightboxImage.alt = trigger.querySelector("img")?.alt ?? ""
dialog.showModal()
})
})
})
-1
View File
@@ -1,2 +1 @@
@import "tailwindcss"; @import "tailwindcss";
@plugin "daisyui";