diff --git a/Build/Scripts/codemod-collection-markers.php b/Build/Scripts/codemod-collection-markers.php new file mode 100644 index 000000000..e54c5471f --- /dev/null +++ b/Build/Scripts/codemod-collection-markers.php @@ -0,0 +1,161 @@ + over a Collection field whose body renders exactly one root + * element per entry gets the f:mark.item ViewHelper of Visual Editor + * Enhancements on that root, so the editor can find the entry ("row") on the + * page. Outside edit mode the ViewHelper renders nothing: published pages + * stay byte-identical. The rules live in Classes/Templates/CollectionMarker + * (shared with Tests/Unit/ContentBlockCollectionMarkerTest.php, which is the + * source of truth for the counts); the loops that cannot carry a marker are + * listed with their reasons in CollectionMarkerExceptions. + * + * Usage: + * php Build/Scripts/codemod-collection-markers.php add missing markers + * php Build/Scripts/codemod-collection-markers.php --dry-run show what would change + * php Build/Scripts/codemod-collection-markers.php --check exit 1 on unmarked, unlisted loops + * options: --block= (one Content Block), --path= (default ContentBlocks/ContentElements) + * + * Idempotent: a second run changes nothing. + */ + +use Webconsulting\Desiderio\Templates\CollectionMarker\CollectionLoop; +use Webconsulting\Desiderio\Templates\CollectionMarker\CollectionLoopAnalyzer; +use Webconsulting\Desiderio\Templates\CollectionMarker\CollectionMarkerExceptions; +use Webconsulting\Desiderio\Templates\CollectionMarker\CollectionMarkerRewriter; + +$root = dirname(__DIR__, 2); +require $root . '/vendor/autoload.php'; + +$options = getopt('', ['check', 'dry-run', 'block:', 'path:', 'help']); +if (isset($options['help'])) { + fwrite(STDOUT, "php Build/Scripts/codemod-collection-markers.php [--check|--dry-run] [--block=] [--path=]\n"); + exit(0); +} +$check = isset($options['check']); +$dryRun = isset($options['dry-run']); +$path = is_string($options['path'] ?? null) ? $options['path'] : $root . '/ContentBlocks/ContentElements'; +$onlyBlock = is_string($options['block'] ?? null) ? $options['block'] : null; + +$directories = glob(rtrim($path, '/') . '/*', GLOB_ONLYDIR) ?: []; +$analyzer = new CollectionLoopAnalyzer(); +$exceptions = new CollectionMarkerExceptions(); +$rewriter = new CollectionMarkerRewriter(); + +$counts = ['blocks' => 0, 'loops' => 0, 'nested' => 0, 'marked' => 0, 'exceptions' => 0, 'added' => 0, 'files' => 0]; +$rules = []; +$failures = []; +$usedExceptions = []; + +foreach ($directories as $directory) { + $block = basename($directory); + if ($onlyBlock !== null && $block !== $onlyBlock) { + continue; + } + if (!is_file($directory . '/config.yaml') || !is_file($directory . '/templates/frontend.html')) { + continue; + } + $analysis = $analyzer->analyzeBlock($directory, $exceptions); + if ($analysis->loops === []) { + continue; + } + ++$counts['blocks']; + $template = $directory . '/templates/frontend.html'; + + if (!$check) { + $result = $rewriter->rewrite($analysis); + foreach ($result['errors'] as $error) { + $failures[] = $block . ': ' . $error; + } + if ($result['edits'] !== []) { + ++$counts['files']; + $counts['added'] += count($result['edits']); + fwrite(STDOUT, ($dryRun ? '[dry-run] ' : '') . $block . '/templates/frontend.html: +' . count($result['edits']) . " marker(s)\n"); + foreach ($result['edits'] as $note) { + fwrite(STDOUT, ' ' . $note . "\n"); + } + if ($dryRun) { + fwrite(STDOUT, lineDiff($analysis->document->source, $result['source'])); + } else { + file_put_contents($template, $result['source']); + } + // Re-read what was (or would be) written: the rewrite must leave a + // template the parser reads cleanly and in which every loop passes. + $analysis = $analyzer->analyze($block, $result['source'], $analysis->fields, $exceptions); + } + } + + foreach ($analysis->failures() as $failure) { + $failures[] = $block . ': ' . $failure; + } + foreach ($analysis->loops as $loop) { + ++$counts['loops']; + if ($loop->field->parent !== null) { + ++$counts['nested']; + } + if ($loop->exception !== null) { + ++$counts['exceptions']; + $usedExceptions[$loop->key() . '#' . $loop->occurrence] = true; + $usedExceptions[$loop->key()] = true; + continue; + } + if ($loop->isMarked()) { + ++$counts['marked']; + foreach ($loop->roots as $rootNode) { + $rule = CollectionLoop::ruleFor($rootNode); + if ($rule === CollectionLoop::RULE_COMPONENT && str_contains((string)$rootNode->attribute('attributes'), 'f:merge(')) { + $rule .= ' (merged)'; + } + $rules[$rule] = ($rules[$rule] ?? 0) + 1; + } + } + } +} + +if ($onlyBlock === null) { + foreach (array_keys($exceptions->all()) as $key) { + if (!isset($usedExceptions[$key])) { + $failures[] = 'CollectionMarkerExceptions: "' . $key . '" matches no Collection loop (stale entry)'; + } + } +} + +ksort($rules); +fwrite(STDOUT, sprintf( + "%d Collection loops in %d Content Blocks (%d over nested Collections): %d marked, %d listed exceptions%s\n", + $counts['loops'], + $counts['blocks'], + $counts['nested'], + $counts['marked'], + $counts['exceptions'], + $check ? '' : sprintf('; %s %d marker(s) in %d file(s)', $dryRun ? 'would add' : 'added', $counts['added'], $counts['files']), +)); +foreach ($rules as $rule => $count) { + fwrite(STDOUT, sprintf(" marked roots, %s: %d\n", $rule, $count)); +} +if ($failures !== []) { + fwrite(STDERR, count($failures) . " problem(s):\n " . implode("\n ", $failures) . "\n"); + exit(1); +} +exit(0); + +/** + * The changed lines, "-" before and "+" after (the rewrite never adds or + * removes a line, so lines pair up by number). + */ +function lineDiff(string $before, string $after): string +{ + $old = explode("\n", $before); + $new = explode("\n", $after); + $out = ''; + foreach ($new as $index => $line) { + if (($old[$index] ?? null) !== $line) { + $out .= sprintf(" %5d - %s\n %5d + %s\n", $index + 1, trim((string)($old[$index] ?? '')), $index + 1, trim($line)); + } + } + return $out; +} diff --git a/Build/Scripts/compare-element-renders.php b/Build/Scripts/compare-element-renders.php new file mode 100644 index 000000000..f16f33def --- /dev/null +++ b/Build/Scripts/compare-element-renders.php @@ -0,0 +1,93 @@ + [--edit-mode --cookie=] + * php Build/Scripts/compare-element-renders.php compare + * + * is the output of `vendor/bin/typo3 desiderio:library:urls --json` + * (for example in the disposable app of Build/CiApp). Capture the old state, + * flush caches, capture the new one, compare. EXT:form renders a random + * honeypot field and signed form state on every request; those values are + * masked, everything else must match byte for byte. Two captures of the same + * state compare identical, which shows the masking hides no real difference. + */ + +$command = $argv[1] ?? ''; +if ($command === 'capture' && isset($argv[2], $argv[3])) { + $options = getopt('', ['edit-mode', 'cookie:'], $restIndex); + exit(capture($argv[2], $argv[3], isset($options['edit-mode']), is_string($options['cookie'] ?? null) ? $options['cookie'] : null)); +} +if ($command === 'compare' && isset($argv[2], $argv[3])) { + exit(compare($argv[2], $argv[3])); +} +fwrite(STDERR, "usage: capture [--edit-mode --cookie=] | compare \n"); +exit(2); + +function capture(string $urlsFile, string $directory, bool $editMode, ?string $cookie): int +{ + $decoded = json_decode((string)file_get_contents($urlsFile), true); + $elements = is_array($decoded) ? ($decoded['elements'] ?? $decoded) : []; + if (!is_dir($directory) && !mkdir($directory, 0777, true)) { + fwrite(STDERR, "cannot create $directory\n"); + return 2; + } + $failed = 0; + foreach ($elements as $element) { + $url = (string)$element['url'] . ($editMode ? '&editMode=1' : ''); + $handle = curl_init($url); + curl_setopt_array($handle, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 120]); + if ($cookie !== null) { + curl_setopt($handle, CURLOPT_COOKIE, 'be_typo_user=' . $cookie); + } + $body = (string)curl_exec($handle); + $status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE); + if ($status !== 200) { + ++$failed; + fwrite(STDERR, $element['cType'] . ": HTTP $status\n"); + } + file_put_contents($directory . '/' . $element['cType'] . '-' . $element['uid'] . '.html', $body); + } + fwrite(STDOUT, count($elements) . " previews captured, $failed not HTTP 200\n"); + return $failed === 0 ? 0 : 1; +} + +function compare(string $left, string $right): int +{ + $files = array_map(basename(...), glob($left . '/*.html') ?: []); + $identical = $masked = 0; + $different = []; + foreach ($files as $file) { + $a = (string)file_get_contents($left . '/' . $file); + $b = @file_get_contents($right . '/' . $file); + if ($b === false) { + $different[] = $file . ' (missing)'; + } elseif ($a === $b) { + ++$identical; + } elseif (maskFormTokens($a) === maskFormTokens($b)) { + ++$masked; + } else { + $different[] = $file; + } + } + fwrite(STDOUT, sprintf("%d previews: %d byte-identical, %d identical after masking EXT:form tokens, %d different\n", count($files), $identical, $masked, count($different))); + foreach ($different as $file) { + fwrite(STDOUT, ' ' . $file . "\n"); + } + return $different === [] ? 0 : 1; +} + +function maskFormTokens(string $html): string +{ + if (preg_match_all('/ 0) { + foreach ($matches[1] as $index => $honeypot) { + $html = str_replace($honeypot, 'HONEYPOT' . $index, $html); + } + } + return (string)preg_replace('/(name="[^"]*(?:__state|__trustedProperties|__referrer\]\[[^"]*|__session)[^"]*" value=")[^"]*"/', '$1MASKED"', $html); +} diff --git a/Build/Scripts/sync-shadcn-fluid-primitives.php b/Build/Scripts/sync-shadcn-fluid-primitives.php index 22e7e2bfc..9d842e08f 100644 --- a/Build/Scripts/sync-shadcn-fluid-primitives.php +++ b/Build/Scripts/sync-shadcn-fluid-primitives.php @@ -554,6 +554,21 @@ function renderAttributesArgument(): string . '' . "\n"; } +/** + * The same argument for a component whose markup must not change: the comment + * continues the previous argument's line, so no extra newline is rendered. + */ +function renderBridgedAttributesArgument(): string +{ + return "\n" + . " `attributes` carries what a row or control needs beyond the shadcn contract\n" + . " (aria-*, data-* hooks, the Visual Editor's row markers). Keys are\n" + . " template-authored, values are escaped. The comment bridges two lines so\n" + . " the extra argument emits no whitespace.\n" + . "" + . '' . "\n"; +} + function extraAttributes(): string { return ' {attributeName}="{attributeValue}"'; @@ -1121,7 +1136,9 @@ function renderTabsTrigger(array $recipe, string $header): string . '' . "\n" . '' . "\n" . '' . "\n" - . '' . "\n\n" + . '' + . renderBridgedAttributesArgument() + . "\n" . '' . "\n" . ' ' . "\n" @@ -1147,7 +1164,9 @@ function renderTabsContent(array $recipe, string $header): string . '' . "\n" . '' . "\n" . '' . "\n" - . '' . "\n\n" + . '' + . renderBridgedAttributesArgument() + . "\n" . '' . "\n" . ' ' . "\n" . '' . "\n"; diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a96553a9..54fa27b31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ All notable changes to **webconsulting/desiderio** are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/) and the project adheres to [Semantic Versioning](https://semver.org/). +## [4.36.0] — unreleased + +### Added + +- Collection row markers for the Visual Editor: every `` over a Content Block Collection marks each entry's root element with `f:mark.item` (Visual Editor Enhancements 1.6+), so the editor highlights, dims and — from Visual Editor Enhancements 1.7 — offers row controls on the page. 185 of 189 collection loops in 156 elements carry markers (149 HTML roots, 39 component roots, 2 of them merged with existing `attributes`), including the 13 loops over nested Collections; 4 loops without one element per entry are listed exceptions with reasons (chart, chart-contribution and chart-donut computation/JSON loops, the gallery's featured view). Outside edit mode the marker renders nothing: all 263 element previews render byte-identical to 4.34.1 (checked before this branch was rebased onto 4.35.0). +- `Build/Scripts/codemod-collection-markers.php` adds missing markers (`--dry-run`, `--check`; idempotent) with the rules in `Classes/Templates/CollectionMarker`; `ContentBlockCollectionMarkerTest` gates every loop. Guide: Developer → Collection row markers. +- `CheckedListItem`, `TableRow`, `TableCell`, `FeatureItem`, `TabsTrigger` and `TabsContent` accept an `attributes` argument and spread it onto their root tag, like `Card`. + +### Changed + +- Requires `webconsulting/visual-editor-enhancements` `^1.6` (was `^0.8 || ^1.0`). Where that extension is not loaded, desiderio registers a stand-in `f:mark.item` that renders nothing, so templates never meet an unknown ViewHelper. ## [4.35.0] — 2026-11-08 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 728769128..199096161 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -80,6 +80,12 @@ Desiderio targets **TYPO3 14.3.6+ and PHP 8.4–8.5**. Use the Collection must not keep its own `fields:` (they are inert). The audit gates all of this; the [collection guide](Documentation/Developer/CollectionTableConsolidation.rst) explains the shared models and upgrade procedure. +- Every `` over a Content Block `Collection` marks each entry's root + element with `f:mark.item` (the Visual Editor's row marker, invisible + outside edit mode). Run `php Build/Scripts/codemod-collection-markers.php` + after template changes; `--check` and `ContentBlockCollectionMarkerTest` + fail on unmarked loops that are not listed exceptions. See the + [row marker guide](Documentation/Developer/CollectionRowMarkers.rst). - Content Block image fields render through `` or `f:uri.image()`. Pass custom `data-*` attributes through structured Fluid arguments such as `data="{d-gallery-main: 'true'}"`; do not hand-write literal `` tags for diff --git a/Classes/Templates/CollectionMarker/BlockAnalysis.php b/Classes/Templates/CollectionMarker/BlockAnalysis.php new file mode 100644 index 000000000..dc7826dc7 --- /dev/null +++ b/Classes/Templates/CollectionMarker/BlockAnalysis.php @@ -0,0 +1,79 @@ + */ + public array $loops = []; + + /** @var list */ + public array $unresolved = []; + + /** @var list */ + public array $strayMarkers = []; + + /** + * @param list $fields + */ + public function __construct( + public readonly string $block, + public readonly MarkupDocument $document, + public readonly array $fields, + ) {} + + /** + * @return list + */ + public function collectionIdentifiers(): array + { + return array_values(array_unique(array_map(static fn(CollectionField $field): string => $field->identifier, $this->allFields()))); + } + + /** + * Root and nested Collections, depth first. + * + * @param list|null $fields + * @return list + */ + public function allFields(?array $fields = null): array + { + $all = []; + foreach ($fields ?? $this->fields as $field) { + $all[] = $field; + $all = [...$all, ...$this->allFields($field->children)]; + } + return $all; + } + + /** + * What `--check` and the lint test fail on. + * + * @return list + */ + public function failures(): array + { + $failures = [...$this->document->errors, ...$this->unresolved, ...$this->strayMarkers]; + foreach ($this->loops as $loop) { + foreach ($loop->problems as $problem) { + $failures[] = $problem; + } + if ($loop->exception === null && !$loop->isMarked()) { + $failures[] = 'line ' . $loop->line . ': over ' . $loop->field->column + . ' is neither marked nor a listed exception (' . $loop->shape . ' root)'; + } + if ($loop->exception !== null && $loop->markers !== []) { + $failures[] = 'line ' . $loop->line . ': ' . $loop->key() . ' is a listed exception but carries a marker'; + } + } + return $failures; + } +} diff --git a/Classes/Templates/CollectionMarker/CollectionField.php b/Classes/Templates/CollectionMarker/CollectionField.php new file mode 100644 index 000000000..419cb07f6 --- /dev/null +++ b/Classes/Templates/CollectionMarker/CollectionField.php @@ -0,0 +1,116 @@ +__` with dashes + * removed (prefixType full) or `_` (prefixType vendor); + * fields of a Collection's own table are never prefixed. + * + * @internal used by the collection marker codemod and its lint test only + */ +final class CollectionField +{ + /** @var list */ + public array $children = []; + + /** + * File fields of the entry that hold at most one file: a loop over one of + * them renders its body once or not at all. + * + * @var list + */ + public array $singleFileFields = []; + + public function __construct( + public readonly string $identifier, + public readonly string $column, + public readonly string $table, + public readonly string $path, + public readonly ?CollectionField $parent, + ) {} + + /** + * The root Collection fields of a Content Block (nested ones as children). + * + * @return list + */ + public static function fromConfigFile(string $configFile): array + { + $yaml = Yaml::parseFile($configFile); + if (!is_array($yaml)) { + return []; + } + $name = is_string($yaml['name'] ?? null) ? $yaml['name'] : ''; + $fields = is_array($yaml['fields'] ?? null) ? $yaml['fields'] : []; + + return self::collect($fields, $yaml, $name, null); + } + + /** + * @param array $fields + * @param array $block + * @return list + */ + private static function collect(array $fields, array $block, string $name, ?CollectionField $parent): array + { + $collections = []; + foreach ($fields as $field) { + if (!is_array($field) || ($field['type'] ?? null) !== 'Collection' || !is_string($field['identifier'] ?? null)) { + continue; + } + $identifier = $field['identifier']; + $table = $field['table'] ?? $field['foreign_table'] ?? $identifier; + $collection = new self( + $identifier, + $parent === null ? self::rootColumn($identifier, $field, $block, $name) : $identifier, + is_string($table) ? $table : $identifier, + $parent === null ? $identifier : $parent->path . '.' . $identifier, + $parent, + ); + $children = is_array($field['fields'] ?? null) ? $field['fields'] : []; + $collection->children = self::collect($children, $block, $name, $collection); + foreach ($children as $child) { + if (is_array($child) && ($child['type'] ?? null) === 'File' && (int)($child['maxitems'] ?? 0) === 1 && is_string($child['identifier'] ?? null)) { + $collection->singleFileFields[] = $child['identifier']; + } + } + $collections[] = $collection; + } + return $collections; + } + + /** + * @param array $field + * @param array $block + */ + private static function rootColumn(string $identifier, array $field, array $block, string $name): string + { + if ((bool)($field['useExistingField'] ?? false)) { + return $identifier; + } + $prefix = array_key_exists('prefixField', $field) ? (bool)$field['prefixField'] : (bool)($block['prefixFields'] ?? true); + if (!$prefix || !str_contains($name, '/')) { + return $identifier; + } + [$vendor, $element] = explode('/', $name, 2); + $vendorPrefix = str_replace('-', '', is_string($block['vendorPrefix'] ?? null) ? $block['vendorPrefix'] : $vendor); + $type = $field['prefixType'] ?? $block['prefixType'] ?? 'full'; + + return $type === 'vendor' + ? $vendorPrefix . '_' . $identifier + : $vendorPrefix . '_' . str_replace('-', '', $element) . '_' . $identifier; + } +} diff --git a/Classes/Templates/CollectionMarker/CollectionLoop.php b/Classes/Templates/CollectionMarker/CollectionLoop.php new file mode 100644 index 000000000..0a52b998c --- /dev/null +++ b/Classes/Templates/CollectionMarker/CollectionLoop.php @@ -0,0 +1,73 @@ +` over a Collection field in a Content Block template and what + * the codemod makes of it. + * + * @internal used by the collection marker codemod and its lint test only + */ +final class CollectionLoop +{ + /** The loop body renders exactly one root element per entry (per render path). */ + public const string SHAPE_SINGLE = 'single'; + /** The body renders several sibling roots per entry. */ + public const string SHAPE_MULTI = 'multi'; + /** The body renders text only (JSON, inline values) or nothing. */ + public const string SHAPE_NONE = 'none'; + + /** Plain HTML root: an inline marker before the open tag's ">". */ + public const string RULE_HTML = 'html'; + /** `d:` component root: the marker array goes into its `attributes` argument. */ + public const string RULE_COMPONENT = 'component'; + /** Tag-based Fluid ViewHelper root: the marker array goes into `additionalAttributes`. */ + public const string RULE_FLUID_TAG = 'fluid-tag'; + + /** @var list */ + public array $roots = []; + + public string $shape = self::SHAPE_NONE; + + /** + * Root offset => the marker found on it: [variable, collection]. + * + * @var array + */ + public array $markers = []; + + /** @var list */ + public array $problems = []; + + public ?string $exception = null; + + public function __construct( + public readonly string $block, + public readonly CollectionField $field, + public readonly MarkupNode $loop, + public readonly string $as, + public readonly int $line, + /** 1-based position among the loops over the same field in this template */ + public readonly int $occurrence, + ) {} + + public function key(): string + { + return $this->block . '.' . $this->field->path; + } + + public static function ruleFor(MarkupNode $root): string + { + if (!$root->isFluidTag()) { + return self::RULE_HTML; + } + return $root->prefix() === 'd' ? self::RULE_COMPONENT : self::RULE_FLUID_TAG; + } + + public function isMarked(): bool + { + return $this->roots !== [] && count($this->markers) === count($this->roots); + } +} diff --git a/Classes/Templates/CollectionMarker/CollectionLoopAnalyzer.php b/Classes/Templates/CollectionMarker/CollectionLoopAnalyzer.php new file mode 100644 index 000000000..58305f30e --- /dev/null +++ b/Classes/Templates/CollectionMarker/CollectionLoopAnalyzer.php @@ -0,0 +1,315 @@ +` over a Collection field in a Content Block's frontend + * template, works out what one iteration renders, and reads the row markers + * already in place. + * + * A loop is recognised when `each` is `{.}` and `` is `data` + * (the content element) or the `as` variable of an enclosing loop over a + * Collection that declares `` (nested collections), or `{}` for + * an ``. A loop that names + * a Collection in any other form is reported as unresolved, so `--check` + * cannot pass while a loop escapes the rules. + * + * Root rules: f:if/f:then/f:else, f:switch/f:case/f:defaultCase and + * f:spaceless are transparent (alternative branches count once), and so is an + * inner `` over a File field of the entry with `maxitems: 1` (it renders + * its body at most once - the gallery thumbnails); + * f:variable, f:asset.*, f:comment and HTML comments render nothing; any + * other element is a root, non-blank text makes the body text-shaped. + * + * @internal used by the collection marker codemod and its lint test only + */ +final class CollectionLoopAnalyzer +{ + public const string MARKER_PATTERN = '/\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*->\s*f:mark\.item\(\s*collection:\s*\'([^\']*)\'/'; + + private const array TRANSPARENT = ['f:then', 'f:else', 'f:spaceless', 'f:case', 'f:defaultCase']; + + private const array NO_OUTPUT = ['f:variable', 'f:comment', 'f:argument']; + + private readonly MarkupParser $parser; + + public function __construct(?MarkupParser $parser = null) + { + $this->parser = $parser ?? new MarkupParser(); + } + + public function analyzeBlock(string $blockDirectory, ?CollectionMarkerExceptions $exceptions = null): BlockAnalysis + { + $block = basename($blockDirectory); + $template = $blockDirectory . '/templates/frontend.html'; + $fields = CollectionField::fromConfigFile($blockDirectory . '/config.yaml'); + + return $this->analyze($block, (string)file_get_contents($template), $fields, $exceptions ?? new CollectionMarkerExceptions()); + } + + /** + * @param list $fields + */ + public function analyze(string $block, string $source, array $fields, CollectionMarkerExceptions $exceptions): BlockAnalysis + { + $document = $this->parser->parse($source); + $analysis = new BlockAnalysis($block, $document, $fields); + $occurrences = []; + $this->walk($document->root, ['data' => $fields], [], $analysis, $occurrences); + + foreach ($analysis->loops as $loop) { + $loop->exception = $exceptions->reasonFor($loop); + } + $this->findStrayMarkers($analysis); + + return $analysis; + } + + /** + * @param array> $scope variable => the Collections reachable as . + * @param array $aliases variable => the Collection it holds as a list + * @param array $occurrences + */ + private function walk(MarkupNode $node, array $scope, array $aliases, BlockAnalysis $analysis, array &$occurrences): void + { + foreach ($node->children as $child) { + if ($child->type !== MarkupNode::ELEMENT) { + continue; + } + if ($child->name === 'f:variable') { + $name = $child->attribute('name'); + $field = $this->resolve($child->attribute('value'), $scope, $aliases); + if ($name !== null && $field !== null) { + $aliases[$name] = $field; + } + } + $childScope = $scope; + if ($child->name === 'f:for') { + $each = $child->attribute('each'); + $field = $this->resolve($each, $scope, $aliases); + $as = $child->attribute('as') ?? ''; + if ($field !== null) { + $occurrence = $occurrences[$field->path] = ($occurrences[$field->path] ?? 0) + 1; + $loop = new CollectionLoop( + $analysis->block, + $field, + $child, + $as, + substr_count(substr($analysis->document->source, 0, $child->start), "\n") + 1, + $occurrence, + ); + $this->inspectBody($loop, $analysis->document->source); + $analysis->loops[] = $loop; + $childScope[$as] = $field->children; + } else { + $this->reportUnresolved($child, $each, $scope, $aliases, $analysis); + unset($childScope[$as]); + } + } + $this->walk($child, $childScope, $aliases, $analysis, $occurrences); + } + } + + /** + * @param array> $scope + * @param array $aliases + */ + private function resolve(?string $expression, array $scope, array $aliases): ?CollectionField + { + if ($expression === null || preg_match('/^\{\s*([A-Za-z_][A-Za-z0-9_]*)(?:\.([A-Za-z_][A-Za-z0-9_]*))?\s*\}$/', trim($expression), $match) !== 1) { + return null; + } + if (!isset($match[2])) { + return $aliases[$match[1]] ?? null; + } + foreach ($scope[$match[1]] ?? [] as $field) { + if ($field->identifier === $match[2]) { + return $field; + } + } + return null; + } + + /** + * An f:for that names a Collection of this block in a form the rules do + * not read (a filter chain, an unknown alias, an index) is surfaced. + * + * @param array> $scope + * @param array $aliases + */ + private function reportUnresolved(MarkupNode $loop, ?string $each, array $scope, array $aliases, BlockAnalysis $analysis): void + { + if ($each === null || preg_match_all('/\b([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_]*)/', $each, $matches, PREG_SET_ORDER) === 0) { + return; + } + $identifiers = $analysis->collectionIdentifiers(); + foreach ($matches as $match) { + if (!in_array($match[2], $identifiers, true)) { + continue; + } + // {data.title} where title is no Collection of data, or a file + // field named like a nested Collection: in scope and not a list. + if (isset($scope[$match[1]]) && !in_array($match[2], array_map(static fn(CollectionField $field): string => $field->identifier, $scope[$match[1]]), true)) { + continue; + } + $analysis->unresolved[] = 'line ' . (substr_count(substr($analysis->document->source, 0, $loop->start), "\n") + 1) + . ': loops over Collection "' . $match[2] . '" in a form the codemod does not read'; + return; + } + } + + private function inspectBody(CollectionLoop $loop, string $source): void + { + [$count, $roots, $text] = $this->roots($loop->loop->children, $source, $loop); + $loop->roots = $roots; + $loop->shape = match (true) { + $text || $count === 0 => CollectionLoop::SHAPE_NONE, + $count === 1 => CollectionLoop::SHAPE_SINGLE, + default => CollectionLoop::SHAPE_MULTI, + }; + foreach ($roots as $root) { + $marker = $this->markerOn($root, $source); + if ($marker === null) { + continue; + } + $loop->markers[$root->start] = $marker; + if ($marker['variable'] !== $loop->as) { + $loop->problems[] = 'marker on line ' . $this->line($source, $root->start) . ' marks "' . $marker['variable'] . '" instead of the loop variable "' . $loop->as . '"'; + } + if ($marker['collection'] !== $loop->field->column) { + $loop->problems[] = 'marker on line ' . $this->line($source, $root->start) . ' names collection "' . $marker['collection'] . '" instead of "' . $loop->field->column . '"'; + } + } + } + + /** + * What a sequence of sibling nodes renders: the most roots any one render + * path produces, every root element on any path, and whether non-blank + * text is rendered next to them. + * + * @param list $nodes + * @return array{0: int, 1: list, 2: bool} + */ + private function roots(array $nodes, string $source, CollectionLoop $loop): array + { + $count = 0; + $roots = []; + $text = false; + foreach ($nodes as $node) { + if ($node->type === MarkupNode::TEXT) { + $text = $text || trim(substr($source, $node->start, $node->end - $node->start)) !== ''; + continue; + } + if ($node->type === MarkupNode::COMMENT || in_array($node->name, self::NO_OUTPUT, true) || str_starts_with($node->name, 'f:asset.')) { + continue; + } + $alternatives = match (true) { + $node->name === 'f:if' => $this->ifBranches($node), + $node->name === 'f:switch' => array_map( + static fn(MarkupNode $case): array => $case->children, + array_values(array_filter($node->children, static fn(MarkupNode $case): bool => in_array($case->name, ['f:case', 'f:defaultCase'], true))), + ), + in_array($node->name, self::TRANSPARENT, true), $this->isSingleFileLoop($node, $loop) => [$node->children], + default => null, + }; + if ($alternatives === null) { + ++$count; + $roots[] = $node; + continue; + } + if ($node->name === 'f:if' && $node->selfClosing && ($node->attribute('then') !== null || $node->attribute('else') !== null)) { + $text = true; + continue; + } + $most = 0; + foreach ($alternatives as $alternative) { + [$branchCount, $branchRoots, $branchText] = $this->roots($alternative, $source, $loop); + $most = max($most, $branchCount); + $roots = [...$roots, ...$branchRoots]; + $text = $text || $branchText; + } + $count += $most; + } + return [$count, $roots, $text]; + } + + private function isSingleFileLoop(MarkupNode $node, CollectionLoop $loop): bool + { + if ($node->name !== 'f:for' || preg_match('/^\{\s*([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_]*)\s*\}$/', trim((string)$node->attribute('each')), $match) !== 1) { + return false; + } + return $match[1] === $loop->as && in_array($match[2], $loop->field->singleFileFields, true); + } + + /** + * @return list> + */ + private function ifBranches(MarkupNode $if): array + { + $branches = array_values(array_filter($if->children, static fn(MarkupNode $child): bool => in_array($child->name, ['f:then', 'f:else'], true))); + if ($branches === []) { + return [$if->children]; + } + return array_map(static fn(MarkupNode $branch): array => $branch->children, $branches); + } + + /** + * @return array{variable: string, collection: string}|null + */ + public function markerOn(MarkupNode $root, string $source): ?array + { + $carrier = match (CollectionLoop::ruleFor($root)) { + CollectionLoop::RULE_HTML => implode(' ', array_map( + static fn(array $attribute): string => (string)$attribute['value'], + array_filter($root->attributes, static fn(array $attribute): bool => $attribute['name'] === ''), + )), + CollectionLoop::RULE_COMPONENT => (string)$root->attribute('attributes'), + default => (string)$root->attribute('additionalAttributes'), + }; + if (preg_match(self::MARKER_PATTERN, $carrier, $match) !== 1) { + return null; + } + return ['variable' => $match[1], 'collection' => $match[2]]; + } + + /** + * Every f:mark.item in the template must sit on the root of a recognised + * Collection loop, in the place its rule puts it. + */ + private function findStrayMarkers(BlockAnalysis $analysis): void + { + $source = $analysis->document->source; + $accepted = []; + foreach ($analysis->loops as $loop) { + foreach ($loop->roots as $root) { + if (isset($loop->markers[$root->start])) { + $accepted[] = [$root->start, $root->openEnd]; + } + } + } + $comments = []; + foreach ($analysis->document->elements() as $element) { + if ($element->name === 'f:comment') { + $comments[] = [$element->start, $element->end]; + } + } + if (preg_match_all('/f:mark\.item\b/', $source, $matches, PREG_OFFSET_CAPTURE) === 0) { + return; + } + foreach ($matches[0] as [, $offset]) { + foreach ([...$accepted, ...$comments] as [$start, $end]) { + if ($offset >= $start && $offset < $end) { + continue 2; + } + } + $analysis->strayMarkers[] = 'line ' . $this->line($source, $offset) . ': f:mark.item outside the root of a Collection loop'; + } + } + + private function line(string $source, int $offset): int + { + return substr_count(substr($source, 0, $offset), "\n") + 1; + } +} diff --git a/Classes/Templates/CollectionMarker/CollectionMarkerExceptions.php b/Classes/Templates/CollectionMarker/CollectionMarkerExceptions.php new file mode 100644 index 000000000..a31dbca5e --- /dev/null +++ b/Classes/Templates/CollectionMarker/CollectionMarkerExceptions.php @@ -0,0 +1,45 @@ +.` (every loop over that + * Collection) or `.#` (only the n-th loop over it in + * the template). Without a marker the Visual Editor still lists the entries in + * its panel; only the on-page row controls are missing for these rows. + * + * @internal used by the collection marker codemod and its lint test only + */ +final class CollectionMarkerExceptions +{ + public const array EXCEPTIONS = [ + 'chart.data_points#1' => 'Computes the summary values only (f:variable, no output); the bars are drawn by charts.js. The data table loop (#2) carries the markers.', + 'chart-contribution.points#1' => 'Writes the JSON array charts.js draws from (f:format.json inside an f:variable); no element per entry. The data table loop (#2) carries the markers.', + 'chart-donut.segments#1' => 'Writes the JSON array charts.js draws the ring from (f:format.json inside an f:variable); no element per entry. The legend (#2) and the data table (#3) carry the markers.', + 'gallery.items#1' => 'The featured view renders only the first entry, as two siblings (lightbox image and caption) the gallery script swaps; no single root. The thumbnail loop (#2) carries the markers.', + ]; + + /** + * @param array|null $exceptions + */ + public function __construct( + private readonly ?array $exceptions = null, + ) {} + + public function reasonFor(CollectionLoop $loop): ?string + { + $exceptions = $this->exceptions ?? self::EXCEPTIONS; + return $exceptions[$loop->key() . '#' . $loop->occurrence] ?? $exceptions[$loop->key()] ?? null; + } + + /** + * @return array + */ + public function all(): array + { + return $this->exceptions ?? self::EXCEPTIONS; + } +} diff --git a/Classes/Templates/CollectionMarker/CollectionMarkerRewriter.php b/Classes/Templates/CollectionMarker/CollectionMarkerRewriter.php new file mode 100644 index 000000000..c1407f504 --- /dev/null +++ b/Classes/Templates/CollectionMarker/CollectionMarkerRewriter.php @@ -0,0 +1,113 @@ + -> f:mark.item(collection: '')}` right before + * the open tag's ">" (or "/>"). No space is written in front of it: the + * ViewHelper's output starts with one, and outside edit mode it renders + * '' - the published markup stays byte-identical. + * - `d:` component root: `attributes="{ -> f:mark.item(collection: + * '', format: 'array')}"` after the last argument. An existing + * `attributes` value (an array literal or a variable) is kept and merged: + * `{ -> f:mark.item(...) -> f:merge(with: )}` - outside edit + * mode the marker is [] and the merge returns the existing array unchanged. + * - Any other root (a tag-based Fluid ViewHelper) is not rewritten; it needs + * a listed exception or a hand-written marker. + * + * @internal used by the collection marker codemod and its lint test only + */ +final class CollectionMarkerRewriter +{ + /** + * @return array{source: string, edits: list, errors: list} + */ + public function rewrite(BlockAnalysis $analysis): array + { + $source = $analysis->document->source; + /** @var array $edits */ + $edits = []; + $errors = []; + foreach ($analysis->loops as $loop) { + if ($loop->exception !== null || $loop->shape !== CollectionLoop::SHAPE_SINGLE) { + continue; + } + foreach ($loop->roots as $root) { + if (isset($loop->markers[$root->start])) { + continue; + } + $line = substr_count(substr($source, 0, $root->start), "\n") + 1; + $edit = $this->editFor($loop, $root); + if (is_string($edit)) { + $errors[] = 'line ' . $line . ': ' . $edit; + continue; + } + $edit['note'] = 'line ' . $line . ': ' . $loop->key() . ' <' . $root->name . '> (' . CollectionLoop::ruleFor($root) . ')'; + $edits[$edit['start']] = $edit; + } + } + krsort($edits); + foreach ($edits as $edit) { + $source = substr_replace($source, $edit['text'], $edit['start'], $edit['end'] - $edit['start']); + } + + return ['source' => $source, 'edits' => array_reverse(array_column($edits, 'note')), 'errors' => $errors]; + } + + /** + * @return array{start: int, end: int, text: string}|string the splice, or why there is none + */ + private function editFor(CollectionLoop $loop, MarkupNode $root): array|string + { + $collection = $loop->field->column; + switch (CollectionLoop::ruleFor($root)) { + case CollectionLoop::RULE_HTML: + return [ + 'start' => $root->insertAt, + 'end' => $root->insertAt, + 'text' => '{' . $loop->as . ' -> f:mark.item(collection: \'' . $collection . '\')}', + ]; + case CollectionLoop::RULE_COMPONENT: + $marker = $loop->as . ' -> f:mark.item(collection: \'' . $collection . '\', format: \'array\')'; + $existing = $root->attributeSpan('attributes'); + if ($existing === null) { + $after = $root->attributes === [] ? $root->start + 1 + strlen($root->name) : max(array_column($root->attributes, 'end')); + return ['start' => $after, 'end' => $after, 'text' => ' attributes="{' . $marker . '}"']; + } + $with = $this->mergeOperand((string)$existing['value']); + if ($with === null) { + return '<' . $root->name . ' attributes="' . $existing['value'] . '"> cannot be merged with the marker (expected an array literal or a variable)'; + } + return [ + 'start' => $existing['valueStart'], + 'end' => $existing['valueEnd'], + 'text' => '{' . $marker . ' -> f:merge(with: ' . $with . ')}', + ]; + default: + return '<' . $root->name . '> is a Fluid ViewHelper root; mark it by hand or list the loop as an exception'; + } + } + + /** + * The existing `attributes` value as an f:merge `with:` operand: a + * variable path stays a path, an array literal stays the literal. + */ + private function mergeOperand(string $value): ?string + { + $value = trim($value); + if (preg_match('/^\{\s*([A-Za-z_][A-Za-z0-9_.]*)\s*\}$/', $value, $match) === 1) { + return $match[1]; + } + $isViewHelperCall = preg_match('/^\{\s*[A-Za-z][A-Za-z0-9]*:[A-Za-z][A-Za-z0-9.]*\s*\(/', $value) === 1; + if (!$isViewHelperCall && str_ends_with($value, '}') && !str_contains($value, '->') && preg_match('/^\{\s*[\'"]?[A-Za-z_-][A-Za-z0-9_-]*[\'"]?\s*:/', $value) === 1) { + return $value; + } + return null; + } +} diff --git a/Classes/Templates/CollectionMarker/MarkupDocument.php b/Classes/Templates/CollectionMarker/MarkupDocument.php new file mode 100644 index 000000000..a6709e638 --- /dev/null +++ b/Classes/Templates/CollectionMarker/MarkupDocument.php @@ -0,0 +1,38 @@ + $errors + */ + public function __construct( + public string $source, + public MarkupNode $root, + public array $errors, + ) {} + + /** + * Every element in document order. + * + * @return \Generator + */ + public function elements(?MarkupNode $node = null): \Generator + { + foreach (($node ?? $this->root)->children as $child) { + if ($child->type === MarkupNode::ELEMENT) { + yield $child; + yield from $this->elements($child); + } + } + } +} diff --git a/Classes/Templates/CollectionMarker/MarkupNode.php b/Classes/Templates/CollectionMarker/MarkupNode.php new file mode 100644 index 000000000..51f638977 --- /dev/null +++ b/Classes/Templates/CollectionMarker/MarkupNode.php @@ -0,0 +1,89 @@ + */ + public array $children = []; + + /** + * Attributes of an element's open tag in source order. A bare inline + * expression between attributes ({row -> f:mark.item(...)}) or a nested + * Fluid tag inside an HTML open tag is recorded with an empty name. + * + * @var list + */ + public array $attributes = []; + + public ?MarkupNode $parent = null; + + /** Offset of the open tag's closing ">" (or "/" of "/>"); where an attribute is inserted. */ + public int $insertAt = 0; + + /** Offset just past the open tag. */ + public int $openEnd = 0; + + /** Offset of the close tag's "<" (or $end for void and self-closing elements). */ + public int $closeStart = 0; + + public bool $selfClosing = false; + + public function __construct( + public readonly string $type, + public readonly string $name, + public readonly int $start, + public int $end, + ) {} + + public function isFluidTag(): bool + { + return $this->type === self::ELEMENT && str_contains($this->name, ':'); + } + + public function prefix(): string + { + return $this->isFluidTag() ? explode(':', $this->name, 2)[0] : ''; + } + + public function attribute(string $name): ?string + { + foreach ($this->attributes as $attribute) { + if ($attribute['name'] === $name) { + return $attribute['value']; + } + } + return null; + } + + /** + * @return array{name: string, value: string|null, start: int, end: int, valueStart: int, valueEnd: int}|null + */ + public function attributeSpan(string $name): ?array + { + foreach ($this->attributes as $attribute) { + if ($attribute['name'] === $name) { + return $attribute; + } + } + return null; + } + + public function openTag(string $source): string + { + return substr($source, $this->start, $this->openEnd - $this->start); + } +} diff --git a/Classes/Templates/CollectionMarker/MarkupParser.php b/Classes/Templates/CollectionMarker/MarkupParser.php new file mode 100644 index 000000000..7b7ef5a51 --- /dev/null +++ b/Classes/Templates/CollectionMarker/MarkupParser.php @@ -0,0 +1,347 @@ +" and quotes + * (`condition="{a} > 1"`, `"{f:translate(key: 'x')}"`); a value ends at the + * first unescaped matching quote, exactly as Fluid's tag pattern reads it; + * - bare inline expressions between attributes + * (`
f:mark.item(collection: 'c')}>`), brace-balanced + * with quoted strings skipped; + * - Fluid tags nested inside an HTML open tag (desiderio's attribute spread: + * `
{k}="{v}">`); + * - `` bodies, HTML comments and CDATA are opaque; + * - `
')->errors); + self::assertNotSame([], $parser->parse('
')->errors); + self::assertNotSame([], $parser->parse('
')->errors); + } + + private function analyze(string $template, ?CollectionMarkerExceptions $exceptions = null): BlockAnalysis + { + return (new CollectionLoopAnalyzer())->analyze('demo-block', $template, $this->fields(), $exceptions ?? new CollectionMarkerExceptions([])); + } + + /** + * @return list + */ + private function fields(): array + { + $file = tempnam(sys_get_temp_dir(), 'cb-config'); + self::assertIsString($file); + file_put_contents($file, self::CONFIG); + try { + return CollectionField::fromConfigFile($file); + } finally { + unlink($file); + } + } +} diff --git a/Tests/Unit/ComponentStructureTest.php b/Tests/Unit/ComponentStructureTest.php index 2e37e92de..c6b47718d 100644 --- a/Tests/Unit/ComponentStructureTest.php +++ b/Tests/Unit/ComponentStructureTest.php @@ -167,6 +167,40 @@ public function testTypographyCarriesExtraAttributesThroughOneEscapeHatch(): voi self::assertStringContainsString('mt-6 border-l-2 pl-6 italic', $typography); } + /** + * The molecules a collection loop renders as one entry's root take the + * Visual Editor's row marker through `attributes` (like Card): declared + * argument, spread onto every root tag, and the argument emits no + * whitespace so the published markup did not change when it was added. + */ + public function testRowRootMoleculesDeclareAttributes(): void + { + $spread = ' {attributeName}="{attributeValue}"'; + $rootTags = [ + 'CheckedListItem' => ['
  • [' [' ['
    [' [' $tags) { + $source = (string)file_get_contents(self::COMPONENTS_DIR . '/Molecule/' . $molecule . '/' . $molecule . '.fluid.html'); + self::assertMatchesRegularExpression( + '#/>(?:.*?)?\n#s', + $source, + $molecule . ' declares attributes on the line of the previous argument', + ); + self::assertSame(count($tags), substr_count($source, $spread), $molecule . ' spreads attributes once per root tag'); + foreach ($tags as $tag) { + $start = strpos($source, $tag); + self::assertIsInt($start, $molecule . ': ' . $tag); + $openTag = substr($source, $start, (int)strpos($source, '', $start) - $start); + self::assertStringContainsString(' over a Collection field marks the root element of each + * entry, or is a listed exception with a reason. This is the lint behind + * `php Build/Scripts/codemod-collection-markers.php --check` and the source + * of truth for the counts. + */ +final class ContentBlockCollectionMarkerTest extends AbstractContentBlockTestCase +{ + private const string COMPONENTS_DIR = __DIR__ . '/../../Resources/Private/Components'; + + /** Collection loops, marked loops and listed exceptions in the shipped templates. */ + private const int EXPECTED_LOOPS = 189; + private const int EXPECTED_MARKED_LOOPS = 185; + private const int EXPECTED_EXCEPTIONS = 4; + private const int EXPECTED_COLLECTIONS = 175; + + /** @var array|null */ + private static ?array $analyses = null; + + public function testEveryCollectionLoopCarriesRowMarkerOrIsListedException(): void + { + $loops = 0; + $marked = 0; + $exceptions = 0; + $collections = 0; + $usedExceptions = []; + foreach (self::analyses() as $block => $analysis) { + self::assertSame([], $analysis->failures(), $block . ' (run php Build/Scripts/codemod-collection-markers.php)'); + $looped = []; + foreach ($analysis->loops as $loop) { + ++$loops; + $looped[$loop->field->path] = true; + if ($loop->exception !== null) { + ++$exceptions; + $usedExceptions[$loop->key() . '#' . $loop->occurrence] = true; + $usedExceptions[$loop->key()] = true; + self::assertNotSame(CollectionLoop::SHAPE_SINGLE, $loop->shape, $loop->key() . '#' . $loop->occurrence . ' renders one root per entry: mark it instead of listing it'); + continue; + } + self::assertTrue($loop->isMarked(), $loop->key() . '#' . $loop->occurrence . ' is not marked'); + ++$marked; + } + foreach ($analysis->allFields() as $field) { + ++$collections; + self::assertArrayHasKey($field->path, $looped, $block . '.' . $field->path . ' is never looped in frontend.html'); + } + } + foreach (CollectionMarkerExceptions::EXCEPTIONS as $key => $reason) { + self::assertArrayHasKey($key, $usedExceptions, 'Stale exception ' . $key); + self::assertGreaterThan(40, strlen($reason), 'Exception ' . $key . ' needs a reason'); + } + self::assertSame(self::EXPECTED_COLLECTIONS, $collections); + self::assertSame(self::EXPECTED_LOOPS, $loops); + self::assertSame(self::EXPECTED_MARKED_LOOPS, $marked); + self::assertSame(self::EXPECTED_EXCEPTIONS, $exceptions); + } + + public function testNoMarkerOutsideCollectionLoops(): void + { + foreach (self::analyses() as $block => $analysis) { + self::assertSame([], $analysis->strayMarkers, $block); + $markers = preg_match_all('/f:mark\.item\(/', $analysis->document->source); + $placed = array_sum(array_map(static fn(CollectionLoop $loop): int => count($loop->markers), $analysis->loops)); + self::assertSame($placed, $markers, $block . ': every f:mark.item sits on a loop root'); + } + foreach (self::globList(self::CONTENT_BLOCKS_DIR . '/*/templates/backend-preview.fluid.html') as $preview) { + self::assertStringNotContainsString('f:mark.item', (string)file_get_contents($preview), $preview . ': backend previews are not edited in the Visual Editor'); + } + $components = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(self::COMPONENTS_DIR, \FilesystemIterator::SKIP_DOTS)); + foreach ($components as $file) { + if ($file instanceof \SplFileInfo && $file->isFile()) { + self::assertStringNotContainsString('f:mark.item', (string)file_get_contents($file->getPathname()), $file->getPathname() . ': components receive markers through attributes'); + } + } + } + + public function testRowRootComponentsAcceptAttributes(): void + { + $components = []; + foreach (self::analyses() as $analysis) { + foreach ($analysis->loops as $loop) { + foreach ($loop->roots as $root) { + if (CollectionLoop::ruleFor($root) === CollectionLoop::RULE_COMPONENT && isset($loop->markers[$root->start])) { + $components[$root->name][] = $loop->key(); + } + } + } + } + ksort($components); + self::assertSame( + ['d:atom.link', 'd:molecule.card', 'd:molecule.checkedListItem', 'd:molecule.featureItem', 'd:molecule.tableCell', 'd:molecule.tableRow', 'd:molecule.tabsContent', 'd:molecule.tabsTrigger'], + array_keys($components), + ); + foreach (array_keys($components) as $tag) { + [, $name] = explode(':', $tag, 2); + [$level, $component] = explode('.', $name, 2); + $component = ucfirst($component); + $file = self::COMPONENTS_DIR . '/' . ucfirst($level) . '/' . $component . '/' . $component . '.fluid.html'; + self::assertFileExists($file); + $source = (string)file_get_contents($file); + self::assertStringContainsString('', $source, $tag); + self::assertStringContainsString(' {attributeName}="{attributeValue}"', $source, $tag . ' spreads attributes onto its root tag'); + } + } + + public function testMarkerCollectionNameMatchesTheLoopedField(): void + { + foreach (self::analyses() as $block => $analysis) { + $config = Yaml::parseFile(self::CONTENT_BLOCKS_DIR . '/' . $block . '/config.yaml'); + self::assertIsArray($config); + $typeName = $config['typeName'] ?? null; + self::assertIsString($typeName); + foreach ($analysis->loops as $loop) { + // Content Blocks: a root Collection with prefixField: true is + // the column _ (prefixFields is off for + // every desiderio block); a nested one keeps its identifier. + $expected = $loop->field->parent === null ? $typeName . '_' . $loop->field->identifier : $loop->field->identifier; + self::assertSame($expected, $loop->field->column, $block . '.' . $loop->field->path); + foreach ($loop->markers as $marker) { + self::assertSame($loop->as, $marker['variable'], $loop->key() . ': the marker marks the loop variable'); + self::assertSame($expected, $marker['collection'], $loop->key() . ': the marker names the looped column'); + } + } + preg_match_all("/f:mark\\.item\\(collection: '([^']+)'/", $analysis->document->source, $matches); + $columns = array_map(static fn(CollectionField $field): string => $field->column, $analysis->allFields()); + foreach ($matches[1] as $collection) { + self::assertContains($collection, $columns, $block . ': "' . $collection . '" is no Collection column of this element'); + } + } + } + + /** + * @return array + */ + private static function analyses(): array + { + if (self::$analyses === null) { + $analyzer = new CollectionLoopAnalyzer(); + self::$analyses = []; + foreach (self::globList(self::CONTENT_BLOCKS_DIR . '/*', GLOB_ONLYDIR) as $directory) { + $analysis = $analyzer->analyzeBlock($directory); + if ($analysis->fields !== []) { + self::$analyses[basename($directory)] = $analysis; + } + } + } + return self::$analyses; + } +} diff --git a/Tests/Unit/ViewHelpers/RowMarkerFallbackItemViewHelperTest.php b/Tests/Unit/ViewHelpers/RowMarkerFallbackItemViewHelperTest.php new file mode 100644 index 000000000..08d407a30 --- /dev/null +++ b/Tests/Unit/ViewHelpers/RowMarkerFallbackItemViewHelperTest.php @@ -0,0 +1,40 @@ +initializeArguments(); + $arguments = $viewHelper->prepareArguments(); + self::assertSame(['record', 'collection', 'format'], array_keys($arguments)); + self::assertTrue($arguments['collection']->isRequired()); + self::assertSame('record', $viewHelper->getContentArgumentName()); + + $viewHelper->setArguments(['record' => null, 'collection' => 'items', 'format' => 'attributes']); + self::assertSame('', $viewHelper->render()); + $viewHelper->setArguments(['record' => null, 'collection' => 'items', 'format' => 'array']); + self::assertSame([], $viewHelper->render()); + } + + public function testIsRegisteredOnlyWhenVisualEditorEnhancementsCannotServeTheMarker(): void + { + $localconf = (string)file_get_contents(__DIR__ . '/../../../ext_localconf.php'); + self::assertStringContainsString( + "if (!ExtensionManagementUtility::isLoaded('visual_editor_enhancements')\n || !class_exists('Webconsulting\\\\VisualEditorEnhancements\\\\ViewHelpers\\\\Mark\\\\ItemViewHelper')\n) {\n \$GLOBALS['TYPO3_CONF_VARS']['SYS']['fluid']['namespaces']['f'][] = 'Webconsulting\\\\Desiderio\\\\ViewHelpers\\\\RowMarkerFallback';", + $localconf, + ); + } +} diff --git a/composer.json b/composer.json index e1197397b..193ce7832 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "typo3/cms-fluid": "^14.3.6", "typo3/cms-form": "^14.3.6", "typo3/cms-workspaces": "^14.3.6", - "webconsulting/visual-editor-enhancements": "^0.8 || ^1.0 || dev-main" + "webconsulting/visual-editor-enhancements": "^1.6 || dev-main" }, "minimum-stability": "stable", "prefer-stable": true, @@ -65,7 +65,7 @@ "extra": { "typo3/cms": { "extension-key": "desiderio", - "version": "4.35.0", + "version": "4.36.0", "Package": { "providesPackages": {} } diff --git a/ext_emconf.php b/ext_emconf.php index 19905dcce..1e90f1793 100644 --- a/ext_emconf.php +++ b/ext_emconf.php @@ -11,7 +11,7 @@ 'author' => 'webconsulting studio', 'author_email' => '', 'state' => 'stable', - 'version' => '4.35.0', + 'version' => '4.36.0', 'constraints' => [ 'depends' => [ 'php' => '8.4.0-8.5.99', diff --git a/ext_localconf.php b/ext_localconf.php index 2c237d861..67f7b3f31 100644 --- a/ext_localconf.php +++ b/ext_localconf.php @@ -102,3 +102,16 @@ $desiderioDisabledFormSets[] = 'typo3/styleguide-form-set'; $GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['form']['disabledSets'] = array_values(array_unique($desiderioDisabledFormSets)); } + +// Row markers: the Content Block templates mark each collection entry with +// `{entry -> f:mark.item(collection: '…')}` (Build/Scripts/codemod-collection-markers.php). +// The ViewHelper ships with Visual Editor Enhancements 1.6+, which writes the +// data-ve-* attributes in edit mode only. Should that extension not be loaded +// (a classic-mode install, a test or project setup without it, an older +// release), register a stand-in that renders nothing, like the real one does +// outside edit mode, so no template fails on an unknown ViewHelper. +if (!ExtensionManagementUtility::isLoaded('visual_editor_enhancements') + || !class_exists('Webconsulting\\VisualEditorEnhancements\\ViewHelpers\\Mark\\ItemViewHelper') +) { + $GLOBALS['TYPO3_CONF_VARS']['SYS']['fluid']['namespaces']['f'][] = 'Webconsulting\\Desiderio\\ViewHelpers\\RowMarkerFallback'; +}