554 lines
23 KiB
PHP
554 lines
23 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Support;
|
|
|
|
use Illuminate\Database\Eloquent\Model as Eloquent;
|
|
use Illuminate\Support\Str;
|
|
use IriksIT\Manager\Models\BlockTemplate;
|
|
use IriksIT\Manager\Models\Page;
|
|
use IriksIT\Manager\Support\Blocks\CoreTypes;
|
|
|
|
/**
|
|
* The blocks of a page: an ordered list of `{id, type, data, style, hidden}`. A block type has fields (the types of `Fields`) and
|
|
* style options chosen from sets the site defines (`manager.blocks.tokens`); the site draws a block with its own view or component.
|
|
*
|
|
* A site adds block types in `manager.blocks.types` (or `Blocks::register()`), and replaces a shipped one by using its key.
|
|
* `Blocks::for('home')` is what the public site reads; the manager screen reads `Blocks::catalogue()` and `Blocks::forEditor()`.
|
|
* See `docs/design/page-builder.md` in the repository.
|
|
*/
|
|
final class Blocks
|
|
{
|
|
/** @var array<string, array<string, mixed>> */
|
|
private static array $extra = [];
|
|
|
|
/** @param array<string, mixed> $definition see `Blocks\CoreTypes` */
|
|
public static function register(string $key, array $definition): void
|
|
{
|
|
self::$extra[$key] = $definition;
|
|
}
|
|
|
|
public static function forgetRegistered(): void
|
|
{
|
|
self::$extra = [];
|
|
}
|
|
|
|
/** The choices of every style option: what ships, over which the site sets its own. @return array<string, array<string, string>> */
|
|
public static function tokens(): array
|
|
{
|
|
$out = CoreTypes::tokens();
|
|
|
|
foreach ((array) config('manager.blocks.tokens', []) as $name => $choices) {
|
|
if (is_string($name) && is_array($choices) && $choices !== []) {
|
|
$out[$name] = array_map('strval', $choices);
|
|
}
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* Every block type that is available now: a type of a feature that is off is not there.
|
|
*
|
|
* @return array<string, array{key: string, label: string, simple_label: ?string, group: string, icon: string, style: list<string>, resolves: ?string, fields: array<string, array<string, mixed>>}>
|
|
*/
|
|
public static function types(): array
|
|
{
|
|
$definitions = array_replace(CoreTypes::all(), (array) config('manager.blocks.types', []), self::$extra);
|
|
$tokens = self::tokens();
|
|
$out = [];
|
|
|
|
foreach ($definitions as $key => $definition) {
|
|
if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) || ! is_array($definition)) {
|
|
continue;
|
|
}
|
|
|
|
if (isset($definition['feature']) && ! Features::on((string) $definition['feature'])) {
|
|
continue;
|
|
}
|
|
|
|
$fields = (array) ($definition['fields'] ?? []);
|
|
|
|
// A block that shows the records of a list offers the lists the site has.
|
|
if (($definition['resolves'] ?? null) === 'list' && isset($fields['source'])) {
|
|
$fields['source']['options'] = array_map(fn (array $resource) => $resource['label'], Resources::all());
|
|
}
|
|
|
|
$out[$key] = [
|
|
'key' => $key,
|
|
'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
|
'simple_label' => Fields::simpleText($definition, 'label'),
|
|
'group' => (string) ($definition['group'] ?? 'Content'),
|
|
'icon' => (string) ($definition['icon'] ?? $key),
|
|
'style' => array_values(array_filter((array) ($definition['style'] ?? []), fn ($name) => is_string($name) && isset($tokens[$name]))),
|
|
'resolves' => isset($definition['resolves']) ? (string) $definition['resolves'] : null,
|
|
'fields' => Fields::normalize($fields),
|
|
];
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* What the screen needs to offer the types (the fields as the form builds them, and the style choices).
|
|
*
|
|
* @param ?list<string> $allowed null: every type
|
|
* @return list<array<string, mixed>>
|
|
*/
|
|
public static function catalogue(?array $allowed = null): array
|
|
{
|
|
$tokens = self::tokens();
|
|
$out = [];
|
|
|
|
foreach (self::types() as $key => $type) {
|
|
if ($allowed !== null && ! in_array($key, $allowed, true)) {
|
|
continue;
|
|
}
|
|
|
|
$out[] = [
|
|
'key' => $key,
|
|
'label' => $type['label'],
|
|
'simple_label' => $type['simple_label'],
|
|
'group' => $type['group'],
|
|
'icon' => $type['icon'],
|
|
'fields' => Fields::described($type['fields']),
|
|
'style' => array_map(fn (string $name) => ['key' => $name, 'options' => $tokens[$name], 'default' => array_key_first($tokens[$name])], $type['style']),
|
|
];
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* What may be saved: unknown types and types a page does not allow are dropped, the data is cleaned by the fields of the type, the
|
|
* style options are kept to the choices there are, and every block gets an id.
|
|
*
|
|
* @param array<array-key, mixed> $input
|
|
* @param ?list<string> $allowed
|
|
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, hidden: bool}>
|
|
*/
|
|
public static function clean(array $input, ?array $allowed = null): array
|
|
{
|
|
$types = self::types();
|
|
$max = max(1, (int) config('manager.blocks.max', 100));
|
|
$out = [];
|
|
|
|
foreach ($input as $block) {
|
|
$type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null;
|
|
|
|
if ($type === null || ! isset($types[$type]) || ($allowed !== null && ! in_array($type, $allowed, true))) {
|
|
continue;
|
|
}
|
|
|
|
$out[] = [
|
|
'id' => self::id($block['id'] ?? null),
|
|
'type' => $type,
|
|
'data' => Fields::clean($types[$type]['fields'], (array) ($block['data'] ?? [])),
|
|
'style' => self::style($types[$type], (array) ($block['style'] ?? [])),
|
|
'hidden' => filter_var($block['hidden'] ?? false, FILTER_VALIDATE_BOOLEAN),
|
|
];
|
|
|
|
if (count($out) >= $max) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* Validation rules for the blocks of a request, keyed `blocks`, `blocks.<i>.…`.
|
|
*
|
|
* @param array<array-key, mixed> $input
|
|
* @param ?list<string> $allowed
|
|
* @return array<string, mixed>
|
|
*/
|
|
public static function rules(array $input, ?array $allowed = null, bool $bindings = false): array
|
|
{
|
|
$types = self::types();
|
|
$rules = [
|
|
'blocks' => ['nullable', 'array', 'max:'.max(1, (int) config('manager.blocks.max', 100))],
|
|
'blocks.*' => ['array'],
|
|
'blocks.*.type' => ['required', 'string', 'max:40'],
|
|
'blocks.*.id' => ['nullable', 'string', 'max:40'],
|
|
'blocks.*.hidden' => ['boolean'],
|
|
'blocks.*.style' => ['nullable', 'array'],
|
|
'blocks.*.data' => ['nullable', 'array'],
|
|
];
|
|
|
|
foreach ($input as $index => $block) {
|
|
$type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null;
|
|
|
|
if ($type !== null && isset($types[$type]) && ($allowed === null || in_array($type, $allowed, true))) {
|
|
$fieldRules = Fields::rules($types[$type]['fields'], "blocks.{$index}.data.");
|
|
$rules = [...$rules, ...($bindings ? self::allowBindings($fieldRules) : $fieldRules)];
|
|
}
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
/**
|
|
* For a page layout: an address or picture may also begin with `{record.<field>}` (the value is checked when it is drawn).
|
|
*
|
|
* @param array<string, list<mixed>> $rules
|
|
* @return array<string, list<mixed>>
|
|
*/
|
|
private static function allowBindings(array $rules): array
|
|
{
|
|
$address = 'regex:'.Fields::ADDRESS;
|
|
$binding = '#^\{record\.[a-z][a-z0-9_]*\}[^\s<>"\']*$#i';
|
|
|
|
return array_map(fn (array $list) => array_map(fn ($rule) => $rule === $address
|
|
? function (string $attribute, mixed $value, \Closure $fail) use ($binding): void {
|
|
if (! is_string($value) || (preg_match(Fields::ADDRESS, $value) !== 1 && preg_match($binding, $value) !== 1)) {
|
|
$fail(__('The :attribute must be a web address, a path of the site or {record.<field>}.', ['attribute' => $attribute]));
|
|
}
|
|
}
|
|
: $rule, $list), $rules);
|
|
}
|
|
|
|
/**
|
|
* The stored blocks as the editor shows them: every block of a known type, hidden ones too, every field with its value.
|
|
*
|
|
* @param array<array-key, mixed> $stored
|
|
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, hidden: bool}>
|
|
*/
|
|
public static function forEditor(array $stored): array
|
|
{
|
|
$types = self::types();
|
|
$out = [];
|
|
|
|
foreach ($stored as $block) {
|
|
$type = is_array($block) && is_string($block['type'] ?? null) ? $block['type'] : null;
|
|
|
|
if ($type === null || ! isset($types[$type])) {
|
|
continue;
|
|
}
|
|
|
|
$out[] = [
|
|
'id' => self::id($block['id'] ?? null),
|
|
'type' => $type,
|
|
'data' => Fields::values($types[$type]['fields'], (array) ($block['data'] ?? [])),
|
|
'style' => self::style($types[$type], (array) ($block['style'] ?? [])),
|
|
'hidden' => (bool) ($block['hidden'] ?? false),
|
|
];
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* What the public site draws for a page: the visible blocks in order, each with its data (defaults filled in) and style, and, for a
|
|
* block that shows a list, the records of that list. A block of a feature that is off, or of a list that is gone, is left out.
|
|
*
|
|
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, items?: list<array<string, mixed>>}>
|
|
*/
|
|
public static function for(string $slug): array
|
|
{
|
|
// A person editing the page sees the blocks of the preview they asked for, not the saved ones.
|
|
$saved = Page::query()->where('slug', $slug)->first()?->blocks;
|
|
$stored = BlockPreview::current($slug) ?? (is_array($saved) ? $saved : []);
|
|
|
|
return self::render($stored, null);
|
|
}
|
|
|
|
/**
|
|
* The page of one record (a service, a project): the blocks of the page layout of its list (`manager.resources.<key>.template`),
|
|
* with `{record.<field>}` in the text, address and picture fields filled in from the record, as `for()` gives them. A `cards` block
|
|
* can show only what belongs to the record (`match_list` = `match_record`) and leave the record itself out. Empty when the list
|
|
* has no page layout, is off, or the record is not active.
|
|
*
|
|
* @param Eloquent|array{id: mixed, values: array<string, mixed>} $record a model of the list, or `Resources::row()`
|
|
* @return list<array{id: string, type: string, data: array<string, mixed>, style: array<string, string>, items?: list<array<string, mixed>>}>
|
|
*/
|
|
public static function forRecord(string $resource, Eloquent|array $record): array
|
|
{
|
|
$definition = Resources::find($resource);
|
|
|
|
if ($definition === null || $definition['template'] === false) {
|
|
return [];
|
|
}
|
|
|
|
$row = $record instanceof Eloquent ? Resources::row($definition, $record) : $record;
|
|
|
|
if (! ($row['values']['is_active'] ?? true)) {
|
|
return [];
|
|
}
|
|
|
|
$template = BlockTemplate::query()->where('resource', $resource)->first();
|
|
$allowed = self::templateTypes($resource);
|
|
|
|
return self::render(is_array($template?->blocks) ? $template->blocks : [], ['resource' => $resource, 'row' => $row], $allowed);
|
|
}
|
|
|
|
/**
|
|
* The block types the page layout of a list may use (`manager.resources.<key>.template`: `true` for all, or a list). Empty without one.
|
|
*
|
|
* @return list<string>
|
|
*/
|
|
public static function templateTypes(string $resource): array
|
|
{
|
|
$allowed = Resources::find($resource)['template'] ?? false;
|
|
$known = array_keys(self::types());
|
|
|
|
if ($allowed === true) {
|
|
return $known;
|
|
}
|
|
|
|
return is_array($allowed) ? array_values(array_intersect($known, $allowed)) : [];
|
|
}
|
|
|
|
/**
|
|
* @param array<array-key, mixed> $stored
|
|
* @param ?array{resource: string, row: array{id: mixed, values: array<string, mixed>}} $context the record a page layout is drawn for
|
|
* @param ?list<string> $allowed
|
|
* @return list<array<string, mixed>>
|
|
*/
|
|
private static function render(array $stored, ?array $context, ?array $allowed = null): array
|
|
{
|
|
$types = self::types();
|
|
$out = [];
|
|
|
|
foreach (self::forEditor($stored) as $block) {
|
|
if ($block['hidden'] || ($allowed !== null && ! in_array($block['type'], $allowed, true))) {
|
|
continue;
|
|
}
|
|
|
|
$fields = $types[$block['type']]['fields'];
|
|
$data = $context === null ? $block['data'] : self::bind($fields, $block['data'], $context['row']);
|
|
$entry = ['id' => $block['id'], 'type' => $block['type'], 'data' => self::withHtml($fields, $data), 'style' => $block['style']];
|
|
|
|
if ($types[$block['type']]['resolves'] === 'list') {
|
|
$items = self::items($data, $context);
|
|
|
|
if ($items === null) {
|
|
continue;
|
|
}
|
|
|
|
$entry['items'] = $items;
|
|
}
|
|
|
|
$out[] = $entry;
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* `{record.<field>}` in the text, address and picture fields of a block (also in a list or a repeater) becomes the value of that
|
|
* field of the record, or nothing when the record has no such field. The value is text like any other: it is escaped when it is drawn,
|
|
* Markdown cannot carry HTML, and an address or picture that comes out unsafe becomes `#` (an address) or nothing (a picture).
|
|
*
|
|
* @param array<string, array<string, mixed>> $fields normalized
|
|
* @param array<string, mixed> $data
|
|
* @param array{id: mixed, values: array<string, mixed>} $row
|
|
* @return array<string, mixed>
|
|
*/
|
|
private static function bind(array $fields, array $data, array $row): array
|
|
{
|
|
$values = ['id' => $row['id']] + $row['values'];
|
|
$fill = function (string $text) use ($values): string {
|
|
return (string) preg_replace_callback('/\{record\.([a-z][a-z0-9_]*)\}/', function (array $match) use ($values): string {
|
|
$value = $values[$match[1]] ?? null;
|
|
|
|
return is_scalar($value) ? (is_bool($value) ? ($value ? '1' : '') : (string) $value) : '';
|
|
}, $text);
|
|
};
|
|
|
|
foreach ($fields as $key => $field) {
|
|
$value = $data[$key] ?? null;
|
|
|
|
switch ($field['type']) {
|
|
case 'text': case 'textarea': case 'markdown':
|
|
$data[$key] = is_string($value) ? $fill($value) : $value;
|
|
break;
|
|
case 'url': case 'media':
|
|
if (is_string($value) && str_contains($value, '{record.')) {
|
|
$address = self::safeUrl($fill($value));
|
|
$data[$key] = $address === '#' && $field['type'] === 'media' ? '' : $address;
|
|
}
|
|
break;
|
|
case 'list': case 'media_list':
|
|
$data[$key] = is_array($value) ? array_map(function ($item) use ($fill, $field) {
|
|
if (! is_string($item) || ! str_contains($item, '{record.')) {
|
|
return $item;
|
|
}
|
|
|
|
$filled = $fill($item);
|
|
|
|
return $field['type'] === 'media_list' ? (self::safeUrl($filled) === '#' ? '' : $filled) : $filled;
|
|
}, $value) : $value;
|
|
break;
|
|
case 'repeater':
|
|
$data[$key] = is_array($value) ? array_map(fn ($row2) => is_array($row2) ? self::bind($field['items'], $row2, $row) : $row2, $value) : $value;
|
|
break;
|
|
}
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
/**
|
|
* Markdown fields come with their safe HTML next to them: `body` gets a `body_html`. Raw HTML in the text is escaped by `Markdown`, so a
|
|
* frontend may print `*_html` as it is and must print everything else as text. The same goes for a repeater with a markdown field.
|
|
*
|
|
* @param array<string, array<string, mixed>> $fields normalized
|
|
* @param array<string, mixed> $data
|
|
* @return array<string, mixed>
|
|
*/
|
|
public static function withHtml(array $fields, array $data): array
|
|
{
|
|
foreach ($fields as $key => $field) {
|
|
if ($field['type'] === 'markdown') {
|
|
$data[$key.'_html'] = Markdown::toHtml((string) ($data[$key] ?? ''));
|
|
} elseif ($field['type'] === 'repeater' && is_array($data[$key] ?? null)) {
|
|
$data[$key] = array_map(fn ($row) => is_array($row) ? self::withHtml($field['items'], $row) : $row, $data[$key]);
|
|
}
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
/** The view that draws a block type: one of the site (`resources/views/blocks/<type>.blade.php`), else the package's. Null when there is none. */
|
|
public static function view(string $type): ?string
|
|
{
|
|
if (preg_match('/^[a-z][a-z0-9_]{0,39}$/', $type) !== 1) {
|
|
return null;
|
|
}
|
|
|
|
foreach (["blocks.{$type}", "manager::blocks.{$type}"] as $view) {
|
|
if (view()->exists($view)) {
|
|
return $view;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/** CSS classes for the style options of a block: `mb--background-dark mb--width-wide`. */
|
|
public static function classes(array $style): string
|
|
{
|
|
$classes = [];
|
|
|
|
foreach ($style as $name => $value) {
|
|
$classes[] = 'mb--'.preg_replace('/[^a-z0-9_-]/i', '', (string) $name).'-'.preg_replace('/[^a-z0-9_-]/i', '', (string) $value);
|
|
}
|
|
|
|
return implode(' ', $classes);
|
|
}
|
|
|
|
/** An address that is safe in an `href` or `src`: http(s), a path, `mailto:`, `tel:` or an anchor; anything else becomes `#`. */
|
|
public static function safeUrl(mixed $url): string
|
|
{
|
|
$url = is_string($url) ? trim($url) : '';
|
|
|
|
// No quote, bracket, backslash or space either: the address may end up in an attribute or in a CSS `url()`.
|
|
return preg_match('~^(https?://|/(?!/)|#|mailto:|tel:)~i', $url) === 1 && preg_match('~[\s"\'()<>\\\\]~', $url) !== 1 ? $url : '#';
|
|
}
|
|
|
|
/**
|
|
* Structured data for search engines that the blocks of a page give: a `faq` block is a `FAQPage`. Print each as JSON in
|
|
* `<script type="application/ld+json">` (the Blade view of the `faq` block does it itself).
|
|
*
|
|
* @param list<array<string, mixed>> $blocks from `for()`
|
|
* @return list<array<string, mixed>>
|
|
*/
|
|
public static function structuredData(array $blocks): array
|
|
{
|
|
$questions = [];
|
|
|
|
foreach ($blocks as $block) {
|
|
if ($block['type'] !== 'faq') {
|
|
continue;
|
|
}
|
|
|
|
foreach ((array) ($block['data']['items'] ?? []) as $item) {
|
|
if (($item['question'] ?? '') !== '' && ($item['answer'] ?? '') !== '') {
|
|
$questions[] = ['@type' => 'Question', 'name' => $item['question'], 'acceptedAnswer' => ['@type' => 'Answer', 'text' => $item['answer']]];
|
|
}
|
|
}
|
|
}
|
|
|
|
return $questions === [] ? [] : [['@context' => 'https://schema.org', '@type' => 'FAQPage', 'mainEntity' => $questions]];
|
|
}
|
|
|
|
/**
|
|
* The records of the list a block shows: the active ones, as many as the block asks. Null when the list does not exist (or its feature is off).
|
|
* On the page of a record the block may show only those that belong to it (`match_list` equals `match_record`, both fields the definitions
|
|
* know, `id` included) and leave the record itself out; a filter that names a field that does not exist shows nothing, not everything.
|
|
*
|
|
* @param array<string, mixed> $data
|
|
* @param ?array{resource: string, row: array{id: mixed, values: array<string, mixed>}} $context
|
|
* @return ?list<array<string, mixed>>
|
|
*/
|
|
private static function items(array $data, ?array $context = null): ?array
|
|
{
|
|
$resource = Resources::find((string) ($data['source'] ?? ''));
|
|
|
|
if ($resource === null) {
|
|
return null;
|
|
}
|
|
|
|
$count = max(1, min(24, (int) ($data['count'] ?? 3) ?: 3));
|
|
$listField = trim((string) ($data['match_list'] ?? ''));
|
|
$recordField = trim((string) ($data['match_record'] ?? ''));
|
|
$filtered = $listField !== '' || $recordField !== '';
|
|
$wanted = null;
|
|
|
|
if ($filtered) {
|
|
$values = $context === null ? [] : ['id' => $context['row']['id']] + $context['row']['values'];
|
|
$known = ($listField === 'id' || isset($resource['fields'][$listField])) && array_key_exists($recordField, $values);
|
|
$wanted = $known && is_scalar($values[$recordField]) && (string) $values[$recordField] !== '' ? (string) $values[$recordField] : false;
|
|
}
|
|
|
|
if ($wanted === false) {
|
|
return [];
|
|
}
|
|
|
|
$items = [];
|
|
|
|
foreach (Resources::query($resource)->limit(200)->get() as $model) {
|
|
$row = Resources::row($resource, $model);
|
|
|
|
if (! ($row['values']['is_active'] ?? true) || count($items) >= $count) {
|
|
continue;
|
|
}
|
|
|
|
if ($context !== null && ($data['skip_this'] ?? true) && $resource['key'] === $context['resource'] && (string) $row['id'] === (string) $context['row']['id']) {
|
|
continue;
|
|
}
|
|
|
|
if ($wanted !== null) {
|
|
$mine = $listField === 'id' ? $row['id'] : ($row['values'][$listField] ?? null);
|
|
|
|
if (! is_scalar($mine) || (string) $mine !== $wanted) {
|
|
continue;
|
|
}
|
|
}
|
|
|
|
$items[] = ['id' => $row['id']] + $row['values'];
|
|
}
|
|
|
|
return $items;
|
|
}
|
|
|
|
/** @param array<string, mixed> $type */
|
|
private static function style(array $type, array $input): array
|
|
{
|
|
$tokens = self::tokens();
|
|
$out = [];
|
|
|
|
foreach ($type['style'] as $name) {
|
|
$value = $input[$name] ?? null;
|
|
$out[$name] = is_string($value) && isset($tokens[$name][$value]) ? $value : (string) array_key_first($tokens[$name]);
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
private static function id(mixed $given): string
|
|
{
|
|
return is_string($given) && preg_match('/^[0-9a-z]{26}$/i', $given) === 1 ? strtolower($given) : strtolower((string) Str::ulid());
|
|
}
|
|
}
|